GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 656 672 97.6 %
Date: 2021-12-06 04:13:56 Branches: 115 146 78.8 %

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
956917
inline uv_loop_t* IsolateData::event_loop() const {
51
956917
  return event_loop_;
52
}
53
54
103896
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
55
103896
  return node_allocator_;
56
}
57
58
55975
inline MultiIsolatePlatform* IsolateData::platform() const {
59
55975
  return platform_;
60
}
61
62
577
inline void IsolateData::set_worker_context(worker::Worker* context) {
63
577
  CHECK_NULL(worker_context_);  // Should be set only once.
64
577
  worker_context_ = context;
65
577
}
66
67
13962
inline worker::Worker* IsolateData::worker_context() const {
68
13962
  return worker_context_;
69
}
70
71
204552
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
72
204552
  return async_wrap_providers_[index].Get(isolate_);
73
}
74
75
2611575
inline AliasedUint32Array& AsyncHooks::fields() {
76
2611575
  return fields_;
77
}
78
79
1697039
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
80
1697039
  return async_id_fields_;
81
}
82
83
617
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
84
617
  return async_ids_stack_;
85
}
86
87
810387
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
88
810387
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
89
617
    js_execution_async_resources_.Reset(
90
1234
        env()->isolate(), v8::Array::New(env()->isolate()));
91
  }
92
810387
  return PersistentToLocal::Strong(js_execution_async_resources_);
93
}
94
95
2402
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
96
2402
  if (i >= native_execution_async_resources_.size()) return {};
97
2402
  return PersistentToLocal::Strong(native_execution_async_resources_[i]);
98
}
99
100
16826
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
16826
  js_promise_hooks_[0].Reset(env()->isolate(), init);
105
16826
  js_promise_hooks_[1].Reset(env()->isolate(), before);
106
16826
  js_promise_hooks_[2].Reset(env()->isolate(), after);
107
16826
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
108
33976
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
109
17150
    if (it->IsEmpty()) {
110
      it = contexts_.erase(it);
111
      it--;
112
      continue;
113
    }
114
34300
    PersistentToLocal::Weak(env()->isolate(), *it)
115
17150
        ->SetPromiseHooks(init, before, after, resolve);
116
  }
117
16826
}
118
119
204204
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
120
204204
  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
1199574
inline Environment* AsyncHooks::env() {
128
1199574
  return Environment::ForAsyncHooks(this);
129
}
130
131
// Remember to keep this code aligned with pushAsyncContext() in JS.
132
782108
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
782108
  if (fields_[kCheck] > 0) {
138
782105
    CHECK_GE(async_id, -1);
139
782105
    CHECK_GE(trigger_async_id, -1);
140
  }
141
142
782108
  uint32_t offset = fields_[kStackLength];
143
782108
  if (offset * 2 >= async_ids_stack_.Length())
144
4
    grow_async_ids_stack();
145
782108
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
146
782108
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
147
782108
  fields_[kStackLength] += 1;
148
782108
  async_id_fields_[kExecutionAsyncId] = async_id;
149
782108
  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, and
158
  // we should avoid creating strong global references that might keep
159
  // these JS resource objects alive longer than necessary.
160
782108
  if (!resource.IsEmpty()) {
161
782104
    native_execution_async_resources_.resize(offset + 1);
162
782104
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
163
  }
164
782108
}
165
166
// Remember to keep this code aligned with popAsyncContext() in JS.
167
781741
inline bool AsyncHooks::pop_async_context(double async_id) {
168
  // In case of an exception then this may have already been reset, if the
169
  // stack was multiple MakeCallback()'s deep.
170
781741
  if (fields_[kStackLength] == 0) return false;
171
172
  // Ask for the async_id to be restored as a check that the stack
173
  // hasn't been corrupted.
174
  // Since async_hooks is experimental, do only perform the check
175
  // when async_hooks is enabled.
176

780704
  if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) {
177
4
    fprintf(stderr,
178
            "Error: async hook stack has become corrupted ("
179
            "actual: %.f, expected: %.f)\n",
180
            async_id_fields_.GetValue(kExecutionAsyncId),
181
            async_id);
182
4
    DumpBacktrace(stderr);
183
4
    fflush(stderr);
184
4
    if (!env()->abort_on_uncaught_exception())
185
4
      exit(1);
186
    fprintf(stderr, "\n");
187
    fflush(stderr);
188
    ABORT_NO_BACKTRACE();
189
  }
