Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

process: refactor bootstrap of worker/main thread stdio, fatalException, and script evaluation #25199

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
170 changes: 64 additions & 106 deletions lib/internal/bootstrap/node.js
Expand Up @@ -19,16 +19,30 @@

const { internalBinding, NativeModule } = loaderExports;

const exceptionHandlerState = { captureFn: null };
let getOptionValue;

function startup() {
setupTraceCategoryState();

setupProcessObject();

// Do this good and early, since it handles errors.
setupProcessFatal();
// TODO(joyeecheung): this does not have to done so early, any fatal errors
// thrown before user code execution should simply crash the process
// and we do not care about any clean up at that point. We don't care
// about emitting any events if the process crash upon bootstrap either.
{
const {
fatalException,
setUncaughtExceptionCaptureCallback,
hasUncaughtExceptionCaptureCallback
} = NativeModule.require('internal/process/execution');

process._fatalException = fatalException;
process.setUncaughtExceptionCaptureCallback =
setUncaughtExceptionCaptureCallback;
process.hasUncaughtExceptionCaptureCallback =
hasUncaughtExceptionCaptureCallback;
}

setupGlobalVariables();

Expand Down Expand Up @@ -84,20 +98,14 @@ function startup() {
process.reallyExit = rawMethods.reallyExit;
process._kill = rawMethods._kill;

const wrapped = perThreadSetup.wrapProcessMethods(
rawMethods, exceptionHandlerState
);
const wrapped = perThreadSetup.wrapProcessMethods(rawMethods);
process._rawDebug = wrapped._rawDebug;
process.hrtime = wrapped.hrtime;
process.hrtime.bigint = wrapped.hrtimeBigInt;
process.cpuUsage = wrapped.cpuUsage;
process.memoryUsage = wrapped.memoryUsage;
process.kill = wrapped.kill;
process.exit = wrapped.exit;
process.setUncaughtExceptionCaptureCallback =
wrapped.setUncaughtExceptionCaptureCallback;
process.hasUncaughtExceptionCaptureCallback =
wrapped.hasUncaughtExceptionCaptureCallback;
}

NativeModule.require('internal/process/warning').setup();
Expand Down Expand Up @@ -133,9 +141,13 @@ function startup() {
}

if (isMainThread) {
mainThreadSetup.setupStdio();
const { getStdout, getStdin, getStderr } =
NativeModule.require('internal/process/stdio').getMainThreadStdio();
setupProcessStdio(getStdout, getStdin, getStderr);
} else {
workerThreadSetup.setupStdio();
const { getStdout, getStdin, getStderr } =
workerThreadSetup.initializeWorkerStdio();
setupProcessStdio(getStdout, getStdin, getStderr);
}

if (global.__coverage__)
Expand Down Expand Up @@ -287,8 +299,14 @@ function startup() {
function startExecution() {
// This means we are in a Worker context, and any script execution
// will be directed by the worker module.
if (internalBinding('worker').getEnvMessagePort() !== undefined) {
NativeModule.require('internal/worker').setupChild(evalScript);
if (!isMainThread) {
const workerThreadSetup = NativeModule.require(
'internal/process/worker_thread_only'
);
// Set up the message port and start listening
const { workerFatalExeception } = workerThreadSetup.setup();
// Overwrite fatalException
process._fatalException = workerFatalExeception;
return;
}

Expand Down Expand Up @@ -359,7 +377,9 @@ function executeUserCode() {
addBuiltinLibsToObject
} = NativeModule.require('internal/modules/cjs/helpers');
addBuiltinLibsToObject(global);
evalScript('[eval]', wrapForBreakOnFirstLine(getOptionValue('--eval')));
const source = getOptionValue('--eval');
const { evalScript } = NativeModule.require('internal/process/execution');
evalScript('[eval]', source, process._breakFirstLine);
return;
}

Expand Down Expand Up @@ -413,7 +433,8 @@ function executeUserCode() {

// User passed '-e' or '--eval' along with `-i` or `--interactive`
if (process._eval != null) {
evalScript('[eval]', wrapForBreakOnFirstLine(process._eval));
const { evalScript } = NativeModule.require('internal/process/execution');
evalScript('[eval]', process._eval, process._breakFirstLine);
}
return;
}
Expand All @@ -435,7 +456,8 @@ function readAndExecuteStdin() {
checkScriptSyntax(code, '[stdin]');
} else {
process._eval = code;
evalScript('[stdin]', wrapForBreakOnFirstLine(process._eval));
const { evalScript } = NativeModule.require('internal/process/execution');
evalScript('[stdin]', process._eval, process._breakFirstLine);
}
});
}
Expand Down Expand Up @@ -476,6 +498,31 @@ function setupProcessObject() {
EventEmitter.call(process);
}

