GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.h Lines: 43 43 100.0 %
Date: 2022-08-16 04:20:39 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_builtins.h"
38
#include "node_main_instance.h"
39
#include "node_options.h"
40
#include "node_perf_common.h"
41
#include "node_snapshotable.h"
42
#include "req_wrap.h"
43
#include "util.h"
44
#include "uv.h"
45
#include "v8.h"
46
47
#include <array>
48
#include <atomic>
49
#include <cstdint>
50
#include <functional>
51
#include <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(builtin_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
12824
  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
21900
  ~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
10950
  ~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
10950
  ~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
6101
  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
2942298
  CleanupHookCallback(Callback fn,
929
                      void* arg,
930
                      uint64_t insertion_order_counter)
931
2942298
      : 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
                                           InternalFieldInfoBase* info);
960
struct DeserializeRequest {
961
  DeserializeRequestCallback cb;
962
  v8::Global<v8::Object> holder;
963
  int index;
964
  InternalFieldInfoBase* info = nullptr;  // Owned by the request
965
966
  // Move constructor
967
42648
  DeserializeRequest(DeserializeRequest&& other) = default;
968
};
969
970
struct EnvSerializeInfo {
971
  std::vector<PropInfo> native_objects;
972
  std::vector<std::string> builtins;
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 SnapshotMetadata {
988
  // For now kFullyCustomized is only built with the --build-snapshot CLI flag.
989
  // We might want to add more types of snapshots in the future.
990
  enum class Type : uint8_t { kDefault, kFullyCustomized };
991
992
  Type type;
993
  std::string node_version;
994
  std::string node_arch;
995
  std::string node_platform;
996
  // Result of v8::ScriptCompiler::CachedDataVersionTag().
997
  uint32_t v8_cache_version_tag;
998
};
999
1000
struct SnapshotData {
1001
  enum class DataOwnership { kOwned, kNotOwned };
1002
1003
  static const uint32_t kMagic = 0x143da19;
1004
  static const SnapshotIndex kNodeBaseContextIndex = 0;
1005
  static const SnapshotIndex kNodeMainContextIndex = kNodeBaseContextIndex + 1;
1006
1007
  DataOwnership data_ownership = DataOwnership::kOwned;
1008
1009
  SnapshotMetadata metadata;
1010
1011
  // The result of v8::SnapshotCreator::CreateBlob() during the snapshot
1012
  // building process.
1013
  v8::StartupData v8_snapshot_blob_data{nullptr, 0};
1014
1015
  IsolateDataSerializeInfo isolate_data_info;
1016
  // TODO(joyeecheung): there should be a vector of env_info once we snapshot
1017
  // the worker environments.
1018
  EnvSerializeInfo env_info;
1019
1020
  // A vector of built-in ids and v8::ScriptCompiler::CachedData, this can be
1021
  // shared across Node.js instances because they are supposed to share the
1022
  // read only space. We use builtins::CodeCacheInfo because
1023
  // v8::ScriptCompiler::CachedData is not copyable.
1024
  std::vector<builtins::CodeCacheInfo> code_cache;
1025
1026
  void ToBlob(FILE* out) const;
1027
  // If returns false, the metadata doesn't match the current Node.js binary,
1028
  // and the caller should not consume the snapshot data.
1029
  bool Check() const;
1030
  static bool FromBlob(SnapshotData* out, FILE* in);
1031
1032
  ~SnapshotData();
1033
1034
  SnapshotData(const SnapshotData&) = delete;
1035
  SnapshotData& operator=(const SnapshotData&) = delete;
1036
  SnapshotData(SnapshotData&&) = delete;
1037
  SnapshotData& operator=(SnapshotData&&) = delete;
1038
1039
9
  SnapshotData() = default;
1040
};
1041
1042
class Environment : public MemoryRetainer {
1043
 public:
1044
  Environment(const Environment&) = delete;
1045
  Environment& operator=(const Environment&) = delete;
1046
  Environment(Environment&&) = delete;
1047
  Environment& operator=(Environment&&) = delete;
1048
1049
24
  SET_MEMORY_INFO_NAME(Environment)
1050
1051
  inline size_t SelfSize() const override;
1052
48
  bool IsRootNode() const override { return true; }
1053
  void MemoryInfo(MemoryTracker* tracker) const override;
1054
1055
  EnvSerializeInfo Serialize(v8::SnapshotCreator* creator);
1056
  void CreateProperties();
1057
  void DeserializeProperties(const EnvSerializeInfo* info);
1058
1059
  void PrintInfoForSnapshotIfDebug();
1060
  void PrintAllBaseObjects();
1061
  void VerifyNoStrongBaseObjects();
1062
  void EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1063
                                 v8::Local<v8::Object> holder,
1064
                                 int index,
1065
                                 InternalFieldInfoBase* info);
1066
  void RunDeserializeRequests();
1067
  // Should be called before InitializeInspector()
1068
  void InitializeDiagnostics();
1069
1070
  std::string GetCwd();
1071
1072
#if HAVE_INSPECTOR
1073
  // If the environment is created for a worker, pass parent_handle and
1074
  // the ownership if transferred into the Environment.
1075
  int InitializeInspector(
1076
      std::unique_ptr<inspector::ParentInspectorHandle> parent_handle);
1077
#endif
1078
1079
  v8::MaybeLocal<v8::Value> BootstrapInternalLoaders();
1080
  v8::MaybeLocal<v8::Value> BootstrapNode();
1081
  v8::MaybeLocal<v8::Value> RunBootstrapping();
1082
1083
  inline size_t async_callback_scope_depth() const;
1084
  inline void PushAsyncCallbackScope();
1085
  inline void PopAsyncCallbackScope();
1086
1087
  static inline Environment* GetCurrent(v8::Isolate* isolate);
1088
  static inline Environment* GetCurrent(v8::Local<v8::Context> context);
1089
  static inline Environment* GetCurrent(
1090
      const v8::FunctionCallbackInfo<v8::Value>& info);
1091
1092
  template <typename T>
1093
  static inline Environment* GetCurrent(
1094
      const v8::PropertyCallbackInfo<T>& info);
1095
1096
  // Methods created using SetMethod(), SetPrototypeMethod(), etc. inside
1097
  // this scope can access the created T* object using
1098
  // GetBindingData<T>(args) later.
1099
  template <typename T>
1100
  T* AddBindingData(v8::Local<v8::Context> context,
1101
                    v8::Local<v8::Object> target);
1102
  template <typename T, typename U>
1103
  static inline T* GetBindingData(const v8::PropertyCallbackInfo<U>& info);
1104
  template <typename T>
1105
  static inline T* GetBindingData(
1106
      const v8::FunctionCallbackInfo<v8::Value>& info);
1107
  template <typename T>
1108
  static inline T* GetBindingData(v8::Local<v8::Context> context);
1109
1110
  typedef std::unordered_map<
1111
      FastStringKey,
1112
      BaseObjectPtr<BaseObject>,
1113
      FastStringKey::Hash> BindingDataStore;
1114
1115
  // Create an Environment without initializing a main Context. Use
1116
  // InitializeMainContext() to initialize a main context for it.
1117
  Environment(IsolateData* isolate_data,
1118
              v8::Isolate* isolate,
1119
              const std::vector<std::string>& args,
1120
              const std::vector<std::string>& exec_args,
1121
              const EnvSerializeInfo* env_info,
1122
              EnvironmentFlags::Flags flags,
1123
              ThreadId thread_id);
1124
  void InitializeMainContext(v8::Local<v8::Context> context,
1125
                             const EnvSerializeInfo* env_info);
1126
  // Create an Environment and initialize the provided main context for it.
1127
  Environment(IsolateData* isolate_data,
1128
              v8::Local<v8::Context> context,
1129
              const std::vector<std::string>& args,
1130
              const std::vector<std::string>& exec_args,
1131
              const EnvSerializeInfo* env_info,
1132
              EnvironmentFlags::Flags flags,
1133
              ThreadId thread_id);
1134
  ~Environment() override;
1135
1136
  void InitializeLibuv();
1137
  inline const std::vector<std::string>& exec_argv();
1138
  inline const std::vector<std::string>& argv();
1139
  const std::string& exec_path() const;
1140
1141
  typedef void (*HandleCleanupCb)(Environment* env,
1142
                                  uv_handle_t* handle,
1143
                                  void* arg);
1144
  struct HandleCleanup {
1145
    uv_handle_t* handle_;
1146
    HandleCleanupCb cb_;
1147
    void* arg_;
1148
  };
1149
1150
  void RegisterHandleCleanups();
1151
  void CleanupHandles();
1152
  void Exit(int code);
1153
  void ExitEnv();
1154
1155
  // Register clean-up cb to be called on environment destruction.
1156
  inline void RegisterHandleCleanup(uv_handle_t* handle,
1157
                                    HandleCleanupCb cb,
1158
                                    void* arg);
1159
1160
  template <typename T, typename OnCloseCallback>
1161
  inline void CloseHandle(T* handle, OnCloseCallback callback);
1162
1163
  void AssignToContext(v8::Local<v8::Context> context, const ContextInfo& info);
1164
1165
  void StartProfilerIdleNotifier();
1166
1167
  inline v8::Isolate* isolate() const;
1168
  inline uv_loop_t* event_loop() const;
1169
  void TryLoadAddon(const char* filename,
1170
                    int flags,
1171
                    const std::function<bool(binding::DLib*)>& was_loaded);
1172
1173
  static inline Environment* from_timer_handle(uv_timer_t* handle);
1174
  inline uv_timer_t* timer_handle();
1175
1176
  static inline Environment* from_immediate_check_handle(uv_check_t* handle);
1177
  inline uv_check_t* immediate_check_handle();
1178
  inline uv_idle_t* immediate_idle_handle();
1179
1180
  inline void IncreaseWaitingRequestCounter();
1181
  inline void DecreaseWaitingRequestCounter();
1182
1183
  inline AsyncHooks* async_hooks();
1184
  inline ImmediateInfo* immediate_info();
1185
  inline TickInfo* tick_info();
1186
  inline uint64_t timer_base() const;
1187
  inline std::shared_ptr<KVStore> env_vars();
1188
  inline void set_env_vars(std::shared_ptr<KVStore> env_vars);
1189
1190
  inline IsolateData* isolate_data() const;
1191
1192
  inline bool printed_error() const;
1193
  inline void set_printed_error(bool value);
1194
1195
  void PrintSyncTrace() const;
1196
  inline void set_trace_sync_io(bool value);
1197
1198
  inline void set_force_context_aware(bool value);
1199
  inline bool force_context_aware() const;
1200
1201
  // This is a pseudo-boolean that keeps track of whether the process is
1202
  // exiting.
1203
  inline void set_exiting(bool value);
1204
  inline AliasedUint32Array& exiting();
1205
1206
  // This stores whether the --abort-on-uncaught-exception flag was passed
1207
  // to Node.
1208
  inline bool abort_on_uncaught_exception() const;
1209
  inline void set_abort_on_uncaught_exception(bool value);
1210
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
1211
  // should abort the process or not if --abort-on-uncaught-exception was
1212
  // passed to Node. If the flag was not passed, it is ignored.
1213
  inline AliasedUint32Array& should_abort_on_uncaught_toggle();
1214
1215
  inline AliasedInt32Array& stream_base_state();
1216
1217
  // The necessary API for async_hooks.
1218
  inline double new_async_id();
1219
  inline double execution_async_id();
1220
  inline double trigger_async_id();
1221
  inline double get_default_trigger_async_id();
1222
1223
  // List of id's that have been destroyed and need the destroy() cb called.
1224
  inline std::vector<double>* destroy_async_id_list();
1225
1226
  std::set<struct node_module*> internal_bindings;
1227
  std::set<std::string> builtins_with_cache;
1228
  std::set<std::string> builtins_without_cache;
1229
  // This is only filled during deserialization. We use a vector since
1230
  // it's only used for tests.
1231
  std::vector<std::string> builtins_in_snapshot;
1232
1233
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
1234
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
1235
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
1236
      id_to_script_map;
1237
  std::unordered_map<uint32_t, contextify::CompiledFnEntry*> id_to_function_map;
1238
1239
  inline uint32_t get_next_module_id();
1240
  inline uint32_t get_next_script_id();
1241
  inline uint32_t get_next_function_id();
1242
1243
1387031
  EnabledDebugList* enabled_debug_list() { return &enabled_debug_list_; }
1244
1245
  inline performance::PerformanceState* performance_state();
1246
1247
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
1248
                              int errorno,
1249
                              const char* syscall = nullptr,
1250
                              const char* message = nullptr,
1251
                              const char* path = nullptr,
1252
                              const char* dest = nullptr);
