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: 483 486 99.4 %
Date: 2019-02-26 22:23:30 Branches: 81 110 73.6 %

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


1212140
  if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) {
164
    fprintf(stderr,
165
            "Error: async hook stack has become corrupted ("
166
            "actual: %.f, expected: %.f)\n",
167
            async_id_fields_.GetValue(kExecutionAsyncId),
168
4
            async_id);
169
4
    DumpBacktrace(stderr);
170
4
    fflush(stderr);
171
4
    if (!env()->abort_on_uncaught_exception())
172
4
      exit(1);
173
    fprintf(stderr, "\n");
174
    fflush(stderr);
175
    ABORT_NO_BACKTRACE();
176
  }
177
178
1212136
  uint32_t offset = fields_[kStackLength] - 1;
179
1212137
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
180
1212137
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
181
1212137
  fields_[kStackLength] = offset;
182
183
1212137
  return fields_[kStackLength] > 0;
184
}
185
186
// Keep in sync with clearAsyncIdStack in lib/internal/async_hooks.js.
187
55
inline void Environment::AsyncHooks::clear_async_id_stack() {
188
55
  async_id_fields_[kExecutionAsyncId] = 0;
189
55
  async_id_fields_[kTriggerAsyncId] = 0;
190
55
  fields_[kStackLength] = 0;
191
55
}
192
193
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
194
// async_wrap-inl.h to avoid a circular dependency.
195
196
943198
inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope
197
  ::DefaultTriggerAsyncIdScope(Environment* env,
198
                               double default_trigger_async_id)
199
943198
    : async_hooks_(env->async_hooks()) {
200
943198
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
201
943198
    CHECK_GE(default_trigger_async_id, 0);
202
  }
203
204
1886396
  old_default_trigger_async_id_ =
205
1886396
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
206
1886396
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
207
943198
    default_trigger_async_id;
208
943198
}
209
210
943197
inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope
211
  ::~DefaultTriggerAsyncIdScope() {
212
1886394
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
213
943197
    old_default_trigger_async_id_;
214
943197
}
215
216
217
832993
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
218
832993
  return ContainerOf(&Environment::async_hooks_, hooks);
219
}
220
221
222
1384867
inline Environment::AsyncCallbackScope::AsyncCallbackScope(Environment* env)
223
1384867
    : env_(env) {
224
1384867
  env_->makecallback_cntr_++;
225
1384867
}
226
227
1384496
inline Environment::AsyncCallbackScope::~AsyncCallbackScope() {
228
1384496
  env_->makecallback_cntr_--;
229
1384496
}
230
231
1208457
inline size_t Environment::makecallback_depth() const {
232
1208457
  return makecallback_cntr_;
233
}
234
235
4403
inline Environment::ImmediateInfo::ImmediateInfo(v8::Isolate* isolate)
236
4403
    : fields_(isolate, kFieldsCount) {}
237
238
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
239
4393
    Environment::ImmediateInfo::fields() {
240
4393
  return fields_;
241
}
242
243
563400
inline uint32_t Environment::ImmediateInfo::count() const {
244
563400
  return fields_[kCount];
245
}
246
247
79359
inline uint32_t Environment::ImmediateInfo::ref_count() const {
248
79359
  return fields_[kRefCount];
249
}
250
251
52430
inline bool Environment::ImmediateInfo::has_outstanding() const {
252
52430
  return fields_[kHasOutstanding] == 1;
253
}
254
255
49656
inline void Environment::ImmediateInfo::count_inc(uint32_t increment) {
256
49656
  fields_[kCount] += increment;
257
49656
}
258
259
46270
inline void Environment::ImmediateInfo::count_dec(uint32_t decrement) {
260
46270
  fields_[kCount] -= decrement;
261
46270
}
262
263
27450
inline void Environment::ImmediateInfo::ref_count_inc(uint32_t increment) {
264
27450
  fields_[kRefCount] += increment;
265
27450
}
266
267
46270
inline void Environment::ImmediateInfo::ref_count_dec(uint32_t decrement) {
268
46270
  fields_[kRefCount] -= decrement;
269
46270
}
270
271
4403
inline Environment::TickInfo::TickInfo(v8::Isolate* isolate)
272
4403
    : fields_(isolate, kFieldsCount) {}
