GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 653 666 98.0 %
Date: 2022-01-05 04:13:52 Branches: 114 144 79.2 %

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_INL_H_
23
#define SRC_ENV_INL_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
#include "aliased_buffer.h"
28
#include "allocated_buffer-inl.h"
29
#include "callback_queue-inl.h"
30
#include "env.h"
31
#include "node.h"
32
#include "node_context_data.h"
33
#include "node_perf_common.h"
34
#include "util-inl.h"
35
#include "uv.h"
36
#include "v8-fast-api-calls.h"
37
#include "v8.h"
38
39
#include <cstddef>
40
#include <cstdint>
41
42
#include <utility>
43
44
namespace node {
45
46
inline v8::Isolate* IsolateData::isolate() const {
47
  return isolate_;
48
}
49
50
1000693
inline uv_loop_t* IsolateData::event_loop() const {
51
1000693
  return event_loop_;
52
}
53
54
103360
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
55
103360
  return node_allocator_;
56
}
57
58
56160
inline MultiIsolatePlatform* IsolateData::platform() const {
59
56160
  return platform_;
60
}
61
62
580
inline void IsolateData::set_worker_context(worker::Worker* context) {
63
580
  CHECK_NULL(worker_context_);  // Should be set only once.
64
580
  worker_context_ = context;
65
580
}
66
67
14122
inline worker::Worker* IsolateData::worker_context() const {
68
14122
  return worker_context_;
69
}
70
71
205116
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
72
205116
  return async_wrap_providers_[index].Get(isolate_);
73
}
74
75
2584860
inline AliasedUint32Array& AsyncHooks::fields() {
76
2584860
  return fields_;
77
}
78
79
1639344
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
80
1639344
  return async_id_fields_;
81
}
82
83
620
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
84
620
  return async_ids_stack_;
85
}
86
87
800769
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
88
800769
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
89
620
    js_execution_async_resources_.Reset(
90
1240
        env()->isolate(), v8::Array::New(env()->isolate()));
91
  }
92
800769
  return PersistentToLocal::Strong(js_execution_async_resources_);
93
}
94
95
2401
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
96
2401
  if (i >= native_execution_async_resources_.size()) return {};
97
2401
  return native_execution_async_resources_[i];
98
}
99
100
16844
inline void AsyncHooks::SetJSPromiseHooks(v8::Local<v8::Function> init,
101
                                          v8::Local<v8::Function> before,
102
                                          v8::Local<v8::Function> after,
103
                                          v8::Local<v8::Function> resolve) {
104
16844
  js_promise_hooks_[0].Reset(env()->isolate(), init);
105
16844
  js_promise_hooks_[1].Reset(env()->isolate(), before);
106
16844
  js_promise_hooks_[2].Reset(env()->isolate(), after);
107
16844
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
108
34012
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
109
17168
    if (it->IsEmpty()) {
110
      it = contexts_.erase(it);
111
      it--;
112
      continue;
113
    }
114
34336
    PersistentToLocal::Weak(env()->isolate(), *it)
115
17168
        ->SetPromiseHooks(init, before, after, resolve);
116
  }
117
16844
}
118
119
204768
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
120
204768
  return env()->isolate_data()->async_wrap_provider(idx);
121
}
122
123
1
inline void AsyncHooks::no_force_checks() {
124
1
  fields_[kCheck] -= 1;
125
1
}
126
127
410677
inline Environment* AsyncHooks::env() {
128
410677
  return Environment::ForAsyncHooks(this);
129
}
130
131
// Remember to keep this code aligned with pushAsyncContext() in JS.
132
774369
inline void AsyncHooks::push_async_context(double async_id,
133
                                           double trigger_async_id,
134
                                           v8::Local<v8::Object> resource) {
135
  // Since async_hooks is experimental, do only perform the check
136
  // when async_hooks is enabled.
137
774369
  if (fields_[kCheck] > 0) {
138
774366
    CHECK_GE(async_id, -1);
139
774366
    CHECK_GE(trigger_async_id, -1);
140
  }
141
142
774369
  uint32_t offset = fields_[kStackLength];
143
774369
  if (offset * 2 >= async_ids_stack_.Length())
144
4
    grow_async_ids_stack();
145
774369
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
146
774369
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
147
774369
  fields_[kStackLength] += 1;
148
774369
  async_id_fields_[kExecutionAsyncId] = async_id;
149
774369
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
150
151
#ifdef DEBUG
152
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
153
    CHECK(native_execution_async_resources_[i].IsEmpty());
154
#endif
155
156
  // When this call comes from JS (as a way of increasing the stack size),
157
  // `resource` will be empty, because JS caches these values anyway.
158
774369
  if (!resource.IsEmpty()) {
159
774365
    native_execution_async_resources_.resize(offset + 1);
160
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
161
774365
    native_execution_async_resources_[offset] = resource;
162
  }
163
774369
}
164
165
// Remember to keep this code aligned with popAsyncContext() in JS.
166
774003
inline bool AsyncHooks::pop_async_context(double async_id) {
167
  // In case of an exception then this may have already been reset, if the
168
  // stack was multiple MakeCallback()'s deep.
169
774003
  if (UNLIKELY(fields_[kStackLength] == 0)) return false;
170
171
  // Ask for the async_id to be restored as a check that the stack
172
  // hasn't been corrupted.
173
  // Since async_hooks is experimental, do only perform the check
174
  // when async_hooks is enabled.
175
1545927
  if (UNLIKELY(fields_[kCheck] > 0 &&
176

1545927
               async_id_fields_[kExecutionAsyncId] != async_id)) {
177
4
    FailWithCorruptedAsyncStack(async_id);
178
  }
179
180
772961
  uint32_t offset = fields_[kStackLength] - 1;
181
772961
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
182
772961
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
183
772961
  fields_[kStackLength] = offset;
184
185
1545922
  if (LIKELY(offset < native_execution_async_resources_.size() &&
186

1545922
             !native_execution_async_resources_[offset].IsEmpty())) {
187
#ifdef DEBUG
188
    for (uint32_t i = offset + 1;
189
         i < native_execution_async_resources_.size();
190
         i++) {
191
      CHECK(native_execution_async_resources_[i].IsEmpty());
192
    }
193
#endif
194
772961
    native_execution_async_resources_.resize(offset);
195
772961
    if (native_execution_async_resources_.size() <
196

992108
            native_execution_async_resources_.capacity() / 2 &&
197
219147
        native_execution_async_resources_.size() > 16) {
198
      native_execution_async_resources_.shrink_to_fit();
199
    }
200
  }
201
202
1545922
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
203
27188
    v8::HandleScope handle_scope(env()->isolate());
204
54376
    USE(js_execution_async_resources()->Set(
205
        env()->context(),
206
        env()->length_string(),
207
108752
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
208
  }
209
210
772961
  return fields_[kStackLength] > 0;
211
}
212
213
1984
void AsyncHooks::clear_async_id_stack() {
214
1984
  v8::Isolate* isolate = env()->isolate();
215
1984
  v8::HandleScope handle_scope(isolate);
216
1984
  if (!js_execution_async_resources_.IsEmpty()) {
217
2728
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
218
        env()->context(),
219
        env()->length_string(),
220
5456
        v8::Integer::NewFromUnsigned(isolate, 0)));
221
  }
