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: 351 402 87.3 %
Date: 2020-02-27 22:14:15 Branches: 208 300 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_revert.h"
39
#include "node_v8_platform-inl.h"
40
#include "node_version.h"
41
42
#if HAVE_OPENSSL
43
#include "node_crypto.h"
44
#endif
45
46
#if defined(NODE_HAVE_I18N_SUPPORT)
47
#include "node_i18n.h"
48
#endif
49
50
#if HAVE_INSPECTOR
51
#include "inspector_agent.h"
52
#include "inspector_io.h"
53
#endif
54
55
#if defined HAVE_DTRACE || defined HAVE_ETW
56
#include "node_dtrace.h"
57
#endif
58
59
#if NODE_USE_V8_PLATFORM
60
#include "libplatform/libplatform.h"
61
#endif  // NODE_USE_V8_PLATFORM
62
#include "v8-profiler.h"
63
64
#if HAVE_INSPECTOR
65
#include "inspector/worker_inspector.h"  // ParentInspectorHandle
66
#endif
67
68
#include "large_pages/node_large_page.h"
69
70
#ifdef NODE_REPORT
71
#include "node_report.h"
72
#endif
73
74
#if defined(__APPLE__) || defined(__linux__)
75
#define NODE_USE_V8_WASM_TRAP_HANDLER 1
76
#else
77
#define NODE_USE_V8_WASM_TRAP_HANDLER 0
78
#endif
79
80
#if NODE_USE_V8_WASM_TRAP_HANDLER
81
#include <atomic>
82
#include "v8-wasm-trap-handler-posix.h"
83
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
84
85
// ========== global C headers ==========
86
87
#include <fcntl.h>  // _O_RDWR
88
#include <sys/types.h>
89
90
#if defined(NODE_HAVE_I18N_SUPPORT)
91
#include <unicode/uvernum.h>
92
#include <unicode/utypes.h>
93
#endif
94
95
96
#if defined(LEAK_SANITIZER)
97
#include <sanitizer/lsan_interface.h>
98
#endif
99
100
#if defined(_MSC_VER)
101
#include <direct.h>
102
#include <io.h>
103
#define STDIN_FILENO 0
104
#else
105
#include <pthread.h>
106
#include <sys/resource.h>  // getrlimit, setrlimit
107
#include <termios.h>       // tcgetattr, tcsetattr
108
#include <unistd.h>        // STDIN_FILENO, STDERR_FILENO
109
#endif
110
111
// ========== global C++ headers ==========
112
113
#include <cerrno>
114
#include <climits>  // PATH_MAX
115
#include <csignal>
116
#include <cstdio>
117
#include <cstdlib>
118
#include <cstring>
119
120
#include <string>
121
#include <vector>
122
123
namespace node {
124
125
using native_module::NativeModuleEnv;
126
127
using v8::EscapableHandleScope;
128
using v8::Function;
129
using v8::FunctionCallbackInfo;
130
using v8::HandleScope;
131
using v8::Isolate;
132
using v8::Local;
133
using v8::Maybe;
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
// Tells whether --prof is passed.
156
bool v8_is_profiling = false;
157
158
// node_v8_platform-inl.h
159
4202
struct V8Platform v8_platform;
160
}  // namespace per_process
161
162
#ifdef __POSIX__
163
void SignalExit(int signo, siginfo_t* info, void* ucontext) {
164
  ResetStdio();
165
  raise(signo);
166
}
167
#endif  // __POSIX__
168
169
21929
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
170
                                      const char* id,
171
                                      std::vector<Local<String>>* parameters,