273
274
4394
inline AliasedBuffer<uint8_t, v8::Uint8Array>& Environment::TickInfo::fields() {
275
4394
  return fields_;
276
}
277
278
1980464
inline bool Environment::TickInfo::has_tick_scheduled() const {
279
1980464
  return fields_[kHasTickScheduled] == 1;
280
}
281
282
422369
inline bool Environment::TickInfo::has_rejection_to_warn() const {
283
422369
  return fields_[kHasRejectionToWarn] == 1;
284
}
285
286
8949
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
287
                                         const ContextInfo& info) {
288
  context->SetAlignedPointerInEmbedderData(
289
8949
      ContextEmbedderIndex::kEnvironment, this);
290
  // Used by EnvPromiseHook to know that we are on a node context.
291
  context->SetAlignedPointerInEmbedderData(
292
17898
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
293
#if HAVE_INSPECTOR
294
8949
  inspector_agent()->ContextCreated(context, info);
295
#endif  // HAVE_INSPECTOR
296
8949
}
297
298
1242966
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
299
1242966
  return GetCurrent(isolate->GetCurrentContext());
300
}
301
302
1467651
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
303


5870605
  if (UNLIKELY(context.IsEmpty() ||
304
      context->GetNumberOfEmbedderDataFields() <
305
          ContextEmbedderIndex::kContextTag ||
306
      context->GetAlignedPointerFromEmbedderData(
307
          ContextEmbedderIndex::kContextTag) !=
308
          Environment::kNodeContextTagPtr)) {
309
1
    return nullptr;
310
  }
311
312
  return static_cast<Environment*>(
313
      context->GetAlignedPointerFromEmbedderData(
314
2935300
          ContextEmbedderIndex::kEnvironment));
315
}
316
317
5494508
inline Environment* Environment::GetCurrent(
318
    const v8::FunctionCallbackInfo<v8::Value>& info) {
319
10989016
  CHECK(info.Data()->IsExternal());
320
16483527
  return static_cast<Environment*>(info.Data().As<v8::External>()->Value());
321
}
322
323
template <typename T>
324
12330
inline Environment* Environment::GetCurrent(
325
    const v8::PropertyCallbackInfo<T>& info) {
326

24660
  CHECK(info.Data()->IsExternal());
327
  return static_cast<Environment*>(
328
36990
      info.Data().template As<v8::External>()->Value());
329
}
330
331
7
inline Environment* Environment::GetThreadLocalEnv() {
332
7
  return static_cast<Environment*>(uv_key_get(&thread_local_env));
333
}
334
335
171
inline bool Environment::profiler_idle_notifier_started() const {
336
171
  return profiler_idle_notifier_started_;
337
}
338
339
68859446
inline v8::Isolate* Environment::isolate() const {
340
68859446
  return isolate_;
341
}
342
343
5759
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
344
5759
  return ContainerOf(&Environment::timer_handle_, handle);
345
}
346
347
21732
inline uv_timer_t* Environment::timer_handle() {
348
21732
  return &timer_handle_;
349
}
350
351
563400
inline Environment* Environment::from_immediate_check_handle(
352
    uv_check_t* handle) {
353
563400
  return ContainerOf(&Environment::immediate_check_handle_, handle);
354
}
355
356
17612
inline uv_check_t* Environment::immediate_check_handle() {
357
17612
  return &immediate_check_handle_;
358
}
359
360
82628
inline uv_idle_t* Environment::immediate_idle_handle() {
361
82628
  return &immediate_idle_handle_;
362
}
363
364
22015
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
365
                                               HandleCleanupCb cb,
366
                                               void* arg) {
367
22015
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
368
22015
}
369
370
template <typename T, typename OnCloseCallback>
371
20577
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
372
20577
  handle_cleanup_waiting_++;
373
  static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle");
374
  static_assert(offsetof(T, data) == offsetof(uv_handle_t, data),
375
                "T is a libuv handle");
376
  static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb),
377
                "T is a libuv handle");
378
  struct CloseData {
379
    Environment* env;
380
    OnCloseCallback callback;
381
    void* original_data;
382
  };
383
20577
  handle->data = new CloseData { this, callback, handle->data };
