GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 469 498 94.2 %
Date: 2022-05-26 04:15:45 Branches: 214 274 78.1 %

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

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

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

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

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

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

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

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

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

10944
  if (tls_min_v1_3 && tls_max_v1_2) {
138
1
    errors->push_back("either --tls-min-v1.3 or --tls-max-v1.2 can be "
139
                      "used, not both");
140
  }
141
142
10944
  if (heap_snapshot_near_heap_limit < 0) {
143
    errors->push_back("--heap-snapshot-near-heap-limit must not be negative");
144
  }
145
146
10944
  if (test_runner) {
147
11
    if (syntax_check_only) {
148
1
      errors->push_back("either --test or --check can be used, not both");
149
    }
150
151
11
    if (has_eval_string) {
152
2
      errors->push_back("either --test or --eval can be used, not both");
153
    }
154
155
11
    if (force_repl) {
156
1
      errors->push_back("either --test or --interactive can be used, not both");
157
    }
158
159
11
    if (debug_options_.inspector_enabled) {
160
2
      errors->push_back("the inspector cannot be used with --test");
161
    }
162
  }
163
164
#if HAVE_INSPECTOR
165
10944
  if (!cpu_prof) {
166
10933
    if (!cpu_prof_name.empty()) {
167
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
168
    }
169
10933
    if (!cpu_prof_dir.empty()) {
170
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
171
    }
172
    // We can't catch the case where the value passed is the default value,
173
    // then the option just becomes a noop which is fine.
174
10933
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
175
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
176
    }
177
  }
178
179


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


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
892
4
    return host.substr(1, host.size() - 2);
893
  else
894
108
    return host;
895
}
896
897
100
inline int ParseAndValidatePort(const std::string& port,
898
                                std::vector<std::string>* errors) {
899
  char* endptr;
900
100
  errno = 0;
901
  const unsigned long result =                 // NOLINT(runtime/int)
902
100
    strtoul(port.c_str(), &endptr, 10);
903

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

100
      (result != 0 && result < 1024) || result > 65535) {
905
    errors->push_back(" must be 0 or in range 1024 to 65535.");
906
  }
907
100
  return static_cast<int>(result);