190
191
780700
  uint32_t offset = fields_[kStackLength] - 1;
192
780700
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
193
780700
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
194
780700
  fields_[kStackLength] = offset;
195
196
1561400
  if (LIKELY(offset < native_execution_async_resources_.size() &&
197

1561400
             !native_execution_async_resources_[offset].IsEmpty())) {
198
#ifdef DEBUG
199
    for (uint32_t i = offset + 1;
200
         i < native_execution_async_resources_.size();
201
         i++) {
202
      CHECK(native_execution_async_resources_[i].IsEmpty());
203
    }
204
#endif
205
780700
    native_execution_async_resources_.resize(offset);
206
780700
    if (native_execution_async_resources_.size() <
207

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

2944689
  return can_call_into_js_ && !is_stopping();
836
}
837
838
1304
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
839
1304
  can_call_into_js_ = can_call_into_js;
840
1304
}
841
842
1454905
inline bool Environment::has_run_bootstrapping_code() const {
843
1454905
  return has_run_bootstrapping_code_;
844
}
845
846
5494
inline void Environment::DoneBootstrapping() {
847
5494
  has_run_bootstrapping_code_ = true;
848
  // This adjusts the return value of base_object_created_after_bootstrap() so
849
  // that tests that check the count do not have to account for internally
850
  // created BaseObjects.
851
5494
  base_object_created_by_bootstrap_ = base_object_count_;
852
5494
}
853
854
19
inline bool Environment::has_serialized_options() const {
855
19
  return has_serialized_options_;
856
}
857
858
5477
inline void Environment::set_has_serialized_options(bool value) {
859
5477
  has_serialized_options_ = value;
860
5477
}
861
862
7951
inline bool Environment::is_main_thread() const {
863
7951
  return worker_context() == nullptr;
864
}
865
866
976
inline bool Environment::no_native_addons() const {
867
1948
  return (flags_ & EnvironmentFlags::kNoNativeAddons) ||
868
1948
          !options_->allow_native_addons;
869
}
870
871
5459
inline bool Environment::should_not_register_esm_loader() const {
872
5459
  return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
873
}
874
875
13977
inline bool Environment::owns_process_state() const {
876
13977
  return flags_ & EnvironmentFlags::kOwnsProcessState;
877
}
878
879
5488
inline bool Environment::owns_inspector() const {
880
5488
  return flags_ & EnvironmentFlags::kOwnsInspector;
881
}
882
883
113401
inline bool Environment::tracks_unmanaged_fds() const {
884
113401
  return flags_ & EnvironmentFlags::kTrackUnmanagedFds;
885
}
886
887
2606
inline bool Environment::hide_console_windows() const {
888
2606
  return flags_ & EnvironmentFlags::kHideConsoleWindows;
889
}
890
891
6264
inline bool Environment::no_global_search_paths() const {
892
12528
  return (flags_ & EnvironmentFlags::kNoGlobalSearchPaths) ||
893
12528
         !options_->global_search_paths;
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
5323
void Environment::set_source_maps_enabled(bool on) {
905
5323
  source_maps_enabled_ = on;
906
5323
}
907
908
877
bool Environment::source_maps_enabled() const {
909
877
  return source_maps_enabled_;
910
}
911
912
6705
inline uint64_t Environment::thread_id() const {
913
6705
  return thread_id_;
914
}
915
916
13962
inline worker::Worker* Environment::worker_context() const {
917
13962
  return isolate_data()->worker_context();
918
}
919
920
802
inline void Environment::add_sub_worker_context(worker::Worker* context) {
921
802
  sub_worker_contexts_.insert(context);
922
802
}
923
924
828
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
925
828
  sub_worker_contexts_.erase(context);
926
828
}
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
1588
inline void Environment::add_refs(int64_t diff) {
934
1588
  task_queues_async_refs_ += diff;
935
1588
  CHECK_GE(task_queues_async_refs_, 0);
936
1588
  if (task_queues_async_refs_ == 0)
937
179
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
938
  else
939
1409
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
940
1588
}
941
942
4446108
inline bool Environment::is_stopping() const {
943
4446108
  return is_stopping_.load();
944
}
945
946
5089
inline void Environment::set_stopping(bool value) {
947
5089
  is_stopping_.store(value);
948
5089
}
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
40426
inline performance::PerformanceState* Environment::performance_state() {
969
40426
  return performance_state_.get();
970
}
971
972
6556525
inline IsolateData* Environment::isolate_data() const {
973
6556525
  return isolate_data_;
974
}
975
976
66466
inline uv_buf_t Environment::allocate_managed_buffer(
977
    const size_t suggested_size) {
978
132932
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
979
  std::unique_ptr<v8::BackingStore> bs =
980
66466
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
981
66466
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
982
66466
  released_allocated_buffers()->emplace(buf.base, std::move(bs));
983
66466
  return buf;
984
}
985
986
80999
inline std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
987
    const uv_buf_t& buf) {
988
80999
  std::unique_ptr<v8::BackingStore> bs;
989
80999
  if (buf.base != nullptr) {
990
66466
    auto map = released_allocated_buffers();
991
66466
    auto it = map->find(buf.base);
992
66466
    CHECK_NE(it, map->end());
993
66466
    bs = std::move(it->second);
994
66466
    map->erase(it);
995
  }
996
80999
  return bs;
997
}
998
999
std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
1000
132932
    Environment::released_allocated_buffers() {
1001
132932
  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
14
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
14
      UVException(isolate(), errorno, syscall, message, path, dest));