172
                                      std::vector<Local<Value>>* arguments) {
173
21929
  EscapableHandleScope scope(env->isolate());
174
  MaybeLocal<Function> maybe_fn =
175
21929
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
176
177
21930
  if (maybe_fn.IsEmpty()) {
178
    return MaybeLocal<Value>();
179
  }
180
181
21930
  Local<Function> fn = maybe_fn.ToLocalChecked();
182
  MaybeLocal<Value> result = fn->Call(env->context(),
183
                                      Undefined(env->isolate()),
184
21930
                                      arguments->size(),
185
87720
                                      arguments->data());
186
187
  // If there was an error during bootstrap, it must be unrecoverable
188
  // (e.g. max call stack exceeded). Clear the stack so that the
189
  // AsyncCallbackScope destructor doesn't fail on the id check.
190
  // There are only two ways to have a stack size > 1: 1) the user manually
191
  // called MakeCallback or 2) user awaited during bootstrap, which triggered
192
  // _tickCallback().
193
21692
  if (result.IsEmpty()) {
194
29
    env->async_hooks()->clear_async_id_stack();
195
  }
196
197
21692
  return scope.EscapeMaybe(result);
198
}
199
200
#if HAVE_INSPECTOR
201
4367
int Environment::InitializeInspector(
202
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
203
8734
  std::string inspector_path;
204
4367
  if (parent_handle) {
205
    DCHECK(!is_main_thread());
206
228
    inspector_path = parent_handle->url();
207
228
    inspector_agent_->SetParentHandle(std::move(parent_handle));
208
  } else {
209
4139
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
210
  }
211
212
4367
  CHECK(!inspector_agent_->IsListening());
213
  // Inspector agent can't fail to start, but if it was configured to listen
214
  // right away on the websocket port and fails to bind/etc, this will return
215
  // false.
216
8734
  inspector_agent_->Start(inspector_path,
217
                          options_->debug_options(),
218
8734
                          inspector_host_port(),
219
8734
                          is_main_thread());
220

4445
  if (options_->debug_options().inspector_enabled &&
221
78
      !inspector_agent_->IsListening()) {
222
5
    return 12;  // Signal internal error
223
  }
224
225
4362
  profiler::StartProfilers(this);
226
227
4362
  if (inspector_agent_->options().break_node_first_line) {
228
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
229
  }
230
231
4362
  return 0;
232
}
233
#endif  // HAVE_INSPECTOR && NODE_USE_V8_PLATFORM
234
235
4367
void Environment::InitializeDiagnostics() {
236
4367
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
237
4367
      Environment::BuildEmbedderGraph, this);
238
4367
  if (options_->trace_uncaught)
239
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
240
241
#if defined HAVE_DTRACE || defined HAVE_ETW
242
  InitDTrace(this);
243
#endif
244
4367
}
245
246
4391
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
247
4391
  EscapableHandleScope scope(isolate_);
248
249
  // Create binding loaders
250
  std::vector<Local<String>> loaders_params = {
251
      process_string(),
252
4391
      FIXED_ONE_BYTE_STRING(isolate_, "getLinkedBinding"),
253
4391
      FIXED_ONE_BYTE_STRING(isolate_, "getInternalBinding"),
254
17564
      primordials_string()};
255
  std::vector<Local<Value>> loaders_args = {
256
      process_object(),
257
8782
      NewFunctionTemplate(binding::GetLinkedBinding)
258
13173
          ->GetFunction(context())
259
          .ToLocalChecked(),
260
8782
      NewFunctionTemplate(binding::GetInternalBinding)
261
13173
          ->GetFunction(context())
262
          .ToLocalChecked(),
263
17564
      primordials()};
264
265
  // Bootstrap internal loaders
266
  Local<Value> loader_exports;
267
8782
  if (!ExecuteBootstrapper(
268
           this, "internal/bootstrap/loaders", &loaders_params, &loaders_args)
269
4391
           .ToLocal(&loader_exports)) {
270
    return MaybeLocal<Value>();
271
  }
272
4391
  CHECK(loader_exports->IsObject());
273
4391
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
274
  Local<Value> internal_binding_loader =
275
17564
      loader_exports_obj->Get(context(), internal_binding_string())
276
4391
          .ToLocalChecked();
277
4391
  CHECK(internal_binding_loader->IsFunction());
278
4391
  set_internal_binding_loader(internal_binding_loader.As<Function>());
279
  Local<Value> require =
280
17564
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
281
4391
  CHECK(require->IsFunction());
282
4391
  set_native_module_require(require.As<Function>());
283
284
4391
  return scope.Escape(loader_exports);
