GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 464 493 94.1 %
Date: 2022-04-29 04:15:07 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
10578
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
10578
  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
21156
      SplitString(inspect_publish_uid_string, ',');
53
10578
  inspect_publish_uid.console = false;
54
10578
  inspect_publish_uid.http = false;
55
31732
  for (const std::string& destination : destinations) {
56
21154
    if (destination == "stderr") {
57
10577
      inspect_publish_uid.console = true;
58
10577
    } else if (destination == "http") {
59
10577
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
10578
}
66
67
10032
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

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

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

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

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

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

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

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


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


10578
  if (heap_prof && heap_prof_dir.empty() && !diagnostic_dir.empty()) {
198
1
    heap_prof_dir = diagnostic_dir;
199
  }
200
201
10578
  debug_options_.CheckOptions(errors);
202
#endif  // HAVE_INSPECTOR
203
10578
}
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
5089
  explicit EnvironmentOptionsParser(const DebugOptionsParser& dop)
216
5089
    : EnvironmentOptionsParser() {
217
5089
    Insert(dop, &EnvironmentOptions::get_debug_options);
218
5089
  }
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
546
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
546
  _piop_instance.Parse(
260
    args, exec_args, v8_args, options, required_env_settings, errors);
261
546
}
262
263
template <>
264
10032
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
10032
  _ppop_instance.Parse(
270
    args, exec_args, v8_args, options, required_env_settings, errors);
271
10032
}
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
5089
DebugOptionsParser::DebugOptionsParser() {
278
5089
  AddOption("--inspect-port",
279
            "set host:port for inspector",
280
            &DebugOptions::host_port,
281
            kAllowedInEnvironment);
282
5089
  AddAlias("--debug-port", "--inspect-port");
283
284
5089
  AddOption("--inspect",
285
            "activate inspector on host:port (default: 127.0.0.1:9229)",
286
            &DebugOptions::inspector_enabled,
287
            kAllowedInEnvironment);
288
15267
  AddAlias("--inspect=", { "--inspect-port", "--inspect" });
289
290
5089
  AddOption("--debug", "", &DebugOptions::deprecated_debug);
291
5089
  AddAlias("--debug=", "--debug");
292
5089
  AddOption("--debug-brk", "", &DebugOptions::deprecated_debug);
293
5089
  AddAlias("--debug-brk=", "--debug-brk");
294
295
5089
  AddOption("--inspect-brk",
296
            "activate inspector on host:port and break at start of user script",
297
            &DebugOptions::break_first_line,
298
            kAllowedInEnvironment);
299
5089
  Implies("--inspect-brk", "--inspect");
300
15267
  AddAlias("--inspect-brk=", { "--inspect-port", "--inspect-brk" });
301
302
5089
  AddOption("--inspect-brk-node", "", &DebugOptions::break_node_first_line);
303
5089
  Implies("--inspect-brk-node", "--inspect");
304
15267
  AddAlias("--inspect-brk-node=", { "--inspect-port", "--inspect-brk-node" });
305
306
5089
  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
5089
}
312
313
5089
EnvironmentOptionsParser::EnvironmentOptionsParser() {
314
5089
  AddOption("--conditions",
315
            "additional user conditions for conditional exports and imports",
316
            &EnvironmentOptions::conditions,
317
            kAllowedInEnvironment);
318
5089
  AddAlias("-C", "--conditions");
319
5089
  AddOption("--diagnostic-dir",
320
            "set dir for all output files"
321
            " (default: current working directory)",
322
            &EnvironmentOptions::diagnostic_dir,
323
            kAllowedInEnvironment);
324
5089
  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
5089
  AddOption("--enable-source-maps",
332
            "Source Map V3 support for stack traces",
333
            &EnvironmentOptions::enable_source_maps,
334
            kAllowedInEnvironment);
335
5089
  AddOption("--experimental-abortcontroller", "",
336
            NoOp{}, kAllowedInEnvironment);
337
5089
  AddOption("--experimental-fetch",
338
            "experimental Fetch API",
339
            &EnvironmentOptions::experimental_fetch,
340
            kAllowedInEnvironment,
341
            true);
342
5089
  AddOption("--experimental-global-webcrypto",
343
            "expose experimental Web Crypto API on the global scope",
344
            &EnvironmentOptions::experimental_global_web_crypto,
345
            kAllowedInEnvironment);
346
5089
  AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvironment);
