GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 394 444 88.7 %
Date: 2022-09-02 04:23:42 Branches: 250 357 70.0 %

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
6126
int Environment::InitializeInspector(
170
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
171
12252
  std::string inspector_path;
172
6126
  bool is_main = !parent_handle;
173
6126
  if (parent_handle) {
174
715
    inspector_path = parent_handle->url();
175
715
    inspector_agent_->SetParentHandle(std::move(parent_handle));
176
  } else {
177
5411
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
178
  }
179
180
6126
  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
12252
  inspector_agent_->Start(inspector_path,
185
6126
                          options_->debug_options(),
186
12252
                          inspector_host_port(),
187
                          is_main);
188

6207
  if (options_->debug_options().inspector_enabled &&
189
81
      !inspector_agent_->IsListening()) {
190
5
    return 12;  // Signal internal error
191
  }
192
193
6121
  profiler::StartProfilers(this);
194
195
6121
  if (inspector_agent_->options().break_node_first_line) {
196
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
197
  }
198
199
6121
  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
6098
void Environment::InitializeDiagnostics() {
242
6098
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
243
      Environment::BuildEmbedderGraph, this);
244
6098
  if (options_->heap_snapshot_near_heap_limit > 0) {
245
1
    isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
246
                                       this);
247
  }
248
6098
  if (options_->trace_uncaught)
249
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
250
6098
  if (options_->trace_atomics_wait) {
251
2
    isolate_->SetAtomicsWaitCallback(AtomicsWaitCallback, this);
252
2
    AddCleanupHook([](void* data) {
253
2
      Environment* env = static_cast<Environment*>(data);
254
2
      env->isolate()->SetAtomicsWaitCallback(nullptr, nullptr);
255
2
    }, this);
256
  }
257
6098
}
258
259
static
260
6098
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
261
6098
  EscapableHandleScope scope(env->isolate());
262
6098
  CHECK_NOT_NULL(main_script_id);
263
6098
  Realm* realm = env->principal_realm();
264
265
  // Arguments must match the parameters specified in
266
  // BuiltinLoader::LookupAndCompile().
267
  std::vector<Local<Value>> arguments = {env->process_object(),
268
                                         env->builtin_module_require(),
269
                                         env->internal_binding_loader(),
270
30490
                                         env->primordials()};
271
272
  return scope.EscapeMaybe(
273
11926
      realm->ExecuteBootstrapper(main_script_id, &arguments));
274
}
275
276
6098
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
277
  InternalCallbackScope callback_scope(
278
      env,
279
      Object::New(env->isolate()),
280
      { 1, 0 },
281
11924
      InternalCallbackScope::kSkipAsyncHooks);
282
283
6098
  if (cb != nullptr) {
284
24
    EscapableHandleScope scope(env->isolate());
285
286
48
    if (StartExecution(env, "internal/main/environment").IsEmpty()) return {};
287
288
    StartExecutionCallbackInfo info = {
289
24
        env->process_object(),
290
24
        env->builtin_module_require(),
291
    };
292
293
46
    return scope.EscapeMaybe(cb(info));
294
  }
295
296
  // TODO(joyeecheung): move these conditions into JS land and let the
297
  // deserialize main function take precedence. For workers, we need to
298
  // move the pre-execution part into a different file that can be
299
  // reused when dealing with user-defined main functions.
300
12148
  if (!env->snapshot_deserialize_main().IsEmpty()) {
301
    return env->RunSnapshotDeserializeMain();
302
  }
303
304
6074
  if (env->worker_context() != nullptr) {
305
713
    return StartExecution(env, "internal/main/worker_thread");
306
  }
307
308
10452
  std::string first_argv;
309
5361
  if (env->argv().size() > 1) {
310
4823
    first_argv = env->argv()[1];
311
  }
312
313
5361
  if (first_argv == "inspect") {
314
38
    return StartExecution(env, "internal/main/inspect");
315
  }
316
317
5323
  if (per_process::cli_options->build_snapshot) {
318
1
    return StartExecution(env, "internal/main/mksnapshot");
319
  }
320
321
5322
  if (per_process::cli_options->print_help) {
322
2
    return StartExecution(env, "internal/main/print_help");
323
  }
324
325
326
5320
  if (env->options()->prof_process) {
327
1
    return StartExecution(env, "internal/main/prof_process");
328
  }
329
330
  // -e/--eval without -i/--interactive
331


5319
  if (env->options()->has_eval_string && !env->options()->force_repl) {
332
503
    return StartExecution(env, "internal/main/eval_string");
333
  }
334
335
4816
  if (env->options()->syntax_check_only) {
336
39
    return StartExecution(env, "internal/main/check_syntax");
337
  }
338
339
4777
  if (env->options()->test_runner) {
340
5
    return StartExecution(env, "internal/main/test_runner");
341
  }
342
343

4772
  if (!first_argv.empty() && first_argv != "-") {
344
4727
    return StartExecution(env, "internal/main/run_main_module");
345
  }
346
347


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

316975
    if (nr == SIGKILL || nr == SIGSTOP)
430
20450
      continue;
431

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

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

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

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

30741
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
591
30741
    if (!is_same_file) continue;  // Program reopened file descriptor.
592
593
    int flags;
594
    do
595
30735
      flags = fcntl(fd, F_GETFL);
596

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

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

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


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

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

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

16151
  if (!(flags & ProcessInitializationFlags::kNoUseLargePages) &&
857
10767
      (per_process::cli_options->use_largepages == "on" ||
858
5383
       per_process::cli_options->use_largepages == "silent")) {
859
1
    int lp_result = node::MapStaticCodeToLargePages();
860

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

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