GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 474 503 94.2 %
Date: 2022-08-06 04:16:36 Branches: 214 274 78.1 %

Line Branch Exec Source
1
#include "node_options.h"  // NOLINT(build/include_inline)
2
#include "node_options-inl.h"
3
4
#include "env-inl.h"
5
#include "node_binding.h"
6
#include "node_external_reference.h"
7
#include "node_internals.h"
8
#if HAVE_OPENSSL
9
#include "openssl/opensslv.h"
10
#endif
11
12
#include <errno.h>
13
#include <sstream>
14
#include <limits>
15
#include <algorithm>
16
#include <cstdlib>  // strtoul, errno
17
18
using v8::Boolean;
19
using v8::Context;
20
using v8::FunctionCallbackInfo;
21
using v8::Integer;
22
using v8::Isolate;
23
using v8::Local;
24
using v8::Map;
25
using v8::Number;
26
using v8::Object;
27
using v8::Undefined;
28
using v8::Value;
29
30
namespace node {
31
32
namespace per_process {
33
Mutex cli_options_mutex;
34
std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
35
}  // namespace per_process
36
37
11234
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
11234
  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
22468
      SplitString(inspect_publish_uid_string, ',');
53
11234
  inspect_publish_uid.console = false;
54
11234
  inspect_publish_uid.http = false;
55
33700
  for (const std::string& destination : destinations) {
56
22466
    if (destination == "stderr") {
57
11233
      inspect_publish_uid.console = true;
58
11233
    } else if (destination == "http") {
59
11233
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
11234
}
66
67
10650
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

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

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

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

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

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

11234
  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
11234
  if (heap_snapshot_near_heap_limit < 0) {
143
    errors->push_back("--heap-snapshot-near-heap-limit must not be negative");
144
  }
145
146
11234
  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 (debug_options_.inspector_enabled) {
160
2
      errors->push_back("the inspector cannot be used with --test");
161
    }
162
  }
163
164
#if HAVE_INSPECTOR
165
11234
  if (!cpu_prof) {
166
11223
    if (!cpu_prof_name.empty()) {
167
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
168
    }
169
11223
    if (!cpu_prof_dir.empty()) {
170
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
171
    }
172
    // We can't catch the case where the value passed is the default value,
173
    // then the option just becomes a noop which is fine.
174
11223
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
175
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
176
    }
177
  }
178
179


11234
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
180
1
      cpu_prof_dir = diagnostic_dir;
181
    }
182
183
11234
  if (!heap_prof) {
184
11223
    if (!heap_prof_name.empty()) {
185
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
186
    }
187
11223
    if (!heap_prof_dir.empty()) {
188
1
      errors->push_back("--heap-prof-dir must be used with --heap-prof");
189
    }
190
    // We can't catch the case where the value passed is the default value,
191
    // then the option just becomes a noop which is fine.
192
11223
    if (heap_prof_interval != kDefaultHeapProfInterval) {
193
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
194
    }
195
  }
196
197


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
917
4
    return host.substr(1, host.size() - 2);
918
  else
919
108
    return host;
920
}
921
922
100
inline int ParseAndValidatePort(const std::string& port,
923
                                std::vector<std::string>* errors) {
924
  char* endptr;
925
100
  errno = 0;
926
  const unsigned long result =                 // NOLINT(runtime/int)
927
100
    strtoul(port.c_str(), &endptr, 10);
928

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

100
      (result != 0 && result < 1024) || result > 65535) {
930
    errors->push_back(" must be 0 or in range 1024 to 65535.");
931
  }
932
100
  return static_cast<int>(result);
