GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 448 475 94.3 %
Date: 2021-09-19 04:12:45 Branches: 201 258 77.9 %

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("--global-search-paths",
411
            "disable global module search paths",
412
            &EnvironmentOptions::global_search_paths,
413
            kAllowedInEnvironment,
414
            true);
415
4930
  AddOption("--warnings",
416
            "silence all process warnings",
417
            &EnvironmentOptions::warnings,
418
            kAllowedInEnvironment,
419
            true);
420
4930
  AddOption("--force-context-aware",
421
            "disable loading non-context-aware addons",
422
            &EnvironmentOptions::force_context_aware,
423
            kAllowedInEnvironment);
424
4930
  AddOption("--pending-deprecation",
425
            "emit pending deprecation warnings",
426
            &EnvironmentOptions::pending_deprecation,
427
            kAllowedInEnvironment);
428
4930
  AddOption("--preserve-symlinks",
429
            "preserve symbolic links when resolving",
430
            &EnvironmentOptions::preserve_symlinks,
431
            kAllowedInEnvironment);
432
4930
  AddOption("--preserve-symlinks-main",
433
            "preserve symbolic links when resolving the main module",
434
            &EnvironmentOptions::preserve_symlinks_main,
435
            kAllowedInEnvironment);
436
4930
  AddOption("--prof",
437
            "Generate V8 profiler output.",
438
4930
            V8Option{});
439
4930
  AddOption("--prof-process",
440
            "process V8 profiler output generated using --prof",
441
            &EnvironmentOptions::prof_process);
442
  // Options after --prof-process are passed through to the prof processor.
443
14790
  AddAlias("--prof-process", { "--prof-process", "--" });
444
#if HAVE_INSPECTOR
445
4930
  AddOption("--cpu-prof",
446
            "Start the V8 CPU profiler on start up, and write the CPU profile "
447
            "to disk before exit. If --cpu-prof-dir is not specified, write "
448
            "the profile to the current working directory.",
449
            &EnvironmentOptions::cpu_prof);
450
4930
  AddOption("--cpu-prof-name",
451
            "specified file name of the V8 CPU profile generated with "
452
            "--cpu-prof",
453
            &EnvironmentOptions::cpu_prof_name);
454
4930
  AddOption("--cpu-prof-interval",
455
            "specified sampling interval in microseconds for the V8 CPU "
456
            "profile generated with --cpu-prof. (default: 1000)",
457
            &EnvironmentOptions::cpu_prof_interval);
458
4930
  AddOption("--cpu-prof-dir",
459
            "Directory where the V8 profiles generated by --cpu-prof will be "
460
            "placed. Does not affect --prof.",
461
            &EnvironmentOptions::cpu_prof_dir);
462
4930
  AddOption(
463
      "--heap-prof",
464
      "Start the V8 heap profiler on start up, and write the heap profile "
465
      "to disk before exit. If --heap-prof-dir is not specified, write "
466
      "the profile to the current working directory.",
467
      &EnvironmentOptions::heap_prof);
468
4930
  AddOption("--heap-prof-name",
469
            "specified file name of the V8 heap profile generated with "
470
            "--heap-prof",
471
            &EnvironmentOptions::heap_prof_name);
472
4930
  AddOption("--heap-prof-dir",
473
            "Directory where the V8 heap profiles generated by --heap-prof "
474
            "will be placed.",
475
            &EnvironmentOptions::heap_prof_dir);
476
4930
  AddOption("--heap-prof-interval",
477
            "specified sampling interval in bytes for the V8 heap "
478
            "profile generated with --heap-prof. (default: 512 * 1024)",
479
            &EnvironmentOptions::heap_prof_interval);
480
#endif  // HAVE_INSPECTOR
481
4930
  AddOption("--max-http-header-size",
482
            "set the maximum size of HTTP headers (default: 16384 (16KB))",
483
            &EnvironmentOptions::max_http_header_size,
484
            kAllowedInEnvironment);