285
}
286
287
4391
MaybeLocal<Value> Environment::BootstrapNode() {
288
4391
  EscapableHandleScope scope(isolate_);
289
290
8782
  Local<Object> global = context()->Global();
291
  // TODO(joyeecheung): this can be done in JS land now.
292
17564
  global->Set(context(), FIXED_ONE_BYTE_STRING(isolate_, "global"), global)
293
      .Check();
294
295
  // process, require, internalBinding, primordials
296
  std::vector<Local<String>> node_params = {
297
      process_string(),
298
      require_string(),
299
      internal_binding_string(),
300
8782
      primordials_string()};
301
  std::vector<Local<Value>> node_args = {
302
      process_object(),
303
      native_module_require(),
304
      internal_binding_loader(),
305
26346
      primordials()};
306
307
  MaybeLocal<Value> result = ExecuteBootstrapper(
308
4391
      this, "internal/bootstrap/node", &node_params, &node_args);
309
310
4391
  if (result.IsEmpty()) {
311
    return scope.EscapeMaybe(result);
312
  }
313
314
  auto thread_switch_id =
315
4391
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
316
4391
                       : "internal/bootstrap/switches/is_not_main_thread";
317
  result =
318
4391
      ExecuteBootstrapper(this, thread_switch_id, &node_params, &node_args);
319
320
4391
  if (result.IsEmpty()) {
321
    return scope.EscapeMaybe(result);
322
  }
323
324
  auto process_state_switch_id =
325
4391
      owns_process_state()
326
4391
          ? "internal/bootstrap/switches/does_own_process_state"
327
4391
          : "internal/bootstrap/switches/does_not_own_process_state";
328
  result = ExecuteBootstrapper(
329
4391
      this, process_state_switch_id, &node_params, &node_args);
330
331
4391
  if (result.IsEmpty()) {
332
    return scope.EscapeMaybe(result);
333
  }
334
335
4391
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
336
  Local<Object> env_var_proxy;
337
17564
  if (!CreateEnvVarProxy(context(), isolate_, as_callback_data())
338

13173
           .ToLocal(&env_var_proxy) ||
339
17564
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
340
    return MaybeLocal<Value>();
341
  }
342
343
4391
  return scope.EscapeMaybe(result);
344
}
345
346
4391
MaybeLocal<Value> Environment::RunBootstrapping() {
347
4391
  EscapableHandleScope scope(isolate_);
348
349
4391
  CHECK(!has_run_bootstrapping_code());
350
351
8782
  if (BootstrapInternalLoaders().IsEmpty()) {
352
    return MaybeLocal<Value>();
353
  }
354
355
  Local<Value> result;
356
8782
  if (!BootstrapNode().ToLocal(&result)) {
357
    return MaybeLocal<Value>();
358
  }
359
360
  // Make sure that no request or handle is created during bootstrap -
361
  // if necessary those should be done in pre-execution.
362
  // Usually, doing so would trigger the checks present in the ReqWrap and
363
  // HandleWrap classes, so this is only a consistency check.
364
4391
  CHECK(req_wrap_queue()->IsEmpty());
365
4391
  CHECK(handle_wrap_queue()->IsEmpty());
366
367
4391
  set_has_run_bootstrapping_code(true);
368
369
4391
  return scope.Escape(result);
370
}
371
372
4351
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
373
4351
  Environment* env = Environment::GetCurrent(args);
374
4351
  env->performance_state()->Mark(
375
4351
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
376
4351
}
377
378
4365
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
379
4365
  EscapableHandleScope scope(env->isolate());
380
4365
  CHECK_NOT_NULL(main_script_id);
381
382
  std::vector<Local<String>> parameters = {
383
      env->process_string(),
384
      env->require_string(),
385
      env->internal_binding_string(),
386
      env->primordials_string(),
387
8467
      FIXED_ONE_BYTE_STRING(env->isolate(), "markBootstrapComplete")};
388
389
  std::vector<Local<Value>> arguments = {
390
      env->process_object(),
391
      env->native_module_require(),
392
      env->internal_binding_loader(),
393
      env->primordials(),
394
8731
      env->NewFunctionTemplate(MarkBootstrapComplete)
395
13097
          ->GetFunction(env->context())
396
25930
          .ToLocalChecked()};
397
398
  InternalCallbackScope callback_scope(
399
    env,
400
    Object::New(env->isolate()),
401
    { 1, 0 },
402
8493
    InternalCallbackScope::kSkipAsyncHooks);
403
404
  return scope.EscapeMaybe(
405
8467
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
406
}
407
408
4138
MaybeLocal<Value> StartMainThreadExecution(Environment* env) {
409
  // To allow people to extend Node in different ways, this hook allows
410
  // one to drop a file lib/_third_party_main.js into the build
411
  // directory which will be executed instead of Node's normal loading.
412
4138
  if (NativeModuleEnv::Exists("_third_party_main")) {
413
    return StartExecution(env, "internal/main/run_third_party_main");
414
  }
415
416
8012
  std::string first_argv;
417
4138
  if (env->argv().size() > 1) {
418
3813
    first_argv = env->argv()[1];
419
  }
420
421

4138
  if (first_argv == "inspect" || first_argv == "debug") {
422
4
    return StartExecution(env, "internal/main/inspect");
423
  }
424
425
4134
  if (per_process::cli_options->print_help) {
426
1
    return StartExecution(env, "internal/main/print_help");
427
  }
428
429
430
4133
  if (env->options()->prof_process) {
431
1
    return StartExecution(env, "internal/main/prof_process");
432
  }
433
434
  // -e/--eval without -i/--interactive
435


4132
  if (env->options()->has_eval_string && !env->options()->force_repl) {
436
299
    return StartExecution(env, "internal/main/eval_string");
437
  }
438
439
3833
  if (env->options()->syntax_check_only) {
440
34
    return StartExecution(env, "internal/main/check_syntax");
441
  }
442
443

3799
  if (!first_argv.empty() && first_argv != "-") {
444
3763
    return StartExecution(env, "internal/main/run_main_module");
445
  }
446
447


36
  if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
448
19
    return StartExecution(env, "internal/main/repl");
449
  }
