GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 656 668 98.2 %
Date: 2022-05-08 04:15:02 Branches: 112 142 78.9 %

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
1184850
inline uv_loop_t* IsolateData::event_loop() const {
51
1184850
  return event_loop_;
52
}
53
54
112612
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
55
112612
  return node_allocator_;
56
}
57
58
57601
inline MultiIsolatePlatform* IsolateData::platform() const {
59
57601
  return platform_;
60
}
61
62
803
inline void IsolateData::set_worker_context(worker::Worker* context) {
63
803
  CHECK_NULL(worker_context_);  // Should be set only once.
64
803
  worker_context_ = context;
65
803
}
66
67
16460
inline worker::Worker* IsolateData::worker_context() const {
68
16460
  return worker_context_;
69
}
70
71
215833
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
72
215833
  return async_wrap_providers_[index].Get(isolate_);
73
}
74
75
2636175
inline AliasedUint32Array& AsyncHooks::fields() {
76
2636175
  return fields_;
77
}
78
79
1717576
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
80
1717576
  return async_id_fields_;
81
}
82
83
848
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
84
848
  return async_ids_stack_;
85
}
86
87
813751
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
88
813751
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
89
848
    js_execution_async_resources_.Reset(
90
1696
        env()->isolate(), v8::Array::New(env()->isolate()));
91
  }
92
813751
  return PersistentToLocal::Strong(js_execution_async_resources_);
93
}
94
95
2403
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
96
2403
  if (i >= native_execution_async_resources_.size()) return {};
97
2403
  return native_execution_async_resources_[i];
98
}
99
100
15858
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
15858
  js_promise_hooks_[0].Reset(env()->isolate(), init);
105
15858
  js_promise_hooks_[1].Reset(env()->isolate(), before);
106
15858
  js_promise_hooks_[2].Reset(env()->isolate(), after);
107
15858
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
108
32043
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
109
16185
    if (it->IsEmpty()) {
110
      contexts_.erase(it--);
111
      continue;
112
    }
113
32370
    PersistentToLocal::Weak(env()->isolate(), *it)
114
16185
        ->SetPromiseHooks(init, before, after, resolve);
115
  }
116
15858
}
117
118
215485
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
119
215485
  return env()->isolate_data()->async_wrap_provider(idx);
120
}
121
122
1
inline void AsyncHooks::no_force_checks() {
123
1
  fields_[kCheck] -= 1;
124
1
}
125
126
431662
inline Environment* AsyncHooks::env() {
127
431662
  return Environment::ForAsyncHooks(this);
128
}
129
130
// Remember to keep this code aligned with pushAsyncContext() in JS.
131
783814
inline void AsyncHooks::push_async_context(double async_id,
132
                                           double trigger_async_id,
133
                                           v8::Local<v8::Object> resource) {
134
  // Since async_hooks is experimental, do only perform the check
135
  // when async_hooks is enabled.
136
783814
  if (fields_[kCheck] > 0) {
137
783811
    CHECK_GE(async_id, -1);
138
783811
    CHECK_GE(trigger_async_id, -1);
139
  }
140
141
783814
  uint32_t offset = fields_[kStackLength];
142
783814
  if (offset * 2 >= async_ids_stack_.Length())
143
4
    grow_async_ids_stack();
144
783814
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
145
783814
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
146
783814
  fields_[kStackLength] += 1;
147
783814
  async_id_fields_[kExecutionAsyncId] = async_id;
148
783814
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
149
150
#ifdef DEBUG
151
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
152
    CHECK(native_execution_async_resources_[i].IsEmpty());
153
#endif
154
155
  // When this call comes from JS (as a way of increasing the stack size),
156
  // `resource` will be empty, because JS caches these values anyway.
157
783814
  if (!resource.IsEmpty()) {
158
783810
    native_execution_async_resources_.resize(offset + 1);
159
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
160
783810
    native_execution_async_resources_[offset] = resource;
161
  }
162
783814
}
163
164
// Remember to keep this code aligned with popAsyncContext() in JS.
165
783424
inline bool AsyncHooks::pop_async_context(double async_id) {
166
  // In case of an exception then this may have already been reset, if the
167
  // stack was multiple MakeCallback()'s deep.
168
783424
  if (UNLIKELY(fields_[kStackLength] == 0)) return false;
169
170
  // Ask for the async_id to be restored as a check that the stack
171
  // hasn't been corrupted.
172
  // Since async_hooks is experimental, do only perform the check
173
  // when async_hooks is enabled.
174
1564755
  if (UNLIKELY(fields_[kCheck] > 0 &&
175

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

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

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

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

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