485
4930
  AddOption("--redirect-warnings",
486
            "write warnings to file instead of stderr",
487
            &EnvironmentOptions::redirect_warnings,
488
            kAllowedInEnvironment);
489
4930
  AddOption("--test-udp-no-try-send", "",  // For testing only.
490
            &EnvironmentOptions::test_udp_no_try_send);
491
4930
  AddOption("--throw-deprecation",
492
            "throw an exception on deprecations",
493
            &EnvironmentOptions::throw_deprecation,
494
            kAllowedInEnvironment);
495
4930
  AddOption("--trace-atomics-wait",
496
            "trace Atomics.wait() operations",
497
            &EnvironmentOptions::trace_atomics_wait,
498
            kAllowedInEnvironment);
499
4930
  AddOption("--trace-deprecation",
500
            "show stack traces on deprecations",
501
            &EnvironmentOptions::trace_deprecation,
502
            kAllowedInEnvironment);
503
4930
  AddOption("--trace-exit",
504
            "show stack trace when an environment exits",
505
            &EnvironmentOptions::trace_exit,
506
            kAllowedInEnvironment);
507
4930
  AddOption("--trace-sync-io",
508
            "show stack trace when use of sync IO is detected after the "
509
            "first tick",
510
            &EnvironmentOptions::trace_sync_io,
511
            kAllowedInEnvironment);
512
4930
  AddOption("--trace-tls",
513
            "prints TLS packet trace information to stderr",
514
            &EnvironmentOptions::trace_tls,
515
            kAllowedInEnvironment);
516
4930
  AddOption("--trace-uncaught",
517
            "show stack traces for the `throw` behind uncaught exceptions",
518
            &EnvironmentOptions::trace_uncaught,
519
            kAllowedInEnvironment);
520
4930
  AddOption("--trace-warnings",
521
            "show stack traces on process warnings",
522
            &EnvironmentOptions::trace_warnings,
523
            kAllowedInEnvironment);
524
4930
  AddOption("--extra-info-on-fatal-exception",
525
            "hide extra information on fatal exception that causes exit",
526
            &EnvironmentOptions::extra_info_on_fatal_exception,
527
            kAllowedInEnvironment,
528
            true);
529
4930
  AddOption("--unhandled-rejections",
530
            "define unhandled rejections behavior. Options are 'strict' "
531
            "(always raise an error), 'throw' (raise an error unless "
532
            "'unhandledRejection' hook is set), 'warn' (log a warning), 'none' "
533
            "(silence warnings), 'warn-with-error-code' (log a warning and set "
534
            "exit code 1 unless 'unhandledRejection' hook is set). (default: "
535
            "throw)",
536
            &EnvironmentOptions::unhandled_rejections,
537
            kAllowedInEnvironment);
538
4930
  AddOption("--verify-base-objects",
539
            "", /* undocumented, only for debugging */
540
            &EnvironmentOptions::verify_base_objects,
541
            kAllowedInEnvironment);
542
543
4930
  AddOption("--check",
544
            "syntax check script without executing",
545
            &EnvironmentOptions::syntax_check_only);
546
4930
  AddAlias("-c", "--check");
547
  // This option is only so that we can tell --eval with an empty string from
548
  // no eval at all. Having it not start with a dash makes it inaccessible
549
  // from the parser itself, but available for using Implies().
550
  // TODO(addaleax): When moving --help over to something generated from the
551
  // programmatic descriptions, this will need some special care.
552
  // (See also [ssl_openssl_cert_store] below.)
553
4930
  AddOption("[has_eval_string]", "", &EnvironmentOptions::has_eval_string);
554
4930
  AddOption("--eval", "evaluate script", &EnvironmentOptions::eval_string);
555
4930
  Implies("--eval", "[has_eval_string]");
556
4930
  AddOption("--print",
557
            "evaluate script and print result",
558
            &EnvironmentOptions::print_eval);
559
4930
  AddAlias("-e", "--eval");
