Spidermonkey And Garbage Collection
I am embedding Spidermonkey in my C++ application. I need to implementing some custom Javascript functions in native C++ that pass around a jsval. I need to guard the jsval agains
Solution 1:
Referring to SpiderMonkey 17 and up
jsval
or any other GC thing should be protected if there is a chance of triggering GC while the GC thing is in use. This is required even if jsval
refers to an already protected storage. SpiderMonkey's GC is a moving GC.
Use RootedValue
to protect stack based jsval
and Heap<JS::Value>
for heap based jsval
(jsval
is the same as JS::Value
). Use Handle<JS::Value>
and MutableHandle<JS::Value>
for arguments of functions.
Here is an excerpt from RootingAPI comments:
* 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.
** 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.
Post a Comment for "Spidermonkey And Garbage Collection"