Browse Source

vm: update API to use options argument

Passing a filename is still supported in place of certain options
arguments, for backward-compatibility, but timeout and display-errors
are not translated since those were undocumented.

Also managed to eliminate an extra stack trace line by not calling
through the `createScript` export.

Added a few message tests to show how `displayErrors` works.
v0.11.7-release
Domenic Denicola 12 years ago
committed by isaacs
parent
commit
fd3657610e
  1. 6
      lib/module.js
  2. 10
      lib/repl.js
  3. 50
      lib/vm.js
  4. 10
      src/node.js
  5. 105
      src/node_contextify.cc
  6. 1
      test/message/eval_messages.out
  7. 1
      test/message/stdin_messages.out
  8. 30
      test/message/vm_display_runtime_error.js
  9. 16
      test/message/vm_display_runtime_error.out
  10. 30
      test/message/vm_display_syntax_error.js
  11. 15
      test/message/vm_display_syntax_error.out
  12. 42
      test/message/vm_dont_display_runtime_error.js
  13. 17
      test/message/vm_dont_display_runtime_error.out
  14. 42
      test/message/vm_dont_display_syntax_error.js
  15. 16
      test/message/vm_dont_display_syntax_error.out
  16. 4
      test/simple/test-repl-syntax-error-handling.js
  17. 24
      test/simple/test-vm-timeout.js

6
lib/module.js

