GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.h Lines: 41 41 100.0 %
Date: 2021-11-16 04:13:57 Branches: 1 2 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 "callback_queue.h"
33
#include "debug_utils.h"
34
#include "handle_wrap.h"
35
#include "node.h"
36
#include "node_binding.h"
37
#include "node_main_instance.h"
38
#include "node_options.h"
39
#include "node_perf_common.h"
40
#include "node_snapshotable.h"
41
#include "req_wrap.h"
42
#include "util.h"
43
#include "uv.h"
44
#include "v8.h"
45
46
#include <array>
47
#include <atomic>
48
#include <cstdint>
49
#include <functional>
50
#include <iostream>
51
#include <list>
52
#include <unordered_map>
53
#include <unordered_set>
54
#include <vector>
55
56
namespace node {
57
58
namespace contextify {
59
class ContextifyScript;
60
class CompiledFnEntry;
61
}
62
63
namespace performance {
64
class PerformanceState;
65
}
66
67
namespace tracing {
68
class AgentWriterHandle;
69
}
70
71
#if HAVE_INSPECTOR
72
namespace profiler {
73
class V8CoverageConnection;
74
class V8CpuProfilerConnection;
75
class V8HeapProfilerConnection;
76
}  // namespace profiler
77
78
namespace inspector {
79
class ParentInspectorHandle;
80
}
81
#endif  // HAVE_INSPECTOR
82
83
namespace worker {
84
class Worker;
85
}
86
87
namespace loader {
88
class ModuleWrap;
89
90
struct PackageConfig {
91
  enum class Exists { Yes, No };
92
  enum class IsValid { Yes, No };
93
  enum class HasMain { Yes, No };
94
  enum class HasName { Yes, No };
95
  enum PackageType : uint32_t { None = 0, CommonJS, Module };
96
97
  const Exists exists;
98
  const IsValid is_valid;
99
  const HasMain has_main;
100
  const std::string main;
101
  const HasName has_name;
102
  const std::string name;
103
  const PackageType type;
104
105
  v8::Global<v8::Value> exports;
106
};
107
}  // namespace loader
108
109
enum class FsStatsOffset {
110
  kDev = 0,
111
  kMode,
112
  kNlink,
113
  kUid,
114
  kGid,
115
  kRdev,
116
  kBlkSize,
117
  kIno,
118
  kSize,
119
  kBlocks,
120
  kATimeSec,
121
  kATimeNsec,
122
  kMTimeSec,
123
  kMTimeNsec,
124
  kCTimeSec,
125
  kCTimeNsec,
126
  kBirthTimeSec,
127
  kBirthTimeNsec,
128
  kFsStatsFieldsNumber
129
};
130
131
// Stat fields buffers contain twice the number of entries in an uv_stat_t
132
// because `fs.StatWatcher` needs room to store 2 `fs.Stats` instances.
133
constexpr size_t kFsStatsBufferLength =
134
    static_cast<size_t>(FsStatsOffset::kFsStatsFieldsNumber) * 2;
135
136
// PER_ISOLATE_* macros: We have a lot of per-isolate properties
137
// and adding and maintaining their getters and setters by hand would be
138
// difficult so let's make the preprocessor generate them for us.
139
//
140
// In each macro, `V` is expected to be the name of a macro or function which
141
// accepts the number of arguments provided in each tuple in the macro body,
142
// typically two. The named function will be invoked against each tuple.
143
//
144
// Make sure that any macro V defined for use with the PER_ISOLATE_* macros is
145
// undefined again after use.
146
147
// Private symbols are per-isolate primitives but Environment proxies them
148
// for the sake of convenience.  Strings should be ASCII-only and have a
149
// "node:" prefix to avoid name clashes with third-party code.
150
#define PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)                              \
151
  V(alpn_buffer_private_symbol, "node:alpnBuffer")                            \
152
  V(arrow_message_private_symbol, "node:arrowMessage")                        \
153
  V(contextify_context_private_symbol, "node:contextify:context")             \
154
  V(contextify_global_private_symbol, "node:contextify:global")               \
155
  V(decorated_private_symbol, "node:decorated")                               \
156
  V(napi_type_tag, "node:napi:type_tag")                                      \
157
  V(napi_wrapper, "node:napi:wrapper")                                        \
158
  V(untransferable_object_private_symbol, "node:untransferableObject")        \
159
160
// Symbols are per-isolate primitives but Environment proxies them
161
// for the sake of convenience.
162
#define PER_ISOLATE_SYMBOL_PROPERTIES(V)                                       \
163
  V(async_id_symbol, "async_id_symbol")                                        \
164
  V(handle_onclose_symbol, "handle_onclose")                                   \
165
  V(no_message_symbol, "no_message_symbol")                                    \
166
  V(messaging_deserialize_symbol, "messaging_deserialize_symbol")              \
167
  V(messaging_transfer_symbol, "messaging_transfer_symbol")                    \
168
  V(messaging_clone_symbol, "messaging_clone_symbol")                          \
169
  V(messaging_transfer_list_symbol, "messaging_transfer_list_symbol")          \
170
  V(oninit_symbol, "oninit")                                                   \
171
  V(owner_symbol, "owner_symbol")                                              \
172
  V(onpskexchange_symbol, "onpskexchange")                                     \
173
  V(trigger_async_id_symbol, "trigger_async_id_symbol")                        \
174
175
// Strings are per-isolate primitives but Environment proxies them
176
// for the sake of convenience.  Strings should be ASCII-only.
177
#define PER_ISOLATE_STRING_PROPERTIES(V)                                       \
178
  V(ack_string, "ack")                                                         \
179
  V(address_string, "address")                                                 \
180
  V(aliases_string, "aliases")                                                 \
181
  V(args_string, "args")                                                       \
182
  V(asn1curve_string, "asn1Curve")                                             \
183
  V(async_ids_stack_string, "async_ids_stack")                                 \
184
  V(bits_string, "bits")                                                       \
185
  V(block_list_string, "blockList")                                            \
186
  V(buffer_string, "buffer")                                                   \
187
  V(bytes_parsed_string, "bytesParsed")                                        \
188
  V(bytes_read_string, "bytesRead")                                            \
189
  V(bytes_written_string, "bytesWritten")                                      \
190
  V(cached_data_produced_string, "cachedDataProduced")                         \
191
  V(cached_data_rejected_string, "cachedDataRejected")                         \
192
  V(cached_data_string, "cachedData")                                          \
193
  V(cache_key_string, "cacheKey")                                              \
194
  V(change_string, "change")                                                   \
195
  V(channel_string, "channel")                                                 \
196
  V(chunks_sent_since_last_write_string, "chunksSentSinceLastWrite")           \
197
  V(clone_unsupported_type_str, "Cannot transfer object of unsupported type.") \
198
  V(code_string, "code")                                                       \
199
  V(commonjs_string, "commonjs")                                               \
200
  V(config_string, "config")                                                   \
201
  V(constants_string, "constants")                                             \
202
  V(crypto_dh_string, "dh")                                                    \
203
  V(crypto_dsa_string, "dsa")                                                  \
204
  V(crypto_ec_string, "ec")                                                    \
205
  V(crypto_ed25519_string, "ed25519")                                          \
206
  V(crypto_ed448_string, "ed448")                                              \
207
  V(crypto_x25519_string, "x25519")                                            \
208
  V(crypto_x448_string, "x448")                                                \
209
  V(crypto_rsa_string, "rsa")                                                  \
210
  V(crypto_rsa_pss_string, "rsa-pss")                                          \
211
  V(cwd_string, "cwd")                                                         \
212
  V(data_string, "data")                                                       \
213
  V(default_is_true_string, "defaultIsTrue")                                   \
214
  V(deserialize_info_string, "deserializeInfo")                                \
215
  V(dest_string, "dest")                                                       \
216
  V(destroyed_string, "destroyed")                                             \
217
  V(detached_string, "detached")                                               \
218
  V(dh_string, "DH")                                                           \
219
  V(divisor_length_string, "divisorLength")                                    \
220
  V(dns_a_string, "A")                                                         \
221
  V(dns_aaaa_string, "AAAA")                                                   \
222
  V(dns_caa_string, "CAA")                                                     \
223
  V(dns_critical_string, "critical")                                           \
224
  V(dns_cname_string, "CNAME")                                                 \
225
  V(dns_mx_string, "MX")                                                       \
226
  V(dns_naptr_string, "NAPTR")                                                 \
227
  V(dns_ns_string, "NS")                                                       \
228
  V(dns_ptr_string, "PTR")                                                     \
229
  V(dns_soa_string, "SOA")                                                     \
230
  V(dns_srv_string, "SRV")                                                     \
231
  V(dns_txt_string, "TXT")                                                     \
232
  V(done_string, "done")                                                       \
233
  V(duration_string, "duration")                                               \
234
  V(ecdh_string, "ECDH")                                                       \
235
  V(emit_string, "emit")                                                       \
236
  V(emit_warning_string, "emitWarning")                                        \
237
  V(empty_object_string, "{}")                                                 \
238
  V(encoding_string, "encoding")                                               \
239
  V(entries_string, "entries")                                                 \
240
  V(entry_type_string, "entryType")                                            \
241
  V(env_pairs_string, "envPairs")                                              \
242
  V(env_var_settings_string, "envVarSettings")                                 \
243
  V(errno_string, "errno")                                                     \
244
  V(error_string, "error")                                                     \
245
  V(exchange_string, "exchange")                                               \
246
  V(exit_code_string, "exitCode")                                              \
247
  V(expire_string, "expire")                                                   \
248
  V(exponent_string, "exponent")                                               \
249
  V(exports_string, "exports")                                                 \
250
  V(ext_key_usage_string, "ext_key_usage")                                     \
251
  V(external_stream_string, "_externalStream")                                 \
252
  V(family_string, "family")                                                   \
253
  V(fatal_exception_string, "_fatalException")                                 \
254
  V(fd_string, "fd")                                                           \
255
  V(fields_string, "fields")                                                   \
256
  V(file_string, "file")                                                       \
257
  V(filename_string, "filename")                                               \
258
  V(fingerprint256_string, "fingerprint256")                                   \
259
  V(fingerprint512_string, "fingerprint512")                                   \
260
  V(fingerprint_string, "fingerprint")                                         \
261
  V(flags_string, "flags")                                                     \
262
  V(flowlabel_string, "flowlabel")                                             \
263
  V(fragment_string, "fragment")                                               \
264
  V(frames_received_string, "framesReceived")                                  \
265
  V(frames_sent_string, "framesSent")                                          \
266
  V(function_string, "function")                                               \
267
  V(get_data_clone_error_string, "_getDataCloneError")                         \
268
  V(get_shared_array_buffer_id_string, "_getSharedArrayBufferId")              \
269
  V(gid_string, "gid")                                                         \
270
  V(h2_string, "h2")                                                           \
271
  V(handle_string, "handle")                                                   \
272
  V(hash_algorithm_string, "hashAlgorithm")                                    \
273
  V(help_text_string, "helpText")                                              \
274
  V(homedir_string, "homedir")                                                 \
275
  V(host_string, "host")                                                       \
276
  V(hostmaster_string, "hostmaster")                                           \
277
  V(http_1_1_string, "http/1.1")                                               \
278
  V(id_string, "id")                                                           \
279
  V(identity_string, "identity")                                               \
280
  V(ignore_string, "ignore")                                                   \
281
  V(infoaccess_string, "infoAccess")                                           \
282
  V(inherit_string, "inherit")                                                 \
283
  V(input_string, "input")                                                     \
284
  V(internal_binding_string, "internalBinding")                                \
285
  V(internal_string, "internal")                                               \
286
  V(ipv4_string, "IPv4")                                                       \
287
  V(ipv6_string, "IPv6")                                                       \
288
  V(isclosing_string, "isClosing")                                             \
289
  V(issuer_string, "issuer")                                                   \
290
  V(issuercert_string, "issuerCertificate")                                    \
291
  V(jwk_crv_string, "crv")                                                     \
292
  V(jwk_d_string, "d")                                                         \
293
  V(jwk_dp_string, "dp")                                                       \
294
  V(jwk_dq_string, "dq")                                                       \
295
  V(jwk_dsa_string, "DSA")                                                     \
296
  V(jwk_e_string, "e")                                                         \
297
  V(jwk_ec_string, "EC")                                                       \
298
  V(jwk_g_string, "g")                                                         \
299
  V(jwk_k_string, "k")                                                         \
300
  V(jwk_p_string, "p")                                                         \
301
  V(jwk_q_string, "q")                                                         \
302
  V(jwk_qi_string, "qi")                                                       \
303
  V(jwk_kty_string, "kty")                                                     \
304
  V(jwk_n_string, "n")                                                         \
305
  V(jwk_oct_string, "oct")                                                     \
306
  V(jwk_okp_string, "OKP")                                                     \
307
  V(jwk_rsa_string, "RSA")                                                     \
308
  V(jwk_x_string, "x")                                                         \
309
  V(jwk_y_string, "y")                                                         \
310
  V(kill_signal_string, "killSignal")                                          \
311
  V(kind_string, "kind")                                                       \
312
  V(length_string, "length")                                                   \
313
  V(library_string, "library")                                                 \
314
  V(mac_string, "mac")                                                         \
315
  V(max_buffer_string, "maxBuffer")                                            \
316
  V(max_concurrent_streams_string, "maxConcurrentStreams")                     \
317
  V(message_port_constructor_string, "MessagePort")                            \
318
  V(message_port_string, "messagePort")                                        \
319
  V(message_string, "message")                                                 \
320
  V(messageerror_string, "messageerror")                                       \
321
  V(mgf1_hash_algorithm_string, "mgf1HashAlgorithm")                           \
322
  V(minttl_string, "minttl")                                                   \
323
  V(module_string, "module")                                                   \
324
  V(modulus_string, "modulus")                                                 \
325
  V(modulus_length_string, "modulusLength")                                    \
326
  V(name_string, "name")                                                       \
327
  V(named_curve_string, "namedCurve")                                          \
328
  V(netmask_string, "netmask")                                                 \
329
  V(next_string, "next")                                                       \
330
  V(nistcurve_string, "nistCurve")                                             \
331
  V(node_string, "node")                                                       \
332
  V(nsname_string, "nsname")                                                   \
333
  V(ocsp_request_string, "OCSPRequest")                                        \
334
  V(oncertcb_string, "oncertcb")                                               \
335
  V(onchange_string, "onchange")                                               \
336
  V(onclienthello_string, "onclienthello")                                     \
337
  V(oncomplete_string, "oncomplete")                                           \
338
  V(onconnection_string, "onconnection")                                       \
339
  V(ondone_string, "ondone")                                                   \
340
  V(onerror_string, "onerror")                                                 \
341
  V(onexit_string, "onexit")                                                   \
342
  V(onhandshakedone_string, "onhandshakedone")                                 \
343
  V(onhandshakestart_string, "onhandshakestart")                               \
344
  V(onkeylog_string, "onkeylog")                                               \
345
  V(onmessage_string, "onmessage")                                             \
346
  V(onnewsession_string, "onnewsession")                                       \
347
  V(onocspresponse_string, "onocspresponse")                                   \
348
  V(onreadstart_string, "onreadstart")                                         \
349
  V(onreadstop_string, "onreadstop")                                           \
350
  V(onshutdown_string, "onshutdown")                                           \
351
  V(onsignal_string, "onsignal")                                               \
352
  V(onunpipe_string, "onunpipe")                                               \
353
  V(onwrite_string, "onwrite")                                                 \
354
  V(openssl_error_stack, "opensslErrorStack")                                  \
355
  V(options_string, "options")                                                 \
356
  V(order_string, "order")                                                     \
357
  V(output_string, "output")                                                   \
358
  V(overlapped_string, "overlapped")                                           \
359
  V(parse_error_string, "Parse Error")                                         \
360
  V(password_string, "password")                                               \
361
  V(path_string, "path")                                                       \
362
  V(pending_handle_string, "pendingHandle")                                    \
363
  V(pid_string, "pid")                                                         \
364
  V(ping_rtt_string, "pingRTT")                                                \
365
  V(pipe_source_string, "pipeSource")                                          \
366
  V(pipe_string, "pipe")                                                       \
367
  V(pipe_target_string, "pipeTarget")                                          \
368
  V(port1_string, "port1")                                                     \
369
  V(port2_string, "port2")                                                     \
370
  V(port_string, "port")                                                       \
371
  V(preference_string, "preference")                                           \
372
  V(primordials_string, "primordials")                                         \
373
  V(priority_string, "priority")                                               \
374
  V(process_string, "process")                                                 \
375
  V(promise_string, "promise")                                                 \
376
  V(psk_string, "psk")                                                         \
377
  V(pubkey_string, "pubkey")                                                   \
378
  V(public_exponent_string, "publicExponent")                                  \
379
  V(query_string, "query")                                                     \
380
  V(rate_string, "rate")                                                       \
381
  V(raw_string, "raw")                                                         \
382
  V(read_host_object_string, "_readHostObject")                                \
383
  V(readable_string, "readable")                                               \
384
  V(reason_string, "reason")                                                   \
385
  V(refresh_string, "refresh")                                                 \
386
  V(regexp_string, "regexp")                                                   \
387
  V(rename_string, "rename")                                                   \
388
  V(replacement_string, "replacement")                                         \
389
  V(require_string, "require")                                                 \
390
  V(retry_string, "retry")                                                     \
391
  V(salt_length_string, "saltLength")                                          \
392
  V(scheme_string, "scheme")                                                   \
393
  V(scopeid_string, "scopeid")                                                 \
394
  V(serial_number_string, "serialNumber")                                      \
395
  V(serial_string, "serial")                                                   \
396
  V(servername_string, "servername")                                           \
397
  V(service_string, "service")                                                 \
398
  V(session_id_string, "sessionId")                                            \
399
  V(shell_string, "shell")                                                     \
400
  V(signal_string, "signal")                                                   \
401
  V(sink_string, "sink")                                                       \
402
  V(size_string, "size")                                                       \
403
  V(sni_context_err_string, "Invalid SNI context")                             \
404
  V(sni_context_string, "sni_context")                                         \
405
  V(source_string, "source")                                                   \
406
  V(stack_string, "stack")                                                     \
407
  V(standard_name_string, "standardName")                                      \
408
  V(start_time_string, "startTime")                                            \
409
  V(state_string, "state")                                                     \
410
  V(stats_string, "stats")                                                     \
411
  V(status_string, "status")                                                   \
412
  V(stdio_string, "stdio")                                                     \
413
  V(stream_average_duration_string, "streamAverageDuration")                   \
414
  V(stream_count_string, "streamCount")                                        \
415
  V(subject_string, "subject")                                                 \
416
  V(subjectaltname_string, "subjectaltname")                                   \
417
  V(syscall_string, "syscall")                                                 \
418
  V(target_string, "target")                                                   \
419
  V(thread_id_string, "threadId")                                              \
420
  V(ticketkeycallback_string, "onticketkeycallback")                           \
421
  V(timeout_string, "timeout")                                                 \
422
  V(time_to_first_byte_string, "timeToFirstByte")                              \
423
  V(time_to_first_byte_sent_string, "timeToFirstByteSent")                     \
424
  V(time_to_first_header_string, "timeToFirstHeader")                          \
425
  V(tls_ticket_string, "tlsTicket")                                            \
426
  V(transfer_string, "transfer")                                               \
427
  V(ttl_string, "ttl")                                                         \
428
  V(type_string, "type")                                                       \
429
  V(uid_string, "uid")                                                         \
430
  V(unknown_string, "<unknown>")                                               \
431
  V(url_special_ftp_string, "ftp:")                                            \
432
  V(url_special_file_string, "file:")                                          \
433
  V(url_special_http_string, "http:")                                          \
434
  V(url_special_https_string, "https:")                                        \
435
  V(url_special_ws_string, "ws:")                                              \
436
  V(url_special_wss_string, "wss:")                                            \
437
  V(url_string, "url")                                                         \
438
  V(username_string, "username")                                               \
439
  V(valid_from_string, "valid_from")                                           \
440
  V(valid_to_string, "valid_to")                                               \
441
  V(value_string, "value")                                                     \
442
  V(verify_error_string, "verifyError")                                        \
443
  V(version_string, "version")                                                 \
444
  V(weight_string, "weight")                                                   \
445
  V(windows_hide_string, "windowsHide")                                        \
446
  V(windows_verbatim_arguments_string, "windowsVerbatimArguments")             \
447
  V(wrap_string, "wrap")                                                       \
448
  V(writable_string, "writable")                                               \
449
  V(write_host_object_string, "_writeHostObject")                              \
450
  V(write_queue_size_string, "writeQueueSize")                                 \
451
  V(x_forwarded_string, "x-forwarded-for")                                     \
452
  V(zero_return_string, "ZERO_RETURN")
453
454
#define ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)                             \
455
  V(async_wrap_ctor_template, v8::FunctionTemplate)                            \
456
  V(async_wrap_object_ctor_template, v8::FunctionTemplate)                     \
457
  V(base_object_ctor_template, v8::FunctionTemplate)                           \
458
  V(binding_data_ctor_template, v8::FunctionTemplate)                          \
459
  V(blob_constructor_template, v8::FunctionTemplate)                           \
460
  V(blocklist_constructor_template, v8::FunctionTemplate)                      \
461
  V(compiled_fn_entry_template, v8::ObjectTemplate)                            \
462
  V(dir_instance_template, v8::ObjectTemplate)                                 \
463
  V(fd_constructor_template, v8::ObjectTemplate)                               \
464
  V(fdclose_constructor_template, v8::ObjectTemplate)                          \
465
  V(filehandlereadwrap_template, v8::ObjectTemplate)                           \
466
  V(fsreqpromise_constructor_template, v8::ObjectTemplate)                     \
467
  V(handle_wrap_ctor_template, v8::FunctionTemplate)                           \
468
  V(histogram_ctor_template, v8::FunctionTemplate)                             \
469
  V(http2settings_constructor_template, v8::ObjectTemplate)                    \
470
  V(http2stream_constructor_template, v8::ObjectTemplate)                      \
471
  V(http2ping_constructor_template, v8::ObjectTemplate)                        \
472
  V(i18n_converter_template, v8::ObjectTemplate)                               \
473
  V(intervalhistogram_constructor_template, v8::FunctionTemplate)              \
474
  V(libuv_stream_wrap_ctor_template, v8::FunctionTemplate)                     \
475
  V(message_port_constructor_template, v8::FunctionTemplate)                   \
476
  V(microtask_queue_ctor_template, v8::FunctionTemplate)                       \
477
  V(pipe_constructor_template, v8::FunctionTemplate)                           \
478
  V(promise_wrap_template, v8::ObjectTemplate)                                 \
479
  V(sab_lifetimepartner_constructor_template, v8::FunctionTemplate)            \
480
  V(script_context_constructor_template, v8::FunctionTemplate)                 \
481
  V(secure_context_constructor_template, v8::FunctionTemplate)                 \
482
  V(shutdown_wrap_template, v8::ObjectTemplate)                                \
483
  V(socketaddress_constructor_template, v8::FunctionTemplate)                  \
484
  V(streambaseoutputstream_constructor_template, v8::ObjectTemplate)           \
485
  V(qlogoutputstream_constructor_template, v8::ObjectTemplate)                 \
486
  V(tcp_constructor_template, v8::FunctionTemplate)                            \
487
  V(tty_constructor_template, v8::FunctionTemplate)                            \
488
  V(write_wrap_template, v8::ObjectTemplate)                                   \
489
  V(worker_heap_snapshot_taker_template, v8::ObjectTemplate)                   \
490
  V(x509_constructor_template, v8::FunctionTemplate)
491
492
#define ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)                                \
493
  V(async_hooks_after_function, v8::Function)                                  \
494
  V(async_hooks_before_function, v8::Function)                                 \
495
  V(async_hooks_callback_trampoline, v8::Function)                             \
496
  V(async_hooks_binding, v8::Object)                                           \
497
  V(async_hooks_destroy_function, v8::Function)                                \
498
  V(async_hooks_init_function, v8::Function)                                   \
499
  V(async_hooks_promise_resolve_function, v8::Function)                        \
500
  V(buffer_prototype_object, v8::Object)                                       \
501
  V(crypto_key_object_constructor, v8::Function)                               \
502
  V(crypto_key_object_handle_constructor, v8::Function)                        \
503
  V(crypto_key_object_private_constructor, v8::Function)                       \
504
  V(crypto_key_object_public_constructor, v8::Function)                        \
505
  V(crypto_key_object_secret_constructor, v8::Function)                        \
506
  V(domexception_function, v8::Function)                                       \
507
  V(enhance_fatal_stack_after_inspector, v8::Function)                         \
508
  V(enhance_fatal_stack_before_inspector, v8::Function)                        \
509
  V(fs_use_promises_symbol, v8::Symbol)                                        \
510
  V(host_import_module_dynamically_callback, v8::Function)                     \
511
  V(host_initialize_import_meta_object_callback, v8::Function)                 \
512
  V(http2session_on_altsvc_function, v8::Function)                             \
513
  V(http2session_on_error_function, v8::Function)                              \
514
  V(http2session_on_frame_error_function, v8::Function)                        \
515
  V(http2session_on_goaway_data_function, v8::Function)                        \
516
  V(http2session_on_headers_function, v8::Function)                            \
517
  V(http2session_on_origin_function, v8::Function)                             \
518
  V(http2session_on_ping_function, v8::Function)                               \
519
  V(http2session_on_priority_function, v8::Function)                           \
520
  V(http2session_on_settings_function, v8::Function)                           \
521
  V(http2session_on_stream_close_function, v8::Function)                       \
522
  V(http2session_on_stream_trailers_function, v8::Function)                    \
523
  V(internal_binding_loader, v8::Function)                                     \
524
  V(immediate_callback_function, v8::Function)                                 \
525
  V(inspector_console_extension_installer, v8::Function)                       \
526
  V(inspector_disable_async_hooks, v8::Function)                               \
527
  V(inspector_enable_async_hooks, v8::Function)                                \
528
  V(messaging_deserialize_create_object, v8::Function)                         \
529
  V(message_port, v8::Object)                                                  \
530
  V(native_module_require, v8::Function)                                       \
531
  V(performance_entry_callback, v8::Function)                                  \
532
  V(performance_entry_template, v8::Function)                                  \
533
  V(prepare_stack_trace_callback, v8::Function)                                \
534
  V(process_object, v8::Object)                                                \
535
  V(primordials, v8::Object)                                                   \
536
  V(primordials_safe_map_prototype_object, v8::Object)                         \
537
  V(primordials_safe_set_prototype_object, v8::Object)                         \
538
  V(primordials_safe_weak_map_prototype_object, v8::Object)                    \
539
  V(primordials_safe_weak_set_prototype_object, v8::Object)                    \
540
  V(promise_hook_handler, v8::Function)                                        \
541
  V(promise_reject_callback, v8::Function)                                     \
542
  V(script_data_constructor_function, v8::Function)                            \
543
  V(source_map_cache_getter, v8::Function)                                     \
544
  V(tick_callback_function, v8::Function)                                      \
545
  V(timers_callback_function, v8::Function)                                    \
546
  V(tls_wrap_constructor_function, v8::Function)                               \
547
  V(trace_category_state_function, v8::Function)                               \
548
  V(udp_constructor_function, v8::Function)                                    \
549
  V(url_constructor_function, v8::Function)
550
551
class Environment;
552
struct AllocatedBuffer;
553
554
typedef size_t SnapshotIndex;
555
class IsolateData : public MemoryRetainer {
556
 public:
557
  IsolateData(v8::Isolate* isolate,
558
              uv_loop_t* event_loop,
559
              MultiIsolatePlatform* platform = nullptr,
560
              ArrayBufferAllocator* node_allocator = nullptr,
561
              const std::vector<size_t>* indexes = nullptr);
562
22
  SET_MEMORY_INFO_NAME(IsolateData)
563
22
  SET_SELF_SIZE(IsolateData)
564
  void MemoryInfo(MemoryTracker* tracker) const override;
565
  std::vector<size_t> Serialize(v8::SnapshotCreator* creator);
566
567
  inline uv_loop_t* event_loop() const;
568
  inline MultiIsolatePlatform* platform() const;
569
  inline std::shared_ptr<PerIsolateOptions> options();
570
  inline void set_options(std::shared_ptr<PerIsolateOptions> options);
571
572
  inline NodeArrayBufferAllocator* node_allocator() const;
573
574
  inline worker::Worker* worker_context() const;
575
  inline void set_worker_context(worker::Worker* context);
576
577
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
578
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
579
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
580
#define V(TypeName, PropertyName)                                             \
581
  inline v8::Local<TypeName> PropertyName() const;
582
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
583
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
584
  PER_ISOLATE_STRING_PROPERTIES(VS)
585
#undef V
586
#undef VY
587
#undef VS
588
#undef VP
589
  inline v8::Local<v8::String> async_wrap_provider(int index) const;
590
591
  size_t max_young_gen_size = 1;
592
  std::unordered_map<const char*, v8::Eternal<v8::String>> static_str_map;
593
594
  inline v8::Isolate* isolate() const;
595
  IsolateData(const IsolateData&) = delete;
596
  IsolateData& operator=(const IsolateData&) = delete;
597
  IsolateData(IsolateData&&) = delete;
598
  IsolateData& operator=(IsolateData&&) = delete;
599
600
 private:
601
  void DeserializeProperties(const std::vector<size_t>* indexes);
602
  void CreateProperties();
603
604
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
605
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
606
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
607
#define V(TypeName, PropertyName)                                             \
608
  v8::Eternal<TypeName> PropertyName ## _;
609
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
610
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
611
  PER_ISOLATE_STRING_PROPERTIES(VS)
612
#undef V
613
#undef VY
614
#undef VS
615
#undef VP
616
  // Keep a list of all Persistent strings used for AsyncWrap Provider types.
617
  std::array<v8::Eternal<v8::String>, AsyncWrap::PROVIDERS_LENGTH>
618
      async_wrap_providers_;
619
620
  v8::Isolate* const isolate_;
621
  uv_loop_t* const event_loop_;
622
  NodeArrayBufferAllocator* const node_allocator_;
623
  MultiIsolatePlatform* platform_;
624
  std::shared_ptr<PerIsolateOptions> options_;
625
  worker::Worker* worker_context_ = nullptr;
626
};
627
628
struct ContextInfo {
629
11586
  explicit ContextInfo(const std::string& name) : name(name) {}
630
  const std::string name;
631
  std::string origin;
632
  bool is_default = false;
633
};
634
635
class EnabledDebugList;
636
637
class KVStore {
638
 public:
639
5749
  KVStore() = default;
640
10346
  virtual ~KVStore() = default;
641
  KVStore(const KVStore&) = delete;
642
  KVStore& operator=(const KVStore&) = delete;
643
  KVStore(KVStore&&) = delete;
644
  KVStore& operator=(KVStore&&) = delete;
645
646
  virtual v8::MaybeLocal<v8::String> Get(v8::Isolate* isolate,
647
                                         v8::Local<v8::String> key) const = 0;
648
  virtual v8::Maybe<std::string> Get(const char* key) const = 0;
649
  virtual void Set(v8::Isolate* isolate,
650
                   v8::Local<v8::String> key,
651
                   v8::Local<v8::String> value) = 0;
652
  virtual int32_t Query(v8::Isolate* isolate,
653
                        v8::Local<v8::String> key) const = 0;
654
  virtual int32_t Query(const char* key) const = 0;
655
  virtual void Delete(v8::Isolate* isolate, v8::Local<v8::String> key) = 0;
656
  virtual v8::Local<v8::Array> Enumerate(v8::Isolate* isolate) const = 0;
657
658
  virtual std::shared_ptr<KVStore> Clone(v8::Isolate* isolate) const;
659
  virtual v8::Maybe<bool> AssignFromObject(v8::Local<v8::Context> context,
660
                                           v8::Local<v8::Object> entries);
661
662
  static std::shared_ptr<KVStore> CreateMapKVStore();
663
};
664
665
namespace per_process {
666
extern std::shared_ptr<KVStore> system_environment;
667
}
668
669
struct EnvSerializeInfo;
670
671
class AsyncHooks : public MemoryRetainer {
672
 public:
673
22
  SET_MEMORY_INFO_NAME(AsyncHooks)
674
22
  SET_SELF_SIZE(AsyncHooks)
675
  void MemoryInfo(MemoryTracker* tracker) const override;
676
677
  // Reason for both UidFields and Fields are that one is stored as a double*
678
  // and the other as a uint32_t*.
679
  enum Fields {
680
    kInit,
681
    kBefore,
682
    kAfter,
683
    kDestroy,
684
    kPromiseResolve,
685
    kTotals,
686
    kCheck,
687
    kStackLength,
688
    kUsesExecutionAsyncResource,
689
    kFieldsCount,
690
  };
691
692
  enum UidFields {
693
    kExecutionAsyncId,
694
    kTriggerAsyncId,
695
    kAsyncIdCounter,
696
    kDefaultTriggerAsyncId,
697
    kUidFieldsCount,
698
  };
699
700
  inline AliasedUint32Array& fields();
701
  inline AliasedFloat64Array& async_id_fields();
702
  inline AliasedFloat64Array& async_ids_stack();
703
  inline v8::Local<v8::Array> js_execution_async_resources();
704
  // Returns the native executionAsyncResource value at stack index `index`.
705
  // Resources provided on the JS side are not stored on the native stack,
706
  // in which case an empty `Local<>` is returned.
707
  // The `js_execution_async_resources` array contains the value in that case.
708
  inline v8::Local<v8::Object> native_execution_async_resource(size_t index);
709
710
  inline void SetJSPromiseHooks(v8::Local<v8::Function> init,
711
                                v8::Local<v8::Function> before,
712
                                v8::Local<v8::Function> after,
713
                                v8::Local<v8::Function> resolve);
714
715
  inline v8::Local<v8::String> provider_string(int idx);
716
717
  inline void no_force_checks();
718
  inline Environment* env();
719
720
  inline void push_async_context(double async_id, double trigger_async_id,
721
      v8::Local<v8::Object> execution_async_resource_);
722
  inline bool pop_async_context(double async_id);
723
  inline void clear_async_id_stack();  // Used in fatal exceptions.
724
725
  inline void AddContext(v8::Local<v8::Context> ctx);
726
  inline void RemoveContext(v8::Local<v8::Context> ctx);
727
728
  AsyncHooks(const AsyncHooks&) = delete;
729
  AsyncHooks& operator=(const AsyncHooks&) = delete;
730
  AsyncHooks(AsyncHooks&&) = delete;
731
  AsyncHooks& operator=(AsyncHooks&&) = delete;
732
19680
  ~AsyncHooks() = default;
733
734
  // Used to set the kDefaultTriggerAsyncId in a scope. This is instead of
735
  // passing the trigger_async_id along with other constructor arguments.
736
  class DefaultTriggerAsyncIdScope {
737
   public:
738
    DefaultTriggerAsyncIdScope() = delete;
739
    explicit DefaultTriggerAsyncIdScope(Environment* env,
740
                                        double init_trigger_async_id);
741
    explicit DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap);
742
    ~DefaultTriggerAsyncIdScope();
743
744
    DefaultTriggerAsyncIdScope(const DefaultTriggerAsyncIdScope&) = delete;
745
    DefaultTriggerAsyncIdScope& operator=(const DefaultTriggerAsyncIdScope&) =
746
        delete;
747
    DefaultTriggerAsyncIdScope(DefaultTriggerAsyncIdScope&&) = delete;
748
    DefaultTriggerAsyncIdScope& operator=(DefaultTriggerAsyncIdScope&&) =
749
        delete;
750
751
   private:
752
    AsyncHooks* async_hooks_;
753
    double old_default_trigger_async_id_;
754
  };
755
756
  struct SerializeInfo {
757
    AliasedBufferIndex async_ids_stack;
758
    AliasedBufferIndex fields;
759
    AliasedBufferIndex async_id_fields;
760
    SnapshotIndex js_execution_async_resources;
761
    std::vector<SnapshotIndex> native_execution_async_resources;
762
  };
763
764
  SerializeInfo Serialize(v8::Local<v8::Context> context,
765
                          v8::SnapshotCreator* creator);
766
  void Deserialize(v8::Local<v8::Context> context);
767
768
 private:
769
  friend class Environment;  // So we can call the constructor.
770
  explicit AsyncHooks(v8::Isolate* isolate, const SerializeInfo* info);
771
772
  // Stores the ids of the current execution context stack.
773
  AliasedFloat64Array async_ids_stack_;
774
  // Attached to a Uint32Array that tracks the number of active hooks for
775
  // each type.
776
  AliasedUint32Array fields_;
777
  // Attached to a Float64Array that tracks the state of async resources.
778
  AliasedFloat64Array async_id_fields_;
779
780
  void grow_async_ids_stack();
781
782
  v8::Global<v8::Array> js_execution_async_resources_;
783
  std::vector<v8::Global<v8::Object>> native_execution_async_resources_;
784
785
  // Non-empty during deserialization
786
  const SerializeInfo* info_ = nullptr;
787
788
  std::vector<v8::Global<v8::Context>> contexts_;
789
790
  std::array<v8::Global<v8::Function>, 4> js_promise_hooks_;
791
};
792
793
class ImmediateInfo : public MemoryRetainer {
794
 public:
795
  inline AliasedUint32Array& fields();
796
  inline uint32_t count() const;
797
  inline uint32_t ref_count() const;
798
  inline bool has_outstanding() const;
799
  inline void ref_count_inc(uint32_t increment);
800
  inline void ref_count_dec(uint32_t decrement);
801
802
  ImmediateInfo(const ImmediateInfo&) = delete;
803
  ImmediateInfo& operator=(const ImmediateInfo&) = delete;
804
  ImmediateInfo(ImmediateInfo&&) = delete;
805
  ImmediateInfo& operator=(ImmediateInfo&&) = delete;
806
9840
  ~ImmediateInfo() = default;
807
808
22
  SET_MEMORY_INFO_NAME(ImmediateInfo)
809
22
  SET_SELF_SIZE(ImmediateInfo)
810
  void MemoryInfo(MemoryTracker* tracker) const override;
811
812
  struct SerializeInfo {
813
    AliasedBufferIndex fields;
814
  };
815
  SerializeInfo Serialize(v8::Local<v8::Context> context,
816
                          v8::SnapshotCreator* creator);
817
  void Deserialize(v8::Local<v8::Context> context);
818
819
 private:
820
  friend class Environment;  // So we can call the constructor.
821
  explicit ImmediateInfo(v8::Isolate* isolate, const SerializeInfo* info);
822
823
  enum Fields { kCount, kRefCount, kHasOutstanding, kFieldsCount };
824
825
  AliasedUint32Array fields_;
826
};
827
828
class TickInfo : public MemoryRetainer {
829
 public:
830
  inline AliasedUint8Array& fields();
831
  inline bool has_tick_scheduled() const;
832
  inline bool has_rejection_to_warn() const;
833
834
22
  SET_MEMORY_INFO_NAME(TickInfo)
835
22
  SET_SELF_SIZE(TickInfo)
836
  void MemoryInfo(MemoryTracker* tracker) const override;
837
838
  TickInfo(const TickInfo&) = delete;
839
  TickInfo& operator=(const TickInfo&) = delete;
840
  TickInfo(TickInfo&&) = delete;
841
  TickInfo& operator=(TickInfo&&) = delete;
842
9840
  ~TickInfo() = default;
843
844
  struct SerializeInfo {
845
    AliasedBufferIndex fields;
846
  };
847
  SerializeInfo Serialize(v8::Local<v8::Context> context,
848
                          v8::SnapshotCreator* creator);
849
  void Deserialize(v8::Local<v8::Context> context);
850
851
 private:
852
  friend class Environment;  // So we can call the constructor.
853
  explicit TickInfo(v8::Isolate* isolate, const SerializeInfo* info);
854
855
  enum Fields { kHasTickScheduled = 0, kHasRejectionToWarn, kFieldsCount };
856
857
  AliasedUint8Array fields_;
858
};
859
860
class TrackingTraceStateObserver :
861
    public v8::TracingController::TraceStateObserver {
862
 public:
863
5496
  explicit TrackingTraceStateObserver(Environment* env) : env_(env) {}
864
865
87
  void OnTraceEnabled() override {
866
87
    UpdateTraceCategoryState();
867
87
  }
868
869
34
  void OnTraceDisabled() override {
870
34
    UpdateTraceCategoryState();
871
34
  }
872
873
 private:
874
  void UpdateTraceCategoryState();
875
876
  Environment* env_;
877
};
878
879
class ShouldNotAbortOnUncaughtScope {
880
 public:
881
  explicit inline ShouldNotAbortOnUncaughtScope(Environment* env);
882
  inline void Close();
883
  inline ~ShouldNotAbortOnUncaughtScope();
884
  ShouldNotAbortOnUncaughtScope(const ShouldNotAbortOnUncaughtScope&) = delete;
885
  ShouldNotAbortOnUncaughtScope& operator=(
886
      const ShouldNotAbortOnUncaughtScope&) = delete;
887
  ShouldNotAbortOnUncaughtScope(ShouldNotAbortOnUncaughtScope&&) = delete;
888
  ShouldNotAbortOnUncaughtScope& operator=(ShouldNotAbortOnUncaughtScope&&) =
889
      delete;
890
891
 private:
892
  Environment* env_;
893
};
894
895
class CleanupHookCallback {
896
 public:
897
  typedef void (*Callback)(void*);
898
899
722326
  CleanupHookCallback(Callback fn,
900
                      void* arg,
901
                      uint64_t insertion_order_counter)
902
722326
      : fn_(fn), arg_(arg), insertion_order_counter_(insertion_order_counter) {}
903
904
  // Only hashes `arg_`, since that is usually enough to identify the hook.
905
  struct Hash {
906
    inline size_t operator()(const CleanupHookCallback& cb) const;
907
  };
908
909
  // Compares by `fn_` and `arg_` being equal.
910
  struct Equal {
911
    inline bool operator()(const CleanupHookCallback& a,
912
                           const CleanupHookCallback& b) const;
913
  };
914
915
  inline BaseObject* GetBaseObject() const;
916
917
 private:
918
  friend class Environment;
919
  Callback fn_;
920
  void* arg_;
921
922
  // We keep track of the insertion order for these objects, so that we can
923
  // call the callbacks in reverse order when we are cleaning up.
924
  uint64_t insertion_order_counter_;
925
};
926
927
struct PropInfo {
928
  std::string name;     // name for debugging
929
  size_t id;            // In the list - in case there are any empty entries
930
  SnapshotIndex index;  // In the snapshot
931
};
932
933
typedef void (*DeserializeRequestCallback)(v8::Local<v8::Context> context,
934
                                           v8::Local<v8::Object> holder,
935
                                           int index,
936
                                           InternalFieldInfo* info);