347
5089
  AddOption("--experimental-loader",
348
            "use the specified module as a custom loader",
349
            &EnvironmentOptions::userland_loader,
350
            kAllowedInEnvironment);
351
5089
  AddAlias("--loader", "--experimental-loader");
352
5089
  AddOption("--experimental-modules", "", NoOp{}, kAllowedInEnvironment);
353
5089
  AddOption("--experimental-network-imports",
354
            "experimental https: support for the ES Module loader",
355
            &EnvironmentOptions::experimental_https_modules,
356
            kAllowedInEnvironment);
357
5089
  AddOption("--experimental-wasm-modules",
358
            "experimental ES Module support for webassembly modules",
359
            &EnvironmentOptions::experimental_wasm_modules,
360
            kAllowedInEnvironment);
361
5089
  AddOption("--experimental-import-meta-resolve",
362
            "experimental ES Module import.meta.resolve() support",
363
            &EnvironmentOptions::experimental_import_meta_resolve,
364
            kAllowedInEnvironment);
365
5089
  AddOption("--experimental-policy",
366
            "use the specified file as a "
367
            "security policy",
368
            &EnvironmentOptions::experimental_policy,
369
            kAllowedInEnvironment);
370
5089
  AddOption("[has_policy_integrity_string]",
371
            "",
372
            &EnvironmentOptions::has_policy_integrity_string);
373
5089
  AddOption("--policy-integrity",
374
            "ensure the security policy contents match "
375
            "the specified integrity",
376
            &EnvironmentOptions::experimental_policy_integrity,
377
            kAllowedInEnvironment);
378
5089
  Implies("--policy-integrity", "[has_policy_integrity_string]");
379
5089
  AddOption("--experimental-repl-await",
380
            "experimental await keyword support in REPL",
381
            &EnvironmentOptions::experimental_repl_await,
382
            kAllowedInEnvironment,
383
            true);
384
5089
  AddOption("--experimental-vm-modules",
385
            "experimental ES Module support in vm module",
386
            &EnvironmentOptions::experimental_vm_modules,
387
            kAllowedInEnvironment);
388
5089
  AddOption("--experimental-worker", "", NoOp{}, kAllowedInEnvironment);
389
5089
  AddOption("--experimental-report", "", NoOp{}, kAllowedInEnvironment);
390
5089
  AddOption("--experimental-wasi-unstable-preview1",
391
            "experimental WASI support",
392
            &EnvironmentOptions::experimental_wasi,
393
            kAllowedInEnvironment);
394
5089
  AddOption("--expose-internals", "", &EnvironmentOptions::expose_internals);
395
5089
  AddOption("--frozen-intrinsics",
396
            "experimental frozen intrinsics support",
397
            &EnvironmentOptions::frozen_intrinsics,
398
            kAllowedInEnvironment);
399
5089
  AddOption("--heapsnapshot-signal",
400
            "Generate heap snapshot on specified signal",
401
            &EnvironmentOptions::heap_snapshot_signal,
402
            kAllowedInEnvironment);
403
5089
  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
5089
  AddOption("--http-parser", "", NoOp{}, kAllowedInEnvironment);
410
5089
  AddOption("--insecure-http-parser",
411
            "use an insecure HTTP parser that accepts invalid HTTP headers",
412
            &EnvironmentOptions::insecure_http_parser,
413
            kAllowedInEnvironment);
