GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 481 514 93.6 %
Date: 2022-09-11 04:22:34 Branches: 218 282 77.3 %

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
11611
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
11611
  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
23222
      SplitString(inspect_publish_uid_string, ',');
53
11611
  inspect_publish_uid.console = false;
54
11611
  inspect_publish_uid.http = false;
55
34831
  for (const std::string& destination : destinations) {
56
23220
    if (destination == "stderr") {
57
11610
      inspect_publish_uid.console = true;
58
11610
    } else if (destination == "http") {
59
11610
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
11611
}
66
67
11030
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

11030
  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
11030
  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
11032
  if (use_largepages != "off" &&
90

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

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

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

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

9
    if (experimental_specifier_resolution != "node" &&
118
        experimental_specifier_resolution != "explicit") {
119
      errors->push_back(
120
        "invalid value for --experimental-specifier-resolution");
121
    }
122
  }
123
124

11611
  if (syntax_check_only && has_eval_string) {
125
4
    errors->push_back("either --check or --eval can be used, not both");
126
  }
127
128
11631
  if (!unhandled_rejections.empty() &&
129
39
      unhandled_rejections != "warn-with-error-code" &&
130
36
      unhandled_rejections != "throw" &&
131
32
      unhandled_rejections != "strict" &&
132

11646
      unhandled_rejections != "warn" &&
133
10
      unhandled_rejections != "none") {
134
1
    errors->push_back("invalid value for --unhandled-rejections");
135
  }
136
137

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


11611
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
204
1
      cpu_prof_dir = diagnostic_dir;
205
    }
206
207
11611
  if (!heap_prof) {
208
11600
    if (!heap_prof_name.empty()) {
209
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
210
    }
211
11600
    if (!heap_prof_dir.empty()) {
212
1
      errors->push_back("--heap-prof-dir must be used with --heap-prof");
213
    }
214
    // We can't catch the case where the value passed is the default value,
215
    // then the option just becomes a noop which is fine.
216
11600
    if (heap_prof_interval != kDefaultHeapProfInterval) {
217
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
218
    }
219
  }
220
221


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


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

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

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

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


987558
    switch (option_info.type) {
1074
151932
      case kNoOp:
1075
      case kV8Option:
1076
        // Special case for --abort-on-uncaught-exception which is also
1077
        // respected by Node.js internals
1078
151932
        if (item.first == "--abort-on-uncaught-exception") {
1079
6906
          value = Boolean::New(
1080
6906
            isolate, original_per_env->abort_on_uncaught_exception);
1081
        } else {
1082
145026
          value = Undefined(isolate);
1083
        }
1084
151932
        break;
1085
545574
      case kBoolean:
1086
1091148
        value = Boolean::New(isolate,
1087
1091148
                             *_ppop_instance.Lookup<bool>(field, opts));
1088
545574
        break;
1089
27624
      case kInteger:
1090
55248
        value = Number::New(
1091
            isolate,
1092
55248
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1093
27624
        break;
1094
20718
      case kUInteger:
1095
41436
        value = Number::New(
1096
            isolate,
1097
41436
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1098
20718
        break;
1099
193368
      case kString:
1100
386736
        if (!ToV8Value(context,
1101
386736
                       *_ppop_instance.Lookup<std::string>(field, opts))
1102
193368
                 .ToLocal(&value)) {
1103
          return;
1104
        }
1105
193368
        break;
1106
41436
      case kStringList:
1107
82872
        if (!ToV8Value(context,
1108
82872
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1109
41436
                 .ToLocal(&value)) {
1110
          return;
1111
        }
1112
41436
        break;
1113
6906
      case kHostPort: {
1114
        const HostPort& host_port =
1115
6906
          *_ppop_instance.Lookup<HostPort>(field, opts);
1116
6906
        Local<Object> obj = Object::New(isolate);
1117
        Local<Value> host;
1118
6906
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1119

34530
            obj->Set(context, env->host_string(), host).IsNothing() ||
1120
6906
            obj->Set(context,
1121
                     env->port_string(),
1122
27624
                     Integer::New(isolate, host_port.port()))
1123
6906
                .IsNothing()) {
1124
          return;
1125
        }
1126
6906
        value = obj;
1127
6906
        break;
1128
      }
1129
      default:
1130
        UNREACHABLE();
1131
    }
1132
987558
    CHECK(!value.IsEmpty());
1133
1134
987558
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1135
987558
    Local<Object> info = Object::New(isolate);
1136
    Local<Value> help_text;
1137
987558
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1138
1975116
        !info->Set(context, env->help_text_string(), help_text)
1139

1975116
             .FromMaybe(false) ||
1140
1975116
        !info->Set(context,
1141
                   env->env_var_settings_string(),
1142
                   Integer::New(isolate,
1143
2962674
                                static_cast<int>(option_info.env_setting)))
1144

1975116
             .FromMaybe(false) ||
1145
1975116
        !info->Set(context,
1146
                   env->type_string(),
1147
2962674
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1148

1975116
             .FromMaybe(false) ||
1149
1975116
        !info->Set(context,
1150
                   env->default_is_true_string(),
1151
2962674
                   Boolean::New(isolate, option_info.default_is_true))
1152

1975116
             .FromMaybe(false) ||
1153

4937790
        info->Set(context, env->value_string(), value).IsNothing() ||
1154

2962674
        options->Set(context, name, info).IsEmpty()) {
1155
      return;
1156
    }
1157
  }
1158
1159
  Local<Value> aliases;
1160
13812
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1161
1162
6906
  if (aliases.As<Object>()
1163
13812
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1164
6906
          .IsNothing()) {
1165
    return;
1166
  }
1167
1168
6906
  Local<Object> ret = Object::New(isolate);
1169
27624
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1170

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

22336
    return credentials::SafeGetenv(name, &text) ? text : "";
1242
  });
