GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 409 466 87.8 %
Date: 2022-11-20 04:28:36 Branches: 256 373 68.6 %

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

6514
  if (options_->debug_options().inspector_enabled &&
189
118
      !inspector_agent_->IsListening()) {
190
8
    return;
191
  }
192
193
6388
  profiler::StartProfilers(this);
194
195
6388
  if (inspector_agent_->options().break_node_first_line) {
196
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
197
  }
198
199
6388
  return;
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
6368
void Environment::InitializeDiagnostics() {
242
6368
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
243
      Environment::BuildEmbedderGraph, this);
244
6368
  if (heap_snapshot_near_heap_limit_ > 0) {
245
1
    AddHeapSnapshotNearHeapLimitCallback();
246
  }
247
6368
  if (options_->trace_uncaught)
248
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
249
6368
  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
6368
}
257
258
static
259
6368
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
260
6368
  EscapableHandleScope scope(env->isolate());
261
6368
  CHECK_NOT_NULL(main_script_id);
262
6368
  Realm* realm = env->principal_realm();
263
264
12438
  return scope.EscapeMaybe(realm->ExecuteBootstrapper(main_script_id));
265
}
266
267
6368
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
268
  InternalCallbackScope callback_scope(
269
      env,
270
      Object::New(env->isolate()),
271
      { 1, 0 },
272
12436
      InternalCallbackScope::kSkipAsyncHooks);
273
274
6368
  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
12688
  if (!env->snapshot_deserialize_main().IsEmpty()) {
292
    return env->RunSnapshotDeserializeMain();
293
  }
294
295
6344
  if (env->worker_context() != nullptr) {
296
730
    return StartExecution(env, "internal/main/worker_thread");
297
  }
298
299
10930
  std::string first_argv;
300
5614
  if (env->argv().size() > 1) {
301
5061
    first_argv = env->argv()[1];
302
  }
303
304
5614
  if (first_argv == "inspect") {
305
38
    return StartExecution(env, "internal/main/inspect");
306
  }
307
308
5576
  if (per_process::cli_options->build_snapshot) {
309
2
    return StartExecution(env, "internal/main/mksnapshot");
310
  }
311
312
5574
  if (per_process::cli_options->print_help) {
313
2
    return StartExecution(env, "internal/main/print_help");
314
  }
315
316
317
5572
  if (env->options()->prof_process) {
318
1
    return StartExecution(env, "internal/main/prof_process");
319
  }
320
321
  // -e/--eval without -i/--interactive
322


5571
  if (env->options()->has_eval_string && !env->options()->force_repl) {
323
516
    return StartExecution(env, "internal/main/eval_string");
324
  }
325
326
5055
  if (env->options()->syntax_check_only) {
327
39
    return StartExecution(env, "internal/main/check_syntax");
328
  }
329
330
5016
  if (env->options()->test_runner) {
331
15
    return StartExecution(env, "internal/main/test_runner");
332
  }
333
334
5001
  if (env->options()->watch_mode) {
335
10
    return StartExecution(env, "internal/main/watch_mode");
336
  }
337
338

