Shell global objects

These are the global objects that are set up automatically by the SpiderMonkey js command-line interpreter when you start the program.

Note: this list overlaps with "Built-in functions" in Introduction to the JavaScript shell and is probably not complete. See js/src/shell/js.cpp (around shell_functions) for more.

This page lists variables and functions available on SpiderMonkey 53. There may be some difference between each versions.  You can get the list of functions by help() function in js shell.

Variables

scriptArgs
An array that contains arguments passed to js shell.
scriptPath
A string that is a patch of script.
console
An object that has following property:
log
Evaluate and print expressions to stdout. This function is an alias of the print() function.
timesAccessed
Returns a number that indicates how many times this variable is accessed
PerfMeasurement
See PerfMeasurement.jsm.

Shell only functions

Functions always available

version([number])
Get or force a script compilation version number.
options([option ...])
Get or toggle JavaScript options.
load(['foo.js' ...])
Load files named by string arguments. Filename is relative to the current working directory.
loadRelativeToScript(['foo.js' ...])
Load files named by string arguments. Filename is relative to the calling script.
evaluate(code[, options])
Evaluate code as though it were the contents of a file. options is an optional object that may have these properties:
isRunOnce
use the isRunOnce compiler option (default: false)
noScriptRval
use the no-script-rval compiler option (default: false)
fileName
filename for error messages and debug info
lineNumber
starting line number for error messages and debug info
columnNumber
starting column number for error messages and debug info
global
global in which to execute the code
newContext
if true, create and use a new cx (default: false)
catchTermination
if true, catch termination (failure without an exception value, as for slow scripts or out-of-memory) and return 'terminated'
element
if present with value v, convert v to an object o and mark the source as being attached to the DOM element o. If the property is omitted or v is null, don't attribute the source to any DOM element.
elementAttributeName
if present and not undefined, the name of property of element that holds this code. This is what Debugger.Source.prototype.elementAttributeName returns.
sourceMapURL
if present with value v, convert v to a string, and provide that as the code's source map URL. If omitted, attach no source map URL to the code (although the code may provide one itself, via a //#sourceMappingURL comment).
sourceIsLazy
if present and true, indicates that, after compilation, script source should not be cached by the JS engine and should be lazily loaded from the embedding as-needed.
loadBytecode
if true, and if the source is a CacheEntryObject, the bytecode would be loaded and decoded from the cache entry instead of being parsed, then it would be executed as usual.
saveBytecode
if true, and if the source is a CacheEntryObject, the bytecode would be encoded and saved into the cache entry after the script execution.
assertEqBytecode
if true, and if both loadBytecode and saveBytecode are true, then the loaded bytecode and the encoded bytecode are compared. and an assertion is raised if they differ.
run('foo.js')
Run the file named by the first argument, returning the number of of milliseconds spent compiling and executing it.
readline()
Read a single line from stdin.
readlineBuf([ buf ])
Emulate readline() on the specified string. The first call with a string argument sets the source buffer. Subsequent calls without an argument then read from this buffer line by line.
print([exp ...])
Evaluate and print expressions to stdout.
printErr([exp ...])
Evaluate and print expressions to stderr.
putstr([exp])
Evaluate and print expression without newline.
dateNow()
Return the current time with sub-ms precision.
help([name ...])
Display usage and help messages.
quit()
Quit the shell.
assertEq(actual, expected[, msg])
Throw if the first two arguments are not the same (both +0 or both -0, both NaN, or non-zero and ===).
startTimingMutator()
Start accounting time to mutator vs GC.
stopTimingMutator()
Stop accounting time to mutator vs GC and dump the results.
throwError()
Throw an error from JS_ReportError.
intern(str)
Internalize str in the atom table.
getslx(obj)
Get script line extent.
evalcx(s[, o])
Evaluate s in optional sandbox object o. if (s == '' && !o) return new o with eager standard classes, if (s == 'lazy' && !o) return new o with lazy standard classes
evalInWorker(str)
Evaluate str in a separate thread with its own runtime.
getSharedArrayBuffer()
Retrieve the SharedArrayBuffer object from the cross-worker mailbox. The object retrieved may not be identical to the object that was installed, but it references the same shared memory. getSharedArrayBuffer performs an ordering memory barrier.
setSharedArrayBuffer()
Install the SharedArrayBuffer object in the cross-worker mailbox. setSharedArrayBuffer performs an ordering memory barrier.
shapeOf(obj)
Get the shape of obj (an implementation detail).
groupOf(obj)
Get the group of obj (an implementation detail).
unwrappedObjectsHaveSameShape(obj1, obj2)
Returns true iff obj1 and obj2 have the same shape, false otherwise. Both objects are unwrapped first, so this can be used on objects from different globals.
sleep(dt)
Sleep for dt seconds.
compile(code)
Compiles a string to bytecode, potentially throwing.
parseModule(code)
Parses source text as a module and returns a Module object.
setModuleResolveHook(function(module, specifier) {})
Set the HostResolveImportedModule hook to function. This hook is used to look up a previously loaded module object. It should be implemented by the module loader.
getModuleLoadPath()
Return any --module-load-path argument passed to the shell. Used by the module loader.
parse(code)
Parses a string, potentially throwing.
syntaxParse(code)
Check the syntax of a string, returning success value
offThreadCompileScript(code[, options])
Compile code on a helper thread. To wait for the compilation to finish and run the code, call runOffThreadScript. If present, options may have properties saying how the code should be compiled:
noScriptRval
use the no-script-rval compiler option (default: false)
fileName
filename for error messages and debug info
lineNumber
starting line number for error messages and debug info
columnNumber
starting column number for error messages and debug info
element
if present with value v, convert v to an object o and mark the source as being attached to the DOM element o. If the property is omitted or v is null, don't attribute the source to any DOM element.
elementAttributeName
if present and not undefined, the name of property of element that holds this code. This is what Debugger.Source.prototype.elementAttributeName returns.
runOffThreadScript()
Wait for off-thread compilation to complete. If an error occurred, throw the appropriate exception; otherwise, run the script and return its value.
offThreadCompileModule(code)
Compile code on a helper thread. To wait for the compilation to finish and get the module object, call finishOffThreadModule.
finishOffThreadModule()
Wait for off-thread compilation to complete. If an error occurred, throw the appropriate exception; otherwise, return the module object
timeout([seconds], [func])
Get/Set the limit in seconds for the execution time for the current context. A negative value (default) means that the execution time is unlimited. If a second argument is provided, it will be invoked when the timer elapses. Calling this function will replace any callback set by setInterruptCallback.
interruptIf(cond)
Requests interrupt callback if cond is true. If a callback function is set via timeout or setInterruptCallback, it will be called. No-op otherwise.
invokeInterruptCallback(fun)
Forcefully set the interrupt flag and invoke the interrupt handler. If a callback function is set via timeout or setInterruptCallback, it will be called. Before returning, fun is called with the return value of the interrupt handler.
setInterruptCallback(func)
Sets func as the interrupt callback function. Calling this function will replace any callback set by timeout.
enableLastWarning()
Enable storing the last warning.
disableLastWarning()
Disable storing the last warning.
getLastWarning()
Returns an object that represents the last warning.
clearLastWarning()
Clear the last warning.
elapsed()
Execution time elapsed for the current thread.
decompileFunction(func)
Decompile a function.
decompileThis()
Decompile the currently executing script.
thisFilename()
Return the filename of the current script
newGlobal([options])
Return a new global object in a new compartment. If options is given, it may have any of the following properties:
sameZoneAs
the compartment will be in the same zone as the given object (defaults to a new zone)
invisibleToDebugger
the global will be invisible to the debugger (default false)
principal
if present, its value converted to a number must be an integer that fits in 32 bits; use that as the new compartment's principal. Shell principals are toys, meant only for testing; one shell principal subsumes another if its set bits are a superset of the other's. Thus, a principal of 0 subsumes nothing, while a principals of ~0 subsumes all other principals. The absence of a principal is treated as if its bits were 0xffff, for subsumption purposes. If this property is omitted, supply no principal.
createMappedArrayBuffer(filename, [offset, [size]])
Create an array buffer that mmaps the given file.
addPromiseReactions(promise, onResolve, onReject)
Calls the JS::AddPromiseReactions JSAPI function with the given arguments.
getMaxArgs()
Return the maximum number of supported args for a call.
objectEmulatingUndefined()
Return a new object obj for which typeof obj === "undefined", obj == null and obj == undefined (and vice versa for !=), and ToBoolean(obj) === false.
isCachingEnabled()
Return whether JS caching is enabled.
setCachingEnabled(b)
Enable or disable JS caching.
cacheEntry(code)
Return a new opaque object which emulates a cache entry of a script. This object encapsulates the code and its cached content. The cache entry is filled and read by the evaluate function by using it in place of the source, and by setting saveBytecode and loadBytecode options.
printProfilerEvents()
Register a callback with the profiler that prints javascript profiler events to stderr. Callback is only registered if profiling is enabled.
enableSingleStepProfiling()
This function will fail on platforms that don't support single-step profiling (currently everything but ARM-simulator). When enabled, at every instruction a backtrace will be recorded and stored in an array. Adjacent duplicate backtraces are discarded.
disableSingleStepProfiling()
Return the array of backtraces recorded by enableSingleStepProfiling.
enableSPSProfiling()
Enables SPS instrumentation and corresponding assertions, with slow assertions disabled.
enableSPSProfilingWithSlowAssertions()
Enables SPS instrumentation and corresponding assertions, with slow assertions enabled.
disableSPSProfiling()
Disables SPS instrumentation
isLatin1(s)
Return true iff the string's characters are stored as Latin1.
stackPointerInfo()
Return an int32 value which corresponds to the offset of the latest stack pointer, such that one can take the differences of 2 to estimate a frame-size.
entryPoints(params)
Carry out some JSAPI operation as directed by params, and return an array of objects describing which JavaScript entry points were invoked as a result. params is an object whose properties indicate what operation to perform. Here are the recognized groups of properties:
{ function }
Call the object params.function with no arguments.
{ object, property }
Fetch the property named params.property of params.object.
{ ToString }
Apply JS::ToString to params.toString.
{ ToNumber }
Apply JS::ToNumber to params.toNumber.
{ eval }
Apply JS::Evaluate to params.eval.
The return value is an array of strings, with one element for each JavaScript invocation that occurred as a result of the given operation. Each element is the name of the function invoked, or the string 'eval:FILENAME' if the code was invoked by eval or something similar.
drainJobQueue()
Take jobs from the shell's job queue in FIFO order and run them until the queue is empty.
setPromiseRejectionTrackerCallback()
Sets the callback to be invoked whenever a Promise rejection is unhandled or a previously-unhandled rejection becomes handled.