450
451
17
  return StartExecution(env, "internal/main/eval_stdin");
452
}
453
454
4138
void LoadEnvironment(Environment* env) {
455
4138
  CHECK(env->is_main_thread());
456
  // TODO(joyeecheung): Not all of the execution modes in
457
  // StartMainThreadExecution() make sense for embedders. Pick the
458
  // useful ones out, and allow embedders to customize the entry
459
  // point more directly without using _third_party_main.js
460
4138
  USE(StartMainThreadExecution(env));
461
3874
}
462
463
#ifdef __POSIX__
464
typedef void (*sigaction_cb)(int signo, siginfo_t* info, void* ucontext);
465
#endif
466
#if NODE_USE_V8_WASM_TRAP_HANDLER
467
4202
static std::atomic<sigaction_cb> previous_sigsegv_action;
468
469
6
void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) {
470
6
  if (!v8::TryHandleWebAssemblyTrapPosix(signo, info, ucontext)) {
471
6
    sigaction_cb prev = previous_sigsegv_action.load();
472
6
    if (prev != nullptr) {
473
6
      prev(signo, info, ucontext);
474
    } else {
475
      // Reset to the default signal handler, i.e. cause a hard crash.
476
      struct sigaction sa;
477
      memset(&sa, 0, sizeof(sa));
478
      sa.sa_handler = SIG_DFL;
479
      CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
480
481
      ResetStdio();
482
      raise(signo);
483
    }
484
  }
485
6
}
486
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
487
488
#ifdef __POSIX__
489
12789
void RegisterSignalHandler(int signal,
490
                           sigaction_cb handler,
491
                           bool reset_handler) {
492
12789
  CHECK_NOT_NULL(handler);
493
#if NODE_USE_V8_WASM_TRAP_HANDLER
494
12789
  if (signal == SIGSEGV) {
495
4
    CHECK(previous_sigsegv_action.is_lock_free());
496
4
    CHECK(!reset_handler);
497
4
    previous_sigsegv_action.store(handler);
498
4
    return;
499
  }
500
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
501
  struct sigaction sa;
502
12785
  memset(&sa, 0, sizeof(sa));
503
12785
  sa.sa_sigaction = handler;
504
12785
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
505
12785
  sigfillset(&sa.sa_mask);
506
12785
  CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
507
}
508
509
#endif  // __POSIX__
510
511
#ifdef __POSIX__
512
static struct {
513
  int flags;
514
  bool isatty;
515
  struct stat stat;
516
  struct termios termios;
517
} stdio[1 + STDERR_FILENO];
518
#endif  // __POSIX__
519
520
521
4199
inline void PlatformInit() {
522
#ifdef __POSIX__
523
#if HAVE_INSPECTOR
524
  sigset_t sigmask;
525
4199
  sigemptyset(&sigmask);
526
4199
  sigaddset(&sigmask, SIGUSR1);
527
4199
  const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
528
#endif  // HAVE_INSPECTOR
529
530
  // Make sure file descriptors 0-2 are valid before we start logging anything.
531
16796
  for (auto& s : stdio) {
532
12597
    const int fd = &s - stdio;
533
12597
    if (fstat(fd, &s.stat) == 0)
534
12595
      continue;
535
    // Anything but EBADF means something is seriously wrong.  We don't
536
    // have to special-case EINTR, fstat() is not interruptible.
537
2
    if (errno != EBADF)
538
      ABORT();
539
2
    if (fd != open("/dev/null", O_RDWR))
540
      ABORT();
541
2
    if (fstat(fd, &s.stat) != 0)
542
      ABORT();
543
  }
544
545
#if HAVE_INSPECTOR
546
4199
  CHECK_EQ(err, 0);
547
#endif  // HAVE_INSPECTOR
548
549
  // TODO(addaleax): NODE_SHARED_MODE does not really make sense here.
550
#ifndef NODE_SHARED_MODE
551
  // Restore signal dispositions, the parent process may have changed them.
552
  struct sigaction act;
553
4199
  memset(&act, 0, sizeof(act));
554
555
  // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
556
  // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
557
  // Counting up to SIGRTMIN doesn't work for the same reason.
558
134368
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
559

130169
    if (nr == SIGKILL || nr == SIGSTOP)
560
8398
      continue;
561

121771
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
562
121771
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
563
  }