908
}
909
910
100
HostPort SplitHostPort(const std::string& arg,
911
                      std::vector<std::string>* errors) {
912
  // remove_brackets only works if no port is specified
913
  // so if it has an effect only an IPv6 address was specified.
914
200
  std::string host = RemoveBrackets(arg);
915
100
  if (host.length() < arg.length())
916
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
917
918
100
  size_t colon = arg.rfind(':');
919
100
  if (colon == std::string::npos) {
920
    // Either a port number or a host name.  Assume that
921
    // if it's not all decimal digits, it's a host name.
922
390
    for (char c : arg) {
923

302
      if (c < '0' || c > '9') {
924
        return HostPort{arg, DebugOptions::kDefaultInspectorPort};
925
      }
926
    }
927
88
    return HostPort { "", ParseAndValidatePort(arg, errors) };
928
  }
929
  // Host and port found:
930
24
  return HostPort { RemoveBrackets(arg.substr(0, colon)),
931
12
                    ParseAndValidatePort(arg.substr(colon + 1), errors) };
932
}
933
934
1
std::string GetBashCompletion() {
935
2
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
936
1
  const auto& parser = _ppop_instance;
937
938
2
  std::ostringstream out;
939
940
  out << "_node_complete() {\n"
941
         "  local cur_word options\n"
942
         "  cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n"
943
         "  if [[ \"${cur_word}\" == -* ]] ; then\n"
944
1
         "    COMPREPLY=( $(compgen -W '";
945
946
136
  for (const auto& item : parser.options_) {
947
135
    if (item.first[0] != '[') {
948
132
      out << item.first << " ";
949
    }
950
  }
951
23
  for (const auto& item : parser.aliases_) {
952
22
    if (item.first[0] != '[') {
953
22
      out << item.first << " ";
954
    }
955
  }
956
1
  if (parser.aliases_.size() > 0) {
957
1
    out.seekp(-1, out.cur);  // Strip the trailing space
958
  }
959
960
  out << "' -- \"${cur_word}\") )\n"
961
         "    return 0\n"
962
         "  else\n"
963
         "    COMPREPLY=( $(compgen -f \"${cur_word}\") )\n"
964
         "    return 0\n"
965
         "  fi\n"
966
         "}\n"
967
         "complete -o filenames -o nospace -o bashdefault "
968
1
         "-F _node_complete node node_g";
969
1
  return out.str();
970
}
971
972
// Return a map containing all the options and their metadata as well
973
// as the aliases
974
void GetCLIOptions(const FunctionCallbackInfo<Value>& args) {
975
6559
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
976
6559
  Environment* env = Environment::GetCurrent(args);
977
6559
  if (!env->has_run_bootstrapping_code()) {
978
    // No code because this is an assertion.
979
    return env->ThrowError(
980
        "Should not query options before bootstrapping is done");
981
  }
982
6559
  env->set_has_serialized_options(true);
983
984
6559
  Isolate* isolate = env->isolate();
985
6559
  Local<Context> context = env->context();
986
987
  // Temporarily act as if the current Environment's/IsolateData's options were
988
  // the default options, i.e. like they are the ones we'd access for global
989
  // options parsing, so that all options are available from the main parser.
990
6559
  auto original_per_isolate = per_process::cli_options->per_isolate;
991
6559
  per_process::cli_options->per_isolate = env->isolate_data()->options();
992
6559
  auto original_per_env = per_process::cli_options->per_isolate->per_env;
993
6559
  per_process::cli_options->per_isolate->per_env = env->options();
994
6559
  auto on_scope_leave = OnScopeLeave([&]() {
995
6559
    per_process::cli_options->per_isolate->per_env = original_per_env;
996
6559
    per_process::cli_options->per_isolate = original_per_isolate;
997
6559
  });
998
999
6559
  Local<Map> options = Map::New(isolate);
1000
6559
  if (options
1001
13118
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1002
6559
          .IsNothing()) {
1003
    return;
1004
  }
1005
1006
892024
  for (const auto& item : _ppop_instance.options_) {
1007
    Local<Value> value;
1008
885465
    const auto& option_info = item.second;
1009
885465
    auto field = option_info.field;
1010
885465
    PerProcessOptions* opts = per_process::cli_options.get();
1011


885465
    switch (option_info.type) {
1012
144298
      case kNoOp:
1013
      case kV8Option:
1014
        // Special case for --abort-on-uncaught-exception which is also
1015
        // respected by Node.js internals
1016
144298
        if (item.first == "--abort-on-uncaught-exception") {
1017
6559
          value = Boolean::New(
1018
6559
            isolate, original_per_env->abort_on_uncaught_exception);
1019
        } else {
1020
137739
          value = Undefined(isolate);
1021
        }
1022
144298
        break;
1023
485366
      case kBoolean:
1024
970732
        value = Boolean::New(isolate,
1025
970732
                             *_ppop_instance.Lookup<bool>(field, opts));
1026
485366
        break;
1027
26236
      case kInteger:
1028
52472
        value = Number::New(
1029
            isolate,
1030
52472
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1031
26236
        break;
1032
19677
      case kUInteger:
1033
39354
        value = Number::New(
1034
            isolate,
1035
39354
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1036
19677
        break;
1037
177093
      case kString:
1038
354186
        if (!ToV8Value(context,
1039
354186
                       *_ppop_instance.Lookup<std::string>(field, opts))
1040
177093
                 .ToLocal(&value)) {
1041
          return;
1042
        }
1043
177093
        break;
1044
26236
      case kStringList:
1045
52472
        if (!ToV8Value(context,
1046
52472
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1047
26236
                 .ToLocal(&value)) {
1048
          return;
1049
        }
1050
26236
        break;
1051
6559
      case kHostPort: {
1052
        const HostPort& host_port =
1053
6559
          *_ppop_instance.Lookup<HostPort>(field, opts);
1054
6559
        Local<Object> obj = Object::New(isolate);
1055
        Local<Value> host;
1056
6559
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1057

32795
            obj->Set(context, env->host_string(), host).IsNothing() ||
1058
6559
            obj->Set(context,
1059
                     env->port_string(),
1060
26236
                     Integer::New(isolate, host_port.port()))
1061
6559
                .IsNothing()) {
1062
          return;
1063
        }
1064
6559
        value = obj;
1065
6559
        break;
1066
      }
1067
      default:
1068
        UNREACHABLE();
1069
    }
1070
885465
    CHECK(!value.IsEmpty());
1071
1072
885465
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1073
885465
    Local<Object> info = Object::New(isolate);
1074
    Local<Value> help_text;
1075
885465
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1076
1770930
        !info->Set(context, env->help_text_string(), help_text)
1077

1770930
             .FromMaybe(false) ||
1078
1770930
        !info->Set(context,
1079
                   env->env_var_settings_string(),
1080
                   Integer::New(isolate,
1081
2656395
                                static_cast<int>(option_info.env_setting)))
1082

1770930
             .FromMaybe(false) ||
1083
1770930
        !info->Set(context,
1084
                   env->type_string(),
1085
2656395
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1086

1770930
             .FromMaybe(false) ||
1087
1770930
        !info->Set(context,
1088
                   env->default_is_true_string(),
1089
2656395
                   Boolean::New(isolate, option_info.default_is_true))
1090

1770930
             .FromMaybe(false) ||
1091

4427325
        info->Set(context, env->value_string(), value).IsNothing() ||
1092

2656395
        options->Set(context, name, info).IsEmpty()) {
1093
      return;
1094
    }
1095
  }
1096
1097
  Local<Value> aliases;
1098
13118
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1099
1100
6559
  if (aliases.As<Object>()
1101
13118
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1102
6559
          .IsNothing()) {
1103
    return;
1104
  }
1105
1106
6559
  Local<Object> ret = Object::New(isolate);
1107
26236
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1108

26236
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1109
    return;
1110
  }
1111
1112
13118
  args.GetReturnValue().Set(ret);
1113
}
1114
1115
6007
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1116
6007
  Environment* env = Environment::GetCurrent(args);
1117
6007
  if (!env->has_run_bootstrapping_code()) {
1118
    // No code because this is an assertion.
1119
    return env->ThrowError(
1120
        "Should not query options before bootstrapping is done");
1121
  }
1122
6007
  Isolate* isolate = args.GetIsolate();
1123
6007
  Local<Context> context = env->context();
1124
6007
  Local<Object> ret = Object::New(isolate);
1125
1126
12014
  if (ret->Set(context,
1127
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1128
18021
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1129
6007
      .IsNothing()) return;
1130
1131
12014
  if (ret->Set(context,
1132
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1133
18021
           Boolean::New(isolate, env->no_global_search_paths()))
1134
6007
      .IsNothing()) return;
1135
1136
12014
  args.GetReturnValue().Set(ret);
1137
}
1138
1139
851
void Initialize(Local<Object> target,
1140
                Local<Value> unused,
1141
                Local<Context> context,
1142
                void* priv) {
1143
851
  Environment* env = Environment::GetCurrent(context);
1144
851
  Isolate* isolate = env->isolate();
1145
851
  env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions);
1146
851
  env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions);
