GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/env-inl.h Lines: 571 576 99.1 %
Date: 2020-09-06 22:14:11 Branches: 96 124 77.4 %

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 "callback_queue-inl.h"
29
#include "env.h"
30
#include "node.h"
31
#include "util-inl.h"
32
#include "uv.h"
33
#include "v8.h"
34
#include "node_perf_common.h"
35
#include "node_context_data.h"
36
37
#include <cstddef>
38
#include <cstdint>
39
40
#include <utility>
41
42
namespace node {
43
44
inline v8::Isolate* IsolateData::isolate() const {
45
  return isolate_;
46
}
47
48
714318
inline uv_loop_t* IsolateData::event_loop() const {
49
714318
  return event_loop_;
50
}
51
52
674595
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
53
674595
  return node_allocator_;
54
}
55
56
46171
inline MultiIsolatePlatform* IsolateData::platform() const {
57
46171
  return platform_;
58
}
59
60
422
inline void IsolateData::set_worker_context(worker::Worker* context) {
61
422
  CHECK_NULL(worker_context_);  // Should be set only once.
62
422
  worker_context_ = context;
63
422
}
64
65
19184
inline worker::Worker* IsolateData::worker_context() const {
66
19184
  return worker_context_;
67
}
68
69
208881
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
70
417762
  return async_wrap_providers_[index].Get(isolate_);
71
}
72
73
4026740
inline AliasedUint32Array& AsyncHooks::fields() {
74
4026740
  return fields_;
75
}
76
77
2502095
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
78
2502095
  return async_id_fields_;
79
}
80
81
453
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
82
453
  return async_ids_stack_;
83
}
84
85
1109514
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
86
2219028
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
87
453
    js_execution_async_resources_.Reset(
88
906
        env()->isolate(), v8::Array::New(env()->isolate()));
89
  }
90
1109514
  return PersistentToLocal::Strong(js_execution_async_resources_);
91
}
92
93
274
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
94
274
  if (i >= native_execution_async_resources_.size()) return {};
95
274
  return PersistentToLocal::Strong(native_execution_async_resources_[i]);
96
}
97
98
208827
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
99
208827
  return env()->isolate_data()->async_wrap_provider(idx);
100
}
101
102
1
inline void AsyncHooks::no_force_checks() {
103
1
  fields_[kCheck] -= 1;
104
1
}
105
106
1368661
inline Environment* AsyncHooks::env() {
107
1368661
  return Environment::ForAsyncHooks(this);
108
}
109
110
// Remember to keep this code aligned with pushAsyncContext() in JS.
111
1095661
inline void AsyncHooks::push_async_context(double async_id,
112
                                           double trigger_async_id,
113
                                           v8::Local<v8::Object> resource) {
114
  // Since async_hooks is experimental, do only perform the check
115
  // when async_hooks is enabled.
116
1095661
  if (fields_[kCheck] > 0) {
117
1095725
    CHECK_GE(async_id, -1);
118
1095725
    CHECK_GE(trigger_async_id, -1);
119
  }
120
121
1095737
  uint32_t offset = fields_[kStackLength];
122
1095721
  if (offset * 2 >= async_ids_stack_.Length())
123
8
    grow_async_ids_stack();
124
1095715
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
125
1095731
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
126
1095724
  fields_[kStackLength] += 1;
127
1095718
  async_id_fields_[kExecutionAsyncId] = async_id;
128
1095723
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
129
130
#ifdef DEBUG
131
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
132
    CHECK(native_execution_async_resources_[i].IsEmpty());
133
#endif
134
135
  // When this call comes from JS (as a way of increasing the stack size),
136
  // `resource` will be empty, because JS caches these values anyway, and
137
  // we should avoid creating strong global references that might keep
138
  // these JS resource objects alive longer than necessary.
139
1095717
  if (!resource.IsEmpty()) {
140
1095711
    native_execution_async_resources_.resize(offset + 1);
141
1095605
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
142
  }
143
1095727
}
144
145
// Remember to keep this code aligned with popAsyncContext() in JS.
146
1095313
inline bool AsyncHooks::pop_async_context(double async_id) {
147
  // In case of an exception then this may have already been reset, if the
148
  // stack was multiple MakeCallback()'s deep.
149
1095313
  if (fields_[kStackLength] == 0) return false;
150
151
  // Ask for the async_id to be restored as a check that the stack
152
  // hasn't been corrupted.
153
  // Since async_hooks is experimental, do only perform the check
154
  // when async_hooks is enabled.
155

1094303
  if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) {
156
4
    fprintf(stderr,
157
            "Error: async hook stack has become corrupted ("
158
            "actual: %.f, expected: %.f)\n",
159
            async_id_fields_.GetValue(kExecutionAsyncId),
160
4
            async_id);
161
4
    DumpBacktrace(stderr);
162
4
    fflush(stderr);
163
4
    if (!env()->abort_on_uncaught_exception())
164
4
      exit(1);
165
    fprintf(stderr, "\n");
166
    fflush(stderr);
167
    ABORT_NO_BACKTRACE();
168
  }
