GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/env.h Lines: 47 47 100.0 %
Date: 2019-10-08 22:34:21 Branches: 14 26 53.8 %

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



164961
  class NativeImmediateCallbackImpl final : public NativeImmediateCallback {
1405
   public:
1406
    NativeImmediateCallbackImpl(Fn&& callback,
1407
                                v8::Global<v8::Object>&& keep_alive,
1408
                                bool refed);
1409
    void Call(Environment* env) override;
1410
1411
   private:
1412
    Fn callback_;
1413
    v8::Global<v8::Object> keep_alive_;
1414
  };
1415
1416
  std::unique_ptr<NativeImmediateCallback> native_immediate_callbacks_head_;
1417
  NativeImmediateCallback* native_immediate_callbacks_tail_ = nullptr;
1418
1419
  void RunAndClearNativeImmediates();
1420
  static void CheckImmediate(uv_check_t* handle);
1421
1422
  // Use an unordered_set, so that we have efficient insertion and removal.
1423
  std::unordered_set<CleanupHookCallback,
1424
                     CleanupHookCallback::Hash,
1425
                     CleanupHookCallback::Equal> cleanup_hooks_;
1426
  uint64_t cleanup_hook_counter_ = 0;
1427
  bool started_cleanup_ = false;
1428
1429
  // A custom async abstraction (a pair of async handle and a state variable)
1430
  // Used by embedders to shutdown running Node instance.
1431
  AsyncRequest thread_stopper_;
1432
1433
  typedef std::unordered_set<std::shared_ptr<v8::ArrayBuffer::Allocator>>
1434
      ArrayBufferAllocatorList;
1435
  ArrayBufferAllocatorList* keep_alive_allocators_ = nullptr;
1436
1437
  template <typename T>
1438
  void ForEachBaseObject(T&& iterator);
1439
1440
#define V(PropertyName, TypeName) v8::Global<TypeName> PropertyName ## _;
1441
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1442
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1443
#undef V
1444
1445
  v8::Global<v8::Context> context_;
1446
};
1447
1448
}  // namespace node
1449
1450
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1451
1452
#endif  // SRC_ENV_H_