GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 400 458 87.3 %
Date: 2022-06-20 04:16:14 Branches: 231 341 67.7 %

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_env.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 defined HAVE_DTRACE || defined HAVE_ETW
59
#include "node_dtrace.h"
60
#endif
61
62
#if NODE_USE_V8_PLATFORM
63
#include "libplatform/libplatform.h"
64
#endif  // NODE_USE_V8_PLATFORM
65
#include "v8-profiler.h"
66
67
#if HAVE_INSPECTOR
68
#include "inspector/worker_inspector.h"  // ParentInspectorHandle
69
#endif
70
71
#include "large_pages/node_large_page.h"
72
73
#if defined(__APPLE__) || defined(__linux__) || defined(_WIN32)
74
#define NODE_USE_V8_WASM_TRAP_HANDLER 1
75
#else
76
#define NODE_USE_V8_WASM_TRAP_HANDLER 0
77
#endif
78
79
#if NODE_USE_V8_WASM_TRAP_HANDLER
80
#if defined(_WIN32)
81
#include "v8-wasm-trap-handler-win.h"
82
#else
83
#include <atomic>
84
#include "v8-wasm-trap-handler-posix.h"
85
#endif
86
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
87
88
// ========== global C headers ==========
89
90
#include <fcntl.h>  // _O_RDWR
91
#include <sys/types.h>
92
93
#if defined(NODE_HAVE_I18N_SUPPORT)
94
#include <unicode/uvernum.h>
95
#include <unicode/utypes.h>
96
#endif
97
98
99
#if defined(LEAK_SANITIZER)
100
#include <sanitizer/lsan_interface.h>
101
#endif
102
103
#if defined(_MSC_VER)
104
#include <direct.h>
105
#include <io.h>
106
#define STDIN_FILENO 0
107
#else
108
#include <pthread.h>
109
#include <sys/resource.h>  // getrlimit, setrlimit
110
#include <termios.h>       // tcgetattr, tcsetattr
111
#include <unistd.h>        // STDIN_FILENO, STDERR_FILENO
112
#endif
113
114
// ========== global C++ headers ==========
115
116
#include <cerrno>
117
#include <climits>  // PATH_MAX
118
#include <csignal>
119
#include <cstdio>
120
#include <cstdlib>
121
#include <cstring>
122
123
#include <string>
124
#include <vector>
125
126
namespace node {
127
128
using native_module::NativeModuleEnv;
129
130
using v8::EscapableHandleScope;
131
using v8::Function;
132
using v8::FunctionCallbackInfo;
133
using v8::Isolate;
134
using v8::Local;
135
using v8::MaybeLocal;
136
using v8::Object;
137
using v8::String;
138
using v8::Undefined;
139
using v8::V8;
140
using v8::Value;
141
142
namespace per_process {
143
144
// node_revert.h
145
// Bit flag used to track security reverts.
146
unsigned int reverted_cve = 0;
147
148
// util.h
149
// Tells whether the per-process V8::Initialize() is called and
150
// if it is safe to call v8::Isolate::TryGetCurrent().
151
bool v8_initialized = false;
152
153
// node_internals.h
154
// process-relative uptime base in nanoseconds, initialized in node::Start()
155
uint64_t node_start_time;
156
157
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
158
PVOID old_vectored_exception_handler;
159
#endif
160
161
// node_v8_platform-inl.h
162
struct V8Platform v8_platform;
163
}  // namespace per_process
164
165
// The section in the OpenSSL configuration file to be loaded.
166
const char* conf_section_name = STRINGIFY(NODE_OPENSSL_CONF_NAME);
167
168
#ifdef __POSIX__
169
void SignalExit(int signo, siginfo_t* info, void* ucontext) {
170
  ResetStdio();
171
  raise(signo);
172
}
173
#endif  // __POSIX__
174
175
12805
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
176
                                      const char* id,
177
                                      std::vector<Local<String>>* parameters,
178
                                      std::vector<Local<Value>>* arguments) {
179
12805
  EscapableHandleScope scope(env->isolate());
180
  MaybeLocal<Function> maybe_fn =
181
12805
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
182
183
  Local<Function> fn;
184
12805
  if (!maybe_fn.ToLocal(&fn)) {
185
    return MaybeLocal<Value>();
186
  }
187
188
  MaybeLocal<Value> result = fn->Call(env->context(),
189
                                      Undefined(env->isolate()),
190
12805
                                      arguments->size(),
191
38415
                                      arguments->data());
192
193
  // If there was an error during bootstrap, it must be unrecoverable
194
  // (e.g. max call stack exceeded). Clear the stack so that the
195
  // AsyncCallbackScope destructor doesn't fail on the id check.
196
  // There are only two ways to have a stack size > 1: 1) the user manually
197
  // called MakeCallback or 2) user awaited during bootstrap, which triggered
198
  // _tickCallback().
199
12564
  if (result.IsEmpty()) {
200
33
    env->async_hooks()->clear_async_id_stack();
201
  }
202
203
12564
  return scope.EscapeMaybe(result);
204
}
205
206
#if HAVE_INSPECTOR
207
6470
int Environment::InitializeInspector(
208
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
209
12940
  std::string inspector_path;
210
6470
  bool is_main = !parent_handle;
211
6470
  if (parent_handle) {
212
1214
    inspector_path = parent_handle->url();
213
1214
    inspector_agent_->SetParentHandle(std::move(parent_handle));
214
  } else {
215
5256
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
216
  }
217
218
6470
  CHECK(!inspector_agent_->IsListening());
219
  // Inspector agent can't fail to start, but if it was configured to listen
220
  // right away on the websocket port and fails to bind/etc, this will return
221
  // false.
222
12940
  inspector_agent_->Start(inspector_path,
223
6470
                          options_->debug_options(),
224
12940
                          inspector_host_port(),
225
                          is_main);
226

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

8
  switch (event) {
259
#define V(key, msg)                         \
260
    case Isolate::AtomicsWaitEvent::key:    \
261
      message = msg;                        \
262
      break;
263
8
    ATOMIC_WAIT_EVENTS(V)
264
#undef V
265
  }
266
267
16
  fprintf(stderr,
268
          "(node:%d) [Thread %" PRIu64 "] Atomics.wait(%p + %zx, %" PRId64
269
              ", %.f) %s\n",
270
8
          static_cast<int>(uv_os_getpid()),
271
          env->thread_id(),
272
16
          array_buffer->GetBackingStore()->Data(),
273
          offset_in_bytes,
274
          value,
275
          timeout_in_ms,
276
          message);
277
8
}
278
279
6443
void Environment::InitializeDiagnostics() {
280
6443
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
281
      Environment::BuildEmbedderGraph, this);
