GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 415 475 87.4 %
Date: 2022-08-05 04:16:08 Branches: 251 363 69.1 %

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

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

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

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


5268
  if (env->options()->has_eval_string && !env->options()->force_repl) {
483
469
    return StartExecution(env, "internal/main/eval_string");
484
  }
485
486
4799
  if (env->options()->syntax_check_only) {
487
39
    return StartExecution(env, "internal/main/check_syntax");
488
  }
489
490
4760
  if (env->options()->test_runner) {
491
9
    return StartExecution(env, "internal/main/test_runner");
492
  }
493
494

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


45
  if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
499
28
    return StartExecution(env, "internal/main/repl");
500
  }
501
502
17
  return StartExecution(env, "internal/main/eval_stdin");
503
}
504
505
#ifdef __POSIX__
506
typedef void (*sigaction_cb)(int signo, siginfo_t* info, void* ucontext);
507
#endif
508
#if NODE_USE_V8_WASM_TRAP_HANDLER
509
#if defined(_WIN32)
510
static LONG TrapWebAssemblyOrContinue(EXCEPTION_POINTERS* exception) {
511
  if (v8::TryHandleWebAssemblyTrapWindows(exception)) {
512
    return EXCEPTION_CONTINUE_EXECUTION;
513
  }
514
  return EXCEPTION_CONTINUE_SEARCH;
515
}
516
#else
517
static std::atomic<sigaction_cb> previous_sigsegv_action;
518
519
6
void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) {
520
6
  if (!v8::TryHandleWebAssemblyTrapPosix(signo, info, ucontext)) {
521
6
    sigaction_cb prev = previous_sigsegv_action.load();
522
6
    if (prev != nullptr) {
523
6
      prev(signo, info, ucontext);
524
    } else {
525
      // Reset to the default signal handler, i.e. cause a hard crash.
526
      struct sigaction sa;
527
      memset(&sa, 0, sizeof(sa));
528
      sa.sa_handler = SIG_DFL;
529
      CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
530
531
      ResetStdio();
532
      raise(signo);
533
    }
534
  }
535
6
}
536
#endif  // defined(_WIN32)
537
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
538
539
#ifdef __POSIX__
540
17167
void RegisterSignalHandler(int signal,
541
                           sigaction_cb handler,
542
                           bool reset_handler) {
543
17167
  CHECK_NOT_NULL(handler);
544
#if NODE_USE_V8_WASM_TRAP_HANDLER
545
17167
  if (signal == SIGSEGV) {
546
4
    CHECK(previous_sigsegv_action.is_lock_free());
547
4
    CHECK(!reset_handler);
548
4
    previous_sigsegv_action.store(handler);
549
4
    return;
550
  }
551
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
552
  struct sigaction sa;
553
17163
  memset(&sa, 0, sizeof(sa));
554
17163
  sa.sa_sigaction = handler;
555
17163
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
556
17163
  sigfillset(&sa.sa_mask);
557
17163
  CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
558
}
559
#endif  // __POSIX__
560
561
#ifdef __POSIX__
562
static struct {
563
  int flags;
564
  bool isatty;
565
  struct stat stat;
566
  struct termios termios;
567
} stdio[1 + STDERR_FILENO];
568
#endif  // __POSIX__
569
570
571
5378
inline void PlatformInit() {
572
#ifdef __POSIX__
573
#if HAVE_INSPECTOR
574
  sigset_t sigmask;
575
5378
  sigemptyset(&sigmask);
576
5378
  sigaddset(&sigmask, SIGUSR1);
577
5378
  const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
578
#endif  // HAVE_INSPECTOR
579
580
  // Make sure file descriptors 0-2 are valid before we start logging anything.
581
21512
  for (auto& s : stdio) {
582
16134
    const int fd = &s - stdio;
583
16134
    if (fstat(fd, &s.stat) == 0)
584
16132
      continue;
585
    // Anything but EBADF means something is seriously wrong.  We don't
586
    // have to special-case EINTR, fstat() is not interruptible.
587
2
    if (errno != EBADF)
588
      ABORT();
589
2
    if (fd != open("/dev/null", O_RDWR))
590
      ABORT();
591
2
    if (fstat(fd, &s.stat) != 0)
592
      ABORT();
593
  }
594
595
#if HAVE_INSPECTOR
596
5378
  CHECK_EQ(err, 0);
597
#endif  // HAVE_INSPECTOR
598
599
  // TODO(addaleax): NODE_SHARED_MODE does not really make sense here.
600
#ifndef NODE_SHARED_MODE
601
  // Restore signal dispositions, the parent process may have changed them.
602
  struct sigaction act;
603
5378
  memset(&act, 0, sizeof(act));
604
605
  // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
606
  // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
607
  // Counting up to SIGRTMIN doesn't work for the same reason.
608
172096
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
609

166718
    if (nr == SIGKILL || nr == SIGSTOP)
610
10756
      continue;
611

155962
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
612
155962
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
613
  }
