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: 569 574 99.1 %
Date: 2020-08-22 22:13:06 Branches: 98 124 79.0 %

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
715410
inline uv_loop_t* IsolateData::event_loop() const {
49
715410
  return event_loop_;
50
}
51
52
674771
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
53
674771
  return node_allocator_;
54
}
55
56
46147
inline MultiIsolatePlatform* IsolateData::platform() const {
57
46147
  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
19161
inline worker::Worker* IsolateData::worker_context() const {
66
19161
  return worker_context_;
67
}
68
69
207810
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
70
415620
  return async_wrap_providers_[index].Get(isolate_);
71
}
72
73
3976047
inline AliasedUint32Array& AsyncHooks::fields() {
74
3976047
  return fields_;
75
}
76
77
2377984
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
78
2377984
  return async_id_fields_;
79
}
80
81
454
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
82
454
  return async_ids_stack_;
83
}
84
85
1109108
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
86
2218216
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
87
454
    js_execution_async_resources_.Reset(
88
908
        env()->isolate(), v8::Array::New(env()->isolate()));
89
  }
90
1109108
  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
207756
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
99
207756
  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
1366956
inline Environment* AsyncHooks::env() {
107
1366956
  return Environment::ForAsyncHooks(this);
108
}
109
110
// Remember to keep this code aligned with pushAsyncContext() in JS.
111
1095143
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
1095143
  if (fields_[kCheck] > 0) {
117
1095263
    CHECK_GE(async_id, -1);
118
1095263
    CHECK_GE(trigger_async_id, -1);
119
  }
120
121
1095342
  uint32_t offset = fields_[kStackLength];
122
1095336
  if (offset * 2 >= async_ids_stack_.Length())
123
8
    grow_async_ids_stack();
124
1095321
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
125
1095342
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
126
1095343
  fields_[kStackLength] += 1;
127
1095333
  async_id_fields_[kExecutionAsyncId] = async_id;
128
1095354
  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
1095339
  if (!resource.IsEmpty()) {
140
1095337
    native_execution_async_resources_.resize(offset + 1);
141
1095157
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
142
  }
143
1095355
}
144
145
// Remember to keep this code aligned with popAsyncContext() in JS.
146
1094949
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
1094949
  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

1093924
  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
1093918
  uint32_t offset = fields_[kStackLength] - 1;
171
1093917
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
172
1093917
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
173
1093920
  fields_[kStackLength] = offset;
174
175

2187832
  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
1093917
    native_execution_async_resources_.resize(offset);
185
2187831
    if (native_execution_async_resources_.size() <
186

1313894
            native_execution_async_resources_.capacity() / 2 &&
187
219978
        native_execution_async_resources_.size() > 16) {
188
      native_execution_async_resources_.shrink_to_fit();
189
    }
190
  }
191
192
2187829
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
193
29482
    v8::HandleScope handle_scope(env()->isolate());
194
44223
    USE(js_execution_async_resources()->Set(
195
        env()->context(),
196
        env()->length_string(),
197
73705
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
198
  }
199
200
1093919
  return fields_[kStackLength] > 0;
201
}
202
203
1720
void AsyncHooks::clear_async_id_stack() {
204
1720
  v8::Isolate* isolate = env()->isolate();
205
3440
  v8::HandleScope handle_scope(isolate);
206
3440
  if (!js_execution_async_resources_.IsEmpty()) {
207
3798
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
208
        env()->context(),
209
        env()->length_string(),
210
6330
        v8::Integer::NewFromUnsigned(isolate, 0)));
211
  }
212
1720
  native_execution_async_resources_.clear();
213
1720
  native_execution_async_resources_.shrink_to_fit();
214
215
1720
  async_id_fields_[kExecutionAsyncId] = 0;
216
1720
  async_id_fields_[kTriggerAsyncId] = 0;
217
1720
  fields_[kStackLength] = 0;
218
1720
}
219
220
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
221
// async_wrap-inl.h to avoid a circular dependency.
222
223
484911
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
224
484911
    Environment* env, double default_trigger_async_id)
