GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 390 450 86.7 %
Date: 2022-02-06 04:14:03 Branches: 223 335 66.6 %

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 "memory_tracker-inl.h"
29
#include "histogram-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_v8_platform-inl.h"
42
#include "node_version.h"
43
44
#if HAVE_OPENSSL
45
#include "allocated_buffer-inl.h"  // Inlined functions needed by node_crypto.h
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
#ifdef __POSIX__
166
void SignalExit(int signo, siginfo_t* info, void* ucontext) {
167
  ResetStdio();
168
  raise(signo);
169
}
170
#endif  // __POSIX__
171
172
8651
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
173
                                      const char* id,
174
                                      std::vector<Local<String>>* parameters,
175
                                      std::vector<Local<Value>>* arguments) {
176
8651
  EscapableHandleScope scope(env->isolate());
177
  MaybeLocal<Function> maybe_fn =
178
8651
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
179
180
  Local<Function> fn;
181
8651
  if (!maybe_fn.ToLocal(&fn)) {
182
    return MaybeLocal<Value>();
183
  }
184
185
  MaybeLocal<Value> result = fn->Call(env->context(),
186
                                      Undefined(env->isolate()),
187
8651
                                      arguments->size(),
188
25953
                                      arguments->data());
189
190
  // If there was an error during bootstrap, it must be unrecoverable
191
  // (e.g. max call stack exceeded). Clear the stack so that the
192
  // AsyncCallbackScope destructor doesn't fail on the id check.
193
  // There are only two ways to have a stack size > 1: 1) the user manually
194
  // called MakeCallback or 2) user awaited during bootstrap, which triggered
195
  // _tickCallback().
196
8401
  if (result.IsEmpty()) {
197
33
    env->async_hooks()->clear_async_id_stack();
198
  }
199
200
8401
  return scope.EscapeMaybe(result);
201
}
202
203
#if HAVE_INSPECTOR
204
5541
int Environment::InitializeInspector(
205
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
206
11082
  std::string inspector_path;
207
5541
  bool is_main = !parent_handle;
208
5541
  if (parent_handle) {
209
570
    inspector_path = parent_handle->url();
210
570
    inspector_agent_->SetParentHandle(std::move(parent_handle));
211
  } else {
212
4971
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
213
  }
214
215
5541
  CHECK(!inspector_agent_->IsListening());
216
  // Inspector agent can't fail to start, but if it was configured to listen
217
  // right away on the websocket port and fails to bind/etc, this will return
218
  // false.
219
11082
  inspector_agent_->Start(inspector_path,
220
5541
                          options_->debug_options(),
221
11082
                          inspector_host_port(),
222
                          is_main);
223

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

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

2496
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
401
    return MaybeLocal<Value>();
402
  }
403
404
624
  return scope.EscapeMaybe(result);
405
}
406
407
624
MaybeLocal<Value> Environment::RunBootstrapping() {
408
624
  EscapableHandleScope scope(isolate_);
409
410
624
  CHECK(!has_run_bootstrapping_code());
411
412
1248
  if (BootstrapInternalLoaders().IsEmpty()) {
413
    return MaybeLocal<Value>();
414
  }
415
416
  Local<Value> result;
417
1248
  if (!BootstrapNode().ToLocal(&result)) {
418
    return MaybeLocal<Value>();
419
  }
420
421
  // Make sure that no request or handle is created during bootstrap -
422
  // if necessary those should be done in pre-execution.
423
  // Usually, doing so would trigger the checks present in the ReqWrap and
424
  // HandleWrap classes, so this is only a consistency check.
425
624
  CHECK(req_wrap_queue()->IsEmpty());
426
624
  CHECK(handle_wrap_queue()->IsEmpty());
427
428
624
  DoneBootstrapping();
429
430
624
  return scope.Escape(result);
431
}
432
433
5505
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
434
5505
  Environment* env = Environment::GetCurrent(args);
435
5505
  env->performance_state()->Mark(
436
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
437
5505
}
438
439
static
440
5514
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
441
5514
  EscapableHandleScope scope(env->isolate());
442
5514
  CHECK_NOT_NULL(main_script_id);
