GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 655 668 98.1 %
Date: 2022-02-20 04:14:12 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
990979
inline uv_loop_t* IsolateData::event_loop() const {
51
990979
  return event_loop_;
52
}
53
54
103697
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
55
103697
  return node_allocator_;
56
}
57
58
56343
inline MultiIsolatePlatform* IsolateData::platform() const {
59
56343
  return platform_;
60
}
61
62
584
inline void IsolateData::set_worker_context(worker::Worker* context) {
63
584
  CHECK_NULL(worker_context_);  // Should be set only once.
64
584
  worker_context_ = context;
65
584
}
66
67
14001
inline worker::Worker* IsolateData::worker_context() const {
68
14001
  return worker_context_;
69
}
70
71
206498
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
72
206498
  return async_wrap_providers_[index].Get(isolate_);
73
}
74
75
2603776
inline AliasedUint32Array& AsyncHooks::fields() {
76
2603776
  return fields_;
77
}
78
79
1655108
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
80
1655108
  return async_id_fields_;
81
}
82
83
624
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
84
624
  return async_ids_stack_;
85
}
86
87
807689
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
88
807689
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
89
624
    js_execution_async_resources_.Reset(
90
1248
        env()->isolate(), v8::Array::New(env()->isolate()));
91
  }
92
807689
  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
17157
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
17157
  js_promise_hooks_[0].Reset(env()->isolate(), init);
105
17157
  js_promise_hooks_[1].Reset(env()->isolate(), before);
106
17157
  js_promise_hooks_[2].Reset(env()->isolate(), after);
107
17157
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
108
34638
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
109
17481
    if (it->IsEmpty()) {
110
      it = contexts_.erase(it);
111
      it--;
112
      continue;
113
    }
114
34962
    PersistentToLocal::Weak(env()->isolate(), *it)
115
17481
        ->SetPromiseHooks(init, before, after, resolve);
116
  }
117
17157
}
118
119
206150
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
120
206150
  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
415999
inline Environment* AsyncHooks::env() {
128
415999
  return Environment::ForAsyncHooks(this);
129
}
130
131
// Remember to keep this code aligned with pushAsyncContext() in JS.
132
780705
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
780705
  if (fields_[kCheck] > 0) {
138
780701
    CHECK_GE(async_id, -1);
139
780701
    CHECK_GE(trigger_async_id, -1);
140
  }
141
142
780705
  uint32_t offset = fields_[kStackLength];
143
780705
  if (offset * 2 >= async_ids_stack_.Length())
144
4
    grow_async_ids_stack();
145
780705
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
146
780705
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
147
780705
  fields_[kStackLength] += 1;
148
780705
  async_id_fields_[kExecutionAsyncId] = async_id;
149
780705
  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
780705
  if (!resource.IsEmpty()) {
159
780701
    native_execution_async_resources_.resize(offset + 1);
160
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
161
780701
    native_execution_async_resources_[offset] = resource;
162
  }
163
780705
}
164
165
// Remember to keep this code aligned with popAsyncContext() in JS.
166
780331
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
780331
  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
1558574
  if (UNLIKELY(fields_[kCheck] > 0 &&
176

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

1558570
             !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
779285
    native_execution_async_resources_.resize(offset);
195
779285
    if (native_execution_async_resources_.size() <
196

998539
            native_execution_async_resources_.capacity() / 2 &&
197
219254
        native_execution_async_resources_.size() > 16) {
198
      native_execution_async_resources_.shrink_to_fit();
199
    }
200
  }
201
202
1558570
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
203
27780
    v8::HandleScope handle_scope(env()->isolate());
204
55560
    USE(js_execution_async_resources()->Set(
205
        env()->context(),
206
        env()->length_string(),
207
111120
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
208
  }
209
210
779285
  return fields_[kStackLength] > 0;
211
}
212
213
1998
void AsyncHooks::clear_async_id_stack() {
214
1998
  v8::Isolate* isolate = env()->isolate();
215
1998
  v8::HandleScope handle_scope(isolate);
216
1998
  if (!js_execution_async_resources_.IsEmpty()) {
217
2748
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
218
        env()->context(),
219
        env()->length_string(),
220
5496
        v8::Integer::NewFromUnsigned(isolate, 0)));
221
  }
222
1998
  native_execution_async_resources_.clear();
223
1998
  native_execution_async_resources_.shrink_to_fit();
224
225
1998
  async_id_fields_[kExecutionAsyncId] = 0;