937
struct DeserializeRequest {
938
  DeserializeRequestCallback cb;
939
  v8::Global<v8::Object> holder;
940
  int index;
941
  InternalFieldInfo* info = nullptr;  // Owned by the request
942
943
  // Move constructor
944
29208
  DeserializeRequest(DeserializeRequest&& other) = default;
945
};
946
947
struct EnvSerializeInfo {
948
  std::vector<PropInfo> bindings;
949
  std::vector<std::string> native_modules;
950
  AsyncHooks::SerializeInfo async_hooks;
951
  TickInfo::SerializeInfo tick_info;
952
  ImmediateInfo::SerializeInfo immediate_info;
953
  performance::PerformanceState::SerializeInfo performance_state;
954
  AliasedBufferIndex stream_base_state;
955
  AliasedBufferIndex should_abort_on_uncaught_toggle;
956
957
  std::vector<PropInfo> persistent_templates;
958
  std::vector<PropInfo> persistent_values;
959
960
  SnapshotIndex context;
961
  friend std::ostream& operator<<(std::ostream& o, const EnvSerializeInfo& i);
962
};
963
964
struct SnapshotData {
965
6
  SnapshotData() { blob.data = nullptr; }
966
  v8::StartupData blob;
967
  std::vector<size_t> isolate_data_indices;
968
  EnvSerializeInfo env_info;
969
};
970
971
class Environment : public MemoryRetainer {
972
 public:
973
  Environment(const Environment&) = delete;
974
  Environment& operator=(const Environment&) = delete;
975
  Environment(Environment&&) = delete;
976
  Environment& operator=(Environment&&) = delete;
977
978
22
  SET_MEMORY_INFO_NAME(Environment)
979
980
  inline size_t SelfSize() const override;
981
44
  bool IsRootNode() const override { return true; }
982
  void MemoryInfo(MemoryTracker* tracker) const override;
983
984
  EnvSerializeInfo Serialize(v8::SnapshotCreator* creator);
985
  void CreateProperties();
986
  void DeserializeProperties(const EnvSerializeInfo* info);
987
988
  void PrintInfoForSnapshotIfDebug();
989
  void PrintAllBaseObjects();
990
  void VerifyNoStrongBaseObjects();
991
  void EnqueueDeserializeRequest(DeserializeRequestCallback cb,
992
                                 v8::Local<v8::Object> holder,
993
                                 int index,
994
                                 InternalFieldInfo* info);
995
  void RunDeserializeRequests();
996
  // Should be called before InitializeInspector()
997
  void InitializeDiagnostics();
998
999
  std::string GetCwd();
1000
1001
#if HAVE_INSPECTOR
1002
  // If the environment is created for a worker, pass parent_handle and
1003
  // the ownership if transferred into the Environment.
1004
  int InitializeInspector(
1005
      std::unique_ptr<inspector::ParentInspectorHandle> parent_handle);
1006
#endif
1007
1008
  v8::MaybeLocal<v8::Value> BootstrapInternalLoaders();
1009
  v8::MaybeLocal<v8::Value> BootstrapNode();
1010
  v8::MaybeLocal<v8::Value> RunBootstrapping();
1011
1012
  inline size_t async_callback_scope_depth() const;
1013
  inline void PushAsyncCallbackScope();
1014
  inline void PopAsyncCallbackScope();
1015
1016
  static inline Environment* GetCurrent(v8::Isolate* isolate);
1017
  static inline Environment* GetCurrent(v8::Local<v8::Context> context);
1018
  static inline Environment* GetCurrent(
1019
      const v8::FunctionCallbackInfo<v8::Value>& info);
1020
1021
  template <typename T>
1022
  static inline Environment* GetCurrent(
1023
      const v8::PropertyCallbackInfo<T>& info);
1024
1025
  // Methods created using SetMethod(), SetPrototypeMethod(), etc. inside
1026
  // this scope can access the created T* object using
1027
  // GetBindingData<T>(args) later.
1028
  template <typename T>
1029
  T* AddBindingData(v8::Local<v8::Context> context,
1030
                    v8::Local<v8::Object> target);
1031
  template <typename T, typename U>
1032
  static inline T* GetBindingData(const v8::PropertyCallbackInfo<U>& info);
1033
  template <typename T>
1034
  static inline T* GetBindingData(
1035
      const v8::FunctionCallbackInfo<v8::Value>& info);
1036
  template <typename T>
1037
  static inline T* GetBindingData(v8::Local<v8::Context> context);
1038
1039
  typedef std::unordered_map<
1040
      FastStringKey,
1041
      BaseObjectPtr<BaseObject>,
1042
      FastStringKey::Hash> BindingDataStore;
1043
1044
  // Create an Environment without initializing a main Context. Use
1045
  // InitializeMainContext() to initialize a main context for it.
1046
  Environment(IsolateData* isolate_data,
1047
              v8::Isolate* isolate,
1048
              const std::vector<std::string>& args,
1049
              const std::vector<std::string>& exec_args,
1050
              const EnvSerializeInfo* env_info,
1051
              EnvironmentFlags::Flags flags,
1052
              ThreadId thread_id);
1053
  void InitializeMainContext(v8::Local<v8::Context> context,
1054
                             const EnvSerializeInfo* env_info);
1055
  // Create an Environment and initialize the provided main context for it.
1056
  Environment(IsolateData* isolate_data,
1057
              v8::Local<v8::Context> context,
1058
              const std::vector<std::string>& args,
1059
              const std::vector<std::string>& exec_args,
1060
              const EnvSerializeInfo* env_info,
1061
              EnvironmentFlags::Flags flags,
1062
              ThreadId thread_id);
1063
  ~Environment() override;
1064
1065
  void InitializeLibuv();
1066
  inline const std::vector<std::string>& exec_argv();
1067
  inline const std::vector<std::string>& argv();
1068
  const std::string& exec_path() const;
1069
1070
  typedef void (*HandleCleanupCb)(Environment* env,
1071
                                  uv_handle_t* handle,
1072
                                  void* arg);
1073
  struct HandleCleanup {
1074
    uv_handle_t* handle_;
1075
    HandleCleanupCb cb_;
1076
    void* arg_;
1077
  };
1078
1079
  void RegisterHandleCleanups();
1080
  void CleanupHandles();
1081
  void Exit(int code);
1082
  void ExitEnv();
1083
1084
  // Register clean-up cb to be called on environment destruction.
1085
  inline void RegisterHandleCleanup(uv_handle_t* handle,
1086
                                    HandleCleanupCb cb,
1087
                                    void* arg);
1088
1089
  template <typename T, typename OnCloseCallback>
1090
  inline void CloseHandle(T* handle, OnCloseCallback callback);
1091
1092
  inline void AssignToContext(v8::Local<v8::Context> context,
1093
                              const ContextInfo& info);
1094
1095
  void StartProfilerIdleNotifier();
1096
1097
  inline v8::Isolate* isolate() const;
1098
  inline uv_loop_t* event_loop() const;
1099
  inline void TryLoadAddon(
1100
      const char* filename,
1101
      int flags,
1102
      const std::function<bool(binding::DLib*)>& was_loaded);
1103
1104
  static inline Environment* from_timer_handle(uv_timer_t* handle);
1105
  inline uv_timer_t* timer_handle();
1106
1107
  static inline Environment* from_immediate_check_handle(uv_check_t* handle);
1108
  inline uv_check_t* immediate_check_handle();
1109
  inline uv_idle_t* immediate_idle_handle();
1110
1111
  inline void IncreaseWaitingRequestCounter();
1112
  inline void DecreaseWaitingRequestCounter();
1113
1114
  inline AsyncHooks* async_hooks();
1115
  inline ImmediateInfo* immediate_info();
1116
  inline TickInfo* tick_info();
1117
  inline uint64_t timer_base() const;
1118
  inline std::shared_ptr<KVStore> env_vars();
1119
  inline void set_env_vars(std::shared_ptr<KVStore> env_vars);
1120
1121
  inline IsolateData* isolate_data() const;
1122
1123
  inline bool printed_error() const;
1124
  inline void set_printed_error(bool value);
1125
1126
  void PrintSyncTrace() const;
1127
  inline void set_trace_sync_io(bool value);
1128
1129
  inline void set_force_context_aware(bool value);
1130
  inline bool force_context_aware() const;
1131
1132
  // This stores whether the --abort-on-uncaught-exception flag was passed
1133
  // to Node.
1134
  inline bool abort_on_uncaught_exception() const;
1135
  inline void set_abort_on_uncaught_exception(bool value);
1136
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
1137
  // should abort the process or not if --abort-on-uncaught-exception was
1138
  // passed to Node. If the flag was not passed, it is ignored.
1139
  inline AliasedUint32Array& should_abort_on_uncaught_toggle();
1140
1141
  inline AliasedInt32Array& stream_base_state();
1142
1143
  // The necessary API for async_hooks.
1144
  inline double new_async_id();
1145
  inline double execution_async_id();
1146
  inline double trigger_async_id();
1147
  inline double get_default_trigger_async_id();
1148
1149
  // List of id's that have been destroyed and need the destroy() cb called.
1150
  inline std::vector<double>* destroy_async_id_list();
1151
1152
  std::set<struct node_module*> internal_bindings;
1153
  std::set<std::string> native_modules_with_cache;
1154
  std::set<std::string> native_modules_without_cache;
1155
  // This is only filled during deserialization. We use a vector since
1156
  // it's only used for tests.
1157
  std::vector<std::string> native_modules_in_snapshot;
1158
1159
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
1160
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
1161
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
1162
      id_to_script_map;
1163
  std::unordered_map<uint32_t, contextify::CompiledFnEntry*> id_to_function_map;
1164
1165
  inline uint32_t get_next_module_id();
1166
  inline uint32_t get_next_script_id();
1167
  inline uint32_t get_next_function_id();
1168
1169
1310774
  EnabledDebugList* enabled_debug_list() { return &enabled_debug_list_; }
1170
1171
  inline performance::PerformanceState* performance_state();
1172
1173
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
1174
                              int errorno,
1175
                              const char* syscall = nullptr,
1176
                              const char* message = nullptr,
1177
                              const char* path = nullptr,
1178
                              const char* dest = nullptr);