384
82262
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
385
20554
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
386
20554
    data->env->handle_cleanup_waiting_--;
387
20554
    handle->data = data->original_data;
388
20554
    data->callback(reinterpret_cast<T*>(handle));
389
61708
  });
390
20577
}
391
392
220947
void Environment::IncreaseWaitingRequestCounter() {
393
220947
  request_waiting_++;
394
220947
}
395
396
220928
void Environment::DecreaseWaitingRequestCounter() {
397
220928
  request_waiting_--;
398
220928
  CHECK_GE(request_waiting_, 0);
399
220928
}
400
401
1848307
inline uv_loop_t* Environment::event_loop() const {
402
1848307
  return isolate_data()->event_loop();
403
}
404
405
135
inline void Environment::TryLoadAddon(
406
    const char* filename,
407
    int flags,
408
    const std::function<bool(binding::DLib*)>& was_loaded) {
409
135
  loaded_addons_.emplace_back(filename, flags);
410
135
  if (!was_loaded(&loaded_addons_.back())) {
411
7
    loaded_addons_.pop_back();
412
  }
413
135
}
414
415
#if HAVE_INSPECTOR
416
128172
inline bool Environment::is_in_inspector_console_call() const {
417
128172
  return is_in_inspector_console_call_;
418
}
419
420
256342
inline void Environment::set_is_in_inspector_console_call(bool value) {
421
256342
  is_in_inspector_console_call_ = value;
422
256342
}
423
#endif
424
425
10820306
inline Environment::AsyncHooks* Environment::async_hooks() {
426
10820306
  return &async_hooks_;
427
}
428
429
869228
inline Environment::ImmediateInfo* Environment::immediate_info() {
430
869228
  return &immediate_info_;
431
}
432
433
994630
inline Environment::TickInfo* Environment::tick_info() {
434
994630
  return &tick_info_;
435
}
436
437
685782
inline uint64_t Environment::timer_base() const {
438
685782
  return timer_base_;
439
}
440
441
12
inline bool Environment::printed_error() const {
442
12
  return printed_error_;
443
}
444
445
12
inline void Environment::set_printed_error(bool value) {
446
12
  printed_error_ = value;
447
12
}
448
449
3870
inline void Environment::set_trace_sync_io(bool value) {
450
3870
  options_->trace_sync_io = value;
451
3870
}
452
453
19
inline bool Environment::abort_on_uncaught_exception() const {
454
19
  return options_->abort_on_uncaught_exception;
455
}
456
457
169
inline void Environment::set_abort_on_uncaught_exception(bool value) {
458
169
  options_->abort_on_uncaught_exception = value;
459
169
}
460
461
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
462
4431
Environment::should_abort_on_uncaught_toggle() {
463
4431
  return should_abort_on_uncaught_toggle_;
464
}
465
466
inline AliasedBuffer<int32_t, v8::Int32Array>&
467
2292996
Environment::stream_base_state() {
468
2292996
  return stream_base_state_;
469
}
470
471
260
inline uint32_t Environment::get_next_module_id() {
472
260
  return module_id_counter_++;
473
}
474
4527
inline uint32_t Environment::get_next_script_id() {
475
4527
  return script_id_counter_++;
476
}
477
41443
inline uint32_t Environment::get_next_function_id() {
478
41443
  return function_id_counter_++;
479
}
480
481
4874
Environment::ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
482
    Environment* env)
483
4874
    : env_(env) {
484
4874
  env_->should_not_abort_scope_counter_++;
485
4874
}
486
487
4873
Environment::ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
488
4873
  Close();