282
6443
  if (options_->heap_snapshot_near_heap_limit > 0) {
283
1
    isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
284
                                       this);
285
  }
286
6443
  if (options_->trace_uncaught)
287
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
288
6443
  if (options_->trace_atomics_wait) {
289
2
    isolate_->SetAtomicsWaitCallback(AtomicsWaitCallback, this);
290
2
    AddCleanupHook([](void* data) {
291
2
      Environment* env = static_cast<Environment*>(data);
292
2
      env->isolate()->SetAtomicsWaitCallback(nullptr, nullptr);
293
2
    }, this);
294
  }
295
296
#if defined HAVE_DTRACE || defined HAVE_ETW
297
  InitDTrace(this);
298
#endif
299
6443
}
300
301
1269
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
302
1269
  EscapableHandleScope scope(isolate_);
303
304
  // Create binding loaders
305
  std::vector<Local<String>> loaders_params = {
306
1269
      process_string(),
307
1269
      FIXED_ONE_BYTE_STRING(isolate_, "getLinkedBinding"),
308
1269
      FIXED_ONE_BYTE_STRING(isolate_, "getInternalBinding"),
309
2538
      primordials_string()};
310
  std::vector<Local<Value>> loaders_args = {
311
      process_object(),
312
1269
      NewFunctionTemplate(binding::GetLinkedBinding)
313
1269
          ->GetFunction(context())
314
          .ToLocalChecked(),
315
1269
      NewFunctionTemplate(binding::GetInternalBinding)
316
1269
          ->GetFunction(context())
317
          .ToLocalChecked(),
318
8883
      primordials()};
319
320
  // Bootstrap internal loaders
321
  Local<Value> loader_exports;
322
1269
  if (!ExecuteBootstrapper(
323
1269
           this, "internal/bootstrap/loaders", &loaders_params, &loaders_args)
324
1269
           .ToLocal(&loader_exports)) {
325
    return MaybeLocal<Value>();
326
  }
327
1269
  CHECK(loader_exports->IsObject());
328
1269
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
329
  Local<Value> internal_binding_loader =
330
2538
      loader_exports_obj->Get(context(), internal_binding_string())
331
1269
          .ToLocalChecked();
332
1269
  CHECK(internal_binding_loader->IsFunction());
333
1269
  set_internal_binding_loader(internal_binding_loader.As<Function>());
334
  Local<Value> require =
335
3807
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
336
1269
  CHECK(require->IsFunction());
337
1269
  set_native_module_require(require.As<Function>());
338
339
1269
  return scope.Escape(loader_exports);
340
}
341
342
1269
MaybeLocal<Value> Environment::BootstrapNode() {
343
1269
  EscapableHandleScope scope(isolate_);
344
345
2538
  Local<Object> global = context()->Global();
346
  // TODO(joyeecheung): this can be done in JS land now.
347
2538
  global->Set(context(), FIXED_ONE_BYTE_STRING(isolate_, "global"), global)
348
      .Check();
349
350
  // process, require, internalBinding, primordials
351
  std::vector<Local<String>> node_params = {
352
1269
      process_string(),
353
1269
      require_string(),
354
1269
      internal_binding_string(),
355
2538
      primordials_string()};
356
  std::vector<Local<Value>> node_args = {
357
      process_object(),
358
      native_module_require(),
359
      internal_binding_loader(),
360
7614
      primordials()};
361
362
  MaybeLocal<Value> result = ExecuteBootstrapper(
363
1269
      this, "internal/bootstrap/node", &node_params, &node_args);
364
365
1269
  if (result.IsEmpty()) {
366
    return MaybeLocal<Value>();
367
  }
368
369
1269
  if (!no_browser_globals()) {
370
    result = ExecuteBootstrapper(
371
1269
        this, "internal/bootstrap/browser", &node_params, &node_args);
372
373
1269
    if (result.IsEmpty()) {
374
      return MaybeLocal<Value>();
375
    }
376
  }
377
378
  // TODO(joyeecheung): skip these in the snapshot building for workers.
379
  auto thread_switch_id =
380
1269
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
381
1269
                       : "internal/bootstrap/switches/is_not_main_thread";
382
  result =
383
1269
      ExecuteBootstrapper(this, thread_switch_id, &node_params, &node_args);
384
385
1269
  if (result.IsEmpty()) {
386
    return MaybeLocal<Value>();
387
  }
388
389
  auto process_state_switch_id =
390
1269
      owns_process_state()
391
1269
          ? "internal/bootstrap/switches/does_own_process_state"
392
1269
          : "internal/bootstrap/switches/does_not_own_process_state";
393
  result = ExecuteBootstrapper(
394
1269
      this, process_state_switch_id, &node_params, &node_args);
395
396
1269
  if (result.IsEmpty()) {
397
    return MaybeLocal<Value>();
398
  }
399
400
1269
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
401
  Local<Object> env_var_proxy;
402
3807
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
403

5076
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
404
    return MaybeLocal<Value>();
405
  }