1179
1180
  // If this flag is set, calls into JS (if they would be observable
1181
  // from userland) must be avoided.  This flag does not indicate whether
1182
  // calling into JS is allowed from a VM perspective at this point.
1183
  inline bool can_call_into_js() const;
1184
  inline void set_can_call_into_js(bool can_call_into_js);
1185
1186
  // Increase or decrease a counter that manages whether this Environment
1187
  // keeps the event loop alive on its own or not. The counter starts out at 0,
1188
  // meaning it does not, and any positive value will make it keep the event
1189
  // loop alive.
1190
  // This is used by Workers to manage their own .ref()/.unref() implementation,
1191
  // as Workers aren't directly associated with their own libuv handles.
1192
  inline void add_refs(int64_t diff);
1193
1194
  inline bool has_run_bootstrapping_code() const;
1195
  inline void DoneBootstrapping();
1196
1197
  inline bool has_serialized_options() const;
1198
  inline void set_has_serialized_options(bool has_serialized_options);
1199
1200
  inline bool is_main_thread() const;
1201
  inline bool no_native_addons() const;
1202
  inline bool should_not_register_esm_loader() const;
1203
  inline bool owns_process_state() const;
1204
  inline bool owns_inspector() const;
1205
  inline bool tracks_unmanaged_fds() const;
