GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 448 477 93.9 %
Date: 2021-11-04 03:14:03 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_internals.h"
7
#if HAVE_OPENSSL
8
#include "openssl/opensslv.h"
9
#endif
10
11
#include <errno.h>
12
#include <sstream>
13
#include <limits>
14
#include <algorithm>
15
#include <cstdlib>  // strtoul, errno
16
17
using v8::Boolean;
18
using v8::Context;
19
using v8::FunctionCallbackInfo;
20
using v8::Integer;
21
using v8::Isolate;
22
using v8::Local;
23
using v8::Map;
24
using v8::Number;
25
using v8::Object;
26
using v8::Undefined;
27
using v8::Value;
28
29
namespace node {
30
31
namespace per_process {
32
Mutex cli_options_mutex;
33
std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
34
}  // namespace per_process
35
36
10228
void DebugOptions::CheckOptions(std::vector<std::string>* errors) {
37
#if !NODE_USE_V8_PLATFORM && !HAVE_INSPECTOR
38
  if (inspector_enabled) {
39
    errors->push_back("Inspector is not available when Node is compiled "
40
                      "--without-v8-platform and --without-inspector.");
41
  }
42
#endif
43
44
10228
  if (deprecated_debug) {
45
4
    errors->push_back("[DEP0062]: `node --debug` and `node --debug-brk` "
46
                      "are invalid. Please use `node --inspect` and "
47
                      "`node --inspect-brk` instead.");
48
  }
49
50
  std::vector<std::string> destinations =
51
20456
      SplitString(inspect_publish_uid_string, ',');
52
10228
  inspect_publish_uid.console = false;
53
10228
  inspect_publish_uid.http = false;
54
30682
  for (const std::string& destination : destinations) {
55
20454
    if (destination == "stderr") {
56
10227
      inspect_publish_uid.console = true;
57
10227
    } else if (destination == "http") {
58
10227
      inspect_publish_uid.http = true;
59
    } else {
60
      errors->push_back("--inspect-publish-uid destination can be "
61
                        "stderr or http");
62
    }
63
  }
64
10228
}
65
66
9710
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
67
#if HAVE_OPENSSL
68

9710
  if (use_openssl_ca && use_bundled_ca) {
69
1
    errors->push_back("either --use-openssl-ca or --use-bundled-ca can be "
70
                      "used, not both");
71
  }
72
73
  // Any value less than 2 disables use of the secure heap.
74
9710
  if (secure_heap >= 2) {
75
2
    if ((secure_heap & (secure_heap - 1)) != 0)
76
1
      errors->push_back("--secure-heap must be a power of 2");
77
2
    secure_heap_min =
78
6
        std::min({
79
2
            secure_heap,
80
2
            secure_heap_min,
81
            static_cast<int64_t>(std::numeric_limits<int>::max())});
82
2
    secure_heap_min = std::max(static_cast<int64_t>(2), secure_heap_min);
83
2
    if ((secure_heap_min & (secure_heap_min - 1)) != 0)
84
1
      errors->push_back("--secure-heap-min must be a power of 2");
85
  }
86
#endif
87
9712
  if (use_largepages != "off" &&
88

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

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

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

20
    if (module_type != "commonjs" && module_type != "module") {
110
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
111
    }
112
  }
113
114
10228
  if (!experimental_specifier_resolution.empty()) {
115

10
    if (experimental_specifier_resolution != "node" &&
116
        experimental_specifier_resolution != "explicit") {
117
      errors->push_back(
118
        "invalid value for --experimental-specifier-resolution");
119
    }
120
  }
121
122

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

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

10228
  if (tls_min_v1_3 && tls_max_v1_2) {
136
1
    errors->push_back("either --tls-min-v1.3 or --tls-max-v1.2 can be "
137
                      "used, not both");
138
  }
139
140
10228
  if (heap_snapshot_near_heap_limit < 0) {
141
    errors->push_back("--heap-snapshot-near-heap-limit must not be negative");
142
  }
143
144
#if HAVE_INSPECTOR
145
10228
  if (!cpu_prof) {
146
10217
    if (!cpu_prof_name.empty()) {
147
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
148
    }
149
10217
    if (!cpu_prof_dir.empty()) {
150
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
151
    }
152
    // We can't catch the case where the value passed is the default value,
153
    // then the option just becomes a noop which is fine.
154
10217
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
155
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
156
    }
157
  }
158
159


10228
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
160
1
      cpu_prof_dir = diagnostic_dir;
161
    }