222
1984
  native_execution_async_resources_.clear();
223
1984
  native_execution_async_resources_.shrink_to_fit();
224
225
1984
  async_id_fields_[kExecutionAsyncId] = 0;
226
1984
  async_id_fields_[kTriggerAsyncId] = 0;
227
1984
  fields_[kStackLength] = 0;
228
1984
}
229
230
6131
inline void AsyncHooks::AddContext(v8::Local<v8::Context> ctx) {
231
24128
  ctx->SetPromiseHooks(
232
6131
    js_promise_hooks_[0].IsEmpty() ?
233
6131
      v8::Local<v8::Function>() :
234
198
      PersistentToLocal::Strong(js_promise_hooks_[0]),
235
6131
    js_promise_hooks_[1].IsEmpty() ?
236
6131
      v8::Local<v8::Function>() :
237
198
      PersistentToLocal::Strong(js_promise_hooks_[1]),
238
6131
    js_promise_hooks_[2].IsEmpty() ?
239
6131
      v8::Local<v8::Function>() :
240
198
      PersistentToLocal::Strong(js_promise_hooks_[2]),
241
6131
    js_promise_hooks_[3].IsEmpty() ?
242
6131
      v8::Local<v8::Function>() :
243
      PersistentToLocal::Strong(js_promise_hooks_[3]));
244
245
6131
  size_t id = contexts_.size();
246
6131
  contexts_.resize(id + 1);
247
6131
  contexts_[id].Reset(env()->isolate(), ctx);
248
6131
  contexts_[id].SetWeak();
249
6131
}
250
251
508
inline void AsyncHooks::RemoveContext(v8::Local<v8::Context> ctx) {
252
508
  v8::Isolate* isolate = env()->isolate();
253
1016
  v8::HandleScope handle_scope(isolate);
254
4236
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
255
3728
    if (it->IsEmpty()) {
256
61
      it = contexts_.erase(it);
257
61
      it--;
258
61
      continue;
259
    }
260
    v8::Local<v8::Context> saved_context =
261
3667
      PersistentToLocal::Weak(isolate, *it);
262
3667
    if (saved_context == ctx) {
263
      it->Reset();
264
      contexts_.erase(it);
265
      break;
266
    }
267
  }
268
508
}
269
270
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
271
// async_wrap-inl.h to avoid a circular dependency.
272
273
239271
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
274
239271
    Environment* env, double default_trigger_async_id)
275
239271
    : async_hooks_(env->async_hooks()) {
276
239271
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
277
239271
    CHECK_GE(default_trigger_async_id, 0);
278
  }
279
280
239271
  old_default_trigger_async_id_ =
281
239271
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
282
239271
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
283
239271
    default_trigger_async_id;
284
239271
}
285
286
478540
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
287
239270
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
288
239270
    old_default_trigger_async_id_;
289
239270
}
290
291
410677
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
292
410677
  return ContainerOf(&Environment::async_hooks_, hooks);
293
}
294
295
774025
inline size_t Environment::async_callback_scope_depth() const {
296
774025
  return async_callback_scope_depth_;
297
}
298
299
786061
inline void Environment::PushAsyncCallbackScope() {
300
786061
  async_callback_scope_depth_++;
301
786061
}
302
303
785568
inline void Environment::PopAsyncCallbackScope() {
304
785568
  async_callback_scope_depth_--;
305
785568
}
306
307
620
inline AliasedUint32Array& ImmediateInfo::fields() {
308
620
  return fields_;
309
}
310
311
176227
inline uint32_t ImmediateInfo::count() const {
312
176227
  return fields_[kCount];
313
}
314
315
265456
inline uint32_t ImmediateInfo::ref_count() const {
316
265456
  return fields_[kRefCount];
317
}
318
319
41728
inline bool ImmediateInfo::has_outstanding() const {
320
41728
  return fields_[kHasOutstanding] == 1;
321
}
322
323
33258
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
324
33258
  fields_[kRefCount] += increment;
325
33258
}
326
327
191410
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
328
191410
  fields_[kRefCount] -= decrement;
