GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 450 510 88.2 %
Date: 2022-08-12 04:19:25 Branches: 273 399 68.4 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node.h"
23
24
// ========== local headers ==========
25
26
#include "debug_utils-inl.h"
27
#include "env-inl.h"
28
#include "histogram-inl.h"
29
#include "memory_tracker-inl.h"
30
#include "node_binding.h"
31
#include "node_builtins.h"
32
#include "node_errors.h"
33
#include "node_internals.h"
34
#include "node_main_instance.h"
35
#include "node_metadata.h"
36
#include "node_options-inl.h"
37
#include "node_perf.h"
38
#include "node_process-inl.h"
39
#include "node_report.h"
40
#include "node_revert.h"
41
#include "node_snapshot_builder.h"
42
#include "node_v8_platform-inl.h"
43
#include "node_version.h"
44
45
#if HAVE_OPENSSL
46
#include "node_crypto.h"
47
#endif
48
49
#if defined(NODE_HAVE_I18N_SUPPORT)
50
#include "node_i18n.h"
51
#endif
52
53
#if HAVE_INSPECTOR
54
#include "inspector_agent.h"
55
#include "inspector_io.h"
56
#endif
57
58
#if NODE_USE_V8_PLATFORM
59
#include "libplatform/libplatform.h"
60
#endif  // NODE_USE_V8_PLATFORM
61
#include "v8-profiler.h"
62
63
#if HAVE_INSPECTOR
64
#include "inspector/worker_inspector.h"  // ParentInspectorHandle
65
#endif
66
67
#include "large_pages/node_large_page.h"
68
69
#if defined(__APPLE__) || defined(__linux__) || defined(_WIN32)
70
#define NODE_USE_V8_WASM_TRAP_HANDLER 1
71
#else
72
#define NODE_USE_V8_WASM_TRAP_HANDLER 0
73
#endif
74
75
#if NODE_USE_V8_WASM_TRAP_HANDLER
76
#if defined(_WIN32)
77
#include "v8-wasm-trap-handler-win.h"
78
#else
79
#include <atomic>
80
#include "v8-wasm-trap-handler-posix.h"
81
#endif
82
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
83
84
// ========== global C headers ==========
85
86
#include <fcntl.h>  // _O_RDWR
87
#include <sys/types.h>
88
89
#if defined(NODE_HAVE_I18N_SUPPORT)
90
#include <unicode/uvernum.h>
91
#include <unicode/utypes.h>
92
#endif
93
94
95
#if defined(LEAK_SANITIZER)
96
#include <sanitizer/lsan_interface.h>
97
#endif
98
99
#if defined(_MSC_VER)
100
#include <direct.h>
101
#include <io.h>
102
#define STDIN_FILENO 0
103
#else
104
#include <pthread.h>
105
#include <sys/resource.h>  // getrlimit, setrlimit
106
#include <termios.h>       // tcgetattr, tcsetattr
107
#include <unistd.h>        // STDIN_FILENO, STDERR_FILENO
108
#endif
109
110
// ========== global C++ headers ==========
111
112
#include <cerrno>
113
#include <climits>  // PATH_MAX
114
#include <csignal>
115
#include <cstdio>
116
#include <cstdlib>
117
#include <cstring>
118
119
#include <string>
120
#include <vector>
121
122
namespace node {
123
124
using builtins::BuiltinLoader;
125
126
using v8::EscapableHandleScope;
127
using v8::Function;
128
using v8::Isolate;
129
using v8::Local;
130
using v8::MaybeLocal;
131
using v8::Object;
132
using v8::String;
133
using v8::Undefined;
134
using v8::V8;
135
using v8::Value;
136
137
namespace per_process {
138
139
// node_revert.h
140
// Bit flag used to track security reverts.
141
unsigned int reverted_cve = 0;
142
143
// util.h
144
// Tells whether the per-process V8::Initialize() is called and
145
// if it is safe to call v8::Isolate::TryGetCurrent().
146
bool v8_initialized = false;
147
148
// node_internals.h
149
// process-relative uptime base in nanoseconds, initialized in node::Start()
150
uint64_t node_start_time;
151
152
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
153
PVOID old_vectored_exception_handler;
154
#endif
155
156
// node_v8_platform-inl.h
157
struct V8Platform v8_platform;
158
}  // namespace per_process
159
160
// The section in the OpenSSL configuration file to be loaded.
161
const char* conf_section_name = STRINGIFY(NODE_OPENSSL_CONF_NAME);
162
163
#ifdef __POSIX__
164
void SignalExit(int signo, siginfo_t* info, void* ucontext) {
165
  ResetStdio();
166
  raise(signo);
167
}
168
#endif  // __POSIX__
169
170
9937
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
171
                                      const char* id,
172
                                      std::vector<Local<Value>>* arguments) {
173
9937
  EscapableHandleScope scope(env->isolate());
174
  MaybeLocal<Function> maybe_fn =
175
9937
      BuiltinLoader::LookupAndCompile(env->context(), id, env);
176
177
  Local<Function> fn;
178
9937
  if (!maybe_fn.ToLocal(&fn)) {
179
    return MaybeLocal<Value>();
180
  }
181
182
  MaybeLocal<Value> result = fn->Call(env->context(),
183
                                      Undefined(env->isolate()),
184
9937
                                      arguments->size(),
185
29811
                                      arguments->data());
186
187
  // If there was an error during bootstrap, it must be unrecoverable
188
  // (e.g. max call stack exceeded). Clear the stack so that the
189
  // AsyncCallbackScope destructor doesn't fail on the id check.
190
  // There are only two ways to have a stack size > 1: 1) the user manually
191
  // called MakeCallback or 2) user awaited during bootstrap, which triggered
192
  // _tickCallback().
193
9686
  if (result.IsEmpty()) {
194
34
    env->async_hooks()->clear_async_id_stack();
195
  }
196
197
9686
  return scope.EscapeMaybe(result);
198
}
199
200
#if HAVE_INSPECTOR
201
6095
int Environment::InitializeInspector(
202
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
203
12190
  std::string inspector_path;
204
6095
  bool is_main = !parent_handle;
205
6095
  if (parent_handle) {
206
715
    inspector_path = parent_handle->url();
207
715
    inspector_agent_->SetParentHandle(std::move(parent_handle));
208
  } else {
209
5380
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
210
  }
211
212
6095
  CHECK(!inspector_agent_->IsListening());
213
  // Inspector agent can't fail to start, but if it was configured to listen
214
  // right away on the websocket port and fails to bind/etc, this will return
215
  // false.
216
12190
  inspector_agent_->Start(inspector_path,
217
6095
                          options_->debug_options(),
218
12190
                          inspector_host_port(),
219
                          is_main);
220

6176
  if (options_->debug_options().inspector_enabled &&
221
81
      !inspector_agent_->IsListening()) {
222
5
    return 12;  // Signal internal error
223
  }
224
225
6090
  profiler::StartProfilers(this);
226
227
6090
  if (inspector_agent_->options().break_node_first_line) {
228
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
229
  }
230
231
6090
  return 0;
232
}
233
#endif  // HAVE_INSPECTOR
234
235
#define ATOMIC_WAIT_EVENTS(V)                                               \
236
  V(kStartWait,           "started")                                        \
