summaryrefslogtreecommitdiff
path: root/lib/internal/bootstrap/node.js
blob: 071b68903d56d0394780bf2d0d9276fcad7947c2 (plain)
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// Hello, and welcome to hacking node.js!
//
// This file is invoked by node::LoadEnvironment in src/node.cc, and is
// responsible for bootstrapping the node.js core. As special caution is given
// to the performance of the startup process, many dependencies are invoked
// lazily.
//
// Before this file is run, lib/internal/bootstrap/loaders.js gets run first
// to bootstrap the internal binding and module loaders, including
// process.binding(), process._linkedBinding(), internalBinding() and
// NativeModule. And then { internalBinding, NativeModule } will be passed
// into this bootstrapper to bootstrap Node.js core.
'use strict';

// This file is compiled as if it's wrapped in a function with arguments
// passed by node::LoadEnvironment()
/* global process, loaderExports, isMainThread, ownsProcessState */

const { internalBinding, NativeModule } = loaderExports;

const { getOptionValue } = NativeModule.require('internal/options');
const config = internalBinding('config');

setupTraceCategoryState();

setupProcessObject();

// 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();

// Bootstrappers for all threads, including worker threads and main thread
const perThreadSetup = NativeModule.require('internal/process/per_thread');
// Bootstrappers for the main thread only
let mainThreadSetup;
// Bootstrappers for the worker threads only
let workerThreadSetup;
if (ownsProcessState) {
  mainThreadSetup = NativeModule.require(
    'internal/process/main_thread_only'
  );
} else {
  workerThreadSetup = NativeModule.require(
    'internal/process/worker_thread_only'
  );
}

// process.config is serialized config.gypi
process.config = JSON.parse(internalBinding('native_module').config);

const rawMethods = internalBinding('process_methods');
// Set up methods and events on the process object for the main thread
if (isMainThread) {
  // This depends on process being an event emitter
  mainThreadSetup.setupSignalHandlers(internalBinding);

  process.abort = rawMethods.abort;
  const wrapped = mainThreadSetup.wrapProcessMethods(rawMethods);
  process.umask = wrapped.umask;
  process.chdir = wrapped.chdir;

  // TODO(joyeecheung): deprecate and remove these underscore methods
  process._debugProcess = rawMethods._debugProcess;
  process._debugEnd = rawMethods._debugEnd;
  process._startProfilerIdleNotifier =
    rawMethods._startProfilerIdleNotifier;
  process._stopProfilerIdleNotifier = rawMethods._stopProfilerIdleNotifier;
} else {
  const wrapped = workerThreadSetup.wrapProcessMethods(rawMethods);

  process.abort = workerThreadSetup.unavailable('process.abort()');
  process.chdir = workerThreadSetup.unavailable('process.chdir()');
  process.umask = wrapped.umask;
}

// Set up methods on the process object for all threads
{
  process.cwd = rawMethods.cwd;
  process.dlopen = rawMethods.dlopen;
  process.uptime = rawMethods.uptime;

  // TODO(joyeecheung): either remove them or make them public
  process._getActiveRequests = rawMethods._getActiveRequests;
  process._getActiveHandles = rawMethods._getActiveHandles;

  // TODO(joyeecheung): remove these
  process.reallyExit = rawMethods.reallyExit;
  process._kill = rawMethods._kill;

  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;
}

const {
  onWarning,
  emitWarning
} = NativeModule.require('internal/process/warning');
if (!process.noProcessWarnings && process.env.NODE_NO_WARNINGS !== '1') {
  process.on('warning', onWarning);
}
process.emitWarning = emitWarning;

const {
  nextTick,
  runNextTicks
} = NativeModule.require('internal/process/next_tick').setup();

process.nextTick = nextTick;
// Used to emulate a tick manually in the JS land.
// A better name for this function would be `runNextTicks` but
// it has been exposed to the process object so we keep this legacy name
// TODO(joyeecheung): either remove it or make it public
process._tickCallback = runNextTicks;

