GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 404 457 88.4 %
Date: 2022-10-07 04:22:37 Branches: 258 369 69.9 %

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

6413
  if (options_->debug_options().inspector_enabled &&
189
115
      !inspector_agent_->IsListening()) {
190
5
    return ExitCode::kInvalidCommandLineArgument2;  // Signal internal error
191
  }
192
193
6293
  profiler::StartProfilers(this);
194
195
6293
  if (inspector_agent_->options().break_node_first_line) {
196
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
197
  }
198
199
6293
  return ExitCode::kNoFailure;
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
6270
void Environment::InitializeDiagnostics() {
242
6270
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
243
      Environment::BuildEmbedderGraph, this);
244
6270
  if (heap_snapshot_near_heap_limit_ > 0) {
245
1
    AddHeapSnapshotNearHeapLimitCallback();
246
  }
247
6270
  if (options_->trace_uncaught)
248
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
249
6270
  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
6270
}
257
258
static
259
6270
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
260
6270
  EscapableHandleScope scope(env->isolate());
261
6270
  CHECK_NOT_NULL(main_script_id);
262
6270
  Realm* realm = env->principal_realm();
263
264
12270
  return scope.EscapeMaybe(realm->ExecuteBootstrapper(main_script_id));
265
}
266
267
6270
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
268
  InternalCallbackScope callback_scope(
269
      env,
270
      Object::New(env->isolate()),
271
      { 1, 0 },
272
12268
      InternalCallbackScope::kSkipAsyncHooks);
273
274
6270
  if (cb != nullptr) {
275
24
    EscapableHandleScope scope(env->isolate());
276
277
48
    if (StartExecution(env, "internal/main/environment").IsEmpty()) return {};
278
279
    StartExecutionCallbackInfo info = {
280
24
        env->process_object(),
281
24
        env->builtin_module_require(),
282
    };
283
284
46
    return scope.EscapeMaybe(cb(info));
285
  }
286
287
  // TODO(joyeecheung): move these conditions into JS land and let the
288
  // deserialize main function take precedence. For workers, we need to
289
  // move the pre-execution part into a different file that can be
290
  // reused when dealing with user-defined main functions.
291
12492
  if (!env->snapshot_deserialize_main().IsEmpty()) {
292
    return env->RunSnapshotDeserializeMain();
293
  }
294
295
6246
  if (env->worker_context() != nullptr) {
296
726
    return StartExecution(env, "internal/main/worker_thread");
297
  }
298
299
10770
  std::string first_argv;
300
5520
  if (env->argv().size() > 1) {
301
4969
    first_argv = env->argv()[1];
302
  }
303
304
5520
  if (first_argv == "inspect") {
305
38
    return StartExecution(env, "internal/main/inspect");
306
  }
307
308
5482
  if (per_process::cli_options->build_snapshot) {
309
1
    return StartExecution(env, "internal/main/mksnapshot");
310
  }
311
312
5481
  if (per_process::cli_options->print_help) {
313
2
    return StartExecution(env, "internal/main/print_help");
314
  }
315
316
317
5479
  if (env->options()->prof_process) {
318
1
    return StartExecution(env, "internal/main/prof_process");
319
  }
320
321
  // -e/--eval without -i/--interactive
322


5478
  if (env->options()->has_eval_string && !env->options()->force_repl) {
323
514
    return StartExecution(env, "internal/main/eval_string");
324
  }
325
326
4964
  if (env->options()->syntax_check_only) {
327
39
    return StartExecution(env, "internal/main/check_syntax");
328
  }
329
330
4925
  if (env->options()->test_runner) {
331
10
    return StartExecution(env, "internal/main/test_runner");
332
  }
333
334


4915
  if (env->options()->watch_mode && !first_argv.empty()) {
335
11
    return StartExecution(env, "internal/main/watch_mode");
336
  }
337
338

4904
  if (!first_argv.empty() && first_argv != "-") {
339
4858
    return StartExecution(env, "internal/main/run_main_module");
340
  }
341
342


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

327236
    if (nr == SIGKILL || nr == SIGSTOP)
425
21112
      continue;
426

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

16779
      } while (s.flags == -1 && errno == EINTR);  // NOLINT
487
16779
      CHECK_NE(s.flags, -1);
488
489
16779
      if (uv_guess_handle(fd) != UV_TTY) continue;
490
120
      s.isatty = true;
491
492
      do {
493
120
        err = tcgetattr(fd, &s.termios);
494

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

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

31734
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
586
31734
    if (!is_same_file) continue;  // Program reopened file descriptor.
587
588
    int flags;
589
    do
590
31728
      flags = fcntl(fd, F_GETFL);
591

31728
    while (flags == -1 && errno == EINTR);  // NOLINT
592
31728
    CHECK_NE(flags, -1);
593
594
    // Restore the O_NONBLOCK flag if it changed.
595
31728
    if (O_NONBLOCK & (flags ^ s.flags)) {
596
1416
      flags &= ~O_NONBLOCK;
597
1416
      flags |= s.flags & O_NONBLOCK;
598
599
      int err;
600
      do
601
1416
        err = fcntl(fd, F_SETFL, flags);
602

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

228
      while (err == -1 && errno == EINTR);  // NOLINT
619
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
620
621
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
622
      // tcsetattr will fail with err == -1 and errno == EPERM.
623


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
624
    }
625
  }