237
  V(kWokenUp,             "was woken up by another thread")                 \
238
  V(kTimedOut,            "timed out")                                      \
239
  V(kTerminatedExecution, "was stopped by terminated execution")            \
240
  V(kAPIStopped,          "was stopped through the embedder API")           \
241
  V(kNotEqual,            "did not wait because the values mismatched")     \
242
243
8
static void AtomicsWaitCallback(Isolate::AtomicsWaitEvent event,
244
                                Local<v8::SharedArrayBuffer> array_buffer,
245
                                size_t offset_in_bytes, int64_t value,
246
                                double timeout_in_ms,
247
                                Isolate::AtomicsWaitWakeHandle* stop_handle,
248
                                void* data) {
249
8
  Environment* env = static_cast<Environment*>(data);
250
251
8
  const char* message = "(unknown event)";
252

8
  switch (event) {
253
#define V(key, msg)                         \
254
    case Isolate::AtomicsWaitEvent::key:    \
255
      message = msg;                        \
256
      break;
257
8
    ATOMIC_WAIT_EVENTS(V)
258
#undef V
259
  }
260
261
16
  fprintf(stderr,
262
          "(node:%d) [Thread %" PRIu64 "] Atomics.wait(%p + %zx, %" PRId64
263
          ", %.f) %s\n",
264
8
          static_cast<int>(uv_os_getpid()),
265
          env->thread_id(),
266
          array_buffer->Data(),
267
          offset_in_bytes,
268
          value,
269
          timeout_in_ms,
270
          message);
271
8
}
272
273
6065
void Environment::InitializeDiagnostics() {
274
6065
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
275
      Environment::BuildEmbedderGraph, this);
276
6065
  if (options_->heap_snapshot_near_heap_limit > 0) {
277
1
    isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
278
                                       this);
279
  }
280
6065
  if (options_->trace_uncaught)
281
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
282
6065
  if (options_->trace_atomics_wait) {
283
2
    isolate_->SetAtomicsWaitCallback(AtomicsWaitCallback, this);
284
2
    AddCleanupHook([](void* data) {
285
2
      Environment* env = static_cast<Environment*>(data);
286
2
      env->isolate()->SetAtomicsWaitCallback(nullptr, nullptr);
287
2
    }, this);
288
  }
289
6065
}
290
291
771
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
292
771
  EscapableHandleScope scope(isolate_);
293
294
  // Arguments must match the parameters specified in
295
  // BuiltinLoader::LookupAndCompile().
296
  std::vector<Local<Value>> loaders_args = {
297
      process_object(),
298
771
      NewFunctionTemplate(isolate_, binding::GetLinkedBinding)
299
771
          ->GetFunction(context())
300
          .ToLocalChecked(),
301
771
      NewFunctionTemplate(isolate_, binding::GetInternalBinding)
302
771
          ->GetFunction(context())
303
          .ToLocalChecked(),
304
5397
      primordials()};
305
306
  // Bootstrap internal loaders
307
  Local<Value> loader_exports;
308
771
  if (!ExecuteBootstrapper(this, "internal/bootstrap/loaders", &loaders_args)
309
771
           .ToLocal(&loader_exports)) {
310
    return MaybeLocal<Value>();
311
  }
312
771
  CHECK(loader_exports->IsObject());
313
771
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
314
  Local<Value> internal_binding_loader =
315
1542
      loader_exports_obj->Get(context(), internal_binding_string())
316
771
          .ToLocalChecked();
317
771
  CHECK(internal_binding_loader->IsFunction());
318
771
  set_internal_binding_loader(internal_binding_loader.As<Function>());
319
  Local<Value> require =
320
2313
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
321
771
  CHECK(require->IsFunction());
322
771
  set_builtin_module_require(require.As<Function>());
323
324
771
  return scope.Escape(loader_exports);
325
}
326
327
771
MaybeLocal<Value> Environment::BootstrapNode() {
328
771
  EscapableHandleScope scope(isolate_);
329
330
  // Arguments must match the parameters specified in
331
  // BuiltinLoader::LookupAndCompile().
332
  // process, require, internalBinding, primordials
333
  std::vector<Local<Value>> node_args = {process_object(),
334
                                         builtin_module_require(),
335
                                         internal_binding_loader(),
336
4626
                                         primordials()};
337
338
  MaybeLocal<Value> result =
339
771
      ExecuteBootstrapper(this, "internal/bootstrap/node", &node_args);
340
341
771
  if (result.IsEmpty()) {
342
    return MaybeLocal<Value>();
343
  }
344
345
771
  if (!no_browser_globals()) {
346
    result =
347
771
        ExecuteBootstrapper(this, "internal/bootstrap/browser", &node_args);
348
349
771
    if (result.IsEmpty()) {
350
      return MaybeLocal<Value>();
351
    }
352
  }
353
354
  // TODO(joyeecheung): skip these in the snapshot building for workers.
355
  auto thread_switch_id =
356
771
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
357
771
                       : "internal/bootstrap/switches/is_not_main_thread";
358
771
  result = ExecuteBootstrapper(this, thread_switch_id, &node_args);
359
360
771
  if (result.IsEmpty()) {
361
    return MaybeLocal<Value>();
362
  }
363
364
  auto process_state_switch_id =
365
771
      owns_process_state()
366
771
          ? "internal/bootstrap/switches/does_own_process_state"
367
771
          : "internal/bootstrap/switches/does_not_own_process_state";
368
771
  result = ExecuteBootstrapper(this, process_state_switch_id, &node_args);
369
370
771
  if (result.IsEmpty()) {
371
    return MaybeLocal<Value>();
372
  }
373
374
771
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
375
  Local<Object> env_var_proxy;
376
2313
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
377

3084
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
378
    return MaybeLocal<Value>();
379
  }
