GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 471 500 94.2 %
Date: 2022-06-12 04:16:28 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
10960
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
10960
  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
21920
      SplitString(inspect_publish_uid_string, ',');
53
10960
  inspect_publish_uid.console = false;
54
10960
  inspect_publish_uid.http = false;
55
32878
  for (const std::string& destination : destinations) {
56
21918
    if (destination == "stderr") {
57
10959
      inspect_publish_uid.console = true;
58
10959
    } else if (destination == "http") {
59
10959
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
10960
}
66
67
10412
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

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

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

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

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

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

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

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


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


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
902
4
    return host.substr(1, host.size() - 2);
903
  else
904
108
    return host;
905
}
906
907
100
inline int ParseAndValidatePort(const std::string& port,
908
                                std::vector<std::string>* errors) {
909
  char* endptr;
910
100
  errno = 0;
911
  const unsigned long result =                 // NOLINT(runtime/int)
912
100
    strtoul(port.c_str(), &endptr, 10);
913

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

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

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


899816
    switch (option_info.type) {
1022
144496
      case kNoOp:
1023
      case kV8Option:
1024
        // Special case for --abort-on-uncaught-exception which is also
1025
        // respected by Node.js internals
1026
144496
        if (item.first == "--abort-on-uncaught-exception") {
1027
6568
          value = Boolean::New(
1028
6568
            isolate, original_per_env->abort_on_uncaught_exception);
1029
        } else {
1030
137928
          value = Undefined(isolate);
1031
        }
1032
144496
        break;
1033
499168
      case kBoolean:
1034
998336
        value = Boolean::New(isolate,
1035
998336
                             *_ppop_instance.Lookup<bool>(field, opts));
1036
499168
        break;
1037
26272
      case kInteger:
1038
52544
        value = Number::New(
1039
            isolate,
1040
52544
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1041
26272
        break;
1042
19704
      case kUInteger:
1043
39408
        value = Number::New(
1044
            isolate,
1045
39408
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1046
19704
        break;
1047
177336
      case kString:
1048
354672
        if (!ToV8Value(context,
1049
354672
                       *_ppop_instance.Lookup<std::string>(field, opts))
1050
177336
                 .ToLocal(&value)) {
1051
          return;
1052
        }
1053
177336
        break;
1054
26272
      case kStringList:
1055
52544
        if (!ToV8Value(context,
1056
52544
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1057
26272
                 .ToLocal(&value)) {
1058
          return;
1059
        }
1060
26272
        break;
1061
6568
      case kHostPort: {
1062
        const HostPort& host_port =
1063
6568
          *_ppop_instance.Lookup<HostPort>(field, opts);
1064
6568
        Local<Object> obj = Object::New(isolate);
1065
        Local<Value> host;
1066
6568
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1067

32840
            obj->Set(context, env->host_string(), host).IsNothing() ||
1068
6568
            obj->Set(context,
1069
                     env->port_string(),
1070
26272
                     Integer::New(isolate, host_port.port()))
1071
6568
                .IsNothing()) {
1072
          return;
1073
        }
1074
6568
        value = obj;
1075
6568
        break;
1076
      }
1077
      default:
1078
        UNREACHABLE();
1079
    }
1080
899816
    CHECK(!value.IsEmpty());
1081
1082
899816
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1083
899816
    Local<Object> info = Object::New(isolate);
1084
    Local<Value> help_text;
1085
899816
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1086
1799632
        !info->Set(context, env->help_text_string(), help_text)
1087

1799632
             .FromMaybe(false) ||
1088
1799632
        !info->Set(context,
1089
                   env->env_var_settings_string(),
1090
                   Integer::New(isolate,
1091
2699448
                                static_cast<int>(option_info.env_setting)))
1092

1799632
             .FromMaybe(false) ||
1093
1799632
        !info->Set(context,
1094
                   env->type_string(),
1095
2699448
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1096

1799632
             .FromMaybe(false) ||
1097
1799632
        !info->Set(context,
1098
                   env->default_is_true_string(),
1099
2699448
                   Boolean::New(isolate, option_info.default_is_true))
1100

1799632
             .FromMaybe(false) ||
1101

4499080
        info->Set(context, env->value_string(), value).IsNothing() ||
1102

2699448
        options->Set(context, name, info).IsEmpty()) {
1103
      return;
1104
    }
1105
  }
1106
1107
  Local<Value> aliases;
1108
13136
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1109
1110
6568
  if (aliases.As<Object>()
1111
13136
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1112
6568
          .IsNothing()) {
1113
    return;
1114
  }
1115
1116
6568
  Local<Object> ret = Object::New(isolate);
1117
26272
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1118

26272
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1119
    return;
1120
  }
1121
1122
13136
  args.GetReturnValue().Set(ret);
1123
}
1124
1125
6014
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1126
6014
  Environment* env = Environment::GetCurrent(args);
