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: 417 421 99.0 %
Date: 2019-02-13 22:28:58 Branches: 65 90 72.2 %

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 "env.h"
29
#include "node.h"
30
#include "util-inl.h"
31
#include "uv.h"
32
#include "v8.h"
33
#include "node_perf_common.h"
34
#include "node_context_data.h"
35
#include "node_worker.h"
36
37
#include <stddef.h>
38
#include <stdint.h>
39
40
namespace node {
41
42
inline v8::Isolate* IsolateData::isolate() const {
43
  return isolate_;
44
}
45
46
3459271
inline uv_loop_t* IsolateData::event_loop() const {
47
3459271
  return event_loop_;
48
}
49
50
4415
inline uint32_t* IsolateData::zero_fill_field() const {
51
4415
  return zero_fill_field_;
52
}
53
54
142490
inline MultiIsolatePlatform* IsolateData::platform() const {
55
142490
  return platform_;
56
}
57
58
4417
inline Environment::AsyncHooks::AsyncHooks()
59
    : async_ids_stack_(env()->isolate(), 16 * 2),
60
      fields_(env()->isolate(), kFieldsCount),
61
185514
      async_id_fields_(env()->isolate(), kUidFieldsCount) {
62
4417
  v8::HandleScope handle_scope(env()->isolate());
63
64
  // Always perform async_hooks checks, not just when async_hooks is enabled.
65
  // TODO(AndreasMadsen): Consider removing this for LTS releases.
66
  // See discussion in https://github.com/nodejs/node/pull/15454
67
  // When removing this, do it by reverting the commit. Otherwise the test
68
  // and flag changes won't be included.
69
4417
  fields_[kCheck] = 1;
70
71
  // kDefaultTriggerAsyncId should be -1, this indicates that there is no
72
  // specified default value and it should fallback to the executionAsyncId.
73
  // 0 is not used as the magic value, because that indicates a missing context
74
  // which is different from a default context.
75
4417
  async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
76
77
  // kAsyncIdCounter should start at 1 because that'll be the id the execution
78
  // context during bootstrap (code that runs before entering uv_run()).
79
4417
  async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
80
81
  // Create all the provider strings that will be passed to JS. Place them in
82
  // an array so the array index matches the PROVIDER id offset. This way the
83
  // strings can be retrieved quickly.
84
#define V(Provider)                                                           \
85
  providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                           \
86
      env()->isolate(),                                                       \
87
      v8::String::NewFromOneByte(                                             \
88
        env()->isolate(),                                                     \
89
        reinterpret_cast<const uint8_t*>(#Provider),                          \
90
        v8::NewStringType::kInternalized,                                     \
91
        sizeof(#Provider) - 1).ToLocalChecked());
92
366611
  NODE_ASYNC_PROVIDER_TYPES(V)
93
#undef V
94
4417
}
95
96
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
97
5216363
Environment::AsyncHooks::fields() {
98
5216363
  return fields_;
99
}
100
101
inline AliasedBuffer<double, v8::Float64Array>&
102
4686771
Environment::AsyncHooks::async_id_fields() {
103
4686771
  return async_id_fields_;
104
}
105
106
inline AliasedBuffer<double, v8::Float64Array>&
107
4413
Environment::AsyncHooks::async_ids_stack() {
108
4413
  return async_ids_stack_;
109
}
110
111
363479
inline v8::Local<v8::String> Environment::AsyncHooks::provider_string(int idx) {
112
726958
  return providers_[idx].Get(env()->isolate());
113
}
114
115
1
inline void Environment::AsyncHooks::no_force_checks() {
116
1
  fields_[kCheck] -= 1;
117
1
}
118
119
839951
inline Environment* Environment::AsyncHooks::env() {
120
839951
  return Environment::ForAsyncHooks(this);
121
}
122
123
// Remember to keep this code aligned with pushAsyncIds() in JS.
124
1208872
inline void Environment::AsyncHooks::push_async_ids(double async_id,
125
                                                    double trigger_async_id) {
126
  // Since async_hooks is experimental, do only perform the check
127
  // when async_hooks is enabled.
128
1208872
  if (fields_[kCheck] > 0) {
129
1208867
    CHECK_GE(async_id, -1);
130
1208867
    CHECK_GE(trigger_async_id, -1);
131
  }
132
133
1208874
  uint32_t offset = fields_[kStackLength];
134
1208875
  if (offset * 2 >= async_ids_stack_.Length())
135
8
    grow_async_ids_stack();
136
1208875
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
137
1208875
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
138
1208873
  fields_[kStackLength] += 1;
139
1208875
  async_id_fields_[kExecutionAsyncId] = async_id;
140
1208874
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
141
1208874
}
142
143
// Remember to keep this code aligned with popAsyncIds() in JS.
144
1208544
inline bool Environment::AsyncHooks::pop_async_id(double async_id) {
145
  // In case of an exception then this may have already been reset, if the
146
  // stack was multiple MakeCallback()'s deep.
147
1208544
  if (fields_[kStackLength] == 0) return false;
148
149
  // Ask for the async_id to be restored as a check that the stack
150
  // hasn't been corrupted.
151
  // Since async_hooks is experimental, do only perform the check
152
  // when async_hooks is enabled.
153


1207914
  if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) {
154
    fprintf(stderr,
155
            "Error: async hook stack has become corrupted ("
156
            "actual: %.f, expected: %.f)\n",
157
            async_id_fields_.GetValue(kExecutionAsyncId),
158
4
            async_id);
159
4
    DumpBacktrace(stderr);
160
4
    fflush(stderr);
161
4
    if (!env()->abort_on_uncaught_exception())
162
4
      exit(1);
163
    fprintf(stderr, "\n");
164
    fflush(stderr);
165
    ABORT_NO_BACKTRACE();
166
  }
167
168
1207909
  uint32_t offset = fields_[kStackLength] - 1;
169
1207910
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
170
1207910
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
171
1207910
  fields_[kStackLength] = offset;
172
173
1207909
  return fields_[kStackLength] > 0;
174
}
175
176
// Keep in sync with clearAsyncIdStack in lib/internal/async_hooks.js.
177
52
inline void Environment::AsyncHooks::clear_async_id_stack() {
178
52
  async_id_fields_[kExecutionAsyncId] = 0;
179
52
  async_id_fields_[kTriggerAsyncId] = 0;
180
52
  fields_[kStackLength] = 0;
181
52
}
182
183
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
184
// async_wrap-inl.h to avoid a circular dependency.
185
186
958221
inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope
187
  ::DefaultTriggerAsyncIdScope(Environment* env,
188
                               double default_trigger_async_id)
189
958221
    : async_hooks_(env->async_hooks()) {
190
958221
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
191
958221
    CHECK_GE(default_trigger_async_id, 0);
192
  }
193
194
1916442
  old_default_trigger_async_id_ =
195
1916442
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
196
1916442
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
197
958221
    default_trigger_async_id;
198
958221
}
199
200
958220
inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope
201
  ::~DefaultTriggerAsyncIdScope() {
202
1916440
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
203
958220
    old_default_trigger_async_id_;
204
958220
}
205
206
207
839951
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
208
839951
  return ContainerOf(&Environment::async_hooks_, hooks);
209
}
210
211
212
1382629
inline Environment::AsyncCallbackScope::AsyncCallbackScope(Environment* env)
213
1382629
    : env_(env) {
214
1382629
  env_->makecallback_cntr_++;
215
1382629
}
216
217
1382032
inline Environment::AsyncCallbackScope::~AsyncCallbackScope() {
218
1382032
  env_->makecallback_cntr_--;
219
1382032
}
220
221
1204210
inline size_t Environment::makecallback_depth() const {
222
1204210
  return makecallback_cntr_;
223
}
224
225
4417
inline Environment::ImmediateInfo::ImmediateInfo(v8::Isolate* isolate)
226
4417
    : fields_(isolate, kFieldsCount) {}
227
228
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
229
4409
    Environment::ImmediateInfo::fields() {
230
4409
  return fields_;
231
}
232
233
547736
inline uint32_t Environment::ImmediateInfo::count() const {
234
547736
  return fields_[kCount];
235
}
236
237
79410
inline uint32_t Environment::ImmediateInfo::ref_count() const {
238
79410
  return fields_[kRefCount];
239
}
240
241
52513
inline bool Environment::ImmediateInfo::has_outstanding() const {
242
52513
  return fields_[kHasOutstanding] == 1;
243
}
244
245
49612
inline void Environment::ImmediateInfo::count_inc(uint32_t increment) {
246
49612
  fields_[kCount] += increment;
247
49612
}
248
249
46234
inline void Environment::ImmediateInfo::count_dec(uint32_t decrement) {
250
46234
  fields_[kCount] -= decrement;
251
46234
}
252
253
27418
inline void Environment::ImmediateInfo::ref_count_inc(uint32_t increment) {
254
27418
  fields_[kRefCount] += increment;
255
27418
}
256
257
46234
inline void Environment::ImmediateInfo::ref_count_dec(uint32_t decrement) {
258
46234
  fields_[kRefCount] -= decrement;
259
46234
}
260
261
4417
inline Environment::TickInfo::TickInfo(v8::Isolate* isolate)
262
4417
    : fields_(isolate, kFieldsCount) {}
263
264
4411
inline AliasedBuffer<uint8_t, v8::Uint8Array>& Environment::TickInfo::fields() {
265
4411
  return fields_;
266
}
267
268
1951489
inline bool Environment::TickInfo::has_tick_scheduled() const {
269
1951489
  return fields_[kHasTickScheduled] == 1;
270
}
271
272
421699
inline bool Environment::TickInfo::has_rejection_to_warn() const {
273
421699
  return fields_[kHasRejectionToWarn] == 1;
274
}
275
276
8940
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
277
                                         const ContextInfo& info) {
278
  context->SetAlignedPointerInEmbedderData(
279
8940
      ContextEmbedderIndex::kEnvironment, this);
280
  // Used by EnvPromiseHook to know that we are on a node context.
281
  context->SetAlignedPointerInEmbedderData(
282
17880
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
283
#if HAVE_INSPECTOR
284
8940
  inspector_agent()->ContextCreated(context, info);
285
#endif  // HAVE_INSPECTOR
286
8940
}
287
288
1242143
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
289
1242143
  return GetCurrent(isolate->GetCurrentContext());
290
}
291
292
1453926
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
293


