GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 483 516 93.6 %
Date: 2022-09-07 04:19:57 Branches: 220 284 77.5 %

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

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

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

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

11532
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
107
1
    errors->push_back("--policy-integrity cannot be empty");
108
  }
109
110
11532
  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
11532
  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

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

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

11532
  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
11532
  if (heap_snapshot_near_heap_limit < 0) {
143
    errors->push_back("--heapsnapshot-near-heap-limit must not be negative");
144
  }
145
146
11532
  if (test_runner) {
147
15
    if (syntax_check_only) {
148
1
      errors->push_back("either --test or --check can be used, not both");
149
    }
150
151
15
    if (has_eval_string) {
152
2
      errors->push_back("either --test or --eval can be used, not both");
153
    }
154
155
15
    if (force_repl) {
156
1
      errors->push_back("either --test or --interactive can be used, not both");
157
    }
158
159
15
    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
15
    if (debug_options_.inspector_enabled) {
165
2
      errors->push_back("the inspector cannot be used with --test");
166
    }
167
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_TEST_RUNNER
168
    debug_options_.allow_attaching_debugger = false;
169
#endif
170
  }
171
172
11532
  if (watch_mode) {
173
10
    if (syntax_check_only) {
174
      errors->push_back("either --watch or --check can be used, not both");
175
    }
176
177
10
    if (has_eval_string) {
178
      errors->push_back("either --watch or --eval can be used, not both");
179
    }
180
181
10
    if (force_repl) {
182
      errors->push_back("either --watch or --interactive "
183
                        "can be used, not both");
184
    }
185
186
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_WATCH_MODE
187
    debug_options_.allow_attaching_debugger = false;
188
#endif
189
  }
190
191
#if HAVE_INSPECTOR
192
11532
  if (!cpu_prof) {
193
11521
    if (!cpu_prof_name.empty()) {
194
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
195
    }
196
11521
    if (!cpu_prof_dir.empty()) {
197
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
198
    }
199
    // We can't catch the case where the value passed is the default value,
200
    // then the option just becomes a noop which is fine.
201
11521
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
202
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
203
    }
204
  }
205
206


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


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


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

100
  if (errno != 0 || *endptr != '\0'||
969

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

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


980837
    switch (option_info.type) {
1077
150898
      case kNoOp:
1078
      case kV8Option:
1079
        // Special case for --abort-on-uncaught-exception which is also
1080
        // respected by Node.js internals
1081
150898
        if (item.first == "--abort-on-uncaught-exception") {
1082
6859
          value = Boolean::New(
1083
6859
            isolate, original_per_env->abort_on_uncaught_exception);
1084
        } else {
1085
144039
          value = Undefined(isolate);
1086
        }
1087
150898
        break;
1088
541861
      case kBoolean:
1089
1083722
        value = Boolean::New(isolate,
1090
1083722
                             *_ppop_instance.Lookup<bool>(field, opts));
1091
541861
        break;
1092
27436
      case kInteger:
1093
54872
        value = Number::New(
1094
            isolate,
1095
54872
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1096
27436
        break;
1097
20577
      case kUInteger:
1098
41154
        value = Number::New(
1099
            isolate,
1100
41154
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1101
20577
        break;
1102
192052
      case kString:
1103
384104
        if (!ToV8Value(context,
1104
384104
                       *_ppop_instance.Lookup<std::string>(field, opts))
1105
192052
                 .ToLocal(&value)) {
1106
          return;
1107
        }
1108
192052
        break;
1109
41154
      case kStringList:
1110
82308
        if (!ToV8Value(context,
1111
82308
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1112
41154
                 .ToLocal(&value)) {
1113
          return;
1114
        }
1115
41154
        break;
1116
6859
      case kHostPort: {
1117
        const HostPort& host_port =
1118
6859
          *_ppop_instance.Lookup<HostPort>(field, opts);
1119
6859
        Local<Object> obj = Object::New(isolate);
1120
        Local<Value> host;
1121
6859
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1122

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

1961674
             .FromMaybe(false) ||
1143
1961674
        !info->Set(context,
1144
                   env->env_var_settings_string(),
1145
                   Integer::New(isolate,
1146
2942511
                                static_cast<int>(option_info.env_setting)))
1147

1961674
             .FromMaybe(false) ||
1148
1961674
        !info->Set(context,
1149
                   env->type_string(),
1150
2942511
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1151

1961674
             .FromMaybe(false) ||
1152
1961674
        !info->Set(context,
1153
                   env->default_is_true_string(),
1154
2942511
                   Boolean::New(isolate, option_info.default_is_true))
1155

1961674
             .FromMaybe(false) ||
1156

4904185
        info->Set(context, env->value_string(), value).IsNothing() ||
1157

2942511
        options->Set(context, name, info).IsEmpty()) {
1158
      return;
1159
    }
1160
  }
1161
1162
  Local<Value> aliases;
1163
13718
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1164
1165
6859
  if (aliases.As<Object>()
1166
13718
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1167
6859
          .IsNothing()) {
1168
    return;
1169
  }
1170
1171
6859
  Local<Object> ret = Object::New(isolate);
1172
27436
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1173

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

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

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

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