560
4930
  AddAlias("--print <arg>", "-pe");
561
14790
  AddAlias("-pe", { "--print", "--eval" });
562
4930
  AddAlias("-p", "--print");
563
4930
  AddOption("--require",
564
            "module to preload (option can be repeated)",
565
            &EnvironmentOptions::preload_modules,
566
            kAllowedInEnvironment);
567
4930
  AddAlias("-r", "--require");
568
4930
  AddOption("--interactive",
569
            "always enter the REPL even if stdin does not appear "
570
            "to be a terminal",
571
            &EnvironmentOptions::force_repl);
572
4930
  AddAlias("-i", "--interactive");
573
574
4930
  AddOption("--napi-modules", "", NoOp{}, kAllowedInEnvironment);
575
576
4930
  AddOption("--tls-keylog",
577
            "log TLS decryption keys to named file for traffic analysis",
578
            &EnvironmentOptions::tls_keylog, kAllowedInEnvironment);
579
580
4930
  AddOption("--tls-min-v1.0",
581
            "set default TLS minimum to TLSv1.0 (default: TLSv1.2)",
582
            &EnvironmentOptions::tls_min_v1_0,
583
            kAllowedInEnvironment);
584
4930
  AddOption("--tls-min-v1.1",
585
            "set default TLS minimum to TLSv1.1 (default: TLSv1.2)",
586
            &EnvironmentOptions::tls_min_v1_1,
587
            kAllowedInEnvironment);
588
4930
  AddOption("--tls-min-v1.2",
589
            "set default TLS minimum to TLSv1.2 (default: TLSv1.2)",
590
            &EnvironmentOptions::tls_min_v1_2,
591
            kAllowedInEnvironment);
592
4930
  AddOption("--tls-min-v1.3",
593
            "set default TLS minimum to TLSv1.3 (default: TLSv1.2)",
594
            &EnvironmentOptions::tls_min_v1_3,
595
            kAllowedInEnvironment);
596
4930
  AddOption("--tls-max-v1.2",
597
            "set default TLS maximum to TLSv1.2 (default: TLSv1.3)",
598
            &EnvironmentOptions::tls_max_v1_2,
599
            kAllowedInEnvironment);
600
  // Current plan is:
601
  // - 11.x and below: TLS1.3 is opt-in with --tls-max-v1.3
602
  // - 12.x: TLS1.3 is opt-out with --tls-max-v1.2
603
  // In either case, support both options they are uniformly available.
604
4930
  AddOption("--tls-max-v1.3",
605
            "set default TLS maximum to TLSv1.3 (default: TLSv1.3)",
606
            &EnvironmentOptions::tls_max_v1_3,
607
            kAllowedInEnvironment);
608
4930
}
609
610
4930
PerIsolateOptionsParser::PerIsolateOptionsParser(
611
4930
  const EnvironmentOptionsParser& eop) {
612
4930
  AddOption("--track-heap-objects",
613
            "track heap object allocations for heap snapshots",
614
            &PerIsolateOptions::track_heap_objects,
615
            kAllowedInEnvironment);
616
4930
  AddOption("--node-snapshot",
617
            "",  // It's a debug-only option.
618
            &PerIsolateOptions::node_snapshot,
619
            kAllowedInEnvironment);
620
621
  // Explicitly add some V8 flags to mark them as allowed in NODE_OPTIONS.
622
4930
  AddOption("--abort-on-uncaught-exception",
623
            "aborting instead of exiting causes a core file to be generated "
624
            "for analysis",
625
4930
            V8Option{},
626
            kAllowedInEnvironment);
627
4930
  AddOption("--interpreted-frames-native-stack",
628
            "help system profilers to translate JavaScript interpreted frames",
629
4930
            V8Option{}, kAllowedInEnvironment);
630
4930
  AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvironment);
631
4930
  AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvironment);
632
4930
  AddOption("--perf-basic-prof-only-functions",
633
            "",
634
4930
            V8Option{},
635
            kAllowedInEnvironment);