5815706
  if (UNLIKELY(context.IsEmpty() ||
294
      context->GetNumberOfEmbedderDataFields() <
295
          ContextEmbedderIndex::kContextTag ||
296
      context->GetAlignedPointerFromEmbedderData(
297
          ContextEmbedderIndex::kContextTag) !=
298
          Environment::kNodeContextTagPtr)) {
299
1
    return nullptr;
300
  }
301
302
  return static_cast<Environment*>(
303
      context->GetAlignedPointerFromEmbedderData(
304
2907854
          ContextEmbedderIndex::kEnvironment));
305
}
306
307
8359565
inline Environment* Environment::GetCurrent(
308
    const v8::FunctionCallbackInfo<v8::Value>& info) {
309
16719130
  CHECK(info.Data()->IsExternal());
310
25078704
  return static_cast<Environment*>(info.Data().As<v8::External>()->Value());
311
}
312
313
template <typename T>
314
13921
inline Environment* Environment::GetCurrent(
315
    const v8::PropertyCallbackInfo<T>& info) {
316

27842
  CHECK(info.Data()->IsExternal());
317
  return static_cast<Environment*>(
318
41763
      info.Data().template As<v8::External>()->Value());
319
}
320
321
7
inline Environment* Environment::GetThreadLocalEnv() {
322
7
  return static_cast<Environment*>(uv_key_get(&thread_local_env));
323
}
324
325
155
inline bool Environment::profiler_idle_notifier_started() const {
326
155
  return profiler_idle_notifier_started_;
327
}
328
329
72328079
inline v8::Isolate* Environment::isolate() const {
330
72328079
  return isolate_;
331
}
332
333
5681
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
334
5681
  return ContainerOf(&Environment::timer_handle_, handle);