225
484911
    : async_hooks_(env->async_hooks()) {
226
484911
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
227
484911
    CHECK_GE(default_trigger_async_id, 0);
228
  }
229
230
484911
  old_default_trigger_async_id_ =
231
969822
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
232
484911
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
484911
    default_trigger_async_id;
234
484911
}
235
236
969820
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
237
484910
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
238
969820
    old_default_trigger_async_id_;
239
484910
}
240
241
1366811
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
242
1366811
  return ContainerOf(&Environment::async_hooks_, hooks);
243
}
244
245
1084333
inline size_t Environment::async_callback_scope_depth() const {
246
1084333
  return async_callback_scope_depth_;
247
}
248
249
1094330
inline void Environment::PushAsyncCallbackScope() {
250
1094330
  async_callback_scope_depth_++;
251
1094330
}
252
253
1094166
inline void Environment::PopAsyncCallbackScope() {
254
1094166
  async_callback_scope_depth_--;
255
1094166
}
256
257
454
inline AliasedUint32Array& ImmediateInfo::fields() {
258
454
  return fields_;
259
}
260
261
402667
inline uint32_t ImmediateInfo::count() const {
262
402667
  return fields_[kCount];
263
}
264
265
477899
inline uint32_t ImmediateInfo::ref_count() const {
266
477899
  return fields_[kRefCount];
267
}
268
269
30967
inline bool ImmediateInfo::has_outstanding() const {
270
30967
  return fields_[kHasOutstanding] == 1;
271
}
272
273
32615
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
274
32615
  fields_[kRefCount] += increment;
275
32615
}
276
277
415257
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
278
415257
  fields_[kRefCount] -= decrement;
279
415264
}
280
281
454
inline AliasedUint8Array& TickInfo::fields() {
282
454
  return fields_;
283
}
284
285
2026449
inline bool TickInfo::has_tick_scheduled() const {
286
2026449
  return fields_[kHasTickScheduled] == 1;
287
}
288
289
589949
inline bool TickInfo::has_rejection_to_warn() const {
290
589949
  return fields_[kHasRejectionToWarn] == 1;
291
}
292
293
5370
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
294
                                         const ContextInfo& info) {
295
5370
  context->SetAlignedPointerInEmbedderData(
296
5370
      ContextEmbedderIndex::kEnvironment, this);
297
  // Used by Environment::GetCurrent to know that we are on a node context.
298
10740
  context->SetAlignedPointerInEmbedderData(
299
5370
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
300
  // Used to retrieve bindings
301
5370
  context->SetAlignedPointerInEmbedderData(
302
10740
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
303
304
#if HAVE_INSPECTOR
305
5370
  inspector_agent()->ContextCreated(context, info);
306
#endif  // HAVE_INSPECTOR
307
5370
}
308
309
1103618
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
310
1103618
  if (UNLIKELY(!isolate->InContext())) return nullptr;
311
2206309
  v8::HandleScope handle_scope(isolate);
312
1103197
  return GetCurrent(isolate->GetCurrentContext());
313
}
314
315
6809799
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
316
6809799
  if (UNLIKELY(context.IsEmpty())) {
317
1
    return nullptr;
318
  }
319
6809798
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
320
               ContextEmbedderIndex::kContextTag)) {
321
11
    return nullptr;
322
  }
323
13619876
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
324
                   ContextEmbedderIndex::kContextTag) !=
325
               Environment::kNodeContextTagPtr)) {
326
    return nullptr;
327
  }
328
  return static_cast<Environment*>(
329
6809938
      context->GetAlignedPointerFromEmbedderData(
330
6809938
          ContextEmbedderIndex::kEnvironment));
