GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 396 446 88.8 %
Date: 2022-09-11 04:22:34 Branches: 256 365 70.1 %

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_realm-inl.h"
40
#include "node_report.h"
41
#include "node_revert.h"
42
#include "node_snapshot_builder.h"
43
#include "node_v8_platform-inl.h"
44
#include "node_version.h"
45
46
#if HAVE_OPENSSL
47
#include "node_crypto.h"
48
#endif
49
50
#if defined(NODE_HAVE_I18N_SUPPORT)
51
#include "node_i18n.h"
52
#endif
53
54
#if HAVE_INSPECTOR
55
#include "inspector_agent.h"
56
#include "inspector_io.h"
57
#endif
58
59
#if NODE_USE_V8_PLATFORM
60
#include "libplatform/libplatform.h"
61
#endif  // NODE_USE_V8_PLATFORM
62
#include "v8-profiler.h"
63
64
#if HAVE_INSPECTOR
65
#include "inspector/worker_inspector.h"  // ParentInspectorHandle
66
#endif
67
68
#include "large_pages/node_large_page.h"
69
70
#if defined(__APPLE__) || defined(__linux__) || defined(_WIN32)
71
#define NODE_USE_V8_WASM_TRAP_HANDLER 1
72
#else
73
#define NODE_USE_V8_WASM_TRAP_HANDLER 0
74
#endif
75
76
#if NODE_USE_V8_WASM_TRAP_HANDLER
77
#if defined(_WIN32)
78
#include "v8-wasm-trap-handler-win.h"
79
#else
80
#include <atomic>
81
#include "v8-wasm-trap-handler-posix.h"
82
#endif
83
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
84
85
// ========== global C headers ==========
86
87
#include <fcntl.h>  // _O_RDWR
88
#include <sys/types.h>
89
90
#if defined(NODE_HAVE_I18N_SUPPORT)
91
#include <unicode/uvernum.h>
92
#include <unicode/utypes.h>
93
#endif
94
95
96
#if defined(LEAK_SANITIZER)
97
#include <sanitizer/lsan_interface.h>
98
#endif
99
100
#if defined(_MSC_VER)
101
#include <direct.h>
102
#include <io.h>
103
#define STDIN_FILENO 0
104
#else
105
#include <pthread.h>
106
#include <sys/resource.h>  // getrlimit, setrlimit
107
#include <termios.h>       // tcgetattr, tcsetattr
108
#include <unistd.h>        // STDIN_FILENO, STDERR_FILENO
109
#endif
110
111
// ========== global C++ headers ==========
112
113
#include <cerrno>
114
#include <climits>  // PATH_MAX
115
#include <csignal>
116
#include <cstdio>
117
#include <cstdlib>
118
#include <cstring>
119
120
#include <string>
121
#include <vector>
122
123
namespace node {
124
125
using builtins::BuiltinLoader;
126
127
using v8::EscapableHandleScope;
128
using v8::Isolate;
129
using v8::Local;
130
using v8::MaybeLocal;
131
using v8::Object;
132
using v8::V8;
133
using v8::Value;
134
135
namespace per_process {
136
137
// node_revert.h
138
// Bit flag used to track security reverts.
139
unsigned int reverted_cve = 0;
140
141
// util.h
142
// Tells whether the per-process V8::Initialize() is called and
143
// if it is safe to call v8::Isolate::TryGetCurrent().
144
bool v8_initialized = false;
145
146
// node_internals.h
147
// process-relative uptime base in nanoseconds, initialized in node::Start()
148
uint64_t node_start_time;
149
150
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
151
PVOID old_vectored_exception_handler;
152
#endif
153
154
// node_v8_platform-inl.h
155
struct V8Platform v8_platform;
156
}  // namespace per_process
157
158
// The section in the OpenSSL configuration file to be loaded.
159
const char* conf_section_name = STRINGIFY(NODE_OPENSSL_CONF_NAME);
160
161
#ifdef __POSIX__
162
void SignalExit(int signo, siginfo_t* info, void* ucontext) {
163
  ResetStdio();
164
  raise(signo);
165
}
166
#endif  // __POSIX__
167
168
#if HAVE_INSPECTOR
169
6286
int Environment::InitializeInspector(
170
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
171
12572
  std::string inspector_path;
172
6286
  bool is_main = !parent_handle;
173
6286
  if (parent_handle) {
174
726
    inspector_path = parent_handle->url();
175
726
    inspector_agent_->SetParentHandle(std::move(parent_handle));
176
  } else {
177
5560
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
178
  }
179
180
6286
  CHECK(!inspector_agent_->IsListening());
181
  // Inspector agent can't fail to start, but if it was configured to listen
182
  // right away on the websocket port and fails to bind/etc, this will return
183
  // false.
184
12572
  inspector_agent_->Start(inspector_path,
185
6286
                          options_->debug_options(),
186
12572
                          inspector_host_port(),
187
                          is_main);
188

6401
  if (options_->debug_options().inspector_enabled &&
189
115
      !inspector_agent_->IsListening()) {
190
5
    return 12;  // Signal internal error
191
  }
192
193
6281
  profiler::StartProfilers(this);
194
195
6281
  if (inspector_agent_->options().break_node_first_line) {
196
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
197
  }
198
199
6281
  return 0;
200
}
201
#endif  // HAVE_INSPECTOR
202
203
#define ATOMIC_WAIT_EVENTS(V)                                               \
204
  V(kStartWait,           "started")                                        \
205
  V(kWokenUp,             "was woken up by another thread")                 \
206
  V(kTimedOut,            "timed out")                                      \
207
  V(kTerminatedExecution, "was stopped by terminated execution")            \
208
  V(kAPIStopped,          "was stopped through the embedder API")           \
209
  V(kNotEqual,            "did not wait because the values mismatched")     \
210
211
8
static void AtomicsWaitCallback(Isolate::AtomicsWaitEvent event,
212
                                Local<v8::SharedArrayBuffer> array_buffer,
213
                                size_t offset_in_bytes, int64_t value,
214
                                double timeout_in_ms,
215
                                Isolate::AtomicsWaitWakeHandle* stop_handle,
216
                                void* data) {
217
8
  Environment* env = static_cast<Environment*>(data);
218
219
8
  const char* message = "(unknown event)";
220

8
  switch (event) {
221
#define V(key, msg)                         \
222
    case Isolate::AtomicsWaitEvent::key:    \
223
      message = msg;                        \
224
      break;
225
8
    ATOMIC_WAIT_EVENTS(V)
226
#undef V
227
  }
228
229
16
  fprintf(stderr,
230
          "(node:%d) [Thread %" PRIu64 "] Atomics.wait(%p + %zx, %" PRId64
231
          ", %.f) %s\n",
232
8
          static_cast<int>(uv_os_getpid()),
233
          env->thread_id(),
234
          array_buffer->Data(),
235
          offset_in_bytes,
236
          value,
237
          timeout_in_ms,
238
          message);
239
8
}
240
241
6257
void Environment::InitializeDiagnostics() {
242
6257
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
243
      Environment::BuildEmbedderGraph, this);
244
6257
  if (heap_snapshot_near_heap_limit_ > 0) {
245
1
    AddHeapSnapshotNearHeapLimitCallback();
246
  }
247
6257
  if (options_->trace_uncaught)
248
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
249
6257
  if (options_->trace_atomics_wait) {
250
2
    isolate_->SetAtomicsWaitCallback(AtomicsWaitCallback, this);
251
2
    AddCleanupHook([](void* data) {
252
2
      Environment* env = static_cast<Environment*>(data);
253
2
      env->isolate()->SetAtomicsWaitCallback(nullptr, nullptr);
254
2
    }, this);
255
  }
256
6257
}
257
258
static
259
6257
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
260
6257
  EscapableHandleScope scope(env->isolate());
