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: 356 424 84.0 %
Date: 2020-06-24 22:13:30 Branches: 212 315 67.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__)
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
#include <atomic>
80
#include "v8-wasm-trap-handler-posix.h"
81
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
82
83
// ========== global C headers ==========
84
85
#include <fcntl.h>  // _O_RDWR
86
#include <sys/types.h>
87
88
#if defined(NODE_HAVE_I18N_SUPPORT)
89
#include <unicode/uvernum.h>
90
#include <unicode/utypes.h>
91
#endif
92
93
94
#if defined(LEAK_SANITIZER)
95
#include <sanitizer/lsan_interface.h>
96
#endif
97
98
#if defined(_MSC_VER)
99
#include <direct.h>
100
#include <io.h>
101
#define STDIN_FILENO 0
102
#else
103
#include <pthread.h>
104
#include <sys/resource.h>  // getrlimit, setrlimit
105
#include <termios.h>       // tcgetattr, tcsetattr
106
#include <unistd.h>        // STDIN_FILENO, STDERR_FILENO
107
#endif
108
109
// ========== global C++ headers ==========
110
111
#include <cerrno>
112
#include <climits>  // PATH_MAX
113
#include <csignal>
114
#include <cstdio>
115
#include <cstdlib>
116
#include <cstring>
117
118
#include <string>
119
#include <vector>
120
121
namespace node {
122
123
using native_module::NativeModuleEnv;
124
125
using v8::EscapableHandleScope;
126
using v8::Function;
127
using v8::FunctionCallbackInfo;
128
using v8::Isolate;
129
using v8::Local;
130
using v8::MaybeLocal;
131
using v8::Object;
132
using v8::String;
133
using v8::Undefined;
134
using v8::V8;
135
using v8::Value;
136
137
namespace per_process {
138
139
// node_revert.h
140
// Bit flag used to track security reverts.
141
unsigned int reverted_cve = 0;
142
143
// util.h
144
// Tells whether the per-process V8::Initialize() is called and
145
// if it is safe to call v8::Isolate::GetCurrent().
146
bool v8_initialized = false;
147
148
// node_internals.h
149
// process-relative uptime base in nanoseconds, initialized in node::Start()
150
uint64_t node_start_time;
151
// Tells whether --prof is passed.
152
bool v8_is_profiling = false;
153
154
// node_v8_platform-inl.h
155
4399
struct V8Platform v8_platform;
156
}  // namespace per_process
157
158
#ifdef __POSIX__
159
void SignalExit(int signo, siginfo_t* info, void* ucontext) {
160
  ResetStdio();
161
  raise(signo);
162
}
163
#endif  // __POSIX__
164
165
23500
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
166
                                      const char* id,
167
                                      std::vector<Local<String>>* parameters,
168
                                      std::vector<Local<Value>>* arguments) {
169
23500
  EscapableHandleScope scope(env->isolate());
170
  MaybeLocal<Function> maybe_fn =
171
23500
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
172
173
  Local<Function> fn;
174
23500
  if (!maybe_fn.ToLocal(&fn)) {
175
    return MaybeLocal<Value>();
176
  }
177
178
  MaybeLocal<Value> result = fn->Call(env->context(),
179
                                      Undefined(env->isolate()),
180
23500
                                      arguments->size(),
181
94000
                                      arguments->data());
182
183
  // If there was an error during bootstrap, it must be unrecoverable
184
  // (e.g. max call stack exceeded). Clear the stack so that the
185
  // AsyncCallbackScope destructor doesn't fail on the id check.
186
  // There are only two ways to have a stack size > 1: 1) the user manually
187
  // called MakeCallback or 2) user awaited during bootstrap, which triggered
188
  // _tickCallback().
189
23212
  if (result.IsEmpty()) {
190
30
    env->async_hooks()->clear_async_id_stack();
191
  }
192
193
23212
  return scope.EscapeMaybe(result);
194
}
195
196
#if HAVE_INSPECTOR
197
4703
int Environment::InitializeInspector(
198
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
199
9406
  std::string inspector_path;
200
4703
  bool is_main = !parent_handle;
201
4703
  if (parent_handle) {
202
336
    inspector_path = parent_handle->url();
203
336
    inspector_agent_->SetParentHandle(std::move(parent_handle));
204
  } else {
205
4367
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
206
  }
207
208
4703
  CHECK(!inspector_agent_->IsListening());
209
  // Inspector agent can't fail to start, but if it was configured to listen
210
  // right away on the websocket port and fails to bind/etc, this will return
211
  // false.
212
9406
  inspector_agent_->Start(inspector_path,
213
                          options_->debug_options(),
214
9406
                          inspector_host_port(),
215
4703
                          is_main);
216

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

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

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


4326
  if (env->options()->has_eval_string && !env->options()->force_repl) {
488
307
    return StartExecution(env, "internal/main/eval_string");
489
  }
490
491
4019
  if (env->options()->syntax_check_only) {
492
34
    return StartExecution(env, "internal/main/check_syntax");
493
  }
494
495

3985
  if (!first_argv.empty() && first_argv != "-") {
496
3949
    return StartExecution(env, "internal/main/run_main_module");
497
  }
498
499


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

136152
    if (nr == SIGKILL || nr == SIGSTOP)
603
8784
      continue;
604

127368
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
605
127368
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
606
  }
