Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
196 changes: 195 additions & 1 deletion lib/internal/debugger/inspect_helpers.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
'use strict';

const {
ArrayPrototypePop,
ArrayPrototypePush,
ArrayPrototypePushApply,
MapPrototypeGet,
Number,
Promise,
PromiseWithResolvers,
RegExpPrototypeExec,
RegExpPrototypeSymbolReplace,
SafePromiseRace,
StringPrototypeEndsWith,
StringPrototypeIndexOf,
StringPrototypeSlice,
StringPrototypeStartsWith,
} = primordials;

const { spawn } = require('child_process');
Expand All @@ -18,12 +27,24 @@ const {
AbortController,
} = require('internal/abort_controller');

const { ERR_DEBUGGER_STARTUP_ERROR } = require('internal/errors').codes;
const {
ERR_DEBUGGER_ERROR,
ERR_DEBUGGER_STARTUP_ERROR,
} = require('internal/errors').codes;
const {
exitCodes: {
kInvalidCommandLineArgument,
},
} = internalBinding('errors');
const {
types: {
kBoolean,
kNoOp,
kV8Option,
},
} = internalBinding('options');

const { getCLIOptionsInfo } = require('internal/options');

const debugRegex = /Debugger listening on ws:\/\/\[?(.+?)\]?:(\d+)\//;

Expand Down Expand Up @@ -61,6 +82,176 @@ function ensureTrailingNewline(text) {
return StringPrototypeEndsWith(text, '\n') ? text : `${text}\n`;
}

// Mirror OptionsParser::Parse() far enough to find the child script. Options
// before it must not undo the inspector setup added by launchChildProcess().
function validateChildArgs(childArgs) {
const { options, aliases } = getCLIOptionsInfo();
const syntheticArgs = [];
let breakFirstLine = true;
let childArgIndex = 0;
let inspectorEnabled = true;

function peekArg() {
return syntheticArgs.length > 0 ?
syntheticArgs[syntheticArgs.length - 1] :
childArgs[childArgIndex];
}

function shiftArg() {
return syntheticArgs.length > 0 ?
ArrayPrototypePop(syntheticArgs) :
childArgs[childArgIndex++];
}

while (true) {
const nextArg = peekArg();
if (nextArg === undefined || nextArg.length <= 1 || nextArg[0] !== '-') {
break;
}

const isSynthetic = syntheticArgs.length > 0;
const arg = shiftArg();
if (arg === '--') { break; }
if (!isSynthetic &&
(arg === '--experimental-config-file' ||
arg === '--experimental-default-config-file')) {
// ConfigReader rewrites these to an inline default path before parsing.
continue;
}
if (!isSynthetic &&
StringPrototypeStartsWith(
arg, '--experimental-default-config-file=')) {
// ConfigReader rejects this form before parsing the remaining options.
return;
}

const equalsIndex = arg[1] === '-' ? StringPrototypeIndexOf(arg, '=') : -1;
let name = equalsIndex === -1 ? arg : StringPrototypeSlice(arg, 0, equalsIndex);
if (name.length > 2) {
name = `${StringPrototypeSlice(name, 0, 2)}${
RegExpPrototypeSymbolReplace(/_/g, StringPrototypeSlice(name, 2), '-')}`;
}

let isNegation = false;
if (StringPrototypeStartsWith(name, '--no-')) {
name = `--${StringPrototypeSlice(name, 5)}`;
isNegation = true;
}

while (true) {
let expansion = MapPrototypeGet(aliases, name);
if (expansion === undefined && equalsIndex !== -1) {
expansion = MapPrototypeGet(aliases, `${name}=`);
}
const aliasArg = peekArg();
if (expansion === undefined &&
aliasArg !== undefined &&
aliasArg.length > 0 &&
aliasArg[0] !== '-') {
expansion = MapPrototypeGet(aliases, `${name} <arg>`);
}
if (expansion === undefined) { break; }

const previousName = name;
// process.allowedNodeEnvironmentFlags may remove a self-recursive
// first entry from the cached alias metadata. Preserve the native
// parser's synthetic option terminator in that case.
if (expansion[0] === '--') {
for (let i = expansion.length - 1; i >= 0; i--) {
ArrayPrototypePush(syntheticArgs, expansion[i]);
}
break;
}
name = expansion[0];
for (let i = expansion.length - 1; i > 0; i--) {
ArrayPrototypePush(syntheticArgs, expansion[i]);
}
if (name === previousName) { break; }
}

const info = MapPrototypeGet(options, name);
if (info === undefined) { continue; }
if (isNegation && info.type !== kBoolean && info.type !== kV8Option) {
return;
}
if (info.type === kBoolean || info.type === kNoOp || info.type === kV8Option) {
if (name === '--inspect') {
inspectorEnabled = !isNegation;
} else if (name === '--inspect-brk') {
breakFirstLine = !isNegation;
if (!isNegation) { inspectorEnabled = true; }
} else if (!isNegation &&
(name === '--inspect-wait' ||
name === '--inspect-brk-node')) {
inspectorEnabled = true;
}
continue;
}

if (equalsIndex !== -1) {
if (equalsIndex === arg.length - 1) { return; }
continue;
}

const value = peekArg();
if (value === undefined || (value.length > 0 && value[0] === '-')) {
return;
}
shiftArg();
}

if (!inspectorEnabled) {
throw new ERR_DEBUGGER_STARTUP_ERROR(
'--no-inspect is incompatible with node inspect before the child script');
}
if (!breakFirstLine) {
throw new ERR_DEBUGGER_STARTUP_ERROR(
'--no-inspect-brk is incompatible with node inspect before the child script');
}
}

