GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node.cc Lines: 362 408 88.7 %
Date: 2020-11-20 19:51:53 Branches: 214 309 69.3 %

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

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

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

1752
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
390
1752
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
391
    return MaybeLocal<Value>();
392
  }
393
394
438
  return scope.EscapeMaybe(result);
395
}
396
397
438
MaybeLocal<Value> Environment::RunBootstrapping() {
398
438
  EscapableHandleScope scope(isolate_);
399
400
437
  CHECK(!has_run_bootstrapping_code());
401
402
876
  if (BootstrapInternalLoaders().IsEmpty()) {
403
    return MaybeLocal<Value>();
404
  }
405
406
  Local<Value> result;
407
876
  if (!BootstrapNode().ToLocal(&result)) {
408
    return MaybeLocal<Value>();
409
  }
410
411
  // Make sure that no request or handle is created during bootstrap -
412
  // if necessary those should be done in pre-execution.
413
  // Usually, doing so would trigger the checks present in the ReqWrap and
414
  // HandleWrap classes, so this is only a consistency check.
415
438
  CHECK(req_wrap_queue()->IsEmpty());
416
438
  CHECK(handle_wrap_queue()->IsEmpty());
417
418
438
  set_has_run_bootstrapping_code(true);
419
420
438
  return scope.Escape(result);
421
}
422
423
4990
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
424
4990
  Environment* env = Environment::GetCurrent(args);
425
4990
  env->performance_state()->Mark(
426
4990
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
427
4990
}
428
429
static
430
4998
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
431
4998
  EscapableHandleScope scope(env->isolate());
432
4998
  CHECK_NOT_NULL(main_script_id);
433
434
  std::vector<Local<String>> parameters = {
435
      env->process_string(),
436
      env->require_string(),
437
      env->internal_binding_string(),
438
      env->primordials_string(),
439
9713
      FIXED_ONE_BYTE_STRING(env->isolate(), "markBootstrapComplete")};
440
441
  std::vector<Local<Value>> arguments = {
442
      env->process_object(),
443
      env->native_module_require(),
444
      env->internal_binding_loader(),
445
      env->primordials(),
446
9996
      env->NewFunctionTemplate(MarkBootstrapComplete)
447
14994
          ->GetFunction(env->context())
448
29705
          .ToLocalChecked()};
449
450
  return scope.EscapeMaybe(
451
9713
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
452
}
453
454
4998
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
455
  InternalCallbackScope callback_scope(
456
      env,
457
      Object::New(env->isolate()),
458
      { 1, 0 },
459
9711
      InternalCallbackScope::kSkipAsyncHooks);
460
461
4998
  if (cb != nullptr) {
462
18
    EscapableHandleScope scope(env->isolate());
463
464
36
    if (StartExecution(env, "internal/bootstrap/environment").IsEmpty())
465
      return {};
466
467
    StartExecutionCallbackInfo info = {
468
      env->process_object(),
469
      env->native_module_require(),
470
18
    };
471
472
34
    return scope.EscapeMaybe(cb(info));
473
  }
474
475
4980
  if (env->worker_context() != nullptr) {
476
386
    return StartExecution(env, "internal/main/worker_thread");
477
  }
478
479
8905
  std::string first_argv;
480
4594
  if (env->argv().size() > 1) {
481
4270
    first_argv = env->argv()[1];
482
  }
483
484
4594
  if (first_argv == "inspect") {
485
3
    return StartExecution(env, "internal/main/inspect");
486
  }
487
488
4591
  if (per_process::cli_options->print_help) {
489
1
    return StartExecution(env, "internal/main/print_help");
490
  }
491
492
493
4590
  if (env->options()->prof_process) {
494
1
    return StartExecution(env, "internal/main/prof_process");
495
  }
496
497
  // -e/--eval without -i/--interactive
498


4589
  if (env->options()->has_eval_string && !env->options()->force_repl) {
499
298
    return StartExecution(env, "internal/main/eval_string");
500
  }
501
502
4291
  if (env->options()->syntax_check_only) {
503
34
    return StartExecution(env, "internal/main/check_syntax");
504
  }
505
506

4257
  if (!first_argv.empty() && first_argv != "-") {
507
4220
    return StartExecution(env, "internal/main/run_main_module");
508
  }
509
510


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

144522
    if (nr == SIGKILL || nr == SIGSTOP)
622
9324
      continue;
623

135198
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
624
135198
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
625
  }
626
#endif  // !NODE_SHARED_MODE
627
628
  // Record the state of the stdio file descriptors so we can restore it
629
  // on exit.  Needs to happen before installing signal handlers because
630
  // they make use of that information.