1127
6014
  if (!env->has_run_bootstrapping_code()) {
1128
    // No code because this is an assertion.
1129
    return env->ThrowError(
1130
        "Should not query options before bootstrapping is done");
1131
  }
1132
6014
  Isolate* isolate = args.GetIsolate();
1133
6014
  Local<Context> context = env->context();
1134
6014
  Local<Object> ret = Object::New(isolate);
1135
1136
12028
  if (ret->Set(context,
1137
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1138
18042
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1139
6014
      .IsNothing()) return;
1140
1141
12028
  if (ret->Set(context,
1142
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1143
18042
           Boolean::New(isolate, env->no_global_search_paths()))
1144
6014
      .IsNothing()) return;
1145
1146
12028
  args.GetReturnValue().Set(ret);
1147
}
1148
1149
854
void Initialize(Local<Object> target,
1150
                Local<Value> unused,
1151
                Local<Context> context,
1152
                void* priv) {
1153
854
  Environment* env = Environment::GetCurrent(context);
1154
854
  Isolate* isolate = env->isolate();
1155
854
  env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions);
1156
854
  env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions);
1157
1158
854
  Local<Object> env_settings = Object::New(isolate);
1159
2562
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1160
2562
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1161
  target
1162
854
      ->Set(
1163
1708
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1164
      .Check();
1165
1166
854
  Local<Object> types = Object::New(isolate);
1167
2562
  NODE_DEFINE_CONSTANT(types, kNoOp);
1168
2562
  NODE_DEFINE_CONSTANT(types, kV8Option);
1169
2562
  NODE_DEFINE_CONSTANT(types, kBoolean);
1170
2562
  NODE_DEFINE_CONSTANT(types, kInteger);
1171
2562
  NODE_DEFINE_CONSTANT(types, kUInteger);
1172
2562
  NODE_DEFINE_CONSTANT(types, kString);
1173
2562
  NODE_DEFINE_CONSTANT(types, kHostPort);
1174
2562
  NODE_DEFINE_CONSTANT(types, kStringList);
1175
1708
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1176
      .Check();
1177
854
}
1178
1179
5205
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1180
5205
  registry->Register(GetCLIOptions);
1181
5205
  registry->Register(GetEmbedderOptions);
1182
5205
}
1183
}  // namespace options_parser
1184
1185
5273
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1186
5273
  HandleEnvOptions(env_options, [](const char* name) {
1187
21092
    std::string text;
1188

21092
    return credentials::SafeGetenv(name, &text) ? text : "";
1189
  });
1190
5273
}
1191
1192
5549
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1193
                      std::function<std::string(const char*)> opt_getter) {
1194
5549
  env_options->pending_deprecation =
1195
11098
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1196
1197
5549
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1198
1199
5549
  env_options->preserve_symlinks_main =
1200
11098
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1201
1202
5549
  if (env_options->redirect_warnings.empty())
1203
5549
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1204
5549
}
1205
1206
5431
std::vector<std::string> ParseNodeOptionsEnvVar(
1207
    const std::string& node_options, std::vector<std::string>* errors) {
1208
5431
  std::vector<std::string> env_argv;
1209
1210
5431
  bool is_in_string = false;
1211
5431
  bool will_start_new_arg = true;
1212
8035
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1213
2604
    char c = node_options.at(index);
1214
1215
    // Backslashes escape the following character
1216

2604
    if (c == '\\' && is_in_string) {
1217
      if (index + 1 == node_options.size()) {
1218
        errors->push_back("invalid value for NODE_OPTIONS "
1219
                          "(invalid escape)\n");
1220
        return env_argv;
1221
      } else {
1222
        c = node_options.at(++index);
1223
      }
1224

2604
    } else if (c == ' ' && !is_in_string) {
1225
32
      will_start_new_arg = true;
1226
32
      continue;
1227
2572
    } else if (c == '"') {
1228
4
      is_in_string = !is_in_string;
1229
4
      continue;
1230
    }
1231
1232
2568
    if (will_start_new_arg) {
1233
108
      env_argv.emplace_back(std::string(1, c));
1234
108
      will_start_new_arg = false;
1235
    } else {
1236
2460
      env_argv.back() += c;
1237
    }
1238
  }
1239
1240
5431
  if (is_in_string) {
1241
    errors->push_back("invalid value for NODE_OPTIONS "
1242
                      "(unterminated string)\n");
1243
  }
1244
5431
  return env_argv;
1245
}
1246
}  // namespace node
1247
1248
5273
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1249
5205
NODE_MODULE_EXTERNAL_REFERENCE(options,
1250
                               node::options_parser::RegisterExternalReferences)