564
#endif  // !NODE_SHARED_MODE
565
566
  // Record the state of the stdio file descriptors so we can restore it
567
  // on exit.  Needs to happen before installing signal handlers because
568
  // they make use of that information.
569
16796
  for (auto& s : stdio) {
570
12597
    const int fd = &s - stdio;
571
    int err;
572
573
    do
574
12597
      s.flags = fcntl(fd, F_GETFL);
575

12597
    while (s.flags == -1 && errno == EINTR);  // NOLINT
576
12597
    CHECK_NE(s.flags, -1);
577
578
12597
    if (uv_guess_handle(fd) != UV_TTY) continue;
579
120
    s.isatty = true;
580
581
    do
582
120
      err = tcgetattr(fd, &s.termios);
583

120
    while (err == -1 && errno == EINTR);  // NOLINT
584
120
    CHECK_EQ(err, 0);
585
  }
586
587
4199
  RegisterSignalHandler(SIGINT, SignalExit, true);
588
4199
  RegisterSignalHandler(SIGTERM, SignalExit, true);
589
590
#if NODE_USE_V8_WASM_TRAP_HANDLER
591
  // Tell V8 to disable emitting WebAssembly
592
  // memory bounds checks. This means that we have
593
  // to catch the SIGSEGV in TrapWebAssemblyOrContinue
594
  // and pass the signal context to V8.
595
  {
596
    struct sigaction sa;
597
4199
    memset(&sa, 0, sizeof(sa));
598
4199
    sa.sa_sigaction = TrapWebAssemblyOrContinue;
599
4199
    CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
600
  }
601
4199
  V8::EnableWebAssemblyTrapHandler(false);
602
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
603
604
  // Raise the open file descriptor limit.
605
  struct rlimit lim;
606

4199
  if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
607
    // Do a binary search for the limit.
608
    rlim_t min = lim.rlim_cur;
609
    rlim_t max = 1 << 20;
610
    // But if there's a defined upper bound, don't search, just set it.
611
    if (lim.rlim_max != RLIM_INFINITY) {
612
      min = lim.rlim_max;
613
      max = lim.rlim_max;
614
    }
615
    do {
616
      lim.rlim_cur = min + (max - min) / 2;
617
      if (setrlimit(RLIMIT_NOFILE, &lim)) {
618
        max = lim.rlim_cur;
619
      } else {
620
        min = lim.rlim_cur;
621
      }
622
    } while (min + 1 < max);
623
  }
624
#endif  // __POSIX__
625
#ifdef _WIN32
626
  for (int fd = 0; fd <= 2; ++fd) {
627
    auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
628
    if (handle == INVALID_HANDLE_VALUE ||
629
        GetFileType(handle) == FILE_TYPE_UNKNOWN) {
630
      // Ignore _close result. If it fails or not depends on used Windows
631
      // version. We will just check _open result.
632
      _close(fd);
633
      if (fd != _open("nul", _O_RDWR))
634
        ABORT();
635
    }
636
  }