329
191410
}
330
331
620
inline AliasedUint8Array& TickInfo::fields() {
332
620
  return fields_;
333
}
334
335
1381202
inline bool TickInfo::has_tick_scheduled() const {
336
1381202
  return fields_[kHasTickScheduled] == 1;
337
}
338
339
507249
inline bool TickInfo::has_rejection_to_warn() const {
340
507249
  return fields_[kHasRejectionToWarn] == 1;
341
}
342
343
6131
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
344
                                         const ContextInfo& info) {
345
6131
  context->SetAlignedPointerInEmbedderData(
346
      ContextEmbedderIndex::kEnvironment, this);
347
  // Used by Environment::GetCurrent to know that we are on a node context.
348
6131
  context->SetAlignedPointerInEmbedderData(
349
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
350
  // Used to retrieve bindings
351
12262
  context->SetAlignedPointerInEmbedderData(
352
6131
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
353
354
#if HAVE_INSPECTOR
355
6131
  inspector_agent()->ContextCreated(context, info);
356
#endif  // HAVE_INSPECTOR
357
358
6131
  this->async_hooks()->AddContext(context);
359
6131
}
360
361
49871
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
362
49871
  if (UNLIKELY(!isolate->InContext())) return nullptr;
363
97476
  v8::HandleScope handle_scope(isolate);
364
48738
  return GetCurrent(isolate->GetCurrentContext());
365
}
366
367
5411436
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
368
5411436
  if (UNLIKELY(context.IsEmpty())) {
369
1
    return nullptr;
370
  }
371
5411435
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
372
5411435
               ContextEmbedderIndex::kContextTag)) {
373
11
    return nullptr;
374
  }
375
5411424
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
376
                   ContextEmbedderIndex::kContextTag) !=
377
5411424
               Environment::kNodeContextTagPtr)) {
378
    return nullptr;
379
  }
380
  return static_cast<Environment*>(
381
5411424
      context->GetAlignedPointerFromEmbedderData(
382
5411424
          ContextEmbedderIndex::kEnvironment));
383
}
384
385
3656131
inline Environment* Environment::GetCurrent(
386
    const v8::FunctionCallbackInfo<v8::Value>& info) {
387
3656131
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
388
}
389
390
template <typename T>
391
2620778
inline Environment* Environment::GetCurrent(
392
    const v8::PropertyCallbackInfo<T>& info) {
393
2620778
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
394
}
395
396
template <typename T, typename U>
397
inline T* Environment::GetBindingData(const v8::PropertyCallbackInfo<U>& info) {
398
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
399
}
400
401
template <typename T>
402
788072
inline T* Environment::GetBindingData(
403
    const v8::FunctionCallbackInfo<v8::Value>& info) {
404
788072
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
405
}
406
407
template <typename T>
408
788074
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
409
  BindingDataStore* map = static_cast<BindingDataStore*>(
410
788074
      context->GetAlignedPointerFromEmbedderData(
411
          ContextEmbedderIndex::kBindingListIndex));
412
  DCHECK_NOT_NULL(map);
413
788074
  auto it = map->find(T::type_name);
414
788074
  if (UNLIKELY(it == map->end())) return nullptr;
415
788074
  T* result = static_cast<T*>(it->second.get());
416
  DCHECK_NOT_NULL(result);
417
  DCHECK_EQ(result->env(), GetCurrent(context));
418
788074
  return result;
419
}
420
421
template <typename T>
422
23143
inline T* Environment::AddBindingData(
423
    v8::Local<v8::Context> context,
424
    v8::Local<v8::Object> target) {
425
  DCHECK_EQ(GetCurrent(context), this);
426
  // This won't compile if T is not a BaseObject subclass.
427
46286
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
428
  BindingDataStore* map = static_cast<BindingDataStore*>(
429
23143
      context->GetAlignedPointerFromEmbedderData(
430
          ContextEmbedderIndex::kBindingListIndex));
431
  DCHECK_NOT_NULL(map);
432
23143
  auto result = map->emplace(T::type_name, item);
433
23143
  CHECK(result.second);
434
  DCHECK_EQ(GetBindingData<T>(context), item.get());
435
23143
  return item.get();
436
}
437
438
23210807
inline v8::Isolate* Environment::isolate() const {
439
23210807
  return isolate_;
440
}
441
442
7034
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
443
7034
  return ContainerOf(&Environment::timer_handle_, handle);
444
}
445
446
27048
inline uv_timer_t* Environment::timer_handle() {
447
27048
  return &timer_handle_;
448
}
449
450
176227
inline Environment* Environment::from_immediate_check_handle(
451
    uv_check_t* handle) {
452
176227
  return ContainerOf(&Environment::immediate_check_handle_, handle);
453
}
454
455
21956
inline uv_check_t* Environment::immediate_check_handle() {
456
21956
  return &immediate_check_handle_;
457
}
458
459
219732
inline uv_idle_t* Environment::immediate_idle_handle() {
460
219732
  return &immediate_idle_handle_;
461
}
462
463
32934
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
464
                                               HandleCleanupCb cb,
465
                                               void* arg) {
466
32934
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
467
32934
}
468
469
template <typename T, typename OnCloseCallback>
470
34606
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
471
34454
  handle_cleanup_waiting_++;
472
  static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle");
473
  static_assert(offsetof(T, data) == offsetof(uv_handle_t, data),
474
                "T is a libuv handle");
475
  static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb),
476
                "T is a libuv handle");
477
  struct CloseData {
478
    Environment* env;
479
    OnCloseCallback callback;
480
    void* original_data;
481
  };
482
34530
  handle->data = new CloseData { this, callback, handle->data };
483
34834
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
484
68908
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
485
34530
    data->env->handle_cleanup_waiting_--;
