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: 485 613 79.1 %
Date: 2021-02-19 04:08:54 Branches: 61 136 44.9 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#ifndef SRC_ENV_INL_H_
23
#define SRC_ENV_INL_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
#include "aliased_buffer.h"
28
#include "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
233047
inline uv_loop_t* IsolateData::event_loop() const {
49
233047
  return event_loop_;
50
}
51
52
2509
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
53
2509
  return node_allocator_;
54
}
55
56
479
inline MultiIsolatePlatform* IsolateData::platform() const {
57
479
  return platform_;
58
}
59
60
inline void IsolateData::set_worker_context(worker::Worker* context) {
61
  CHECK_NULL(worker_context_);  // Should be set only once.
62
  worker_context_ = context;
63
}
64
65
409
inline worker::Worker* IsolateData::worker_context() const {
66
409
  return worker_context_;
67
}
68
69
19423
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
70
38846
  return async_wrap_providers_[index].Get(isolate_);
71
}
72
73
126632
inline AliasedUint32Array& AsyncHooks::fields() {
74
126632
  return fields_;
75
}
76
77
81421
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
78
81421
  return async_id_fields_;
79
}
80
81
52
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
82
52
  return async_ids_stack_;
83
}
84
85
27700
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
86
55400
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
87
52
    js_execution_async_resources_.Reset(
88
104
        env()->isolate(), v8::Array::New(env()->isolate()));
89
  }
90
27700
  return PersistentToLocal::Strong(js_execution_async_resources_);
91
}
92
93
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
94
  if (i >= native_execution_async_resources_.size()) return {};
95
  return PersistentToLocal::Strong(native_execution_async_resources_[i]);
96
}
97
98
19017
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
99
19017
  return env()->isolate_data()->async_wrap_provider(idx);
100
}
101
102
inline void AsyncHooks::no_force_checks() {
103
  fields_[kCheck] -= 1;
104
}
105
106
46833
inline Environment* AsyncHooks::env() {
107
46833
  return Environment::ForAsyncHooks(this);
108
}
109
110
// Remember to keep this code aligned with pushAsyncContext() in JS.
111
27650
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
27650
  if (fields_[kCheck] > 0) {
117
27650
    CHECK_GE(async_id, -1);
118
27650
    CHECK_GE(trigger_async_id, -1);
119
  }
120
121
27650
  uint32_t offset = fields_[kStackLength];
122
27650
  if (offset * 2 >= async_ids_stack_.Length())
123
    grow_async_ids_stack();
124
27650
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
125
27650
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
126
27650
  fields_[kStackLength] += 1;
127
27650
  async_id_fields_[kExecutionAsyncId] = async_id;
128
27650
  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
27650
  if (!resource.IsEmpty()) {
140
27650
    native_execution_async_resources_.resize(offset + 1);
141
27650
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
142
  }
143
27650
}
144
145
// Remember to keep this code aligned with popAsyncContext() in JS.
146
27647
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
27647
  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

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

55294
  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
27647
    native_execution_async_resources_.resize(offset);
185
55294
    if (native_execution_async_resources_.size() <
186

43349
            native_execution_async_resources_.capacity() / 2 &&
187
15702
        native_execution_async_resources_.size() > 16) {
188
      native_execution_async_resources_.shrink_to_fit();
189
    }
190
  }
191
192
55294
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
193
2
    v8::HandleScope handle_scope(env()->isolate());
194
3
    USE(js_execution_async_resources()->Set(
195
        env()->context(),
196
        env()->length_string(),
197
5
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
198
  }
199
200
27647
  return fields_[kStackLength] > 0;
201
}
202
203
54
void AsyncHooks::clear_async_id_stack() {
204
54
  v8::Isolate* isolate = env()->isolate();
205
108
  v8::HandleScope handle_scope(isolate);
206
108
  if (!js_execution_async_resources_.IsEmpty()) {
207
6
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
208
        env()->context(),
209
        env()->length_string(),
210
10
        v8::Integer::NewFromUnsigned(isolate, 0)));
211
  }
212
54
  native_execution_async_resources_.clear();
213
54
  native_execution_async_resources_.shrink_to_fit();
214
215
54
  async_id_fields_[kExecutionAsyncId] = 0;
216
54
  async_id_fields_[kTriggerAsyncId] = 0;
217
54
  fields_[kStackLength] = 0;
218
54
}
219
220
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
221
// async_wrap-inl.h to avoid a circular dependency.
222
223
1797
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
224
1797
    Environment* env, double default_trigger_async_id)