406
407
1269
  return scope.EscapeMaybe(result);
408
}
409
410
1269
MaybeLocal<Value> Environment::RunBootstrapping() {
411
1269
  EscapableHandleScope scope(isolate_);
412
413
1269
  CHECK(!has_run_bootstrapping_code());
414
415
2538
  if (BootstrapInternalLoaders().IsEmpty()) {
416
    return MaybeLocal<Value>();
417
  }
418
419
  Local<Value> result;
420
2538
  if (!BootstrapNode().ToLocal(&result)) {
421
    return MaybeLocal<Value>();
422
  }
423
424
  // Make sure that no request or handle is created during bootstrap -
425
  // if necessary those should be done in pre-execution.
426
  // Usually, doing so would trigger the checks present in the ReqWrap and
427
  // HandleWrap classes, so this is only a consistency check.
428
1269
  CHECK(req_wrap_queue()->IsEmpty());
429
1269
  CHECK(handle_wrap_queue()->IsEmpty());
430
431
1269
  DoneBootstrapping();
432
433
1269
  return scope.Escape(result);
434
}
435
436
6434
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
437
6434
  Environment* env = Environment::GetCurrent(args);
438
6434
  env->performance_state()->Mark(
439
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
440
6434
}
441
442
static
443
6443
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
444
6443
  EscapableHandleScope scope(env->isolate());
445
6443
  CHECK_NOT_NULL(main_script_id);
446
447
  std::vector<Local<String>> parameters = {
448
6443
      env->process_string(),
449
6443
      env->require_string(),
450
6443
      env->internal_binding_string(),
451
6443
      env->primordials_string(),
452
12647
      FIXED_ONE_BYTE_STRING(env->isolate(), "markBootstrapComplete")};
453
454
  std::vector<Local<Value>> arguments = {
455
      env->process_object(),
456
      env->native_module_require(),
457
      env->internal_binding_loader(),
458
      env->primordials(),
459
6443
      env->NewFunctionTemplate(MarkBootstrapComplete)
460
6443
          ->GetFunction(env->context())
461
38658
          .ToLocalChecked()};
462
463
  return scope.EscapeMaybe(
464
12647
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
465
}
466
467
6443
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
468
  InternalCallbackScope callback_scope(
469
      env,
470
      Object::New(env->isolate()),
471
      { 1, 0 },
472
12645
      InternalCallbackScope::kSkipAsyncHooks);
473
474
6443
  if (cb != nullptr) {
475
22
    EscapableHandleScope scope(env->isolate());
476
477
44
    if (StartExecution(env, "internal/bootstrap/environment").IsEmpty())
478
      return {};
479
480
    StartExecutionCallbackInfo info = {
481
22
      env->process_object(),
482
22
      env->native_module_require(),
483
    };
484
485
42
    return scope.EscapeMaybe(cb(info));
486
  }
487
488
  // TODO(joyeecheung): move these conditions into JS land and let the
489
  // deserialize main function take precedence. For workers, we need to
490
  // move the pre-execution part into a different file that can be
491
  // reused when dealing with user-defined main functions.
492
12842
  if (!env->snapshot_deserialize_main().IsEmpty()) {
493
    return env->RunSnapshotDeserializeMain();
494
  }
495
496
6421
  if (env->worker_context() != nullptr) {
497
1212
    return StartExecution(env, "internal/main/worker_thread");
498
  }
499
500
10179
  std::string first_argv;
501
5209
  if (env->argv().size() > 1) {
502
4719
    first_argv = env->argv()[1];
503
  }
504
505
5209
  if (first_argv == "inspect") {
506
37
    return StartExecution(env, "internal/main/inspect");
507
  }
508
509
5172
  if (per_process::cli_options->build_snapshot) {
510
    return StartExecution(env, "internal/main/mksnapshot");
511
  }
512
513
5172
  if (per_process::cli_options->print_help) {
514
1
    return StartExecution(env, "internal/main/print_help");
515
  }
516
517
518
5171
  if (env->options()->prof_process) {
519
1
    return StartExecution(env, "internal/main/prof_process");
520
  }
521
522
  // -e/--eval without -i/--interactive
523


5170
  if (env->options()->has_eval_string && !env->options()->force_repl) {
524
457
    return StartExecution(env, "internal/main/eval_string");
525
  }
526
527
4713
  if (env->options()->syntax_check_only) {
528
36
    return StartExecution(env, "internal/main/check_syntax");
529
  }
530
531
4677
  if (env->options()->test_runner) {
532
5
    return StartExecution(env, "internal/main/test_runner");
533
  }
534
535

4672
  if (!first_argv.empty() && first_argv != "-") {
536
4629
    return StartExecution(env, "internal/main/run_main_module");
537
  }
