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