GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 448 506 88.5 %
Date: 2022-08-06 04:16:36 Branches: 269 391 68.8 %

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
9979
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
171
                                      const char* id,
172
                                      std::vector<Local<Value>>* arguments) {
173
9979
  EscapableHandleScope scope(env->isolate());
174
  MaybeLocal<Function> maybe_fn =
175
9979
      NativeModuleLoader::LookupAndCompile(env->context(), id, env);
176
177
  Local<Function> fn;
178
9979
  if (!maybe_fn.ToLocal(&fn)) {
179
    return MaybeLocal<Value>();
180
  }
181
182
  MaybeLocal<Value> result = fn->Call(env->context(),
183
                                      Undefined(env->isolate()),
184
9979
                                      arguments->size(),
185
29937
                                      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
9730
  if (result.IsEmpty()) {
194
35
    env->async_hooks()->clear_async_id_stack();
195
  }
196
197
9730
  return scope.EscapeMaybe(result);
198
}
199
200
#if HAVE_INSPECTOR
201
6088
int Environment::InitializeInspector(
202
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
203
12176
  std::string inspector_path;
204
6088
  bool is_main = !parent_handle;
205
6088
  if (parent_handle) {
206
725
    inspector_path = parent_handle->url();
207
725
    inspector_agent_->SetParentHandle(std::move(parent_handle));
208
  } else {
209
5363
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
210
  }
211
212
6088
  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
12176
  inspector_agent_->Start(inspector_path,
217
6088
                          options_->debug_options(),
218
12176
                          inspector_host_port(),
219
                          is_main);
220

6169
  if (options_->debug_options().inspector_enabled &&
221
81
      !inspector_agent_->IsListening()) {
222
5
    return 12;  // Signal internal error
223
  }
224
225
6083
  profiler::StartProfilers(this);
226
227
6083
  if (inspector_agent_->options().break_node_first_line) {
228
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
229
  }
230
231
6083
  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
6057
void Environment::InitializeDiagnostics() {
274
6057
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
275
      Environment::BuildEmbedderGraph, this);
276
6057
  if (options_->heap_snapshot_near_heap_limit > 0) {
277
1
    isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
278
                                       this);
279
  }
280
6057
  if (options_->trace_uncaught)
281
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
282
6057
  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
6057
}
290
291
781
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
292
781
  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
781
      NewFunctionTemplate(isolate_, binding::GetLinkedBinding)
299
781
          ->GetFunction(context())
300
          .ToLocalChecked(),
301
781
      NewFunctionTemplate(isolate_, binding::GetInternalBinding)
302
781
          ->GetFunction(context())
303
          .ToLocalChecked(),
304
5467
      primordials()};
305
306
  // Bootstrap internal loaders
307
  Local<Value> loader_exports;
308
781
  if (!ExecuteBootstrapper(this, "internal/bootstrap/loaders", &loaders_args)
309
781
           .ToLocal(&loader_exports)) {
310
    return MaybeLocal<Value>();
311
  }
312
781
  CHECK(loader_exports->IsObject());
313
781
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
314
  Local<Value> internal_binding_loader =
315
1562
      loader_exports_obj->Get(context(), internal_binding_string())
316
781
          .ToLocalChecked();
317
781
  CHECK(internal_binding_loader->IsFunction());
318
781
  set_internal_binding_loader(internal_binding_loader.As<Function>());
319
  Local<Value> require =
320
2343
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
321
781
  CHECK(require->IsFunction());
322
781
  set_native_module_require(require.As<Function>());
323
324
781
  return scope.Escape(loader_exports);
325
}
326
327
781
MaybeLocal<Value> Environment::BootstrapNode() {
328
781
  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
4686
      primordials()};
338
339
  MaybeLocal<Value> result =
340
781
      ExecuteBootstrapper(this, "internal/bootstrap/node", &node_args);
341
342
781
  if (result.IsEmpty()) {
343
    return MaybeLocal<Value>();
344
  }
