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

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

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

999843
            native_execution_async_resources_.capacity() / 2 &&
197
220025
        native_execution_async_resources_.size() > 16) {
198
      native_execution_async_resources_.shrink_to_fit();
199
    }
200
  }
201
202
1559636
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
203
28038
    v8::HandleScope handle_scope(env()->isolate());
204
56076
    USE(js_execution_async_resources()->Set(
205
        env()->context(),
206
        env()->length_string(),
207
112152
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
208
  }
209
210
779818
  return fields_[kStackLength] > 0;
211
}
212
213
2000
void AsyncHooks::clear_async_id_stack() {
214
2000
  v8::Isolate* isolate = env()->isolate();
215
2000
  v8::HandleScope handle_scope(isolate);
216
2000
  if (!js_execution_async_resources_.IsEmpty()) {
217
2750
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
218
        env()->context(),
219
        env()->length_string(),
220
5500
        v8::Integer::NewFromUnsigned(isolate, 0)));
221
  }
222
2000
  native_execution_async_resources_.clear();
223
2000
  native_execution_async_resources_.shrink_to_fit();
224
225
2000
  async_id_fields_[kExecutionAsyncId] = 0;
226
2000
  async_id_fields_[kTriggerAsyncId] = 0;
227
2000
  fields_[kStackLength] = 0;
228
2000
}
229
230
6167
inline void AsyncHooks::AddContext(v8::Local<v8::Context> ctx) {
231
24272
  ctx->SetPromiseHooks(
232
6167
    js_promise_hooks_[0].IsEmpty() ?
233
6167
      v8::Local<v8::Function>() :
234
198
      PersistentToLocal::Strong(js_promise_hooks_[0]),
235
6167
    js_promise_hooks_[1].IsEmpty() ?
236
6167
      v8::Local<v8::Function>() :
237
198
      PersistentToLocal::Strong(js_promise_hooks_[1]),
238
6167
    js_promise_hooks_[2].IsEmpty() ?
239
6167
      v8::Local<v8::Function>() :
240
198
      PersistentToLocal::Strong(js_promise_hooks_[2]),
241
6167
    js_promise_hooks_[3].IsEmpty() ?
242
6167
      v8::Local<v8::Function>() :
243
      PersistentToLocal::Strong(js_promise_hooks_[3]));
244
245
6167
  size_t id = contexts_.size();
246
6167
  contexts_.resize(id + 1);
247
6167
  contexts_[id].Reset(env()->isolate(), ctx);
248
6167
  contexts_[id].SetWeak();
249
6167
}
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
241789
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
274
241789
    Environment* env, double default_trigger_async_id)
275
241789
    : async_hooks_(env->async_hooks()) {
276
241789
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
277
241789
    CHECK_GE(default_trigger_async_id, 0);
278
  }
279
280
241789
  old_default_trigger_async_id_ =
281
241789
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
282
241789
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
283
241789
    default_trigger_async_id;
284
241789
}
285
286
483576
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
287
241788
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
288
241788
    old_default_trigger_async_id_;
289
241788
}
290
291
418084
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
292
418084
  return ContainerOf(&Environment::async_hooks_, hooks);
293
}
294
295
780889
inline size_t Environment::async_callback_scope_depth() const {
296
780889
  return async_callback_scope_depth_;
297
}
298
299
793067
inline void Environment::PushAsyncCallbackScope() {
300
793067
  async_callback_scope_depth_++;
301
793067
}
302
303
792574
inline void Environment::PopAsyncCallbackScope() {
304
792574
  async_callback_scope_depth_--;
305
792574
}
306
307
625
inline AliasedUint32Array& ImmediateInfo::fields() {
308
625
  return fields_;
309
}
310
311
177501
inline uint32_t ImmediateInfo::count() const {
312
177501
  return fields_[kCount];
313
}
314
315
267638
inline uint32_t ImmediateInfo::ref_count() const {
316
267638
  return fields_[kRefCount];
317
}
318
319
42055
inline bool ImmediateInfo::has_outstanding() const {
320
42055
  return fields_[kHasOutstanding] == 1;
321
}
322
323
33576
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
324
33576
  fields_[kRefCount] += increment;