226
1998
  async_id_fields_[kTriggerAsyncId] = 0;
227
1998
  fields_[kStackLength] = 0;
228
1998
}
229
230
6105
inline void AsyncHooks::AddContext(v8::Local<v8::Context> ctx) {
231
24024
  ctx->SetPromiseHooks(
232
6105
    js_promise_hooks_[0].IsEmpty() ?
233
6105
      v8::Local<v8::Function>() :
234
198
      PersistentToLocal::Strong(js_promise_hooks_[0]),
235
6105
    js_promise_hooks_[1].IsEmpty() ?
236
6105
      v8::Local<v8::Function>() :
237
198
      PersistentToLocal::Strong(js_promise_hooks_[1]),
238
6105
    js_promise_hooks_[2].IsEmpty() ?
239
6105
      v8::Local<v8::Function>() :
240
198
      PersistentToLocal::Strong(js_promise_hooks_[2]),
241
6105
    js_promise_hooks_[3].IsEmpty() ?
242
6105
      v8::Local<v8::Function>() :
243
      PersistentToLocal::Strong(js_promise_hooks_[3]));
244
245
6105
  size_t id = contexts_.size();
246
6105
  contexts_.resize(id + 1);
247
6105
  contexts_[id].Reset(env()->isolate(), ctx);
248
6105
  contexts_[id].SetWeak();
249
6105
}
250
251
499
inline void AsyncHooks::RemoveContext(v8::Local<v8::Context> ctx) {
252
499
  v8::Isolate* isolate = env()->isolate();
253
998
  v8::HandleScope handle_scope(isolate);
254
3849
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
255
3350
    if (it->IsEmpty()) {
256
61
      it = contexts_.erase(it);
257
61
      it--;
258
61
      continue;
259
    }
260
    v8::Local<v8::Context> saved_context =
261
3289
      PersistentToLocal::Weak(isolate, *it);
262
3289
    if (saved_context == ctx) {
263
      it->Reset();
264
      contexts_.erase(it);
265
      break;
266
    }
267
  }
268
499
}
269
270
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
271
// async_wrap-inl.h to avoid a circular dependency.
272
273
241867
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
274
241867
    Environment* env, double default_trigger_async_id)
275
241867
    : async_hooks_(env->async_hooks()) {
276
241867
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
277
241867
    CHECK_GE(default_trigger_async_id, 0);
278
  }
279
280
241867
  old_default_trigger_async_id_ =
281
241867
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
282
241867
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
283
241867
    default_trigger_async_id;
284
241867
}
285
286
483732
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
287
241866
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
288
241866
    old_default_trigger_async_id_;
289
241866
}
290
291
415999
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
292
415999
  return ContainerOf(&Environment::async_hooks_, hooks);
293
}
294
295
780355
inline size_t Environment::async_callback_scope_depth() const {
296
780355
  return async_callback_scope_depth_;
297
}
298
299
792237
inline void Environment::PushAsyncCallbackScope() {
300
792237
  async_callback_scope_depth_++;
301
792237
}
302
303
791633
inline void Environment::PopAsyncCallbackScope() {
304
791633
  async_callback_scope_depth_--;
305
791633
}
306
307
624
inline AliasedUint32Array& ImmediateInfo::fields() {
308
624
  return fields_;
309
}
310
311
179099
inline uint32_t ImmediateInfo::count() const {
312
179099
  return fields_[kCount];
313
}
314
315
269669
inline uint32_t ImmediateInfo::ref_count() const {
316
269669
  return fields_[kRefCount];
317
}
318
319
42949
inline bool ImmediateInfo::has_outstanding() const {
320
42949
  return fields_[kHasOutstanding] == 1;
321
}
322
323
33554
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
324
33554
  fields_[kRefCount] += increment;
325
33554
}
326
327
194108
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
328
194108
  fields_[kRefCount] -= decrement;
