GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 480 511 93.9 %
Date: 2022-10-07 04:22:37 Branches: 214 274 78.1 %

Line Branch Exec Source
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
#if HAVE_OPENSSL
9
#include "openssl/opensslv.h"
10
#endif
11
12
#include <errno.h>
13
#include <sstream>
14
#include <limits>
15
#include <algorithm>
16
#include <cstdlib>  // strtoul, errno
17
18
using v8::Boolean;
19
using v8::Context;
20
using v8::FunctionCallbackInfo;
21
using v8::Integer;
22
using v8::Isolate;
23
using v8::Local;
24
using v8::Map;
25
using v8::Number;
26
using v8::Object;
27
using v8::Undefined;
28
using v8::Value;
29
30
namespace node {
31
32
namespace per_process {
33
Mutex cli_options_mutex;
34
std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
35
}  // namespace per_process
36
37
11639
void DebugOptions::CheckOptions(std::vector<std::string>* errors) {
38
#if !NODE_USE_V8_PLATFORM && !HAVE_INSPECTOR
39
  if (inspector_enabled) {
40
    errors->push_back("Inspector is not available when Node is compiled "
41
                      "--without-v8-platform and --without-inspector.");
42
  }
43
#endif
44
45
11639
  if (deprecated_debug) {
46
4
    errors->push_back("[DEP0062]: `node --debug` and `node --debug-brk` "
47
                      "are invalid. Please use `node --inspect` and "
48
                      "`node --inspect-brk` instead.");
49
  }
50
51
  std::vector<std::string> destinations =
52
23278
      SplitString(inspect_publish_uid_string, ',');
53
11639
  inspect_publish_uid.console = false;
54
11639
  inspect_publish_uid.http = false;
55
34915
  for (const std::string& destination : destinations) {
56
23276
    if (destination == "stderr") {
57
11638
      inspect_publish_uid.console = true;
58
11638
    } else if (destination == "http") {
59
11638
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
11639
}
66
67
11050
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

11050
  if (use_openssl_ca && use_bundled_ca) {
70
1
    errors->push_back("either --use-openssl-ca or --use-bundled-ca can be "
71
                      "used, not both");
72
  }
73
74
  // Any value less than 2 disables use of the secure heap.
75
11050
  if (secure_heap >= 2) {
76
2
    if ((secure_heap & (secure_heap - 1)) != 0)
77
1
      errors->push_back("--secure-heap must be a power of 2");
78
2
    secure_heap_min =
79
6
        std::min({
80
2
            secure_heap,
81
2
            secure_heap_min,
82
            static_cast<int64_t>(std::numeric_limits<int>::max())});
83
2
    secure_heap_min = std::max(static_cast<int64_t>(2), secure_heap_min);
84
2
    if ((secure_heap_min & (secure_heap_min - 1)) != 0)
85
1
      errors->push_back("--secure-heap-min must be a power of 2");
86
  }
87
#endif  // HAVE_OPENSSL
88
89
11052
  if (use_largepages != "off" &&
90

11052
      use_largepages != "on" &&
91
1
      use_largepages != "silent") {
92
1
    errors->push_back("invalid value for --use-largepages");
93
  }
94
11050
  per_isolate->CheckOptions(errors);
95
11050
}
96
97
11639
void PerIsolateOptions::CheckOptions(std::vector<std::string>* errors) {
98
11639
  per_env->CheckOptions(errors);
99
11639
}
100
101
11639
void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors) {
102

11639
  if (has_policy_integrity_string && experimental_policy.empty()) {
103
    errors->push_back("--policy-integrity requires "
104
                      "--experimental-policy be enabled");
105
  }
106

11639
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
107
1
    errors->push_back("--policy-integrity cannot be empty");
108
  }
109
110
11639
  if (!module_type.empty()) {
111

58
    if (module_type != "commonjs" && module_type != "module") {
112
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
113
    }
114
  }
115
116

11639
  if (syntax_check_only && has_eval_string) {
117
4
    errors->push_back("either --check or --eval can be used, not both");
118
  }
119
120
11659
  if (!unhandled_rejections.empty() &&
121
39
      unhandled_rejections != "warn-with-error-code" &&
122
36
      unhandled_rejections != "throw" &&
123
32
      unhandled_rejections != "strict" &&
124

11674
      unhandled_rejections != "warn" &&
125
10
      unhandled_rejections != "none") {
126
1
    errors->push_back("invalid value for --unhandled-rejections");
127
  }
128
129

11639
  if (tls_min_v1_3 && tls_max_v1_2) {
130
1
    errors->push_back("either --tls-min-v1.3 or --tls-max-v1.2 can be "
131
                      "used, not both");
132
  }
133
134
11639
  if (heap_snapshot_near_heap_limit < 0) {
135
    errors->push_back("--heapsnapshot-near-heap-limit must not be negative");
136
  }
137
138
11639
  if (test_runner) {
139
14
    if (syntax_check_only) {
140
1
      errors->push_back("either --test or --check can be used, not both");
141
    }
142
143
14
    if (has_eval_string) {
144
2
      errors->push_back("either --test or --eval can be used, not both");
145
    }
146
147
14
    if (force_repl) {
148
1
      errors->push_back("either --test or --interactive can be used, not both");
149
    }
150
151
14
    if (watch_mode) {
152
      // TODO(MoLow): Support (incremental?) watch mode within test runner
153
      errors->push_back("either --test or --watch can be used, not both");
154
    }
155
156
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_TEST_RUNNER
157
    debug_options_.allow_attaching_debugger = false;
158
#endif
159
  }
160
161
11639
  if (watch_mode) {
162
11
    if (syntax_check_only) {
163
      errors->push_back("either --watch or --check can be used, not both");
164
    }
165
166
11
    if (has_eval_string) {
167
      errors->push_back("either --watch or --eval can be used, not both");
168
    }
169
170
11
    if (force_repl) {
171
      errors->push_back("either --watch or --interactive "
172
                        "can be used, not both");
173
    }
174
175
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_WATCH_MODE
176
    debug_options_.allow_attaching_debugger = false;
177
#endif
178
  }
179
180
#if HAVE_INSPECTOR
181
11639
  if (!cpu_prof) {
182
11628
    if (!cpu_prof_name.empty()) {
183
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
184
    }
185
11628
    if (!cpu_prof_dir.empty()) {
186
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
187
    }
188
    // We can't catch the case where the value passed is the default value,
189
    // then the option just becomes a noop which is fine.
190
11628
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
191
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
192
    }
193
  }
194
195


11639
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
196
1
      cpu_prof_dir = diagnostic_dir;
197
    }
198
199
11639
  if (!heap_prof) {
200
11628
    if (!heap_prof_name.empty()) {
201
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
202
    }
203
11628
    if (!heap_prof_dir.empty()) {
204
1
      errors->push_back("--heap-prof-dir must be used with --heap-prof");
205
    }
206
    // We can't catch the case where the value passed is the default value,
207
    // then the option just becomes a noop which is fine.
208
11628
    if (heap_prof_interval != kDefaultHeapProfInterval) {
209
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
210
    }
211
  }