225
1797
    : async_hooks_(env->async_hooks()) {
226
1797
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
227
1797
    CHECK_GE(default_trigger_async_id, 0);
228
  }
229
230
1797
  old_default_trigger_async_id_ =
231
3594
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
232
1797
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
1797
    default_trigger_async_id;
234
1797
}
235
236
3594
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
237
1797
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
238
3594
    old_default_trigger_async_id_;
239
1797
}
240
241
46833
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
242
46833
  return ContainerOf(&Environment::async_hooks_, hooks);
243
}
244
245
27647
inline size_t Environment::async_callback_scope_depth() const {
246
27647
  return async_callback_scope_depth_;
247
}
248
249
27973
inline void Environment::PushAsyncCallbackScope() {
250
27973
  async_callback_scope_depth_++;
251
27973
}
252
253
27969
inline void Environment::PopAsyncCallbackScope() {
254
27969
  async_callback_scope_depth_--;
255
27969
}
256
257
52
inline AliasedUint32Array& ImmediateInfo::fields() {
258
52
  return fields_;
259
}
260
261
6396
inline uint32_t ImmediateInfo::count() const {
262
6396
  return fields_[kCount];
263
}
264
265
6868
inline uint32_t ImmediateInfo::ref_count() const {
266
6868
  return fields_[kRefCount];
267
}
268
269
inline bool ImmediateInfo::has_outstanding() const {
270
  return fields_[kHasOutstanding] == 1;
271
}
272
273
81
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
274
81
  fields_[kRefCount] += increment;
275
81
}
276
277
6787
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
278
6787
  fields_[kRefCount] -= decrement;
279
6787
}
280
281
52
inline AliasedUint8Array& TickInfo::fields() {
282
52
  return fields_;
283
}
284
285
54870
inline bool TickInfo::has_tick_scheduled() const {
286
54870
  return fields_[kHasTickScheduled] == 1;
287
}
288
289
24891
inline bool TickInfo::has_rejection_to_warn() const {
290
24891
  return fields_[kHasRejectionToWarn] == 1;
291
}
292
293
154
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
294
                                         const ContextInfo& info) {
295
154
  context->SetAlignedPointerInEmbedderData(
296
154
      ContextEmbedderIndex::kEnvironment, this);
297
  // Used by Environment::GetCurrent to know that we are on a node context.
298
308
  context->SetAlignedPointerInEmbedderData(
299
154
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
300
  // Used to retrieve bindings
301
154
  context->SetAlignedPointerInEmbedderData(
302
308
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
303
304
#if HAVE_INSPECTOR
305
154
  inspector_agent()->ContextCreated(context, info);
306
#endif  // HAVE_INSPECTOR
307
154
}
308
309
32632
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
310
32632
  if (UNLIKELY(!isolate->InContext())) return nullptr;
311
65048
  v8::HandleScope handle_scope(isolate);
312
32524
  return GetCurrent(isolate->GetCurrentContext());
313
}
314
315
566102
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
316
566102
  if (UNLIKELY(context.IsEmpty())) {
317
1
    return nullptr;
318
  }
319
566101
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
320
               ContextEmbedderIndex::kContextTag)) {
321
10
    return nullptr;
322
  }
323
1132182
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
324
                   ContextEmbedderIndex::kContextTag) !=
325
               Environment::kNodeContextTagPtr)) {
326
    return nullptr;
327
  }
328
  return static_cast<Environment*>(
329
566091
      context->GetAlignedPointerFromEmbedderData(
330
566091
          ContextEmbedderIndex::kEnvironment));
331
}
332
333
407427
inline Environment* Environment::GetCurrent(
334
    const v8::FunctionCallbackInfo<v8::Value>& info) {
335
407427
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
336
}
337
338
template <typename T>
339
121617
inline Environment* Environment::GetCurrent(
340
    const v8::PropertyCallbackInfo<T>& info) {
341
121617
  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
188767
inline T* Environment::GetBindingData(
351
    const v8::FunctionCallbackInfo<v8::Value>& info) {
352
188767
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
353
}
354
355
template <typename T>
356
188767
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
357
  BindingDataStore* map = static_cast<BindingDataStore*>(
358
188767
      context->GetAlignedPointerFromEmbedderData(
359
188767
          ContextEmbedderIndex::kBindingListIndex));
360
  DCHECK_NOT_NULL(map);
361
188767
  auto it = map->find(T::type_name);
362
188767
  if (UNLIKELY(it == map->end())) return nullptr;
363
188767
  T* result = static_cast<T*>(it->second.get());
364
  DCHECK_NOT_NULL(result);
365
  DCHECK_EQ(result->env(), GetCurrent(context));
366
188767
  return result;
367
}
368
369
template <typename T>
370
122
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
244
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
376
  BindingDataStore* map = static_cast<BindingDataStore*>(
377
122
      context->GetAlignedPointerFromEmbedderData(
378
122
          ContextEmbedderIndex::kBindingListIndex));