325
33576
}
326
327
192949
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
328
192949
  fields_[kRefCount] -= decrement;
329
192949
}
330
331
625
inline AliasedUint8Array& TickInfo::fields() {
332
625
  return fields_;
333
}
334
335
1393111
inline bool TickInfo::has_tick_scheduled() const {
336
1393111
  return fields_[kHasTickScheduled] == 1;
337
}
338
339
505351
inline bool TickInfo::has_rejection_to_warn() const {
340
505351
  return fields_[kHasRejectionToWarn] == 1;
341
}
342
343
6167
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
344
                                         const ContextInfo& info) {
345
6167
  context->SetAlignedPointerInEmbedderData(
346
      ContextEmbedderIndex::kEnvironment, this);
347
  // Used by Environment::GetCurrent to know that we are on a node context.
348
6167
  context->SetAlignedPointerInEmbedderData(
349
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
350
  // Used to retrieve bindings
351
12334
  context->SetAlignedPointerInEmbedderData(
352
6167
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
353
354
#if HAVE_INSPECTOR
355
6167
  inspector_agent()->ContextCreated(context, info);
356
#endif  // HAVE_INSPECTOR
357
358
6167
  this->async_hooks()->AddContext(context);
359
6167
}
360
361
50890
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
362
50890
  if (UNLIKELY(!isolate->InContext())) return nullptr;
363
100384
  v8::HandleScope handle_scope(isolate);
364
50192
  return GetCurrent(isolate->GetCurrentContext());
365
}
366
367
6187020
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
368
6187020
  if (UNLIKELY(context.IsEmpty())) {
369
1
    return nullptr;
370
  }
371
6187019
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
372
6187019
               ContextEmbedderIndex::kContextTag)) {
373
11
    return nullptr;
374
  }
375
6187008
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
376
                   ContextEmbedderIndex::kContextTag) !=
377
6187008
               Environment::kNodeContextTagPtr)) {
378
    return nullptr;
379
  }
380
  return static_cast<Environment*>(
381
6187008
      context->GetAlignedPointerFromEmbedderData(
382
6187008
          ContextEmbedderIndex::kEnvironment));
383
}
384
385
4410458
inline Environment* Environment::GetCurrent(
386
    const v8::FunctionCallbackInfo<v8::Value>& info) {
387
4410458
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
388
}
389
390
template <typename T>
391
2640360
inline Environment* Environment::GetCurrent(
392
    const v8::PropertyCallbackInfo<T>& info) {
393
2640360
  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
800275
inline T* Environment::GetBindingData(
403
    const v8::FunctionCallbackInfo<v8::Value>& info) {
404
800275
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
405
}
406
407
template <typename T>
408
800277
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
409
  BindingDataStore* map = static_cast<BindingDataStore*>(
410
800277
      context->GetAlignedPointerFromEmbedderData(
411
          ContextEmbedderIndex::kBindingListIndex));
412
  DCHECK_NOT_NULL(map);
413
800277
  auto it = map->find(T::type_name);
414
800277
  if (UNLIKELY(it == map->end())) return nullptr;
415
800277
  T* result = static_cast<T*>(it->second.get());
416
  DCHECK_NOT_NULL(result);
417
  DCHECK_EQ(result->env(), GetCurrent(context));
418
800277
  return result;
419
}
420
421
template <typename T>
422
23330
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
46660
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
428
  BindingDataStore* map = static_cast<BindingDataStore*>(
429
23330
      context->GetAlignedPointerFromEmbedderData(
430
          ContextEmbedderIndex::kBindingListIndex));
431
  DCHECK_NOT_NULL(map);
432
23330
  auto result = map->emplace(T::type_name, item);
433
23330
  CHECK(result.second);
