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