261
6257
  CHECK_NOT_NULL(main_script_id);
262
6257
  Realm* realm = env->principal_realm();
263
264
  // Arguments must match the parameters specified in
265
  // BuiltinLoader::LookupAndCompile().
266
  std::vector<Local<Value>> arguments = {env->process_object(),
267
                                         env->builtin_module_require(),
268
                                         env->internal_binding_loader(),
269
31285
                                         env->primordials()};
270
271
  return scope.EscapeMaybe(
272
12249
      realm->ExecuteBootstrapper(main_script_id, &arguments));
273
}
274
275
6257
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
276
  InternalCallbackScope callback_scope(
277
      env,
278
      Object::New(env->isolate()),
279
      { 1, 0 },
280
12247
      InternalCallbackScope::kSkipAsyncHooks);
281
282
6257
  if (cb != nullptr) {
283
24
    EscapableHandleScope scope(env->isolate());
284
285
48
    if (StartExecution(env, "internal/main/environment").IsEmpty()) return {};
286
287
    StartExecutionCallbackInfo info = {
288
24
        env->process_object(),
289
24
        env->builtin_module_require(),
290
    };
291
292
46
    return scope.EscapeMaybe(cb(info));
293
  }
294
295
  // TODO(joyeecheung): move these conditions into JS land and let the
296
  // deserialize main function take precedence. For workers, we need to
297
  // move the pre-execution part into a different file that can be
298
  // reused when dealing with user-defined main functions.
299
12466
  if (!env->snapshot_deserialize_main().IsEmpty()) {
300
    return env->RunSnapshotDeserializeMain();
301
  }
302
303
6233
  if (env->worker_context() != nullptr) {
304
723
    return StartExecution(env, "internal/main/worker_thread");
305
  }
306
307
10755
  std::string first_argv;
308
5510
  if (env->argv().size() > 1) {
309
4967
    first_argv = env->argv()[1];
310
  }
311
312
5510
  if (first_argv == "inspect") {
313
38
    return StartExecution(env, "internal/main/inspect");
314
  }
315
316
5472
  if (per_process::cli_options->build_snapshot) {
317
1
    return StartExecution(env, "internal/main/mksnapshot");
318
  }
319
320
5471
  if (per_process::cli_options->print_help) {
321
2
    return StartExecution(env, "internal/main/print_help");
322
  }
323
324
325
5469
  if (env->options()->prof_process) {
326
1
    return StartExecution(env, "internal/main/prof_process");
327
  }
328
329
  // -e/--eval without -i/--interactive
330


5468
  if (env->options()->has_eval_string && !env->options()->force_repl) {
331
506
    return StartExecution(env, "internal/main/eval_string");
332
  }
333
334
4962
  if (env->options()->syntax_check_only) {
335
39
    return StartExecution(env, "internal/main/check_syntax");
336
  }
337
338
4923
  if (env->options()->test_runner) {
339
10
    return StartExecution(env, "internal/main/test_runner");
340
  }
341
342


4913
  if (env->options()->watch_mode && !first_argv.empty()) {
343
11
    return StartExecution(env, "internal/main/watch_mode");
344
  }
345
346

4902
  if (!first_argv.empty() && first_argv != "-") {
347
4856
    return StartExecution(env, "internal/main/run_main_module");
348
  }
349
350


46
  if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
351
28
    return StartExecution(env, "internal/main/repl");
352
  }
353
354
18
  return StartExecution(env, "internal/main/eval_stdin");