4991
  if (!first_argv.empty() && first_argv != "-") {
339
4945
    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
18112
void RegisterSignalHandler(int signal,
385
                           sigaction_cb handler,
386
                           bool reset_handler) {
387
18112
  CHECK_NOT_NULL(handler);
388
#if NODE_USE_V8_WASM_TRAP_HANDLER
389
18112
  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
18108
  memset(&sa, 0, sizeof(sa));
398
18108
  sa.sa_sigaction = handler;
399
18108
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
400
18108
  sigfillset(&sa.sa_mask);
401
18108
  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
10714
void ResetSignalHandlers() {
415
#ifdef __POSIX__
416
  // Restore signal dispositions, the parent process may have changed them.
417
  struct sigaction act;
418
10714
  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
342848
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
424

332134
    if (nr == SIGKILL || nr == SIGSTOP)
425
21428
      continue;
426

310706
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
427
310706
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
428
  }
429
#endif  // __POSIX__
430
10714
}
431
432
static std::atomic<uint32_t> init_process_flags = 0;
433
434
5688
static void PlatformInit(ProcessInitializationFlags::Flags flags) {
435
  // init_process_flags is accessed in ResetStdio(),
436
  // which can be called from signal handlers.
437
5688
  CHECK(init_process_flags.is_lock_free());
438
5688
  init_process_flags.store(flags);
439
440
5688
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
441
5688
    atexit(ResetStdio);
442
  }
443
444
#ifdef __POSIX__
445
5688
  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
5688
    setvbuf(stdout, nullptr, _IONBF, 0);
449
5688
    setvbuf(stderr, nullptr, _IONBF, 0);
450
451
    // Make sure file descriptors 0-2 are valid before we start logging
452
    // anything.
453
22752
    for (auto& s : stdio) {
454
17064
      const int fd = &s - stdio;
455
17064
      if (fstat(fd, &s.stat) == 0) continue;
456
457
      // Anything but EBADF means something is seriously wrong.  We don't
458
      // have to special-case EINTR, fstat() is not interruptible.
459
2
      if (errno != EBADF) ABORT();
460
461
      // If EBADF (file descriptor doesn't exist), open /dev/null and duplicate
462
      // its file descriptor to the invalid file descriptor.  Make sure *that*
463
      // file descriptor is valid.  POSIX doesn't guarantee the next file
464
      // descriptor open(2) gives us is the lowest available number anymore in
465
      // POSIX.1-2017, which is why dup2(2) is needed.
466
      int null_fd;
467
468
      do {
469
2
        null_fd = open("/dev/null", O_RDWR);
470

2
      } while (null_fd < 0 && errno == EINTR);
471
472
2
      if (null_fd != fd) {
473
        int err;
474
475
        do {
476
          err = dup2(null_fd, fd);
477
        } while (err < 0 && errno == EINTR);
478
        CHECK_EQ(err, 0);
479
      }
480
481
2
      if (fstat(fd, &s.stat) < 0) ABORT();
482
    }
483
  }
484
485
5688
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
486
#if HAVE_INSPECTOR
487
    sigset_t sigmask;
488
5688
    sigemptyset(&sigmask);
489
5688
    sigaddset(&sigmask, SIGUSR1);
490
5688
    const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
491
5688
    CHECK_EQ(err, 0);
492
#endif  // HAVE_INSPECTOR
493
494
5688
    ResetSignalHandlers();
495
  }
496
497
5688
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
498
    // Record the state of the stdio file descriptors so we can restore it
499
    // on exit.  Needs to happen before installing signal handlers because
500
    // they make use of that information.
501
22752
    for (auto& s : stdio) {
502
17064
      const int fd = &s - stdio;
503
      int err;
504
505
      do {
506
17064
        s.flags = fcntl(fd, F_GETFL);
507

17064
      } while (s.flags == -1 && errno == EINTR);  // NOLINT
508
17064
      CHECK_NE(s.flags, -1);
509
510
17064
      if (uv_guess_handle(fd) != UV_TTY) continue;
511
120
      s.isatty = true;
512
513
      do {
514
120
        err = tcgetattr(fd, &s.termios);
515

120
      } while (err == -1 && errno == EINTR);  // NOLINT
516
120
      CHECK_EQ(err, 0);
517
    }
518
  }
519
520
5688
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
521
5688
    RegisterSignalHandler(SIGINT, SignalExit, true);
522
5688
    RegisterSignalHandler(SIGTERM, SignalExit, true);
523
524
#if NODE_USE_V8_WASM_TRAP_HANDLER
525
#if defined(_WIN32)
526
    {
527
      constexpr ULONG first = TRUE;
528
      per_process::old_vectored_exception_handler =
529
          AddVectoredExceptionHandler(first, TrapWebAssemblyOrContinue);
530
    }
531
#else
532
    // Tell V8 to disable emitting WebAssembly
533
    // memory bounds checks. This means that we have
