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: 370 418 88.5 %
Date: 2021-06-08 04:12:09 Branches: 217 319 68.0 %

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::GetCurrent().
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
4845
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
7088
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
173
                                      const char* id,
174
                                      std::vector<Local<String>>* parameters,
175
                                      std::vector<Local<Value>>* arguments) {
176
7088
  EscapableHandleScope scope(env->isolate());
177
  MaybeLocal<Function> maybe_fn =
178
7088
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
179
180
  Local<Function> fn;
181
7088
  if (!maybe_fn.ToLocal(&fn)) {
182
    return MaybeLocal<Value>();
183
  }
184
185
  MaybeLocal<Value> result = fn->Call(env->context(),
186
                                      Undefined(env->isolate()),
187
7088
                                      arguments->size(),
188
28352
                                      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
6832
  if (result.IsEmpty()) {
197
33
    env->async_hooks()->clear_async_id_stack();
198
  }
199
200
6832
  return scope.EscapeMaybe(result);
201
}
202
203
#if HAVE_INSPECTOR
204
5230
int Environment::InitializeInspector(
205
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
206
10460
  std::string inspector_path;
207
5230
  bool is_main = !parent_handle;
208
5230
  if (parent_handle) {
209
414
    inspector_path = parent_handle->url();
210
414
    inspector_agent_->SetParentHandle(std::move(parent_handle));
211
  } else {
212
4816
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
213
  }
214
215
5230
  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
10460
  inspector_agent_->Start(inspector_path,
220
                          options_->debug_options(),
221
10460
                          inspector_host_port(),
222
5230
                          is_main);
223

5311
  if (options_->debug_options().inspector_enabled &&
224
81
      !inspector_agent_->IsListening()) {
225
5
    return 12;  // Signal internal error
226
  }
227
228
5225
  profiler::StartProfilers(this);
229
230
5225
  if (inspector_agent_->options().break_node_first_line) {
231
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
232
  }
233
234
5225
  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
4
    ATOMIC_WAIT_EVENTS(V)
261
2
#undef V
262
  }
263
264
9
  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
8
          message);
274
8
}
275
276
5205
void Environment::InitializeDiagnostics() {
277
5205
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
278
5205
      Environment::BuildEmbedderGraph, this);
279
5205
  if (options_->heap_snapshot_near_heap_limit > 0) {
280
1
    isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
281
1
                                       this);
282
  }
283
5205
  if (options_->trace_uncaught)
284
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
285
5205
  if (options_->trace_atomics_wait) {
286
2
    isolate_->SetAtomicsWaitCallback(AtomicsWaitCallback, this);
287
10
    AddCleanupHook([](void* data) {
288
2
      Environment* env = static_cast<Environment*>(data);
289
2
      env->isolate()->SetAtomicsWaitCallback(nullptr, nullptr);
290
8
    }, this);
291
  }
292
293
#if defined HAVE_DTRACE || defined HAVE_ETW
294
  InitDTrace(this);
295
#endif
296
5205
}
297
298
467
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
299
467
  EscapableHandleScope scope(isolate_);
300
301
  // Create binding loaders
302
  std::vector<Local<String>> loaders_params = {
303
      process_string(),
304
467
      FIXED_ONE_BYTE_STRING(isolate_, "getLinkedBinding"),
305
467
      FIXED_ONE_BYTE_STRING(isolate_, "getInternalBinding"),
306
1868
      primordials_string()};
307
  std::vector<Local<Value>> loaders_args = {
308
      process_object(),
309
934
      NewFunctionTemplate(binding::GetLinkedBinding)
310
1401
          ->GetFunction(context())
311
          .ToLocalChecked(),
312
934
      NewFunctionTemplate(binding::GetInternalBinding)
313
1401
          ->GetFunction(context())
314
          .ToLocalChecked(),
315
1867
      primordials()};
316
317
  // Bootstrap internal loaders
318
  Local<Value> loader_exports;
319
934
  if (!ExecuteBootstrapper(
320
           this, "internal/bootstrap/loaders", &loaders_params, &loaders_args)
321
467
           .ToLocal(&loader_exports)) {
322
    return MaybeLocal<Value>();
323
  }
324
467
  CHECK(loader_exports->IsObject());
325
467
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
326
  Local<Value> internal_binding_loader =
327
1868
      loader_exports_obj->Get(context(), internal_binding_string())
328
467
          .ToLocalChecked();
329
467
  CHECK(internal_binding_loader->IsFunction());
330
467
  set_internal_binding_loader(internal_binding_loader.As<Function>());