414
5089
  AddOption("--input-type",
415
            "set module type for string input",
416
            &EnvironmentOptions::module_type,
417
            kAllowedInEnvironment);
418
5089
  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
5089
  AddAlias("--es-module-specifier-resolution",
424
           "--experimental-specifier-resolution");
425
5089
  AddOption("--deprecation",
426
            "silence deprecation warnings",
427
            &EnvironmentOptions::deprecation,
428
            kAllowedInEnvironment,
429
            true);
430
5089
  AddOption("--force-async-hooks-checks",
431
            "disable checks for async_hooks",
432
            &EnvironmentOptions::force_async_hooks_checks,
433
            kAllowedInEnvironment,
434
            true);
435
5089
  AddOption("--addons",
436
            "disable loading native addons",
437
            &EnvironmentOptions::allow_native_addons,
438
            kAllowedInEnvironment,
439
            true);
440
5089
  AddOption("--global-search-paths",
441
            "disable global module search paths",
442
            &EnvironmentOptions::global_search_paths,
443
            kAllowedInEnvironment,
444
            true);
445
5089
  AddOption("--warnings",
446
            "silence all process warnings",
447
            &EnvironmentOptions::warnings,
448
            kAllowedInEnvironment,
449
            true);
450
5089
  AddOption("--force-context-aware",
451
            "disable loading non-context-aware addons",
452
            &EnvironmentOptions::force_context_aware,
453
            kAllowedInEnvironment);
454
5089
  AddOption("--pending-deprecation",
455
            "emit pending deprecation warnings",
456
            &EnvironmentOptions::pending_deprecation,
457
            kAllowedInEnvironment);
458
5089
  AddOption("--preserve-symlinks",
459
            "preserve symbolic links when resolving",
460
            &EnvironmentOptions::preserve_symlinks,
461
            kAllowedInEnvironment);
462
5089
  AddOption("--preserve-symlinks-main",
463
            "preserve symbolic links when resolving the main module",
464
            &EnvironmentOptions::preserve_symlinks_main,
465
            kAllowedInEnvironment);
466
5089
  AddOption("--prof",
467
            "Generate V8 profiler output.",
468
            V8Option{});
469
5089
  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
15267
  AddAlias("--prof-process", { "--prof-process", "--" });
474
#if HAVE_INSPECTOR
475
5089
  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
5089
  AddOption("--cpu-prof-name",
481
            "specified file name of the V8 CPU profile generated with "
482
            "--cpu-prof",
483
            &EnvironmentOptions::cpu_prof_name);
484
5089
  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
5089
  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
5089
  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
5089
  AddOption("--heap-prof-name",
499
            "specified file name of the V8 heap profile generated with "
500
            "--heap-prof",
501
            &EnvironmentOptions::heap_prof_name);
502
5089
  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
5089
  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
5089
  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
5089
  AddOption("--redirect-warnings",
516
            "write warnings to file instead of stderr",
517
            &EnvironmentOptions::redirect_warnings,
518
            kAllowedInEnvironment);
519
5089
  AddOption("--test",
520
            "launch test runner on startup",
521
            &EnvironmentOptions::test_runner);
522
5089
  AddOption("--test-only",
523
            "run tests with 'only' option set",
524
            &EnvironmentOptions::test_only,
525
            kAllowedInEnvironment);
526
5089
  AddOption("--test-udp-no-try-send", "",  // For testing only.
527
            &EnvironmentOptions::test_udp_no_try_send);
528
5089
  AddOption("--throw-deprecation",
529
            "throw an exception on deprecations",
530
            &EnvironmentOptions::throw_deprecation,
531
            kAllowedInEnvironment);
532
5089
  AddOption("--trace-atomics-wait",
533
            "trace Atomics.wait() operations",
534
            &EnvironmentOptions::trace_atomics_wait,
535
            kAllowedInEnvironment);
