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