GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/env.h Lines: 46 46 100.0 %
Date: 2019-07-28 22:34:34 Branches: 6 12 50.0 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#ifndef SRC_ENV_H_
23
#define SRC_ENV_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
#include "aliased_buffer.h"
28
#if HAVE_INSPECTOR
29
#include "inspector_agent.h"
30
#include "inspector_profiler.h"
31
#endif
32
#include "handle_wrap.h"
33
#include "node.h"
34
#include "node_binding.h"
35
#include "node_http2_state.h"
36
#include "node_main_instance.h"
37
#include "node_options.h"
38
#include "req_wrap.h"
39
#include "util.h"
40
#include "uv.h"
41
#include "v8.h"
42
43
#include <array>
44
#include <atomic>
45
#include <cstdint>
46
#include <functional>
47
#include <list>
48
#include <unordered_map>
49
#include <unordered_set>
50
#include <vector>
51
52
struct nghttp2_rcbuf;
53
54
namespace node {
55
56
namespace contextify {
57
class ContextifyScript;
58
class CompiledFnEntry;
59
}
60
61
namespace fs {
62
class FileHandleReadWrap;
63
}
64
65
namespace performance {
66
class performance_state;
67
}
68
69
namespace tracing {
70
class AgentWriterHandle;
71
}
72
73
#if HAVE_INSPECTOR
74
namespace profiler {
75
class V8CoverageConnection;
76
class V8CpuProfilerConnection;
77
class V8HeapProfilerConnection;
78
}  // namespace profiler
79
80
namespace inspector {
81
class ParentInspectorHandle;
82
}
83
#endif  // HAVE_INSPECTOR
84
85
namespace worker {
86
class Worker;
87
}
88
89
namespace loader {
90
class ModuleWrap;
91
92
4984
struct PackageConfig {
93
  enum class Exists { Yes, No };
94
  enum class IsValid { Yes, No };
95
  enum class HasMain { Yes, No };
96
  enum PackageType : uint32_t { None = 0, CommonJS, Module };
97
98
  const Exists exists;
99
  const IsValid is_valid;
100
  const HasMain has_main;
101
  const std::string main;
102
  const PackageType type;
103
104
  v8::Global<v8::Value> exports;
105
};
106
}  // namespace loader
107
108
enum class FsStatsOffset {
109
  kDev = 0,
110
  kMode,
111
  kNlink,
112
  kUid,
113
  kGid,
114
  kRdev,
115
  kBlkSize,
116
  kIno,
117
  kSize,
118
  kBlocks,
119
  kATimeSec,
120
  kATimeNsec,
121
  kMTimeSec,
122
  kMTimeNsec,
123
  kCTimeSec,
124
  kCTimeNsec,
125
  kBirthTimeSec,
126
  kBirthTimeNsec,
127
  kFsStatsFieldsNumber
128
};
129
130
// Stat fields buffers contain twice the number of entries in an uv_stat_t
131
// because `fs.StatWatcher` needs room to store 2 `fs.Stats` instances.
132
constexpr size_t kFsStatsBufferLength =
133
    static_cast<size_t>(FsStatsOffset::kFsStatsFieldsNumber) * 2;
134
135
// PER_ISOLATE_* macros: We have a lot of per-isolate properties
136
// and adding and maintaining their getters and setters by hand would be
137
// difficult so let's make the preprocessor generate them for us.
138
//
139
// In each macro, `V` is expected to be the name of a macro or function which
140
// accepts the number of arguments provided in each tuple in the macro body,
141
// typically two. The named function will be invoked against each tuple.
142
//
143
// Make sure that any macro V defined for use with the PER_ISOLATE_* macros is
144
// undefined again after use.
145
146
// Private symbols are per-isolate primitives but Environment proxies them
147
// for the sake of convenience.  Strings should be ASCII-only and have a
148
// "node:" prefix to avoid name clashes with third-party code.
149
#define PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)                              \
150
  V(alpn_buffer_private_symbol, "node:alpnBuffer")                            \
151
  V(arrow_message_private_symbol, "node:arrowMessage")                        \
152
  V(contextify_context_private_symbol, "node:contextify:context")             \
153
  V(contextify_global_private_symbol, "node:contextify:global")               \
154
  V(decorated_private_symbol, "node:decorated")                               \
155
  V(napi_wrapper, "node:napi:wrapper")                                        \
156
  V(sab_lifetimepartner_symbol, "node:sharedArrayBufferLifetimePartner")      \
157
158
// Symbols are per-isolate primitives but Environment proxies them
159
// for the sake of convenience.
160
#define PER_ISOLATE_SYMBOL_PROPERTIES(V)                                      \
161
  V(handle_onclose_symbol, "handle_onclose")                                  \
162
  V(no_message_symbol, "no_message_symbol")                                   \
163
  V(oninit_symbol, "oninit")                                                  \
164
  V(owner_symbol, "owner")                                                    \
165
166
// Strings are per-isolate primitives but Environment proxies them
167
// for the sake of convenience.  Strings should be ASCII-only.
168
#define PER_ISOLATE_STRING_PROPERTIES(V)                                       \
169
  V(address_string, "address")                                                 \
170
  V(aliases_string, "aliases")                                                 \
171
  V(args_string, "args")                                                       \
172
  V(asn1curve_string, "asn1Curve")                                             \
173
  V(async_ids_stack_string, "async_ids_stack")                                 \
174
  V(bits_string, "bits")                                                       \
175
  V(buffer_string, "buffer")                                                   \
176
  V(bytes_parsed_string, "bytesParsed")                                        \
177
  V(bytes_read_string, "bytesRead")                                            \
178
  V(bytes_written_string, "bytesWritten")                                      \
179
  V(cached_data_produced_string, "cachedDataProduced")                         \
180
  V(cached_data_rejected_string, "cachedDataRejected")                         \
181
  V(cached_data_string, "cachedData")                                          \
182
  V(cache_key_string, "cacheKey")                                              \
183
  V(change_string, "change")                                                   \
184
  V(channel_string, "channel")                                                 \
185
  V(chunks_sent_since_last_write_string, "chunksSentSinceLastWrite")           \
186
  V(clone_unsupported_type_str, "Cannot transfer object of unsupported type.") \
187
  V(code_string, "code")                                                       \
188
  V(commonjs_string, "commonjs")                                               \
189
  V(config_string, "config")                                                   \
190
  V(constants_string, "constants")                                             \
191
  V(crypto_dsa_string, "dsa")                                                  \
192
  V(crypto_ec_string, "ec")                                                    \
193
  V(crypto_ed25519_string, "ed25519")                                          \
194
  V(crypto_ed448_string, "ed448")                                              \
195
  V(crypto_x25519_string, "x25519")                                            \
196
  V(crypto_x448_string, "x448")                                                \
197
  V(crypto_rsa_string, "rsa")                                                  \
198
  V(crypto_rsa_pss_string, "rsa-pss")                                          \
199
  V(cwd_string, "cwd")                                                         \
200
  V(data_string, "data")                                                       \
201
  V(dest_string, "dest")                                                       \
202
  V(destroyed_string, "destroyed")                                             \
203
  V(detached_string, "detached")                                               \
204
  V(dns_a_string, "A")                                                         \
205
  V(dns_aaaa_string, "AAAA")                                                   \
206
  V(dns_cname_string, "CNAME")                                                 \
207
  V(dns_mx_string, "MX")                                                       \
208
  V(dns_naptr_string, "NAPTR")                                                 \
209
  V(dns_ns_string, "NS")                                                       \
210
  V(dns_ptr_string, "PTR")                                                     \
211
  V(dns_soa_string, "SOA")                                                     \
212
  V(dns_srv_string, "SRV")                                                     \
213
  V(dns_txt_string, "TXT")                                                     \
214
  V(duration_string, "duration")                                               \
215
  V(emit_warning_string, "emitWarning")                                        \
216
  V(encoding_string, "encoding")                                               \
217
  V(entries_string, "entries")                                                 \
218
  V(entry_type_string, "entryType")                                            \
219
  V(env_pairs_string, "envPairs")                                              \
220
  V(env_var_settings_string, "envVarSettings")                                 \
221
  V(errno_string, "errno")                                                     \
222
  V(error_string, "error")                                                     \
223
  V(exchange_string, "exchange")                                               \
224
  V(exit_code_string, "exitCode")                                              \
225
  V(expire_string, "expire")                                                   \
226
  V(exponent_string, "exponent")                                               \
227
  V(exports_string, "exports")                                                 \
228
  V(ext_key_usage_string, "ext_key_usage")                                     \
229
  V(external_stream_string, "_externalStream")                                 \
230
  V(family_string, "family")                                                   \
231
  V(fatal_exception_string, "_fatalException")                                 \
232
  V(fd_string, "fd")                                                           \
233
  V(file_string, "file")                                                       \
234
  V(fingerprint256_string, "fingerprint256")                                   \
235
  V(fingerprint_string, "fingerprint")                                         \
236
  V(flags_string, "flags")                                                     \
237
  V(fragment_string, "fragment")                                               \
238
  V(function_string, "function")                                               \
239
  V(get_data_clone_error_string, "_getDataCloneError")                         \
240
  V(get_shared_array_buffer_id_string, "_getSharedArrayBufferId")              \
241
  V(gid_string, "gid")                                                         \
242
  V(h2_string, "h2")                                                           \
243
  V(handle_string, "handle")                                                   \
244
  V(help_text_string, "helpText")                                              \
245
  V(homedir_string, "homedir")                                                 \
246
  V(host_string, "host")                                                       \
247
  V(hostmaster_string, "hostmaster")                                           \
248
  V(http_1_1_string, "http/1.1")                                               \
249
  V(ignore_string, "ignore")                                                   \
250
  V(infoaccess_string, "infoAccess")                                           \
251
  V(inherit_string, "inherit")                                                 \
252
  V(input_string, "input")                                                     \
253
  V(internal_binding_string, "internalBinding")                                \
254
  V(internal_string, "internal")                                               \
255
  V(ipv4_string, "IPv4")                                                       \
256
  V(ipv6_string, "IPv6")                                                       \
257
  V(isclosing_string, "isClosing")                                             \
258
  V(issuer_string, "issuer")                                                   \
259
  V(issuercert_string, "issuerCertificate")                                    \
260
  V(kill_signal_string, "killSignal")                                          \
261
  V(kind_string, "kind")                                                       \
262
  V(library_string, "library")                                                 \
263
  V(mac_string, "mac")                                                         \
264
  V(main_string, "main")                                                       \
265
  V(max_buffer_string, "maxBuffer")                                            \
266
  V(message_port_constructor_string, "MessagePort")                            \
267
  V(message_port_string, "messagePort")                                        \
268
  V(message_string, "message")                                                 \
269
  V(minttl_string, "minttl")                                                   \
270
  V(module_string, "module")                                                   \
271
  V(modulus_string, "modulus")                                                 \
272
  V(name_string, "name")                                                       \
273
  V(netmask_string, "netmask")                                                 \
274
  V(nistcurve_string, "nistCurve")                                             \
275
  V(nsname_string, "nsname")                                                   \
276
  V(ocsp_request_string, "OCSPRequest")                                        \
277
  V(oncertcb_string, "oncertcb")                                               \
278
  V(onchange_string, "onchange")                                               \
279
  V(onclienthello_string, "onclienthello")                                     \
280
  V(oncomplete_string, "oncomplete")                                           \
281
  V(onconnection_string, "onconnection")                                       \
282
  V(ondone_string, "ondone")                                                   \
283
  V(onerror_string, "onerror")                                                 \
284
  V(onexit_string, "onexit")                                                   \
285
  V(onhandshakedone_string, "onhandshakedone")                                 \
286
  V(onhandshakestart_string, "onhandshakestart")                               \
287
  V(onkeylog_string, "onkeylog")                                               \
288
  V(onmessage_string, "onmessage")                                             \
289
  V(onnewsession_string, "onnewsession")                                       \
290
  V(onocspresponse_string, "onocspresponse")                                   \
291
  V(onreadstart_string, "onreadstart")                                         \
292
  V(onreadstop_string, "onreadstop")                                           \
293
  V(onshutdown_string, "onshutdown")                                           \
294
  V(onsignal_string, "onsignal")                                               \
295
  V(onunpipe_string, "onunpipe")                                               \
296
  V(onwrite_string, "onwrite")                                                 \
297
  V(openssl_error_stack, "opensslErrorStack")                                  \
298
  V(options_string, "options")                                                 \
299
  V(order_string, "order")                                                     \
300
  V(output_string, "output")                                                   \
301
  V(parse_error_string, "Parse Error")                                         \
302
  V(password_string, "password")                                               \
303
  V(path_string, "path")                                                       \
304
  V(pending_handle_string, "pendingHandle")                                    \
305
  V(pid_string, "pid")                                                         \
306
  V(pipe_source_string, "pipeSource")                                          \
307
  V(pipe_string, "pipe")                                                       \
308
  V(pipe_target_string, "pipeTarget")                                          \
309
  V(port1_string, "port1")                                                     \
310
  V(port2_string, "port2")                                                     \
311
  V(port_string, "port")                                                       \
312
  V(preference_string, "preference")                                           \
313
  V(primordials_string, "primordials")                                         \
314
  V(priority_string, "priority")                                               \
315
  V(process_string, "process")                                                 \
316
  V(promise_string, "promise")                                                 \
317
  V(pubkey_string, "pubkey")                                                   \
318
  V(query_string, "query")                                                     \
319
  V(raw_string, "raw")                                                         \
320
  V(read_host_object_string, "_readHostObject")                                \
321
  V(readable_string, "readable")                                               \
322
  V(reason_string, "reason")                                                   \
323
  V(refresh_string, "refresh")                                                 \
324
  V(regexp_string, "regexp")                                                   \
325
  V(rename_string, "rename")                                                   \
326
  V(replacement_string, "replacement")                                         \
327
  V(require_string, "require")                                                 \
328
  V(retry_string, "retry")                                                     \
329
  V(scheme_string, "scheme")                                                   \
330
  V(scopeid_string, "scopeid")                                                 \
331
  V(serial_number_string, "serialNumber")                                      \
332
  V(serial_string, "serial")                                                   \
333
  V(servername_string, "servername")                                           \
334
  V(service_string, "service")                                                 \
335
  V(session_id_string, "sessionId")                                            \
336
  V(shell_string, "shell")                                                     \
337
  V(signal_string, "signal")                                                   \
338
  V(sink_string, "sink")                                                       \
339
  V(size_string, "size")                                                       \
340
  V(sni_context_err_string, "Invalid SNI context")                             \
341
  V(sni_context_string, "sni_context")                                         \
342
  V(source_string, "source")                                                   \
343
  V(stack_string, "stack")                                                     \
344
  V(start_time_string, "startTime")                                            \
345
  V(status_string, "status")                                                   \
346
  V(stdio_string, "stdio")                                                     \
347
  V(subject_string, "subject")                                                 \
348
  V(subjectaltname_string, "subjectaltname")                                   \
349
  V(syscall_string, "syscall")                                                 \
350
  V(target_string, "target")                                                   \
351
  V(thread_id_string, "threadId")                                              \
352
  V(ticketkeycallback_string, "onticketkeycallback")                           \
353
  V(timeout_string, "timeout")                                                 \
354
  V(tls_ticket_string, "tlsTicket")                                            \
355
  V(ttl_string, "ttl")                                                         \
356
  V(type_string, "type")                                                       \
357
  V(uid_string, "uid")                                                         \
358
  V(unknown_string, "<unknown>")                                               \
359
  V(url_string, "url")                                                         \
360
  V(username_string, "username")                                               \
361
  V(valid_from_string, "valid_from")                                           \
362
  V(valid_to_string, "valid_to")                                               \
363
  V(value_string, "value")                                                     \
364
  V(verify_error_string, "verifyError")                                        \
365
  V(version_string, "version")                                                 \
366
  V(weight_string, "weight")                                                   \
367
  V(windows_hide_string, "windowsHide")                                        \
368
  V(windows_verbatim_arguments_string, "windowsVerbatimArguments")             \
369
  V(wrap_string, "wrap")                                                       \
370
  V(writable_string, "writable")                                               \
371
  V(write_host_object_string, "_writeHostObject")                              \
372
  V(write_queue_size_string, "writeQueueSize")                                 \
373
  V(x_forwarded_string, "x-forwarded-for")                                     \
374
  V(zero_return_string, "ZERO_RETURN")
375
376
#define ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)                             \
377
  V(as_callback_data_template, v8::FunctionTemplate)                           \
378
  V(async_wrap_ctor_template, v8::FunctionTemplate)                            \
379
  V(async_wrap_object_ctor_template, v8::FunctionTemplate)                     \
380
  V(compiled_fn_entry_template, v8::ObjectTemplate)                            \
381
  V(fd_constructor_template, v8::ObjectTemplate)                               \
382
  V(fdclose_constructor_template, v8::ObjectTemplate)                          \
383
  V(filehandlereadwrap_template, v8::ObjectTemplate)                           \
384
  V(fsreqpromise_constructor_template, v8::ObjectTemplate)                     \
385
  V(handle_wrap_ctor_template, v8::FunctionTemplate)                           \
386
  V(http2settings_constructor_template, v8::ObjectTemplate)                    \
387
  V(http2stream_constructor_template, v8::ObjectTemplate)                      \
388
  V(http2ping_constructor_template, v8::ObjectTemplate)                        \
389
  V(libuv_stream_wrap_ctor_template, v8::FunctionTemplate)                     \
390
  V(message_event_object_template, v8::ObjectTemplate)                         \
391
  V(message_port_constructor_template, v8::FunctionTemplate)                   \
392
  V(pipe_constructor_template, v8::FunctionTemplate)                           \
393
  V(promise_wrap_template, v8::ObjectTemplate)                                 \
394
  V(sab_lifetimepartner_constructor_template, v8::FunctionTemplate)            \
395
  V(script_context_constructor_template, v8::FunctionTemplate)                 \
396
  V(secure_context_constructor_template, v8::FunctionTemplate)                 \
397
  V(shutdown_wrap_template, v8::ObjectTemplate)                                \
398
  V(streambaseoutputstream_constructor_template, v8::ObjectTemplate)           \
399
  V(tcp_constructor_template, v8::FunctionTemplate)                            \
400
  V(tty_constructor_template, v8::FunctionTemplate)                            \
401
  V(write_wrap_template, v8::ObjectTemplate)
402
403
#define ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)                                \
404
  V(as_callback_data, v8::Object)                                              \
405
  V(async_hooks_after_function, v8::Function)                                  \
406
  V(async_hooks_before_function, v8::Function)                                 \
407
  V(async_hooks_binding, v8::Object)                                           \
408
  V(async_hooks_destroy_function, v8::Function)                                \
409
  V(async_hooks_init_function, v8::Function)                                   \
410
  V(async_hooks_promise_resolve_function, v8::Function)                        \
411
  V(buffer_prototype_object, v8::Object)                                       \
412
  V(crypto_key_object_constructor, v8::Function)                               \
413
  V(domain_callback, v8::Function)                                             \
414
  V(domexception_function, v8::Function)                                       \
415
  V(enhance_fatal_stack_after_inspector, v8::Function)                         \
416
  V(enhance_fatal_stack_before_inspector, v8::Function)                        \
417
  V(fs_use_promises_symbol, v8::Symbol)                                        \
418
  V(host_import_module_dynamically_callback, v8::Function)                     \
419
  V(host_initialize_import_meta_object_callback, v8::Function)                 \
420
  V(http2session_on_altsvc_function, v8::Function)                             \
421
  V(http2session_on_error_function, v8::Function)                              \
422
  V(http2session_on_frame_error_function, v8::Function)                        \
423
  V(http2session_on_goaway_data_function, v8::Function)                        \
424
  V(http2session_on_headers_function, v8::Function)                            \
425
  V(http2session_on_origin_function, v8::Function)                             \
426
  V(http2session_on_ping_function, v8::Function)                               \
427
  V(http2session_on_priority_function, v8::Function)                           \
428
  V(http2session_on_select_padding_function, v8::Function)                     \
429
  V(http2session_on_settings_function, v8::Function)                           \
430
  V(http2session_on_stream_close_function, v8::Function)                       \
431
  V(http2session_on_stream_trailers_function, v8::Function)                    \
432
  V(internal_binding_loader, v8::Function)                                     \
433
  V(immediate_callback_function, v8::Function)                                 \
434
  V(inspector_console_extension_installer, v8::Function)                       \
435
  V(message_port, v8::Object)                                                  \
436
  V(native_module_require, v8::Function)                                       \
437
  V(performance_entry_callback, v8::Function)                                  \
438
  V(performance_entry_template, v8::Function)                                  \
439
  V(prepare_stack_trace_callback, v8::Function)                                \
440
  V(process_object, v8::Object)                                                \
441
  V(primordials, v8::Object)                                                   \
442
  V(promise_reject_callback, v8::Function)                                     \
443
  V(script_data_constructor_function, v8::Function)                            \
444
  V(tick_callback_function, v8::Function)                                      \
445
  V(timers_callback_function, v8::Function)                                    \
446
  V(tls_wrap_constructor_function, v8::Function)                               \
447
  V(trace_category_state_function, v8::Function)                               \
448
  V(udp_constructor_function, v8::Function)                                    \
449
  V(url_constructor_function, v8::Function)
450
451
class Environment;
452
453
9158
class IsolateData : public MemoryRetainer {
454
 public:
455
  IsolateData(v8::Isolate* isolate,
456
              uv_loop_t* event_loop,
457
              MultiIsolatePlatform* platform = nullptr,
458
              ArrayBufferAllocator* node_allocator = nullptr,
459
              const std::vector<size_t>* indexes = nullptr);
460
51
  SET_MEMORY_INFO_NAME(IsolateData)
461
51
  SET_SELF_SIZE(IsolateData)
462
  void MemoryInfo(MemoryTracker* tracker) const override;
463
  std::vector<size_t> Serialize(v8::SnapshotCreator* creator);
464
465
  inline uv_loop_t* event_loop() const;
466
  inline MultiIsolatePlatform* platform() const;
467
  inline std::shared_ptr<PerIsolateOptions> options();
468
  inline void set_options(std::shared_ptr<PerIsolateOptions> options);
469
470
  inline bool uses_node_allocator() const;
471
  inline v8::ArrayBuffer::Allocator* allocator() const;
472
  inline NodeArrayBufferAllocator* node_allocator() const;
473
474
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
475
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
476
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
477
#define V(TypeName, PropertyName)                                             \
478
  inline v8::Local<TypeName> PropertyName(v8::Isolate* isolate) const;
479
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
480
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
481
  PER_ISOLATE_STRING_PROPERTIES(VS)
482
#undef V
483
#undef VY
484
#undef VS
485
#undef VP
486
487
  std::unordered_map<nghttp2_rcbuf*, v8::Eternal<v8::String>> http2_static_strs;
488
  inline v8::Isolate* isolate() const;
489
  IsolateData(const IsolateData&) = delete;
490
  IsolateData& operator=(const IsolateData&) = delete;
491
  IsolateData(IsolateData&&) = delete;
492
  IsolateData& operator=(IsolateData&&) = delete;
493
494
 private:
495
  void DeserializeProperties(const std::vector<size_t>* indexes);
496
  void CreateProperties();
497
498
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
499
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
500
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
501
#define V(TypeName, PropertyName)                                             \
502
  v8::Eternal<TypeName> PropertyName ## _;
503
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
504
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
505
  PER_ISOLATE_STRING_PROPERTIES(VS)
506
#undef V
507
#undef VY
508
#undef VS
509
#undef VP
510
511
  v8::Isolate* const isolate_;
512
  uv_loop_t* const event_loop_;
513
  v8::ArrayBuffer::Allocator* const allocator_;
514
  NodeArrayBufferAllocator* const node_allocator_;
515
  const bool uses_node_allocator_;
516
  MultiIsolatePlatform* platform_;
517
  std::shared_ptr<PerIsolateOptions> options_;
518
};
519
520
10393
struct ContextInfo {
521
10393
  explicit ContextInfo(const std::string& name) : name(name) {}
522
  const std::string name;
523
  std::string origin;
524
  bool is_default = false;
525
};
526
527
// Listing the AsyncWrap provider types first enables us to cast directly
528
// from a provider type to a debug category.
529
#define DEBUG_CATEGORY_NAMES(V)                                                \
530
  NODE_ASYNC_PROVIDER_TYPES(V)                                                 \
531
  V(INSPECTOR_SERVER)                                                          \
532
  V(INSPECTOR_PROFILER)
533
534
enum class DebugCategory {
535
#define V(name) name,
536
  DEBUG_CATEGORY_NAMES(V)
537
#undef V
538
  CATEGORY_COUNT
539
};
540
541
// A unique-pointer-ish object that is compatible with the JS engine's
542
// ArrayBuffer::Allocator.
543
struct AllocatedBuffer {
544
 public:
545
  explicit inline AllocatedBuffer(Environment* env = nullptr);
546
  inline AllocatedBuffer(Environment* env, uv_buf_t buf);
547
  inline ~AllocatedBuffer();
548
  inline void Resize(size_t len);
549
550
  inline uv_buf_t release();
551
  inline char* data();
552
  inline const char* data() const;
553
  inline size_t size() const;
554
  inline void clear();
555
556
  inline v8::MaybeLocal<v8::Object> ToBuffer();
557
  inline v8::Local<v8::ArrayBuffer> ToArrayBuffer();
558
559
  inline AllocatedBuffer(AllocatedBuffer&& other);
560
  inline AllocatedBuffer& operator=(AllocatedBuffer&& other);
561
  AllocatedBuffer(const AllocatedBuffer& other) = delete;
562
  AllocatedBuffer& operator=(const AllocatedBuffer& other) = delete;
563
564
 private:
565
  Environment* env_;
566
  // We do not pass this to libuv directly, but uv_buf_t is a convenient way
567
  // to represent a chunk of memory, and plays nicely with other parts of core.
568
  uv_buf_t buffer_;
569
570
  friend class Environment;
571
};
572
573
class AsyncRequest : public MemoryRetainer {
574
 public:
575
5171
  AsyncRequest() = default;
576
  ~AsyncRequest();
577
578
  AsyncRequest(const AsyncRequest&) = delete;
579
  AsyncRequest& operator=(const AsyncRequest&) = delete;
580
  AsyncRequest(AsyncRequest&&) = delete;
581
  AsyncRequest& operator=(AsyncRequest&&) = delete;
582
583
  void Install(Environment* env, void* data, uv_async_cb target);
584
  void Uninstall();
585
  void Stop();
586
  inline void set_stopped(bool flag);
587
  inline bool is_stopped() const;
588
  uv_async_t* GetHandle();
589
  void MemoryInfo(MemoryTracker* tracker) const override;
590
591
592
55
  SET_MEMORY_INFO_NAME(AsyncRequest)
593
59
  SET_SELF_SIZE(AsyncRequest)
594
595
 private:
596
  Environment* env_;
597
  uv_async_t* async_ = nullptr;
598
  std::atomic_bool stopped_ {true};
599
};
600
601
class KVStore {
602
 public:
603
5033
  KVStore() = default;
604
4638
  virtual ~KVStore() = default;
605
  KVStore(const KVStore&) = delete;
606
  KVStore& operator=(const KVStore&) = delete;
607
  KVStore(KVStore&&) = delete;
608
  KVStore& operator=(KVStore&&) = delete;
609
610
  virtual v8::Local<v8::String> Get(v8::Isolate* isolate,
611
                                    v8::Local<v8::String> key) const = 0;
612
  virtual void Set(v8::Isolate* isolate,
613
                   v8::Local<v8::String> key,
614
                   v8::Local<v8::String> value) = 0;
615
  virtual int32_t Query(v8::Isolate* isolate,
616
                        v8::Local<v8::String> key) const = 0;
617
  virtual void Delete(v8::Isolate* isolate, v8::Local<v8::String> key) = 0;
618
  virtual v8::Local<v8::Array> Enumerate(v8::Isolate* isolate) const = 0;
619
620
  virtual std::shared_ptr<KVStore> Clone(v8::Isolate* isolate) const;
621
  virtual v8::Maybe<bool> AssignFromObject(v8::Local<v8::Context> context,
622
                                           v8::Local<v8::Object> entries);
623
624
  static std::shared_ptr<KVStore> CreateMapKVStore();
625
};
626
627
namespace per_process {
628
extern std::shared_ptr<KVStore> system_environment;
629
}
630
631
class AsyncHooks : public MemoryRetainer {
632
 public:
633
51
  SET_MEMORY_INFO_NAME(AsyncHooks)
634
51
  SET_SELF_SIZE(AsyncHooks)
635
  void MemoryInfo(MemoryTracker* tracker) const override;
636
637
  // Reason for both UidFields and Fields are that one is stored as a double*
638
  // and the other as a uint32_t*.
639
  enum Fields {
640
    kInit,
641
    kBefore,
642
    kAfter,
643
    kDestroy,
644
    kPromiseResolve,
645
    kTotals,
646
    kCheck,
647
    kStackLength,
648
    kFieldsCount,
649
  };
650
651
  enum UidFields {
652
    kExecutionAsyncId,
653
    kTriggerAsyncId,
654
    kAsyncIdCounter,
655
    kDefaultTriggerAsyncId,
656
    kUidFieldsCount,
657
  };
658
659
  inline AliasedUint32Array& fields();
660
  inline AliasedFloat64Array& async_id_fields();
661
  inline AliasedFloat64Array& async_ids_stack();
662
663
  inline v8::Local<v8::String> provider_string(int idx);
664
665
  inline void no_force_checks();
666
  inline Environment* env();
667
668
  inline void push_async_ids(double async_id, double trigger_async_id);
669
  inline bool pop_async_id(double async_id);
670
  inline void clear_async_id_stack();  // Used in fatal exceptions.
671
672
  AsyncHooks(const AsyncHooks&) = delete;
673
  AsyncHooks& operator=(const AsyncHooks&) = delete;
674
  AsyncHooks(AsyncHooks&&) = delete;
675
  AsyncHooks& operator=(AsyncHooks&&) = delete;
676
4570
  ~AsyncHooks() = default;
677
678
  // Used to set the kDefaultTriggerAsyncId in a scope. This is instead of
679
  // passing the trigger_async_id along with other constructor arguments.
680
  class DefaultTriggerAsyncIdScope {
681
   public:
682
    DefaultTriggerAsyncIdScope() = delete;
683
    explicit DefaultTriggerAsyncIdScope(Environment* env,
684
                                        double init_trigger_async_id);
685
    explicit DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap);
686
    ~DefaultTriggerAsyncIdScope();
687
688
    DefaultTriggerAsyncIdScope(const DefaultTriggerAsyncIdScope&) = delete;
689
    DefaultTriggerAsyncIdScope& operator=(const DefaultTriggerAsyncIdScope&) =
690
        delete;
691
    DefaultTriggerAsyncIdScope(DefaultTriggerAsyncIdScope&&) = delete;
692
    DefaultTriggerAsyncIdScope& operator=(DefaultTriggerAsyncIdScope&&) =
693
        delete;
694
695
   private:
696
    AsyncHooks* async_hooks_;
697
    double old_default_trigger_async_id_;
698
  };
699
700
 private:
701
  friend class Environment;  // So we can call the constructor.
702
  inline AsyncHooks();
703
  // Keep a list of all Persistent strings used for Provider types.
704
  std::array<v8::Eternal<v8::String>, AsyncWrap::PROVIDERS_LENGTH> providers_;
705
  // Stores the ids of the current execution context stack.
706
  AliasedFloat64Array async_ids_stack_;
707
  // Attached to a Uint32Array that tracks the number of active hooks for
708
  // each type.
709
  AliasedUint32Array fields_;
710
  // Attached to a Float64Array that tracks the state of async resources.
711
  AliasedFloat64Array async_id_fields_;
712
713
  void grow_async_ids_stack();
714
};
715
716
class AsyncCallbackScope {
717
 public:
718
  AsyncCallbackScope() = delete;
719
  explicit AsyncCallbackScope(Environment* env);
720
  ~AsyncCallbackScope();
721
  AsyncCallbackScope(const AsyncCallbackScope&) = delete;
722
  AsyncCallbackScope& operator=(const AsyncCallbackScope&) = delete;
723
  AsyncCallbackScope(AsyncCallbackScope&&) = delete;
724
  AsyncCallbackScope& operator=(AsyncCallbackScope&&) = delete;
725
726
 private:
727
  Environment* env_;
728
};
729
730
class ImmediateInfo : public MemoryRetainer {
731
 public:
732
  inline AliasedUint32Array& fields();
733
  inline uint32_t count() const;
734
  inline uint32_t ref_count() const;
735
  inline bool has_outstanding() const;
736
  inline void count_inc(uint32_t increment);
737
  inline void count_dec(uint32_t decrement);
738
  inline void ref_count_inc(uint32_t increment);
739
  inline void ref_count_dec(uint32_t decrement);
740
741
  ImmediateInfo(const ImmediateInfo&) = delete;
742
  ImmediateInfo& operator=(const ImmediateInfo&) = delete;
743
  ImmediateInfo(ImmediateInfo&&) = delete;
744
  ImmediateInfo& operator=(ImmediateInfo&&) = delete;
745
4570
  ~ImmediateInfo() = default;
746
747
51
  SET_MEMORY_INFO_NAME(ImmediateInfo)
748
51
  SET_SELF_SIZE(ImmediateInfo)
749
  void MemoryInfo(MemoryTracker* tracker) const override;
750
751
 private:
752
  friend class Environment;  // So we can call the constructor.
753
  inline explicit ImmediateInfo(v8::Isolate* isolate);
754
755
  enum Fields { kCount, kRefCount, kHasOutstanding, kFieldsCount };
756
757
  AliasedUint32Array fields_;
758
};
759
760
class TickInfo : public MemoryRetainer {
761
 public:
762
  inline AliasedUint8Array& fields();
763
  inline bool has_tick_scheduled() const;
764
  inline bool has_rejection_to_warn() const;
765
766
51
  SET_MEMORY_INFO_NAME(TickInfo)
767
51
  SET_SELF_SIZE(TickInfo)
768
  void MemoryInfo(MemoryTracker* tracker) const override;
769
770
  TickInfo(const TickInfo&) = delete;
771
  TickInfo& operator=(const TickInfo&) = delete;
772
  TickInfo(TickInfo&&) = delete;
773
  TickInfo& operator=(TickInfo&&) = delete;
774
4570
  ~TickInfo() = default;
775
776
 private:
777
  friend class Environment;  // So we can call the constructor.
778
  inline explicit TickInfo(v8::Isolate* isolate);
779
780
  enum Fields { kHasTickScheduled = 0, kHasRejectionToWarn, kFieldsCount };
781
782
  AliasedUint8Array fields_;
783
};
784
785
9138
class TrackingTraceStateObserver :
786
    public v8::TracingController::TraceStateObserver {
787
 public:
788
4965
  explicit TrackingTraceStateObserver(Environment* env) : env_(env) {}
789
790
102
  void OnTraceEnabled() override {
791
102
    UpdateTraceCategoryState();
792
102
  }
793
794
32
  void OnTraceDisabled() override {
795
32
    UpdateTraceCategoryState();
796
32
  }
797
798
 private:
799
  void UpdateTraceCategoryState();
800
801
  Environment* env_;
802
};
803
804
class ShouldNotAbortOnUncaughtScope {
805
 public:
806
  explicit inline ShouldNotAbortOnUncaughtScope(Environment* env);
807
  inline void Close();
808
  inline ~ShouldNotAbortOnUncaughtScope();
809
  ShouldNotAbortOnUncaughtScope(const ShouldNotAbortOnUncaughtScope&) = delete;
810
  ShouldNotAbortOnUncaughtScope& operator=(
811
      const ShouldNotAbortOnUncaughtScope&) = delete;
812
  ShouldNotAbortOnUncaughtScope(ShouldNotAbortOnUncaughtScope&&) = delete;
813
  ShouldNotAbortOnUncaughtScope& operator=(ShouldNotAbortOnUncaughtScope&&) =
814
      delete;
815
816
 private:
817
  Environment* env_;
818
};
819
820
class CleanupHookCallback {
821
 public:
822
1397466
  CleanupHookCallback(void (*fn)(void*),
823
                      void* arg,
824
                      uint64_t insertion_order_counter)
825
1397466
      : fn_(fn), arg_(arg), insertion_order_counter_(insertion_order_counter) {}
826
827
  // Only hashes `arg_`, since that is usually enough to identify the hook.
828
  struct Hash {
829
    inline size_t operator()(const CleanupHookCallback& cb) const;
830
  };
831
832
  // Compares by `fn_` and `arg_` being equal.
833
  struct Equal {
834
    inline bool operator()(const CleanupHookCallback& a,
835
                           const CleanupHookCallback& b) const;
836
  };
837
838
  inline BaseObject* GetBaseObject() const;
839
840
 private:
841
  friend class Environment;
842
  void (*fn_)(void*);
843
  void* arg_;
844
845
  // We keep track of the insertion order for these objects, so that we can
846
  // call the callbacks in reverse order when we are cleaning up.
847
  uint64_t insertion_order_counter_;
848
};
849
850
class Environment : public MemoryRetainer {
851
 public:
852
  Environment(const Environment&) = delete;
853
  Environment& operator=(const Environment&) = delete;
854
  Environment(Environment&&) = delete;
855
  Environment& operator=(Environment&&) = delete;
856
857
51
  SET_MEMORY_INFO_NAME(Environment)
858
859
  inline size_t SelfSize() const override;
860
86
  bool IsRootNode() const override { return true; }
861
  void MemoryInfo(MemoryTracker* tracker) const override;
862
863
  void CreateProperties();
864
  // Should be called before InitializeInspector()
865
  void InitializeDiagnostics();
866
#if HAVE_INSPECTOR && NODE_USE_V8_PLATFORM
867
  // If the environment is created for a worker, pass parent_handle and
868
  // the ownership if transferred into the Environment.
869
  int InitializeInspector(inspector::ParentInspectorHandle* parent_handle);
870
#endif
871
872
  v8::MaybeLocal<v8::Value> BootstrapInternalLoaders();
873
  v8::MaybeLocal<v8::Value> BootstrapNode();
874
  v8::MaybeLocal<v8::Value> RunBootstrapping();
875
876
  inline size_t async_callback_scope_depth() const;
877
  inline void PushAsyncCallbackScope();
878
  inline void PopAsyncCallbackScope();
879
880
  enum Flags {
881
    kNoFlags = 0,
882
    kIsMainThread = 1 << 0,
883
    kOwnsProcessState = 1 << 1,
884
    kOwnsInspector = 1 << 2,
885
  };
886
887
  static inline Environment* GetCurrent(v8::Isolate* isolate);
888
  static inline Environment* GetCurrent(v8::Local<v8::Context> context);
889
  static inline Environment* GetCurrent(
890
      const v8::FunctionCallbackInfo<v8::Value>& info);
891
892
  template <typename T>
893
  static inline Environment* GetCurrent(
894
      const v8::PropertyCallbackInfo<T>& info);
895
896
  static inline Environment* GetFromCallbackData(v8::Local<v8::Value> val);
897
898
  static uv_key_t thread_local_env;
899
  static inline Environment* GetThreadLocalEnv();
900
901
  Environment(IsolateData* isolate_data,
902
              v8::Local<v8::Context> context,
903
              const std::vector<std::string>& args,
904
              const std::vector<std::string>& exec_args,
905
              Flags flags = Flags(),
906
              uint64_t thread_id = kNoThreadId);
907
  ~Environment();
908
909
  void InitializeLibuv(bool start_profiler_idle_notifier);
910
  inline const std::vector<std::string>& exec_argv();
911
  inline const std::vector<std::string>& argv();
912
  const std::string& exec_path() const;
913
914
  typedef void (*HandleCleanupCb)(Environment* env,
915
                                  uv_handle_t* handle,
916
                                  void* arg);
917
  struct HandleCleanup {
918
    uv_handle_t* handle_;
919
    HandleCleanupCb cb_;
920
    void* arg_;
921
  };
922
923
  void RegisterHandleCleanups();
924
  void CleanupHandles();
925
  void Exit(int code);
926
  void ExitEnv();
927
928
  // Register clean-up cb to be called on environment destruction.
929
  inline void RegisterHandleCleanup(uv_handle_t* handle,
930
                                    HandleCleanupCb cb,
931
                                    void* arg);
932
933
  template <typename T, typename OnCloseCallback>
934
  inline void CloseHandle(T* handle, OnCloseCallback callback);
935
936
  inline void AssignToContext(v8::Local<v8::Context> context,
937
                              const ContextInfo& info);
938
939
  void StartProfilerIdleNotifier();
940
  void StopProfilerIdleNotifier();
941
  inline bool profiler_idle_notifier_started() const;
942
943
  inline v8::Isolate* isolate() const;
944
  inline uv_loop_t* event_loop() const;
945
  inline void TryLoadAddon(
946
      const char* filename,
947
      int flags,
948
      const std::function<bool(binding::DLib*)>& was_loaded);
949
950
  static inline Environment* from_timer_handle(uv_timer_t* handle);
951
  inline uv_timer_t* timer_handle();
952
953
  static inline Environment* from_immediate_check_handle(uv_check_t* handle);
954
  inline uv_check_t* immediate_check_handle();
955
  inline uv_idle_t* immediate_idle_handle();
956
957
  inline void IncreaseWaitingRequestCounter();
958
  inline void DecreaseWaitingRequestCounter();
959
960
  inline AsyncHooks* async_hooks();
961
  inline ImmediateInfo* immediate_info();
962
  inline TickInfo* tick_info();
963
  inline uint64_t timer_base() const;
964
  inline std::shared_ptr<KVStore> env_vars();
965
  inline void set_env_vars(std::shared_ptr<KVStore> env_vars);
966
967
  inline IsolateData* isolate_data() const;
968
969
  // Utilities that allocate memory using the Isolate's ArrayBuffer::Allocator.
970
  // In particular, using AllocateManaged() will provide a RAII-style object
971
  // with easy conversion to `Buffer` and `ArrayBuffer` objects.
972
  inline AllocatedBuffer AllocateManaged(size_t size, bool checked = true);
973
  inline char* Allocate(size_t size);
974
  inline char* AllocateUnchecked(size_t size);
975
  char* Reallocate(char* data, size_t old_size, size_t size);
976
  inline void Free(char* data, size_t size);
977
978
  inline bool printed_error() const;
979
  inline void set_printed_error(bool value);
980
981
  void PrintSyncTrace() const;
982
  inline void set_trace_sync_io(bool value);
983
984
  // This stores whether the --abort-on-uncaught-exception flag was passed
985
  // to Node.
986
  inline bool abort_on_uncaught_exception() const;
987
  inline void set_abort_on_uncaught_exception(bool value);
988
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
989
  // should abort the process or not if --abort-on-uncaught-exception was
990
  // passed to Node. If the flag was not passed, it is ignored.
991
  inline AliasedUint32Array& should_abort_on_uncaught_toggle();
992
993
  inline AliasedInt32Array& stream_base_state();
994
995
  // The necessary API for async_hooks.
996
  inline double new_async_id();
997
  inline double execution_async_id();
998
  inline double trigger_async_id();
999
  inline double get_default_trigger_async_id();
1000
1001
  // List of id's that have been destroyed and need the destroy() cb called.
1002
  inline std::vector<double>* destroy_async_id_list();
1003
1004
  std::set<std::string> native_modules_with_cache;
1005
  std::set<std::string> native_modules_without_cache;
1006
1007
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
1008
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
1009
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
1010
      id_to_script_map;
1011
  std::unordered_map<uint32_t, contextify::CompiledFnEntry*> id_to_function_map;
1012
1013
  inline uint32_t get_next_module_id();
1014
  inline uint32_t get_next_script_id();
1015
  inline uint32_t get_next_function_id();
1016
1017
  std::unordered_map<std::string, const loader::PackageConfig>
1018
      package_json_cache;
1019
1020
  inline double* heap_statistics_buffer() const;
1021
  inline void set_heap_statistics_buffer(double* pointer);
1022
1023
  inline double* heap_space_statistics_buffer() const;
1024
  inline void set_heap_space_statistics_buffer(double* pointer);
1025
1026
  inline char* http_parser_buffer() const;
1027
  inline void set_http_parser_buffer(char* buffer);
1028
  inline bool http_parser_buffer_in_use() const;
1029
  inline void set_http_parser_buffer_in_use(bool in_use);
1030
1031
  inline http2::Http2State* http2_state() const;
1032
  inline void set_http2_state(std::unique_ptr<http2::Http2State> state);
1033
1034
  inline bool debug_enabled(DebugCategory category) const;
1035
  inline void set_debug_enabled(DebugCategory category, bool enabled);
1036
  void set_debug_categories(const std::string& cats, bool enabled);
1037
1038
  inline AliasedFloat64Array* fs_stats_field_array();
1039
  inline AliasedBigUint64Array* fs_stats_field_bigint_array();
1040
1041
  inline std::vector<std::unique_ptr<fs::FileHandleReadWrap>>&
1042
      file_handle_read_wrap_freelist();
1043
1044
  inline performance::performance_state* performance_state();
1045
  inline std::unordered_map<std::string, uint64_t>* performance_marks();
1046
1047
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
1048
                              int errorno,
1049
                              const char* syscall = nullptr,
1050
                              const char* message = nullptr,
1051
                              const char* path = nullptr,
1052
                              const char* dest = nullptr);