212
213


11639
  if (heap_prof && heap_prof_dir.empty() && !diagnostic_dir.empty()) {
214
1
    heap_prof_dir = diagnostic_dir;
215
  }
216
217
11639
  debug_options_.CheckOptions(errors);
218
#endif  // HAVE_INSPECTOR
219
11639
}
220
221
namespace options_parser {
222
223
class DebugOptionsParser : public OptionsParser<DebugOptions> {
224
 public:
225
  DebugOptionsParser();
226
};
227
228
class EnvironmentOptionsParser : public OptionsParser<EnvironmentOptions> {
229
 public:
230
  EnvironmentOptionsParser();
231
5594
  explicit EnvironmentOptionsParser(const DebugOptionsParser& dop)
232
5594
    : EnvironmentOptionsParser() {
233
5594
    Insert(dop, &EnvironmentOptions::get_debug_options);
234
5594
  }
235
};
236
237
class PerIsolateOptionsParser : public OptionsParser<PerIsolateOptions> {
238
 public:
239
  PerIsolateOptionsParser() = delete;
240
  explicit PerIsolateOptionsParser(const EnvironmentOptionsParser& eop);
241
};
242
243
class PerProcessOptionsParser : public OptionsParser<PerProcessOptions> {
244
 public:
245
  PerProcessOptionsParser() = delete;
246
  explicit PerProcessOptionsParser(const PerIsolateOptionsParser& iop);
247
};
248
249
#if HAVE_INSPECTOR
250
const DebugOptionsParser _dop_instance{};
251
const EnvironmentOptionsParser _eop_instance{_dop_instance};
252
253
// This Parse is not dead code. It is used by embedders (e.g., Electron).
254
template <>
255
void Parse(
256
  StringVector* const args, StringVector* const exec_args,
257
  StringVector* const v8_args,
258
  DebugOptions* const options,
259
  OptionEnvvarSettings required_env_settings, StringVector* const errors) {
260
  _dop_instance.Parse(
261
    args, exec_args, v8_args, options, required_env_settings, errors);
262
}
263
#else
264
const EnvironmentOptionsParser _eop_instance{};
265
#endif  // HAVE_INSPECTOR
266
const PerIsolateOptionsParser _piop_instance{_eop_instance};
267
const PerProcessOptionsParser _ppop_instance{_piop_instance};
268
269
template <>
270
589
void Parse(
271
  StringVector* const args, StringVector* const exec_args,
272
  StringVector* const v8_args,
273
  PerIsolateOptions* const options,
274
  OptionEnvvarSettings required_env_settings, StringVector* const errors) {
275
589
  _piop_instance.Parse(
276
    args, exec_args, v8_args, options, required_env_settings, errors);
277
589
}
278
279
template <>
280
11050
void Parse(
281
  StringVector* const args, StringVector* const exec_args,
282
  StringVector* const v8_args,
283
  PerProcessOptions* const options,
284
  OptionEnvvarSettings required_env_settings, StringVector* const errors) {
285
11050
  _ppop_instance.Parse(
286
    args, exec_args, v8_args, options, required_env_settings, errors);
287
11050
}
288
289
// XXX: If you add an option here, please also add it to doc/node.1 and
290
// doc/api/cli.md
291
// TODO(addaleax): Make that unnecessary.
292
293
5594
DebugOptionsParser::DebugOptionsParser() {
294
5594
  AddOption("--inspect-port",
295
            "set host:port for inspector",
296
            &DebugOptions::host_port,
297
            kAllowedInEnvironment);
298
5594
  AddAlias("--debug-port", "--inspect-port");
299
300
5594
  AddOption("--inspect",
301
            "activate inspector on host:port (default: 127.0.0.1:9229)",
302
            &DebugOptions::inspector_enabled,
303
            kAllowedInEnvironment);
304
16782
  AddAlias("--inspect=", { "--inspect-port", "--inspect" });
305
306
5594
  AddOption("--debug", "", &DebugOptions::deprecated_debug);
307
5594
  AddAlias("--debug=", "--debug");
308
5594
  AddOption("--debug-brk", "", &DebugOptions::deprecated_debug);
309
5594
  AddAlias("--debug-brk=", "--debug-brk");
310
311
5594
  AddOption("--inspect-brk",
312
            "activate inspector on host:port and break at start of user script",
313
            &DebugOptions::break_first_line,
314
            kAllowedInEnvironment);
315
5594
  Implies("--inspect-brk", "--inspect");
316
16782
  AddAlias("--inspect-brk=", { "--inspect-port", "--inspect-brk" });
317
318
5594
  AddOption("--inspect-brk-node", "", &DebugOptions::break_node_first_line);
319
5594
  Implies("--inspect-brk-node", "--inspect");
320
16782
  AddAlias("--inspect-brk-node=", { "--inspect-port", "--inspect-brk-node" });
321
322
5594
  AddOption("--inspect-publish-uid",
323
            "comma separated list of destinations for inspector uid"
324
            "(default: stderr,http)",
325
            &DebugOptions::inspect_publish_uid_string,
326
            kAllowedInEnvironment);
327
5594
}
328
329
5594
EnvironmentOptionsParser::EnvironmentOptionsParser() {
330
5594
  AddOption("--conditions",
331
            "additional user conditions for conditional exports and imports",
332
            &EnvironmentOptions::conditions,
333
            kAllowedInEnvironment);
334
5594
  AddAlias("-C", "--conditions");
335
5594
  AddOption("--diagnostic-dir",
336
            "set dir for all output files"
337
            " (default: current working directory)",
338
            &EnvironmentOptions::diagnostic_dir,
339
            kAllowedInEnvironment);
340
5594
  AddOption("--dns-result-order",
341
            "set default value of verbatim in dns.lookup. Options are "
342
            "'ipv4first' (IPv4 addresses are placed before IPv6 addresses) "
343
            "'verbatim' (addresses are in the order the DNS resolver "
344
            "returned)",
345
            &EnvironmentOptions::dns_result_order,
346
            kAllowedInEnvironment);
347
5594
  AddOption("--enable-source-maps",
348
            "Source Map V3 support for stack traces",
349
            &EnvironmentOptions::enable_source_maps,
350
            kAllowedInEnvironment);
351
5594
  AddOption("--experimental-abortcontroller", "",
352
            NoOp{}, kAllowedInEnvironment);
353
5594
  AddOption("--experimental-fetch",
354
            "experimental Fetch API",
355
            &EnvironmentOptions::experimental_fetch,
356
            kAllowedInEnvironment,
357
            true);
358
5594
  AddOption("--experimental-global-customevent",
359
            "expose experimental CustomEvent on the global scope",
360
            &EnvironmentOptions::experimental_global_customevent,
361
            kAllowedInEnvironment);
362
5594
  AddOption("--experimental-global-webcrypto",
363
            "expose experimental Web Crypto API on the global scope",
364
            &EnvironmentOptions::experimental_global_web_crypto,
365
            kAllowedInEnvironment,
366
            true);
367
5594
  AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvironment);
368
5594
  AddOption("--experimental-loader",
369
            "use the specified module as a custom loader",
370
            &EnvironmentOptions::userland_loaders,
371
            kAllowedInEnvironment);
372
5594
  AddAlias("--loader", "--experimental-loader");
373
5594
  AddOption("--experimental-modules", "", NoOp{}, kAllowedInEnvironment);
374
5594
  AddOption("--experimental-network-imports",
375
            "experimental https: support for the ES Module loader",
376
            &EnvironmentOptions::experimental_https_modules,
377
            kAllowedInEnvironment);
378
5594
  AddOption("--experimental-wasm-modules",
379
            "experimental ES Module support for webassembly modules",
380
            &EnvironmentOptions::experimental_wasm_modules,
381
            kAllowedInEnvironment);
382
5594
  AddOption("--experimental-import-meta-resolve",
383
            "experimental ES Module import.meta.resolve() support",
384
            &EnvironmentOptions::experimental_import_meta_resolve,
385
            kAllowedInEnvironment);
386
5594
  AddOption("--experimental-policy",
387
            "use the specified file as a "
388
            "security policy",
389
            &EnvironmentOptions::experimental_policy,
390
            kAllowedInEnvironment);
391
5594
  AddOption("[has_policy_integrity_string]",
392
            "",
393
            &EnvironmentOptions::has_policy_integrity_string);
394
5594
  AddOption("--policy-integrity",
395
            "ensure the security policy contents match "
396
            "the specified integrity",
397
            &EnvironmentOptions::experimental_policy_integrity,
398
            kAllowedInEnvironment);
399
5594
  Implies("--policy-integrity", "[has_policy_integrity_string]");
400
5594
  AddOption("--experimental-repl-await",
401
            "experimental await keyword support in REPL",
402
            &EnvironmentOptions::experimental_repl_await,
403
            kAllowedInEnvironment,
404
            true);
405
5594
  AddOption("--experimental-vm-modules",
406
            "experimental ES Module support in vm module",
407
            &EnvironmentOptions::experimental_vm_modules,
408
            kAllowedInEnvironment);
409
5594
  AddOption("--experimental-worker", "", NoOp{}, kAllowedInEnvironment);
410
5594
  AddOption("--experimental-report", "", NoOp{}, kAllowedInEnvironment);
411
5594
  AddOption("--experimental-wasi-unstable-preview1",
412
            "experimental WASI support",
413
            &EnvironmentOptions::experimental_wasi,
414
            kAllowedInEnvironment);
415
5594
  AddOption("--expose-internals", "", &EnvironmentOptions::expose_internals);
416
5594
  AddOption("--frozen-intrinsics",
417
            "experimental frozen intrinsics support",
418
            &EnvironmentOptions::frozen_intrinsics,
419
            kAllowedInEnvironment);
420
5594
  AddOption("--heapsnapshot-signal",
421
            "Generate heap snapshot on specified signal",
422
            &EnvironmentOptions::heap_snapshot_signal,
423
            kAllowedInEnvironment);
424
5594
  AddOption("--heapsnapshot-near-heap-limit",
425
            "Generate heap snapshots whenever V8 is approaching "
426
            "the heap limit. No more than the specified number of "
427
            "heap snapshots will be generated.",
428
            &EnvironmentOptions::heap_snapshot_near_heap_limit,
429
            kAllowedInEnvironment);
430
5594
  AddOption("--http-parser", "", NoOp{}, kAllowedInEnvironment);
431
5594
  AddOption("--insecure-http-parser",
432
            "use an insecure HTTP parser that accepts invalid HTTP headers",
433
            &EnvironmentOptions::insecure_http_parser,
434
            kAllowedInEnvironment);
435
5594
  AddOption("--input-type",
436
            "set module type for string input",
437
            &EnvironmentOptions::module_type,
438
            kAllowedInEnvironment);
439
5594
  AddOption(
440
      "--experimental-specifier-resolution", "", NoOp{}, kAllowedInEnvironment);
441
5594
  AddAlias("--es-module-specifier-resolution",
442
           "--experimental-specifier-resolution");
443
5594
  AddOption("--deprecation",
444
            "silence deprecation warnings",
445
            &EnvironmentOptions::deprecation,
446
            kAllowedInEnvironment,
447
            true);
448
5594
  AddOption("--force-async-hooks-checks",
449
            "disable checks for async_hooks",
450
            &EnvironmentOptions::force_async_hooks_checks,
451
            kAllowedInEnvironment,
452
            true);
453
5594
  AddOption(
454
      "--force-node-api-uncaught-exceptions-policy",
455
      "enforces 'uncaughtException' event on Node API asynchronous callbacks",
456
      &EnvironmentOptions::force_node_api_uncaught_exceptions_policy,
457
      kAllowedInEnvironment,
458
      false);
459
5594
  AddOption("--addons",
460
            "disable loading native addons",
461
            &EnvironmentOptions::allow_native_addons,
462
            kAllowedInEnvironment,
463
            true);
464
5594
  AddOption("--global-search-paths",
465
            "disable global module search paths",
466
            &EnvironmentOptions::global_search_paths,
467
            kAllowedInEnvironment,
468
            true);
469
5594
  AddOption("--warnings",
470
            "silence all process warnings",
471
            &EnvironmentOptions::warnings,
472
            kAllowedInEnvironment,
473
            true);
474
5594
  AddOption("--force-context-aware",
475
            "disable loading non-context-aware addons",
476
            &EnvironmentOptions::force_context_aware,
477
            kAllowedInEnvironment);
478
5594
  AddOption("--pending-deprecation",
479
            "emit pending deprecation warnings",
480
            &EnvironmentOptions::pending_deprecation,
481
            kAllowedInEnvironment);
482
5594
  AddOption("--preserve-symlinks",
483
            "preserve symbolic links when resolving",
484
            &EnvironmentOptions::preserve_symlinks,
485
            kAllowedInEnvironment);
486
5594
  AddOption("--preserve-symlinks-main",
487
            "preserve symbolic links when resolving the main module",
488
            &EnvironmentOptions::preserve_symlinks_main,
489
            kAllowedInEnvironment);
490
5594
  AddOption("--prof",
491
            "Generate V8 profiler output.",
492
            V8Option{});
493
5594
  AddOption("--prof-process",
494
            "process V8 profiler output generated using --prof",
495
            &EnvironmentOptions::prof_process);
496
  // Options after --prof-process are passed through to the prof processor.
497
16782
  AddAlias("--prof-process", { "--prof-process", "--" });
498
#if HAVE_INSPECTOR
499
5594
  AddOption("--cpu-prof",
500
            "Start the V8 CPU profiler on start up, and write the CPU profile "
501
            "to disk before exit. If --cpu-prof-dir is not specified, write "
502
            "the profile to the current working directory.",
503
            &EnvironmentOptions::cpu_prof);
504
5594
  AddOption("--cpu-prof-name",
505
            "specified file name of the V8 CPU profile generated with "
506
            "--cpu-prof",
507
            &EnvironmentOptions::cpu_prof_name);
508
5594
  AddOption("--cpu-prof-interval",
509
            "specified sampling interval in microseconds for the V8 CPU "
510
            "profile generated with --cpu-prof. (default: 1000)",
511
            &EnvironmentOptions::cpu_prof_interval);
512
5594
  AddOption("--cpu-prof-dir",
513
            "Directory where the V8 profiles generated by --cpu-prof will be "
514
            "placed. Does not affect --prof.",
515
            &EnvironmentOptions::cpu_prof_dir);
516
5594
  AddOption(
517
      "--heap-prof",
518
      "Start the V8 heap profiler on start up, and write the heap profile "
519
      "to disk before exit. If --heap-prof-dir is not specified, write "
520
      "the profile to the current working directory.",
521
      &EnvironmentOptions::heap_prof);
522
5594
  AddOption("--heap-prof-name",
523
            "specified file name of the V8 heap profile generated with "
524
            "--heap-prof",
525
            &EnvironmentOptions::heap_prof_name);
526
5594
  AddOption("--heap-prof-dir",
527
            "Directory where the V8 heap profiles generated by --heap-prof "
528
            "will be placed.",
529
            &EnvironmentOptions::heap_prof_dir);
530
5594
  AddOption("--heap-prof-interval",
531
            "specified sampling interval in bytes for the V8 heap "
532
            "profile generated with --heap-prof. (default: 512 * 1024)",
533
            &EnvironmentOptions::heap_prof_interval);
534
#endif  // HAVE_INSPECTOR
535
5594
  AddOption("--max-http-header-size",
536
            "set the maximum size of HTTP headers (default: 16384 (16KB))",
537
            &EnvironmentOptions::max_http_header_size,
538
            kAllowedInEnvironment);
539
5594
  AddOption("--redirect-warnings",
540
            "write warnings to file instead of stderr",
541
            &EnvironmentOptions::redirect_warnings,
542
            kAllowedInEnvironment);
543
5594
  AddOption("--test",
544
            "launch test runner on startup",
545
            &EnvironmentOptions::test_runner);
546
5594
  AddOption("--test-name-pattern",
547
            "run tests whose name matches this regular expression",
548
            &EnvironmentOptions::test_name_pattern);
549
5594
  AddOption("--test-only",
550
            "run tests with 'only' option set",
551
            &EnvironmentOptions::test_only,
552
            kAllowedInEnvironment);
553
5594
  AddOption("--test-udp-no-try-send", "",  // For testing only.
554
            &EnvironmentOptions::test_udp_no_try_send);
555
5594
  AddOption("--throw-deprecation",
556
            "throw an exception on deprecations",
557
            &EnvironmentOptions::throw_deprecation,
558
            kAllowedInEnvironment);
559
5594
  AddOption("--trace-atomics-wait",
560
            "(deprecated) trace Atomics.wait() operations",
561
            &EnvironmentOptions::trace_atomics_wait,
562
            kAllowedInEnvironment);
563
5594
  AddOption("--trace-deprecation",
564
            "show stack traces on deprecations",
565
            &EnvironmentOptions::trace_deprecation,
566
            kAllowedInEnvironment);
567
5594
  AddOption("--trace-exit",
568
            "show stack trace when an environment exits",
569
            &EnvironmentOptions::trace_exit,
570
            kAllowedInEnvironment);
571
5594
  AddOption("--trace-sync-io",
572
            "show stack trace when use of sync IO is detected after the "
573
            "first tick",
574
            &EnvironmentOptions::trace_sync_io,
575
            kAllowedInEnvironment);
576
5594
  AddOption("--trace-tls",
577
            "prints TLS packet trace information to stderr",
578
            &EnvironmentOptions::trace_tls,
579
            kAllowedInEnvironment);
580
5594
  AddOption("--trace-uncaught",
581
            "show stack traces for the `throw` behind uncaught exceptions",
582
            &EnvironmentOptions::trace_uncaught,
583
            kAllowedInEnvironment);
584
5594
  AddOption("--trace-warnings",
585
            "show stack traces on process warnings",
586
            &EnvironmentOptions::trace_warnings,
587
            kAllowedInEnvironment);
588
5594
  AddOption("--extra-info-on-fatal-exception",
589
            "hide extra information on fatal exception that causes exit",
590
            &EnvironmentOptions::extra_info_on_fatal_exception,
591
            kAllowedInEnvironment,
592
            true);
593
5594
  AddOption("--unhandled-rejections",
594
            "define unhandled rejections behavior. Options are 'strict' "
595
            "(always raise an error), 'throw' (raise an error unless "
596
            "'unhandledRejection' hook is set), 'warn' (log a warning), 'none' "
597
            "(silence warnings), 'warn-with-error-code' (log a warning and set "
598
            "exit code 1 unless 'unhandledRejection' hook is set). (default: "
599
            "throw)",
600
            &EnvironmentOptions::unhandled_rejections,
601
            kAllowedInEnvironment);
602
5594
  AddOption("--verify-base-objects",
603
            "", /* undocumented, only for debugging */
604
            &EnvironmentOptions::verify_base_objects,
605
            kAllowedInEnvironment);
606
5594
  AddOption("--watch",
607
            "run in watch mode",
608
            &EnvironmentOptions::watch_mode,
609
            kAllowedInEnvironment);
610
5594
  AddOption("--watch-path",
611
            "path to watch",
612
            &EnvironmentOptions::watch_mode_paths,
613
            kAllowedInEnvironment);
614
5594
  Implies("--watch-path", "--watch");
615
5594
  AddOption("--check",
616
            "syntax check script without executing",
617
            &EnvironmentOptions::syntax_check_only);
618
5594
  AddAlias("-c", "--check");
619
  // This option is only so that we can tell --eval with an empty string from
620
  // no eval at all. Having it not start with a dash makes it inaccessible
621
  // from the parser itself, but available for using Implies().
622
  // TODO(addaleax): When moving --help over to something generated from the
623
  // programmatic descriptions, this will need some special care.
624
  // (See also [ssl_openssl_cert_store] below.)
625
5594
  AddOption("[has_eval_string]", "", &EnvironmentOptions::has_eval_string);
626
5594
  AddOption("--eval", "evaluate script", &EnvironmentOptions::eval_string);
627
5594
  Implies("--eval", "[has_eval_string]");
628
5594
  AddOption("--print",
629
            "evaluate script and print result",
630
            &EnvironmentOptions::print_eval);
631
5594
  AddAlias("-e", "--eval");
632
5594
  AddAlias("--print <arg>", "-pe");
633
16782
  AddAlias("-pe", { "--print", "--eval" });
634
5594
  AddAlias("-p", "--print");
635
5594
  AddOption("--require",
636
            "CommonJS module to preload (option can be repeated)",
637
            &EnvironmentOptions::preload_cjs_modules,
638
            kAllowedInEnvironment);
639
5594
  AddAlias("-r", "--require");
640
5594
  AddOption("--import",
641
            "ES module to preload (option can be repeated)",
642
            &EnvironmentOptions::preload_esm_modules,
643
            kAllowedInEnvironment);
644
5594
  AddOption("--interactive",
645
            "always enter the REPL even if stdin does not appear "
646
            "to be a terminal",
647
            &EnvironmentOptions::force_repl);
648
5594
  AddAlias("-i", "--interactive");
649
650
5594
  AddOption("--update-assert-snapshot",
651
            "update assert snapshot files",
652
            &EnvironmentOptions::update_assert_snapshot,
653
            kAllowedInEnvironment);
654
655
5594
  AddOption("--napi-modules", "", NoOp{}, kAllowedInEnvironment);
656
657
5594
  AddOption("--tls-keylog",
658
            "log TLS decryption keys to named file for traffic analysis",
659
            &EnvironmentOptions::tls_keylog, kAllowedInEnvironment);
660
661
5594
  AddOption("--tls-min-v1.0",
662
            "set default TLS minimum to TLSv1.0 (default: TLSv1.2)",
663
            &EnvironmentOptions::tls_min_v1_0,
664
            kAllowedInEnvironment);
665
5594
  AddOption("--tls-min-v1.1",
666
            "set default TLS minimum to TLSv1.1 (default: TLSv1.2)",
667
            &EnvironmentOptions::tls_min_v1_1,
668
            kAllowedInEnvironment);
669
5594
  AddOption("--tls-min-v1.2",
670
            "set default TLS minimum to TLSv1.2 (default: TLSv1.2)",
671
            &EnvironmentOptions::tls_min_v1_2,
672
            kAllowedInEnvironment);
673
5594
  AddOption("--tls-min-v1.3",
674
            "set default TLS minimum to TLSv1.3 (default: TLSv1.2)",
675
            &EnvironmentOptions::tls_min_v1_3,
676
            kAllowedInEnvironment);
677
5594
  AddOption("--tls-max-v1.2",
678
            "set default TLS maximum to TLSv1.2 (default: TLSv1.3)",
679
            &EnvironmentOptions::tls_max_v1_2,
680
            kAllowedInEnvironment);
681
  // Current plan is:
682
  // - 11.x and below: TLS1.3 is opt-in with --tls-max-v1.3
683
  // - 12.x: TLS1.3 is opt-out with --tls-max-v1.2
684
  // In either case, support both options they are uniformly available.
685
5594
  AddOption("--tls-max-v1.3",
686
            "set default TLS maximum to TLSv1.3 (default: TLSv1.3)",
687
            &EnvironmentOptions::tls_max_v1_3,
688
            kAllowedInEnvironment);
689
5594
}
690
691
5594
PerIsolateOptionsParser::PerIsolateOptionsParser(
692
5594
  const EnvironmentOptionsParser& eop) {
693
5594
  AddOption("--track-heap-objects",
694
            "track heap object allocations for heap snapshots",
695
            &PerIsolateOptions::track_heap_objects,
696
            kAllowedInEnvironment);
697
698
  // Explicitly add some V8 flags to mark them as allowed in NODE_OPTIONS.
699
5594
  AddOption("--abort-on-uncaught-exception",
700
            "aborting instead of exiting causes a core file to be generated "
701
            "for analysis",
702
            V8Option{},
703
            kAllowedInEnvironment);
704
5594
  AddOption("--interpreted-frames-native-stack",
705
            "help system profilers to translate JavaScript interpreted frames",
706
            V8Option{}, kAllowedInEnvironment);
707
5594
  AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvironment);