169
170
1094281
  uint32_t offset = fields_[kStackLength] - 1;
171
1094288
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
172
1094287
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
173
1094287
  fields_[kStackLength] = offset;
174
175

2188570
  if (LIKELY(offset < native_execution_async_resources_.size() &&
176
             !native_execution_async_resources_[offset].IsEmpty())) {
177
#ifdef DEBUG
178
    for (uint32_t i = offset + 1;
179
         i < native_execution_async_resources_.size();
180
         i++) {
181
      CHECK(native_execution_async_resources_[i].IsEmpty());
182
    }
183
#endif
184
1094287
    native_execution_async_resources_.resize(offset);
185
2188587
    if (native_execution_async_resources_.size() <
186

1320140
            native_execution_async_resources_.capacity() / 2 &&
187
225844
        native_execution_async_resources_.size() > 16) {
188
      native_execution_async_resources_.shrink_to_fit();
189
    }
190
  }
191
192
2188568
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
193
29556
    v8::HandleScope handle_scope(env()->isolate());
194
44334
    USE(js_execution_async_resources()->Set(
195
        env()->context(),
196
        env()->length_string(),
197
73890
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
198
  }
199
200
1094282
  return fields_[kStackLength] > 0;
201
}
202
203
1717
void AsyncHooks::clear_async_id_stack() {
204
1717
  v8::Isolate* isolate = env()->isolate();
205
3434
  v8::HandleScope handle_scope(isolate);
206
3434
  if (!js_execution_async_resources_.IsEmpty()) {
207
3792
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
208
        env()->context(),
209
        env()->length_string(),
210
6320
        v8::Integer::NewFromUnsigned(isolate, 0)));
211
  }
212
1717
  native_execution_async_resources_.clear();
213
1717
  native_execution_async_resources_.shrink_to_fit();
214
215
1717
  async_id_fields_[kExecutionAsyncId] = 0;
216
1717
  async_id_fields_[kTriggerAsyncId] = 0;
217
1717
  fields_[kStackLength] = 0;
218
1717
}
219
220
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
221
// async_wrap-inl.h to avoid a circular dependency.
222
223
524559
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
224
524559
    Environment* env, double default_trigger_async_id)
225
524559
    : async_hooks_(env->async_hooks()) {
226
524559
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
227
524559
    CHECK_GE(default_trigger_async_id, 0);
228
  }
229
230
524559
  old_default_trigger_async_id_ =
231
1049118
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
232
524559
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
524559
    default_trigger_async_id;
234
524559
}
235
236
1049116
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
237
524558
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
238
1049116
    old_default_trigger_async_id_;
239
524558
}
240
241
1368576
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
242
1368576
  return ContainerOf(&Environment::async_hooks_, hooks);
243
}
244
245
1084700
inline size_t Environment::async_callback_scope_depth() const {
246
1084700
  return async_callback_scope_depth_;
247
}
248
249
1094868
inline void Environment::PushAsyncCallbackScope() {
250
1094868
  async_callback_scope_depth_++;
251
1094868
}
252
253
1094525
inline void Environment::PopAsyncCallbackScope() {
254
1094525
  async_callback_scope_depth_--;
255
1094525
}
256
257
453
inline AliasedUint32Array& ImmediateInfo::fields() {
258
453
  return fields_;
259
}
260
261
402223
inline uint32_t ImmediateInfo::count() const {
262
402223
  return fields_[kCount];
263
}
264
265
477716
inline uint32_t ImmediateInfo::ref_count() const {
266
477716
  return fields_[kRefCount];
267
}
268
269
31028
inline bool ImmediateInfo::has_outstanding() const {
270
31028
  return fields_[kHasOutstanding] == 1;
271
}
272
273
32772
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
274
32772
  fields_[kRefCount] += increment;
275
32772
}
276
277
414838
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
278
414838
  fields_[kRefCount] -= decrement;
