debugger: move node-inspect to internal library

node-inspect developers have agreed to move node-inspect into core
rather than vendor it as a dependency.

Refs: https://github.com/nodejs/node/discussions/36481

PR-URL: https://github.com/nodejs/node/pull/38161
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Jan Krems <jan.krems@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
This commit is contained in:
Rich Trott 2021-04-08 03:49:53 -07:00
parent dfc00ea038
commit 0ca876ac96
5 changed files with 1840 additions and 4 deletions

View File

@ -0,0 +1,369 @@
/*
* Copyright Node.js contributors. All rights reserved.
*
* 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.
*/
// TODO(trott): enable ESLint
/* eslint-disable */
'use strict';
const { spawn } = require('child_process');
const { EventEmitter } = require('events');
const net = require('net');
const util = require('util');
const runAsStandalone = typeof __dirname !== 'undefined';
const { 0: InspectClient, 1: createRepl } =
runAsStandalone ?
// This copy of node-inspect is on-disk, relative paths make sense.
[
require('./inspect_client'),
require('./inspect_repl'),
] :
// This copy of node-inspect is built into the node executable.
[
require('internal/inspector/inspect_client'),
require('internal/inspector/inspect_repl'),
];
const debuglog = util.debuglog('inspect');
class StartupError extends Error {
constructor(message) {
super(message);
this.name = 'StartupError';
}
}
function portIsFree(host, port, timeout = 9999) {
if (port === 0) return Promise.resolve(); // Binding to a random port.
const retryDelay = 150;
let didTimeOut = false;
return new Promise((resolve, reject) => {
setTimeout(() => {
didTimeOut = true;
reject(new StartupError(
`Timeout (${timeout}) waiting for ${host}:${port} to be free`));
}, timeout);
function pingPort() {
if (didTimeOut) return;
const socket = net.connect(port, host);
let didRetry = false;
function retry() {
if (!didRetry && !didTimeOut) {
didRetry = true;
setTimeout(pingPort, retryDelay);
}
}
socket.on('error', (error) => {
if (error.code === 'ECONNREFUSED') {
resolve();
} else {
retry();
}
});
socket.on('connect', () => {
socket.destroy();
retry();
});
}
pingPort();
});
}
function runScript(script, scriptArgs, inspectHost, inspectPort, childPrint) {
return portIsFree(inspectHost, inspectPort)
.then(() => {
return new Promise((resolve) => {
const needDebugBrk = process.version.match(/^v(6|7)\./);
const args = (needDebugBrk ?
['--inspect', `--debug-brk=${inspectPort}`] :
[`--inspect-brk=${inspectPort}`])
.concat([script], scriptArgs);
const child = spawn(process.execPath, args);
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', childPrint);
child.stderr.on('data', childPrint);
let output = '';
function waitForListenHint(text) {
output += text;
if (/Debugger listening on ws:\/\/\[?(.+?)\]?:(\d+)\//.test(output)) {
const host = RegExp.$1;
const port = Number.parseInt(RegExp.$2);
child.stderr.removeListener('data', waitForListenHint);
resolve([child, port, host]);
}
}
child.stderr.on('data', waitForListenHint);
});
});
}
function createAgentProxy(domain, client) {
const agent = new EventEmitter();
agent.then = (...args) => {
// TODO: potentially fetch the protocol and pretty-print it here.
const descriptor = {
[util.inspect.custom](depth, { stylize }) {
return stylize(`[Agent ${domain}]`, 'special');
},
};
return Promise.resolve(descriptor).then(...args);
};
return new Proxy(agent, {
get(target, name) {
if (name in target) return target[name];
return function callVirtualMethod(params) {
return client.callMethod(`${domain}.${name}`, params);
};
},
});
}
class NodeInspector {
constructor(options, stdin, stdout) {
this.options = options;
this.stdin = stdin;
this.stdout = stdout;
this.paused = true;
this.child = null;
if (options.script) {
this._runScript = runScript.bind(null,
options.script,
options.scriptArgs,
options.host,
options.port,
this.childPrint.bind(this));
} else {
this._runScript =
() => Promise.resolve([null, options.port, options.host]);
}
this.client = new InspectClient();
this.domainNames = ['Debugger', 'HeapProfiler', 'Profiler', 'Runtime'];
this.domainNames.forEach((domain) => {
this[domain] = createAgentProxy(domain, this.client);
});
this.handleDebugEvent = (fullName, params) => {
const { 0: domain, 1: name } = fullName.split('.');
if (domain in this) {
this[domain].emit(name, params);
}
};
this.client.on('debugEvent', this.handleDebugEvent);
const startRepl = createRepl(this);
// Handle all possible exits
process.on('exit', () => this.killChild());
process.once('SIGTERM', process.exit.bind(process, 0));
process.once('SIGHUP', process.exit.bind(process, 0));
this.run()
.then(() => startRepl())
.then((repl) => {
this.repl = repl;
this.repl.on('exit', () => {
process.exit(0);
});
this.paused = false;
})
.then(null, (error) => process.nextTick(() => { throw error; }));
}
suspendReplWhile(fn) {
if (this.repl) {
this.repl.pause();
}
this.stdin.pause();
this.paused = true;
return new Promise((resolve) => {
resolve(fn());
}).then(() => {
this.paused = false;
if (this.repl) {
this.repl.resume();
this.repl.displayPrompt();
}
this.stdin.resume();
}).then(null, (error) => process.nextTick(() => { throw error; }));
}
killChild() {
this.client.reset();
if (this.child) {
this.child.kill();
this.child = null;
}
}
run() {
this.killChild();
return this._runScript().then(({ 0: child, 1: port, 2: host }) => {
this.child = child;
let connectionAttempts = 0;
const attemptConnect = () => {
++connectionAttempts;
debuglog('connection attempt #%d', connectionAttempts);
this.stdout.write('.');
return this.client.connect(port, host)
.then(() => {
debuglog('connection established');
this.stdout.write(' ok');
}, (error) => {
debuglog('connect failed', error);
// If it's failed to connect 10 times then print failed message
if (connectionAttempts >= 10) {
this.stdout.write(' failed to connect, please retry\n');
process.exit(1);
}
return new Promise((resolve) => setTimeout(resolve, 500))
.then(attemptConnect);
});
};
this.print(`connecting to ${host}:${port} ..`, true);
return attemptConnect();
});
}
clearLine() {
if (this.stdout.isTTY) {
this.stdout.cursorTo(0);
this.stdout.clearLine(1);
} else {
this.stdout.write('\b');
}
}
print(text, oneline = false) {
this.clearLine();
this.stdout.write(oneline ? text : `${text}\n`);
}
childPrint(text) {
this.print(
text.toString()
.split(/\r\n|\r|\n/g)
.filter((chunk) => !!chunk)
.map((chunk) => `< ${chunk}`)
.join('\n')
);
if (!this.paused) {
this.repl.displayPrompt(true);
}
if (/Waiting for the debugger to disconnect\.\.\.\n$/.test(text)) {
this.killChild();
}
}
}
function parseArgv([target, ...args]) {
let host = '127.0.0.1';
let port = 9229;
let isRemote = false;
let script = target;
let scriptArgs = args;
const hostMatch = target.match(/^([^:]+):(\d+)$/);
const portMatch = target.match(/^--port=(\d+)$/);
if (hostMatch) {
// Connecting to remote debugger
host = hostMatch[1];
port = parseInt(hostMatch[2], 10);
isRemote = true;
script = null;
} else if (portMatch) {
// Start on custom port
port = parseInt(portMatch[1], 10);
script = args[0];
scriptArgs = args.slice(1);
} else if (args.length === 1 && /^\d+$/.test(args[0]) && target === '-p') {
// Start debugger against a given pid
const pid = parseInt(args[0], 10);
try {
process._debugProcess(pid);
} catch (e) {
if (e.code === 'ESRCH') {
console.error(`Target process: ${pid} doesn't exist.`);
process.exit(1);
}
throw e;
}
script = null;
isRemote = true;
}
return {
host, port, isRemote, script, scriptArgs,
};
}
function startInspect(argv = process.argv.slice(2),
stdin = process.stdin,
stdout = process.stdout) {
if (argv.length < 1) {
const invokedAs = runAsStandalone ?
'node-inspect' :
`${process.argv0} ${process.argv[1]}`;
console.error(`Usage: ${invokedAs} script.js`);
console.error(` ${invokedAs} <host>:<port>`);
console.error(` ${invokedAs} -p <pid>`);
process.exit(1);
}
const options = parseArgv(argv);
const inspector = new NodeInspector(options, stdin, stdout);
stdin.resume();
function handleUnexpectedError(e) {
if (!(e instanceof StartupError)) {
console.error('There was an internal error in Node.js. ' +
'Please report this bug.');
console.error(e.message);
console.error(e.stack);
} else {
console.error(e.message);
}
if (inspector.child) inspector.child.kill();
process.exit(1);
}
process.on('uncaughtException', handleUnexpectedError);
}
exports.start = startInspect;