355
}
356
357
#ifdef __POSIX__
358
typedef void (*sigaction_cb)(int signo, siginfo_t* info, void* ucontext);
359
#endif
360
#if NODE_USE_V8_WASM_TRAP_HANDLER
361
#if defined(_WIN32)
362
static LONG TrapWebAssemblyOrContinue(EXCEPTION_POINTERS* exception) {
363
  if (v8::TryHandleWebAssemblyTrapWindows(exception)) {
364
    return EXCEPTION_CONTINUE_EXECUTION;
365
  }
366
  return EXCEPTION_CONTINUE_SEARCH;
367
}
368
#else
369
static std::atomic<sigaction_cb> previous_sigsegv_action;
370
371
6
void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) {
372
6
  if (!v8::TryHandleWebAssemblyTrapPosix(signo, info, ucontext)) {
373
6
    sigaction_cb prev = previous_sigsegv_action.load();
374
6
    if (prev != nullptr) {
375
6
      prev(signo, info, ucontext);
376
    } else {
377
      // Reset to the default signal handler, i.e. cause a hard crash.
378
      struct sigaction sa;
379
      memset(&sa, 0, sizeof(sa));
380
      sa.sa_handler = SIG_DFL;
381
      CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
382
383
      ResetStdio();
384
      raise(signo);
385
    }
386
  }
387
6
}
388
#endif  // defined(_WIN32)
389
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
390
391
#ifdef __POSIX__
392
17878
void RegisterSignalHandler(int signal,
393
                           sigaction_cb handler,
394
                           bool reset_handler) {
395
17878
  CHECK_NOT_NULL(handler);
396
#if NODE_USE_V8_WASM_TRAP_HANDLER
397
17878
  if (signal == SIGSEGV) {
398
4
    CHECK(previous_sigsegv_action.is_lock_free());
399
4
    CHECK(!reset_handler);
400
4
    previous_sigsegv_action.store(handler);
401
4
    return;
402
  }
403
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
404
  struct sigaction sa;
405
17874
  memset(&sa, 0, sizeof(sa));
406
17874
  sa.sa_sigaction = handler;
407
17874
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
408
17874
  sigfillset(&sa.sa_mask);
409
17874
  CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
410
}
411
#endif  // __POSIX__
412
413
#ifdef __POSIX__
414
static struct {
415
  int flags;
416
  bool isatty;
417
  struct stat stat;
418
  struct termios termios;
419
} stdio[1 + STDERR_FILENO];
420
#endif  // __POSIX__
421
422
10537
void ResetSignalHandlers() {
423
#ifdef __POSIX__
424
  // Restore signal dispositions, the parent process may have changed them.
425
  struct sigaction act;
426
10537
  memset(&act, 0, sizeof(act));
427
428
  // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
429
  // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
430
  // Counting up to SIGRTMIN doesn't work for the same reason.
431
337184
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
432

326647
    if (nr == SIGKILL || nr == SIGSTOP)
433
21074
      continue;
434

305573
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
435
305573
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
436
  }
437
#endif  // __POSIX__
438
10537
}
439
440
static std::atomic<uint64_t> init_process_flags = 0;
441
442
5583
static void PlatformInit(ProcessInitializationFlags::Flags flags) {
443
  // init_process_flags is accessed in ResetStdio(),
444
  // which can be called from signal handlers.
445
5583
  CHECK(init_process_flags.is_lock_free());
446
  init_process_flags.store(flags);
447
448
5583
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
449
5583
    atexit(ResetStdio);
450
  }
451
452
#ifdef __POSIX__
453
5583
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
454
    // Disable stdio buffering, it interacts poorly with printf()
455
    // calls elsewhere in the program (e.g., any logging from V8.)
456
5583
    setvbuf(stdout, nullptr, _IONBF, 0);
457
5583
    setvbuf(stderr, nullptr, _IONBF, 0);
458
459
    // Make sure file descriptors 0-2 are valid before we start logging
460
    // anything.
461
22332
    for (auto& s : stdio) {
462
16749
      const int fd = &s - stdio;
463
16749
      if (fstat(fd, &s.stat) == 0) continue;
464
      // Anything but EBADF means something is seriously wrong.  We don't
465
      // have to special-case EINTR, fstat() is not interruptible.
466
2
      if (errno != EBADF) ABORT();
467
2
      if (fd != open("/dev/null", O_RDWR)) ABORT();
468
2
      if (fstat(fd, &s.stat) != 0) ABORT();
469
    }
470
  }
471
472
5583
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
473
#if HAVE_INSPECTOR
474
    sigset_t sigmask;
475
5583
    sigemptyset(&sigmask);
476
5583
    sigaddset(&sigmask, SIGUSR1);
477
5583
    const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
478
5583
    CHECK_EQ(err, 0);
479
#endif  // HAVE_INSPECTOR
480
481
5583
    ResetSignalHandlers();
482
  }
483
484
5583
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
485
    // Record the state of the stdio file descriptors so we can restore it
486
    // on exit.  Needs to happen before installing signal handlers because
487
    // they make use of that information.
488
22332
    for (auto& s : stdio) {
489
16749
      const int fd = &s - stdio;
490
      int err;
491
492
      do {
493
16749
        s.flags = fcntl(fd, F_GETFL);
494

16749
      } while (s.flags == -1 && errno == EINTR);  // NOLINT
495
16749
      CHECK_NE(s.flags, -1);
496
497
16749
      if (uv_guess_handle(fd) != UV_TTY) continue;
498
120
      s.isatty = true;
499
500
      do {
501
120
        err = tcgetattr(fd, &s.termios);
502

120
      } while (err == -1 && errno == EINTR);  // NOLINT
503
120
      CHECK_EQ(err, 0);
504
    }
505
  }
506
507
5583
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
508
5583
    RegisterSignalHandler(SIGINT, SignalExit, true);