331
}
332
333
4160127
inline Environment* Environment::GetCurrent(
334
    const v8::FunctionCallbackInfo<v8::Value>& info) {
335
4160127
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
336
}
337
338
template <typename T>
339
1233840
inline Environment* Environment::GetCurrent(
340
    const v8::PropertyCallbackInfo<T>& info) {
341
1233840
  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
544882
inline T* Environment::GetBindingData(
351
    const v8::FunctionCallbackInfo<v8::Value>& info) {
352
544882
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
353
}
354
355
template <typename T>
356
544883
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
357
  BindingDataStore* map = static_cast<BindingDataStore*>(
358
544883
      context->GetAlignedPointerFromEmbedderData(
359
544883
          ContextEmbedderIndex::kBindingListIndex));
360
  DCHECK_NOT_NULL(map);
361
544883
  auto it = map->find(T::binding_data_name);
362
544883
  if (UNLIKELY(it == map->end())) return nullptr;
363
544883
  T* result = static_cast<T*>(it->second.get());
364
  DCHECK_NOT_NULL(result);
365
  DCHECK_EQ(result->env(), GetCurrent(context));
366
544883
  return result;
367
}
368
369
template <typename T>
370
6310
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
12620
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
376
  BindingDataStore* map = static_cast<BindingDataStore*>(
377
6309
      context->GetAlignedPointerFromEmbedderData(
378
6309
          ContextEmbedderIndex::kBindingListIndex));
379
  DCHECK_NOT_NULL(map);
380
6309
  auto result = map->emplace(T::binding_data_name, item);
381
6309
  CHECK(result.second);
382
  DCHECK_EQ(GetBindingData<T>(context), item.get());
383
12619
  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
29045065
inline v8::Isolate* Environment::isolate() const {
391
29045065
  return isolate_;
392
}
393
394
5038
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
395
5038
  return ContainerOf(&Environment::timer_handle_, handle);
396
}
397
398
21670
inline uv_timer_t* Environment::timer_handle() {
399
21670
  return &timer_handle_;
400
}
401
402
402666
inline Environment* Environment::from_immediate_check_handle(
403
    uv_check_t* handle) {
404
402666
  return ContainerOf(&Environment::immediate_check_handle_, handle);
405
}
406
407
19276
inline uv_check_t* Environment::immediate_check_handle() {
408
19276
  return &immediate_check_handle_;
409
}
410
411
444050
inline uv_idle_t* Environment::immediate_idle_handle() {
412
444050
  return &immediate_idle_handle_;
413
}
414
415
19276
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
416
                                               HandleCleanupCb cb,
417
                                               void* arg) {
418
19276
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
419
19276
}
420
421
template <typename T, typename OnCloseCallback>
422
21475
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
423
21475
  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
21475
  handle->data = new CloseData { this, callback, handle->data };
435
85898
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
436
42949
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
437
21479
    data->env->handle_cleanup_waiting_--;
438
21477
    handle->data = data->original_data;
439
21480
    data->callback(reinterpret_cast<T*>(handle));
440
21478
  });
441
21474
}
442
443
79414
void Environment::IncreaseWaitingRequestCounter() {
444
79414
  request_waiting_++;
445
79414
}
446
447
79408
void Environment::DecreaseWaitingRequestCounter() {
448
79408
  request_waiting_--;
449
79408
  CHECK_GE(request_waiting_, 0);
450
79408
}
451
452
710563
inline uv_loop_t* Environment::event_loop() const {
453
710563
  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
40480
inline bool Environment::is_in_inspector_console_call() const {
468
40480
  return is_in_inspector_console_call_;
469
}
470
471
80958
inline void Environment::set_is_in_inspector_console_call(bool value) {
472
80958
  is_in_inspector_console_call_ = value;
473
80958
}
474
#endif
475
476
6527753
inline AsyncHooks* Environment::async_hooks() {
477
6527753
  return &async_hooks_;
478
}
479
480
1359871
inline ImmediateInfo* Environment::immediate_info() {
481
1359871
  return &immediate_info_;
482
}
483
484
1013700
inline TickInfo* Environment::tick_info() {
485
1013700
  return &tick_info_;
486
}
487
488
48604
inline uint64_t Environment::timer_base() const {
489
48604
  return timer_base_;
490
}
491
492
1246000
inline std::shared_ptr<KVStore> Environment::env_vars() {
493
1246000
  return env_vars_;
494
}
495
496
5254
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
497
5254
  env_vars_ = env_vars;
498
5254
}
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
8028
inline void Environment::set_trace_sync_io(bool value) {
509
8028
  trace_sync_io_ = value;
510
8028
}
511
512
68
inline bool Environment::abort_on_uncaught_exception() const {
513
68
  return options_->abort_on_uncaught_exception;
514
}
515
516
413
inline void Environment::set_abort_on_uncaught_exception(bool value) {
517
413
  options_->abort_on_uncaught_exception = value;
518
413
}
519
520
484
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
521
484
  return should_abort_on_uncaught_toggle_;