View File

@ -0,0 +1,355 @@
/*
* Copyright Node.js contributors. All rights reserved.
*
* 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.
*/
// TODO(trott): enable ESLint
/* eslint-disable */
'use strict';
const Buffer = require('buffer').Buffer;
const { EventEmitter } = require('events');
const http = require('http');
const URL = require('url');
const util = require('util');
const debuglog = util.debuglog('inspect');
const kOpCodeText = 0x1;
const kOpCodeClose = 0x8;
const kFinalBit = 0x80;
const kReserved1Bit = 0x40;
const kReserved2Bit = 0x20;
const kReserved3Bit = 0x10;
const kOpCodeMask = 0xF;
const kMaskBit = 0x80;
const kPayloadLengthMask = 0x7F;
const kMaxSingleBytePayloadLength = 125;
const kMaxTwoBytePayloadLength = 0xFFFF;
const kTwoBytePayloadLengthField = 126;
const kEightBytePayloadLengthField = 127;
const kMaskingKeyWidthInBytes = 4;
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
function unpackError({ code, message, data }) {
const err = new Error(`${message} - ${data}`);
err.code = code;
Error.captureStackTrace(err, unpackError);
return err;
}
function encodeFrameHybi17(payload) {
var i;
const dataLength = payload.length;
let singleByteLength;
let additionalLength;
if (dataLength > kMaxTwoBytePayloadLength) {
singleByteLength = kEightBytePayloadLengthField;
additionalLength = Buffer.alloc(8);
let remaining = dataLength;
for (i = 0; i < 8; ++i) {
additionalLength[7 - i] = remaining & 0xFF;
remaining >>= 8;
}
} else if (dataLength > kMaxSingleBytePayloadLength) {
singleByteLength = kTwoBytePayloadLengthField;
additionalLength = Buffer.alloc(2);
additionalLength[0] = (dataLength & 0xFF00) >> 8;
additionalLength[1] = dataLength & 0xFF;
} else {
additionalLength = Buffer.alloc(0);
singleByteLength = dataLength;
}
const header = Buffer.from([
kFinalBit | kOpCodeText,
kMaskBit | singleByteLength,
]);
const mask = Buffer.alloc(4);
const masked = Buffer.alloc(dataLength);
for (i = 0; i < dataLength; ++i) {
masked[i] = payload[i] ^ mask[i % kMaskingKeyWidthInBytes];
}
return Buffer.concat([header, additionalLength, mask, masked]);
}
function decodeFrameHybi17(data) {
const dataAvailable = data.length;
const notComplete = { closed: false, payload: null, rest: data };
let payloadOffset = 2;
if ((dataAvailable - payloadOffset) < 0) return notComplete;
const firstByte = data[0];
const secondByte = data[1];
const final = (firstByte & kFinalBit) !== 0;
const reserved1 = (firstByte & kReserved1Bit) !== 0;
const reserved2 = (firstByte & kReserved2Bit) !== 0;
const reserved3 = (firstByte & kReserved3Bit) !== 0;
const opCode = firstByte & kOpCodeMask;
const masked = (secondByte & kMaskBit) !== 0;
const compressed = reserved1;
if (compressed) {
throw new Error('Compressed frames not supported');
}
if (!final || reserved2 || reserved3) {
throw new Error('Only compression extension is supported');
}
if (masked) {
throw new Error('Masked server frame - not supported');
}
let closed = false;
switch (opCode) {
case kOpCodeClose:
closed = true;
break;
case kOpCodeText:
break;
default:
throw new Error(`Unsupported op code ${opCode}`);
}
let payloadLength = secondByte & kPayloadLengthMask;
switch (payloadLength) {
case kTwoBytePayloadLengthField:
payloadOffset += 2;
payloadLength = (data[2] << 8) + data[3];
break;
case kEightBytePayloadLengthField:
payloadOffset += 8;
payloadLength = 0;
for (var i = 0; i < 8; ++i) {
payloadLength <<= 8;
payloadLength |= data[2 + i];
}
break;
default:
// Nothing. We already have the right size.
}
if ((dataAvailable - payloadOffset - payloadLength) < 0) return notComplete;
const payloadEnd = payloadOffset + payloadLength;
return {
payload: data.slice(payloadOffset, payloadEnd),
rest: data.slice(payloadEnd),
closed,
};
}
class Client extends EventEmitter {
constructor() {
super();
this.handleChunk = this._handleChunk.bind(this);
this._port = undefined;
this._host = undefined;
this.reset();
}
_handleChunk(chunk) {
this._unprocessed = Buffer.concat([this._unprocessed, chunk]);
while (this._unprocessed.length > 2) {
const {
closed,
payload: payloadBuffer,
rest
} = decodeFrameHybi17(this._unprocessed);
this._unprocessed = rest;
if (closed) {
this.reset();
return;
}
if (payloadBuffer === null || payloadBuffer.length === 0) break;
const payloadStr = payloadBuffer.toString();
debuglog('< %s', payloadStr);
const lastChar = payloadStr[payloadStr.length - 1];
if (payloadStr[0] !== '{' || lastChar !== '}') {
throw new Error(`Payload does not look like JSON: ${payloadStr}`);
}
let payload;
try {
payload = JSON.parse(payloadStr);
} catch (parseError) {
parseError.string = payloadStr;
throw parseError;
}
const { id, method, params, result, error } = payload;
if (id) {
const handler = this._pending[id];
if (handler) {
delete this._pending[id];
handler(error, result);
}
} else if (method) {
this.emit('debugEvent', method, params);
this.emit(method, params);
} else {
throw new Error(`Unsupported response: ${payloadStr}`);
}
}
}
reset() {
if (this._http) {
this._http.destroy();
}
this._http = null;
this._lastId = 0;
this._socket = null;
this._pending = {};
this._unprocessed = Buffer.alloc(0);
}
callMethod(method, params) {
return new Promise((resolve, reject) => {
if (!this._socket) {
reject(new Error('Use `run` to start the app again.'));
return;
}
const data = { id: ++this._lastId, method, params };
this._pending[data.id] = (error, result) => {
if (error) reject(unpackError(error));
else resolve(isEmpty(result) ? undefined : result);
};
const json = JSON.stringify(data);
debuglog('> %s', json);
this._socket.write(encodeFrameHybi17(Buffer.from(json)));
});
}
_fetchJSON(urlPath) {
return new Promise((resolve, reject) => {
const httpReq = http.get({
host: this._host,
port: this._port,
path: urlPath,
});
const chunks = [];
function onResponse(httpRes) {
function parseChunks() {
const resBody = Buffer.concat(chunks).toString();
if (httpRes.statusCode !== 200) {
reject(new Error(`Unexpected ${httpRes.statusCode}: ${resBody}`));
return;
}
try {
resolve(JSON.parse(resBody));
} catch (parseError) {
reject(new Error(`Response didn't contain JSON: ${resBody}`));
}
}
httpRes.on('error', reject);
httpRes.on('data', (chunk) => chunks.push(chunk));
httpRes.on('end', parseChunks);
}
httpReq.on('error', reject);
httpReq.on('response', onResponse);
});
}
connect(port, host) {
this._port = port;
this._host = host;
return this._discoverWebsocketPath()
.then((urlPath) => this._connectWebsocket(urlPath));
}
_discoverWebsocketPath() {
return this._fetchJSON('/json')
.then(({ 0: { webSocketDebuggerUrl } }) =>
URL.parse(webSocketDebuggerUrl).path);
}
_connectWebsocket(urlPath) {
this.reset();
const key1 = require('crypto').randomBytes(16).toString('base64');
debuglog('request websocket', key1);
const httpReq = this._http = http.request({
host: this._host,
port: this._port,
path: urlPath,
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket',
'Sec-WebSocket-Key': key1,
'Sec-WebSocket-Version': '13',
},
});
httpReq.on('error', (e) => {
this.emit('error', e);
});
httpReq.on('response', (httpRes) => {
if (httpRes.statusCode >= 400) {
process.stderr.write(`Unexpected HTTP code: ${httpRes.statusCode}\n`);
httpRes.pipe(process.stderr);
} else {
httpRes.pipe(process.stderr);
}
});
const handshakeListener = (res, socket) => {
// TODO: we *could* validate res.headers[sec-websocket-accept]
debuglog('websocket upgrade');
this._socket = socket;
socket.on('data', this.handleChunk);
socket.on('close', () => {
this.emit('close');
});
this.emit('ready');
};
return new Promise((resolve, reject) => {
this.once('error', reject);
this.once('ready', resolve);
httpReq.on('upgrade', handshakeListener);
httpReq.end();
});
}
}
module.exports = Client;