1038
14
}
1039
1040
1482416
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
1482416
                                   c_function);
1054
}
1055
1056
255681
inline void Environment::SetMethod(v8::Local<v8::Object> that,
1057
                                   const char* name,
1058
                                   v8::FunctionCallback callback) {
1059
255681
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1060
  v8::Local<v8::Function> function =
1061
255681
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1062
                          v8::ConstructorBehavior::kThrow,
1063
255681
                          v8::SideEffectType::kHasSideEffect)
1064
255681
          ->GetFunction(context)
1065
255681
          .ToLocalChecked();
1066
  // kInternalized strings are created in the old space.
1067
255681
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1068
  v8::Local<v8::String> name_string =
1069
511362
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1070
511362
  that->Set(context, name_string, function).Check();
1071
255681
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1072
255681
}
1073
1074
1234
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
1234
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1079
  v8::Local<v8::Function> function =
1080
1234
      NewFunctionTemplate(slow_callback,
1081
                          v8::Local<v8::Signature>(),
1082
                          v8::ConstructorBehavior::kThrow,
1083
                          v8::SideEffectType::kHasNoSideEffect,
1084
1234
                          c_function)
1085
1234
          ->GetFunction(context)
1086
1234
          .ToLocalChecked();
1087
1234
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1088
  v8::Local<v8::String> name_string =
1089
2468
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1090
1234
  that->Set(context, name_string, function).Check();
1091
1234
}
1092
1093
122101
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
1094
                                               const char* name,
1095
                                               v8::FunctionCallback callback) {
1096
122101
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1097
  v8::Local<v8::Function> function =
1098
122101
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1099
                          v8::ConstructorBehavior::kThrow,
1100
122101
                          v8::SideEffectType::kHasNoSideEffect)
1101
122101
          ->GetFunction(context)
1102
122101
          .ToLocalChecked();
1103
  // kInternalized strings are created in the old space.
1104
122101
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1105
  v8::Local<v8::String> name_string =
