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