-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
pre_execution.js
786 lines (702 loc) Β· 24.6 KB
/
pre_execution.js
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
'use strict';
const {
ArrayPrototypeForEach,
Date,
DatePrototypeGetDate,
DatePrototypeGetFullYear,
DatePrototypeGetHours,
DatePrototypeGetMinutes,
DatePrototypeGetMonth,
DatePrototypeGetSeconds,
NumberParseInt,
ObjectDefineProperty,
ObjectFreeze,
ObjectGetOwnPropertyDescriptor,
SafeMap,
String,
StringPrototypeStartsWith,
Symbol,
SymbolAsyncDispose,
SymbolDispose,
globalThis,
} = primordials;
const {
getOptionValue,
refreshOptions,
getEmbedderOptions,
} = require('internal/options');
const { reconnectZeroFillToggle } = require('internal/buffer');
const {
exposeInterface,
exposeLazyInterfaces,
defineReplaceableLazyAttribute,
setupCoverageHooks,
} = require('internal/util');
const {
ERR_INVALID_THIS,
ERR_MANIFEST_ASSERT_INTEGRITY,
ERR_NO_CRYPTO,
ERR_MISSING_OPTION,
ERR_ACCESS_DENIED,
} = require('internal/errors').codes;
const assert = require('internal/assert');
const {
namespace: {
addSerializeCallback,
isBuildingSnapshot,
},
} = require('internal/v8/startup_snapshot');
function prepareMainThreadExecution(expandArgv1 = false, initializeModules = true) {
return prepareExecution({
expandArgv1,
initializeModules,
isMainThread: true,
});
}
function prepareWorkerThreadExecution() {
prepareExecution({
expandArgv1: false,
initializeModules: false, // Will need to initialize it after policy setup
isMainThread: false,
});
}
function prepareShadowRealmExecution() {
// Patch the process object with legacy properties and normalizations.
// Do not expand argv1 as it is not available in ShadowRealm.
patchProcessObject(false);
setupDebugEnv();
// Disable custom loaders in ShadowRealm.
setupUserModules(true);
const {
privateSymbols: {
host_defined_option_symbol,
},
} = internalBinding('util');
const {
vm_dynamic_import_default_internal,
} = internalBinding('symbols');
// For ShadowRealm.prototype.importValue(), the referrer name is
// always null, so the native ImportModuleDynamically() callback would
// always fallback to look up the host-defined option from the
// global object using host_defined_option_symbol. Using
// vm_dynamic_import_default_internal as the host-defined option
// instructs the JS-land importModuleDynamicallyCallback() to
// proxy the request to defaultImportModuleDynamically().
globalThis[host_defined_option_symbol] =
vm_dynamic_import_default_internal;
}
function prepareExecution(options) {
const { expandArgv1, initializeModules, isMainThread } = options;
refreshRuntimeOptions();
reconnectZeroFillToggle();
// Patch the process object and get the resolved main entry point.
const mainEntry = patchProcessObject(expandArgv1);
setupTraceCategoryState();
setupInspectorHooks();
setupNavigator();
setupWarningHandler();
setupUndici();
setupWebCrypto();
setupCustomEvent();
setupCodeCoverage();
setupDebugEnv();
// Process initial diagnostic reporting configuration, if present.
initializeReport();
// Load permission system API
initializePermission();
initializeSourceMapsHandlers();
initializeDeprecations();
require('internal/dns/utils').initializeDns();
setupSymbolDisposePolyfill();
if (isMainThread) {
assert(internalBinding('worker').isMainThread);
// Worker threads will get the manifest in the message handler.
const policy = readPolicyFromDisk();
if (policy) {
require('internal/process/policy')
.setup(policy.manifestSrc, policy.manifestURL);
}
// Print stack trace on `SIGINT` if option `--trace-sigint` presents.
setupStacktracePrinterOnSigint();
initializeReportSignalHandlers(); // Main-thread-only.
initializeHeapSnapshotSignalHandlers();
// 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().
setupChildProcessIpcChannel();
// If this is a worker in cluster mode, start up the communication
// channel. This needs to be done before any user code gets executed
// (including preload modules).
initializeClusterIPC();
// TODO(joyeecheung): do this for worker threads as well.
require('internal/v8/startup_snapshot').runDeserializeCallbacks();
} else {
assert(!internalBinding('worker').isMainThread);
// The setup should be called in LOAD_SCRIPT message handler.
assert(!initializeModules);
}
if (initializeModules) {
setupUserModules();
}
return mainEntry;
}
function setupSymbolDisposePolyfill() {
// TODO(MoLow): Remove this polyfill once Symbol.dispose and Symbol.asyncDispose are available in V8.
// eslint-disable-next-line node-core/prefer-primordials
if (typeof Symbol.dispose !== 'symbol') {
ObjectDefineProperty(Symbol, 'dispose', {
__proto__: null,
configurable: false,
enumerable: false,
value: SymbolDispose,
writable: false,
});
}
// eslint-disable-next-line node-core/prefer-primordials
if (typeof Symbol.asyncDispose !== 'symbol') {
ObjectDefineProperty(Symbol, 'asyncDispose', {
__proto__: null,
configurable: false,
enumerable: false,
value: SymbolAsyncDispose,
writable: false,
});
}
}
function setupUserModules(forceDefaultLoader = false) {
initializeCJSLoader();
initializeESMLoader(forceDefaultLoader);
const {
hasStartedUserCJSExecution,
hasStartedUserESMExecution,
} = require('internal/modules/helpers');
assert(!hasStartedUserCJSExecution());
assert(!hasStartedUserESMExecution());
if (getEmbedderOptions().hasEmbedderPreload) {
runEmbedderPreload();
}
// Do not enable preload modules if custom loaders are disabled.
// For example, loader workers are responsible for doing this themselves.
// And preload modules are not supported in ShadowRealm as well.
if (!forceDefaultLoader) {
loadPreloadModules();
}
// Need to be done after --require setup.
initializeFrozenIntrinsics();
}
function refreshRuntimeOptions() {
refreshOptions();
}
/**
* Patch the process object with legacy properties and normalizations.
* Replace `process.argv[0]` with `process.execPath`, preserving the original `argv[0]` value as `process.argv0`.
* Replace `process.argv[1]` with the resolved absolute file path of the entry point, if found.
* @param {boolean} expandArgv1 - Whether to replace `process.argv[1]` with the resolved absolute file path of
* the main entry point.
*/
function patchProcessObject(expandArgv1) {
const binding = internalBinding('process_methods');
binding.patchProcessObject(process);
// Since we replace process.argv[0] below, preserve the original value in case the user needs it.
ObjectDefineProperty(process, 'argv0', {
__proto__: null,
enumerable: true,
// Only set it to true during snapshot building.
configurable: isBuildingSnapshot(),
value: process.argv[0],
});
process.exitCode = undefined;
process._exiting = false;
process.argv[0] = process.execPath;
/** @type {string} */
let mainEntry;
// If requested, update process.argv[1] to replace whatever the user provided with the resolved absolute file path of
// the entry point.
if (expandArgv1 && process.argv[1] &&
!StringPrototypeStartsWith(process.argv[1], '-')) {
// Expand process.argv[1] into a full path.
const path = require('path');
try {
mainEntry = path.resolve(process.argv[1]);
process.argv[1] = mainEntry;
} catch {
// Continue regardless of error.
}
}
// We need to initialize the global console here again with process.stdout
// and friends for snapshot deserialization.
const globalConsole = require('internal/console/global');
const { initializeGlobalConsole } = require('internal/console/constructor');
initializeGlobalConsole(globalConsole);
// TODO(joyeecheung): most of these should be deprecated and removed,
// except some that we need to be able to mutate during run time.
addReadOnlyProcessAlias('_eval', '--eval');
addReadOnlyProcessAlias('_print_eval', '--print');
addReadOnlyProcessAlias('_syntax_check_only', '--check');
addReadOnlyProcessAlias('_forceRepl', '--interactive');
addReadOnlyProcessAlias('_preload_modules', '--require');
addReadOnlyProcessAlias('noDeprecation', '--no-deprecation');
addReadOnlyProcessAlias('noProcessWarnings', '--no-warnings');
addReadOnlyProcessAlias('traceProcessWarnings', '--trace-warnings');
addReadOnlyProcessAlias('throwDeprecation', '--throw-deprecation');
addReadOnlyProcessAlias('profProcess', '--prof-process');
addReadOnlyProcessAlias('traceDeprecation', '--trace-deprecation');
addReadOnlyProcessAlias('_breakFirstLine', '--inspect-brk', false);
addReadOnlyProcessAlias('_breakNodeFirstLine', '--inspect-brk-node', false);
return mainEntry;
}
function addReadOnlyProcessAlias(name, option, enumerable = true) {
const value = getOptionValue(option);
if (value) {
ObjectDefineProperty(process, name, {
__proto__: null,
writable: false,
configurable: true,
enumerable,
value,
});
}
}
function setupWarningHandler() {
const {
onWarning,
resetForSerialization,
} = require('internal/process/warning');
if (getOptionValue('--warnings') &&
process.env.NODE_NO_WARNINGS !== '1') {
process.on('warning', onWarning);
// The code above would add the listener back during deserialization,
// if applicable.
if (isBuildingSnapshot()) {
addSerializeCallback(() => {
process.removeListener('warning', onWarning);
resetForSerialization();
});
}
}
}
// https://fetch.spec.whatwg.org/
// https://websockets.spec.whatwg.org/
function setupUndici() {
if (getOptionValue('--no-experimental-fetch')) {
delete globalThis.fetch;
delete globalThis.FormData;
delete globalThis.Headers;
delete globalThis.Request;
delete globalThis.Response;
}
if (getOptionValue('--no-experimental-websocket')) {
delete globalThis.WebSocket;
}
}
// TODO(aduh95): move this to internal/bootstrap/web/* when the CLI flag is
// removed.
function setupNavigator() {
if (getEmbedderOptions().noBrowserGlobals ||
getOptionValue('--no-experimental-global-navigator')) {
return;
}
// https://html.spec.whatwg.org/multipage/system-state.html#the-navigator-object
exposeLazyInterfaces(globalThis, 'internal/navigator', ['Navigator']);
defineReplaceableLazyAttribute(globalThis, 'internal/navigator', ['navigator'], false);
}
// TODO(aduh95): move this to internal/bootstrap/web/* when the CLI flag is
// removed.
function setupWebCrypto() {
if (getEmbedderOptions().noBrowserGlobals ||
getOptionValue('--no-experimental-global-webcrypto')) {
return;
}
if (internalBinding('config').hasOpenSSL) {
defineReplaceableLazyAttribute(
globalThis,
'internal/crypto/webcrypto',
['crypto'],
false,
function cryptoThisCheck() {
if (this !== globalThis && this != null)
throw new ERR_INVALID_THIS(
'nullish or must be the global object');
},
);
exposeLazyInterfaces(
globalThis, 'internal/crypto/webcrypto',
['Crypto', 'CryptoKey', 'SubtleCrypto'],
);
} else {
ObjectDefineProperty(globalThis, 'crypto',
{ __proto__: null, ...ObjectGetOwnPropertyDescriptor({
get crypto() {
throw new ERR_NO_CRYPTO();
},
}, 'crypto') });
}
}
function setupCodeCoverage() {
// 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. Don't do anything if the
// --experimental-test-coverage flag is present, as the test runner will
// handle coverage.
if (process.env.NODE_V8_COVERAGE &&
!getOptionValue('--experimental-test-coverage')) {
process.env.NODE_V8_COVERAGE =
setupCoverageHooks(process.env.NODE_V8_COVERAGE);
}
}
// TODO(daeyeon): move this to internal/bootstrap/web/* when the CLI flag is
// removed.
function setupCustomEvent() {
if (getEmbedderOptions().noBrowserGlobals ||
getOptionValue('--no-experimental-global-customevent')) {
return;
}
const { CustomEvent } = require('internal/event_target');
exposeInterface(globalThis, 'CustomEvent', CustomEvent);
}
function setupStacktracePrinterOnSigint() {
if (!getOptionValue('--trace-sigint')) {
return;
}
const { SigintWatchdog } = require('internal/watchdog');
const watchdog = new SigintWatchdog();
watchdog.start();
}
function initializeReport() {
ObjectDefineProperty(process, 'report', {
__proto__: null,
enumerable: true,
configurable: true,
get() {
const { report } = require('internal/process/report');
return report;
},
});
}
function setupDebugEnv() {
require('internal/util/debuglog').initializeDebugEnv(process.env.NODE_DEBUG);
if (getOptionValue('--expose-internals')) {
require('internal/bootstrap/realm').BuiltinModule.exposeInternals();
}
}
// This has to be called after initializeReport() is called
function initializeReportSignalHandlers() {
if (getOptionValue('--report-on-signal')) {
const { addSignalHandler } = require('internal/process/report');
addSignalHandler();
}
}
function initializeHeapSnapshotSignalHandlers() {
const signal = getOptionValue('--heapsnapshot-signal');
const diagnosticDir = getOptionValue('--diagnostic-dir');
if (!signal)
return;
require('internal/validators').validateSignalName(signal);
const { writeHeapSnapshot } = require('v8');
function doWriteHeapSnapshot() {
const heapSnapshotFilename = getHeapSnapshotFilename(diagnosticDir);
writeHeapSnapshot(heapSnapshotFilename);
}
process.on(signal, doWriteHeapSnapshot);
// The code above would add the listener back during deserialization,
// if applicable.
if (isBuildingSnapshot()) {
addSerializeCallback(() => {
process.removeListener(signal, doWriteHeapSnapshot);
});
}
}
function setupTraceCategoryState() {
const { isTraceCategoryEnabled } = internalBinding('trace_events');
const { toggleTraceCategoryState } = require('internal/process/per_thread');
toggleTraceCategoryState(isTraceCategoryEnabled('node.async_hooks'));
}
function setupInspectorHooks() {
// If Debugger.setAsyncCallStackDepth is sent during bootstrap,
// we cannot immediately call into JS to enable the hooks, which could
// interrupt the JS execution of bootstrap. So instead we save the
// notification in the inspector agent if it's sent in the middle of
// bootstrap, and process the notification later here.
if (internalBinding('config').hasInspector) {
const {
enable,
disable,
} = require('internal/inspector_async_hook');
internalBinding('inspector').registerAsyncHook(enable, disable);
}
}
// In general deprecations are initialized wherever the APIs are implemented,
// this is used to deprecate APIs implemented in C++ where the deprecation
// utilities are not easily accessible.
function initializeDeprecations() {
const { deprecate } = require('internal/util');
const pendingDeprecation = getOptionValue('--pending-deprecation');
// DEP0103: access to `process.binding('util').isX` type checkers
// TODO(addaleax): Turn into a full runtime deprecation.
const utilBinding = internalBinding('util');
const types = 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];
}
// TODO(joyeecheung): this is a legacy property exposed to process.
// Now that we use the config binding to carry this information, remove
// it from the process. We may consider exposing it properly in
// process.features.
const { noBrowserGlobals } = internalBinding('config');
if (noBrowserGlobals) {
ObjectDefineProperty(process, '_noBrowserGlobals', {
__proto__: null,
writable: false,
enumerable: true,
configurable: true,
value: noBrowserGlobals,
});
}
if (pendingDeprecation) {
process.binding = deprecate(process.binding,
'process.binding() is deprecated. ' +
'Please use public APIs instead.', 'DEP0111');
process._tickCallback = deprecate(process._tickCallback,
'process._tickCallback() is deprecated',
'DEP0134');
}
}
function setupChildProcessIpcChannel() {
if (process.env.NODE_CHANNEL_FD) {
const assert = require('internal/assert');
const fd = NumberParseInt(process.env.NODE_CHANNEL_FD, 10);
assert(fd >= 0);
// Make sure it's not accidentally inherited by child processes.
delete process.env.NODE_CHANNEL_FD;
const serializationMode =
process.env.NODE_CHANNEL_SERIALIZATION_MODE || 'json';
delete process.env.NODE_CHANNEL_SERIALIZATION_MODE;
require('child_process')._forkChild(fd, serializationMode);
assert(process.send);
}
}
function initializeClusterIPC() {
if (process.argv[1] && process.env.NODE_UNIQUE_ID) {
const cluster = require('cluster');
cluster._setupWorker();
// Make sure it's not accidentally inherited by child processes.
delete process.env.NODE_UNIQUE_ID;
}
}
function initializePermission() {
const experimentalPermission = getOptionValue('--experimental-permission');
if (experimentalPermission) {
process.binding = function binding(_module) {
throw new ERR_ACCESS_DENIED('process.binding');
};
// Guarantee path module isn't monkey-patched to bypass permission model
ObjectFreeze(require('path'));
process.emitWarning('Permission is an experimental feature',
'ExperimentalWarning');
const { has, deny } = require('internal/process/permission');
const warnFlags = [
'--allow-addons',
'--allow-child-process',
'--allow-worker',
];
for (const flag of warnFlags) {
if (getOptionValue(flag)) {
process.emitWarning(
`The flag ${flag} must be used with extreme caution. ` +
'It could invalidate the permission model.', 'SecurityWarning');
}
}
const warnCommaFlags = [
'--allow-fs-read',
'--allow-fs-write',
];
for (const flag of warnCommaFlags) {
const value = getOptionValue(flag);
if (value.length === 1 && value[0].includes(',')) {
process.emitWarning(
`The ${flag} CLI flag has changed. ` +
'Passing a comma-separated list of paths is no longer valid. ' +
'Documentation can be found at ' +
'https://nodejs.org/api/permissions.html#file-system-permissions',
'Warning',
);
}
}
ObjectDefineProperty(process, 'permission', {
__proto__: null,
enumerable: true,
configurable: false,
value: {
has,
deny,
},
});
} else {
const availablePermissionFlags = [
'--allow-fs-read',
'--allow-fs-write',
'--allow-addons',
'--allow-child-process',
'--allow-worker',
];
ArrayPrototypeForEach(availablePermissionFlags, (flag) => {
const value = getOptionValue(flag);
if (value.length) {
throw new ERR_MISSING_OPTION('--experimental-permission');
}
});
}
}
function readPolicyFromDisk() {
const experimentalPolicy = getOptionValue('--experimental-policy');
if (experimentalPolicy) {
process.emitWarning('Policies are experimental.',
'ExperimentalWarning');
const { pathToFileURL, URL } = require('internal/url');
// URL here as it is slightly different parsing
// no bare specifiers for now
let manifestURL;
if (require('path').isAbsolute(experimentalPolicy)) {
manifestURL = pathToFileURL(experimentalPolicy);
} else {
const cwdURL = pathToFileURL(process.cwd());
cwdURL.pathname += '/';
manifestURL = new URL(experimentalPolicy, cwdURL);
}
const fs = require('fs');
const src = fs.readFileSync(manifestURL, 'utf8');
const experimentalPolicyIntegrity = getOptionValue('--policy-integrity');
if (experimentalPolicyIntegrity) {
const SRI = require('internal/policy/sri');
const { createHash, timingSafeEqual } = require('crypto');
const realIntegrities = new SafeMap();
const integrityEntries = SRI.parse(experimentalPolicyIntegrity);
let foundMatch = false;
for (let i = 0; i < integrityEntries.length; i++) {
const {
algorithm,
value: expected,
} = integrityEntries[i];
const hash = createHash(algorithm);
hash.update(src);
const digest = hash.digest();
if (digest.length === expected.length &&
timingSafeEqual(digest, expected)) {
foundMatch = true;
break;
}
realIntegrities.set(algorithm, digest.toString('base64'));
}
if (!foundMatch) {
throw new ERR_MANIFEST_ASSERT_INTEGRITY(manifestURL, realIntegrities);
}
}
return {
manifestSrc: src, manifestURL: manifestURL.href,
};
}
}
function initializeCJSLoader() {
const { initializeCJS } = require('internal/modules/cjs/loader');
initializeCJS();
}
function initializeESMLoader(forceDefaultLoader) {
const { initializeESM } = require('internal/modules/esm/utils');
initializeESM(forceDefaultLoader);
// Patch the vm module when --experimental-vm-modules is on.
// Please update the comments in vm.js when this block changes.
if (getOptionValue('--experimental-vm-modules')) {
const {
Module, SourceTextModule, SyntheticModule,
} = require('internal/vm/module');
const vm = require('vm');
vm.Module = Module;
vm.SourceTextModule = SourceTextModule;
vm.SyntheticModule = SyntheticModule;
}
}
function initializeSourceMapsHandlers() {
const {
setSourceMapsEnabled,
} = require('internal/source_map/source_map_cache');
setSourceMapsEnabled(getOptionValue('--enable-source-maps'));
}
function initializeFrozenIntrinsics() {
if (getOptionValue('--frozen-intrinsics')) {
process.emitWarning('The --frozen-intrinsics flag is experimental',
'ExperimentalWarning');
require('internal/freeze_intrinsics')();
}
}
function runEmbedderPreload() {
internalBinding('mksnapshot').runEmbedderPreload(process, require);
}
function loadPreloadModules() {
// For user code, we preload modules if `-r` is passed
const preloadModules = getOptionValue('--require');
const isOrcastrationProcess = getOptionValue('--test');
if (preloadModules && preloadModules.length > 0 && !isOrcastrationProcess) {
const {
Module: {
_preloadModules,
},
} = require('internal/modules/cjs/loader');
_preloadModules(preloadModules);
}
}
function markBootstrapComplete() {
internalBinding('performance').markBootstrapComplete();
}
// Sequence number for diagnostic filenames
let sequenceNumOfheapSnapshot = 0;
// To generate the HeapSnapshotFilename while using custom diagnosticDir
function getHeapSnapshotFilename(diagnosticDir) {
if (!diagnosticDir) return undefined;
const date = new Date();
const year = DatePrototypeGetFullYear(date);
const month = String(DatePrototypeGetMonth(date) + 1).padStart(2, '0');
const day = String(DatePrototypeGetDate(date)).padStart(2, '0');
const hours = String(DatePrototypeGetHours(date)).padStart(2, '0');
const minutes = String(DatePrototypeGetMinutes(date)).padStart(2, '0');
const seconds = String(DatePrototypeGetSeconds(date)).padStart(2, '0');
const dateString = `${year}${month}${day}`;
const timeString = `${hours}${minutes}${seconds}`;
const pid = process.pid;
const threadId = internalBinding('worker').threadId;
const fileSequence = (++sequenceNumOfheapSnapshot).toString().padStart(3, '0');
return `${diagnosticDir}/Heap.${dateString}.${timeString}.${pid}.${threadId}.${fileSequence}.heapsnapshot`;
}
module.exports = {
setupUserModules,
prepareMainThreadExecution,
prepareWorkerThreadExecution,
prepareShadowRealmExecution,
markBootstrapComplete,
loadPreloadModules,
initializeFrozenIntrinsics,
};