1206
  inline bool hide_console_windows() const;
1207
  inline bool no_global_search_paths() const;
1208
  inline uint64_t thread_id() const;
1209
  inline worker::Worker* worker_context() const;
1210
  Environment* worker_parent_env() const;
1211
  inline void add_sub_worker_context(worker::Worker* context);
1212
  inline void remove_sub_worker_context(worker::Worker* context);
1213
  void stop_sub_worker_contexts();
1214
  template <typename Fn>
1215
  inline void ForEachWorker(Fn&& iterator);
1216
  inline bool is_stopping() const;
1217
  inline void set_stopping(bool value);
1218
  inline std::list<node_module>* extra_linked_bindings();
1219
  inline node_module* extra_linked_bindings_head();
1220
  inline node_module* extra_linked_bindings_tail();
1221
  inline const Mutex& extra_linked_bindings_mutex() const;
1222
1223
  inline bool filehandle_close_warning() const;
1224
  inline void set_filehandle_close_warning(bool on);
1225
1226
  inline void set_source_maps_enabled(bool on);
1227
  inline bool source_maps_enabled() const;
1228
1229
  inline void ThrowError(const char* errmsg);
1230
  inline void ThrowTypeError(const char* errmsg);
1231
  inline void ThrowRangeError(const char* errmsg);