const credentials = internalBinding('credentials');
if (credentials.implementsPosixCredentials) {
  process.getuid = credentials.getuid;
  process.geteuid = credentials.geteuid;
  process.getgid = credentials.getgid;
  process.getegid = credentials.getegid;
  process.getgroups = credentials.getgroups;

  if (ownsProcessState) {
    const wrapped = mainThreadSetup.wrapPosixCredentialSetters(credentials);
    process.initgroups = wrapped.initgroups;
    process.setgroups = wrapped.setgroups;
    process.setegid = wrapped.setegid;
    process.seteuid = wrapped.seteuid;
    process.setgid = wrapped.setgid;
    process.setuid = wrapped.setuid;
  } else {
    process.initgroups =
      workerThreadSetup.unavailable('process.initgroups()');
    process.setgroups = workerThreadSetup.unavailable('process.setgroups()');
    process.setegid = workerThreadSetup.unavailable('process.setegid()');
    process.seteuid = workerThreadSetup.unavailable('process.seteuid()');
    process.setgid = workerThreadSetup.unavailable('process.setgid()');
    process.setuid = workerThreadSetup.unavailable('process.setuid()');
  }
}

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

if (config.hasInspector) {
  const {
    enable,
    disable
  } = NativeModule.require('internal/inspector_async_hook');
  internalBinding('inspector').registerAsyncHook(enable, disable);
}

// If the process is spawned with env NODE_CHANNEL_FD, it's probably
// spawned by our child_process module, then initialize IPC.
// This attaches some internal event listeners and creates:
// process.send(), process.channel, process.connected,
// process.disconnect()
if (process.env.NODE_CHANNEL_FD) {
  if (ownsProcessState) {
    mainThreadSetup.setupChildProcessIpcChannel();
  } else {
    Object.defineProperty(process, 'channel', {
      enumerable: false,
      get: workerThreadSetup.unavailable('process.channel')
    });

    Object.defineProperty(process, 'connected', {
      enumerable: false,
      get: workerThreadSetup.unavailable('process.connected')
    });

    process.send = workerThreadSetup.unavailable('process.send()');
    process.disconnect =
      workerThreadSetup.unavailable('process.disconnect()');
  }
}

const browserGlobals = !process._noBrowserGlobals;
if (browserGlobals) {
  setupGlobalTimeouts();
  setupGlobalConsole();
  setupGlobalURL();
  setupGlobalEncoding();
  setupQueueMicrotask();
}

setupDOMException();

// On OpenBSD process.execPath will be relative unless we
// get the full path before process.execPath is used.
if (process.platform === 'openbsd') {
  const { realpathSync } = NativeModule.require('fs');
  process.execPath = realpathSync.native(process.execPath);
}

Object.defineProperty(process, 'argv0', {
  enumerable: true,
  configurable: false,
  value: process.argv[0]
});
process.argv[0] = process.execPath;

const { deprecate } = NativeModule.require('internal/util');
{
  // Install legacy getters on the `util` binding for typechecking.
  // TODO(addaleax): Turn into a full runtime deprecation.
  const pendingDeprecation = getOptionValue('--pending-deprecation');
  const utilBinding = internalBinding('util');
  const types = NativeModule.require('internal/util/types');
  for (const name of [
    'isArrayBuffer', 'isArrayBufferView', 'isAsyncFunction',
    'isDataView', 'isDate', 'isExternal', 'isMap', 'isMapIterator',
    'isNativeError', 'isPromise', 'isRegExp', 'isSet', 'isSetIterator',
    'isTypedArray', 'isUint8Array', 'isAnyArrayBuffer'
  ]) {
    utilBinding[name] = pendingDeprecation ?
      deprecate(types[name],
                'Accessing native typechecking bindings of Node ' +
                'directly is deprecated. ' +
                `Please use \`util.types.${name}\` instead.`,
                'DEP0103') :
      types[name];
  }
}