538
539


43
  if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
540
26
    return StartExecution(env, "internal/main/repl");
541
  }
542
543
17
  return StartExecution(env, "internal/main/eval_stdin");
544
}
545
546
#ifdef __POSIX__
547
typedef void (*sigaction_cb)(int signo, siginfo_t* info, void* ucontext);
548
#endif
549
#if NODE_USE_V8_WASM_TRAP_HANDLER
550
#if defined(_WIN32)
551
static LONG TrapWebAssemblyOrContinue(EXCEPTION_POINTERS* exception) {
552
  if (v8::TryHandleWebAssemblyTrapWindows(exception)) {
553
    return EXCEPTION_CONTINUE_EXECUTION;
554
  }
555
  return EXCEPTION_CONTINUE_SEARCH;
556
}
557
#else
558
static std::atomic<sigaction_cb> previous_sigsegv_action;
559
560
6
void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) {
561
6
  if (!v8::TryHandleWebAssemblyTrapPosix(signo, info, ucontext)) {
562
6
    sigaction_cb prev = previous_sigsegv_action.load();
563
6
    if (prev != nullptr) {
564
6
      prev(signo, info, ucontext);
565
    } else {
566
      // Reset to the default signal handler, i.e. cause a hard crash.
567
      struct sigaction sa;
568
      memset(&sa, 0, sizeof(sa));
569
      sa.sa_handler = SIG_DFL;
570
      CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
571
572
      ResetStdio();
573
      raise(signo);
574
    }
575
  }
576
6
}
577
#endif  // defined(_WIN32)
578
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
579
580
#ifdef __POSIX__
581
16210
void RegisterSignalHandler(int signal,
582
                           sigaction_cb handler,
583
                           bool reset_handler) {
584
16210
  CHECK_NOT_NULL(handler);
585
#if NODE_USE_V8_WASM_TRAP_HANDLER
586
16210
  if (signal == SIGSEGV) {
587
4
    CHECK(previous_sigsegv_action.is_lock_free());
588
4
    CHECK(!reset_handler);
589
4
    previous_sigsegv_action.store(handler);
590
4
    return;
591
  }
592
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
593
  struct sigaction sa;
594
16206
  memset(&sa, 0, sizeof(sa));
595
16206
  sa.sa_sigaction = handler;
596
16206
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
597
16206
  sigfillset(&sa.sa_mask);
598
16206
  CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
599
}
600
#endif  // __POSIX__
601
602
#ifdef __POSIX__
603
static struct {
604
  int flags;
605
  bool isatty;
606
  struct stat stat;
607
  struct termios termios;
608
} stdio[1 + STDERR_FILENO];
609
#endif  // __POSIX__
610
611
612
5273
inline void PlatformInit() {
613
#ifdef __POSIX__
614
#if HAVE_INSPECTOR
615
  sigset_t sigmask;
616
5273
  sigemptyset(&sigmask);
617
5273
  sigaddset(&sigmask, SIGUSR1);
618
5273
  const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
619
#endif  // HAVE_INSPECTOR
620
621
  // Make sure file descriptors 0-2 are valid before we start logging anything.
622
21092
  for (auto& s : stdio) {
623
15819
    const int fd = &s - stdio;
624
15819
    if (fstat(fd, &s.stat) == 0)
625
15817
      continue;
626
    // Anything but EBADF means something is seriously wrong.  We don't
627
    // have to special-case EINTR, fstat() is not interruptible.
628
2
    if (errno != EBADF)
629
      ABORT();
630
2
    if (fd != open("/dev/null", O_RDWR))
631
      ABORT();
632
2
    if (fstat(fd, &s.stat) != 0)
633
      ABORT();
634
  }
635
636
#if HAVE_INSPECTOR
637
5273
  CHECK_EQ(err, 0);
638
#endif  // HAVE_INSPECTOR
639
640
  // TODO(addaleax): NODE_SHARED_MODE does not really make sense here.
641
#ifndef NODE_SHARED_MODE
642
  // Restore signal dispositions, the parent process may have changed them.
643
  struct sigaction act;
644
5273
  memset(&act, 0, sizeof(act));
645
646
  // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
647
  // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
648
  // Counting up to SIGRTMIN doesn't work for the same reason.
649
168736
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
650

163463
    if (nr == SIGKILL || nr == SIGSTOP)
651
10546
      continue;
652

152917
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
653
152917
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
654
  }
655
#endif  // !NODE_SHARED_MODE
656
657
  // Record the state of the stdio file descriptors so we can restore it
658
  // on exit.  Needs to happen before installing signal handlers because
659
  // they make use of that information.
660
21092
  for (auto& s : stdio) {
661
15819
    const int fd = &s - stdio;
662
    int err;
663
664
    do
665
15819
      s.flags = fcntl(fd, F_GETFL);
666

15819
    while (s.flags == -1 && errno == EINTR);  // NOLINT
667
15819
    CHECK_NE(s.flags, -1);
668
669
15819
    if (uv_guess_handle(fd) != UV_TTY) continue;
670
120
    s.isatty = true;
671
672
    do
673
120
      err = tcgetattr(fd, &s.termios);
674

120
    while (err == -1 && errno == EINTR);  // NOLINT
675
120
    CHECK_EQ(err, 0);
676
  }
677
678
5273
  RegisterSignalHandler(SIGINT, SignalExit, true);
679
5273
  RegisterSignalHandler(SIGTERM, SignalExit, true);
