Skip to content

Commit 610574b

Browse files
committed
Use node's vm module to run in clean context
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
1 parent ff3f0fd commit 610574b

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

lib/execjs/support/node_runner.js

+9-13
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,17 @@
1-
(function(program, execJS) { execJS(program) })(function(global, process, module, exports, require, console, setTimeout, setInterval, clearTimeout, clearInterval, setImmediate, clearImmediate) { #{source}
2-
}, function(program) {
1+
(function(execJS) { execJS() })(function() {
2+
var source = #{::JSON.dump(source)};
3+
source = "(function(){"+ source + "})()";
4+
35
var output, print = function(string) {
46
process.stdout.write('' + string);
57
};
68
try {
7-
var __process__ = process;
8-
delete this.process;
9-
delete this.console;
10-
delete this.setTimeout;
11-
delete this.setInterval;
12-
delete this.clearTimeout;
13-
delete this.clearInterval;
14-
delete this.setImmediate;
15-
delete this.clearImmediate;
9+
var program = function(){
10+
var vm = require('vm');
11+
var script = new vm.Script(source, {filename: "(execjs)"});
12+
return script.runInNewContext();
13+
}
1614
result = program();
17-
this.process = __process__;
1815
if (typeof result == 'undefined' && result !== null) {
1916
print('["ok"]');
2017
} else {
@@ -25,7 +22,6 @@
2522
}
2623
}
2724
} catch (err) {
28-
this.process = __process__;
2925
print(JSON.stringify(['err', '' + err, err.stack]));
3026
}
3127
});

0 commit comments

Comments
 (0)