607
#endif  // !NODE_SHARED_MODE
608
609
  // Record the state of the stdio file descriptors so we can restore it
610
  // on exit.  Needs to happen before installing signal handlers because
611
  // they make use of that information.
612
17568
  for (auto& s : stdio) {
613
13176
    const int fd = &s - stdio;
614
    int err;
615
616
    do
617
13176
      s.flags = fcntl(fd, F_GETFL);
618

13176
    while (s.flags == -1 && errno == EINTR);  // NOLINT
619
13176
    CHECK_NE(s.flags, -1);
620
621
13176
    if (uv_guess_handle(fd) != UV_TTY) continue;
622
120
    s.isatty = true;
623
624
    do
625
120
      err = tcgetattr(fd, &s.termios);
626

120
    while (err == -1 && errno == EINTR);  // NOLINT
627
120
    CHECK_EQ(err, 0);
628
  }
629
630
4392
  RegisterSignalHandler(SIGINT, SignalExit, true);
631
4392
  RegisterSignalHandler(SIGTERM, SignalExit, true);
632
633
#if NODE_USE_V8_WASM_TRAP_HANDLER
634
  // Tell V8 to disable emitting WebAssembly
635
  // memory bounds checks. This means that we have
636
  // to catch the SIGSEGV in TrapWebAssemblyOrContinue
637
  // and pass the signal context to V8.
638
  {
639
    struct sigaction sa;
640
4392
    memset(&sa, 0, sizeof(sa));
641
4392
    sa.sa_sigaction = TrapWebAssemblyOrContinue;
642
4392
    CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
643
  }
644
4392
  V8::EnableWebAssemblyTrapHandler(false);
645
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
646
647
  // Raise the open file descriptor limit.
648
  struct rlimit lim;
649

4392
  if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
650
    // Do a binary search for the limit.
651
    rlim_t min = lim.rlim_cur;
652
    rlim_t max = 1 << 20;
653
    // But if there's a defined upper bound, don't search, just set it.
654
    if (lim.rlim_max != RLIM_INFINITY) {
655
      min = lim.rlim_max;
656
      max = lim.rlim_max;
657
    }
658
    do {
659
      lim.rlim_cur = min + (max - min) / 2;
660
      if (setrlimit(RLIMIT_NOFILE, &lim)) {
661
        max = lim.rlim_cur;
662
      } else {
663
        min = lim.rlim_cur;
664
      }
665
    } while (min + 1 < max);
666
  }
667
#endif  // __POSIX__
668
#ifdef _WIN32
669
  for (int fd = 0; fd <= 2; ++fd) {
670
    auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
671
    if (handle == INVALID_HANDLE_VALUE ||
672
        GetFileType(handle) == FILE_TYPE_UNKNOWN) {
673
      // Ignore _close result. If it fails or not depends on used Windows
674
      // version. We will just check _open result.
675
      _close(fd);
676
      if (fd != _open("nul", _O_RDWR))
677
        ABORT();
678
    }
679
  }
