GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 398 456 87.3 %
Date: 2022-07-10 04:16:23 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
12971
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
176
                                      const char* id,
177
                                      std::vector<Local<String>>* parameters,
178
                                      std::vector<Local<Value>>* arguments) {
179
12971
  EscapableHandleScope scope(env->isolate());
180
  MaybeLocal<Function> maybe_fn =
181
12971
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
182
183
  Local<Function> fn;
184
12971
  if (!maybe_fn.ToLocal(&fn)) {
185
    return MaybeLocal<Value>();
186
  }
187
188
  MaybeLocal<Value> result = fn->Call(env->context(),
189
                                      Undefined(env->isolate()),
190
12971
                                      arguments->size(),
191
38913
                                      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
12728
  if (result.IsEmpty()) {
200
33
    env->async_hooks()->clear_async_id_stack();
201
  }
202
203
12728
  return scope.EscapeMaybe(result);
204
}
205
206
#if HAVE_INSPECTOR
207
6522
int Environment::InitializeInspector(
208
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
209
13044
  std::string inspector_path;
210
6522
  bool is_main = !parent_handle;
211
6522
  if (parent_handle) {
212
1237
    inspector_path = parent_handle->url();
213
1237
    inspector_agent_->SetParentHandle(std::move(parent_handle));
214
  } else {
215
5285
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
216
  }
217
218
6522
  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
13044
  inspector_agent_->Start(inspector_path,
223
6522
                          options_->debug_options(),
224
13044
                          inspector_host_port(),
225
                          is_main);
226

6603
  if (options_->debug_options().inspector_enabled &&
227
81
      !inspector_agent_->IsListening()) {
228
5
    return 12;  // Signal internal error
229
  }
230
231
6517
  profiler::StartProfilers(this);
232
233
6517
  if (inspector_agent_->options().break_node_first_line) {
234
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
235
  }
236
237
6517
  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
6494
void Environment::InitializeDiagnostics() {
280
6494
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
281
      Environment::BuildEmbedderGraph, this);
282
6494
  if (options_->heap_snapshot_near_heap_limit > 0) {
283
1
    isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
284
                                       this);
285
  }
286
6494
  if (options_->trace_uncaught)
287
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
288
6494
  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
6494
}
300
301
1292
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
302
1292
  EscapableHandleScope scope(isolate_);
303
304
  // Create binding loaders
305
  std::vector<Local<String>> loaders_params = {
306
1292
      process_string(),
307
1292
      FIXED_ONE_BYTE_STRING(isolate_, "getLinkedBinding"),
308
1292
      FIXED_ONE_BYTE_STRING(isolate_, "getInternalBinding"),
309
2584
      primordials_string()};
310
  std::vector<Local<Value>> loaders_args = {
311
      process_object(),
312
1292
      NewFunctionTemplate(binding::GetLinkedBinding)
313
1292
          ->GetFunction(context())
314
          .ToLocalChecked(),
315
1292
      NewFunctionTemplate(binding::GetInternalBinding)
316
1292
          ->GetFunction(context())
317
          .ToLocalChecked(),
318
9044
      primordials()};
319
320
  // Bootstrap internal loaders
321
  Local<Value> loader_exports;
322
1292
  if (!ExecuteBootstrapper(
323
1292
           this, "internal/bootstrap/loaders", &loaders_params, &loaders_args)
324
1292
           .ToLocal(&loader_exports)) {
325
    return MaybeLocal<Value>();
326
  }
327
1292
  CHECK(loader_exports->IsObject());
328
1292
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
329
  Local<Value> internal_binding_loader =
330
2584
      loader_exports_obj->Get(context(), internal_binding_string())
331
1292
          .ToLocalChecked();
332
1292
  CHECK(internal_binding_loader->IsFunction());
333
1292
  set_internal_binding_loader(internal_binding_loader.As<Function>());
334
  Local<Value> require =
335
3876
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
336
1292
  CHECK(require->IsFunction());
337
1292
  set_native_module_require(require.As<Function>());
338
339
1292
  return scope.Escape(loader_exports);