443
444
  std::vector<Local<String>> parameters = {
445
5514
      env->process_string(),
446
5514
      env->require_string(),
447
5514
      env->internal_binding_string(),
448
5514
      env->primordials_string(),
449
10780
      FIXED_ONE_BYTE_STRING(env->isolate(), "markBootstrapComplete")};
450
451
  std::vector<Local<Value>> arguments = {
452
      env->process_object(),
453
      env->native_module_require(),
454
      env->internal_binding_loader(),
455
      env->primordials(),
456
5514
      env->NewFunctionTemplate(MarkBootstrapComplete)
457
5514
          ->GetFunction(env->context())
458
33084
          .ToLocalChecked()};
459
460
  return scope.EscapeMaybe(
461
10780
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
462
}
463
464
5514
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
465
  InternalCallbackScope callback_scope(
466
      env,
467
      Object::New(env->isolate()),
468
      { 1, 0 },
469
10778
      InternalCallbackScope::kSkipAsyncHooks);
470
471
5514
  if (cb != nullptr) {
472
22
    EscapableHandleScope scope(env->isolate());
473
474
44
    if (StartExecution(env, "internal/bootstrap/environment").IsEmpty())
475
      return {};
476
477
    StartExecutionCallbackInfo info = {
478
22
      env->process_object(),
479
22
      env->native_module_require(),
480
    };
481
482
42
    return scope.EscapeMaybe(cb(info));
483
  }
484
485
5492
  if (env->worker_context() != nullptr) {
486
568
    return StartExecution(env, "internal/main/worker_thread");
487
  }
488
489
9600
  std::string first_argv;
490
4924
  if (env->argv().size() > 1) {
491
4592
    first_argv = env->argv()[1];
492
  }
493
494
4924
  if (first_argv == "inspect") {
495
32
    return StartExecution(env, "internal/main/inspect");
496
  }
497
498
4892
  if (per_process::cli_options->print_help) {
499
1
    return StartExecution(env, "internal/main/print_help");
500
  }
501
502
503
4891
  if (env->options()->prof_process) {
504
1
    return StartExecution(env, "internal/main/prof_process");
505
  }
506
507
  // -e/--eval without -i/--interactive
508


4890
  if (env->options()->has_eval_string && !env->options()->force_repl) {
509
301
    return StartExecution(env, "internal/main/eval_string");
510
  }
511
512
4589
  if (env->options()->syntax_check_only) {
513
36
    return StartExecution(env, "internal/main/check_syntax");
514
  }
515
516

4553
  if (!first_argv.empty() && first_argv != "-") {
517
4511
    return StartExecution(env, "internal/main/run_main_module");
518
  }
519
520


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

154442
    if (nr == SIGKILL || nr == SIGSTOP)
632
9964
      continue;
633

144478
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
634
144478
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
635
  }
636
#endif  // !NODE_SHARED_MODE
637
638
  // Record the state of the stdio file descriptors so we can restore it
639
  // on exit.  Needs to happen before installing signal handlers because
640
  // they make use of that information.