329
194108
}
330
331
624
inline AliasedUint8Array& TickInfo::fields() {
332
624
  return fields_;
333
}
334
335
1392165
inline bool TickInfo::has_tick_scheduled() const {
336
1392165
  return fields_[kHasTickScheduled] == 1;
337
}
338
339
504881
inline bool TickInfo::has_rejection_to_warn() const {
340
504881
  return fields_[kHasRejectionToWarn] == 1;
341
}
342
343
6105
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
344
                                         const ContextInfo& info) {
345
6105
  context->SetAlignedPointerInEmbedderData(
346
      ContextEmbedderIndex::kEnvironment, this);
347
  // Used by Environment::GetCurrent to know that we are on a node context.
348
6105
  context->SetAlignedPointerInEmbedderData(
349
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
350
  // Used to retrieve bindings
351
12210
  context->SetAlignedPointerInEmbedderData(
352
6105
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
353
354
#if HAVE_INSPECTOR
355
6105
  inspector_agent()->ContextCreated(context, info);
356
#endif  // HAVE_INSPECTOR
357
358
6105
  this->async_hooks()->AddContext(context);
359
6105
}
360
361
50961
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
362
50961
  if (UNLIKELY(!isolate->InContext())) return nullptr;
363
100524
  v8::HandleScope handle_scope(isolate);
364
50262
  return GetCurrent(isolate->GetCurrentContext());
365
}
366
367
5851907
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
368
5851907
  if (UNLIKELY(context.IsEmpty())) {
369
1
    return nullptr;
370
  }
371
5851906
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
372
5851906
               ContextEmbedderIndex::kContextTag)) {
373
11
    return nullptr;
374
  }
375
5851895
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
376
                   ContextEmbedderIndex::kContextTag) !=
377
5851895
               Environment::kNodeContextTagPtr)) {
378
    return nullptr;
379
  }
380
  return static_cast<Environment*>(
381
5851895
      context->GetAlignedPointerFromEmbedderData(
382
5851895
          ContextEmbedderIndex::kEnvironment));
383
}
384
385
4381978
inline Environment* Environment::GetCurrent(
386
    const v8::FunctionCallbackInfo<v8::Value>& info) {
387
4381978
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
388
}
389
390
template <typename T>
391
2028736
inline Environment* Environment::GetCurrent(
392
    const v8::PropertyCallbackInfo<T>& info) {
393
2028736
  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
772573
inline T* Environment::GetBindingData(
403
    const v8::FunctionCallbackInfo<v8::Value>& info) {
404
772573
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
405
}
406
407
template <typename T>
408
772575
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
409
  BindingDataStore* map = static_cast<BindingDataStore*>(
410
772575
      context->GetAlignedPointerFromEmbedderData(
411
          ContextEmbedderIndex::kBindingListIndex));
412
  DCHECK_NOT_NULL(map);
413
772575
  auto it = map->find(T::type_name);
414
772575
  if (UNLIKELY(it == map->end())) return nullptr;
415
772575
  T* result = static_cast<T*>(it->second.get());
416
  DCHECK_NOT_NULL(result);
417
  DCHECK_EQ(result->env(), GetCurrent(context));
418
772575
  return result;
419
}
420
421
template <typename T>
422
23080
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
46160
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
428
  BindingDataStore* map = static_cast<BindingDataStore*>(
429
23080
      context->GetAlignedPointerFromEmbedderData(
430
          ContextEmbedderIndex::kBindingListIndex));
431
  DCHECK_NOT_NULL(map);
432
23080
  auto result = map->emplace(T::type_name, item);
433
23080
  CHECK(result.second);
434
  DCHECK_EQ(GetBindingData<T>(context), item.get());
435
23080
  return item.get();
436
}
437
438
24141818
inline v8::Isolate* Environment::isolate() const {
439
24141818
  return isolate_;
440
}
441
442
6407
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
443
6407
  return ContainerOf(&Environment::timer_handle_, handle);
444
}
445
446
26375
inline uv_timer_t* Environment::timer_handle() {
447
26375
  return &timer_handle_;
448
}
449
450
179099
inline Environment* Environment::from_immediate_check_handle(
451
    uv_check_t* handle) {
452
179099
  return ContainerOf(&Environment::immediate_check_handle_, handle);
453
}
454
455
21888
inline uv_check_t* Environment::immediate_check_handle() {
456
21888
  return &immediate_check_handle_;
457
}
458
459
222810
inline uv_idle_t* Environment::immediate_idle_handle() {
460
222810
  return &immediate_idle_handle_;
461
}
462
463
32832
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
464
                                               HandleCleanupCb cb,
465
                                               void* arg) {
466
32832
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
467
32832
}
468
469
template <typename T, typename OnCloseCallback>
470
33706
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
471
33554
  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
33630
  handle->data = new CloseData { this, callback, handle->data };
483
33934
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
484
67108
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
485
33630
    data->env->handle_cleanup_waiting_--;
486
33630
    handle->data = data->original_data;
487
33630
    data->callback(reinterpret_cast<T*>(handle));