680
681
#if NODE_USE_V8_WASM_TRAP_HANDLER
682
#if defined(_WIN32)
683
  {
684
    constexpr ULONG first = TRUE;
685
    per_process::old_vectored_exception_handler =
686
        AddVectoredExceptionHandler(first, TrapWebAssemblyOrContinue);
687
  }
688
#else
689
  // Tell V8 to disable emitting WebAssembly
690
  // memory bounds checks. This means that we have
691
  // to catch the SIGSEGV in TrapWebAssemblyOrContinue
692
  // and pass the signal context to V8.
693
  {
694
    struct sigaction sa;
695
5273
    memset(&sa, 0, sizeof(sa));
696
5273
    sa.sa_sigaction = TrapWebAssemblyOrContinue;
697
5273
    sa.sa_flags = SA_SIGINFO;
698
5273
    CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
699
  }
700
#endif  // defined(_WIN32)
701
5273
  V8::EnableWebAssemblyTrapHandler(false);
702
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
703
704
  // Raise the open file descriptor limit.
705
  struct rlimit lim;
706

5273
  if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
707
    // Do a binary search for the limit.
708
    rlim_t min = lim.rlim_cur;
709
    rlim_t max = 1 << 20;
710
    // But if there's a defined upper bound, don't search, just set it.
711
    if (lim.rlim_max != RLIM_INFINITY) {
712
      min = lim.rlim_max;
713
      max = lim.rlim_max;
714
    }
715
    do {
716
      lim.rlim_cur = min + (max - min) / 2;
717
      if (setrlimit(RLIMIT_NOFILE, &lim)) {
718
        max = lim.rlim_cur;
719
      } else {
720
        min = lim.rlim_cur;
721
      }
722
    } while (min + 1 < max);
723
  }
724
#endif  // __POSIX__
725
#ifdef _WIN32
726
  for (int fd = 0; fd <= 2; ++fd) {
727
    auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
728
    if (handle == INVALID_HANDLE_VALUE ||
729
        GetFileType(handle) == FILE_TYPE_UNKNOWN) {
730
      // Ignore _close result. If it fails or not depends on used Windows
731
      // version. We will just check _open result.
732
      _close(fd);
733
      if (fd != _open("nul", _O_RDWR))
734
        ABORT();
735
    }
736
  }
737
#endif  // _WIN32
738
5273
}
739
740
741
// Safe to call more than once and from signal handlers.
742
9991
void ResetStdio() {
743
9991
  uv_tty_reset_mode();
744
#ifdef __POSIX__
745
39964
  for (auto& s : stdio) {
746
29973
    const int fd = &s - stdio;
747
748
    struct stat tmp;
749
29973
    if (-1 == fstat(fd, &tmp)) {
750
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
751
6
      continue;
752
    }
753
754
29973
    bool is_same_file =
755

29973
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
756
29973
    if (!is_same_file) continue;  // Program reopened file descriptor.
757
758
    int flags;
759
    do
760
29967
      flags = fcntl(fd, F_GETFL);
761

29967
    while (flags == -1 && errno == EINTR);  // NOLINT
762
29967
    CHECK_NE(flags, -1);
763
764
    // Restore the O_NONBLOCK flag if it changed.
765
29967
    if (O_NONBLOCK & (flags ^ s.flags)) {
766
1163
      flags &= ~O_NONBLOCK;
767
1163
      flags |= s.flags & O_NONBLOCK;
768
769
      int err;
770
      do
771
1163
        err = fcntl(fd, F_SETFL, flags);
772

1163
      while (err == -1 && errno == EINTR);  // NOLINT
773
1163
      CHECK_NE(err, -1);
774
    }
775
776
29967
    if (s.isatty) {
777
      sigset_t sa;
778
      int err;
779
780
      // We might be a background job that doesn't own the TTY so block SIGTTOU
781
      // before making the tcsetattr() call, otherwise that signal suspends us.
782
228
      sigemptyset(&sa);
783
228
      sigaddset(&sa, SIGTTOU);
784
785
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
786
      do
787
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
788

228
      while (err == -1 && errno == EINTR);  // NOLINT
789
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
790
791
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
792
      // tcsetattr will fail with err == -1 and errno == EPERM.
793


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
794
    }
795
  }
796
#endif  // __POSIX__
797
9991
}
798
799
800
10428
int ProcessGlobalArgs(std::vector<std::string>* args,
801
                      std::vector<std::string>* exec_args,
802
                      std::vector<std::string>* errors,
803
                      OptionEnvvarSettings settings) {
804
  // Parse a few arguments which are specific to Node.
805
20856
  std::vector<std::string> v8_args;
806
807
20856
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
808
10428
  options_parser::Parse(
809
      args,
810
      exec_args,
811
      &v8_args,
812
      per_process::cli_options.get(),
813
      settings,
814
      errors);
815
816
10428
  if (!errors->empty()) return 9;
817
818
20756
  std::string revert_error;
819
10378
  for (const std::string& cve : per_process::cli_options->security_reverts) {
820
1
    Revert(cve.c_str(), &revert_error);
821
1
    if (!revert_error.empty()) {
822
1
      errors->emplace_back(std::move(revert_error));
823
1
      return 12;
824
    }
825
  }
826
827
20753
  if (per_process::cli_options->disable_proto != "delete" &&
828

20753
      per_process::cli_options->disable_proto != "throw" &&
829
10375
      per_process::cli_options->disable_proto != "") {
830
    errors->emplace_back("invalid mode passed to --disable-proto");
831
    return 12;
832
  }
833
834
  // TODO(aduh95): remove this when the harmony-import-assertions flag
835
  // is removed in V8.
836
20754
  if (std::find(v8_args.begin(), v8_args.end(),
837
10377
                "--no-harmony-import-assertions") == v8_args.end()) {
838
10377
    v8_args.emplace_back("--harmony-import-assertions");
839
  }
840
841
20754
  auto env_opts = per_process::cli_options->per_isolate->per_env;
842
20754
  if (std::find(v8_args.begin(), v8_args.end(),
843

20736
                "--abort-on-uncaught-exception") != v8_args.end() ||
844
10377
      std::find(v8_args.begin(), v8_args.end(),
845
20736
                "--abort_on_uncaught_exception") != v8_args.end()) {
846
21
    env_opts->abort_on_uncaught_exception = true;
847
  }
848
849
#ifdef __POSIX__
850
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
851
  // performance penalty of frequent EINTR wakeups when the profiler is running.
852
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
853
10377
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
854
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
855
  }