162
163
10228
  if (!heap_prof) {
164
10217
    if (!heap_prof_name.empty()) {
165
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
166
    }
167
10217
    if (!heap_prof_dir.empty()) {
168
1
      errors->push_back("--heap-prof-dir must be used with --heap-prof");
169
    }
170
    // We can't catch the case where the value passed is the default value,
171
    // then the option just becomes a noop which is fine.
172
10217
    if (heap_prof_interval != kDefaultHeapProfInterval) {
173
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
174
    }
175
  }
176
177


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
851
4
    return host.substr(1, host.size() - 2);
852
  else
853
108
    return host;
854
}
855
856
100
inline int ParseAndValidatePort(const std::string& port,
857
                                std::vector<std::string>* errors) {
858
  char* endptr;
859
100
  errno = 0;
860
  const unsigned long result =                 // NOLINT(runtime/int)
861
100
    strtoul(port.c_str(), &endptr, 10);
862

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

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

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


698240
    switch (option_info.type) {
971
103645
      case kNoOp:
972
      case kV8Option:
973
        // Special case for --abort-on-uncaught-exception which is also
974
        // respected by Node.js internals
975
103645
        if (item.first == "--abort-on-uncaught-exception") {
976
5455
          value = Boolean::New(
977
5455
            isolate, original_per_env->abort_on_uncaught_exception);
978
        } else {
979
98190
          value = Undefined(isolate);
980
        }
981
103645
        break;
982
381850
      case kBoolean:
983
763700
        value = Boolean::New(isolate,
984
763700
                             *_ppop_instance.Lookup<bool>(field, opts));
985
381850
        break;
986
21820
      case kInteger:
987
43640
        value = Number::New(
988
            isolate,
989
43640
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
990
21820
        break;
991
16365
      case kUInteger:
992
32730
        value = Number::New(
993
            isolate,
994
32730
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
995
16365
        break;
996
152740
      case kString:
997
305480
        if (!ToV8Value(context,
998
305480
                       *_ppop_instance.Lookup<std::string>(field, opts))
999
152740
                 .ToLocal(&value)) {
1000
          return;
1001
        }
1002
152740
        break;
1003
16365
      case kStringList:
1004
32730
        if (!ToV8Value(context,
1005
32730
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1006
16365
                 .ToLocal(&value)) {
1007
          return;
1008
        }
1009
16365
        break;
1010
5455
      case kHostPort: {
1011
        const HostPort& host_port =
1012
5455
          *_ppop_instance.Lookup<HostPort>(field, opts);
1013
5455
        Local<Object> obj = Object::New(isolate);
1014
        Local<Value> host;
1015
5455
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1016

27275
            obj->Set(context, env->host_string(), host).IsNothing() ||
1017
5455
            obj->Set(context,
1018
                     env->port_string(),
1019
21820
                     Integer::New(isolate, host_port.port()))
1020
5455
                .IsNothing()) {
1021
          return;
1022
        }
1023
5455
        value = obj;
1024
5455
        break;
1025
      }
1026
      default:
1027
        UNREACHABLE();
1028
    }
1029
698240
    CHECK(!value.IsEmpty());
1030
1031
698240
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1032
698240
    Local<Object> info = Object::New(isolate);
1033
    Local<Value> help_text;
1034
698240
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1035
1396480
        !info->Set(context, env->help_text_string(), help_text)
1036

1396480
             .FromMaybe(false) ||
1037
1396480
        !info->Set(context,
1038
                   env->env_var_settings_string(),
1039
                   Integer::New(isolate,
1040
2094720
                                static_cast<int>(option_info.env_setting)))
1041

1396480
             .FromMaybe(false) ||
1042
1396480
        !info->Set(context,
1043
                   env->type_string(),
1044
2094720
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1045

1396480
             .FromMaybe(false) ||
1046
1396480
        !info->Set(context,
1047
                   env->default_is_true_string(),
1048
2094720
                   Boolean::New(isolate, option_info.default_is_true))
1049

1396480
             .FromMaybe(false) ||
1050

3491200
        info->Set(context, env->value_string(), value).IsNothing() ||
1051

2094720
        options->Set(context, name, info).IsEmpty()) {
1052
      return;
1053
    }
1054
  }
1055
1056
  Local<Value> aliases;
1057
10910
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1058
1059
5455
  if (aliases.As<Object>()
1060
10910
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1061
5455
          .IsNothing()) {
1062
    return;
1063
  }
1064
1065
5455
  Local<Object> ret = Object::New(isolate);
1066
21820
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1067

21820
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1068
    return;
1069
  }
1070
1071
10910
  args.GetReturnValue().Set(ret);
1072
}
1073
1074
5437
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1075
5437
  Environment* env = Environment::GetCurrent(args);