380
381
771
  return scope.EscapeMaybe(result);
382
}
383
384
771
MaybeLocal<Value> Environment::RunBootstrapping() {
385
771
  EscapableHandleScope scope(isolate_);
386
387
771
  CHECK(!has_run_bootstrapping_code());
388
389
1542
  if (BootstrapInternalLoaders().IsEmpty()) {
390
    return MaybeLocal<Value>();
391
  }
392
393
  Local<Value> result;
394
1542
  if (!BootstrapNode().ToLocal(&result)) {
395
    return MaybeLocal<Value>();
396
  }
397
398
  // Make sure that no request or handle is created during bootstrap -
399
  // if necessary those should be done in pre-execution.
400
  // Usually, doing so would trigger the checks present in the ReqWrap and
401
  // HandleWrap classes, so this is only a consistency check.
402
771
  CHECK(req_wrap_queue()->IsEmpty());
403
771
  CHECK(handle_wrap_queue()->IsEmpty());
404
405
771
  DoneBootstrapping();
406
407
771
  return scope.Escape(result);
408
}
409
410
static
411
6065
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
412
6065
  EscapableHandleScope scope(env->isolate());
413
6065
  CHECK_NOT_NULL(main_script_id);
414
415
  // Arguments must match the parameters specified in
416
  // BuiltinLoader::LookupAndCompile().
417
  std::vector<Local<Value>> arguments = {env->process_object(),
418
                                         env->builtin_module_require(),
419
                                         env->internal_binding_loader(),
420
30325
                                         env->primordials()};
421
422
  return scope.EscapeMaybe(
423
11881
      ExecuteBootstrapper(env, main_script_id, &arguments));
424
}
425
426
6065
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
427
  InternalCallbackScope callback_scope(
428
      env,
429
      Object::New(env->isolate()),
430
      { 1, 0 },
431
11879
      InternalCallbackScope::kSkipAsyncHooks);
432
433
6065
  if (cb != nullptr) {
434
22
    EscapableHandleScope scope(env->isolate());
435
436
44
    if (StartExecution(env, "internal/main/environment").IsEmpty()) return {};
437
438
    StartExecutionCallbackInfo info = {
439
22
        env->process_object(),
440
22
        env->builtin_module_require(),
441
    };
442
443
42
    return scope.EscapeMaybe(cb(info));
444
  }
445
446
  // TODO(joyeecheung): move these conditions into JS land and let the
447
  // deserialize main function take precedence. For workers, we need to
448
  // move the pre-execution part into a different file that can be
449
  // reused when dealing with user-defined main functions.
450
12086
  if (!env->snapshot_deserialize_main().IsEmpty()) {
451
    return env->RunSnapshotDeserializeMain();
452
  }
453
454
6043
  if (env->worker_context() != nullptr) {
455
710
    return StartExecution(env, "internal/main/worker_thread");
456
  }
457
458
10417
  std::string first_argv;
459
5333
  if (env->argv().size() > 1) {
460
4824
    first_argv = env->argv()[1];
461
  }
462
463
5333
  if (first_argv == "inspect") {
464
38
    return StartExecution(env, "internal/main/inspect");
465
  }
466
467
5295
  if (per_process::cli_options->build_snapshot) {
468
1
    return StartExecution(env, "internal/main/mksnapshot");
469
  }
470
471
5294
  if (per_process::cli_options->print_help) {
472
2
    return StartExecution(env, "internal/main/print_help");
473
  }
474
475
476
5292
  if (env->options()->prof_process) {
477
1
    return StartExecution(env, "internal/main/prof_process");
478
  }
479
480
  // -e/--eval without -i/--interactive
481


5291
  if (env->options()->has_eval_string && !env->options()->force_repl) {
482
472
    return StartExecution(env, "internal/main/eval_string");
483
  }
484
485
4819
  if (env->options()->syntax_check_only) {
486
39
    return StartExecution(env, "internal/main/check_syntax");
487
  }
488
489
4780
  if (env->options()->test_runner) {
490
9
    return StartExecution(env, "internal/main/test_runner");
491
  }
492
493

4771
  if (!first_argv.empty() && first_argv != "-") {
494
4725
    return StartExecution(env, "internal/main/run_main_module");
495
  }
496
497


46
  if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
498
28
    return StartExecution(env, "internal/main/repl");
499
  }
500
501
18
  return StartExecution(env, "internal/main/eval_stdin");
502
}
503
504
#ifdef __POSIX__
505
typedef void (*sigaction_cb)(int signo, siginfo_t* info, void* ucontext);
506
#endif
507
#if NODE_USE_V8_WASM_TRAP_HANDLER
508
#if defined(_WIN32)
509
static LONG TrapWebAssemblyOrContinue(EXCEPTION_POINTERS* exception) {
510
  if (v8::TryHandleWebAssemblyTrapWindows(exception)) {
511
    return EXCEPTION_CONTINUE_EXECUTION;
512
  }
513
  return EXCEPTION_CONTINUE_SEARCH;
514
}
515
#else
516
static std::atomic<sigaction_cb> previous_sigsegv_action;
517
518
6
void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) {
519
6
  if (!v8::TryHandleWebAssemblyTrapPosix(signo, info, ucontext)) {
520
6
    sigaction_cb prev = previous_sigsegv_action.load();
521
6
    if (prev != nullptr) {
522
6
      prev(signo, info, ucontext);
523
    } else {
524
      // Reset to the default signal handler, i.e. cause a hard crash.
525
      struct sigaction sa;
526
      memset(&sa, 0, sizeof(sa));
527
      sa.sa_handler = SIG_DFL;
528
      CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
529
530
      ResetStdio();
531
      raise(signo);
532
    }
533
  }
534
6
}
535
#endif  // defined(_WIN32)
536
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
537
538
#ifdef __POSIX__
539
17092
void RegisterSignalHandler(int signal,
540
                           sigaction_cb handler,
541
                           bool reset_handler) {
542
17092
  CHECK_NOT_NULL(handler);
543
#if NODE_USE_V8_WASM_TRAP_HANDLER
544
17092
  if (signal == SIGSEGV) {
545
4
    CHECK(previous_sigsegv_action.is_lock_free());
546
4
    CHECK(!reset_handler);
547
4
    previous_sigsegv_action.store(handler);
548
4
    return;
549
  }
550
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
551
  struct sigaction sa;
552
17088
  memset(&sa, 0, sizeof(sa));
553
17088
  sa.sa_sigaction = handler;
554
17088
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
555
17088
  sigfillset(&sa.sa_mask);
556
17088
  CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
557
}
558
#endif  // __POSIX__
559
560
#ifdef __POSIX__
561
static struct {
562
  int flags;
563
  bool isatty;
564
  struct stat stat;
565
  struct termios termios;
566
} stdio[1 + STDERR_FILENO];
567
#endif  // __POSIX__
568
569
10220
void ResetSignalHandlers() {
570
#ifdef __POSIX__
571
  // Restore signal dispositions, the parent process may have changed them.
572
  struct sigaction act;
573
10220
  memset(&act, 0, sizeof(act));
574
575
  // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
576
  // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
577
  // Counting up to SIGRTMIN doesn't work for the same reason.
578
327040
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
579

316820
    if (nr == SIGKILL || nr == SIGSTOP)
580
20440
      continue;
581

296380
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
582
296380
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
583
  }