340
}
341
342
1292
MaybeLocal<Value> Environment::BootstrapNode() {
343
1292
  EscapableHandleScope scope(isolate_);
344
345
  // process, require, internalBinding, primordials
346
  std::vector<Local<String>> node_params = {
347
1292
      process_string(),
348
1292
      require_string(),
349
1292
      internal_binding_string(),
350
2584
      primordials_string()};
351
  std::vector<Local<Value>> node_args = {
352
      process_object(),
353
      native_module_require(),
354
      internal_binding_loader(),
355
7752
      primordials()};
356
357
  MaybeLocal<Value> result = ExecuteBootstrapper(
358
1292
      this, "internal/bootstrap/node", &node_params, &node_args);
359
360
1292
  if (result.IsEmpty()) {
361
    return MaybeLocal<Value>();
362
  }
363
364
1292
  if (!no_browser_globals()) {
365
    result = ExecuteBootstrapper(
366
1292
        this, "internal/bootstrap/browser", &node_params, &node_args);
367
368
1292
    if (result.IsEmpty()) {
369
      return MaybeLocal<Value>();
370
    }
371
  }
372
373
  // TODO(joyeecheung): skip these in the snapshot building for workers.
374
  auto thread_switch_id =
375
1292
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
376
1292
                       : "internal/bootstrap/switches/is_not_main_thread";
377
  result =
378
1292
      ExecuteBootstrapper(this, thread_switch_id, &node_params, &node_args);
379
380
1292
  if (result.IsEmpty()) {
381
    return MaybeLocal<Value>();
382
  }
383
384
  auto process_state_switch_id =
385
1292
      owns_process_state()
386
1292
          ? "internal/bootstrap/switches/does_own_process_state"
387
1292
          : "internal/bootstrap/switches/does_not_own_process_state";
388
  result = ExecuteBootstrapper(
389
1292
      this, process_state_switch_id, &node_params, &node_args);
390
391
1292
  if (result.IsEmpty()) {
392
    return MaybeLocal<Value>();
393
  }
394
395
1292
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
396
  Local<Object> env_var_proxy;
397
3876
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
398

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


5198
  if (env->options()->has_eval_string && !env->options()->force_repl) {
519
460
    return StartExecution(env, "internal/main/eval_string");
520
  }
521
522
4738
  if (env->options()->syntax_check_only) {
523
36
    return StartExecution(env, "internal/main/check_syntax");
524
  }
525
526
4702
  if (env->options()->test_runner) {
527
6
    return StartExecution(env, "internal/main/test_runner");
528
  }
529
530

4696
  if (!first_argv.empty() && first_argv != "-") {
531
4651
    return StartExecution(env, "internal/main/run_main_module");
532
  }
533
534


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

164362
    if (nr == SIGKILL || nr == SIGSTOP)
646
10604
      continue;
647

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

15906
    while (s.flags == -1 && errno == EINTR);  // NOLINT
662
15906
    CHECK_NE(s.flags, -1);
663
664
15906
    if (uv_guess_handle(fd) != UV_TTY) continue;
665
120
    s.isatty = true;
666
667
    do
668
120
      err = tcgetattr(fd, &s.termios);
669

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

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

30129
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
751
30129
    if (!is_same_file) continue;  // Program reopened file descriptor.
752
753
    int flags;
754
    do
755
30123
      flags = fcntl(fd, F_GETFL);
756

30123
    while (flags == -1 && errno == EINTR);  // NOLINT
757
30123
    CHECK_NE(flags, -1);
758
759
    // Restore the O_NONBLOCK flag if it changed.
760
30123
    if (O_NONBLOCK & (flags ^ s.flags)) {
761
1167
      flags &= ~O_NONBLOCK;
762
1167
      flags |= s.flags & O_NONBLOCK;
763
764
      int err;
765
      do
766
1167
        err = fcntl(fd, F_SETFL, flags);
767

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

228
      while (err == -1 && errno == EINTR);  // NOLINT
784
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
785
786
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
787
      // tcsetattr will fail with err == -1 and errno == EPERM.
788


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

20869
      per_process::cli_options->disable_proto != "throw" &&
824
10433
      per_process::cli_options->disable_proto != "") {
825
    errors->emplace_back("invalid mode passed to --disable-proto");
826
    return 12;
827
  }
828
829
  // TODO(aduh95): remove this when the harmony-import-assertions flag
830
  // is removed in V8.
831
20870
  if (std::find(v8_args.begin(), v8_args.end(),
832
10435
                "--no-harmony-import-assertions") == v8_args.end()) {
833
10435
    v8_args.emplace_back("--harmony-import-assertions");
834
  }
835
836
20870
  auto env_opts = per_process::cli_options->per_isolate->per_env;
837
20870
  if (std::find(v8_args.begin(), v8_args.end(),
838

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

10499
  if (per_process::cli_options->use_largepages == "on" ||
1040
5249
      per_process::cli_options->use_largepages == "silent") {
1041
1
    int result = node::MapStaticCodeToLargePages();
1042

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