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-09-13 22:28:55 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
5738
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(fd_constructor_template, v8::ObjectTemplate)                               \
386
  V(fdclose_constructor_template, v8::ObjectTemplate)                          \
387
  V(filehandlereadwrap_template, v8::ObjectTemplate)                           \
388
  V(fsreqpromise_constructor_template, v8::ObjectTemplate)                     \
389
  V(handle_wrap_ctor_template, v8::FunctionTemplate)                           \
390
  V(http2settings_constructor_template, v8::ObjectTemplate)                    \
391
  V(http2stream_constructor_template, v8::ObjectTemplate)                      \
392
  V(http2ping_constructor_template, v8::ObjectTemplate)                        \
393
  V(libuv_stream_wrap_ctor_template, v8::FunctionTemplate)                     \
394
  V(message_event_object_template, v8::ObjectTemplate)                         \
395
  V(message_port_constructor_template, v8::FunctionTemplate)                   \
396
  V(pipe_constructor_template, v8::FunctionTemplate)                           \
397
  V(promise_wrap_template, v8::ObjectTemplate)                                 \
398
  V(sab_lifetimepartner_constructor_template, v8::FunctionTemplate)            \
399
  V(script_context_constructor_template, v8::FunctionTemplate)                 \
400
  V(secure_context_constructor_template, v8::FunctionTemplate)                 \
401
  V(shutdown_wrap_template, v8::ObjectTemplate)                                \
402
  V(streambaseoutputstream_constructor_template, v8::ObjectTemplate)           \
403
  V(tcp_constructor_template, v8::FunctionTemplate)                            \
404
  V(tty_constructor_template, v8::FunctionTemplate)                            \
405
  V(write_wrap_template, v8::ObjectTemplate)
406
407
#define ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)                                \
408
  V(as_callback_data, v8::Object)                                              \
409
  V(async_hooks_after_function, v8::Function)                                  \
410
  V(async_hooks_before_function, v8::Function)                                 \
411
  V(async_hooks_binding, v8::Object)                                           \
412
  V(async_hooks_destroy_function, v8::Function)                                \
413
  V(async_hooks_init_function, v8::Function)                                   \
414
  V(async_hooks_promise_resolve_function, v8::Function)                        \
415
  V(buffer_prototype_object, v8::Object)                                       \
416
  V(crypto_key_object_constructor, v8::Function)                               \
417
  V(domain_callback, v8::Function)                                             \
418
  V(domexception_function, v8::Function)                                       \
419
  V(enhance_fatal_stack_after_inspector, v8::Function)                         \
420
  V(enhance_fatal_stack_before_inspector, v8::Function)                        \
421
  V(fs_use_promises_symbol, v8::Symbol)                                        \
422
  V(host_import_module_dynamically_callback, v8::Function)                     \
423
  V(host_initialize_import_meta_object_callback, v8::Function)                 \
424
  V(http2session_on_altsvc_function, v8::Function)                             \
425
  V(http2session_on_error_function, v8::Function)                              \
426
  V(http2session_on_frame_error_function, v8::Function)                        \
427
  V(http2session_on_goaway_data_function, v8::Function)                        \
428
  V(http2session_on_headers_function, v8::Function)                            \
429
  V(http2session_on_origin_function, v8::Function)                             \
430
  V(http2session_on_ping_function, v8::Function)                               \
431
  V(http2session_on_priority_function, v8::Function)                           \
432
  V(http2session_on_settings_function, v8::Function)                           \
433
  V(http2session_on_stream_close_function, v8::Function)                       \
434
  V(http2session_on_stream_trailers_function, v8::Function)                    \
435
  V(internal_binding_loader, v8::Function)                                     \
436
  V(immediate_callback_function, v8::Function)                                 \
437
  V(inspector_console_extension_installer, v8::Function)                       \
438
  V(message_port, v8::Object)                                                  \
439
  V(native_module_require, v8::Function)                                       \
440
  V(performance_entry_callback, v8::Function)                                  \
441
  V(performance_entry_template, v8::Function)                                  \
442
  V(prepare_stack_trace_callback, v8::Function)                                \
443
  V(process_object, v8::Object)                                                \
444
  V(primordials, v8::Object)                                                   \
445
  V(promise_reject_callback, v8::Function)                                     \
446
  V(script_data_constructor_function, v8::Function)                            \
447
  V(tick_callback_function, v8::Function)                                      \
448
  V(timers_callback_function, v8::Function)                                    \
449
  V(tls_wrap_constructor_function, v8::Function)                               \
450
  V(trace_category_state_function, v8::Function)                               \
451
  V(udp_constructor_function, v8::Function)                                    \
452
  V(url_constructor_function, v8::Function)