1232
  inline void ThrowErrnoException(int errorno,
1233
                                  const char* syscall = nullptr,
1234
                                  const char* message = nullptr,
1235
                                  const char* path = nullptr);
1236
  inline void ThrowUVException(int errorno,
1237
                               const char* syscall = nullptr,
1238
                               const char* message = nullptr,
1239
                               const char* path = nullptr,
1240
                               const char* dest = nullptr);
1241
1242
  inline v8::Local<v8::FunctionTemplate>
1243
      NewFunctionTemplate(v8::FunctionCallback callback,
1244
                          v8::Local<v8::Signature> signature =
1245
                              v8::Local<v8::Signature>(),
1246
                          v8::ConstructorBehavior behavior =
1247
                              v8::ConstructorBehavior::kAllow,
1248
                          v8::SideEffectType side_effect =
1249
                              v8::SideEffectType::kHasSideEffect);
1250
1251
  // Convenience methods for NewFunctionTemplate().
1252
  inline void SetMethod(v8::Local<v8::Object> that,
1253
                        const char* name,
1254
                        v8::FunctionCallback callback);
1255
1256
  inline void SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1257
                             const char* name,
1258
                             v8::FunctionCallback callback);
1259
1260
  inline void SetInstanceMethod(v8::Local<v8::FunctionTemplate> that,
1261
                                const char* name,
1262
                                v8::FunctionCallback callback);
