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