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