453
454
class Environment;
455
456
9566
class IsolateData : public MemoryRetainer {
457
 public:
458
  IsolateData(v8::Isolate* isolate,
459
              uv_loop_t* event_loop,
460
              MultiIsolatePlatform* platform = nullptr,
461
              ArrayBufferAllocator* node_allocator = nullptr,
462
              const std::vector<size_t>* indexes = nullptr);
463
51
  SET_MEMORY_INFO_NAME(IsolateData)
464
51
  SET_SELF_SIZE(IsolateData)
465
  void MemoryInfo(MemoryTracker* tracker) const override;
466
  std::vector<size_t> Serialize(v8::SnapshotCreator* creator);
467
468
  inline uv_loop_t* event_loop() const;
469
  inline MultiIsolatePlatform* platform() const;
470
  inline std::shared_ptr<PerIsolateOptions> options();
471
  inline void set_options(std::shared_ptr<PerIsolateOptions> options);
472
473
  inline bool uses_node_allocator() const;
474
  inline v8::ArrayBuffer::Allocator* allocator() const;
475
  inline NodeArrayBufferAllocator* node_allocator() const;
476
477
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
478
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
479
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
480
#define V(TypeName, PropertyName)                                             \
481
  inline v8::Local<TypeName> PropertyName(v8::Isolate* isolate) const;
482
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
483
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
484
  PER_ISOLATE_STRING_PROPERTIES(VS)
485
#undef V
486
#undef VY
487
#undef VS
488
#undef VP
489
490
  std::unordered_map<nghttp2_rcbuf*, v8::Eternal<v8::String>> http2_static_strs;
491
  inline v8::Isolate* isolate() const;
492
  IsolateData(const IsolateData&) = delete;
493
  IsolateData& operator=(const IsolateData&) = delete;
494
  IsolateData(IsolateData&&) = delete;
495
  IsolateData& operator=(IsolateData&&) = delete;
496
497
 private:
498
  void DeserializeProperties(const std::vector<size_t>* indexes);
499
  void CreateProperties();
500
501
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
502
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
503
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
504
#define V(TypeName, PropertyName)                                             \
505
  v8::Eternal<TypeName> PropertyName ## _;
506
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
507
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
508
  PER_ISOLATE_STRING_PROPERTIES(VS)
509
#undef V
510
#undef VY
511
#undef VS
512
#undef VP
513
514
  v8::Isolate* const isolate_;
515
  uv_loop_t* const event_loop_;
516
  v8::ArrayBuffer::Allocator* const allocator_;
517
  NodeArrayBufferAllocator* const node_allocator_;
518
  const bool uses_node_allocator_;
519
  MultiIsolatePlatform* platform_;
520
  std::shared_ptr<PerIsolateOptions> options_;
521
};
522
523
10827
struct ContextInfo {
524
10827
  explicit ContextInfo(const std::string& name) : name(name) {}
525
  const std::string name;
526
  std::string origin;
527
  bool is_default = false;
528
};
529
530
// Listing the AsyncWrap provider types first enables us to cast directly
531
// from a provider type to a debug category.
532
#define DEBUG_CATEGORY_NAMES(V)                                                \
533
  NODE_ASYNC_PROVIDER_TYPES(V)                                                 \
534
  V(INSPECTOR_SERVER)                                                          \
535
  V(INSPECTOR_PROFILER)
