Backed out changeset 1e582a0e5593 (bug 1852921) for causing build bustages
[gecko.git] / js / src / jsapi.h
blob88bb99ad2f1d70bf435eaf6be1a2dcf7a9d23481
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 /* JavaScript API. */
9 #ifndef jsapi_h
10 #define jsapi_h
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"
22 #include <stdarg.h>
23 #include <stddef.h>
24 #include <stdint.h>
25 #include <stdio.h>
27 #include "jspubtd.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"
33 #include "js/Class.h"
34 #include "js/CompileOptions.h"
35 #include "js/Context.h"
36 #include "js/Debug.h"
37 #include "js/ErrorInterceptor.h"
38 #include "js/ErrorReport.h"
39 #include "js/Exception.h"
40 #include "js/GCAPI.h"
41 #include "js/GCVector.h"
42 #include "js/GlobalObject.h"
43 #include "js/HashTable.h"
44 #include "js/Id.h"
45 #include "js/Interrupt.h"
46 #include "js/MapAndSet.h"
47 #include "js/MemoryCallbacks.h"
48 #include "js/MemoryFunctions.h"
49 #include "js/Principals.h"
50 #include "js/PropertyAndElement.h" // JS_Enumerate
51 #include "js/PropertyDescriptor.h"
52 #include "js/PropertySpec.h"
53 #include "js/Realm.h"
54 #include "js/RealmIterators.h"
55 #include "js/RealmOptions.h"
56 #include "js/RefCounted.h"
57 #include "js/RootingAPI.h"
58 #include "js/ScriptPrivate.h"
59 #include "js/Stack.h"
60 #include "js/StreamConsumer.h"
61 #include "js/String.h"
62 #include "js/TelemetryTimers.h"
63 #include "js/TracingAPI.h"
64 #include "js/Transcoding.h"
65 #include "js/UniquePtr.h"
66 #include "js/Utility.h"
67 #include "js/Value.h"
68 #include "js/ValueArray.h"
69 #include "js/Vector.h"
70 #include "js/WaitCallbacks.h"
71 #include "js/WeakMap.h"
72 #include "js/WrapperCallbacks.h"
73 #include "js/Zone.h"
75 /************************************************************************/
77 namespace JS {
78 /**
79 * Tell JS engine whether to use fdlibm for Math.sin, Math.cos, and Math.tan.
80 * Using fdlibm ensures that we don't expose a math fingerprint.
82 extern JS_PUBLIC_API void SetUseFdlibmForSinCosTan(bool value);
83 } // namespace JS
85 /************************************************************************/
87 struct JSFunctionSpec;
88 struct JSPropertySpec;
90 namespace JS {
92 template <typename UnitT>
93 class SourceText;
95 class TwoByteChars;
97 using ValueVector = JS::GCVector<JS::Value>;
98 using IdVector = JS::GCVector<jsid>;
99 using ScriptVector = JS::GCVector<JSScript*>;
100 using StringVector = JS::GCVector<JSString*>;
102 } /* namespace JS */
104 /************************************************************************/
106 static MOZ_ALWAYS_INLINE JS::Value JS_NumberValue(double d) {
107 int32_t i;
108 d = JS::CanonicalizeNaN(d);
109 if (mozilla::NumberIsInt32(d, &i)) {
110 return JS::Int32Value(i);
112 return JS::DoubleValue(d);
115 /************************************************************************/
117 JS_PUBLIC_API bool JS_StringHasBeenPinned(JSContext* cx, JSString* str);
119 /************************************************************************/
121 /** Microseconds since the epoch, midnight, January 1, 1970 UTC. */
122 extern JS_PUBLIC_API int64_t JS_Now(void);
124 extern JS_PUBLIC_API bool JS_ValueToObject(JSContext* cx, JS::HandleValue v,
125 JS::MutableHandleObject objp);
127 extern JS_PUBLIC_API JSFunction* JS_ValueToFunction(JSContext* cx,
128 JS::HandleValue v);
130 extern JS_PUBLIC_API JSFunction* JS_ValueToConstructor(JSContext* cx,
131 JS::HandleValue v);
133 extern JS_PUBLIC_API JSString* JS_ValueToSource(JSContext* cx,
134 JS::Handle<JS::Value> v);
136 extern JS_PUBLIC_API bool JS_DoubleIsInt32(double d, int32_t* ip);
138 extern JS_PUBLIC_API JSType JS_TypeOfValue(JSContext* cx,
139 JS::Handle<JS::Value> v);
141 namespace JS {
143 extern JS_PUBLIC_API const char* InformalValueTypeName(const JS::Value& v);
145 } /* namespace JS */
147 /** True iff fun is the global eval function. */
148 extern JS_PUBLIC_API bool JS_IsBuiltinEvalFunction(JSFunction* fun);
150 /** True iff fun is the Function constructor. */
151 extern JS_PUBLIC_API bool JS_IsBuiltinFunctionConstructor(JSFunction* fun);
153 extern JS_PUBLIC_API const char* JS_GetImplementationVersion(void);
155 extern JS_PUBLIC_API void JS_SetWrapObjectCallbacks(
156 JSContext* cx, const JSWrapObjectCallbacks* callbacks);
158 // Examine a value to determine if it is one of the built-in Error types.
159 // If so, return the error type.
160 extern JS_PUBLIC_API mozilla::Maybe<JSExnType> JS_GetErrorType(
161 const JS::Value& val);
163 extern JS_PUBLIC_API bool JS_WrapObject(JSContext* cx,
164 JS::MutableHandleObject objp);
166 extern JS_PUBLIC_API bool JS_WrapValue(JSContext* cx,
167 JS::MutableHandleValue vp);
169 extern JS_PUBLIC_API JSObject* JS_TransplantObject(JSContext* cx,
170 JS::HandleObject origobj,
171 JS::HandleObject target);
174 * Resolve id, which must contain either a string or an int, to a standard
175 * class name in obj if possible, defining the class's constructor and/or
176 * prototype and storing true in *resolved. If id does not name a standard
177 * class or a top-level property induced by initializing a standard class,
178 * store false in *resolved and just return true. Return false on error,
179 * as usual for bool result-typed API entry points.
181 * This API can be called directly from a global object class's resolve op,
182 * to define standard classes lazily. The class should either have an enumerate
183 * hook that calls JS_EnumerateStandardClasses, or a newEnumerate hook that
184 * calls JS_NewEnumerateStandardClasses. newEnumerate is preferred because it's
185 * faster (does not define all standard classes).
187 extern JS_PUBLIC_API bool JS_ResolveStandardClass(JSContext* cx,
188 JS::HandleObject obj,
189 JS::HandleId id,
190 bool* resolved);
192 extern JS_PUBLIC_API bool JS_MayResolveStandardClass(const JSAtomState& names,
193 jsid id,
194 JSObject* maybeObj);
196 extern JS_PUBLIC_API bool JS_EnumerateStandardClasses(JSContext* cx,
197 JS::HandleObject obj);
200 * Fill "properties" with a list of standard class names that have not yet been
201 * resolved on "obj". This can be used as (part of) a newEnumerate class hook
202 * on a global. Already-resolved things are excluded because they might have
203 * been deleted by script after being resolved and enumeration considers
204 * already-defined properties anyway.
206 extern JS_PUBLIC_API bool JS_NewEnumerateStandardClasses(
207 JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
208 bool enumerableOnly);
211 * Fill "properties" with a list of standard class names. This can be used for
212 * proxies that want to define behavior that looks like enumerating a global
213 * without touching the global itself.
215 extern JS_PUBLIC_API bool JS_NewEnumerateStandardClassesIncludingResolved(
216 JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
217 bool enumerableOnly);
219 extern JS_PUBLIC_API bool JS_GetClassObject(JSContext* cx, JSProtoKey key,
220 JS::MutableHandle<JSObject*> objp);
222 extern JS_PUBLIC_API bool JS_GetClassPrototype(
223 JSContext* cx, JSProtoKey key, JS::MutableHandle<JSObject*> objp);
225 namespace JS {
228 * Determine if the given object is an instance/prototype/constructor for a
229 * standard class. If so, return the associated JSProtoKey. If not, return
230 * JSProto_Null.
233 extern JS_PUBLIC_API JSProtoKey IdentifyStandardInstance(JSObject* obj);
235 extern JS_PUBLIC_API JSProtoKey IdentifyStandardPrototype(JSObject* obj);
237 extern JS_PUBLIC_API JSProtoKey
238 IdentifyStandardInstanceOrPrototype(JSObject* obj);
240 extern JS_PUBLIC_API JSProtoKey IdentifyStandardConstructor(JSObject* obj);
242 extern JS_PUBLIC_API void ProtoKeyToId(JSContext* cx, JSProtoKey key,
243 JS::MutableHandleId idp);
245 } /* namespace JS */
247 extern JS_PUBLIC_API JSProtoKey JS_IdToProtoKey(JSContext* cx, JS::HandleId id);
249 extern JS_PUBLIC_API JSObject* JS_GlobalLexicalEnvironment(JSObject* obj);
251 extern JS_PUBLIC_API bool JS_HasExtensibleLexicalEnvironment(JSObject* obj);
253 extern JS_PUBLIC_API JSObject* JS_ExtensibleLexicalEnvironment(JSObject* obj);
256 * Add 'Reflect.parse', a SpiderMonkey extension, to the Reflect object on the
257 * given global.
259 extern JS_PUBLIC_API bool JS_InitReflectParse(JSContext* cx,
260 JS::HandleObject global);
263 * Add various profiling-related functions as properties of the given object.
264 * Defined in builtin/Profilers.cpp.
266 extern JS_PUBLIC_API bool JS_DefineProfilingFunctions(JSContext* cx,
267 JS::HandleObject obj);
269 namespace JS {
272 * Tell JS engine whether Profile Timeline Recording is enabled or not.
273 * If Profile Timeline Recording is enabled, data shown there like stack won't
274 * be optimized out.
275 * This is global state and not associated with specific runtime or context.
277 extern JS_PUBLIC_API void SetProfileTimelineRecordingEnabled(bool enabled);
279 extern JS_PUBLIC_API bool IsProfileTimelineRecordingEnabled();
281 } // namespace JS
283 /************************************************************************/
285 extern JS_PUBLIC_API bool JS_ValueToId(JSContext* cx, JS::HandleValue v,
286 JS::MutableHandleId idp);
288 extern JS_PUBLIC_API bool JS_StringToId(JSContext* cx, JS::HandleString s,
289 JS::MutableHandleId idp);
291 extern JS_PUBLIC_API bool JS_IdToValue(JSContext* cx, jsid id,
292 JS::MutableHandle<JS::Value> vp);
294 namespace JS {
297 * Convert obj to a primitive value. On success, store the result in vp and
298 * return true.
300 * The hint argument must be JSTYPE_STRING, JSTYPE_NUMBER, or
301 * JSTYPE_UNDEFINED (no hint).
303 * Implements: ES6 7.1.1 ToPrimitive(input, [PreferredType]).
305 extern JS_PUBLIC_API bool ToPrimitive(JSContext* cx, JS::HandleObject obj,
306 JSType hint, JS::MutableHandleValue vp);
309 * If args.get(0) is one of the strings "string", "number", or "default", set
310 * result to JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_UNDEFINED accordingly and
311 * return true. Otherwise, return false with a TypeError pending.
313 * This can be useful in implementing a @@toPrimitive method.
315 extern JS_PUBLIC_API bool GetFirstArgumentAsTypeHint(JSContext* cx,
316 CallArgs args,
317 JSType* result);
319 } /* namespace JS */
322 * Defines a builtin constructor and prototype. Returns the prototype object.
324 * - Defines a property named `name` on `obj`, with its value set to a
325 * newly-created JS function that invokes the `constructor` JSNative. The
326 * `length` of the function is `nargs`.
328 * - Creates a prototype object with proto `protoProto` and class `protoClass`.
329 * If `protoProto` is `nullptr`, `Object.prototype` will be used instead.
330 * If `protoClass` is `nullptr`, the prototype object will be a plain JS
331 * object.
333 * - The `ps` and `fs` properties/functions will be defined on the prototype
334 * object.
336 * - The `static_ps` and `static_fs` properties/functions will be defined on the
337 * constructor.
339 extern JS_PUBLIC_API JSObject* JS_InitClass(
340 JSContext* cx, JS::HandleObject obj, const JSClass* protoClass,
341 JS::HandleObject protoProto, const char* name, JSNative constructor,
342 unsigned nargs, const JSPropertySpec* ps, const JSFunctionSpec* fs,
343 const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs);
346 * Set up ctor.prototype = proto and proto.constructor = ctor with the
347 * right property flags.
349 extern JS_PUBLIC_API bool JS_LinkConstructorAndPrototype(
350 JSContext* cx, JS::Handle<JSObject*> ctor, JS::Handle<JSObject*> proto);
352 extern JS_PUBLIC_API bool JS_InstanceOf(JSContext* cx,
353 JS::Handle<JSObject*> obj,
354 const JSClass* clasp,
355 JS::CallArgs* args);
357 extern JS_PUBLIC_API bool JS_HasInstance(JSContext* cx,
358 JS::Handle<JSObject*> obj,
359 JS::Handle<JS::Value> v, bool* bp);
361 namespace JS {
363 // Implementation of
364 // http://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance. If
365 // you're looking for the equivalent of "instanceof", you want JS_HasInstance,
366 // not this function.
367 extern JS_PUBLIC_API bool OrdinaryHasInstance(JSContext* cx,
368 HandleObject objArg,
369 HandleValue v, bool* bp);
371 } // namespace JS
373 extern JS_PUBLIC_API JSObject* JS_GetConstructor(JSContext* cx,
374 JS::Handle<JSObject*> proto);
376 extern JS_PUBLIC_API JSObject* JS_NewObject(JSContext* cx,
377 const JSClass* clasp);
379 extern JS_PUBLIC_API bool JS_IsNative(JSObject* obj);
382 * Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default
383 * proto. If proto is nullptr, the JS object will have `null` as [[Prototype]].
385 extern JS_PUBLIC_API JSObject* JS_NewObjectWithGivenProto(
386 JSContext* cx, const JSClass* clasp, JS::Handle<JSObject*> proto);
389 * Creates a new plain object, like `new Object()`, with Object.prototype as
390 * [[Prototype]].
392 extern JS_PUBLIC_API JSObject* JS_NewPlainObject(JSContext* cx);
395 * Freeze obj, and all objects it refers to, recursively. This will not recurse
396 * through non-extensible objects, on the assumption that those are already
397 * deep-frozen.
399 extern JS_PUBLIC_API bool JS_DeepFreezeObject(JSContext* cx,
400 JS::Handle<JSObject*> obj);
403 * Freezes an object; see ES5's Object.freeze(obj) method.
405 extern JS_PUBLIC_API bool JS_FreezeObject(JSContext* cx,
406 JS::Handle<JSObject*> obj);
408 /*** Standard internal methods **********************************************
410 * The functions below are the fundamental operations on objects.
412 * ES6 specifies 14 internal methods that define how objects behave. The
413 * standard is actually quite good on this topic, though you may have to read
414 * it a few times. See ES6 sections 6.1.7.2 and 6.1.7.3.
416 * When 'obj' is an ordinary object, these functions have boring standard
417 * behavior as specified by ES6 section 9.1; see the section about internal
418 * methods in js/src/vm/NativeObject.h.
420 * Proxies override the behavior of internal methods. So when 'obj' is a proxy,
421 * any one of the functions below could do just about anything. See
422 * js/public/Proxy.h.
426 * Get the prototype of |obj|, storing it in |proto|.
428 * Implements: ES6 [[GetPrototypeOf]] internal method.
430 extern JS_PUBLIC_API bool JS_GetPrototype(JSContext* cx, JS::HandleObject obj,
431 JS::MutableHandleObject result);
434 * If |obj| (underneath any functionally-transparent wrapper proxies) has as
435 * its [[GetPrototypeOf]] trap the ordinary [[GetPrototypeOf]] behavior defined
436 * for ordinary objects, set |*isOrdinary = true| and store |obj|'s prototype
437 * in |result|. Otherwise set |*isOrdinary = false|. In case of error, both
438 * outparams have unspecified value.
440 extern JS_PUBLIC_API bool JS_GetPrototypeIfOrdinary(
441 JSContext* cx, JS::HandleObject obj, bool* isOrdinary,
442 JS::MutableHandleObject result);
445 * Change the prototype of obj.
447 * Implements: ES6 [[SetPrototypeOf]] internal method.
449 * In cases where ES6 [[SetPrototypeOf]] returns false without an exception,
450 * JS_SetPrototype throws a TypeError and returns false.
452 * Performance warning: JS_SetPrototype is very bad for performance. It may
453 * cause compiled jit-code to be invalidated. It also causes not only obj but
454 * all other objects in the same "group" as obj to be permanently deoptimized.
455 * It's better to create the object with the right prototype from the start.
457 extern JS_PUBLIC_API bool JS_SetPrototype(JSContext* cx, JS::HandleObject obj,
458 JS::HandleObject proto);
461 * Determine whether obj is extensible. Extensible objects can have new
462 * properties defined on them. Inextensible objects can't, and their
463 * [[Prototype]] slot is fixed as well.
465 * Implements: ES6 [[IsExtensible]] internal method.
467 extern JS_PUBLIC_API bool JS_IsExtensible(JSContext* cx, JS::HandleObject obj,
468 bool* extensible);
471 * Attempt to make |obj| non-extensible.
473 * Not all failures are treated as errors. See the comment on
474 * JS::ObjectOpResult in js/public/Class.h.
476 * Implements: ES6 [[PreventExtensions]] internal method.
478 extern JS_PUBLIC_API bool JS_PreventExtensions(JSContext* cx,
479 JS::HandleObject obj,
480 JS::ObjectOpResult& result);
483 * Attempt to make the [[Prototype]] of |obj| immutable, such that any attempt
484 * to modify it will fail. If an error occurs during the attempt, return false
485 * (with a pending exception set, depending upon the nature of the error). If
486 * no error occurs, return true with |*succeeded| set to indicate whether the
487 * attempt successfully made the [[Prototype]] immutable.
489 * This is a nonstandard internal method.
491 extern JS_PUBLIC_API bool JS_SetImmutablePrototype(JSContext* cx,
492 JS::HandleObject obj,
493 bool* succeeded);
496 * Equivalent to `Object.assign(target, src)`: Copies the properties from the
497 * `src` object (which must not be null) to `target` (which also must not be
498 * null).
500 extern JS_PUBLIC_API bool JS_AssignObject(JSContext* cx,
501 JS::HandleObject target,
502 JS::HandleObject src);
504 namespace JS {
507 * On success, returns true, setting |*isMap| to true if |obj| is a Map object
508 * or a wrapper around one, or to false if not. Returns false on failure.
510 * This method returns true with |*isMap == false| when passed an ES6 proxy
511 * whose target is a Map, or when passed a revoked proxy.
513 extern JS_PUBLIC_API bool IsMapObject(JSContext* cx, JS::HandleObject obj,
514 bool* isMap);
517 * On success, returns true, setting |*isSet| to true if |obj| is a Set object
518 * or a wrapper around one, or to false if not. Returns false on failure.
520 * This method returns true with |*isSet == false| when passed an ES6 proxy
521 * whose target is a Set, or when passed a revoked proxy.
523 extern JS_PUBLIC_API bool IsSetObject(JSContext* cx, JS::HandleObject obj,
524 bool* isSet);
526 } /* namespace JS */
529 * Assign 'undefined' to all of the object's non-reserved slots. Note: this is
530 * done for all slots, regardless of the associated property descriptor.
532 JS_PUBLIC_API void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj);
534 extern JS_PUBLIC_API void JS_SetReservedSlot(JSObject* obj, uint32_t index,
535 const JS::Value& v);
537 extern JS_PUBLIC_API void JS_InitReservedSlot(JSObject* obj, uint32_t index,
538 void* ptr, size_t nbytes,
539 JS::MemoryUse use);
541 template <typename T>
542 void JS_InitReservedSlot(JSObject* obj, uint32_t index, T* ptr,
543 JS::MemoryUse use) {
544 JS_InitReservedSlot(obj, index, ptr, sizeof(T), use);
547 /************************************************************************/
549 /* native that can be called as a ctor */
550 static constexpr unsigned JSFUN_CONSTRUCTOR = 0x400;
552 /* | of all the JSFUN_* flags */
553 static constexpr unsigned JSFUN_FLAGS_MASK = 0x400;
555 static_assert((JSPROP_FLAGS_MASK & JSFUN_FLAGS_MASK) == 0,
556 "JSFUN_* flags do not overlap JSPROP_* flags, because bits from "
557 "the two flag-sets appear in the same flag in some APIs");
560 * Functions and scripts.
562 extern JS_PUBLIC_API JSFunction* JS_NewFunction(JSContext* cx, JSNative call,
563 unsigned nargs, unsigned flags,
564 const char* name);
566 namespace JS {
568 extern JS_PUBLIC_API JSFunction* GetSelfHostedFunction(
569 JSContext* cx, const char* selfHostedName, HandleId id, unsigned nargs);
572 * Create a new function based on the given JSFunctionSpec, *fs.
573 * id is the result of a successful call to
574 * `PropertySpecNameToId(cx, fs->name, &id)` or
575 `PropertySpecNameToPermanentId(cx, fs->name, &id)`.
577 * Unlike JS_DefineFunctions, this does not treat fs as an array.
578 * *fs must not be JS_FS_END.
580 extern JS_PUBLIC_API JSFunction* NewFunctionFromSpec(JSContext* cx,
581 const JSFunctionSpec* fs,
582 HandleId id);
585 * Same as above, but without an id arg, for callers who don't have
586 * the id already.
588 extern JS_PUBLIC_API JSFunction* NewFunctionFromSpec(JSContext* cx,
589 const JSFunctionSpec* fs);
591 } /* namespace JS */
593 extern JS_PUBLIC_API JSObject* JS_GetFunctionObject(JSFunction* fun);
596 * Return the function's identifier as a JSString, or null if fun is unnamed.
597 * The returned string lives as long as fun, so you don't need to root a saved
598 * reference to it if fun is well-connected or rooted, and provided you bound
599 * the use of the saved reference by fun's lifetime.
601 extern JS_PUBLIC_API JSString* JS_GetFunctionId(JSFunction* fun);
604 * Return a function's display name. This is the defined name if one was given
605 * where the function was defined, or it could be an inferred name by the JS
606 * engine in the case that the function was defined to be anonymous. This can
607 * still return nullptr if a useful display name could not be inferred. The
608 * same restrictions on rooting as those in JS_GetFunctionId apply.
610 extern JS_PUBLIC_API JSString* JS_GetFunctionDisplayId(JSFunction* fun);
613 * Return the arity of fun, which includes default parameters and rest
614 * parameter. This can be used as `nargs` parameter for other functions.
616 extern JS_PUBLIC_API uint16_t JS_GetFunctionArity(JSFunction* fun);
619 * Return the length of fun, which is the original value of .length property.
621 JS_PUBLIC_API bool JS_GetFunctionLength(JSContext* cx, JS::HandleFunction fun,
622 uint16_t* length);
625 * Infallible predicate to test whether obj is a function object (faster than
626 * comparing obj's class name to "Function", but equivalent unless someone has
627 * overwritten the "Function" identifier with a different constructor and then
628 * created instances using that constructor that might be passed in as obj).
630 extern JS_PUBLIC_API bool JS_ObjectIsFunction(JSObject* obj);
632 extern JS_PUBLIC_API bool JS_IsNativeFunction(JSObject* funobj, JSNative call);
634 /** Return whether the given function is a valid constructor. */
635 extern JS_PUBLIC_API bool JS_IsConstructor(JSFunction* fun);
637 extern JS_PUBLIC_API bool JS_ObjectIsBoundFunction(JSObject* obj);
639 extern JS_PUBLIC_API JSObject* JS_GetBoundFunctionTarget(JSObject* obj);
641 extern JS_PUBLIC_API JSObject* JS_GetGlobalFromScript(JSScript* script);
643 extern JS_PUBLIC_API const char* JS_GetScriptFilename(JSScript* script);
645 extern JS_PUBLIC_API unsigned JS_GetScriptBaseLineNumber(JSContext* cx,
646 JSScript* script);
648 extern JS_PUBLIC_API JSScript* JS_GetFunctionScript(JSContext* cx,
649 JS::HandleFunction fun);
651 extern JS_PUBLIC_API JSString* JS_DecompileScript(JSContext* cx,
652 JS::Handle<JSScript*> script);
654 extern JS_PUBLIC_API JSString* JS_DecompileFunction(
655 JSContext* cx, JS::Handle<JSFunction*> fun);
657 namespace JS {
660 * Supply an alternative stack to incorporate into captured SavedFrame
661 * backtraces as the imputed caller of asynchronous JavaScript calls, like async
662 * function resumptions and DOM callbacks.
664 * When one async function awaits the result of another, it's natural to think
665 * of that as a sort of function call: just as execution resumes from an
666 * ordinary call expression when the callee returns, with the return value
667 * providing the value of the call expression, execution resumes from an 'await'
668 * expression after the awaited asynchronous function call returns, passing the
669 * return value along.
671 * Call the two async functions in such a situation the 'awaiter' and the
672 * 'awaitee'.
674 * As an async function, the awaitee contains 'await' expressions of its own.
675 * Whenever it executes after its first 'await', there are never any actual
676 * frames on the JavaScript stack under it; its awaiter is certainly not there.
677 * An await expression's continuation is invoked as a promise callback, and
678 * those are always called directly from the event loop in their own microtick.
679 * (Ignore unusual cases like nested event loops.)
681 * But because await expressions bear such a strong resemblance to calls (and
682 * deliberately so!), it would be unhelpful for stacks captured within the
683 * awaitee to be empty; instead, they should present the awaiter as the caller.
685 * The AutoSetAsyncStackForNewCalls RAII class supplies a SavedFrame stack to
686 * treat as the caller of any JavaScript invocations that occur within its
687 * lifetime. Any SavedFrame stack captured during such an invocation uses the
688 * SavedFrame passed to the constructor's 'stack' parameter as the 'asyncParent'
689 * property of the SavedFrame for the invocation's oldest frame. Its 'parent'
690 * property will be null, so stack-walking code can distinguish this
691 * awaiter/awaitee transition from an ordinary caller/callee transition.
693 * The constructor's 'asyncCause' parameter supplies a string explaining what
694 * sort of asynchronous call caused 'stack' to be spliced into the backtrace;
695 * for example, async function resumptions use the string "async". This appears
696 * as the 'asyncCause' property of the 'asyncParent' SavedFrame.
698 * Async callers are distinguished in the string form of a SavedFrame chain by
699 * including the 'asyncCause' string in the frame. It appears before the
700 * function name, with the two separated by a '*'.
702 * Note that, as each compartment has its own set of SavedFrames, the
703 * 'asyncParent' may actually point to a copy of 'stack', rather than the exact
704 * SavedFrame object passed.
706 * The youngest frame of 'stack' is not mutated to take the asyncCause string as
707 * its 'asyncCause' property; SavedFrame objects are immutable. Rather, a fresh
708 * clone of the frame is created with the needed 'asyncCause' property.
710 * The 'kind' argument specifies how aggressively 'stack' supplants any
711 * JavaScript frames older than this AutoSetAsyncStackForNewCalls object. If
712 * 'kind' is 'EXPLICIT', then all captured SavedFrame chains take on 'stack' as
713 * their 'asyncParent' where the chain crosses this object's scope. If 'kind' is
714 * 'IMPLICIT', then 'stack' is only included in captured chains if there are no
715 * other JavaScript frames on the stack --- that is, only if the stack would
716 * otherwise end at that point.
718 * AutoSetAsyncStackForNewCalls affects only SavedFrame chains; it does not
719 * affect Debugger.Frame or js::FrameIter. SavedFrame chains are used for
720 * Error.stack, allocation profiling, Promise debugging, and so on.
722 * See also `js/src/doc/SavedFrame/SavedFrame.md` for documentation on async
723 * stack frames.
725 class MOZ_STACK_CLASS JS_PUBLIC_API AutoSetAsyncStackForNewCalls {
726 JSContext* cx;
727 RootedObject oldAsyncStack;
728 const char* oldAsyncCause;
729 bool oldAsyncCallIsExplicit;
731 public:
732 enum class AsyncCallKind {
733 // The ordinary kind of call, where we may apply an async
734 // parent if there is no ordinary parent.
735 IMPLICIT,
736 // An explicit async parent, e.g., callFunctionWithAsyncStack,
737 // where we always want to override any ordinary parent.
738 EXPLICIT
741 // The stack parameter cannot be null by design, because it would be
742 // ambiguous whether that would clear any scheduled async stack and make the
743 // normal stack reappear in the new call, or just keep the async stack
744 // already scheduled for the new call, if any.
746 // asyncCause is owned by the caller and its lifetime must outlive the
747 // lifetime of the AutoSetAsyncStackForNewCalls object. It is strongly
748 // encouraged that asyncCause be a string constant or similar statically
749 // allocated string.
750 AutoSetAsyncStackForNewCalls(JSContext* cx, HandleObject stack,
751 const char* asyncCause,
752 AsyncCallKind kind = AsyncCallKind::IMPLICIT);
753 ~AutoSetAsyncStackForNewCalls();
756 } // namespace JS
758 /************************************************************************/
760 namespace JS {
762 JS_PUBLIC_API bool PropertySpecNameEqualsId(JSPropertySpec::Name name,
763 HandleId id);
766 * Create a jsid that does not need to be marked for GC.
768 * 'name' is a JSPropertySpec::name or JSFunctionSpec::name value. The
769 * resulting jsid, on success, is either an interned string or a well-known
770 * symbol; either way it is immune to GC so there is no need to visit *idp
771 * during GC marking.
773 JS_PUBLIC_API bool PropertySpecNameToPermanentId(JSContext* cx,
774 JSPropertySpec::Name name,
775 jsid* idp);
777 } /* namespace JS */
779 /************************************************************************/
782 * A JS context always has an "owner thread". The owner thread is set when the
783 * context is created (to the current thread) and practically all entry points
784 * into the JS engine check that a context (or anything contained in the
785 * context: runtime, compartment, object, etc) is only touched by its owner
786 * thread. Embeddings may check this invariant outside the JS engine by calling
787 * JS_AbortIfWrongThread (which will abort if not on the owner thread, even for
788 * non-debug builds).
791 extern JS_PUBLIC_API void JS_AbortIfWrongThread(JSContext* cx);
793 /************************************************************************/
796 * A constructor can request that the JS engine create a default new 'this'
797 * object of the given class, using the callee to determine parentage and
798 * [[Prototype]].
800 extern JS_PUBLIC_API JSObject* JS_NewObjectForConstructor(
801 JSContext* cx, const JSClass* clasp, const JS::CallArgs& args);
803 /************************************************************************/
805 extern JS_PUBLIC_API void JS_SetParallelParsingEnabled(JSContext* cx,
806 bool enabled);
808 extern JS_PUBLIC_API void JS_SetOffthreadIonCompilationEnabled(JSContext* cx,
809 bool enabled);
811 // clang-format off
812 #define JIT_COMPILER_OPTIONS(Register) \
813 Register(BASELINE_INTERPRETER_WARMUP_TRIGGER, "blinterp.warmup.trigger") \
814 Register(BASELINE_WARMUP_TRIGGER, "baseline.warmup.trigger") \
815 Register(IC_FORCE_MEGAMORPHIC, "ic.force-megamorphic") \
816 Register(ION_NORMAL_WARMUP_TRIGGER, "ion.warmup.trigger") \
817 Register(ION_GVN_ENABLE, "ion.gvn.enable") \
818 Register(ION_FORCE_IC, "ion.forceinlineCaches") \
819 Register(ION_ENABLE, "ion.enable") \
820 Register(JIT_TRUSTEDPRINCIPALS_ENABLE, "jit_trustedprincipals.enable") \
821 Register(ION_CHECK_RANGE_ANALYSIS, "ion.check-range-analysis") \
822 Register(ION_FREQUENT_BAILOUT_THRESHOLD, "ion.frequent-bailout-threshold") \
823 Register(BASE_REG_FOR_LOCALS, "base-reg-for-locals") \
824 Register(INLINING_BYTECODE_MAX_LENGTH, "inlining.bytecode-max-length") \
825 Register(BASELINE_INTERPRETER_ENABLE, "blinterp.enable") \
826 Register(BASELINE_ENABLE, "baseline.enable") \
827 Register(OFFTHREAD_COMPILATION_ENABLE, "offthread-compilation.enable") \
828 Register(FULL_DEBUG_CHECKS, "jit.full-debug-checks") \
829 Register(JUMP_THRESHOLD, "jump-threshold") \
830 Register(NATIVE_REGEXP_ENABLE, "native_regexp.enable") \
831 Register(JIT_HINTS_ENABLE, "jitHints.enable") \
832 Register(SIMULATOR_ALWAYS_INTERRUPT, "simulator.always-interrupt") \
833 Register(SPECTRE_INDEX_MASKING, "spectre.index-masking") \
834 Register(SPECTRE_OBJECT_MITIGATIONS, "spectre.object-mitigations") \
835 Register(SPECTRE_STRING_MITIGATIONS, "spectre.string-mitigations") \
836 Register(SPECTRE_VALUE_MASKING, "spectre.value-masking") \
837 Register(SPECTRE_JIT_TO_CXX_CALLS, "spectre.jit-to-cxx-calls") \
838 Register(WRITE_PROTECT_CODE, "write-protect-code") \
839 Register(WATCHTOWER_MEGAMORPHIC, "watchtower.megamorphic") \
840 Register(WASM_FOLD_OFFSETS, "wasm.fold-offsets") \
841 Register(WASM_DELAY_TIER2, "wasm.delay-tier2") \
842 Register(WASM_JIT_BASELINE, "wasm.baseline") \
843 Register(WASM_JIT_OPTIMIZING, "wasm.optimizing")
844 // clang-format on
846 typedef enum JSJitCompilerOption {
847 #define JIT_COMPILER_DECLARE(key, str) JSJITCOMPILER_##key,
849 JIT_COMPILER_OPTIONS(JIT_COMPILER_DECLARE)
850 #undef JIT_COMPILER_DECLARE
852 JSJITCOMPILER_NOT_AN_OPTION
853 } JSJitCompilerOption;
855 extern JS_PUBLIC_API void JS_SetGlobalJitCompilerOption(JSContext* cx,
856 JSJitCompilerOption opt,
857 uint32_t value);
858 extern JS_PUBLIC_API bool JS_GetGlobalJitCompilerOption(JSContext* cx,
859 JSJitCompilerOption opt,
860 uint32_t* valueOut);
862 namespace JS {
864 // Disable all Spectre mitigations for this process after creating the initial
865 // JSContext. Must be called on this context's thread.
866 extern JS_PUBLIC_API void DisableSpectreMitigationsAfterInit();
868 }; // namespace JS
871 * Convert a uint32_t index into a jsid.
873 extern JS_PUBLIC_API bool JS_IndexToId(JSContext* cx, uint32_t index,
874 JS::MutableHandleId);
877 * Convert chars into a jsid.
879 * |chars| may not be an index.
881 extern JS_PUBLIC_API bool JS_CharsToId(JSContext* cx, JS::TwoByteChars chars,
882 JS::MutableHandleId);
885 * Test if the given string is a valid ECMAScript identifier
887 extern JS_PUBLIC_API bool JS_IsIdentifier(JSContext* cx, JS::HandleString str,
888 bool* isIdentifier);
891 * Test whether the given chars + length are a valid ECMAScript identifier.
892 * This version is infallible, so just returns whether the chars are an
893 * identifier.
895 extern JS_PUBLIC_API bool JS_IsIdentifier(const char16_t* chars, size_t length);
897 namespace js {
898 class ScriptSource;
899 } // namespace js
901 namespace JS {
903 class MOZ_RAII JS_PUBLIC_API AutoFilename {
904 private:
905 js::ScriptSource* ss_;
906 mozilla::Variant<const char*, UniqueChars> filename_;
908 AutoFilename(const AutoFilename&) = delete;
909 AutoFilename& operator=(const AutoFilename&) = delete;
911 public:
912 AutoFilename()
913 : ss_(nullptr), filename_(mozilla::AsVariant<const char*>(nullptr)) {}
915 ~AutoFilename() { reset(); }
917 void reset();
919 void setOwned(UniqueChars&& filename);
920 void setUnowned(const char* filename);
921 void setScriptSource(js::ScriptSource* ss);
923 const char* get() const;
927 * Return the current filename, line number and column number of the most
928 * currently running frame. Returns true if a scripted frame was found, false
929 * otherwise.
931 * If a the embedding has hidden the scripted caller for the topmost activation
932 * record, this will also return false.
934 extern JS_PUBLIC_API bool DescribeScriptedCaller(
935 JSContext* cx, AutoFilename* filename = nullptr, uint32_t* lineno = nullptr,
936 JS::ColumnNumberZeroOrigin* column = nullptr);
938 extern JS_PUBLIC_API JSObject* GetScriptedCallerGlobal(JSContext* cx);
941 * Informs the JS engine that the scripted caller should be hidden. This can be
942 * used by the embedding to maintain an override of the scripted caller in its
943 * calculations, by hiding the scripted caller in the JS engine and pushing data
944 * onto a separate stack, which it inspects when DescribeScriptedCaller returns
945 * null.
947 * We maintain a counter on each activation record. Add() increments the counter
948 * of the topmost activation, and Remove() decrements it. The count may never
949 * drop below zero, and must always be exactly zero when the activation is
950 * popped from the stack.
952 extern JS_PUBLIC_API void HideScriptedCaller(JSContext* cx);
954 extern JS_PUBLIC_API void UnhideScriptedCaller(JSContext* cx);
956 class MOZ_RAII AutoHideScriptedCaller {
957 public:
958 explicit AutoHideScriptedCaller(JSContext* cx) : mContext(cx) {
959 HideScriptedCaller(mContext);
961 ~AutoHideScriptedCaller() { UnhideScriptedCaller(mContext); }
963 protected:
964 JSContext* mContext;
968 * Attempt to disable Wasm's usage of reserving a large virtual memory
969 * allocation to avoid bounds checking overhead. This must be called before any
970 * Wasm module or memory is created in this process, or else this function will
971 * fail.
973 [[nodiscard]] extern JS_PUBLIC_API bool DisableWasmHugeMemory();
976 * Return true iff the given object is either a SavedFrame object or wrapper
977 * around a SavedFrame object, and it is not the SavedFrame.prototype object.
979 extern JS_PUBLIC_API bool IsMaybeWrappedSavedFrame(JSObject* obj);
982 * Return true iff the given object is a SavedFrame object and not the
983 * SavedFrame.prototype object.
985 extern JS_PUBLIC_API bool IsUnwrappedSavedFrame(JSObject* obj);
987 } /* namespace JS */
989 namespace js {
992 * Hint that we expect a crash. Currently, the only thing that cares is the
993 * breakpad injector, which (if loaded) will suppress minidump generation.
995 extern JS_PUBLIC_API void NoteIntentionalCrash();
997 } /* namespace js */
999 #ifdef DEBUG
1000 namespace JS {
1002 extern JS_PUBLIC_API void SetSupportDifferentialTesting(bool value);
1005 #endif /* DEBUG */
1007 #endif /* jsapi_h */