856
#endif
857
858
20754
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
859
10377
  if (v8_args.size() > 0) {
860
31269
    for (size_t i = 0; i < v8_args.size(); ++i)
861
20892
      v8_args_as_char_ptr[i] = &v8_args[i][0];
862
10377
    int argc = v8_args.size();
863
10377
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
864
10377
    v8_args_as_char_ptr.resize(argc);
865
  }
866
867
  // Anything that's still in v8_argv is not a V8 or a node option.
868
10378
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
869
1
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
870
871
10377
  if (v8_args_as_char_ptr.size() > 1) return 9;
872
873
10376
  return 0;
874
}
875
876
static std::atomic_bool init_called{false};
877
878
8
int InitializeNodeWithArgs(std::vector<std::string>* argv,
879
                           std::vector<std::string>* exec_argv,
880
                           std::vector<std::string>* errors) {
881
8
  return InitializeNodeWithArgs(argv, exec_argv, errors,
882
8
                                ProcessFlags::kNoFlags);
883
}
884
885
5281
int InitializeNodeWithArgs(std::vector<std::string>* argv,
886
                           std::vector<std::string>* exec_argv,
887
                           std::vector<std::string>* errors,
888
                           ProcessFlags::Flags flags) {
889
  // Make sure InitializeNodeWithArgs() is called only once.
890
5281
  CHECK(!init_called.exchange(true));
891
892
  // Initialize node_start_time to get relative uptime.
893
5281
  per_process::node_start_time = uv_hrtime();
894
895
  // Register built-in modules
896
5281
  binding::RegisterBuiltinModules();
897
898
  // Make inherited handles noninheritable.
899
5281
  if (!(flags & ProcessFlags::kEnableStdioInheritance))
900
5281
    uv_disable_stdio_inheritance();
901
902
  // Cache the original command line to be
903
  // used in diagnostic reports.
904
5281
  per_process::cli_options->cmdline = *argv;
905
906
#if defined(NODE_V8_OPTIONS)
907
  // Should come before the call to V8::SetFlagsFromCommandLine()
908
  // so the user can disable a flag --foo at run-time by passing
909
  // --no_foo from the command line.
910
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
911
#endif
912
913
5281
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
914
915
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
916
5281
  if (!(flags & ProcessFlags::kDisableNodeOptionsEnv)) {
917
5281
    std::string node_options;
918
919
5281
    if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
920
      std::vector<std::string> env_argv =
921
5164
          ParseNodeOptionsEnvVar(node_options, errors);
922
923
5164
      if (!errors->empty()) return 9;
924
925
      // [0] is expected to be the program name, fill it in from the real argv.
926
5164
      env_argv.insert(env_argv.begin(), argv->at(0));
927
928
5164
      const int exit_code = ProcessGlobalArgs(&env_argv,
929
                                              nullptr,
930
                                              errors,
931
                                              kAllowedInEnvironment);
932
5164
      if (exit_code != 0) return exit_code;
933
    }
934
  }
935
#endif
936
937
5264
  if (!(flags & ProcessFlags::kDisableCLIOptions)) {
938
5264
    const int exit_code = ProcessGlobalArgs(argv,
939
                                            exec_argv,
940
                                            errors,
941
                                            kDisallowedInEnvironment);
942
5264
    if (exit_code != 0) return exit_code;
943
  }
944
945
  // Set the process.title immediately after processing argv if --title is set.
946
5229
  if (!per_process::cli_options->title.empty())
947
2
    uv_set_process_title(per_process::cli_options->title.c_str());
948
949
#if defined(NODE_HAVE_I18N_SUPPORT)
950
5229
  if (!(flags & ProcessFlags::kNoICU)) {
951
    // If the parameter isn't given, use the env variable.
952
5229
    if (per_process::cli_options->icu_data_dir.empty())
953
5229
      credentials::SafeGetenv("NODE_ICU_DATA",
954
5229
                              &per_process::cli_options->icu_data_dir);
955
956
#ifdef NODE_ICU_DEFAULT_DATA_DIR
957
    // If neither the CLI option nor the environment variable was specified,
958
    // fall back to the configured default
959
    if (per_process::cli_options->icu_data_dir.empty()) {
960
      // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
961
      // file and can be read.
962
      static const char full_path[] =
963
          NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
964
965
      FILE* f = fopen(full_path, "rb");
966
967
      if (f != nullptr) {
968
        fclose(f);
969
        per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
970
      }
971
    }
972
#endif  // NODE_ICU_DEFAULT_DATA_DIR
973
974
    // Initialize ICU.
975
    // If icu_data_dir is empty here, it will load the 'minimal' data.
976
5229
    if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
977
      errors->push_back("could not initialize ICU "
978
                        "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
979
      return 9;
980
    }
981
5229
    per_process::metadata.versions.InitializeIntlVersions();
982
  }