631
18648
  for (auto& s : stdio) {
632
13986
    const int fd = &s - stdio;
633
    int err;
634
635
    do
636
13986
      s.flags = fcntl(fd, F_GETFL);
637

13986
    while (s.flags == -1 && errno == EINTR);  // NOLINT
638
13986
    CHECK_NE(s.flags, -1);
639
640
13986
    if (uv_guess_handle(fd) != UV_TTY) continue;
641
120
    s.isatty = true;
642
643
    do
644
120
      err = tcgetattr(fd, &s.termios);
645

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

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

26148
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
727
26148
    if (!is_same_file) continue;  // Program reopened file descriptor.
728
729
    int flags;
730
    do
731
26142
      flags = fcntl(fd, F_GETFL);
732

26142
    while (flags == -1 && errno == EINTR);  // NOLINT
733
26142
    CHECK_NE(flags, -1);
734
735
    // Restore the O_NONBLOCK flag if it changed.
736
26142
    if (O_NONBLOCK & (flags ^ s.flags)) {
737
836
      flags &= ~O_NONBLOCK;
738
836
      flags |= s.flags & O_NONBLOCK;
739
740
      int err;
741
      do
742
836
        err = fcntl(fd, F_SETFL, flags);
743

836
      while (err == -1 && errno == EINTR);  // NOLINT
744
836
      CHECK_NE(err, -1);
745
    }
746
747
26142
    if (s.isatty) {
748
      sigset_t sa;
749
      int err;
750
751
      // We might be a background job that doesn't own the TTY so block SIGTTOU
752
      // before making the tcsetattr() call, otherwise that signal suspends us.
753
228
      sigemptyset(&sa);
754
228
      sigaddset(&sa, SIGTTOU);
755
756
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
757
      do
758
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
759

228
      while (err == -1 && errno == EINTR);  // NOLINT
760
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
761
762
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
763
      // tcsetattr will fail with err == -1 and errno == EPERM.
764


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
765
    }
766
  }
767
#endif  // __POSIX__
768
8716
}
769
770
771
9207
int ProcessGlobalArgs(std::vector<std::string>* args,
772
                      std::vector<std::string>* exec_args,
773
                      std::vector<std::string>* errors,
774
                      OptionEnvvarSettings settings) {
775
  // Parse a few arguments which are specific to Node.
776
18414
  std::vector<std::string> v8_args;
777
778
18414
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
779
9207
  options_parser::Parse(
780
      args,
781
      exec_args,
782
      &v8_args,
783
      per_process::cli_options.get(),
784
      settings,
785
9207
      errors);
786
787
9207
  if (!errors->empty()) return 9;
788
789
18328
  std::string revert_error;
790
9164
  for (const std::string& cve : per_process::cli_options->security_reverts) {
791
1
    Revert(cve.c_str(), &revert_error);
792
1
    if (!revert_error.empty()) {
793
1
      errors->emplace_back(std::move(revert_error));
794
1
      return 12;
795
    }
796
  }
797
798

27488
  if (per_process::cli_options->disable_proto != "delete" &&
799

18324
      per_process::cli_options->disable_proto != "throw" &&
800
9161
      per_process::cli_options->disable_proto != "") {
801
    errors->emplace_back("invalid mode passed to --disable-proto");
802
    return 12;
803
  }
804
805
  // TODO(mylesborins): remove this when the harmony-top-level-await flag
806
  // is removed in V8
807
18326
  if (std::find(v8_args.begin(), v8_args.end(),
808
18326
                "--no-harmony-top-level-await") == v8_args.end()) {
809
9161
    v8_args.push_back("--harmony-top-level-await");
810
  }
811
812
18326
  auto env_opts = per_process::cli_options->per_isolate->per_env;
813
36652
  if (std::find(v8_args.begin(), v8_args.end(),
814

36634
                "--abort-on-uncaught-exception") != v8_args.end() ||
815
18308
      std::find(v8_args.begin(), v8_args.end(),
816
27453
                "--abort_on_uncaught_exception") != v8_args.end()) {
817
21
    env_opts->abort_on_uncaught_exception = true;
818
  }
819
820
#ifdef __POSIX__
821
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
822
  // performance penalty of frequent EINTR wakeups when the profiler is running.
823
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
824
9163
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
825
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
826
  }
827
#endif
828
829
18326
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
830
9163
  if (v8_args.size() > 0) {
831
27637
    for (size_t i = 0; i < v8_args.size(); ++i)
832
18474
      v8_args_as_char_ptr[i] = &v8_args[i][0];
833
9163
    int argc = v8_args.size();
834
9163
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
835
9163
    v8_args_as_char_ptr.resize(argc);
836
  }
837
838
  // Anything that's still in v8_argv is not a V8 or a node option.
839
9176
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
840
13
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
841
842
9163
  if (v8_args_as_char_ptr.size() > 1) return 9;
843
844
9152
  return 0;