708
5594
  AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvironment);
709
5594
  AddOption("--perf-basic-prof-only-functions",
710
            "",
711
            V8Option{},
712
            kAllowedInEnvironment);
713
5594
  AddOption("--perf-prof", "", V8Option{}, kAllowedInEnvironment);
714
5594
  AddOption("--perf-prof-unwinding-info",
715
            "",
716
            V8Option{},
717
            kAllowedInEnvironment);
718
5594
  AddOption("--stack-trace-limit", "", V8Option{}, kAllowedInEnvironment);
719
5594
  AddOption("--disallow-code-generation-from-strings",
720
            "disallow eval and friends",
721
            V8Option{},
722
            kAllowedInEnvironment);
723
5594
  AddOption("--huge-max-old-generation-size",
724
             "increase default maximum heap size on machines with 16GB memory "
725
             "or more",
726
             V8Option{},
727
             kAllowedInEnvironment);
728
5594
  AddOption("--jitless",
729
             "disable runtime allocation of executable memory",
730
             V8Option{},
731
             kAllowedInEnvironment);
732
5594
  AddOption("--report-uncaught-exception",
733
            "generate diagnostic report on uncaught exceptions",
734
            &PerIsolateOptions::report_uncaught_exception,
735
            kAllowedInEnvironment);