614
#endif  // !NODE_SHARED_MODE
615
616
  // Record the state of the stdio file descriptors so we can restore it
617
  // on exit.  Needs to happen before installing signal handlers because
618
  // they make use of that information.
619
21512
  for (auto& s : stdio) {
620
16134
    const int fd = &s - stdio;
621
    int err;
622
623
    do
624
16134
      s.flags = fcntl(fd, F_GETFL);
625

16134
    while (s.flags == -1 && errno == EINTR);  // NOLINT
626
16134
    CHECK_NE(s.flags, -1);
627
628
16134
    if (uv_guess_handle(fd) != UV_TTY) continue;
629
120
    s.isatty = true;
630
631
    do
632
120
      err = tcgetattr(fd, &s.termios);
633

120
    while (err == -1 && errno == EINTR);  // NOLINT
634
120
    CHECK_EQ(err, 0);
635
  }
636
637
5378
  RegisterSignalHandler(SIGINT, SignalExit, true);
638
5378
  RegisterSignalHandler(SIGTERM, SignalExit, true);
639
640
#if NODE_USE_V8_WASM_TRAP_HANDLER
641
#if defined(_WIN32)
642
  {
643
    constexpr ULONG first = TRUE;
644
    per_process::old_vectored_exception_handler =
645
        AddVectoredExceptionHandler(first, TrapWebAssemblyOrContinue);
646
  }
647
#else
648
  // Tell V8 to disable emitting WebAssembly
649
  // memory bounds checks. This means that we have
650
  // to catch the SIGSEGV in TrapWebAssemblyOrContinue
651
  // and pass the signal context to V8.
652
  {
653
    struct sigaction sa;
654
5378
    memset(&sa, 0, sizeof(sa));
655
5378
    sa.sa_sigaction = TrapWebAssemblyOrContinue;
656
5378
    sa.sa_flags = SA_SIGINFO;
657
5378
    CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
658
  }
659
#endif  // defined(_WIN32)
660
5378
  V8::EnableWebAssemblyTrapHandler(false);
661
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
662
663
  // Raise the open file descriptor limit.
664
  struct rlimit lim;
665

5378
  if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
666
    // Do a binary search for the limit.
667
    rlim_t min = lim.rlim_cur;
668
    rlim_t max = 1 << 20;
669
    // But if there's a defined upper bound, don't search, just set it.
670
    if (lim.rlim_max != RLIM_INFINITY) {
671
      min = lim.rlim_max;
672
      max = lim.rlim_max;
673
    }
674
    do {
675
      lim.rlim_cur = min + (max - min) / 2;
676
      if (setrlimit(RLIMIT_NOFILE, &lim)) {
677
        max = lim.rlim_cur;
678
      } else {
679
        min = lim.rlim_cur;
680
      }
681
    } while (min + 1 < max);
682
  }
683
#endif  // __POSIX__
684
#ifdef _WIN32
685
  for (int fd = 0; fd <= 2; ++fd) {
686
    auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
687
    if (handle == INVALID_HANDLE_VALUE ||
688
        GetFileType(handle) == FILE_TYPE_UNKNOWN) {
689
      // Ignore _close result. If it fails or not depends on used Windows
690
      // version. We will just check _open result.
691
      _close(fd);
692
      if (fd != _open("nul", _O_RDWR))
693
        ABORT();
694
    }
695
  }