434
  DCHECK_EQ(GetBindingData<T>(context), item.get());
435
23330
  return item.get();
436
}
437
438
24535762
inline v8::Isolate* Environment::isolate() const {
439
24535762
  return isolate_;
440
}
441
442
7554
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
443
7554
  return ContainerOf(&Environment::timer_handle_, handle);
444
}
445
446
27718
inline uv_timer_t* Environment::timer_handle() {
447
27718
  return &timer_handle_;
448
}
449
450
177501
inline Environment* Environment::from_immediate_check_handle(
451
    uv_check_t* handle) {
452
177501
  return ContainerOf(&Environment::immediate_check_handle_, handle);
453
}
454
455
22128
inline uv_check_t* Environment::immediate_check_handle() {
456
22128
  return &immediate_check_handle_;
457
}
458
459
221441
inline uv_idle_t* Environment::immediate_idle_handle() {
460
221441
  return &immediate_idle_handle_;
461
}
462
463
33192
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
464
                                               HandleCleanupCb cb,
465
                                               void* arg) {
466
33192
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
467
33192
}
468
469
template <typename T, typename OnCloseCallback>
470
34905
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
471
34753
  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
34829
  handle->data = new CloseData { this, callback, handle->data };
483
35133
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
484
69506
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
485
34829
    data->env->handle_cleanup_waiting_--;
486
34829
    handle->data = data->original_data;
487
34829
    data->callback(reinterpret_cast<T*>(handle));
488
  });
489
34829
}
490
491
90824
void Environment::IncreaseWaitingRequestCounter() {
492
90824
  request_waiting_++;
493
90824
}
494
495
90815
void Environment::DecreaseWaitingRequestCounter() {
496
90815
  request_waiting_--;
497
90815
  CHECK_GE(request_waiting_, 0);
498
90815
}
499
500
1016763
inline uv_loop_t* Environment::event_loop() const {
501
1016763
  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
44423
inline bool Environment::is_in_inspector_console_call() const {
516
44423
  return is_in_inspector_console_call_;
517
}
518
519
88844
inline void Environment::set_is_in_inspector_console_call(bool value) {
520
88844
  is_in_inspector_console_call_ = value;
521
88844
}
522
#endif
523
524
5833482
inline AsyncHooks* Environment::async_hooks() {
525
5833482
  return &async_hooks_;
526
}
527
528
714344
inline ImmediateInfo* Environment::immediate_info() {
529
714344
  return &immediate_info_;
530
}
531
532
697202
inline TickInfo* Environment::tick_info() {
533
697202
  return &tick_info_;
534
}
535
536
63145
inline uint64_t Environment::timer_base() const {
537
63145
  return timer_base_;
538
}
539
540
1335333
inline std::shared_ptr<KVStore> Environment::env_vars() {
541
1335333
  return env_vars_;
542
}
543
544
6134
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
545
6134
  env_vars_ = env_vars;
546
6134
}
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
10108
inline void Environment::set_trace_sync_io(bool value) {
557
10108
  trace_sync_io_ = value;
558
10108
}
559
560
104
inline bool Environment::abort_on_uncaught_exception() const {
561
104
  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
573
inline void Environment::set_abort_on_uncaught_exception(bool value) {
573
573
  options_->abort_on_uncaught_exception = value;
574
573
}
575
576
655
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
577
655
  return should_abort_on_uncaught_toggle_;
578
}
579
580
303765
inline AliasedInt32Array& Environment::stream_base_state() {
581
303765
  return stream_base_state_;
582
}
583
584
47299
inline uint32_t Environment::get_next_module_id() {
585
47299
  return module_id_counter_++;
586
}
587
3736
inline uint32_t Environment::get_next_script_id() {
588
3736
  return script_id_counter_++;
589
}
590
38806
inline uint32_t Environment::get_next_function_id() {
591
38806
  return function_id_counter_++;
592
}
593
594
97888
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
595
97888
    Environment* env)