1076
5437
  if (!env->has_run_bootstrapping_code()) {
1077
    // No code because this is an assertion.
1078
    return env->ThrowError(
1079
        "Should not query options before bootstrapping is done");
1080
  }
1081
5437
  Isolate* isolate = args.GetIsolate();
1082
5437
  Local<Context> context = env->context();
1083
5437
  Local<Object> ret = Object::New(isolate);
1084
1085
10874
  if (ret->Set(context,
1086
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1087
16311
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1088
5437
      .IsNothing()) return;
1089
1090
10874
  if (ret->Set(context,
1091
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1092
16311
           Boolean::New(isolate, env->no_global_search_paths()))
1093
5437
      .IsNothing()) return;
1094
1095
10874
  args.GetReturnValue().Set(ret);
1096
}
1097
1098
5439
void Initialize(Local<Object> target,
1099
                Local<Value> unused,
1100
                Local<Context> context,
1101
                void* priv) {
1102
5439
  Environment* env = Environment::GetCurrent(context);
1103
5439
  Isolate* isolate = env->isolate();
1104
5439
  env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions);
1105
5439
  env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions);
1106
1107
5439
  Local<Object> env_settings = Object::New(isolate);
1108
16317
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1109
16317
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1110
  target
1111
5439
      ->Set(
1112
10878
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1113
      .Check();
1114
1115
5439
  Local<Object> types = Object::New(isolate);
1116
16317
  NODE_DEFINE_CONSTANT(types, kNoOp);
1117
16317
  NODE_DEFINE_CONSTANT(types, kV8Option);
1118
16317
  NODE_DEFINE_CONSTANT(types, kBoolean);
1119
16317
  NODE_DEFINE_CONSTANT(types, kInteger);
1120
16317
  NODE_DEFINE_CONSTANT(types, kUInteger);
1121
16317
  NODE_DEFINE_CONSTANT(types, kString);
1122
16317
  NODE_DEFINE_CONSTANT(types, kHostPort);
1123
16317
  NODE_DEFINE_CONSTANT(types, kStringList);
1124
10878
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1125
      .Check();
1126
5439
}
1127
1128
}  // namespace options_parser
1129
1130
4921
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1131
4921
  HandleEnvOptions(env_options, [](const char* name) {
1132
19684
    std::string text;
1133

19684
    return credentials::SafeGetenv(name, &text) ? text : "";
1134
  });
1135
4921
}
1136
1137
5182
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1138
                      std::function<std::string(const char*)> opt_getter) {
1139
5182
  env_options->pending_deprecation =
1140
10364
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1141
1142
5182
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1143
1144
5182
  env_options->preserve_symlinks_main =
1145
10364
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1146
1147
5182
  if (env_options->redirect_warnings.empty())
1148
5182
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1149
5182
}
1150
1151
5066
std::vector<std::string> ParseNodeOptionsEnvVar(
1152
    const std::string& node_options, std::vector<std::string>* errors) {
1153
5066
  std::vector<std::string> env_argv;
1154
1155
5066
  bool is_in_string = false;
1156
5066
  bool will_start_new_arg = true;
1157
7670
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1158
2604
    char c = node_options.at(index);
1159
1160
    // Backslashes escape the following character
1161

2604
    if (c == '\\' && is_in_string) {
1162
      if (index + 1 == node_options.size()) {
1163
        errors->push_back("invalid value for NODE_OPTIONS "
1164
                          "(invalid escape)\n");
1165
        return env_argv;
1166
      } else {
1167
        c = node_options.at(++index);
1168
      }
1169

2604
    } else if (c == ' ' && !is_in_string) {
1170
32
      will_start_new_arg = true;
1171
32
      continue;
1172
2572
    } else if (c == '"') {
1173
4
      is_in_string = !is_in_string;
1174
4
      continue;
1175
    }
1176
1177
2568
    if (will_start_new_arg) {
1178
108
      env_argv.emplace_back(std::string(1, c));
1179
108
      will_start_new_arg = false;
1180
    } else {
1181
2460
      env_argv.back() += c;
1182
    }
1183
  }
1184
1185
5066
  if (is_in_string) {
1186
    errors->push_back("invalid value for NODE_OPTIONS "
1187
                      "(unterminated string)\n");
1188
  }
1189
5066
  return env_argv;
1190
}
1191
}  // namespace node
1192
1193
4921
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)