// process.allowedNodeEnvironmentFlags
Object.defineProperty(process, 'allowedNodeEnvironmentFlags', {
  get() {
    const flags = perThreadSetup.buildAllowedFlags();
    process.allowedNodeEnvironmentFlags = flags;
    return process.allowedNodeEnvironmentFlags;
  },
  // If the user tries to set this to another value, override
  // this completely to that value.
  set(value) {
    Object.defineProperty(this, 'allowedNodeEnvironmentFlags', {
      value,
      configurable: true,
      enumerable: true,
      writable: true
    });
  },
  enumerable: true,
  configurable: true
});
// process.assert
process.assert = deprecate(
  perThreadSetup.assert,
  'process.assert() is deprecated. Please use the `assert` module instead.',
  'DEP0100');

// TODO(joyeecheung): this property has not been well-maintained, should we
// deprecate it in favor of a better API?
const { isDebugBuild, hasOpenSSL, hasInspector } = config;
Object.defineProperty(process, 'features', {
  enumerable: true,
  writable: false,
  configurable: false,
  value: {
    inspector: hasInspector,
    debug: isDebugBuild,
    uv: true,
    ipv6: true,  // TODO(bnoordhuis) ping libuv
    tls_alpn: hasOpenSSL,
    tls_sni: hasOpenSSL,
    tls_ocsp: hasOpenSSL,
    tls: hasOpenSSL
  }
});

// User-facing NODE_V8_COVERAGE environment variable that writes
// ScriptCoverage to a specified file.
if (process.env.NODE_V8_COVERAGE) {
  const originalReallyExit = process.reallyExit;
  const cwd = NativeModule.require('internal/process/execution').tryGetCwd();
  const { resolve } = NativeModule.require('path');
  // Resolve the coverage directory to an absolute path, and
  // overwrite process.env so that the original path gets passed
  // to child processes even when they switch cwd.
  const coverageDirectory = resolve(cwd, process.env.NODE_V8_COVERAGE);
  process.env.NODE_V8_COVERAGE = coverageDirectory;
  const {
    writeCoverage,
    setCoverageDirectory
  } = NativeModule.require('internal/coverage-gen/with_profiler');
  setCoverageDirectory(coverageDirectory);
  process.on('exit', writeCoverage);
  process.reallyExit = (code) => {
    writeCoverage();
    originalReallyExit(code);
  };
}

if (getOptionValue('--experimental-report')) {
  const {
    config,
    handleSignal,
    report,
    syncConfig
  } = NativeModule.require('internal/process/report');
  process.report = report;
  // Download the CLI / ENV config into JS land.
  syncConfig(config, false);
  if (config.events.includes('signal')) {
    process.on(config.signal, handleSignal);
  }
}

function setupTraceCategoryState() {
  const {
    traceCategoryState,
    setTraceCategoryStateUpdateHandler
  } = internalBinding('trace_events');
  const kCategoryAsyncHooks = 0;
  let traceEventsAsyncHook;

  function toggleTraceCategoryState() {
    // Dynamically enable/disable the traceEventsAsyncHook
    const asyncHooksEnabled = !!traceCategoryState[kCategoryAsyncHooks];

    if (asyncHooksEnabled) {
      // Lazy load internal/trace_events_async_hooks only if the async_hooks
      // trace event category is enabled.
      if (!traceEventsAsyncHook) {
        traceEventsAsyncHook =
          NativeModule.require('internal/trace_events_async_hooks');
      }
      traceEventsAsyncHook.enable();
    } else if (traceEventsAsyncHook) {
      traceEventsAsyncHook.disable();
    }
  }

  toggleTraceCategoryState();
  setTraceCategoryStateUpdateHandler(toggleTraceCategoryState);
}

