GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 490 521 94.0 %
Date: 2022-10-14 05:16:24 Branches: 208 270 77.0 %

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
5623
Mutex cli_options_mutex;
34
5623
std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
35
}  // namespace per_process
36
37
11696
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
11696
  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
23392
      SplitString(inspect_publish_uid_string, ',');
53
11696
  inspect_publish_uid.console = false;
54
11696
  inspect_publish_uid.http = false;
55
35086
  for (const std::string& destination : destinations) {
56
23390
    if (destination == "stderr") {
57
11695
      inspect_publish_uid.console = true;
58
11695
    } else if (destination == "http") {
59
11695
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
11696
}
66
67
11105
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

11105
  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
11105
  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

22212
  if (use_largepages != "off" &&
90

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

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

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

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

11696
  if (syntax_check_only && has_eval_string) {
117
4
    errors->push_back("either --check or --eval can be used, not both");
118
  }
119
120

23412
  if (!unhandled_rejections.empty() &&
121
39
      unhandled_rejections != "warn-with-error-code" &&
122
36
      unhandled_rejections != "throw" &&
123
32
      unhandled_rejections != "strict" &&
124

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

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


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


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


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

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

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

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


1000944
    switch (option_info.type) {
1068
159873
      case kNoOp:
1069
      case kV8Option:
1070
        // Special case for --abort-on-uncaught-exception which is also
1071
        // respected by Node.js internals
1072
159873
        if (item.first == "--abort-on-uncaught-exception") {
1073
13902
          value = Boolean::New(
1074
6951
            isolate, original_per_env->abort_on_uncaught_exception);
1075
        } else {
1076
152922
          value = Undefined(isolate);
1077
        }
1078
159873
        break;
1079
549129
      case kBoolean:
1080
1098258
        value = Boolean::New(isolate,
1081
1098258
                             *_ppop_instance.Lookup<bool>(field, opts));
1082
549129
        break;
1083
27804
      case kInteger:
1084
55608
        value = Number::New(
1085
            isolate,
1086
55608
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1087
27804
        break;
1088
20853
      case kUInteger:
1089
41706
        value = Number::New(
1090
            isolate,
1091
41706
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1092
20853
        break;
1093
187677
      case kString:
1094
563031
        if (!ToV8Value(context,
1095
375354
                       *_ppop_instance.Lookup<std::string>(field, opts))
1096
187677
                 .ToLocal(&value)) {
1097
          return;
1098
        }
1099
187677
        break;
1100
48657
      case kStringList:
1101
145971
        if (!ToV8Value(context,
1102
97314
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1103
48657
                 .ToLocal(&value)) {
1104
          return;
1105
        }
1106
48657
        break;
1107
6951
      case kHostPort: {
1108
        const HostPort& host_port =
1109
6951
          *_ppop_instance.Lookup<HostPort>(field, opts);
1110
6951
        Local<Object> obj = Object::New(isolate);
1111
        Local<Value> host;
1112

27804
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1113

41706
            obj->Set(context, env->host_string(), host).IsNothing() ||
1114
13902
            obj->Set(context,
1115
                     env->port_string(),
1116
20853
                     Integer::New(isolate, host_port.port()))
1117
6951
                .IsNothing()) {
1118
          return;
1119
        }
1120
6951
        value = obj;
1121
6951
        break;
1122
      }
1123
      default:
1124
        UNREACHABLE();
1125
    }
1126
1000944
    CHECK(!value.IsEmpty());
1127
1128
2001888
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1129
1000944
    Local<Object> info = Object::New(isolate);
1130
    Local<Value> help_text;
1131

4003776
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1132
4003776
        !info->Set(context, env->help_text_string(), help_text)
1133
4003776
             .FromMaybe(false) ||
1134
3002832
        !info->Set(context,
1135
                   env->env_var_settings_string(),
1136
                   Integer::New(isolate,
1137
3002832
                                static_cast<int>(option_info.env_setting)))
1138
4003776
             .FromMaybe(false) ||
1139
3002832
        !info->Set(context,
1140
                   env->type_string(),
1141
3002832
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1142
4003776
             .FromMaybe(false) ||
1143
3002832
        !info->Set(context,
1144
                   env->default_is_true_string(),
1145
3002832
                   Boolean::New(isolate, option_info.default_is_true))
1146
4003776
             .FromMaybe(false) ||
1147

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

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

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

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

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

22420
NODE_MODULE_EXTERNAL_REFERENCE(options,
1297
                               node::options_parser::RegisterExternalReferences)