1263
1264
1265
  // Safe variants denote the function has no side effects.
1266
  inline void SetMethodNoSideEffect(v8::Local<v8::Object> that,
1267
                                    const char* name,
1268
                                    v8::FunctionCallback callback);
1269
  inline void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that,
1270
                                         const char* name,
1271
                                         v8::FunctionCallback callback);
1272
1273
  enum class SetConstructorFunctionFlag {
1274
    NONE,
1275
    SET_CLASS_NAME,
1276
  };
1277
1278
  inline void SetConstructorFunction(v8::Local<v8::Object> that,
1279
                          const char* name,
1280
                          v8::Local<v8::FunctionTemplate> tmpl,
1281
                          SetConstructorFunctionFlag flag =
1282
                              SetConstructorFunctionFlag::SET_CLASS_NAME);
1283
1284
  inline void SetConstructorFunction(v8::Local<v8::Object> that,
1285
                          v8::Local<v8::String> name,
1286
                          v8::Local<v8::FunctionTemplate> tmpl,
1287
                          SetConstructorFunctionFlag flag =
1288
                              SetConstructorFunctionFlag::SET_CLASS_NAME);
1289
1290
  void AtExit(void (*cb)(void* arg), void* arg);
1291
  void RunAtExitCallbacks();
1292
1293
  void RunWeakRefCleanup();
