GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 469 498 94.2 %
Date: 2022-05-21 04:15:56 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
10918
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
10918
  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
21836
      SplitString(inspect_publish_uid_string, ',');
53
10918
  inspect_publish_uid.console = false;
54
10918
  inspect_publish_uid.http = false;
55
32752
  for (const std::string& destination : destinations) {
56
21834
    if (destination == "stderr") {
57
10917
      inspect_publish_uid.console = true;
58
10917
    } else if (destination == "http") {
59
10917
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
10918
}
66
67
10370
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

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

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

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

49
    if (module_type != "commonjs" && module_type != "module") {
112
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
113
    }
114
  }
115
116
10918
  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

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

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

10918
  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
10918
  if (heap_snapshot_near_heap_limit < 0) {
143
    errors->push_back("--heap-snapshot-near-heap-limit must not be negative");
144
  }
145
146
10918
  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
10918
  if (!cpu_prof) {
166
10907
    if (!cpu_prof_name.empty()) {
167
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
168
    }
169
10907
    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
10907
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
175
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
176
    }
177
  }
178
179


10918
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
180
1
      cpu_prof_dir = diagnostic_dir;
181
    }
182
183
10918
  if (!heap_prof) {
184
10907
    if (!heap_prof_name.empty()) {
185
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
186
    }
187
10907
    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
10907
    if (heap_prof_interval != kDefaultHeapProfInterval) {
193
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
194
    }
195
  }
196
197


10918
  if (heap_prof && heap_prof_dir.empty() && !diagnostic_dir.empty()) {
198
1
    heap_prof_dir = diagnostic_dir;
199
  }
200
201
10918
  debug_options_.CheckOptions(errors);
202
#endif  // HAVE_INSPECTOR
203
10918
}
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
5252
  explicit EnvironmentOptionsParser(const DebugOptionsParser& dop)
216
5252
    : EnvironmentOptionsParser() {
217
5252
    Insert(dop, &EnvironmentOptions::get_debug_options);
218
5252
  }
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
10370
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
10370
  _ppop_instance.Parse(
270
    args, exec_args, v8_args, options, required_env_settings, errors);
271
10370
}
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
5252
DebugOptionsParser::DebugOptionsParser() {
278
5252
  AddOption("--inspect-port",
279
            "set host:port for inspector",
280
            &DebugOptions::host_port,
281
            kAllowedInEnvironment);
282
5252
  AddAlias("--debug-port", "--inspect-port");
283
284
5252
  AddOption("--inspect",
285
            "activate inspector on host:port (default: 127.0.0.1:9229)",
286
            &DebugOptions::inspector_enabled,
287
            kAllowedInEnvironment);
288
15756
  AddAlias("--inspect=", { "--inspect-port", "--inspect" });
289
290
5252
  AddOption("--debug", "", &DebugOptions::deprecated_debug);
291
5252
  AddAlias("--debug=", "--debug");
292
5252
  AddOption("--debug-brk", "", &DebugOptions::deprecated_debug);
293
5252
  AddAlias("--debug-brk=", "--debug-brk");
294
295
5252
  AddOption("--inspect-brk",
296
            "activate inspector on host:port and break at start of user script",
297
            &DebugOptions::break_first_line,
298
            kAllowedInEnvironment);
299
5252
  Implies("--inspect-brk", "--inspect");
300
15756
  AddAlias("--inspect-brk=", { "--inspect-port", "--inspect-brk" });
301
302
5252
  AddOption("--inspect-brk-node", "", &DebugOptions::break_node_first_line);
303
5252
  Implies("--inspect-brk-node", "--inspect");
304
15756
  AddAlias("--inspect-brk-node=", { "--inspect-port", "--inspect-brk-node" });
305
306
5252
  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
5252
}
312
313
5252
EnvironmentOptionsParser::EnvironmentOptionsParser() {
314
5252
  AddOption("--conditions",
315
            "additional user conditions for conditional exports and imports",
316
            &EnvironmentOptions::conditions,
317
            kAllowedInEnvironment);
318
5252
  AddAlias("-C", "--conditions");
319
5252
  AddOption("--diagnostic-dir",
320
            "set dir for all output files"
321
            " (default: current working directory)",
322
            &EnvironmentOptions::diagnostic_dir,
323
            kAllowedInEnvironment);
324
5252
  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
5252
  AddOption("--enable-source-maps",
332
            "Source Map V3 support for stack traces",
333
            &EnvironmentOptions::enable_source_maps,
334
            kAllowedInEnvironment);
335
5252
  AddOption("--experimental-abortcontroller", "",
336
            NoOp{}, kAllowedInEnvironment);
337
5252
  AddOption("--experimental-fetch",
338
            "experimental Fetch API",
339
            &EnvironmentOptions::experimental_fetch,
340
            kAllowedInEnvironment,
341
            true);
342
5252
  AddOption("--experimental-global-webcrypto",
343
            "expose experimental Web Crypto API on the global scope",
344
            &EnvironmentOptions::experimental_global_web_crypto,
345
            kAllowedInEnvironment);
346
5252
  AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvironment);