Functions available only in DEBUG build

disassemble([fun/code])
Return the disassembly for the given function or code. All disassembly functions take these options as leading string arguments:
-r
disassemble recursively
-l
show line numbers
-S
omit source notes
dis([fun/code])
Disassemble functions into bytecodes.
disfile('foo.js')
Disassemble script file into bytecodes.
dissrc([fun/code])
Disassemble functions with source lines.
notes([fun])
Show source notes for functions.
stackDump(showArgs, showLocals, showThisProps)
Tries to print a lot of information about the current stack. Similar to the DumpJSStack() function in the browser.
arrayInfo(a1, a2, ...)
Report statistics about arrays.

Functions available only if ENABLE_INTL_API is defined

addIntlExtras(obj)
Adds various not-yet-standardized Intl functions as properties on the provided object (this should generally be Intl itself). The added functions and their behavior are experimental: don't depend upon them unless you're willing to update your code if these experimental APIs change underneath you.

Functions available if --fuzzing-safe is not specified

clone(fun[, scope])
Clone function object.
getSelfHostedValue()
Get a self-hosted value by its name. Note that these values don't get cached, so repeatedly getting the same value creates multiple distinct clones.
line2pc([fun,] line)
Map line number to PC.
pc2line(fun[, pc])
Map PC to line number.
nestedShell(shellArgs...)
Execute the given code in a new JS shell process, passing this nested shell the arguments passed to nestedShell. argv[0] of the nested shell will be argv[0] of the current shell (which is assumed to be the actual path to the shell. arguments[0] (of the call to nestedShell) will be argv[1], arguments[1] will be argv[2], etc.
assertFloat32(value, isFloat32)
In IonMonkey only, asserts that value has (resp. hasn't) the MIRType::Float32 if isFloat32 is true (resp. false).
assertRecoveredOnBailout(var)
In IonMonkey only, asserts that variable has RecoveredOnBailout flag.
withSourceHook(hook, fun)
Set this JS runtime's lazy source retrieval hook (that is, the hook used to find sources compiled with CompileOptions::LAZY_SOURCE) to hook; call fun with no arguments; and then restore the runtime's original hook. Return or throw whatever fun did. hook gets passed the requested code's URL, and should return a string.

Notes:

  1. SpiderMonkey may assert if the returned code isn't close enough to the script's real code, so this function is not fuzzer-safe.
  2. The runtime can have only one source retrieval hook active at a time. If fun is not careful, hook could be asked to retrieve the source code for compilations that occurred long before it was set, and that it knows nothing about. The reverse applies as well: the original hook, that we reinstate after the call to fun completes, might be asked for the source code of compilations that fun performed, and which, presumably, only hook knows how to find.

 

wrapWithProto(obj)
Wrap an object into a noop wrapper with prototype semantics. Note: This is not fuzzing safe because it can be used to construct deeply nested wrapper chains that cannot exist in the wild.
trackedOpts(fun)
Returns an object describing the tracked optimizations of fun, if any. If fun is not a scripted function or has not been compiled by Ion, null is returned.
dumpScopeChain(obj)
Prints the scope chain of an interpreted function or a module.
crash([message])
Crashes the process with a MOZ_CRASH.
setARMHwCapFlags("flag1,flag2 flag3")
On non-ARM, no-op. On ARM, set the hardware capabilities. The list of flags is available by calling this function with help as the flag's name
wasmLoop(filename, imports)
Performs an AFL-style persistent loop reading data from the given file and passing it to thewasmEval function together with the specified imports object.

Testing functions

Testing functions are available also on Firefox via Components.utils.getJSTestingFunctions()

Functions always available

gc([obj] | 'zone' [, 'shrinking'])
Run the garbage collector. When obj is given, GC only its zone. If zone is given, GC any zones that were scheduled for GC via schedulegc. If shrinking is passed as the optional second argument, perform a shrinking GC rather than a normal GC.
minorgc([aboutToOverflow])
Run a minor collector on the Nursery. When aboutToOverflow is true, marks the store buffer as about-to-overflow before collecting.
gcparam(name [, value])
Wrapper for JS_[GS]etGCParameter. The name is one of:
  • maxBytes
  • maxMallocBytes
  • gcBytes
  • gcNumber
  • mode
  • unusedChunks
  • totalChunks
  • sliceTimeBudget
  • markStackLimit
  • highFrequencyTimeLimit
  • highFrequencyLowLimit
  • highFrequencyHighLimit
  • highFrequencyHeapGrowthMax
  • highFrequencyHeapGrowthMin
  • lowFrequencyHeapGrowth
  • dynamicHeapGrowth
  • dynamicMarkSlice
  • allocationThreshold
  • minEmptyChunkCount
  • maxEmptyChunkCount
  • compactingEnabled
  • refreshFrameSlicesEnabled
relazifyFunctions(...)
Perform a GC and allow relazification of functions. Accepts the same arguments as gc().
getBuildConfiguration()
Return an object describing some of the configuration options SpiderMonkey was built with.
hasChild(parent, child)
Return true if child is a child of parent, as determined by a call to TraceChildren
setSavedStacksRNGState(seed)
Set this compartment's SavedStacks' RNG state.
getSavedFrameCount()
Return the number of SavedFrame instances stored in this compartment's SavedStacks cache.
saveStack([maxDepth [, compartment]])
Capture a stack. If maxDepth is given, capture at most maxDepth number of frames. If compartment is given, allocate the js::SavedFrame instances with the given object's compartment.
saveStack(object [, shouldIgnoreSelfHosted = true]])
Capture a stack back to the first frame whose principals are subsumed by the object's compartment's principals. If shouldIgnoreSelfHosted is given, control whether self-hosted frames are considered when checking principals.
callFunctionFromNativeFrame(function)
Call function with a (C++-)native frame on stack. Required for testing that SaveStack properly handles native frames.
callFunctionWithAsyncStack(function, stack, asyncCause)
Call function, using the provided stack as the async stack responsible for the call, and propagate its return value or the exception it throws. The function is called with no arguments, and this is undefined. The specified asyncCause is attached to the provided stack frame.
enableTrackAllocations()
Start capturing the JS stack at every allocation. Note that this sets an object metadata callback that will override any other object metadata callback that may be set.
disableTrackAllocations()
Stop capturing the JS stack at every allocation.
makeFinalizeObserver()
Get a special object whose finalization increases the counter returned by the finalizeCount function.
finalizeCount()
Return the current value of the finalization counter that is incremented each time an object returned by the makeFinalizeObserver is finalized.
resetFinalizeCount()
Reset the value returned by finalizeCount().
gcPreserveCode()
Preserve JIT code during garbage collections.
startgc([n [, 'shrinking']])
Start an incremental GC and run a slice that processes about n objects. If shrinking is passesd as the optional second argument, perform a shrinking GC rather than a normal GC.
gcslice([n])
Start or continue an an incremental GC, running a slice that processes about n objects.
abortgc()
Abort the current incremental GC.
fullcompartmentchecks(true|false)
If true, check for compartment mismatches before every GC.
nondeterministicGetWeakMapKeys(weakmap)
Return an array of the keys in the given WeakMap.
internalConst(name)
Query an internal constant for the engine. See InternalConst source for the list of constant names.
isProxy(obj)
If true, obj is a proxy of some sort
dumpHeap(['collectNurseryBeforeDump'], [filename])
Dump reachable and unreachable objects to the named file, or to stdout. If collectNurseryBeforeDump is specified, a minor GC is performed first, otherwise objects in the nursery are ignored.
terminate()
Terminate JavaScript execution, as if we had run out of memory or been terminated by the slow script dialog.
readSPSProfilingStack()
Reads the jit stack using ProfilingFrameIterator.
enableOsiPointRegisterChecks()
Emit extra code to verify live regs at the start of a VM call are not modified before its OsiPoint.
displayName(fn)
Gets the display name for a function, which can possibly be a guessed or inferred name based on where the function was defined. This can be different from the name property on the function.
isAsmJSCompilationAvailable
Returns whether asm.js compilation is currently available or whether it is disabled (e.g., by the debugger).
isSimdAvailable
Returns true if SIMD extensions are supported on this platform.
getCompilerOptions()
Return an object describing some of the JIT compiler options.
isAsmJSModule(fn)
Returns whether the given value is a function containing "use asm" that has been validated according to the asm.js spec.
isAsmJSModuleLoadedFromCache(fn)
Return whether the given asm.js module function has been loaded directly from the cache. This function throws an error if fn is not a validated asm.js module.
isAsmJSFunction(fn)
Returns whether the given value is a nested function in an asm.js module that has been both compile- and link-time validated.
wasmIsSupported()
Returns a boolean indicating whether WebAssembly is supported on the current device.
wasmTextToBinary(str)
Translates the given text wasm module into its binary encoding.
wasmBinaryToText(bin)
Translates binary encoding to text format
wasmExtractCode(module)
Extracts generated machine code from WebAssembly.Module.
isLazyFunction(fun)
True if fun is a lazy JSFunction.
isRelazifiableFunction(fun)
Ture if fun is a JSFunction with a relazifiable JSScript.
enableShellAllocationMetadataBuilder()
Use ShellAllocationMetadataBuilder to supply metadata for all newly created objects.
getAllocationMetadata(obj)
Get the metadata for an object.
bailout()
Force a bailout out of ionmonkey (if running in ionmonkey).
bailAfter(number)
Start a counter to bail once after passing the given amount of possible bailout positions in ionmonkey.
inJit()
Returns true when called within (jit-)compiled code. When jit compilation is disabled this function returns an error string. This function returns false in all other cases. Depending on truthiness, you should continue to wait for compilation to happen or stop execution.
inIon()
Returns true when called within ion. When ion is disabled or when compilation is abnormally slow to start, this function returns an error string. Otherwise, this function returns false. This behaviour ensures that a falsy value means that we are not in ion, but expect a compilation to occur in the future. Conversely, a truthy value means that we are either in ion or that there is litle or no chance of ion ever compiling the current script.
assertJitStackInvariants()
Iterates the Jit stack and check that stack invariants hold.
setCompilerOption(option, number)
Set a compiler option indexed in JSCompileOption enum to a number.
setIonCheckGraphCoherency(bool)
Set whether Ion should perform graph consistency (DEBUG-only) assertions. These assertions are valuable and should be generally enabled, however they can be very expensive for large (wasm) programs.
serialize(data, [transferables, [policy]])
Serialize data using JS_WriteStructuredClone. Returns a structured clone buffer object. policy must be an object. The following keys' string values will be used to determine whether the corresponding types may be serialized (value allow, the default) or not (value deny). If denied types are encountered a TypeError will be thrown during cloning. Valid keys: SharedArrayBuffer.
deserialize(clonebuffer)
Deserialize data generated by serialize.
detachArrayBuffer(buffer)
Detach the given ArrayBuffer object from its memory, i.e. as if it had been transferred to a WebWorker.
helperThreadCount()
Returns the number of helper threads available for off-main-thread tasks.
reportOutOfMemory()
Report OOM, then clear the exception and return undefined. For crash testing.
throwOutOfMemory()
Throw out of memory exception, for OOM handling testing.
reportLargeAllocationFailure()
Call the large allocation failure callback, as though a large malloc call failed, then return undefined. In Gecko, this sends a memory pressure notification, which can free up some memory.
findPath(start, target)
Return an array describing one of the shortest paths of GC heap edges from start to target, or undefined if target is unreachable from start. Each element of the array is either of the form: { node: {object or string}, edge: {string describing edge from node} } , if the node is a JavaScript object or value; or of the form: { type: {string describing node}, edge: {string describing edge} } , if the node is some internal thing that is not a proper JavaScript value (like a shape or a scope chain element). The destination of the i'th array element's edge is the node of the i+1'th array element; the destination of the last array element is implicitly target.
shortestPaths(start, targets, maxNumPaths)
Return an array of arrays of shortest retaining paths. There is an array of shortest retaining paths for each object in targets. The maximum number of paths in each of those arrays is bounded by maxNumPaths. Each element in a path is of the form { predecessor, edge }.
sharedMemoryEnabled()
Return true if SharedArrayBuffer and Atomics are enabled
evalReturningScope(scriptStr, [global])
Evaluate the script in a new scope and return the scope. If global is present, clone the script to global before executing.
cloneAndExecuteScript(source, global)
Compile source in the current compartment, clone it into global's compartment, and run it there.
backtrace()
Dump out a brief backtrace.
getBacktrace([options])
Return the current stack as a string. Takes an optional options object, which may contain any or all of the boolean properties options.args - show arguments to each function options.locals - show local variables in each frame options.thisprops - show the properties of the this object of each frame
byteSize(value)
Return the size in bytes occupied by value, or undefined if value is not allocated in memory.
byteSizeOfScript(f)
Return the size in bytes occupied by the function f's JSScript.
setImmutablePrototype(obj)
Try to make obj's [[Prototype]] immutable, such that subsequent attempts to change it will fail. Return true if obj's [[Prototype]] was successfully made immutable (or if it already was immutable), false otherwise. Throws in case of internal error, or if the operation doesn't even make sense (for example, because the object is a revoked proxy).
setLazyParsingDisabled(bool)
Explicitly disable lazy parsing in the current compartment. The default is that lazy parsing is not explicitly disabled.
setDiscardSource(bool)
Explicitly enable source discarding in the current compartment. The default is that source discarding is not explicitly enabled.
getConstructorName(object)
If the given object was created with new Ctor, return the constructor's display name. Otherwise, return null.
allocationMarker([options])
Return a freshly allocated object whose [[Class]] name is AllocationMarker. Such objects are allocated only by calls to this function, never implicitly by the system, making them suitable for use in allocation tooling tests. Takes an optional options object which may contain the following properties: * nursery: bool, whether to allocate the object in the nursery
setGCCallback({action:"...", options...})
Set the GC callback. action may be:
minorGC
run a nursery collection
majorGC
run a major collection, nesting up to a given depth
getLcovInfo(global)
Generate LCOV tracefile for the given compartment. If no global are provided then the current global is used as the default one.
getModuleEnvironmentNames(module)
Get the list of a module environment's bound names for a specified module.
getModuleEnvironmentValue(module, name)
Get the value of a bound name in a module environment.
enableForEach()
Enables the deprecated, non-standard for-each.
disableForEach()
Disables the deprecated, non-standard for-each.

Functions available only if SPIDERMONKEY_PROMISE is defined

settlePromiseNow(promise)
'Settle' a promise immediately. This just marks the promise as resolved with a value of undefined and causes the firing of any onPromiseSettled hooks set on Debugger instances that are observing the given promise's global as a debuggee.
getWaitForAllPromise(densePromisesArray)
Calls the GetWaitForAllPromise JSAPI function and returns the result Promise.
resolvePromise(promise, resolution)
Resolve a Promise by calling the JSAPI function JS::ResolvePromise.
rejectPromise(promise, reason)
Reject a Promise by calling the JSAPI function JS::RejectPromise.

Functions available only if SPIDERMONKEY_PROMISE is not defined

makeFakePromise()
Create an object whose [[Class]] name is 'Promise' and call JS::dbg::onNewPromise on it before returning it. It doesn't actually have any of the other behavior associated with promises.
settleFakePromise(promise)
'Settle' a promise created by makeFakePromise(). This doesn't have any observable effects outside of firing any onPromiseSettled hooks set on Debugger instances that are observing the given promise's global as a debuggee.

Functions available only if JS_GC_ZEAL is defined

gczeal(level, [N])
Specifies how zealous the garbage collector should be. Some of these modes can be set simultaneously, by passing multiple level options, e.g. "2;4" will activate both modes 2 and 4. Modes can be specified by name or number.

Values:

0: (None)
Normal amount of collection (resets all modes)
1: (Poke)
Collect when roots are added or removed
2: (Alloc)
Collect when every N allocations (default: 100)
3: (FrameGC)
Collect when the window paints (browser only)
4: (VerifierPre)
Verify pre write barriers between instructions
5: (FrameVerifierPre)
Verify pre write barriers between paints
6: (StackRooting)
Verify stack rooting
7: (GenerationalGC)
Collect the nursery every N nursery allocations
8: (IncrementalRootsThenFinish)
Incremental GC in two slices: 1) mark roots 2) finish collection
9: (IncrementalMarkAllThenFinish)
Incremental GC in two slices: 1) mark all 2) new marking and finish
10: (IncrementalMultipleSlices)
Incremental GC in multiple slices
11: (IncrementalMarkingValidator)
Verify incremental marking
12: (ElementsBarrier)
Always use the individual element post-write barrier, regardless of elements size
13: (CheckHashTablesOnMinorGC)
Check internal hashtables on minor GC
14: (Compact)
Perform a shrinking collection every N allocations
15: (CheckHeapAfterGC)
Walk the heap to check its integrity after every GC
16: (CheckNursery)
Check nursery integrity on minor GC

 