680
#endif  // _WIN32
681
4392
}
682
683
684
// Safe to call more than once and from signal handlers.
685
8269
void ResetStdio() {
686
8269
  uv_tty_reset_mode();
687
#ifdef __POSIX__
688
33076
  for (auto& s : stdio) {
689
24807
    const int fd = &s - stdio;
690
691
    struct stat tmp;
692
24807
    if (-1 == fstat(fd, &tmp)) {
693
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
694
6
      continue;
695
    }
696
697
    bool is_same_file =
698

24807
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
699
24807
    if (!is_same_file) continue;  // Program reopened file descriptor.
700
701
    int flags;
702
    do
703
24801
      flags = fcntl(fd, F_GETFL);
704

24801
    while (flags == -1 && errno == EINTR);  // NOLINT
705
24801
    CHECK_NE(flags, -1);
706
707
    // Restore the O_NONBLOCK flag if it changed.
708
24801
    if (O_NONBLOCK & (flags ^ s.flags)) {
709
751
      flags &= ~O_NONBLOCK;
710
751
      flags |= s.flags & O_NONBLOCK;
711
712
      int err;
713
      do
714
751
        err = fcntl(fd, F_SETFL, flags);
715

751
      while (err == -1 && errno == EINTR);  // NOLINT
716
751
      CHECK_NE(err, -1);
717
    }
718
719
24801
    if (s.isatty) {
720
      sigset_t sa;
721
      int err;
722
723
      // We might be a background job that doesn't own the TTY so block SIGTTOU
724
      // before making the tcsetattr() call, otherwise that signal suspends us.
725
228
      sigemptyset(&sa);
726
228
      sigaddset(&sa, SIGTTOU);
727
728
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
729
      do
730
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
731

228
      while (err == -1 && errno == EINTR);  // NOLINT
732
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
733
228
      CHECK_EQ(0, err);
734
    }
735
  }
736
#endif  // __POSIX__
737
8269
}
738
739
740
8675
int ProcessGlobalArgs(std::vector<std::string>* args,
741
                      std::vector<std::string>* exec_args,
742
                      std::vector<std::string>* errors,
743
                      OptionEnvvarSettings settings) {
744
  // Parse a few arguments which are specific to Node.
745
17350
  std::vector<std::string> v8_args;
746
747
17350
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
748
8675
  options_parser::Parse(
749
      args,
750
      exec_args,
751
      &v8_args,
752
      per_process::cli_options.get(),
753
      settings,
754
8675
      errors);
755
756
8675
  if (!errors->empty()) return 9;
757
758
17264
  std::string revert_error;
759
8632
  for (const std::string& cve : per_process::cli_options->security_reverts) {
760
1
    Revert(cve.c_str(), &revert_error);
761
1
    if (!revert_error.empty()) {
762
1
      errors->emplace_back(std::move(revert_error));
763
1
      return 12;
764
    }
765
  }
766
767

25892
  if (per_process::cli_options->disable_proto != "delete" &&
768

17260
      per_process::cli_options->disable_proto != "throw" &&
769
8629
      per_process::cli_options->disable_proto != "") {
770
    errors->emplace_back("invalid mode passed to --disable-proto");
771
    return 12;
772
  }
773
774
17262
  auto env_opts = per_process::cli_options->per_isolate->per_env;
775
34524
  if (std::find(v8_args.begin(), v8_args.end(),
776

34507
                "--abort-on-uncaught-exception") != v8_args.end() ||
777
17245
      std::find(v8_args.begin(), v8_args.end(),
778
25859
                "--abort_on_uncaught_exception") != v8_args.end()) {
779
20
    env_opts->abort_on_uncaught_exception = true;
780
  }
781
782
  // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
783
  // manually?  That would give us a little more control over its runtime
784
  // behavior but it could also interfere with the user's intentions in ways
785
  // we fail to anticipate.  Dillema.
786
8631
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
787
2
    per_process::v8_is_profiling = true;
788
  }
