GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 445 472 94.3 %
Date: 2021-09-15 04:12:31 Branches: 200 256 78.1 %

Line Branch Exec Source
1
#include "node_options.h"  // NOLINT(build/include_inline)
2
#include "node_options-inl.h"
3
4
#include "env-inl.h"
5
#include "node_binding.h"
6
#include "node_internals.h"
7
8
#include <errno.h>
9
#include <sstream>
10
#include <limits>
11
#include <algorithm>
12
#include <cstdlib>  // strtoul, errno
13
14
using v8::Boolean;
15
using v8::Context;
16
using v8::FunctionCallbackInfo;
17
using v8::Integer;
18
using v8::Isolate;
19
using v8::Local;
20
using v8::Map;
21
using v8::Number;
22
using v8::Object;
23
using v8::Undefined;
24
using v8::Value;
25
26
namespace node {
27
28
namespace per_process {
29
Mutex cli_options_mutex;
30
std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
31
}  // namespace per_process
32
33
10234
void DebugOptions::CheckOptions(std::vector<std::string>* errors) {
34
#if !NODE_USE_V8_PLATFORM && !HAVE_INSPECTOR
35
  if (inspector_enabled) {
36
    errors->push_back("Inspector is not available when Node is compiled "
37
                      "--without-v8-platform and --without-inspector.");
38
  }
39
#endif
40
41
10234
  if (deprecated_debug) {
42
4
    errors->push_back("[DEP0062]: `node --debug` and `node --debug-brk` "
43
                      "are invalid. Please use `node --inspect` and "
44
                      "`node --inspect-brk` instead.");
45
  }
46
47
  std::vector<std::string> destinations =
48
20468
      SplitString(inspect_publish_uid_string, ',');
49
10234
  inspect_publish_uid.console = false;
50
10234
  inspect_publish_uid.http = false;
51
30700
  for (const std::string& destination : destinations) {
52
20466
    if (destination == "stderr") {
53
10233
      inspect_publish_uid.console = true;
54
10233
    } else if (destination == "http") {
55
10233
      inspect_publish_uid.http = true;
56
    } else {
57
      errors->push_back("--inspect-publish-uid destination can be "
58
                        "stderr or http");
59
    }
60
  }
61
10234
}
62
63
9716
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
64
#if HAVE_OPENSSL
65

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

9718
      use_largepages != "on" &&
86
1
      use_largepages != "silent") {
87
1
    errors->push_back("invalid value for --use-largepages");
88
  }
89
9716
  per_isolate->CheckOptions(errors);
90
9716
}
91
92
10234
void PerIsolateOptions::CheckOptions(std::vector<std::string>* errors) {
93
10234
  per_env->CheckOptions(errors);
94
10234
}
95
96
10234
void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors) {
97

10234
  if (has_policy_integrity_string && experimental_policy.empty()) {
98
    errors->push_back("--policy-integrity requires "
99
                      "--experimental-policy be enabled");
100
  }
101

10234
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
102
1
    errors->push_back("--policy-integrity cannot be empty");
103
  }
104
105
10234
  if (!module_type.empty()) {
106

20
    if (module_type != "commonjs" && module_type != "module") {
107
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
108
    }
109
  }
110
111
10234
  if (!experimental_specifier_resolution.empty()) {
112

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

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

10269
      unhandled_rejections != "warn" &&
128
10
      unhandled_rejections != "none") {
129
1
    errors->push_back("invalid value for --unhandled-rejections");
130
  }
131
132

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


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


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
836
4
    return host.substr(1, host.size() - 2);
837
  else
838
108
    return host;
839
}
840
841
100
inline int ParseAndValidatePort(const std::string& port,
842
                                std::vector<std::string>* errors) {
843
  char* endptr;
844
100
  errno = 0;
845
  const unsigned long result =                 // NOLINT(runtime/int)
846
100
    strtoul(port.c_str(), &endptr, 10);
847

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

100
      (result != 0 && result < 1024) || result > 65535) {
849
    errors->push_back(" must be 0 or in range 1024 to 65535.");
850
  }