536
537
enum class DebugCategory {
538
#define V(name) name,
539
  DEBUG_CATEGORY_NAMES(V)
540
#undef V
541
  CATEGORY_COUNT
542
};
543
544
// A unique-pointer-ish object that is compatible with the JS engine's
545
// ArrayBuffer::Allocator.
546
struct AllocatedBuffer {
547
 public:
548
  explicit inline AllocatedBuffer(Environment* env = nullptr);
549
  inline AllocatedBuffer(Environment* env, uv_buf_t buf);
550
  inline ~AllocatedBuffer();
551
  inline void Resize(size_t len);
552
553
  inline uv_buf_t release();
554
  inline char* data();
555
  inline const char* data() const;
556
  inline size_t size() const;
557
  inline void clear();
558
559
  inline v8::MaybeLocal<v8::Object> ToBuffer();
560
  inline v8::Local<v8::ArrayBuffer> ToArrayBuffer();
561
562
  inline AllocatedBuffer(AllocatedBuffer&& other);
563
  inline AllocatedBuffer& operator=(AllocatedBuffer&& other);
564
  AllocatedBuffer(const AllocatedBuffer& other) = delete;
565
  AllocatedBuffer& operator=(const AllocatedBuffer& other) = delete;
566
567
 private:
568
  Environment* env_;
569
  // We do not pass this to libuv directly, but uv_buf_t is a convenient way
570
  // to represent a chunk of memory, and plays nicely with other parts of core.
571
  uv_buf_t buffer_;
572
573
  friend class Environment;
574
};
575
576
class AsyncRequest : public MemoryRetainer {
577
 public:
578
5397
  AsyncRequest() = default;
579
  ~AsyncRequest();
580
581
  AsyncRequest(const AsyncRequest&) = delete;
582
  AsyncRequest& operator=(const AsyncRequest&) = delete;
583
  AsyncRequest(AsyncRequest&&) = delete;
584
  AsyncRequest& operator=(AsyncRequest&&) = delete;
585
586
  void Install(Environment* env, void* data, uv_async_cb target);
587
  void Uninstall();
588
  void Stop();
589
  inline void set_stopped(bool flag);
590
  inline bool is_stopped() const;
591
  uv_async_t* GetHandle();
592
  void MemoryInfo(MemoryTracker* tracker) const override;
593
594
595
55
  SET_MEMORY_INFO_NAME(AsyncRequest)
596
59
  SET_SELF_SIZE(AsyncRequest)
597
598
 private:
599
  Environment* env_;
600
  uv_async_t* async_ = nullptr;
601
  std::atomic_bool stopped_ {true};
602
};
603
604
class KVStore {
605
 public:
606
5246
  KVStore() = default;
607
4842
  virtual ~KVStore() = default;
608
  KVStore(const KVStore&) = delete;
609
  KVStore& operator=(const KVStore&) = delete;
610
  KVStore(KVStore&&) = delete;
611
  KVStore& operator=(KVStore&&) = delete;
612
613
  virtual v8::MaybeLocal<v8::String> Get(v8::Isolate* isolate,
614
                                         v8::Local<v8::String> key) const = 0;
615
  virtual void Set(v8::Isolate* isolate,
616
                   v8::Local<v8::String> key,
617
                   v8::Local<v8::String> value) = 0;
618
  virtual int32_t Query(v8::Isolate* isolate,
619
                        v8::Local<v8::String> key) const = 0;
620
  virtual void Delete(v8::Isolate* isolate, v8::Local<v8::String> key) = 0;
621
  virtual v8::Local<v8::Array> Enumerate(v8::Isolate* isolate) const = 0;
622
623
  virtual std::shared_ptr<KVStore> Clone(v8::Isolate* isolate) const;
624
  virtual v8::Maybe<bool> AssignFromObject(v8::Local<v8::Context> context,
625
                                           v8::Local<v8::Object> entries);
626
627
  static std::shared_ptr<KVStore> CreateMapKVStore();
628
};
629
630
namespace per_process {
631
extern std::shared_ptr<KVStore> system_environment;
632
}
633
634
class AsyncHooks : public MemoryRetainer {
635
 public:
636
51
  SET_MEMORY_INFO_NAME(AsyncHooks)
637
51
  SET_SELF_SIZE(AsyncHooks)
638
  void MemoryInfo(MemoryTracker* tracker) const override;
639
640
  // Reason for both UidFields and Fields are that one is stored as a double*
641
  // and the other as a uint32_t*.
642
  enum Fields {
643
    kInit,
644
    kBefore,
645
    kAfter,
646
    kDestroy,
647
    kPromiseResolve,
648
    kTotals,
649
    kCheck,
650
    kStackLength,
651
    kFieldsCount,
652
  };
653
654
  enum UidFields {
655
    kExecutionAsyncId,
656
    kTriggerAsyncId,
657
    kAsyncIdCounter,
658
    kDefaultTriggerAsyncId,
659
    kUidFieldsCount,
660
  };
661
662
  inline AliasedUint32Array& fields();
663
  inline AliasedFloat64Array& async_id_fields();
664
  inline AliasedFloat64Array& async_ids_stack();
665
666
  inline v8::Local<v8::String> provider_string(int idx);
667
668
  inline void no_force_checks();
669
  inline Environment* env();
670
671
  inline void push_async_ids(double async_id, double trigger_async_id);
672
  inline bool pop_async_id(double async_id);
673
  inline void clear_async_id_stack();  // Used in fatal exceptions.
674
675
  AsyncHooks(const AsyncHooks&) = delete;
676
  AsyncHooks& operator=(const AsyncHooks&) = delete;
677
  AsyncHooks(AsyncHooks&&) = delete;
678
  AsyncHooks& operator=(AsyncHooks&&) = delete;
679
4777
  ~AsyncHooks() = default;
680
681
  // Used to set the kDefaultTriggerAsyncId in a scope. This is instead of
682
  // passing the trigger_async_id along with other constructor arguments.
683
  class DefaultTriggerAsyncIdScope {
684
   public:
685
    DefaultTriggerAsyncIdScope() = delete;
686
    explicit DefaultTriggerAsyncIdScope(Environment* env,
687
                                        double init_trigger_async_id);
688
    explicit DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap);
689
    ~DefaultTriggerAsyncIdScope();
690
691
    DefaultTriggerAsyncIdScope(const DefaultTriggerAsyncIdScope&) = delete;
692
    DefaultTriggerAsyncIdScope& operator=(const DefaultTriggerAsyncIdScope&) =
693
        delete;
694
    DefaultTriggerAsyncIdScope(DefaultTriggerAsyncIdScope&&) = delete;
695
    DefaultTriggerAsyncIdScope& operator=(DefaultTriggerAsyncIdScope&&) =
696
        delete;
697
698
   private:
699
    AsyncHooks* async_hooks_;
700
    double old_default_trigger_async_id_;
701
  };
702
703
 private:
704
  friend class Environment;  // So we can call the constructor.
705
  inline AsyncHooks();
706
  // Keep a list of all Persistent strings used for Provider types.
707
  std::array<v8::Eternal<v8::String>, AsyncWrap::PROVIDERS_LENGTH> providers_;
708
  // Stores the ids of the current execution context stack.
709
  AliasedFloat64Array async_ids_stack_;
710
  // Attached to a Uint32Array that tracks the number of active hooks for
711
  // each type.
712
  AliasedUint32Array fields_;
713
  // Attached to a Float64Array that tracks the state of async resources.
714
  AliasedFloat64Array async_id_fields_;
715
716
  void grow_async_ids_stack();