522
}
523
524
1297994
inline AliasedInt32Array& Environment::stream_base_state() {
525
1297994
  return stream_base_state_;
526
}
527
528
32460
inline uint32_t Environment::get_next_module_id() {
529
32460
  return module_id_counter_++;
530
}
531
1923
inline uint32_t Environment::get_next_script_id() {
532
1923
  return script_id_counter_++;
533
}
534
25984
inline uint32_t Environment::get_next_function_id() {
535
25984
  return function_id_counter_++;
536
}
537
538
66624
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
539
66624
    Environment* env)
540
66624
    : env_(env) {
541
66624
  env_->PushShouldNotAbortOnUncaughtScope();
542
66625
}
543
544
133249
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
545
66623
  Close();
546
66626
}
547
548
66806
void ShouldNotAbortOnUncaughtScope::Close() {
549
66806
  if (env_ != nullptr) {
550
66625
    env_->PopShouldNotAbortOnUncaughtScope();
551
66626
    env_ = nullptr;
552
  }
553
66807
}
554
555
66622
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
556
66622
  should_not_abort_scope_counter_++;
557
66622
}
558
559
66624
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
560
66624
  should_not_abort_scope_counter_--;
561
66624
}
562
563
1
inline bool Environment::inside_should_not_abort_on_uncaught_scope() const {
564
1
  return should_not_abort_scope_counter_ > 0;
565
}
566
567
334803
inline std::vector<double>* Environment::destroy_async_id_list() {
568
334803
  return &destroy_async_id_list_;
569
}
570
571
208340
inline double Environment::new_async_id() {
572
208340
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
573
208340
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
574
}
575
576
237796
inline double Environment::execution_async_id() {
577
237796
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
578
}
579
580
59986
inline double Environment::trigger_async_id() {
581
59986
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
582
}
583
584
208337
inline double Environment::get_default_trigger_async_id() {
585
  double default_trigger_async_id =
586
208337
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
587
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
588
208337
  if (default_trigger_async_id < 0)
589
167136
    default_trigger_async_id = execution_async_id();
590
208336
  return default_trigger_async_id;
591
}
592
593
49700
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
594
49700
  return options_;
595
}
596
597
13913
inline const std::vector<std::string>& Environment::argv() {
598
13913
  return argv_;
599
}
600
601
5351
inline const std::vector<std::string>& Environment::exec_argv() {
602
5351
  return exec_argv_;
603
}
604
605
9638
inline const std::string& Environment::exec_path() const {
606
9638
  return exec_path_;
607
}
608
609
#if HAVE_INSPECTOR
610
4812
inline void Environment::set_coverage_directory(const char* dir) {
611
4812
  coverage_directory_ = std::string(dir);
612
4812
}
613
614
4837
inline void Environment::set_coverage_connection(
615
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
616
4837
  CHECK_NULL(coverage_connection_);
617
4837
  std::swap(coverage_connection_, connection);
618
4837
}
619
620
14504
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
621
14504
  return coverage_connection_.get();
