GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.h Lines: 40 40 100.0 %
Date: 2022-06-12 04:16:28 Branches: 1 2 50.0 %

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