717
};
718
719
class AsyncCallbackScope {
720
 public:
721
  AsyncCallbackScope() = delete;
722
  explicit AsyncCallbackScope(Environment* env);
723
  ~AsyncCallbackScope();
724
  AsyncCallbackScope(const AsyncCallbackScope&) = delete;
725
  AsyncCallbackScope& operator=(const AsyncCallbackScope&) = delete;
726
  AsyncCallbackScope(AsyncCallbackScope&&) = delete;
727
  AsyncCallbackScope& operator=(AsyncCallbackScope&&) = delete;
728
729
 private:
730
  Environment* env_;
731
};
732
733
class ImmediateInfo : public MemoryRetainer {
734
 public:
735
  inline AliasedUint32Array& fields();
736
  inline uint32_t count() const;
737
  inline uint32_t ref_count() const;
738
  inline bool has_outstanding() const;
739
  inline void count_inc(uint32_t increment);
740
  inline void count_dec(uint32_t decrement);
741
  inline void ref_count_inc(uint32_t increment);
742
  inline void ref_count_dec(uint32_t decrement);
743
744
  ImmediateInfo(const ImmediateInfo&) = delete;
745
  ImmediateInfo& operator=(const ImmediateInfo&) = delete;
746
  ImmediateInfo(ImmediateInfo&&) = delete;
747
  ImmediateInfo& operator=(ImmediateInfo&&) = delete;
748
4777
  ~ImmediateInfo() = default;
749
750
51
  SET_MEMORY_INFO_NAME(ImmediateInfo)
751
51
  SET_SELF_SIZE(ImmediateInfo)
752
  void MemoryInfo(MemoryTracker* tracker) const override;
753
754
 private:
755
  friend class Environment;  // So we can call the constructor.
756
  inline explicit ImmediateInfo(v8::Isolate* isolate);
757
758
  enum Fields { kCount, kRefCount, kHasOutstanding, kFieldsCount };
759
760
  AliasedUint32Array fields_;
761
};
762
763
class TickInfo : public MemoryRetainer {
764
 public:
765
  inline AliasedUint8Array& fields();
766
  inline bool has_tick_scheduled() const;
767
  inline bool has_rejection_to_warn() const;
768
769
51
  SET_MEMORY_INFO_NAME(TickInfo)
770
51
  SET_SELF_SIZE(TickInfo)
771
  void MemoryInfo(MemoryTracker* tracker) const override;
772
773
  TickInfo(const TickInfo&) = delete;
774
  TickInfo& operator=(const TickInfo&) = delete;
775
  TickInfo(TickInfo&&) = delete;
776
  TickInfo& operator=(TickInfo&&) = delete;
777
4777
  ~TickInfo() = default;
778
779
 private:
780
  friend class Environment;  // So we can call the constructor.
781
  inline explicit TickInfo(v8::Isolate* isolate);
782
783
  enum Fields { kHasTickScheduled = 0, kHasRejectionToWarn, kFieldsCount };
784
785
  AliasedUint8Array fields_;
786
};
787
788
9552
class TrackingTraceStateObserver :
789
    public v8::TracingController::TraceStateObserver {
790
 public:
791
5181
  explicit TrackingTraceStateObserver(Environment* env) : env_(env) {}
792
793
102
  void OnTraceEnabled() override {
794
102
    UpdateTraceCategoryState();
795
102
  }
796
797
32
  void OnTraceDisabled() override {
798
32
    UpdateTraceCategoryState();
799
32
  }
800
801
 private:
802
  void UpdateTraceCategoryState();
803
804
  Environment* env_;
805
};
806
807
class ShouldNotAbortOnUncaughtScope {
808
 public:
809
  explicit inline ShouldNotAbortOnUncaughtScope(Environment* env);
810
  inline void Close();
811
  inline ~ShouldNotAbortOnUncaughtScope();
812
  ShouldNotAbortOnUncaughtScope(const ShouldNotAbortOnUncaughtScope&) = delete;
813
  ShouldNotAbortOnUncaughtScope& operator=(
814
      const ShouldNotAbortOnUncaughtScope&) = delete;
815
  ShouldNotAbortOnUncaughtScope(ShouldNotAbortOnUncaughtScope&&) = delete;
816
  ShouldNotAbortOnUncaughtScope& operator=(ShouldNotAbortOnUncaughtScope&&) =
817
      delete;
818
819
 private:
820
  Environment* env_;
821
};
822
823
class CleanupHookCallback {
824
 public:
825
1467965
  CleanupHookCallback(void (*fn)(void*),
826
                      void* arg,
827
                      uint64_t insertion_order_counter)
828
1467965
      : fn_(fn), arg_(arg), insertion_order_counter_(insertion_order_counter) {}
829
830
  // Only hashes `arg_`, since that is usually enough to identify the hook.
831
  struct Hash {
832
    inline size_t operator()(const CleanupHookCallback& cb) const;
833
  };
834
835
  // Compares by `fn_` and `arg_` being equal.
836
  struct Equal {
837
    inline bool operator()(const CleanupHookCallback& a,
838
                           const CleanupHookCallback& b) const;
839
  };
840
841
  inline BaseObject* GetBaseObject() const;
842
843
 private:
844
  friend class Environment;
845
  void (*fn_)(void*);
846
  void* arg_;
847
848
  // We keep track of the insertion order for these objects, so that we can
849
  // call the callbacks in reverse order when we are cleaning up.
850
  uint64_t insertion_order_counter_;
851
};
852
853
class Environment : public MemoryRetainer {
854
 public:
855
  Environment(const Environment&) = delete;
856
  Environment& operator=(const Environment&) = delete;
857
  Environment(Environment&&) = delete;
858
  Environment& operator=(Environment&&) = delete;
859
860
51
  SET_MEMORY_INFO_NAME(Environment)
861
862
  inline size_t SelfSize() const override;
863
86
  bool IsRootNode() const override { return true; }
864
  void MemoryInfo(MemoryTracker* tracker) const override;
865
866
  void CreateProperties();
867
  // Should be called before InitializeInspector()
868
  void InitializeDiagnostics();
869
#if HAVE_INSPECTOR && NODE_USE_V8_PLATFORM
870
  // If the environment is created for a worker, pass parent_handle and
871
  // the ownership if transferred into the Environment.
872
  int InitializeInspector(inspector::ParentInspectorHandle* parent_handle);
873
#endif
874
875
  v8::MaybeLocal<v8::Value> BootstrapInternalLoaders();
876
  v8::MaybeLocal<v8::Value> BootstrapNode();
877
  v8::MaybeLocal<v8::Value> RunBootstrapping();
878
879
  inline size_t async_callback_scope_depth() const;
880
  inline void PushAsyncCallbackScope();
881
  inline void PopAsyncCallbackScope();
882
883
  enum Flags {
884
    kNoFlags = 0,
885
    kIsMainThread = 1 << 0,
886
    kOwnsProcessState = 1 << 1,
887
    kOwnsInspector = 1 << 2,
888
  };
889
890
  static inline Environment* GetCurrent(v8::Isolate* isolate);
891
  static inline Environment* GetCurrent(v8::Local<v8::Context> context);
892
  static inline Environment* GetCurrent(
893
      const v8::FunctionCallbackInfo<v8::Value>& info);
894
895
  template <typename T>
896
  static inline Environment* GetCurrent(
897
      const v8::PropertyCallbackInfo<T>& info);
898
899
  static inline Environment* GetFromCallbackData(v8::Local<v8::Value> val);
900
901
  static uv_key_t thread_local_env;
902
  static inline Environment* GetThreadLocalEnv();
903
904
  Environment(IsolateData* isolate_data,
905
              v8::Local<v8::Context> context,
906
              const std::vector<std::string>& args,
907
              const std::vector<std::string>& exec_args,
908
              Flags flags = Flags(),
909
              uint64_t thread_id = kNoThreadId);
910
  ~Environment();
911
912
  void InitializeLibuv(bool start_profiler_idle_notifier);
913
  inline const std::vector<std::string>& exec_argv();
914
  inline const std::vector<std::string>& argv();
915
  const std::string& exec_path() const;
916
917
  typedef void (*HandleCleanupCb)(Environment* env,
918
                                  uv_handle_t* handle,
919
                                  void* arg);
920
  struct HandleCleanup {
921
    uv_handle_t* handle_;
922
    HandleCleanupCb cb_;
923
    void* arg_;
924
  };
925
926
  void RegisterHandleCleanups();
927
  void CleanupHandles();
928
  void Exit(int code);
929
  void ExitEnv();
930
931
  // Register clean-up cb to be called on environment destruction.
932
  inline void RegisterHandleCleanup(uv_handle_t* handle,
933
                                    HandleCleanupCb cb,
934
                                    void* arg);
935
936
  template <typename T, typename OnCloseCallback>
937
  inline void CloseHandle(T* handle, OnCloseCallback callback);
938
939
  inline void AssignToContext(v8::Local<v8::Context> context,
940
                              const ContextInfo& info);
941
942
  void StartProfilerIdleNotifier();
943
  void StopProfilerIdleNotifier();
944
  inline bool profiler_idle_notifier_started() const;
945
946
  inline v8::Isolate* isolate() const;
947
  inline uv_loop_t* event_loop() const;
948
  inline void TryLoadAddon(
949
      const char* filename,
950
      int flags,
951
      const std::function<bool(binding::DLib*)>& was_loaded);
952
953
  static inline Environment* from_timer_handle(uv_timer_t* handle);
954
  inline uv_timer_t* timer_handle();
955
956
  static inline Environment* from_immediate_check_handle(uv_check_t* handle);
957
  inline uv_check_t* immediate_check_handle();
958
  inline uv_idle_t* immediate_idle_handle();
959
960
  inline void IncreaseWaitingRequestCounter();
961
  inline void DecreaseWaitingRequestCounter();
962
963
  inline AsyncHooks* async_hooks();
964
  inline ImmediateInfo* immediate_info();
965
  inline TickInfo* tick_info();
966
  inline uint64_t timer_base() const;
967
  inline std::shared_ptr<KVStore> env_vars();
968
  inline void set_env_vars(std::shared_ptr<KVStore> env_vars);
969
970
  inline IsolateData* isolate_data() const;
971
972
  // Utilities that allocate memory using the Isolate's ArrayBuffer::Allocator.
973
  // In particular, using AllocateManaged() will provide a RAII-style object
974
  // with easy conversion to `Buffer` and `ArrayBuffer` objects.
975
  inline AllocatedBuffer AllocateManaged(size_t size, bool checked = true);
976
  inline char* Allocate(size_t size);
977
  inline char* AllocateUnchecked(size_t size);
978
  char* Reallocate(char* data, size_t old_size, size_t size);
979
  inline void Free(char* data, size_t size);
980
981
  inline bool printed_error() const;
982
  inline void set_printed_error(bool value);
983
984
  void PrintSyncTrace() const;
985
  inline void set_trace_sync_io(bool value);
986
987
  // This stores whether the --abort-on-uncaught-exception flag was passed
988
  // to Node.
989
  inline bool abort_on_uncaught_exception() const;
990
  inline void set_abort_on_uncaught_exception(bool value);
991
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
992
  // should abort the process or not if --abort-on-uncaught-exception was
993
  // passed to Node. If the flag was not passed, it is ignored.
994
  inline AliasedUint32Array& should_abort_on_uncaught_toggle();
995
996
  inline AliasedInt32Array& stream_base_state();
997
998
  // The necessary API for async_hooks.
999
  inline double new_async_id();
1000
  inline double execution_async_id();
1001
  inline double trigger_async_id();
1002
  inline double get_default_trigger_async_id();
1003
1004
  // List of id's that have been destroyed and need the destroy() cb called.
1005
  inline std::vector<double>* destroy_async_id_list();
1006
1007
  std::set<std::string> native_modules_with_cache;
1008
  std::set<std::string> native_modules_without_cache;
1009
1010
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
1011
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
1012
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
1013
      id_to_script_map;
1014
  std::unordered_map<uint32_t, contextify::CompiledFnEntry*> id_to_function_map;
1015
1016
  inline uint32_t get_next_module_id();
1017
  inline uint32_t get_next_script_id();
1018
  inline uint32_t get_next_function_id();
1019
1020
  std::unordered_map<std::string, const loader::PackageConfig>
1021
      package_json_cache;
1022
1023
  inline double* heap_statistics_buffer() const;
1024
  inline void set_heap_statistics_buffer(double* pointer);
1025
1026
  inline double* heap_space_statistics_buffer() const;
1027
  inline void set_heap_space_statistics_buffer(double* pointer);
1028
1029
  inline double* heap_code_statistics_buffer() const;
1030
  inline void set_heap_code_statistics_buffer(double* pointer);
1031
1032
  inline char* http_parser_buffer() const;
1033
  inline void set_http_parser_buffer(char* buffer);
1034
  inline bool http_parser_buffer_in_use() const;
1035
  inline void set_http_parser_buffer_in_use(bool in_use);
1036
1037
  inline http2::Http2State* http2_state() const;
1038
  inline void set_http2_state(std::unique_ptr<http2::Http2State> state);
1039
1040
  inline bool debug_enabled(DebugCategory category) const;
1041
  inline void set_debug_enabled(DebugCategory category, bool enabled);
1042
  void set_debug_categories(const std::string& cats, bool enabled);
1043
1044
  inline AliasedFloat64Array* fs_stats_field_array();
1045
  inline AliasedBigUint64Array* fs_stats_field_bigint_array();
1046
1047
  inline std::vector<std::unique_ptr<fs::FileHandleReadWrap>>&
1048
      file_handle_read_wrap_freelist();
1049
1050
  inline performance::performance_state* performance_state();
1051
  inline std::unordered_map<std::string, uint64_t>* performance_marks();
1052
1053
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
1054
                              int errorno,
1055
                              const char* syscall = nullptr,
1056
                              const char* message = nullptr,
1057
                              const char* path = nullptr,
1058
                              const char* dest = nullptr);