1253
1254
  // If this flag is set, calls into JS (if they would be observable
1255
  // from userland) must be avoided.  This flag does not indicate whether
1256
  // calling into JS is allowed from a VM perspective at this point.
1257
  inline bool can_call_into_js() const;
1258
  inline void set_can_call_into_js(bool can_call_into_js);
1259
1260
  // Increase or decrease a counter that manages whether this Environment
1261
  // keeps the event loop alive on its own or not. The counter starts out at 0,
1262
  // meaning it does not, and any positive value will make it keep the event
1263
  // loop alive.
1264
  // This is used by Workers to manage their own .ref()/.unref() implementation,
1265
  // as Workers aren't directly associated with their own libuv handles.
1266
  void add_refs(int64_t diff);
1267
1268
  inline bool has_run_bootstrapping_code() const;
1269
  inline void DoneBootstrapping();
1270
1271
  inline bool has_serialized_options() const;
1272
  inline void set_has_serialized_options(bool has_serialized_options);
1273
1274
  inline bool is_main_thread() const;
1275
  inline bool no_native_addons() const;
1276
  inline bool should_not_register_esm_loader() const;
1277
  inline bool should_create_inspector() const;
1278
  inline bool owns_process_state() const;
1279
  inline bool owns_inspector() const;
1280
  inline bool tracks_unmanaged_fds() const;