1243
5584
}
1244
1245
5877
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1246
                      std::function<std::string(const char*)> opt_getter) {
1247
5877
  env_options->pending_deprecation =
1248
11754
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1249
1250
5877
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1251
1252
5877
  env_options->preserve_symlinks_main =
1253
11754
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1254
1255
5877
  if (env_options->redirect_warnings.empty())
1256
5877
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1257
5877
}
1258
1259
5755
std::vector<std::string> ParseNodeOptionsEnvVar(
1260
    const std::string& node_options, std::vector<std::string>* errors) {
1261
5755
  std::vector<std::string> env_argv;
1262
1263
5755
  bool is_in_string = false;
1264
5755
  bool will_start_new_arg = true;
1265
8359
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1266
2604
    char c = node_options.at(index);
1267
1268
    // Backslashes escape the following character
1269

2604
    if (c == '\\' && is_in_string) {
1270
      if (index + 1 == node_options.size()) {
1271
        errors->push_back("invalid value for NODE_OPTIONS "
1272
                          "(invalid escape)\n");
1273
        return env_argv;
1274
      } else {
1275
        c = node_options.at(++index);
1276
      }
1277

2604
    } else if (c == ' ' && !is_in_string) {
1278
32
      will_start_new_arg = true;
1279
32
      continue;
1280
2572
    } else if (c == '"') {
1281
4
      is_in_string = !is_in_string;
1282
4
      continue;
1283
    }
1284
1285
2568
    if (will_start_new_arg) {
1286
108
      env_argv.emplace_back(std::string(1, c));
1287
108
      will_start_new_arg = false;
1288
    } else {
1289
2460
      env_argv.back() += c;
1290
    }
1291
  }
1292
1293
5755
  if (is_in_string) {
1294
    errors->push_back("invalid value for NODE_OPTIONS "
1295
                      "(unterminated string)\n");
1296
  }
1297
5755
  return env_argv;
1298
}
1299
}  // namespace node
1300
1301
5584
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1302
5514
NODE_MODULE_EXTERNAL_REFERENCE(options,
1303
                               node::options_parser::RegisterExternalReferences)