347
5252
  AddOption("--experimental-loader",
348
            "use the specified module as a custom loader",
349
            &EnvironmentOptions::userland_loaders,
350
            kAllowedInEnvironment);
351
5252
  AddAlias("--loader", "--experimental-loader");
352
5252
  AddOption("--experimental-modules", "", NoOp{}, kAllowedInEnvironment);
353
5252
  AddOption("--experimental-network-imports",
354
            "experimental https: support for the ES Module loader",
355
            &EnvironmentOptions::experimental_https_modules,
356
            kAllowedInEnvironment);
357
5252
  AddOption("--experimental-wasm-modules",
358
            "experimental ES Module support for webassembly modules",
359
            &EnvironmentOptions::experimental_wasm_modules,
360
            kAllowedInEnvironment);
361
5252
  AddOption("--experimental-import-meta-resolve",
362
            "experimental ES Module import.meta.resolve() support",
363
            &EnvironmentOptions::experimental_import_meta_resolve,
364
            kAllowedInEnvironment);
365
5252
  AddOption("--experimental-policy",
366
            "use the specified file as a "
367
            "security policy",
368
            &EnvironmentOptions::experimental_policy,
369
            kAllowedInEnvironment);
370
5252
  AddOption("[has_policy_integrity_string]",
371
            "",
372
            &EnvironmentOptions::has_policy_integrity_string);
373
5252
  AddOption("--policy-integrity",
374
            "ensure the security policy contents match "
375
            "the specified integrity",
376
            &EnvironmentOptions::experimental_policy_integrity,
377
            kAllowedInEnvironment);
378
5252
  Implies("--policy-integrity", "[has_policy_integrity_string]");
379
5252
  AddOption("--experimental-repl-await",
380
            "experimental await keyword support in REPL",
381
            &EnvironmentOptions::experimental_repl_await,
382
            kAllowedInEnvironment,
383
            true);
384
5252
  AddOption("--experimental-vm-modules",
385
            "experimental ES Module support in vm module",
386
            &EnvironmentOptions::experimental_vm_modules,
387
            kAllowedInEnvironment);
388
5252
  AddOption("--experimental-worker", "", NoOp{}, kAllowedInEnvironment);
389
5252
  AddOption("--experimental-report", "", NoOp{}, kAllowedInEnvironment);
390
5252
  AddOption("--experimental-wasi-unstable-preview1",
391
            "experimental WASI support",
392
            &EnvironmentOptions::experimental_wasi,
393
            kAllowedInEnvironment);
394
5252
  AddOption("--expose-internals", "", &EnvironmentOptions::expose_internals);
395
5252
  AddOption("--frozen-intrinsics",
396
            "experimental frozen intrinsics support",
397
            &EnvironmentOptions::frozen_intrinsics,
398
            kAllowedInEnvironment);