1281
  inline bool hide_console_windows() const;
1282
  inline bool no_global_search_paths() const;
1283
  inline bool no_browser_globals() const;
1284
  inline uint64_t thread_id() const;
1285
  inline worker::Worker* worker_context() const;
1286
  Environment* worker_parent_env() const;
1287
  inline void add_sub_worker_context(worker::Worker* context);
1288
  inline void remove_sub_worker_context(worker::Worker* context);
1289
  void stop_sub_worker_contexts();
1290
  template <typename Fn>
1291
  inline void ForEachWorker(Fn&& iterator);
1292
  inline bool is_stopping() const;
1293
  inline void set_stopping(bool value);
1294
  inline std::list<node_module>* extra_linked_bindings();
1295
  inline node_module* extra_linked_bindings_head();
1296
  inline node_module* extra_linked_bindings_tail();
1297
  inline const Mutex& extra_linked_bindings_mutex() const;
1298
1299
  inline bool filehandle_close_warning() const;
1300
  inline void set_filehandle_close_warning(bool on);
1301
1302
  inline void set_source_maps_enabled(bool on);
1303
  inline bool source_maps_enabled() const;
1304
1305
  inline void ThrowError(const char* errmsg);
1306
  inline void ThrowTypeError(const char* errmsg);
1307
  inline void ThrowRangeError(const char* errmsg);
