Visit Mozilla.org

JS AddRoot

From MDC

(Redirected from JS AddNamedRoot)

Register a variable as a member of the garbage collector's root set, to protect anything the root points at from garbage collection.

[edit] Syntax

JSBool JS_AddRoot(JSContext *cx, void *rp);

JSBool JS_AddNamedRoot(JSContext *cx, void *rp, const char *name);

JSBool JS_AddNamedRootRT(JSRuntime *rt, void *rp, const char *name);
Name Type Description
cx JSContext * (in JS_AddRoot and JS_AddNamedRoot) The context in which to add the new root.

Requires request. (In a JS_THREADSAFE build, the caller must be in a request on this JSContext.)

rt JSRuntime * (in JS_AddNamedRootRT) The runtime in which to add the new root.
rp void * The address of the variable to be registered as a root.
name const char * (in JS_AddNamedRoot and JS_AddNamedRootRT) The name of the new root, or NULL.

[edit] Description

The functions JS_AddRoot, JS_AddNamedRoot, and JS_AddNamedRootRT add a C/C++ variable to the garbage collector's root set, the set of variables used as starting points each time the collector checks to see what memory is reachable. The garbage collector aggressively collects and recycles memory that it deems unreachable, so roots are often necessary to protect data from being prematurely collected.

rp is the address of a C/C++ variable (or field, or array element) of type jsdouble *, JSString *, JSObject *, or jsval. This variable must already be initialized. (For example, it must not be an uninitialized local variable. That could cause sporadic crashes during garbage collection, which can be hard to debug.) The variable must remain in memory until the balancing call to JS_RemoveRoot. If JS_AddNamedRoot succeeds, then as long as this variable points to a JavaScript value (a string or object, for example), that value is protected from garbage collection. If the variable points to an object, then any memory reachable from its properties is automatically protected from garbage collection, too.

Do not pass a pointer to a JS double, string, or object—rp must be either a pointer to a pointer variable or a pointer to a jsval variable.

An entry for rp is added to the garbage collector's root set for the JSRuntime associated with cx (or, in JS_AddNamedRootRT, the runtime rt). The name parameter, if present and non-null, is stored in the JSRuntime's root table entry along with rp. The name string's lifetime must last at least until the balancing call to JS_RemoveRoot. Typically name is a static string constant, identifying the source location of the call to JS_AddNamedRoot for debugging purposes. JS_DumpNamedRoots can be used to access this information from a debugger.

On success, these functions return JS_TRUE. Otherwise they report an out of memory error and return JS_FALSE.

LXR ID Search for JS_AddRoot
LXR ID Search for JS_AddNamedRoot
LXR ID Search for JS_AddNamedRootRT