1059
1060
  // If this flag is set, calls into JS (if they would be observable
1061
  // from userland) must be avoided.  This flag does not indicate whether
1062
  // calling into JS is allowed from a VM perspective at this point.
1063
  inline bool can_call_into_js() const;
1064
  inline void set_can_call_into_js(bool can_call_into_js);
1065
1066
  inline bool has_run_bootstrapping_code() const;
1067
  inline void set_has_run_bootstrapping_code(bool has_run_bootstrapping_code);
1068
1069
  inline bool has_serialized_options() const;
1070
  inline void set_has_serialized_options(bool has_serialized_options);
1071
1072
  static uint64_t AllocateThreadId();
1073
  static constexpr uint64_t kNoThreadId = -1;
1074
1075
  inline bool is_main_thread() const;
1076
  inline bool owns_process_state() const;
1077
  inline bool owns_inspector() const;
1078
  inline uint64_t thread_id() const;
1079
  inline worker::Worker* worker_context() const;
1080
  inline void set_worker_context(worker::Worker* context);
1081
  inline void add_sub_worker_context(worker::Worker* context);
1082
  inline void remove_sub_worker_context(worker::Worker* context);
1083
  void stop_sub_worker_contexts();
1084
  inline bool is_stopping() const;
1085
1086
  inline void ThrowError(const char* errmsg);