379
  DCHECK_NOT_NULL(map);
380
122
  auto result = map->emplace(T::type_name, item);
381
122
  CHECK(result.second);
382
  DCHECK_EQ(GetBindingData<T>(context), item.get());
383
244
  return item.get();
384
}
385
386
1306596
inline v8::Isolate* Environment::isolate() const {
387
1306596
  return isolate_;
388
}
389
390
1
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
391
1
  return ContainerOf(&Environment::timer_handle_, handle);
392
}
393
394
462
inline uv_timer_t* Environment::timer_handle() {
395
462
  return &timer_handle_;
396
}
397
398
6396
inline Environment* Environment::from_immediate_check_handle(
399
    uv_check_t* handle) {
400
6396
  return ContainerOf(&Environment::immediate_check_handle_, handle);
401
}
402
403
480
inline uv_check_t* Environment::immediate_check_handle() {
404
480
  return &immediate_check_handle_;
405
}
406
407
6795
inline uv_idle_t* Environment::immediate_idle_handle() {
408
6795
  return &immediate_idle_handle_;
409
}
410
411
480
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
412
                                               HandleCleanupCb cb,
413
                                               void* arg) {
414
480
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
415
480
}
416
417
template <typename T, typename OnCloseCallback>
418
602
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
419
602
  handle_cleanup_waiting_++;
420
  static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle");
421
  static_assert(offsetof(T, data) == offsetof(uv_handle_t, data),
422
                "T is a libuv handle");
423
  static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb),
424
                "T is a libuv handle");
425
  struct CloseData {
426
    Environment* env;
427
    OnCloseCallback callback;
428
    void* original_data;
429
  };
430
602
  handle->data = new CloseData { this, callback, handle->data };
431
2408
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
432
1204
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
433
602
    data->env->handle_cleanup_waiting_--;
434
602
    handle->data = data->original_data;
435
602
    data->callback(reinterpret_cast<T*>(handle));
436
602
  });
437
602
}
438
439
17022
void Environment::IncreaseWaitingRequestCounter() {
440
17022
  request_waiting_++;
441
17022
}
442
443
17022
void Environment::DecreaseWaitingRequestCounter() {
444
17022
  request_waiting_--;
445
17022
  CHECK_GE(request_waiting_, 0);
446
17022
}
447
448
232895
inline uv_loop_t* Environment::event_loop() const {
449
232895
  return isolate_data()->event_loop();
450
}
451
452
inline void Environment::TryLoadAddon(
453
    const char* filename,
454
    int flags,
455
    const std::function<bool(binding::DLib*)>& was_loaded) {
456
  loaded_addons_.emplace_back(filename, flags);
457
  if (!was_loaded(&loaded_addons_.back())) {
458
    loaded_addons_.pop_back();
459
  }
460
}
461
462
#if HAVE_INSPECTOR
463
224
inline bool Environment::is_in_inspector_console_call() const {
464
224
  return is_in_inspector_console_call_;
465
}
466
467
448
inline void Environment::set_is_in_inspector_console_call(bool value) {
468
448
  is_in_inspector_console_call_ = value;
469
448
}
470
#endif
471
472
240587
inline AsyncHooks* Environment::async_hooks() {
473
240587
  return &async_hooks_;
474
}
475
476
20184
inline ImmediateInfo* Environment::immediate_info() {
477
20184
  return &immediate_info_;
478
}
479
480
27487
inline TickInfo* Environment::tick_info() {
481
27487
  return &tick_info_;
482
}
483
484
1100
inline uint64_t Environment::timer_base() const {
485
1100
  return timer_base_;
486
}
487
488
122433
inline std::shared_ptr<KVStore> Environment::env_vars() {
489
122433
  return env_vars_;
490
}
491
492
152
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
493
152
  env_vars_ = env_vars;