399
5252
  AddOption("--heapsnapshot-signal",
400
            "Generate heap snapshot on specified signal",
401
            &EnvironmentOptions::heap_snapshot_signal,
402
            kAllowedInEnvironment);
403
5252
  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
5252
  AddOption("--http-parser", "", NoOp{}, kAllowedInEnvironment);
410
5252
  AddOption("--insecure-http-parser",
411
            "use an insecure HTTP parser that accepts invalid HTTP headers",
412
            &EnvironmentOptions::insecure_http_parser,
413
            kAllowedInEnvironment);
414
5252
  AddOption("--input-type",
415
            "set module type for string input",
416
            &EnvironmentOptions::module_type,
417
            kAllowedInEnvironment);
418
5252
  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
5252
  AddAlias("--es-module-specifier-resolution",
424
           "--experimental-specifier-resolution");
425
5252
  AddOption("--deprecation",
426
            "silence deprecation warnings",
427
            &EnvironmentOptions::deprecation,
428
            kAllowedInEnvironment,
429
            true);
430
5252
  AddOption("--force-async-hooks-checks",
431
            "disable checks for async_hooks",
432
            &EnvironmentOptions::force_async_hooks_checks,
433
            kAllowedInEnvironment,
434
            true);
435
5252
  AddOption("--addons",
436
            "disable loading native addons",
437
            &EnvironmentOptions::allow_native_addons,
438
            kAllowedInEnvironment,
439
            true);
440
5252
  AddOption("--global-search-paths",
441
            "disable global module search paths",
442
            &EnvironmentOptions::global_search_paths,
443
            kAllowedInEnvironment,
444
            true);
445
5252
  AddOption("--warnings",
446
            "silence all process warnings",
447
            &EnvironmentOptions::warnings,
448
            kAllowedInEnvironment,
449
            true);
450
5252
  AddOption("--force-context-aware",
451
            "disable loading non-context-aware addons",
452
            &EnvironmentOptions::force_context_aware,
453
            kAllowedInEnvironment);
454
5252
  AddOption("--pending-deprecation",
455
            "emit pending deprecation warnings",
456
            &EnvironmentOptions::pending_deprecation,
457
            kAllowedInEnvironment);
458
5252
  AddOption("--preserve-symlinks",
459
            "preserve symbolic links when resolving",
460
            &EnvironmentOptions::preserve_symlinks,
461
            kAllowedInEnvironment);
462
5252
  AddOption("--preserve-symlinks-main",
463
            "preserve symbolic links when resolving the main module",
464
            &EnvironmentOptions::preserve_symlinks_main,
465
            kAllowedInEnvironment);
466
5252
  AddOption("--prof",
467
            "Generate V8 profiler output.",
468
            V8Option{});
469
5252
  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
15756
  AddAlias("--prof-process", { "--prof-process", "--" });
474
#if HAVE_INSPECTOR
475
5252
  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
5252
  AddOption("--cpu-prof-name",
481
            "specified file name of the V8 CPU profile generated with "
482
            "--cpu-prof",
483
            &EnvironmentOptions::cpu_prof_name);
484
5252
  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
5252
  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
5252
  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
5252
  AddOption("--heap-prof-name",
499
            "specified file name of the V8 heap profile generated with "
500
            "--heap-prof",
501
            &EnvironmentOptions::heap_prof_name);
502
5252
  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
5252
  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
5252
  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
5252
  AddOption("--redirect-warnings",
516
            "write warnings to file instead of stderr",
517
            &EnvironmentOptions::redirect_warnings,
518
            kAllowedInEnvironment);
519
5252
  AddOption("--test",
520
            "launch test runner on startup",
521
            &EnvironmentOptions::test_runner);
522
5252
  AddOption("--test-only",
523
            "run tests with 'only' option set",
524
            &EnvironmentOptions::test_only,
525
            kAllowedInEnvironment);