584
#endif  // __POSIX__
585
10220
}
586
587
static std::atomic<uint64_t> init_process_flags = 0;
588
589
5408
static void PlatformInit(ProcessInitializationFlags::Flags flags) {
590
  // init_process_flags is accessed in ResetStdio(),
591
  // which can be called from signal handlers.
592
5408
  CHECK(init_process_flags.is_lock_free());
593
  init_process_flags.store(flags);
594
595
5408
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
596
5408
    atexit(ResetStdio);
597
  }
598
599
#ifdef __POSIX__
600
5408
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
601
    // Disable stdio buffering, it interacts poorly with printf()
602
    // calls elsewhere in the program (e.g., any logging from V8.)
603
5408
    setvbuf(stdout, nullptr, _IONBF, 0);
604
5408
    setvbuf(stderr, nullptr, _IONBF, 0);
605
606
    // Make sure file descriptors 0-2 are valid before we start logging
607
    // anything.
608
21632
    for (auto& s : stdio) {
609
16224
      const int fd = &s - stdio;
610
16224
      if (fstat(fd, &s.stat) == 0) continue;
611
      // Anything but EBADF means something is seriously wrong.  We don't
612
      // have to special-case EINTR, fstat() is not interruptible.
613
2
      if (errno != EBADF) ABORT();
614
2
      if (fd != open("/dev/null", O_RDWR)) ABORT();
615
2
      if (fstat(fd, &s.stat) != 0) ABORT();
616
    }
617
  }
618
619
5408
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
620
#if HAVE_INSPECTOR
621
    sigset_t sigmask;
622
5408
    sigemptyset(&sigmask);
623
5408
    sigaddset(&sigmask, SIGUSR1);
624
5408
    const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
625
5408
    CHECK_EQ(err, 0);
626
#endif  // HAVE_INSPECTOR
627
628
5408
    ResetSignalHandlers();
629
  }
630
631
5408
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
632
    // Record the state of the stdio file descriptors so we can restore it
633
    // on exit.  Needs to happen before installing signal handlers because
634
    // they make use of that information.
635
21632
    for (auto& s : stdio) {
636
16224
      const int fd = &s - stdio;
637
      int err;
638
639
      do {
640
16224
        s.flags = fcntl(fd, F_GETFL);
641

16224
      } while (s.flags == -1 && errno == EINTR);  // NOLINT
642
16224
      CHECK_NE(s.flags, -1);
643
644
16224
      if (uv_guess_handle(fd) != UV_TTY) continue;
645
120
      s.isatty = true;
646
647
      do {
648
120
        err = tcgetattr(fd, &s.termios);
649

120
      } while (err == -1 && errno == EINTR);  // NOLINT
650
120
      CHECK_EQ(err, 0);
651
    }
652
  }
653
654
5408
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
655
5408
    RegisterSignalHandler(SIGINT, SignalExit, true);
656
5408
    RegisterSignalHandler(SIGTERM, SignalExit, true);
657
658
#if NODE_USE_V8_WASM_TRAP_HANDLER
659
#if defined(_WIN32)
660
    {
661
      constexpr ULONG first = TRUE;
662
      per_process::old_vectored_exception_handler =
663
          AddVectoredExceptionHandler(first, TrapWebAssemblyOrContinue);
664
    }
665
#else
666
    // Tell V8 to disable emitting WebAssembly
667
    // memory bounds checks. This means that we have
668
    // to catch the SIGSEGV in TrapWebAssemblyOrContinue
669
    // and pass the signal context to V8.
670
    {
671
      struct sigaction sa;
672
5408
      memset(&sa, 0, sizeof(sa));
673
5408
      sa.sa_sigaction = TrapWebAssemblyOrContinue;
674
5408
      sa.sa_flags = SA_SIGINFO;
675
5408
      CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
676
    }
677
#endif  // defined(_WIN32)
678
5408
    V8::EnableWebAssemblyTrapHandler(false);
679
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
680
  }
681
682
5408
  if (!(flags & ProcessInitializationFlags::kNoAdjustResourceLimits)) {
683
    // Raise the open file descriptor limit.
684
    struct rlimit lim;
685

5408
    if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
686
      // Do a binary search for the limit.
687
      rlim_t min = lim.rlim_cur;
688
      rlim_t max = 1 << 20;
689
      // But if there's a defined upper bound, don't search, just set it.
690
      if (lim.rlim_max != RLIM_INFINITY) {
691
        min = lim.rlim_max;
692
        max = lim.rlim_max;
693
      }
694
      do {
695
        lim.rlim_cur = min + (max - min) / 2;
696
        if (setrlimit(RLIMIT_NOFILE, &lim)) {
697
          max = lim.rlim_cur;
698
        } else {
699
          min = lim.rlim_cur;
700
        }
701
      } while (min + 1 < max);
702
    }
703
  }
704
#endif  // __POSIX__
705
#ifdef _WIN32
706
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
707
    for (int fd = 0; fd <= 2; ++fd) {
708
      auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
709
      if (handle == INVALID_HANDLE_VALUE ||
710
          GetFileType(handle) == FILE_TYPE_UNKNOWN) {
711
        // Ignore _close result. If it fails or not depends on used Windows
712
        // version. We will just check _open result.
713
        _close(fd);
714
        if (fd != _open("nul", _O_RDWR)) ABORT();
715
      }
716
    }
717
  }