983
984
# ifndef __POSIX__
985
  std::string tz;
986
  if (credentials::SafeGetenv("TZ", &tz) && !tz.empty()) {
987
    i18n::SetDefaultTimeZone(tz.c_str());
988
  }
989
# endif
990
991
#endif  // defined(NODE_HAVE_I18N_SUPPORT)
992
993
  // We should set node_is_initialized here instead of in node::Start,
994
  // otherwise embedders using node::Init to initialize everything will not be
995
  // able to set it and native modules will not load for them.
996
5229
  node_is_initialized = true;
997
5229
  return 0;
998
}
999
1000
5273
InitializationResult InitializeOncePerProcess(int argc, char** argv) {
1001
5273
  return InitializeOncePerProcess(argc, argv, kDefaultInitialization);
1002
}
1003
1004
5273
InitializationResult InitializeOncePerProcess(
1005
  int argc,
1006
  char** argv,
1007
  InitializationSettingsFlags flags,
1008
  ProcessFlags::Flags process_flags) {
1009
5273
  uint64_t init_flags = flags;
1010
5273
  if (init_flags & kDefaultInitialization) {
1011
5273
    init_flags = init_flags | kInitializeV8 | kInitOpenSSL | kRunPlatformInit;
1012
  }
1013
1014
  // Initialized the enabled list for Debug() calls with system
1015
  // environment variables.
1016
5273
  per_process::enabled_debug_list.Parse(nullptr);
1017
1018
5273
  atexit(ResetStdio);
1019
1020
5273
  if (init_flags & kRunPlatformInit)
1021
5273
    PlatformInit();
1022
1023
5273
  CHECK_GT(argc, 0);
1024
1025
  // Hack around with the argv pointer. Used for process.title = "blah".
1026
5273
  argv = uv_setup_args(argc, argv);
1027
1028
5273
  InitializationResult result;
1029
5273
  result.args = std::vector<std::string>(argv, argv + argc);
1030
10546
  std::vector<std::string> errors;
1031
1032
  // This needs to run *before* V8::Initialize().
1033
  {
1034
5273
    result.exit_code = InitializeNodeWithArgs(
1035
        &(result.args), &(result.exec_args), &errors, process_flags);
1036
5326
    for (const std::string& error : errors)
1037
53
      fprintf(stderr, "%s: %s\n", result.args.at(0).c_str(), error.c_str());
1038
5273
    if (result.exit_code != 0) {
1039
52
      result.early_return = true;
1040
52
      return result;
1041
    }
1042
  }
1043
1044

10441
  if (per_process::cli_options->use_largepages == "on" ||
1045
5220
      per_process::cli_options->use_largepages == "silent") {
1046
1
    int result = node::MapStaticCodeToLargePages();
1047

1
    if (per_process::cli_options->use_largepages == "on" && result != 0) {
1048
      fprintf(stderr, "%s\n", node::LargePagesError(result));
1049
    }
1050
  }
1051
1052
5221
  if (per_process::cli_options->print_version) {
1053
3
    printf("%s\n", NODE_VERSION);
1054
3
    result.exit_code = 0;
1055
3
    result.early_return = true;
1056
3
    return result;
1057
  }
1058
1059
5218
  if (per_process::cli_options->print_bash_completion) {
1060
2
    std::string completion = options_parser::GetBashCompletion();
1061
1
    printf("%s\n", completion.c_str());
1062
1
    result.exit_code = 0;
1063
1
    result.early_return = true;
1064
1
    return result;
1065
  }
1066
1067
5217
  if (per_process::cli_options->print_v8_help) {
1068
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1069
    result.exit_code = 0;
1070
    result.early_return = true;
1071
    return result;
1072
  }
1073
1074
5217
  if (init_flags & kInitOpenSSL) {
1075
#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1076
    {
1077
10434
      std::string extra_ca_certs;
1078
5217
      if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1079
4
        crypto::UseExtraCaCerts(extra_ca_certs);
1080
    }
1081
    // In the case of FIPS builds we should make sure
1082
    // the random source is properly initialized first.
1083
#if OPENSSL_VERSION_MAJOR >= 3
1084
    // Call OPENSSL_init_crypto to initialize OPENSSL_INIT_LOAD_CONFIG to
1085
    // avoid the default behavior where errors raised during the parsing of the
1086
    // OpenSSL configuration file are not propagated and cannot be detected.
1087
    //
1088
    // If FIPS is configured the OpenSSL configuration file will have an
1089
    // .include pointing to the fipsmodule.cnf file generated by the openssl
1090
    // fipsinstall command. If the path to this file is incorrect no error
1091
    // will be reported.
1092
    //
1093
    // For Node.js this will mean that EntropySource will be called by V8 as
1094
    // part of its initialization process, and EntropySource will in turn call
1095
    // CheckEntropy. CheckEntropy will call RAND_status which will now always
1096
    // return 0, leading to an endless loop and the node process will appear to
1097
    // hang/freeze.
1098
1099
    // Passing NULL as the config file will allow the default openssl.cnf file
1100
    // to be loaded, but the default section in that file will not be used,
1101
    // instead only the section that matches the value of conf_section_name
1102
    // will be read from the default configuration file.
1103
5217
    const char* conf_file = nullptr;
1104
    // To allow for using the previous default where the 'openssl_conf' appname
1105
    // was used, the command line option 'openssl-shared-config' can be used to
1106
    // force the old behavior.
1107
5217
    if (per_process::cli_options->openssl_shared_config) {
1108
      conf_section_name = "openssl_conf";
1109
    }
1110
    // Use OPENSSL_CONF environment variable is set.
1111
5217
    std::string env_openssl_conf;
1112
5217
    credentials::SafeGetenv("OPENSSL_CONF", &env_openssl_conf);
1113
5217
    if (!env_openssl_conf.empty()) {
1114
1
      conf_file = env_openssl_conf.c_str();
1115
    }
1116
    // Use --openssl-conf command line option if specified.
1117
5217
    if (!per_process::cli_options->openssl_config.empty()) {
1118
      conf_file = per_process::cli_options->openssl_config.c_str();
1119
    }
1120
1121
5217
    OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
1122
5217
    OPENSSL_INIT_set_config_filename(settings, conf_file);
1123
5217
    OPENSSL_INIT_set_config_appname(settings, conf_section_name);
1124
5217
    OPENSSL_INIT_set_config_file_flags(settings,
1125
                                       CONF_MFLAGS_IGNORE_MISSING_FILE);
1126
1127
5217
    OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
1128
5217
    OPENSSL_INIT_free(settings);
1129
1130
5217
    if (ERR_peek_error() != 0) {
1131
      result.exit_code = ERR_GET_REASON(ERR_peek_error());
1132
      result.early_return = true;
1133
      fprintf(stderr, "OpenSSL configuration error:\n");
1134
      ERR_print_errors_fp(stderr);
1135
      return result;
1136
    }
1137
#else  // OPENSSL_VERSION_MAJOR < 3
1138
    if (FIPS_mode()) {
1139
      OPENSSL_init();
1140
    }
1141
#endif
1142
5217
  if (!crypto::ProcessFipsOptions()) {
1143
2
      result.exit_code = ERR_GET_REASON(ERR_peek_error());
1144
2
      result.early_return = true;
1145
2
      fprintf(stderr, "OpenSSL error when trying to enable FIPS:\n");
1146
2
      ERR_print_errors_fp(stderr);
1147
2
      return result;
1148
  }
1149
1150
  // V8 on Windows doesn't have a good source of entropy. Seed it from
1151
  // OpenSSL's pool.
1152
5215
  V8::SetEntropySource(crypto::EntropySource);
1153
#endif  // HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1154
}
1155
5215
  per_process::v8_platform.Initialize(
1156
5215
      static_cast<int>(per_process::cli_options->v8_thread_pool_size));
1157
5215
  if (init_flags & kInitializeV8) {
1158
    V8::Initialize();
1159
  }
1160
1161
5215
  performance::performance_v8_start = PERFORMANCE_NOW();
1162
5215
  per_process::v8_initialized = true;
1163
1164
5215
  return result;
1165
}
1166
1167
4706
void TearDownOncePerProcess() {
1168
4706
  per_process::v8_initialized = false;
1169
4706
  V8::Dispose();
1170
1171
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1172
  RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1173
#endif
1174
1175
  // uv_run cannot be called from the time before the beforeExit callback
1176
  // runs until the program exits unless the event loop has any referenced
1177
  // handles after beforeExit terminates. This prevents unrefed timers
1178
  // that happen to terminate during shutdown from being run unsafely.
1179
  // Since uv_run cannot be called, uv_async handles held by the platform
1180
  // will never be fully cleaned up.
1181
4706
  per_process::v8_platform.Dispose();
1182
4706
}
1183
1184
5267
int Start(int argc, char** argv) {
1185
10025
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1186
5267
  if (result.early_return) {
1187
58
    return result.exit_code;
1188
  }
1189
1190
5209
  if (per_process::cli_options->build_snapshot) {
1191
    fprintf(stderr,
1192
            "--build-snapshot is not yet supported in the node binary\n");
1193
    return 1;
1194
  }
1195
1196
  {
1197
5209
    bool use_node_snapshot = per_process::cli_options->node_snapshot;
1198
    const SnapshotData* snapshot_data =
1199
5209
        use_node_snapshot ? SnapshotBuilder::GetEmbeddedSnapshotData()
1200
5209
                          : nullptr;
1201
5209
    uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1202
1203
5209
    if (snapshot_data != nullptr) {
1204
5207
      native_module::NativeModuleEnv::RefreshCodeCache(
1205
5207
          snapshot_data->code_cache);
1206
    }
1207
    NodeMainInstance main_instance(snapshot_data,
1208
                                   uv_default_loop(),
1209
5209
                                   per_process::v8_platform.Platform(),
1210
                                   result.args,
1211
5209
                                   result.exec_args);
1212
5209
    result.exit_code = main_instance.Run();
1213
  }
1214
1215
4700
  TearDownOncePerProcess();
1216
4700
  return result.exit_code;
1217
}
1218
1219
825
int Stop(Environment* env) {
1220
825
  env->ExitEnv();
1221
825
  return 0;
1222
}
1223
1224
}  // namespace node
1225
1226
#if !HAVE_INSPECTOR
1227
void Initialize() {}
1228
1229
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1230
#endif  // !HAVE_INSPECTOR