494
152
}
495
496
inline bool Environment::printed_error() const {
497
  return printed_error_;
498
}
499
500
inline void Environment::set_printed_error(bool value) {
501
  printed_error_ = value;
502
}
503
504
210
inline void Environment::set_trace_sync_io(bool value) {
505
210
  trace_sync_io_ = value;
506
210
}
507
508
1
inline bool Environment::abort_on_uncaught_exception() const {
509
1
  return options_->abort_on_uncaught_exception;
510
}
511
512
inline void Environment::set_force_context_aware(bool value) {
513
  options_->force_context_aware = value;
514
}
515
516
inline bool Environment::force_context_aware() const {
517
  return options_->force_context_aware;
518
}
519
520
3
inline void Environment::set_abort_on_uncaught_exception(bool value) {
521
3
  options_->abort_on_uncaught_exception = value;
522
3
}
523
524
52
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
525
52
  return should_abort_on_uncaught_toggle_;
526
}
527
528
4107
inline AliasedInt32Array& Environment::stream_base_state() {
529
4107
  return stream_base_state_;
530
}
531
532
1072
inline uint32_t Environment::get_next_module_id() {
533
1072
  return module_id_counter_++;
534
}
535
12
inline uint32_t Environment::get_next_script_id() {
536
12
  return script_id_counter_++;
537
}
538
13491
inline uint32_t Environment::get_next_function_id() {
539
13491
  return function_id_counter_++;
540
}
541
542
2155
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
543
2155
    Environment* env)
544
2155
    : env_(env) {
545
2155
  env_->PushShouldNotAbortOnUncaughtScope();
546
2155
}
547
548
4310
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
549
2155
  Close();
550
2155
}
551
552
2155
void ShouldNotAbortOnUncaughtScope::Close() {
553
2155
  if (env_ != nullptr) {
554
2155
    env_->PopShouldNotAbortOnUncaughtScope();
555
2155
    env_ = nullptr;
556
  }
557
2155
}
558
559
2155
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
560
2155
  should_not_abort_scope_counter_++;
561
2155
}
562
563
2155
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
564
2155
  should_not_abort_scope_counter_--;
565
2155
}
566
567
inline bool Environment::inside_should_not_abort_on_uncaught_scope() const {
568
  return should_not_abort_scope_counter_ > 0;
569
}
570
571
104
inline std::vector<double>* Environment::destroy_async_id_list() {
572
104
  return &destroy_async_id_list_;
573
}
574
575
19017
inline double Environment::new_async_id() {
576
19017
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
577
19017
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
578
}
579
580
18927
inline double Environment::execution_async_id() {
581
18927
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
582
}
583
584
inline double Environment::trigger_async_id() {
585
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
586
}
587
588
19017
inline double Environment::get_default_trigger_async_id() {
589
  double default_trigger_async_id =
590
19017
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
591
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
592
19017
  if (default_trigger_async_id < 0)
593
18927
    default_trigger_async_id = execution_async_id();
594
19017
  return default_trigger_async_id;
595
}
596
597
1669
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
598
1669
  return options_;
599
}
600
601
318
inline const std::vector<std::string>& Environment::argv() {
602
318
  return argv_;
603
}
604
605
120
inline const std::vector<std::string>& Environment::exec_argv() {
606
120
  return exec_argv_;
607
}
608
609
240
inline const std::string& Environment::exec_path() const {
610
240
  return exec_path_;
611
}
612
613
inline std::string Environment::GetCwd() {
614
  char cwd[PATH_MAX_BYTES];
615
  size_t size = PATH_MAX_BYTES;
616
  const int err = uv_cwd(cwd, &size);
617
618
  if (err == 0) {
619
    CHECK_GT(size, 0);
620
    return cwd;
621
  }
622
623
  // This can fail if the cwd is deleted. In that case, fall back to
624
  // exec_path.
625
  const std::string& exec_path = exec_path_;
626
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
627
}
628
629
#if HAVE_INSPECTOR
630
118
inline void Environment::set_coverage_directory(const char* dir) {
631
118
  coverage_directory_ = std::string(dir);
632
118
}
633
634
143
inline void Environment::set_coverage_connection(
635
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
636
143
  CHECK_NULL(coverage_connection_);
637
143
  std::swap(coverage_connection_, connection);
638
143
}
639
640
431
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
641
431
  return coverage_connection_.get();