718
#endif  // _WIN32
719
5408
}
720
721
// Safe to call more than once and from signal handlers.
722
10241
void ResetStdio() {
723
20482
  if (init_process_flags.load() &
724
10241
      ProcessInitializationFlags::kNoStdioInitialization) {
725
    return;
726
  }
727
728
10241
  uv_tty_reset_mode();
729
#ifdef __POSIX__
730
40964
  for (auto& s : stdio) {
731
30723
    const int fd = &s - stdio;
732
733
    struct stat tmp;
734
30723
    if (-1 == fstat(fd, &tmp)) {
735
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
736
6
      continue;
737
    }
738
739
30723
    bool is_same_file =
740

30723
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
741
30723
    if (!is_same_file) continue;  // Program reopened file descriptor.
742
743
    int flags;
744
    do
745
30717
      flags = fcntl(fd, F_GETFL);
746

30717
    while (flags == -1 && errno == EINTR);  // NOLINT
747
30717
    CHECK_NE(flags, -1);
748
749
    // Restore the O_NONBLOCK flag if it changed.
750
30717
    if (O_NONBLOCK & (flags ^ s.flags)) {
751
1207
      flags &= ~O_NONBLOCK;
752
1207
      flags |= s.flags & O_NONBLOCK;
753
754
      int err;
755
      do
756
1207
        err = fcntl(fd, F_SETFL, flags);
757

1207
      while (err == -1 && errno == EINTR);  // NOLINT
758
1207
      CHECK_NE(err, -1);
759
    }
760
761
30717
    if (s.isatty) {
762
      sigset_t sa;
763
      int err;
764
765
      // We might be a background job that doesn't own the TTY so block SIGTTOU
766
      // before making the tcsetattr() call, otherwise that signal suspends us.
767
228
      sigemptyset(&sa);
768
228
      sigaddset(&sa, SIGTTOU);
769
770
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
771
      do
772
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
773

228
      while (err == -1 && errno == EINTR);  // NOLINT
774
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
775
776
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
777
      // tcsetattr will fail with err == -1 and errno == EPERM.
778


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
779
    }
780
  }
781
#endif  // __POSIX__
782
}
783
784
785
10684
int ProcessGlobalArgs(std::vector<std::string>* args,
786
                      std::vector<std::string>* exec_args,
787
                      std::vector<std::string>* errors,
788
                      OptionEnvvarSettings settings) {
789
  // Parse a few arguments which are specific to Node.
790
21368
  std::vector<std::string> v8_args;
791
792
21368
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
793
10684
  options_parser::Parse(
794
      args,
795
      exec_args,
796
      &v8_args,
797
      per_process::cli_options.get(),
798
      settings,
799
      errors);
800
801
10684
  if (!errors->empty()) return 9;
802
803
21268
  std::string revert_error;
804
10634
  for (const std::string& cve : per_process::cli_options->security_reverts) {
805
1
    Revert(cve.c_str(), &revert_error);
806
1
    if (!revert_error.empty()) {
807
1
      errors->emplace_back(std::move(revert_error));
808
1
      return 12;
809
    }
810
  }
811
812
21265
  if (per_process::cli_options->disable_proto != "delete" &&
813

21265
      per_process::cli_options->disable_proto != "throw" &&
814
10631
      per_process::cli_options->disable_proto != "") {
815
    errors->emplace_back("invalid mode passed to --disable-proto");
816
    return 12;
817
  }
818
819
  // TODO(aduh95): remove this when the harmony-import-assertions flag
820
  // is removed in V8.
821
21266
  if (std::find(v8_args.begin(), v8_args.end(),
822
10633
                "--no-harmony-import-assertions") == v8_args.end()) {
823
10633
    v8_args.emplace_back("--harmony-import-assertions");
824
  }
825
826
21266
  auto env_opts = per_process::cli_options->per_isolate->per_env;
827
21266
  if (std::find(v8_args.begin(), v8_args.end(),
828

21248
                "--abort-on-uncaught-exception") != v8_args.end() ||
829
10633
      std::find(v8_args.begin(), v8_args.end(),
830
21248
                "--abort_on_uncaught_exception") != v8_args.end()) {
831
21
    env_opts->abort_on_uncaught_exception = true;
832
  }
833
834
#ifdef __POSIX__
835
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
836
  // performance penalty of frequent EINTR wakeups when the profiler is running.
837
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
838
10633
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
839
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
840
  }
841
#endif
842
843
21266
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
844
10633
  if (v8_args.size() > 0) {
845
32038
    for (size_t i = 0; i < v8_args.size(); ++i)
846
21405
      v8_args_as_char_ptr[i] = &v8_args[i][0];
847
10633
    int argc = v8_args.size();
848
10633
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
849
10633
    v8_args_as_char_ptr.resize(argc);
850
  }
851
852
  // Anything that's still in v8_argv is not a V8 or a node option.
853
10634
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
854
1
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
855
856
10633
  if (v8_args_as_char_ptr.size() > 1) return 9;
857
858
10632
  return 0;
