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