486
34530
    handle->data = data->original_data;
487
34530
    data->callback(reinterpret_cast<T*>(handle));
488
  });
489
34530
}
490
491
89827
void Environment::IncreaseWaitingRequestCounter() {
492
89827
  request_waiting_++;
493
89827
}
494
495
89811
void Environment::DecreaseWaitingRequestCounter() {
496
89811
  request_waiting_--;
497
89811
  CHECK_GE(request_waiting_, 0);
498
89811
}
499
500
995171
inline uv_loop_t* Environment::event_loop() const {
501
995171
  return isolate_data()->event_loop();
502
}
503
504
164
inline void Environment::TryLoadAddon(
505
    const char* filename,
506
    int flags,
507
    const std::function<bool(binding::DLib*)>& was_loaded) {
508
164
  loaded_addons_.emplace_back(filename, flags);
509
164
  if (!was_loaded(&loaded_addons_.back())) {
510
8
    loaded_addons_.pop_back();
511
  }
512
164
}
513
514
#if HAVE_INSPECTOR
515
44297
inline bool Environment::is_in_inspector_console_call() const {
516
44297
  return is_in_inspector_console_call_;
517
}
518
519
88592
inline void Environment::set_is_in_inspector_console_call(bool value) {
520
88592
  is_in_inspector_console_call_ = value;
521
88592
}
522
#endif
523
524
5778276
inline AsyncHooks* Environment::async_hooks() {
525
5778276
  return &async_hooks_;
526
}
527
528
708699
inline ImmediateInfo* Environment::immediate_info() {
529
708699
  return &immediate_info_;
530
}
531
532
691242
inline TickInfo* Environment::tick_info() {
533
691242
  return &tick_info_;
534
}
535
536
60117
inline uint64_t Environment::timer_base() const {
537
60117
  return timer_base_;
538
}
539
540
1325372
inline std::shared_ptr<KVStore> Environment::env_vars() {
541
1325372
  return env_vars_;
542
}
543
544
6086
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
545
6086
  env_vars_ = env_vars;
546
6086
}
547
548
17
inline bool Environment::printed_error() const {
549
17
  return printed_error_;
550
}
551
552
17
inline void Environment::set_printed_error(bool value) {
553
17
  printed_error_ = value;
554
17
}
555
556
10033
inline void Environment::set_trace_sync_io(bool value) {
557
10033
  trace_sync_io_ = value;
558
10033
}
559
560
89
inline bool Environment::abort_on_uncaught_exception() const {
561
89
  return options_->abort_on_uncaught_exception;
562
}
563
564
inline void Environment::set_force_context_aware(bool value) {
565
  options_->force_context_aware = value;
566
}
567
568
41
inline bool Environment::force_context_aware() const {
569
41
  return options_->force_context_aware;
570
}
571
572
568
inline void Environment::set_abort_on_uncaught_exception(bool value) {
573
568
  options_->abort_on_uncaught_exception = value;
574
568
}
575
576
650
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
577
650
  return should_abort_on_uncaught_toggle_;
578
}
579
580
300568
inline AliasedInt32Array& Environment::stream_base_state() {
581
300568
  return stream_base_state_;
582
}
583
584
45876
inline uint32_t Environment::get_next_module_id() {
585
45876
  return module_id_counter_++;
586
}
587
3158
inline uint32_t Environment::get_next_script_id() {
588
3158
  return script_id_counter_++;
589
}
590
38045
inline uint32_t Environment::get_next_function_id() {
591
38045
  return function_id_counter_++;
592
}
593
594
94511
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
595
94511
    Environment* env)
596
94511
    : env_(env) {
597
94511
  env_->PushShouldNotAbortOnUncaughtScope();
598
94511
}
599
600
189018
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
601
94509
  Close();
602
94509
}
603
604
94701
void ShouldNotAbortOnUncaughtScope::Close() {
605
94701
  if (env_ != nullptr) {
606
94509
    env_->PopShouldNotAbortOnUncaughtScope();
607
94509
    env_ = nullptr;
608
  }
609
94701
}
610
611
94511
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
612
94511
  should_not_abort_scope_counter_++;
613
94511
}
614
615
94509
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
616
94509
  should_not_abort_scope_counter_--;
617
94509
}
618
619
1
inline bool Environment::inside_should_not_abort_on_uncaught_scope() const {
620
1
  return should_not_abort_scope_counter_ > 0;
621
}
622
623
405392
inline std::vector<double>* Environment::destroy_async_id_list() {
624
405392
  return &destroy_async_id_list_;
625
}
626
627
205321
inline double Environment::new_async_id() {
628
205321
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
629
205321
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
630
}
631
632
236960
inline double Environment::execution_async_id() {
633
236960
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
634
}
635
636
67992
inline double Environment::trigger_async_id() {
637
67992
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
638
}
639
640
205318
inline double Environment::get_default_trigger_async_id() {
641
  double default_trigger_async_id =
642
205318
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
643
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
644
205318
  if (default_trigger_async_id < 0)
645
168940
    default_trigger_async_id = execution_async_id();
646
205318
  return default_trigger_async_id;
647
}
648
649
61718
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
650
61718
  return options_;