1053
1054
  // If this flag is set, calls into JS (if they would be observable
1055
  // from userland) must be avoided.  This flag does not indicate whether
1056
  // calling into JS is allowed from a VM perspective at this point.
1057
  inline bool can_call_into_js() const;
1058
  inline void set_can_call_into_js(bool can_call_into_js);
1059
1060
  inline bool has_run_bootstrapping_code() const;
1061
  inline void set_has_run_bootstrapping_code(bool has_run_bootstrapping_code);
1062
1063
  inline bool has_serialized_options() const;
1064
  inline void set_has_serialized_options(bool has_serialized_options);
1065
1066
  static uint64_t AllocateThreadId();
1067
  static constexpr uint64_t kNoThreadId = -1;
1068
1069
  inline bool is_main_thread() const;
1070
  inline bool owns_process_state() const;
1071
  inline bool owns_inspector() const;
1072
  inline uint64_t thread_id() const;
1073
  inline worker::Worker* worker_context() const;
1074
  inline void set_worker_context(worker::Worker* context);
1075
  inline void add_sub_worker_context(worker::Worker* context);
1076
  inline void remove_sub_worker_context(worker::Worker* context);
1077
  void stop_sub_worker_contexts();
1078
  inline bool is_stopping() const;
1079
1080
  inline void ThrowError(const char* errmsg);