642
}
643
644
118
inline const std::string& Environment::coverage_directory() const {
645
118
  return coverage_directory_;
646
}
647
648
inline void Environment::set_cpu_profiler_connection(
649
    std::unique_ptr<profiler::V8CpuProfilerConnection> connection) {
650
  CHECK_NULL(cpu_profiler_connection_);
651
  std::swap(cpu_profiler_connection_, connection);
652
}
653
654
inline profiler::V8CpuProfilerConnection*
655
145
Environment::cpu_profiler_connection() {
656
145
  return cpu_profiler_connection_.get();
657
}
658
659
inline void Environment::set_cpu_prof_interval(uint64_t interval) {
660
  cpu_prof_interval_ = interval;
661
}
662
663
inline uint64_t Environment::cpu_prof_interval() const {
664
  return cpu_prof_interval_;
665
}
666
667
inline void Environment::set_cpu_prof_name(const std::string& name) {
668
  cpu_prof_name_ = name;
669
}
670
671
inline const std::string& Environment::cpu_prof_name() const {
672
  return cpu_prof_name_;
673
}
674
675
inline void Environment::set_cpu_prof_dir(const std::string& dir) {
676
  cpu_prof_dir_ = dir;
677
}
678
679
inline const std::string& Environment::cpu_prof_dir() const {
680
  return cpu_prof_dir_;
681
}
682
683
inline void Environment::set_heap_profiler_connection(
684
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
685
  CHECK_NULL(heap_profiler_connection_);
686
  std::swap(heap_profiler_connection_, connection);
687
}
688
689
inline profiler::V8HeapProfilerConnection*
690
145
Environment::heap_profiler_connection() {
691
145
  return heap_profiler_connection_.get();
692
}
693
694
inline void Environment::set_heap_prof_name(const std::string& name) {
695
  heap_prof_name_ = name;
696
}
697
698
inline const std::string& Environment::heap_prof_name() const {
699
  return heap_prof_name_;
700
}
701
702
inline void Environment::set_heap_prof_dir(const std::string& dir) {
703
  heap_prof_dir_ = dir;
704
}
705
706
inline const std::string& Environment::heap_prof_dir() const {
707
  return heap_prof_dir_;
708
}
709
710
inline void Environment::set_heap_prof_interval(uint64_t interval) {
711
  heap_prof_interval_ = interval;
712
}
713
714
inline uint64_t Environment::heap_prof_interval() const {
715
  return heap_prof_interval_;
716
}
717
718
#endif  // HAVE_INSPECTOR
719
720
inline
721
297
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
722
297
  return inspector_host_port_;
723
}
724
725
1565
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
726
1565
  return options_;
727
}
728
729
inline void IsolateData::set_options(
730
    std::shared_ptr<PerIsolateOptions> options) {
731
  options_ = std::move(options);
732
}
733
734
template <typename Fn>
735
82
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
736
164
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
737
82
  native_immediates_.Push(std::move(callback));
738
739


82
  if (flags & CallbackFlags::kRefed) {
740


81
    if (immediate_info()->ref_count() == 0)
741
56
      ToggleImmediateRef(true);
742
81
    immediate_info()->ref_count_inc(1);
743
  }
744
82
}
745
746
template <typename Fn>
747
12
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
748
  auto callback = native_immediates_threadsafe_.CreateCallback(
749
24
      std::move(cb), flags);
750
  {
751
24
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
752
12
    native_immediates_threadsafe_.Push(std::move(callback));
753

12
    if (task_queues_async_initialized_)
754
11
      uv_async_send(&task_queues_async_);
755
  }
756
12
}
757
758
template <typename Fn>
759
149
void Environment::RequestInterrupt(Fn&& cb) {
760
  auto callback = native_immediates_interrupts_.CreateCallback(
761
298
      std::move(cb), CallbackFlags::kRefed);
762
  {
763
298
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
764
149
    native_immediates_interrupts_.Push(std::move(callback));
765
149
    if (task_queues_async_initialized_)
766
5
      uv_async_send(&task_queues_async_);
767
  }
768
149
  RequestInterruptFromV8();
769
149
}
770
771
86152
inline bool Environment::can_call_into_js() const {
772

86152
  return can_call_into_js_ && !is_stopping();
773
}
774
775
12
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
776
12
  can_call_into_js_ = can_call_into_js;
