GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 456 485 94.0 %
Date: 2022-03-23 03:15:06 Branches: 204 264 77.3 %

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
10457
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
10457
  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
20914
      SplitString(inspect_publish_uid_string, ',');
53
10457
  inspect_publish_uid.console = false;
54
10457
  inspect_publish_uid.http = false;
55
31369
  for (const std::string& destination : destinations) {
56
20912
    if (destination == "stderr") {
57
10456
      inspect_publish_uid.console = true;
58
10456
    } else if (destination == "http") {
59
10456
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
10457
}
66
67
9925
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

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

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

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

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

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

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

10457
  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
10457
  if (heap_snapshot_near_heap_limit < 0) {
143
    errors->push_back("--heap-snapshot-near-heap-limit must not be negative");
144
  }
145
146
#if HAVE_INSPECTOR
147
10457
  if (!cpu_prof) {
148
10446
    if (!cpu_prof_name.empty()) {
149
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
150
    }
151
10446
    if (!cpu_prof_dir.empty()) {
152
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
153
    }
154
    // We can't catch the case where the value passed is the default value,
155
    // then the option just becomes a noop which is fine.
156
10446
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
157
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
158
    }
159
  }
160
161


10457
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
162
1
      cpu_prof_dir = diagnostic_dir;
163
    }
164
165
10457
  if (!heap_prof) {
166
10446
    if (!heap_prof_name.empty()) {
167
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
168
    }
169
10446
    if (!heap_prof_dir.empty()) {
170
1
      errors->push_back("--heap-prof-dir must be used with --heap-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
10446
    if (heap_prof_interval != kDefaultHeapProfInterval) {
175
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
176
    }
177
  }
178
179


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
860
4
    return host.substr(1, host.size() - 2);
861
  else
862
108
    return host;
863
}
864
865
100
inline int ParseAndValidatePort(const std::string& port,
866
                                std::vector<std::string>* errors) {
867
  char* endptr;
868
100
  errno = 0;
869
  const unsigned long result =                 // NOLINT(runtime/int)
870
100
    strtoul(port.c_str(), &endptr, 10);
871

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

100
      (result != 0 && result < 1024) || result > 65535) {
873
    errors->push_back(" must be 0 or in range 1024 to 65535.");
874
  }
875
100
  return static_cast<int>(result);
876
}
877
878
100
HostPort SplitHostPort(const std::string& arg,
879
                      std::vector<std::string>* errors) {
880
  // remove_brackets only works if no port is specified
881
  // so if it has an effect only an IPv6 address was specified.
882
200
  std::string host = RemoveBrackets(arg);
883
100
  if (host.length() < arg.length())
884
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
885
886
100
  size_t colon = arg.rfind(':');
887
100
  if (colon == std::string::npos) {
888
    // Either a port number or a host name.  Assume that
889
    // if it's not all decimal digits, it's a host name.
890
390
    for (char c : arg) {
891

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


730980
    switch (option_info.type) {
980
117180
      case kNoOp:
981
      case kV8Option:
982
        // Special case for --abort-on-uncaught-exception which is also
983
        // respected by Node.js internals
984
117180
        if (item.first == "--abort-on-uncaught-exception") {
985
5580
          value = Boolean::New(
986
5580
            isolate, original_per_env->abort_on_uncaught_exception);
987
        } else {
988
111600
          value = Undefined(isolate);
989
        }
990
117180
        break;
991
396180
      case kBoolean:
992
792360
        value = Boolean::New(isolate,
993
792360
                             *_ppop_instance.Lookup<bool>(field, opts));
994
396180
        break;
995
22320
      case kInteger:
996
44640
        value = Number::New(
997
            isolate,
998
44640
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
999
22320
        break;
1000
16740
      case kUInteger:
1001
33480
        value = Number::New(
1002
            isolate,
1003
33480
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1004
16740
        break;
1005
156240
      case kString:
1006
312480
        if (!ToV8Value(context,
1007
312480
                       *_ppop_instance.Lookup<std::string>(field, opts))
1008
156240
                 .ToLocal(&value)) {
1009
          return;
1010
        }
1011
156240
        break;
1012
16740
      case kStringList:
1013
33480
        if (!ToV8Value(context,
1014
33480
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1015
16740
                 .ToLocal(&value)) {
1016
          return;
1017
        }
1018
16740
        break;
1019
5580
      case kHostPort: {
1020
        const HostPort& host_port =
1021
5580
          *_ppop_instance.Lookup<HostPort>(field, opts);
1022
5580
        Local<Object> obj = Object::New(isolate);
1023
        Local<Value> host;
1024
5580
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1025

27900
            obj->Set(context, env->host_string(), host).IsNothing() ||
1026
5580
            obj->Set(context,
1027
                     env->port_string(),
1028
22320
                     Integer::New(isolate, host_port.port()))
1029
5580
                .IsNothing()) {
1030
          return;
1031
        }
1032
5580
        value = obj;
1033
5580
        break;
1034
      }
1035
      default:
1036
        UNREACHABLE();
1037
    }
1038
730980
    CHECK(!value.IsEmpty());
1039
1040
730980
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1041
730980
    Local<Object> info = Object::New(isolate);
1042
    Local<Value> help_text;
1043
730980
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1044
1461960
        !info->Set(context, env->help_text_string(), help_text)
1045

1461960
             .FromMaybe(false) ||
1046
1461960
        !info->Set(context,
1047
                   env->env_var_settings_string(),
1048
                   Integer::New(isolate,
1049
2192940
                                static_cast<int>(option_info.env_setting)))
1050

1461960
             .FromMaybe(false) ||
1051
1461960
        !info->Set(context,
1052
                   env->type_string(),
1053
2192940
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1054

1461960
             .FromMaybe(false) ||
1055
1461960
        !info->Set(context,
1056
                   env->default_is_true_string(),
1057
2192940
                   Boolean::New(isolate, option_info.default_is_true))
1058

1461960
             .FromMaybe(false) ||
1059

3654900
        info->Set(context, env->value_string(), value).IsNothing() ||
1060

2192940
        options->Set(context, name, info).IsEmpty()) {
1061
      return;
1062
    }
1063
  }
1064
1065
  Local<Value> aliases;
1066
11160
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1067
1068
5580
  if (aliases.As<Object>()
1069
11160
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1070
5580
          .IsNothing()) {
1071
    return;
1072
  }
1073
1074
5580
  Local<Object> ret = Object::New(isolate);
1075
22320
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1076

22320
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1077
    return;
1078
  }
1079
1080
11160
  args.GetReturnValue().Set(ret);
1081
}
1082
1083
5552
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1084
5552
  Environment* env = Environment::GetCurrent(args);
1085
5552
  if (!env->has_run_bootstrapping_code()) {
1086
    // No code because this is an assertion.
1087
    return env->ThrowError(
1088
        "Should not query options before bootstrapping is done");
1089
  }
1090
5552
  Isolate* isolate = args.GetIsolate();
1091
5552
  Local<Context> context = env->context();
1092
5552
  Local<Object> ret = Object::New(isolate);
1093
1094
11104
  if (ret->Set(context,
1095
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1096
16656
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1097
5552
      .IsNothing()) return;
1098
1099
11104
  if (ret->Set(context,
1100
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1101
16656
           Boolean::New(isolate, env->no_global_search_paths()))
1102
5552
      .IsNothing()) return;
1103
1104
11104
  args.GetReturnValue().Set(ret);
1105
}
1106
1107
625
void Initialize(Local<Object> target,
1108
                Local<Value> unused,
1109
                Local<Context> context,
1110
                void* priv) {
1111
625
  Environment* env = Environment::GetCurrent(context);
1112
625
  Isolate* isolate = env->isolate();
1113
625
  env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions);
1114
625
  env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions);
1115
1116
625
  Local<Object> env_settings = Object::New(isolate);
1117
1875
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1118
1875
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1119
  target
1120
625
      ->Set(
1121
1250
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1122
      .Check();
1123
1124
625
  Local<Object> types = Object::New(isolate);
1125
1875
  NODE_DEFINE_CONSTANT(types, kNoOp);
1126
1875
  NODE_DEFINE_CONSTANT(types, kV8Option);
1127
1875
  NODE_DEFINE_CONSTANT(types, kBoolean);
1128
1875
  NODE_DEFINE_CONSTANT(types, kInteger);
1129
1875
  NODE_DEFINE_CONSTANT(types, kUInteger);
1130
1875
  NODE_DEFINE_CONSTANT(types, kString);
1131
1875
  NODE_DEFINE_CONSTANT(types, kHostPort);
1132
1875
  NODE_DEFINE_CONSTANT(types, kStringList);
1133
1250
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1134
      .Check();
1135
625
}
1136
1137
4968
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1138
4968
  registry->Register(GetCLIOptions);
1139
4968
  registry->Register(GetEmbedderOptions);
1140
4968
}
1141
}  // namespace options_parser
1142
1143
5029
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1144
5029
  HandleEnvOptions(env_options, [](const char* name) {
1145
20116
    std::string text;
1146

20116
    return credentials::SafeGetenv(name, &text) ? text : "";
1147
  });