async function waitForDebugger(
client,
callMethod = (method) => client.callMethod(method),
) {
const {
promise: waitingPromise,
resolve: resolveWaiting,
} = PromiseWithResolvers();
const {
promise: closedPromise,
reject: rejectClosed,
} = PromiseWithResolvers();
const onWaiting = () => resolveWaiting();
const onClose = () => {
rejectClosed(new ERR_DEBUGGER_ERROR(
'Debugger session ended while waiting for target startup'));
};

// The inspector can accept a connection before the target reaches its
// startup wait. Enabling NodeRuntime makes that state observable whether
// the target was already waiting or starts waiting later.
client.once('NodeRuntime.waitingForDebugger', onWaiting);
client.once('close', onClose);
try {
await SafePromiseRace([
callMethod('NodeRuntime.enable'),
closedPromise,
]);
await SafePromiseRace([
waitingPromise,
closedPromise,
]);
await SafePromiseRace([
callMethod('NodeRuntime.disable'),
closedPromise,
]);
} finally {
client.removeListener('NodeRuntime.waitingForDebugger', onWaiting);
client.removeListener('close', onClose);
}
}

function writeInspectUsageAndExit(invokedAs, message, exitCode) {
const code = exitCode ?? (message ? kInvalidCommandLineArgument : 0);
const out = code === 0 ? process.stdout : process.stderr;
Expand Down Expand Up @@ -141,6 +332,8 @@ probe output schema.

async function launchChildProcess(childArgs, inspectHost, inspectPort,
childOutput, options = { __proto__: null }) {
validateChildArgs(childArgs);

if (!options.skipPortPreflight) {
await portIsFree(inspectHost, inspectPort);
}
Expand Down Expand Up @@ -189,5 +382,6 @@ async function launchChildProcess(childArgs, inspectHost, inspectPort,
module.exports = {
ensureTrailingNewline,
launchChildProcess,
waitForDebugger,
writeInspectUsageAndExit,
};
12 changes: 12 additions & 0 deletions lib/internal/debugger/inspect_probe.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const InspectClient = require('internal/debugger/inspect_client');
const {
ensureTrailingNewline,
launchChildProcess,
waitForDebugger,
} = require('internal/debugger/inspect_helpers');

const { ERR_DEBUGGER_STARTUP_ERROR } = require('internal/errors').codes;
Expand Down Expand Up @@ -1044,6 +1045,17 @@ class ProbeInspectorSession {
this.connected = true;

try {
try {
await waitForDebugger(
this.client,
(method) => this.callCdp(method),
);
} catch (err) {
// A close event may have completed the structured report while the
// readiness helper was rejecting its disconnect race.
if (this.finished) { throw kInspectorFailedSentinel; }
throw err;
}
await this.callCdp('Runtime.enable');
await this.callCdp('Debugger.enable');
await this.bindBreakpoints();
Expand Down
7 changes: 6 additions & 1 deletion lib/internal/debugger/inspect_repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ const { fileURLToPath } = require('internal/url');
const { customInspectSymbol, SideEffectFreeRegExpPrototypeSymbolReplace } = require('internal/util');
const { inspect: utilInspect } = require('internal/util/inspect');
const { isObjectLiteral } = require('internal/repl/utils');
const { waitForDebugger } = require('internal/debugger/inspect_helpers');
const debuglog = require('internal/util/debuglog').debuglog('inspect');

const SHORTCUTS = {
Expand Down Expand Up @@ -1204,9 +1205,13 @@ function createRepl(inspector) {
}

async function initAfterStart() {
const waitForDebuggerOnStart = !!inspector.options?.script;
waitForInitialBreakRender =
!!inspector.options?.script &&
waitForDebuggerOnStart &&
process.env.NODE_INSPECT_RESUME_ON_START !== '1';
if (waitForDebuggerOnStart) {
await waitForDebugger(inspector.client);
}
await Runtime.enable();
await Profiler.enable();
await Profiler.setSamplingInterval({ interval: 100 });
Expand Down
21 changes: 18 additions & 3 deletions lib/internal/streams/iter/broadcast.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,17 +116,32 @@ class BroadcastImpl {

push(...args) {
const { transforms, options } = parsePullArgs(args);
const signal = options?.signal;
validateAbortSignal(signal, 'options.signal');

// Avoid registering a consumer that the pre-aborted pipeline will never
// read or detach.
if (signal?.aborted) {
return {
__proto__: null,
// eslint-disable-next-line require-yield
async *[SymbolAsyncIterator]() {
throw signal.reason;
},
};
}

const rawConsumer = this.#createRawConsumer();

// When transforms are present, delegate to pull() which creates its
// own internal AbortController that follows the external signal.
// When no transforms, return rawConsumer directly (controller elided
// per PULL-02 optimization -- no transforms means no signal recipient).
if (transforms.length > 0 || options?.signal) {
if (transforms.length > 0 || signal) {
const pullArgs = [...transforms];
if (options?.signal) {
if (signal) {
ArrayPrototypePush(pullArgs,
{ __proto__: null, signal: options.signal });
{ __proto__: null, signal });
}
return pullWithTransforms(rawConsumer, ...pullArgs);
}
Expand Down
24 changes: 21 additions & 3 deletions lib/internal/streams/iter/share.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,29 @@ class ShareImpl {

pull(...args) {
const { transforms, options } = parsePullArgs(args);
const signal = options?.signal;
validateAbortSignal(signal, 'options.signal');

// Avoid registering a consumer that the pre-aborted pipeline will never
// read or detach.
if (signal?.aborted) {
return {
__proto__: null,
// eslint-disable-next-line require-yield
async *[SymbolAsyncIterator]() {
throw signal.reason;
},
};
}

const rawConsumer = this.#createRawConsumer();

if (transforms.length > 0 || options?.signal) {
if (options) {
return pullWithTransforms(rawConsumer, ...transforms, options);
if (transforms.length > 0 || signal) {
if (signal) {
return pullWithTransforms(
rawConsumer,
...transforms,
{ __proto__: null, signal });
}
return pullWithTransforms(rawConsumer, ...transforms);
}
Expand Down
5 changes: 2 additions & 3 deletions lib/internal/streams/iter/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const { isArrayBufferView, isAnyArrayBuffer } = require('internal/util/types');
const { kValidatedTransform } = require('internal/streams/iter/types');
const {
checkRangesOrGetDefault,
kValidateObjectAllowArray,
validateFiniteNumber,
validateObject,
} = require('internal/validators');
Expand Down Expand Up @@ -106,9 +107,7 @@ function validateDictionary(dictionary) {

function validateParams(params, maxParam, errClass) {
if (params === undefined) return;
if (typeof params !== 'object' || params === null) {
throw new ERR_INVALID_ARG_TYPE('options.params', 'Object', params);
}
validateObject(params, 'options.params', kValidateObjectAllowArray);
const keys = ObjectKeys(params);
for (let i = 0; i < keys.length; i++) {
const origKey = keys[i];
Expand Down
Loading
Loading