1294
1295
  // Strings and private symbols are shared across shared contexts
1296
  // The getters simply proxy to the per-isolate primitive.
1297
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1298
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1299
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1300
#define V(TypeName, PropertyName)                                             \
1301
  inline v8::Local<TypeName> PropertyName() const;
1302
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1303
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1304
  PER_ISOLATE_STRING_PROPERTIES(VS)
1305
#undef V
1306
#undef VS
1307
#undef VY
1308
#undef VP
1309
1310
#define V(PropertyName, TypeName)                                             \
1311
  inline v8::Local<TypeName> PropertyName() const;                            \
1312
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
1313
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1314
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1315
#undef V
1316
1317
  inline v8::Local<v8::Context> context() const;
1318
1319
#if HAVE_INSPECTOR
1320
74379
  inline inspector::Agent* inspector_agent() const {
1321
74379
    return inspector_agent_.get();
1322
  }
1323
1324
  inline bool is_in_inspector_console_call() const;
1325
  inline void set_is_in_inspector_console_call(bool value);
1326
#endif
1327
1328
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
1329
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
1330
1331
57170
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
1332
77839
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
1333
1334
1
  inline bool EmitProcessEnvWarning() {
1335
1
    bool current_value = emit_env_nonstring_warning_;
1336
1
    emit_env_nonstring_warning_ = false;
1337
1
    return current_value;
1338
  }
1339
1340
1
  inline bool EmitErrNameWarning() {
1341
1
    bool current_value = emit_err_name_warning_;
1342
1
    emit_err_name_warning_ = false;
1343
1
    return current_value;
1344
  }
1345
1346
  // cb will be called as cb(env) on the next event loop iteration.
1347
  // Unlike the JS setImmediate() function, nested SetImmediate() calls will
1348
  // be run without returning control to the event loop, similar to nextTick().
1349
  template <typename Fn>