636
4930
  AddOption("--perf-prof", "", V8Option{}, kAllowedInEnvironment);
637
4930
  AddOption("--perf-prof-unwinding-info",
638
            "",
639
4930
            V8Option{},
640
            kAllowedInEnvironment);
641
4930
  AddOption("--stack-trace-limit", "", V8Option{}, kAllowedInEnvironment);
642
4930
  AddOption("--disallow-code-generation-from-strings",
643
            "disallow eval and friends",
644
4930
            V8Option{},
645
            kAllowedInEnvironment);
646
4930
  AddOption("--huge-max-old-generation-size",
647
             "increase default maximum heap size on machines with 16GB memory "
648
             "or more",
649
4930
             V8Option{},
650
             kAllowedInEnvironment);
651
4930
  AddOption("--jitless",
652
             "disable runtime allocation of executable memory",
653
4930
             V8Option{},
654
             kAllowedInEnvironment);
655
4930
  AddOption("--report-uncaught-exception",
656
            "generate diagnostic report on uncaught exceptions",
657
            &PerIsolateOptions::report_uncaught_exception,
658
            kAllowedInEnvironment);
659
4930
  AddOption("--report-on-signal",
660
            "generate diagnostic report upon receiving signals",
661
            &PerIsolateOptions::report_on_signal,
662
            kAllowedInEnvironment);
663
4930
  AddOption("--report-signal",
664
            "causes diagnostic report to be produced on provided signal,"
665
            " unsupported in Windows. (default: SIGUSR2)",
666
            &PerIsolateOptions::report_signal,
667
            kAllowedInEnvironment);
668
4930
  Implies("--report-signal", "--report-on-signal");
669
670
4930
  AddOption("--experimental-top-level-await",
671
            "",
672
            &PerIsolateOptions::experimental_top_level_await,
673
            kAllowedInEnvironment);
674
4930
  AddOption("--harmony-top-level-await", "", V8Option{});
675
4930
  Implies("--experimental-top-level-await", "--harmony-top-level-await");
676
4930
  Implies("--harmony-top-level-await", "--experimental-top-level-await");
677
4930
  ImpliesNot("--no-harmony-top-level-await", "--experimental-top-level-await");
678
679
4930
  Insert(eop, &PerIsolateOptions::get_per_env_options);