777
12
}
778
779
140904
inline bool Environment::has_run_bootstrapping_code() const {
780
140904
  return has_run_bootstrapping_code_;
781
}
782
783
152
inline void Environment::DoneBootstrapping() {
784
152
  has_run_bootstrapping_code_ = true;
785
  // This adjusts the return value of base_object_created_after_bootstrap() so
786
  // that tests that check the count do not have to account for internally
787
  // created BaseObjects.
788
152
  base_object_created_by_bootstrap_ = base_object_count_;
789
152
}
790
791
inline bool Environment::has_serialized_options() const {
792
  return has_serialized_options_;
793
}
794
795
120
inline void Environment::set_has_serialized_options(bool value) {
796
120
  has_serialized_options_ = value;
797
120
}
798
799
305
inline bool Environment::is_main_thread() const {
800
305
  return worker_context() == nullptr;
801
}
802
803
120
inline bool Environment::should_not_register_esm_loader() const {
804
120
  return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
805
}
806
807
539
inline bool Environment::owns_process_state() const {
808
539
  return flags_ & EnvironmentFlags::kOwnsProcessState;
809
}
810
811
145
inline bool Environment::owns_inspector() const {
812
145
  return flags_ & EnvironmentFlags::kOwnsInspector;
813
}
814
815
33212
inline bool Environment::tracks_unmanaged_fds() const {
816
33212
  return flags_ & EnvironmentFlags::kTrackUnmanagedFds;
817
}
818
819
bool Environment::filehandle_close_warning() const {
820
  return emit_filehandle_warning_;
821
}
822
823
void Environment::set_filehandle_close_warning(bool on) {
824
  emit_filehandle_warning_ = on;
825
}
826
827
void Environment::set_source_maps_enabled(bool on) {
828
  source_maps_enabled_ = on;
829
}
830
831
3
bool Environment::source_maps_enabled() const {
832
3
  return source_maps_enabled_;
833
}
834
835
186
inline uint64_t Environment::thread_id() const {
836
186
  return thread_id_;
837
}
838
839
409
inline worker::Worker* Environment::worker_context() const {
840
409
  return isolate_data()->worker_context();
841
}
842
843
inline void Environment::add_sub_worker_context(worker::Worker* context) {
844
  sub_worker_contexts_.insert(context);
845
}
846
847
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
848
  sub_worker_contexts_.erase(context);
849
}
850
851
template <typename Fn>
852
inline void Environment::ForEachWorker(Fn&& iterator) {
853
  for (worker::Worker* w : sub_worker_contexts_) iterator(w);
854
}
855
856
inline void Environment::add_refs(int64_t diff) {
857
  task_queues_async_refs_ += diff;
858
  CHECK_GE(task_queues_async_refs_, 0);
859
  if (task_queues_async_refs_ == 0)
860
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
861
  else
862
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
863
}
864
865
142027
inline bool Environment::is_stopping() const {
866
142027
  return is_stopping_.load();
867
}
868
869
156
inline void Environment::set_stopping(bool value) {
870
156
  is_stopping_.store(value);
871
156
}
872
873
3
inline std::list<node_module>* Environment::extra_linked_bindings() {
874
3
  return &extra_linked_bindings_;
875
}
876
877
7
inline node_module* Environment::extra_linked_bindings_head() {
878
10
  return extra_linked_bindings_.size() > 0 ?
879
10
      &extra_linked_bindings_.front() : nullptr;
880
}
881
882
7
inline const Mutex& Environment::extra_linked_bindings_mutex() const {
883
7
  return extra_linked_bindings_mutex_;
884
}
885
886
334
inline performance::PerformanceState* Environment::performance_state() {
887
334
  return performance_state_.get();
888
}
889
890
inline std::unordered_map<std::string, uint64_t>*
891
    Environment::performance_marks() {
892
  return &performance_marks_;
893
}
894
895
492398
inline IsolateData* Environment::isolate_data() const {
896
492398
  return isolate_data_;
897
}
898
899
std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
900
2772
    Environment::released_allocated_buffers() {
901
2772
  return &released_allocated_buffers_;
902
}
903
904
inline void Environment::ThrowError(const char* errmsg) {
905
  ThrowError(v8::Exception::Error, errmsg);
906
}
907
908
inline void Environment::ThrowTypeError(const char* errmsg) {
909
  ThrowError(v8::Exception::TypeError, errmsg);
910
}
911
912
inline void Environment::ThrowRangeError(const char* errmsg) {
913
  ThrowError(v8::Exception::RangeError, errmsg);
914
}
915
916
inline void Environment::ThrowError(
917
    v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
918
    const char* errmsg) {
919
  v8::HandleScope handle_scope(isolate());
920
  isolate()->ThrowException(fun(OneByteString(isolate(), errmsg)));
921
}
922
923
inline void Environment::ThrowErrnoException(int errorno,
924
                                             const char* syscall,
925
                                             const char* message,
926
                                             const char* path) {
927
  isolate()->ThrowException(
928
      ErrnoException(isolate(), errorno, syscall, message, path));
929
}
930
931
inline void Environment::ThrowUVException(int errorno,
932
                                          const char* syscall,
933
                                          const char* message,
934
                                          const char* path,
935
                                          const char* dest) {
936
  isolate()->ThrowException(
937
      UVException(isolate(), errorno, syscall, message, path, dest));
938
}
939
940
inline v8::Local<v8::FunctionTemplate>
941
32634
    Environment::NewFunctionTemplate(v8::FunctionCallback callback,
942
                                     v8::Local<v8::Signature> signature,
943
                                     v8::ConstructorBehavior behavior,
944
                                     v8::SideEffectType side_effect_type) {
945
  return v8::FunctionTemplate::New(isolate(), callback, v8::Local<v8::Value>(),
946
32634
                                   signature, 0, behavior, side_effect_type);
947
}
948
949
14531
inline void Environment::SetMethod(v8::Local<v8::Object> that,
950
                                   const char* name,
951
                                   v8::FunctionCallback callback) {
952
14531
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
953
  v8::Local<v8::Function> function =
954
29062
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
955
                          v8::ConstructorBehavior::kThrow,
956
14531
                          v8::SideEffectType::kHasSideEffect)
