-
Notifications
You must be signed in to change notification settings - Fork 30k
/
node.cc
1505 lines (1308 loc) Β· 51 KB
/
node.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "node.h"
#include "node_dotenv.h"
#include "node_task_runner.h"
// ========== local headers ==========
#include "debug_utils-inl.h"
#include "env-inl.h"
#include "histogram-inl.h"
#include "memory_tracker-inl.h"
#include "node_binding.h"
#include "node_builtins.h"
#include "node_errors.h"
#include "node_internals.h"
#include "node_main_instance.h"
#include "node_metadata.h"
#include "node_options-inl.h"
#include "node_perf.h"
#include "node_process-inl.h"
#include "node_realm-inl.h"
#include "node_report.h"
#include "node_revert.h"
#include "node_sea.h"
#include "node_snapshot_builder.h"
#include "node_v8_platform-inl.h"
#include "node_version.h"
#if HAVE_OPENSSL
#include "ncrypto.h"
#include "node_crypto.h"
#endif
#if defined(NODE_HAVE_I18N_SUPPORT)
#include "node_i18n.h"
#endif
#if HAVE_INSPECTOR
#include "inspector_agent.h"
#include "inspector_io.h"
#endif
#if NODE_USE_V8_PLATFORM
#include "libplatform/libplatform.h"
#endif // NODE_USE_V8_PLATFORM
#include "v8-profiler.h"
#include "cppgc/platform.h"
#if HAVE_INSPECTOR
#include "inspector/worker_inspector.h" // ParentInspectorHandle
#endif
#ifdef NODE_ENABLE_VTUNE_PROFILING
#include "../deps/v8/src/third_party/vtune/v8-vtune.h"
#endif
#include "large_pages/node_large_page.h"
#if defined(__APPLE__) || defined(__linux__) || defined(_WIN32)
#define NODE_USE_V8_WASM_TRAP_HANDLER 1
#else
#define NODE_USE_V8_WASM_TRAP_HANDLER 0
#endif
#if NODE_USE_V8_WASM_TRAP_HANDLER
#if defined(_WIN32)
#include "v8-wasm-trap-handler-win.h"
#else
#include <atomic>
#include "v8-wasm-trap-handler-posix.h"
#endif
#endif // NODE_USE_V8_WASM_TRAP_HANDLER
// ========== global C headers ==========
#include <fcntl.h> // _O_RDWR
#include <sys/types.h>
#if defined(NODE_HAVE_I18N_SUPPORT)
#include <unicode/uvernum.h>
#include <unicode/utypes.h>
#endif
#if defined(LEAK_SANITIZER)
#include <sanitizer/lsan_interface.h>
#endif
#if defined(_MSC_VER)
#include <direct.h>
#include <io.h>
#define STDIN_FILENO 0
#else
#include <pthread.h>
#include <sys/resource.h> // getrlimit, setrlimit
#include <termios.h> // tcgetattr, tcsetattr
#include <unistd.h> // STDIN_FILENO, STDERR_FILENO
#endif
// ========== global C++ headers ==========
#include <cerrno>
#include <climits> // PATH_MAX
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <tuple>
#include <vector>
namespace node {
using v8::Array;
using v8::Context;
using v8::EscapableHandleScope;
using v8::Function;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::Object;
using v8::V8;
using v8::Value;
namespace per_process {
// node_dotenv.h
// Instance is used to store environment variables including NODE_OPTIONS.
node::Dotenv dotenv_file = Dotenv();
// node_revert.h
// Bit flag used to track security reverts.
unsigned int reverted_cve = 0;
// util.h
// Tells whether the per-process V8::Initialize() is called and
// if it is safe to call v8::Isolate::TryGetCurrent().
bool v8_initialized = false;
// node_internals.h
// process-relative uptime base in nanoseconds, initialized in node::Start()
uint64_t node_start_time;
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
PVOID old_vectored_exception_handler;
#endif
// node_v8_platform-inl.h
struct V8Platform v8_platform;
} // namespace per_process
// The section in the OpenSSL configuration file to be loaded.
const char* conf_section_name = STRINGIFY(NODE_OPENSSL_CONF_NAME);
#ifdef __POSIX__
void SignalExit(int signo, siginfo_t* info, void* ucontext) {
ResetStdio();
raise(signo);
}
#endif // __POSIX__
#if HAVE_INSPECTOR
void Environment::InitializeInspector(
std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
std::string inspector_path;
bool is_main = !parent_handle;
if (parent_handle) {
inspector_path = parent_handle->url();
inspector_agent_->SetParentHandle(std::move(parent_handle));
} else {
inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
}
CHECK(!inspector_agent_->IsListening());
// Inspector agent can't fail to start, but if it was configured to listen
// right away on the websocket port and fails to bind/etc, this will return
// false.
inspector_agent_->Start(inspector_path,
options_->debug_options(),
inspector_host_port(),
is_main);
if (options_->debug_options().inspector_enabled &&
!inspector_agent_->IsListening()) {
return;
}
if (should_wait_for_inspector_frontend()) {
WaitForInspectorFrontendByOptions();
}
profiler::StartProfilers(this);
}
void Environment::WaitForInspectorFrontendByOptions() {
if (!inspector_agent_->WaitForConnectByOptions()) {
return;
}
if (inspector_agent_->options().break_node_first_line) {
inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
}
return;
}
#endif // HAVE_INSPECTOR
void Environment::InitializeDiagnostics() {
isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
Environment::BuildEmbedderGraph, this);
if (heap_snapshot_near_heap_limit_ > 0) {
AddHeapSnapshotNearHeapLimitCallback();
}
if (options_->trace_uncaught)
isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
if (options_->trace_promises) {
isolate_->SetPromiseHook(TracePromises);
}
}
static
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
EscapableHandleScope scope(env->isolate());
CHECK_NOT_NULL(main_script_id);
Realm* realm = env->principal_realm();
return scope.EscapeMaybe(realm->ExecuteBootstrapper(main_script_id));
}
// Convert the result returned by an intermediate main script into
// StartExecutionCallbackInfo. Currently the result is an array containing
// [process, requireFunction, cjsRunner]
std::optional<StartExecutionCallbackInfo> CallbackInfoFromArray(
Local<Context> context, Local<Value> result) {
CHECK(result->IsArray());
Local<Array> args = result.As<Array>();
CHECK_EQ(args->Length(), 3);
Local<Value> process_obj, require_fn, runcjs_fn;
if (!args->Get(context, 0).ToLocal(&process_obj) ||
!args->Get(context, 1).ToLocal(&require_fn) ||
!args->Get(context, 2).ToLocal(&runcjs_fn)) {
return std::nullopt;
}
CHECK(process_obj->IsObject());
CHECK(require_fn->IsFunction());
CHECK(runcjs_fn->IsFunction());
// TODO(joyeecheung): some support for running ESM as an entrypoint
// is needed. The simplest API would be to add a run_esm to
// StartExecutionCallbackInfo which compiles, links (to builtins)
// and evaluates a SourceTextModule.
// TODO(joyeecheung): the env pointer should be part of
// StartExecutionCallbackInfo, otherwise embedders are forced to use
// lambdas to pass it into the callback, which can make the code
// difficult to read.
node::StartExecutionCallbackInfo info{process_obj.As<Object>(),
require_fn.As<Function>(),
runcjs_fn.As<Function>()};
return info;
}
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
InternalCallbackScope callback_scope(
env,
Object::New(env->isolate()),
{ 1, 0 },
InternalCallbackScope::kSkipAsyncHooks);
// Only snapshot builder or embedder applications set the
// callback.
if (cb != nullptr) {
EscapableHandleScope scope(env->isolate());
Local<Value> result;
if (env->isolate_data()->is_building_snapshot()) {
if (!StartExecution(env, "internal/main/mksnapshot").ToLocal(&result)) {
return MaybeLocal<Value>();
}
} else {
if (!StartExecution(env, "internal/main/embedding").ToLocal(&result)) {
return MaybeLocal<Value>();
}
}
auto info = CallbackInfoFromArray(env->context(), result);
if (!info.has_value()) {
MaybeLocal<Value>();
}
#if HAVE_INSPECTOR
if (env->options()->debug_options().break_first_line) {
env->inspector_agent()->PauseOnNextJavascriptStatement("Break on start");
}
#endif
env->performance_state()->Mark(
performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
return scope.EscapeMaybe(cb(info.value()));
}
CHECK(!env->isolate_data()->is_building_snapshot());
#ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION
if (sea::IsSingleExecutable()) {
sea::SeaResource sea = sea::FindSingleExecutableResource();
// The SEA preparation blob building process should already enforce this,
// this check is just here to guard against the unlikely case where
// the SEA preparation blob has been manually modified by someone.
CHECK_IMPLIES(sea.use_snapshot(),
!env->snapshot_deserialize_main().IsEmpty());
}
#endif
// Ignore env file if we're in watch mode.
// Without it env is not updated when restarting child process.
// Child process has --watch flag removed, so it will load the file.
if (env->options()->has_env_file_string && !env->options()->watch_mode) {
per_process::dotenv_file.SetEnvironment(env);
}
// TODO(joyeecheung): move these conditions into JS land and let the
// deserialize main function take precedence. For workers, we need to
// move the pre-execution part into a different file that can be
// reused when dealing with user-defined main functions.
if (!env->snapshot_deserialize_main().IsEmpty()) {
return env->RunSnapshotDeserializeMain();
}
if (env->worker_context() != nullptr) {
return StartExecution(env, "internal/main/worker_thread");
}
std::string first_argv;
if (env->argv().size() > 1) {
first_argv = env->argv()[1];
}
if (first_argv == "inspect") {
return StartExecution(env, "internal/main/inspect");
}
if (per_process::cli_options->print_help) {
return StartExecution(env, "internal/main/print_help");
}
if (env->options()->prof_process) {
return StartExecution(env, "internal/main/prof_process");
}
// -e/--eval without -i/--interactive
if (env->options()->has_eval_string && !env->options()->force_repl) {
return StartExecution(env, "internal/main/eval_string");
}
if (env->options()->syntax_check_only) {
return StartExecution(env, "internal/main/check_syntax");
}
if (env->options()->test_runner) {
return StartExecution(env, "internal/main/test_runner");
}
if (env->options()->watch_mode) {
return StartExecution(env, "internal/main/watch_mode");
}
if (!first_argv.empty() && first_argv != "-") {
return StartExecution(env, "internal/main/run_main_module");
}
if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
return StartExecution(env, "internal/main/repl");
}
return StartExecution(env, "internal/main/eval_stdin");
}
#ifdef __POSIX__
typedef void (*sigaction_cb)(int signo, siginfo_t* info, void* ucontext);
#endif
#if NODE_USE_V8_WASM_TRAP_HANDLER
static std::atomic<bool> is_wasm_trap_handler_configured{false};
#if defined(_WIN32)
static LONG WINAPI TrapWebAssemblyOrContinue(EXCEPTION_POINTERS* exception) {
if (v8::TryHandleWebAssemblyTrapWindows(exception)) {
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
#else
static std::atomic<sigaction_cb> previous_sigsegv_action;
// TODO(align behavior between macos and other in next major version)
#if defined(__APPLE__)
static std::atomic<sigaction_cb> previous_sigbus_action;
#endif // __APPLE__
void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) {
if (!v8::TryHandleWebAssemblyTrapPosix(signo, info, ucontext)) {
#if defined(__APPLE__)
sigaction_cb prev = signo == SIGBUS ? previous_sigbus_action.load()
: previous_sigsegv_action.load();
#else
sigaction_cb prev = previous_sigsegv_action.load();
#endif // __APPLE__
if (prev != nullptr) {
prev(signo, info, ucontext);
} else {
// Reset to the default signal handler, i.e. cause a hard crash.
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_DFL;
CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
ResetStdio();
raise(signo);
}
}
}
#endif // defined(_WIN32)
#endif // NODE_USE_V8_WASM_TRAP_HANDLER
#ifdef __POSIX__
void RegisterSignalHandler(int signal,
sigaction_cb handler,
bool reset_handler) {
CHECK_NOT_NULL(handler);
#if NODE_USE_V8_WASM_TRAP_HANDLER
// Stash the user-registered handlers for TrapWebAssemblyOrContinue
// to call out to when the signal is not coming from a WASM OOM.
if (signal == SIGSEGV && is_wasm_trap_handler_configured.load()) {
CHECK(previous_sigsegv_action.is_lock_free());
CHECK(!reset_handler);
previous_sigsegv_action.store(handler);
return;
}
// TODO(align behavior between macos and other in next major version)
#if defined(__APPLE__)
if (signal == SIGBUS && is_wasm_trap_handler_configured.load()) {
CHECK(previous_sigbus_action.is_lock_free());
CHECK(!reset_handler);
previous_sigbus_action.store(handler);
return;
}
#endif // __APPLE__
#endif // NODE_USE_V8_WASM_TRAP_HANDLER
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = handler;
sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
sigfillset(&sa.sa_mask);
CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
}
#endif // __POSIX__
#ifdef __POSIX__
static struct {
int flags;
bool isatty;
struct stat stat;
struct termios termios;
} stdio[1 + STDERR_FILENO];
#endif // __POSIX__
void ResetSignalHandlers() {
#ifdef __POSIX__
// Restore signal dispositions, the parent process may have changed them.
struct sigaction act;
memset(&act, 0, sizeof(act));
// The hard-coded upper limit is because NSIG is not very reliable; on Linux,
// it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
// Counting up to SIGRTMIN doesn't work for the same reason.
for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
if (nr == SIGKILL || nr == SIGSTOP)
continue;
act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
if (act.sa_handler == SIG_DFL) {
// The only bad handler value we can inherit from before exec is SIG_IGN
// (any actual function pointer is reset to SIG_DFL during exec).
// If that's the case, we want to reset it back to SIG_DFL.
// However, it's also possible that an embeder (or an LD_PRELOAD-ed
// library) has set up own signal handler for own purposes
// (e.g. profiling). If that's the case, we want to keep it intact.
struct sigaction old;
CHECK_EQ(0, sigaction(nr, nullptr, &old));
if ((old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_IGN) continue;
}
CHECK_EQ(0, sigaction(nr, &act, nullptr));
}
#endif // __POSIX__
}
// We use uint32_t since that can be accessed as a lock-free atomic
// variable on all platforms that we support, which we require in
// order for its value to be usable inside signal handlers.
static std::atomic<uint32_t> init_process_flags = 0;
static_assert(
std::is_same_v<std::underlying_type_t<ProcessInitializationFlags::Flags>,
uint32_t>);
static void PlatformInit(ProcessInitializationFlags::Flags flags) {
// init_process_flags is accessed in ResetStdio(),
// which can be called from signal handlers.
CHECK(init_process_flags.is_lock_free());
init_process_flags.store(flags);
if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
atexit(ResetStdio);
}
#ifdef __POSIX__
if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
// Disable stdio buffering, it interacts poorly with printf()
// calls elsewhere in the program (e.g., any logging from V8.)
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
// Make sure file descriptors 0-2 are valid before we start logging
// anything.
for (auto& s : stdio) {
const int fd = &s - stdio;
if (fstat(fd, &s.stat) == 0) continue;
// Anything but EBADF means something is seriously wrong. We don't
// have to special-case EINTR, fstat() is not interruptible.
if (errno != EBADF) ABORT();
// If EBADF (file descriptor doesn't exist), open /dev/null and duplicate
// its file descriptor to the invalid file descriptor. Make sure *that*
// file descriptor is valid. POSIX doesn't guarantee the next file
// descriptor open(2) gives us is the lowest available number anymore in
// POSIX.1-2017, which is why dup2(2) is needed.
int null_fd;
do {
null_fd = open("/dev/null", O_RDWR);
} while (null_fd < 0 && errno == EINTR);
if (null_fd != fd) {
int err;
do {
err = dup2(null_fd, fd);
} while (err < 0 && errno == EINTR);
CHECK_EQ(err, 0);
}
if (fstat(fd, &s.stat) < 0) ABORT();
}
}
if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
#if HAVE_INSPECTOR
sigset_t sigmask;
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGUSR1);
const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
CHECK_EQ(err, 0);
#endif // HAVE_INSPECTOR
ResetSignalHandlers();
}
if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
// Record the state of the stdio file descriptors so we can restore it
// on exit. Needs to happen before installing signal handlers because
// they make use of that information.
for (auto& s : stdio) {
const int fd = &s - stdio;
int err;
do {
s.flags = fcntl(fd, F_GETFL);
} while (s.flags == -1 && errno == EINTR); // NOLINT
CHECK_NE(s.flags, -1);
if (uv_guess_handle(fd) != UV_TTY) continue;
s.isatty = true;
do {
err = tcgetattr(fd, &s.termios);
} while (err == -1 && errno == EINTR); // NOLINT
CHECK_EQ(err, 0);
}
}
if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
RegisterSignalHandler(SIGINT, SignalExit, true);
RegisterSignalHandler(SIGTERM, SignalExit, true);
}
if (!(flags & ProcessInitializationFlags::kNoAdjustResourceLimits)) {
// Raise the open file descriptor limit.
struct rlimit lim;
if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
// Do a binary search for the limit.
rlim_t min = lim.rlim_cur;
rlim_t max = 1 << 20;
// But if there's a defined upper bound, don't search, just set it.
if (lim.rlim_max != RLIM_INFINITY) {
min = lim.rlim_max;
max = lim.rlim_max;
}
do {
lim.rlim_cur = min + (max - min) / 2;
if (setrlimit(RLIMIT_NOFILE, &lim)) {
max = lim.rlim_cur;
} else {
min = lim.rlim_cur;
}
} while (min + 1 < max);
}
}
#endif // __POSIX__
#ifdef _WIN32
if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
for (int fd = 0; fd <= 2; ++fd) {
auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
if (handle == INVALID_HANDLE_VALUE ||
GetFileType(handle) == FILE_TYPE_UNKNOWN) {
// Ignore _close result. If it fails or not depends on used Windows
// version. We will just check _open result.
_close(fd);
if (fd != _open("nul", _O_RDWR)) ABORT();
}
}
}
#endif // _WIN32
}
// Safe to call more than once and from signal handlers.
void ResetStdio() {
if (init_process_flags.load() &
ProcessInitializationFlags::kNoStdioInitialization) {
return;
}
uv_tty_reset_mode();
#ifdef __POSIX__
for (auto& s : stdio) {
const int fd = &s - stdio;
struct stat tmp;
if (-1 == fstat(fd, &tmp)) {
CHECK_EQ(errno, EBADF); // Program closed file descriptor.
continue;
}
bool is_same_file =
(s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
if (!is_same_file) continue; // Program reopened file descriptor.
int flags;
do
flags = fcntl(fd, F_GETFL);
while (flags == -1 && errno == EINTR); // NOLINT
CHECK_NE(flags, -1);
// Restore the O_NONBLOCK flag if it changed.
if (O_NONBLOCK & (flags ^ s.flags)) {
flags &= ~O_NONBLOCK;
flags |= s.flags & O_NONBLOCK;
int err;
do
err = fcntl(fd, F_SETFL, flags);
while (err == -1 && errno == EINTR); // NOLINT
CHECK_NE(err, -1);
}
if (s.isatty) {
sigset_t sa;
int err;
// We might be a background job that doesn't own the TTY so block SIGTTOU
// before making the tcsetattr() call, otherwise that signal suspends us.
sigemptyset(&sa);
sigaddset(&sa, SIGTTOU);
CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
do
err = tcsetattr(fd, TCSANOW, &s.termios);
while (err == -1 && errno == EINTR); // NOLINT
CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
// Normally we expect err == 0. But if macOS App Sandbox is enabled,
// tcsetattr will fail with err == -1 and errno == EPERM.
CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
}
}
#endif // __POSIX__
}
static ExitCode ProcessGlobalArgsInternal(std::vector<std::string>* args,
std::vector<std::string>* exec_args,
std::vector<std::string>* errors,
OptionEnvvarSettings settings) {
// Parse a few arguments which are specific to Node.
std::vector<std::string> v8_args;
Mutex::ScopedLock lock(per_process::cli_options_mutex);
options_parser::Parse(
args,
exec_args,
&v8_args,
per_process::cli_options.get(),
settings,
errors);
if (!errors->empty()) return ExitCode::kInvalidCommandLineArgument;
std::string revert_error;
for (const std::string& cve : per_process::cli_options->security_reverts) {
Revert(cve.c_str(), &revert_error);
if (!revert_error.empty()) {
errors->emplace_back(std::move(revert_error));
// TODO(joyeecheung): merge into kInvalidCommandLineArgument.
return ExitCode::kInvalidCommandLineArgument2;
}
}
if (per_process::cli_options->disable_proto != "delete" &&
per_process::cli_options->disable_proto != "throw" &&
per_process::cli_options->disable_proto != "") {
errors->emplace_back("invalid mode passed to --disable-proto");
// TODO(joyeecheung): merge into kInvalidCommandLineArgument.
return ExitCode::kInvalidCommandLineArgument2;
}
// TODO(aduh95): remove this when the harmony-import-attributes flag
// is removed in V8.
if (std::find(v8_args.begin(),
v8_args.end(),
"--no-harmony-import-attributes") == v8_args.end()) {
v8_args.emplace_back("--harmony-import-attributes");
}
auto env_opts = per_process::cli_options->per_isolate->per_env;
if (std::find(v8_args.begin(), v8_args.end(),
"--abort-on-uncaught-exception") != v8_args.end() ||
std::find(v8_args.begin(), v8_args.end(),
"--abort_on_uncaught_exception") != v8_args.end()) {
env_opts->abort_on_uncaught_exception = true;
}
#ifdef __POSIX__
// Block SIGPROF signals when sleeping in epoll_wait/kevent/etc. Avoids the
// performance penalty of frequent EINTR wakeups when the profiler is running.
// Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
}
#endif
std::vector<char*> v8_args_as_char_ptr(v8_args.size());
if (v8_args.size() > 0) {
for (size_t i = 0; i < v8_args.size(); ++i)
v8_args_as_char_ptr[i] = v8_args[i].data();
int argc = v8_args.size();
V8::SetFlagsFromCommandLine(&argc, v8_args_as_char_ptr.data(), true);
v8_args_as_char_ptr.resize(argc);
}
// Anything that's still in v8_argv is not a V8 or a node option.
for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
if (v8_args_as_char_ptr.size() > 1)
return ExitCode::kInvalidCommandLineArgument;
return ExitCode::kNoFailure;
}
int ProcessGlobalArgs(std::vector<std::string>* args,
std::vector<std::string>* exec_args,
std::vector<std::string>* errors,
OptionEnvvarSettings settings) {
return static_cast<int>(
ProcessGlobalArgsInternal(args, exec_args, errors, settings));
}
static std::atomic_bool init_called{false};
// TODO(addaleax): Turn this into a wrapper around InitializeOncePerProcess()
// (with the corresponding additional flags set), then eventually remove this.
static ExitCode InitializeNodeWithArgsInternal(
std::vector<std::string>* argv,
std::vector<std::string>* exec_argv,
std::vector<std::string>* errors,
ProcessInitializationFlags::Flags flags) {
// Make sure InitializeNodeWithArgs() is called only once.
CHECK(!init_called.exchange(true));
// Initialize node_start_time to get relative uptime.
per_process::node_start_time = uv_hrtime();
// Register built-in bindings
binding::RegisterBuiltinBindings();
// Make inherited handles noninheritable.
if (!(flags & ProcessInitializationFlags::kEnableStdioInheritance) &&
!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
uv_disable_stdio_inheritance();
}
// Cache the original command line to be
// used in diagnostic reports.
per_process::cli_options->cmdline = *argv;
// Node provides a "v8.setFlagsFromString" method to dynamically change flags.
// Hence do not freeze flags when initializing V8. In a browser setting, this
// is security relevant, for Node it's less important.
V8::SetFlagsFromString("--no-freeze-flags-after-init");
#if defined(NODE_V8_OPTIONS)
// Should come before the call to V8::SetFlagsFromCommandLine()
// so the user can disable a flag --foo at run-time by passing
// --no_foo from the command line.
V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
#endif
if (!!(flags & ProcessInitializationFlags::kGeneratePredictableSnapshot) ||
per_process::cli_options->per_isolate->build_snapshot) {
v8::V8::SetFlagsFromString("--predictable");
v8::V8::SetFlagsFromString("--random_seed=42");
}
// Specify this explicitly to avoid being affected by V8 changes to the
// default value.
V8::SetFlagsFromString("--rehash-snapshot");
HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
std::string node_options;
auto env_files = node::Dotenv::GetDataFromArgs(*argv);
if (!env_files.empty()) {
CHECK(!per_process::v8_initialized);
for (const auto& file_data : env_files) {
switch (per_process::dotenv_file.ParsePath(file_data.path)) {
case Dotenv::ParseResult::Valid:
break;
case Dotenv::ParseResult::InvalidContent:
errors->push_back(file_data.path + ": invalid format");
break;
case Dotenv::ParseResult::FileError:
if (file_data.is_optional) {
fprintf(stderr,
"%s not found. Continuing without it.\n",
file_data.path.c_str());
continue;
}
errors->push_back(file_data.path + ": not found");
break;
default:
UNREACHABLE();
}
}
per_process::dotenv_file.AssignNodeOptionsIfAvailable(&node_options);
}
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
if (!(flags & ProcessInitializationFlags::kDisableNodeOptionsEnv)) {
// NODE_OPTIONS environment variable is preferred over the file one.
if (credentials::SafeGetenv("NODE_OPTIONS", &node_options) ||
!node_options.empty()) {
std::vector<std::string> env_argv =
ParseNodeOptionsEnvVar(node_options, errors);
if (!errors->empty()) return ExitCode::kInvalidCommandLineArgument;
// [0] is expected to be the program name, fill it in from the real argv.
env_argv.insert(env_argv.begin(), argv->at(0));
const ExitCode exit_code = ProcessGlobalArgsInternal(
&env_argv, nullptr, errors, kAllowedInEnvvar);
if (exit_code != ExitCode::kNoFailure) return exit_code;
}
} else {
std::string node_repl_external_env = {};
if (credentials::SafeGetenv("NODE_REPL_EXTERNAL_MODULE",
&node_repl_external_env) ||
!node_repl_external_env.empty()) {
errors->emplace_back("NODE_REPL_EXTERNAL_MODULE can't be used with "
"kDisableNodeOptionsEnv");
return ExitCode::kInvalidCommandLineArgument;
}
}
#endif
if (!(flags & ProcessInitializationFlags::kDisableCLIOptions)) {
const ExitCode exit_code =
ProcessGlobalArgsInternal(argv, exec_argv, errors, kDisallowedInEnvvar);
if (exit_code != ExitCode::kNoFailure) return exit_code;
}
// Set the process.title immediately after processing argv if --title is set.
if (!per_process::cli_options->title.empty())
uv_set_process_title(per_process::cli_options->title.c_str());
#if defined(NODE_HAVE_I18N_SUPPORT)
if (!(flags & ProcessInitializationFlags::kNoICU)) {
// If the parameter isn't given, use the env variable.
if (per_process::cli_options->icu_data_dir.empty())
credentials::SafeGetenv("NODE_ICU_DATA",
&per_process::cli_options->icu_data_dir);
#ifdef NODE_ICU_DEFAULT_DATA_DIR
// If neither the CLI option nor the environment variable was specified,
// fall back to the configured default
if (per_process::cli_options->icu_data_dir.empty()) {
// Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
// file and can be read.
static const char full_path[] =
NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
FILE* f = fopen(full_path, "rb");
if (f != nullptr) {
fclose(f);
per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
}
}
#endif // NODE_ICU_DEFAULT_DATA_DIR
// Initialize ICU.
// If icu_data_dir is empty here, it will load the 'minimal' data.
std::string icu_error;
if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir,
&icu_error)) {
errors->push_back(icu_error +
": Could not initialize ICU. "
"Check the directory specified by NODE_ICU_DATA or "
"--icu-data-dir contains " U_ICUDATA_NAME ".dat and "
"it's readable\n");
return ExitCode::kInvalidCommandLineArgument;
}
per_process::metadata.versions.InitializeIntlVersions();
}
# ifndef __POSIX__
std::string tz;
if (credentials::SafeGetenv("TZ", &tz) && !tz.empty()) {
i18n::SetDefaultTimeZone(tz.c_str());
}
# endif
#endif // defined(NODE_HAVE_I18N_SUPPORT)
// We should set node_is_initialized here instead of in node::Start,
// otherwise embedders using node::Init to initialize everything will not be
// able to set it and native addons will not load for them.
node_is_initialized = true;
return ExitCode::kNoFailure;
}
int InitializeNodeWithArgs(std::vector<std::string>* argv,
std::vector<std::string>* exec_argv,
std::vector<std::string>* errors,
ProcessInitializationFlags::Flags flags) {
return static_cast<int>(
InitializeNodeWithArgsInternal(argv, exec_argv, errors, flags));
}
static std::shared_ptr<InitializationResultImpl>
InitializeOncePerProcessInternal(const std::vector<std::string>& args,
ProcessInitializationFlags::Flags flags =
ProcessInitializationFlags::kNoFlags) {
auto result = std::make_shared<InitializationResultImpl>();
result->args_ = args;
if (!(flags & ProcessInitializationFlags::kNoParseGlobalDebugVariables)) {
// Initialized the enabled list for Debug() calls with system
// environment variables.
per_process::enabled_debug_list.Parse(nullptr);
}
PlatformInit(flags);