1081
  inline void ThrowTypeError(const char* errmsg);
1082
  inline void ThrowRangeError(const char* errmsg);
1083
  inline void ThrowErrnoException(int errorno,
1084
                                  const char* syscall = nullptr,
1085
                                  const char* message = nullptr,
1086
                                  const char* path = nullptr);
1087
  inline void ThrowUVException(int errorno,
1088
                               const char* syscall = nullptr,
1089
                               const char* message = nullptr,
1090
                               const char* path = nullptr,
1091
                               const char* dest = nullptr);
1092
1093
  inline v8::Local<v8::FunctionTemplate>
1094
      NewFunctionTemplate(v8::FunctionCallback callback,
1095
                          v8::Local<v8::Signature> signature =
1096
                              v8::Local<v8::Signature>(),
1097
                          v8::ConstructorBehavior behavior =
1098
                              v8::ConstructorBehavior::kAllow,
1099
                          v8::SideEffectType side_effect =
1100
                              v8::SideEffectType::kHasSideEffect);
1101
1102
  // Convenience methods for NewFunctionTemplate().
1103
  inline void SetMethod(v8::Local<v8::Object> that,
1104
                        const char* name,
1105
                        v8::FunctionCallback callback);
1106
1107
  inline void SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1108
                             const char* name,