345
346
781
  if (!no_browser_globals()) {
347
    result =
348
781
        ExecuteBootstrapper(this, "internal/bootstrap/browser", &node_args);
349
350
781
    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
781
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
358
781
                       : "internal/bootstrap/switches/is_not_main_thread";
359
781
  result = ExecuteBootstrapper(this, thread_switch_id, &node_args);
360
361
781
  if (result.IsEmpty()) {
362
    return MaybeLocal<Value>();
363
  }
364
365
  auto process_state_switch_id =
366
781
      owns_process_state()
367
781
          ? "internal/bootstrap/switches/does_own_process_state"
368
781
          : "internal/bootstrap/switches/does_not_own_process_state";
369
781
  result = ExecuteBootstrapper(this, process_state_switch_id, &node_args);
370
371
781
  if (result.IsEmpty()) {
372
    return MaybeLocal<Value>();
373
  }
374
375
781
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
376
  Local<Object> env_var_proxy;
377
2343
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
378

3124
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
379
    return MaybeLocal<Value>();
380
  }
381
382
781
  return scope.EscapeMaybe(result);
383
}
384
385
781
MaybeLocal<Value> Environment::RunBootstrapping() {
386
781
  EscapableHandleScope scope(isolate_);
387
388
781
  CHECK(!has_run_bootstrapping_code());
389
390
1562
  if (BootstrapInternalLoaders().IsEmpty()) {
391
    return MaybeLocal<Value>();
392
  }
393
394
  Local<Value> result;
395
1562
  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
781
  CHECK(req_wrap_queue()->IsEmpty());
404
781
  CHECK(handle_wrap_queue()->IsEmpty());
405
406
781
  DoneBootstrapping();
407
408
781
  return scope.Escape(result);
409
}
410
411
static
412
6057
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
413
6057
  EscapableHandleScope scope(env->isolate());
414
6057
  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
30285
                                         env->primordials()};
422
423
  return scope.EscapeMaybe(
424
11867
      ExecuteBootstrapper(env, main_script_id, &arguments));
425
}
426
427
6057
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
428
  InternalCallbackScope callback_scope(
429
      env,
430
      Object::New(env->isolate()),
431
      { 1, 0 },
432
11865
      InternalCallbackScope::kSkipAsyncHooks);
433
434
6057
  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
12070
  if (!env->snapshot_deserialize_main().IsEmpty()) {
452
    return env->RunSnapshotDeserializeMain();
453
  }
454
455
6035
  if (env->worker_context() != nullptr) {
456
719
    return StartExecution(env, "internal/main/worker_thread");
457
  }
458
459
10385
  std::string first_argv;
460
5316
  if (env->argv().size() > 1) {
461
4807
    first_argv = env->argv()[1];
462
  }
463
464
5316
  if (first_argv == "inspect") {
465
38
    return StartExecution(env, "internal/main/inspect");
466
  }
467
468
5278
  if (per_process::cli_options->build_snapshot) {
469
1
    return StartExecution(env, "internal/main/mksnapshot");
470
  }
471
472
5277
  if (per_process::cli_options->print_help) {
473
2
    return StartExecution(env, "internal/main/print_help");
474
  }
475
476
477
5275
  if (env->options()->prof_process) {
478
1
    return StartExecution(env, "internal/main/prof_process");
479
  }
480
481
  // -e/--eval without -i/--interactive
482


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

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


46
  if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
499
28
    return StartExecution(env, "internal/main/repl");
500
  }
501
502
18
  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
17305
void RegisterSignalHandler(int signal,
541
                           sigaction_cb handler,
542
                           bool reset_handler) {
543
17305
  CHECK_NOT_NULL(handler);
544
#if NODE_USE_V8_WASM_TRAP_HANDLER
545
17305
  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
17301
  memset(&sa, 0, sizeof(sa));
554
17301
  sa.sa_sigaction = handler;
555
17301
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
556
17301
  sigfillset(&sa.sa_mask);
557
17301
  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
10192
void ResetSignalHandlers() {
571
#ifdef __POSIX__
572
  // Restore signal dispositions, the parent process may have changed them.
573
  struct sigaction act;
574
10192
  memset(&act, 0, sizeof(act));
575
576
  // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
577
  // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
578
  // Counting up to SIGRTMIN doesn't work for the same reason.
579
326144
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
580

315952
    if (nr == SIGKILL || nr == SIGSTOP)
581
20384
      continue;
582

295568
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
583
295568
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
584
  }
585
#endif  // __POSIX__
586
10192
}
587
588
static std::atomic<uint64_t> init_process_flags = 0;
589
590
5391
static void PlatformInit(ProcessInitializationFlags::Flags flags) {
591
  // init_process_flags is accessed in ResetStdio(),
592
  // which can be called from signal handlers.
593
5391
  CHECK(init_process_flags.is_lock_free());
594
  init_process_flags.store(flags);
595
596
5391
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
597
5391
    atexit(ResetStdio);
598
  }