509
5583
    RegisterSignalHandler(SIGTERM, SignalExit, true);
510
511
#if NODE_USE_V8_WASM_TRAP_HANDLER
512
#if defined(_WIN32)
513
    {
514
      constexpr ULONG first = TRUE;
515
      per_process::old_vectored_exception_handler =
516
          AddVectoredExceptionHandler(first, TrapWebAssemblyOrContinue);
517
    }
518
#else
519
    // Tell V8 to disable emitting WebAssembly
520
    // memory bounds checks. This means that we have
521
    // to catch the SIGSEGV in TrapWebAssemblyOrContinue
522
    // and pass the signal context to V8.
523
    {
524
      struct sigaction sa;
525
5583
      memset(&sa, 0, sizeof(sa));
526
5583
      sa.sa_sigaction = TrapWebAssemblyOrContinue;
527
5583
      sa.sa_flags = SA_SIGINFO;
528
5583
      CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
529
    }
530
#endif  // defined(_WIN32)
531
5583
    V8::EnableWebAssemblyTrapHandler(false);
532
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
533
  }
534
535
5583
  if (!(flags & ProcessInitializationFlags::kNoAdjustResourceLimits)) {
536
    // Raise the open file descriptor limit.
537
    struct rlimit lim;
538

5583
    if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
539
      // Do a binary search for the limit.
540
      rlim_t min = lim.rlim_cur;
541
      rlim_t max = 1 << 20;
542
      // But if there's a defined upper bound, don't search, just set it.
543
      if (lim.rlim_max != RLIM_INFINITY) {
544
        min = lim.rlim_max;
545
        max = lim.rlim_max;
546
      }
547
      do {
548
        lim.rlim_cur = min + (max - min) / 2;
549
        if (setrlimit(RLIMIT_NOFILE, &lim)) {
550
          max = lim.rlim_cur;
551
        } else {
552
          min = lim.rlim_cur;
553
        }
554
      } while (min + 1 < max);
555
    }
556
  }
557
#endif  // __POSIX__
558
#ifdef _WIN32
559
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
560
    for (int fd = 0; fd <= 2; ++fd) {
561
      auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
562
      if (handle == INVALID_HANDLE_VALUE ||
563
          GetFileType(handle) == FILE_TYPE_UNKNOWN) {
564
        // Ignore _close result. If it fails or not depends on used Windows
565
        // version. We will just check _open result.
566
        _close(fd);
567
        if (fd != _open("nul", _O_RDWR)) ABORT();
568
      }
569
    }
570
  }
571
#endif  // _WIN32
572
5583
}
573
574
// Safe to call more than once and from signal handlers.
575
10559
void ResetStdio() {
576
21118
  if (init_process_flags.load() &
577
10559
      ProcessInitializationFlags::kNoStdioInitialization) {
578
    return;
579
  }
580
581
10559
  uv_tty_reset_mode();
582
#ifdef __POSIX__
583
42236
  for (auto& s : stdio) {
584
31677
    const int fd = &s - stdio;
585
586
    struct stat tmp;
587
31677
    if (-1 == fstat(fd, &tmp)) {
588
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
589
6
      continue;
590
    }
591
592
31677
    bool is_same_file =
593

31677
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
594
31677
    if (!is_same_file) continue;  // Program reopened file descriptor.
595
596
    int flags;
597
    do
598
31671
      flags = fcntl(fd, F_GETFL);
599

31671
    while (flags == -1 && errno == EINTR);  // NOLINT
600
31671
    CHECK_NE(flags, -1);
601
602
    // Restore the O_NONBLOCK flag if it changed.
603
31671
    if (O_NONBLOCK & (flags ^ s.flags)) {
604
1477
      flags &= ~O_NONBLOCK;
605
1477
      flags |= s.flags & O_NONBLOCK;
606
607
      int err;
608
      do
609
1477
        err = fcntl(fd, F_SETFL, flags);
610

1477
      while (err == -1 && errno == EINTR);  // NOLINT
611
1477
      CHECK_NE(err, -1);
612
    }
613
614
31671
    if (s.isatty) {
615
      sigset_t sa;
616
      int err;
617
618
      // We might be a background job that doesn't own the TTY so block SIGTTOU
619
      // before making the tcsetattr() call, otherwise that signal suspends us.
620
228
      sigemptyset(&sa);
621
228
      sigaddset(&sa, SIGTTOU);
622
623
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
624
      do
625
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
626

228
      while (err == -1 && errno == EINTR);  // NOLINT
627
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
628
629
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
630
      // tcsetattr will fail with err == -1 and errno == EPERM.
631


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
632
    }
633
  }
634
#endif  // __POSIX__
635
}
636
637
638
11030
int ProcessGlobalArgs(std::vector<std::string>* args,
639
                      std::vector<std::string>* exec_args,
640
                      std::vector<std::string>* errors,
641
                      OptionEnvvarSettings settings) {
642
  // Parse a few arguments which are specific to Node.
643
22060
  std::vector<std::string> v8_args;
644
645
22060
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
646
11030
  options_parser::Parse(
647
      args,
648
      exec_args,
649
      &v8_args,
650
      per_process::cli_options.get(),
651
      settings,
652
      errors);
653
654
11030
  if (!errors->empty()) return 9;
655
656
21964
  std::string revert_error;
657
10982
  for (const std::string& cve : per_process::cli_options->security_reverts) {
658
1
    Revert(cve.c_str(), &revert_error);
659
1
    if (!revert_error.empty()) {
660
1
      errors->emplace_back(std::move(revert_error));
661
1
      return 12;
662
    }
663
  }
664
665
21961
  if (per_process::cli_options->disable_proto != "delete" &&
666

21961
      per_process::cli_options->disable_proto != "throw" &&
667
10979
      per_process::cli_options->disable_proto != "") {
668
    errors->emplace_back("invalid mode passed to --disable-proto");
669
    return 12;
670
  }
671
672
  // TODO(aduh95): remove this when the harmony-import-assertions flag
673
  // is removed in V8.
674
21962
  if (std::find(v8_args.begin(), v8_args.end(),
675
10981
                "--no-harmony-import-assertions") == v8_args.end()) {
676
10981
    v8_args.emplace_back("--harmony-import-assertions");
677
  }
678
679
21962
  auto env_opts = per_process::cli_options->per_isolate->per_env;
680
21962
  if (std::find(v8_args.begin(), v8_args.end(),
681

21944
                "--abort-on-uncaught-exception") != v8_args.end() ||
682
10981
      std::find(v8_args.begin(), v8_args.end(),
683
21944
                "--abort_on_uncaught_exception") != v8_args.end()) {
684
21
    env_opts->abort_on_uncaught_exception = true;
685
  }
686
687
#ifdef __POSIX__
688
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
689
  // performance penalty of frequent EINTR wakeups when the profiler is running.
690
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
691
10981
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
692
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
693
  }
