All files / lib/internal/inspector _inspect.js

95.05% Statements 365/384
91.78% Branches 67/73
95.83% Functions 23/24
95.05% Lines 365/384

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 38530x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 1x 1x 1x 30x 30x 31x 31x 30x 30x 30x 30x 30x 30x 30x 30x 30x 96x 96x 1x 1x 1x 95x 95x 95x 95x 95x 96x 29x 29x 96x 31x 30x 30x 31x 31x 31x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 31x 30x 108x 108x 108x               108x 108x 108x 108x 10464x 435x 435x 435x 108x 108x 108x 30x 30x 30x 27x 27x 27x 27x 27x 27x 27x 27x 24x 24x 24x 24x 24x 24x 24x 27x 3x 3x 3x 27x 27x 27x 27x 27x 108x 27x 27x 3204x 3204x 3204x 3204x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 25x 25x 25x 25x 27x 27x 30x 30x 56x 56x 56x 56x 56x 56x 56x 56x 55x 55x 55x 55x 55x 55x 56x 56x 30x 30x 63x 63x 30x 30x 30x 63x 30x 30x 34x 34x 34x 33x 33x 33x 33x 37x 37x 37x 37x 32x 32x 32x 37x 5x 5x 5x 37x 1x 1x 34x 30x 30x 217x     217x 217x 217x 217x 30x 30x 217x 217x 217x 30x 30x 30x 72x 72x 72x 72x 72x 72x 72x     72x 72x 72x 72x 72x 72x 72x 72x 26x 26x 72x 72x 72x 72x 72x 72x     72x 30x 30x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 2x 2x 2x 2x 2x 28x 4x 4x 4x 4x 26x 22x 2x 2x 2x 2x 2x 1x 1x 1x 1x     1x 1x 1x 27x 27x 27x 27x 28x 30x 29x 29x 29x 29x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 28x 28x 28x 28x 28x 1x         1x 1x 1x 1x 1x 1x 28x 28x 29x 30x  
/*
 * 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(aduh95): remove restricted syntax errors
/* eslint-disable no-restricted-syntax */
 
'use strict';
 
const {
  ArrayPrototypeConcat,
  ArrayPrototypeForEach,
  ArrayPrototypeJoin,
  ArrayPrototypeMap,
  ArrayPrototypePop,
  ArrayPrototypeShift,
  ArrayPrototypeSlice,
  Error,
  FunctionPrototypeBind,
  Number,
  Promise,
  PromisePrototypeCatch,
  PromisePrototypeThen,
  PromiseResolve,
  Proxy,
  RegExpPrototypeSymbolMatch,
  RegExpPrototypeSymbolSplit,
  RegExpPrototypeTest,
  StringPrototypeEndsWith,
  StringPrototypeSplit,
} = primordials;
 
const { spawn } = require('child_process');
const { EventEmitter } = require('events');
const net = require('net');
const util = require('util');
const {
  setInterval,
  setTimeout,
} = require('timers/promises');
const {
  AbortController,
} = require('internal/abort_controller');
 
// TODO(aduh95): remove console calls
const console = require('internal/console/global');
 
const { 0: InspectClient, 1: createRepl } =
    [
      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';
  }
}
 
async function portIsFree(host, port, timeout = 9999) {
  if (port === 0) return; // Binding to a random port.
 
  const retryDelay = 150;
  const ac = new AbortController();
  const { signal } = ac;
 
  setTimeout(timeout).then(() => ac.abort());
 
  const asyncIterator = setInterval(retryDelay);
  while (true) {
    await asyncIterator.next();
    if (signal.aborted) {
      throw new StartupError(
        `Timeout (${timeout}) waiting for ${host}:${port} to be free`);
    }
    const error = await new Promise((resolve) => {
      const socket = net.connect(port, host);
      socket.on('error', resolve);
      socket.on('connect', resolve);
    });
    if (error?.code === 'ECONNREFUSED') {
      return;
    }
  }
}
 
