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