1087
  inline void ThrowTypeError(const char* errmsg);
1088
  inline void ThrowRangeError(const char* errmsg);
1089
  inline void ThrowErrnoException(int errorno,
1090
                                  const char* syscall = nullptr,
1091
                                  const char* message = nullptr,
1092
                                  const char* path = nullptr);
1093
  inline void ThrowUVException(int errorno,
1094
                               const char* syscall = nullptr,
1095
                               const char* message = nullptr,
1096
                               const char* path = nullptr,
1097
                               const char* dest = nullptr);
1098
1099
  inline v8::Local<v8::FunctionTemplate>
1100
      NewFunctionTemplate(v8::FunctionCallback callback,
1101
                          v8::Local<v8::Signature> signature =
1102
                              v8::Local<v8::Signature>(),
1103
                          v8::ConstructorBehavior behavior =
1104
                              v8::ConstructorBehavior::kAllow,
1105
                          v8::SideEffectType side_effect =
1106
                              v8::SideEffectType::kHasSideEffect);
1107
1108
  // Convenience methods for NewFunctionTemplate().
1109
  inline void SetMethod(v8::Local<v8::Object> that,
1110
                        const char* name,
1111
                        v8::FunctionCallback callback);
1112
1113
  inline void SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1114
                             const char* name,
1115
                             v8::FunctionCallback callback);
1116
1117
  // Safe variants denote the function has no side effects.
1118
  inline void SetMethodNoSideEffect(v8::Local<v8::Object> that,
1119
                                    const char* name,
1120
                                    v8::FunctionCallback callback);
1121
  inline void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that,
1122
                                         const char* name,
1123
                                         v8::FunctionCallback callback);
1124
1125
  void BeforeExit(void (*cb)(void* arg), void* arg);
1126
  void RunBeforeExitCallbacks();
1127
  void AtExit(void (*cb)(void* arg), void* arg);
1128
  void RunAtExitCallbacks();
1129
1130
  // Strings and private symbols are shared across shared contexts
1131
  // The getters simply proxy to the per-isolate primitive.