694
#endif
695
696
21962
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
697
10981
  if (v8_args.size() > 0) {
698
33084
    for (size_t i = 0; i < v8_args.size(); ++i)
699
22103
      v8_args_as_char_ptr[i] = &v8_args[i][0];
700
10981
    int argc = v8_args.size();
701
10981
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
702
10981
    v8_args_as_char_ptr.resize(argc);
703
  }
704
705
  // Anything that's still in v8_argv is not a V8 or a node option.
706
10982
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
707
1
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
708
709
10981
  if (v8_args_as_char_ptr.size() > 1) return 9;
710
711
10980
  return 0;
712
}
713
714
static std::atomic_bool init_called{false};
715
716
// TODO(addaleax): Turn this into a wrapper around InitializeOncePerProcess()
717
// (with the corresponding additional flags set), then eventually remove this.
718
5584
int InitializeNodeWithArgs(std::vector<std::string>* argv,
719
                           std::vector<std::string>* exec_argv,
720
                           std::vector<std::string>* errors,
721
                           ProcessInitializationFlags::Flags flags) {
722
  // Make sure InitializeNodeWithArgs() is called only once.
723
5584
  CHECK(!init_called.exchange(true));
724
725
  // Initialize node_start_time to get relative uptime.
726
5584
  per_process::node_start_time = uv_hrtime();
727
728
  // Register built-in modules
729
5584
  binding::RegisterBuiltinModules();
730
731
  // Make inherited handles noninheritable.
732
5584
  if (!(flags & ProcessInitializationFlags::kEnableStdioInheritance) &&
733
5584
      !(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
734
5584
    uv_disable_stdio_inheritance();
735
  }
736
737
  // Cache the original command line to be
738
  // used in diagnostic reports.
739
5584
  per_process::cli_options->cmdline = *argv;
740
741
#if defined(NODE_V8_OPTIONS)
742
  // Should come before the call to V8::SetFlagsFromCommandLine()
743
  // so the user can disable a flag --foo at run-time by passing
744
  // --no_foo from the command line.
745
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
746
#endif
747
748
5584
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
749
750
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
751
5584
  if (!(flags & ProcessInitializationFlags::kDisableNodeOptionsEnv)) {
752
5584
    std::string node_options;
753
754
5584
    if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
755
      std::vector<std::string> env_argv =
756
5463
          ParseNodeOptionsEnvVar(node_options, errors);
757
758
5463
      if (!errors->empty()) return 9;
759
760
      // [0] is expected to be the program name, fill it in from the real argv.
761
5463
      env_argv.insert(env_argv.begin(), argv->at(0));
762
763
5463
      const int exit_code = ProcessGlobalArgs(&env_argv,
764
                                              nullptr,
765
                                              errors,
766
                                              kAllowedInEnvironment);
767
5463
      if (exit_code != 0) return exit_code;
768
    }
769
  }
770
#endif
771
772
5567
  if (!(flags & ProcessInitializationFlags::kDisableCLIOptions)) {
773
5567
    const int exit_code = ProcessGlobalArgs(argv,
774
                                            exec_argv,
775
                                            errors,
776
                                            kDisallowedInEnvironment);
777
5567
    if (exit_code != 0) return exit_code;
778
  }
779
780
  // Set the process.title immediately after processing argv if --title is set.
781
5534
  if (!per_process::cli_options->title.empty())
782
2
    uv_set_process_title(per_process::cli_options->title.c_str());
783
784
#if defined(NODE_HAVE_I18N_SUPPORT)
785
5534
  if (!(flags & ProcessInitializationFlags::kNoICU)) {
786
    // If the parameter isn't given, use the env variable.
787
5534
    if (per_process::cli_options->icu_data_dir.empty())
788
11068
      credentials::SafeGetenv("NODE_ICU_DATA",
789
5534
                              &per_process::cli_options->icu_data_dir);
790
791
#ifdef NODE_ICU_DEFAULT_DATA_DIR
792
    // If neither the CLI option nor the environment variable was specified,
793
    // fall back to the configured default
794
    if (per_process::cli_options->icu_data_dir.empty()) {
795
      // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
796
      // file and can be read.
797
      static const char full_path[] =
798
          NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
799
800
      FILE* f = fopen(full_path, "rb");
801
802
      if (f != nullptr) {
803
        fclose(f);
804
        per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
805
      }
806
    }
807
#endif  // NODE_ICU_DEFAULT_DATA_DIR
808
809
    // Initialize ICU.
810
    // If icu_data_dir is empty here, it will load the 'minimal' data.
811
5534
    if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
812
      errors->push_back("could not initialize ICU "
813
                        "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
814
      return 9;
815
    }
816
5534
    per_process::metadata.versions.InitializeIntlVersions();
817
  }
818
819
# ifndef __POSIX__
820
  std::string tz;
821
  if (credentials::SafeGetenv("TZ", &tz) && !tz.empty()) {
822
    i18n::SetDefaultTimeZone(tz.c_str());
823
  }
824
# endif
825
826
#endif  // defined(NODE_HAVE_I18N_SUPPORT)
827
828
  // We should set node_is_initialized here instead of in node::Start,
829
  // otherwise embedders using node::Init to initialize everything will not be
830
  // able to set it and native addons will not load for them.
831
5534
  node_is_initialized = true;
832
5534
  return 0;
833
}
834
835
5583
std::unique_ptr<InitializationResult> InitializeOncePerProcess(
836
    const std::vector<std::string>& args,
837
    ProcessInitializationFlags::Flags flags) {
838
11166
  auto result = std::make_unique<InitializationResultImpl>();
839
5583
  result->args_ = args;
840
841
5583
  if (!(flags & ProcessInitializationFlags::kNoParseGlobalDebugVariables)) {
842
    // Initialized the enabled list for Debug() calls with system
843
    // environment variables.
844
5583
    per_process::enabled_debug_list.Parse();
845
  }
846
847
5583
  PlatformInit(flags);
848
849
  // This needs to run *before* V8::Initialize().
850
  {
851
5583
    result->exit_code_ = InitializeNodeWithArgs(
852
5583
        &result->args_, &result->exec_args_, &result->errors_, flags);
853
5583
    if (result->exit_code() != 0) {
854
50
      result->early_return_ = true;
855
50
      return result;
856
    }
857
  }
858
859

16598
  if (!(flags & ProcessInitializationFlags::kNoUseLargePages) &&
860
11065
      (per_process::cli_options->use_largepages == "on" ||
861
5532
       per_process::cli_options->use_largepages == "silent")) {
862
1
    int lp_result = node::MapStaticCodeToLargePages();
863

1
    if (per_process::cli_options->use_largepages == "on" && lp_result != 0) {
864
      result->errors_.emplace_back(node::LargePagesError(lp_result));
865
    }
866
  }
867
868
5533
  if (!(flags & ProcessInitializationFlags::kNoPrintHelpOrVersionOutput)) {
869
5533
    if (per_process::cli_options->print_version) {
870
3
      printf("%s\n", NODE_VERSION);
871
3
      result->exit_code_ = 0;
872
3
      result->early_return_ = true;
873
3
      return result;
874
    }
875
876
5530
    if (per_process::cli_options->print_bash_completion) {
877
2
      std::string completion = options_parser::GetBashCompletion();
878
1
      printf("%s\n", completion.c_str());
879
1
      result->exit_code_ = 0;
880
1
      result->early_return_ = true;
881
1
      return result;
882
    }
883
884
5529
    if (per_process::cli_options->print_v8_help) {
885
      V8::SetFlagsFromString("--help", static_cast<size_t>(6));
886
      result->exit_code_ = 0;
887
      result->early_return_ = true;
888
      return result;
889
    }
890
  }
891
892
5529
  if (!(flags & ProcessInitializationFlags::kNoInitOpenSSL)) {
893
#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
894
2
    auto GetOpenSSLErrorString = []() -> std::string {
895
2
      std::string ret;
896
2
      ERR_print_errors_cb(
897
2
          [](const char* str, size_t len, void* opaque) {
898
2
            std::string* ret = static_cast<std::string*>(opaque);
899
2
            ret->append(str, len);
900
2
            ret->append("\n");
901
2
            return 0;
902
          },
903
          static_cast<void*>(&ret));
904
2
      return ret;
905
    };
906
907
    {
908
11058
      std::string extra_ca_certs;
909
5529
      if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
910
4
        crypto::UseExtraCaCerts(extra_ca_certs);
911
    }
912
    // In the case of FIPS builds we should make sure
913
    // the random source is properly initialized first.
914
#if OPENSSL_VERSION_MAJOR >= 3
915
    // Call OPENSSL_init_crypto to initialize OPENSSL_INIT_LOAD_CONFIG to
916
    // avoid the default behavior where errors raised during the parsing of the
917
    // OpenSSL configuration file are not propagated and cannot be detected.
918
    //
919
    // If FIPS is configured the OpenSSL configuration file will have an
920
    // .include pointing to the fipsmodule.cnf file generated by the openssl
921
    // fipsinstall command. If the path to this file is incorrect no error
922
    // will be reported.
923
    //
924
    // For Node.js this will mean that EntropySource will be called by V8 as
925
    // part of its initialization process, and EntropySource will in turn call
926
    // CheckEntropy. CheckEntropy will call RAND_status which will now always
927
    // return 0, leading to an endless loop and the node process will appear to
928
    // hang/freeze.
929
930
    // Passing NULL as the config file will allow the default openssl.cnf file
931
    // to be loaded, but the default section in that file will not be used,
932
    // instead only the section that matches the value of conf_section_name
933
    // will be read from the default configuration file.
934
5529
    const char* conf_file = nullptr;
935
    // To allow for using the previous default where the 'openssl_conf' appname
936
    // was used, the command line option 'openssl-shared-config' can be used to
937
    // force the old behavior.
938
5529
    if (per_process::cli_options->openssl_shared_config) {
939
      conf_section_name = "openssl_conf";
940
    }
941
    // Use OPENSSL_CONF environment variable is set.
942
5529
    std::string env_openssl_conf;
943
5529
    credentials::SafeGetenv("OPENSSL_CONF", &env_openssl_conf);
944
5529
    if (!env_openssl_conf.empty()) {
945
1
      conf_file = env_openssl_conf.c_str();
946
    }
947
    // Use --openssl-conf command line option if specified.
948
5529
    if (!per_process::cli_options->openssl_config.empty()) {
949
3
      conf_file = per_process::cli_options->openssl_config.c_str();
950
    }
951
952
5529
    OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
953
5529
    OPENSSL_INIT_set_config_filename(settings, conf_file);
954
5529
    OPENSSL_INIT_set_config_appname(settings, conf_section_name);
955
5529
    OPENSSL_INIT_set_config_file_flags(settings,
956
                                       CONF_MFLAGS_IGNORE_MISSING_FILE);
957
958
5529
    OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
959
5529
    OPENSSL_INIT_free(settings);
960
961
5529
    if (ERR_peek_error() != 0) {
962
      // XXX: ERR_GET_REASON does not return something that is
963
      // useful as an exit code at all.
964
      result->exit_code_ = ERR_GET_REASON(ERR_peek_error());
965
      result->early_return_ = true;
966
      result->errors_.emplace_back("OpenSSL configuration error:\n" +
967
                                   GetOpenSSLErrorString());
968
      return result;
969
    }
970
#else  // OPENSSL_VERSION_MAJOR < 3
971
    if (FIPS_mode()) {
972
      OPENSSL_init();
973
    }
974
#endif
975
5529
    if (!crypto::ProcessFipsOptions()) {
976
      // XXX: ERR_GET_REASON does not return something that is
977
      // useful as an exit code at all.
978
2
      result->exit_code_ = ERR_GET_REASON(ERR_peek_error());
979
2
      result->early_return_ = true;
980
2
      result->errors_.emplace_back(
981
4
          "OpenSSL error when trying to enable FIPS:\n" +
982
6
          GetOpenSSLErrorString());
983
2
      return result;
984
    }
985
986
    // Seed V8's PRNG from OpenSSL's pool. This is recommended by V8 and a
987
    // potentially better source of randomness than what V8 uses by default, but
988
    // it does not guarantee that pseudo-random values produced by V8 will be
989
    // cryptograhically secure.
990
5527
    V8::SetEntropySource(crypto::EntropySource);
991
#endif  // HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
992
  }
993
994
5527
  if (!(flags & ProcessInitializationFlags::kNoInitializeNodeV8Platform)) {
995
5520
    per_process::v8_platform.Initialize(
996
5520
        static_cast<int>(per_process::cli_options->v8_thread_pool_size));
997
5520
    result->platform_ = per_process::v8_platform.Platform();
998
  }
999
1000
5527
  if (!(flags & ProcessInitializationFlags::kNoInitializeV8)) {
1001
    V8::Initialize();
1002
  }
1003
1004
5527
  performance::performance_v8_start = PERFORMANCE_NOW();
1005
5527
  per_process::v8_initialized = true;
1006
1007
5527
  return result;
1008
}
1009
1010
4954
void TearDownOncePerProcess() {
1011
4954
  const uint64_t flags = init_process_flags.load();
1012
4954
  ResetStdio();
1013
4954
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
1014
4954
    ResetSignalHandlers();
1015
  }