626
#endif  // __POSIX__
627
}
628
629
11050
static ExitCode ProcessGlobalArgsInternal(std::vector<std::string>* args,
630
                                          std::vector<std::string>* exec_args,
631
                                          std::vector<std::string>* errors,
632
                                          OptionEnvvarSettings settings) {
633
  // Parse a few arguments which are specific to Node.
634
22100
  std::vector<std::string> v8_args;
635
636
22100
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
637
11050
  options_parser::Parse(
638
      args,
639
      exec_args,
640
      &v8_args,
641
      per_process::cli_options.get(),
642
      settings,
643
      errors);
644
645
11050
  if (!errors->empty()) return ExitCode::kInvalidCommandLineArgument;
646
647
22004
  std::string revert_error;
648
11002
  for (const std::string& cve : per_process::cli_options->security_reverts) {
649
1
    Revert(cve.c_str(), &revert_error);
650
1
    if (!revert_error.empty()) {
651
1
      errors->emplace_back(std::move(revert_error));
652
      // TODO(joyeecheung): merge into kInvalidCommandLineArgument.
653
1
      return ExitCode::kInvalidCommandLineArgument2;
654
    }
655
  }
656
657
22001
  if (per_process::cli_options->disable_proto != "delete" &&
658

22001
      per_process::cli_options->disable_proto != "throw" &&
659
10999
      per_process::cli_options->disable_proto != "") {
660
    errors->emplace_back("invalid mode passed to --disable-proto");
661
    // TODO(joyeecheung): merge into kInvalidCommandLineArgument.
662
    return ExitCode::kInvalidCommandLineArgument2;
663
  }
664
665
  // TODO(aduh95): remove this when the harmony-import-assertions flag
666
  // is removed in V8.
667
22002
  if (std::find(v8_args.begin(), v8_args.end(),
668
11001
                "--no-harmony-import-assertions") == v8_args.end()) {
669
11001
    v8_args.emplace_back("--harmony-import-assertions");
670
  }
671
672
22002
  auto env_opts = per_process::cli_options->per_isolate->per_env;
673
22002
  if (std::find(v8_args.begin(), v8_args.end(),
674

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

16628
  if (!(flags & ProcessInitializationFlags::kNoUseLargePages) &&
868
11085
      (per_process::cli_options->use_largepages == "on" ||
869
5542
       per_process::cli_options->use_largepages == "silent")) {
870
1
    int lp_result = node::MapStaticCodeToLargePages();
871

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

5515
    if (read_data != nullptr && read_data->Check()) {
1150
      // If we fail to read the embedded snapshot, treat it as if Node.js
1151
      // was built without one.
1152
5515
      *snapshot_data_ptr = read_data;
1153
    }
1154
  }
1155
1156
5519
  if ((*snapshot_data_ptr) != nullptr) {
1157
5517
    BuiltinLoader::RefreshCodeCache((*snapshot_data_ptr)->code_cache);
1158
  }
1159
  NodeMainInstance main_instance(*snapshot_data_ptr,
1160
                                 uv_default_loop(),
1161
5519
                                 per_process::v8_platform.Platform(),
1162
                                 result->args(),
1163
11038
                                 result->exec_args());
1164
5519
  exit_code = main_instance.Run();
1165
4947
  return exit_code;
1166
}
1167
1168
5580
static ExitCode StartInternal(int argc, char** argv) {
1169
5580
  CHECK_GT(argc, 0);
1170
1171
  // Hack around with the argv pointer. Used for process.title = "blah".
1172
5580
  argv = uv_setup_args(argc, argv);
1173
1174
  std::unique_ptr<InitializationResultImpl> result =
1175
      InitializeOncePerProcessInternal(
1176
16168
          std::vector<std::string>(argv, argv + argc));
1177
5633
  for (const std::string& error : result->errors()) {
1178
53
    FPrintF(stderr, "%s: %s\n", result->args().at(0), error);
1179
  }
1180
5580
  if (result->early_return()) {
1181
56
    return result->exit_code_enum();
1182
  }
1183
1184
  DCHECK_EQ(result->exit_code_enum(), ExitCode::kNoFailure);
1185
5524
  const SnapshotData* snapshot_data = nullptr;
1186
1187
4952
  auto cleanup_process = OnScopeLeave([&]() {
1188
4952
    TearDownOncePerProcess();
1189
1190
4952
    if (snapshot_data != nullptr &&
1191
4947
        snapshot_data->data_ownership == SnapshotData::DataOwnership::kOwned) {
1192
2
      delete snapshot_data;
1193
    }
1194
10476
  });
1195
1196
5524
  uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1197
1198
  // --build-snapshot indicates that we are in snapshot building mode.
1199
5524
  if (per_process::cli_options->build_snapshot) {
1200
4
    if (result->args().size() < 2) {
1201
1
      fprintf(stderr,
1202
              "--build-snapshot must be used with an entry point script.\n"
1203
              "Usage: node --build-snapshot /path/to/entry.js\n");
1204
1
      return ExitCode::kInvalidCommandLineArgument;
1205
    }
1206
3
    return GenerateAndWriteSnapshotData(&snapshot_data, result.get());
1207
  }
1208
1209
  // Without --build-snapshot, we are in snapshot loading mode.
1210
5520
  return LoadSnapshotDataAndRun(&snapshot_data, result.get());
1211
}
1212
1213
5580
int Start(int argc, char** argv) {
1214
5580
  return static_cast<int>(StartInternal(argc, argv));
1215
}
1216
1217
380
int Stop(Environment* env) {
1218
380
  env->ExitEnv();
1219
380
  return 0;
1220
}
1221
1222
}  // namespace node
1223
1224
#if !HAVE_INSPECTOR
1225
void Initialize() {}
1226
1227
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1228
#endif  // !HAVE_INSPECTOR