1147
1148
851
  Local<Object> env_settings = Object::New(isolate);
1149
2553
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1150
2553
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1151
  target
1152
851
      ->Set(
1153
1702
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1154
      .Check();
1155
1156
851
  Local<Object> types = Object::New(isolate);
1157
2553
  NODE_DEFINE_CONSTANT(types, kNoOp);
1158
2553
  NODE_DEFINE_CONSTANT(types, kV8Option);
1159
2553
  NODE_DEFINE_CONSTANT(types, kBoolean);
1160
2553
  NODE_DEFINE_CONSTANT(types, kInteger);
1161
2553
  NODE_DEFINE_CONSTANT(types, kUInteger);
1162
2553
  NODE_DEFINE_CONSTANT(types, kString);
1163
2553
  NODE_DEFINE_CONSTANT(types, kHostPort);
1164
2553
  NODE_DEFINE_CONSTANT(types, kStringList);
1165
1702
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1166
      .Check();
1167
851
}
1168
1169
5197
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1170
5197
  registry->Register(GetCLIOptions);
1171
5197
  registry->Register(GetEmbedderOptions);
1172
5197
}
1173
}  // namespace options_parser
1174
1175
5265
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1176
5265
  HandleEnvOptions(env_options, [](const char* name) {
1177
21060
    std::string text;
1178

21060
    return credentials::SafeGetenv(name, &text) ? text : "";
1179
  });
1180
5265
}
1181
1182
5541
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1183
                      std::function<std::string(const char*)> opt_getter) {
1184
5541
  env_options->pending_deprecation =
1185
11082
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1186
1187
5541
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1188
1189
5541
  env_options->preserve_symlinks_main =
1190
11082
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1191
1192
5541
  if (env_options->redirect_warnings.empty())
1193
5541
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1194
5541
}
1195
1196
5423
std::vector<std::string> ParseNodeOptionsEnvVar(
1197
    const std::string& node_options, std::vector<std::string>* errors) {
1198
5423
  std::vector<std::string> env_argv;
1199
1200
5423
  bool is_in_string = false;
1201
5423
  bool will_start_new_arg = true;
1202
8027
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1203
2604
    char c = node_options.at(index);
1204
1205
    // Backslashes escape the following character
1206

2604
    if (c == '\\' && is_in_string) {
1207
      if (index + 1 == node_options.size()) {
1208
        errors->push_back("invalid value for NODE_OPTIONS "
1209
                          "(invalid escape)\n");
1210
        return env_argv;
1211
      } else {
1212
        c = node_options.at(++index);
1213
      }
1214

2604
    } else if (c == ' ' && !is_in_string) {
1215
32
      will_start_new_arg = true;
1216
32
      continue;
1217
2572
    } else if (c == '"') {
1218
4
      is_in_string = !is_in_string;
1219
4
      continue;
1220
    }
1221
1222
2568
    if (will_start_new_arg) {
1223
108
      env_argv.emplace_back(std::string(1, c));
1224
108
      will_start_new_arg = false;
1225
    } else {
1226
2460
      env_argv.back() += c;
1227
    }
1228
  }
1229
1230
5423
  if (is_in_string) {
1231
    errors->push_back("invalid value for NODE_OPTIONS "
1232
                      "(unterminated string)\n");
1233
  }
1234
5423
  return env_argv;
1235
}
1236
}  // namespace node
1237
1238
5265
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1239
5197
NODE_MODULE_EXTERNAL_REFERENCE(options,
1240
                               node::options_parser::RegisterExternalReferences)