1132
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1133
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1134
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1135
#define V(TypeName, PropertyName)                                             \
1136
  inline v8::Local<TypeName> PropertyName() const;
1137
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1138
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1139
  PER_ISOLATE_STRING_PROPERTIES(VS)
1140
#undef V
1141
#undef VS
1142
#undef VY
1143
#undef VP
1144
1145
#define V(PropertyName, TypeName)                                             \
1146
  inline v8::Local<TypeName> PropertyName() const;                            \
1147
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
1148
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1149
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1150
#undef V
1151
1152
  inline v8::Local<v8::Context> context() const;
1153
1154
#if HAVE_INSPECTOR
1155
301517
  inline inspector::Agent* inspector_agent() const {
1156
301517
    return inspector_agent_.get();
1157
  }
1158
1159
  inline bool is_in_inspector_console_call() const;
1160
  inline void set_is_in_inspector_console_call(bool value);
1161
#endif
1162
1163
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
1164
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
1165
1166
88374
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
1167
117629
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
1168
1169
1
  inline bool EmitProcessEnvWarning() {
1170
1
    bool current_value = emit_env_nonstring_warning_;
1171
1
    emit_env_nonstring_warning_ = false;
1172
1
    return current_value;
1173
  }
1174
1175
1
  inline bool EmitErrNameWarning() {
1176
1
    bool current_value = emit_err_name_warning_;
1177
1
    emit_err_name_warning_ = false;
1178
1
    return current_value;
1179
  }
1180
1181
  // cb will be called as cb(env) on the next event loop iteration.
1182
  // keep_alive will be kept alive between now and after the callback has run.
1183
  template <typename Fn>
1184
  inline void SetImmediate(Fn&& cb,
1185
                           v8::Local<v8::Object> keep_alive =
1186
                               v8::Local<v8::Object>());
1187
  template <typename Fn>
1188
  inline void SetUnrefImmediate(Fn&& cb,
1189
                                v8::Local<v8::Object> keep_alive =
1190
                                    v8::Local<v8::Object>());
1191
  // This needs to be available for the JS-land setImmediate().
1192
  void ToggleImmediateRef(bool ref);
1193
1194
  inline void PushShouldNotAbortOnUncaughtScope();
1195
  inline void PopShouldNotAbortOnUncaughtScope();
1196
  inline bool inside_should_not_abort_on_uncaught_scope() const;
1197
1198
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
1199
1200
  v8::Local<v8::Value> GetNow();
1201
  void ScheduleTimer(int64_t duration);
1202
  void ToggleTimerRef(bool ref);
1203
1204
  inline void AddCleanupHook(void (*fn)(void*), void* arg);
1205
  inline void RemoveCleanupHook(void (*fn)(void*), void* arg);
1206
  void RunCleanup();
1207
1208
  static void BuildEmbedderGraph(v8::Isolate* isolate,
1209
                                 v8::EmbedderGraph* graph,
1210
                                 void* data);
1211
1212
  inline std::shared_ptr<EnvironmentOptions> options();
1213
  inline std::shared_ptr<HostPort> inspector_host_port();
1214
1215
20811
  inline AsyncRequest* thread_stopper() { return &thread_stopper_; }
1216
1217
#if HAVE_INSPECTOR
1218
  void set_coverage_connection(
1219
      std::unique_ptr<profiler::V8CoverageConnection> connection);
1220
  profiler::V8CoverageConnection* coverage_connection();
1221
1222
  inline void set_coverage_directory(const char* directory);
1223
  inline const std::string& coverage_directory() const;
1224
1225
  void set_cpu_profiler_connection(
1226
      std::unique_ptr<profiler::V8CpuProfilerConnection> connection);
1227
  profiler::V8CpuProfilerConnection* cpu_profiler_connection();
1228
1229
  inline void set_cpu_prof_name(const std::string& name);
1230
  inline const std::string& cpu_prof_name() const;
1231
1232
  inline void set_cpu_prof_interval(uint64_t interval);
1233
  inline uint64_t cpu_prof_interval() const;
1234
1235
  inline void set_cpu_prof_dir(const std::string& dir);
1236
  inline const std::string& cpu_prof_dir() const;
1237
1238
  void set_heap_profiler_connection(
1239
      std::unique_ptr<profiler::V8HeapProfilerConnection> connection);
1240
  profiler::V8HeapProfilerConnection* heap_profiler_connection();
1241
1242
  inline void set_heap_prof_name(const std::string& name);
1243
  inline const std::string& heap_prof_name() const;
1244
1245
  inline void set_heap_prof_dir(const std::string& dir);
1246
  inline const std::string& heap_prof_dir() const;
1247
1248
  inline void set_heap_prof_interval(uint64_t interval);
1249
  inline uint64_t heap_prof_interval() const;
1250
1251
#endif  // HAVE_INSPECTOR
1252
1253
 private:
1254
  template <typename Fn>
1255
  inline void CreateImmediate(Fn&& cb,
1256
                              v8::Local<v8::Object> keep_alive,
1257
                              bool ref);
1258
1259
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1260
                         const char* errmsg);
1261
1262
  std::list<binding::DLib> loaded_addons_;
1263
  v8::Isolate* const isolate_;
1264
  IsolateData* const isolate_data_;
1265
  uv_timer_t timer_handle_;
1266
  uv_check_t immediate_check_handle_;
1267
  uv_idle_t immediate_idle_handle_;
1268
  uv_prepare_t idle_prepare_handle_;
1269
  uv_check_t idle_check_handle_;
1270
  bool profiler_idle_notifier_started_ = false;