const debugRegex = /Debugger listening on ws:\/\/\[?(.+?)\]?:(\d+)\//;
async function runScript(script, scriptArgs, inspectHost, inspectPort,
                         childPrint) {
  await portIsFree(inspectHost, inspectPort);
  const args = ArrayPrototypeConcat(
    [`--inspect-brk=${inspectPort}`, script],
    scriptArgs);
  const child = spawn(process.execPath, args);
  child.stdout.setEncoding('utf8');
  child.stderr.setEncoding('utf8');
  child.stdout.on('data', (chunk) => childPrint(chunk, 'stdout'));
  child.stderr.on('data', (chunk) => childPrint(chunk, 'stderr'));
 
  let output = '';
  return new Promise((resolve) => {
    function waitForListenHint(text) {
      output += text;
      const debug = RegExpPrototypeSymbolMatch(debugRegex, output);
      if (debug) {
        const host = debug[1];
        const port = Number(debug[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 = (then, _catch) => {
    // TODO: potentially fetch the protocol and pretty-print it here.
    const descriptor = {
      [util.inspect.custom](depth, { stylize }) {
        return stylize(`[Agent ${domain}]`, 'special');
      },
    };
    return PromisePrototypeThen(PromiseResolve(descriptor), then, _catch);
  };
 
  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 = FunctionPrototypeBind(
        runScript, null,
        options.script,
        options.scriptArgs,
        options.host,
        options.port,
        FunctionPrototypeBind(this.childPrint, this));
    } else {
      this._runScript =
          () => PromiseResolve([null, options.port, options.host]);
    }
 
    this.client = new InspectClient();
 
    this.domainNames = ['Debugger', 'HeapProfiler', 'Profiler', 'Runtime'];
    ArrayPrototypeForEach(this.domainNames, (domain) => {
      this[domain] = createAgentProxy(domain, this.client);
    });
    this.handleDebugEvent = (fullName, params) => {
      const { 0: domain, 1: name } = StringPrototypeSplit(fullName, '.');
      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());
    const exitCodeZero = () => process.exit(0);
    process.once('SIGTERM', exitCodeZero);
    process.once('SIGHUP', exitCodeZero);
 
    PromisePrototypeCatch(PromisePrototypeThen(this.run(), async () => {
      const repl = await startRepl();
      this.repl = repl;
      this.repl.on('exit', exitCodeZero);
      this.paused = false;
    }), (error) => process.nextTick(() => { throw error; }));
  }
 
  suspendReplWhile(fn) {
    if (this.repl) {
      this.repl.pause();
    }
    this.stdin.pause();
    this.paused = true;
    return PromisePrototypeCatch(PromisePrototypeThen(new Promise((resolve) => {
      resolve(fn());
    }), () => {
      this.paused = false;
      if (this.repl) {
        this.repl.resume();
        this.repl.displayPrompt();
      }
      this.stdin.resume();
    }), (error) => process.nextTick(() => { throw error; }));
  }
 
  killChild() {
    this.client.reset();
    if (this.child) {
      this.child.kill();
      this.child = null;
    }
  }
 
  async run() {
    this.killChild();
 
    const { 0: child, 1: port, 2: host } = await this._runScript();
    this.child = child;
 
    this.print(`connecting to ${host}:${port} ..`, false);
    for (let attempt = 0; attempt < 5; attempt++) {
      debuglog('connection attempt #%d', attempt);
      this.stdout.write('.');
      try {
        await this.client.connect(port, host);
        debuglog('connection established');
        this.stdout.write(' ok\n');
        return;
      } catch (error) {
        debuglog('connect failed', error);
        await setTimeout(1000);
      }
    }
    this.stdout.write(' failed to connect, please retry\n');
    process.exit(1);
  }
 
  clearLine() {
    if (this.stdout.isTTY) {
      this.stdout.cursorTo(0);
      this.stdout.clearLine(1);
    } else {
      this.stdout.write('\b');
    }
  }
 
  print(text, appendNewline = false) {
    this.clearLine();
    this.stdout.write(appendNewline ? `${text}\n` : text);
  }
 
  #stdioBuffers = { stdout: '', stderr: '' };
  childPrint(text, which) {
    const lines = RegExpPrototypeSymbolSplit(
      /\r\n|\r|\n/g,
      this.#stdioBuffers[which] + text);
 
    this.#stdioBuffers[which] = '';
 
    if (lines[lines.length - 1] !== '') {
      this.#stdioBuffers[which] = ArrayPrototypePop(lines);
    }
 
    const textToPrint = ArrayPrototypeJoin(
      ArrayPrototypeMap(lines, (chunk) => `< ${chunk}`),
      '\n');
 
    if (lines.length) {
      this.print(textToPrint, true);
      if (!this.paused) {
        this.repl.displayPrompt(true);
      }
    }
 
    if (StringPrototypeEndsWith(
      textToPrint,
      'Waiting for the debugger to disconnect...\n'
    )) {
      this.killChild();
    }
  }
}
 
function parseArgv(args) {
  const target = ArrayPrototypeShift(args);
  let host = '127.0.0.1';
  let port = 9229;
  let isRemote = false;
  let script = target;
  let scriptArgs = args;
 
  const hostMatch = RegExpPrototypeSymbolMatch(/^([^:]+):(\d+)$/, target);
  const portMatch = RegExpPrototypeSymbolMatch(/^--port=(\d+)$/, target);
 
  if (hostMatch) {
    // Connecting to remote debugger
    host = hostMatch[1];
    port = Number(hostMatch[2]);
    isRemote = true;
    script = null;
  } else if (portMatch) {
    // Start on custom port
    port = Number(portMatch[1]);
    script = args[0];
    scriptArgs = ArrayPrototypeSlice(args, 1);
  } else if (args.length === 1 && RegExpPrototypeTest(/^\d+$/, args[0]) &&
             target === '-p') {
    // Start debugger against a given pid
    const pid = Number(args[0]);
    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 = ArrayPrototypeSlice(process.argv, 2),
                      stdin = process.stdin,
                      stdout = process.stdout) {
  if (argv.length < 1) {
    const invokedAs = `${process.argv0} ${process.argv[1]}`;
 
    console.error(`Usage: ${invokedAs} script.js`);
    console.error(`       ${invokedAs} <host>:<port>`);
    console.error(`       ${invokedAs} --port=<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;