845
}
846
847
static std::atomic_bool init_called{false};
848
849
4670
int InitializeNodeWithArgs(std::vector<std::string>* argv,
850
                           std::vector<std::string>* exec_argv,
851
                           std::vector<std::string>* errors) {
852
  // Make sure InitializeNodeWithArgs() is called only once.
853
4670
  CHECK(!init_called.exchange(true));
854
855
  // Initialize node_start_time to get relative uptime.
856
4670
  per_process::node_start_time = uv_hrtime();
857
858
  // Register built-in modules
859
4670
  binding::RegisterBuiltinModules();
860
861
  // Make inherited handles noninheritable.
862
4670
  uv_disable_stdio_inheritance();
863
864
  // Cache the original command line to be
865
  // used in diagnostic reports.
866
4670
  per_process::cli_options->cmdline = *argv;
867
868
#if defined(NODE_V8_OPTIONS)
869
  // Should come before the call to V8::SetFlagsFromCommandLine()
870
  // so the user can disable a flag --foo at run-time by passing
871
  // --no_foo from the command line.
872
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
873
#endif
874
875
4670
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
876
877
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
878
9340
  std::string node_options;
879
880
4670
  if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
881
    std::vector<std::string> env_argv =
882
9091
        ParseNodeOptionsEnvVar(node_options, errors);
883
884
4554
    if (!errors->empty()) return 9;
885
886
    // [0] is expected to be the program name, fill it in from the real argv.
887
4554
    env_argv.insert(env_argv.begin(), argv->at(0));
888
889
    const int exit_code = ProcessGlobalArgs(&env_argv,
890
                                            nullptr,
891
                                            errors,
892
4554
                                            kAllowedInEnvironment);
893

4554
    if (exit_code != 0) return exit_code;
894
  }
895
#endif
896
897
  const int exit_code = ProcessGlobalArgs(argv,
898
                                          exec_argv,
899
                                          errors,
900
4653
                                          kDisallowedInEnvironment);
901
4653
  if (exit_code != 0) return exit_code;
902
903
  // Set the process.title immediately after processing argv if --title is set.
904
4615
  if (!per_process::cli_options->title.empty())
905
2
    uv_set_process_title(per_process::cli_options->title.c_str());
906
907
#if defined(NODE_HAVE_I18N_SUPPORT)
908
  // If the parameter isn't given, use the env variable.
909
4615
  if (per_process::cli_options->icu_data_dir.empty())
910
4615
    credentials::SafeGetenv("NODE_ICU_DATA",
911
9230
                            &per_process::cli_options->icu_data_dir);
912
913
#ifdef NODE_ICU_DEFAULT_DATA_DIR
914
  // If neither the CLI option nor the environment variable was specified,
915
  // fall back to the configured default
916
  if (per_process::cli_options->icu_data_dir.empty()) {
917
    // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
918
    // file and can be read.
919
    static const char full_path[] =
920
        NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
921
922
    FILE* f = fopen(full_path, "rb");
923
924
    if (f != nullptr) {
925
      fclose(f);
926
      per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
927
    }
928
  }
929
#endif  // NODE_ICU_DEFAULT_DATA_DIR
930
931
  // Initialize ICU.
932
  // If icu_data_dir is empty here, it will load the 'minimal' data.
933
4615
  if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
934
    errors->push_back("could not initialize ICU "
935
                      "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
936
    return 9;
937
  }
938
4615
  per_process::metadata.versions.InitializeIntlVersions();
939
#endif
940
941
4615
  NativeModuleEnv::InitializeCodeCache();
942
943
  // We should set node_is_initialized here instead of in node::Start,
944
  // otherwise embedders using node::Init to initialize everything will not be
945
  // able to set it and native modules will not load for them.
946
4615
  node_is_initialized = true;
947
4615
  return 0;