279
414871
}
280
281
453
inline AliasedUint8Array& TickInfo::fields() {
282
453
  return fields_;
283
}
284
285
2037877
inline bool TickInfo::has_tick_scheduled() const {
286
2037877
  return fields_[kHasTickScheduled] == 1;
287
}
288
289
589958
inline bool TickInfo::has_rejection_to_warn() const {
290
589958
  return fields_[kHasRejectionToWarn] == 1;
291
}
292
293
5398
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
294
                                         const ContextInfo& info) {
295
5398
  context->SetAlignedPointerInEmbedderData(
296
5398
      ContextEmbedderIndex::kEnvironment, this);
297
  // Used by Environment::GetCurrent to know that we are on a node context.
298
10796
  context->SetAlignedPointerInEmbedderData(
299
5398
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
300
  // Used to retrieve bindings
301
5398
  context->SetAlignedPointerInEmbedderData(
302
10796
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
303
304
#if HAVE_INSPECTOR
305
5398
  inspector_agent()->ContextCreated(context, info);
306
#endif  // HAVE_INSPECTOR
307
5398
}
308
309
1103885
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
310
1103885
  if (UNLIKELY(!isolate->InContext())) return nullptr;
311
2206556
  v8::HandleScope handle_scope(isolate);
312
1103297
  return GetCurrent(isolate->GetCurrentContext());
313
}
314
315
7482054
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
316
7482054
  if (UNLIKELY(context.IsEmpty())) {
317
1
    return nullptr;
318
  }
319
7482053
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
320
               ContextEmbedderIndex::kContextTag)) {
321
11
    return nullptr;
322
  }
323
14964286
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
324
                   ContextEmbedderIndex::kContextTag) !=
325
               Environment::kNodeContextTagPtr)) {
326
    return nullptr;
327
  }
328
  return static_cast<Environment*>(
329
7482143
      context->GetAlignedPointerFromEmbedderData(
330
7482143
          ContextEmbedderIndex::kEnvironment));
331
}
332
333
4830853
inline Environment* Environment::GetCurrent(
334
    const v8::FunctionCallbackInfo<v8::Value>& info) {
335
4830853
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
336
}
337
338
template <typename T>
339
1234714
inline Environment* Environment::GetCurrent(
340
    const v8::PropertyCallbackInfo<T>& info) {
341
1234714
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
342
}
343
344
template <typename T, typename U>
345
inline T* Environment::GetBindingData(const v8::PropertyCallbackInfo<U>& info) {
346
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
347
}
348
349
template <typename T>
350
541932
inline T* Environment::GetBindingData(
351
    const v8::FunctionCallbackInfo<v8::Value>& info) {
352
541932
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
353
}
354
355
template <typename T>
356
541933
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
357
  BindingDataStore* map = static_cast<BindingDataStore*>(
358
541933
      context->GetAlignedPointerFromEmbedderData(
359
541933
          ContextEmbedderIndex::kBindingListIndex));
360
  DCHECK_NOT_NULL(map);
361
541933
  auto it = map->find(T::binding_data_name);
362
541933
  if (UNLIKELY(it == map->end())) return nullptr;
363
541933
  T* result = static_cast<T*>(it->second.get());
364
  DCHECK_NOT_NULL(result);
365
  DCHECK_EQ(result->env(), GetCurrent(context));
366
541933
  return result;
367
}
368
369
template <typename T>
370
6318
inline T* Environment::AddBindingData(
371
    v8::Local<v8::Context> context,
372
    v8::Local<v8::Object> target) {
373
  DCHECK_EQ(GetCurrent(context), this);
374
  // This won't compile if T is not a BaseObject subclass.
375
12636
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
376
  BindingDataStore* map = static_cast<BindingDataStore*>(
377
6318
      context->GetAlignedPointerFromEmbedderData(
378
6318
          ContextEmbedderIndex::kBindingListIndex));
379
  DCHECK_NOT_NULL(map);
380
6318
  auto result = map->emplace(T::binding_data_name, item);
381
6318
  CHECK(result.second);
382
  DCHECK_EQ(GetBindingData<T>(context), item.get());
383
12636
  return item.get();
384
}
385
386
1
inline Environment* Environment::GetThreadLocalEnv() {
387
1
  return static_cast<Environment*>(uv_key_get(&thread_local_env));
388
}
389
390
29799341
inline v8::Isolate* Environment::isolate() const {
391
29799341
  return isolate_;
392
}
393
394
5126
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
395
5126
  return ContainerOf(&Environment::timer_handle_, handle);
396
}
397
398
21862
inline uv_timer_t* Environment::timer_handle() {
399
21862
  return &timer_handle_;
400
}
401
402
402223
inline Environment* Environment::from_immediate_check_handle(
403
    uv_check_t* handle) {
404
402223
  return ContainerOf(&Environment::immediate_check_handle_, handle);
405
}
406
407
19308
inline uv_check_t* Environment::immediate_check_handle() {
408
19308
  return &immediate_check_handle_;
409
}
410
411
443781
inline uv_idle_t* Environment::immediate_idle_handle() {
412
443781
  return &immediate_idle_handle_;
413
}
414
415
19308
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
416
                                               HandleCleanupCb cb,
417
                                               void* arg) {
418
19308
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
419
19308
}
420
421
template <typename T, typename OnCloseCallback>
422
21499
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
423
21499
  handle_cleanup_waiting_++;
424
  static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle");
425
  static_assert(offsetof(T, data) == offsetof(uv_handle_t, data),
426
                "T is a libuv handle");
427
  static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb),
428
                "T is a libuv handle");
429
  struct CloseData {
430
    Environment* env;
431
    OnCloseCallback callback;
432
    void* original_data;
433
  };