1308
  inline void ThrowErrnoException(int errorno,
1309
                                  const char* syscall = nullptr,
1310
                                  const char* message = nullptr,
1311
                                  const char* path = nullptr);
1312
  inline void ThrowUVException(int errorno,
1313
                               const char* syscall = nullptr,
1314
                               const char* message = nullptr,
1315
                               const char* path = nullptr,
1316
                               const char* dest = nullptr);
1317
1318
  void AtExit(void (*cb)(void* arg), void* arg);
1319
  void RunAtExitCallbacks();
1320
1321
  void RunWeakRefCleanup();
1322
1323
  v8::MaybeLocal<v8::Value> RunSnapshotSerializeCallback() const;
1324
  v8::MaybeLocal<v8::Value> RunSnapshotDeserializeCallback() const;
1325
  v8::MaybeLocal<v8::Value> RunSnapshotDeserializeMain() const;
1326
1327
  // Strings and private symbols are shared across shared contexts
1328
  // The getters simply proxy to the per-isolate primitive.
1329
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1330
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1331
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1332
#define V(TypeName, PropertyName)                                             \
1333
  inline v8::Local<TypeName> PropertyName() const;
1334
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1335
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1336
  PER_ISOLATE_STRING_PROPERTIES(VS)
1337
#undef V
1338
#undef VS
1339
#undef VY
1340
#undef VP
1341
1342
#define V(PropertyName, TypeName)                                             \
1343
  inline v8::Local<TypeName> PropertyName() const;                            \