651
}
652
653
15795
inline const std::vector<std::string>& Environment::argv() {
654
15795
  return argv_;
655
}
656
657
6039
inline const std::vector<std::string>& Environment::exec_argv() {
658
6039
  return exec_argv_;
659
}
660
661
10978
inline const std::string& Environment::exec_path() const {
662
10978
  return exec_path_;
663
}
664
665
11
inline std::string Environment::GetCwd() {
666
  char cwd[PATH_MAX_BYTES];
667
11
  size_t size = PATH_MAX_BYTES;
668
11
  const int err = uv_cwd(cwd, &size);
669
670
11
  if (err == 0) {
671
11
    CHECK_GT(size, 0);
672
11
    return cwd;
673
  }
674
675
  // This can fail if the cwd is deleted. In that case, fall back to
676
  // exec_path.
677
  const std::string& exec_path = exec_path_;
678
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
679
}
680
681
#if HAVE_INSPECTOR
682
5484
inline void Environment::set_coverage_directory(const char* dir) {
683
5484
  coverage_directory_ = std::string(dir);
684
5484
}
685
686
5507
inline void Environment::set_coverage_connection(
687
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
688
5507
  CHECK_NULL(coverage_connection_);
689
5507
  std::swap(coverage_connection_, connection);
690
5507
}
691
692
16520
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
693
16520
  return coverage_connection_.get();
694
}
695
696
5469
inline const std::string& Environment::coverage_directory() const {
697
5469
  return coverage_directory_;
698
}
699
700
12
inline void Environment::set_cpu_profiler_connection(
701
    std::unique_ptr<profiler::V8CpuProfilerConnection> connection) {
702
12
  CHECK_NULL(cpu_profiler_connection_);
703
12
  std::swap(cpu_profiler_connection_, connection);
704
12
}
705
706
inline profiler::V8CpuProfilerConnection*
707
5523
Environment::cpu_profiler_connection() {
708
5523
  return cpu_profiler_connection_.get();
709
}
710
711
12
inline void Environment::set_cpu_prof_interval(uint64_t interval) {
712
12
  cpu_prof_interval_ = interval;
713
12
}
714
715
12
inline uint64_t Environment::cpu_prof_interval() const {
716
12
  return cpu_prof_interval_;
717
}
718
719
12
inline void Environment::set_cpu_prof_name(const std::string& name) {
720
12
  cpu_prof_name_ = name;
721
12
}
722
723
12
inline const std::string& Environment::cpu_prof_name() const {
724
12
  return cpu_prof_name_;
725
}
726
727
12
inline void Environment::set_cpu_prof_dir(const std::string& dir) {
728
12
  cpu_prof_dir_ = dir;
729
12
}
730
731
12
inline const std::string& Environment::cpu_prof_dir() const {
732
12
  return cpu_prof_dir_;
733
}
734
735
12
inline void Environment::set_heap_profiler_connection(
736
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
737
12
  CHECK_NULL(heap_profiler_connection_);
738
12
  std::swap(heap_profiler_connection_, connection);
739
12
}
740
741
inline profiler::V8HeapProfilerConnection*
742
5511
Environment::heap_profiler_connection() {
743
5511
  return heap_profiler_connection_.get();
744
}
745
746
12
inline void Environment::set_heap_prof_name(const std::string& name) {
747
12
  heap_prof_name_ = name;
748
12
}
749
750
12
inline const std::string& Environment::heap_prof_name() const {
751
12
  return heap_prof_name_;
752
}
753
754
12
inline void Environment::set_heap_prof_dir(const std::string& dir) {
755
12
  heap_prof_dir_ = dir;
756
12
}
757
758
12
inline const std::string& Environment::heap_prof_dir() const {
759
12
  return heap_prof_dir_;
760
}
761
762
12
inline void Environment::set_heap_prof_interval(uint64_t interval) {
763
12
  heap_prof_interval_ = interval;
764
12
}
765
766
12
inline uint64_t Environment::heap_prof_interval() const {
767
12
  return heap_prof_interval_;
768
}
769
770
#endif  // HAVE_INSPECTOR
771
772
inline
773
11184
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
774
11184
  return inspector_host_port_;
775
}
776
777
104283
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
778
104283
  return options_;
779
}
780
781
257
inline void IsolateData::set_options(
782
    std::shared_ptr<PerIsolateOptions> options) {
783
257
  options_ = std::move(options);
784
257
}
785
786
template <typename Fn>
787
90393
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
788
180786
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
789
90393
  native_immediates_.Push(std::move(callback));
790
791
90393
  if (flags & CallbackFlags::kRefed) {
792
66502
    if (immediate_info()->ref_count() == 0)
793
49968
      ToggleImmediateRef(true);
794
66502
    immediate_info()->ref_count_inc(1);
795
  }
796
90393
}
797
798
template <typename Fn>
799
2780
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
800
5560
  auto callback = native_immediates_threadsafe_.CreateCallback(
801
2780
      std::move(cb), flags);
802
  {
803
5560
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
804
2780
    native_immediates_threadsafe_.Push(std::move(callback));
805
2780
    if (task_queues_async_initialized_)
806
2132
      uv_async_send(&task_queues_async_);
807
  }
808
2780
}
809
810
template <typename Fn>
811
9353
void Environment::RequestInterrupt(Fn&& cb) {
812
18706
  auto callback = native_immediates_interrupts_.CreateCallback(
813
9353
      std::move(cb), CallbackFlags::kRefed);
814
  {
815
18706
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
816
9353
    native_immediates_interrupts_.Push(std::move(callback));
817
9353
    if (task_queues_async_initialized_)
818
3721
      uv_async_send(&task_queues_async_);
819
  }
820
9353
  RequestInterruptFromV8();
821
9353
}
822
823
2918634
inline bool Environment::can_call_into_js() const {
824

2918634
  return can_call_into_js_ && !is_stopping();
825
}
826
827
1216
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
828
1216
  can_call_into_js_ = can_call_into_js;
