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