489
4873
}
490
491
5075
void Environment::ShouldNotAbortOnUncaughtScope::Close() {
492
5075
  if (env_ != nullptr) {
493
4873
    env_->should_not_abort_scope_counter_--;
494
4873
    env_ = nullptr;
495
  }
496
5075
}
497
498
1
bool Environment::inside_should_not_abort_on_uncaught_scope() const {
499
1
  return should_not_abort_scope_counter_ > 0;
500
}
501
502
202979
inline std::vector<double>* Environment::destroy_async_id_list() {
503
202979
  return &destroy_async_id_list_;
504
}
505
506
454780
inline double Environment::new_async_id() {
507
454780
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
508
454780
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
509
}
510
511
384613
inline double Environment::execution_async_id() {
512
384613
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
513
}
514
515
37270
inline double Environment::trigger_async_id() {
516
37270
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
517
}
518
519
454777
inline double Environment::get_default_trigger_async_id() {
520
  double default_trigger_async_id =
521
454777
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
522
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
523
454777
  if (default_trigger_async_id < 0)
524
346694
    default_trigger_async_id = execution_async_id();
525
454777
  return default_trigger_async_id;
526
}
527
528
4389
inline double* Environment::heap_statistics_buffer() const {
529
4389
  CHECK_NOT_NULL(heap_statistics_buffer_);
530
4389
  return heap_statistics_buffer_;
531
}
532
533
4387
inline void Environment::set_heap_statistics_buffer(double* pointer) {
534
4387
  CHECK_NULL(heap_statistics_buffer_);  // Should be set only once.
535
4387
  heap_statistics_buffer_ = pointer;
536
4387
}
537
538
4388
inline double* Environment::heap_space_statistics_buffer() const {
539
4388
  CHECK_NOT_NULL(heap_space_statistics_buffer_);
540
4388
  return heap_space_statistics_buffer_;
541
}
542
543
4387
inline void Environment::set_heap_space_statistics_buffer(double* pointer) {
544
4387
  CHECK_NULL(heap_space_statistics_buffer_);  // Should be set only once.
545
4387
  heap_space_statistics_buffer_ = pointer;
546
4387
}
547
548
192340
inline char* Environment::http_parser_buffer() const {
549
192340
  return http_parser_buffer_;
550
}
551
552
281
inline void Environment::set_http_parser_buffer(char* buffer) {
553
281
  CHECK_NULL(http_parser_buffer_);  // Should be set only once.
554
281
  http_parser_buffer_ = buffer;
555
281
}
556
557
64107
inline bool Environment::http_parser_buffer_in_use() const {
558
64107
  return http_parser_buffer_in_use_;
559
}
560
561
128211
inline void Environment::set_http_parser_buffer_in_use(bool in_use) {
562
128211
  http_parser_buffer_in_use_ = in_use;
563
128211
}
564
565
19410
inline http2::Http2State* Environment::http2_state() const {
566
19410
  return http2_state_.get();
567
}
568
569
220
inline void Environment::set_http2_state(
570
    std::unique_ptr<http2::Http2State> buffer) {
571
220
  CHECK(!http2_state_);  // Should be set only once.
572
220
  http2_state_ = std::move(buffer);
573
220
}
574
575
717085
bool Environment::debug_enabled(DebugCategory category) const {
576
  DCHECK_GE(static_cast<int>(category), 0);
577
  DCHECK_LT(static_cast<int>(category),
578
           static_cast<int>(DebugCategory::CATEGORY_COUNT));
579
717085
  return debug_enabled_[static_cast<int>(category)];
580
}
581
582
4
void Environment::set_debug_enabled(DebugCategory category, bool enabled) {
583
  DCHECK_GE(static_cast<int>(category), 0);
584
  DCHECK_LT(static_cast<int>(category),
585
           static_cast<int>(DebugCategory::CATEGORY_COUNT));
586
4
  debug_enabled_[static_cast<int>(category)] = enabled;
587
4
}
588
589
inline AliasedBuffer<double, v8::Float64Array>*
590
193807
Environment::fs_stats_field_array() {
591
193807
  return &fs_stats_field_array_;
592
}
593
594
inline AliasedBuffer<uint64_t, v8::BigUint64Array>*
595
4399
Environment::fs_stats_field_bigint_array() {
596
4399
  return &fs_stats_field_bigint_array_;
597
}
598
599
inline std::vector<std::unique_ptr<fs::FileHandleReadWrap>>&
600
438
Environment::file_handle_read_wrap_freelist() {
601
438
  return file_handle_read_wrap_freelist_;
602
}
603
604
108882
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
605
108882
  return options_;
606
}
607
608
8889
inline std::shared_ptr<HostPort> Environment::inspector_host_port() {
609
8889
  return inspector_host_port_;
610
}
611
612
13310
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
613
13310
  return options_;