789
790
#ifdef __POSIX__
791
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
792
  // performance penalty of frequent EINTR wakeups when the profiler is running.
793
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
794
8631
  if (per_process::v8_is_profiling) {
795
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
796
  }
797
#endif
798
799
17262
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
800
8631
  if (v8_args.size() > 0) {
801
17425
    for (size_t i = 0; i < v8_args.size(); ++i)
802
8794
      v8_args_as_char_ptr[i] = &v8_args[i][0];
803
8631
    int argc = v8_args.size();
804
8631
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
805
8631
    v8_args_as_char_ptr.resize(argc);
806
  }
807
808
  // Anything that's still in v8_argv is not a V8 or a node option.
809
8644
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
810
13
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
811
812
8631
  if (v8_args_as_char_ptr.size() > 1) return 9;
813
814
8620
  return 0;
815
}
816
817
static std::atomic_bool init_called{false};
818
819
4398
int InitializeNodeWithArgs(std::vector<std::string>* argv,
820
                           std::vector<std::string>* exec_argv,
821
                           std::vector<std::string>* errors) {
822
  // Make sure InitializeNodeWithArgs() is called only once.
823
4398
  CHECK(!init_called.exchange(true));
824
825
  // Initialize node_start_time to get relative uptime.
826
4398
  per_process::node_start_time = uv_hrtime();
827
828
  // Register built-in modules
829
4398
  binding::RegisterBuiltinModules();
830
831
  // Make inherited handles noninheritable.
832
4398
  uv_disable_stdio_inheritance();
833
834
  // Cache the original command line to be
835
  // used in diagnostic reports.
836
4398
  per_process::cli_options->cmdline = *argv;
837
838
#if defined(NODE_V8_OPTIONS)
839
  // Should come before the call to V8::SetFlagsFromCommandLine()
840
  // so the user can disable a flag --foo at run-time by passing
841
  // --no_foo from the command line.
842
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
843
#endif
844
845
4398
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
846
847
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
848
8796
  std::string node_options;
849
850
4398
  if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
851
    std::vector<std::string> env_argv =
852
8571
        ParseNodeOptionsEnvVar(node_options, errors);
853
854
4294
    if (!errors->empty()) return 9;
855
856
    // [0] is expected to be the program name, fill it in from the real argv.
857
4294
    env_argv.insert(env_argv.begin(), argv->at(0));
858
859
    const int exit_code = ProcessGlobalArgs(&env_argv,
860
                                            nullptr,
861
                                            errors,
862
4294
                                            kAllowedInEnvironment);
863

4294
    if (exit_code != 0) return exit_code;
864
  }
865
#endif
866
867
  const int exit_code = ProcessGlobalArgs(argv,
868
                                          exec_argv,
869
                                          errors,
870
4381
                                          kDisallowedInEnvironment);
871
4381
  if (exit_code != 0) return exit_code;
872
873
  // Set the process.title immediately after processing argv if --title is set.
874
4343
  if (!per_process::cli_options->title.empty())
875
2
    uv_set_process_title(per_process::cli_options->title.c_str());
876
877
#if defined(NODE_HAVE_I18N_SUPPORT)
878
  // If the parameter isn't given, use the env variable.
879
4343
  if (per_process::cli_options->icu_data_dir.empty())
880
4343
    credentials::SafeGetenv("NODE_ICU_DATA",
881
8686
                            &per_process::cli_options->icu_data_dir);
882
883
#ifdef NODE_ICU_DEFAULT_DATA_DIR
884
  // If neither the CLI option nor the environment variable was specified,
885
  // fall back to the configured default
886
  if (per_process::cli_options->icu_data_dir.empty()) {
887
    // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
888
    // file and can be read.
889
    static const char full_path[] =
890
        NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
891
892
    FILE* f = fopen(full_path, "rb");
893
894
    if (f != nullptr) {
895
      fclose(f);
896
      per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
897
    }
898
  }
899
#endif  // NODE_ICU_DEFAULT_DATA_DIR
900
901
  // Initialize ICU.
902
  // If icu_data_dir is empty here, it will load the 'minimal' data.