526
5252
  AddOption("--test-udp-no-try-send", "",  // For testing only.
527
            &EnvironmentOptions::test_udp_no_try_send);
528
5252
  AddOption("--throw-deprecation",
529
            "throw an exception on deprecations",
530
            &EnvironmentOptions::throw_deprecation,
531
            kAllowedInEnvironment);
532
5252
  AddOption("--trace-atomics-wait",
533
            "trace Atomics.wait() operations",
534
            &EnvironmentOptions::trace_atomics_wait,
535
            kAllowedInEnvironment);
536
5252
  AddOption("--trace-deprecation",
537
            "show stack traces on deprecations",
538
            &EnvironmentOptions::trace_deprecation,
539
            kAllowedInEnvironment);
540
5252
  AddOption("--trace-exit",
541
            "show stack trace when an environment exits",
542
            &EnvironmentOptions::trace_exit,
543
            kAllowedInEnvironment);
544
5252
  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
5252
  AddOption("--trace-tls",
550
            "prints TLS packet trace information to stderr",
551
            &EnvironmentOptions::trace_tls,
552
            kAllowedInEnvironment);
553
5252
  AddOption("--trace-uncaught",
554
            "show stack traces for the `throw` behind uncaught exceptions",
555
            &EnvironmentOptions::trace_uncaught,
556
            kAllowedInEnvironment);
557
5252
  AddOption("--trace-warnings",
558
            "show stack traces on process warnings",
559
            &EnvironmentOptions::trace_warnings,
560
            kAllowedInEnvironment);
561
5252
  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
5252
  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
5252
  AddOption("--verify-base-objects",
576
            "", /* undocumented, only for debugging */
577
            &EnvironmentOptions::verify_base_objects,
578
            kAllowedInEnvironment);
579
580
5252
  AddOption("--check",
581
            "syntax check script without executing",
582
            &EnvironmentOptions::syntax_check_only);
583
5252
  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
5252
  AddOption("[has_eval_string]", "", &EnvironmentOptions::has_eval_string);
591
5252
  AddOption("--eval", "evaluate script", &EnvironmentOptions::eval_string);
592
5252
  Implies("--eval", "[has_eval_string]");
593
5252
  AddOption("--print",
594
            "evaluate script and print result",
595
            &EnvironmentOptions::print_eval);
596
5252
  AddAlias("-e", "--eval");
597
5252
  AddAlias("--print <arg>", "-pe");
598
15756
  AddAlias("-pe", { "--print", "--eval" });
599
5252
  AddAlias("-p", "--print");
600
5252
  AddOption("--require",
601
            "module to preload (option can be repeated)",
602
            &EnvironmentOptions::preload_modules,
603
            kAllowedInEnvironment);
604
5252
  AddAlias("-r", "--require");
605
5252
  AddOption("--interactive",
606
            "always enter the REPL even if stdin does not appear "
607
            "to be a terminal",
608
            &EnvironmentOptions::force_repl);
609
5252
  AddAlias("-i", "--interactive");
610
611
5252
  AddOption("--napi-modules", "", NoOp{}, kAllowedInEnvironment);
612
613
5252
  AddOption("--tls-keylog",
614
            "log TLS decryption keys to named file for traffic analysis",
615
            &EnvironmentOptions::tls_keylog, kAllowedInEnvironment);
616
617
5252
  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
5252
  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
5252
  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
5252
  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
5252
  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
5252
  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
5252
}
646
647
5252
PerIsolateOptionsParser::PerIsolateOptionsParser(
648
5252
  const EnvironmentOptionsParser& eop) {
649
5252
  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
5252
  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
5252
  AddOption("--interpreted-frames-native-stack",
661
            "help system profilers to translate JavaScript interpreted frames",
662
            V8Option{}, kAllowedInEnvironment);
663
5252
  AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvironment);
664
5252
  AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvironment);
665
5252
  AddOption("--perf-basic-prof-only-functions",
666
            "",
667
            V8Option{},
668
            kAllowedInEnvironment);
