GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 399 456 87.5 %
Date: 2022-06-06 04:15:48 Branches: 230 339 67.8 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node.h"
23
24
// ========== local headers ==========
25
26
#include "debug_utils-inl.h"
27
#include "env-inl.h"
28
#include "histogram-inl.h"
29
#include "memory_tracker-inl.h"
30
#include "node_binding.h"
31
#include "node_errors.h"
32
#include "node_internals.h"
33
#include "node_main_instance.h"
34
#include "node_metadata.h"
35
#include "node_native_module_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
10308
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
176
                                      const char* id,
177
                                      std::vector<Local<String>>* parameters,
178
                                      std::vector<Local<Value>>* arguments) {
179
10308
  EscapableHandleScope scope(env->isolate());
180
  MaybeLocal<Function> maybe_fn =
181
10308
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
182
183
  Local<Function> fn;
184
10308
  if (!maybe_fn.ToLocal(&fn)) {
185
    return MaybeLocal<Value>();
186
  }
187
188
  MaybeLocal<Value> result = fn->Call(env->context(),
189
                                      Undefined(env->isolate()),
190
10308
                                      arguments->size(),
191
30924
                                      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
10066
  if (result.IsEmpty()) {
200
33
    env->async_hooks()->clear_async_id_stack();
201
  }
202
203
10066
  return scope.EscapeMaybe(result);
204
}
205
206
#if HAVE_INSPECTOR
207
6048
int Environment::InitializeInspector(
208
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
209
12096
  std::string inspector_path;
210
6048
  bool is_main = !parent_handle;
211
6048
  if (parent_handle) {
212
799
    inspector_path = parent_handle->url();
213
799
    inspector_agent_->SetParentHandle(std::move(parent_handle));
214
  } else {
215
5249
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
216
  }
217
218
6048
  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
12096
  inspector_agent_->Start(inspector_path,
223
6048
                          options_->debug_options(),
224
12096
                          inspector_host_port(),
225
                          is_main);
226

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

3416
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
404
    return MaybeLocal<Value>();
405
  }
406
407
854
  return scope.EscapeMaybe(result);
408
}
409
410
854
MaybeLocal<Value> Environment::RunBootstrapping() {
411
854
  EscapableHandleScope scope(isolate_);
412
413
854
  CHECK(!has_run_bootstrapping_code());
414
415
1708
  if (BootstrapInternalLoaders().IsEmpty()) {
416
    return MaybeLocal<Value>();
417
  }
418
419
  Local<Value> result;
420
1708
  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
854
  CHECK(req_wrap_queue()->IsEmpty());
429
854
  CHECK(handle_wrap_queue()->IsEmpty());
430
431
854
  DoneBootstrapping();
432
433
854
  return scope.Escape(result);
434
}
435
436
6012
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
437
6012
  Environment* env = Environment::GetCurrent(args);
438
6012
  env->performance_state()->Mark(
439
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
440
6012
}
441
442
static
443
6021
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
444
6021
  EscapableHandleScope scope(env->isolate());
445
6021
  CHECK_NOT_NULL(main_script_id);
446
447
  std::vector<Local<String>> parameters = {
448
6021
      env->process_string(),
449
6021
      env->require_string(),
450
6021
      env->internal_binding_string(),
451
6021
      env->primordials_string(),
452
11802
      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
6021
      env->NewFunctionTemplate(MarkBootstrapComplete)
460
6021
          ->GetFunction(env->context())
461
36126
          .ToLocalChecked()};
462
463
  return scope.EscapeMaybe(
464
11802
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
465
}
466
467
6021
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
468
  InternalCallbackScope callback_scope(
469
      env,
470
      Object::New(env->isolate()),
471
      { 1, 0 },
472
11800
      InternalCallbackScope::kSkipAsyncHooks);
473
474
6021
  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
5999
  if (env->worker_context() != nullptr) {
489
797
    return StartExecution(env, "internal/main/worker_thread");
490
  }
491
492
10164
  std::string first_argv;
493
5202
  if (env->argv().size() > 1) {
494
4713
    first_argv = env->argv()[1];
495
  }
496
497
5202
  if (first_argv == "inspect") {
498
37
    return StartExecution(env, "internal/main/inspect");
499
  }
500
501
5165
  if (per_process::cli_options->build_snapshot) {
502
    return StartExecution(env, "internal/main/mksnapshot");
503
  }
504
505
5165
  if (per_process::cli_options->print_help) {
506
1
    return StartExecution(env, "internal/main/print_help");
507
  }
508
509
510
5164
  if (env->options()->prof_process) {
511
1
    return StartExecution(env, "internal/main/prof_process");
512
  }
513
514
  // -e/--eval without -i/--interactive
515


5163
  if (env->options()->has_eval_string && !env->options()->force_repl) {
516
456
    return StartExecution(env, "internal/main/eval_string");
517
  }
518
519
4707
  if (env->options()->syntax_check_only) {
520
36
    return StartExecution(env, "internal/main/check_syntax");
521
  }
522
523
4671
  if (env->options()->test_runner) {
524
5
    return StartExecution(env, "internal/main/test_runner");
525
  }
526
527

4666
  if (!first_argv.empty() && first_argv != "-") {
528
4623
    return StartExecution(env, "internal/main/run_main_module");
529
  }
530
531


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

163246
    if (nr == SIGKILL || nr == SIGSTOP)
643
10532
      continue;
644

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

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

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

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

29670
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
748
29670
    if (!is_same_file) continue;  // Program reopened file descriptor.
749
750
    int flags;
751
    do
752
29664
      flags = fcntl(fd, F_GETFL);
753

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

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

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


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

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

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

10427
  if (per_process::cli_options->use_largepages == "on" ||
1037
5213
      per_process::cli_options->use_largepages == "silent") {
1038
1
    int result = node::MapStaticCodeToLargePages();
1039

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