680
4930
}
681
682
4930
PerProcessOptionsParser::PerProcessOptionsParser(
683
4930
  const PerIsolateOptionsParser& iop) {
684
4930
  AddOption("--title",
685
            "the process title to use on startup",
686
            &PerProcessOptions::title,
687
            kAllowedInEnvironment);
688
4930
  AddOption("--trace-event-categories",
689
            "comma separated list of trace event categories to record",
690
            &PerProcessOptions::trace_event_categories,
691
            kAllowedInEnvironment);
692
4930
  AddOption("--trace-event-file-pattern",
693
            "Template string specifying the filepath for the trace-events "
694
            "data, it supports ${rotation} and ${pid}.",
695
            &PerProcessOptions::trace_event_file_pattern,
696
            kAllowedInEnvironment);
697
14790
  AddAlias("--trace-events-enabled", {
698
9860
    "--trace-event-categories", "v8,node,node.async_hooks" });
699
4930
  AddOption("--v8-pool-size",
700
            "set V8's thread pool size",
701
            &PerProcessOptions::v8_thread_pool_size,
702
            kAllowedInEnvironment);
703
4930
  AddOption("--zero-fill-buffers",
704
            "automatically zero-fill all newly allocated Buffer and "
705
            "SlowBuffer instances",
706
            &PerProcessOptions::zero_fill_all_buffers,
707
            kAllowedInEnvironment);
708
4930
  AddOption("--debug-arraybuffer-allocations",
709
            "", /* undocumented, only for debugging */
710
            &PerProcessOptions::debug_arraybuffer_allocations,
711
            kAllowedInEnvironment);
712
4930
  AddOption("--disable-proto",
713
            "disable Object.prototype.__proto__",
714
            &PerProcessOptions::disable_proto,
715
            kAllowedInEnvironment);
716
717
  // 12.x renamed this inadvertently, so alias it for consistency within the
718
  // release line, while using the original name for consistency with older
719
  // release lines.
720
4930
  AddOption("--security-revert", "", &PerProcessOptions::security_reverts);
721
4930
  AddAlias("--security-reverts", "--security-revert");
722
4930
  AddOption("--completion-bash",
723
            "print source-able bash completion script",
724
            &PerProcessOptions::print_bash_completion);
725
4930
  AddOption("--help",
726
            "print node command line options",
727
            &PerProcessOptions::print_help);
728
4930
  AddAlias("-h", "--help");
729
4930
  AddOption(
730
      "--version", "print Node.js version", &PerProcessOptions::print_version);
731
4930
  AddAlias("-v", "--version");
732
4930
  AddOption("--v8-options",
733
            "print V8 command line options",
734
            &PerProcessOptions::print_v8_help);
735
4930
  AddOption("--report-compact",
736
            "output compact single-line JSON",
737
            &PerProcessOptions::report_compact,
738
            kAllowedInEnvironment);
739
4930
  AddOption("--report-dir",
740
            "define custom report pathname."
741
            " (default: current working directory)",
742
            &PerProcessOptions::report_directory,
743
            kAllowedInEnvironment);
744
4930
  AddAlias("--report-directory", "--report-dir");
745
4930
  AddOption("--report-filename",
746
            "define custom report file name."
747
            " (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)",
748
            &PerProcessOptions::report_filename,
749
            kAllowedInEnvironment);
750
4930
  AddOption("--report-on-fatalerror",
751
              "generate diagnostic report on fatal (internal) errors",
752
              &PerProcessOptions::report_on_fatalerror,
753
              kAllowedInEnvironment);
754
755
#ifdef NODE_HAVE_I18N_SUPPORT
756
4930
  AddOption("--icu-data-dir",
757
            "set ICU data load path to dir (overrides NODE_ICU_DATA)"
758
#ifndef NODE_HAVE_SMALL_ICU
759
            " (note: linked-in ICU data is present)"
760
#endif
761
            ,
762
            &PerProcessOptions::icu_data_dir,
763
            kAllowedInEnvironment);
764
#endif
765
766
#if HAVE_OPENSSL
767
4930
  AddOption("--openssl-config",
768
            "load OpenSSL configuration from the specified file "
769
            "(overrides OPENSSL_CONF)",
770
            &PerProcessOptions::openssl_config,
771
            kAllowedInEnvironment);
772
4930
  AddOption("--tls-cipher-list",
773
            "use an alternative default TLS cipher list",
774
            &PerProcessOptions::tls_cipher_list,
775
            kAllowedInEnvironment);
776
4930
  AddOption("--use-openssl-ca",
777
            "use OpenSSL's default CA store"
778
#if defined(NODE_OPENSSL_CERT_STORE)
779
            " (default)"
780
#endif
781
            ,
782
            &PerProcessOptions::use_openssl_ca,
783
            kAllowedInEnvironment);
784
4930
  AddOption("--use-bundled-ca",
785
            "use bundled CA store"
786
#if !defined(NODE_OPENSSL_CERT_STORE)
787
            " (default)"
788
#endif
789
            ,
790
            &PerProcessOptions::use_bundled_ca,
791
            kAllowedInEnvironment);
792
  // Similar to [has_eval_string] above, except that the separation between
793
  // this and use_openssl_ca only exists for option validation after parsing.
794
  // This is not ideal.
795
4930
  AddOption("[ssl_openssl_cert_store]",
796
            "",
797
            &PerProcessOptions::ssl_openssl_cert_store);
798
4930
  Implies("--use-openssl-ca", "[ssl_openssl_cert_store]");
799
4930
  ImpliesNot("--use-bundled-ca", "[ssl_openssl_cert_store]");
800
4930
  AddOption("--enable-fips",
801
            "enable FIPS crypto at startup",
802
            &PerProcessOptions::enable_fips_crypto,
803
            kAllowedInEnvironment);
804
4930
  AddOption("--force-fips",
805
            "force FIPS crypto (cannot be disabled)",
806
            &PerProcessOptions::force_fips_crypto,
807
            kAllowedInEnvironment);
808
4930
  AddOption("--secure-heap",
809
            "total size of the OpenSSL secure heap",
810
            &PerProcessOptions::secure_heap,
811
            kAllowedInEnvironment);
812
4930
  AddOption("--secure-heap-min",
813
            "minimum allocation size from the OpenSSL secure heap",
814
            &PerProcessOptions::secure_heap_min,
815
            kAllowedInEnvironment);
816
#endif
817
4930
  AddOption("--use-largepages",
818
            "Map the Node.js static code to large pages. Options are "
819
            "'off' (the default value, meaning do not map), "
820
            "'on' (map and ignore failure, reporting it to stderr), "
821
            "or 'silent' (map and silently ignore failure)",
822
            &PerProcessOptions::use_largepages,
823
            kAllowedInEnvironment);
824
825
4930
  AddOption("--trace-sigint",
826
            "enable printing JavaScript stacktrace on SIGINT",
827
            &PerProcessOptions::trace_sigint,
828
            kAllowedInEnvironment);
829
830
4930
  Insert(iop, &PerProcessOptions::get_per_isolate_options);
831
832
4930
  AddOption("--node-memory-debug",
833
            "Run with extra debug checks for memory leaks in Node.js itself",
834
4930
            NoOp{}, kAllowedInEnvironment);
835
4930
  Implies("--node-memory-debug", "--debug-arraybuffer-allocations");
836
4930
  Implies("--node-memory-debug", "--verify-base-objects");
837
4930
}
838
839
112
inline std::string RemoveBrackets(const std::string& host) {
840


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

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

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

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


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

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

1384046
             .FromMaybe(false) ||
1027
1384046
        !info->Set(context,
1028
                   env->env_var_settings_string(),
1029
                   Integer::New(isolate,
1030
2076069
                                static_cast<int>(option_info.env_setting)))
1031

1384046
             .FromMaybe(false) ||
1032
1384046
        !info->Set(context,
1033
                   env->type_string(),
1034
2076069
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1035

1384046
             .FromMaybe(false) ||
1036
1384046
        !info->Set(context,
1037
                   env->default_is_true_string(),
1038
2076069
                   Boolean::New(isolate, option_info.default_is_true))
1039

1384046
             .FromMaybe(false) ||
1040

3460115
        info->Set(context, env->value_string(), value).IsNothing() ||
1041

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

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

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

2630
    if (c == '\\' && is_in_string) {
1139
      if (index + 1 == node_options.size()) {
1140
        errors->push_back("invalid value for NODE_OPTIONS "
1141
                          "(invalid escape)\n");
1142
        return env_argv;
1143
      } else {
1144
        c = node_options.at(++index);
1145
      }
1146

2630
    } else if (c == ' ' && !is_in_string) {
1147
32
      will_start_new_arg = true;
1148
32
      continue;
1149
2598
    } else if (c == '"') {
1150
4
      is_in_string = !is_in_string;
1151
4
      continue;
1152
    }
1153
1154
2594
    if (will_start_new_arg) {
1155
109
      env_argv.emplace_back(std::string(1, c));
1156
109
      will_start_new_arg = false;
1157
    } else {
1158
2485
      env_argv.back() += c;
1159
    }
1160
  }
1161
1162
5069
  if (is_in_string) {
1163
    errors->push_back("invalid value for NODE_OPTIONS "
1164
                      "(unterminated string)\n");
1165
  }
1166
5069
  return env_argv;
1167
}
1168
}  // namespace node
1169
1170
4924
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)