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