957
29062
          ->GetFunction(context)
958
14531
          .ToLocalChecked();
959
  // kInternalized strings are created in the old space.
960
14531
  const v8::NewStringType type = v8::NewStringType::kInternalized;
961
  v8::Local<v8::String> name_string =
962
29062
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
963
29062
  that->Set(context, name_string, function).Check();
964
14531
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
965
14531
}
966
967
3642
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
968
                                               const char* name,
969
                                               v8::FunctionCallback callback) {
970
3642
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
971
  v8::Local<v8::Function> function =
972
7284
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
973
                          v8::ConstructorBehavior::kThrow,
974
3642
                          v8::SideEffectType::kHasNoSideEffect)
975
7284
          ->GetFunction(context)
976
3642
          .ToLocalChecked();
977
  // kInternalized strings are created in the old space.
978
3642
  const v8::NewStringType type = v8::NewStringType::kInternalized;
979
  v8::Local<v8::String> name_string =
980
7284
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
981
7284
  that->Set(context, name_string, function).Check();
982
3642
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
983
3642
}
984
985
9670
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
986
                                        const char* name,
987
                                        v8::FunctionCallback callback) {
988
9670
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
989
  v8::Local<v8::FunctionTemplate> t =
990
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
991
9670
                          v8::SideEffectType::kHasSideEffect);
992
  // kInternalized strings are created in the old space.
993
9670
  const v8::NewStringType type = v8::NewStringType::kInternalized;
994
  v8::Local<v8::String> name_string =
995
19340
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
996
19340
  that->PrototypeTemplate()->Set(name_string, t);
997
9670
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
998
9670
}
999
1000
872
inline void Environment::SetProtoMethodNoSideEffect(
1001
    v8::Local<v8::FunctionTemplate> that,
1002
    const char* name,
1003
    v8::FunctionCallback callback) {
1004
872
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1005
  v8::Local<v8::FunctionTemplate> t =
1006
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1007
872
                          v8::SideEffectType::kHasNoSideEffect);
1008
  // kInternalized strings are created in the old space.
1009
872
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1010
  v8::Local<v8::String> name_string =
1011
1744
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1012
1744
  that->PrototypeTemplate()->Set(name_string, t);
1013
872
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1014
872
}
1015
1016
inline void Environment::SetInstanceMethod(v8::Local<v8::FunctionTemplate> that,
1017
                                           const char* name,
1018
                                           v8::FunctionCallback callback) {
1019
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1020
  v8::Local<v8::FunctionTemplate> t =
1021
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1022
                          v8::SideEffectType::kHasSideEffect);
1023
  // kInternalized strings are created in the old space.
1024
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1025
  v8::Local<v8::String> name_string =
1026
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1027
  that->InstanceTemplate()->Set(name_string, t);
1028
  t->SetClassName(name_string);
1029
}
1030
1031
2284
inline void Environment::SetConstructorFunction(
1032
    v8::Local<v8::Object> that,
1033
    const char* name,
1034
    v8::Local<v8::FunctionTemplate> tmpl) {
1035
2284
  SetConstructorFunction(that, OneByteString(isolate(), name), tmpl);
1036
2284
}
1037
1038
2444
inline void Environment::SetConstructorFunction(
1039
    v8::Local<v8::Object> that,
1040
    v8::Local<v8::String> name,
1041
    v8::Local<v8::FunctionTemplate> tmpl) {
1042
2444
  tmpl->SetClassName(name);
1043
4888
  that->Set(
1044
      context(),
1045
      name,
1046
12220
      tmpl->GetFunction(context()).ToLocalChecked()).Check();
1047
2444
}
1048
1049
48243
void Environment::AddCleanupHook(CleanupCallback fn, void* arg) {
1050
96486
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
1051
48243
    fn, arg, cleanup_hook_counter_++
1052
48243
  });