335
}
336
337
21690
inline uv_timer_t* Environment::timer_handle() {
338
21690
  return &timer_handle_;
339
}
340
341
547736
inline Environment* Environment::from_immediate_check_handle(
342
    uv_check_t* handle) {
343
547736
  return ContainerOf(&Environment::immediate_check_handle_, handle);
344
}
345
346
17668
inline uv_check_t* Environment::immediate_check_handle() {
347
17668
  return &immediate_check_handle_;
348
}
349
350
82727
inline uv_idle_t* Environment::immediate_idle_handle() {
351
82727
  return &immediate_idle_handle_;
352
}
353
354
22085
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
355
                                               HandleCleanupCb cb,
356
                                               void* arg) {
357
22085
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
358
22085
}
359
360
template <typename T, typename OnCloseCallback>
361
20627
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
362
20627
  handle_cleanup_waiting_++;
363
  static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle");
364
  static_assert(offsetof(T, data) == offsetof(uv_handle_t, data),
365
                "T is a libuv handle");
366
  static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb),
367
                "T is a libuv handle");
368
  struct CloseData {
369
    Environment* env;
370
    OnCloseCallback callback;
371
    void* original_data;
372
  };
373
20627
  handle->data = new CloseData { this, callback, handle->data };
374
82462
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
375
20604
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
376
20604
    data->env->handle_cleanup_waiting_--;