1109
                             v8::FunctionCallback callback);
1110
1111
  // Safe variants denote the function has no side effects.
1112
  inline void SetMethodNoSideEffect(v8::Local<v8::Object> that,
1113
                                    const char* name,
1114
                                    v8::FunctionCallback callback);
1115
  inline void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that,
1116
                                         const char* name,
1117
                                         v8::FunctionCallback callback);
1118
1119
  void BeforeExit(void (*cb)(void* arg), void* arg);
1120
  void RunBeforeExitCallbacks();
1121
  void AtExit(void (*cb)(void* arg), void* arg);
1122
  void RunAtExitCallbacks();
1123
1124
  // Strings and private symbols are shared across shared contexts
1125
  // The getters simply proxy to the per-isolate primitive.
1126
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1127
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1128
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1129
#define V(TypeName, PropertyName)                                             \
1130
  inline v8::Local<TypeName> PropertyName() const;
1131
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1132
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1133
  PER_ISOLATE_STRING_PROPERTIES(VS)
1134
#undef V
1135
#undef VS
1136
#undef VY
1137
#undef VP
1138
1139
#define V(PropertyName, TypeName)                                             \
1140
  inline v8::Local<TypeName> PropertyName() const;                            \
1141
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
1142
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1143
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1144
#undef V
1145
1146
  inline v8::Local<v8::Context> context() const;