933
}
934
935
100
HostPort SplitHostPort(const std::string& arg,
936
                      std::vector<std::string>* errors) {
937
  // remove_brackets only works if no port is specified
938
  // so if it has an effect only an IPv6 address was specified.
939
200
  std::string host = RemoveBrackets(arg);
940
100
  if (host.length() < arg.length())
941
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
942
943
100
  size_t colon = arg.rfind(':');
944
100
  if (colon == std::string::npos) {
945
    // Either a port number or a host name.  Assume that
946
    // if it's not all decimal digits, it's a host name.
947
390
    for (char c : arg) {
948

302
      if (c < '0' || c > '9') {
949
        return HostPort{arg, DebugOptions::kDefaultInspectorPort};
950
      }
951
    }
952
88
    return HostPort { "", ParseAndValidatePort(arg, errors) };
953
  }
954
  // Host and port found:
955
24
  return HostPort { RemoveBrackets(arg.substr(0, colon)),
956
12
                    ParseAndValidatePort(arg.substr(colon + 1), errors) };
957
}
958
959
1
std::string GetBashCompletion() {
960
2
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
961
1
  const auto& parser = _ppop_instance;
962
963
2
  std::ostringstream out;
964
965
  out << "_node_complete() {\n"
966
         "  local cur_word options\n"
967
         "  cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n"
968
         "  if [[ \"${cur_word}\" == -* ]] ; then\n"
969
1
         "    COMPREPLY=( $(compgen -W '";
970
971
141
  for (const auto& item : parser.options_) {
972
140
    if (item.first[0] != '[') {
973
137
      out << item.first << " ";
974
    }
975
  }
976
23
  for (const auto& item : parser.aliases_) {
977
22
    if (item.first[0] != '[') {
978
22
      out << item.first << " ";
979
    }
980
  }
981
1
  if (parser.aliases_.size() > 0) {
982
1
    out.seekp(-1, out.cur);  // Strip the trailing space
983
  }
984
985
  out << "' -- \"${cur_word}\") )\n"
986
         "    return 0\n"
987
         "  else\n"
988
         "    COMPREPLY=( $(compgen -f \"${cur_word}\") )\n"
989
         "    return 0\n"
990
         "  fi\n"
991
         "}\n"
992
         "complete -o filenames -o nospace -o bashdefault "
993
1
         "-F _node_complete node node_g";
994
1
  return out.str();
995
}
996
997
// Return a map containing all the options and their metadata as well
998
// as the aliases
999
void GetCLIOptions(const FunctionCallbackInfo<Value>& args) {
1000
6654
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
1001
6654
  Environment* env = Environment::GetCurrent(args);
1002
6654
  if (!env->has_run_bootstrapping_code()) {
1003
    // No code because this is an assertion.
1004
    return env->ThrowError(
1005
        "Should not query options before bootstrapping is done");
1006
  }
1007
6654
  env->set_has_serialized_options(true);
1008
1009
6654
  Isolate* isolate = env->isolate();
1010
6654
  Local<Context> context = env->context();
1011
1012
  // Temporarily act as if the current Environment's/IsolateData's options were
1013
  // the default options, i.e. like they are the ones we'd access for global
1014
  // options parsing, so that all options are available from the main parser.
1015
6654
  auto original_per_isolate = per_process::cli_options->per_isolate;
1016
6654
  per_process::cli_options->per_isolate = env->isolate_data()->options();
1017
6654
  auto original_per_env = per_process::cli_options->per_isolate->per_env;
1018
6654
  per_process::cli_options->per_isolate->per_env = env->options();
1019
6654
  auto on_scope_leave = OnScopeLeave([&]() {
1020
6654
    per_process::cli_options->per_isolate->per_env = original_per_env;
1021
6654
    per_process::cli_options->per_isolate = original_per_isolate;
1022
6654
  });
1023
1024
6654
  Local<Map> options = Map::New(isolate);
1025
6654
  if (options
1026
13308
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1027
6654
          .IsNothing()) {
1028
    return;
1029
  }
1030
1031
938214
  for (const auto& item : _ppop_instance.options_) {
1032
    Local<Value> value;
1033
931560
    const auto& option_info = item.second;
1034
931560
    auto field = option_info.field;
1035
931560
    PerProcessOptions* opts = per_process::cli_options.get();
1036


931560
    switch (option_info.type) {
1037
146388
      case kNoOp:
1038
      case kV8Option:
1039
        // Special case for --abort-on-uncaught-exception which is also
1040
        // respected by Node.js internals
1041
146388
        if (item.first == "--abort-on-uncaught-exception") {
1042
6654
          value = Boolean::New(
1043
6654
            isolate, original_per_env->abort_on_uncaught_exception);
1044
        } else {
1045
139734
          value = Undefined(isolate);
1046
        }
1047
146388
        break;
1048
512358
      case kBoolean:
1049
1024716
        value = Boolean::New(isolate,
1050
1024716
                             *_ppop_instance.Lookup<bool>(field, opts));
1051
512358
        break;
1052
26616
      case kInteger:
1053
53232
        value = Number::New(
1054
            isolate,
1055
53232
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1056
26616
        break;
1057
19962
      case kUInteger:
1058
39924
        value = Number::New(
1059
            isolate,
1060
39924
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1061
19962
        break;
1062
186312
      case kString:
1063
372624
        if (!ToV8Value(context,
1064
372624
                       *_ppop_instance.Lookup<std::string>(field, opts))
1065
186312
                 .ToLocal(&value)) {
1066
          return;
1067
        }
1068
186312
        break;
1069
33270
      case kStringList:
1070
66540
        if (!ToV8Value(context,
1071
66540
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1072
33270
                 .ToLocal(&value)) {
1073
          return;
1074
        }
1075
33270
        break;
1076
6654
      case kHostPort: {
1077
        const HostPort& host_port =
1078
6654
          *_ppop_instance.Lookup<HostPort>(field, opts);
1079
6654
        Local<Object> obj = Object::New(isolate);
1080
        Local<Value> host;
1081
6654
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1082

33270
            obj->Set(context, env->host_string(), host).IsNothing() ||
1083
6654
            obj->Set(context,
1084
                     env->port_string(),
1085
26616
                     Integer::New(isolate, host_port.port()))
1086
6654
                .IsNothing()) {
1087
          return;
1088
        }
1089
6654
        value = obj;
1090
6654
        break;
1091
      }
1092
      default:
1093
        UNREACHABLE();
1094
    }
1095
931560
    CHECK(!value.IsEmpty());
1096
1097
931560
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1098
931560
    Local<Object> info = Object::New(isolate);
1099
    Local<Value> help_text;
1100
931560
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1101
1863120
        !info->Set(context, env->help_text_string(), help_text)
1102

1863120
             .FromMaybe(false) ||
1103
1863120
        !info->Set(context,
1104
                   env->env_var_settings_string(),
1105
                   Integer::New(isolate,
1106
2794680
                                static_cast<int>(option_info.env_setting)))
1107

1863120
             .FromMaybe(false) ||
1108
1863120
        !info->Set(context,
1109
                   env->type_string(),
1110
2794680
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1111

1863120
             .FromMaybe(false) ||
1112
1863120
        !info->Set(context,
1113
                   env->default_is_true_string(),
1114
2794680
                   Boolean::New(isolate, option_info.default_is_true))
1115

1863120
             .FromMaybe(false) ||
1116

4657800
        info->Set(context, env->value_string(), value).IsNothing() ||
1117

2794680
        options->Set(context, name, info).IsEmpty()) {
1118
      return;
1119
    }
1120
  }
1121
1122
  Local<Value> aliases;
1123
13308
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1124
1125
6654
  if (aliases.As<Object>()
1126
13308
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1127
6654
          .IsNothing()) {
1128
    return;
1129
  }
1130
1131
6654
  Local<Object> ret = Object::New(isolate);
1132
26616
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1133

26616
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1134
    return;
1135
  }
1136
1137
13308
  args.GetReturnValue().Set(ret);
1138
}
1139
1140
6053
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1141
6053
  Environment* env = Environment::GetCurrent(args);
1142
6053
  if (!env->has_run_bootstrapping_code()) {
1143
    // No code because this is an assertion.
1144
    return env->ThrowError(
1145
        "Should not query options before bootstrapping is done");
1146
  }
1147
6053
  Isolate* isolate = args.GetIsolate();
1148
6053
  Local<Context> context = env->context();
1149
6053
  Local<Object> ret = Object::New(isolate);
1150
1151
12106
  if (ret->Set(context,
1152
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1153
18159
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1154
6053
      .IsNothing()) return;
1155
1156
12106
  if (ret->Set(context,
1157
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1158
18159
           Boolean::New(isolate, env->no_global_search_paths()))
1159
6053
      .IsNothing()) return;
1160
1161
12106
  args.GetReturnValue().Set(ret);
1162
}
1163
1164
781
void Initialize(Local<Object> target,
1165
                Local<Value> unused,
1166
                Local<Context> context,
1167
                void* priv) {
1168
781
  Environment* env = Environment::GetCurrent(context);
1169
781
  Isolate* isolate = env->isolate();
1170
781
  SetMethodNoSideEffect(context, target, "getCLIOptions", GetCLIOptions);
1171
781
  SetMethodNoSideEffect(
1172
      context, target, "getEmbedderOptions", GetEmbedderOptions);
1173
1174
781
  Local<Object> env_settings = Object::New(isolate);
1175
2343
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1176
2343
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1177
  target
1178
781
      ->Set(
1179
1562
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1180
      .Check();
1181
1182
781
  Local<Object> types = Object::New(isolate);
1183
2343
  NODE_DEFINE_CONSTANT(types, kNoOp);
1184
2343
  NODE_DEFINE_CONSTANT(types, kV8Option);
1185
2343
  NODE_DEFINE_CONSTANT(types, kBoolean);
1186
2343
  NODE_DEFINE_CONSTANT(types, kInteger);
1187
2343
  NODE_DEFINE_CONSTANT(types, kUInteger);
1188
2343
  NODE_DEFINE_CONSTANT(types, kString);
1189
2343
  NODE_DEFINE_CONSTANT(types, kHostPort);
1190
2343
  NODE_DEFINE_CONSTANT(types, kStringList);
1191
1562
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1192
      .Check();
1193
781
}
1194
1195
5320
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1196
5320
  registry->Register(GetCLIOptions);
1197
5320
  registry->Register(GetEmbedderOptions);
1198
5320
}
1199
}  // namespace options_parser
1200
1201
5392
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1202
5392
  HandleEnvOptions(env_options, [](const char* name) {
1203
21568
    std::string text;
1204

21568
    return credentials::SafeGetenv(name, &text) ? text : "";
1205
  });