function setupProcessObject() {
  const EventEmitter = NativeModule.require('events');
  const origProcProto = Object.getPrototypeOf(process);
  Object.setPrototypeOf(origProcProto, EventEmitter.prototype);
  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',
    writable: false,
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(global, 'process', {
    value: process,
    enumerable: false,
    writable: true,
    configurable: true
  });
  const util = NativeModule.require('util');

  function makeGetter(name) {
    return util.deprecate(function() {
      return this;
    }, `'${name}' is deprecated, use 'global'`, 'DEP0016');
  }

  function makeSetter(name) {
    return util.deprecate(function(value) {
      Object.defineProperty(this, name, {
        configurable: true,
        writable: true,
        enumerable: true,
        value: value
      });
    }, `'${name}' is deprecated, use 'global'`, 'DEP0016');
  }

  Object.defineProperties(global, {
    GLOBAL: {
      configurable: true,
      get: makeGetter('GLOBAL'),
      set: makeSetter('GLOBAL')
    },
    root: {
      configurable: true,
      get: makeGetter('root'),
      set: makeSetter('root')
    }
  });

  const { Buffer } = NativeModule.require('buffer');
  const bufferBinding = internalBinding('buffer');

  // Only after this point can C++ use Buffer::New()
  bufferBinding.setBufferPrototype(Buffer.prototype);
  delete bufferBinding.setBufferPrototype;
  delete bufferBinding.zeroFill;

  Object.defineProperty(global, 'Buffer', {
    value: Buffer,
    enumerable: false,
    writable: true,
    configurable: true
  });

  process.domain = null;
  process._exiting = false;
}

function setupGlobalTimeouts() {
  const timers = NativeModule.require('timers');
  global.clearImmediate = timers.clearImmediate;
  global.clearInterval = timers.clearInterval;
  global.clearTimeout = timers.clearTimeout;
  global.setImmediate = timers.setImmediate;
  global.setInterval = timers.setInterval;
  global.setTimeout = timers.setTimeout;
}

function setupGlobalConsole() {
  const consoleFromVM = global.console;
  const consoleFromNode =
    NativeModule.require('internal/console/global');
  // Override global console from the one provided by the VM
  // to the one implemented by Node.js
  Object.defineProperty(global, 'console', {
    configurable: true,
    enumerable: false,
    value: consoleFromNode,
    writable: true
  });

  if (config.hasInspector) {
    const inspector = NativeModule.require('internal/util/inspector');
    // This will be exposed by `require('inspector').console` later.
    inspector.consoleFromVM = consoleFromVM;
    // TODO(joyeecheung): postpone this until the first time inspector
    // is activated.
    inspector.wrapConsole(consoleFromNode, consoleFromVM);
    const { setConsoleExtensionInstaller } = internalBinding('inspector');
    // Setup inspector command line API.
    setConsoleExtensionInstaller(inspector.installConsoleExtensions);
  }
}

function setupGlobalURL() {
  const { URL, URLSearchParams } = NativeModule.require('internal/url');
  Object.defineProperties(global, {
    URL: {
      value: URL,
      writable: true,
      configurable: true,
      enumerable: false
    },
    URLSearchParams: {
      value: URLSearchParams,
      writable: true,
      configurable: true,
      enumerable: false
    }
  });
}

function setupGlobalEncoding() {
  const { TextEncoder, TextDecoder } = NativeModule.require('util');
  Object.defineProperties(global, {
    TextEncoder: {
      value: TextEncoder,
      writable: true,
      configurable: true,
      enumerable: false
    },
    TextDecoder: {
      value: TextDecoder,
      writable: true,
      configurable: true,
      enumerable: false
    }
  });
}

function setupQueueMicrotask() {
  Object.defineProperty(global, 'queueMicrotask', {
    get() {
      process.emitWarning('queueMicrotask() is experimental.',
                          'ExperimentalWarning');
      const { queueMicrotask } =
        NativeModule.require('internal/queue_microtask');

      Object.defineProperty(global, 'queueMicrotask', {
        value: queueMicrotask,
        writable: true,
        enumerable: false,
        configurable: true,
      });
      return queueMicrotask;
    },
    set(v) {
      Object.defineProperty(global, 'queueMicrotask', {
        value: v,
        writable: true,
        enumerable: false,
        configurable: true,
      });
    },
    enumerable: false,
    configurable: true,
  });
}

function setupDOMException() {
  // Registers the constructor with C++.
  const DOMException = NativeModule.require('internal/domexception');
  const { registerDOMException } = internalBinding('messaging');
  registerDOMException(DOMException);
}