637
#endif  // _WIN32
638
4199
}
639
640
641
// Safe to call more than once and from signal handlers.
642
7949
void ResetStdio() {
643
7949
  uv_tty_reset_mode();
644
#ifdef __POSIX__
645
31796
  for (auto& s : stdio) {
646
23847
    const int fd = &s - stdio;
647
648
    struct stat tmp;
649
23847
    if (-1 == fstat(fd, &tmp)) {
650
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
651
6
      continue;
652
    }
653
654
    bool is_same_file =
655

23847
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
656
23847
    if (!is_same_file) continue;  // Program reopened file descriptor.
657
658
    int flags;
659
    do
660
23841
      flags = fcntl(fd, F_GETFL);
661

23841
    while (flags == -1 && errno == EINTR);  // NOLINT
662
23841
    CHECK_NE(flags, -1);
663
664
    // Restore the O_NONBLOCK flag if it changed.
665
23841
    if (O_NONBLOCK & (flags ^ s.flags)) {
666
751
      flags &= ~O_NONBLOCK;
667
751
      flags |= s.flags & O_NONBLOCK;
668
669
      int err;
670
      do
671
751
        err = fcntl(fd, F_SETFL, flags);
672

751
      while (err == -1 && errno == EINTR);  // NOLINT
673
751
      CHECK_NE(err, -1);
674
    }
675
676
23841
    if (s.isatty) {
677
      sigset_t sa;
678
      int err;
679
680
      // We might be a background job that doesn't own the TTY so block SIGTTOU
681
      // before making the tcsetattr() call, otherwise that signal suspends us.
682
228
      sigemptyset(&sa);
683
228
      sigaddset(&sa, SIGTTOU);
684
685
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
686
      do
687
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
688

228
      while (err == -1 && errno == EINTR);  // NOLINT
689
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
690
228
      CHECK_EQ(0, err);
691
    }
692
  }
693
#endif  // __POSIX__
694
7949
}
695
696
697
8289
int ProcessGlobalArgs(std::vector<std::string>* args,
698
                      std::vector<std::string>* exec_args,
699
                      std::vector<std::string>* errors,
700
                      OptionEnvvarSettings settings) {
701
  // Parse a few arguments which are specific to Node.
702
16578
  std::vector<std::string> v8_args;
703
704
16578
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
705
8289
  options_parser::Parse(
706
      args,
707
      exec_args,
708
      &v8_args,
709
      per_process::cli_options.get(),
710
      settings,
711
8289
      errors);
712
713
8289
  if (!errors->empty()) return 9;
714
715
16494
  std::string revert_error;
716
8247
  for (const std::string& cve : per_process::cli_options->security_reverts) {
717
1
    Revert(cve.c_str(), &revert_error);
718
1
    if (!revert_error.empty()) {
719
1
      errors->emplace_back(std::move(revert_error));
720
1
      return 12;
721
    }
722
  }
723
724
16492
  auto env_opts = per_process::cli_options->per_isolate->per_env;
725
32984
  if (std::find(v8_args.begin(), v8_args.end(),
726

32967
                "--abort-on-uncaught-exception") != v8_args.end() ||
727
16475
      std::find(v8_args.begin(), v8_args.end(),
728
24704
                "--abort_on_uncaught_exception") != v8_args.end()) {
729
20
    env_opts->abort_on_uncaught_exception = true;
730
  }
731
732
  // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
733
  // manually?  That would give us a little more control over its runtime
734
  // behavior but it could also interfere with the user's intentions in ways
735
  // we fail to anticipate.  Dillema.
736
8246
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
737
2
    per_process::v8_is_profiling = true;
738
  }
739
740
#ifdef __POSIX__
741
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
742
  // performance penalty of frequent EINTR wakeups when the profiler is running.
743
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
744
8246
  if (per_process::v8_is_profiling) {
745
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
746
  }
747
#endif
748
749
16492
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
750
8246
  if (v8_args.size() > 0) {
751
16645
    for (size_t i = 0; i < v8_args.size(); ++i)
752
8399
      v8_args_as_char_ptr[i] = &v8_args[i][0];
753
8246
    int argc = v8_args.size();
754
8246
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
755
8246
    v8_args_as_char_ptr.resize(argc);
756
  }
757
758
  // Anything that's still in v8_argv is not a V8 or a node option.
759
8259
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
760
13
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
761
762
8246
  if (v8_args_as_char_ptr.size() > 1) return 9;
763
764
8235
  return 0;
765
}
766
767
static std::atomic_bool init_called{false};
768
769
4201
int InitializeNodeWithArgs(std::vector<std::string>* argv,
770
                           std::vector<std::string>* exec_argv,
771
                           std::vector<std::string>* errors) {
772
  // Make sure InitializeNodeWithArgs() is called only once.
773
4201
  CHECK(!init_called.exchange(true));
774
775
  // Initialize node_start_time to get relative uptime.
776
4201
  per_process::node_start_time = uv_hrtime();
777
778
  // Register built-in modules
779
4201
  binding::RegisterBuiltinModules();
780
781
  // Make inherited handles noninheritable.
782
4201
  uv_disable_stdio_inheritance();
783
784
#ifdef NODE_REPORT
785
  // Cache the original command line to be
786
  // used in diagnostic reports.
787
4201
  per_process::cli_options->cmdline = *argv;
788
#endif  //  NODE_REPORT
789
790
#if defined(NODE_V8_OPTIONS)
791
  // Should come before the call to V8::SetFlagsFromCommandLine()
792
  // so the user can disable a flag --foo at run-time by passing
793
  // --no_foo from the command line.
794
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
795
#endif
796
797
4201
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
798
799
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
800
8402
  std::string node_options;
801
802
4201
  if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
803
    std::vector<std::string> env_argv =
804
8191
        ParseNodeOptionsEnvVar(node_options, errors);
805
806
4103
    if (!errors->empty()) return 9;
807
808
    // [0] is expected to be the program name, fill it in from the real argv.
809
4103
    env_argv.insert(env_argv.begin(), argv->at(0));
810
811
    const int exit_code = ProcessGlobalArgs(&env_argv,
812
                                            nullptr,
813
                                            errors,
814
4103
                                            kAllowedInEnvironment);
815

4103
    if (exit_code != 0) return exit_code;
816
  }
817
#endif
818
819
  const int exit_code = ProcessGlobalArgs(argv,
820
                                          exec_argv,
821
                                          errors,
822
4186
                                          kDisallowedInEnvironment);