488
  });
489
33630
}
490
491
90196
void Environment::IncreaseWaitingRequestCounter() {
492
90196
  request_waiting_++;
493
90196
}
494
495
90187
void Environment::DecreaseWaitingRequestCounter() {
496
90187
  request_waiting_--;
497
90187
  CHECK_GE(request_waiting_, 0);
498
90187
}
499
500
985474
inline uv_loop_t* Environment::event_loop() const {
501
985474
  return isolate_data()->event_loop();
502
}
503
504
158
inline void Environment::TryLoadAddon(
505
    const char* filename,
506
    int flags,
507
    const std::function<bool(binding::DLib*)>& was_loaded) {
508
158
  loaded_addons_.emplace_back(filename, flags);
509
158
  if (!was_loaded(&loaded_addons_.back())) {
510
8
    loaded_addons_.pop_back();
511
  }
512
158
}
513
514
#if HAVE_INSPECTOR
515
44628
inline bool Environment::is_in_inspector_console_call() const {
516
44628
  return is_in_inspector_console_call_;
517
}
518
519
89254
inline void Environment::set_is_in_inspector_console_call(bool value) {
520
89254
  is_in_inspector_console_call_ = value;
521
89254
}
522
#endif
523
524
5821622
inline AsyncHooks* Environment::async_hooks() {
525
5821622
  return &async_hooks_;
526
}
527
528
720003
inline ImmediateInfo* Environment::immediate_info() {
529
720003
  return &immediate_info_;
530
}
531
532
696726
inline TickInfo* Environment::tick_info() {
533
696726
  return &tick_info_;
534
}
535
536
57336
inline uint64_t Environment::timer_base() const {
537
57336
  return timer_base_;
538
}
539
540
1033127
inline std::shared_ptr<KVStore> Environment::env_vars() {
541
1033127
  return env_vars_;
542
}
543
544
6073
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
545
6073
  env_vars_ = env_vars;
546
6073
}
547
548
18
inline bool Environment::printed_error() const {
549
18
  return printed_error_;
550
}
551
552
18
inline void Environment::set_printed_error(bool value) {
553
18
  printed_error_ = value;
554
18
}
555
556
9868
inline void Environment::set_trace_sync_io(bool value) {
557
9868
  trace_sync_io_ = value;
558
9868
}
559
560
105
inline bool Environment::abort_on_uncaught_exception() const {
561
105
  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
572
inline void Environment::set_abort_on_uncaught_exception(bool value) {
573
572
  options_->abort_on_uncaught_exception = value;
574
572
}
575
576
654
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
577
654
  return should_abort_on_uncaught_toggle_;
578
}
579
580
304102
inline AliasedInt32Array& Environment::stream_base_state() {
581
304102
  return stream_base_state_;
582
}
583
584
47054
inline uint32_t Environment::get_next_module_id() {
585
47054
  return module_id_counter_++;
586
}
587
3327
inline uint32_t Environment::get_next_script_id() {
588
3327
  return script_id_counter_++;
589
}
590
38699
inline uint32_t Environment::get_next_function_id() {
591
38699
  return function_id_counter_++;
592
}
593
594
96994
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
595
96994
    Environment* env)
596
96994
    : env_(env) {
597
96994
  env_->PushShouldNotAbortOnUncaughtScope();
598
96994
}
599
600
193982
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
601
96991
  Close();
602
96991
}
603
604
97184
void ShouldNotAbortOnUncaughtScope::Close() {
605
97184
  if (env_ != nullptr) {
606
96991
    env_->PopShouldNotAbortOnUncaughtScope();
607
96991
    env_ = nullptr;
608
  }
609
97184
}
610
611
96994
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
612
96994
  should_not_abort_scope_counter_++;
613
96994
}
614
615
96991
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
616
96991
  should_not_abort_scope_counter_--;
617
96991
}
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
413605
inline std::vector<double>* Environment::destroy_async_id_list() {
624
413605
  return &destroy_async_id_list_;
625
}
626
627
206703
inline double Environment::new_async_id() {
628
206703
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
629
206703
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
630
}
631
632
239286
inline double Environment::execution_async_id() {
633
239286
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
634
}
635
636
69492
inline double Environment::trigger_async_id() {
637
69492
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
638
}
639
640
206700
inline double Environment::get_default_trigger_async_id() {
641
  double default_trigger_async_id =
642
206700
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
643
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
644
206700
  if (default_trigger_async_id < 0)
645
169766
    default_trigger_async_id = execution_async_id();
646
206700
  return default_trigger_async_id;
647
}
648
649
62240
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
650
62240
  return options_;