1147
1148
#if HAVE_INSPECTOR
1149
260319
  inline inspector::Agent* inspector_agent() const {
1150
260319
    return inspector_agent_.get();
1151
  }
1152
1153
  inline bool is_in_inspector_console_call() const;
1154
  inline void set_is_in_inspector_console_call(bool value);
1155
#endif
1156
1157
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
1158
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
1159
1160
73682
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
1161
99283
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
1162
1163
1
  inline bool EmitProcessEnvWarning() {
1164
1
    bool current_value = emit_env_nonstring_warning_;
1165
1
    emit_env_nonstring_warning_ = false;
1166
1
    return current_value;
1167
  }
1168
1169
1
  inline bool EmitErrNameWarning() {
1170
1
    bool current_value = emit_err_name_warning_;
1171
1
    emit_err_name_warning_ = false;
1172
1
    return current_value;
1173
  }
1174
1175
  typedef void (*native_immediate_callback)(Environment* env, void* data);
1176
  // cb will be called as cb(env, data) on the next event loop iteration.
1177
  // obj will be kept alive between now and after the callback has run.
1178
  inline void SetImmediate(native_immediate_callback cb,
1179
                           void* data,
1180
                           v8::Local<v8::Object> obj = v8::Local<v8::Object>());
1181
  inline void SetUnrefImmediate(native_immediate_callback cb,
1182
                                void* data,
1183
                                v8::Local<v8::Object> obj =
1184
                                    v8::Local<v8::Object>());