536
5089
  AddOption("--trace-deprecation",
537
            "show stack traces on deprecations",
538
            &EnvironmentOptions::trace_deprecation,
539
            kAllowedInEnvironment);
540
5089
  AddOption("--trace-exit",
541
            "show stack trace when an environment exits",
542
            &EnvironmentOptions::trace_exit,
543
            kAllowedInEnvironment);
544
5089
  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
5089
  AddOption("--trace-tls",
550
            "prints TLS packet trace information to stderr",
551
            &EnvironmentOptions::trace_tls,
552
            kAllowedInEnvironment);
553
5089
  AddOption("--trace-uncaught",
554
            "show stack traces for the `throw` behind uncaught exceptions",
555
            &EnvironmentOptions::trace_uncaught,
556
            kAllowedInEnvironment);
557
5089
  AddOption("--trace-warnings",
558
            "show stack traces on process warnings",
559
            &EnvironmentOptions::trace_warnings,
560
            kAllowedInEnvironment);
561
5089
  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
5089
  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
5089
  AddOption("--verify-base-objects",
576
            "", /* undocumented, only for debugging */
577
            &EnvironmentOptions::verify_base_objects,
578
            kAllowedInEnvironment);
579
580
5089
  AddOption("--check",
581
            "syntax check script without executing",
582
            &EnvironmentOptions::syntax_check_only);
583
5089
  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
5089
  AddOption("[has_eval_string]", "", &EnvironmentOptions::has_eval_string);
591
5089
  AddOption("--eval", "evaluate script", &EnvironmentOptions::eval_string);
592
5089
  Implies("--eval", "[has_eval_string]");
593
5089
  AddOption("--print",
594
            "evaluate script and print result",
595
            &EnvironmentOptions::print_eval);
596
5089
  AddAlias("-e", "--eval");
597
5089
  AddAlias("--print <arg>", "-pe");
598
15267
  AddAlias("-pe", { "--print", "--eval" });
599
5089
  AddAlias("-p", "--print");
600
5089
  AddOption("--require",
601
            "module to preload (option can be repeated)",
602
            &EnvironmentOptions::preload_modules,
603
            kAllowedInEnvironment);
604
5089
  AddAlias("-r", "--require");
605
5089
  AddOption("--interactive",
606
            "always enter the REPL even if stdin does not appear "
607
            "to be a terminal",
608
            &EnvironmentOptions::force_repl);
609
5089
  AddAlias("-i", "--interactive");
610
611
5089
  AddOption("--napi-modules", "", NoOp{}, kAllowedInEnvironment);
612
613
5089
  AddOption("--tls-keylog",
614
            "log TLS decryption keys to named file for traffic analysis",
615
            &EnvironmentOptions::tls_keylog, kAllowedInEnvironment);
616
617
5089
  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
5089
  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
5089
  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
5089
  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
5089
  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
5089
  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
5089
}
646
647
5089
PerIsolateOptionsParser::PerIsolateOptionsParser(
648
5089
  const EnvironmentOptionsParser& eop) {
649
5089
  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
5089
  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
5089
  AddOption("--interpreted-frames-native-stack",
661
            "help system profilers to translate JavaScript interpreted frames",
662
            V8Option{}, kAllowedInEnvironment);
663
5089
  AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvironment);
664
5089
  AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvironment);
665
5089
  AddOption("--perf-basic-prof-only-functions",
666
            "",
667
            V8Option{},
668
            kAllowedInEnvironment);
669
5089
  AddOption("--perf-prof", "", V8Option{}, kAllowedInEnvironment);
670
5089
  AddOption("--perf-prof-unwinding-info",
671
            "",
672
            V8Option{},
673
            kAllowedInEnvironment);
674
5089
  AddOption("--stack-trace-limit", "", V8Option{}, kAllowedInEnvironment);
675
5089
  AddOption("--disallow-code-generation-from-strings",
676
            "disallow eval and friends",
677
            V8Option{},
678
            kAllowedInEnvironment);
