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/. */
12 #include "mozilla/AlreadyAddRefed.h"
13 #include "mozilla/FloatingPoint.h"
14 #include "mozilla/Maybe.h"
15 #include "mozilla/MemoryReporting.h"
16 #include "mozilla/RangedPtr.h"
17 #include "mozilla/RefPtr.h"
18 #include "mozilla/TimeStamp.h"
19 #include "mozilla/Utf8.h"
20 #include "mozilla/Variant.h"
29 #include "js/AllocPolicy.h"
30 #include "js/CallAndConstruct.h" // JS::Call, JS_CallFunction, JS_CallFunctionName, JS_CallFunctionValue
31 #include "js/CallArgs.h"
32 #include "js/CharacterEncoding.h"
34 #include "js/CompileOptions.h"
35 #include "js/Context.h"
37 #include "js/ErrorInterceptor.h"
38 #include "js/ErrorReport.h"
39 #include "js/Exception.h"
41 #include "js/GCVector.h"
42 #include "js/GlobalObject.h"
43 #include "js/HashTable.h"
45 #include "js/Interrupt.h"
46 #include "js/MapAndSet.h"
47 #include "js/MemoryCallbacks.h"
48 #include "js/MemoryFunctions.h"
49 #include "js/OffThreadScriptCompilation.h"
50 #include "js/Principals.h"
51 #include "js/PropertyAndElement.h" // JS_Enumerate
52 #include "js/PropertyDescriptor.h"
53 #include "js/PropertySpec.h"
55 #include "js/RealmIterators.h"
56 #include "js/RealmOptions.h"
57 #include "js/RefCounted.h"
58 #include "js/RootingAPI.h"
59 #include "js/ScriptPrivate.h"
61 #include "js/StreamConsumer.h"
62 #include "js/String.h"
63 #include "js/TelemetryTimers.h"
64 #include "js/TracingAPI.h"
65 #include "js/Transcoding.h"
66 #include "js/UniquePtr.h"
67 #include "js/Utility.h"
69 #include "js/ValueArray.h"
70 #include "js/Vector.h"
71 #include "js/WaitCallbacks.h"
72 #include "js/WeakMap.h"
73 #include "js/WrapperCallbacks.h"
76 /************************************************************************/
80 * Tell JS engine whether to use fdlibm for Math.sin, Math.cos, and Math.tan.
81 * Using fdlibm ensures that we don't expose a math fingerprint.
83 extern JS_PUBLIC_API
void SetUseFdlibmForSinCosTan(bool value
);
86 /************************************************************************/
88 struct JSFunctionSpec
;
89 struct JSPropertySpec
;
93 template <typename UnitT
>
98 using ValueVector
= JS::GCVector
<JS::Value
>;
99 using IdVector
= JS::GCVector
<jsid
>;
100 using ScriptVector
= JS::GCVector
<JSScript
*>;
101 using StringVector
= JS::GCVector
<JSString
*>;
105 /************************************************************************/
107 static MOZ_ALWAYS_INLINE
JS::Value
JS_NumberValue(double d
) {
109 d
= JS::CanonicalizeNaN(d
);
110 if (mozilla::NumberIsInt32(d
, &i
)) {
111 return JS::Int32Value(i
);
113 return JS::DoubleValue(d
);
116 /************************************************************************/
118 JS_PUBLIC_API
bool JS_StringHasBeenPinned(JSContext
* cx
, JSString
* str
);
120 /************************************************************************/
122 /** Microseconds since the epoch, midnight, January 1, 1970 UTC. */
123 extern JS_PUBLIC_API
int64_t JS_Now(void);
125 extern JS_PUBLIC_API
bool JS_ValueToObject(JSContext
* cx
, JS::HandleValue v
,
126 JS::MutableHandleObject objp
);
128 extern JS_PUBLIC_API JSFunction
* JS_ValueToFunction(JSContext
* cx
,
131 extern JS_PUBLIC_API JSFunction
* JS_ValueToConstructor(JSContext
* cx
,
134 extern JS_PUBLIC_API JSString
* JS_ValueToSource(JSContext
* cx
,
135 JS::Handle
<JS::Value
> v
);
137 extern JS_PUBLIC_API
bool JS_DoubleIsInt32(double d
, int32_t* ip
);
139 extern JS_PUBLIC_API JSType
JS_TypeOfValue(JSContext
* cx
,
140 JS::Handle
<JS::Value
> v
);
144 extern JS_PUBLIC_API
const char* InformalValueTypeName(const JS::Value
& v
);
148 /** True iff fun is the global eval function. */
149 extern JS_PUBLIC_API
bool JS_IsBuiltinEvalFunction(JSFunction
* fun
);
151 /** True iff fun is the Function constructor. */
152 extern JS_PUBLIC_API
bool JS_IsBuiltinFunctionConstructor(JSFunction
* fun
);
154 extern JS_PUBLIC_API
const char* JS_GetImplementationVersion(void);
156 extern JS_PUBLIC_API
void JS_SetWrapObjectCallbacks(
157 JSContext
* cx
, const JSWrapObjectCallbacks
* callbacks
);
159 // Examine a value to determine if it is one of the built-in Error types.
160 // If so, return the error type.
161 extern JS_PUBLIC_API
mozilla::Maybe
<JSExnType
> JS_GetErrorType(
162 const JS::Value
& val
);
164 extern JS_PUBLIC_API
bool JS_WrapObject(JSContext
* cx
,
165 JS::MutableHandleObject objp
);
167 extern JS_PUBLIC_API
bool JS_WrapValue(JSContext
* cx
,
168 JS::MutableHandleValue vp
);
170 extern JS_PUBLIC_API JSObject
* JS_TransplantObject(JSContext
* cx
,
171 JS::HandleObject origobj
,
172 JS::HandleObject target
);
175 * Resolve id, which must contain either a string or an int, to a standard
176 * class name in obj if possible, defining the class's constructor and/or
177 * prototype and storing true in *resolved. If id does not name a standard
178 * class or a top-level property induced by initializing a standard class,
179 * store false in *resolved and just return true. Return false on error,
180 * as usual for bool result-typed API entry points.
182 * This API can be called directly from a global object class's resolve op,
183 * to define standard classes lazily. The class should either have an enumerate
184 * hook that calls JS_EnumerateStandardClasses, or a newEnumerate hook that
185 * calls JS_NewEnumerateStandardClasses. newEnumerate is preferred because it's
186 * faster (does not define all standard classes).
188 extern JS_PUBLIC_API
bool JS_ResolveStandardClass(JSContext
* cx
,
189 JS::HandleObject obj
,
193 extern JS_PUBLIC_API
bool JS_MayResolveStandardClass(const JSAtomState
& names
,
197 extern JS_PUBLIC_API
bool JS_EnumerateStandardClasses(JSContext
* cx
,
198 JS::HandleObject obj
);
201 * Fill "properties" with a list of standard class names that have not yet been
202 * resolved on "obj". This can be used as (part of) a newEnumerate class hook
203 * on a global. Already-resolved things are excluded because they might have
204 * been deleted by script after being resolved and enumeration considers
205 * already-defined properties anyway.
207 extern JS_PUBLIC_API
bool JS_NewEnumerateStandardClasses(
208 JSContext
* cx
, JS::HandleObject obj
, JS::MutableHandleIdVector properties
,
209 bool enumerableOnly
);
212 * Fill "properties" with a list of standard class names. This can be used for
213 * proxies that want to define behavior that looks like enumerating a global
214 * without touching the global itself.
216 extern JS_PUBLIC_API
bool JS_NewEnumerateStandardClassesIncludingResolved(
217 JSContext
* cx
, JS::HandleObject obj
, JS::MutableHandleIdVector properties
,
218 bool enumerableOnly
);
220 extern JS_PUBLIC_API
bool JS_GetClassObject(JSContext
* cx
, JSProtoKey key
,
221 JS::MutableHandle
<JSObject
*> objp
);
223 extern JS_PUBLIC_API
bool JS_GetClassPrototype(
224 JSContext
* cx
, JSProtoKey key
, JS::MutableHandle
<JSObject
*> objp
);
229 * Determine if the given object is an instance/prototype/constructor for a
230 * standard class. If so, return the associated JSProtoKey. If not, return
234 extern JS_PUBLIC_API JSProtoKey
IdentifyStandardInstance(JSObject
* obj
);
236 extern JS_PUBLIC_API JSProtoKey
IdentifyStandardPrototype(JSObject
* obj
);
238 extern JS_PUBLIC_API JSProtoKey
239 IdentifyStandardInstanceOrPrototype(JSObject
* obj
);
241 extern JS_PUBLIC_API JSProtoKey
IdentifyStandardConstructor(JSObject
* obj
);
243 extern JS_PUBLIC_API
void ProtoKeyToId(JSContext
* cx
, JSProtoKey key
,
244 JS::MutableHandleId idp
);
248 extern JS_PUBLIC_API JSProtoKey
JS_IdToProtoKey(JSContext
* cx
, JS::HandleId id
);
250 extern JS_PUBLIC_API JSObject
* JS_GlobalLexicalEnvironment(JSObject
* obj
);
252 extern JS_PUBLIC_API
bool JS_HasExtensibleLexicalEnvironment(JSObject
* obj
);
254 extern JS_PUBLIC_API JSObject
* JS_ExtensibleLexicalEnvironment(JSObject
* obj
);
257 * Add 'Reflect.parse', a SpiderMonkey extension, to the Reflect object on the
260 extern JS_PUBLIC_API
bool JS_InitReflectParse(JSContext
* cx
,
261 JS::HandleObject global
);
264 * Add various profiling-related functions as properties of the given object.
265 * Defined in builtin/Profilers.cpp.
267 extern JS_PUBLIC_API
bool JS_DefineProfilingFunctions(JSContext
* cx
,
268 JS::HandleObject obj
);
273 * Tell JS engine whether Profile Timeline Recording is enabled or not.
274 * If Profile Timeline Recording is enabled, data shown there like stack won't
276 * This is global state and not associated with specific runtime or context.
278 extern JS_PUBLIC_API
void SetProfileTimelineRecordingEnabled(bool enabled
);
280 extern JS_PUBLIC_API
bool IsProfileTimelineRecordingEnabled();
284 /************************************************************************/
286 extern JS_PUBLIC_API
bool JS_ValueToId(JSContext
* cx
, JS::HandleValue v
,
287 JS::MutableHandleId idp
);
289 extern JS_PUBLIC_API
bool JS_StringToId(JSContext
* cx
, JS::HandleString s
,
290 JS::MutableHandleId idp
);
292 extern JS_PUBLIC_API
bool JS_IdToValue(JSContext
* cx
, jsid id
,
293 JS::MutableHandle
<JS::Value
> vp
);
298 * Convert obj to a primitive value. On success, store the result in vp and
301 * The hint argument must be JSTYPE_STRING, JSTYPE_NUMBER, or
302 * JSTYPE_UNDEFINED (no hint).
304 * Implements: ES6 7.1.1 ToPrimitive(input, [PreferredType]).
306 extern JS_PUBLIC_API
bool ToPrimitive(JSContext
* cx
, JS::HandleObject obj
,
307 JSType hint
, JS::MutableHandleValue vp
);
310 * If args.get(0) is one of the strings "string", "number", or "default", set
311 * result to JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_UNDEFINED accordingly and
312 * return true. Otherwise, return false with a TypeError pending.
314 * This can be useful in implementing a @@toPrimitive method.
316 extern JS_PUBLIC_API
bool GetFirstArgumentAsTypeHint(JSContext
* cx
,
323 * Defines a builtin constructor and prototype. Returns the prototype object.
325 * - Defines a property named `name` on `obj`, with its value set to a
326 * newly-created JS function that invokes the `constructor` JSNative. The
327 * `length` of the function is `nargs`.
329 * - Creates a prototype object with proto `protoProto` and class `protoClass`.
330 * If `protoProto` is `nullptr`, `Object.prototype` will be used instead.
331 * If `protoClass` is `nullptr`, the prototype object will be a plain JS
334 * - The `ps` and `fs` properties/functions will be defined on the prototype
337 * - The `static_ps` and `static_fs` properties/functions will be defined on the
340 extern JS_PUBLIC_API JSObject
* JS_InitClass(
341 JSContext
* cx
, JS::HandleObject obj
, const JSClass
* protoClass
,
342 JS::HandleObject protoProto
, const char* name
, JSNative constructor
,
343 unsigned nargs
, const JSPropertySpec
* ps
, const JSFunctionSpec
* fs
,
344 const JSPropertySpec
* static_ps
, const JSFunctionSpec
* static_fs
);
347 * Set up ctor.prototype = proto and proto.constructor = ctor with the
348 * right property flags.
350 extern JS_PUBLIC_API
bool JS_LinkConstructorAndPrototype(
351 JSContext
* cx
, JS::Handle
<JSObject
*> ctor
, JS::Handle
<JSObject
*> proto
);
353 extern JS_PUBLIC_API
bool JS_InstanceOf(JSContext
* cx
,
354 JS::Handle
<JSObject
*> obj
,
355 const JSClass
* clasp
,
358 extern JS_PUBLIC_API
bool JS_HasInstance(JSContext
* cx
,
359 JS::Handle
<JSObject
*> obj
,
360 JS::Handle
<JS::Value
> v
, bool* bp
);
365 // http://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance. If
366 // you're looking for the equivalent of "instanceof", you want JS_HasInstance,
367 // not this function.
368 extern JS_PUBLIC_API
bool OrdinaryHasInstance(JSContext
* cx
,
370 HandleValue v
, bool* bp
);
374 extern JS_PUBLIC_API JSObject
* JS_GetConstructor(JSContext
* cx
,
375 JS::Handle
<JSObject
*> proto
);
377 extern JS_PUBLIC_API JSObject
* JS_NewObject(JSContext
* cx
,
378 const JSClass
* clasp
);
380 extern JS_PUBLIC_API
bool JS_IsNative(JSObject
* obj
);
383 * Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default
384 * proto. If proto is nullptr, the JS object will have `null` as [[Prototype]].
386 extern JS_PUBLIC_API JSObject
* JS_NewObjectWithGivenProto(
387 JSContext
* cx
, const JSClass
* clasp
, JS::Handle
<JSObject
*> proto
);
390 * Creates a new plain object, like `new Object()`, with Object.prototype as
393 extern JS_PUBLIC_API JSObject
* JS_NewPlainObject(JSContext
* cx
);
396 * Freeze obj, and all objects it refers to, recursively. This will not recurse
397 * through non-extensible objects, on the assumption that those are already
400 extern JS_PUBLIC_API
bool JS_DeepFreezeObject(JSContext
* cx
,
401 JS::Handle
<JSObject
*> obj
);
404 * Freezes an object; see ES5's Object.freeze(obj) method.
406 extern JS_PUBLIC_API
bool JS_FreezeObject(JSContext
* cx
,
407 JS::Handle
<JSObject
*> obj
);
409 /*** Standard internal methods **********************************************
411 * The functions below are the fundamental operations on objects.
413 * ES6 specifies 14 internal methods that define how objects behave. The
414 * standard is actually quite good on this topic, though you may have to read
415 * it a few times. See ES6 sections 6.1.7.2 and 6.1.7.3.
417 * When 'obj' is an ordinary object, these functions have boring standard
418 * behavior as specified by ES6 section 9.1; see the section about internal
419 * methods in js/src/vm/NativeObject.h.
421 * Proxies override the behavior of internal methods. So when 'obj' is a proxy,
422 * any one of the functions below could do just about anything. See
427 * Get the prototype of |obj|, storing it in |proto|.
429 * Implements: ES6 [[GetPrototypeOf]] internal method.
431 extern JS_PUBLIC_API
bool JS_GetPrototype(JSContext
* cx
, JS::HandleObject obj
,
432 JS::MutableHandleObject result
);
435 * If |obj| (underneath any functionally-transparent wrapper proxies) has as
436 * its [[GetPrototypeOf]] trap the ordinary [[GetPrototypeOf]] behavior defined
437 * for ordinary objects, set |*isOrdinary = true| and store |obj|'s prototype
438 * in |result|. Otherwise set |*isOrdinary = false|. In case of error, both
439 * outparams have unspecified value.
441 extern JS_PUBLIC_API
bool JS_GetPrototypeIfOrdinary(
442 JSContext
* cx
, JS::HandleObject obj
, bool* isOrdinary
,
443 JS::MutableHandleObject result
);
446 * Change the prototype of obj.
448 * Implements: ES6 [[SetPrototypeOf]] internal method.
450 * In cases where ES6 [[SetPrototypeOf]] returns false without an exception,
451 * JS_SetPrototype throws a TypeError and returns false.
453 * Performance warning: JS_SetPrototype is very bad for performance. It may
454 * cause compiled jit-code to be invalidated. It also causes not only obj but
455 * all other objects in the same "group" as obj to be permanently deoptimized.
456 * It's better to create the object with the right prototype from the start.
458 extern JS_PUBLIC_API
bool JS_SetPrototype(JSContext
* cx
, JS::HandleObject obj
,
459 JS::HandleObject proto
);
462 * Determine whether obj is extensible. Extensible objects can have new
463 * properties defined on them. Inextensible objects can't, and their
464 * [[Prototype]] slot is fixed as well.
466 * Implements: ES6 [[IsExtensible]] internal method.
468 extern JS_PUBLIC_API
bool JS_IsExtensible(JSContext
* cx
, JS::HandleObject obj
,
472 * Attempt to make |obj| non-extensible.
474 * Not all failures are treated as errors. See the comment on
475 * JS::ObjectOpResult in js/public/Class.h.
477 * Implements: ES6 [[PreventExtensions]] internal method.
479 extern JS_PUBLIC_API
bool JS_PreventExtensions(JSContext
* cx
,
480 JS::HandleObject obj
,
481 JS::ObjectOpResult
& result
);
484 * Attempt to make the [[Prototype]] of |obj| immutable, such that any attempt
485 * to modify it will fail. If an error occurs during the attempt, return false
486 * (with a pending exception set, depending upon the nature of the error). If
487 * no error occurs, return true with |*succeeded| set to indicate whether the
488 * attempt successfully made the [[Prototype]] immutable.
490 * This is a nonstandard internal method.
492 extern JS_PUBLIC_API
bool JS_SetImmutablePrototype(JSContext
* cx
,
493 JS::HandleObject obj
,
497 * Equivalent to `Object.assign(target, src)`: Copies the properties from the
498 * `src` object (which must not be null) to `target` (which also must not be
501 extern JS_PUBLIC_API
bool JS_AssignObject(JSContext
* cx
,
502 JS::HandleObject target
,
503 JS::HandleObject src
);
508 * On success, returns true, setting |*isMap| to true if |obj| is a Map object
509 * or a wrapper around one, or to false if not. Returns false on failure.
511 * This method returns true with |*isMap == false| when passed an ES6 proxy
512 * whose target is a Map, or when passed a revoked proxy.
514 extern JS_PUBLIC_API
bool IsMapObject(JSContext
* cx
, JS::HandleObject obj
,
518 * On success, returns true, setting |*isSet| to true if |obj| is a Set object
519 * or a wrapper around one, or to false if not. Returns false on failure.
521 * This method returns true with |*isSet == false| when passed an ES6 proxy
522 * whose target is a Set, or when passed a revoked proxy.
524 extern JS_PUBLIC_API
bool IsSetObject(JSContext
* cx
, JS::HandleObject obj
,
530 * Assign 'undefined' to all of the object's non-reserved slots. Note: this is
531 * done for all slots, regardless of the associated property descriptor.
533 JS_PUBLIC_API
void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj
);
535 extern JS_PUBLIC_API
void JS_SetReservedSlot(JSObject
* obj
, uint32_t index
,
538 extern JS_PUBLIC_API
void JS_InitReservedSlot(JSObject
* obj
, uint32_t index
,
539 void* ptr
, size_t nbytes
,
542 template <typename T
>
543 void JS_InitReservedSlot(JSObject
* obj
, uint32_t index
, T
* ptr
,
545 JS_InitReservedSlot(obj
, index
, ptr
, sizeof(T
), use
);
548 /************************************************************************/
550 /* native that can be called as a ctor */
551 static constexpr unsigned JSFUN_CONSTRUCTOR
= 0x400;
553 /* | of all the JSFUN_* flags */
554 static constexpr unsigned JSFUN_FLAGS_MASK
= 0x400;
556 static_assert((JSPROP_FLAGS_MASK
& JSFUN_FLAGS_MASK
) == 0,
557 "JSFUN_* flags do not overlap JSPROP_* flags, because bits from "
558 "the two flag-sets appear in the same flag in some APIs");
561 * Functions and scripts.
563 extern JS_PUBLIC_API JSFunction
* JS_NewFunction(JSContext
* cx
, JSNative call
,
564 unsigned nargs
, unsigned flags
,
569 extern JS_PUBLIC_API JSFunction
* GetSelfHostedFunction(
570 JSContext
* cx
, const char* selfHostedName
, HandleId id
, unsigned nargs
);
573 * Create a new function based on the given JSFunctionSpec, *fs.
574 * id is the result of a successful call to
575 * `PropertySpecNameToId(cx, fs->name, &id)` or
576 `PropertySpecNameToPermanentId(cx, fs->name, &id)`.
578 * Unlike JS_DefineFunctions, this does not treat fs as an array.
579 * *fs must not be JS_FS_END.
581 extern JS_PUBLIC_API JSFunction
* NewFunctionFromSpec(JSContext
* cx
,
582 const JSFunctionSpec
* fs
,
586 * Same as above, but without an id arg, for callers who don't have
589 extern JS_PUBLIC_API JSFunction
* NewFunctionFromSpec(JSContext
* cx
,
590 const JSFunctionSpec
* fs
);
594 extern JS_PUBLIC_API JSObject
* JS_GetFunctionObject(JSFunction
* fun
);
597 * Return the function's identifier as a JSString, or null if fun is unnamed.
598 * The returned string lives as long as fun, so you don't need to root a saved
599 * reference to it if fun is well-connected or rooted, and provided you bound
600 * the use of the saved reference by fun's lifetime.
602 extern JS_PUBLIC_API JSString
* JS_GetFunctionId(JSFunction
* fun
);
605 * Return a function's display name. This is the defined name if one was given
606 * where the function was defined, or it could be an inferred name by the JS
607 * engine in the case that the function was defined to be anonymous. This can
608 * still return nullptr if a useful display name could not be inferred. The
609 * same restrictions on rooting as those in JS_GetFunctionId apply.
611 extern JS_PUBLIC_API JSString
* JS_GetFunctionDisplayId(JSFunction
* fun
);
614 * Return the arity of fun, which includes default parameters and rest
615 * parameter. This can be used as `nargs` parameter for other functions.
617 extern JS_PUBLIC_API
uint16_t JS_GetFunctionArity(JSFunction
* fun
);
620 * Return the length of fun, which is the original value of .length property.
622 JS_PUBLIC_API
bool JS_GetFunctionLength(JSContext
* cx
, JS::HandleFunction fun
,
626 * Infallible predicate to test whether obj is a function object (faster than
627 * comparing obj's class name to "Function", but equivalent unless someone has
628 * overwritten the "Function" identifier with a different constructor and then
629 * created instances using that constructor that might be passed in as obj).
631 extern JS_PUBLIC_API
bool JS_ObjectIsFunction(JSObject
* obj
);
633 extern JS_PUBLIC_API
bool JS_IsNativeFunction(JSObject
* funobj
, JSNative call
);
635 /** Return whether the given function is a valid constructor. */
636 extern JS_PUBLIC_API
bool JS_IsConstructor(JSFunction
* fun
);
638 extern JS_PUBLIC_API
bool JS_ObjectIsBoundFunction(JSObject
* obj
);
640 extern JS_PUBLIC_API JSObject
* JS_GetBoundFunctionTarget(JSObject
* obj
);
642 extern JS_PUBLIC_API JSObject
* JS_GetGlobalFromScript(JSScript
* script
);
644 extern JS_PUBLIC_API
const char* JS_GetScriptFilename(JSScript
* script
);
646 extern JS_PUBLIC_API
unsigned JS_GetScriptBaseLineNumber(JSContext
* cx
,
649 extern JS_PUBLIC_API JSScript
* JS_GetFunctionScript(JSContext
* cx
,
650 JS::HandleFunction fun
);
652 extern JS_PUBLIC_API JSString
* JS_DecompileScript(JSContext
* cx
,
653 JS::Handle
<JSScript
*> script
);
655 extern JS_PUBLIC_API JSString
* JS_DecompileFunction(
656 JSContext
* cx
, JS::Handle
<JSFunction
*> fun
);
661 * Supply an alternative stack to incorporate into captured SavedFrame
662 * backtraces as the imputed caller of asynchronous JavaScript calls, like async
663 * function resumptions and DOM callbacks.
665 * When one async function awaits the result of another, it's natural to think
666 * of that as a sort of function call: just as execution resumes from an
667 * ordinary call expression when the callee returns, with the return value
668 * providing the value of the call expression, execution resumes from an 'await'
669 * expression after the awaited asynchronous function call returns, passing the
670 * return value along.
672 * Call the two async functions in such a situation the 'awaiter' and the
675 * As an async function, the awaitee contains 'await' expressions of its own.
676 * Whenever it executes after its first 'await', there are never any actual
677 * frames on the JavaScript stack under it; its awaiter is certainly not there.
678 * An await expression's continuation is invoked as a promise callback, and
679 * those are always called directly from the event loop in their own microtick.
680 * (Ignore unusual cases like nested event loops.)
682 * But because await expressions bear such a strong resemblance to calls (and
683 * deliberately so!), it would be unhelpful for stacks captured within the
684 * awaitee to be empty; instead, they should present the awaiter as the caller.
686 * The AutoSetAsyncStackForNewCalls RAII class supplies a SavedFrame stack to
687 * treat as the caller of any JavaScript invocations that occur within its
688 * lifetime. Any SavedFrame stack captured during such an invocation uses the
689 * SavedFrame passed to the constructor's 'stack' parameter as the 'asyncParent'
690 * property of the SavedFrame for the invocation's oldest frame. Its 'parent'
691 * property will be null, so stack-walking code can distinguish this
692 * awaiter/awaitee transition from an ordinary caller/callee transition.
694 * The constructor's 'asyncCause' parameter supplies a string explaining what
695 * sort of asynchronous call caused 'stack' to be spliced into the backtrace;
696 * for example, async function resumptions use the string "async". This appears
697 * as the 'asyncCause' property of the 'asyncParent' SavedFrame.
699 * Async callers are distinguished in the string form of a SavedFrame chain by
700 * including the 'asyncCause' string in the frame. It appears before the
701 * function name, with the two separated by a '*'.
703 * Note that, as each compartment has its own set of SavedFrames, the
704 * 'asyncParent' may actually point to a copy of 'stack', rather than the exact
705 * SavedFrame object passed.
707 * The youngest frame of 'stack' is not mutated to take the asyncCause string as
708 * its 'asyncCause' property; SavedFrame objects are immutable. Rather, a fresh
709 * clone of the frame is created with the needed 'asyncCause' property.
711 * The 'kind' argument specifies how aggressively 'stack' supplants any
712 * JavaScript frames older than this AutoSetAsyncStackForNewCalls object. If
713 * 'kind' is 'EXPLICIT', then all captured SavedFrame chains take on 'stack' as
714 * their 'asyncParent' where the chain crosses this object's scope. If 'kind' is
715 * 'IMPLICIT', then 'stack' is only included in captured chains if there are no
716 * other JavaScript frames on the stack --- that is, only if the stack would
717 * otherwise end at that point.
719 * AutoSetAsyncStackForNewCalls affects only SavedFrame chains; it does not
720 * affect Debugger.Frame or js::FrameIter. SavedFrame chains are used for
721 * Error.stack, allocation profiling, Promise debugging, and so on.
723 * See also `js/src/doc/SavedFrame/SavedFrame.md` for documentation on async
726 class MOZ_STACK_CLASS JS_PUBLIC_API AutoSetAsyncStackForNewCalls
{
728 RootedObject oldAsyncStack
;
729 const char* oldAsyncCause
;
730 bool oldAsyncCallIsExplicit
;
733 enum class AsyncCallKind
{
734 // The ordinary kind of call, where we may apply an async
735 // parent if there is no ordinary parent.
737 // An explicit async parent, e.g., callFunctionWithAsyncStack,
738 // where we always want to override any ordinary parent.
742 // The stack parameter cannot be null by design, because it would be
743 // ambiguous whether that would clear any scheduled async stack and make the
744 // normal stack reappear in the new call, or just keep the async stack
745 // already scheduled for the new call, if any.
747 // asyncCause is owned by the caller and its lifetime must outlive the
748 // lifetime of the AutoSetAsyncStackForNewCalls object. It is strongly
749 // encouraged that asyncCause be a string constant or similar statically
751 AutoSetAsyncStackForNewCalls(JSContext
* cx
, HandleObject stack
,
752 const char* asyncCause
,
753 AsyncCallKind kind
= AsyncCallKind::IMPLICIT
);
754 ~AutoSetAsyncStackForNewCalls();
759 /************************************************************************/
763 JS_PUBLIC_API
bool PropertySpecNameEqualsId(JSPropertySpec::Name name
,
767 * Create a jsid that does not need to be marked for GC.
769 * 'name' is a JSPropertySpec::name or JSFunctionSpec::name value. The
770 * resulting jsid, on success, is either an interned string or a well-known
771 * symbol; either way it is immune to GC so there is no need to visit *idp
774 JS_PUBLIC_API
bool PropertySpecNameToPermanentId(JSContext
* cx
,
775 JSPropertySpec::Name name
,
780 /************************************************************************/
783 * A JS context always has an "owner thread". The owner thread is set when the
784 * context is created (to the current thread) and practically all entry points
785 * into the JS engine check that a context (or anything contained in the
786 * context: runtime, compartment, object, etc) is only touched by its owner
787 * thread. Embeddings may check this invariant outside the JS engine by calling
788 * JS_AbortIfWrongThread (which will abort if not on the owner thread, even for
792 extern JS_PUBLIC_API
void JS_AbortIfWrongThread(JSContext
* cx
);
794 /************************************************************************/
797 * A constructor can request that the JS engine create a default new 'this'
798 * object of the given class, using the callee to determine parentage and
801 extern JS_PUBLIC_API JSObject
* JS_NewObjectForConstructor(
802 JSContext
* cx
, const JSClass
* clasp
, const JS::CallArgs
& args
);
804 /************************************************************************/
806 extern JS_PUBLIC_API
void JS_SetParallelParsingEnabled(JSContext
* cx
,
809 extern JS_PUBLIC_API
void JS_SetOffthreadIonCompilationEnabled(JSContext
* cx
,
813 #define JIT_COMPILER_OPTIONS(Register) \
814 Register(BASELINE_INTERPRETER_WARMUP_TRIGGER, "blinterp.warmup.trigger") \
815 Register(BASELINE_WARMUP_TRIGGER, "baseline.warmup.trigger") \
816 Register(IC_FORCE_MEGAMORPHIC, "ic.force-megamorphic") \
817 Register(ION_NORMAL_WARMUP_TRIGGER, "ion.warmup.trigger") \
818 Register(ION_GVN_ENABLE, "ion.gvn.enable") \
819 Register(ION_FORCE_IC, "ion.forceinlineCaches") \
820 Register(ION_ENABLE, "ion.enable") \
821 Register(JIT_TRUSTEDPRINCIPALS_ENABLE, "jit_trustedprincipals.enable") \
822 Register(ION_CHECK_RANGE_ANALYSIS, "ion.check-range-analysis") \
823 Register(ION_FREQUENT_BAILOUT_THRESHOLD, "ion.frequent-bailout-threshold") \
824 Register(BASE_REG_FOR_LOCALS, "base-reg-for-locals") \
825 Register(INLINING_BYTECODE_MAX_LENGTH, "inlining.bytecode-max-length") \
826 Register(BASELINE_INTERPRETER_ENABLE, "blinterp.enable") \
827 Register(BASELINE_ENABLE, "baseline.enable") \
828 Register(OFFTHREAD_COMPILATION_ENABLE, "offthread-compilation.enable") \
829 Register(FULL_DEBUG_CHECKS, "jit.full-debug-checks") \
830 Register(JUMP_THRESHOLD, "jump-threshold") \
831 Register(NATIVE_REGEXP_ENABLE, "native_regexp.enable") \
832 Register(JIT_HINTS_ENABLE, "jitHints.enable") \
833 Register(SIMULATOR_ALWAYS_INTERRUPT, "simulator.always-interrupt") \
834 Register(SPECTRE_INDEX_MASKING, "spectre.index-masking") \
835 Register(SPECTRE_OBJECT_MITIGATIONS, "spectre.object-mitigations") \
836 Register(SPECTRE_STRING_MITIGATIONS, "spectre.string-mitigations") \
837 Register(SPECTRE_VALUE_MASKING, "spectre.value-masking") \
838 Register(SPECTRE_JIT_TO_CXX_CALLS, "spectre.jit-to-cxx-calls") \
839 Register(WRITE_PROTECT_CODE, "write-protect-code") \
840 Register(WATCHTOWER_MEGAMORPHIC, "watchtower.megamorphic") \
841 Register(WASM_FOLD_OFFSETS, "wasm.fold-offsets") \
842 Register(WASM_DELAY_TIER2, "wasm.delay-tier2") \
843 Register(WASM_JIT_BASELINE, "wasm.baseline") \
844 Register(WASM_JIT_OPTIMIZING, "wasm.optimizing")
847 typedef enum JSJitCompilerOption
{
848 #define JIT_COMPILER_DECLARE(key, str) JSJITCOMPILER_##key,
850 JIT_COMPILER_OPTIONS(JIT_COMPILER_DECLARE
)
851 #undef JIT_COMPILER_DECLARE
853 JSJITCOMPILER_NOT_AN_OPTION
854 } JSJitCompilerOption
;
856 extern JS_PUBLIC_API
void JS_SetGlobalJitCompilerOption(JSContext
* cx
,
857 JSJitCompilerOption opt
,
859 extern JS_PUBLIC_API
bool JS_GetGlobalJitCompilerOption(JSContext
* cx
,
860 JSJitCompilerOption opt
,
865 // Disable all Spectre mitigations for this process after creating the initial
866 // JSContext. Must be called on this context's thread.
867 extern JS_PUBLIC_API
void DisableSpectreMitigationsAfterInit();
872 * Convert a uint32_t index into a jsid.
874 extern JS_PUBLIC_API
bool JS_IndexToId(JSContext
* cx
, uint32_t index
,
875 JS::MutableHandleId
);
878 * Convert chars into a jsid.
880 * |chars| may not be an index.
882 extern JS_PUBLIC_API
bool JS_CharsToId(JSContext
* cx
, JS::TwoByteChars chars
,
883 JS::MutableHandleId
);
886 * Test if the given string is a valid ECMAScript identifier
888 extern JS_PUBLIC_API
bool JS_IsIdentifier(JSContext
* cx
, JS::HandleString str
,
892 * Test whether the given chars + length are a valid ECMAScript identifier.
893 * This version is infallible, so just returns whether the chars are an
896 extern JS_PUBLIC_API
bool JS_IsIdentifier(const char16_t
* chars
, size_t length
);
904 class MOZ_RAII JS_PUBLIC_API AutoFilename
{
906 js::ScriptSource
* ss_
;
907 mozilla::Variant
<const char*, UniqueChars
> filename_
;
909 AutoFilename(const AutoFilename
&) = delete;
910 AutoFilename
& operator=(const AutoFilename
&) = delete;
914 : ss_(nullptr), filename_(mozilla::AsVariant
<const char*>(nullptr)) {}
916 ~AutoFilename() { reset(); }
920 void setOwned(UniqueChars
&& filename
);
921 void setUnowned(const char* filename
);
922 void setScriptSource(js::ScriptSource
* ss
);
924 const char* get() const;
928 * Return the current filename, line number and column number of the most
929 * currently running frame. Returns true if a scripted frame was found, false
932 * If a the embedding has hidden the scripted caller for the topmost activation
933 * record, this will also return false.
935 extern JS_PUBLIC_API
bool DescribeScriptedCaller(
936 JSContext
* cx
, AutoFilename
* filename
= nullptr, unsigned* lineno
= nullptr,
937 unsigned* column
= nullptr);
939 extern JS_PUBLIC_API JSObject
* GetScriptedCallerGlobal(JSContext
* cx
);
942 * Informs the JS engine that the scripted caller should be hidden. This can be
943 * used by the embedding to maintain an override of the scripted caller in its
944 * calculations, by hiding the scripted caller in the JS engine and pushing data
945 * onto a separate stack, which it inspects when DescribeScriptedCaller returns
948 * We maintain a counter on each activation record. Add() increments the counter
949 * of the topmost activation, and Remove() decrements it. The count may never
950 * drop below zero, and must always be exactly zero when the activation is
951 * popped from the stack.
953 extern JS_PUBLIC_API
void HideScriptedCaller(JSContext
* cx
);
955 extern JS_PUBLIC_API
void UnhideScriptedCaller(JSContext
* cx
);
957 class MOZ_RAII AutoHideScriptedCaller
{
959 explicit AutoHideScriptedCaller(JSContext
* cx
) : mContext(cx
) {
960 HideScriptedCaller(mContext
);
962 ~AutoHideScriptedCaller() { UnhideScriptedCaller(mContext
); }
969 * Attempt to disable Wasm's usage of reserving a large virtual memory
970 * allocation to avoid bounds checking overhead. This must be called before any
971 * Wasm module or memory is created in this process, or else this function will
974 [[nodiscard
]] extern JS_PUBLIC_API
bool DisableWasmHugeMemory();
977 * Return true iff the given object is either a SavedFrame object or wrapper
978 * around a SavedFrame object, and it is not the SavedFrame.prototype object.
980 extern JS_PUBLIC_API
bool IsMaybeWrappedSavedFrame(JSObject
* obj
);
983 * Return true iff the given object is a SavedFrame object and not the
984 * SavedFrame.prototype object.
986 extern JS_PUBLIC_API
bool IsUnwrappedSavedFrame(JSObject
* obj
);
993 * Hint that we expect a crash. Currently, the only thing that cares is the
994 * breakpad injector, which (if loaded) will suppress minidump generation.
996 extern JS_PUBLIC_API
void NoteIntentionalCrash();
1003 extern JS_PUBLIC_API
void SetSupportDifferentialTesting(bool value
);
1008 #endif /* jsapi_h */