736
5594
  AddOption("--report-on-signal",
737
            "generate diagnostic report upon receiving signals",
738
            &PerIsolateOptions::report_on_signal,
739
            kAllowedInEnvironment);
740
5594
  AddOption("--report-signal",
741
            "causes diagnostic report to be produced on provided signal,"
742
            " unsupported in Windows. (default: SIGUSR2)",
743
            &PerIsolateOptions::report_signal,
744
            kAllowedInEnvironment);
745
5594
  Implies("--report-signal", "--report-on-signal");
746
747
5594
  AddOption(
748
      "--experimental-top-level-await", "", NoOp{}, kAllowedInEnvironment);
749
750
5594
  AddOption("--experimental-shadow-realm",
751
            "",
752
            &PerIsolateOptions::experimental_shadow_realm,
753
            kAllowedInEnvironment);
754
5594
  AddOption("--harmony-shadow-realm", "", V8Option{});
755
5594
  Implies("--experimental-shadow-realm", "--harmony-shadow-realm");
756
5594
  Implies("--harmony-shadow-realm", "--experimental-shadow-realm");
757
5594
  ImpliesNot("--no-harmony-shadow-realm", "--experimental-shadow-realm");
758
759
5594
  Insert(eop, &PerIsolateOptions::get_per_env_options);