679
5089
  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
5089
  AddOption("--jitless",
685
             "disable runtime allocation of executable memory",
686
             V8Option{},
687
             kAllowedInEnvironment);
688
5089
  AddOption("--report-uncaught-exception",
689
            "generate diagnostic report on uncaught exceptions",
690
            &PerIsolateOptions::report_uncaught_exception,
691
            kAllowedInEnvironment);
692
5089
  AddOption("--report-on-signal",
693
            "generate diagnostic report upon receiving signals",
694
            &PerIsolateOptions::report_on_signal,
695
            kAllowedInEnvironment);
696
5089
  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
5089
  Implies("--report-signal", "--report-on-signal");
702
703
5089
  AddOption(
704
      "--experimental-top-level-await", "", NoOp{}, kAllowedInEnvironment);
705
706
5089
  Insert(eop, &PerIsolateOptions::get_per_env_options);
707
5089
}
708
709
5089
PerProcessOptionsParser::PerProcessOptionsParser(
710
5089
  const PerIsolateOptionsParser& iop) {
711
5089
  AddOption("--title",
712
            "the process title to use on startup",
713
            &PerProcessOptions::title,
714
            kAllowedInEnvironment);
715
5089
  AddOption("--trace-event-categories",
716
            "comma separated list of trace event categories to record",
717
            &PerProcessOptions::trace_event_categories,
718
            kAllowedInEnvironment);
719
5089
  AddOption("--trace-event-file-pattern",
720
            "Template string specifying the filepath for the trace-events "
721
            "data, it supports ${rotation} and ${pid}.",
722
            &PerProcessOptions::trace_event_file_pattern,
723
            kAllowedInEnvironment);
724
15267
  AddAlias("--trace-events-enabled", {
725
10178
    "--trace-event-categories", "v8,node,node.async_hooks" });
726
5089
  AddOption("--v8-pool-size",
727
            "set V8's thread pool size",
728
            &PerProcessOptions::v8_thread_pool_size,
729
            kAllowedInEnvironment);
730
5089
  AddOption("--zero-fill-buffers",
731
            "automatically zero-fill all newly allocated Buffer and "
732
            "SlowBuffer instances",
733
            &PerProcessOptions::zero_fill_all_buffers,
734
            kAllowedInEnvironment);
735
5089
  AddOption("--debug-arraybuffer-allocations",
736
            "", /* undocumented, only for debugging */
737
            &PerProcessOptions::debug_arraybuffer_allocations,
738
            kAllowedInEnvironment);
739
5089
  AddOption("--disable-proto",
740
            "disable Object.prototype.__proto__",
741
            &PerProcessOptions::disable_proto,
742
            kAllowedInEnvironment);
743
5089
  AddOption("--build-snapshot",
744
            "Generate a snapshot blob when the process exits."
745
            "Currently only supported in the node_mksnapshot binary.",
746
            &PerProcessOptions::build_snapshot,
747
            kDisallowedInEnvironment);
748
5089
  AddOption("--node-snapshot",
749
            "",  // It's a debug-only option.
750
            &PerProcessOptions::node_snapshot,
751
            kAllowedInEnvironment);
752
  // 12.x renamed this inadvertently, so alias it for consistency within the
753
  // release line, while using the original name for consistency with older
754
  // release lines.
755
5089
  AddOption("--security-revert", "", &PerProcessOptions::security_reverts);
756
5089
  AddAlias("--security-reverts", "--security-revert");
757
5089
  AddOption("--completion-bash",
758
            "print source-able bash completion script",
759
            &PerProcessOptions::print_bash_completion);
760
5089
  AddOption("--help",
761
            "print node command line options",
762
            &PerProcessOptions::print_help);
763
5089
  AddAlias("-h", "--help");
764
5089
  AddOption(
765
      "--version", "print Node.js version", &PerProcessOptions::print_version);
766
5089
  AddAlias("-v", "--version");
767
5089
  AddOption("--v8-options",
768
            "print V8 command line options",
769
            &PerProcessOptions::print_v8_help);
770
5089
  AddOption("--report-compact",
771
            "output compact single-line JSON",
772
            &PerProcessOptions::report_compact,
773
            kAllowedInEnvironment);
774
5089
  AddOption("--report-dir",
775
            "define custom report pathname."
776
            " (default: current working directory)",
777
            &PerProcessOptions::report_directory,
778
            kAllowedInEnvironment);
779
5089
  AddAlias("--report-directory", "--report-dir");
780
5089
  AddOption("--report-filename",
781
            "define custom report file name."
782
            " (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)",
783
            &PerProcessOptions::report_filename,
784
            kAllowedInEnvironment);
785
5089
  AddOption("--report-on-fatalerror",
786
              "generate diagnostic report on fatal (internal) errors",
787
              &PerProcessOptions::report_on_fatalerror,
788
              kAllowedInEnvironment);
789
790
#ifdef NODE_HAVE_I18N_SUPPORT
791
5089
  AddOption("--icu-data-dir",
792
            "set ICU data load path to dir (overrides NODE_ICU_DATA)"
793
#ifndef NODE_HAVE_SMALL_ICU
794
            " (note: linked-in ICU data is present)"
795
#endif
796
            ,
797
            &PerProcessOptions::icu_data_dir,
798
            kAllowedInEnvironment);
799
#endif
800
801
#if HAVE_OPENSSL
802
5089
  AddOption("--openssl-config",
803
            "load OpenSSL configuration from the specified file "
804
            "(overrides OPENSSL_CONF)",
805
            &PerProcessOptions::openssl_config,
806
            kAllowedInEnvironment);
807
5089
  AddOption("--tls-cipher-list",
808
            "use an alternative default TLS cipher list",
809
            &PerProcessOptions::tls_cipher_list,
810
            kAllowedInEnvironment);
811
5089
  AddOption("--use-openssl-ca",
812
            "use OpenSSL's default CA store"
813
#if defined(NODE_OPENSSL_CERT_STORE)
814
            " (default)"
815
#endif
816
            ,
817
            &PerProcessOptions::use_openssl_ca,
818
            kAllowedInEnvironment);
819
5089
  AddOption("--use-bundled-ca",
820
            "use bundled CA store"
821
#if !defined(NODE_OPENSSL_CERT_STORE)
822
            " (default)"
823
#endif
824
            ,
825
            &PerProcessOptions::use_bundled_ca,
826
            kAllowedInEnvironment);
827
  // Similar to [has_eval_string] above, except that the separation between
828
  // this and use_openssl_ca only exists for option validation after parsing.
829
  // This is not ideal.
830
5089
  AddOption("[ssl_openssl_cert_store]",
831
            "",
832
            &PerProcessOptions::ssl_openssl_cert_store);
833
5089
  Implies("--use-openssl-ca", "[ssl_openssl_cert_store]");
834
5089
  ImpliesNot("--use-bundled-ca", "[ssl_openssl_cert_store]");
835
5089
  AddOption("--enable-fips",
836
            "enable FIPS crypto at startup",
837
            &PerProcessOptions::enable_fips_crypto,
838
            kAllowedInEnvironment);
839
5089
  AddOption("--force-fips",
840
            "force FIPS crypto (cannot be disabled)",
841
            &PerProcessOptions::force_fips_crypto,
842
            kAllowedInEnvironment);
843
5089
  AddOption("--secure-heap",
844
            "total size of the OpenSSL secure heap",
845
            &PerProcessOptions::secure_heap,
846
            kAllowedInEnvironment);
847
5089
  AddOption("--secure-heap-min",
848
            "minimum allocation size from the OpenSSL secure heap",
849
            &PerProcessOptions::secure_heap_min,
850
            kAllowedInEnvironment);
851
#endif  // HAVE_OPENSSL
852
#if OPENSSL_VERSION_MAJOR >= 3
853
5089
  AddOption("--openssl-legacy-provider",
854
            "enable OpenSSL 3.0 legacy provider",
855
            &PerProcessOptions::openssl_legacy_provider,
856
            kAllowedInEnvironment);
857
858
#endif  // OPENSSL_VERSION_MAJOR
859
5089
  AddOption("--use-largepages",
860
            "Map the Node.js static code to large pages. Options are "
861
            "'off' (the default value, meaning do not map), "
862
            "'on' (map and ignore failure, reporting it to stderr), "
863
            "or 'silent' (map and silently ignore failure)",
864
            &PerProcessOptions::use_largepages,
865
            kAllowedInEnvironment);
866
867
5089
  AddOption("--trace-sigint",
868
            "enable printing JavaScript stacktrace on SIGINT",
869
            &PerProcessOptions::trace_sigint,
870
            kAllowedInEnvironment);
871
872
5089
  Insert(iop, &PerProcessOptions::get_per_isolate_options);
873
874
5089
  AddOption("--node-memory-debug",
875
            "Run with extra debug checks for memory leaks in Node.js itself",
876
            NoOp{}, kAllowedInEnvironment);
877
5089
  Implies("--node-memory-debug", "--debug-arraybuffer-allocations");
878
5089
  Implies("--node-memory-debug", "--verify-base-objects");
879
5089
}
880
881
112
inline std::string RemoveBrackets(const std::string& host) {
882


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
883
4
    return host.substr(1, host.size() - 2);
884
  else
885
108
    return host;
886
}
887
888
100
inline int ParseAndValidatePort(const std::string& port,
889
                                std::vector<std::string>* errors) {
890
  char* endptr;
891
100
  errno = 0;
892
  const unsigned long result =                 // NOLINT(runtime/int)
893
100
    strtoul(port.c_str(), &endptr, 10);
894

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

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

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


800527
    switch (option_info.type) {
1003
126399
      case kNoOp:
1004
      case kV8Option:
1005
        // Special case for --abort-on-uncaught-exception which is also
1006
        // respected by Node.js internals
1007
126399
        if (item.first == "--abort-on-uncaught-exception") {
1008
6019
          value = Boolean::New(
1009
6019
            isolate, original_per_env->abort_on_uncaught_exception);
1010
        } else {
1011
120380
          value = Undefined(isolate);
1012
        }
1013
126399
        break;
1014
439387
      case kBoolean:
1015
878774
        value = Boolean::New(isolate,
1016
878774
                             *_ppop_instance.Lookup<bool>(field, opts));
1017
439387
        break;
1018
24076
      case kInteger:
1019
48152
        value = Number::New(
1020
            isolate,
1021
48152
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1022
24076
        break;
1023
18057
      case kUInteger:
1024
36114
        value = Number::New(
1025
            isolate,
1026
36114
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1027
18057
        break;
1028
168532
      case kString:
1029
337064
        if (!ToV8Value(context,
1030
337064
                       *_ppop_instance.Lookup<std::string>(field, opts))
1031
168532
                 .ToLocal(&value)) {
1032
          return;
1033
        }
1034
168532
        break;
1035
18057
      case kStringList:
1036
36114
        if (!ToV8Value(context,
1037
36114
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1038
18057
                 .ToLocal(&value)) {
1039
          return;
1040
        }
1041
18057
        break;
1042
6019
      case kHostPort: {
1043
        const HostPort& host_port =
1044
6019
          *_ppop_instance.Lookup<HostPort>(field, opts);
1045
6019
        Local<Object> obj = Object::New(isolate);
1046
        Local<Value> host;
1047
6019
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1048

30095
            obj->Set(context, env->host_string(), host).IsNothing() ||
1049
6019
            obj->Set(context,
1050
                     env->port_string(),
1051
24076
                     Integer::New(isolate, host_port.port()))
1052
6019
                .IsNothing()) {
1053
          return;
1054
        }
1055
6019
        value = obj;
1056
6019
        break;
1057
      }
1058
      default:
1059
        UNREACHABLE();
1060
    }
1061
800527
    CHECK(!value.IsEmpty());
1062
1063
800527
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1064
800527
    Local<Object> info = Object::New(isolate);
1065
    Local<Value> help_text;
1066
800527
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1067
1601054
        !info->Set(context, env->help_text_string(), help_text)
1068

1601054
             .FromMaybe(false) ||
1069
1601054
        !info->Set(context,
1070
                   env->env_var_settings_string(),
1071
                   Integer::New(isolate,
1072
2401581
                                static_cast<int>(option_info.env_setting)))
1073

1601054
             .FromMaybe(false) ||
1074
1601054
        !info->Set(context,
1075
                   env->type_string(),
1076
2401581
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1077

1601054
             .FromMaybe(false) ||
1078
1601054
        !info->Set(context,
1079
                   env->default_is_true_string(),
1080
2401581
                   Boolean::New(isolate, option_info.default_is_true))
1081

1601054
             .FromMaybe(false) ||
1082

4002635
        info->Set(context, env->value_string(), value).IsNothing() ||
1083

2401581
        options->Set(context, name, info).IsEmpty()) {
1084
      return;
1085
    }
1086
  }
1087
1088
  Local<Value> aliases;
1089
12038
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1090
1091
6019
  if (aliases.As<Object>()
1092
12038
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1093
6019
          .IsNothing()) {
1094
    return;
1095
  }
1096
1097
6019
  Local<Object> ret = Object::New(isolate);
1098
24076
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1099

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

20332
    return credentials::SafeGetenv(name, &text) ? text : "";
1170
  });
