GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 481 513 93.8 %
Date: 2022-10-23 04:21:34 Branches: 217 280 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
11744
void DebugOptions::CheckOptions(std::vector<std::string>* errors,
38
                                std::vector<std::string>* argv) {
39
#if !NODE_USE_V8_PLATFORM && !HAVE_INSPECTOR
40
  if (inspector_enabled) {
41
    errors->push_back("Inspector is not available when Node is compiled "
42
                      "--without-v8-platform and --without-inspector.");
43
  }
44
#endif
45
46
11744
  if (deprecated_debug) {
47
4
    errors->push_back("[DEP0062]: `node --debug` and `node --debug-brk` "
48
                      "are invalid. Please use `node --inspect` and "
49
                      "`node --inspect-brk` instead.");
50
  }
51
52
  std::vector<std::string> destinations =
53
23488
      SplitString(inspect_publish_uid_string, ',');
54
11744
  inspect_publish_uid.console = false;
55
11744
  inspect_publish_uid.http = false;
56
35230
  for (const std::string& destination : destinations) {
57
23486
    if (destination == "stderr") {
58
11743
      inspect_publish_uid.console = true;
59
11743
    } else if (destination == "http") {
60
11743
      inspect_publish_uid.http = true;
61
    } else {
62
      errors->push_back("--inspect-publish-uid destination can be "
63
                        "stderr or http");
64
    }
65
  }
66
11744
}
67
68
11151
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors,
69
                                     std::vector<std::string>* argv) {
70
#if HAVE_OPENSSL
71

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

11153
      use_largepages != "on" &&
93
1
      use_largepages != "silent") {
94
1
    errors->push_back("invalid value for --use-largepages");
95
  }
96
11151
  per_isolate->CheckOptions(errors, argv);
97
11151
}
98
99
11744
void PerIsolateOptions::CheckOptions(std::vector<std::string>* errors,
100
                                     std::vector<std::string>* argv) {
101
11744
  per_env->CheckOptions(errors, argv);
102
11744
}
103
104
11744
void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors,
105
                                      std::vector<std::string>* argv) {
106

11744
  if (has_policy_integrity_string && experimental_policy.empty()) {
107
    errors->push_back("--policy-integrity requires "
108
                      "--experimental-policy be enabled");
109
  }
110

11744
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
111
1
    errors->push_back("--policy-integrity cannot be empty");
112
  }
113
114
11744
  if (!module_type.empty()) {
115

58
    if (module_type != "commonjs" && module_type != "module") {
116
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
117
    }
118
  }
119
120

11744
  if (syntax_check_only && has_eval_string) {
121
4
    errors->push_back("either --check or --eval can be used, not both");
122
  }
123
124
11764
  if (!unhandled_rejections.empty() &&
125
39
      unhandled_rejections != "warn-with-error-code" &&
126
36
      unhandled_rejections != "throw" &&
127
32
      unhandled_rejections != "strict" &&
128

11779
      unhandled_rejections != "warn" &&
129
10
      unhandled_rejections != "none") {
130
1
    errors->push_back("invalid value for --unhandled-rejections");
131
  }
132
133

11744
  if (tls_min_v1_3 && tls_max_v1_2) {
134
1
    errors->push_back("either --tls-min-v1.3 or --tls-max-v1.2 can be "
135
                      "used, not both");
136
  }
137
138
11744
  if (heap_snapshot_near_heap_limit < 0) {
139
    errors->push_back("--heapsnapshot-near-heap-limit must not be negative");
140
  }
141
142
11744
  if (test_runner) {
143
14
    if (syntax_check_only) {
144
1
      errors->push_back("either --test or --check can be used, not both");
145
    }
146
147
14
    if (has_eval_string) {
148
2
      errors->push_back("either --test or --eval can be used, not both");
149
    }
150
151
14
    if (force_repl) {
152
1
      errors->push_back("either --test or --interactive can be used, not both");
153
    }
154
155
14
    if (watch_mode) {
156
      // TODO(MoLow): Support (incremental?) watch mode within test runner
157
      errors->push_back("either --test or --watch can be used, not both");
158
    }
159
160
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_TEST_RUNNER
161
    debug_options_.allow_attaching_debugger = false;
162
#endif
163
  }
164
165
11744
  if (watch_mode) {
166
11
    if (syntax_check_only) {
167
      errors->push_back("either --watch or --check can be used, not both");
168
11
    } else if (has_eval_string) {
169
      errors->push_back("either --watch or --eval can be used, not both");
170
11
    } else if (force_repl) {
171
      errors->push_back("either --watch or --interactive "
172
                        "can be used, not both");
173

11
    } else if (argv->size() < 1 || (*argv)[1].empty()) {
174
      errors->push_back("--watch requires specifying a file");
175
    }
176
177
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_WATCH_MODE
178
    debug_options_.allow_attaching_debugger = false;
179
#endif
180
  }