696
#endif  // _WIN32
697
5378
}
698
699
700
// Safe to call more than once and from signal handlers.
701
10090
void ResetStdio() {
702
10090
  uv_tty_reset_mode();
703
#ifdef __POSIX__
704
40360
  for (auto& s : stdio) {
705
30270
    const int fd = &s - stdio;
706
707
    struct stat tmp;
708
30270
    if (-1 == fstat(fd, &tmp)) {
709
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
710
6
      continue;
711
    }
712
713
30270
    bool is_same_file =
714

30270
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
715
30270
    if (!is_same_file) continue;  // Program reopened file descriptor.
716
717
    int flags;
718
    do
719
30264
      flags = fcntl(fd, F_GETFL);
720

30264
    while (flags == -1 && errno == EINTR);  // NOLINT
721
30264
    CHECK_NE(flags, -1);
722
723
    // Restore the O_NONBLOCK flag if it changed.
724
30264
    if (O_NONBLOCK & (flags ^ s.flags)) {
725
1233
      flags &= ~O_NONBLOCK;
726
1233
      flags |= s.flags & O_NONBLOCK;
727
728
      int err;
729
      do
730
1233
        err = fcntl(fd, F_SETFL, flags);
731

1233
      while (err == -1 && errno == EINTR);  // NOLINT
732
1233
      CHECK_NE(err, -1);
733
    }
734
735
30264
    if (s.isatty) {
736
      sigset_t sa;
737
      int err;
738
739
      // We might be a background job that doesn't own the TTY so block SIGTTOU
740
      // before making the tcsetattr() call, otherwise that signal suspends us.
741
228
      sigemptyset(&sa);
742
228
      sigaddset(&sa, SIGTTOU);
743
744
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
745
      do
746
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
747

228
      while (err == -1 && errno == EINTR);  // NOLINT
748
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
749
750
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
751
      // tcsetattr will fail with err == -1 and errno == EPERM.
752


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
753
    }
754
  }
755
#endif  // __POSIX__
756
10090
}
757
758
759
10638
int ProcessGlobalArgs(std::vector<std::string>* args,
760
                      std::vector<std::string>* exec_args,
761
                      std::vector<std::string>* errors,
762
                      OptionEnvvarSettings settings) {
763
  // Parse a few arguments which are specific to Node.
764
21276
  std::vector<std::string> v8_args;
765
766
21276
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
767
10638
  options_parser::Parse(
768
      args,
769
      exec_args,
770
      &v8_args,
771
      per_process::cli_options.get(),
772
      settings,
773
      errors);
774
775
10638
  if (!errors->empty()) return 9;
776
777
21176
  std::string revert_error;
778
10588
  for (const std::string& cve : per_process::cli_options->security_reverts) {
779
1
    Revert(cve.c_str(), &revert_error);
780
1
    if (!revert_error.empty()) {
781
1
      errors->emplace_back(std::move(revert_error));
782
1
      return 12;
783
    }
784
  }
785
786
21173
  if (per_process::cli_options->disable_proto != "delete" &&
787

21173
      per_process::cli_options->disable_proto != "throw" &&
788
10585
      per_process::cli_options->disable_proto != "") {
789
    errors->emplace_back("invalid mode passed to --disable-proto");
790
    return 12;
791
  }
792
793
  // TODO(aduh95): remove this when the harmony-import-assertions flag
794
  // is removed in V8.
795
21174
  if (std::find(v8_args.begin(), v8_args.end(),
796
10587
                "--no-harmony-import-assertions") == v8_args.end()) {
797
10587
    v8_args.emplace_back("--harmony-import-assertions");
798
  }
799
800
21174
  auto env_opts = per_process::cli_options->per_isolate->per_env;
801
21174
  if (std::find(v8_args.begin(), v8_args.end(),
802

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

10651
  if (per_process::cli_options->use_largepages == "on" ||
997
5325
      per_process::cli_options->use_largepages == "silent") {
998
1
    int result = node::MapStaticCodeToLargePages();
999

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