JS-Interpreter is a sandboxed JavaScript interpreter written in JavaScript. It allows for execution of arbitrary JavaScript code line by line. Execution is completely isolated from the main JavaScript environment. Multiple instances of the JS-Interpreter allow for multi-threaded concurrent JavaScript without the use of Web Workers.
Play with the JS-Interpreter demo.
Get the source code.
Start by including the two JavaScript source files:
<script src="acorn.js"></script> <script src="interpreter.js"></script>
Alternatively, use the compressed bundle (70kb):
<script src="acorn_interpreter.js"></script>
Next, instantiate an interpreter with the JavaScript code that needs to be parsed:
var myCode = 'var a=1; for(var i=0;i<4;i++){a*=i;} a;'; var myInterpreter = new Interpreter(myCode);
Additional JavaScript code may be added at any time (frequently used to interactively call previously defined functions):
myInterpreter.appendCode('foo();');
To run the code step by step, call the step
function
repeatedly until it returns false:
function nextStep() { if (myInterpreter.step()) { window.setTimeout(nextStep, 0); } } nextStep();
Alternatively, if the code is known to be safe from infinite loops, it may
be executed to completion by calling the run
function once:
myInterpreter.run();
In cases where the code encounters asynchronous API calls (see below),
run
will return true if it is blocked and needs to be reexecuted
at a later time.
Similar to the eval
function, the result of the last
statement executed is available in myInterpreter.value
:
var myInterpreter = new Interpreter('6 * 7'); myInterpreter.run(); alert(myInterpreter.value);
Additionally, API calls may be added to the interpreter during creation.
Here is the addition of alert()
and a url
variable:
var myCode = 'alert(url);'; var initFunc = function(interpreter, scope) { interpreter.setProperty(scope, 'url', String(location)); var wrapper = function(text) { return alert(text); }; interpreter.setProperty(scope, 'alert', interpreter.createNativeFunction(wrapper)); }; var myInterpreter = new Interpreter(myCode, initFunc);
See the JSON demo for an example of
exchanging JSON between the browser and the interpreter.
For more complicated examples, see the initGlobalScope
function
which creates APIs for Math, Array, Function, and other globals.
Asynchronous API functions may wrapped so that they appear to be
synchronous to interpreter. For example, a getXhr(url)
function
that returns the contents of an XMLHttpRequest could be defined in
initFunc
like this:
var wrapper = function(href, callback) { var req = new XMLHttpRequest(); req.open('GET', href, true); req.onreadystatechange = function() { if (req.readyState == 4 && req.status == 200) { callback(req.responseText); } }; req.send(null); }; interpreter.setProperty(scope, 'getXhr', interpreter.createAsyncFunction(wrapper));
This snippet uses createAsyncFunction
in the same way that
createNativeFunction
was used earlier. The difference is that
the wrapped asynchronous function's return value is ignored. Instead, an
extra callback function is passed in when the wrapper is called. When the
wrapper is ready to return, it calls the callback function with the value it
wishes to return. From the point of view of the code running inside the
JS-Interpreter, a function call was made and the result was returned
immediately.
For a working example, see the async demo.
A unique feature of the JS-Interpreter is its ability to pause execution, serialize the current state, then resume the execution at that point at a later time. Loops, variables, closures, and all other state is preserved.
Uses of this feature include continuously executing programs that survive a server reboot, loading a stack image that has been computed up to a certain point, forking execution, or rolling back to a stored state.
One drawback is that the serialized format is not human-readable, and it is also not guaranteed that future versions of the JS-Interpreter will be able to parse the serialization from older versions. Another drawback is that the serialization format is rather large; it has a 60 kb overhead due to the standard polyfills.
For a working example, see the serialization demo.
JavaScript is single-threaded, but the JS-Interpreter allows one to run multiple threads at the same time. Creating two or more completely independent threads that run separately from each other is trivial: just create two or more instances of the Interpreter, each with its own code, and alternate calling each interpreter's step function. They may communicate indirectly with each other through any external APIs that are provided.
A slightly more complex case is where two or more threads should share the
same global scope. To implement this, 1) create one JS-Interpreter, 2) create
a separate list of stacks, 3) assign the .scope
property of the
root node of each stack to the interpreter's .global
property,
4) then assign the desired stack to the interpreter's stateStack
property before calling step
.
For a working example, see the thread demo.
A common use-case of the JS-Interpreter is to sandbox potentially hostile code. The interpreter is secure by default: it does not use blacklists to prevent dangerous actions, instead it creates its own virtual machine with no external APIs except as provided by the developer. To date not one security bug has been reported.
Infinite loops are handled by calling the step
function
a maximum number of times, or by calling step
indefinitely many
times but using a setTimeout between each call to ensure other tasks have a
chance to execute.
Memory bombs (e.g. var x='X'; while(1) x=x+x;
) can be detected
by periodically serializing the interpereter into a JSON string, and aborting
execution if the string length is too long.
The version of JavaScript implemented by the interpreter has a few differences from that which executes in a browser:
let
or
Set
aren't implemented. Feel free to fork the project if you need more than ES5.The only dependency is Acorn, a beautifully written JavaScript parser by Marijn Haverbeke. It is included in the JS-Interpreter package.
The limiting factor for browser support is the use of
Object.create(null)
to create hash objects in both Acorn and JS-Interpreter.
This results in the following minimum browser requirements:
This project is not an official Google product.