760
5594
}
761
762
5594
PerProcessOptionsParser::PerProcessOptionsParser(
763
5594
  const PerIsolateOptionsParser& iop) {
764
5594
  AddOption("--title",
765
            "the process title to use on startup",
766
            &PerProcessOptions::title,
767
            kAllowedInEnvironment);
768
5594
  AddOption("--trace-event-categories",
769
            "comma separated list of trace event categories to record",
770
            &PerProcessOptions::trace_event_categories,
771
            kAllowedInEnvironment);
772
5594
  AddOption("--trace-event-file-pattern",
773
            "Template string specifying the filepath for the trace-events "
774
            "data, it supports ${rotation} and ${pid}.",
775
            &PerProcessOptions::trace_event_file_pattern,
776
            kAllowedInEnvironment);
777
16782
  AddAlias("--trace-events-enabled", {
778
11188
    "--trace-event-categories", "v8,node,node.async_hooks" });
779
5594
  AddOption("--v8-pool-size",
780
            "set V8's thread pool size",
781
            &PerProcessOptions::v8_thread_pool_size,
782
            kAllowedInEnvironment);
783
5594
  AddOption("--zero-fill-buffers",
784
            "automatically zero-fill all newly allocated Buffer and "
785
            "SlowBuffer instances",
786
            &PerProcessOptions::zero_fill_all_buffers,
787
            kAllowedInEnvironment);
788
5594
  AddOption("--debug-arraybuffer-allocations",
789
            "", /* undocumented, only for debugging */
790
            &PerProcessOptions::debug_arraybuffer_allocations,
791
            kAllowedInEnvironment);
792
5594
  AddOption("--disable-proto",
793
            "disable Object.prototype.__proto__",
794
            &PerProcessOptions::disable_proto,
795
            kAllowedInEnvironment);
796
5594
  AddOption("--build-snapshot",
797
            "Generate a snapshot blob when the process exits."
798
            " Currently only supported in the node_mksnapshot binary.",
799
            &PerProcessOptions::build_snapshot,
800
            kDisallowedInEnvironment);
801
5594
  AddOption("--node-snapshot",
802
            "",  // It's a debug-only option.
803
            &PerProcessOptions::node_snapshot,
804
            kAllowedInEnvironment);
805
5594
  AddOption("--snapshot-blob",
806
            "Path to the snapshot blob that's either the result of snapshot"
807
            "building, or the blob that is used to restore the application "
808
            "state",
809
            &PerProcessOptions::snapshot_blob,
810
            kAllowedInEnvironment);
811
812
  // 12.x renamed this inadvertently, so alias it for consistency within the
813
  // release line, while using the original name for consistency with older
814
  // release lines.
815
5594
  AddOption("--security-revert", "", &PerProcessOptions::security_reverts);
816
5594
  AddAlias("--security-reverts", "--security-revert");
817
5594
  AddOption("--completion-bash",
818
            "print source-able bash completion script",
819
            &PerProcessOptions::print_bash_completion);
820
5594
  AddOption("--help",
821
            "print node command line options",
822
            &PerProcessOptions::print_help);
823
5594
  AddAlias("-h", "--help");
824
5594
  AddOption(
825
      "--version", "print Node.js version", &PerProcessOptions::print_version);
826
5594
  AddAlias("-v", "--version");
827
5594
  AddOption("--v8-options",
828
            "print V8 command line options",
829
            &PerProcessOptions::print_v8_help);
830
5594
  AddOption("--report-compact",
831
            "output compact single-line JSON",
832
            &PerProcessOptions::report_compact,
833
            kAllowedInEnvironment);
834
5594
  AddOption("--report-dir",
835
            "define custom report pathname."
836
            " (default: current working directory)",
837
            &PerProcessOptions::report_directory,
838
            kAllowedInEnvironment);
839
5594
  AddAlias("--report-directory", "--report-dir");
840
5594
  AddOption("--report-filename",
841
            "define custom report file name."
842
            " (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)",
843
            &PerProcessOptions::report_filename,
844
            kAllowedInEnvironment);
845
5594
  AddOption("--report-on-fatalerror",
846
              "generate diagnostic report on fatal (internal) errors",
847
              &PerProcessOptions::report_on_fatalerror,
848
              kAllowedInEnvironment);
849
850
#ifdef NODE_HAVE_I18N_SUPPORT
851
5594
  AddOption("--icu-data-dir",
852
            "set ICU data load path to dir (overrides NODE_ICU_DATA)"
853
#ifndef NODE_HAVE_SMALL_ICU
854
            " (note: linked-in ICU data is present)"
855
#endif
856
            ,
857
            &PerProcessOptions::icu_data_dir,
858
            kAllowedInEnvironment);
859
#endif
860
861
#if HAVE_OPENSSL
862
5594
  AddOption("--openssl-config",
863
            "load OpenSSL configuration from the specified file "
864
            "(overrides OPENSSL_CONF)",
865
            &PerProcessOptions::openssl_config,
866
            kAllowedInEnvironment);
867
5594
  AddOption("--tls-cipher-list",
868
            "use an alternative default TLS cipher list",
869
            &PerProcessOptions::tls_cipher_list,
870
            kAllowedInEnvironment);
871
5594
  AddOption("--use-openssl-ca",
872
            "use OpenSSL's default CA store"
873
#if defined(NODE_OPENSSL_CERT_STORE)
874
            " (default)"
875
#endif
876
            ,
877
            &PerProcessOptions::use_openssl_ca,
878
            kAllowedInEnvironment);
879
5594
  AddOption("--use-bundled-ca",
880
            "use bundled CA store"
881
#if !defined(NODE_OPENSSL_CERT_STORE)
882
            " (default)"
883
#endif
884
            ,
885
            &PerProcessOptions::use_bundled_ca,
886
            kAllowedInEnvironment);
887
  // Similar to [has_eval_string] above, except that the separation between
888
  // this and use_openssl_ca only exists for option validation after parsing.
889
  // This is not ideal.
890
5594
  AddOption("[ssl_openssl_cert_store]",
891
            "",
892
            &PerProcessOptions::ssl_openssl_cert_store);
893
5594
  Implies("--use-openssl-ca", "[ssl_openssl_cert_store]");
894
5594
  ImpliesNot("--use-bundled-ca", "[ssl_openssl_cert_store]");
895
5594
  AddOption("--enable-fips",
896
            "enable FIPS crypto at startup",
897
            &PerProcessOptions::enable_fips_crypto,
898
            kAllowedInEnvironment);
899
5594
  AddOption("--force-fips",
900
            "force FIPS crypto (cannot be disabled)",
901
            &PerProcessOptions::force_fips_crypto,
902
            kAllowedInEnvironment);
903
5594
  AddOption("--secure-heap",
904
            "total size of the OpenSSL secure heap",
905
            &PerProcessOptions::secure_heap,
906
            kAllowedInEnvironment);
907
5594
  AddOption("--secure-heap-min",
908
            "minimum allocation size from the OpenSSL secure heap",
909
            &PerProcessOptions::secure_heap_min,
910
            kAllowedInEnvironment);
911
#endif  // HAVE_OPENSSL
912
#if OPENSSL_VERSION_MAJOR >= 3
913
5594
  AddOption("--openssl-legacy-provider",
914
            "enable OpenSSL 3.0 legacy provider",
915
            &PerProcessOptions::openssl_legacy_provider,
916
            kAllowedInEnvironment);
917
5594
  AddOption("--openssl-shared-config",
918
            "enable OpenSSL shared configuration",
919
            &PerProcessOptions::openssl_shared_config,
920
            kAllowedInEnvironment);
921
922
#endif  // OPENSSL_VERSION_MAJOR
923
5594
  AddOption("--use-largepages",
924
            "Map the Node.js static code to large pages. Options are "
925
            "'off' (the default value, meaning do not map), "
926
            "'on' (map and ignore failure, reporting it to stderr), "
927
            "or 'silent' (map and silently ignore failure)",
928
            &PerProcessOptions::use_largepages,
929
            kAllowedInEnvironment);
930
931
5594
  AddOption("--trace-sigint",
932
            "enable printing JavaScript stacktrace on SIGINT",
933
            &PerProcessOptions::trace_sigint,
934
            kAllowedInEnvironment);
935
936
5594
  Insert(iop, &PerProcessOptions::get_per_isolate_options);
937
938
5594
  AddOption("--node-memory-debug",
939
            "Run with extra debug checks for memory leaks in Node.js itself",
940
            NoOp{}, kAllowedInEnvironment);
941
5594
  Implies("--node-memory-debug", "--debug-arraybuffer-allocations");
942
5594
  Implies("--node-memory-debug", "--verify-base-objects");
943
5594
}
944
945
165
inline std::string RemoveBrackets(const std::string& host) {
946


165
  if (!host.empty() && host.front() == '[' && host.back() == ']')
947
8
    return host.substr(1, host.size() - 2);
948
  else
949
157
    return host;
950
}
951
952
145
inline int ParseAndValidatePort(const std::string& port,
953
                                std::vector<std::string>* errors) {
954
  char* endptr;
955
145
  errno = 0;
956
  const unsigned long result =                 // NOLINT(runtime/int)
957
145
    strtoul(port.c_str(), &endptr, 10);
958

145
  if (errno != 0 || *endptr != '\0'||
959

145
      (result != 0 && result < 1024) || result > 65535) {
960
    errors->push_back(" must be 0 or in range 1024 to 65535.");
961
  }
962
145
  return static_cast<int>(result);
963
}
964
965
145
HostPort SplitHostPort(const std::string& arg,
966
                      std::vector<std::string>* errors) {
967
  // remove_brackets only works if no port is specified
968
  // so if it has an effect only an IPv6 address was specified.
969
290
  std::string host = RemoveBrackets(arg);
970
145
  if (host.length() < arg.length())
971
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
972
973
145
  size_t colon = arg.rfind(':');
974
145
  if (colon == std::string::npos) {
975
    // Either a port number or a host name.  Assume that
976
    // if it's not all decimal digits, it's a host name.
977
598
    for (char c : arg) {
978

473
      if (c < '0' || c > '9') {
979
        return HostPort{arg, DebugOptions::kDefaultInspectorPort};
980
      }
981
    }
982
125
    return HostPort { "", ParseAndValidatePort(arg, errors) };
983
  }
984
  // Host and port found:
985
40
  return HostPort { RemoveBrackets(arg.substr(0, colon)),
986
20
                    ParseAndValidatePort(arg.substr(colon + 1), errors) };
987
}
988
989
1
std::string GetBashCompletion() {
990
2
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
991
1
  const auto& parser = _ppop_instance;
992
993
2
  std::ostringstream out;
994
995
  out << "_node_complete() {\n"
996
         "  local cur_word options\n"
997
         "  cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n"
998
         "  if [[ \"${cur_word}\" == -* ]] ; then\n"
999
1
         "    COMPREPLY=( $(compgen -W '";
1000
1001
145
  for (const auto& item : parser.options_) {
1002
144
    if (item.first[0] != '[') {
1003
141
      out << item.first << " ";
1004
    }
1005
  }
1006
23
  for (const auto& item : parser.aliases_) {
1007
22
    if (item.first[0] != '[') {
1008
22
      out << item.first << " ";
1009
    }
1010
  }
1011
1
  if (parser.aliases_.size() > 0) {
1012
1
    out.seekp(-1, out.cur);  // Strip the trailing space
1013
  }
1014
1015
  out << "' -- \"${cur_word}\") )\n"
1016
         "    return 0\n"
1017
         "  else\n"
1018
         "    COMPREPLY=( $(compgen -f \"${cur_word}\") )\n"
1019
         "    return 0\n"
1020
         "  fi\n"
1021
         "}\n"
1022
         "complete -o filenames -o nospace -o bashdefault "
1023
1
         "-F _node_complete node node_g";
1024
1
  return out.str();
1025
}
1026
1027
// Return a map containing all the options and their metadata as well
1028
// as the aliases
1029
void GetCLIOptions(const FunctionCallbackInfo<Value>& args) {
1030
6926
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
1031
6926
  Environment* env = Environment::GetCurrent(args);
1032
6926
  if (!env->has_run_bootstrapping_code()) {
1033
    // No code because this is an assertion.
1034
    return env->ThrowError(
1035
        "Should not query options before bootstrapping is done");
1036
  }
1037
6926
  env->set_has_serialized_options(true);
1038
1039
6926
  Isolate* isolate = env->isolate();
1040
6926
  Local<Context> context = env->context();
1041
1042
  // Temporarily act as if the current Environment's/IsolateData's options were
1043
  // the default options, i.e. like they are the ones we'd access for global
1044
  // options parsing, so that all options are available from the main parser.
1045
6926
  auto original_per_isolate = per_process::cli_options->per_isolate;
1046
6926
  per_process::cli_options->per_isolate = env->isolate_data()->options();
1047
6926
  auto original_per_env = per_process::cli_options->per_isolate->per_env;
1048
6926
  per_process::cli_options->per_isolate->per_env = env->options();
1049
6926
  auto on_scope_leave = OnScopeLeave([&]() {
1050
6926
    per_process::cli_options->per_isolate->per_env = original_per_env;
1051
6926
    per_process::cli_options->per_isolate = original_per_isolate;
1052
6926
  });
1053
1054
6926
  Local<Map> options = Map::New(isolate);
1055
6926
  if (options
1056
13852
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1057
6926
          .IsNothing()) {
1058
    return;
1059
  }
1060
1061
1004270
  for (const auto& item : _ppop_instance.options_) {
1062
    Local<Value> value;
1063
997344
    const auto& option_info = item.second;
1064
997344
    auto field = option_info.field;
1065
997344
    PerProcessOptions* opts = per_process::cli_options.get();
1066


997344
    switch (option_info.type) {
1067
159298
      case kNoOp:
1068
      case kV8Option:
1069
        // Special case for --abort-on-uncaught-exception which is also
1070
        // respected by Node.js internals
1071
159298
        if (item.first == "--abort-on-uncaught-exception") {
1072
6926
          value = Boolean::New(
1073
6926
            isolate, original_per_env->abort_on_uncaught_exception);
1074
        } else {
1075
152372
          value = Undefined(isolate);
1076
        }
1077
159298
        break;
1078
547154
      case kBoolean:
1079
1094308
        value = Boolean::New(isolate,
1080
1094308
                             *_ppop_instance.Lookup<bool>(field, opts));
1081
547154
        break;
1082
27704
      case kInteger:
1083
55408
        value = Number::New(
1084
            isolate,
1085
55408
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1086
27704
        break;
1087
20778
      case kUInteger:
1088
41556
        value = Number::New(
1089
            isolate,
1090
41556
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1091
20778
        break;
1092
187002
      case kString:
1093
374004
        if (!ToV8Value(context,
1094
374004
                       *_ppop_instance.Lookup<std::string>(field, opts))
1095
187002
                 .ToLocal(&value)) {
1096
          return;
1097
        }
1098
187002
        break;
1099
48482
      case kStringList:
1100
96964
        if (!ToV8Value(context,
1101
96964
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1102
48482
                 .ToLocal(&value)) {
1103
          return;
1104
        }
1105
48482
        break;
1106
6926
      case kHostPort: {
1107
        const HostPort& host_port =
1108
6926
          *_ppop_instance.Lookup<HostPort>(field, opts);
1109
6926
        Local<Object> obj = Object::New(isolate);
1110
        Local<Value> host;
1111
6926
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1112

34630
            obj->Set(context, env->host_string(), host).IsNothing() ||
1113
6926
            obj->Set(context,
1114
                     env->port_string(),
1115
27704
                     Integer::New(isolate, host_port.port()))
1116
6926
                .IsNothing()) {
1117
          return;
1118
        }
1119
6926
        value = obj;
1120
6926
        break;
1121
      }
1122
      default:
1123
        UNREACHABLE();
1124
    }
1125
997344
    CHECK(!value.IsEmpty());
1126
1127
997344
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1128
997344
    Local<Object> info = Object::New(isolate);
1129
    Local<Value> help_text;
1130
997344
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1131
1994688
        !info->Set(context, env->help_text_string(), help_text)
1132

1994688
             .FromMaybe(false) ||
1133
1994688
        !info->Set(context,
1134
                   env->env_var_settings_string(),
1135
                   Integer::New(isolate,
1136
2992032
                                static_cast<int>(option_info.env_setting)))
1137

1994688
             .FromMaybe(false) ||
1138
1994688
        !info->Set(context,
1139
                   env->type_string(),
1140
2992032
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1141

1994688
             .FromMaybe(false) ||
1142
1994688
        !info->Set(context,
1143
                   env->default_is_true_string(),
1144
2992032
                   Boolean::New(isolate, option_info.default_is_true))
1145

1994688
             .FromMaybe(false) ||
1146

4986720
        info->Set(context, env->value_string(), value).IsNothing() ||
1147

2992032
        options->Set(context, name, info).IsEmpty()) {
1148
      return;
1149
    }
1150
  }
1151
1152
  Local<Value> aliases;
1153
13852
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1154
1155
6926
  if (aliases.As<Object>()
1156
13852
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1157
6926
          .IsNothing()) {
1158
    return;
1159
  }
1160
1161
6926
  Local<Object> ret = Object::New(isolate);
1162
27704
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1163

27704
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1164
    return;
1165
  }
1166
1167
13852
  args.GetReturnValue().Set(ret);
1168
}
1169
1170
6256
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1171
6256
  Environment* env = Environment::GetCurrent(args);
1172
6256
  if (!env->has_run_bootstrapping_code()) {
1173
    // No code because this is an assertion.
1174
    return env->ThrowError(
1175
        "Should not query options before bootstrapping is done");
1176
  }
1177
6256
  Isolate* isolate = args.GetIsolate();
1178
6256
  Local<Context> context = env->context();
1179
6256
  Local<Object> ret = Object::New(isolate);
1180
1181
12512
  if (ret->Set(context,
1182
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1183
18768
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1184
6256
      .IsNothing()) return;
1185
1186
12512
  if (ret->Set(context,
1187
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1188
18768
           Boolean::New(isolate, env->no_global_search_paths()))
1189
6256
      .IsNothing()) return;
1190
1191
12512
  args.GetReturnValue().Set(ret);
1192
}
1193
1194
787
void Initialize(Local<Object> target,
1195
                Local<Value> unused,
1196
                Local<Context> context,
1197
                void* priv) {
1198
787
  Environment* env = Environment::GetCurrent(context);
1199
787
  Isolate* isolate = env->isolate();
1200
787
  SetMethodNoSideEffect(context, target, "getCLIOptions", GetCLIOptions);
1201
787
  SetMethodNoSideEffect(
1202
      context, target, "getEmbedderOptions", GetEmbedderOptions);
1203
1204
787
  Local<Object> env_settings = Object::New(isolate);
1205
2361
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1206
2361
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1207
  target
1208
787
      ->Set(
1209
1574
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1210
      .Check();
1211
1212
787
  Local<Object> types = Object::New(isolate);
1213
2361
  NODE_DEFINE_CONSTANT(types, kNoOp);
1214
2361
  NODE_DEFINE_CONSTANT(types, kV8Option);
1215
2361
  NODE_DEFINE_CONSTANT(types, kBoolean);
1216
2361
  NODE_DEFINE_CONSTANT(types, kInteger);
1217
2361
  NODE_DEFINE_CONSTANT(types, kUInteger);
1218
2361
  NODE_DEFINE_CONSTANT(types, kString);
1219
2361
  NODE_DEFINE_CONSTANT(types, kHostPort);
1220
2361
  NODE_DEFINE_CONSTANT(types, kStringList);
1221
1574
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1222
      .Check();
1223
787
}
1224
1225
5524
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1226
5524
  registry->Register(GetCLIOptions);
1227
5524
  registry->Register(GetEmbedderOptions);
1228
5524
}
1229
}  // namespace options_parser
1230
1231
5594
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1232
5594
  HandleEnvOptions(env_options, [](const char* name) {
1233
22376
    std::string text;
1234

22376
    return credentials::SafeGetenv(name, &text) ? text : "";
1235
  });