1344
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
1345
  PER_ISOLATE_TEMPLATE_PROPERTIES(V)
1346
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1347
#undef V
1348
1349
  inline v8::Local<v8::Context> context() const;
1350
1351
#if HAVE_INSPECTOR
1352
103703
  inline inspector::Agent* inspector_agent() const {
1353
103703
    return inspector_agent_.get();
1354
  }
1355
1356
  inline bool is_in_inspector_console_call() const;
1357
  inline void set_is_in_inspector_console_call(bool value);
1358
#endif
1359
1360
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
1361
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
1362
1363
59083
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
1364
77967
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
1365
1366
6854
  inline uint64_t time_origin() {
1367
6854
    return time_origin_;
1368
  }
1369
6838
  inline double time_origin_timestamp() {
1370
6838
    return time_origin_timestamp_;
1371
  }
1372
1373
1
  inline bool EmitProcessEnvWarning() {
1374
1
    bool current_value = emit_env_nonstring_warning_;
1375
1
    emit_env_nonstring_warning_ = false;
1376
1
    return current_value;
1377
  }
1378
1379
1
  inline bool EmitErrNameWarning() {
1380
1
    bool current_value = emit_err_name_warning_;
1381
1
    emit_err_name_warning_ = false;
1382
1
    return current_value;
1383
  }
1384
1385
  // cb will be called as cb(env) on the next event loop iteration.
1386
  // Unlike the JS setImmediate() function, nested SetImmediate() calls will
1387
  // be run without returning control to the event loop, similar to nextTick().
1388
  template <typename Fn>