1271
1272
  AsyncHooks async_hooks_;
1273
  ImmediateInfo immediate_info_;
1274
  TickInfo tick_info_;
1275
  const uint64_t timer_base_;
1276
  std::shared_ptr<KVStore> env_vars_;
1277
  bool printed_error_ = false;
1278
  bool trace_sync_io_ = false;
1279
  bool emit_env_nonstring_warning_ = true;
1280
  bool emit_err_name_warning_ = true;
1281
  size_t async_callback_scope_depth_ = 0;
1282
  std::vector<double> destroy_async_id_list_;
1283
1284
#if HAVE_INSPECTOR
1285
  std::unique_ptr<profiler::V8CoverageConnection> coverage_connection_;
1286
  std::unique_ptr<profiler::V8CpuProfilerConnection> cpu_profiler_connection_;
1287
  std::string coverage_directory_;
1288
  std::string cpu_prof_dir_;
1289
  std::string cpu_prof_name_;
1290
  uint64_t cpu_prof_interval_;
1291
  std::unique_ptr<profiler::V8HeapProfilerConnection> heap_profiler_connection_;
1292
  std::string heap_prof_dir_;
1293
  std::string heap_prof_name_;
1294
  uint64_t heap_prof_interval_;
1295
#endif  // HAVE_INSPECTOR
1296
1297
  std::shared_ptr<EnvironmentOptions> options_;
1298
  // options_ contains debug options parsed from CLI arguments,
1299
  // while inspector_host_port_ stores the actual inspector host
1300
  // and port being used. For example the port is -1 by default
1301
  // and can be specified as 0 (meaning any port allocated when the
1302
  // server starts listening), but when the inspector server starts
1303
  // the inspector_host_port_->port() will be the actual port being
1304
  // used.
1305
  std::shared_ptr<HostPort> inspector_host_port_;
1306
  std::vector<std::string> exec_argv_;
1307
  std::vector<std::string> argv_;
1308
  std::string exec_path_;
1309
1310
  uint32_t module_id_counter_ = 0;
1311
  uint32_t script_id_counter_ = 0;
1312
  uint32_t function_id_counter_ = 0;
1313
1314
  AliasedUint32Array should_abort_on_uncaught_toggle_;
1315
  int should_not_abort_scope_counter_ = 0;
1316
1317
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1318
1319
  AliasedInt32Array stream_base_state_;
1320
1321
  std::unique_ptr<performance::performance_state> performance_state_;
1322
  std::unordered_map<std::string, uint64_t> performance_marks_;
1323
1324
  bool has_run_bootstrapping_code_ = false;
1325
  bool has_serialized_options_ = false;
1326
1327
  bool can_call_into_js_ = true;
1328
  Flags flags_;
1329
  uint64_t thread_id_;
1330
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1331
1332
  static void* const kNodeContextTagPtr;
1333
  static int const kNodeContextTag;
1334
1335
#if HAVE_INSPECTOR
1336
  std::unique_ptr<inspector::Agent> inspector_agent_;
1337
  bool is_in_inspector_console_call_ = false;
1338
#endif
1339
1340
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1341
  // the start of the class because it is used by
1342
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1343
  // symbols for Environment, which assumes that the position of members in
1344
  // memory are predictable. For more information please refer to
1345
  // `doc/guides/node-postmortem-support.md`
1346
  friend int GenDebugSymbols();
1347
  HandleWrapQueue handle_wrap_queue_;
1348
  ReqWrapQueue req_wrap_queue_;
1349
  std::list<HandleCleanup> handle_cleanup_queue_;
1350
  int handle_cleanup_waiting_ = 0;
1351
  int request_waiting_ = 0;
1352
1353
  double* heap_statistics_buffer_ = nullptr;
1354
  double* heap_space_statistics_buffer_ = nullptr;
1355
  double* heap_code_statistics_buffer_ = nullptr;
1356
1357
  char* http_parser_buffer_ = nullptr;
1358
  bool http_parser_buffer_in_use_ = false;
1359
  std::unique_ptr<http2::Http2State> http2_state_;
1360
1361
  bool debug_enabled_[static_cast<int>(DebugCategory::CATEGORY_COUNT)] = {0};
1362
1363
  AliasedFloat64Array fs_stats_field_array_;
1364
  AliasedBigUint64Array fs_stats_field_bigint_array_;
1365
1366
  std::vector<std::unique_ptr<fs::FileHandleReadWrap>>
1367
      file_handle_read_wrap_freelist_;
1368
1369
  worker::Worker* worker_context_ = nullptr;
1370
1371
  static void RunTimers(uv_timer_t* handle);
1372
1373
  struct ExitCallback {
1374
    void (*cb_)(void* arg);
1375
    void* arg_;
1376
  };
1377
  std::list<ExitCallback> before_exit_functions_;
1378
1379
  std::list<ExitCallback> at_exit_functions_;
1380
1381
  class NativeImmediateCallback {
1382
   public:
1383
    explicit inline NativeImmediateCallback(bool refed);
1384
1385
54854
    virtual ~NativeImmediateCallback() = default;
1386
    virtual void Call(Environment* env) = 0;
1387
1388
    inline bool is_refed() const;
1389
    inline std::unique_ptr<NativeImmediateCallback> get_next();
1390
    inline void set_next(std::unique_ptr<NativeImmediateCallback> next);
1391
1392
   private:
1393
    bool refed_;
1394
    std::unique_ptr<NativeImmediateCallback> next_;
1395
  };
1396
1397
  template <typename Fn>
1398



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