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

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

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

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

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

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

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

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

10483
  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
10483
  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
10483
  if (!cpu_prof) {
148
10472
    if (!cpu_prof_name.empty()) {
149
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
150
    }
151
10472
    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
10472
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
157
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
158
    }
159
  }
160
161


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


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
869
4
    return host.substr(1, host.size() - 2);
870
  else
871
108
    return host;
872
}
873
874
100
inline int ParseAndValidatePort(const std::string& port,
875
                                std::vector<std::string>* errors) {
876
  char* endptr;
877
100
  errno = 0;
878
  const unsigned long result =                 // NOLINT(runtime/int)
879
100
    strtoul(port.c_str(), &endptr, 10);
880

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

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

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


792547
    switch (option_info.type) {
989
125139
      case kNoOp:
990
      case kV8Option:
991
        // Special case for --abort-on-uncaught-exception which is also
992
        // respected by Node.js internals
993
125139
        if (item.first == "--abort-on-uncaught-exception") {
994
5959
          value = Boolean::New(
995
5959
            isolate, original_per_env->abort_on_uncaught_exception);
996
        } else {
997
119180
          value = Undefined(isolate);
998
        }
999
125139
        break;
1000
435007
      case kBoolean:
1001
870014
        value = Boolean::New(isolate,
1002
870014
                             *_ppop_instance.Lookup<bool>(field, opts));
1003
435007
        break;
1004
23836
      case kInteger:
1005
47672
        value = Number::New(
1006
            isolate,
1007
47672
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1008
23836
        break;
1009
17877
      case kUInteger:
1010
35754
        value = Number::New(
1011
            isolate,
1012
35754
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1013
17877
        break;
1014
166852
      case kString:
1015
333704
        if (!ToV8Value(context,
1016
333704
                       *_ppop_instance.Lookup<std::string>(field, opts))
1017
166852
                 .ToLocal(&value)) {
1018
          return;
1019
        }
1020
166852
        break;
1021
17877
      case kStringList:
1022
35754
        if (!ToV8Value(context,
1023
35754
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1024
17877
                 .ToLocal(&value)) {
1025
          return;
1026
        }
1027
17877
        break;
1028
5959
      case kHostPort: {
1029
        const HostPort& host_port =
1030
5959
          *_ppop_instance.Lookup<HostPort>(field, opts);
1031
5959
        Local<Object> obj = Object::New(isolate);
1032
        Local<Value> host;
1033
5959
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1034

29795
            obj->Set(context, env->host_string(), host).IsNothing() ||
1035
5959
            obj->Set(context,
1036
                     env->port_string(),
1037
23836
                     Integer::New(isolate, host_port.port()))
1038
5959
                .IsNothing()) {
1039
          return;
1040
        }
1041
5959
        value = obj;
1042
5959
        break;
1043
      }
1044
      default:
1045
        UNREACHABLE();
1046
    }
1047
792547
    CHECK(!value.IsEmpty());
1048
1049
792547
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1050
792547
    Local<Object> info = Object::New(isolate);
1051
    Local<Value> help_text;
1052
792547
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1053
1585094
        !info->Set(context, env->help_text_string(), help_text)
1054

1585094
             .FromMaybe(false) ||
1055
1585094
        !info->Set(context,
1056
                   env->env_var_settings_string(),
1057
                   Integer::New(isolate,
1058
2377641
                                static_cast<int>(option_info.env_setting)))
1059

1585094
             .FromMaybe(false) ||
1060
1585094
        !info->Set(context,
1061
                   env->type_string(),
1062
2377641
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1063

1585094
             .FromMaybe(false) ||
1064
1585094
        !info->Set(context,
1065
                   env->default_is_true_string(),
1066
2377641
                   Boolean::New(isolate, option_info.default_is_true))
1067

1585094
             .FromMaybe(false) ||
1068

3962735
        info->Set(context, env->value_string(), value).IsNothing() ||
1069

2377641
        options->Set(context, name, info).IsEmpty()) {
1070
      return;
1071
    }
1072
  }
1073
1074
  Local<Value> aliases;
1075
11918
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1076
1077
5959
  if (aliases.As<Object>()
1078
11918
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1079
5959
          .IsNothing()) {
1080
    return;
1081
  }
1082
1083
5959
  Local<Object> ret = Object::New(isolate);
1084
23836
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1085

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

20168
    return credentials::SafeGetenv(name, &text) ? text : "";
1156
  });
1157
5042
}
1158
1159
5310
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1160
                      std::function<std::string(const char*)> opt_getter) {
1161
5310
  env_options->pending_deprecation =
1162
10620
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1163
1164
5310
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1165
1166
5310
  env_options->preserve_symlinks_main =
1167
10620
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1168
1169
5310
  if (env_options->redirect_warnings.empty())
1170
5310
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1171
5310
}
1172
1173
5193
std::vector<std::string> ParseNodeOptionsEnvVar(
1174
    const std::string& node_options, std::vector<std::string>* errors) {
1175
5193
  std::vector<std::string> env_argv;
1176
1177
5193
  bool is_in_string = false;
1178
5193
  bool will_start_new_arg = true;
1179
7797
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1180
2604
    char c = node_options.at(index);
1181
1182
    // Backslashes escape the following character
1183

2604
    if (c == '\\' && is_in_string) {
1184
      if (index + 1 == node_options.size()) {
1185
        errors->push_back("invalid value for NODE_OPTIONS "
1186
                          "(invalid escape)\n");
1187
        return env_argv;
1188
      } else {
1189
        c = node_options.at(++index);
1190
      }
1191

2604
    } else if (c == ' ' && !is_in_string) {
1192
32
      will_start_new_arg = true;
1193
32
      continue;
1194
2572
    } else if (c == '"') {
1195
4
      is_in_string = !is_in_string;
1196
4
      continue;
1197
    }
1198
1199
2568
    if (will_start_new_arg) {
1200
108
      env_argv.emplace_back(std::string(1, c));
1201
108
      will_start_new_arg = false;
1202
    } else {
1203
2460
      env_argv.back() += c;
1204
    }
1205
  }
1206
1207
5193
  if (is_in_string) {
1208
    errors->push_back("invalid value for NODE_OPTIONS "
1209
                      "(unterminated string)\n");
1210
  }
1211
5193
  return env_argv;
1212
}
1213
}  // namespace node
1214
1215
5042
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1216
4981
NODE_MODULE_EXTERNAL_REFERENCE(options,
1217
                               node::options_parser::RegisterExternalReferences)