851
100
  return static_cast<int>(result);
852
}
853
854
100
HostPort SplitHostPort(const std::string& arg,
855
                      std::vector<std::string>* errors) {
856
  // remove_brackets only works if no port is specified
857
  // so if it has an effect only an IPv6 address was specified.
858
200
  std::string host = RemoveBrackets(arg);
859
100
  if (host.length() < arg.length())
860
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
861
862
100
  size_t colon = arg.rfind(':');
863
100
  if (colon == std::string::npos) {
864
    // Either a port number or a host name.  Assume that
865
    // if it's not all decimal digits, it's a host name.
866
390
    for (char c : arg) {
867

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


686574
    switch (option_info.type) {
956
103531
      case kNoOp:
957
      case kV8Option:
958
        // Special case for --abort-on-uncaught-exception which is also
959
        // respected by Node.js internals
960
103531
        if (item.first == "--abort-on-uncaught-exception") {
961
5449
          value = Boolean::New(
962
5449
            isolate, original_per_env->abort_on_uncaught_exception);
963
        } else {
964
98082
          value = Undefined(isolate);
965
        }
966
103531
        break;
967
370532
      case kBoolean:
968
741064
        value = Boolean::New(isolate,
969
741064
                             *_ppop_instance.Lookup<bool>(field, opts));
970
370532
        break;
971
21796
      case kInteger:
972
43592
        value = Number::New(
973
            isolate,
974
43592
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
975
21796
        break;
976
16347
      case kUInteger:
977
32694
        value = Number::New(
978
            isolate,
979
32694
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
980
16347
        break;
981
152572
      case kString:
982
305144
        if (!ToV8Value(context,
983
305144
                       *_ppop_instance.Lookup<std::string>(field, opts))
984
152572
                 .ToLocal(&value)) {
985
          return;
986
        }
987
152572
        break;
988
16347
      case kStringList:
989
32694
        if (!ToV8Value(context,
990
32694
                       *_ppop_instance.Lookup<StringVector>(field, opts))
991
16347
                 .ToLocal(&value)) {
992
          return;
993
        }
994
16347
        break;
995
5449
      case kHostPort: {
996
        const HostPort& host_port =
997
5449
          *_ppop_instance.Lookup<HostPort>(field, opts);
998
5449
        Local<Object> obj = Object::New(isolate);
999
        Local<Value> host;
1000
5449
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1001

27245
            obj->Set(context, env->host_string(), host).IsNothing() ||
1002
5449
            obj->Set(context,
1003
                     env->port_string(),
1004
21796
                     Integer::New(isolate, host_port.port()))
1005
5449
                .IsNothing()) {
1006
          return;
1007
        }
1008
5449
        value = obj;
1009
5449
        break;
1010
      }
1011
      default:
1012
        UNREACHABLE();
1013
    }
1014
686574
    CHECK(!value.IsEmpty());
1015
1016
686574
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1017
686574
    Local<Object> info = Object::New(isolate);
1018
    Local<Value> help_text;
1019
686574
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1020
1373148
        !info->Set(context, env->help_text_string(), help_text)
1021

1373148
             .FromMaybe(false) ||
1022
1373148
        !info->Set(context,
1023
                   env->env_var_settings_string(),
1024
                   Integer::New(isolate,
1025
2059722
                                static_cast<int>(option_info.env_setting)))
1026

1373148
             .FromMaybe(false) ||
1027
1373148
        !info->Set(context,
1028
                   env->type_string(),
1029
2059722
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1030

1373148
             .FromMaybe(false) ||
1031
1373148
        !info->Set(context,
1032
                   env->default_is_true_string(),
1033
2059722
                   Boolean::New(isolate, option_info.default_is_true))
1034

1373148
             .FromMaybe(false) ||
1035

3432870
        info->Set(context, env->value_string(), value).IsNothing() ||
1036

2059722
        options->Set(context, name, info).IsEmpty()) {
1037
      return;
1038
    }
1039
  }
1040
1041
  Local<Value> aliases;
1042
10898
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1043
1044
5449
  if (aliases.As<Object>()
1045
10898
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1046
5449
          .IsNothing()) {
1047
    return;
1048
  }
1049
1050
5449
  Local<Object> ret = Object::New(isolate);
1051
21796
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1052

21796
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1053
    return;
1054
  }
1055
1056
10898
  args.GetReturnValue().Set(ret);
1057
}
1058
1059
5434
void Initialize(Local<Object> target,
1060
                Local<Value> unused,
1061
                Local<Context> context,
1062
                void* priv) {
1063
5434
  Environment* env = Environment::GetCurrent(context);
1064
5434
  Isolate* isolate = env->isolate();
1065
5434
  env->SetMethodNoSideEffect(target, "getOptions", GetOptions);
1066
1067
5434
  Local<Object> env_settings = Object::New(isolate);
1068
16302
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1069
16302
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1070
  target
1071
5434
      ->Set(
1072
16302
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1073
      .Check();
1074
1075
  target
1076
5434
      ->Set(context,
1077
            FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1078
16302
            Boolean::New(isolate, env->should_not_register_esm_loader()))
1079
      .Check();
1080
1081
5434
  Local<Object> types = Object::New(isolate);
1082
16302
  NODE_DEFINE_CONSTANT(types, kNoOp);
1083
16302
  NODE_DEFINE_CONSTANT(types, kV8Option);
1084
16302
  NODE_DEFINE_CONSTANT(types, kBoolean);
1085
16302
  NODE_DEFINE_CONSTANT(types, kInteger);
1086
16302
  NODE_DEFINE_CONSTANT(types, kUInteger);
1087
16302
  NODE_DEFINE_CONSTANT(types, kString);
1088
16302
  NODE_DEFINE_CONSTANT(types, kHostPort);
1089
16302
  NODE_DEFINE_CONSTANT(types, kStringList);
1090
10868
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1091
      .Check();
1092
5434
}
1093
1094
}  // namespace options_parser
1095
1096
4924
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1097
4924
  HandleEnvOptions(env_options, [](const char* name) {
1098
19696
    std::string text;
1099

19696
    return credentials::SafeGetenv(name, &text) ? text : "";
1100
  });
1101
4924
}
1102
1103
5185
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1104
                      std::function<std::string(const char*)> opt_getter) {
1105
5185
  env_options->pending_deprecation =
1106
10370
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1107
1108
5185
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1109
1110
5185
  env_options->preserve_symlinks_main =
1111
10370
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1112
1113
5185
  if (env_options->redirect_warnings.empty())
1114
5185
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1115
5185
}
1116
1117
5069
std::vector<std::string> ParseNodeOptionsEnvVar(
1118
    const std::string& node_options, std::vector<std::string>* errors) {
1119
5069
  std::vector<std::string> env_argv;
1120
1121
5069
  bool is_in_string = false;
1122
5069
  bool will_start_new_arg = true;
1123
7699
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1124
2630
    char c = node_options.at(index);
1125
1126
    // Backslashes escape the following character
1127

2630
    if (c == '\\' && is_in_string) {
1128
      if (index + 1 == node_options.size()) {
1129
        errors->push_back("invalid value for NODE_OPTIONS "
1130
                          "(invalid escape)\n");
1131
        return env_argv;
1132
      } else {
1133
        c = node_options.at(++index);
1134
      }
1135

2630
    } else if (c == ' ' && !is_in_string) {
1136
32
      will_start_new_arg = true;
1137
32
      continue;
1138
2598
    } else if (c == '"') {
1139
4
      is_in_string = !is_in_string;
1140
4
      continue;
1141
    }
1142
1143
2594
    if (will_start_new_arg) {
1144
109
      env_argv.emplace_back(std::string(1, c));
1145
109
      will_start_new_arg = false;
1146
    } else {
1147
2485
      env_argv.back() += c;
1148
    }
1149
  }
1150
1151
5069
  if (is_in_string) {
1152
    errors->push_back("invalid value for NODE_OPTIONS "
1153
                      "(unterminated string)\n");
1154
  }
1155
5069
  return env_argv;
1156
}
1157
}  // namespace node
1158
1159
4924
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)