1148
5029
}
1149
1150
5297
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1151
                      std::function<std::string(const char*)> opt_getter) {
1152
5297
  env_options->pending_deprecation =
1153
10594
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1154
1155
5297
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1156
1157
5297
  env_options->preserve_symlinks_main =
1158
10594
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1159
1160
5297
  if (env_options->redirect_warnings.empty())
1161
5297
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1162
5297
}
1163
1164
5180
std::vector<std::string> ParseNodeOptionsEnvVar(
1165
    const std::string& node_options, std::vector<std::string>* errors) {
1166
5180
  std::vector<std::string> env_argv;
1167
1168
5180
  bool is_in_string = false;
1169
5180
  bool will_start_new_arg = true;
1170
7784
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1171
2604
    char c = node_options.at(index);
1172
1173
    // Backslashes escape the following character
1174

2604
    if (c == '\\' && is_in_string) {
1175
      if (index + 1 == node_options.size()) {
1176
        errors->push_back("invalid value for NODE_OPTIONS "
1177
                          "(invalid escape)\n");
1178
        return env_argv;
1179
      } else {
1180
        c = node_options.at(++index);
1181
      }
1182

2604
    } else if (c == ' ' && !is_in_string) {
1183
32
      will_start_new_arg = true;
1184
32
      continue;
1185
2572
    } else if (c == '"') {
1186
4
      is_in_string = !is_in_string;
1187
4
      continue;
1188
    }
1189
1190
2568
    if (will_start_new_arg) {
1191
108
      env_argv.emplace_back(std::string(1, c));
1192
108
      will_start_new_arg = false;
1193
    } else {
1194
2460
      env_argv.back() += c;
1195
    }
1196
  }
1197
1198
5180
  if (is_in_string) {
1199
    errors->push_back("invalid value for NODE_OPTIONS "
1200
                      "(unterminated string)\n");
1201
  }
1202
5180
  return env_argv;
1203
}
1204
}  // namespace node
1205
1206
5029
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1207
4968
NODE_MODULE_EXTERNAL_REFERENCE(options,
1208
                               node::options_parser::RegisterExternalReferences)