596
97888
    : env_(env) {
597
97888
  env_->PushShouldNotAbortOnUncaughtScope();
598
97888
}
599
600
195770
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
601
97885
  Close();
602
97885
}
603
604
98078
void ShouldNotAbortOnUncaughtScope::Close() {
605
98078
  if (env_ != nullptr) {
606
97885
    env_->PopShouldNotAbortOnUncaughtScope();
607
97885
    env_ = nullptr;
608
  }
609
98078
}
610
611
97888
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
612
97888
  should_not_abort_scope_counter_++;
613
97888
}
614
615
97885
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
616
97885
  should_not_abort_scope_counter_--;
617
97885
}
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
414158
inline std::vector<double>* Environment::destroy_async_id_list() {
624
414158
  return &destroy_async_id_list_;
625
}
626
627
207673
inline double Environment::new_async_id() {
628
207673
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
629
207673
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
630
}
631
632
240006
inline double Environment::execution_async_id() {
633
240006
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
634
}
635
636
69527
inline double Environment::trigger_async_id() {
637
69527
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
638
}
639
640
207670
inline double Environment::get_default_trigger_async_id() {
641
  double default_trigger_async_id =
642
207670
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
643
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
644
207670
  if (default_trigger_async_id < 0)
645
170451
    default_trigger_async_id = execution_async_id();
646
207670
  return default_trigger_async_id;
647
}
648
649
62211
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
650
62211
  return options_;
651
}
652
653
15920
inline const std::vector<std::string>& Environment::argv() {
654
15920
  return argv_;
655
}
656
657
6084
inline const std::vector<std::string>& Environment::exec_argv() {
658
6084
  return exec_argv_;
659
}
660
661
11064
inline const std::string& Environment::exec_path() const {
662
11064
  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
5528
inline void Environment::set_coverage_directory(const char* dir) {
683
5528
  coverage_directory_ = std::string(dir);
684
5528
}
685
686
5553
inline void Environment::set_coverage_connection(
687
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
688
5553
  CHECK_NULL(coverage_connection_);
689
5553
  std::swap(coverage_connection_, connection);
690
5553
}
691
692
16658
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
693
16658
  return coverage_connection_.get();
694
}
695
696
5512
inline const std::string& Environment::coverage_directory() const {
697
5512
  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
5569
Environment::cpu_profiler_connection() {
708
5569
  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
5557
Environment::heap_profiler_connection() {
743
5557
  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
11292
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
774
11292
  return inspector_host_port_;
775
}
776
777
107418
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
778
107418
  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
91434
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
788
182868
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
789
91434
  native_immediates_.Push(std::move(callback));
790
791
91434
  if (flags & CallbackFlags::kRefed) {
792
67138
    if (immediate_info()->ref_count() == 0)
793
50234
      ToggleImmediateRef(true);
794
67138
    immediate_info()->ref_count_inc(1);
795
  }
796
91434
}
797
798
template <typename Fn>
799
3400
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
800
6800
  auto callback = native_immediates_threadsafe_.CreateCallback(
801
3400
      std::move(cb), flags);
802
  {
803
6800
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
804
3400
    native_immediates_threadsafe_.Push(std::move(callback));
805
3400
    if (task_queues_async_initialized_)
806
2937
      uv_async_send(&task_queues_async_);
807
  }
808
3400
}
809
810
template <typename Fn>
811
9413
void Environment::RequestInterrupt(Fn&& cb) {
812
18826
  auto callback = native_immediates_interrupts_.CreateCallback(
813
9413
      std::move(cb), CallbackFlags::kRefed);
814
  {
815
18826
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
816
9413
    native_immediates_interrupts_.Push(std::move(callback));
817
9413
    if (task_queues_async_initialized_)
818
3731
      uv_async_send(&task_queues_async_);
819
  }
820
9413
  RequestInterruptFromV8();
821
9413
}
822
823
2952588
inline bool Environment::can_call_into_js() const {
824

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

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