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