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: 45 45 100.0 %
Date: 2019-05-05 22:32:45 Branches: 5 10 50.0 %

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