641
19928
  for (auto& s : stdio) {
642
14946
    const int fd = &s - stdio;
643
    int err;
644
645
    do
646
14946
      s.flags = fcntl(fd, F_GETFL);
647

14946
    while (s.flags == -1 && errno == EINTR);  // NOLINT
648
14946
    CHECK_NE(s.flags, -1);
649
650
14946
    if (uv_guess_handle(fd) != UV_TTY) continue;
651
120
    s.isatty = true;
652
653
    do
654
120
      err = tcgetattr(fd, &s.termios);
655

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

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

28311
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
737
28311
    if (!is_same_file) continue;  // Program reopened file descriptor.
738
739
    int flags;
740
    do
741
28305
      flags = fcntl(fd, F_GETFL);
742

28305
    while (flags == -1 && errno == EINTR);  // NOLINT
743
28305
    CHECK_NE(flags, -1);
744
745
    // Restore the O_NONBLOCK flag if it changed.
746
28305
    if (O_NONBLOCK & (flags ^ s.flags)) {
747
992
      flags &= ~O_NONBLOCK;
748
992
      flags |= s.flags & O_NONBLOCK;
749
750
      int err;
751
      do
752
992
        err = fcntl(fd, F_SETFL, flags);
753

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

228
      while (err == -1 && errno == EINTR);  // NOLINT
770
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
771
772
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
773
      // tcsetattr will fail with err == -1 and errno == EPERM.
774


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

19605
      per_process::cli_options->disable_proto != "throw" &&
810
9801
      per_process::cli_options->disable_proto != "") {
811
    errors->emplace_back("invalid mode passed to --disable-proto");
812
    return 12;
813
  }
814
815
  // TODO(aduh95): remove this when the harmony-import-assertions flag
816
  // is removed in V8.
817
19606
  if (std::find(v8_args.begin(), v8_args.end(),
818
9803
                "--no-harmony-import-assertions") == v8_args.end()) {
819
9803
    v8_args.push_back("--harmony-import-assertions");
820
  }
821
822
19606
  auto env_opts = per_process::cli_options->per_isolate->per_env;
823
19606
  if (std::find(v8_args.begin(), v8_args.end(),
824

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

9871
  if (per_process::cli_options->use_largepages == "on" ||
1028
4935
      per_process::cli_options->use_largepages == "silent") {
1029
1
    int result = node::MapStaticCodeToLargePages();
1030

1
    if (per_process::cli_options->use_largepages == "on" && result != 0) {
1031
      fprintf(stderr, "%s\n", node::LargePagesError(result));
1032
    }
1033
  }
1034
1035
4936
  if (per_process::cli_options->print_version) {
1036
3
    printf("%s\n", NODE_VERSION);
1037
3
    result.exit_code = 0;
1038
3
    result.early_return = true;
1039
3
    return result;
1040
  }
1041
1042
4933
  if (per_process::cli_options->print_bash_completion) {
1043
2
    std::string completion = options_parser::GetBashCompletion();
1044
1
    printf("%s\n", completion.c_str());
1045
1
    result.exit_code = 0;
1046
1
    result.early_return = true;
1047
1
    return result;
1048
  }
1049
1050
4932
  if (per_process::cli_options->print_v8_help) {
1051
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1052
    result.exit_code = 0;
1053
    result.early_return = true;
1054
    return result;
1055
  }
1056
1057
4932
  if (init_flags & kInitOpenSSL) {
1058
#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1059
    {
1060
9864
      std::string extra_ca_certs;
1061
4932
      if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1062
4
        crypto::UseExtraCaCerts(extra_ca_certs);
1063
    }
1064
    // In the case of FIPS builds we should make sure
1065
    // the random source is properly initialized first.
1066
#if OPENSSL_VERSION_MAJOR >= 3
1067
    // Call OPENSSL_init_crypto to initialize OPENSSL_INIT_LOAD_CONFIG to
1068
    // avoid the default behavior where errors raised during the parsing of the
1069
    // OpenSSL configuration file are not propagated and cannot be detected.
1070
    //
1071
    // If FIPS is configured the OpenSSL configuration file will have an
1072
    // .include pointing to the fipsmodule.cnf file generated by the openssl
1073
    // fipsinstall command. If the path to this file is incorrect no error
1074
    // will be reported.
1075
    //
1076
    // For Node.js this will mean that EntropySource will be called by V8 as
1077
    // part of its initialization process, and EntropySource will in turn call
1078
    // CheckEntropy. CheckEntropy will call RAND_status which will now always
1079
    // return 0, leading to an endless loop and the node process will appear to
1080
    // hang/freeze.
1081
4932
    std::string env_openssl_conf;
1082
4932
    credentials::SafeGetenv("OPENSSL_CONF", &env_openssl_conf);
1083
1084
4932
    bool has_cli_conf = !per_process::cli_options->openssl_config.empty();
1085

4932
    if (has_cli_conf || !env_openssl_conf.empty()) {
1086
      OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
1087
      OPENSSL_INIT_set_config_file_flags(settings, CONF_MFLAGS_DEFAULT_SECTION);
1088
      if (has_cli_conf) {
1089
        const char* conf = per_process::cli_options->openssl_config.c_str();
1090
        OPENSSL_INIT_set_config_filename(settings, conf);
1091
      }
1092
      OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
1093
      OPENSSL_INIT_free(settings);
1094
1095
      if (ERR_peek_error() != 0) {
1096
        result.exit_code = ERR_GET_REASON(ERR_peek_error());
1097
        result.early_return = true;
1098
        fprintf(stderr, "OpenSSL configuration error:\n");
1099
        ERR_print_errors_fp(stderr);
1100
        return result;
1101
      }
1102
    }
1103
#else  // OPENSSL_VERSION_MAJOR < 3
1104
    if (FIPS_mode()) {
1105
      OPENSSL_init();
1106
    }
1107
#endif
1108
4932
  if (!crypto::ProcessFipsOptions()) {
1109
2
      result.exit_code = ERR_GET_REASON(ERR_peek_error());
1110
2
      result.early_return = true;
1111
2
      fprintf(stderr, "OpenSSL error when trying to enable FIPS:\n");
1112
2
      ERR_print_errors_fp(stderr);
1113
2
      return result;
1114
  }
1115
1116
  // V8 on Windows doesn't have a good source of entropy. Seed it from
1117
  // OpenSSL's pool.
1118
4930
  V8::SetEntropySource(crypto::EntropySource);
1119
#endif  // HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1120
}
1121
4930
  per_process::v8_platform.Initialize(
1122
4930
      static_cast<int>(per_process::cli_options->v8_thread_pool_size));
1123
4930
  if (init_flags & kInitializeV8) {
1124
    V8::Initialize();
1125
  }
1126
1127
4930
  performance::performance_v8_start = PERFORMANCE_NOW();
1128
4930
  per_process::v8_initialized = true;
1129
1130
4930
  return result;
1131
}
1132
1133
4444
void TearDownOncePerProcess() {
1134
4444
  per_process::v8_initialized = false;
1135
4444
  V8::Dispose();
1136
1137
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1138
  RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1139
#endif
1140
1141
  // uv_run cannot be called from the time before the beforeExit callback
1142
  // runs until the program exits unless the event loop has any referenced
1143
  // handles after beforeExit terminates. This prevents unrefed timers
1144
  // that happen to terminate during shutdown from being run unsafely.
1145
  // Since uv_run cannot be called, uv_async handles held by the platform
1146
  // will never be fully cleaned up.
1147
4444
  per_process::v8_platform.Dispose();
1148
4444
}
1149
1150
4976
int Start(int argc, char** argv) {
1151
9466
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1152
4976
  if (result.early_return) {
1153
52
    return result.exit_code;
1154
  }
1155
1156
  {
1157
9362
    Isolate::CreateParams params;
1158
4924
    const std::vector<size_t>* indices = nullptr;
1159
4924
    const EnvSerializeInfo* env_info = nullptr;
1160
    bool use_node_snapshot =
1161
4924
        per_process::cli_options->per_isolate->node_snapshot;
1162
4924
    if (use_node_snapshot) {
1163
4923
      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();
1164
4923
      if (blob != nullptr) {
1165
4923
        params.snapshot_blob = blob;
1166
4923
        indices = NodeMainInstance::GetIsolateDataIndices();
1167
4923
        env_info = NodeMainInstance::GetEnvSerializeInfo();
1168
      }
1169
    }
1170
4924
    uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1171
1172
    NodeMainInstance main_instance(&params,
1173
                                   uv_default_loop(),
1174
4924
                                   per_process::v8_platform.Platform(),
1175
                                   result.args,
1176
                                   result.exec_args,
1177
4924
                                   indices);
1178
4924
    result.exit_code = main_instance.Run(env_info);
1179
  }
1180
1181
4438
  TearDownOncePerProcess();
1182
4438
  return result.exit_code;
1183
}
1184
1185
168
int Stop(Environment* env) {
1186
168
  env->ExitEnv();
1187
168
  return 0;
1188
}
1189
1190
}  // namespace node
1191
1192
#if !HAVE_INSPECTOR
1193
void Initialize() {}
1194
1195
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1196
#endif  // !HAVE_INSPECTOR