534
    // to catch the SIGSEGV in TrapWebAssemblyOrContinue
535
    // and pass the signal context to V8.
536
    {
537
      struct sigaction sa;
538
5688
      memset(&sa, 0, sizeof(sa));
539
5688
      sa.sa_sigaction = TrapWebAssemblyOrContinue;
540
5688
      sa.sa_flags = SA_SIGINFO;
541
5688
      CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
542
    }
543
#endif  // defined(_WIN32)
544
5688
    V8::EnableWebAssemblyTrapHandler(false);
545
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
546
  }
547
548
5688
  if (!(flags & ProcessInitializationFlags::kNoAdjustResourceLimits)) {
549
    // Raise the open file descriptor limit.
550
    struct rlimit lim;
551

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

32208
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
607
32208
    if (!is_same_file) continue;  // Program reopened file descriptor.
608
609
    int flags;
610
    do
611
32202
      flags = fcntl(fd, F_GETFL);
612

32202
    while (flags == -1 && errno == EINTR);  // NOLINT
613
32202
    CHECK_NE(flags, -1);
614
615
    // Restore the O_NONBLOCK flag if it changed.
616
32202
    if (O_NONBLOCK & (flags ^ s.flags)) {
617
1496
      flags &= ~O_NONBLOCK;
618
1496
      flags |= s.flags & O_NONBLOCK;
619
620
      int err;
621
      do
622
1496
        err = fcntl(fd, F_SETFL, flags);
623

1496
      while (err == -1 && errno == EINTR);  // NOLINT
624
1496
      CHECK_NE(err, -1);
625
    }
626
627
32202
    if (s.isatty) {
628
      sigset_t sa;
629
      int err;
630
631
      // We might be a background job that doesn't own the TTY so block SIGTTOU
632
      // before making the tcsetattr() call, otherwise that signal suspends us.
633
228
      sigemptyset(&sa);
634
228
      sigaddset(&sa, SIGTTOU);
635
636
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
637
      do
638
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
639

228
      while (err == -1 && errno == EINTR);  // NOLINT
640
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
641
642
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
643
      // tcsetattr will fail with err == -1 and errno == EPERM.
644


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
645
    }
646
  }