614
}
615
616
4
inline void IsolateData::set_options(
617
    std::shared_ptr<PerIsolateOptions> options) {
618
4
  options_ = std::move(options);
619
4
}
620
621
49656
void Environment::CreateImmediate(native_immediate_callback cb,
622
                                  void* data,
623
                                  v8::Local<v8::Object> obj,
624
                                  bool ref) {
625
  native_immediate_callbacks_.push_back({
626
    cb,
627
    data,
628
49656
    std::unique_ptr<Persistent<v8::Object>>(obj.IsEmpty() ?
629
27446
        nullptr : new Persistent<v8::Object>(isolate_, obj)),
630
    ref
631

126758
  });
632
49656
  immediate_info()->count_inc(1);
633
49656
}
634
635
27450
void Environment::SetImmediate(native_immediate_callback cb,
636
                               void* data,
637
                               v8::Local<v8::Object> obj) {
638
27450
  CreateImmediate(cb, data, obj, true);
639
640
27450
  if (immediate_info()->ref_count() == 0)
641
22685
    ToggleImmediateRef(true);
642
27450
  immediate_info()->ref_count_inc(1);
643
27450
}
644
645
22206
void Environment::SetUnrefImmediate(native_immediate_callback cb,
646
                                    void* data,
647
                                    v8::Local<v8::Object> obj) {
648
22206
  CreateImmediate(cb, data, obj, false);
649
22206
}
650
651
4167199
inline bool Environment::can_call_into_js() const {
652

4167199
  return can_call_into_js_ && (is_main_thread() || !is_stopping_worker());
653
}
654
655
4034
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
656
4034
  can_call_into_js_ = can_call_into_js;
657
4034
}
658
659
4402
inline bool Environment::has_run_bootstrapping_code() const {
660
4402
  return has_run_bootstrapping_code_;
661
}
662
663
4401
inline void Environment::set_has_run_bootstrapping_code(bool value) {
664
4401
  has_run_bootstrapping_code_ = value;
665
4401
}
666
667
4197491
inline bool Environment::is_main_thread() const {
668
4197491
  return flags_ & kIsMainThread;
669
}
670
671
26663
inline bool Environment::owns_process_state() const {
672
26663
  return flags_ & kOwnsProcessState;
673
}
674
675
4403
inline bool Environment::owns_inspector() const {
676
4403
  return flags_ & kOwnsInspector;
677
}
678
679
4560
inline uint64_t Environment::thread_id() const {
680
4560
  return thread_id_;
681
}
682
683
inline worker::Worker* Environment::worker_context() const {
684
  return worker_context_;
685
}
686
687
169
inline void Environment::set_worker_context(worker::Worker* context) {
688
169
  CHECK_NULL(worker_context_);  // Should be set only once.
689
169
  worker_context_ = context;
690
169
}
691
692
170
inline void Environment::add_sub_worker_context(worker::Worker* context) {
693
170
  sub_worker_contexts_.insert(context);
694
170
}
695
696
193
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
697
193
  sub_worker_contexts_.erase(context);
698
193
}
699
700
20468
inline bool Environment::is_stopping_worker() const {
701
20468
  CHECK(!is_main_thread());
702
20468
  return worker_context_->is_stopped();
703
}
704
705
34397
inline performance::performance_state* Environment::performance_state() {
706
34397
  return performance_state_.get();
707
}
708
709
inline std::unordered_map<std::string, uint64_t>*
710
42
    Environment::performance_marks() {
711
42
  return &performance_marks_;
712
}
713
714
8058988
inline IsolateData* Environment::isolate_data() const {
715
8058988
  return isolate_data_;
716
}
717
718
466826
inline char* Environment::AllocateUnchecked(size_t size) {
719
  return static_cast<char*>(
720
466826
      isolate_data()->allocator()->AllocateUninitialized(size));
721
}
722
723
445283
inline char* Environment::Allocate(size_t size) {
724
445283
  char* ret = AllocateUnchecked(size);
725
445283
  CHECK_NE(ret, nullptr);
726
445283
  return ret;
727
}
728
729
988238
inline void Environment::Free(char* data, size_t size) {
730
988238
  if (data != nullptr)
731
34088
    isolate_data()->allocator()->Free(data, size);
732
988238
}
733
734
466826
inline AllocatedBuffer Environment::AllocateManaged(size_t size, bool checked) {
735
466826
  char* data = checked ? Allocate(size) : AllocateUnchecked(size);
736
466826
  if (data == nullptr) size = 0;
737
466826
  return AllocatedBuffer(this, uv_buf_init(data, size));
738
}
739
740
886839
inline AllocatedBuffer::AllocatedBuffer(Environment* env, uv_buf_t buf)
741
886839
    : env_(env), buffer_(buf) {}