181
182
#if HAVE_INSPECTOR
183
11744
  if (!cpu_prof) {
184
11733
    if (!cpu_prof_name.empty()) {
185
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
186
    }
187
11733
    if (!cpu_prof_dir.empty()) {
188
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-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
11733
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
193
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
194
    }
195
  }
196
197


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


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


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

148
  if (errno != 0 || *endptr != '\0'||
962

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

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


1004112
    switch (option_info.type) {
1070
160379
      case kNoOp:
1071
      case kV8Option:
1072
        // Special case for --abort-on-uncaught-exception which is also
1073
        // respected by Node.js internals
1074
160379
        if (item.first == "--abort-on-uncaught-exception") {
1075
6973
          value = Boolean::New(
1076
6973
            isolate, original_per_env->abort_on_uncaught_exception);
1077
        } else {
1078
153406
          value = Undefined(isolate);
1079
        }
1080
160379
        break;
1081
550867
      case kBoolean:
1082
1101734
        value = Boolean::New(isolate,
1083
1101734
                             *_ppop_instance.Lookup<bool>(field, opts));
1084
550867
        break;
1085
27892
      case kInteger:
1086
55784
        value = Number::New(
1087
            isolate,
1088
55784
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1089
27892
        break;
1090
20919
      case kUInteger:
1091
41838
        value = Number::New(
1092
            isolate,
1093
41838
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1094
20919
        break;
1095
188271
      case kString:
1096
376542
        if (!ToV8Value(context,
1097
376542
                       *_ppop_instance.Lookup<std::string>(field, opts))
1098
188271
                 .ToLocal(&value)) {
1099
          return;
1100
        }
1101
188271
        break;
1102
48811
      case kStringList:
1103
97622
        if (!ToV8Value(context,
1104
97622
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1105
48811
                 .ToLocal(&value)) {
1106
          return;
1107
        }
1108
48811
        break;
1109
6973
      case kHostPort: {
1110
        const HostPort& host_port =
1111
6973
          *_ppop_instance.Lookup<HostPort>(field, opts);
1112
6973
        Local<Object> obj = Object::New(isolate);
1113
        Local<Value> host;
1114
6973
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1115

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

2008224
             .FromMaybe(false) ||
1136
2008224
        !info->Set(context,
1137
                   env->env_var_settings_string(),
1138
                   Integer::New(isolate,
1139
3012336
                                static_cast<int>(option_info.env_setting)))
1140

2008224
             .FromMaybe(false) ||
1141
2008224
        !info->Set(context,
1142
                   env->type_string(),
1143
3012336
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1144

2008224
             .FromMaybe(false) ||
1145
2008224
        !info->Set(context,
1146
                   env->default_is_true_string(),
1147
3012336
                   Boolean::New(isolate, option_info.default_is_true))
1148

2008224
             .FromMaybe(false) ||
1149

5020560
        info->Set(context, env->value_string(), value).IsNothing() ||
1150

3012336
        options->Set(context, name, info).IsEmpty()) {
1151
      return;
1152
    }
1153
  }
1154
1155
  Local<Value> aliases;
1156
13946
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1157
1158
6973
  if (aliases.As<Object>()
1159
13946
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1160
6973
          .IsNothing()) {
1161
    return;
1162
  }
1163
1164
6973
  Local<Object> ret = Object::New(isolate);
1165
27892
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1166

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

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

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

2610
    } else if (c == ' ' && !is_in_string) {
1274
32
      will_start_new_arg = true;
1275
32
      continue;
1276
2578
    } else if (c == '"') {
1277
4
      is_in_string = !is_in_string;
1278
4
      continue;
1279
    }
1280
1281
2574
    if (will_start_new_arg) {
1282
109
      env_argv.emplace_back(std::string(1, c));
1283
109
      will_start_new_arg = false;
1284
    } else {
1285
2465
      env_argv.back() += c;
1286
    }
1287
  }
1288
1289
5822
  if (is_in_string) {
1290
    errors->push_back("invalid value for NODE_OPTIONS "
1291
                      "(unterminated string)\n");
1292
  }
1293
5822
  return env_argv;
1294
}
1295
}  // namespace node
1296
1297
5645
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1298
5574
NODE_MODULE_EXTERNAL_REFERENCE(options,
1299
                               node::options_parser::RegisterExternalReferences)