434
21499
  handle->data = new CloseData { this, callback, handle->data };
435
85993
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
436
42994
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
437
21500
    data->env->handle_cleanup_waiting_--;
438
21497
    handle->data = data->original_data;
439
21498
    data->callback(reinterpret_cast<T*>(handle));
440
21500
  });
441
21498
}
442
443
79818
void Environment::IncreaseWaitingRequestCounter() {
444
79818
  request_waiting_++;
445
79818
}
446
447
79812
void Environment::DecreaseWaitingRequestCounter() {
448
79812
  request_waiting_--;
449
79812
  CHECK_GE(request_waiting_, 0);
450
79812
}
451
452
709463
inline uv_loop_t* Environment::event_loop() const {
453
709463
  return isolate_data()->event_loop();
454
}
455
456
158
inline void Environment::TryLoadAddon(
457
    const char* filename,
458
    int flags,
459
    const std::function<bool(binding::DLib*)>& was_loaded) {
460
158
  loaded_addons_.emplace_back(filename, flags);
461
158
  if (!was_loaded(&loaded_addons_.back())) {
462
8
    loaded_addons_.pop_back();
463
  }
464
158
}
465
466
#if HAVE_INSPECTOR
467
40499
inline bool Environment::is_in_inspector_console_call() const {
468
40499
  return is_in_inspector_console_call_;
469
}
470
471
80996
inline void Environment::set_is_in_inspector_console_call(bool value) {
472
80996
  is_in_inspector_console_call_ = value;
473
80996
}
474
#endif
475
476
6622995
inline AsyncHooks* Environment::async_hooks() {
477
6622995
  return &async_hooks_;
478
}
479
480
1359067
inline ImmediateInfo* Environment::immediate_info() {
481
1359067
  return &immediate_info_;
482
}
483
484
1019421
inline TickInfo* Environment::tick_info() {
485
1019421
  return &tick_info_;
486
}
487
488
49121
inline uint64_t Environment::timer_base() const {
489
49121
  return timer_base_;
490
}
491
492
1246907
inline std::shared_ptr<KVStore> Environment::env_vars() {
493
1246907
  return env_vars_;
494
}
495
496
5261
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
497
5261
  env_vars_ = env_vars;
498
5261
}
499
500
14
inline bool Environment::printed_error() const {
501
14
  return printed_error_;
502
}
503
504
14
inline void Environment::set_printed_error(bool value) {
505
14
  printed_error_ = value;
506
14
}
507
508
8043
inline void Environment::set_trace_sync_io(bool value) {
509
8043
  trace_sync_io_ = value;
510
8043
}
511
512
68
inline bool Environment::abort_on_uncaught_exception() const {
513
68
  return options_->abort_on_uncaught_exception;
514
}
515
516
inline void Environment::set_force_context_aware(bool value) {
517
  options_->force_context_aware = value;
518
}
519
520
42
inline bool Environment::force_context_aware() const {
521
42
  return options_->force_context_aware;
522
}
523
524
412
inline void Environment::set_abort_on_uncaught_exception(bool value) {
525
412
  options_->abort_on_uncaught_exception = value;
526
412
}
527
528
483
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
529
483
  return should_abort_on_uncaught_toggle_;
530
}
531
532
1296637
inline AliasedInt32Array& Environment::stream_base_state() {
533
1296637
  return stream_base_state_;
534
}
535
536
31987
inline uint32_t Environment::get_next_module_id() {
537
31987
  return module_id_counter_++;
538
}
539
2070
inline uint32_t Environment::get_next_script_id() {
540
2070
  return script_id_counter_++;
541
}
542
26235
inline uint32_t Environment::get_next_function_id() {
543
26235
  return function_id_counter_++;
544
}
545
546
65827
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
547
65827
    Environment* env)
548
65827
    : env_(env) {
549
65827
  env_->PushShouldNotAbortOnUncaughtScope();
550
65827
}
551
552
131652
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
553
65826
  Close();
554
65826
}
555
556
66010
void ShouldNotAbortOnUncaughtScope::Close() {
557
66010
  if (env_ != nullptr) {
558
65826
    env_->PopShouldNotAbortOnUncaughtScope();
559
65826
    env_ = nullptr;
560
  }
561
66010
}
562
563
65827
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
564
65827
  should_not_abort_scope_counter_++;
565
65827
}
566
567
65826
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
568
65826
  should_not_abort_scope_counter_--;