377
20604
    handle->data = data->original_data;
378
20604
    data->callback(reinterpret_cast<T*>(handle));
379
61858
  });
380
20627
}
381
382
222079
void Environment::IncreaseWaitingRequestCounter() {
383
222079
  request_waiting_++;
384
222079
}
385
386
222062
void Environment::DecreaseWaitingRequestCounter() {
387
222062
  request_waiting_--;
388
222062
  CHECK_GE(request_waiting_, 0);
389
222062
}
390
391
3454853
inline uv_loop_t* Environment::event_loop() const {
392
3454853
  return isolate_data()->event_loop();
393
}
394
395
126
inline void Environment::TryLoadAddon(
396
    const char* filename,
397
    int flags,
398
    std::function<bool(binding::DLib*)> was_loaded) {
399
126
  loaded_addons_.emplace_back(filename, flags);
400
126
  if (!was_loaded(&loaded_addons_.back())) {
401
6
    loaded_addons_.pop_back();
402
  }
403
126
}
404
405
10868011
inline Environment::AsyncHooks* Environment::async_hooks() {
406
10868011
  return &async_hooks_;
407
}
408
409
853566
inline Environment::ImmediateInfo* Environment::immediate_info() {
410
853566
  return &immediate_info_;
411
}
412
413
980159
inline Environment::TickInfo* Environment::tick_info() {
414
980159
  return &tick_info_;
415
}
416
417
691429
inline uint64_t Environment::timer_base() const {
418
691429
  return timer_base_;
419
}
420
421
12
inline bool Environment::printed_error() const {
422
12
  return printed_error_;
423
}
424
425
12
inline void Environment::set_printed_error(bool value) {
426
12
  printed_error_ = value;
427
12
}
428
429
3902
inline void Environment::set_trace_sync_io(bool value) {
430
3902
  options_->trace_sync_io = value;
431
3902
}
432
433
19
inline bool Environment::abort_on_uncaught_exception() const {
434
19
  return options_->abort_on_uncaught_exception;
435
}
436
437
151
inline void Environment::set_abort_on_uncaught_exception(bool value) {
438
151
  options_->abort_on_uncaught_exception = value;
439
151
}
440
441
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
442
4447
Environment::should_abort_on_uncaught_toggle() {
443
4447
  return should_abort_on_uncaught_toggle_;
444
}
445
446
inline AliasedBuffer<uint8_t, v8::Uint8Array>&
447
4499
Environment::trace_category_state() {
448
4499
  return trace_category_state_;
449
}
450
451
inline AliasedBuffer<int32_t, v8::Int32Array>&
452
2284437
Environment::stream_base_state() {
453
2284437
  return stream_base_state_;
454
}
455
456
258
inline uint32_t Environment::get_next_module_id() {
457
258
  return module_id_counter_++;
458
}
459
446216
inline uint32_t Environment::get_next_script_id() {
460
446216
  return script_id_counter_++;
461
}
462
463
446560
Environment::ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
464
    Environment* env)
465
446560
    : env_(env) {
466
446560
  env_->should_not_abort_scope_counter_++;
467
446560
}
468
469
446559
Environment::ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
470
446559
  Close();
