A JS context always has an “owner thread”. The owner thread is set when the
context is created (to the current thread) and practically all entry points
into the JS engine check that a context (or anything contained in the
context: runtime, compartment, object, etc) is only touched by its owner
thread. Embeddings may check this invariant outside the JS engine by calling
JS_AbortIfWrongThread (which will abort if not on the owner thread, even for
non-debug builds).
Register externally maintained GC roots.
Equivalent to Object.assign(target, src)
: Copies the properties from the
src
object (which must not be null) to target
(which also must not be
null).
Perform the method call rval = obj[name](args)
.
Call a function, passing a this-value and arguments. This is the C++
equivalent of rval = Reflect.apply(fun, obj, args)
.
Convert chars into a jsid.
Concatenate two strings, possibly resulting in a rope.
See above for thread safety comments.
Copies all own properties and private fields from |obj| to |target|. Both
|obj| and |target| must not be cross-compartment wrappers because we have to
enter their realms.
Copies the string’s characters to a null-terminated char16_t buffer.
For JS_DecodeBytes, set *dstlenp to the size of the destination buffer before
the call; on return, *dstlenp contains the number of characters actually
stored. To determine the necessary destination buffer size, make a sizing
call that passes nullptr for dst.
Freeze obj, and all objects it refers to, recursively. This will not recurse
through non-extensible objects, on the assumption that those are already
deep-frozen.
Other property-defining functions
Add various profiling-related functions as properties of the given object.
Defined in builtin/Profilers.cpp.
Define a property on obj.
Define a property on obj, throwing a TypeError if the attempt fails.
This is the C++ equivalent of Object.defineProperty(obj, id, desc)
.
Delete a property. This is the C++ equivalent of
result = Reflect.deleteProperty(obj, id)
.
Delete a property, ignoring strict failures. This is the C++ equivalent of
the JS delete obj[id]
in non-strict mode code.
DO NOT USE, only present for Rust bindings as a temporary hack
DEPRECATED
Encode string into a buffer. The function does not stores an additional
zero byte. The function returns (size_t) -1 if the string can not be
encoded into bytes with no error reported. Otherwise it returns the number
of bytes that are necessary to encode the string. If that exceeds the
length parameter, the string will be cut and only length bytes will be
written into the buffer.
DEPRECATED
DEPRECATED
Get an array of the non-symbol enumerable properties of obj.
This function is roughly equivalent to:
If the given object is an exception object, the exception will have (or be
able to lazily create) an error report struct, and this function will return
the address of that struct. Otherwise, it returns nullptr. The lifetime
of the error report struct that might be returned is the same as the
lifetime of the exception object.
Evaluate a script in the scope of the current global of cx.
As above, but providing an explicit scope chain. envChain must not include
the global object on it; that’s implicit. It needs to contain the other
objects that should end up on the script’s scope chain.
Get the value of the property obj[id]
, or undefined if no such property
exists. This is the C++ equivalent of vp = Reflect.get(obj, id, receiver)
.
Perform the same property assignment as Reflect.set(obj, id, v, receiver)
.
Freezes an object; see ES5’s Object.freeze(obj) method.
A variant of JS_ShutDown for process which used JS_FrontendOnlyInit instead
of JS_Init.
Return the ArrayBuffer or SharedArrayBuffer underlying an ArrayBufferView.
This may return a detached buffer. |obj| must be an object that would
return true for JS_IsArrayBufferViewObject().
More generic name for JS_GetTypedArrayByteLength to cover DataViews as well
More generic name for JS_GetTypedArrayByteOffset to cover DataViews as well
Same as above, but for any kind of ArrayBufferView. Prefer the type-specific
versions when possible.
Return a “fixed” pointer (one that will not move during a GC) to the
ArrayBufferView’s data. Note that this will not keep the object alive; the
holding object should be rooted or traced. If the view is storing the data
inline, this will copy the data to the provided buffer, returning nullptr if
bufSize is inadequate.
Return the ‘callbacks’ arg passed to JS_NewExternalStringLatin1,
JS_NewExternalUCString, JS_NewMaybeExternalStringLatin1,
or JS_NewMaybeExternalUCString.
Return a function’s display name as name
out-parameter.
Return the function’s identifier as a JSString, or null if fun is unnamed.
Almost same as JS_GetFunctionDisplayId.
Almost same as JS_GetFunctionId.
Get the value of the property obj[id]
, or undefined if no such property
exists. The result is stored in vp.
Get the prototype of |obj|, storing it in |proto|.
If |obj| (underneath any functionally-transparent wrapper proxies) has as
its [[GetPrototypeOf]] trap the ordinary [[GetPrototypeOf]] behavior defined
for ordinary objects, set |*isOrdinary = true| and store |obj|’s prototype
in |result|. Otherwise set |*isOrdinary = false|. In case of error, both
outparams have unspecified value.
Get number of bytes in the string encoding (without accounting for a
terminating zero bytes. The function returns (size_t) -1 if the string
can not be encoded into bytes and reports an error using cx accordingly.
Return the byte length of a typed array.
Return the byte offset from the start of an ArrayBuffer to the start of a
typed array view.
Return the number of elements in a typed array.
Return the isShared flag of a typed array, which denotes whether
the underlying buffer is a SharedArrayBuffer.
Spidermonkey does not have a good way of keeping track of what compartments
should be marked on their own. We can mark the roots unconditionally, but
marking GC things only relevant in live compartments is hard. To mitigate
this, we create a static trace hook, installed on each global object, from
which we can be sure the compartment is relevant, and mark it.
Determine whether obj has an own property with the key id
.
Compute the expression id in obj
.
Convert a uint32_t index into a jsid.
Defines a builtin constructor and prototype. Returns the prototype object.
Add ‘Reflect.parse’, a SpiderMonkey extension, to the Reflect object on the
given global.
Copy the own properties of src to dst in a fast way. src and dst must both
be native and must be in the compartment of cx. They must have the same
class, the same parent, and the same prototype. Class reserved slots will
NOT be copied.
Check whether obj supports JS_GetArrayBufferView* APIs. Note that this may
return false if a security wrapper is encountered that denies the
unwrapping. If this test or one of the more specific tests succeeds, then it
is safe to call the various ArrayBufferView accessor JSAPI calls defined
below.
True iff fun is the global eval function.
True iff fun is the Function constructor.
Return whether the given function is a valid constructor.
Determine whether the given object is backed by a DeadObjectProxy.
Determine whether obj is extensible. Extensible objects can have new
properties defined on them. Inextensible objects can’t, and their
[[Prototype]] slot is fixed as well.
Test if the given string is a valid ECMAScript identifier
Test whether the given chars + length are a valid ECMAScript identifier.
This version is infallible, so just returns whether the chars are an
identifier.
Check whether obj supports JS_GetTypedArray* APIs. Note that this may return
false if a security wrapper is encountered that denies the unwrapping. If
this test or one of the JS_Is*Array tests succeeds, then it is safe to call
the various accessor JSAPI calls defined below.
This function calls |compartmentCallback| on every compartment until either
all compartments have been iterated or CompartmentIterResult::Stop is
returned. Beware that there is no guarantee that the compartment will survive
after the callback returns. Also, barriers are disabled via the TraceSession.
This function calls |compartmentCallback| on every compartment in the given
zone until either all compartments have been iterated or
CompartmentIterResult::Stop is returned. Beware that there is no guarantee
that the compartment will survive after the callback returns. Also, barriers
are disabled via the TraceSession.
Set up ctor.prototype = proto and proto.constructor = ctor with the
right property flags.
Mark a jsid after entering a new compartment. Different zones separately
mark the ids in a runtime, and this must be used any time an id is obtained
from one compartment and then used in another compartment, unless the two
compartments are guaranteed to be in the same zone.
If value stores a jsid (an atomized string or symbol), mark that id as for
JS_MarkCrossZoneId.
If the bufSize passed to JS_GetArrayBufferViewFixedData is at least this
many bytes, then any copied data is guaranteed to fit into the provided
buffer.
Create a new DataView using the given buffer for storage. The given buffer
must be an ArrayBuffer or SharedArrayBuffer (or a cross-compartment wrapper
of either type), and the offset and length must fit within the bounds of the
buffer. Currently, nullptr will be returned and an exception will be thrown
if these conditions do not hold, but do not depend on that behavior.
Creates a new dead wrapper object in the given scope. To be used when
attempting to wrap objects from scopes which are already dead.
Create a dependent string, i.e., a string that owns no character storage,
but that refers to a slice of another string’s chars. Dependent strings
are mutable by definition, so the thread safety comments above apply.
Fill “properties” with a list of standard class names that have not yet been
resolved on “obj”. This can be used as (part of) a newEnumerate class hook
on a global. Already-resolved things are excluded because they might have
been deleted by script after being resolved and enumeration considers
already-defined properties anyway.
Fill “properties” with a list of standard class names. This can be used for
proxies that want to define behavior that looks like enumerating a global
without touching the global itself.
Create a new JSString whose chars member refers to external memory, i.e.,
memory requiring application-specific finalization.
Create a new JSString whose chars member may refer to external memory.
If a new external string is allocated, |*allocatedExternal| is set to true.
Otherwise the returned string is either not an external string or an
external string allocated by a previous call and |*allocatedExternal| is set
to false. If |*allocatedExternal| is false, |fin| won’t be called.
Similar to JS_NewMaybeExternalStringLatin1.
A constructor can request that the JS engine create a default new ‘this’
object of the given class, using the callee to determine parentage and
[[Prototype]].
Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default
proto. If proto is nullptr, the JS object will have null
as [[Prototype]].
Allocate an object in exactly the same way as JS_NewObjectWithGivenProto, but
without invoking the metadata callback on it. This allows creation of
internal bookkeeping objects that are guaranteed to not have metadata
attached to them.
Creates a new plain object, like new Object()
, with Object.prototype as
[[Prototype]].
Microseconds since the epoch, midnight, January 1, 1970 UTC.
Infallible predicate to test whether obj is a function object (faster than
comparing obj’s class name to “Function”, but equivalent unless someone has
overwritten the “Function” identifier with a different constructor and then
created instances using that constructor that might be passed in as obj).
Performs the JSON.parse operation as specified by ECMAScript.
Performs the JSON.parse operation as specified by ECMAScript.
Performs the JSON.parse operation as specified by ECMAScript.
Performs the JSON.parse operation as specified by ECMAScript, using the
given |reviver| argument as the corresponding optional argument to that
function.
Performs the JSON.parse operation as specified by ECMAScript, using the
given |reviver| argument as the corresponding optional argument to that
function.
Attempt to make |obj| non-extensible.
Implements StructuredDeserialize and StructuredDeserializeWithTransfer.
Undo a call to JS_AddExtraGCRootsTracer.
Complain when an allocation size overflows the maximum supported limit.
Report an exception represented by the sprintf-like conversion of format
and its arguments.
Complain when out of memory.
Resolve id, which must contain either a string or an int, to a standard
class name in obj if possible, defining the class’s constructor and/or
prototype and storing true in *resolved. If id does not name a standard
class or a top-level property induced by initializing a standard class,
store false in *resolved and just return true. Return false on error,
as usual for bool result-typed API entry points.
Assign ‘undefined’ to all of the object’s non-reserved slots. Note: this is
done for all slots, regardless of the associated property descriptor.
This function can be used to track memory used by ICU. If it is called, it
must be called before JS_Init. Don’t use it unless you know what you’re
doing!
Attempt to make the [[Prototype]] of |obj| immutable, such that any attempt
to modify it will fail. If an error occurs during the attempt, return false
(with a pending exception set, depending upon the nature of the error). If
no error occurs, return true with |*succeeded| set to indicate whether the
attempt successfully made the [[Prototype]] immutable.
Set the size of the native stack that should not be exceed. To disable
stack size checking pass 0.
Perform the assignment obj[id] = v
.
Change the prototype of obj.
Destroy free-standing resources allocated by SpiderMonkey, not associated
with any runtime, context, or other structure.
Performs the JSON.stringify operation, as specified by ECMAScript, except
writing stringified data by exactly one call of |callback|, passing |data| as
argument.
Given a buffer, return false if the buffer might become a valid JavaScript
script with the addition of more lines, or true if the validity of such a
script is conclusively known (because it’s the prefix of a valid script –
and possibly the entirety of such a script).
Implements StructuredSerialize, StructuredSerializeForStorage, and
StructuredSerializeWithTransfer.
A wrapper for |js_free(p)| that may delay |js_free(p)| invocation as a
performance optimization. |cx| may be nullptr.
Same as above, but for buffers that will be used with the BYOB
(Bring Your Own Buffer) JSString creation functions, such as
JS_NewLatin1String and JS_NewUCString
Called when the transferring objects are checked. If this function returns
false, the serialization ends throwing a DataCloneError exception.
Called when freeing a transferable handled by the embedding. Note that it
should never trigger a garbage collection (and will assert in a
debug build if it does.)
Add a property named by id to obj.
Delete a property named by id in obj.
The old-style JSClass.enumerate op should define all lazy properties not
yet reflected in obj.
UniquePtr is a smart pointer that wholly owns a resource. Ownership may be
transferred out of a UniquePtr through explicit action, but otherwise the
resource is destroyed when the UniquePtr is destroyed.
Finalize obj, which the garbage collector has determined to be unreachable
from other live objects or from GC roots. Obviously, finalizers must never
store a reference to obj.
The type of ObjectOps::funToString. This callback allows an object to
provide a custom string to use when Function.prototype.toString is invoked on
that object. A null return value means OOM.
A class with a resolve hook can optionally have a mayResolve hook. This hook
must have no side effects and must return true for a given id if the resolve
hook may resolve this id. This is useful when we’re doing a “pure” lookup: if
mayResolve returns false, we know we don’t have to call the effectful resolve
hook.
The type of ObjectOps::enumerate. This callback overrides a portion of
SpiderMonkey’s default [[Enumerate]] internal method. When an ordinary object
is enumerated, that object and each object on its prototype chain is tested
for an enumerate op, and those ops are called in order. The properties each
op adds to the ‘properties’ vector are added to the set of values the for-in
loop will iterate over. All of this is nonstandard.
Callback used by the wrap hook to ask the embedding to prepare an object
for wrapping in a context. This might include unwrapping other wrappers
or even finding a more suitable object for the new compartment. If |origObj|
is non-null, then it is the original object we are going to swap into during
a transplant.
Resolve a lazy property named by id in obj by defining it directly in obj.
Lazy properties are those reflected from some peer native property space
(e.g., the DOM attributes for a given node reflected as obj) on demand.
Function type for trace operation of the class called to enumerate all
traceable things reachable from obj’s private data structure. For each such
thing, a trace implementation must call JS::TraceEdge on the thing’s
location.
Callback used to ask the embedding for the cross compartment wrapper handler
that implements the desired prolicy for this kind of object in the
destination compartment. |obj| is the object to be wrapped. If |existing| is
non-nullptr, it will point to an existing wrapper object that should be
re-used if possible. |existing| is guaranteed to be a cross-compartment
wrapper with a lazily-defined prototype and the correct global. It is
guaranteed not to wrap a function.
MozRefCountType is Mozilla’s reference count type.
Read structured data from the reader r. This hook is used to read a value
previously serialized by a call to the WriteStructuredCloneOp hook.
This is called when JS_ReadStructuredClone receives a transferable object
not known to the engine. If this hook does not exist or returns false, the
JS engine calls the reportError op if set, otherwise it throws a
DATA_CLONE_ERR DOM Exception. This method is called before any other
callback and must return a non-null object in returnObject on success.
Called when a SharedArrayBuffer (including one owned by a Wasm memory object)
has been processed in context cx
by structured cloning. If receiving
is
true then the SAB has been received from a channel and a new SAB object has
been created; if false then an existing SAB has been serialized onto a
channel.
This is called when serialization or deserialization encounters an error.
To follow HTML5, the application must throw a DATA_CLONE_ERR DOMException
with error set to one of the JS_SCERR_* values.
Called when JS_WriteStructuredClone receives a transferable object not
handled by the engine. If this hook does not exist or returns false, the JS
engine will call the reportError hook or fall back to throwing a
DATA_CLONE_ERR DOM Exception. This method is called before any other
callback.
Structured data serialization hook. The engine can write primitive values,
Objects, Arrays, Dates, RegExps, TypedArrays, ArrayBuffers, Sets, Maps,
and SharedTypedArrays. Any other type of object requires application support.
This callback must first use the JS_WriteUint32Pair API to write an object
header, passing a value greater than JS_SCTAG_USER to the tag parameter.
Then it can use the JS_Write* APIs to write any other relevant parts of
the value v to the writer w. closure is any value passed to the
JS_WriteStructuredClone function.