569
65826
}
570
571
1
inline bool Environment::inside_should_not_abort_on_uncaught_scope() const {
572
1
  return should_not_abort_scope_counter_ > 0;
573
}
574
575
337973
inline std::vector<double>* Environment::destroy_async_id_list() {
576
337973
  return &destroy_async_id_list_;
577
}
578
579
209411
inline double Environment::new_async_id() {
580
209411
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
581
209411
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
582
}
583
584
239327
inline double Environment::execution_async_id() {
585
239327
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
586
}
587
588
60409
inline double Environment::trigger_async_id() {
589
60409
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
590
}
591
592
209408
inline double Environment::get_default_trigger_async_id() {
593
  double default_trigger_async_id =
594
209408
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
595
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
596
209408
  if (default_trigger_async_id < 0)
597
168236
    default_trigger_async_id = execution_async_id();
598
209408
  return default_trigger_async_id;
599
}
600
601
49636
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
602
49636
  return options_;
603
}
604
605
13938
inline const std::vector<std::string>& Environment::argv() {
606
13938
  return argv_;
607
}
608
609
5360
inline const std::vector<std::string>& Environment::exec_argv() {
610
5360
  return exec_argv_;
611
}
612
613
9654
inline const std::string& Environment::exec_path() const {
614
9654
  return exec_path_;
615
}
616
617
#if HAVE_INSPECTOR
618
4821
inline void Environment::set_coverage_directory(const char* dir) {
619
4821
  coverage_directory_ = std::string(dir);
620
4821
}
621
622
4841
inline void Environment::set_coverage_connection(
623
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
624
4841
  CHECK_NULL(coverage_connection_);
625
4844
  std::swap(coverage_connection_, connection);
626
4842
}
627
628
14525
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
629
14525
  return coverage_connection_.get();
630
}
631
632
4801
inline const std::string& Environment::coverage_directory() const {
633
4801
  return coverage_directory_;
634
}
635
636
12
inline void Environment::set_cpu_profiler_connection(
637
    std::unique_ptr<profiler::V8CpuProfilerConnection> connection) {
638
12
  CHECK_NULL(cpu_profiler_connection_);
639
12
  std::swap(cpu_profiler_connection_, connection);
640
12
}
641
642
inline profiler::V8CpuProfilerConnection*
643
4860
Environment::cpu_profiler_connection() {
644
4860
  return cpu_profiler_connection_.get();
645
}
646
647
12
inline void Environment::set_cpu_prof_interval(uint64_t interval) {
648
12
  cpu_prof_interval_ = interval;
649
12
}
650
651
12
inline uint64_t Environment::cpu_prof_interval() const {
652
12
  return cpu_prof_interval_;
653
}
654
655
12
inline void Environment::set_cpu_prof_name(const std::string& name) {
656
12
  cpu_prof_name_ = name;
657
12
}
658
659
12
inline const std::string& Environment::cpu_prof_name() const {
660
12
  return cpu_prof_name_;
661
}
662
663
12
inline void Environment::set_cpu_prof_dir(const std::string& dir) {
664
12
  cpu_prof_dir_ = dir;
665
12
}
666
667
12
inline const std::string& Environment::cpu_prof_dir() const {
668
12
  return cpu_prof_dir_;
669
}
670
671
12
inline void Environment::set_heap_profiler_connection(
672
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
673
12
  CHECK_NULL(heap_profiler_connection_);
674
12
  std::swap(heap_profiler_connection_, connection);
675
12
}
676
677
inline profiler::V8HeapProfilerConnection*
678
4849
Environment::heap_profiler_connection() {
679
4849
  return heap_profiler_connection_.get();
680
}
681
682
12
inline void Environment::set_heap_prof_name(const std::string& name) {
683
12
  heap_prof_name_ = name;
684
12
}
685
686
12
inline const std::string& Environment::heap_prof_name() const {
687
12
  return heap_prof_name_;
688
}
689
690
12
inline void Environment::set_heap_prof_dir(const std::string& dir) {
691
12
  heap_prof_dir_ = dir;
692
12
}
693
694
12
inline const std::string& Environment::heap_prof_dir() const {
695
12
  return heap_prof_dir_;
696
}
697
698
12
inline void Environment::set_heap_prof_interval(uint64_t interval) {
699
12
  heap_prof_interval_ = interval;
700
12
}
701
702
12
inline uint64_t Environment::heap_prof_interval() const {
703
12
  return heap_prof_interval_;
704
}
705
706
#endif  // HAVE_INSPECTOR
707
708
inline
709
9810
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
710
9810
  return inspector_host_port_;
711
}
712
713
51720
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
714
51720
  return options_;
715
}
716
717
96
inline void IsolateData::set_options(
718
    std::shared_ptr<PerIsolateOptions> options) {
719
96
  options_ = std::move(options);
720
96
}
721
722
template <typename Fn>
723
54973
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
724
109946
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
725
54973
  native_immediates_.Push(std::move(callback));
726
727


54973
  if (flags & CallbackFlags::kRefed) {
728


32772
    if (immediate_info()->ref_count() == 0)
729
24913
      ToggleImmediateRef(true);
730
32772
    immediate_info()->ref_count_inc(1);
731
  }