schedulegc([num | obj])
If num is given, schedule a GC after num allocations. If obj is given, schedule a GC of obj's zone. Returns the number of allocations before the next trigger.
selectforgc(obj1, obj2, ...)
Schedule the given objects to be marked in the next GC slice.
verifyprebarriers()
Start or end a run of the pre-write barrier verifier.
verifypostbarriers()
Does nothing (the post-write barrier verifier has been remove).
gcstate()
Report the global GC state.
deterministicgc(true|false)
If true, only allow determinstic GCs to run.

Functions available only if JS_TRACE_LOGGING is defined

startTraceLogger()
Start logging the mainThread. Note: tracelogging starts automatically. Disable it by setting environment variable TLOPTIONS=disableMainThread
stopTraceLogger()
Stop logging the mainThread.

Functions available only in nightly build

objectAddress(obj)
Return the current address of the object. For debugging only--this address may change during a moving GC.
sharedAddress(obj)
Return the address of the shared storage of a SharedArrayBuffer.

Functions available only in DEBUG build

dumpObject()
Dump an internal representation of an object.
dumpStringRepresentation(str)
Print a human-readable description of how the string str is represented.
setRNGState(seed0, seed1)
Set this compartment's RNG state.

Functions available only in DEBUG build or JS_OOM_BREAKPOINT is defined