823
4186
  if (exit_code != 0) return exit_code;
824
825
  // Set the process.title immediately after processing argv if --title is set.
826
4147
  if (!per_process::cli_options->title.empty())
827
2
    uv_set_process_title(per_process::cli_options->title.c_str());
828
829
#if defined(NODE_HAVE_I18N_SUPPORT)
830
  // If the parameter isn't given, use the env variable.
831
4147
  if (per_process::cli_options->icu_data_dir.empty())
832
4147
    credentials::SafeGetenv("NODE_ICU_DATA",
833
8294
                            &per_process::cli_options->icu_data_dir);
834
835
#ifdef NODE_ICU_DEFAULT_DATA_DIR
836
  // If neither the CLI option nor the environment variable was specified,
837
  // fall back to the configured default
838
  if (per_process::cli_options->icu_data_dir.empty()) {
839
    // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
840
    // file and can be read.
841
    static const char full_path[] =
842
        NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
843
844
    FILE* f = fopen(full_path, "rb");
845
846
    if (f != nullptr) {
847
      fclose(f);
848
      per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
849
    }
850
  }
851
#endif  // NODE_ICU_DEFAULT_DATA_DIR
852
853
  // Initialize ICU.
854
  // If icu_data_dir is empty here, it will load the 'minimal' data.
855
4147
  if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
856
    errors->push_back("could not initialize ICU "
857
                      "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
858
    return 9;
859
  }
860
4147
  per_process::metadata.versions.InitializeIntlVersions();
861
#endif
862
863
4147
  NativeModuleEnv::InitializeCodeCache();
864
865
  // We should set node_is_initialized here instead of in node::Start,
866
  // otherwise embedders using node::Init to initialize everything will not be
867
  // able to set it and native modules will not load for them.
868
4147
  node_is_initialized = true;
869
4147
  return 0;