732
54973
}
733
734
template <typename Fn>
735
1297
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
736
  auto callback = native_immediates_threadsafe_.CreateCallback(
737
2594
      std::move(cb), flags);
738
  {
739
2593
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
740
1297
    native_immediates_threadsafe_.Push(std::move(callback));
741

1297
    if (task_queues_async_initialized_)
742
960
      uv_async_send(&task_queues_async_);
743
  }
744
1297
}
745
746
template <typename Fn>
747
7766
void Environment::RequestInterrupt(Fn&& cb) {
748
  auto callback = native_immediates_interrupts_.CreateCallback(
749
15534
      std::move(cb), CallbackFlags::kRefed);
750
  {
751
15536
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
752
7768
    native_immediates_interrupts_.Push(std::move(callback));
753
7768
    if (task_queues_async_initialized_)
754
2794
      uv_async_send(&task_queues_async_);
755
  }
756
7768
  RequestInterruptFromV8();
757
7768
}
758
759
3909624
inline bool Environment::can_call_into_js() const {
760

3909624
  return can_call_into_js_ && !is_stopping();
761
}
762
763
964
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
764
964
  can_call_into_js_ = can_call_into_js;
765
965
}
766
767
1372256
inline bool Environment::has_run_bootstrapping_code() const {
768
1372256
  return has_run_bootstrapping_code_;
769
}
770
771
4856
inline void Environment::set_has_run_bootstrapping_code(bool value) {
772
4856
  has_run_bootstrapping_code_ = value;
773
4856
}
774
775
19
inline bool Environment::has_serialized_options() const {
776
19
  return has_serialized_options_;
777
}
778
779
4827
inline void Environment::set_has_serialized_options(bool value) {
780
4827
  has_serialized_options_ = value;
781
4827
}
782
783
13964
inline bool Environment::is_main_thread() const {
784
13964
  return worker_context() == nullptr;
785
}
786
787
4827
inline bool Environment::should_not_register_esm_loader() const {
788
4827
  return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
789
}
790
791
15680
inline bool Environment::owns_process_state() const {
792
15680
  return flags_ & EnvironmentFlags::kOwnsProcessState;
793
}
794
795
4853
inline bool Environment::owns_inspector() const {
796
4853
  return flags_ & EnvironmentFlags::kOwnsInspector;
797
}
798
799
89864
inline bool Environment::tracks_unmanaged_fds() const {
800
89864
  return flags_ & EnvironmentFlags::kTrackUnmanagedFds;
801
}
802
803
2
bool Environment::filehandle_close_warning() const {
804
2
  return emit_filehandle_warning_;
805
}
806
807
2
void Environment::set_filehandle_close_warning(bool on) {
808
2
  emit_filehandle_warning_ = on;
809
2
}
810
811
181
bool Environment::emit_insecure_umask_warning() const {
812
181
  return emit_insecure_umask_warning_;
813
}
814
815
5
void Environment::set_emit_insecure_umask_warning(bool on) {
816
5
  emit_insecure_umask_warning_ = on;
817
5
}
818
819
13
void Environment::set_source_maps_enabled(bool on) {
820
13
  source_maps_enabled_ = on;
821
13
}
822
823
919
bool Environment::source_maps_enabled() const {
824
919
  return source_maps_enabled_;
825
}
826
827
9411
inline uint64_t Environment::thread_id() const {
828
9411
  return thread_id_;
829
}
830
831
19184
inline worker::Worker* Environment::worker_context() const {
832
19184
  return isolate_data()->worker_context();
833
}
834
835
625
inline void Environment::add_sub_worker_context(worker::Worker* context) {
836
625
  sub_worker_contexts_.insert(context);
837
625
}
838
839
650
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
840
650
  sub_worker_contexts_.erase(context);