1171
5083
}
1172
1173
5358
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1174
                      std::function<std::string(const char*)> opt_getter) {
1175
5358
  env_options->pending_deprecation =
1176
10716
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1177
1178
5358
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1179
1180
5358
  env_options->preserve_symlinks_main =
1181
10716
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1182
1183
5358
  if (env_options->redirect_warnings.empty())
1184
5358
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1185
5358
}
1186
1187
5240
std::vector<std::string> ParseNodeOptionsEnvVar(
1188
    const std::string& node_options, std::vector<std::string>* errors) {
1189
5240
  std::vector<std::string> env_argv;
1190
1191
5240
  bool is_in_string = false;
1192
5240
  bool will_start_new_arg = true;
1193
7844
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1194
2604
    char c = node_options.at(index);
1195
1196
    // Backslashes escape the following character
1197

2604
    if (c == '\\' && is_in_string) {
1198
      if (index + 1 == node_options.size()) {
1199
        errors->push_back("invalid value for NODE_OPTIONS "
1200
                          "(invalid escape)\n");
1201
        return env_argv;
1202
      } else {
1203
        c = node_options.at(++index);
1204
      }
1205

2604
    } else if (c == ' ' && !is_in_string) {
1206
32
      will_start_new_arg = true;
1207
32
      continue;
1208
2572
    } else if (c == '"') {
1209
4
      is_in_string = !is_in_string;
1210
4
      continue;
1211
    }
1212
1213
2568
    if (will_start_new_arg) {
1214
108
      env_argv.emplace_back(std::string(1, c));
1215
108
      will_start_new_arg = false;
1216
    } else {
1217
2460
      env_argv.back() += c;
1218
    }
1219
  }
1220
1221
5240
  if (is_in_string) {
1222
    errors->push_back("invalid value for NODE_OPTIONS "
1223
                      "(unterminated string)\n");
1224
  }
1225
5240
  return env_argv;
1226
}
1227
}  // namespace node
1228
1229
5083
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1230
5015
NODE_MODULE_EXTERNAL_REFERENCE(options,
1231
                               node::options_parser::RegisterExternalReferences)