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