742
743
398876
inline void AllocatedBuffer::Resize(size_t len) {
744
398876
  char* new_data = env_->Reallocate(buffer_.base, buffer_.len, len);
745

398876
  CHECK_IMPLIES(len > 0, new_data != nullptr);
746
398876
  buffer_ = uv_buf_init(new_data, len);
747
398876
}
748
749
1878980
inline uv_buf_t AllocatedBuffer::release() {
750
1878980
  uv_buf_t ret = buffer_;
751
1878980
  buffer_ = uv_buf_init(nullptr, 0);
752
1878980
  return ret;
753
}
754
755
377207
inline char* AllocatedBuffer::data() {
756
377207
  return buffer_.base;
757
}
758
759
inline const char* AllocatedBuffer::data() const {
760
  return buffer_.base;
761
}
762
763
712266
inline size_t AllocatedBuffer::size() const {
764
712266
  return buffer_.len;
765
}
766
767
52844
inline AllocatedBuffer::AllocatedBuffer(Environment* env)
768
52844
    : env_(env), buffer_(uv_buf_init(nullptr, 0)) {}
769
770
106
inline AllocatedBuffer::AllocatedBuffer(AllocatedBuffer&& other)
771
106
    : AllocatedBuffer() {
772
106
  *this = std::move(other);
773
106
}
774
775
48637
inline AllocatedBuffer& AllocatedBuffer::operator=(AllocatedBuffer&& other) {
776
48637
  clear();
777
48637
  env_ = other.env_;
778
48637
  buffer_ = other.release();
779
48637
  return *this;
780
}
781
782
939601
inline AllocatedBuffer::~AllocatedBuffer() {
783
939601
  clear();
784
939601
}
785
786
988238
inline void AllocatedBuffer::clear() {
787
988238
  uv_buf_t buf = release();
788
988238
  env_->Free(buf.base, buf.len);
789
988238
}
790
791
// It's a bit awkward to define this Buffer::New() overload here, but it
792
// avoids a circular dependency with node_internals.h.
793
namespace Buffer {
794
v8::MaybeLocal<v8::Object> New(Environment* env,
795
                               char* data,
796
                               size_t length,
797
                               bool uses_malloc);
798
}
799
800
43716
inline v8::MaybeLocal<v8::Object> AllocatedBuffer::ToBuffer() {
801
43716
  CHECK_NOT_NULL(env_);
802
43716
  v8::MaybeLocal<v8::Object> obj = Buffer::New(env_, data(), size(), false);
803
43716
  if (!obj.IsEmpty()) release();
804
43716
  return obj;
805
}
806
807
390178
inline v8::Local<v8::ArrayBuffer> AllocatedBuffer::ToArrayBuffer() {
808
390178
  CHECK_NOT_NULL(env_);
809
390178
  uv_buf_t buf = release();
810
  return v8::ArrayBuffer::New(env_->isolate(),
811
                              buf.base,
812
                              buf.len,
813
390178
                              v8::ArrayBufferCreationMode::kInternalized);
814
}
815
816
700
inline void Environment::ThrowError(const char* errmsg) {
817
700
  ThrowError(v8::Exception::Error, errmsg);
818
700
}
819
820
5
inline void Environment::ThrowTypeError(const char* errmsg) {
821
5
  ThrowError(v8::Exception::TypeError, errmsg);
822
5
}
823
824
inline void Environment::ThrowRangeError(const char* errmsg) {
825
  ThrowError(v8::Exception::RangeError, errmsg);
826
}
827
828
705
inline void Environment::ThrowError(
829
    v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
830
    const char* errmsg) {
831
705
  v8::HandleScope handle_scope(isolate());
832
705
  isolate()->ThrowException(fun(OneByteString(isolate(), errmsg)));
833
705
}
834
835
3
inline void Environment::ThrowErrnoException(int errorno,
836
                                             const char* syscall,
837
                                             const char* message,
838
                                             const char* path) {
839
  isolate()->ThrowException(
840
3
      ErrnoException(isolate(), errorno, syscall, message, path));
841
3
}
842
843
14
inline void Environment::ThrowUVException(int errorno,
844
                                          const char* syscall,
845
                                          const char* message,
846
                                          const char* path,
847
                                          const char* dest) {
848
  isolate()->ThrowException(
849
14
      UVException(isolate(), errorno, syscall, message, path, dest));
850
14
}
851
852
inline v8::Local<v8::FunctionTemplate>
853
1611984
    Environment::NewFunctionTemplate(v8::FunctionCallback callback,
854
                                     v8::Local<v8::Signature> signature,
855
                                     v8::ConstructorBehavior behavior,
856
                                     v8::SideEffectType side_effect_type) {
857
1611984
  v8::Local<v8::External> external = as_external();
858
  return v8::FunctionTemplate::New(isolate(), callback, external,
859
1611992
                                   signature, 0, behavior, side_effect_type);
860
}
861
862
625860
inline void Environment::SetMethod(v8::Local<v8::Object> that,
863
                                   const char* name,
864
                                   v8::FunctionCallback callback) {
865
625860
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
866
  v8::Local<v8::Function> function =
867
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
868
                          // TODO(TimothyGu): Investigate if SetMethod is ever
869
                          // used for constructors.
870
                          v8::ConstructorBehavior::kAllow,
871
625866
                          v8::SideEffectType::kHasSideEffect)