1185
  // This needs to be available for the JS-land setImmediate().
1186
  void ToggleImmediateRef(bool ref);
1187
1188
  inline void PushShouldNotAbortOnUncaughtScope();
1189
  inline void PopShouldNotAbortOnUncaughtScope();
1190
  inline bool inside_should_not_abort_on_uncaught_scope() const;
1191
1192
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
1193
1194
  v8::Local<v8::Value> GetNow();
1195
  void ScheduleTimer(int64_t duration);
1196
  void ToggleTimerRef(bool ref);
1197
1198
  inline void AddCleanupHook(void (*fn)(void*), void* arg);
1199
  inline void RemoveCleanupHook(void (*fn)(void*), void* arg);
1200
  void RunCleanup();
1201
1202
  static void BuildEmbedderGraph(v8::Isolate* isolate,
1203
                                 v8::EmbedderGraph* graph,
1204
                                 void* data);
1205
1206
  inline std::shared_ptr<EnvironmentOptions> options();
1207
  inline std::shared_ptr<HostPort> inspector_host_port();
1208
1209
19917
  inline AsyncRequest* thread_stopper() { return &thread_stopper_; }
1210
1211
#if HAVE_INSPECTOR
1212
  void set_coverage_connection(
1213
      std::unique_ptr<profiler::V8CoverageConnection> connection);