File diff suppressed because it is too large Load Diff

View File

@ -13,5 +13,5 @@ markBootstrapComplete();
// Start the debugger agent.
process.nextTick(() => {
require('internal/deps/node-inspect/lib/_inspect').start();
require('internal/inspector/_inspect').start();
});

View File

@ -166,6 +166,9 @@
'lib/internal/heap_utils.js',
'lib/internal/histogram.js',
'lib/internal/idna.js',
'lib/internal/inspector/_inspect.js',
'lib/internal/inspector/inspect_client.js',
'lib/internal/inspector/inspect_repl.js',
'lib/internal/inspector_async_hook.js',
'lib/internal/js_stream_socket.js',
'lib/internal/legacy/processbinding.js',
@ -277,9 +280,6 @@
'deps/v8/tools/tickprocessor.mjs',
'deps/v8/tools/sourcemap.mjs',
'deps/v8/tools/tickprocessor-driver.mjs',
'deps/node-inspect/lib/_inspect.js',
'deps/node-inspect/lib/internal/inspect_client.js',
'deps/node-inspect/lib/internal/inspect_repl.js',
'deps/acorn/acorn/dist/acorn.js',
'deps/acorn/acorn-walk/dist/walk.js',
'deps/acorn-plugins/acorn-class-fields/index.js',