331
  Local<Value> require =
332
1868
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
333
467
  CHECK(require->IsFunction());
334
467
  set_native_module_require(require.As<Function>());
335
336
466
  return scope.Escape(loader_exports);
337
}
338
339
467
MaybeLocal<Value> Environment::BootstrapNode() {
340
467
  EscapableHandleScope scope(isolate_);
341
342
934
  Local<Object> global = context()->Global();
343
  // TODO(joyeecheung): this can be done in JS land now.
344
1868
  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
      process_string(),
350
      require_string(),
351
      internal_binding_string(),
352
934
      primordials_string()};
353
  std::vector<Local<Value>> node_args = {
354
      process_object(),
355
      native_module_require(),
356
      internal_binding_loader(),
357
2802
      primordials()};
358
359
  MaybeLocal<Value> result = ExecuteBootstrapper(
360
467
      this, "internal/bootstrap/node", &node_params, &node_args);
361
362
467
  if (result.IsEmpty()) {
363
    return scope.EscapeMaybe(result);
364
  }
365
366
  // TODO(joyeecheung): skip these in the snapshot building for workers.
367
  auto thread_switch_id =
368
467
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
369
467
                       : "internal/bootstrap/switches/is_not_main_thread";
370
  result =
371
467
      ExecuteBootstrapper(this, thread_switch_id, &node_params, &node_args);
372
373
467
  if (result.IsEmpty()) {
374
    return scope.EscapeMaybe(result);
375
  }
376
377
  auto process_state_switch_id =
378
467
      owns_process_state()
379
467
          ? "internal/bootstrap/switches/does_own_process_state"
380
467
          : "internal/bootstrap/switches/does_not_own_process_state";
381
  result = ExecuteBootstrapper(
382
467
      this, process_state_switch_id, &node_params, &node_args);
383
384
467
  if (result.IsEmpty()) {
385
    return scope.EscapeMaybe(result);
386
  }
387
388
467
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
389
  Local<Object> env_var_proxy;
390

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


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

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


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

149699
    if (nr == SIGKILL || nr == SIGSTOP)
623
9658
      continue;
624

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

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

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

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

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

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

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

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


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