599
600
#ifdef __POSIX__
601
5391
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
602
    // Disable stdio buffering, it interacts poorly with printf()
603
    // calls elsewhere in the program (e.g., any logging from V8.)
604
5391
    setvbuf(stdout, nullptr, _IONBF, 0);
605
5391
    setvbuf(stderr, nullptr, _IONBF, 0);
606
607
    // Make sure file descriptors 0-2 are valid before we start logging
608
    // anything.
609
21564
    for (auto& s : stdio) {
610
16173
      const int fd = &s - stdio;
611
16173
      if (fstat(fd, &s.stat) == 0) continue;
612
      // Anything but EBADF means something is seriously wrong.  We don't
613
      // have to special-case EINTR, fstat() is not interruptible.
614
2
      if (errno != EBADF) ABORT();
615
2
      if (fd != open("/dev/null", O_RDWR)) ABORT();
616
2
      if (fstat(fd, &s.stat) != 0) ABORT();
617
    }
618
  }
619
620
5391
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
621
#if HAVE_INSPECTOR
622
    sigset_t sigmask;
623
5391
    sigemptyset(&sigmask);
624
5391
    sigaddset(&sigmask, SIGUSR1);
625
5391
    const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
626
5391
    CHECK_EQ(err, 0);
627
#endif  // HAVE_INSPECTOR
628
629
5391
    ResetSignalHandlers();
630
  }
631
632
5391
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
633
    // Record the state of the stdio file descriptors so we can restore it
634
    // on exit.  Needs to happen before installing signal handlers because
635
    // they make use of that information.
636
21564
    for (auto& s : stdio) {
637
16173
      const int fd = &s - stdio;
638
      int err;
639
640
      do {
641
16173
        s.flags = fcntl(fd, F_GETFL);
642

16173
      } while (s.flags == -1 && errno == EINTR);  // NOLINT
643
16173
      CHECK_NE(s.flags, -1);
644
645
16173
      if (uv_guess_handle(fd) != UV_TTY) continue;
646
120
      s.isatty = true;
647
648
      do {
649
120
        err = tcgetattr(fd, &s.termios);
650

120
      } while (err == -1 && errno == EINTR);  // NOLINT
651
120
      CHECK_EQ(err, 0);
652
    }
653
  }
654
655
5391
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
656
5391
    RegisterSignalHandler(SIGINT, SignalExit, true);
657
5391
    RegisterSignalHandler(SIGTERM, SignalExit, true);
658
659
#if NODE_USE_V8_WASM_TRAP_HANDLER
660
#if defined(_WIN32)
661
    {
662
      constexpr ULONG first = TRUE;
663
      per_process::old_vectored_exception_handler =
664
          AddVectoredExceptionHandler(first, TrapWebAssemblyOrContinue);
665
    }
666
#else
667
    // Tell V8 to disable emitting WebAssembly
668
    // memory bounds checks. This means that we have
669
    // to catch the SIGSEGV in TrapWebAssemblyOrContinue
670
    // and pass the signal context to V8.
671
    {
672
      struct sigaction sa;
673
5391
      memset(&sa, 0, sizeof(sa));
674
5391
      sa.sa_sigaction = TrapWebAssemblyOrContinue;
675
5391
      sa.sa_flags = SA_SIGINFO;
676
5391
      CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
677
    }
678
#endif  // defined(_WIN32)
679
5391
    V8::EnableWebAssemblyTrapHandler(false);
680
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
681
  }