oomThreadTypes()
Get the number of thread types that can be used as an argument for oomAfterAllocations() and oomAtAllocation().
oomAfterAllocations(count [,threadType])
After count js_malloc memory allocations, fail every following allocation (return nullptr). The optional thread type limits the effect to the specified type of helper thread.
oomAtAllocation(count [,threadType])
After count js_malloc memory allocations, fail the next allocation (return nullptr). The optional thread type limits the effect to the specified type of helper thread.
resetOOMFailure()
Remove the allocation failure scheduled by either oomAfterAllocations() or oomAtAllocation() and return whether any allocation had been caused to fail.
oomTest(function, [expectExceptionOnFailure = true])
Test that the passed function behaves correctly under OOM conditions by repeatedly executing it and simulating allocation failure at successive allocations until the function completes without seeing a failure. By default this tests that an exception is raised if execution fails, but this can be disabled by passing false as the optional second parameter. This is also disabled when --fuzzing-safe is specified.

Functions available only in DEBUG build if --fuzzing-safe is not specified and

parseRegExp(pattern[, flags[, match_only])
Parses a RegExp pattern and returns a tree, potentially throwing.
disRegExp(regexp[, match_only[, input]])
Dumps RegExp bytecode.

Document Tags and Contributors

 Last updated by: arai,