1106
244202
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1107
244202
  that->Set(context, name_string, function).Check();
1108
122101
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1109
122101
}
1110
1111
731920
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1112
                                        const char* name,
1113
                                        v8::FunctionCallback callback) {
1114
731920
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1115
  v8::Local<v8::FunctionTemplate> t =
1116
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1117
731920
                          v8::SideEffectType::kHasSideEffect);
1118
  // kInternalized strings are created in the old space.
1119
731920
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1120
  v8::Local<v8::String> name_string =
1121
1463840
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1122
1463840
  that->PrototypeTemplate()->Set(name_string, t);
1123
731920
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1124
731920
}
1125
1126
120366
inline void Environment::SetProtoMethodNoSideEffect(
1127
    v8::Local<v8::FunctionTemplate> that,
1128
    const char* name,
1129
    v8::FunctionCallback callback) {
1130
120366
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1131
  v8::Local<v8::FunctionTemplate> t =
1132
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1133
120366
                          v8::SideEffectType::kHasNoSideEffect);
1134
  // kInternalized strings are created in the old space.
1135
120366
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1136
  v8::Local<v8::String> name_string =
1137
240732
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1138
240732
  that->PrototypeTemplate()->Set(name_string, t);
1139
120366
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1140
120366
}
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
187158
inline void Environment::SetConstructorFunction(
1158
    v8::Local<v8::Object> that,
1159
    const char* name,
1160
    v8::Local<v8::FunctionTemplate> tmpl,
1161
    SetConstructorFunctionFlag flag) {
1162
187158
  SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag);
1163
187158
}
1164
1165
197661
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
197661
  if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
1171
192389
    tmpl->SetClassName(name);
1172
197661
  that->Set(
1173
      context(),
1174
      name,
1175
395322
      tmpl->GetFunction(context()).ToLocalChecked()).Check();
1176
197661
}
1177
1178
369843
void Environment::AddCleanupHook(CleanupCallback fn, void* arg) {
1179
739686
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
1180
369843
    fn, arg, cleanup_hook_counter_++
1181
369843
  });
1182
  // Make sure there was no existing element with these values.
1183
369843
  CHECK_EQ(insertion_info.second, true);
1184
369843
}
1185
1186
354484
void Environment::RemoveCleanupHook(CleanupCallback fn, void* arg) {
1187
354484
  CleanupHookCallback search { fn, arg, 0 };
1188
354484
  cleanup_hooks_.erase(search);
1189
354484
}
1190
1191
933904
size_t CleanupHookCallback::Hash::operator()(
1192
    const CleanupHookCallback& cb) const {
1193
933904
  return std::hash<void*>()(cb.arg_);
1194
}
1195
1196
463448
bool CleanupHookCallback::Equal::operator()(
1197
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
1198

463448
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
1199
}
1200
1201
467
BaseObject* CleanupHookCallback::GetBaseObject() const {
1202
467
  if (fn_ == BaseObject::DeleteMe)
1203
440
    return static_cast<BaseObject*>(arg_);
1204
  else
1205
27
    return nullptr;
1206
}
1207
1208
template <typename T>
1209
44
void Environment::ForEachBaseObject(T&& iterator) {
1210
978
  for (const auto& hook : cleanup_hooks_) {
1211
934
    BaseObject* obj = hook.GetBaseObject();
1212
934
    if (obj != nullptr)
1213
880
      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
665224
void Environment::modify_base_object_count(int64_t delta) {
1229
665224
  base_object_count_ += delta;
1230
665224
}
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
564
void Environment::set_process_exit_handler(
1246
    std::function<void(Environment*, int)>&& handler) {
1247
564
  process_exit_handler_ = std::move(handler);
1248
564
}
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
41893
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1259
884822
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1260
6216139
  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
41893
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1274
766850
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1275
8940746
  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
1223182
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1289
3814332
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1290
#undef V
1291
1292
6593924
v8::Local<v8::Context> Environment::context() const {
1293
6593924
  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_