1 #include "node_options.h" // NOLINT(build/include_inline)
2 #include "node_options-inl.h"
3
4 #include "env-inl.h"
5 #include "node_binding.h"
6 #include "node_external_reference.h"
7 #include "node_internals.h"
8 #include "node_sea.h"
9 #if HAVE_OPENSSL
10 #include "openssl/opensslv.h"
11 #endif
12
13 #include <errno.h>
14 #include <algorithm>
15 #include <cstdlib> // strtoul, errno
16 #include <limits>
17 #include <sstream>
18 #include <string_view>
19
20 using v8::Boolean;
21 using v8::Context;
22 using v8::FunctionCallbackInfo;
23 using v8::Integer;
24 using v8::Isolate;
25 using v8::Local;
26 using v8::Map;
27 using v8::Number;
28 using v8::Object;
29 using v8::Undefined;
30 using v8::Value;
31
32 namespace node {
33
34 namespace per_process {
35 Mutex cli_options_mutex;
36 std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
37 } // namespace per_process
38
CheckOptions(std::vector<std::string> * errors,std::vector<std::string> * argv)39 void DebugOptions::CheckOptions(std::vector<std::string>* errors,
40 std::vector<std::string>* argv) {
41 #if !NODE_USE_V8_PLATFORM && !HAVE_INSPECTOR
42 if (inspector_enabled) {
43 errors->push_back("Inspector is not available when Node is compiled "
44 "--without-v8-platform and --without-inspector.");
45 }
46 #endif
47
48 if (deprecated_debug) {
49 errors->push_back("[DEP0062]: `node --debug` and `node --debug-brk` "
50 "are invalid. Please use `node --inspect` and "
51 "`node --inspect-brk` instead.");
52 }
53
54 using std::string_view_literals::operator""sv;
55 const std::vector<std::string_view> destinations =
56 SplitString(inspect_publish_uid_string, ","sv);
57 inspect_publish_uid.console = false;
58 inspect_publish_uid.http = false;
59 for (const std::string_view destination : destinations) {
60 if (destination == "stderr"sv) {
61 inspect_publish_uid.console = true;
62 } else if (destination == "http"sv) {
63 inspect_publish_uid.http = true;
64 } else {
65 errors->push_back("--inspect-publish-uid destination can be "
66 "stderr or http");
67 }
68 }
69 }
70
CheckOptions(std::vector<std::string> * errors,std::vector<std::string> * argv)71 void PerProcessOptions::CheckOptions(std::vector<std::string>* errors,
72 std::vector<std::string>* argv) {
73 #if HAVE_OPENSSL
74 if (use_openssl_ca && use_bundled_ca) {
75 errors->push_back("either --use-openssl-ca or --use-bundled-ca can be "
76 "used, not both");
77 }
78
79 // Any value less than 2 disables use of the secure heap.
80 if (secure_heap >= 2) {
81 if ((secure_heap & (secure_heap - 1)) != 0)
82 errors->push_back("--secure-heap must be a power of 2");
83 secure_heap_min =
84 std::min({
85 secure_heap,
86 secure_heap_min,
87 static_cast<int64_t>(std::numeric_limits<int>::max())});
88 secure_heap_min = std::max(static_cast<int64_t>(2), secure_heap_min);
89 if ((secure_heap_min & (secure_heap_min - 1)) != 0)
90 errors->push_back("--secure-heap-min must be a power of 2");
91 }
92 #endif // HAVE_OPENSSL
93
94 if (use_largepages != "off" &&
95 use_largepages != "on" &&
96 use_largepages != "silent") {
97 errors->push_back("invalid value for --use-largepages");
98 }
99 per_isolate->CheckOptions(errors, argv);
100 }
101
CheckOptions(std::vector<std::string> * errors,std::vector<std::string> * argv)102 void PerIsolateOptions::CheckOptions(std::vector<std::string>* errors,
103 std::vector<std::string>* argv) {
104 per_env->CheckOptions(errors, argv);
105 }
106
CheckOptions(std::vector<std::string> * errors,std::vector<std::string> * argv)107 void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors,
108 std::vector<std::string>* argv) {
109 if (has_policy_integrity_string && experimental_policy.empty()) {
110 errors->push_back("--policy-integrity requires "
111 "--experimental-policy be enabled");
112 }
113 if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
114 errors->push_back("--policy-integrity cannot be empty");
115 }
116
117 if (!module_type.empty()) {
118 if (module_type != "commonjs" && module_type != "module") {
119 errors->push_back("--input-type must be \"module\" or \"commonjs\"");
120 }
121 }
122
123 if (!experimental_specifier_resolution.empty()) {
124 if (experimental_specifier_resolution != "node" &&
125 experimental_specifier_resolution != "explicit") {
126 errors->push_back(
127 "invalid value for --experimental-specifier-resolution");
128 }
129 }
130
131 if (syntax_check_only && has_eval_string) {
132 errors->push_back("either --check or --eval can be used, not both");
133 }
134
135 if (!unhandled_rejections.empty() &&
136 unhandled_rejections != "warn-with-error-code" &&
137 unhandled_rejections != "throw" &&
138 unhandled_rejections != "strict" &&
139 unhandled_rejections != "warn" &&
140 unhandled_rejections != "none") {
141 errors->push_back("invalid value for --unhandled-rejections");
142 }
143
144 if (tls_min_v1_3 && tls_max_v1_2) {
145 errors->push_back("either --tls-min-v1.3 or --tls-max-v1.2 can be "
146 "used, not both");
147 }
148
149 if (heap_snapshot_near_heap_limit < 0) {
150 errors->push_back("--heapsnapshot-near-heap-limit must not be negative");
151 }
152
153 if (test_runner) {
154 if (syntax_check_only) {
155 errors->push_back("either --test or --check can be used, not both");
156 }
157
158 if (has_eval_string) {
159 errors->push_back("either --test or --eval can be used, not both");
160 }
161
162 if (force_repl) {
163 errors->push_back("either --test or --interactive can be used, not both");
164 }
165
166 if (watch_mode_paths.size() > 0) {
167 errors->push_back(
168 "--watch-path cannot be used in combination with --test");
169 }
170
171 #ifndef ALLOW_ATTACHING_DEBUGGER_IN_TEST_RUNNER
172 debug_options_.allow_attaching_debugger = false;
173 #endif
174 }
175
176 if (watch_mode) {
177 if (syntax_check_only) {
178 errors->push_back("either --watch or --check can be used, not both");
179 } else if (has_eval_string) {
180 errors->push_back("either --watch or --eval can be used, not both");
181 } else if (force_repl) {
182 errors->push_back("either --watch or --interactive "
183 "can be used, not both");
184 } else if (argv->size() < 1 || (*argv)[1].empty()) {
185 errors->push_back("--watch requires specifying a file");
186 }
187
188 #ifndef ALLOW_ATTACHING_DEBUGGER_IN_WATCH_MODE
189 debug_options_.allow_attaching_debugger = false;
190 #endif
191 }
192
193 #if HAVE_INSPECTOR
194 if (!cpu_prof) {
195 if (!cpu_prof_name.empty()) {
196 errors->push_back("--cpu-prof-name must be used with --cpu-prof");
197 }
198 if (!cpu_prof_dir.empty()) {
199 errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
200 }
201 // We can't catch the case where the value passed is the default value,
202 // then the option just becomes a noop which is fine.
203 if (cpu_prof_interval != kDefaultCpuProfInterval) {
204 errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
205 }
206 }
207
208 if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
209 cpu_prof_dir = diagnostic_dir;
210 }
211
212 if (!heap_prof) {
213 if (!heap_prof_name.empty()) {
214 errors->push_back("--heap-prof-name must be used with --heap-prof");
215 }
216 if (!heap_prof_dir.empty()) {
217 errors->push_back("--heap-prof-dir must be used with --heap-prof");
218 }
219 // We can't catch the case where the value passed is the default value,
220 // then the option just becomes a noop which is fine.
221 if (heap_prof_interval != kDefaultHeapProfInterval) {
222 errors->push_back("--heap-prof-interval must be used with --heap-prof");
223 }
224 }
225
226 if (heap_prof && heap_prof_dir.empty() && !diagnostic_dir.empty()) {
227 heap_prof_dir = diagnostic_dir;
228 }
229
230 debug_options_.CheckOptions(errors, argv);
231 #endif // HAVE_INSPECTOR
232 }
233
234 namespace options_parser {
235
236 class DebugOptionsParser : public OptionsParser<DebugOptions> {
237 public:
238 DebugOptionsParser();
239 };
240
241 class EnvironmentOptionsParser : public OptionsParser<EnvironmentOptions> {
242 public:
243 EnvironmentOptionsParser();
EnvironmentOptionsParser(const DebugOptionsParser & dop)244 explicit EnvironmentOptionsParser(const DebugOptionsParser& dop)
245 : EnvironmentOptionsParser() {
246 Insert(dop, &EnvironmentOptions::get_debug_options);
247 }
248 };
249
250 class PerIsolateOptionsParser : public OptionsParser<PerIsolateOptions> {
251 public:
252 PerIsolateOptionsParser() = delete;
253 explicit PerIsolateOptionsParser(const EnvironmentOptionsParser& eop);
254 };
255
256 class PerProcessOptionsParser : public OptionsParser<PerProcessOptions> {
257 public:
258 PerProcessOptionsParser() = delete;
259 explicit PerProcessOptionsParser(const PerIsolateOptionsParser& iop);
260 };
261
262 #if HAVE_INSPECTOR
263 const DebugOptionsParser _dop_instance{};
264 const EnvironmentOptionsParser _eop_instance{_dop_instance};
265
266 // This Parse is not dead code. It is used by embedders (e.g., Electron).
267 template <>
Parse(StringVector * const args,StringVector * const exec_args,StringVector * const v8_args,DebugOptions * const options,OptionEnvvarSettings required_env_settings,StringVector * const errors)268 void Parse(
269 StringVector* const args, StringVector* const exec_args,
270 StringVector* const v8_args,
271 DebugOptions* const options,
272 OptionEnvvarSettings required_env_settings, StringVector* const errors) {
273 _dop_instance.Parse(
274 args, exec_args, v8_args, options, required_env_settings, errors);
275 }
276 #else
277 const EnvironmentOptionsParser _eop_instance{};
278 #endif // HAVE_INSPECTOR
279 const PerIsolateOptionsParser _piop_instance{_eop_instance};
280 const PerProcessOptionsParser _ppop_instance{_piop_instance};
281
282 template <>
Parse(StringVector * const args,StringVector * const exec_args,StringVector * const v8_args,PerIsolateOptions * const options,OptionEnvvarSettings required_env_settings,StringVector * const errors)283 void Parse(
284 StringVector* const args, StringVector* const exec_args,
285 StringVector* const v8_args,
286 PerIsolateOptions* const options,
287 OptionEnvvarSettings required_env_settings, StringVector* const errors) {
288 _piop_instance.Parse(
289 args, exec_args, v8_args, options, required_env_settings, errors);
290 }
291
292 template <>
Parse(StringVector * const args,StringVector * const exec_args,StringVector * const v8_args,PerProcessOptions * const options,OptionEnvvarSettings required_env_settings,StringVector * const errors)293 void Parse(
294 StringVector* const args, StringVector* const exec_args,
295 StringVector* const v8_args,
296 PerProcessOptions* const options,
297 OptionEnvvarSettings required_env_settings, StringVector* const errors) {
298 _ppop_instance.Parse(
299 args, exec_args, v8_args, options, required_env_settings, errors);
300 }
301
302 // XXX: If you add an option here, please also add it to doc/node.1 and
303 // doc/api/cli.md
304 // TODO(addaleax): Make that unnecessary.
305
DebugOptionsParser()306 DebugOptionsParser::DebugOptionsParser() {
307 #ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION
308 if (sea::IsSingleExecutable()) return;
309 #endif
310
311 AddOption("--inspect-port",
312 "set host:port for inspector",
313 &DebugOptions::host_port,
314 kAllowedInEnvvar);
315 AddAlias("--debug-port", "--inspect-port");
316
317 AddOption("--inspect",
318 "activate inspector on host:port (default: 127.0.0.1:9229)",
319 &DebugOptions::inspector_enabled,
320 kAllowedInEnvvar);
321 AddAlias("--inspect=", { "--inspect-port", "--inspect" });
322
323 AddOption("--debug", "", &DebugOptions::deprecated_debug);
324 AddAlias("--debug=", "--debug");
325 AddOption("--debug-brk", "", &DebugOptions::deprecated_debug);
326 AddAlias("--debug-brk=", "--debug-brk");
327
328 AddOption("--inspect-brk",
329 "activate inspector on host:port and break at start of user script",
330 &DebugOptions::break_first_line,
331 kAllowedInEnvvar);
332 Implies("--inspect-brk", "--inspect");
333 AddAlias("--inspect-brk=", { "--inspect-port", "--inspect-brk" });
334
335 AddOption("--inspect-brk-node", "", &DebugOptions::break_node_first_line);
336 Implies("--inspect-brk-node", "--inspect");
337 AddAlias("--inspect-brk-node=", { "--inspect-port", "--inspect-brk-node" });
338
339 AddOption("--inspect-publish-uid",
340 "comma separated list of destinations for inspector uid"
341 "(default: stderr,http)",
342 &DebugOptions::inspect_publish_uid_string,
343 kAllowedInEnvvar);
344 }
345
EnvironmentOptionsParser()346 EnvironmentOptionsParser::EnvironmentOptionsParser() {
347 AddOption("--conditions",
348 "additional user conditions for conditional exports and imports",
349 &EnvironmentOptions::conditions,
350 kAllowedInEnvvar);
351 AddAlias("-C", "--conditions");
352 AddOption("--diagnostic-dir",
353 "set dir for all output files"
354 " (default: current working directory)",
355 &EnvironmentOptions::diagnostic_dir,
356 kAllowedInEnvvar);
357 AddOption("--dns-result-order",
358 "set default value of verbatim in dns.lookup. Options are "
359 "'ipv4first' (IPv4 addresses are placed before IPv6 addresses) "
360 "'verbatim' (addresses are in the order the DNS resolver "
361 "returned)",
362 &EnvironmentOptions::dns_result_order,
363 kAllowedInEnvvar);
364 AddOption("--enable-network-family-autoselection",
365 "Enable network address family autodetection algorithm",
366 &EnvironmentOptions::enable_network_family_autoselection,
367 kAllowedInEnvvar);
368 AddOption("--enable-source-maps",
369 "Source Map V3 support for stack traces",
370 &EnvironmentOptions::enable_source_maps,
371 kAllowedInEnvvar);
372 AddOption("--experimental-abortcontroller", "", NoOp{}, kAllowedInEnvvar);
373 AddOption("--experimental-fetch",
374 "experimental Fetch API",
375 &EnvironmentOptions::experimental_fetch,
376 kAllowedInEnvvar,
377 true);
378 AddOption("--experimental-global-customevent",
379 "expose experimental CustomEvent on the global scope",
380 &EnvironmentOptions::experimental_global_customevent,
381 kAllowedInEnvvar);
382 AddOption("--experimental-global-webcrypto",
383 "expose experimental Web Crypto API on the global scope",
384 &EnvironmentOptions::experimental_global_web_crypto,
385 kAllowedInEnvvar);
386 AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvvar);
387 AddOption("--experimental-loader",
388 "use the specified module as a custom loader",
389 &EnvironmentOptions::userland_loaders,
390 kAllowedInEnvvar);
391 AddAlias("--loader", "--experimental-loader");
392 AddOption("--experimental-modules", "", NoOp{}, kAllowedInEnvvar);
393 AddOption("--experimental-network-imports",
394 "experimental https: support for the ES Module loader",
395 &EnvironmentOptions::experimental_https_modules,
396 kAllowedInEnvvar);
397 AddOption("--experimental-wasm-modules",
398 "experimental ES Module support for webassembly modules",
399 &EnvironmentOptions::experimental_wasm_modules,
400 kAllowedInEnvvar);
401 AddOption("--experimental-import-meta-resolve",
402 "experimental ES Module import.meta.resolve() support",
403 &EnvironmentOptions::experimental_import_meta_resolve,
404 kAllowedInEnvvar);
405 AddOption("--experimental-policy",
406 "use the specified file as a "
407 "security policy",
408 &EnvironmentOptions::experimental_policy,
409 kAllowedInEnvvar);
410 AddOption("[has_policy_integrity_string]",
411 "",
412 &EnvironmentOptions::has_policy_integrity_string);
413 AddOption("--policy-integrity",
414 "ensure the security policy contents match "
415 "the specified integrity",
416 &EnvironmentOptions::experimental_policy_integrity,
417 kAllowedInEnvvar);
418 Implies("--policy-integrity", "[has_policy_integrity_string]");
419 AddOption("--experimental-repl-await",
420 "experimental await keyword support in REPL",
421 &EnvironmentOptions::experimental_repl_await,
422 kAllowedInEnvvar,
423 true);
424 AddOption("--experimental-vm-modules",
425 "experimental ES Module support in vm module",
426 &EnvironmentOptions::experimental_vm_modules,
427 kAllowedInEnvvar);
428 AddOption("--experimental-worker", "", NoOp{}, kAllowedInEnvvar);
429 AddOption("--experimental-report", "", NoOp{}, kAllowedInEnvvar);
430 AddOption(
431 "--experimental-wasi-unstable-preview1", "", NoOp{}, kAllowedInEnvvar);
432 AddOption("--expose-internals", "", &EnvironmentOptions::expose_internals);
433 AddOption("--frozen-intrinsics",
434 "experimental frozen intrinsics support",
435 &EnvironmentOptions::frozen_intrinsics,
436 kAllowedInEnvvar);
437 AddOption("--heapsnapshot-signal",
438 "Generate heap snapshot on specified signal",
439 &EnvironmentOptions::heap_snapshot_signal,
440 kAllowedInEnvvar);
441 AddOption("--heapsnapshot-near-heap-limit",
442 "Generate heap snapshots whenever V8 is approaching "
443 "the heap limit. No more than the specified number of "
444 "heap snapshots will be generated.",
445 &EnvironmentOptions::heap_snapshot_near_heap_limit,
446 kAllowedInEnvvar);
447 AddOption("--http-parser", "", NoOp{}, kAllowedInEnvvar);
448 AddOption("--insecure-http-parser",
449 "use an insecure HTTP parser that accepts invalid HTTP headers",
450 &EnvironmentOptions::insecure_http_parser,
451 kAllowedInEnvvar);
452 AddOption("--input-type",
453 "set module type for string input",
454 &EnvironmentOptions::module_type,
455 kAllowedInEnvvar);
456 AddOption("--experimental-specifier-resolution",
457 "Select extension resolution algorithm for es modules; "
458 "either 'explicit' (default) or 'node'",
459 &EnvironmentOptions::experimental_specifier_resolution,
460 kAllowedInEnvvar);
461 AddAlias("--es-module-specifier-resolution",
462 "--experimental-specifier-resolution");
463 AddOption("--deprecation",
464 "silence deprecation warnings",
465 &EnvironmentOptions::deprecation,
466 kAllowedInEnvvar,
467 true);
468 AddOption("--force-async-hooks-checks",
469 "disable checks for async_hooks",
470 &EnvironmentOptions::force_async_hooks_checks,
471 kAllowedInEnvvar,
472 true);
473 AddOption(
474 "--force-node-api-uncaught-exceptions-policy",
475 "enforces 'uncaughtException' event on Node API asynchronous callbacks",
476 &EnvironmentOptions::force_node_api_uncaught_exceptions_policy,
477 kAllowedInEnvvar,
478 false);
479 AddOption("--addons",
480 "disable loading native addons",
481 &EnvironmentOptions::allow_native_addons,
482 kAllowedInEnvvar,
483 true);
484 AddOption("--global-search-paths",
485 "disable global module search paths",
486 &EnvironmentOptions::global_search_paths,
487 kAllowedInEnvvar,
488 true);
489 AddOption("--warnings",
490 "silence all process warnings",
491 &EnvironmentOptions::warnings,
492 kAllowedInEnvvar,
493 true);
494 AddOption("--force-context-aware",
495 "disable loading non-context-aware addons",
496 &EnvironmentOptions::force_context_aware,
497 kAllowedInEnvvar);
498 AddOption("--pending-deprecation",
499 "emit pending deprecation warnings",
500 &EnvironmentOptions::pending_deprecation,
501 kAllowedInEnvvar);
502 AddOption("--preserve-symlinks",
503 "preserve symbolic links when resolving",
504 &EnvironmentOptions::preserve_symlinks,
505 kAllowedInEnvvar);
506 AddOption("--preserve-symlinks-main",
507 "preserve symbolic links when resolving the main module",
508 &EnvironmentOptions::preserve_symlinks_main,
509 kAllowedInEnvvar);
510 AddOption("--prof",
511 "Generate V8 profiler output.",
512 V8Option{});
513 AddOption("--prof-process",
514 "process V8 profiler output generated using --prof",
515 &EnvironmentOptions::prof_process);
516 // Options after --prof-process are passed through to the prof processor.
517 AddAlias("--prof-process", { "--prof-process", "--" });
518 #if HAVE_INSPECTOR
519 AddOption("--cpu-prof",
520 "Start the V8 CPU profiler on start up, and write the CPU profile "
521 "to disk before exit. If --cpu-prof-dir is not specified, write "
522 "the profile to the current working directory.",
523 &EnvironmentOptions::cpu_prof);
524 AddOption("--cpu-prof-name",
525 "specified file name of the V8 CPU profile generated with "
526 "--cpu-prof",
527 &EnvironmentOptions::cpu_prof_name);
528 AddOption("--cpu-prof-interval",
529 "specified sampling interval in microseconds for the V8 CPU "
530 "profile generated with --cpu-prof. (default: 1000)",
531 &EnvironmentOptions::cpu_prof_interval);
532 AddOption("--cpu-prof-dir",
533 "Directory where the V8 profiles generated by --cpu-prof will be "
534 "placed. Does not affect --prof.",
535 &EnvironmentOptions::cpu_prof_dir);
536 AddOption(
537 "--heap-prof",
538 "Start the V8 heap profiler on start up, and write the heap profile "
539 "to disk before exit. If --heap-prof-dir is not specified, write "
540 "the profile to the current working directory.",
541 &EnvironmentOptions::heap_prof);
542 AddOption("--heap-prof-name",
543 "specified file name of the V8 heap profile generated with "
544 "--heap-prof",
545 &EnvironmentOptions::heap_prof_name);
546 AddOption("--heap-prof-dir",
547 "Directory where the V8 heap profiles generated by --heap-prof "
548 "will be placed.",
549 &EnvironmentOptions::heap_prof_dir);
550 AddOption("--heap-prof-interval",
551 "specified sampling interval in bytes for the V8 heap "
552 "profile generated with --heap-prof. (default: 512 * 1024)",
553 &EnvironmentOptions::heap_prof_interval);
554 #endif // HAVE_INSPECTOR
555 AddOption("--max-http-header-size",
556 "set the maximum size of HTTP headers (default: 16384 (16KB))",
557 &EnvironmentOptions::max_http_header_size,
558 kAllowedInEnvvar);
559 AddOption("--redirect-warnings",
560 "write warnings to file instead of stderr",
561 &EnvironmentOptions::redirect_warnings,
562 kAllowedInEnvvar);
563 AddOption("--test",
564 "launch test runner on startup",
565 &EnvironmentOptions::test_runner);
566 AddOption("--experimental-test-coverage",
567 "enable code coverage in the test runner",
568 &EnvironmentOptions::test_runner_coverage);
569 AddOption("--test-name-pattern",
570 "run tests whose name matches this regular expression",
571 &EnvironmentOptions::test_name_pattern);
572 AddOption("--test-reporter",
573 "report test output using the given reporter",
574 &EnvironmentOptions::test_reporter,
575 kAllowedInEnvvar);
576 AddOption("--test-reporter-destination",
577 "report given reporter to the given destination",
578 &EnvironmentOptions::test_reporter_destination,
579 kAllowedInEnvvar);
580 AddOption("--test-only",
581 "run tests with 'only' option set",
582 &EnvironmentOptions::test_only,
583 kAllowedInEnvvar);
584 AddOption("--test-udp-no-try-send", "", // For testing only.
585 &EnvironmentOptions::test_udp_no_try_send);
586 AddOption("--throw-deprecation",
587 "throw an exception on deprecations",
588 &EnvironmentOptions::throw_deprecation,
589 kAllowedInEnvvar);
590 AddOption("--trace-atomics-wait",
591 "(deprecated) trace Atomics.wait() operations",
592 &EnvironmentOptions::trace_atomics_wait,
593 kAllowedInEnvvar);
594 AddOption("--trace-deprecation",
595 "show stack traces on deprecations",
596 &EnvironmentOptions::trace_deprecation,
597 kAllowedInEnvvar);
598 AddOption("--trace-exit",
599 "show stack trace when an environment exits",
600 &EnvironmentOptions::trace_exit,
601 kAllowedInEnvvar);
602 AddOption("--trace-sync-io",
603 "show stack trace when use of sync IO is detected after the "
604 "first tick",
605 &EnvironmentOptions::trace_sync_io,
606 kAllowedInEnvvar);
607 AddOption("--trace-tls",
608 "prints TLS packet trace information to stderr",
609 &EnvironmentOptions::trace_tls,
610 kAllowedInEnvvar);
611 AddOption("--trace-uncaught",
612 "show stack traces for the `throw` behind uncaught exceptions",
613 &EnvironmentOptions::trace_uncaught,
614 kAllowedInEnvvar);
615 AddOption("--trace-warnings",
616 "show stack traces on process warnings",
617 &EnvironmentOptions::trace_warnings,
618 kAllowedInEnvvar);
619 AddOption("--extra-info-on-fatal-exception",
620 "hide extra information on fatal exception that causes exit",
621 &EnvironmentOptions::extra_info_on_fatal_exception,
622 kAllowedInEnvvar,
623 true);
624 AddOption("--unhandled-rejections",
625 "define unhandled rejections behavior. Options are 'strict' "
626 "(always raise an error), 'throw' (raise an error unless "
627 "'unhandledRejection' hook is set), 'warn' (log a warning), 'none' "
628 "(silence warnings), 'warn-with-error-code' (log a warning and set "
629 "exit code 1 unless 'unhandledRejection' hook is set). (default: "
630 "throw)",
631 &EnvironmentOptions::unhandled_rejections,
632 kAllowedInEnvvar);
633 AddOption("--verify-base-objects",
634 "", /* undocumented, only for debugging */
635 &EnvironmentOptions::verify_base_objects,
636 kAllowedInEnvvar);
637 AddOption("--watch",
638 "run in watch mode",
639 &EnvironmentOptions::watch_mode,
640 kAllowedInEnvvar);
641 AddOption("--watch-path",
642 "path to watch",
643 &EnvironmentOptions::watch_mode_paths,
644 kAllowedInEnvvar);
645 AddOption("--watch-preserve-output",
646 "preserve outputs on watch mode restart",
647 &EnvironmentOptions::watch_mode_preserve_output,
648 kAllowedInEnvvar);
649 Implies("--watch-path", "--watch");
650 AddOption("--check",
651 "syntax check script without executing",
652 &EnvironmentOptions::syntax_check_only);
653 AddAlias("-c", "--check");
654 // This option is only so that we can tell --eval with an empty string from
655 // no eval at all. Having it not start with a dash makes it inaccessible
656 // from the parser itself, but available for using Implies().
657 // TODO(addaleax): When moving --help over to something generated from the
658 // programmatic descriptions, this will need some special care.
659 // (See also [ssl_openssl_cert_store] below.)
660 AddOption("[has_eval_string]", "", &EnvironmentOptions::has_eval_string);
661 AddOption("--eval", "evaluate script", &EnvironmentOptions::eval_string);
662 Implies("--eval", "[has_eval_string]");
663 AddOption("--print",
664 "evaluate script and print result",
665 &EnvironmentOptions::print_eval);
666 AddAlias("-e", "--eval");
667 AddAlias("--print <arg>", "-pe");
668 AddAlias("-pe", { "--print", "--eval" });
669 AddAlias("-p", "--print");
670 AddOption("--require",
671 "CommonJS module to preload (option can be repeated)",
672 &EnvironmentOptions::preload_cjs_modules,
673 kAllowedInEnvvar);
674 AddAlias("-r", "--require");
675 AddOption("--import",
676 "ES module to preload (option can be repeated)",
677 &EnvironmentOptions::preload_esm_modules,
678 kAllowedInEnvironment);
679 AddOption("--interactive",
680 "always enter the REPL even if stdin does not appear "
681 "to be a terminal",
682 &EnvironmentOptions::force_repl);
683 AddAlias("-i", "--interactive");
684
685 AddOption("--napi-modules", "", NoOp{}, kAllowedInEnvvar);
686
687 AddOption("--tls-keylog",
688 "log TLS decryption keys to named file for traffic analysis",
689 &EnvironmentOptions::tls_keylog,
690 kAllowedInEnvvar);
691
692 AddOption("--tls-min-v1.0",
693 "set default TLS minimum to TLSv1.0 (default: TLSv1.2)",
694 &EnvironmentOptions::tls_min_v1_0,
695 kAllowedInEnvvar);
696 AddOption("--tls-min-v1.1",
697 "set default TLS minimum to TLSv1.1 (default: TLSv1.2)",
698 &EnvironmentOptions::tls_min_v1_1,
699 kAllowedInEnvvar);
700 AddOption("--tls-min-v1.2",
701 "set default TLS minimum to TLSv1.2 (default: TLSv1.2)",
702 &EnvironmentOptions::tls_min_v1_2,
703 kAllowedInEnvvar);
704 AddOption("--tls-min-v1.3",
705 "set default TLS minimum to TLSv1.3 (default: TLSv1.2)",
706 &EnvironmentOptions::tls_min_v1_3,
707 kAllowedInEnvvar);
708 AddOption("--tls-max-v1.2",
709 "set default TLS maximum to TLSv1.2 (default: TLSv1.3)",
710 &EnvironmentOptions::tls_max_v1_2,
711 kAllowedInEnvvar);
712 // Current plan is:
713 // - 11.x and below: TLS1.3 is opt-in with --tls-max-v1.3
714 // - 12.x: TLS1.3 is opt-out with --tls-max-v1.2
715 // In either case, support both options they are uniformly available.
716 AddOption("--tls-max-v1.3",
717 "set default TLS maximum to TLSv1.3 (default: TLSv1.3)",
718 &EnvironmentOptions::tls_max_v1_3,
719 kAllowedInEnvvar);
720 }
721
PerIsolateOptionsParser(const EnvironmentOptionsParser & eop)722 PerIsolateOptionsParser::PerIsolateOptionsParser(
723 const EnvironmentOptionsParser& eop) {
724 AddOption("--track-heap-objects",
725 "track heap object allocations for heap snapshots",
726 &PerIsolateOptions::track_heap_objects,
727 kAllowedInEnvvar);
728
729 // Explicitly add some V8 flags to mark them as allowed in NODE_OPTIONS.
730 AddOption("--abort-on-uncaught-exception",
731 "aborting instead of exiting causes a core file to be generated "
732 "for analysis",
733 V8Option{},
734 kAllowedInEnvvar);
735 AddOption("--interpreted-frames-native-stack",
736 "help system profilers to translate JavaScript interpreted frames",
737 V8Option{}, kAllowedInEnvvar);
738 AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvvar);
739 AddOption("--max-semi-space-size", "", V8Option{}, kAllowedInEnvvar);
740 AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvvar);
741 AddOption("--perf-basic-prof-only-functions",
742 "",
743 V8Option{},
744 kAllowedInEnvvar);
745 AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvvar);
746 AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvvar);
747 AddOption(
748 "--perf-basic-prof-only-functions", "", V8Option{}, kAllowedInEnvvar);
749 AddOption("--perf-prof", "", V8Option{}, kAllowedInEnvvar);
750 AddOption("--perf-prof-unwinding-info", "", V8Option{}, kAllowedInEnvvar);
751 AddOption("--stack-trace-limit", "", V8Option{}, kAllowedInEnvvar);
752 AddOption("--disallow-code-generation-from-strings",
753 "disallow eval and friends",
754 V8Option{},
755 kAllowedInEnvvar);
756 AddOption("--huge-max-old-generation-size",
757 "increase default maximum heap size on machines with 16GB memory "
758 "or more",
759 V8Option{},
760 kAllowedInEnvvar);
761 AddOption("--jitless",
762 "disable runtime allocation of executable memory",
763 V8Option{},
764 kAllowedInEnvvar);
765 AddOption("--report-uncaught-exception",
766 "generate diagnostic report on uncaught exceptions",
767 &PerIsolateOptions::report_uncaught_exception,
768 kAllowedInEnvvar);
769 AddOption("--report-on-signal",
770 "generate diagnostic report upon receiving signals",
771 &PerIsolateOptions::report_on_signal,
772 kAllowedInEnvvar);
773 AddOption("--report-signal",
774 "causes diagnostic report to be produced on provided signal,"
775 " unsupported in Windows. (default: SIGUSR2)",
776 &PerIsolateOptions::report_signal,
777 kAllowedInEnvvar);
778 Implies("--report-signal", "--report-on-signal");
779 AddOption("--enable-etw-stack-walking",
780 "provides heap data to ETW Windows native tracing",
781 V8Option{},
782 kAllowedInEnvironment);
783
784 AddOption("--experimental-top-level-await", "", NoOp{}, kAllowedInEnvvar);
785
786 AddOption("--experimental-shadow-realm",
787 "",
788 &PerIsolateOptions::experimental_shadow_realm,
789 kAllowedInEnvvar);
790 AddOption("--harmony-shadow-realm", "", V8Option{});
791 Implies("--experimental-shadow-realm", "--harmony-shadow-realm");
792 Implies("--harmony-shadow-realm", "--experimental-shadow-realm");
793 ImpliesNot("--no-harmony-shadow-realm", "--experimental-shadow-realm");
794
795 Insert(eop, &PerIsolateOptions::get_per_env_options);
796 }
797
PerProcessOptionsParser(const PerIsolateOptionsParser & iop)798 PerProcessOptionsParser::PerProcessOptionsParser(
799 const PerIsolateOptionsParser& iop) {
800 AddOption("--title",
801 "the process title to use on startup",
802 &PerProcessOptions::title,
803 kAllowedInEnvvar);
804 AddOption("--trace-event-categories",
805 "comma separated list of trace event categories to record",
806 &PerProcessOptions::trace_event_categories,
807 kAllowedInEnvvar);
808 AddOption("--trace-event-file-pattern",
809 "Template string specifying the filepath for the trace-events "
810 "data, it supports ${rotation} and ${pid}.",
811 &PerProcessOptions::trace_event_file_pattern,
812 kAllowedInEnvvar);
813 AddAlias("--trace-events-enabled", {
814 "--trace-event-categories", "v8,node,node.async_hooks" });
815 AddOption("--v8-pool-size",
816 "set V8's thread pool size",
817 &PerProcessOptions::v8_thread_pool_size,
818 kAllowedInEnvvar);
819 AddOption("--zero-fill-buffers",
820 "automatically zero-fill all newly allocated Buffer and "
821 "SlowBuffer instances",
822 &PerProcessOptions::zero_fill_all_buffers,
823 kAllowedInEnvvar);
824 AddOption("--debug-arraybuffer-allocations",
825 "", /* undocumented, only for debugging */
826 &PerProcessOptions::debug_arraybuffer_allocations,
827 kAllowedInEnvvar);
828 AddOption("--disable-proto",
829 "disable Object.prototype.__proto__",
830 &PerProcessOptions::disable_proto,
831 kAllowedInEnvvar);
832 AddOption("--build-snapshot",
833 "Generate a snapshot blob when the process exits."
834 " Currently only supported in the node_mksnapshot binary.",
835 &PerProcessOptions::build_snapshot,
836 kDisallowedInEnvvar);
837 AddOption("--node-snapshot",
838 "", // It's a debug-only option.
839 &PerProcessOptions::node_snapshot,
840 kAllowedInEnvvar);
841 AddOption("--snapshot-blob",
842 "Path to the snapshot blob that's either the result of snapshot"
843 "building, or the blob that is used to restore the application "
844 "state",
845 &PerProcessOptions::snapshot_blob,
846 kAllowedInEnvvar);
847
848 // 12.x renamed this inadvertently, so alias it for consistency within the
849 // release line, while using the original name for consistency with older
850 // release lines.
851 AddOption("--security-revert", "", &PerProcessOptions::security_reverts);
852 AddAlias("--security-reverts", "--security-revert");
853 AddOption("--completion-bash",
854 "print source-able bash completion script",
855 &PerProcessOptions::print_bash_completion);
856 AddOption("--help",
857 "print node command line options",
858 &PerProcessOptions::print_help);
859 AddAlias("-h", "--help");
860 AddOption(
861 "--version", "print Node.js version", &PerProcessOptions::print_version);
862 AddAlias("-v", "--version");
863 AddOption("--v8-options",
864 "print V8 command line options",
865 &PerProcessOptions::print_v8_help);
866 AddOption("--report-compact",
867 "output compact single-line JSON",
868 &PerProcessOptions::report_compact,
869 kAllowedInEnvvar);
870 AddOption("--report-dir",
871 "define custom report pathname."
872 " (default: current working directory)",
873 &PerProcessOptions::report_directory,
874 kAllowedInEnvvar);
875 AddAlias("--report-directory", "--report-dir");
876 AddOption("--report-filename",
877 "define custom report file name."
878 " (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)",
879 &PerProcessOptions::report_filename,
880 kAllowedInEnvvar);
881 AddOption("--report-on-fatalerror",
882 "generate diagnostic report on fatal (internal) errors",
883 &PerProcessOptions::report_on_fatalerror,
884 kAllowedInEnvvar);
885
886 #ifdef NODE_HAVE_I18N_SUPPORT
887 AddOption("--icu-data-dir",
888 "set ICU data load path to dir (overrides NODE_ICU_DATA)"
889 #ifndef NODE_HAVE_SMALL_ICU
890 " (note: linked-in ICU data is present)"
891 #endif
892 ,
893 &PerProcessOptions::icu_data_dir,
894 kAllowedInEnvvar);
895 #endif
896
897 #if HAVE_OPENSSL
898 AddOption("--openssl-config",
899 "load OpenSSL configuration from the specified file "
900 "(overrides OPENSSL_CONF)",
901 &PerProcessOptions::openssl_config,
902 kAllowedInEnvvar);
903 AddOption("--tls-cipher-list",
904 "use an alternative default TLS cipher list",
905 &PerProcessOptions::tls_cipher_list,
906 kAllowedInEnvvar);
907 AddOption("--use-openssl-ca",
908 "use OpenSSL's default CA store"
909 #if defined(NODE_OPENSSL_CERT_STORE)
910 " (default)"
911 #endif
912 ,
913 &PerProcessOptions::use_openssl_ca,
914 kAllowedInEnvvar);
915 AddOption("--use-bundled-ca",
916 "use bundled CA store"
917 #if !defined(NODE_OPENSSL_CERT_STORE)
918 " (default)"
919 #endif
920 ,
921 &PerProcessOptions::use_bundled_ca,
922 kAllowedInEnvvar);
923 // Similar to [has_eval_string] above, except that the separation between
924 // this and use_openssl_ca only exists for option validation after parsing.
925 // This is not ideal.
926 AddOption("[ssl_openssl_cert_store]",
927 "",
928 &PerProcessOptions::ssl_openssl_cert_store);
929 Implies("--use-openssl-ca", "[ssl_openssl_cert_store]");
930 ImpliesNot("--use-bundled-ca", "[ssl_openssl_cert_store]");
931 AddOption("--enable-fips",
932 "enable FIPS crypto at startup",
933 &PerProcessOptions::enable_fips_crypto,
934 kAllowedInEnvvar);
935 AddOption("--force-fips",
936 "force FIPS crypto (cannot be disabled)",
937 &PerProcessOptions::force_fips_crypto,
938 kAllowedInEnvvar);
939 AddOption("--secure-heap",
940 "total size of the OpenSSL secure heap",
941 &PerProcessOptions::secure_heap,
942 kAllowedInEnvvar);
943 AddOption("--secure-heap-min",
944 "minimum allocation size from the OpenSSL secure heap",
945 &PerProcessOptions::secure_heap_min,
946 kAllowedInEnvvar);
947 #endif // HAVE_OPENSSL
948 #if OPENSSL_VERSION_MAJOR >= 3
949 AddOption("--openssl-legacy-provider",
950 "enable OpenSSL 3.0 legacy provider",
951 &PerProcessOptions::openssl_legacy_provider,
952 kAllowedInEnvvar);
953 AddOption("--openssl-shared-config",
954 "enable OpenSSL shared configuration",
955 &PerProcessOptions::openssl_shared_config,
956 kAllowedInEnvvar);
957
958 #endif // OPENSSL_VERSION_MAJOR
959 AddOption("--use-largepages",
960 "Map the Node.js static code to large pages. Options are "
961 "'off' (the default value, meaning do not map), "
962 "'on' (map and ignore failure, reporting it to stderr), "
963 "or 'silent' (map and silently ignore failure)",
964 &PerProcessOptions::use_largepages,
965 kAllowedInEnvvar);
966
967 AddOption("--trace-sigint",
968 "enable printing JavaScript stacktrace on SIGINT",
969 &PerProcessOptions::trace_sigint,
970 kAllowedInEnvvar);
971
972 Insert(iop, &PerProcessOptions::get_per_isolate_options);
973
974 AddOption("--node-memory-debug",
975 "Run with extra debug checks for memory leaks in Node.js itself",
976 NoOp{},
977 kAllowedInEnvvar);
978 Implies("--node-memory-debug", "--debug-arraybuffer-allocations");
979 Implies("--node-memory-debug", "--verify-base-objects");
980 }
981
RemoveBrackets(const std::string & host)982 inline std::string RemoveBrackets(const std::string& host) {
983 if (!host.empty() && host.front() == '[' && host.back() == ']')
984 return host.substr(1, host.size() - 2);
985 else
986 return host;
987 }
988
ParseAndValidatePort(const std::string & port,std::vector<std::string> * errors)989 inline int ParseAndValidatePort(const std::string& port,
990 std::vector<std::string>* errors) {
991 char* endptr;
992 errno = 0;
993 const unsigned long result = // NOLINT(runtime/int)
994 strtoul(port.c_str(), &endptr, 10);
995 if (errno != 0 || *endptr != '\0'||
996 (result != 0 && result < 1024) || result > 65535) {
997 errors->push_back(" must be 0 or in range 1024 to 65535.");
998 }
999 return static_cast<int>(result);
1000 }
1001
SplitHostPort(const std::string & arg,std::vector<std::string> * errors)1002 HostPort SplitHostPort(const std::string& arg,
1003 std::vector<std::string>* errors) {
1004 // remove_brackets only works if no port is specified
1005 // so if it has an effect only an IPv6 address was specified.
1006 std::string host = RemoveBrackets(arg);
1007 if (host.length() < arg.length())
1008 return HostPort{host, DebugOptions::kDefaultInspectorPort};
1009
1010 size_t colon = arg.rfind(':');
1011 if (colon == std::string::npos) {
1012 // Either a port number or a host name. Assume that
1013 // if it's not all decimal digits, it's a host name.
1014 for (char c : arg) {
1015 if (c < '0' || c > '9') {
1016 return HostPort{arg, DebugOptions::kDefaultInspectorPort};
1017 }
1018 }
1019 return HostPort { "", ParseAndValidatePort(arg, errors) };
1020 }
1021 // Host and port found:
1022 return HostPort { RemoveBrackets(arg.substr(0, colon)),
1023 ParseAndValidatePort(arg.substr(colon + 1), errors) };
1024 }
1025
GetBashCompletion()1026 std::string GetBashCompletion() {
1027 Mutex::ScopedLock lock(per_process::cli_options_mutex);
1028 const auto& parser = _ppop_instance;
1029
1030 std::ostringstream out;
1031
1032 out << "_node_complete() {\n"
1033 " local cur_word options\n"
1034 " cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n"
1035 " if [[ \"${cur_word}\" == -* ]] ; then\n"
1036 " COMPREPLY=( $(compgen -W '";
1037
1038 for (const auto& item : parser.options_) {
1039 if (item.first[0] != '[') {
1040 out << item.first << " ";
1041 }
1042 }
1043 for (const auto& item : parser.aliases_) {
1044 if (item.first[0] != '[') {
1045 out << item.first << " ";
1046 }
1047 }
1048 if (parser.aliases_.size() > 0) {
1049 out.seekp(-1, out.cur); // Strip the trailing space
1050 }
1051
1052 out << "' -- \"${cur_word}\") )\n"
1053 " return 0\n"
1054 " else\n"
1055 " COMPREPLY=( $(compgen -f \"${cur_word}\") )\n"
1056 " return 0\n"
1057 " fi\n"
1058 "}\n"
1059 "complete -o filenames -o nospace -o bashdefault "
1060 "-F _node_complete node node_g";
1061 return out.str();
1062 }
1063
1064 // Return a map containing all the options and their metadata as well
1065 // as the aliases
GetCLIOptions(const FunctionCallbackInfo<Value> & args)1066 void GetCLIOptions(const FunctionCallbackInfo<Value>& args) {
1067 Mutex::ScopedLock lock(per_process::cli_options_mutex);
1068 Environment* env = Environment::GetCurrent(args);
1069 if (!env->has_run_bootstrapping_code()) {
1070 // No code because this is an assertion.
1071 return env->ThrowError(
1072 "Should not query options before bootstrapping is done");
1073 }
1074 env->set_has_serialized_options(true);
1075
1076 Isolate* isolate = env->isolate();
1077 Local<Context> context = env->context();
1078
1079 // Temporarily act as if the current Environment's/IsolateData's options were
1080 // the default options, i.e. like they are the ones we'd access for global
1081 // options parsing, so that all options are available from the main parser.
1082 auto original_per_isolate = per_process::cli_options->per_isolate;
1083 per_process::cli_options->per_isolate = env->isolate_data()->options();
1084 auto original_per_env = per_process::cli_options->per_isolate->per_env;
1085 per_process::cli_options->per_isolate->per_env = env->options();
1086 auto on_scope_leave = OnScopeLeave([&]() {
1087 per_process::cli_options->per_isolate->per_env = original_per_env;
1088 per_process::cli_options->per_isolate = original_per_isolate;
1089 });
1090
1091 Local<Map> options = Map::New(isolate);
1092 if (options
1093 ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1094 .IsNothing()) {
1095 return;
1096 }
1097
1098 for (const auto& item : _ppop_instance.options_) {
1099 Local<Value> value;
1100 const auto& option_info = item.second;
1101 auto field = option_info.field;
1102 PerProcessOptions* opts = per_process::cli_options.get();
1103 switch (option_info.type) {
1104 case kNoOp:
1105 case kV8Option:
1106 // Special case for --abort-on-uncaught-exception which is also
1107 // respected by Node.js internals
1108 if (item.first == "--abort-on-uncaught-exception") {
1109 value = Boolean::New(
1110 isolate, original_per_env->abort_on_uncaught_exception);
1111 } else {
1112 value = Undefined(isolate);
1113 }
1114 break;
1115 case kBoolean:
1116 value = Boolean::New(isolate,
1117 *_ppop_instance.Lookup<bool>(field, opts));
1118 break;
1119 case kInteger:
1120 value = Number::New(
1121 isolate,
1122 static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1123 break;
1124 case kUInteger:
1125 value = Number::New(
1126 isolate,
1127 static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1128 break;
1129 case kString:
1130 if (!ToV8Value(context,
1131 *_ppop_instance.Lookup<std::string>(field, opts))
1132 .ToLocal(&value)) {
1133 return;
1134 }
1135 break;
1136 case kStringList:
1137 if (!ToV8Value(context,
1138 *_ppop_instance.Lookup<StringVector>(field, opts))
1139 .ToLocal(&value)) {
1140 return;
1141 }
1142 break;
1143 case kHostPort: {
1144 const HostPort& host_port =
1145 *_ppop_instance.Lookup<HostPort>(field, opts);
1146 Local<Object> obj = Object::New(isolate);
1147 Local<Value> host;
1148 if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1149 obj->Set(context, env->host_string(), host).IsNothing() ||
1150 obj->Set(context,
1151 env->port_string(),
1152 Integer::New(isolate, host_port.port()))
1153 .IsNothing()) {
1154 return;
1155 }
1156 value = obj;
1157 break;
1158 }
1159 default:
1160 UNREACHABLE();
1161 }
1162 CHECK(!value.IsEmpty());
1163
1164 Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1165 Local<Object> info = Object::New(isolate);
1166 Local<Value> help_text;
1167 if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1168 !info->Set(context, env->help_text_string(), help_text)
1169 .FromMaybe(false) ||
1170 !info->Set(context,
1171 env->env_var_settings_string(),
1172 Integer::New(isolate,
1173 static_cast<int>(option_info.env_setting)))
1174 .FromMaybe(false) ||
1175 !info->Set(context,
1176 env->type_string(),
1177 Integer::New(isolate, static_cast<int>(option_info.type)))
1178 .FromMaybe(false) ||
1179 !info->Set(context,
1180 env->default_is_true_string(),
1181 Boolean::New(isolate, option_info.default_is_true))
1182 .FromMaybe(false) ||
1183 info->Set(context, env->value_string(), value).IsNothing() ||
1184 options->Set(context, name, info).IsEmpty()) {
1185 return;
1186 }
1187 }
1188
1189 Local<Value> aliases;
1190 if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1191
1192 if (aliases.As<Object>()
1193 ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1194 .IsNothing()) {
1195 return;
1196 }
1197
1198 Local<Object> ret = Object::New(isolate);
1199 if (ret->Set(context, env->options_string(), options).IsNothing() ||
1200 ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1201 return;
1202 }
1203
1204 args.GetReturnValue().Set(ret);
1205 }
1206
GetEmbedderOptions(const FunctionCallbackInfo<Value> & args)1207 void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1208 Environment* env = Environment::GetCurrent(args);
1209 if (!env->has_run_bootstrapping_code()) {
1210 // No code because this is an assertion.
1211 return env->ThrowError(
1212 "Should not query options before bootstrapping is done");
1213 }
1214 Isolate* isolate = args.GetIsolate();
1215 Local<Context> context = env->context();
1216 Local<Object> ret = Object::New(isolate);
1217
1218 if (ret->Set(context,
1219 FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1220 Boolean::New(isolate, env->should_not_register_esm_loader()))
1221 .IsNothing()) return;
1222
1223 if (ret->Set(context,
1224 FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1225 Boolean::New(isolate, env->no_global_search_paths()))
1226 .IsNothing()) return;
1227
1228 args.GetReturnValue().Set(ret);
1229 }
1230
Initialize(Local<Object> target,Local<Value> unused,Local<Context> context,void * priv)1231 void Initialize(Local<Object> target,
1232 Local<Value> unused,
1233 Local<Context> context,
1234 void* priv) {
1235 Environment* env = Environment::GetCurrent(context);
1236 Isolate* isolate = env->isolate();
1237 SetMethodNoSideEffect(context, target, "getCLIOptions", GetCLIOptions);
1238 SetMethodNoSideEffect(
1239 context, target, "getEmbedderOptions", GetEmbedderOptions);
1240
1241 Local<Object> env_settings = Object::New(isolate);
1242 NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvvar);
1243 NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvvar);
1244 target
1245 ->Set(
1246 context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1247 .Check();
1248
1249 Local<Object> types = Object::New(isolate);
1250 NODE_DEFINE_CONSTANT(types, kNoOp);
1251 NODE_DEFINE_CONSTANT(types, kV8Option);
1252 NODE_DEFINE_CONSTANT(types, kBoolean);
1253 NODE_DEFINE_CONSTANT(types, kInteger);
1254 NODE_DEFINE_CONSTANT(types, kUInteger);
1255 NODE_DEFINE_CONSTANT(types, kString);
1256 NODE_DEFINE_CONSTANT(types, kHostPort);
1257 NODE_DEFINE_CONSTANT(types, kStringList);
1258 target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1259 .Check();
1260 }
1261
RegisterExternalReferences(ExternalReferenceRegistry * registry)1262 void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1263 registry->Register(GetCLIOptions);
1264 registry->Register(GetEmbedderOptions);
1265 }
1266 } // namespace options_parser
1267
HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options)1268 void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1269 HandleEnvOptions(env_options, [](const char* name) {
1270 std::string text;
1271 return credentials::SafeGetenv(name, &text) ? text : "";
1272 });
1273 }
1274
HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,std::function<std::string (const char *)> opt_getter)1275 void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1276 std::function<std::string(const char*)> opt_getter) {
1277 env_options->pending_deprecation =
1278 opt_getter("NODE_PENDING_DEPRECATION") == "1";
1279
1280 env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1281
1282 env_options->preserve_symlinks_main =
1283 opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1284
1285 if (env_options->redirect_warnings.empty())
1286 env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1287 }
1288
ParseNodeOptionsEnvVar(const std::string & node_options,std::vector<std::string> * errors)1289 std::vector<std::string> ParseNodeOptionsEnvVar(
1290 const std::string& node_options, std::vector<std::string>* errors) {
1291 std::vector<std::string> env_argv;
1292
1293 bool is_in_string = false;
1294 bool will_start_new_arg = true;
1295 for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1296 char c = node_options.at(index);
1297
1298 // Backslashes escape the following character
1299 if (c == '\\' && is_in_string) {
1300 if (index + 1 == node_options.size()) {
1301 errors->push_back("invalid value for NODE_OPTIONS "
1302 "(invalid escape)\n");
1303 return env_argv;
1304 } else {
1305 c = node_options.at(++index);
1306 }
1307 } else if (c == ' ' && !is_in_string) {
1308 will_start_new_arg = true;
1309 continue;
1310 } else if (c == '"') {
1311 is_in_string = !is_in_string;
1312 continue;
1313 }
1314
1315 if (will_start_new_arg) {
1316 env_argv.emplace_back(std::string(1, c));
1317 will_start_new_arg = false;
1318 } else {
1319 env_argv.back() += c;
1320 }
1321 }
1322
1323 if (is_in_string) {
1324 errors->push_back("invalid value for NODE_OPTIONS "
1325 "(unterminated string)\n");
1326 }
1327 return env_argv;
1328 }
1329 } // namespace node
1330
1331 NODE_BINDING_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1332 NODE_BINDING_EXTERNAL_REFERENCE(
1333 options, node::options_parser::RegisterExternalReferences)
1334