Skip to content

Commit

Permalink
inspector: Allow require in Runtime.evaluate
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Krems authored and TimothyGu committed Aug 6, 2017
1 parent e96ca62 commit 812e351
Show file tree
Hide file tree
Showing 4 changed files with 168 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/internal/bootstrap_node.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@
return console;
}
});
setupInspectorCommandLineAPI();
}

function installInspectorConsole(globalConsole) {
Expand Down Expand Up @@ -310,6 +311,24 @@
return wrappedConsole;
}

function setupInspectorCommandLineAPI() {
const inspector = process.binding('inspector');
const addCommandLineAPIMethod = inspector.addCommandLineAPIMethod;
if (!addCommandLineAPIMethod) return;

const Module = NativeModule.require('module');
const path = NativeModule.require('path');
const cwd = tryGetCwd(path);

const consoleAPIModule = new Module('[consoleAPI]');
consoleAPIModule.filename = path.join(cwd, consoleAPIModule.id);
consoleAPIModule.paths = Module._nodeModulePaths(cwd);

addCommandLineAPIMethod('require', function require(request) {
return consoleAPIModule.require(request);
});
}

function setupProcessFatal() {
const async_wrap = process.binding('async_wrap');
// Arrays containing hook flags and ids for async_hook calls.
Expand Down
1 change: 1 addition & 0 deletions src/env.h
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ namespace node {
V(context, v8::Context) \
V(domain_array, v8::Array) \
V(domains_stack_array, v8::Array) \
V(inspector_console_api_object, v8::Object) \
V(jsstream_constructor_template, v8::FunctionTemplate) \
V(module_load_list_array, v8::Array) \
V(pbkdf2_constructor_template, v8::ObjectTemplate) \
Expand Down
31 changes: 31 additions & 0 deletions src/inspector_agent.cc
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,20 @@ class NodeInspectorClient : public V8InspectorClient {
return channel_.get();
}

void installAdditionalCommandLineAPI(v8::Local<v8::Context> context,
v8::Local<v8::Object> target) {
v8::Local<v8::Object> console_api = env_->inspector_console_api_object();

v8::Local<v8::Array> properties =
console_api->GetOwnPropertyNames(context).ToLocalChecked();
for (uint32_t i = 0; i < properties->Length(); ++i) {
v8::Local<v8::Value> key = properties->Get(context, i).ToLocalChecked();
target->Set(context,
key,
console_api->Get(context, key).ToLocalChecked()).FromJust();
}
}

void startRepeatingTimer(double interval_s,
TimerCallback callback,
void* data) override {
Expand Down Expand Up @@ -682,6 +696,20 @@ bool Agent::StartIoThread(bool wait_for_connect) {
return true;
}

static void AddCommandLineAPIMethod(
const v8::FunctionCallbackInfo<v8::Value>& info) {
auto env = Environment::GetCurrent(info);
v8::Local<v8::Context> context = env->context();

if (info.Length() != 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
return env->ThrowTypeError("inspector.addCommandLineAPIMethod takes "
"exactly 2 arguments: a string and a function.");
}

v8::Local<v8::Object> console_api = env->inspector_console_api_object();
console_api->Set(context, info[0], info[1]).FromJust();
}

void Agent::Stop() {
if (io_ != nullptr) {
io_->Stop();
Expand Down Expand Up @@ -784,8 +812,11 @@ void Url(const FunctionCallbackInfo<Value>& args) {
void Agent::InitInspector(Local<Object> target, Local<Value> unused,
Local<Context> context, void* priv) {
Environment* env = Environment::GetCurrent(context);
env->set_inspector_console_api_object(Object::New(env->isolate()));

Agent* agent = env->inspector_agent();
env->SetMethod(target, "consoleCall", InspectorConsoleCall);
env->SetMethod(target, "addCommandLineAPIMethod", AddCommandLineAPIMethod);
if (agent->debug_options_.wait_for_connect())
env->SetMethod(target, "callAndPauseOnStart", CallAndPauseOnStart);
env->SetMethod(target, "connect", ConnectJSBindingsSession);
Expand Down
117 changes: 117 additions & 0 deletions test/inspector/test-inspector.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,122 @@ function testI18NCharacters(session) {
]);
}

function testCommandLineAPI(session) {
const testModulePath = require.resolve('../fixtures/empty.js');
const testModuleStr = JSON.stringify(testModulePath);
const printModulePath = require.resolve('../fixtures/printA.js');
const printModuleStr = JSON.stringify(printModulePath);
session.sendInspectorCommands([
[ // we can use `require` outside of a callframe with require in scope
{
'method': 'Runtime.evaluate', 'params': {
'expression': 'typeof require("fs").readFile === "function"',
'includeCommandLineAPI': true
}
}, (message) => assert.strictEqual(true, message['result']['value'])
],
[ // the global require does not have require.cache
{
'method': 'Runtime.evaluate', 'params': {
'expression': 'require.cache === undefined',
'includeCommandLineAPI': true
}
}, (message) => assert.strictEqual(true, message['result']['value'])
],
[ // the `require` in the module shadows the command line API's `require`
{
'method': 'Debugger.evaluateOnCallFrame', 'params': {
'callFrameId': '{"ordinal":0,"injectedScriptId":1}',
'expression': 'typeof require.cache',
'includeCommandLineAPI': true
}
}, (message) => assert.strictEqual('object', message['result']['value'])
],
[ // `require` twice returns the same value
{
'method': 'Runtime.evaluate', 'params': {
// 1. We require the same module twice
// 2. We mutate the exports so we can compare it later on
'expression': `
Object.assign(
require(${testModuleStr}),
{ old: 'yes' }
) === require(${testModuleStr})`,
'includeCommandLineAPI': true
}
}, (message) => assert.strictEqual(true, message['result']['value'])
],
[ // after require the module appears in require.cache
{
'method': 'Debugger.evaluateOnCallFrame', 'params': {
'callFrameId': '{"ordinal":0,"injectedScriptId":1}',
'expression': `require.cache[${testModuleStr}].exports`,
'generatePreview': true,
'includeCommandLineAPI': true
}
}, (message) => {
const { properties } = message.result.preview;
assert.strictEqual('old', properties[0].name);
assert.strictEqual('yes', properties[0].value);
}
],
[ // remove module from require.cache
{
'method': 'Debugger.evaluateOnCallFrame', 'params': {
'callFrameId': '{"ordinal":0,"injectedScriptId":1}',
'expression': `delete require.cache[${testModuleStr}]`,
'includeCommandLineAPI': true
}
},
],
[ // require again, should get fresh (empty) exports
{
'method': 'Runtime.evaluate', 'params': {
'callFrameId': '{"ordinal":0,"injectedScriptId":1}',
'expression': `require(${testModuleStr})`,
'generatePreview': true,
'includeCommandLineAPI': true
}
}, (message) => {
const { properties } = message.result.preview;
assert.strictEqual(0, properties.length);
}
],
[ // require 2nd module, exports an empty object
{
'method': 'Runtime.evaluate', 'params': {
// 'callFrameId': '{"ordinal":0,"injectedScriptId":1}',
'expression': `require(${printModuleStr})`,
'generatePreview': true,
'includeCommandLineAPI': true
}
}, (message) => {
const { properties } = message.result.preview;
assert.strictEqual(0, properties.length);
}
],
[ // both modules end up with the same module.parent
{
'method': 'Debugger.evaluateOnCallFrame', 'params': {
'callFrameId': '{"ordinal":0,"injectedScriptId":1}',
'expression': `({
parentsEqual:
require.cache[${testModuleStr}].parent ===
require.cache[${printModuleStr}].parent,
parentId: require.cache[${testModuleStr}].parent.id,
})`,
'generatePreview': true,
'includeCommandLineAPI': true
}
}, (message) => {
const { properties } = message.result.preview;
assert.strictEqual('[consoleAPI]', properties[1].value);
assert.strictEqual('true', properties[0].value);
}
],
]);
}

function testWaitsForFrontendDisconnect(session, harness) {
console.log('[test]', 'Verify node waits for the frontend to disconnect');
session.sendInspectorCommands({ 'method': 'Debugger.resume' })
Expand All @@ -231,6 +347,7 @@ function runTests(harness) {
testSetBreakpointAndResume,
testInspectScope,
testI18NCharacters,
testCommandLineAPI,
testWaitsForFrontendDisconnect
]).expectShutDown(55);
}
Expand Down

0 comments on commit 812e351

Please sign in to comment.