471
446559
}
472
473
446881
void Environment::ShouldNotAbortOnUncaughtScope::Close() {
474
446881
  if (env_ != nullptr) {
475
446559
    env_->should_not_abort_scope_counter_--;
476
446559
    env_ = nullptr;
477
  }
478
446881
}
479
480
1
bool Environment::inside_should_not_abort_on_uncaught_scope() const {
481
1
  return should_not_abort_scope_counter_ > 0;
482
}
483
484
203033
inline std::vector<double>* Environment::destroy_async_id_list() {
485
203033
  return &destroy_async_id_list_;
486
}
487
488
460534
inline double Environment::new_async_id() {
489
460534
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
490
460534
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
491
}
492
493
388067
inline double Environment::execution_async_id() {
494
388067
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
495
}
496
497
37234
inline double Environment::trigger_async_id() {
498
37234
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
499
}
500
501
460531
inline double Environment::get_default_trigger_async_id() {
502
  double default_trigger_async_id =
503
460531
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
504
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
505
460531
  if (default_trigger_async_id < 0)
506
350181
    default_trigger_async_id = execution_async_id();
507
460531
  return default_trigger_async_id;
508
}
509
510
4404
inline double* Environment::heap_statistics_buffer() const {
511
4404
  CHECK_NOT_NULL(heap_statistics_buffer_);
512
4404
  return heap_statistics_buffer_;
513
}
514
515
4402
inline void Environment::set_heap_statistics_buffer(double* pointer) {
516
4402
  CHECK_NULL(heap_statistics_buffer_);  // Should be set only once.
517
4402
  heap_statistics_buffer_ = pointer;
518
4402
}
519
520
4403
inline double* Environment::heap_space_statistics_buffer() const {
521
4403
  CHECK_NOT_NULL(heap_space_statistics_buffer_);
522
4403
  return heap_space_statistics_buffer_;
523
}
524
525
4402
inline void Environment::set_heap_space_statistics_buffer(double* pointer) {
526
4402
  CHECK_NULL(heap_space_statistics_buffer_);  // Should be set only once.
527
4402
  heap_space_statistics_buffer_ = pointer;
528
4402
}
529
530
195043
inline char* Environment::http_parser_buffer() const {
531
195043
  return http_parser_buffer_;
532
}
533
534
283
inline void Environment::set_http_parser_buffer(char* buffer) {
535
283
  CHECK_NULL(http_parser_buffer_);  // Should be set only once.
536
283
  http_parser_buffer_ = buffer;
537
283
}
538
539
65008
inline bool Environment::http_parser_buffer_in_use() const {
540
65008
  return http_parser_buffer_in_use_;
541
}
542
543
130013
inline void Environment::set_http_parser_buffer_in_use(bool in_use) {
544
130013
  http_parser_buffer_in_use_ = in_use;
545
130013
}
546
547
19406
inline http2::Http2State* Environment::http2_state() const {
548
19406
  return http2_state_.get();
549
}
550
551
218
inline void Environment::set_http2_state(
552
    std::unique_ptr<http2::Http2State> buffer) {
553
218
  CHECK(!http2_state_);  // Should be set only once.
554
218
  http2_state_ = std::move(buffer);
555
218
}
556
557
688529
bool Environment::debug_enabled(DebugCategory category) const {
558
  DCHECK_GE(static_cast<int>(category), 0);
559
  DCHECK_LT(static_cast<int>(category),
560
           static_cast<int>(DebugCategory::CATEGORY_COUNT));
561
688529
  return debug_enabled_[static_cast<int>(category)];
562
}
563
564
4
void Environment::set_debug_enabled(DebugCategory category, bool enabled) {
565
  DCHECK_GE(static_cast<int>(category), 0);
566
  DCHECK_LT(static_cast<int>(category),
567
           static_cast<int>(DebugCategory::CATEGORY_COUNT));
568
4
  debug_enabled_[static_cast<int>(category)] = enabled;
569
4
}
570
571
inline AliasedBuffer<double, v8::Float64Array>*
572
592815
Environment::fs_stats_field_array() {
573
592815
  return &fs_stats_field_array_;
574
}
575
576
inline AliasedBuffer<uint64_t, v8::BigUint64Array>*
577
4416
Environment::fs_stats_field_bigint_array() {
578
4416
  return &fs_stats_field_bigint_array_;
579
}
580
581
inline std::vector<std::unique_ptr<fs::FileHandleReadWrap>>&
582
438
Environment::file_handle_read_wrap_freelist() {
583
438
  return file_handle_read_wrap_freelist_;
584
}
585
586
114413
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
587
114413
  return options_;