28484
  if (per_process::cli_options->disable_proto != "delete" &&
800

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

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

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

9569
  if (per_process::cli_options->use_largepages == "on" ||
1003
4784
      per_process::cli_options->use_largepages == "silent") {
1004
1
    int result = node::MapStaticCodeToLargePages();
1005

1
    if (per_process::cli_options->use_largepages == "on" && result != 0) {
1006
      fprintf(stderr, "%s\n", node::LargePagesError(result));
1007
    }
1008
  }
1009
1010
4785
  if (per_process::cli_options->print_version) {
1011
3
    printf("%s\n", NODE_VERSION);
1012
3
    result.exit_code = 0;
1013
3
    result.early_return = true;
1014
3
    return result;
1015
  }
1016
1017
4782
  if (per_process::cli_options->print_bash_completion) {
1018
2
    std::string completion = options_parser::GetBashCompletion();
1019
1
    printf("%s\n", completion.c_str());
1020
1
    result.exit_code = 0;
1021
1
    result.early_return = true;
1022
1
    return result;
1023
  }
1024
1025
4781
  if (per_process::cli_options->print_v8_help) {
1026
1
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1027
    result.exit_code = 0;
1028
    result.early_return = true;
1029
    return result;
1030
  }
1031
1032
4780
  if (init_flags & kInitOpenSSL) {
1033
#if HAVE_OPENSSL
1034
    {
1035
9560
      std::string extra_ca_certs;
1036
4780
      if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1037
4
        crypto::UseExtraCaCerts(extra_ca_certs);
1038
    }
1039
    // In the case of FIPS builds we should make sure
1040
    // the random source is properly initialized first.
1041
#if OPENSSL_VERSION_MAJOR >= 3
1042
    // Call OPENSSL_init_crypto to initialize OPENSSL_INIT_LOAD_CONFIG to
1043
    // avoid the default behavior where errors raised during the parsing of the
1044
    // OpenSSL configuration file are not propagated and cannot be detected.
1045
    //
1046
    // If FIPS is configured the OpenSSL configuration file will have an
1047
    // .include pointing to the fipsmodule.cnf file generated by the openssl
1048
    // fipsinstall command. If the path to this file is incorrect no error
1049
    // will be reported.
1050
    //
1051
    // For Node.js this will mean that EntropySource will be called by V8 as
1052
    // part of its initialization process, and EntropySource will in turn call
1053
    // CheckEntropy. CheckEntropy will call RAND_status which will now always
1054
    // return 0, leading to an endless loop and the node process will appear to
1055
    // hang/freeze.
1056
    std::string env_openssl_conf;
1057
    credentials::SafeGetenv("OPENSSL_CONF", &env_openssl_conf);
1058
1059
    bool has_cli_conf = !per_process::cli_options->openssl_config.empty();
1060
    if (has_cli_conf || !env_openssl_conf.empty()) {
1061
      OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
1062
      OPENSSL_INIT_set_config_file_flags(settings, CONF_MFLAGS_DEFAULT_SECTION);
1063
      if (has_cli_conf) {
1064
        const char* conf = per_process::cli_options->openssl_config.c_str();
1065
        OPENSSL_INIT_set_config_filename(settings, conf);
1066
      }
1067
      OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
1068
      OPENSSL_INIT_free(settings);
1069
1070
      if (ERR_peek_error() != 0) {
1071
        result.exit_code = ERR_GET_REASON(ERR_peek_error());
1072
        result.early_return = true;
1073
        fprintf(stderr, "OpenSSL configuration error:\n");
1074
        ERR_print_errors_fp(stderr);
1075
        return result;
1076
      }
1077
    }
1078
#else
1079
4780
    if (FIPS_mode()) {
1080
      OPENSSL_init();
1081
    }
1082
#endif
1083
    // V8 on Windows doesn't have a good source of entropy. Seed it from
1084
    // OpenSSL's pool.
1085
4780
    V8::SetEntropySource(crypto::EntropySource);
1086
#endif  // HAVE_OPENSSL
1087
}
1088
4780
  per_process::v8_platform.Initialize(
1089
9560
      static_cast<int>(per_process::cli_options->v8_thread_pool_size));
1090
4780
  if (init_flags & kInitializeV8) {
1091
    V8::Initialize();
1092
  }
1093
1094
4780
  performance::performance_v8_start = PERFORMANCE_NOW();
1095
4780
  per_process::v8_initialized = true;
1096
1097
4780
  return result;
1098
}
1099
1100
4210
void TearDownOncePerProcess() {
1101
4210
  per_process::v8_initialized = false;
1102
4210
  V8::Dispose();
1103
1104
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1105
  RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1106
#endif
1107
1108
  // uv_run cannot be called from the time before the beforeExit callback
1109
  // runs until the program exits unless the event loop has any referenced
1110
  // handles after beforeExit terminates. This prevents unrefed timers
1111
  // that happen to terminate during shutdown from being run unsafely.
1112
  // Since uv_run cannot be called, uv_async handles held by the platform
1113
  // will never be fully cleaned up.
1114
4210
  per_process::v8_platform.Dispose();
1115
4210
}
1116
1117
4821
int Start(int argc, char** argv) {
1118
9071
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1119
4820
  if (result.early_return) {
1120
48
    return result.exit_code;
1121
  }
1122
1123
  {
1124
8974
    Isolate::CreateParams params;
1125
4772
    const std::vector<size_t>* indexes = nullptr;
1126
4772
    const EnvSerializeInfo* env_info = nullptr;
1127
    bool force_no_snapshot =
1128
4772
        per_process::cli_options->per_isolate->no_node_snapshot;
1129
4772
    if (!force_no_snapshot) {
1130
4771
      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();
1131
4771
      if (blob != nullptr) {
1132
4771
        params.snapshot_blob = blob;
1133
4771
        indexes = NodeMainInstance::GetIsolateDataIndexes();
1134
4771
        env_info = NodeMainInstance::GetEnvSerializeInfo();
1135
      }
1136
    }
1137
4772
    uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1138
1139
    NodeMainInstance main_instance(&params,
1140
                                   uv_default_loop(),
1141
4772
                                   per_process::v8_platform.Platform(),
1142
                                   result.args,
1143
                                   result.exec_args,
1144
8974
                                   indexes);
1145
4772
    result.exit_code = main_instance.Run(env_info);
1146
  }
1147
1148
4202
  TearDownOncePerProcess();
1149
4202
  return result.exit_code;
1150
}
1151
1152
118
int Stop(Environment* env) {
1153
118
  env->ExitEnv();
1154
118
  return 0;
1155
}
1156
1157

14535
}  // namespace node
1158
1159
#if !HAVE_INSPECTOR
1160
void Initialize() {}
1161
1162
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1163
#endif  // !HAVE_INSPECTOR