841
650
}
842
843
template <typename Fn>
844
22
inline void Environment::ForEachWorker(Fn&& iterator) {
845
22
  for (worker::Worker* w : sub_worker_contexts_) iterator(w);
846
22
}
847
848
1234
inline void Environment::add_refs(int64_t diff) {
849
1234
  task_queues_async_refs_ += diff;
850
1234
  CHECK_GE(task_queues_async_refs_, 0);
851
1234
  if (task_queues_async_refs_ == 0)
852
154
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
853
  else
854
1080
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
855
1234
}
856
857
6015983
inline bool Environment::is_stopping() const {
858
6015983
  return is_stopping_.load();
859
}
860
861
4481
inline void Environment::set_stopping(bool value) {
862
4481
  is_stopping_.store(value);
863
4484
}
864
865
1
inline std::list<node_module>* Environment::extra_linked_bindings() {
866
1
  return &extra_linked_bindings_;
867
}
868
869
3
inline node_module* Environment::extra_linked_bindings_head() {
870
4
  return extra_linked_bindings_.size() > 0 ?
871
4
      &extra_linked_bindings_.front() : nullptr;
872
}
873
874
3
inline const Mutex& Environment::extra_linked_bindings_mutex() const {
875
3
  return extra_linked_bindings_mutex_;
876
}
877
878
39064
inline performance::PerformanceState* Environment::performance_state() {
879
39064
  return performance_state_.get();
880
}
881
882
inline std::unordered_map<std::string, uint64_t>*
883
49
    Environment::performance_marks() {
884
49
  return &performance_marks_;
885
}
886
887
5201694
inline IsolateData* Environment::isolate_data() const {
888
5201694
  return isolate_data_;
889
}
890
891
std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
892
641506
    Environment::released_allocated_buffers() {
893
641506
  return &released_allocated_buffers_;
894
}
895
896
706
inline void Environment::ThrowError(const char* errmsg) {
897
706
  ThrowError(v8::Exception::Error, errmsg);
898
706
}
899
900
2
inline void Environment::ThrowTypeError(const char* errmsg) {
901
2
  ThrowError(v8::Exception::TypeError, errmsg);
902
2
}
903
904
inline void Environment::ThrowRangeError(const char* errmsg) {
905
  ThrowError(v8::Exception::RangeError, errmsg);
906
}
907
908
708
inline void Environment::ThrowError(
909
    v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
910
    const char* errmsg) {
911
1416
  v8::HandleScope handle_scope(isolate());
912
708
  isolate()->ThrowException(fun(OneByteString(isolate(), errmsg)));
913
708
}
914
915
3
inline void Environment::ThrowErrnoException(int errorno,
916
                                             const char* syscall,
917
                                             const char* message,
918
                                             const char* path) {
919
  isolate()->ThrowException(
920
3
      ErrnoException(isolate(), errorno, syscall, message, path));
921
3
}
922
923
14
inline void Environment::ThrowUVException(int errorno,
924
                                          const char* syscall,
925
                                          const char* message,
926
                                          const char* path,
927
                                          const char* dest) {
928
  isolate()->ThrowException(
929
14
      UVException(isolate(), errorno, syscall, message, path, dest));
930
14
}
931
932
inline v8::Local<v8::FunctionTemplate>
933
1092980
    Environment::NewFunctionTemplate(v8::FunctionCallback callback,
934
                                     v8::Local<v8::Signature> signature,
935
                                     v8::ConstructorBehavior behavior,
936
                                     v8::SideEffectType side_effect_type) {
937
  return v8::FunctionTemplate::New(isolate(), callback, v8::Local<v8::Value>(),
938
1092980
                                   signature, 0, behavior, side_effect_type);
939
}
940
941
388425
inline void Environment::SetMethod(v8::Local<v8::Object> that,
942
                                   const char* name,
943
                                   v8::FunctionCallback callback) {
944
388425
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
945
  v8::Local<v8::Function> function =
946
776852
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
947
                          v8::ConstructorBehavior::kThrow,
948
388424
                          v8::SideEffectType::kHasSideEffect)
949
776853
          ->GetFunction(context)
950
388424
          .ToLocalChecked();
951
  // kInternalized strings are created in the old space.
952
388424
  const v8::NewStringType type = v8::NewStringType::kInternalized;
953
  v8::Local<v8::String> name_string =
954
776851
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
955
776851
  that->Set(context, name_string, function).Check();
956
388424
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
957
388427
}
958
959
50589
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
960
                                               const char* name,
961
                                               v8::FunctionCallback callback) {
962
50589
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
963
  v8::Local<v8::Function> function =
964
101178
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
965
                          v8::ConstructorBehavior::kThrow,
966
50589
                          v8::SideEffectType::kHasNoSideEffect)
967
101177
          ->GetFunction(context)
968
50589
          .ToLocalChecked();
969
  // kInternalized strings are created in the old space.
970
50589
  const v8::NewStringType type = v8::NewStringType::kInternalized;
971
  v8::Local<v8::String> name_string =
972
101178
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
973
101177
  that->Set(context, name_string, function).Check();
974
50588
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
975
50588
}
976
977
459734
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
978
                                        const char* name,
979
                                        v8::FunctionCallback callback) {
980
459734
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
981
  v8::Local<v8::FunctionTemplate> t =
982
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
983
459734
                          v8::SideEffectType::kHasSideEffect);
984
  // kInternalized strings are created in the old space.
985
459734
  const v8::NewStringType type = v8::NewStringType::kInternalized;
986
  v8::Local<v8::String> name_string =
987
919468
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
988
919468
  that->PrototypeTemplate()->Set(name_string, t);
989
459734
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
990
459734
}
991
992
46397
inline void Environment::SetProtoMethodNoSideEffect(
993
    v8::Local<v8::FunctionTemplate> that,
994
    const char* name,
995
    v8::FunctionCallback callback) {
996
46397
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
997
  v8::Local<v8::FunctionTemplate> t =
998
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
999
46397
                          v8::SideEffectType::kHasNoSideEffect);