622
}
623
624
4792
inline const std::string& Environment::coverage_directory() const {
625
4792
  return coverage_directory_;
626
}
627
628
12
inline void Environment::set_cpu_profiler_connection(
629
    std::unique_ptr<profiler::V8CpuProfilerConnection> connection) {
630
12
  CHECK_NULL(cpu_profiler_connection_);
631
12
  std::swap(cpu_profiler_connection_, connection);
632
12
}
633
634
inline profiler::V8CpuProfilerConnection*
635
4854
Environment::cpu_profiler_connection() {
636
4854
  return cpu_profiler_connection_.get();
637
}
638
639
12
inline void Environment::set_cpu_prof_interval(uint64_t interval) {
640
12
  cpu_prof_interval_ = interval;
641
12
}
642
643
12
inline uint64_t Environment::cpu_prof_interval() const {
644
12
  return cpu_prof_interval_;
645
}
646
647
12
inline void Environment::set_cpu_prof_name(const std::string& name) {
648
12
  cpu_prof_name_ = name;
649
12
}
650
651
12
inline const std::string& Environment::cpu_prof_name() const {
652
12
  return cpu_prof_name_;
653
}
654
655
12
inline void Environment::set_cpu_prof_dir(const std::string& dir) {
656
12
  cpu_prof_dir_ = dir;
657
12
}
658
659
12
inline const std::string& Environment::cpu_prof_dir() const {
660
12
  return cpu_prof_dir_;
661
}
662
663
12
inline void Environment::set_heap_profiler_connection(
664
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
665
12
  CHECK_NULL(heap_profiler_connection_);
666
12
  std::swap(heap_profiler_connection_, connection);
667
12
}
668
669
inline profiler::V8HeapProfilerConnection*
670
4841
Environment::heap_profiler_connection() {
671
4841
  return heap_profiler_connection_.get();
672
}
673
674
12
inline void Environment::set_heap_prof_name(const std::string& name) {
675
12
  heap_prof_name_ = name;
676
12
}
677
678
12
inline const std::string& Environment::heap_prof_name() const {
679
12
  return heap_prof_name_;
680
}
681
682
12
inline void Environment::set_heap_prof_dir(const std::string& dir) {
683
12
  heap_prof_dir_ = dir;
684
12
}
685
686
12
inline const std::string& Environment::heap_prof_dir() const {
687
12
  return heap_prof_dir_;
688
}
689
690
12
inline void Environment::set_heap_prof_interval(uint64_t interval) {
691
12
  heap_prof_interval_ = interval;
692
12
}
693
694
12
inline uint64_t Environment::heap_prof_interval() const {
695
12
  return heap_prof_interval_;
696
}
697
698
#endif  // HAVE_INSPECTOR
699
700
inline
701
9796
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
702
9796
  return inspector_host_port_;
703
}
704
705
52165
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
706
52165
  return options_;
707
}
708
709
96
inline void IsolateData::set_options(
710
    std::shared_ptr<PerIsolateOptions> options) {
711
96
  options_ = std::move(options);
712
96
}
713
714
template <typename Fn>
715
54617
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
716
109234
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
717
54617
  native_immediates_.Push(std::move(callback));
718
719


54617
  if (flags & CallbackFlags::kRefed) {
720


32615
    if (immediate_info()->ref_count() == 0)
721
24749
      ToggleImmediateRef(true);
722
32615
    immediate_info()->ref_count_inc(1);
723
  }
724
54617
}
725
726
template <typename Fn>
727
1218
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
728
  auto callback = native_immediates_threadsafe_.CreateCallback(
729
2436
      std::move(cb), flags);
730
  {
731
2436
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
732
1218
    native_immediates_threadsafe_.Push(std::move(callback));
733

1218
    if (task_queues_async_initialized_)
734
950
      uv_async_send(&task_queues_async_);
735
  }
736
1218
}
737
738
template <typename Fn>
739
6845
void Environment::RequestInterrupt(Fn&& cb) {
740
  auto callback = native_immediates_interrupts_.CreateCallback(
741
13690
      std::move(cb), CallbackFlags::kRefed);
742
  {
743
13690
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
744
6845
    native_immediates_interrupts_.Push(std::move(callback));
745
6845
    if (task_queues_async_initialized_)
746
1889
      uv_async_send(&task_queues_async_);
747
  }
748
6845
  RequestInterruptFromV8();
749
6845
}
750
751
3896357
inline bool Environment::can_call_into_js() const {
752

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

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