1016
1017
4954
  per_process::v8_initialized = false;
1018
4954
  if (!(flags & ProcessInitializationFlags::kNoInitializeV8)) {
1019
4949
    V8::Dispose();
1020
  }
1021
1022
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1023
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
1024
    RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1025
  }
1026
#endif
1027
1028
4954
  if (!(flags & ProcessInitializationFlags::kNoInitializeNodeV8Platform)) {
1029
4949
    V8::DisposePlatform();
1030
    // uv_run cannot be called from the time before the beforeExit callback
1031
    // runs until the program exits unless the event loop has any referenced
1032
    // handles after beforeExit terminates. This prevents unrefed timers
1033
    // that happen to terminate during shutdown from being run unsafely.
1034
    // Since uv_run cannot be called, uv_async handles held by the platform
1035
    // will never be fully cleaned up.
1036
4949
    per_process::v8_platform.Dispose();
1037
  }
1038
4954
}
1039
1040
10020
InitializationResult::~InitializationResult() {}
1041
10020
InitializationResultImpl::~InitializationResultImpl() {}
1042
1043
3
int GenerateAndWriteSnapshotData(const SnapshotData** snapshot_data_ptr,
1044
                                 const InitializationResult* result) {
1045
3
  int exit_code = result->exit_code();
1046
  // nullptr indicates there's no snapshot data.
1047
  DCHECK_NULL(*snapshot_data_ptr);
1048
1049
  // node:embedded_snapshot_main indicates that we are using the
1050
  // embedded snapshot and we are not supposed to clean it up.
1051
3
  if (result->args()[1] == "node:embedded_snapshot_main") {
1052
2
    *snapshot_data_ptr = SnapshotBuilder::GetEmbeddedSnapshotData();
1053
2
    if (*snapshot_data_ptr == nullptr) {
1054
      // The Node.js binary is built without embedded snapshot
1055
      fprintf(stderr,
1056
              "node:embedded_snapshot_main was specified as snapshot "
1057
              "entry point but Node.js was built without embedded "
1058
              "snapshot.\n");
1059
      exit_code = 1;
1060
      return exit_code;
1061
    }
1062
  } else {
1063
    // Otherwise, load and run the specified main script.
1064
    std::unique_ptr<SnapshotData> generated_data =
1065
1
        std::make_unique<SnapshotData>();
1066
2
    exit_code = node::SnapshotBuilder::Generate(
1067
2
        generated_data.get(), result->args(), result->exec_args());
1068
1
    if (exit_code == 0) {
1069
      *snapshot_data_ptr = generated_data.release();
1070
    } else {
1071
1
      return exit_code;
1072
    }
1073
  }
1074
1075
  // Get the path to write the snapshot blob to.
1076
2
  std::string snapshot_blob_path;
1077
2
  if (!per_process::cli_options->snapshot_blob.empty()) {
1078
1
    snapshot_blob_path = per_process::cli_options->snapshot_blob;
1079
  } else {
1080
    // Defaults to snapshot.blob in the current working directory.
1081
1
    snapshot_blob_path = std::string("snapshot.blob");
1082
  }
1083
1084
2
  FILE* fp = fopen(snapshot_blob_path.c_str(), "wb");
1085
2
  if (fp != nullptr) {
1086
2
    (*snapshot_data_ptr)->ToBlob(fp);
1087
2
    fclose(fp);
1088
  } else {
1089
    fprintf(stderr,
1090
            "Cannot open %s for writing a snapshot.\n",
1091
            snapshot_blob_path.c_str());
1092
    exit_code = 1;
1093
  }
1094
2
  return exit_code;
1095
}
1096
1097
5510
int LoadSnapshotDataAndRun(const SnapshotData** snapshot_data_ptr,
1098
                           const InitializationResult* result) {
1099
5510
  int exit_code = result->exit_code();
1100
  // nullptr indicates there's no snapshot data.
1101
  DCHECK_NULL(*snapshot_data_ptr);
1102
  // --snapshot-blob indicates that we are reading a customized snapshot.
1103
5510
  if (!per_process::cli_options->snapshot_blob.empty()) {
1104
3
    std::string filename = per_process::cli_options->snapshot_blob;
1105
3
    FILE* fp = fopen(filename.c_str(), "rb");
1106
3
    if (fp == nullptr) {
1107
1
      fprintf(stderr, "Cannot open %s", filename.c_str());
1108
1
      exit_code = 1;
1109
1
      return exit_code;
1110
    }
1111
2
    std::unique_ptr<SnapshotData> read_data = std::make_unique<SnapshotData>();
1112
2
    if (!SnapshotData::FromBlob(read_data.get(), fp)) {
1113
      // If we fail to read the customized snapshot, simply exit with 1.
1114
      exit_code = 1;
1115
      return exit_code;
1116
    }
1117
2
    *snapshot_data_ptr = read_data.release();
1118
2
    fclose(fp);
1119
5507
  } else if (per_process::cli_options->node_snapshot) {
1120
    // If --snapshot-blob is not specified, we are reading the embedded
1121
    // snapshot, but we will skip it if --no-node-snapshot is specified.
1122
    const node::SnapshotData* read_data =
1123
5505
        SnapshotBuilder::GetEmbeddedSnapshotData();
1124

5505
    if (read_data != nullptr && read_data->Check()) {
1125
      // If we fail to read the embedded snapshot, treat it as if Node.js
1126
      // was built without one.
1127
5505
      *snapshot_data_ptr = read_data;
1128
    }
1129
  }
1130
1131
5509
  if ((*snapshot_data_ptr) != nullptr) {
1132
5507
    BuiltinLoader::RefreshCodeCache((*snapshot_data_ptr)->code_cache);
1133
  }
1134
  NodeMainInstance main_instance(*snapshot_data_ptr,
1135
                                 uv_default_loop(),
1136
5509
                                 per_process::v8_platform.Platform(),
1137
5509
                                 result->args(),
1138
11018
                                 result->exec_args());
1139
5509
  exit_code = main_instance.Run();
1140
4938
  return exit_code;
1141
}
1142
1143
5570
int Start(int argc, char** argv) {
1144
5570
  CHECK_GT(argc, 0);
1145
1146
  // Hack around with the argv pointer. Used for process.title = "blah".
1147
5570
  argv = uv_setup_args(argc, argv);
1148
1149
  std::unique_ptr<InitializationResult> result =
1150
16139
      InitializeOncePerProcess(std::vector<std::string>(argv, argv + argc));
1151
5623
  for (const std::string& error : result->errors()) {
1152
53
    FPrintF(stderr, "%s: %s\n", result->args().at(0), error);
1153
  }
1154
5570
  if (result->early_return()) {
1155
56
    return result->exit_code();
1156
  }
1157
1158
  DCHECK_EQ(result->exit_code(), 0);
1159
5514
  const SnapshotData* snapshot_data = nullptr;
1160
1161
4943
  auto cleanup_process = OnScopeLeave([&]() {
1162
4943
    TearDownOncePerProcess();
1163
1164
4943
    if (snapshot_data != nullptr &&
1165
4938
        snapshot_data->data_ownership == SnapshotData::DataOwnership::kOwned) {
1166
2
      delete snapshot_data;
1167
    }
1168
10457
  });
1169
1170
5514
  uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1171
1172
  // --build-snapshot indicates that we are in snapshot building mode.
1173
5514
  if (per_process::cli_options->build_snapshot) {
1174
4
    if (result->args().size() < 2) {
1175
1
      fprintf(stderr,
1176
              "--build-snapshot must be used with an entry point script.\n"
1177
              "Usage: node --build-snapshot /path/to/entry.js\n");
1178
1
      return 9;
1179
    }
1180
3
    return GenerateAndWriteSnapshotData(&snapshot_data, result.get());
1181
  }
1182
1183
  // Without --build-snapshot, we are in snapshot loading mode.
1184
5510
  return LoadSnapshotDataAndRun(&snapshot_data, result.get());
1185
}
1186
1187
372
int Stop(Environment* env) {
1188
372
  env->ExitEnv();
1189
372
  return 0;
1190
}
1191
1192
}  // namespace node
1193
1194
#if !HAVE_INSPECTOR
1195
void Initialize() {}
1196
1197
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1198
#endif  // !HAVE_INSPECTOR