1350
  inline void SetImmediate(
1351
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1352
  template <typename Fn>
1353
  // This behaves like SetImmediate() but can be called from any thread.
1354
  inline void SetImmediateThreadsafe(
1355
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1356
  // This behaves like V8's Isolate::RequestInterrupt(), but also accounts for
1357
  // the event loop (i.e. combines the V8 function with SetImmediate()).
1358
  // The passed callback may not throw exceptions.
1359
  // This function can be called from any thread.
1360
  template <typename Fn>
1361
  inline void RequestInterrupt(Fn&& cb);
1362
  // This needs to be available for the JS-land setImmediate().
1363
  void ToggleImmediateRef(bool ref);
1364
1365
  inline void PushShouldNotAbortOnUncaughtScope();
1366
  inline void PopShouldNotAbortOnUncaughtScope();
1367
  inline bool inside_should_not_abort_on_uncaught_scope() const;
1368
1369
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
1370
1371
  v8::Local<v8::Value> GetNow();
1372
  void ScheduleTimer(int64_t duration);
1373
  void ToggleTimerRef(bool ref);
1374
1375
  using CleanupCallback = CleanupHookCallback::Callback;
1376
  inline void AddCleanupHook(CleanupCallback cb, void* arg);
1377
  inline void RemoveCleanupHook(CleanupCallback cb, void* arg);
1378
  void RunCleanup();
1379
1380
  static size_t NearHeapLimitCallback(void* data,
1381
                                      size_t current_heap_limit,
1382
                                      size_t initial_heap_limit);
1383
  static void BuildEmbedderGraph(v8::Isolate* isolate,
1384
                                 v8::EmbedderGraph* graph,
1385
                                 void* data);
1386
1387
  inline std::shared_ptr<EnvironmentOptions> options();
1388
  inline std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port();
1389
1390
  // The BaseObject count is a debugging helper that makes sure that there are
1391
  // no memory leaks caused by BaseObjects staying alive longer than expected
1392
  // (in particular, no circular BaseObjectPtr references).
1393
  inline void modify_base_object_count(int64_t delta);
1394
  inline int64_t base_object_created_after_bootstrap() const;
1395
  inline int64_t base_object_count() const;
1396
1397
3
  inline int32_t stack_trace_limit() const { return 10; }
1398
1399
#if HAVE_INSPECTOR
1400
  void set_coverage_connection(
1401
      std::unique_ptr<profiler::V8CoverageConnection> connection);
1402
  profiler::V8CoverageConnection* coverage_connection();
1403
1404
  inline void set_coverage_directory(const char* directory);
1405
  inline const std::string& coverage_directory() const;
1406
1407
  void set_cpu_profiler_connection(
1408
      std::unique_ptr<profiler::V8CpuProfilerConnection> connection);
1409
  profiler::V8CpuProfilerConnection* cpu_profiler_connection();
1410
1411
  inline void set_cpu_prof_name(const std::string& name);
1412
  inline const std::string& cpu_prof_name() const;
1413
1414
  inline void set_cpu_prof_interval(uint64_t interval);
1415
  inline uint64_t cpu_prof_interval() const;
1416
1417
  inline void set_cpu_prof_dir(const std::string& dir);
1418
  inline const std::string& cpu_prof_dir() const;
1419
1420
  void set_heap_profiler_connection(
1421
      std::unique_ptr<profiler::V8HeapProfilerConnection> connection);
1422
  profiler::V8HeapProfilerConnection* heap_profiler_connection();
1423
1424
  inline void set_heap_prof_name(const std::string& name);
1425
  inline const std::string& heap_prof_name() const;
1426
1427
  inline void set_heap_prof_dir(const std::string& dir);
1428
  inline const std::string& heap_prof_dir() const;
1429
1430
  inline void set_heap_prof_interval(uint64_t interval);
1431
  inline uint64_t heap_prof_interval() const;
1432
1433
#endif  // HAVE_INSPECTOR
1434
1435
  inline void set_main_utf16(std::unique_ptr<v8::String::Value>);
1436
  inline void set_process_exit_handler(
1437
      std::function<void(Environment*, int)>&& handler);
1438
1439
  void RunAndClearNativeImmediates(bool only_refed = false);
1440
  void RunAndClearInterrupts();
1441
1442
  inline uv_buf_t allocate_managed_buffer(const size_t suggested_size);
1443
  inline std::unique_ptr<v8::BackingStore> release_managed_buffer(
1444
      const uv_buf_t& buf);
1445
  inline std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
1446
      released_allocated_buffers();
1447
1448
  void AddUnmanagedFd(int fd);
1449
  void RemoveUnmanagedFd(int fd);
1450
1451
  template <typename T>
1452
  void ForEachBindingData(T&& iterator);
1453
1454
 private:
1455
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1456
                         const char* errmsg);
1457
1458
  std::list<binding::DLib> loaded_addons_;
1459
  v8::Isolate* const isolate_;
1460
  IsolateData* const isolate_data_;
1461
  uv_timer_t timer_handle_;
1462
  uv_check_t immediate_check_handle_;
1463
  uv_idle_t immediate_idle_handle_;
1464
  uv_prepare_t idle_prepare_handle_;
1465
  uv_check_t idle_check_handle_;
1466
  uv_async_t task_queues_async_;
1467
  int64_t task_queues_async_refs_ = 0;
1468
1469
  AsyncHooks async_hooks_;
1470
  ImmediateInfo immediate_info_;
1471
  TickInfo tick_info_;
1472
  const uint64_t timer_base_;
1473
  std::shared_ptr<KVStore> env_vars_;
1474
  bool printed_error_ = false;
1475
  bool trace_sync_io_ = false;
1476
  bool emit_env_nonstring_warning_ = true;
1477
  bool emit_err_name_warning_ = true;
1478
  bool emit_filehandle_warning_ = true;
1479
  bool source_maps_enabled_ = false;
1480
1481
  size_t async_callback_scope_depth_ = 0;
1482
  std::vector<double> destroy_async_id_list_;
1483
1484
#if HAVE_INSPECTOR
1485
  std::unique_ptr<profiler::V8CoverageConnection> coverage_connection_;
1486
  std::unique_ptr<profiler::V8CpuProfilerConnection> cpu_profiler_connection_;
1487
  std::string coverage_directory_;
1488
  std::string cpu_prof_dir_;
1489
  std::string cpu_prof_name_;
1490
  uint64_t cpu_prof_interval_;
1491
  std::unique_ptr<profiler::V8HeapProfilerConnection> heap_profiler_connection_;
1492
  std::string heap_prof_dir_;
1493
  std::string heap_prof_name_;
1494
  uint64_t heap_prof_interval_;
1495
#endif  // HAVE_INSPECTOR
1496
1497
  std::shared_ptr<EnvironmentOptions> options_;
1498
  // options_ contains debug options parsed from CLI arguments,
1499
  // while inspector_host_port_ stores the actual inspector host
1500
  // and port being used. For example the port is -1 by default
1501
  // and can be specified as 0 (meaning any port allocated when the
1502
  // server starts listening), but when the inspector server starts
1503
  // the inspector_host_port_->port() will be the actual port being
1504
  // used.
1505
  std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port_;
1506
  std::vector<std::string> exec_argv_;
1507
  std::vector<std::string> argv_;
1508
  std::string exec_path_;
1509
1510
  bool is_processing_heap_limit_callback_ = false;
1511
  int64_t heap_limit_snapshot_taken_ = 0;
1512
1513
  uint32_t module_id_counter_ = 0;
1514
  uint32_t script_id_counter_ = 0;
1515
  uint32_t function_id_counter_ = 0;
1516
1517
  AliasedUint32Array should_abort_on_uncaught_toggle_;
1518
  int should_not_abort_scope_counter_ = 0;
1519
1520
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1521
1522
  AliasedInt32Array stream_base_state_;
1523
1524
  uint64_t environment_start_time_;
1525
  std::unique_ptr<performance::PerformanceState> performance_state_;
1526
1527
  bool has_run_bootstrapping_code_ = false;
1528
  bool has_serialized_options_ = false;
1529
1530
  std::atomic_bool can_call_into_js_ { true };
1531
  uint64_t flags_;
1532
  uint64_t thread_id_;
1533
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1534
1535
  static void* const kNodeContextTagPtr;
1536
  static int const kNodeContextTag;
1537
1538
#if HAVE_INSPECTOR
1539
  std::unique_ptr<inspector::Agent> inspector_agent_;
1540
  bool is_in_inspector_console_call_ = false;
1541
#endif
1542
1543
  std::list<DeserializeRequest> deserialize_requests_;
1544
1545
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1546
  // the start of the class because it is used by
1547
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1548
  // symbols for Environment, which assumes that the position of members in
1549
  // memory are predictable. For more information please refer to
1550
  // `doc/guides/node-postmortem-support.md`
1551
  friend int GenDebugSymbols();
1552
  HandleWrapQueue handle_wrap_queue_;
1553
  ReqWrapQueue req_wrap_queue_;
1554
  std::list<HandleCleanup> handle_cleanup_queue_;
1555
  int handle_cleanup_waiting_ = 0;
1556
  int request_waiting_ = 0;
1557
1558
  EnabledDebugList enabled_debug_list_;
1559
1560
  std::list<node_module> extra_linked_bindings_;
1561
  Mutex extra_linked_bindings_mutex_;
1562
1563
  static void RunTimers(uv_timer_t* handle);
1564
1565
  struct ExitCallback {
1566
    void (*cb_)(void* arg);
1567
    void* arg_;
1568
  };
1569
1570
  std::list<ExitCallback> at_exit_functions_;
1571
1572
  typedef CallbackQueue<void, Environment*> NativeImmediateQueue;
1573
  NativeImmediateQueue native_immediates_;
1574
  Mutex native_immediates_threadsafe_mutex_;
1575
  NativeImmediateQueue native_immediates_threadsafe_;
1576
  NativeImmediateQueue native_immediates_interrupts_;
1577
  // Also guarded by native_immediates_threadsafe_mutex_. This can be used when
1578
  // trying to post tasks from other threads to an Environment, as the libuv
1579
  // handle for the immediate queues (task_queues_async_) may not be initialized
1580
  // yet or already have been destroyed.
1581
  bool task_queues_async_initialized_ = false;
1582
1583
  std::atomic<Environment**> interrupt_data_ {nullptr};
1584
  void RequestInterruptFromV8();
1585
  static void CheckImmediate(uv_check_t* handle);
1586
1587
  BindingDataStore bindings_;
1588
1589
  // Use an unordered_set, so that we have efficient insertion and removal.
1590
  std::unordered_set<CleanupHookCallback,
1591
                     CleanupHookCallback::Hash,
1592
                     CleanupHookCallback::Equal> cleanup_hooks_;
1593
  uint64_t cleanup_hook_counter_ = 0;
1594
  bool started_cleanup_ = false;
1595
1596
  int64_t base_object_count_ = 0;
1597
  int64_t base_object_created_by_bootstrap_ = 0;
1598
  std::atomic_bool is_stopping_ { false };
1599
1600
  std::unordered_set<int> unmanaged_fds_;
1601
1602
  std::function<void(Environment*, int)> process_exit_handler_ {
1603
      DefaultProcessExitHandler };
1604
1605
  template <typename T>
1606
  void ForEachBaseObject(T&& iterator);
1607
1608
#define V(PropertyName, TypeName) v8::Global<TypeName> PropertyName ## _;
1609
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1610
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1611
#undef V
1612
1613
  v8::Global<v8::Context> context_;
1614
1615
  // Keeps the main script source alive is one was passed to LoadEnvironment().
1616
  // We should probably find a way to just use plain `v8::String`s created from
1617
  // the source passed to LoadEnvironment() directly instead.
1618
  std::unique_ptr<v8::String::Value> main_utf16_;
1619
1620
  // Used by AllocatedBuffer::release() to keep track of the BackingStore for
1621
  // a given pointer.
1622
  std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>
1623
      released_allocated_buffers_;
1624
};
1625
1626
}  // namespace node
1627
1628
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1629
1630
#endif  // SRC_ENV_H_