1000
  // kInternalized strings are created in the old space.
1001
46397
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1002
  v8::Local<v8::String> name_string =
1003
92794
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1004
92794
  that->PrototypeTemplate()->Set(name_string, t);
1005
46397
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1006
46397
}
1007
1008
31
inline void Environment::SetInstanceMethod(v8::Local<v8::FunctionTemplate> that,
1009
                                           const char* name,
1010
                                           v8::FunctionCallback callback) {
1011
31
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1012
  v8::Local<v8::FunctionTemplate> t =
1013
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1014
31
                          v8::SideEffectType::kHasSideEffect);
1015
  // kInternalized strings are created in the old space.
1016
31
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1017
  v8::Local<v8::String> name_string =
1018
62
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1019
62
  that->InstanceTemplate()->Set(name_string, t);
1020
31
  t->SetClassName(name_string);
1021
31
}
1022
1023
658466
void Environment::AddCleanupHook(void (*fn)(void*), void* arg) {
1024
1316931
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
1025
658466
    fn, arg, cleanup_hook_counter_++
1026
658465
  });
1027
  // Make sure there was no existing element with these values.
1028
658465
  CHECK_EQ(insertion_info.second, true);
1029
658465
}
1030
1031
646550
void Environment::RemoveCleanupHook(void (*fn)(void*), void* arg) {
1032
646550
  CleanupHookCallback search { fn, arg, 0 };
1033
646549
  cleanup_hooks_.erase(search);
1034
646557
}
1035
1036
1496569
size_t CleanupHookCallback::Hash::operator()(
1037
    const CleanupHookCallback& cb) const {
1038
1496569
  return std::hash<void*>()(cb.arg_);
1039
}
1040
1041
746115
bool CleanupHookCallback::Equal::operator()(
1042
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
1043

746115
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
1044
}
1045
1046
367
BaseObject* CleanupHookCallback::GetBaseObject() const {
1047
367
  if (fn_ == BaseObject::DeleteMe)
1048
347
    return static_cast<BaseObject*>(arg_);
1049
  else
1050
20
    return nullptr;
1051
}
1052
1053
template <typename T>
1054
19
void Environment::ForEachBaseObject(T&& iterator) {
1055
386
  for (const auto& hook : cleanup_hooks_) {
1056
367
    BaseObject* obj = hook.GetBaseObject();
1057
367
    if (obj != nullptr)
1058
347
      iterator(obj);
1059
  }
1060
19
}
1061
1062
1293888
void Environment::modify_base_object_count(int64_t delta) {
1063
1293888
  base_object_count_ += delta;
1064
1293888
}
1065
1066
9727
int64_t Environment::base_object_count() const {
1067
9727
  return base_object_count_ - initial_base_object_count_;
1068
}
1069
1070
13
void Environment::set_main_utf16(std::unique_ptr<v8::String::Value> str) {
1071
13
  CHECK(!main_utf16_);
1072
13
  main_utf16_ = std::move(str);
1073
13
}
1074
1075
409
void Environment::set_process_exit_handler(
1076
    std::function<void(Environment*, int)>&& handler) {
1077
409
  process_exit_handler_ = std::move(handler);
1078
409
}
1079
1080
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1081
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1082
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1083
#define V(TypeName, PropertyName)                                             \
1084
  inline                                                                      \
1085
  v8::Local<TypeName> IsolateData::PropertyName() const {                     \
1086
    return PropertyName ## _ .Get(isolate_);                                  \
1087
  }
1088
61762
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1089
569976
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1090
6142016
  PER_ISOLATE_STRING_PROPERTIES(VS)
1091
#undef V
1092
#undef VS
1093
#undef VY
1094
#undef VP
1095
1096
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1097
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1098
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1099
#define V(TypeName, PropertyName)                                             \
1100
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1101
    return isolate_data()->PropertyName();                                    \
1102
  }
1103
30881
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1104
284675
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1105
3066513
  PER_ISOLATE_STRING_PROPERTIES(VS)
1106
#undef V
1107
#undef VS
1108
#undef VY
1109
#undef VP
1110
1111
#define V(PropertyName, TypeName)                                             \
1112
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1113
    return PersistentToLocal::Strong(PropertyName ## _);                      \
1114
  }                                                                           \
1115
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
1116
    PropertyName ## _.Reset(isolate(), value);                                \
1117
  }
1118
607601
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1119
2573167
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1120
#undef V
1121
1122
9910811
v8::Local<v8::Context> Environment::context() const {
1123
9910811
  return PersistentToLocal::Strong(context_);
1124
}
1125
1126
}  // namespace node
1127
1128
// These two files depend on each other. Including base_object-inl.h after this
1129
// file is the easiest way to avoid issues with that circular dependency.
1130
#include "base_object-inl.h"
1131
1132
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1133
1134
#endif  // SRC_ENV_INL_H_