829
1216
}
830
831
1464938
inline bool Environment::has_run_bootstrapping_code() const {
832
1464938
  return has_run_bootstrapping_code_;
833
}
834
835
5522
inline void Environment::DoneBootstrapping() {
836
5522
  has_run_bootstrapping_code_ = true;
837
  // This adjusts the return value of base_object_created_after_bootstrap() so
838
  // that tests that check the count do not have to account for internally
839
  // created BaseObjects.
840
5522
  base_object_created_by_bootstrap_ = base_object_count_;
841
5522
}
842
843
19
inline bool Environment::has_serialized_options() const {
844
19
  return has_serialized_options_;
845
}
846
847
5505
inline void Environment::set_has_serialized_options(bool value) {
848
5505
  has_serialized_options_ = value;
849
5505
}
850
851
8080
inline bool Environment::is_main_thread() const {
852
8080
  return worker_context() == nullptr;
853
}
854
855
976
inline bool Environment::no_native_addons() const {
856
1948
  return (flags_ & EnvironmentFlags::kNoNativeAddons) ||
857
1948
          !options_->allow_native_addons;
858
}
859
860
5487
inline bool Environment::should_not_register_esm_loader() const {
861
5487
  return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
862
}
863
864
14056
inline bool Environment::owns_process_state() const {
865
14056
  return flags_ & EnvironmentFlags::kOwnsProcessState;
866
}
867
868
5516
inline bool Environment::owns_inspector() const {
869
5516
  return flags_ & EnvironmentFlags::kOwnsInspector;
870
}
871
872
124227
inline bool Environment::tracks_unmanaged_fds() const {
873
124227
  return flags_ & EnvironmentFlags::kTrackUnmanagedFds;
874
}
875
876
2613
inline bool Environment::hide_console_windows() const {
877
2613
  return flags_ & EnvironmentFlags::kHideConsoleWindows;
878
}
879
880
6292
inline bool Environment::no_global_search_paths() const {
881
12584
  return (flags_ & EnvironmentFlags::kNoGlobalSearchPaths) ||
882
12584
         !options_->global_search_paths;
883
}
884
885
4
bool Environment::filehandle_close_warning() const {
886
4
  return emit_filehandle_warning_;
887
}
888
889
3
void Environment::set_filehandle_close_warning(bool on) {
890
3
  emit_filehandle_warning_ = on;
891
3
}
892
893
5349
void Environment::set_source_maps_enabled(bool on) {
894
5349
  source_maps_enabled_ = on;
895
5349
}
896
897
878
bool Environment::source_maps_enabled() const {
898
878
  return source_maps_enabled_;
899
}
900
901
6739
inline uint64_t Environment::thread_id() const {
902
6739
  return thread_id_;
903
}
904
905
14122
inline worker::Worker* Environment::worker_context() const {
906
14122
  return isolate_data()->worker_context();
907
}
908
909
802
inline void Environment::add_sub_worker_context(worker::Worker* context) {
910
802
  sub_worker_contexts_.insert(context);
911
802
}
912
913
828
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
914
828
  sub_worker_contexts_.erase(context);
915
828
}
916
917
template <typename Fn>
918
24
inline void Environment::ForEachWorker(Fn&& iterator) {
919
26
  for (worker::Worker* w : sub_worker_contexts_) iterator(w);
920
24
}
921
922
1588
inline void Environment::add_refs(int64_t diff) {
923
1588
  task_queues_async_refs_ += diff;
924
1588
  CHECK_GE(task_queues_async_refs_, 0);
925
1588
  if (task_queues_async_refs_ == 0)
926
179
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
927
  else
928
1409
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
929
1588
}
930
931
4404959
inline bool Environment::is_stopping() const {
932
4404959
  return is_stopping_.load();
933
}
934
935
5198
inline void Environment::set_stopping(bool value) {
936
5198
  is_stopping_.store(value);
937
5198
}
938
939
14
inline std::list<node_module>* Environment::extra_linked_bindings() {
940
14
  return &extra_linked_bindings_;
941
}
942
943
10
inline node_module* Environment::extra_linked_bindings_head() {
944
10
  return extra_linked_bindings_.size() > 0 ?
945
10
      &extra_linked_bindings_.front() : nullptr;
946
}
947
948
9
inline node_module* Environment::extra_linked_bindings_tail() {
949
9
  return extra_linked_bindings_.size() > 0 ?
950
9
      &extra_linked_bindings_.back() : nullptr;
951
}
952
953
19
inline const Mutex& Environment::extra_linked_bindings_mutex() const {
954
19
  return extra_linked_bindings_mutex_;
955
}
956
957
40603
inline performance::PerformanceState* Environment::performance_state() {
958
40603
  return performance_state_.get();
959
}
960
961
6685623
inline IsolateData* Environment::isolate_data() const {
962
6685623
  return isolate_data_;
963
}
964
965
65844
inline uv_buf_t Environment::allocate_managed_buffer(
966
    const size_t suggested_size) {
967
131688
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
968
  std::unique_ptr<v8::BackingStore> bs =
969
65844
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
970
65844
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
971
65844
  released_allocated_buffers()->emplace(buf.base, std::move(bs));
972
65844
  return buf;
973
}
974
975
80391
inline std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
976
    const uv_buf_t& buf) {
977
80391
  std::unique_ptr<v8::BackingStore> bs;
978
80391
  if (buf.base != nullptr) {
979
65844
    auto map = released_allocated_buffers();
980
65844
    auto it = map->find(buf.base);
981
65844
    CHECK_NE(it, map->end());
982
65844
    bs = std::move(it->second);
983
65844
    map->erase(it);
984
  }
985
80391
  return bs;
986
}
987
988
std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
989
131688
    Environment::released_allocated_buffers() {
990
131688
  return &released_allocated_buffers_;
991
}
992
993
8
inline void Environment::ThrowError(const char* errmsg) {
994
8
  ThrowError(v8::Exception::Error, errmsg);
995
8
}
996
997
inline void Environment::ThrowTypeError(const char* errmsg) {
998
  ThrowError(v8::Exception::TypeError, errmsg);
999
}
1000
1001
inline void Environment::ThrowRangeError(const char* errmsg) {
1002
  ThrowError(v8::Exception::RangeError, errmsg);
1003
}
1004
1005
8
inline void Environment::ThrowError(
1006
    v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1007
    const char* errmsg) {
1008
16
  v8::HandleScope handle_scope(isolate());
1009
8
  isolate()->ThrowException(fun(OneByteString(isolate(), errmsg)));
1010
8
}
1011
1012
7
inline void Environment::ThrowErrnoException(int errorno,
1013
                                             const char* syscall,
1014
                                             const char* message,
1015
                                             const char* path) {
1016
  isolate()->ThrowException(
1017
7
      ErrnoException(isolate(), errorno, syscall, message, path));
1018
7
}
1019
1020
14
inline void Environment::ThrowUVException(int errorno,
1021
                                          const char* syscall,
1022
                                          const char* message,
1023
                                          const char* path,
1024
                                          const char* dest) {
1025
  isolate()->ThrowException(
1026
14
      UVException(isolate(), errorno, syscall, message, path, dest));
1027
14
}
1028
1029
1490018
inline v8::Local<v8::FunctionTemplate> Environment::NewFunctionTemplate(
1030
    v8::FunctionCallback callback,
1031
    v8::Local<v8::Signature> signature,
1032
    v8::ConstructorBehavior behavior,
1033
    v8::SideEffectType side_effect_type,
1034
    const v8::CFunction* c_function) {
1035
  return v8::FunctionTemplate::New(isolate(),
1036
                                   callback,
1037
                                   v8::Local<v8::Value>(),
1038
                                   signature,
1039
                                   0,
1040
                                   behavior,
1041
                                   side_effect_type,
1042
1490018
                                   c_function);
1043
}
1044
1045
258868
inline void Environment::SetMethod(v8::Local<v8::Object> that,
1046
                                   const char* name,
1047
                                   v8::FunctionCallback callback) {
1048
258868
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1049
  v8::Local<v8::Function> function =
1050
258868
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1051
                          v8::ConstructorBehavior::kThrow,
1052
258868
                          v8::SideEffectType::kHasSideEffect)