948
}
949
950
4662
InitializationResult InitializeOncePerProcess(int argc, char** argv) {
951
  // Initialized the enabled list for Debug() calls with system
952
  // environment variables.
953
4662
  per_process::enabled_debug_list.Parse(nullptr);
954
955
4662
  atexit(ResetStdio);
956
4662
  PlatformInit();
957
958
4662
  CHECK_GT(argc, 0);
959
960
  // Hack around with the argv pointer. Used for process.title = "blah".
961
4662
  argv = uv_setup_args(argc, argv);
962
963
4662
  InitializationResult result;
964
4662
  result.args = std::vector<std::string>(argv, argv + argc);
965
9323
  std::vector<std::string> errors;
966
967
  // This needs to run *before* V8::Initialize().
968
  {
969
4662
    result.exit_code =
970
4662
        InitializeNodeWithArgs(&(result.args), &(result.exec_args), &errors);
971
4719
    for (const std::string& error : errors)
972
57
      fprintf(stderr, "%s: %s\n", result.args.at(0).c_str(), error.c_str());
973
4662
    if (result.exit_code != 0) {
974
55
      result.early_return = true;
975
55
      return result;
976
    }
977
  }
978
979

9213
  if (per_process::cli_options->use_largepages == "on" ||
980
4606
      per_process::cli_options->use_largepages == "silent") {
981
1
    int result = node::MapStaticCodeToLargePages();
982

1
    if (per_process::cli_options->use_largepages == "on" && result != 0) {
983
      fprintf(stderr, "%s\n", node::LargePagesError(result));
984
    }
985
  }
986
987
4607
  if (per_process::cli_options->print_version) {
988
3
    printf("%s\n", NODE_VERSION);
989
3
    result.exit_code = 0;
990
3
    result.early_return = true;
991
3
    return result;
992
  }
993
994
4604
  if (per_process::cli_options->print_bash_completion) {
995
2
    std::string completion = options_parser::GetBashCompletion();
996
1
    printf("%s\n", completion.c_str());
997
1
    result.exit_code = 0;
998
1
    result.early_return = true;
999
1
    return result;
1000
  }
1001
1002
4603
  if (per_process::cli_options->print_v8_help) {
1003
1
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1004
    result.exit_code = 0;
1005
    result.early_return = true;
1006
    return result;
1007
  }
1008
1009
#if HAVE_OPENSSL
1010
  {
1011
9204
    std::string extra_ca_certs;
1012
4602
    if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1013
4
      crypto::UseExtraCaCerts(extra_ca_certs);
1014
  }
1015
#ifdef NODE_FIPS_MODE
1016
  // In the case of FIPS builds we should make sure
1017
  // the random source is properly initialized first.
1018
  OPENSSL_init();
1019
#endif  // NODE_FIPS_MODE
1020
  // V8 on Windows doesn't have a good source of entropy. Seed it from
1021
  // OpenSSL's pool.
1022
4602
  V8::SetEntropySource(crypto::EntropySource);
1023
#endif  // HAVE_OPENSSL
1024
1025
4602
  per_process::v8_platform.Initialize(
1026
9204
      per_process::cli_options->v8_thread_pool_size);
1027
  V8::Initialize();
1028
4602
  performance::performance_v8_start = PERFORMANCE_NOW();
1029
4602
  per_process::v8_initialized = true;
1030
4602
  return result;
1031
}
1032
1033
4045
void TearDownOncePerProcess() {
1034
4045
  per_process::v8_initialized = false;
1035
4045
  V8::Dispose();
1036
1037
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1038
  RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1039
#endif
1040
1041
  // uv_run cannot be called from the time before the beforeExit callback
1042
  // runs until the program exits unless the event loop has any referenced
1043
  // handles after beforeExit terminates. This prevents unrefed timers
1044
  // that happen to terminate during shutdown from being run unsafely.
1045
  // Since uv_run cannot be called, uv_async handles held by the platform
1046
  // will never be fully cleaned up.
1047
4045
  per_process::v8_platform.Dispose();
1048
4045
}
1049
1050
4654
int Start(int argc, char** argv) {
1051
8750
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1052
4653
  if (result.early_return) {
1053
59
    return result.exit_code;
1054
  }
1055
1056
  {
1057
8631
    Isolate::CreateParams params;
1058
4594
    const std::vector<size_t>* indexes = nullptr;
1059
4594
    const EnvSerializeInfo* env_info = nullptr;
1060
    bool force_no_snapshot =
1061
4594
        per_process::cli_options->per_isolate->no_node_snapshot;
1062
4594
    if (!force_no_snapshot) {
1063
4593
      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();
1064
4593
      if (blob != nullptr) {
1065
4593
        params.snapshot_blob = blob;
1066
4593
        indexes = NodeMainInstance::GetIsolateDataIndexes();
1067
4593
        env_info = NodeMainInstance::GetEnvSerializeInfo();
1068
      }
1069
    }
1070
4594
    uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1071
1072
    NodeMainInstance main_instance(&params,
1073
                                   uv_default_loop(),
1074
4594
                                   per_process::v8_platform.Platform(),
1075
                                   result.args,
1076
                                   result.exec_args,
1077
8631
                                   indexes);
1078
4594
    result.exit_code = main_instance.Run(env_info);
1079
  }
1080
1081
4037
  TearDownOncePerProcess();
1082
4037
  return result.exit_code;
1083
}
1084
1085
96
int Stop(Environment* env) {
1086
96
  env->ExitEnv();
1087
96
  return 0;
1088
}
1089
1090

14034
}  // namespace node
1091
1092
#if !HAVE_INSPECTOR
1093
void Initialize() {}
1094
1095
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1096
#endif  // !HAVE_INSPECTOR