Name Description Size
AllocationRecording.h This struct holds the information needed to create a profiler marker payload that can represent a JS allocation. It translates JS engine specific classes, into something that can be used in the profiler. 2654
AllocPolicy.h JS allocation policies. The allocators here are for system memory with lifetimes which are not managed by the GC. See the comment at the top of vm/MallocProvider.h. 5973
ArrayBuffer.h ArrayBuffer functionality. 9648
BuildId.h Embedding-provided build ID information, used by SpiderMonkey to tag cached compilation data so that cached data can be reused when possible, or discarded and regenerated if necessary. 2137
CallArgs.h [SMDOC] JS::CallArgs API Helper classes encapsulating access to the callee, |this| value, arguments, and argument count for a call/construct operation. JS::CallArgs encapsulates access to a JSNative's un-abstracted |unsigned argc, Value* vp| arguments. The principal way to create a JS::CallArgs is using JS::CallArgsFromVp: // If provided no arguments or a non-numeric first argument, return zero. // Otherwise return |this| exactly as given, without boxing. static bool Func(JSContext* cx, unsigned argc, JS::Value* vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); // Guard against no arguments or a non-numeric arg0. if (args.length() == 0 || !args[0].isNumber()) { args.rval().setInt32(0); return true; } // Access to the callee must occur before accessing/setting // the return value. JSObject& callee = args.callee(); args.rval().setObject(callee); // callee() and calleev() will now assert. // It's always fine to access thisv(). HandleValue thisv = args.thisv(); args.rval().set(thisv); // As the return value was last set to |this|, returns |this|. return true; } CallArgs is exposed publicly and used internally. Not all parts of its public interface are meant to be used by embedders! See inline comments to for details. It's possible (albeit deprecated) to manually index into |vp| to access the callee, |this|, and arguments of a function, and to set its return value. This does not have the error-handling or moving-GC correctness of CallArgs. New code should use CallArgs instead whenever possible. The eventual plan is to change JSNative to take |const CallArgs&| directly, for automatic assertion of correct use and to make calling functions more efficient. Embedders should start internally switching away from using |argc| and |vp| directly, except to create a |CallArgs|. Then, when an eventual release making that change occurs, porting efforts will require changing methods' signatures but won't require invasive changes to the methods' implementations, potentially under time pressure. 11651
CallNonGenericMethod.h js_CallNonGenericMethod_h 4839
CharacterEncoding.h By default, all C/C++ 1-byte-per-character strings passed into the JSAPI are treated as ISO/IEC 8859-1, also known as Latin-1. That is, each byte is treated as a 2-byte character, and there is no way to pass in a string containing characters beyond U+00FF. 13993
Class.h JSClass definition and its component types, plus related interfaces. 34108
CompilationAndEvaluation.h Functions for compiling and evaluating scripts. 15543
CompileOptions.h Options for JavaScript compilation. In the most common use case, a CompileOptions instance is allocated on the stack, and holds non-owning references to non-POD option values: strings, principals, objects, and so on. The code declaring the instance guarantees that such option values will outlive the CompileOptions itself: objects are otherwise rooted, principals have had their reference counts bumped, and strings won't be freed until the CompileOptions goes out of scope. In this situation, CompileOptions only refers to things others own, so it can be lightweight. In some cases, however, we need to hold compilation options with a non-stack-like lifetime. For example, JS::CompileOffThread needs to save compilation options where a worker thread can find them, then return immediately. The worker thread will come along at some later point, and use the options. The compiler itself just needs to be able to access a collection of options; it doesn't care who owns them, or what's keeping them alive. It does its own addrefs/copies/tracing/etc. Furthermore, in some cases compile options are propagated from one entity to another (e.g. from a script to a function defined in that script). This involves copying over some, but not all, of the options. So we have a class hierarchy that reflects these four use cases: - TransitiveCompileOptions is the common base class, representing options that should get propagated from a script to functions defined in that script. This class is abstract and is only ever used as a subclass. - ReadOnlyCompileOptions is the only subclass of TransitiveCompileOptions, representing a full set of compile options. It can be used by code that simply needs to access options set elsewhere, like the compiler. This class too is abstract and is only ever used as a subclass. - The usual CompileOptions class must be stack-allocated, and holds non-owning references to the filename, element, and so on. It's derived from ReadOnlyCompileOptions, so the compiler can use it. - OwningCompileOptions roots / copies / reference counts of all its values, and unroots / frees / releases them when it is destructed. It too is derived from ReadOnlyCompileOptions, so the compiler accepts it. 15653
ContextOptions.h JavaScript API. 5069
Conversions.h ECMAScript conversion operations. 20709
Date.h JavaScript date/time computation and creation functions. 8784
Debug.h 14069
Equality.h Equality operations. 2341
ErrorReport.h Error-reporting types and structures. Despite these types and structures existing in js/public, significant parts of their heritage date back to distant SpiderMonkey past, and they are not all universally well-thought-out as ideal, intended-to-be-permanent API. We may eventually replace this with something more consistent with ECMAScript the language and less consistent with '90s-era JSAPI inventions, but it's doubtful this will happen any time soon. 8189
experimental 1
ForOfIterator.h A convenience class that makes it easy to perform the operations of a for-of loop. 3342
GCAnnotations.h js_GCAnnotations_h 3647
GCAPI.h High-level interface to the JS garbage collector. 36386
GCHashTable.h 23758
GCPolicyAPI.h 7182
GCVariant.h 5575
GCVector.h 10788
HashTable.h js_HashTable_h 1135
HeapAPI.h These values are private to the JS engine. 21265
Id.h Only JSStrings that have been interned via the JSAPI can be turned into jsids by API clients. N.B. if a jsid is backed by a string which has not been interned, that string must be appropriately rooted to avoid being collected by the GC. 7688
Initialization.h SpiderMonkey initialization and shutdown APIs. 4557
JSON.h JSON serialization and deserialization operations. 3621
LocaleSensitive.h Functions and structures related to locale-sensitive behavior, including exposure of the default locale (used by operations like toLocaleString). 3810
MemoryFunctions.h Low-level memory-allocation functions. 3221
MemoryMetrics.h These are the measurements used by Servo. 29357
Modules.h JavaScript module (as in, the syntactic construct) operations. 6324
OffThreadScriptCompilation.h Types and functions related to the compilation of JavaScript off the direct JSAPI-using thread. 5918
Principals.h JSPrincipals and related interfaces. 5012
Printf.h Wrappers for mozilla::Smprintf and friends that are used throughout JS. 1212
ProfilingCategory.h 6391
ProfilingFrameIterator.h After each sample run, this method should be called with the current buffer position at which the buffer contents start. This will update the corresponding field on the JSRuntime. See the field |profilerSampleBufferRangeStart| on JSRuntime for documentation about what this value is used for. 7496
ProfilingStack.h 21839
Promise.h Abstract base class for an ECMAScript Job Queue: https://www.ecma-international.org/ecma-262/9.0/index.html#sec-jobs-and-job-queues SpiderMonkey doesn't schedule Promise resolution jobs itself; instead, the embedding can provide an instance of this class SpiderMonkey can use to do that scheduling. The JavaScript shell includes a simple implementation adequate for running tests. Browsers need to augment job handling to meet their own additional requirements, so they can provide their own implementation. 24303
PropertyDescriptor.h Property descriptors and flags. 13333
PropertySpec.h Property descriptors and flags. 14657
ProtoKey.h A higher-order macro for enumerating all JSProtoKey values. 8463
Proxy.h 29289
Realm.h Ways to get various per-Realm objects. All the getters declared below operate on the JSContext's current Realm. 4660
RealmOptions.h Options specified when creating a realm to determine its behavior, immutable options determining the behavior of an existing realm, and mutable options on an existing realm that may be changed when desired. 9587
RefCounted.h js_RefCounted_h 2444
RegExp.h Regular expression-related operations. 3158
RegExpFlags.h Regular expression flags. 3764
RequiredDefines.h Various #defines required to build SpiderMonkey. Embedders should add this file to the start of the command line via -include or a similar mechanism, or SpiderMonkey public headers may not work correctly. 1210
Result.h [SMDOC] JS::Result `Result` is used as the return type of many SpiderMonkey functions that can either succeed or fail. See "/mfbt/Result.h". ## Which return type to use `Result` is for return values. Obviously, if you're writing a function that can't fail, don't use Result. Otherwise: JS::Result<> - function can fail, doesn't return anything on success (defaults to `JS::Result<JS::Ok, JS::Error&>`) JS::Result<JS::OOM&> - like JS::Result<>, but fails only on OOM JS::Result<Data> - function can fail, returns Data on success JS::Result<Data, JS::OOM&> - returns Data, fails only on OOM mozilla::GenericErrorResult<JS::Error&> - always fails That last type is like a Result with no success type. It's used for functions like `js::ReportNotFunction` that always return an error result. `GenericErrorResult<E>` implicitly converts to `Result<V, E>`, regardless of V. ## Checking Results when your return type is Result When you call a function that returns a `Result`, use the `MOZ_TRY` macro to check for errors: MOZ_TRY(DefenestrateObject(cx, obj)); If `DefenestrateObject` returns a success result, `MOZ_TRY` is done, and control flows to the next statement. If `DefenestrateObject` returns an error result, `MOZ_TRY` will immediately return it, propagating the error to your caller. It's kind of like exceptions, but more explicit -- you can see in the code exactly where errors can happen. You can do a tail call instead of using `MOZ_TRY`: return DefenestrateObject(cx, obj); Indicate success with `return Ok();`. If the function returns a value on success, use `MOZ_TRY_VAR` to get it: RootedValue thrug(cx); MOZ_TRY_VAR(thrug, GetObjectThrug(cx, obj)); This behaves the same as `MOZ_TRY` on error. On success, the success value of `GetObjectThrug(cx, obj)` is assigned to the variable `thrug`. ## Checking Results when your return type is not Result This header defines alternatives to MOZ_TRY and MOZ_TRY_VAR for when you need to call a `Result` function from a function that uses false or nullptr to indicate errors: JS_TRY_OR_RETURN_FALSE(cx, DefenestrateObject(cx, obj)); JS_TRY_VAR_OR_RETURN_FALSE(cx, v, GetObjectThrug(cx, obj)); JS_TRY_OR_RETURN_NULL(cx, DefenestrateObject(cx, obj)); JS_TRY_VAR_OR_RETURN_NULL(cx, v, GetObjectThrug(cx, obj)); When TRY is not what you want, because you need to do some cleanup or recovery on error, use this idiom: if (!cx->resultToBool(expr_that_is_a_Result)) { ... your recovery code here ... } In place of a tail call, you can use one of these methods: return cx->resultToBool(expr); // false on error return cx->resultToPtr(expr); // null on error Once we are using `Result` everywhere, including in public APIs, all of these will go away. ## GC safety When a function returns a `JS::Result<JSObject*>`, it is the program's responsibility to check for errors and root the object before continuing: RootedObject wrapper(cx); MOZ_TRY_VAR(wrapper, Enwrapify(cx, thing)); This is ideal. On error, there is no object to root; on success, the assignment to wrapper roots it. GC safety is ensured. `Result` has methods .isOk(), .isErr(), .unwrap(), and .unwrapErr(), but if you're actually using them, it's possible to create a GC hazard. The static analysis will catch it if so, but that's hardly convenient. So try to stick to the idioms shown above. ## Future directions At present, JS::Error and JS::OOM are empty structs. The plan is to make them GC things that contain the actual error information (including the exception value and a saved stack). The long-term plan is to remove JS_IsExceptionPending and JS_GetPendingException in favor of JS::Error. Exception state will no longer exist. 8038
RootingAPI.h [SMDOC] Stack Rooting Moving GC Stack Rooting A moving GC may change the physical location of GC allocated things, even when they are rooted, updating all pointers to the thing to refer to its new location. The GC must therefore know about all live pointers to a thing, not just one of them, in order to behave correctly. The |Rooted| and |Handle| classes below are used to root stack locations whose value may be held live across a call that can trigger GC. For a code fragment such as: JSObject* obj = NewObject(cx); DoSomething(cx); ... = obj->lastProperty(); If |DoSomething()| can trigger a GC, the stack location of |obj| must be rooted to ensure that the GC does not move the JSObject referred to by |obj| without updating |obj|'s location itself. This rooting must happen regardless of whether there are other roots which ensure that the object itself will not be collected. If |DoSomething()| cannot trigger a GC, and the same holds for all other calls made between |obj|'s definitions and its last uses, then no rooting is required. SpiderMonkey can trigger a GC at almost any time and in ways that are not always clear. For example, the following innocuous-looking actions can cause a GC: allocation of any new GC thing; JSObject::hasProperty; JS_ReportError and friends; and ToNumber, among many others. The following dangerous-looking actions cannot trigger a GC: js_malloc, cx->malloc_, rt->malloc_, and friends and JS_ReportOutOfMemory. The following family of three classes will exactly root a stack location. Incorrect usage of these classes will result in a compile error in almost all cases. Therefore, it is very hard to be incorrectly rooted if you use these classes exclusively. These classes are all templated on the type T of the value being rooted. - Rooted<T> declares a variable of type T, whose value is always rooted. Rooted<T> may be automatically coerced to a Handle<T>, below. Rooted<T> should be used whenever a local variable's value may be held live across a call which can trigger a GC. - Handle<T> is a const reference to a Rooted<T>. Functions which take GC things or values as arguments and need to root those arguments should generally use handles for those arguments and avoid any explicit rooting. This has two benefits. First, when several such functions call each other then redundant rooting of multiple copies of the GC thing can be avoided. Second, if the caller does not pass a rooted value a compile error will be generated, which is quicker and easier to fix than when relying on a separate rooting analysis. - MutableHandle<T> is a non-const reference to Rooted<T>. It is used in the same way as Handle<T> and includes a |set(const T& v)| method to allow updating the value of the referenced Rooted<T>. A MutableHandle<T> can be created with an implicit cast from a Rooted<T>*. In some cases the small performance overhead of exact rooting (measured to be a few nanoseconds on desktop) is too much. In these cases, try the following: - Move all Rooted<T> above inner loops: this allows you to re-use the root on each iteration of the loop. - Pass Handle<T> through your hot call stack to avoid re-rooting costs at every invocation. The following diagram explains the list of supported, implicit type conversions between classes of this family: Rooted<T> ----> Handle<T> | ^ | | | | +---> MutableHandle<T> (via &) All of these types have an implicit conversion to raw pointers. 55031
SavedFrameAPI.h Functions and types related to SavedFrame objects created by the Debugger API. 6180
SharedArrayBuffer.h ArrayBuffer functionality. 2016
SliceBudget.h This class records how much work has been done in a given collection slice, so that we can return before pausing for too long. Some slices are allowed to run for unlimited time, and others are bounded. To reduce the number of gettimeofday calls, we only check the time every 1000 operations. 2551
SourceText.h SourceText encapsulates a count of char16_t (UTF-16) or Utf8Unit (UTF-8) code units (note: code *units*, not bytes or code points) and those code units ("source units"). (Latin-1 is not supported: all places where Latin-1 must be compiled first convert to a supported encoding.) A SourceText either observes without owning, or takes ownership of, source units passed to |SourceText::init|. Thus SourceText can be used to efficiently avoid copying. Rules for use: 1) The passed-in source units must be allocated with js_malloc(), js_calloc(), or js_realloc() if |SourceText::init| is instructed to take ownership of the source units. 2) If |SourceText::init| merely borrows the source units, the user must keep them alive until associated JS compilation is complete. 3) Code that calls |SourceText::take{Chars,Units}()| must keep the source units alive until JS compilation completes. Normally only the JS engine should call |SourceText::take{Chars,Units}()|. 4) Use the appropriate SourceText parameterization depending on the source units encoding. Example use: size_t length = 512; char16_t* chars = js_pod_malloc<char16_t>(length); if (!chars) { JS_ReportOutOfMemory(cx); return false; } JS::SourceText<char16_t> srcBuf; if (!srcBuf.init(cx, chars, length, JS::SourceOwnership::TakeOwnership)) { return false; } JS::Rooted<JSScript*> script(cx); if (!JS::Compile(cx, options, srcBuf, &script)) { return false; } 10854
StableStringChars.h Safely access the contents of a string even as GC can cause the string's contents to move around in memory. 4167
Stream.h JSAPI functions and callbacks related to WHATWG Stream objects. Much of the API here mirrors the standard algorithms and standard JS methods of the objects defined in the Streams standard. One difference is that the functionality of the JS controller object is exposed to C++ as functions taking ReadableStream instances instead, for convenience. 19803
StructuredClone.h API for safe passing of structured data, HTML 2018 Feb 21 section 2.7. <https://html.spec.whatwg.org/multipage/structured-data.html> This is a serialization scheme for JS values, somewhat like JSON. It preserves some aspects of JS objects (strings, numbers, own data properties with string keys, array elements) but not others (methods, getters and setters, prototype chains). Unlike JSON, structured data: - can contain cyclic references. - handles Maps, Sets, and some other object types. - supports *transferring* objects of certain types from one realm to another, rather than cloning them. - is specified by a living standard, and continues to evolve. - is encoded in a nonstandard binary format, and is never exposed to Web content in its serialized form. It's used internally by the browser to send data from one thread/realm/domain to another, not across the network. 27639
SweepingAPI.h 2590
Symbol.h Symbols. 3738
TraceKind.h name type canBeGray inCCGraph 9900
TraceLoggerAPI.h SpiderMonkey TraceLogger APIs. 7936
TracingAPI.h Returns a static string equivalent of |kind|. 16971
TrackedOptimizationInfo.h 10611
Transcoding.h Structures and functions for transcoding compiled scripts and functions to and from memory. 3786
TypeDecls.h js_TypeDecls_h 4018
UbiNode.h 46091
UbiNodeBreadthFirst.h 10134
UbiNodeCensus.h 8169
UbiNodeDominatorTree.h In a directed graph with a root node `R`, a node `A` is said to "dominate" a node `B` iff every path from `R` to `B` contains `A`. A node `A` is said to be the "immediate dominator" of a node `B` iff it dominates `B`, is not `B` itself, and does not dominate any other nodes which also dominate `B` in turn. If we take every node from a graph `G` and create a new graph `T` with edges to each node from its immediate dominator, then `T` is a tree (each node has only one immediate dominator, or none if it is the root). This tree is called a "dominator tree". This class represents a dominator tree constructed from a `JS::ubi::Node` heap graph. The domination relationship and dominator trees are useful tools for analyzing heap graphs because they tell you: - Exactly what could be reclaimed by the GC if some node `A` became unreachable: those nodes which are dominated by `A`, - The "retained size" of a node in the heap graph, in contrast to its "shallow size". The "shallow size" is the space taken by a node itself, not counting anything it references. The "retained size" of a node is its shallow size plus the size of all the things that would be collected if the original node wasn't (directly or indirectly) referencing them. In other words, the retained size is the shallow size of a node plus the shallow sizes of every other node it dominates. For example, the root node in a binary tree might have a small shallow size that does not take up much space itself, but it dominates the rest of the binary tree and its retained size is therefore significant (assuming no external references into the tree). The simple, engineered algorithm presented in "A Simple, Fast Dominance Algorithm" by Cooper el al[0] is used to find dominators and construct the dominator tree. This algorithm runs in O(n^2) time, but is faster in practice than alternative algorithms with better theoretical running times, such as Lengauer-Tarjan which runs in O(e * log(n)). The big caveat to that statement is that Cooper et al found it is faster in practice *on control flow graphs* and I'm not convinced that this property also holds on *heap* graphs. That said, the implementation of this algorithm is *much* simpler than Lengauer-Tarjan and has been found to be fast enough at least for the time being. [0]: http://www.cs.rice.edu/~keith/EMBED/dom.pdf 24250
UbiNodePostOrder.h A post-order depth-first traversal of `ubi::Node` graphs. No GC may occur while an instance of `PostOrder` is live. The `NodeVisitor` type provided to `PostOrder::traverse` must have the following member: bool operator()(Node& node) The node visitor method. This method is called once for each `node` reachable from the start set in post-order. This visitor function should return true on success, or false if an error occurs. A false return value terminates the traversal immediately, and causes `PostOrder::traverse` to return false. The `EdgeVisitor` type provided to `PostOrder::traverse` must have the following member: bool operator()(Node& origin, Edge& edge) The edge visitor method. This method is called once for each outgoing `edge` from `origin` that is reachable from the start set. NB: UNLIKE NODES, THERE IS NO GUARANTEED ORDER IN WHICH EDGES AND THEIR ORIGINS ARE VISITED! This visitor function should return true on success, or false if an error occurs. A false return value terminates the traversal immediately, and causes `PostOrder::traverse` to return false. 5488
UbiNodeShortestPaths.h A back edge along a path in the heap graph. 10411
UbiNodeUtils.h 1239
UniquePtr.h js_UniquePtr_h 1547
Utility.h The public JS engine namespace. 23244
Value.h JS::Value implementation. 41929
Vector.h js_Vector_h 1035
Warnings.h Functionality for issuing and handling warnings. Warnings are situations that aren't inherently full-blown errors (and perhaps for spec compliance *can't* be), but that may represent dubious programming practice that embeddings may wish to know about. (That said, SpiderMonkey exposes various options that, when active, automatically upgrade warnings to errors. See |JS::TransitiveCompileOptions::werrorOptions| and |JS::ContextOptions::werror()|.) SpiderMonkey recognizes an unspecified set of syntactic patterns and runtime behaviors as triggering a warning. Embeddings may also recognize and report additional warnings. 3424
WeakMapPtr.h namespace JS 1415
Wrapper.h Helper for Wrapper::New default options. Callers of Wrapper::New() who wish to specify a prototype for the created Wrapper, *MUST* construct a WrapperOptions with a JSContext. 23698