588
}
589
590
8917
inline std::shared_ptr<HostPort> Environment::inspector_host_port() {
591
8917
  return inspector_host_port_;
592
}
593
594
13373
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
595
13373
  return options_;
596
}
597
598
3
inline void IsolateData::set_options(
599
    std::shared_ptr<PerIsolateOptions> options) {
600
3
  options_ = options;
601
3
}
602
603
49612
void Environment::CreateImmediate(native_immediate_callback cb,
604
                                  void* data,
605
                                  v8::Local<v8::Object> obj,
606
                                  bool ref) {
607
  native_immediate_callbacks_.push_back({
608
    cb,
609
    data,
610
49612
    std::unique_ptr<Persistent<v8::Object>>(obj.IsEmpty() ?
611
27414
        nullptr : new Persistent<v8::Object>(isolate_, obj)),
612
    ref
613

126638
  });
614
49612
  immediate_info()->count_inc(1);
615
49612
}
616
617
27418
void Environment::SetImmediate(native_immediate_callback cb,
618
                               void* data,
619
                               v8::Local<v8::Object> obj) {
620
27418
  CreateImmediate(cb, data, obj, true);
621
622
27418
  if (immediate_info()->ref_count() == 0)
623
22674
    ToggleImmediateRef(true);
624
27418
  immediate_info()->ref_count_inc(1);
625
27418
}
626
627
22194
void Environment::SetUnrefImmediate(native_immediate_callback cb,
628
                                    void* data,
629
                                    v8::Local<v8::Object> obj) {
630
22194
  CreateImmediate(cb, data, obj, false);
631
22194
}
632
633
4567991
inline bool Environment::can_call_into_js() const {
634

4567991
  return can_call_into_js_ && (is_main_thread() || !is_stopping_worker());
635
}
636
637
4048
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
638
4048
  can_call_into_js_ = can_call_into_js;
639
4048
}
640
641
4416
inline bool Environment::has_run_bootstrapping_code() const {
642
4416
  return has_run_bootstrapping_code_;
643
}
644
645
4416
inline void Environment::set_has_run_bootstrapping_code(bool value) {
646
4416
  has_run_bootstrapping_code_ = value;
647
4416
}
648
649
4597482
inline bool Environment::is_main_thread() const {
650
4597482
  return flags_ & kIsMainThread;
651
}
652
653
26703
inline bool Environment::owns_process_state() const {
654
26703
  return flags_ & kOwnsProcessState;
655
}
656
657
4417
inline bool Environment::owns_inspector() const {
658
4417
  return flags_ & kOwnsInspector;
659
}
660
661
4558
inline uint64_t Environment::thread_id() const {
662
4558
  return thread_id_;
663
}
664
665
inline worker::Worker* Environment::worker_context() const {
666
  return worker_context_;
667
}
668
669
151
inline void Environment::set_worker_context(worker::Worker* context) {
670
151
  CHECK_NULL(worker_context_);  // Should be set only once.
671
151
  worker_context_ = context;
672
151
}
673
674
154
inline void Environment::add_sub_worker_context(worker::Worker* context) {
675
154
  sub_worker_contexts_.insert(context);
676
154
}
677
678
176
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
679
176
  sub_worker_contexts_.erase(context);