870
}
871
872
// TODO(addaleax): Deprecate and eventually remove this.
873
1
void Init(int* argc,
874
          const char** argv,
875
          int* exec_argc,
876
          const char*** exec_argv) {
877
2
  std::vector<std::string> argv_(argv, argv + *argc);  // NOLINT
878
2
  std::vector<std::string> exec_argv_;
879
2
  std::vector<std::string> errors;
880
881
  // This (approximately) duplicates some logic that has been moved to
882
  // node::Start(), with the difference that here we explicitly call `exit()`.
883
1
  int exit_code = InitializeNodeWithArgs(&argv_, &exec_argv_, &errors);
884
885
1
  for (const std::string& error : errors)
886
    fprintf(stderr, "%s: %s\n", argv_.at(0).c_str(), error.c_str());
887
1
  if (exit_code != 0) exit(exit_code);
888
889
1
  if (per_process::cli_options->print_version) {
890
    printf("%s\n", NODE_VERSION);
891
    exit(0);
892
  }
893
894
1
  if (per_process::cli_options->print_bash_completion) {
895
    std::string completion = options_parser::GetBashCompletion();
896
    printf("%s\n", completion.c_str());
897
    exit(0);
898
  }
899
900
1
  if (per_process::cli_options->print_v8_help) {
901
    // Doesn't return.
902
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
903
    UNREACHABLE();
904
  }
905
906
1
  *argc = argv_.size();
907
1
  *exec_argc = exec_argv_.size();
908
  // These leak memory, because, in the original code of this function, no
909
  // extra allocations were visible. This should be okay because this function
910
  // is only supposed to be called once per process, though.
911
1
  *exec_argv = Malloc<const char*>(*exec_argc);
912
1
  for (int i = 0; i < *exec_argc; ++i)
913
    (*exec_argv)[i] = strdup(exec_argv_[i].c_str());
914
2
  for (int i = 0; i < *argc; ++i)
915
1
    argv[i] = strdup(argv_[i].c_str());
916
1
}
917
918
4200
InitializationResult InitializeOncePerProcess(int argc, char** argv) {
919
4200
  atexit(ResetStdio);
920
4200
  PlatformInit();
921
922
4200
  CHECK_GT(argc, 0);
923
924
  // Hack around with the argv pointer. Used for process.title = "blah".
925
4200
  argv = uv_setup_args(argc, argv);
926
927
4200
  InitializationResult result;
928
4200
  result.args = std::vector<std::string>(argv, argv + argc);
929
8398
  std::vector<std::string> errors;
930
931
  // This needs to run *before* V8::Initialize().
932
  {
933
4200
    result.exit_code =
934
4200
        InitializeNodeWithArgs(&(result.args), &(result.exec_args), &errors);
935
4256
    for (const std::string& error : errors)
936
56
      fprintf(stderr, "%s: %s\n", result.args.at(0).c_str(), error.c_str());
937
4200
    if (result.exit_code != 0) {
938
54
      result.early_return = true;
939
54
      return result;
940
    }
941
  }
942
943

8291
  if (per_process::cli_options->use_largepages == "on" ||
944
4145
      per_process::cli_options->use_largepages == "silent") {
945
1
    int result = node::MapStaticCodeToLargePages();
946

1
    if (per_process::cli_options->use_largepages == "on" && result != 0) {
947
1
      fprintf(stderr, "%s\n", node::LargePagesError(result));
948
    }
949
  }
950
951
4146
  if (per_process::cli_options->print_version) {
952
3
    printf("%s\n", NODE_VERSION);
953
3
    result.exit_code = 0;
954
3
    result.early_return = true;
955
3
    return result;
956
  }
957
958
4143
  if (per_process::cli_options->print_bash_completion) {
959
1
    std::string completion = options_parser::GetBashCompletion();
960
1
    printf("%s\n", completion.c_str());
961
1
    exit(0);
962
  }
963
964
4142
  if (per_process::cli_options->print_v8_help) {
965
    // Doesn't return.
966
1
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
967
    UNREACHABLE();
968
  }
969
970
#if HAVE_OPENSSL
971
  {
972
8282
    std::string extra_ca_certs;
973
4141
    if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
974
3
      crypto::UseExtraCaCerts(extra_ca_certs);
975
  }
976
#ifdef NODE_FIPS_MODE
977
  // In the case of FIPS builds we should make sure
978
  // the random source is properly initialized first.
979
  OPENSSL_init();
980
#endif  // NODE_FIPS_MODE
981
  // V8 on Windows doesn't have a good source of entropy. Seed it from
982
  // OpenSSL's pool.
983
4141
  V8::SetEntropySource(crypto::EntropySource);
984
#endif  // HAVE_OPENSSL
985
986
4141
  per_process::v8_platform.Initialize(
987
8282
      per_process::cli_options->v8_thread_pool_size);
988
4141
  V8::Initialize();
989
4141
  performance::performance_v8_start = PERFORMANCE_NOW();
990
4141
  per_process::v8_initialized = true;
991
4141
  return result;
992
}
993
994
3736
void TearDownOncePerProcess() {
995
3736
  per_process::v8_initialized = false;
996
3736
  V8::Dispose();
997
998
  // uv_run cannot be called from the time before the beforeExit callback
999
  // runs until the program exits unless the event loop has any referenced
1000
  // handles after beforeExit terminates. This prevents unrefed timers
1001
  // that happen to terminate during shutdown from being run unsafely.
1002
  // Since uv_run cannot be called, uv_async handles held by the platform
1003
  // will never be fully cleaned up.
1004
3736
  per_process::v8_platform.Dispose();
1005
3736
}
1006
1007
4199
int Start(int argc, char** argv) {
1008
7991
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1009
4197
  if (result.early_return) {
1010
57
    return result.exit_code;
1011
  }
1012
1013
  {
1014
7875
    Isolate::CreateParams params;
1015
4140
    const std::vector<size_t>* indexes = nullptr;
1016
7875
    std::vector<intptr_t> external_references;
1017
1018
    bool force_no_snapshot =
1019
4140
        per_process::cli_options->per_isolate->no_node_snapshot;
1020
4140
    if (!force_no_snapshot) {
1021
4139
      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();
1022
4139
      if (blob != nullptr) {
1023
        // TODO(joyeecheung): collect external references and set it in
1024
        // params.external_references.
1025
4139
        external_references.push_back(reinterpret_cast<intptr_t>(nullptr));
1026
4139
        params.external_references = external_references.data();
1027
4139
        params.snapshot_blob = blob;
1028
4139
        indexes = NodeMainInstance::GetIsolateDataIndexes();
1029
      }
1030
    }
1031
1032
    NodeMainInstance main_instance(&params,
1033
                                   uv_default_loop(),
1034
4140
                                   per_process::v8_platform.Platform(),
1035
                                   result.args,
1036
                                   result.exec_args,
1037
7875
                                   indexes);
1038
4140
    result.exit_code = main_instance.Run();
1039
  }
1040
1041
3735
  TearDownOncePerProcess();
1042
3735
  return result.exit_code;
1043
}
1044
1045
61
int Stop(Environment* env) {
1046
61
  env->ExitEnv();
1047
61
  return 0;
1048
}
1049
1050

12606
}  // namespace node
1051
1052
#if !HAVE_INSPECTOR
1053
void Initialize() {}
1054
1055
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1056
#endif  // !HAVE_INSPECTOR