872
1877598
          ->GetFunction(context)
873
1251731
          .ToLocalChecked();
874
  // kInternalized strings are created in the old space.
875
625866
  const v8::NewStringType type = v8::NewStringType::kInternalized;
876
  v8::Local<v8::String> name_string =
877
1251732
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
878
1251728
  that->Set(context, name_string, function).FromJust();
879
625862
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
880
625859
}
881
882
296474
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
883
                                               const char* name,
884
                                               v8::FunctionCallback callback) {
885
296474
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
886
  v8::Local<v8::Function> function =
887
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
888
                          // TODO(TimothyGu): Investigate if SetMethod is ever
889
                          // used for constructors.
890
                          v8::ConstructorBehavior::kAllow,
891
296473
                          v8::SideEffectType::kHasNoSideEffect)
892
889426
          ->GetFunction(context)
893
592950
          .ToLocalChecked();
894
  // kInternalized strings are created in the old space.
895
296473
  const v8::NewStringType type = v8::NewStringType::kInternalized;
896
  v8::Local<v8::String> name_string =
897
592949
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
898
592949
  that->Set(context, name_string, function).FromJust();
899
296473
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
900
296472
}
901
902
474117
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
903
                                        const char* name,
904
                                        v8::FunctionCallback callback) {
905
474117
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
906
  v8::Local<v8::FunctionTemplate> t =
907
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
908
474118
                          v8::SideEffectType::kHasSideEffect);
909
  // kInternalized strings are created in the old space.
910
474118
  const v8::NewStringType type = v8::NewStringType::kInternalized;
911
  v8::Local<v8::String> name_string =
912
948236
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
913
948236
  that->PrototypeTemplate()->Set(name_string, t);
914
474118
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
915
474118
}
916
917
41716
inline void Environment::SetProtoMethodNoSideEffect(
918
    v8::Local<v8::FunctionTemplate> that,
919
    const char* name,
920
    v8::FunctionCallback callback) {
921
41716
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
922
  v8::Local<v8::FunctionTemplate> t =
923
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
924
41716
                          v8::SideEffectType::kHasNoSideEffect);
925
  // kInternalized strings are created in the old space.
926
41716
  const v8::NewStringType type = v8::NewStringType::kInternalized;
927
  v8::Local<v8::String> name_string =
928
83432
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
929
83432
  that->PrototypeTemplate()->Set(name_string, t);