1214
  profiler::V8CoverageConnection* coverage_connection();
1215
1216
  inline void set_coverage_directory(const char* directory);
1217
  inline const std::string& coverage_directory() const;
1218
1219
  void set_cpu_profiler_connection(
1220
      std::unique_ptr<profiler::V8CpuProfilerConnection> connection);
1221
  profiler::V8CpuProfilerConnection* cpu_profiler_connection();
1222
1223
  inline void set_cpu_prof_name(const std::string& name);
1224
  inline const std::string& cpu_prof_name() const;
1225
1226
  inline void set_cpu_prof_interval(uint64_t interval);
1227
  inline uint64_t cpu_prof_interval() const;
1228
1229
  inline void set_cpu_prof_dir(const std::string& dir);
1230
  inline const std::string& cpu_prof_dir() const;
1231
1232
  void set_heap_profiler_connection(
1233
      std::unique_ptr<profiler::V8HeapProfilerConnection> connection);
1234
  profiler::V8HeapProfilerConnection* heap_profiler_connection();
1235
1236
  inline void set_heap_prof_name(const std::string& name);
1237
  inline const std::string& heap_prof_name() const;
1238
1239
  inline void set_heap_prof_dir(const std::string& dir);
1240
  inline const std::string& heap_prof_dir() const;
