microsoft / Chakra-Samples

Repository for Chakra JavaScript engine related samples.
MIT License
216 stars 84 forks source link

Example of calling ChakraCore from Spidermonkey using js-ctypes #55

Open cosinusoidally opened 7 years ago

cosinusoidally commented 7 years ago

In a similar vein to https://github.com/Microsoft/Chakra-Samples/tree/master/ChakraCore%20Samples/Hello%20World/Python I've put together an example that calls ChakraCore from Mozilla's JavaScript VM Spidermonkey using their builtin js-ctypes library. Code is here: https://gist.github.com/cosinusoidally/964164ea173d49ff700a6baeeea0ade6 (plus instructions on how to run the example code using one of Mozilla's prebuilt Spidermonkey shell binaries). As I mentioned in https://github.com/Microsoft/Chakra-Samples/pull/34 I believe there are safety issues regarding JsValueRefs and the conservative stack scanning part of ChakraCore's garbage collector. In my example code I have addressed this issue by calling a C helper function that allocates variables on the C stack and then calls back in to Spidermonkey (which then uses the addresses of those stack allocated variables to hold the JsValueRefs).

Calling the example with:

js -e "unsafe=false;run_gc=true" example.js

should print the string "Hello world!" (generated by ChakraCore).

Calling the example with:

js -e "unsafe=true;run_gc=true" example.js

will segfault as unsafe=true causes the JsValueRefs to be allocated on the Spidermonkey heap (which then get collected when ChakraCore's JsCollectGarbage is called).

Using run_gc=true will cause JsCollectGarbage to be called at various points throughout the program. This simulates the worst case scenario where the GC happens to run when we are attempting to use JsValueRefs that have no reference on the C stack and a reference count of zero (ie JsValueRefs that are garbage).

If this is of interest I could work my example code into a pull requests.