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