669
5252
  AddOption("--perf-prof", "", V8Option{}, kAllowedInEnvironment);
670
5252
  AddOption("--perf-prof-unwinding-info",
671
            "",
672
            V8Option{},
673
            kAllowedInEnvironment);
674
5252
  AddOption("--stack-trace-limit", "", V8Option{}, kAllowedInEnvironment);
675
5252
  AddOption("--disallow-code-generation-from-strings",
676
            "disallow eval and friends",
677
            V8Option{},
678
            kAllowedInEnvironment);
679
5252
  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
5252
  AddOption("--jitless",
685
             "disable runtime allocation of executable memory",
686
             V8Option{},
687
             kAllowedInEnvironment);
688
5252
  AddOption("--report-uncaught-exception",
689
            "generate diagnostic report on uncaught exceptions",
690
            &PerIsolateOptions::report_uncaught_exception,
691
            kAllowedInEnvironment);
692
5252
  AddOption("--report-on-signal",
693
            "generate diagnostic report upon receiving signals",
694
            &PerIsolateOptions::report_on_signal,
695
            kAllowedInEnvironment);
696
5252
  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
5252
  Implies("--report-signal", "--report-on-signal");
702
703
5252
  AddOption(
704
      "--experimental-top-level-await", "", NoOp{}, kAllowedInEnvironment);
705
706
5252
  AddOption("--experimental-shadow-realm",
707
            "",
708
            &PerIsolateOptions::experimental_shadow_realm,
709
            kAllowedInEnvironment);
710
5252
  AddOption("--harmony-shadow-realm", "", V8Option{});
711
5252
  Implies("--experimental-shadow-realm", "--harmony-shadow-realm");
712
5252
  Implies("--harmony-shadow-realm", "--experimental-shadow-realm");
713
5252
  ImpliesNot("--no-harmony-shadow-realm", "--experimental-shadow-realm");
714
715
5252
  Insert(eop, &PerIsolateOptions::get_per_env_options);