1206
5392
}
1207
1208
5686
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1209
                      std::function<std::string(const char*)> opt_getter) {
1210
5686
  env_options->pending_deprecation =
1211
11372
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1212
1213
5686
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1214
1215
5686
  env_options->preserve_symlinks_main =
1216
11372
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1217
1218
5686
  if (env_options->redirect_warnings.empty())
1219
5686
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1220
5686
}
1221
1222
5568
std::vector<std::string> ParseNodeOptionsEnvVar(
1223
    const std::string& node_options, std::vector<std::string>* errors) {
1224
5568
  std::vector<std::string> env_argv;
1225
1226
5568
  bool is_in_string = false;
1227
5568
  bool will_start_new_arg = true;
1228
8172
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1229
2604
    char c = node_options.at(index);
1230
1231
    // Backslashes escape the following character
1232

2604
    if (c == '\\' && is_in_string) {
1233
      if (index + 1 == node_options.size()) {
1234
        errors->push_back("invalid value for NODE_OPTIONS "
1235
                          "(invalid escape)\n");
1236
        return env_argv;
1237
      } else {
1238
        c = node_options.at(++index);
1239
      }
1240

2604
    } else if (c == ' ' && !is_in_string) {
1241
32
      will_start_new_arg = true;
1242
32
      continue;
1243
2572
    } else if (c == '"') {
1244
4
      is_in_string = !is_in_string;
1245
4
      continue;
1246
    }
1247
1248
2568
    if (will_start_new_arg) {
1249
108
      env_argv.emplace_back(std::string(1, c));
1250
108
      will_start_new_arg = false;
1251
    } else {
1252
2460
      env_argv.back() += c;
1253
    }
1254
  }
1255
1256
5568
  if (is_in_string) {
1257
    errors->push_back("invalid value for NODE_OPTIONS "
1258
                      "(unterminated string)\n");
1259
  }
1260
5568
  return env_argv;
1261
}
1262
}  // namespace node
1263
1264
5392
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1265
5320
NODE_MODULE_EXTERNAL_REFERENCE(options,
1266
                               node::options_parser::RegisterExternalReferences)