1241
1242
  inline void set_heap_prof_interval(uint64_t interval);
1243
  inline uint64_t heap_prof_interval() const;
1244
1245
#endif  // HAVE_INSPECTOR
1246
1247
 private:
1248
  inline void CreateImmediate(native_immediate_callback cb,
1249
                              void* data,
1250
                              v8::Local<v8::Object> obj,
1251
                              bool ref);
1252
1253
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1254
                         const char* errmsg);
1255
1256
  std::list<binding::DLib> loaded_addons_;
1257
  v8::Isolate* const isolate_;
1258
  IsolateData* const isolate_data_;
1259
  uv_timer_t timer_handle_;
1260
  uv_check_t immediate_check_handle_;
1261
  uv_idle_t immediate_idle_handle_;
1262
  uv_prepare_t idle_prepare_handle_;
1263
  uv_check_t idle_check_handle_;
1264
  bool profiler_idle_notifier_started_ = false;
1265
1266
  AsyncHooks async_hooks_;
1267
  ImmediateInfo immediate_info_;
1268
  TickInfo tick_info_;
1269
  const uint64_t timer_base_;
1270
  std::shared_ptr<KVStore> env_vars_;
1271
  bool printed_error_ = false;
1272
  bool emit_env_nonstring_warning_ = true;
1273
  bool emit_err_name_warning_ = true;
1274
  size_t async_callback_scope_depth_ = 0;
1275
  std::vector<double> destroy_async_id_list_;
1276
1277
#if HAVE_INSPECTOR
1278
  std::unique_ptr<profiler::V8CoverageConnection> coverage_connection_;
1279
  std::unique_ptr<profiler::V8CpuProfilerConnection> cpu_profiler_connection_;
1280
  std::string coverage_directory_;
1281
  std::string cpu_prof_dir_;
1282
  std::string cpu_prof_name_;
1283
  uint64_t cpu_prof_interval_;
1284
  std::unique_ptr<profiler::V8HeapProfilerConnection> heap_profiler_connection_;
1285
  std::string heap_prof_dir_;
1286
  std::string heap_prof_name_;
1287
  uint64_t heap_prof_interval_;
1288
#endif  // HAVE_INSPECTOR
1289
1290
  std::shared_ptr<EnvironmentOptions> options_;
1291
  // options_ contains debug options parsed from CLI arguments,
1292
  // while inspector_host_port_ stores the actual inspector host
1293
  // and port being used. For example the port is -1 by default
1294
  // and can be specified as 0 (meaning any port allocated when the
1295
  // server starts listening), but when the inspector server starts
1296
  // the inspector_host_port_->port() will be the actual port being
1297
  // used.
1298
  std::shared_ptr<HostPort> inspector_host_port_;
1299
  std::vector<std::string> exec_argv_;
1300
  std::vector<std::string> argv_;
1301
  std::string exec_path_;
1302
1303
  uint32_t module_id_counter_ = 0;
1304
  uint32_t script_id_counter_ = 0;
1305
  uint32_t function_id_counter_ = 0;
1306
1307
  AliasedUint32Array should_abort_on_uncaught_toggle_;
1308
  int should_not_abort_scope_counter_ = 0;
1309
1310
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1311
1312
  AliasedInt32Array stream_base_state_;
1313
1314
  std::unique_ptr<performance::performance_state> performance_state_;
1315
  std::unordered_map<std::string, uint64_t> performance_marks_;
1316
1317
  bool has_run_bootstrapping_code_ = false;
1318
  bool has_serialized_options_ = false;
1319
1320
  bool can_call_into_js_ = true;
1321
  Flags flags_;
1322
  uint64_t thread_id_;
1323
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1324
1325
  static void* const kNodeContextTagPtr;
1326
  static int const kNodeContextTag;
1327
1328
#if HAVE_INSPECTOR
1329
  std::unique_ptr<inspector::Agent> inspector_agent_;
1330
  bool is_in_inspector_console_call_ = false;
1331
#endif
1332
1333
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1334
  // the start of the class because it is used by
1335
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1336
  // symbols for Environment, which assumes that the position of members in
1337
  // memory are predictable. For more information please refer to
1338
  // `doc/guides/node-postmortem-support.md`
1339
  friend int GenDebugSymbols();
1340
  HandleWrapQueue handle_wrap_queue_;
1341
  ReqWrapQueue req_wrap_queue_;
1342
  std::list<HandleCleanup> handle_cleanup_queue_;
1343
  int handle_cleanup_waiting_ = 0;
1344
  int request_waiting_ = 0;
1345
1346
  double* heap_statistics_buffer_ = nullptr;
1347
  double* heap_space_statistics_buffer_ = nullptr;
1348
1349
  char* http_parser_buffer_ = nullptr;
1350
  bool http_parser_buffer_in_use_ = false;
1351
  std::unique_ptr<http2::Http2State> http2_state_;
1352
1353
  bool debug_enabled_[static_cast<int>(DebugCategory::CATEGORY_COUNT)] = {0};
1354
1355
  AliasedFloat64Array fs_stats_field_array_;
1356
  AliasedBigUint64Array fs_stats_field_bigint_array_;
1357
1358
  std::vector<std::unique_ptr<fs::FileHandleReadWrap>>
1359
      file_handle_read_wrap_freelist_;
1360
1361
  worker::Worker* worker_context_ = nullptr;
1362
1363
  static void RunTimers(uv_timer_t* handle);
1364
1365
  struct ExitCallback {
1366
    void (*cb_)(void* arg);
1367
    void* arg_;
1368
  };
1369
  std::list<ExitCallback> before_exit_functions_;
1370
1371
  std::list<ExitCallback> at_exit_functions_;
1372
1373
352262
  struct NativeImmediateCallback {
1374
    native_immediate_callback cb_;
1375
    void* data_;
1376
    v8::Global<v8::Object> keep_alive_;
1377
    bool refed_;
1378
  };
1379
  std::vector<NativeImmediateCallback> native_immediate_callbacks_;
1380
  void RunAndClearNativeImmediates();
1381
  static void CheckImmediate(uv_check_t* handle);
1382
1383
  // Use an unordered_set, so that we have efficient insertion and removal.
1384
  std::unordered_set<CleanupHookCallback,
1385
                     CleanupHookCallback::Hash,
1386
                     CleanupHookCallback::Equal> cleanup_hooks_;
1387
  uint64_t cleanup_hook_counter_ = 0;
1388
  bool started_cleanup_ = false;
1389
1390
  // A custom async abstraction (a pair of async handle and a state variable)
1391
  // Used by embedders to shutdown running Node instance.
1392
  AsyncRequest thread_stopper_;
1393
1394
  template <typename T>
1395
  void ForEachBaseObject(T&& iterator);
1396
1397
#define V(PropertyName, TypeName) v8::Global<TypeName> PropertyName ## _;
1398
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1399
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1400
#undef V
1401
1402
  v8::Global<v8::Context> context_;
1403
};
1404
1405
}  // namespace node
1406
1407
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1408
1409
#endif  // SRC_ENV_H_