716
5252
}
717
718
5252
PerProcessOptionsParser::PerProcessOptionsParser(
719
5252
  const PerIsolateOptionsParser& iop) {
720
5252
  AddOption("--title",
721
            "the process title to use on startup",
722
            &PerProcessOptions::title,
723
            kAllowedInEnvironment);
724
5252
  AddOption("--trace-event-categories",
725
            "comma separated list of trace event categories to record",
726
            &PerProcessOptions::trace_event_categories,
727
            kAllowedInEnvironment);
728
5252
  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
15756
  AddAlias("--trace-events-enabled", {
734
10504
    "--trace-event-categories", "v8,node,node.async_hooks" });
735
5252
  AddOption("--v8-pool-size",
736
            "set V8's thread pool size",
737
            &PerProcessOptions::v8_thread_pool_size,
738
            kAllowedInEnvironment);
739
5252
  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
5252
  AddOption("--debug-arraybuffer-allocations",
745
            "", /* undocumented, only for debugging */
746
            &PerProcessOptions::debug_arraybuffer_allocations,
747
            kAllowedInEnvironment);
748
5252
  AddOption("--disable-proto",
749
            "disable Object.prototype.__proto__",
750
            &PerProcessOptions::disable_proto,
751
            kAllowedInEnvironment);
752
5252
  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
5252
  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
5252
  AddOption("--security-revert", "", &PerProcessOptions::security_reverts);
765
5252
  AddAlias("--security-reverts", "--security-revert");
766
5252
  AddOption("--completion-bash",
767
            "print source-able bash completion script",
768
            &PerProcessOptions::print_bash_completion);
769
5252
  AddOption("--help",
770
            "print node command line options",
771
            &PerProcessOptions::print_help);
772
5252
  AddAlias("-h", "--help");
773
5252
  AddOption(
774
      "--version", "print Node.js version", &PerProcessOptions::print_version);
775
5252
  AddAlias("-v", "--version");
776
5252
  AddOption("--v8-options",
777
            "print V8 command line options",
778
            &PerProcessOptions::print_v8_help);
779
5252
  AddOption("--report-compact",
780
            "output compact single-line JSON",
781
            &PerProcessOptions::report_compact,
782
            kAllowedInEnvironment);
783
5252
  AddOption("--report-dir",
784
            "define custom report pathname."
785
            " (default: current working directory)",
786
            &PerProcessOptions::report_directory,
787
            kAllowedInEnvironment);
788
5252
  AddAlias("--report-directory", "--report-dir");
789
5252
  AddOption("--report-filename",
790
            "define custom report file name."
791
            " (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)",
792
            &PerProcessOptions::report_filename,
793
            kAllowedInEnvironment);
794
5252
  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
5252
  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
5252
  AddOption("--openssl-config",
812
            "load OpenSSL configuration from the specified file "
813
            "(overrides OPENSSL_CONF)",
814
            &PerProcessOptions::openssl_config,
815
            kAllowedInEnvironment);
816
5252
  AddOption("--tls-cipher-list",
817
            "use an alternative default TLS cipher list",
818
            &PerProcessOptions::tls_cipher_list,
819
            kAllowedInEnvironment);
820
5252
  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
5252
  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
5252
  AddOption("[ssl_openssl_cert_store]",
840
            "",
841
            &PerProcessOptions::ssl_openssl_cert_store);
842
5252
  Implies("--use-openssl-ca", "[ssl_openssl_cert_store]");
843
5252
  ImpliesNot("--use-bundled-ca", "[ssl_openssl_cert_store]");
844
5252
  AddOption("--enable-fips",
845
            "enable FIPS crypto at startup",
846
            &PerProcessOptions::enable_fips_crypto,
847
            kAllowedInEnvironment);
848
5252
  AddOption("--force-fips",
849
            "force FIPS crypto (cannot be disabled)",
850
            &PerProcessOptions::force_fips_crypto,
851
            kAllowedInEnvironment);
852
5252
  AddOption("--secure-heap",
853
            "total size of the OpenSSL secure heap",
854
            &PerProcessOptions::secure_heap,
855
            kAllowedInEnvironment);
856
5252
  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
5252
  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
5252
  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
5252
  AddOption("--trace-sigint",
877
            "enable printing JavaScript stacktrace on SIGINT",
878
            &PerProcessOptions::trace_sigint,
879
            kAllowedInEnvironment);
880
881
5252
  Insert(iop, &PerProcessOptions::get_per_isolate_options);
882
883
5252
  AddOption("--node-memory-debug",
884
            "Run with extra debug checks for memory leaks in Node.js itself",
885
            NoOp{}, kAllowedInEnvironment);
886
5252
  Implies("--node-memory-debug", "--debug-arraybuffer-allocations");
887
5252
  Implies("--node-memory-debug", "--verify-base-objects");
888
5252
}
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
6545
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
976
6545
  Environment* env = Environment::GetCurrent(args);
977
6545
  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
6545
  env->set_has_serialized_options(true);
983
984
6545
  Isolate* isolate = env->isolate();
985
6545
  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
6545
  auto original_per_isolate = per_process::cli_options->per_isolate;
991
6545
  per_process::cli_options->per_isolate = env->isolate_data()->options();
992
6545
  auto original_per_env = per_process::cli_options->per_isolate->per_env;
993
6545
  per_process::cli_options->per_isolate->per_env = env->options();
994
6545
  auto on_scope_leave = OnScopeLeave([&]() {
995
6545
    per_process::cli_options->per_isolate->per_env = original_per_env;
996
6545
    per_process::cli_options->per_isolate = original_per_isolate;
997
6545
  });
998
999
6545
  Local<Map> options = Map::New(isolate);
1000
6545
  if (options
1001
13090
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1002
6545
          .IsNothing()) {
1003
    return;
1004
  }