1053
258868
          ->GetFunction(context)
1054
258868
          .ToLocalChecked();
1055
  // kInternalized strings are created in the old space.
1056
258868
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1057
  v8::Local<v8::String> name_string =
1058
517736
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1059
517736
  that->Set(context, name_string, function).Check();
1060
258868
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1061
258868
}
1062
1063
1240
inline void Environment::SetFastMethod(v8::Local<v8::Object> that,
1064
                                       const char* name,
1065
                                       v8::FunctionCallback slow_callback,
1066
                                       const v8::CFunction* c_function) {
1067
1240
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1068
  v8::Local<v8::Function> function =
1069
1240
      NewFunctionTemplate(slow_callback,
1070
                          v8::Local<v8::Signature>(),
1071
                          v8::ConstructorBehavior::kThrow,
1072
                          v8::SideEffectType::kHasNoSideEffect,
1073
1240
                          c_function)
1074
1240
          ->GetFunction(context)
1075
1240
          .ToLocalChecked();
1076
1240
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1077
  v8::Local<v8::String> name_string =
1078
2480
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1079
1240
  that->Set(context, name_string, function).Check();
1080
1240
}
1081
1082
122741
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
1083
                                               const char* name,
1084
                                               v8::FunctionCallback callback) {
1085
122741
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1086
  v8::Local<v8::Function> function =
1087
122741
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1088
                          v8::ConstructorBehavior::kThrow,
1089
122741
                          v8::SideEffectType::kHasNoSideEffect)
1090
122741
          ->GetFunction(context)
1091
122741
          .ToLocalChecked();
1092
  // kInternalized strings are created in the old space.
1093
122741
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1094
  v8::Local<v8::String> name_string =
1095
245482
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1096
245482
  that->Set(context, name_string, function).Check();
1097
122741
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1098
122741
}
1099
1100
734371
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1101
                                        const char* name,
1102
                                        v8::FunctionCallback callback) {
1103
734371
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1104
  v8::Local<v8::FunctionTemplate> t =
1105
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1106
734371
                          v8::SideEffectType::kHasSideEffect);
1107
  // kInternalized strings are created in the old space.
1108
734371
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1109
  v8::Local<v8::String> name_string =
1110
1468742
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1111
1468742
  that->PrototypeTemplate()->Set(name_string, t);
1112
734371
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1113
734371
}
1114
1115
121007
inline void Environment::SetProtoMethodNoSideEffect(
1116
    v8::Local<v8::FunctionTemplate> that,
1117
    const char* name,
1118
    v8::FunctionCallback callback) {
1119
121007
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1120
  v8::Local<v8::FunctionTemplate> t =
1121
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1122
121007
                          v8::SideEffectType::kHasNoSideEffect);
1123
  // kInternalized strings are created in the old space.
1124
121007
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1125
  v8::Local<v8::String> name_string =
1126
242014
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1127
242014
  that->PrototypeTemplate()->Set(name_string, t);
1128
121007
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1129
121007
}
1130
1131
33
inline void Environment::SetInstanceMethod(v8::Local<v8::FunctionTemplate> that,
1132
                                           const char* name,
1133
                                           v8::FunctionCallback callback) {
1134
33
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1135
  v8::Local<v8::FunctionTemplate> t =
1136
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1137
33
                          v8::SideEffectType::kHasSideEffect);