1053
  // Make sure there was no existing element with these values.
1054
48243
  CHECK_EQ(insertion_info.second, true);
1055
48243
}
1056
1057
47041
void Environment::RemoveCleanupHook(CleanupCallback fn, void* arg) {
1058
47041
  CleanupHookCallback search { fn, arg, 0 };
1059
47041
  cleanup_hooks_.erase(search);
1060
47041
}
1061
1062
123130
size_t CleanupHookCallback::Hash::operator()(
1063
    const CleanupHookCallback& cb) const {
1064
123130
  return std::hash<void*>()(cb.arg_);
1065
}
1066
1067
61112
bool CleanupHookCallback::Equal::operator()(
1068
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
1069

61112
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
1070
}
1071
1072
BaseObject* CleanupHookCallback::GetBaseObject() const {
1073
  if (fn_ == BaseObject::DeleteMe)
1074
    return static_cast<BaseObject*>(arg_);
1075
  else
1076
    return nullptr;
1077
}
1078
1079
template <typename T>
1080
void Environment::ForEachBaseObject(T&& iterator) {
1081
  for (const auto& hook : cleanup_hooks_) {
1082
    BaseObject* obj = hook.GetBaseObject();
1083
    if (obj != nullptr)
1084
      iterator(obj);
1085
  }
1086
}
1087
1088
95125
void Environment::modify_base_object_count(int64_t delta) {
1089
95125
  base_object_count_ += delta;
1090
95125
}
1091
1092
14
int64_t Environment::base_object_created_after_bootstrap() const {
1093
14
  return base_object_count_ - base_object_created_by_bootstrap_;
1094
}
1095
1096
2
int64_t Environment::base_object_count() const {
1097
2
  return base_object_count_;
1098
}
1099
1100
15
void Environment::set_main_utf16(std::unique_ptr<v8::String::Value> str) {
1101
15
  CHECK(!main_utf16_);
1102
15
  main_utf16_ = std::move(str);
1103
15
}
1104
1105
3
void Environment::set_process_exit_handler(
1106
    std::function<void(Environment*, int)>&& handler) {
1107
3
  process_exit_handler_ = std::move(handler);
1108
3
}
1109
1110
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1111
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1112
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1113
#define V(TypeName, PropertyName)                                             \
1114
  inline                                                                      \
1115
  v8::Local<TypeName> IsolateData::PropertyName() const {                     \
1116
    return PropertyName ## _ .Get(isolate_);                                  \
1117
  }
1118
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1119
322
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1120
425900
  PER_ISOLATE_STRING_PROPERTIES(VS)
1121
462
#undef V
1122
917
#undef VS
1123
1144
#undef VY
1124
272
#undef VP
1125
2155
1126
4071
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1127
522
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1128
771
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1129
1513
#define V(TypeName, PropertyName)                                             \
1130
774
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1131
    return isolate_data()->PropertyName();                                    \
1132
  }
1133
13491
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1134
27146
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1135
232356
  PER_ISOLATE_STRING_PROPERTIES(VS)
1136
120
#undef V
1137
110
#undef VS
1138
7824
#undef VY
1139
104
#undef VP
1140
2467
1141
2795
#define V(PropertyName, TypeName)                                             \
1142
313
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1143
438
    return PersistentToLocal::Strong(PropertyName ## _);                      \
1144
492
  }                                                                           \
1145
158
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
1146
    PropertyName ## _.Reset(isolate(), value);                                \
1147
  }
1148
5992
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1149
150165
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1150
2415
#undef V
1151
1393
1152
670636
v8::Local<v8::Context> Environment::context() const {
1153
689924
  return PersistentToLocal::Strong(context_);
1154
20366
}
1155
3500
1156
3051
}  // namespace node
1157
463
1158
166
// These two files depend on each other. Including base_object-inl.h after this
1159
211
// file is the easiest way to avoid issues with that circular dependency.
1160
474
#include "base_object-inl.h"
1161
270
1162
13913
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1163
13829
1164
444
#endif  // SRC_ENV_INL_H_