1005
1006
890120
  for (const auto& item : _ppop_instance.options_) {
1007
    Local<Value> value;
1008
883575
    const auto& option_info = item.second;
1009
883575
    auto field = option_info.field;
1010
883575
    PerProcessOptions* opts = per_process::cli_options.get();
1011


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

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

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

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

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

1767150
             .FromMaybe(false) ||
1091

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

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

26180
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1109
    return;
1110
  }
1111
1112
13090
  args.GetReturnValue().Set(ret);
1113
}
1114
1115
5997
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1116
5997
  Environment* env = Environment::GetCurrent(args);
1117
5997
  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
5997
  Isolate* isolate = args.GetIsolate();
1123
5997
  Local<Context> context = env->context();
1124
5997
  Local<Object> ret = Object::New(isolate);
1125
1126
11994
  if (ret->Set(context,
1127
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1128
17991
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1129
5997
      .IsNothing()) return;
1130
1131
11994
  if (ret->Set(context,
1132
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1133
17991
           Boolean::New(isolate, env->no_global_search_paths()))
1134
5997
      .IsNothing()) return;
1135
1136
11994
  args.GetReturnValue().Set(ret);
1137
}
1138
1139
856
void Initialize(Local<Object> target,
1140
                Local<Value> unused,
1141
                Local<Context> context,
1142
                void* priv) {
1143
856
  Environment* env = Environment::GetCurrent(context);
1144
856
  Isolate* isolate = env->isolate();
1145
856
  env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions);
1146
856
  env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions);
1147
1148
856
  Local<Object> env_settings = Object::New(isolate);
1149
2568
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1150
2568
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1151
  target
1152
856
      ->Set(
1153
1712
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1154
      .Check();
1155
1156
856
  Local<Object> types = Object::New(isolate);
1157
2568
  NODE_DEFINE_CONSTANT(types, kNoOp);
1158
2568
  NODE_DEFINE_CONSTANT(types, kV8Option);
1159
2568
  NODE_DEFINE_CONSTANT(types, kBoolean);
1160
2568
  NODE_DEFINE_CONSTANT(types, kInteger);
1161
2568
  NODE_DEFINE_CONSTANT(types, kUInteger);
1162
2568
  NODE_DEFINE_CONSTANT(types, kString);
1163
2568
  NODE_DEFINE_CONSTANT(types, kHostPort);
1164
2568
  NODE_DEFINE_CONSTANT(types, kStringList);
1165
1712
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1166
      .Check();
1167
856
}
1168
1169
5184
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1170
5184
  registry->Register(GetCLIOptions);
1171
5184
  registry->Register(GetEmbedderOptions);
1172
5184
}
1173
}  // namespace options_parser
1174
1175
5252
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1176
5252
  HandleEnvOptions(env_options, [](const char* name) {
1177
21008
    std::string text;
1178

21008
    return credentials::SafeGetenv(name, &text) ? text : "";
1179
  });
1180
5252
}
1181
1182
5528
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1183
                      std::function<std::string(const char*)> opt_getter) {
1184
5528
  env_options->pending_deprecation =
1185
11056
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1186
1187
5528
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1188
1189
5528
  env_options->preserve_symlinks_main =
1190
11056
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1191
1192
5528
  if (env_options->redirect_warnings.empty())
1193
5528
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1194
5528
}
1195
1196
5410
std::vector<std::string> ParseNodeOptionsEnvVar(
1197
    const std::string& node_options, std::vector<std::string>* errors) {
1198
5410
  std::vector<std::string> env_argv;
1199
1200
5410
  bool is_in_string = false;
1201
5410
  bool will_start_new_arg = true;
1202
8014
  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
5410
  if (is_in_string) {
1231
    errors->push_back("invalid value for NODE_OPTIONS "
1232
                      "(unterminated string)\n");
1233
  }
1234
5410
  return env_argv;
1235
}
1236
}  // namespace node
1237
1238
5252
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1239
5184
NODE_MODULE_EXTERNAL_REFERENCE(options,
1240
                               node::options_parser::RegisterExternalReferences)