859
}
860
861
static std::atomic_bool init_called{false};
862
863
// TODO(addaleax): Turn this into a wrapper around InitializeOncePerProcess()
864
// (with the corresponding additional flags set), then eventually remove this.
865
5409
int InitializeNodeWithArgs(std::vector<std::string>* argv,
866
                           std::vector<std::string>* exec_argv,
867
                           std::vector<std::string>* errors,
868
                           ProcessInitializationFlags::Flags flags) {
869
  // Make sure InitializeNodeWithArgs() is called only once.
870
5409
  CHECK(!init_called.exchange(true));
871
872
  // Initialize node_start_time to get relative uptime.
873
5409
  per_process::node_start_time = uv_hrtime();
874
875
  // Register built-in modules
876
5409
  binding::RegisterBuiltinModules();
877
878
  // Make inherited handles noninheritable.
879
5409
  if (!(flags & ProcessInitializationFlags::kEnableStdioInheritance) &&
880
5409
      !(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
881
5409
    uv_disable_stdio_inheritance();
882
  }
883
884
  // Cache the original command line to be
885
  // used in diagnostic reports.
886
5409
  per_process::cli_options->cmdline = *argv;
887
888
#if defined(NODE_V8_OPTIONS)
889
  // Should come before the call to V8::SetFlagsFromCommandLine()
890
  // so the user can disable a flag --foo at run-time by passing
891
  // --no_foo from the command line.
892
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
893
#endif
894
895
5409
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
896
897
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
898
5409
  if (!(flags & ProcessInitializationFlags::kDisableNodeOptionsEnv)) {
899
5409
    std::string node_options;
900
901
5409
    if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
902
      std::vector<std::string> env_argv =
903
5292
          ParseNodeOptionsEnvVar(node_options, errors);
904
905
5292
      if (!errors->empty()) return 9;
906
907
      // [0] is expected to be the program name, fill it in from the real argv.
908
5292
      env_argv.insert(env_argv.begin(), argv->at(0));
909
910
5292
      const int exit_code = ProcessGlobalArgs(&env_argv,
911
                                              nullptr,
912
                                              errors,
913
                                              kAllowedInEnvironment);
914
5292
      if (exit_code != 0) return exit_code;
915
    }
916
  }
917
#endif
918
919
5392
  if (!(flags & ProcessInitializationFlags::kDisableCLIOptions)) {
920
5392
    const int exit_code = ProcessGlobalArgs(argv,
921
                                            exec_argv,
922
                                            errors,
923
                                            kDisallowedInEnvironment);
924
5392
    if (exit_code != 0) return exit_code;
925
  }
926
927
  // Set the process.title immediately after processing argv if --title is set.
928
5357
  if (!per_process::cli_options->title.empty())
929
2
    uv_set_process_title(per_process::cli_options->title.c_str());
930
931
#if defined(NODE_HAVE_I18N_SUPPORT)
932
5357
  if (!(flags & ProcessInitializationFlags::kNoICU)) {
933
    // If the parameter isn't given, use the env variable.
934
5357
    if (per_process::cli_options->icu_data_dir.empty())
935
10714
      credentials::SafeGetenv("NODE_ICU_DATA",
936
5357
                              &per_process::cli_options->icu_data_dir);
937
938
#ifdef NODE_ICU_DEFAULT_DATA_DIR
939
    // If neither the CLI option nor the environment variable was specified,
940
    // fall back to the configured default
941
    if (per_process::cli_options->icu_data_dir.empty()) {
942
      // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
943
      // file and can be read.
944
      static const char full_path[] =
945
          NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
946
947
      FILE* f = fopen(full_path, "rb");
948
949
      if (f != nullptr) {
950
        fclose(f);
951
        per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
952
      }
953
    }
954
#endif  // NODE_ICU_DEFAULT_DATA_DIR
955
956
    // Initialize ICU.
957
    // If icu_data_dir is empty here, it will load the 'minimal' data.
958
5357
    if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
959
      errors->push_back("could not initialize ICU "
960
                        "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
961
      return 9;
962
    }
963
5357
    per_process::metadata.versions.InitializeIntlVersions();
964
  }
965
966
# ifndef __POSIX__
967
  std::string tz;
968
  if (credentials::SafeGetenv("TZ", &tz) && !tz.empty()) {
969
    i18n::SetDefaultTimeZone(tz.c_str());
970
  }
971
# endif
972
973
#endif  // defined(NODE_HAVE_I18N_SUPPORT)
974
975
  // We should set node_is_initialized here instead of in node::Start,
976
  // otherwise embedders using node::Init to initialize everything will not be
977
  // able to set it and native addons will not load for them.
978
5357
  node_is_initialized = true;
979
5357
  return 0;
980
}
981
982
5408
std::unique_ptr<InitializationResult> InitializeOncePerProcess(
983
    const std::vector<std::string>& args,
984
    ProcessInitializationFlags::Flags flags) {
985
10816
  auto result = std::make_unique<InitializationResultImpl>();
986
5408
  result->args_ = args;
987
988
5408
  if (!(flags & ProcessInitializationFlags::kNoParseGlobalDebugVariables)) {
989
    // Initialized the enabled list for Debug() calls with system
990
    // environment variables.
991
5408
    per_process::enabled_debug_list.Parse();
992
  }
993
994
5408
  PlatformInit(flags);
995
996
  // This needs to run *before* V8::Initialize().
997
  {
998
5408
    result->exit_code_ = InitializeNodeWithArgs(
999
5408
        &result->args_, &result->exec_args_, &result->errors_, flags);
1000
5408
    if (result->exit_code() != 0) {
1001
52
      result->early_return_ = true;
1002
52
      return result;
1003
    }
1004
  }
1005
1006

16067
  if (!(flags & ProcessInitializationFlags::kNoUseLargePages) &&
1007
10711
      (per_process::cli_options->use_largepages == "on" ||
1008
5355
       per_process::cli_options->use_largepages == "silent")) {
1009
1
    int lp_result = node::MapStaticCodeToLargePages();
1010

1
    if (per_process::cli_options->use_largepages == "on" && lp_result != 0) {
1011
      result->errors_.emplace_back(node::LargePagesError(lp_result));
1012
    }
1013
  }
1014
1015
5356
  if (!(flags & ProcessInitializationFlags::kNoPrintHelpOrVersionOutput)) {
1016
5356
    if (per_process::cli_options->print_version) {
1017
3
      printf("%s\n", NODE_VERSION);
1018
3
      result->exit_code_ = 0;
1019
3
      result->early_return_ = true;
1020
3
      return result;
1021
    }
1022
1023
5353
    if (per_process::cli_options->print_bash_completion) {
1024
2
      std::string completion = options_parser::GetBashCompletion();
1025
1
      printf("%s\n", completion.c_str());
1026
1
      result->exit_code_ = 0;
1027
1
      result->early_return_ = true;
1028
1
      return result;
1029
    }
1030
1031
5352
    if (per_process::cli_options->print_v8_help) {
1032
      V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1033
      result->exit_code_ = 0;
1034
      result->early_return_ = true;
1035
      return result;
1036
    }
1037
  }
1038
1039
5352
  if (!(flags & ProcessInitializationFlags::kNoInitOpenSSL)) {
1040
#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1041
2
    auto GetOpenSSLErrorString = []() -> std::string {
1042
2
      std::string ret;
1043
2
      ERR_print_errors_cb(
1044
2
          [](const char* str, size_t len, void* opaque) {
1045
2
            std::string* ret = static_cast<std::string*>(opaque);
1046
2
            ret->append(str, len);
1047
2
            ret->append("\n");
1048
2
            return 0;
1049
          },
1050
          static_cast<void*>(&ret));
1051
2
      return ret;
1052
    };
1053
1054
    {
1055
10704
      std::string extra_ca_certs;
1056
5352
      if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1057
4
        crypto::UseExtraCaCerts(extra_ca_certs);
1058
    }
1059
    // In the case of FIPS builds we should make sure
1060
    // the random source is properly initialized first.
1061
#if OPENSSL_VERSION_MAJOR >= 3
1062
    // Call OPENSSL_init_crypto to initialize OPENSSL_INIT_LOAD_CONFIG to
1063
    // avoid the default behavior where errors raised during the parsing of the
1064
    // OpenSSL configuration file are not propagated and cannot be detected.
1065
    //
1066
    // If FIPS is configured the OpenSSL configuration file will have an
1067
    // .include pointing to the fipsmodule.cnf file generated by the openssl
1068
    // fipsinstall command. If the path to this file is incorrect no error
1069
    // will be reported.
1070
    //
1071
    // For Node.js this will mean that EntropySource will be called by V8 as
1072
    // part of its initialization process, and EntropySource will in turn call
1073
    // CheckEntropy. CheckEntropy will call RAND_status which will now always
1074
    // return 0, leading to an endless loop and the node process will appear to
1075
    // hang/freeze.
1076
1077
    // Passing NULL as the config file will allow the default openssl.cnf file
1078
    // to be loaded, but the default section in that file will not be used,
1079
    // instead only the section that matches the value of conf_section_name
1080
    // will be read from the default configuration file.
1081
5352
    const char* conf_file = nullptr;
1082
    // To allow for using the previous default where the 'openssl_conf' appname
1083
    // was used, the command line option 'openssl-shared-config' can be used to
1084
    // force the old behavior.
1085
5352
    if (per_process::cli_options->openssl_shared_config) {
1086
      conf_section_name = "openssl_conf";
1087
    }
1088
    // Use OPENSSL_CONF environment variable is set.
1089
5352
    std::string env_openssl_conf;
1090
5352
    credentials::SafeGetenv("OPENSSL_CONF", &env_openssl_conf);
1091
5352
    if (!env_openssl_conf.empty()) {
1092
1
      conf_file = env_openssl_conf.c_str();
1093
    }
1094
    // Use --openssl-conf command line option if specified.
1095
5352
    if (!per_process::cli_options->openssl_config.empty()) {
1096
      conf_file = per_process::cli_options->openssl_config.c_str();
1097
    }
1098
1099
5352
    OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
1100
5352
    OPENSSL_INIT_set_config_filename(settings, conf_file);
1101
5352
    OPENSSL_INIT_set_config_appname(settings, conf_section_name);
1102
5352
    OPENSSL_INIT_set_config_file_flags(settings,
1103
                                       CONF_MFLAGS_IGNORE_MISSING_FILE);
1104
1105
5352
    OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
1106
5352
    OPENSSL_INIT_free(settings);
1107
1108
5352
    if (ERR_peek_error() != 0) {
1109
      // XXX: ERR_GET_REASON does not return something that is
1110
      // useful as an exit code at all.
1111
      result->exit_code_ = ERR_GET_REASON(ERR_peek_error());
1112
      result->early_return_ = true;
1113
      result->errors_.emplace_back("OpenSSL configuration error:\n" +
1114
                                   GetOpenSSLErrorString());
1115
      return result;
1116
    }
1117
#else  // OPENSSL_VERSION_MAJOR < 3
1118
    if (FIPS_mode()) {
1119
      OPENSSL_init();
1120
    }
1121
#endif
1122
5352
    if (!crypto::ProcessFipsOptions()) {
1123
      // XXX: ERR_GET_REASON does not return something that is
1124
      // useful as an exit code at all.
1125
2
      result->exit_code_ = ERR_GET_REASON(ERR_peek_error());
1126
2
      result->early_return_ = true;
1127
2
      result->errors_.emplace_back(
1128
4
          "OpenSSL error when trying to enable FIPS:\n" +
1129
6
          GetOpenSSLErrorString());
1130
2
      return result;
1131
    }
1132
1133
    // V8 on Windows doesn't have a good source of entropy. Seed it from
1134
    // OpenSSL's pool.
1135
5350
    V8::SetEntropySource(crypto::EntropySource);
1136
#endif  // HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1137
  }
1138
1139
5350
  if (!(flags & ProcessInitializationFlags::kNoInitializeNodeV8Platform)) {
1140
5343
    per_process::v8_platform.Initialize(
1141
5343
        static_cast<int>(per_process::cli_options->v8_thread_pool_size));
1142
5343
    result->platform_ = per_process::v8_platform.Platform();
1143
  }
1144
1145
5350
  if (!(flags & ProcessInitializationFlags::kNoInitializeV8)) {
1146
    V8::Initialize();
1147
  }
1148
1149
5350
  performance::performance_v8_start = PERFORMANCE_NOW();
1150
5350
  per_process::v8_initialized = true;
1151
1152
5350
  return result;
1153
}
1154
1155
4812
void TearDownOncePerProcess() {
1156
4812
  const uint64_t flags = init_process_flags.load();
1157
4812
  ResetStdio();
1158
4812
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
1159
4812
    ResetSignalHandlers();
1160
  }