function setupProcessStdio(getStdout, getStdin, getStderr) {
Object.defineProperty(process, 'stdout', {
configurable: true,
enumerable: true,
get: getStdout
});

Object.defineProperty(process, 'stderr', {
configurable: true,
enumerable: true,
get: getStderr
});

Object.defineProperty(process, 'stdin', {
configurable: true,
enumerable: true,
get: getStdin
});

process.openStdin = function() {
process.stdin.resume();
return process.stdin;
};
}

function setupGlobalVariables() {
Object.defineProperty(global, Symbol.toStringTag, {
value: 'global',
Expand Down Expand Up @@ -639,95 +686,6 @@ function setupDOMException() {
registerDOMException(DOMException);
}

function noop() {}

function setupProcessFatal() {
const {
executionAsyncId,
clearDefaultTriggerAsyncId,
clearAsyncIdStack,
hasAsyncIdStack,
afterHooksExist,
emitAfter
} = NativeModule.require('internal/async_hooks');

process._fatalException = (er) => {
// It's possible that defaultTriggerAsyncId was set for a constructor
// call that threw and was never cleared. So clear it now.
clearDefaultTriggerAsyncId();

if (exceptionHandlerState.captureFn !== null) {
exceptionHandlerState.captureFn(er);
} else if (!process.emit('uncaughtException', er)) {
// If someone handled it, then great. otherwise, die in C++ land
// since that means that we'll exit the process, emit the 'exit' event.
try {
if (!process._exiting) {
process._exiting = true;
process.exitCode = 1;
process.emit('exit', 1);
}
} catch {
// Nothing to be done about it at this point.
}
try {
const { kExpandStackSymbol } = NativeModule.require('internal/util');
if (typeof er[kExpandStackSymbol] === 'function')
er[kExpandStackSymbol]();
} catch {
// Nothing to be done about it at this point.
}
return false;
}

// If we handled an error, then make sure any ticks get processed
// by ensuring that the next Immediate cycle isn't empty.
NativeModule.require('timers').setImmediate(noop);

// Emit the after() hooks now that the exception has been handled.
if (afterHooksExist()) {
do {
emitAfter(executionAsyncId());
} while (hasAsyncIdStack());
// Or completely empty the id stack.
} else {
clearAsyncIdStack();
}

return true;
};
}

function wrapForBreakOnFirstLine(source) {
if (!process._breakFirstLine)
return source;
const fn = `function() {\n\n${source};\n\n}`;
return `process.binding('inspector').callAndPauseOnStart(${fn}, {})`;
}

function evalScript(name, body) {
const CJSModule = NativeModule.require('internal/modules/cjs/loader');
const path = NativeModule.require('path');
const { tryGetCwd } = NativeModule.require('internal/util');
const cwd = tryGetCwd(path);

const module = new CJSModule(name);
module.filename = path.join(cwd, name);
module.paths = CJSModule._nodeModulePaths(cwd);
const script = `global.__filename = ${JSON.stringify(name)};\n` +
'global.exports = exports;\n' +
'global.module = module;\n' +
'global.__dirname = __dirname;\n' +
'global.require = require;\n' +
'return require("vm").runInThisContext(' +
`${JSON.stringify(body)}, { filename: ` +
`${JSON.stringify(name)}, displayErrors: true });\n`;
const result = module._compile(script, `${name}-wrapper`);
if (getOptionValue('--print')) console.log(result);
// Handle any nextTicks added in the first tick of the program.
process._tickCallback();
}

function checkScriptSyntax(source, filename) {
const CJSModule = NativeModule.require('internal/modules/cjs/loader');
const vm = NativeModule.require('vm');
Expand Down
5 changes: 2 additions & 3 deletions lib/internal/console/inspector.js
@@ -1,15 +1,14 @@
'use strict';

const path = require('path');
const CJSModule = require('internal/modules/cjs/loader');
const { makeRequireFunction } = require('internal/modules/cjs/helpers');
const { tryGetCwd } = require('internal/util');
const { tryGetCwd } = require('internal/process/execution');
const { addCommandLineAPI, consoleCall } = internalBinding('inspector');

// Wrap a console implemented by Node.js with features from the VM inspector
function addInspectorApis(consoleFromNode, consoleFromVM) {
// Setup inspector command line API.
const cwd = tryGetCwd(path);
const cwd = tryGetCwd();
const consoleAPIModule = new CJSModule('<inspector console>');
consoleAPIModule.paths =
CJSModule._nodeModulePaths(cwd).concat(CJSModule.globalPaths);
Expand Down