682
683
5391
  if (!(flags & ProcessInitializationFlags::kNoAdjustResourceLimits)) {
684
    // Raise the open file descriptor limit.
685
    struct rlimit lim;
686

5391
    if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
687
      // Do a binary search for the limit.
688
      rlim_t min = lim.rlim_cur;
689
      rlim_t max = 1 << 20;
690
      // But if there's a defined upper bound, don't search, just set it.
691
      if (lim.rlim_max != RLIM_INFINITY) {
692
        min = lim.rlim_max;
693
        max = lim.rlim_max;
694
      }
695
      do {
696
        lim.rlim_cur = min + (max - min) / 2;
697
        if (setrlimit(RLIMIT_NOFILE, &lim)) {
698
          max = lim.rlim_cur;
699
        } else {
700
          min = lim.rlim_cur;
701
        }
702
      } while (min + 1 < max);
703
    }
704
  }
705
#endif  // __POSIX__
706
#ifdef _WIN32
707
  if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
708
    for (int fd = 0; fd <= 2; ++fd) {
709
      auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
710
      if (handle == INVALID_HANDLE_VALUE ||
711
          GetFileType(handle) == FILE_TYPE_UNKNOWN) {
712
        // Ignore _close result. If it fails or not depends on used Windows
713
        // version. We will just check _open result.
714
        _close(fd);
715
        if (fd != _open("nul", _O_RDWR)) ABORT();
716
      }
717
    }
718
  }