930
41716
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
931
41716
}
932
933
inline void Environment::SetTemplateMethod(v8::Local<v8::FunctionTemplate> that,
934
                                           const char* name,
935
                                           v8::FunctionCallback callback) {
936
  v8::Local<v8::FunctionTemplate> t =
937
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
938
                          v8::ConstructorBehavior::kAllow,
939
                          v8::SideEffectType::kHasSideEffect);
940
  // kInternalized strings are created in the old space.
941
  const v8::NewStringType type = v8::NewStringType::kInternalized;
942
  v8::Local<v8::String> name_string =
943
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
944
  that->Set(name_string, t);
945
  t->SetClassName(name_string);  // NODE_SET_METHOD() compatibility.
946
}
947
948
inline void Environment::SetTemplateMethodNoSideEffect(
949
    v8::Local<v8::FunctionTemplate> that,
950
    const char* name,
951
    v8::FunctionCallback callback) {
952
  v8::Local<v8::FunctionTemplate> t =
953
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
954
                          v8::ConstructorBehavior::kAllow,
955
                          v8::SideEffectType::kHasNoSideEffect);
956
  // kInternalized strings are created in the old space.
957
  const v8::NewStringType type = v8::NewStringType::kInternalized;
958
  v8::Local<v8::String> name_string =
959
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
960
  that->Set(name_string, t);
961
  t->SetClassName(name_string);  // NODE_SET_METHOD() compatibility.
962
}
963
964
857299
void Environment::AddCleanupHook(void (*fn)(void*), void* arg) {
965
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
966
    fn, arg, cleanup_hook_counter_++
967
857299
  });
968
  // Make sure there was no existing element with these values.
969
857299
  CHECK_EQ(insertion_info.second, true);
970
857299
}
971
972
855581
void Environment::RemoveCleanupHook(void (*fn)(void*), void* arg) {
973
855581
  CleanupHookCallback search { fn, arg, 0 };
974
855581
  cleanup_hooks_.erase(search);
975
855581
}
976
977
1794020
size_t Environment::CleanupHookCallback::Hash::operator()(
978
    const CleanupHookCallback& cb) const {
979
1794020
  return std::hash<void*>()(cb.arg_);
980
}
981
982
896221
bool Environment::CleanupHookCallback::Equal::operator()(
983
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
984

896221
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
985
}
986
987
94
BaseObject* Environment::CleanupHookCallback::GetBaseObject() const {
988
94
  if (fn_ == BaseObject::DeleteMe)
989
93
    return static_cast<BaseObject*>(arg_);
990
  else
991
1
    return nullptr;
992
}
993
994
template <typename T>
995
32
void Environment::ForEachBaseObject(T&& iterator) {
996
126
  for (const auto& hook : cleanup_hooks_) {
997
94
    BaseObject* obj = hook.GetBaseObject();
998
94
    if (obj != nullptr)
999
93
      iterator(obj);
1000
  }
1001
32
}
1002
1003
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1004
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1005
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1006
#define V(TypeName, PropertyName)                                             \
1007
  inline                                                                      \
1008
  v8::Local<TypeName> IsolateData::PropertyName(v8::Isolate* isolate) const { \
1009
    /* Strings are immutable so casting away const-ness here is okay. */      \
1010
    return const_cast<IsolateData*>(this)->PropertyName ## _.Get(isolate);    \
1011
  }
1012
76938
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1013
263240
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1014
8780428
  PER_ISOLATE_STRING_PROPERTIES(VS)
1015
#undef V
1016
#undef VS
1017
#undef VY
1018
#undef VP
1019
1020
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1021
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1022
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1023
#define V(TypeName, PropertyName)                                             \
1024
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1025
    return isolate_data()->PropertyName(isolate());                           \
1026
  }
1027
38469
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1028
131619
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1029
4390207
  PER_ISOLATE_STRING_PROPERTIES(VS)
1030
#undef V
1031
#undef VS
1032
#undef VY
1033
#undef VP
1034
1035
#define V(PropertyName, TypeName)                                             \
1036
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1037
    return PersistentToLocal::Strong(PropertyName ## _);                      \
1038
  }                                                                           \
1039
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
1040
    PropertyName ## _.Reset(isolate(), value);                                \
1041
  }
1042
22996690
  ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V)
1043
#undef V
1044
1045
}  // namespace node
1046
1047
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1048
1049
#endif  // SRC_ENV_INL_H_