@ -412,7 +412,7 @@ Module.prototype._compile = function(content, filename) {
sandbox.global = sandbox;
sandbox.root = root;
return runInNewContext(content, sandbox, filename);
return runInNewContext(content, sandbox, { filename: filename });
}
debug('load root module');
@ -423,13 +423,13 @@ Module.prototype._compile = function(content, filename) {
global.__dirname = dirname;
global.module = self;
return runInThisContext(content, filename);
return runInThisContext(content, { filename: filename });
}
// create wrapper function
var wrapper = Module.wrap(content);
var compiledWrapper = runInThisContext(wrapper, filename);
var compiledWrapper = runInThisContext(wrapper, { filename: filename });
if (global.v8debug) {
if (!resolvedArgv) {
// we enter the repl if we're not given a filename argument.

10
lib/repl.js

@ -113,9 +113,15 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
var err, result;
try {
if (self.useGlobal) {
result = vm.runInThisContext(code, file, 0, false);
result = vm.runInThisContext(code, {
filename: file,
displayErrors: false
});
} else {
result = vm.runInContext(code, context, file, 0, false);
result = vm.runInContext(code, context, {
filename: file,
displayErrors: false
});
}
} catch (e) {
err = e;

50
lib/vm.js

@ -24,48 +24,50 @@ var Script = binding.ContextifyScript;
var util = require('util');
// The binding provides a few useful primitives:
// - ContextifyScript(code, [filename]), with methods:
// - runInThisContext()
// - runInContext(sandbox, [timeout])
// - ContextifyScript(code, { filename = "evalmachine.anonymous",
// displayErrors = true } = {})
// with methods:
// - runInThisContext({ displayErrors = true } = {})
// - runInContext(sandbox, { displayErrors = true, timeout = undefined } = {})
// - makeContext(sandbox)
// - isContext(sandbox)
// From this we build the entire documented API.
Script.prototype.runInNewContext = function(initSandbox, timeout, disp) {
var context = exports.createContext(initSandbox);
return this.runInContext(context, timeout, disp);
Script.prototype.runInNewContext = function(sandbox, options) {
var context = exports.createContext(sandbox);
return this.runInContext(context, options);
};
exports.Script = Script;
exports.createScript = function(code, filename, disp) {
return new Script(code, filename, disp);
exports.createScript = function(code, options) {
return new Script(code, options);
};
exports.createContext = function(initSandbox) {
if (util.isUndefined(initSandbox)) {
initSandbox = {};
} else if (binding.isContext(initSandbox)) {
return initSandbox;
exports.createContext = function(sandbox) {
if (util.isUndefined(sandbox)) {
sandbox = {};
} else if (binding.isContext(sandbox)) {
return sandbox;
}
binding.makeContext(initSandbox);
return initSandbox;
binding.makeContext(sandbox);
return sandbox;
};
exports.runInContext = function(code, sandbox, filename, timeout, disp) {
var script = exports.createScript(code, filename, disp);
return script.runInContext(sandbox, timeout, disp);
exports.runInContext = function(code, contextifiedSandbox, options) {
var script = new Script(code, options);
return script.runInContext(contextifiedSandbox, options);
};
exports.runInNewContext = function(code, sandbox, filename, timeout, disp) {
var script = exports.createScript(code, filename, disp);
return script.runInNewContext(sandbox, timeout, disp);
exports.runInNewContext = function(code, sandbox, options) {
var script = new Script(code, options);
return script.runInNewContext(sandbox, options);
};
exports.runInThisContext = function(code, filename, timeout, disp) {
var script = exports.createScript(code, filename, disp);
return script.runInThisContext(timeout, disp);
exports.runInThisContext = function(code, options) {
var script = new Script(code, options);
return script.runInThisContext(options);
};
exports.isContext = binding.isContext;

10
src/node.js

@ -382,8 +382,8 @@
'global.__dirname = __dirname;\n' +
'global.require = require;\n' +
'return require("vm").runInThisContext(' +
JSON.stringify(body) + ', ' +
JSON.stringify(name) + ');\n';
JSON.stringify(body) + ', { filename: ' +
JSON.stringify(name) + ' });\n';
}
var result = module._compile(script, name + '-wrapper');
if (process._print_eval) console.log(result);
@ -675,8 +675,8 @@
// node binary, so they can be loaded faster.
var ContextifyScript = process.binding('contextify').ContextifyScript;
function runInThisContext(code, filename) {
var script = new ContextifyScript(code, filename);
function runInThisContext(code, options) {
var script = new ContextifyScript(code, options);
return script.runInThisContext();
}
@ -739,7 +739,7 @@
var source = NativeModule.getSource(this.id);
source = NativeModule.wrap(source);
var fn = runInThisContext(source, this.filename);
var fn = runInThisContext(source, { filename: this.filename });
fn(this.exports, NativeModule.require, this, this.filename);
this.loaded = true;

105
src/node_contextify.cc

@ -321,7 +321,7 @@ class ContextifyScript : ObjectWrap {
}
// args: code, [filename]
// args: code, [options]
static void New(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate);
@ -331,20 +331,25 @@ class ContextifyScript : ObjectWrap {
ContextifyScript *contextify_script = new ContextifyScript();
contextify_script->Wrap(args.Holder());
TryCatch try_catch;
Local<String> code = args[0]->ToString();
Local<String> filename = GetFilenameArg(args, 1);
bool display_exception = GetDisplayArg(args, 2);
bool display_errors = GetDisplayErrorsArg(args, 1);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
return;
}
Local<Context> context = Context::GetCurrent();
Context::Scope context_scope(context);
TryCatch try_catch;
Local<Script> v8_script = Script::New(code, filename);
if (v8_script.IsEmpty()) {
if (display_exception)
if (display_errors) {
DisplayExceptionLine(try_catch.Message());
}
try_catch.ReThrow();
return;
}
@ -358,42 +363,40 @@ class ContextifyScript : ObjectWrap {
}
// args: [timeout]
// args: [options]
static void RunInThisContext(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate);
// Assemble arguments
TryCatch try_catch;
uint64_t timeout = GetTimeoutArg(args, 0);
bool display_errors = GetDisplayErrorsArg(args, 0);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
return;
}
bool display_exception = GetDisplayArg(args, 1);
// Do the eval within this context
EvalMachine(timeout, display_exception, args, try_catch);
EvalMachine(timeout, display_errors, args, try_catch);
}
// args: sandbox, [timeout]
// args: sandbox, [options]
static void RunInContext(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate);
// Assemble arguments
TryCatch try_catch;
if (!args[0]->IsObject()) {
return ThrowTypeError("sandbox argument must be an object.");
return ThrowTypeError("contextifiedSandbox argument must be an object.");
}
Local<Object> sandbox = args[0].As<Object>();
uint64_t timeout = GetTimeoutArg(args, 1);
int64_t timeout = GetTimeoutArg(args, 1);
bool display_errors = GetDisplayErrorsArg(args, 1);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
return;
}
bool display_exception = GetDisplayArg(args, 2);
// Get the context from the sandbox
Local<Context> context =
ContextifyContext::V8ContextFromContextifiedSandbox(sandbox);
@ -404,43 +407,76 @@ class ContextifyScript : ObjectWrap {
// Do the eval within the context
Context::Scope context_scope(context);
EvalMachine(timeout, display_exception, args, try_catch);
EvalMachine(timeout, display_errors, args, try_catch);
}
static int64_t GetTimeoutArg(const FunctionCallbackInfo<Value>& args,
const int i) {
if (args[i]->IsUndefined()) {
return 0;
if (args[i]->IsUndefined() || args[i]->IsString()) {
return -1;
}
if (!args[i]->IsObject()) {
ThrowTypeError("options must be an object");
return -1;
}
Local<String> key = FIXED_ONE_BYTE_STRING(node_isolate, "timeout");
Local<Value> value = args[i].As<Object>()->Get(key);
if (value->IsUndefined()) {
return -1;
}
int64_t timeout = value->IntegerValue();
int64_t timeout = args[i]->IntegerValue();
if (timeout < 0) {
if (timeout <= 0) {
ThrowRangeError("timeout must be a positive number");
return -1;
}
return timeout;
}
static bool GetDisplayArg(const FunctionCallbackInfo<Value>& args,
const int i) {
bool display_exception = true;
if (args[i]->IsBoolean())
display_exception = args[i]->BooleanValue();
static bool GetDisplayErrorsArg(const FunctionCallbackInfo<Value>& args,
const int i) {
if (args[i]->IsUndefined() || args[i]->IsString()) {
return true;
}
if (!args[i]->IsObject()) {
ThrowTypeError("options must be an object");
return false;
}
return display_exception;
Local<String> key = FIXED_ONE_BYTE_STRING(node_isolate, "displayErrors");
Local<Value> value = args[i].As<Object>()->Get(key);
return value->IsUndefined() ? true : value->BooleanValue();
}
static Local<String> GetFilenameArg(const FunctionCallbackInfo<Value>& args,
const int i) {
return !args[i]->IsUndefined()
? args[i]->ToString()
: FIXED_ONE_BYTE_STRING(node_isolate, "evalmachine.<anonymous>");
Local<String> defaultFilename =
FIXED_ONE_BYTE_STRING(node_isolate, "evalmachine.<anonymous>");
if (args[i]->IsUndefined()) {
return defaultFilename;
}
if (args[i]->IsString()) {
return args[i].As<String>();
}
if (!args[i]->IsObject()) {
ThrowTypeError("options must be an object");
return Local<String>();
}
Local<String> key = FIXED_ONE_BYTE_STRING(node_isolate, "filename");
Local<Value> value = args[i].As<Object>()->Get(key);
return value->IsUndefined() ? defaultFilename : value->ToString();
}
static void EvalMachine(const int64_t timeout,
const bool display_exception,
const bool display_errors,
const FunctionCallbackInfo<Value>& args,
TryCatch& try_catch) {
if (!ContextifyScript::InstanceOf(args.This())) {
@ -452,15 +488,9 @@ class ContextifyScript : ObjectWrap {
ObjectWrap::Unwrap<ContextifyScript>(args.This());
Local<Script> script = PersistentToLocal(node_isolate,
wrapped_script->script_);
if (script.IsEmpty()) {
if (display_exception)
DisplayExceptionLine(try_catch.Message());
try_catch.ReThrow();
return;
}
Local<Value> result;
if (timeout) {
if (timeout != -1) {
Watchdog wd(timeout);
result = script->Run();
} else {
@ -474,8 +504,9 @@ class ContextifyScript : ObjectWrap {
if (result.IsEmpty()) {
// Error occurred during execution of the script.
if (display_exception)
if (display_errors) {
DisplayExceptionLine(try_catch.Message());
}
try_catch.ReThrow();
return;
}

1
test/message/eval_messages.out

@ -4,7 +4,6 @@
with(this){__filename}
^^^^
SyntaxError: Strict mode code may not include a with statement
at Object.exports.createScript (vm.js:*)
at Object.exports.runInThisContext (vm.js:*)
at Object.<anonymous> ([eval]-wrapper:*:*)
at Module._compile (module.js:*:*)

1
test/message/stdin_messages.out

@ -4,7 +4,6 @@
with(this){__filename}
^^^^
SyntaxError: Strict mode code may not include a with statement
at Object.exports.createScript (vm.js:*)
at Object.exports.runInThisContext (vm.js:*)
at Object.<anonymous> ([stdin]-wrapper:*:*)
at Module._compile (module.js:*:*)

30
test/message/vm_display_runtime_error.js

@ -0,0 +1,30 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var common = require('../common');
var assert = require('assert');
var vm = require('vm');
console.error('beginning');
vm.runInThisContext('throw new Error("boo!")', { filename: 'test.vm' });
console.error('end');

16
test/message/vm_display_runtime_error.out

@ -0,0 +1,16 @@
beginning
test.vm:1
throw new Error("boo!")
^
Error: boo!
at test.vm:1:7
at Object.exports.runInThisContext (vm.js:*)
at Object.<anonymous> (*test*message*vm_display_runtime_error.js:*)
at Module._compile (module.js:*)
at Object.Module._extensions..js (module.js:*)
at Module.load (module.js:*)
at Function.Module._load (module.js:*)
at Function.Module.runMain (module.js:*)
at startup (node.js:*)
at node.js:*

30
test/message/vm_display_syntax_error.js

@ -0,0 +1,30 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var common = require('../common');
var assert = require('assert');
var vm = require('vm');
console.error('beginning');
vm.runInThisContext('var 5;', { filename: 'test.vm' });
console.error('end');

15
test/message/vm_display_syntax_error.out

@ -0,0 +1,15 @@
beginning
test.vm:1
var 5;
^
SyntaxError: Unexpected number
at Object.exports.runInThisContext (vm.js:*)
at Object.<anonymous> (*test*message*vm_display_syntax_error.js:*)
at Module._compile (module.js:*)
at Object.Module._extensions..js (module.js:*)
at Module.load (module.js:*)
at Function.Module._load (module.js:*)
at Function.Module.runMain (module.js:*)
at startup (node.js:*)
at node.js:*

42
test/message/vm_dont_display_runtime_error.js

@ -0,0 +1,42 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var common = require('../common');
var assert = require('assert');
var vm = require('vm');
console.error('beginning');
try {
vm.runInThisContext('throw new Error("boo!")', {
filename: 'test.vm',
displayErrors: false
});
} catch (e) {}
console.error('middle');
vm.runInThisContext('throw new Error("boo!")', {
filename: 'test.vm',
displayErrors: false
});
console.error('end');

17
test/message/vm_dont_display_runtime_error.out

@ -0,0 +1,17 @@
beginning
middle
vm.js:*
return script.runInThisContext(options);
^
Error: boo!
at test.vm:1:7
at Object.exports.runInThisContext (vm.js:*)
at Object.<anonymous> (*test*message*vm_dont_display_runtime_error.js:*)
at Module._compile (module.js:*)
at Object.Module._extensions..js (module.js:*)
at Module.load (module.js:*)
at Function.Module._load (module.js:*)
at Function.Module.runMain (module.js:*)
at startup (node.js:*)
at node.js:*

42
test/message/vm_dont_display_syntax_error.js

@ -0,0 +1,42 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var common = require('../common');
var assert = require('assert');
var vm = require('vm');
console.error('beginning');
try {
vm.runInThisContext('var 5;', {
filename: 'test.vm',
displayErrors: false
});
} catch (e) {}
console.error('middle');
vm.runInThisContext('var 5;', {
filename: 'test.vm',
displayErrors: false
});
console.error('end');

16
test/message/vm_dont_display_syntax_error.out

@ -0,0 +1,16 @@
beginning
middle
vm.js:*
var script = new Script(code, options);
^
SyntaxError: Unexpected number
at Object.exports.runInThisContext (vm.js:*)
at Object.<anonymous> (*test*message*vm_dont_display_syntax_error.js:*)
at Module._compile (module.js:*)
at Object.Module._extensions..js (module.js:*)
at Module.load (module.js:*)
at Function.Module._load (module.js:*)
at Function.Module.runMain (module.js:*)
at startup (node.js:*)
at node.js:*

4
test/simple/test-repl-syntax-error-handling.js

@ -60,10 +60,10 @@ function parent() {
function child() {
var vm = require('vm');
try {
vm.runInThisContext('haf!@##&$!@$*!@', 'blerg', 0, false);
vm.runInThisContext('haf!@##&$!@$*!@', { displayErrors: false });
} catch (er) {
var caught = true;
}
assert(caught);
vm.runInThisContext('console.log(10)', 'blerg', 0, false);
vm.runInThisContext('console.log(10)', { displayErrors: false });
}

24
test/simple/test-vm-timeout.js

@ -25,32 +25,30 @@ var vm = require('vm');
// Test 1: Timeout of 100ms executing endless loop
assert.throws(function() {
vm.runInThisContext('while(true) {}', '', 100);
vm.runInThisContext('while(true) {}', { timeout: 100 });
});
// Test 2: Timeout must be >= 0ms
assert.throws(function() {
vm.runInThisContext('', '', -1);
});
vm.runInThisContext('', { timeout: -1 });
}, RangeError);
// Test 3: Timeout of 0ms
vm.runInThisContext('', '', 0);
assert.throws(function() {
vm.runInThisContext('', { timeout: 0 });
}, RangeError);
// Test 4: Timeout of 1000ms, script finishes first
vm.runInThisContext('', '', 1000);
vm.runInThisContext('', { timeout: 1000 });
// Test 5: Nested vm timeouts, inner timeout propagates out
try {
assert.throws(function() {
var context = {
log: console.log,
runInVM: function(timeout) {
vm.runInNewContext('while(true) {}', context, '', timeout);
vm.runInNewContext('while(true) {}', context, { timeout: timeout });
}
};
vm.runInNewContext('runInVM(10)', context, '', 100);
vm.runInNewContext('runInVM(10)', context, { timeout: 100 });
throw new Error('Test 5 failed');
} catch (e) {
if (-1 === e.message.search(/Script execution timed out./)) {
throw e;
}
}
}, /Script execution timed out./);

Loading…
Cancel
Save