680
176
}
681
682
20073
inline bool Environment::is_stopping_worker() const {
683
20073
  CHECK(!is_main_thread());
684
20073
  return worker_context_->is_stopped();
685
}
686
687
34430
inline performance::performance_state* Environment::performance_state() {
688
34430
  return performance_state_.get();
689
}
690
691
inline std::unordered_map<std::string, uint64_t>*
692
38
    Environment::performance_marks() {
693
38
  return &performance_marks_;
694
}
695
696
8384469
inline IsolateData* Environment::isolate_data() const {
697
8384469
  return isolate_data_;
698
}
699
700
698
inline void Environment::ThrowError(const char* errmsg) {
701
698
  ThrowError(v8::Exception::Error, errmsg);
702
698
}
703
704
5
inline void Environment::ThrowTypeError(const char* errmsg) {
705
5
  ThrowError(v8::Exception::TypeError, errmsg);
706
5
}
707
708
inline void Environment::ThrowRangeError(const char* errmsg) {
709
  ThrowError(v8::Exception::RangeError, errmsg);
710
}
711
712
703
inline void Environment::ThrowError(
713
    v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
714
    const char* errmsg) {
715
703
  v8::HandleScope handle_scope(isolate());
716
703
  isolate()->ThrowException(fun(OneByteString(isolate(), errmsg)));
717
703
}
718
719
3
inline void Environment::ThrowErrnoException(int errorno,
720
                                             const char* syscall,
721
                                             const char* message,
722
                                             const char* path) {
723
  isolate()->ThrowException(
724
3
      ErrnoException(isolate(), errorno, syscall, message, path));
725
3
}
726
727
14
inline void Environment::ThrowUVException(int errorno,
728
                                          const char* syscall,
729
                                          const char* message,
730
                                          const char* path,
731
                                          const char* dest) {
732
  isolate()->ThrowException(
733
14
      UVException(isolate(), errorno, syscall, message, path, dest));
734
14
}
735
736
inline v8::Local<v8::FunctionTemplate>
737
1611944
    Environment::NewFunctionTemplate(v8::FunctionCallback callback,
738
                                     v8::Local<v8::Signature> signature,
739
                                     v8::ConstructorBehavior behavior,
740
                                     v8::SideEffectType side_effect_type) {
741
1611944
  v8::Local<v8::External> external = as_external();
742
  return v8::FunctionTemplate::New(isolate(), callback, external,
743
1611947
                                   signature, 0, behavior, side_effect_type);
744
}
745
746
614689
inline void Environment::SetMethod(v8::Local<v8::Object> that,
747
                                   const char* name,
748
                                   v8::FunctionCallback callback) {
749
614689
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
750
  v8::Local<v8::Function> function =
751
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
752
                          // TODO(TimothyGu): Investigate if SetMethod is ever
753
                          // used for constructors.
754
                          v8::ConstructorBehavior::kAllow,
755
614695
                          v8::SideEffectType::kHasSideEffect)
756
1844083
          ->GetFunction(context)
757
1229388
          .ToLocalChecked();
758
  // kInternalized strings are created in the old space.
759
614695
  const v8::NewStringType type = v8::NewStringType::kInternalized;
760
  v8::Local<v8::String> name_string =
761
1229391
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
762
1229392
  that->Set(context, name_string, function).FromJust();
763
614696
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
764
614693
}
765
766
297320
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
767
                                               const char* name,
768
                                               v8::FunctionCallback callback) {
769
297320
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
770
  v8::Local<v8::Function> function =
771
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
772
                          // TODO(TimothyGu): Investigate if SetMethod is ever
773
                          // used for constructors.
774
                          v8::ConstructorBehavior::kAllow,
775
297320
                          v8::SideEffectType::kHasNoSideEffect)
776
891960
          ->GetFunction(context)
777
594639
          .ToLocalChecked();
778
  // kInternalized strings are created in the old space.
779
297320
  const v8::NewStringType type = v8::NewStringType::kInternalized;
780
  v8::Local<v8::String> name_string =
781
594641
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
782
594640
  that->Set(context, name_string, function).FromJust();
783
297319
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
784
297321
}
785
786
484026
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
787
                                        const char* name,
788
                                        v8::FunctionCallback callback) {
789
484026
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
790
  v8::Local<v8::FunctionTemplate> t =
791
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
792
484026
                          v8::SideEffectType::kHasSideEffect);
793
  // kInternalized strings are created in the old space.
794
484026
  const v8::NewStringType type = v8::NewStringType::kInternalized;
795
  v8::Local<v8::String> name_string =
796
968052
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
797
968052
  that->PrototypeTemplate()->Set(name_string, t);
798
484026
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
799
484026
}
800
801
41522
inline void Environment::SetProtoMethodNoSideEffect(
802
    v8::Local<v8::FunctionTemplate> that,
803
    const char* name,
804
    v8::FunctionCallback callback) {
805
41522
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
806
  v8::Local<v8::FunctionTemplate> t =
807
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
808
41522
                          v8::SideEffectType::kHasNoSideEffect);
809
  // kInternalized strings are created in the old space.
810
41522
  const v8::NewStringType type = v8::NewStringType::kInternalized;
811
  v8::Local<v8::String> name_string =
812
83044
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
813
83044
  that->PrototypeTemplate()->Set(name_string, t);
