Bug 1846847 [wpt PR 41301] - [FedCM] Don't omit schemes when formatting URLs, a=testonly
[gecko.git] / js / src / jsfriendapi.h
blob74ceb75f6b6c5b5700133f21b3ddc74263a4f183
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef jsfriendapi_h
8 #define jsfriendapi_h
10 #include "jspubtd.h"
12 #include "js/CallArgs.h"
13 #include "js/Class.h"
14 #include "js/GCAPI.h"
15 #include "js/HeapAPI.h"
16 #include "js/Object.h" // JS::GetClass
17 #include "js/shadow/Function.h" // JS::shadow::Function
18 #include "js/shadow/Object.h" // JS::shadow::Object
19 #include "js/TypeDecls.h"
21 class JSJitInfo;
24 * Set a callback used to trace gray roots.
26 * The callback is called after the first slice of GC so the embedding must
27 * implement appropriate barriers on its gray roots to ensure correctness.
29 * This callback may be called multiple times for different sets of zones. Use
30 * JS::ZoneIsGrayMarking() to determine whether roots from a particular zone are
31 * required.
33 extern JS_PUBLIC_API void JS_SetGrayGCRootsTracer(JSContext* cx,
34 JSGrayRootsTracer traceOp,
35 void* data);
37 extern JS_PUBLIC_API JSObject* JS_FindCompilationScope(JSContext* cx,
38 JS::HandleObject obj);
40 extern JS_PUBLIC_API JSFunction* JS_GetObjectFunction(JSObject* obj);
42 /**
43 * Allocate an object in exactly the same way as JS_NewObjectWithGivenProto, but
44 * without invoking the metadata callback on it. This allows creation of
45 * internal bookkeeping objects that are guaranteed to not have metadata
46 * attached to them.
48 extern JS_PUBLIC_API JSObject* JS_NewObjectWithoutMetadata(
49 JSContext* cx, const JSClass* clasp, JS::Handle<JSObject*> proto);
51 extern JS_PUBLIC_API bool JS_NondeterministicGetWeakMapKeys(
52 JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret);
54 extern JS_PUBLIC_API bool JS_NondeterministicGetWeakSetKeys(
55 JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret);
57 // Raw JSScript* because this needs to be callable from a signal handler.
58 extern JS_PUBLIC_API unsigned JS_PCToLineNumber(JSScript* script,
59 jsbytecode* pc,
60 unsigned* columnp = nullptr);
62 /**
63 * Determine whether the given object is backed by a DeadObjectProxy.
65 * Such objects hold no other objects (they have no outgoing reference edges)
66 * and will throw if you touch them (e.g. by reading/writing a property).
68 extern JS_PUBLIC_API bool JS_IsDeadWrapper(JSObject* obj);
70 /**
71 * Creates a new dead wrapper object in the given scope. To be used when
72 * attempting to wrap objects from scopes which are already dead.
74 * If origObject is passed, it must be an proxy object, and will be
75 * used to determine the characteristics of the new dead wrapper.
77 extern JS_PUBLIC_API JSObject* JS_NewDeadWrapper(
78 JSContext* cx, JSObject* origObject = nullptr);
80 namespace js {
82 /**
83 * Get the script private value associated with an object, if any.
85 * The private value is set with SetScriptPrivate() or SetModulePrivate() and is
86 * internally stored on the relevant ScriptSourceObject.
88 * This is used by the cycle collector to trace through
89 * ScriptSourceObjects. This allows private values to contain an nsISupports
90 * pointer and hence support references to cycle collected C++ objects.
92 JS_PUBLIC_API JS::Value MaybeGetScriptPrivate(JSObject* object);
94 } // namespace js
97 * Used by the cycle collector to trace through a shape or object group and
98 * all cycle-participating data it reaches, using bounded stack space.
100 extern JS_PUBLIC_API void JS_TraceShapeCycleCollectorChildren(
101 JS::CallbackTracer* trc, JS::GCCellPtr shape);
102 extern JS_PUBLIC_API void JS_TraceObjectGroupCycleCollectorChildren(
103 JS::CallbackTracer* trc, JS::GCCellPtr group);
105 extern JS_PUBLIC_API JSPrincipals* JS_GetScriptPrincipals(JSScript* script);
107 extern JS_PUBLIC_API bool JS_ScriptHasMutedErrors(JSScript* script);
109 extern JS_PUBLIC_API JSObject* JS_CloneObject(JSContext* cx,
110 JS::HandleObject obj,
111 JS::HandleObject proto);
114 * Copy the own properties of src to dst in a fast way. src and dst must both
115 * be native and must be in the compartment of cx. They must have the same
116 * class, the same parent, and the same prototype. Class reserved slots will
117 * NOT be copied.
119 * dst must not have any properties on it before this function is called.
121 * src must have been allocated via JS_NewObjectWithoutMetadata so that we can
122 * be sure it has no metadata that needs copying to dst. This also means that
123 * dst needs to have the compartment global as its parent. This function will
124 * preserve the existing metadata on dst, if any.
126 extern JS_PUBLIC_API bool JS_InitializePropertiesFromCompatibleNativeObject(
127 JSContext* cx, JS::HandleObject dst, JS::HandleObject src);
129 namespace js {
131 JS_PUBLIC_API bool IsArgumentsObject(JS::HandleObject obj);
133 JS_PUBLIC_API bool AddRawValueRoot(JSContext* cx, JS::Value* vp,
134 const char* name);
136 JS_PUBLIC_API void RemoveRawValueRoot(JSContext* cx, JS::Value* vp);
138 } // namespace js
140 namespace JS {
143 * Set all of the uninitialized lexicals on an object to undefined. Return
144 * true if any lexicals were initialized and false otherwise.
145 * */
146 extern JS_PUBLIC_API bool ForceLexicalInitialization(JSContext* cx,
147 HandleObject obj);
150 * Whether we are poisoning unused/released data for error detection. Governed
151 * by the JS_GC_ALLOW_EXTRA_POISONING #ifdef as well as the
152 * $JSGC_EXTRA_POISONING environment variable.
154 extern JS_PUBLIC_API int IsGCPoisoning();
156 extern JS_PUBLIC_API JSPrincipals* GetRealmPrincipals(JS::Realm* realm);
158 extern JS_PUBLIC_API void SetRealmPrincipals(JS::Realm* realm,
159 JSPrincipals* principals);
161 extern JS_PUBLIC_API bool GetIsSecureContext(JS::Realm* realm);
163 extern JS_PUBLIC_API bool GetDebuggerObservesWasm(JS::Realm* realm);
165 } // namespace JS
168 * Copies all own properties and private fields from |obj| to |target|. Both
169 * |obj| and |target| must not be cross-compartment wrappers because we have to
170 * enter their realms.
172 * This function immediately enters a realm, and does not impose any
173 * restrictions on the realm of |cx|.
175 extern JS_PUBLIC_API bool JS_CopyOwnPropertiesAndPrivateFields(
176 JSContext* cx, JS::HandleObject target, JS::HandleObject obj);
178 extern JS_PUBLIC_API bool JS_WrapPropertyDescriptor(
179 JSContext* cx, JS::MutableHandle<JS::PropertyDescriptor> desc);
181 extern JS_PUBLIC_API bool JS_WrapPropertyDescriptor(
182 JSContext* cx,
183 JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> desc);
185 struct JSFunctionSpecWithHelp {
186 const char* name;
187 JSNative call;
188 uint16_t nargs;
189 uint16_t flags;
190 const JSJitInfo* jitInfo;
191 const char* usage;
192 const char* help;
195 #define JS_FN_HELP(name, call, nargs, flags, usage, help) \
196 { name, call, nargs, (flags) | JSPROP_ENUMERATE, nullptr, usage, help }
197 #define JS_INLINABLE_FN_HELP(name, call, nargs, flags, native, usage, help) \
199 name, call, nargs, (flags) | JSPROP_ENUMERATE, &js::jit::JitInfo_##native, \
200 usage, help \
202 #define JS_FS_HELP_END \
203 { nullptr, nullptr, 0, 0, nullptr, nullptr }
205 extern JS_PUBLIC_API bool JS_DefineFunctionsWithHelp(
206 JSContext* cx, JS::HandleObject obj, const JSFunctionSpecWithHelp* fs);
208 namespace js {
211 * Use the runtime's internal handling of job queues for Promise jobs.
213 * Most embeddings, notably web browsers, will have their own task scheduling
214 * systems and need to integrate handling of Promise jobs into that, so they
215 * will want to manage job queues themselves. For basic embeddings such as the
216 * JS shell that don't have an event loop of their own, it's easier to have
217 * SpiderMonkey handle job queues internally.
219 * Note that the embedding still has to trigger processing of job queues at
220 * right time(s), such as after evaluation of a script has run to completion.
222 extern JS_PUBLIC_API bool UseInternalJobQueues(JSContext* cx);
224 #ifdef DEBUG
226 * Given internal job queues are used, return currently queued jobs as an
227 * array of job objects.
229 extern JS_PUBLIC_API JSObject* GetJobsInInternalJobQueue(JSContext* cx);
230 #endif
233 * Enqueue |job| on the internal job queue.
235 * This is useful in tests for creating situations where a call occurs with no
236 * other JavaScript on the stack.
238 extern JS_PUBLIC_API bool EnqueueJob(JSContext* cx, JS::HandleObject job);
241 * Instruct the runtime to stop draining the internal job queue.
243 * Useful if the embedding is in the process of quitting in reaction to a
244 * builtin being called, or if it wants to resume executing jobs later on.
246 extern JS_PUBLIC_API void StopDrainingJobQueue(JSContext* cx);
248 extern JS_PUBLIC_API void RunJobs(JSContext* cx);
250 extern JS_PUBLIC_API JS::Zone* GetRealmZone(JS::Realm* realm);
252 using PreserveWrapperCallback = bool (*)(JSContext*, JS::HandleObject);
253 using HasReleasedWrapperCallback = bool (*)(JS::HandleObject);
255 extern JS_PUBLIC_API bool IsSystemRealm(JS::Realm* realm);
257 extern JS_PUBLIC_API bool IsSystemCompartment(JS::Compartment* comp);
259 extern JS_PUBLIC_API bool IsSystemZone(JS::Zone* zone);
261 struct WeakMapTracer {
262 JSRuntime* runtime;
264 explicit WeakMapTracer(JSRuntime* rt) : runtime(rt) {}
266 // Weak map tracer callback, called once for every binding of every
267 // weak map that was live at the time of the last garbage collection.
269 // m will be nullptr if the weak map is not contained in a JS Object.
271 // The callback should not GC (and will assert in a debug build if it does
272 // so.)
273 virtual void trace(JSObject* m, JS::GCCellPtr key, JS::GCCellPtr value) = 0;
276 extern JS_PUBLIC_API void TraceWeakMaps(WeakMapTracer* trc);
278 extern JS_PUBLIC_API bool AreGCGrayBitsValid(JSRuntime* rt);
280 extern JS_PUBLIC_API bool ZoneGlobalsAreAllGray(JS::Zone* zone);
282 extern JS_PUBLIC_API bool IsCompartmentZoneSweepingOrCompacting(
283 JS::Compartment* comp);
285 using IterateGCThingCallback = void (*)(void*, JS::GCCellPtr,
286 const JS::AutoRequireNoGC&);
288 extern JS_PUBLIC_API void TraceGrayWrapperTargets(JSTracer* trc,
289 JS::Zone* zone);
292 * Invoke cellCallback on every gray JSObject in the given zone.
294 extern JS_PUBLIC_API void IterateGrayObjects(
295 JS::Zone* zone, IterateGCThingCallback cellCallback, void* data);
297 #if defined(JS_GC_ZEAL) || defined(DEBUG)
298 // Trace the heap and check there are no black to gray edges. These are
299 // not allowed since the cycle collector could throw away the gray thing and
300 // leave a dangling pointer.
302 // This doesn't trace weak maps as these are handled separately.
303 extern JS_PUBLIC_API bool CheckGrayMarkingState(JSRuntime* rt);
304 #endif
306 // Note: this returns nullptr iff |zone| is the atoms zone.
307 extern JS_PUBLIC_API JS::Realm* GetAnyRealmInZone(JS::Zone* zone);
309 // Returns the first realm's global in a compartment. Note: this is not
310 // guaranteed to always be the same realm because individual realms can be
311 // collected by the GC.
312 extern JS_PUBLIC_API JSObject* GetFirstGlobalInCompartment(
313 JS::Compartment* comp);
315 // Returns true if the compartment contains a global object and this global is
316 // not being collected.
317 extern JS_PUBLIC_API bool CompartmentHasLiveGlobal(JS::Compartment* comp);
319 // Returns true if this compartment can be shared across multiple Realms. Used
320 // when we're looking for an existing compartment to place a new Realm in.
321 extern JS_PUBLIC_API bool IsSharableCompartment(JS::Compartment* comp);
323 // This is equal to |&JSObject::class_|. Use it in places where you don't want
324 // to #include vm/JSObject.h.
325 extern JS_PUBLIC_DATA const JSClass* const ObjectClassPtr;
327 JS_PUBLIC_API const JSClass* ProtoKeyToClass(JSProtoKey key);
329 // Returns the key for the class inherited by a given standard class (that
330 // is to say, the prototype of this standard class's prototype).
332 // You must be sure that this corresponds to a standard class with a cached
333 // JSProtoKey before calling this function. In general |key| will match the
334 // cached proto key, except in cases where multiple JSProtoKeys share a
335 // JSClass.
336 inline JSProtoKey InheritanceProtoKeyForStandardClass(JSProtoKey key) {
337 // [Object] has nothing to inherit from.
338 if (key == JSProto_Object) {
339 return JSProto_Null;
342 // If we're ClassSpec defined return the proto key from that
343 if (ProtoKeyToClass(key)->specDefined()) {
344 return ProtoKeyToClass(key)->specInheritanceProtoKey();
347 // Otherwise, we inherit [Object].
348 return JSProto_Object;
351 JS_PUBLIC_API bool ShouldIgnorePropertyDefinition(JSContext* cx, JSProtoKey key,
352 jsid id);
354 JS_PUBLIC_API bool IsFunctionObject(JSObject* obj);
356 JS_PUBLIC_API bool UninlinedIsCrossCompartmentWrapper(const JSObject* obj);
358 // CrossCompartmentWrappers are shared by all realms within the compartment, so
359 // getting a wrapper's realm usually doesn't make sense.
360 static MOZ_ALWAYS_INLINE JS::Realm* GetNonCCWObjectRealm(JSObject* obj) {
361 MOZ_ASSERT(!js::UninlinedIsCrossCompartmentWrapper(obj));
362 return reinterpret_cast<JS::shadow::Object*>(obj)->shape->base->realm;
365 JS_PUBLIC_API void AssertSameCompartment(JSContext* cx, JSObject* obj);
367 JS_PUBLIC_API void AssertSameCompartment(JSContext* cx, JS::HandleValue v);
369 #ifdef JS_DEBUG
370 JS_PUBLIC_API void AssertSameCompartment(JSObject* objA, JSObject* objB);
371 #else
372 inline void AssertSameCompartment(JSObject* objA, JSObject* objB) {}
373 #endif
375 JS_PUBLIC_API void NotifyAnimationActivity(JSObject* obj);
377 JS_PUBLIC_API JSFunction* DefineFunctionWithReserved(
378 JSContext* cx, JSObject* obj, const char* name, JSNative call,
379 unsigned nargs, unsigned attrs);
381 JS_PUBLIC_API JSFunction* NewFunctionWithReserved(JSContext* cx, JSNative call,
382 unsigned nargs,
383 unsigned flags,
384 const char* name);
386 JS_PUBLIC_API JSFunction* NewFunctionByIdWithReserved(JSContext* cx,
387 JSNative native,
388 unsigned nargs,
389 unsigned flags, jsid id);
392 * Get or set function's reserved slot value.
393 * `fun` should be a function created with `*WithReserved` API above.
394 * Such functions have 2 reserved slots, and `which` can be either 0 or 1.
396 JS_PUBLIC_API const JS::Value& GetFunctionNativeReserved(JSObject* fun,
397 size_t which);
399 JS_PUBLIC_API void SetFunctionNativeReserved(JSObject* fun, size_t which,
400 const JS::Value& val);
402 JS_PUBLIC_API bool FunctionHasNativeReserved(JSObject* fun);
404 JS_PUBLIC_API bool GetObjectProto(JSContext* cx, JS::HandleObject obj,
405 JS::MutableHandleObject proto);
407 extern JS_PUBLIC_API JSObject* GetStaticPrototype(JSObject* obj);
409 JS_PUBLIC_API bool GetRealmOriginalEval(JSContext* cx,
410 JS::MutableHandleObject eval);
413 * Add some or all property keys of obj to the id vector *props.
415 * The flags parameter controls which property keys are added. Pass a
416 * combination of the following bits:
418 * JSITER_OWNONLY - Don't also search the prototype chain; only consider
419 * obj's own properties.
421 * JSITER_HIDDEN - Include nonenumerable properties.
423 * JSITER_SYMBOLS - Include property keys that are symbols. The default
424 * behavior is to filter out symbols.
426 * JSITER_SYMBOLSONLY - Exclude non-symbol property keys.
428 * This is the closest C++ API we have to `Reflect.ownKeys(obj)`, or
429 * equivalently, the ES6 [[OwnPropertyKeys]] internal method. Pass
430 * `JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS` as flags to get
431 * results that match the output of Reflect.ownKeys.
433 JS_PUBLIC_API bool GetPropertyKeys(JSContext* cx, JS::HandleObject obj,
434 unsigned flags,
435 JS::MutableHandleIdVector props);
437 JS_PUBLIC_API bool AppendUnique(JSContext* cx, JS::MutableHandleIdVector base,
438 JS::HandleIdVector others);
441 * Determine whether the given string is an array index in the sense of
442 * <https://tc39.github.io/ecma262/#array-index>.
444 * If it isn't, returns false.
446 * If it is, returns true and outputs the index in *indexp.
448 JS_PUBLIC_API bool StringIsArrayIndex(JSLinearString* str, uint32_t* indexp);
451 * Overload of StringIsArrayIndex taking a (char16_t*,length) pair. Behaves
452 * the same as the JSLinearString version.
454 JS_PUBLIC_API bool StringIsArrayIndex(const char16_t* str, uint32_t length,
455 uint32_t* indexp);
457 JS_PUBLIC_API void SetPreserveWrapperCallbacks(
458 JSContext* cx, PreserveWrapperCallback preserveWrapper,
459 HasReleasedWrapperCallback hasReleasedWrapper);
461 JS_PUBLIC_API bool IsObjectInContextCompartment(JSObject* obj,
462 const JSContext* cx);
465 * NB: keep these in sync with the copy in builtin/SelfHostingDefines.h.
467 /* 0x1 is no longer used */
468 /* 0x2 is no longer used */
469 #define JSITER_PRIVATE 0x4 /* Include private names in iteration */
470 #define JSITER_OWNONLY 0x8 /* iterate over obj's own properties only */
471 #define JSITER_HIDDEN 0x10 /* also enumerate non-enumerable properties */
472 #define JSITER_SYMBOLS 0x20 /* also include symbol property keys */
473 #define JSITER_SYMBOLSONLY 0x40 /* exclude string property keys */
474 #define JSITER_FORAWAITOF 0x80 /* for-await-of */
476 using DOMInstanceClassHasProtoAtDepth = bool (*)(const JSClass*, uint32_t,
477 uint32_t);
478 struct JSDOMCallbacks {
479 DOMInstanceClassHasProtoAtDepth instanceClassMatchesProto;
481 using DOMCallbacks = struct JSDOMCallbacks;
483 extern JS_PUBLIC_API void SetDOMCallbacks(JSContext* cx,
484 const DOMCallbacks* callbacks);
486 extern JS_PUBLIC_API const DOMCallbacks* GetDOMCallbacks(JSContext* cx);
488 extern JS_PUBLIC_API JSObject* GetTestingFunctions(JSContext* cx);
490 /* Implemented in jsexn.cpp. */
493 * Get an error type name from a JSExnType constant.
494 * Returns nullptr for invalid arguments and JSEXN_INTERNALERR
496 extern JS_PUBLIC_API JSLinearString* GetErrorTypeName(JSContext* cx,
497 int16_t exnType);
499 /* Implemented in CrossCompartmentWrapper.cpp. */
500 typedef enum NukeReferencesToWindow {
501 NukeWindowReferences,
502 DontNukeWindowReferences
503 } NukeReferencesToWindow;
505 typedef enum NukeReferencesFromTarget {
506 NukeAllReferences,
507 NukeIncomingReferences,
508 } NukeReferencesFromTarget;
511 * These filters are designed to be ephemeral stack classes, and thus don't
512 * do any rooting or holding of their members.
514 struct CompartmentFilter {
515 virtual bool match(JS::Compartment* c) const = 0;
518 struct AllCompartments : public CompartmentFilter {
519 virtual bool match(JS::Compartment* c) const override { return true; }
522 struct SingleCompartment : public CompartmentFilter {
523 JS::Compartment* ours;
524 explicit SingleCompartment(JS::Compartment* c) : ours(c) {}
525 virtual bool match(JS::Compartment* c) const override { return c == ours; }
528 extern JS_PUBLIC_API bool NukeCrossCompartmentWrappers(
529 JSContext* cx, const CompartmentFilter& sourceFilter, JS::Realm* target,
530 NukeReferencesToWindow nukeReferencesToWindow,
531 NukeReferencesFromTarget nukeReferencesFromTarget);
533 extern JS_PUBLIC_API bool AllowNewWrapper(JS::Compartment* target,
534 JSObject* obj);
536 extern JS_PUBLIC_API bool NukedObjectRealm(JSObject* obj);
538 /* Implemented in jsdate.cpp. */
540 /** Detect whether the internal date value is NaN. */
541 extern JS_PUBLIC_API bool DateIsValid(JSContext* cx, JS::HandleObject obj,
542 bool* isValid);
544 extern JS_PUBLIC_API bool DateGetMsecSinceEpoch(JSContext* cx,
545 JS::HandleObject obj,
546 double* msecSinceEpoch);
548 } /* namespace js */
550 namespace js {
552 /* Implemented in vm/StructuredClone.cpp. */
553 extern JS_PUBLIC_API uint64_t GetSCOffset(JSStructuredCloneWriter* writer);
555 } // namespace js
557 namespace js {
559 /* Statically asserted in FunctionFlags.cpp. */
560 static const unsigned JS_FUNCTION_INTERPRETED_BITS = 0x0060;
562 } // namespace js
564 static MOZ_ALWAYS_INLINE const JSJitInfo* FUNCTION_VALUE_TO_JITINFO(
565 const JS::Value& v) {
566 JSObject* obj = &v.toObject();
567 MOZ_ASSERT(JS::GetClass(obj)->isJSFunction());
569 auto* fun = reinterpret_cast<JS::shadow::Function*>(obj);
570 MOZ_ASSERT(!(fun->flagsAndArgCount() & js::JS_FUNCTION_INTERPRETED_BITS),
571 "Unexpected non-native function");
573 return static_cast<const JSJitInfo*>(fun->jitInfoOrScript());
576 static MOZ_ALWAYS_INLINE void SET_JITINFO(JSFunction* func,
577 const JSJitInfo* info) {
578 auto* fun = reinterpret_cast<JS::shadow::Function*>(func);
579 MOZ_ASSERT(!(fun->flagsAndArgCount() & js::JS_FUNCTION_INTERPRETED_BITS));
581 fun->setJitInfoOrScript(const_cast<JSJitInfo*>(info));
584 static_assert(sizeof(jsid) == sizeof(void*));
586 namespace js {
588 static MOZ_ALWAYS_INLINE JS::Value IdToValue(jsid id) {
589 if (id.isString()) {
590 return JS::StringValue(id.toString());
592 if (id.isInt()) {
593 return JS::Int32Value(id.toInt());
595 if (id.isSymbol()) {
596 return JS::SymbolValue(id.toSymbol());
598 MOZ_ASSERT(id.isVoid());
599 return JS::UndefinedValue();
603 * PrepareScriptEnvironmentAndInvoke asserts the embedder has registered a
604 * ScriptEnvironmentPreparer and then it calls the preparer's 'invoke' method
605 * with the given |closure|, with the assumption that the preparer will set up
606 * any state necessary to run script in |global|, invoke |closure| with a valid
607 * JSContext*, report any exceptions thrown from the closure, and return.
609 * PrepareScriptEnvironmentAndInvoke will report any exceptions that are thrown
610 * by the closure. Consumers who want to propagate back whether the closure
611 * succeeded should do so via members of the closure itself.
614 struct ScriptEnvironmentPreparer {
615 struct Closure {
616 virtual bool operator()(JSContext* cx) = 0;
619 virtual void invoke(JS::HandleObject global, Closure& closure) = 0;
622 extern JS_PUBLIC_API void PrepareScriptEnvironmentAndInvoke(
623 JSContext* cx, JS::HandleObject global,
624 ScriptEnvironmentPreparer::Closure& closure);
626 JS_PUBLIC_API void SetScriptEnvironmentPreparer(
627 JSContext* cx, ScriptEnvironmentPreparer* preparer);
629 // Abstract base class for objects that build allocation metadata for JavaScript
630 // values.
631 struct AllocationMetadataBuilder {
632 AllocationMetadataBuilder() = default;
634 // Return a metadata object for the newly constructed object |obj|, or
635 // nullptr if there's no metadata to attach.
637 // Implementations should treat all errors as fatal; there is no way to
638 // report errors from this callback. In particular, the caller provides an
639 // oomUnsafe for overriding implementations to use.
640 virtual JSObject* build(JSContext* cx, JS::HandleObject obj,
641 AutoEnterOOMUnsafeRegion& oomUnsafe) const {
642 return nullptr;
647 * Specify a callback to invoke when creating each JS object in the current
648 * compartment, which may return a metadata object to associate with the
649 * object.
651 JS_PUBLIC_API void SetAllocationMetadataBuilder(
652 JSContext* cx, const AllocationMetadataBuilder* callback);
654 /** Get the metadata associated with an object. */
655 JS_PUBLIC_API JSObject* GetAllocationMetadata(JSObject* obj);
657 JS_PUBLIC_API bool GetElementsWithAdder(JSContext* cx, JS::HandleObject obj,
658 JS::HandleObject receiver,
659 uint32_t begin, uint32_t end,
660 js::ElementAdder* adder);
662 JS_PUBLIC_API bool ForwardToNative(JSContext* cx, JSNative native,
663 const JS::CallArgs& args);
666 * Helper function for HTMLDocument and HTMLFormElement.
668 * These are the only two interfaces that have [OverrideBuiltins], a named
669 * getter, and no named setter. They're implemented as proxies with a custom
670 * getOwnPropertyDescriptor() method. Unfortunately, overriding
671 * getOwnPropertyDescriptor() automatically affects the behavior of set(),
672 * which normally is just common sense but is *not* desired for these two
673 * interfaces.
675 * The fix is for these two interfaces to override set() to ignore the
676 * getOwnPropertyDescriptor() override.
678 * SetPropertyIgnoringNamedGetter is exposed to make it easier to override
679 * set() in this way. It carries out all the steps of BaseProxyHandler::set()
680 * except the initial getOwnPropertyDescriptor() call. The caller must supply
681 * that descriptor as the 'ownDesc' parameter.
683 * Implemented in proxy/BaseProxyHandler.cpp.
685 JS_PUBLIC_API bool SetPropertyIgnoringNamedGetter(
686 JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v,
687 JS::HandleValue receiver,
688 JS::Handle<mozilla::Maybe<JS::PropertyDescriptor>> ownDesc,
689 JS::ObjectOpResult& result);
691 // This function is for one specific use case, please don't use this for
692 // anything else!
693 extern JS_PUBLIC_API bool ExecuteInFrameScriptEnvironment(
694 JSContext* cx, JS::HandleObject obj, JS::HandleScript script,
695 JS::MutableHandleObject scope);
697 extern JS_PUBLIC_API bool IsSavedFrame(JSObject* obj);
699 // Matches the condition in js/src/jit/ProcessExecutableMemory.cpp
700 #if defined(XP_WIN)
701 // Parameters use void* types to avoid #including windows.h. The return value of
702 // this function is returned from the exception handler.
703 typedef long (*JitExceptionHandler)(void* exceptionRecord, // PEXECTION_RECORD
704 void* context); // PCONTEXT
707 * Windows uses "structured exception handling" to handle faults. When a fault
708 * occurs, the stack is searched for a handler (similar to C++ exception
709 * handling). If the search does not find a handler, the "unhandled exception
710 * filter" is called. Breakpad uses the unhandled exception filter to do crash
711 * reporting. Unfortunately, on Win64, JIT code on the stack completely throws
712 * off this unwinding process and prevents the unhandled exception filter from
713 * being called. The reason is that Win64 requires unwind information be
714 * registered for all code regions and JIT code has none. While it is possible
715 * to register full unwind information for JIT code, this is a lot of work (one
716 * has to be able to recover the frame pointer at any PC) so instead we register
717 * a handler for all JIT code that simply calls breakpad's unhandled exception
718 * filter (which will perform crash reporting and then terminate the process).
719 * This would be wrong if there was an outer __try block that expected to handle
720 * the fault, but this is not generally allowed.
722 * Gecko must call SetJitExceptionFilter before any JIT code is compiled and
723 * only once per process.
725 extern JS_PUBLIC_API void SetJitExceptionHandler(JitExceptionHandler handler);
726 #endif
728 extern JS_PUBLIC_API bool ReportIsNotFunction(JSContext* cx, JS::HandleValue v);
730 class MOZ_STACK_CLASS JS_PUBLIC_API AutoAssertNoContentJS {
731 public:
732 explicit AutoAssertNoContentJS(JSContext* cx);
733 ~AutoAssertNoContentJS();
735 private:
736 JSContext* context_;
737 bool prevAllowContentJS_;
741 * This function reports memory used by a zone in bytes, this includes:
742 * * The size of this JS GC zone.
743 * * Malloc memory referred to from this zone.
744 * * JIT memory for this zone.
746 * Note that malloc memory referred to from this zone can include
747 * SharedArrayBuffers which may also be referred to from other zones. Adding the
748 * memory usage of multiple zones may lead to an over-estimate.
750 extern JS_PUBLIC_API uint64_t GetMemoryUsageForZone(JS::Zone* zone);
752 enum class MemoryUse : uint8_t;
754 namespace gc {
756 struct SharedMemoryUse {
757 explicit SharedMemoryUse(MemoryUse use) : count(0), nbytes(0) {
758 #ifdef DEBUG
759 this->use = use;
760 #endif
763 size_t count;
764 size_t nbytes;
765 #ifdef DEBUG
766 MemoryUse use;
767 #endif
770 // A map which tracks shared memory uses (shared in the sense that an allocation
771 // can be referenced by more than one GC thing in a zone). This allows us to
772 // only account for the memory once.
773 using SharedMemoryMap =
774 HashMap<void*, SharedMemoryUse, DefaultHasher<void*>, SystemAllocPolicy>;
776 } /* namespace gc */
778 extern JS_PUBLIC_API const gc::SharedMemoryMap& GetSharedMemoryUsageForZone(
779 JS::Zone* zone);
782 * This function only reports GC heap memory,
783 * and not malloc allocated memory associated with GC things.
784 * It reports the total of all memory for the whole Runtime.
786 extern JS_PUBLIC_API uint64_t GetGCHeapUsage(JSContext* cx);
788 class JS_PUBLIC_API CompartmentTransplantCallback {
789 public:
790 virtual JSObject* getObjectToTransplant(JS::Compartment* compartment) = 0;
793 // Gather a set of remote window proxies by calling the callback on every
794 // compartment, then transform them into cross-compartment wrappers to newTarget
795 // via brain transplants. If there's a proxy in newTarget's compartment, it will
796 // get swapped with newTarget, and the value of newTarget will be updated. If
797 // the callback returns null for a compartment, no cross-compartment wrapper
798 // will be created for that compartment. Any non-null values it returns must be
799 // DOM remote proxies from the compartment that was passed in.
800 extern JS_PUBLIC_API void RemapRemoteWindowProxies(
801 JSContext* cx, CompartmentTransplantCallback* callback,
802 JS::MutableHandleObject newTarget);
804 extern JS_PUBLIC_API JS::Zone* GetObjectZoneFromAnyThread(const JSObject* obj);
806 } /* namespace js */
808 #endif /* jsfriendapi_h */