Skip to content

Commit 3340cb9

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 3340cb9

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed

lib/execjs/support/node_runner.js

+7-13
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,15 @@
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 = "(function(){"+ #{::JSON.dump(source)} + "})()";
33
var output, print = function(string) {
44
process.stdout.write('' + string);
55
};
66
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;
7+
var program = function(){
8+
var vm = require('vm');
9+
var context = vm.createContext();
10+
return vm.runInNewContext(source, context, {filename: "(execjs)"});
11+
}
1612
result = program();
17-
this.process = __process__;
1813
if (typeof result == 'undefined' && result !== null) {
1914
print('["ok"]');
2015
} else {
@@ -25,7 +20,6 @@
2520
}
2621
}
2722
} catch (err) {
28-
this.process = __process__;
2923
print(JSON.stringify(['err', '' + err, err.stack]));
3024
}
3125
});

0 commit comments

Comments
 (0)