814
41522
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
815
41522
}
816
817
inline void Environment::SetTemplateMethod(v8::Local<v8::FunctionTemplate> that,
818
                                           const char* name,
819
                                           v8::FunctionCallback callback) {
820
  v8::Local<v8::FunctionTemplate> t =
821
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
822
                          v8::ConstructorBehavior::kAllow,
823
                          v8::SideEffectType::kHasSideEffect);
824
  // kInternalized strings are created in the old space.
825
  const v8::NewStringType type = v8::NewStringType::kInternalized;
826
  v8::Local<v8::String> name_string =
827
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
828
  that->Set(name_string, t);
829
  t->SetClassName(name_string);  // NODE_SET_METHOD() compatibility.
830
}
831
832
inline void Environment::SetTemplateMethodNoSideEffect(
833
    v8::Local<v8::FunctionTemplate> that,
834
    const char* name,
835
    v8::FunctionCallback callback) {
836
  v8::Local<v8::FunctionTemplate> t =
837
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
838
                          v8::ConstructorBehavior::kAllow,
839
                          v8::SideEffectType::kHasNoSideEffect);
840
  // kInternalized strings are created in the old space.
841
  const v8::NewStringType type = v8::NewStringType::kInternalized;
842
  v8::Local<v8::String> name_string =
843
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
844
  that->Set(name_string, t);
845
  t->SetClassName(name_string);  // NODE_SET_METHOD() compatibility.
846
}
847
848
1295191
void Environment::AddCleanupHook(void (*fn)(void*), void* arg) {
849
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
850
    fn, arg, cleanup_hook_counter_++
851
1295191
  });
852
  // Make sure there was no existing element with these values.
853
1295191
  CHECK_EQ(insertion_info.second, true);
854
1295191
}
855
856
1292488
void Environment::RemoveCleanupHook(void (*fn)(void*), void* arg) {
857
1292488
  CleanupHookCallback search { fn, arg, 0 };
858
1292488
  cleanup_hooks_.erase(search);
859
1292489
}
860
861
2894553
size_t Environment::CleanupHookCallback::Hash::operator()(
862
    const CleanupHookCallback& cb) const {
863
2894553
  return std::hash<void*>()(cb.arg_);
864
}
865
866
1445992
bool Environment::CleanupHookCallback::Equal::operator()(
867
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
868

1445992
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
869
}
870
871
97
BaseObject* Environment::CleanupHookCallback::GetBaseObject() const {
872
97
  if (fn_ == BaseObject::DeleteMe)
873
97
    return static_cast<BaseObject*>(arg_);
874
  else
875
    return nullptr;
876
}
877
878
template <typename T>
879
33
void Environment::ForEachBaseObject(T&& iterator) {
880
130
  for (const auto& hook : cleanup_hooks_) {
881
97
    BaseObject* obj = hook.GetBaseObject();
882
97
    if (obj != nullptr)
883
97
      iterator(obj);
884
  }
885
33
}
886
887
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
888
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
889
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
890
#define V(TypeName, PropertyName)                                             \
891
  inline                                                                      \
892
  v8::Local<TypeName> IsolateData::PropertyName(v8::Isolate* isolate) const { \
893
    /* Strings are immutable so casting away const-ness here is okay. */      \
894
    return const_cast<IsolateData*>(this)->PropertyName ## _.Get(isolate);    \
895
  }
896
77390
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
897
267140
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
898
8805294
  PER_ISOLATE_STRING_PROPERTIES(VS)
899
#undef V
900
#undef VS
901
#undef VY
902
#undef VP
903
904
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
905
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
906
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
907
#define V(TypeName, PropertyName)                                             \
908
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
909
    return isolate_data()->PropertyName(isolate());                           \
910
  }
911
38695
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
912
133570
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
913
4402635
  PER_ISOLATE_STRING_PROPERTIES(VS)
914
#undef V
915
#undef VS
916
#undef VY
917
#undef VP
918
919
#define V(PropertyName, TypeName)                                             \
920
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
921
    return PersistentToLocal::Strong(PropertyName ## _);                      \
922
  }                                                                           \
923
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
924
    PropertyName ## _.Reset(isolate(), value);                                \
925
  }
926
27659256
  ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V)
927
#undef V
928
929
}  // namespace node
930
931
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
932
933
#endif  // SRC_ENV_INL_H_