title: Spidermonkey and Garbage Collection
body: <p>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 against accidental garbage collection.  Is it proper for me to do this:</p>
  
  <p>(1) In an init routine:</p>
  
  <pre><code>static jsval vp; // a STATIC variable, value unknown
  JSBool init((JSContext *cx, uintN argc, jsval *vp) {
     JS_AddValueRoot(cx,  &amp;vp);
  }
  </code></pre>
  
  <p>(2) In one c++ function implementing the Javascript function setter():</p>
  
  <pre><code>JSBool setter(JSContext *cx, uintN argc, jsval *vp) {
     ...
    vp=...;// set to some JSObject and hopefully makes any previous JSObject available for gc
  
  }
  </code></pre>
  
  <p>(3) In a second C++ function call within the same compilation unit implementing the Javascript function getter():</p>
  
  <pre><code>JSBool getter(JSContext *cx, uintN argc, jsval *vp) {
    jsval somethingelse = vp; //directly retrieve the static value stored by setter()
    ....
  }
  </code></pre>
  
  <p>My Javascript script uses the function calls like this:</p>
  
  <pre><code>init();
  setter(...);
  some_other_function_call_that_causes_gc();
  getter();
  setter(...);
  some_other_function_call_that_causes_gc();
  getter();
  ....
  some_other_function_call_that_causes_gc();
  setter(...);
  some_other_function_call_that_causes_gc();
  getter();
  </code></pre>
  
  <p>Note that I never call JS_RemoveRoot() since the <em>static jsval vp</em> is a permanent storage for my jsval passed between 2 function calls.  And, I keep setting new values into the gc rooted static variable vp in my setter(), assuming any previouis JSObject stored in jsval will be available for garbage collection.</p>
  
  <p>Are these proper ways to create gc rooted temporary variables that can be passed across function call? In particular, is the way my setter() replacing a previous JSObject a proper way to make an existing JSObject available for gc (i.e. no memory-leak/crash).</p>
  
  <p>EDIT: The reason why I believe Garbage collection is an issue is that:</p>
  
  <p><a href="https://developer.mozilla.org/En/SpiderMonkey/JSAPI_User_Guide" rel="nofollow">https://developer.mozilla.org/En/SpiderMonkey/JSAPI_User_Guide</a></p>
  
  <p>Under Section JSAPI Concepts, Javascript Values:</p>
  
  <blockquote>
    <p>a jsval by itself does not protect its referent from the garbage
    collector</p>
  </blockquote>
  
  <p><a href="https://developer.mozilla.org/en/SpiderMonkey_Garbage_Collection_Tips" rel="nofollow">https://developer.mozilla.org/en/SpiderMonkey_Garbage_Collection_Tips</a></p>
  
  <p>Example 3 says "<strong>Root as you go</strong>" and shows how a jsval must be assigned to a root.</p>