Skip to content

Commit

Permalink
Use node's vm module to run in clean context
Browse files Browse the repository at this point in the history
As suggested by Joshua Peek in a previous issue. Node's vm module gives
us full control over the globals passed to the context the code is run
in.

In order to do this we store our code as a JS string, wrap it in an IFFE
(to support the `return` symantics we use for all runtimes)

vm.runInNewContext is called with {filename: "(execjs)"} in order to
have the proper filename appear in backtraces. Normally this string is
inserted into backtraces via a gsub in external_runtime.rb which
replaces the filename.

See https://nodejs.org/api/vm.html
  • Loading branch information
jhawthorn committed Oct 10, 2016
1 parent ff3f0fd commit 610574b
Showing 1 changed file with 9 additions and 13 deletions.
22 changes: 9 additions & 13 deletions lib/execjs/support/node_runner.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
(function(program, execJS) { execJS(program) })(function(global, process, module, exports, require, console, setTimeout, setInterval, clearTimeout, clearInterval, setImmediate, clearImmediate) { #{source}
}, function(program) {
(function(execJS) { execJS() })(function() {
var source = #{::JSON.dump(source)};
source = "(function(){"+ source + "})()";

var output, print = function(string) {
process.stdout.write('' + string);
};
try {
var __process__ = process;
delete this.process;
delete this.console;
delete this.setTimeout;
delete this.setInterval;
delete this.clearTimeout;
delete this.clearInterval;
delete this.setImmediate;
delete this.clearImmediate;
var program = function(){
var vm = require('vm');
var script = new vm.Script(source, {filename: "(execjs)"});
return script.runInNewContext();
}
result = program();
this.process = __process__;
if (typeof result == 'undefined' && result !== null) {
print('["ok"]');
} else {
Expand All @@ -25,7 +22,6 @@
}
}
} catch (err) {
this.process = __process__;
print(JSON.stringify(['err', '' + err, err.stack]));
}
});

0 comments on commit 610574b

Please sign in to comment.