903
4343
  if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
904
    errors->push_back("could not initialize ICU "
905
                      "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
906
    return 9;
907
  }
908
4343
  per_process::metadata.versions.InitializeIntlVersions();
909
#endif
910
911
4343
  NativeModuleEnv::InitializeCodeCache();
912
913
  // We should set node_is_initialized here instead of in node::Start,
914
  // otherwise embedders using node::Init to initialize everything will not be
915
  // able to set it and native modules will not load for them.
916
4343
  node_is_initialized = true;
917
4343
  return 0;
918
}
919
920
// TODO(addaleax): Deprecate and eventually remove this.
921
void Init(int* argc,
922
          const char** argv,
923
          int* exec_argc,
924
          const char*** exec_argv) {
925
  std::vector<std::string> argv_(argv, argv + *argc);  // NOLINT
926
  std::vector<std::string> exec_argv_;
927
  std::vector<std::string> errors;
928
929
  // This (approximately) duplicates some logic that has been moved to
930
  // node::Start(), with the difference that here we explicitly call `exit()`.
931
  int exit_code = InitializeNodeWithArgs(&argv_, &exec_argv_, &errors);
932
933
  for (const std::string& error : errors)
934
    fprintf(stderr, "%s: %s\n", argv_.at(0).c_str(), error.c_str());
935
  if (exit_code != 0) exit(exit_code);
936
937
  if (per_process::cli_options->print_version) {
938
    printf("%s\n", NODE_VERSION);
939
    exit(0);
940
  }
941
942
  if (per_process::cli_options->print_bash_completion) {
943
    std::string completion = options_parser::GetBashCompletion();
944
    printf("%s\n", completion.c_str());
945
    exit(0);
946
  }
947
948
  if (per_process::cli_options->print_v8_help) {
949
    // Doesn't return.
950
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
951
    UNREACHABLE();
952
  }
953
954
  *argc = argv_.size();
955
  *exec_argc = exec_argv_.size();
956
  // These leak memory, because, in the original code of this function, no
957
  // extra allocations were visible. This should be okay because this function
958
  // is only supposed to be called once per process, though.
959
  *exec_argv = Malloc<const char*>(*exec_argc);
960
  for (int i = 0; i < *exec_argc; ++i)
961
    (*exec_argv)[i] = strdup(exec_argv_[i].c_str());
962
  for (int i = 0; i < *argc; ++i)
963
    argv[i] = strdup(argv_[i].c_str());
964
}
965
966
4392
InitializationResult InitializeOncePerProcess(int argc, char** argv) {
967
  // Initialized the enabled list for Debug() calls with system
968
  // environment variables.
969
4392
  per_process::enabled_debug_list.Parse(nullptr);
970
971
4392
  atexit(ResetStdio);
972
4392
  PlatformInit();
973
974
4392
  CHECK_GT(argc, 0);
975
976
  // Hack around with the argv pointer. Used for process.title = "blah".
977
4392
  argv = uv_setup_args(argc, argv);
978
979
4392
  InitializationResult result;
980
4392
  result.args = std::vector<std::string>(argv, argv + argc);
981
8782
  std::vector<std::string> errors;
982
983
  // This needs to run *before* V8::Initialize().
984
  {
985
4392
    result.exit_code =
986
4392
        InitializeNodeWithArgs(&(result.args), &(result.exec_args), &errors);
987
4449
    for (const std::string& error : errors)
988
57
      fprintf(stderr, "%s: %s\n", result.args.at(0).c_str(), error.c_str());
989
4392
    if (result.exit_code != 0) {
990
55
      result.early_return = true;
991
55
      return result;
992
    }
993
  }
994
995

8673
  if (per_process::cli_options->use_largepages == "on" ||
996
4336
      per_process::cli_options->use_largepages == "silent") {
997
1
    int result = node::MapStaticCodeToLargePages();
998

1
    if (per_process::cli_options->use_largepages == "on" && result != 0) {
999
1
      fprintf(stderr, "%s\n", node::LargePagesError(result));
1000
    }
1001
  }
1002
1003
4337
  if (per_process::cli_options->print_version) {
1004
3
    printf("%s\n", NODE_VERSION);
1005
3
    result.exit_code = 0;
1006
3
    result.early_return = true;
1007
3
    return result;
1008
  }
1009
1010
4334
  if (per_process::cli_options->print_bash_completion) {
1011
1
    std::string completion = options_parser::GetBashCompletion();
1012
1
    printf("%s\n", completion.c_str());
1013
1
    exit(0);
1014
  }
1015
1016
4333
  if (per_process::cli_options->print_v8_help) {
1017
    // Doesn't return.
1018
1
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1019
    UNREACHABLE();
1020
  }
1021
1022
#if HAVE_OPENSSL
1023
  {
1024
8664
    std::string extra_ca_certs;
1025
4332
    if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1026
4
      crypto::UseExtraCaCerts(extra_ca_certs);
1027
  }
1028
#ifdef NODE_FIPS_MODE
1029
  // In the case of FIPS builds we should make sure
1030
  // the random source is properly initialized first.
1031
  OPENSSL_init();
1032
#endif  // NODE_FIPS_MODE
1033
  // V8 on Windows doesn't have a good source of entropy. Seed it from
1034
  // OpenSSL's pool.
1035
4332
  V8::SetEntropySource(crypto::EntropySource);
1036
#endif  // HAVE_OPENSSL
1037
1038
4332
  per_process::v8_platform.Initialize(
1039
8664
      per_process::cli_options->v8_thread_pool_size);
1040
4332
  V8::Initialize();
1041
4332
  performance::performance_v8_start = PERFORMANCE_NOW();
1042
4332
  per_process::v8_initialized = true;
1043
4332
  return result;
1044
}
1045
1046
3864
void TearDownOncePerProcess() {
1047
3864
  per_process::v8_initialized = false;
1048
3864
  V8::Dispose();
1049
1050
  // uv_run cannot be called from the time before the beforeExit callback
1051
  // runs until the program exits unless the event loop has any referenced
1052
  // handles after beforeExit terminates. This prevents unrefed timers
1053
  // that happen to terminate during shutdown from being run unsafely.
1054
  // Since uv_run cannot be called, uv_async handles held by the platform
1055
  // will never be fully cleaned up.
1056
3864
  per_process::v8_platform.Dispose();
1057
3864
}
1058
1059
4391
int Start(int argc, char** argv) {
1060
8312
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1061
4389
  if (result.early_return) {
1062
58
    return result.exit_code;
1063
  }
1064
1065
  {
1066
8194
    Isolate::CreateParams params;
1067
4331
    const std::vector<size_t>* indexes = nullptr;
1068
8194
    std::vector<intptr_t> external_references;
1069
1070
    bool force_no_snapshot =
1071
4331
        per_process::cli_options->per_isolate->no_node_snapshot;
1072
4331
    if (!force_no_snapshot) {
1073
4330
      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();
1074
4330
      if (blob != nullptr) {
1075
        // TODO(joyeecheung): collect external references and set it in
1076
        // params.external_references.
1077
4330
        external_references.push_back(reinterpret_cast<intptr_t>(nullptr));
1078
4330
        params.external_references = external_references.data();
1079
4330
        params.snapshot_blob = blob;
1080
4330
        indexes = NodeMainInstance::GetIsolateDataIndexes();
1081
      }
1082
    }
1083
1084
    NodeMainInstance main_instance(&params,
1085
                                   uv_default_loop(),
1086
4331
                                   per_process::v8_platform.Platform(),
1087
                                   result.args,
1088
                                   result.exec_args,
1089
8194
                                   indexes);
1090
4331
    result.exit_code = main_instance.Run();
1091
  }
1092
1093
3863
  TearDownOncePerProcess();
1094
3863
  return result.exit_code;
1095
}
1096
1097
85
int Stop(Environment* env) {
1098
85
  env->ExitEnv();
1099
85
  return 0;
1100
}
1101
1102

13197
}  // namespace node
1103
1104
#if !HAVE_INSPECTOR
1105
void Initialize() {}
1106
1107
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1108
#endif  // !HAVE_INSPECTOR