651
}
652
653
15735
inline const std::vector<std::string>& Environment::argv() {
654
15735
  return argv_;
655
}
656
657
6019
inline const std::vector<std::string>& Environment::exec_argv() {
658
6019
  return exec_argv_;
659
}
660
661
10944
inline const std::string& Environment::exec_path() const {
662
10944
  return exec_path_;
663
}
664
665
10
inline std::string Environment::GetCwd() {
666
  char cwd[PATH_MAX_BYTES];
667
10
  size_t size = PATH_MAX_BYTES;
668
10
  const int err = uv_cwd(cwd, &size);
669
670
10
  if (err == 0) {
671
10
    CHECK_GT(size, 0);
672
10
    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
5468
inline void Environment::set_coverage_directory(const char* dir) {
683
5468
  coverage_directory_ = std::string(dir);
684
5468
}
685
686
5491
inline void Environment::set_coverage_connection(
687
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
688
5491
  CHECK_NULL(coverage_connection_);
689
5491
  std::swap(coverage_connection_, connection);
690
5491
}
691
692
16471
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
693
16471
  return coverage_connection_.get();
694
}
695
696
5452
inline const std::string& Environment::coverage_directory() const {
697
5452
  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
5506
Environment::cpu_profiler_connection() {
708
5506
  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
6
inline void Environment::set_heap_profiler_connection(
736
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
737
6
  CHECK_NULL(heap_profiler_connection_);
738
6
  std::swap(heap_profiler_connection_, connection);
739
6
}
740
741
inline profiler::V8HeapProfilerConnection*
742
5488
Environment::heap_profiler_connection() {
743
5488
  return heap_profiler_connection_.get();
744
}
745
746
6
inline void Environment::set_heap_prof_name(const std::string& name) {
747
6
  heap_prof_name_ = name;
748
6
}
749
750
6
inline const std::string& Environment::heap_prof_name() const {
751
6
  return heap_prof_name_;
752
}
753
754
6
inline void Environment::set_heap_prof_dir(const std::string& dir) {
755
6
  heap_prof_dir_ = dir;
756
6
}
757
758
6
inline const std::string& Environment::heap_prof_dir() const {
759
6
  return heap_prof_dir_;
760
}
761
762
6
inline void Environment::set_heap_prof_interval(uint64_t interval) {
763
6
  heap_prof_interval_ = interval;
764
6
}
765
766
6
inline uint64_t Environment::heap_prof_interval() const {
767
6
  return heap_prof_interval_;
768
}
769
770
#endif  // HAVE_INSPECTOR
771
772
inline
773
11168
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
774
11168
  return inspector_host_port_;
775
}
776
777
107003
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
778
107003
  return options_;
779
}
780
781
264
inline void IsolateData::set_options(
782
    std::shared_ptr<PerIsolateOptions> options) {
783
264
  options_ = std::move(options);
784
264
}
785
786
template <typename Fn>
787
91364
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
788
182728
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
789
91364
  native_immediates_.Push(std::move(callback));
790
791
91364
  if (flags & CallbackFlags::kRefed) {
792
67094
    if (immediate_info()->ref_count() == 0)
793
50214
      ToggleImmediateRef(true);
794
67094
    immediate_info()->ref_count_inc(1);
795
  }
796
91364
}
797
798
template <typename Fn>
799
2983
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
800
5966
  auto callback = native_immediates_threadsafe_.CreateCallback(
801
2983
      std::move(cb), flags);
802
  {
803
5966
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
804
2983
    native_immediates_threadsafe_.Push(std::move(callback));
805
2983
    if (task_queues_async_initialized_)
806
2165
      uv_async_send(&task_queues_async_);
807
  }
808
2983
}
809
810
template <typename Fn>
811
9370
void Environment::RequestInterrupt(Fn&& cb) {
812
18740
  auto callback = native_immediates_interrupts_.CreateCallback(
813
9370
      std::move(cb), CallbackFlags::kRefed);
814
  {
815
18740
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
816
9370
    native_immediates_interrupts_.Push(std::move(callback));
817
9370
    if (task_queues_async_initialized_)
818
3749
      uv_async_send(&task_queues_async_);
819
  }
820
9370
  RequestInterruptFromV8();
821
9370
}
822
823
2949176
inline bool Environment::can_call_into_js() const {
824

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

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