1389
  inline void SetImmediate(
1390
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1391
  template <typename Fn>
1392
  // This behaves like SetImmediate() but can be called from any thread.
1393
  inline void SetImmediateThreadsafe(
1394
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1395
  // This behaves like V8's Isolate::RequestInterrupt(), but also accounts for
1396
  // the event loop (i.e. combines the V8 function with SetImmediate()).
1397
  // The passed callback may not throw exceptions.
1398
  // This function can be called from any thread.
1399
  template <typename Fn>
1400
  inline void RequestInterrupt(Fn&& cb);
1401
  // This needs to be available for the JS-land setImmediate().
1402
  void ToggleImmediateRef(bool ref);
1403
1404
  inline void PushShouldNotAbortOnUncaughtScope();
1405
  inline void PopShouldNotAbortOnUncaughtScope();
1406
  inline bool inside_should_not_abort_on_uncaught_scope() const;
1407
1408
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
1409
1410
  v8::Local<v8::Value> GetNow();
1411
  void ScheduleTimer(int64_t duration);
1412
  void ToggleTimerRef(bool ref);
1413
1414
  using CleanupCallback = CleanupHookCallback::Callback;
1415
  inline void AddCleanupHook(CleanupCallback cb, void* arg);
1416
  inline void RemoveCleanupHook(CleanupCallback cb, void* arg);
1417
  void RunCleanup();
1418
1419
  static size_t NearHeapLimitCallback(void* data,
1420
                                      size_t current_heap_limit,
1421
                                      size_t initial_heap_limit);
1422
  static void BuildEmbedderGraph(v8::Isolate* isolate,
1423
                                 v8::EmbedderGraph* graph,
1424
                                 void* data);
1425
1426
  inline std::shared_ptr<EnvironmentOptions> options();
1427
  inline std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port();
1428
1429
  // The BaseObject count is a debugging helper that makes sure that there are
1430
  // no memory leaks caused by BaseObjects staying alive longer than expected
1431
  // (in particular, no circular BaseObjectPtr references).
1432
  inline void modify_base_object_count(int64_t delta);
1433
  inline int64_t base_object_created_after_bootstrap() const;
1434
  inline int64_t base_object_count() const;
1435
1436
3
  inline int32_t stack_trace_limit() const { return 10; }
1437
1438
#if HAVE_INSPECTOR
1439
  void set_coverage_connection(
1440
      std::unique_ptr<profiler::V8CoverageConnection> connection);
1441
  profiler::V8CoverageConnection* coverage_connection();
1442
1443
  inline void set_coverage_directory(const char* directory);
1444
  inline const std::string& coverage_directory() const;
1445
1446
  void set_cpu_profiler_connection(
1447
      std::unique_ptr<profiler::V8CpuProfilerConnection> connection);
1448
  profiler::V8CpuProfilerConnection* cpu_profiler_connection();
1449
1450
  inline void set_cpu_prof_name(const std::string& name);
1451
  inline const std::string& cpu_prof_name() const;
1452
1453
  inline void set_cpu_prof_interval(uint64_t interval);
1454
  inline uint64_t cpu_prof_interval() const;
1455
1456
  inline void set_cpu_prof_dir(const std::string& dir);
1457
  inline const std::string& cpu_prof_dir() const;
1458
1459
  void set_heap_profiler_connection(
1460
      std::unique_ptr<profiler::V8HeapProfilerConnection> connection);
1461
  profiler::V8HeapProfilerConnection* heap_profiler_connection();
1462
1463
  inline void set_heap_prof_name(const std::string& name);
1464
  inline const std::string& heap_prof_name() const;
1465
1466
  inline void set_heap_prof_dir(const std::string& dir);
1467
  inline const std::string& heap_prof_dir() const;
1468
1469
  inline void set_heap_prof_interval(uint64_t interval);
1470
  inline uint64_t heap_prof_interval() const;
1471
1472
#endif  // HAVE_INSPECTOR
1473
1474
  inline void set_main_utf16(std::unique_ptr<v8::String::Value>);
1475
  inline void set_process_exit_handler(
1476
      std::function<void(Environment*, int)>&& handler);
1477
1478
  void RunAndClearNativeImmediates(bool only_refed = false);
1479
  void RunAndClearInterrupts();
1480
1481
  uv_buf_t allocate_managed_buffer(const size_t suggested_size);
1482
  std::unique_ptr<v8::BackingStore> release_managed_buffer(const uv_buf_t& buf);
1483
1484
  void AddUnmanagedFd(int fd);
1485
  void RemoveUnmanagedFd(int fd);
1486
1487
  template <typename T>
1488
  void ForEachBaseObject(T&& iterator);
1489
1490
 private:
1491
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1492
                         const char* errmsg);
1493
1494
  std::list<binding::DLib> loaded_addons_;
1495
  v8::Isolate* const isolate_;
1496
  IsolateData* const isolate_data_;
1497
  uv_timer_t timer_handle_;
1498
  uv_check_t immediate_check_handle_;
1499
  uv_idle_t immediate_idle_handle_;
1500
  uv_prepare_t idle_prepare_handle_;
1501
  uv_check_t idle_check_handle_;
1502
  uv_async_t task_queues_async_;
1503
  int64_t task_queues_async_refs_ = 0;
1504
1505
  AsyncHooks async_hooks_;
1506
  ImmediateInfo immediate_info_;
1507
  TickInfo tick_info_;
1508
  const uint64_t timer_base_;
1509
  std::shared_ptr<KVStore> env_vars_;
1510
  bool printed_error_ = false;
1511
  bool trace_sync_io_ = false;
1512
  bool emit_env_nonstring_warning_ = true;
1513
  bool emit_err_name_warning_ = true;
1514
  bool emit_filehandle_warning_ = true;
1515
  bool source_maps_enabled_ = false;
1516
1517
  size_t async_callback_scope_depth_ = 0;
1518
  std::vector<double> destroy_async_id_list_;
1519
1520
#if HAVE_INSPECTOR
1521
  std::unique_ptr<profiler::V8CoverageConnection> coverage_connection_;
1522
  std::unique_ptr<profiler::V8CpuProfilerConnection> cpu_profiler_connection_;
1523
  std::string coverage_directory_;
1524
  std::string cpu_prof_dir_;
1525
  std::string cpu_prof_name_;
1526
  uint64_t cpu_prof_interval_;
1527
  std::unique_ptr<profiler::V8HeapProfilerConnection> heap_profiler_connection_;
1528
  std::string heap_prof_dir_;
1529
  std::string heap_prof_name_;
1530
  uint64_t heap_prof_interval_;
1531
#endif  // HAVE_INSPECTOR
1532
1533
  std::shared_ptr<EnvironmentOptions> options_;
1534
  // options_ contains debug options parsed from CLI arguments,
1535
  // while inspector_host_port_ stores the actual inspector host
1536
  // and port being used. For example the port is -1 by default
1537
  // and can be specified as 0 (meaning any port allocated when the
1538
  // server starts listening), but when the inspector server starts
1539
  // the inspector_host_port_->port() will be the actual port being
1540
  // used.
1541
  std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port_;
1542
  std::vector<std::string> exec_argv_;
1543
  std::vector<std::string> argv_;
1544
  std::string exec_path_;
1545
1546
  bool is_processing_heap_limit_callback_ = false;
1547
  int64_t heap_limit_snapshot_taken_ = 0;
1548
1549
  uint32_t module_id_counter_ = 0;
1550
  uint32_t script_id_counter_ = 0;
1551
  uint32_t function_id_counter_ = 0;
1552
1553
  AliasedUint32Array exiting_;
1554
1555
  AliasedUint32Array should_abort_on_uncaught_toggle_;
1556
  int should_not_abort_scope_counter_ = 0;
1557
1558
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1559
1560
  AliasedInt32Array stream_base_state_;
1561
1562
  // https://w3c.github.io/hr-time/#dfn-time-origin
1563
  uint64_t time_origin_;
1564
  // https://w3c.github.io/hr-time/#dfn-get-time-origin-timestamp
1565
  double time_origin_timestamp_;
1566
  std::unique_ptr<performance::PerformanceState> performance_state_;
1567
1568
  bool has_run_bootstrapping_code_ = false;
1569
  bool has_serialized_options_ = false;
1570
1571
  std::atomic_bool can_call_into_js_ { true };
1572
  uint64_t flags_;
1573
  uint64_t thread_id_;
1574
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1575
1576
  static void* const kNodeContextTagPtr;
1577
  static int const kNodeContextTag;
1578
1579
#if HAVE_INSPECTOR
1580
  std::unique_ptr<inspector::Agent> inspector_agent_;
1581
  bool is_in_inspector_console_call_ = false;
1582
#endif
1583
1584
  std::list<DeserializeRequest> deserialize_requests_;
1585
1586
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1587
  // the start of the class because it is used by
1588
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1589
  // symbols for Environment, which assumes that the position of members in
1590
  // memory are predictable. For more information please refer to
1591
  // `doc/contributing/node-postmortem-support.md`
1592
  friend int GenDebugSymbols();
1593
  HandleWrapQueue handle_wrap_queue_;
1594
  ReqWrapQueue req_wrap_queue_;
1595
  std::list<HandleCleanup> handle_cleanup_queue_;
1596
  int handle_cleanup_waiting_ = 0;
1597
  int request_waiting_ = 0;
1598
1599
  EnabledDebugList enabled_debug_list_;
1600
1601
  std::list<node_module> extra_linked_bindings_;
1602
  Mutex extra_linked_bindings_mutex_;
1603
1604
  static void RunTimers(uv_timer_t* handle);
1605
1606
  struct ExitCallback {
1607
    void (*cb_)(void* arg);
1608
    void* arg_;
1609
  };
1610
1611
  std::list<ExitCallback> at_exit_functions_;
1612
1613
  typedef CallbackQueue<void, Environment*> NativeImmediateQueue;
1614
  NativeImmediateQueue native_immediates_;
1615
  Mutex native_immediates_threadsafe_mutex_;
1616
  NativeImmediateQueue native_immediates_threadsafe_;
1617
  NativeImmediateQueue native_immediates_interrupts_;
1618
  // Also guarded by native_immediates_threadsafe_mutex_. This can be used when
1619
  // trying to post tasks from other threads to an Environment, as the libuv
1620
  // handle for the immediate queues (task_queues_async_) may not be initialized
1621
  // yet or already have been destroyed.
1622
  bool task_queues_async_initialized_ = false;
1623
1624
  std::atomic<Environment**> interrupt_data_ {nullptr};
1625
  void RequestInterruptFromV8();
1626
  static void CheckImmediate(uv_check_t* handle);
1627
1628
  BindingDataStore bindings_;
1629
1630
  // Use an unordered_set, so that we have efficient insertion and removal.
1631
  std::unordered_set<CleanupHookCallback,
1632
                     CleanupHookCallback::Hash,
1633
                     CleanupHookCallback::Equal> cleanup_hooks_;
1634
  uint64_t cleanup_hook_counter_ = 0;
1635
  bool started_cleanup_ = false;
1636
1637
  int64_t base_object_count_ = 0;
1638
  int64_t base_object_created_by_bootstrap_ = 0;
1639
  std::atomic_bool is_stopping_ { false };
1640
1641
  std::unordered_set<int> unmanaged_fds_;
1642
1643
  std::function<void(Environment*, int)> process_exit_handler_ {
1644
      DefaultProcessExitHandler };
1645
1646
#define V(PropertyName, TypeName) v8::Global<TypeName> PropertyName ## _;
1647
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1648
#undef V
1649
1650
  v8::Global<v8::Context> context_;
1651
1652
  // Keeps the main script source alive is one was passed to LoadEnvironment().
1653
  // We should probably find a way to just use plain `v8::String`s created from
1654
  // the source passed to LoadEnvironment() directly instead.
1655
  std::unique_ptr<v8::String::Value> main_utf16_;
1656
1657
  // Used by allocate_managed_buffer() and release_managed_buffer() to keep
1658
  // track of the BackingStore for a given pointer.
1659
  std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>
1660
      released_allocated_buffers_;
1661
};
1662
1663
}  // namespace node
1664
1665
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1666
1667
#endif  // SRC_ENV_H_