1161
1162
4812
  per_process::v8_initialized = false;
1163
4812
  if (!(flags & ProcessInitializationFlags::kNoInitializeV8)) {
1164
4807
    V8::Dispose();
1165
  }
1166
1167
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1168
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
1169
    RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1170
  }
1171
#endif
1172
1173
4812
  if (!(flags & ProcessInitializationFlags::kNoInitializeNodeV8Platform)) {
1174
4807
    V8::DisposePlatform();
1175
    // uv_run cannot be called from the time before the beforeExit callback
1176
    // runs until the program exits unless the event loop has any referenced
1177
    // handles after beforeExit terminates. This prevents unrefed timers
1178
    // that happen to terminate during shutdown from being run unsafely.
1179
    // Since uv_run cannot be called, uv_async handles held by the platform
1180
    // will never be fully cleaned up.
1181
4807
    per_process::v8_platform.Dispose();
1182
  }
1183
4812
}
1184
1185
9740
InitializationResult::~InitializationResult() {}
1186
9740
InitializationResultImpl::~InitializationResultImpl() {}
1187
1188
3
int GenerateAndWriteSnapshotData(const SnapshotData** snapshot_data_ptr,
1189
                                 const InitializationResult* result) {
1190
3
  int exit_code = result->exit_code();
1191
  // nullptr indicates there's no snapshot data.
1192
  DCHECK_NULL(*snapshot_data_ptr);
1193
1194
  // node:embedded_snapshot_main indicates that we are using the
1195
  // embedded snapshot and we are not supposed to clean it up.
1196
3
  if (result->args()[1] == "node:embedded_snapshot_main") {
1197
2
    *snapshot_data_ptr = SnapshotBuilder::GetEmbeddedSnapshotData();
1198
2
    if (*snapshot_data_ptr == nullptr) {
1199
      // The Node.js binary is built without embedded snapshot
1200
      fprintf(stderr,
1201
              "node:embedded_snapshot_main was specified as snapshot "
1202
              "entry point but Node.js was built without embedded "
1203
              "snapshot.\n");
1204
      exit_code = 1;
1205
      return exit_code;
1206
    }
1207
  } else {
1208
    // Otherwise, load and run the specified main script.
1209
    std::unique_ptr<SnapshotData> generated_data =
1210
1
        std::make_unique<SnapshotData>();
1211
2
    exit_code = node::SnapshotBuilder::Generate(
1212
2
        generated_data.get(), result->args(), result->exec_args());
1213
1
    if (exit_code == 0) {
1214
      *snapshot_data_ptr = generated_data.release();
1215
    } else {
1216
1
      return exit_code;
1217
    }
1218
  }
1219
1220
  // Get the path to write the snapshot blob to.
1221
2
  std::string snapshot_blob_path;
1222
2
  if (!per_process::cli_options->snapshot_blob.empty()) {
1223
1
    snapshot_blob_path = per_process::cli_options->snapshot_blob;
1224
  } else {
1225
    // Defaults to snapshot.blob in the current working directory.
1226
1
    snapshot_blob_path = std::string("snapshot.blob");
1227
  }
1228
1229
2
  FILE* fp = fopen(snapshot_blob_path.c_str(), "wb");
1230
2
  if (fp != nullptr) {
1231
2
    (*snapshot_data_ptr)->ToBlob(fp);
1232
2
    fclose(fp);
1233
  } else {
1234
    fprintf(stderr,
1235
            "Cannot open %s for writing a snapshot.\n",
1236
            snapshot_blob_path.c_str());
1237
    exit_code = 1;
1238
  }
1239
2
  return exit_code;
1240
}
1241
1242
5333
int LoadSnapshotDataAndRun(const SnapshotData** snapshot_data_ptr,
1243
                           const InitializationResult* result) {
1244
5333
  int exit_code = result->exit_code();
1245
  // nullptr indicates there's no snapshot data.
1246
  DCHECK_NULL(*snapshot_data_ptr);
1247
  // --snapshot-blob indicates that we are reading a customized snapshot.
1248
5333
  if (!per_process::cli_options->snapshot_blob.empty()) {
1249
3
    std::string filename = per_process::cli_options->snapshot_blob;
1250
3
    FILE* fp = fopen(filename.c_str(), "rb");
1251
3
    if (fp == nullptr) {
1252
1
      fprintf(stderr, "Cannot open %s", filename.c_str());
1253
1
      exit_code = 1;
1254
1
      return exit_code;
1255
    }
1256
2
    std::unique_ptr<SnapshotData> read_data = std::make_unique<SnapshotData>();
1257
2
    if (!SnapshotData::FromBlob(read_data.get(), fp)) {
1258
      // If we fail to read the customized snapshot, simply exit with 1.
1259
      exit_code = 1;
1260
      return exit_code;
1261
    }
1262
2
    *snapshot_data_ptr = read_data.release();
1263
2
    fclose(fp);
1264
5330
  } else if (per_process::cli_options->node_snapshot) {
1265
    // If --snapshot-blob is not specified, we are reading the embedded
1266
    // snapshot, but we will skip it if --no-node-snapshot is specified.
1267
    const node::SnapshotData* read_data =
1268
5328
        SnapshotBuilder::GetEmbeddedSnapshotData();
1269

5328
    if (read_data != nullptr && read_data->Check()) {
1270
      // If we fail to read the embedded snapshot, treat it as if Node.js
1271
      // was built without one.
1272
5328
      *snapshot_data_ptr = read_data;
1273
    }
1274
  }
1275
1276
5332
  if ((*snapshot_data_ptr) != nullptr) {
1277
5330
    BuiltinLoader::RefreshCodeCache((*snapshot_data_ptr)->code_cache);
1278
  }
1279
  NodeMainInstance main_instance(*snapshot_data_ptr,
1280
                                 uv_default_loop(),
1281
5332
                                 per_process::v8_platform.Platform(),
1282
5332
                                 result->args(),
1283
10664
                                 result->exec_args());
1284
5332
  exit_code = main_instance.Run();
1285
4796
  return exit_code;
1286
}
1287
1288
5395
int Start(int argc, char** argv) {
1289
5395
  CHECK_GT(argc, 0);
1290
1291
  // Hack around with the argv pointer. Used for process.title = "blah".
1292
5395
  argv = uv_setup_args(argc, argv);
1293
1294
  std::unique_ptr<InitializationResult> result =
1295
15649
      InitializeOncePerProcess(std::vector<std::string>(argv, argv + argc));
1296
5450
  for (const std::string& error : result->errors()) {
1297
55
    FPrintF(stderr, "%s: %s\n", result->args().at(0), error);
1298
  }
1299
5395
  if (result->early_return()) {
1300
58
    return result->exit_code();
1301
  }
1302
1303
  DCHECK_EQ(result->exit_code(), 0);
1304
5337
  const SnapshotData* snapshot_data = nullptr;
1305
1306
4801
  auto cleanup_process = OnScopeLeave([&]() {
1307
4801
    TearDownOncePerProcess();
1308
1309
4801
    if (snapshot_data != nullptr &&
1310
4796
        snapshot_data->data_ownership == SnapshotData::DataOwnership::kOwned) {
1311
2
      delete snapshot_data;
1312
    }
1313
10138
  });
1314
1315
5337
  uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1316
1317
  // --build-snapshot indicates that we are in snapshot building mode.
1318
5337
  if (per_process::cli_options->build_snapshot) {
1319
4
    if (result->args().size() < 2) {
1320
1
      fprintf(stderr,
1321
              "--build-snapshot must be used with an entry point script.\n"
1322
              "Usage: node --build-snapshot /path/to/entry.js\n");
1323
1
      return 9;
1324
    }
1325
3
    return GenerateAndWriteSnapshotData(&snapshot_data, result.get());
1326
  }
1327
1328
  // Without --build-snapshot, we are in snapshot loading mode.
1329
5333
  return LoadSnapshotDataAndRun(&snapshot_data, result.get());
1330
}
1331
1332
370
int Stop(Environment* env) {
1333
370
  env->ExitEnv();
1334
370
  return 0;
1335
}
1336
1337
}  // namespace node
1338
1339
#if !HAVE_INSPECTOR
1340
void Initialize() {}
1341
1342
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1343
#endif  // !HAVE_INSPECTOR