1138
  // kInternalized strings are created in the old space.
1139
33
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1140
  v8::Local<v8::String> name_string =
1141
66
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1142
66
  that->InstanceTemplate()->Set(name_string, t);
1143
33
  t->SetClassName(name_string);
1144
33
}
1145
1146
187525
inline void Environment::SetConstructorFunction(
1147
    v8::Local<v8::Object> that,
1148
    const char* name,
1149
    v8::Local<v8::FunctionTemplate> tmpl,
1150
    SetConstructorFunctionFlag flag) {
1151
187525
  SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag);
1152
187525
}
1153
1154
198085
inline void Environment::SetConstructorFunction(
1155
    v8::Local<v8::Object> that,
1156
    v8::Local<v8::String> name,
1157
    v8::Local<v8::FunctionTemplate> tmpl,
1158
    SetConstructorFunctionFlag flag) {
1159
198085
  if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
1160
192785
    tmpl->SetClassName(name);
1161
198085
  that->Set(
1162
      context(),
1163
      name,
1164
396170
      tmpl->GetFunction(context()).ToLocalChecked()).Check();
1165
198085
}
1166
1167
376340
void Environment::AddCleanupHook(CleanupCallback fn, void* arg) {
1168
752680
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
1169
376340
    fn, arg, cleanup_hook_counter_++
1170
376340
  });
1171
  // Make sure there was no existing element with these values.
1172
376340
  CHECK_EQ(insertion_info.second, true);
1173
376340
}
1174
1175
362250
void Environment::RemoveCleanupHook(CleanupCallback fn, void* arg) {
1176
362250
  CleanupHookCallback search { fn, arg, 0 };
1177
362250
  cleanup_hooks_.erase(search);
1178
362250
}
1179
1180
965767
size_t CleanupHookCallback::Hash::operator()(
1181
    const CleanupHookCallback& cb) const {
1182
965767
  return std::hash<void*>()(cb.arg_);
1183
}
1184
1185
480121
bool CleanupHookCallback::Equal::operator()(
1186
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
1187

480121
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
1188
}
1189
1190
467
BaseObject* CleanupHookCallback::GetBaseObject() const {
1191
467
  if (fn_ == BaseObject::DeleteMe)
1192
440
    return static_cast<BaseObject*>(arg_);
1193
  else
1194
27
    return nullptr;
1195
}
1196
1197
template <typename T>
1198
44
void Environment::ForEachBaseObject(T&& iterator) {
1199
978
  for (const auto& hook : cleanup_hooks_) {
1200
934
    BaseObject* obj = hook.GetBaseObject();
1201
934
    if (obj != nullptr)
1202
880
      iterator(obj);
1203
  }
1204
}
1205
1206
template <typename T>
1207
6
void Environment::ForEachBindingData(T&& iterator) {
1208
  BindingDataStore* map = static_cast<BindingDataStore*>(
1209
12
      context()->GetAlignedPointerFromEmbedderData(
1210
          ContextEmbedderIndex::kBindingListIndex));
1211
  DCHECK_NOT_NULL(map);
1212
30
  for (auto& it : *map) {
1213
24
    iterator(it.first, it.second);
1214
  }
1215
6
}
1216
1217
680043
void Environment::modify_base_object_count(int64_t delta) {
1218
680043
  base_object_count_ += delta;
1219
680043
}
1220
1221
14
int64_t Environment::base_object_created_after_bootstrap() const {
1222
14
  return base_object_count_ - base_object_created_by_bootstrap_;
1223
}
1224
1225
2
int64_t Environment::base_object_count() const {
1226
2
  return base_object_count_;
1227
}
1228
1229
17
void Environment::set_main_utf16(std::unique_ptr<v8::String::Value> str) {
1230
17
  CHECK(!main_utf16_);
1231
17
  main_utf16_ = std::move(str);
1232
17
}
1233
1234
567
void Environment::set_process_exit_handler(
1235
    std::function<void(Environment*, int)>&& handler) {
1236
567
  process_exit_handler_ = std::move(handler);
1237
567
}
1238
1239
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1240
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1241
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1242
#define V(TypeName, PropertyName)                                             \
1243
  inline                                                                      \
1244
  v8::Local<TypeName> IsolateData::PropertyName() const {                     \
1245
    return PropertyName ## _ .Get(isolate_);                                  \
1246
  }
1247
42806
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1248
869264
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1249
6333097
  PER_ISOLATE_STRING_PROPERTIES(VS)
1250
#undef V
1251
#undef VS
1252
#undef VY
1253
#undef VP
1254
1255
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1256
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1257
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1258
#define V(TypeName, PropertyName)                                             \
1259
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1260
    return isolate_data()->PropertyName();                                    \
1261
  }
1262
42806
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1263
751025
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1264
9125566
  PER_ISOLATE_STRING_PROPERTIES(VS)
1265
#undef V
1266
#undef VS
1267
#undef VY
1268
#undef VP
1269
1270
#define V(PropertyName, TypeName)                                             \
1271
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1272
    return PersistentToLocal::Strong(PropertyName ## _);                      \
1273
  }                                                                           \
1274
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
1275
    PropertyName ## _.Reset(isolate(), value);                                \
1276
  }
1277
1226208
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1278
3838433
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1279
#undef V
1280
1281
7501172
v8::Local<v8::Context> Environment::context() const {
1282
7501172
  return PersistentToLocal::Strong(context_);
1283
}
1284
1285
}  // namespace node
1286
1287
// These two files depend on each other. Including base_object-inl.h after this
1288
// file is the easiest way to avoid issues with that circular dependency.
1289
#include "base_object-inl.h"
1290
1291
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1292
1293
#endif  // SRC_ENV_INL_H_