1236
5594
}
1237
1238
5891
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1239
                      std::function<std::string(const char*)> opt_getter) {
1240
5891
  env_options->pending_deprecation =
1241
11782
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1242
1243
5891
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1244
1245
5891
  env_options->preserve_symlinks_main =
1246
11782
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1247
1248
5891
  if (env_options->redirect_warnings.empty())
1249
5891
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1250
5891
}
1251
1252
5769
std::vector<std::string> ParseNodeOptionsEnvVar(
1253
    const std::string& node_options, std::vector<std::string>* errors) {
1254
5769
  std::vector<std::string> env_argv;
1255
1256
5769
  bool is_in_string = false;
1257
5769
  bool will_start_new_arg = true;
1258
8373
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1259
2604
    char c = node_options.at(index);
1260
1261
    // Backslashes escape the following character
1262

2604
    if (c == '\\' && is_in_string) {
1263
      if (index + 1 == node_options.size()) {
1264
        errors->push_back("invalid value for NODE_OPTIONS "
1265
                          "(invalid escape)\n");
1266
        return env_argv;
1267
      } else {
1268
        c = node_options.at(++index);
1269
      }
1270

2604
    } else if (c == ' ' && !is_in_string) {
1271
32
      will_start_new_arg = true;
1272
32
      continue;
1273
2572
    } else if (c == '"') {
1274
4
      is_in_string = !is_in_string;
1275
4
      continue;
1276
    }
1277
1278
2568
    if (will_start_new_arg) {
1279
108
      env_argv.emplace_back(std::string(1, c));
1280
108
      will_start_new_arg = false;
1281
    } else {
1282
2460
      env_argv.back() += c;
1283
    }
1284
  }
1285
1286
5769
  if (is_in_string) {
1287
    errors->push_back("invalid value for NODE_OPTIONS "
1288
                      "(unterminated string)\n");
1289
  }
1290
5769
  return env_argv;
1291
}
1292
}  // namespace node
1293
1294
5594
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1295
5524
NODE_MODULE_EXTERNAL_REFERENCE(options,
1296
                               node::options_parser::RegisterExternalReferences)