647
#endif  // __POSIX__
648
}
649
650
11239
static ExitCode ProcessGlobalArgsInternal(std::vector<std::string>* args,
651
                                          std::vector<std::string>* exec_args,
652
                                          std::vector<std::string>* errors,
653
                                          OptionEnvvarSettings settings) {
654
  // Parse a few arguments which are specific to Node.
655
22478
  std::vector<std::string> v8_args;
656
657
22478
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
658
11239
  options_parser::Parse(
659
      args,
660
      exec_args,
661
      &v8_args,
662
      per_process::cli_options.get(),
663
      settings,
664
      errors);
665
666
11239
  if (!errors->empty()) return ExitCode::kInvalidCommandLineArgument;
667
668
22380
  std::string revert_error;
669
11190
  for (const std::string& cve : per_process::cli_options->security_reverts) {
670
1
    Revert(cve.c_str(), &revert_error);
671
1
    if (!revert_error.empty()) {
672
1
      errors->emplace_back(std::move(revert_error));
673
      // TODO(joyeecheung): merge into kInvalidCommandLineArgument.
674
1
      return ExitCode::kInvalidCommandLineArgument2;
675
    }
676
  }
677
678
22377
  if (per_process::cli_options->disable_proto != "delete" &&
679

22377
      per_process::cli_options->disable_proto != "throw" &&
680
11187
      per_process::cli_options->disable_proto != "") {
681
    errors->emplace_back("invalid mode passed to --disable-proto");
682
    // TODO(joyeecheung): merge into kInvalidCommandLineArgument.
683
    return ExitCode::kInvalidCommandLineArgument2;
684
  }
685
686
  // TODO(aduh95): remove this when the harmony-import-assertions flag
687
  // is removed in V8.
688
22378
  if (std::find(v8_args.begin(), v8_args.end(),
689
11189
                "--no-harmony-import-assertions") == v8_args.end()) {
690
11189
    v8_args.emplace_back("--harmony-import-assertions");
691
  }
692
693
22378
  auto env_opts = per_process::cli_options->per_isolate->per_env;
694
22378
  if (std::find(v8_args.begin(), v8_args.end(),
695

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

16910
  if (!(flags & ProcessInitializationFlags::kNoUseLargePages) &&
894
11273
      (per_process::cli_options->use_largepages == "on" ||
895
5636
       per_process::cli_options->use_largepages == "silent")) {
896
1
    int lp_result = node::MapStaticCodeToLargePages();
897

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

5608
    if (read_data != nullptr && read_data->Check()) {
1176
      // If we fail to read the embedded snapshot, treat it as if Node.js
1177
      // was built without one.
1178
5608
      *snapshot_data_ptr = read_data;
1179
    }
1180
  }
1181
1182
5612
  if ((*snapshot_data_ptr) != nullptr) {
1183
5610
    BuiltinLoader::RefreshCodeCache((*snapshot_data_ptr)->code_cache);
1184
  }
1185
  NodeMainInstance main_instance(*snapshot_data_ptr,
1186
                                 uv_default_loop(),
1187
5612
                                 per_process::v8_platform.Platform(),
1188
                                 result->args(),
1189
11224
                                 result->exec_args());
1190
5612
  exit_code = main_instance.Run();
1191
5009
  return exit_code;
1192
}
1193
1194
5675
static ExitCode StartInternal(int argc, char** argv) {
1195
5675
  CHECK_GT(argc, 0);
1196
1197
  // Hack around with the argv pointer. Used for process.title = "blah".
1198
5675
  argv = uv_setup_args(argc, argv);
1199
1200
  std::unique_ptr<InitializationResultImpl> result =
1201
      InitializeOncePerProcessInternal(
1202
16422
          std::vector<std::string>(argv, argv + argc));
1203
5729
  for (const std::string& error : result->errors()) {
1204
54
    FPrintF(stderr, "%s: %s\n", result->args().at(0), error);
1205
  }
1206
5675
  if (result->early_return()) {
1207
57
    return result->exit_code_enum();
1208
  }
1209
1210
  DCHECK_EQ(result->exit_code_enum(), ExitCode::kNoFailure);
1211
5618
  const SnapshotData* snapshot_data = nullptr;
1212
1213
5015
  auto cleanup_process = OnScopeLeave([&]() {
1214
5015
    TearDownOncePerProcess();
1215
1216
5015
    if (snapshot_data != nullptr &&
1217
5010
        snapshot_data->data_ownership == SnapshotData::DataOwnership::kOwned) {
1218
3
      delete snapshot_data;
1219
    }
1220
10633
  });
1221
1222
5618
  uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1223
1224
  // --build-snapshot indicates that we are in snapshot building mode.
1225
5618
  if (per_process::cli_options->build_snapshot) {
1226
5
    if (result->args().size() < 2) {
1227
1
      fprintf(stderr,
1228
              "--build-snapshot must be used with an entry point script.\n"
1229
              "Usage: node --build-snapshot /path/to/entry.js\n");
1230
1
      return ExitCode::kInvalidCommandLineArgument;
1231
    }
1232
4
    return GenerateAndWriteSnapshotData(&snapshot_data, result.get());
1233
  }
1234
1235
  // Without --build-snapshot, we are in snapshot loading mode.
1236
5613
  return LoadSnapshotDataAndRun(&snapshot_data, result.get());
1237
}
1238
1239
5675
int Start(int argc, char** argv) {
1240
5675
  return static_cast<int>(StartInternal(argc, argv));
1241
}
1242
1243
353
int Stop(Environment* env) {
1244
353
  env->ExitEnv();
1245
353
  return 0;
1246
}
1247
1248
}  // namespace node
1249
1250
#if !HAVE_INSPECTOR
1251
void Initialize() {}
1252
1253
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1254
#endif  // !HAVE_INSPECTOR