719
#endif  // _WIN32
720
5391
}
721
722
// Safe to call more than once and from signal handlers.
723
10213
void ResetStdio() {
724
20426
  if (init_process_flags.load() &
725
10213
      ProcessInitializationFlags::kNoStdioInitialization) {
726
    return;
727
  }
728
729
10213
  uv_tty_reset_mode();
730
#ifdef __POSIX__
731
40852
  for (auto& s : stdio) {
732
30639
    const int fd = &s - stdio;
733
734
    struct stat tmp;
735
30639
    if (-1 == fstat(fd, &tmp)) {
736
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
737
6
      continue;
738
    }
739
740
30639
    bool is_same_file =
741

30639
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
742
30639
    if (!is_same_file) continue;  // Program reopened file descriptor.
743
744
    int flags;
745
    do
746
30633
      flags = fcntl(fd, F_GETFL);
747

30633
    while (flags == -1 && errno == EINTR);  // NOLINT
748
30633
    CHECK_NE(flags, -1);
749
750
    // Restore the O_NONBLOCK flag if it changed.
751
30633
    if (O_NONBLOCK & (flags ^ s.flags)) {
752
1201
      flags &= ~O_NONBLOCK;
753
1201
      flags |= s.flags & O_NONBLOCK;
754
755
      int err;
756
      do
757
1201
        err = fcntl(fd, F_SETFL, flags);
758

1201
      while (err == -1 && errno == EINTR);  // NOLINT
759
1201
      CHECK_NE(err, -1);
760
    }
761
762
30633
    if (s.isatty) {
763
      sigset_t sa;
764
      int err;
765
766
      // We might be a background job that doesn't own the TTY so block SIGTTOU
767
      // before making the tcsetattr() call, otherwise that signal suspends us.
768
228
      sigemptyset(&sa);
769
228
      sigaddset(&sa, SIGTTOU);
770
771
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
772
      do
773
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
774

228
      while (err == -1 && errno == EINTR);  // NOLINT
775
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
776
777
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
778
      // tcsetattr will fail with err == -1 and errno == EPERM.
779


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
780
    }
781
  }
782
#endif  // __POSIX__
783
}
784
785
786
10650
int ProcessGlobalArgs(std::vector<std::string>* args,
787
                      std::vector<std::string>* exec_args,
788
                      std::vector<std::string>* errors,
789
                      OptionEnvvarSettings settings) {
790
  // Parse a few arguments which are specific to Node.
791
21300
  std::vector<std::string> v8_args;
792
793
21300
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
794
10650
  options_parser::Parse(
795
      args,
796
      exec_args,
797
      &v8_args,
798
      per_process::cli_options.get(),
799
      settings,
800
      errors);
801
802
10650
  if (!errors->empty()) return 9;
803
804
21200
  std::string revert_error;
805
10600
  for (const std::string& cve : per_process::cli_options->security_reverts) {
806
1
    Revert(cve.c_str(), &revert_error);
807
1
    if (!revert_error.empty()) {
808
1
      errors->emplace_back(std::move(revert_error));
809
1
      return 12;
810
    }
811
  }
812
813
21197
  if (per_process::cli_options->disable_proto != "delete" &&
814

21197
      per_process::cli_options->disable_proto != "throw" &&
815
10597
      per_process::cli_options->disable_proto != "") {
816
    errors->emplace_back("invalid mode passed to --disable-proto");
817
    return 12;
818
  }
819
820
  // TODO(aduh95): remove this when the harmony-import-assertions flag
821
  // is removed in V8.
822
21198
  if (std::find(v8_args.begin(), v8_args.end(),
823
10599
                "--no-harmony-import-assertions") == v8_args.end()) {
824
10599
    v8_args.emplace_back("--harmony-import-assertions");
825
  }
826
827
21198
  auto env_opts = per_process::cli_options->per_isolate->per_env;
828
21198
  if (std::find(v8_args.begin(), v8_args.end(),
829

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

16016
  if (!(flags & ProcessInitializationFlags::kNoUseLargePages) &&
1008
10677
      (per_process::cli_options->use_largepages == "on" ||
1009
5338
       per_process::cli_options->use_largepages == "silent")) {
1010
1
    int lp_result = node::MapStaticCodeToLargePages();
1011

1
    if (per_process::cli_options->use_largepages == "on" && lp_result != 0) {
1012
      result->errors_.emplace_back(node::LargePagesError(lp_result));
1013
    }
1014
  }
1015
1016
5339
  if (!(flags & ProcessInitializationFlags::kNoPrintHelpOrVersionOutput)) {
1017
5339
    if (per_process::cli_options->print_version) {
1018
3
      printf("%s\n", NODE_VERSION);
1019
3
      result->exit_code_ = 0;
1020
3
      result->early_return_ = true;
1021
3
      return result;
1022
    }
1023
1024
5336
    if (per_process::cli_options->print_bash_completion) {
1025
2
      std::string completion = options_parser::GetBashCompletion();
1026
1
      printf("%s\n", completion.c_str());
1027
1
      result->exit_code_ = 0;
1028
1
      result->early_return_ = true;
1029
1
      return result;
1030
    }
1031
1032
5335
    if (per_process::cli_options->print_v8_help) {
1033
      V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1034
      result->exit_code_ = 0;
1035
      result->early_return_ = true;
1036
      return result;
1037
    }
1038
  }
1039
1040
5335
  if (!(flags & ProcessInitializationFlags::kNoInitOpenSSL)) {
1041
#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1042
2
    auto GetOpenSSLErrorString = []() -> std::string {
1043
2
      std::string ret;
1044
2
      ERR_print_errors_cb(
1045
2
          [](const char* str, size_t len, void* opaque) {
1046
2
            std::string* ret = static_cast<std::string*>(opaque);
1047
2
            ret->append(str, len);
1048
2
            ret->append("\n");
1049
2
            return 0;
1050
          },
1051
          static_cast<void*>(&ret));
1052
2
      return ret;
1053
    };
1054
1055
    {
1056
10670
      std::string extra_ca_certs;
1057
5335
      if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1058
4
        crypto::UseExtraCaCerts(extra_ca_certs);
1059
    }
1060
    // In the case of FIPS builds we should make sure
1061
    // the random source is properly initialized first.
1062
#if OPENSSL_VERSION_MAJOR >= 3
1063
    // Call OPENSSL_init_crypto to initialize OPENSSL_INIT_LOAD_CONFIG to
1064
    // avoid the default behavior where errors raised during the parsing of the
1065
    // OpenSSL configuration file are not propagated and cannot be detected.
1066
    //
1067
    // If FIPS is configured the OpenSSL configuration file will have an
1068
    // .include pointing to the fipsmodule.cnf file generated by the openssl
1069
    // fipsinstall command. If the path to this file is incorrect no error
1070
    // will be reported.
1071
    //
1072
    // For Node.js this will mean that EntropySource will be called by V8 as
1073
    // part of its initialization process, and EntropySource will in turn call
1074
    // CheckEntropy. CheckEntropy will call RAND_status which will now always
1075
    // return 0, leading to an endless loop and the node process will appear to
1076
    // hang/freeze.
1077
1078
    // Passing NULL as the config file will allow the default openssl.cnf file
1079
    // to be loaded, but the default section in that file will not be used,
1080
    // instead only the section that matches the value of conf_section_name
1081
    // will be read from the default configuration file.
1082
5335
    const char* conf_file = nullptr;
1083
    // To allow for using the previous default where the 'openssl_conf' appname
1084
    // was used, the command line option 'openssl-shared-config' can be used to
1085
    // force the old behavior.
1086
5335
    if (per_process::cli_options->openssl_shared_config) {
1087
      conf_section_name = "openssl_conf";
1088
    }
1089
    // Use OPENSSL_CONF environment variable is set.
1090
5335
    std::string env_openssl_conf;
1091
5335
    credentials::SafeGetenv("OPENSSL_CONF", &env_openssl_conf);
1092
5335
    if (!env_openssl_conf.empty()) {
1093
1
      conf_file = env_openssl_conf.c_str();
1094
    }
1095
    // Use --openssl-conf command line option if specified.
1096
5335
    if (!per_process::cli_options->openssl_config.empty()) {
1097
      conf_file = per_process::cli_options->openssl_config.c_str();
1098
    }
1099
1100
5335
    OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
1101
5335
    OPENSSL_INIT_set_config_filename(settings, conf_file);
1102
5335
    OPENSSL_INIT_set_config_appname(settings, conf_section_name);
1103
5335
    OPENSSL_INIT_set_config_file_flags(settings,
1104
                                       CONF_MFLAGS_IGNORE_MISSING_FILE);
1105
1106
5335
    OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
1107
5335
    OPENSSL_INIT_free(settings);
1108
1109
5335
    if (ERR_peek_error() != 0) {
1110
      // XXX: ERR_GET_REASON does not return something that is
1111
      // useful as an exit code at all.
1112
      result->exit_code_ = ERR_GET_REASON(ERR_peek_error());
1113
      result->early_return_ = true;
1114
      result->errors_.emplace_back("OpenSSL configuration error:\n" +
1115
                                   GetOpenSSLErrorString());
1116
      return result;
1117
    }
1118
#else  // OPENSSL_VERSION_MAJOR < 3
1119
    if (FIPS_mode()) {
1120
      OPENSSL_init();
1121
    }
1122
#endif
1123
5335
    if (!crypto::ProcessFipsOptions()) {
1124
      // XXX: ERR_GET_REASON does not return something that is
1125
      // useful as an exit code at all.
1126
2
      result->exit_code_ = ERR_GET_REASON(ERR_peek_error());
1127
2
      result->early_return_ = true;
1128
2
      result->errors_.emplace_back(
1129
4
          "OpenSSL error when trying to enable FIPS:\n" +
1130
6
          GetOpenSSLErrorString());
1131
2
      return result;
1132
    }
1133
1134
    // V8 on Windows doesn't have a good source of entropy. Seed it from
1135
    // OpenSSL's pool.
1136
5333
    V8::SetEntropySource(crypto::EntropySource);
1137
#endif  // HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1138
  }
1139
1140
5333
  if (!(flags & ProcessInitializationFlags::kNoInitializeNodeV8Platform)) {
1141
5326
    per_process::v8_platform.Initialize(
1142
5326
        static_cast<int>(per_process::cli_options->v8_thread_pool_size));
1143
5326
    result->platform_ = per_process::v8_platform.Platform();
1144
  }
1145
1146
5333
  if (!(flags & ProcessInitializationFlags::kNoInitializeV8)) {
1147
    V8::Initialize();
1148
  }
1149
1150
5333
  performance::performance_v8_start = PERFORMANCE_NOW();
1151
5333
  per_process::v8_initialized = true;
1152
1153
5333
  return result;
1154
}
1155
1156
4801
void TearDownOncePerProcess() {
1157
4801
  const uint64_t flags = init_process_flags.load();
1158
4801
  ResetStdio();
1159
4801
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
1160
4801
    ResetSignalHandlers();
1161
  }
1162
1163
4801
  per_process::v8_initialized = false;
1164
4801
  if (!(flags & ProcessInitializationFlags::kNoInitializeV8)) {
1165
4796
    V8::Dispose();
1166
  }
1167
1168
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1169
  if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
1170
    RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1171
  }
1172
#endif
1173
1174
4801
  if (!(flags & ProcessInitializationFlags::kNoInitializeNodeV8Platform)) {
1175
4796
    V8::DisposePlatform();
1176
    // uv_run cannot be called from the time before the beforeExit callback
1177
    // runs until the program exits unless the event loop has any referenced
1178
    // handles after beforeExit terminates. This prevents unrefed timers
1179
    // that happen to terminate during shutdown from being run unsafely.
1180
    // Since uv_run cannot be called, uv_async handles held by the platform
1181
    // will never be fully cleaned up.
1182
4796
    per_process::v8_platform.Dispose();
1183
  }
1184
4801
}
1185
1186
9718
InitializationResult::~InitializationResult() {}
1187
9718
InitializationResultImpl::~InitializationResultImpl() {}
1188
1189
3
int GenerateAndWriteSnapshotData(const SnapshotData** snapshot_data_ptr,
1190
                                 const InitializationResult* result) {
1191
3
  int exit_code = result->exit_code();
1192
  // nullptr indicates there's no snapshot data.
1193
  DCHECK_NULL(*snapshot_data_ptr);
1194
1195
  // node:embedded_snapshot_main indicates that we are using the
1196
  // embedded snapshot and we are not supposed to clean it up.
1197
3
  if (result->args()[1] == "node:embedded_snapshot_main") {
1198
2
    *snapshot_data_ptr = SnapshotBuilder::GetEmbeddedSnapshotData();
1199
2
    if (*snapshot_data_ptr == nullptr) {
1200
      // The Node.js binary is built without embedded snapshot
1201
      fprintf(stderr,
1202
              "node:embedded_snapshot_main was specified as snapshot "
1203
              "entry point but Node.js was built without embedded "
1204
              "snapshot.\n");
1205
      exit_code = 1;
1206
      return exit_code;
1207
    }
1208
  } else {
1209
    // Otherwise, load and run the specified main script.
1210
    std::unique_ptr<SnapshotData> generated_data =
1211
1
        std::make_unique<SnapshotData>();
1212
2
    exit_code = node::SnapshotBuilder::Generate(
1213
2
        generated_data.get(), result->args(), result->exec_args());
1214
1
    if (exit_code == 0) {
1215
      *snapshot_data_ptr = generated_data.release();
1216
    } else {
1217
1
      return exit_code;
1218
    }
1219
  }
1220
1221
  // Get the path to write the snapshot blob to.
1222
2
  std::string snapshot_blob_path;
1223
2
  if (!per_process::cli_options->snapshot_blob.empty()) {
1224
1
    snapshot_blob_path = per_process::cli_options->snapshot_blob;
1225
  } else {
1226
    // Defaults to snapshot.blob in the current working directory.
1227
1
    snapshot_blob_path = std::string("snapshot.blob");
1228
  }
1229
1230
2
  FILE* fp = fopen(snapshot_blob_path.c_str(), "wb");
1231
2
  if (fp != nullptr) {
1232
2
    (*snapshot_data_ptr)->ToBlob(fp);
1233
2
    fclose(fp);
1234
  } else {
1235
    fprintf(stderr,
1236
            "Cannot open %s for writing a snapshot.\n",
1237
            snapshot_blob_path.c_str());
1238
    exit_code = 1;
1239
  }
1240
2
  return exit_code;
1241
}
1242
1243
5316
int LoadSnapshotDataAndRun(const SnapshotData** snapshot_data_ptr,
1244
                           const InitializationResult* result) {
1245
5316
  int exit_code = result->exit_code();
1246
  // nullptr indicates there's no snapshot data.
1247
  DCHECK_NULL(*snapshot_data_ptr);
1248
  // --snapshot-blob indicates that we are reading a customized snapshot.
1249
5316
  if (!per_process::cli_options->snapshot_blob.empty()) {
1250
3
    std::string filename = per_process::cli_options->snapshot_blob;
1251
3
    FILE* fp = fopen(filename.c_str(), "rb");
1252
3
    if (fp == nullptr) {
1253
1
      fprintf(stderr, "Cannot open %s", filename.c_str());
1254
1
      exit_code = 1;
1255
1
      return exit_code;
1256
    }
1257
4
    std::unique_ptr<SnapshotData> read_data = std::make_unique<SnapshotData>();
1258
2
    SnapshotData::FromBlob(read_data.get(), fp);
1259
2
    *snapshot_data_ptr = read_data.release();
1260
2
    fclose(fp);
1261
5313
  } else if (per_process::cli_options->node_snapshot) {
1262
    // If --snapshot-blob is not specified, we are reading the embedded
1263
    // snapshot, but we will skip it if --no-node-snapshot is specified.
1264
5311
    *snapshot_data_ptr = SnapshotBuilder::GetEmbeddedSnapshotData();
1265
  }
1266
1267
5315
  if ((*snapshot_data_ptr) != nullptr) {
1268
5313
    NativeModuleLoader::RefreshCodeCache((*snapshot_data_ptr)->code_cache);
1269
  }
1270
  NodeMainInstance main_instance(*snapshot_data_ptr,
1271
                                 uv_default_loop(),
1272
5315
                                 per_process::v8_platform.Platform(),
1273
5315
                                 result->args(),
1274
10630
                                 result->exec_args());
1275
5315
  exit_code = main_instance.Run();
1276
4785
  return exit_code;
1277
}
1278
1279
5378
int Start(int argc, char** argv) {
1280
5378
  CHECK_GT(argc, 0);
1281
1282
  // Hack around with the argv pointer. Used for process.title = "blah".
1283
5378
  argv = uv_setup_args(argc, argv);
1284
1285
  std::unique_ptr<InitializationResult> result =
1286
15604
      InitializeOncePerProcess(std::vector<std::string>(argv, argv + argc));
1287
5433
  for (const std::string& error : result->errors()) {
1288
55
    FPrintF(stderr, "%s: %s\n", result->args().at(0), error);
1289
  }
1290
5378
  if (result->early_return()) {
1291
58
    return result->exit_code();
1292
  }
1293
1294
  DCHECK_EQ(result->exit_code(), 0);
1295
5320
  const SnapshotData* snapshot_data = nullptr;
1296
1297
4790
  auto cleanup_process = OnScopeLeave([&]() {
1298
4790
    TearDownOncePerProcess();
1299
1300
4790
    if (snapshot_data != nullptr &&
1301
4785
        snapshot_data->data_ownership == SnapshotData::DataOwnership::kOwned) {
1302
2
      delete snapshot_data;
1303
    }
1304
10110
  });
1305
1306
5320
  uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1307
1308
  // --build-snapshot indicates that we are in snapshot building mode.
1309
5320
  if (per_process::cli_options->build_snapshot) {
1310
4
    if (result->args().size() < 2) {
1311
1
      fprintf(stderr,
1312
              "--build-snapshot must be used with an entry point script.\n"
1313
              "Usage: node --build-snapshot /path/to/entry.js\n");
1314
1
      return 9;
1315
    }
1316
3
    return GenerateAndWriteSnapshotData(&snapshot_data, result.get());
1317
  }
1318
1319
  // Without --build-snapshot, we are in snapshot loading mode.
1320
5316
  return LoadSnapshotDataAndRun(&snapshot_data, result.get());
1321
}
1322
1323
317
int Stop(Environment* env) {
1324
317
  env->ExitEnv();
1325
317
  return 0;
1326
}
1327
1328
}  // namespace node
1329
1330
#if !HAVE_INSPECTOR
1331
void Initialize() {}
1332
1333
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1334
#endif  // !HAVE_INSPECTOR