Debian Codegraph @

js/src/jsfriendapi.h

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