GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/env.cc Lines: 830 882 94.1 %
Date: 2020-11-21 04:10:54 Branches: 911 1711 53.2 %

Line Branch Exec Source
1
#include "env.h"
2
#include "allocated_buffer-inl.h"
3
#include "async_wrap.h"
4
#include "base_object-inl.h"
5
#include "debug_utils-inl.h"
6
#include "diagnosticfilename-inl.h"
7
#include "memory_tracker-inl.h"
8
#include "node_buffer.h"
9
#include "node_context_data.h"
10
#include "node_errors.h"
11
#include "node_internals.h"
12
#include "node_options-inl.h"
13
#include "node_process.h"
14
#include "node_v8_platform-inl.h"
15
#include "node_worker.h"
16
#include "req_wrap-inl.h"
17
#include "stream_base.h"
18
#include "tracing/agent.h"
19
#include "tracing/traced_value.h"
20
#include "util-inl.h"
21
#include "v8-profiler.h"
22
23
#include <algorithm>
24
#include <atomic>
25
#include <cinttypes>
26
#include <cstdio>
27
#include <iostream>
28
#include <limits>
29
#include <memory>
30
31
namespace node {
32
33
using errors::TryCatchScope;
34
using v8::Boolean;
35
using v8::Context;
36
using v8::EmbedderGraph;
37
using v8::Function;
38
using v8::FunctionTemplate;
39
using v8::HandleScope;
40
using v8::Integer;
41
using v8::Isolate;
42
using v8::Local;
43
using v8::MaybeLocal;
44
using v8::NewStringType;
45
using v8::Number;
46
using v8::Object;
47
using v8::Private;
48
using v8::Script;
49
using v8::SnapshotCreator;
50
using v8::StackTrace;
51
using v8::String;
52
using v8::Symbol;
53
using v8::TracingController;
54
using v8::TryCatch;
55
using v8::Undefined;
56
using v8::Value;
57
using worker::Worker;
58
59
int const Environment::kNodeContextTag = 0x6e6f64;
60
void* const Environment::kNodeContextTagPtr = const_cast<void*>(
61
    static_cast<const void*>(&Environment::kNodeContextTag));
62
63
8
std::vector<size_t> IsolateData::Serialize(SnapshotCreator* creator) {
64
8
  Isolate* isolate = creator->GetIsolate();
65
8
  std::vector<size_t> indexes;
66
16
  HandleScope handle_scope(isolate);
67
  // XXX(joyeecheung): technically speaking, the indexes here should be
68
  // consecutive and we could just return a range instead of an array,
69
  // but that's not part of the V8 API contract so we use an array
70
  // just to be safe.
71
72
#define VP(PropertyName, StringValue) V(Private, PropertyName)
73
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
74
#define VS(PropertyName, StringValue) V(String, PropertyName)
75
#define V(TypeName, PropertyName)                                              \
76
  indexes.push_back(creator->AddData(PropertyName##_.Get(isolate)));
77
32
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
78
56
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
79
1688
  PER_ISOLATE_STRING_PROPERTIES(VS)
80
104
#undef V
81
96
#undef VY
82
80
#undef VS
83
48
#undef VP
84
544
  for (size_t i = 0; i < AsyncWrap::PROVIDERS_LENGTH; i++)
85
1008
    indexes.push_back(creator->AddData(async_wrap_provider(i)));
86
40
87
40
  return indexes;
88
24
}
89
32
90
4633
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
91
4633
  size_t i = 0;
92
9210
  HandleScope handle_scope(isolate_);
93
24
94
24
#define VP(PropertyName, StringValue) V(Private, PropertyName)
95
32
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
96
40
#define VS(PropertyName, StringValue) V(String, PropertyName)
97
40
#define V(TypeName, PropertyName)                                              \
98
24
  do {                                                                         \
99
24
    MaybeLocal<TypeName> field =                                               \
100
24
        isolate_->GetDataFromSnapshotOnce<TypeName>((*indexes)[i++]);          \
101
24
    if (field.IsEmpty()) {                                                     \
102
24
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
103
32
    }                                                                          \
104
40
    PropertyName##_.Set(isolate_, field.ToLocalChecked());                     \
105
40
  } while (0);
106




147016
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
107






220488
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
108
































































































































4703256
  PER_ISOLATE_STRING_PROPERTIES(VS)
109
24
#undef V
110
24
#undef VY
111
#undef VS
112
#undef VP
113
114
284766
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
115
    MaybeLocal<String> field =
116
560346
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
117
280173
    if (field.IsEmpty()) {
118
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
119
    }
120
280173
    async_wrap_providers_[j].Set(isolate_, field.ToLocalChecked());
121
  }
122
4593
}
123
124
460
void IsolateData::CreateProperties() {
125
  // Create string and private symbol properties as internalized one byte
126
  // strings after the platform is properly initialized.
127
  //
128
  // Internalized because it makes property lookups a little faster and
129
  // because the string is created in the old space straight away.  It's going
130
  // to end up in the old space sooner or later anyway but now it doesn't go
131
  // through v8::Eternal's new space handling first.
132
  //
133
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
134
  // decoding step.
135
136
920
  HandleScope handle_scope(isolate_);
137
138
#define V(PropertyName, StringValue)                                           \
139
  PropertyName##_.Set(                                                         \
140
      isolate_,                                                                \
141
      Private::New(isolate_,                                                   \
142
                   String::NewFromOneByte(                                     \
143
                       isolate_,                                               \
144
                       reinterpret_cast<const uint8_t*>(StringValue),          \
145
                       NewStringType::kInternalized,                           \
146
                       sizeof(StringValue) - 1)                                \
147
                       .ToLocalChecked()));
148
1380
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
149
#undef V
150
1380
#define V(PropertyName, StringValue)                                           \
151
  PropertyName##_.Set(                                                         \
152
1380
      isolate_,                                                                \
153
      Symbol::New(isolate_,                                                    \
154
1380
                  String::NewFromOneByte(                                      \
155
460
                      isolate_,                                                \
156
1380
                      reinterpret_cast<const uint8_t*>(StringValue),           \
157
460
                      NewStringType::kInternalized,                            \
158
920
                      sizeof(StringValue) - 1)                                 \
159
1380
                      .ToLocalChecked()));
160
1380
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
161
1840
#undef V
162
1380
#define V(PropertyName, StringValue)                                           \
163
460
  PropertyName##_.Set(                                                         \
164
920
      isolate_,                                                                \
165
460
      String::NewFromOneByte(isolate_,                                         \
166
920
                             reinterpret_cast<const uint8_t*>(StringValue),    \
167
460
                             NewStringType::kInternalized,                     \
168
920
                             sizeof(StringValue) - 1)                          \
169
460
          .ToLocalChecked());
170
236896
  PER_ISOLATE_STRING_PROPERTIES(V)
171
1380
#undef V
172
173
1380
  // Create all the provider strings that will be passed to JS. Place them in
174
  // an array so the array index matches the PROVIDER id offset. This way the
175
1380
  // strings can be retrieved quickly.
176
460
#define V(Provider)                                                           \
177
920
  async_wrap_providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                \
178
1380
      isolate_,                                                               \
179
      String::NewFromOneByte(                                                 \
180
1380
        isolate_,                                                             \
181
        reinterpret_cast<const uint8_t*>(#Provider),                          \
182
        NewStringType::kInternalized,                                         \
183
        sizeof(#Provider) - 1).ToLocalChecked());
184
41400
  NODE_ASYNC_PROVIDER_TYPES(V)
185
#undef V
186
1840
}
187
460
188
5973
IsolateData::IsolateData(Isolate* isolate,
189
1380
                         uv_loop_t* event_loop,
190
                         MultiIsolatePlatform* platform,
191
1380
                         ArrayBufferAllocator* node_allocator,
192
5053
                         const std::vector<size_t>* indexes)
193
1380
    : isolate_(isolate),
194
      event_loop_(event_loop),
195
11442
      node_allocator_(node_allocator == nullptr ? nullptr
196
5469
                                                : node_allocator->GetImpl()),
197
1405654
      platform_(platform) {
198
10566
  options_.reset(
199
16079
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
200
1380
201
5053
  if (indexes == nullptr) {
202
1840
    CreateProperties();
203
  } else {
204
5973
    DeserializeProperties(indexes);
205
  }
206
6433
}
207
208
1402
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
209
460
#define V(PropertyName, StringValue)                                           \
210
920
  tracker->TrackField(#PropertyName, PropertyName());
211
1402
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
212
22
#undef V
213
1402
214
22
#define V(PropertyName, StringValue)                                           \
215
1402
  tracker->TrackField(#PropertyName, PropertyName());
216
66
  PER_ISOLATE_STRING_PROPERTIES(V)
217
44
#undef V
218
22
219
44
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
220
22
221
44
  if (node_allocator_ != nullptr) {
222
22
    tracker->TrackFieldWithSize(
223
44
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
224
22
  }
225
22
  tracker->TrackFieldWithSize(
226
44
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
227
22
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
228
44
}
229
22
230
141
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
231

141
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
232
22
    // Ideally, we’d have a consistent story that treats all threads/Environment
233
22
    // instances equally here. However, tracing is essentially global, and this
234
22
    // callback is called from whichever thread calls `StartTracing()` or
235
22
    // `StopTracing()`. The only way to do this in a threadsafe fashion
236
22
    // seems to be only tracking this from the main thread, and only allowing
237
44
    // these state modifications from the main thread.
238
112
    return;
239
22
  }
240
22
241
155
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
242
155
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
243
22
244
133
  Isolate* isolate = env_->isolate();
245
192
  HandleScope handle_scope(isolate);
246
133
  Local<Function> cb = env_->trace_category_state_function();
247
133
  if (cb.IsEmpty())
248
52
    return;
249
118
  TryCatchScope try_catch(env_);
250
59
  try_catch.SetVerbose(true);
251
118
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
252
177
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
253
}
254
255
446
void Environment::CreateProperties() {
256
892
  HandleScope handle_scope(isolate_);
257
446
  Local<Context> ctx = context();
258
259
  {
260
    Context::Scope context_scope(ctx);
261
446
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
262
1338
    templ->InstanceTemplate()->SetInternalFieldCount(
263
446
        BaseObject::kInternalFieldCount);
264
892
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
265
266
446
    set_binding_data_ctor_template(templ);
267
  }
268
269
  // Store primordials setup by the per-context script in the environment.
270
  Local<Object> per_context_bindings =
271
892
      GetPerContextExports(ctx).ToLocalChecked();
272
  Local<Value> primordials =
273
1338
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
274
446
  CHECK(primordials->IsObject());
275
446
  set_primordials(primordials.As<Object>());
276
277
  Local<Object> process_object =
278
892
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
279
446
  set_process_object(process_object);
280
446
}
281
282
5038
std::string GetExecPath(const std::vector<std::string>& argv) {
283
  char exec_path_buf[2 * PATH_MAX];
284
5038
  size_t exec_path_len = sizeof(exec_path_buf);
285
5038
  std::string exec_path;
286
5038
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
287
5038
    exec_path = std::string(exec_path_buf, exec_path_len);
288
  } else {
289
    exec_path = argv[0];
290
  }
291
292
  // On OpenBSD process.execPath will be relative unless we
293
  // get the full path before process.execPath is used.
294
#if defined(__OpenBSD__)
295
  uv_fs_t req;
296
  req.ptr = nullptr;
297
  if (0 ==
298
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
299
    CHECK_NOT_NULL(req.ptr);
300
    exec_path = std::string(static_cast<char*>(req.ptr));
301
  }
302
  uv_fs_req_cleanup(&req);
303
#endif
304
305
5038
  return exec_path;
306
}
307
308
5038
Environment::Environment(IsolateData* isolate_data,
309
                         Isolate* isolate,
310
                         const std::vector<std::string>& args,
311
                         const std::vector<std::string>& exec_args,
312
                         const EnvSerializeInfo* env_info,
313
                         EnvironmentFlags::Flags flags,
314
5038
                         ThreadId thread_id)
315
    : isolate_(isolate),
316
      isolate_data_(isolate_data),
317
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
318
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
319
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
320
5038
      timer_base_(uv_now(isolate_data->event_loop())),
321
      exec_argv_(exec_args),
322
      argv_(args),
323
      exec_path_(GetExecPath(args)),
324
      should_abort_on_uncaught_toggle_(
325
5038
          isolate_,
326
          1,
327
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
328
5038
      stream_base_state_(isolate_,
329
                         StreamBase::kNumStreamBaseStateFields,
330
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
331
5038
      environment_start_time_(PERFORMANCE_NOW()),
332
      flags_(flags),
333
5038
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
334
5038
                     ? AllocateEnvironmentThreadId().id
335


453420
                     : thread_id.id) {
336
  // We'll be creating new objects so make sure we've entered the context.
337
10076
  HandleScope handle_scope(isolate);
338
339
  // Set some flags if only kDefaultFlags was passed. This can make API version
340
  // transitions easier for embedders.
341
5038
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
342
9284
    flags_ = flags_ |
343
4642
        EnvironmentFlags::kOwnsProcessState |
344
        EnvironmentFlags::kOwnsInspector;
345
  }
346
347
5038
  set_env_vars(per_process::system_environment);
348
  // TODO(joyeecheung): pass Isolate* and env_vars to it instead of the entire
349
  // env
350
5038
  enabled_debug_list_.Parse(this);
351
352
  // We create new copies of the per-Environment option sets, so that it is
353
  // easier to modify them after Environment creation. The defaults are
354
  // part of the per-Isolate option set, for which in turn the defaults are
355
  // part of the per-process option set.
356
5038
  options_.reset(new EnvironmentOptions(*isolate_data->options()->per_env));
357
10076
  inspector_host_port_.reset(
358
15114
      new ExclusiveAccess<HostPort>(options_->debug_options().host_port));
359
360
5038
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
361
396
    set_abort_on_uncaught_exception(false);
362
  }
363
364
#if HAVE_INSPECTOR
365
  // We can only create the inspector agent after having cloned the options.
366
5038
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
367
#endif
368
369
5038
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
370
5038
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
371
5038
    if (TracingController* tracing_controller = writer->GetTracingController())
372
4995
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
373
  }
374
375
5038
  destroy_async_id_list_.reserve(512);
376
377
10076
  performance_state_ = std::make_unique<performance::PerformanceState>(
378
15114
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
379
380
5038
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
381
          TRACING_CATEGORY_NODE1(environment)) != 0) {
382
16
    auto traced_value = tracing::TracedValue::Create();
383
8
    traced_value->BeginArray("args");
384
8
    for (const std::string& arg : args) traced_value->AppendString(arg);
385
8
    traced_value->EndArray();
386
8
    traced_value->BeginArray("exec_args");
387
8
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
388
8
    traced_value->EndArray();
389
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
390
8
                                      "Environment",
391
                                      this,
392
7
                                      "args",
393
8
                                      std::move(traced_value));
394
  }
395
8
396
8
  // This adjusts the return value of base_object_count() so that tests that
397
16
  // check the count do not have to account for internally created BaseObjects.
398
5038
  initial_base_object_count_ = base_object_count();
399
5038
}
400
401
445
Environment::Environment(IsolateData* isolate_data,
402
                         Local<Context> context,
403
                         const std::vector<std::string>& args,
404
                         const std::vector<std::string>& exec_args,
405
                         const EnvSerializeInfo* env_info,
406
                         EnvironmentFlags::Flags flags,
407
445
                         ThreadId thread_id)
408
    : Environment(isolate_data,
409
                  context->GetIsolate(),
410
                  args,
411
                  exec_args,
412
                  env_info,
413
                  flags,
414
445
                  thread_id) {
415
445
  InitializeMainContext(context, env_info);
416
445
}
417
418
5039
void Environment::InitializeMainContext(Local<Context> context,
419
                                        const EnvSerializeInfo* env_info) {
420
5039
  context_.Reset(context->GetIsolate(), context);
421
5039
  AssignToContext(context, ContextInfo(""));
422
5039
  if (env_info != nullptr) {
423
4593
    DeserializeProperties(env_info);
424
  } else {
425
446
    CreateProperties();
426
  }
427
428
5039
  if (options_->no_force_async_hooks_checks) {
429
1
    async_hooks_.no_force_checks();
430
  }
431
432
  // By default, always abort when --abort-on-uncaught-exception was passed.
433
5039
  should_abort_on_uncaught_toggle_[0] = 1;
434
435
5039
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
436
5039
                           environment_start_time_);
437
5039
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
438
10078
                           per_process::node_start_time);
439
5039
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
440
10078
                           performance::performance_v8_start);
441
442
  // This adjusts the return value of base_object_count() so that tests that
443
  // check the count do not have to account for internally created BaseObjects.
444
5039
  initial_base_object_count_ = base_object_count();
445
5039
}
446
447
397327
Environment::~Environment() {
448
4566
  if (Environment** interrupt_data = interrupt_data_.load()) {
449
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
450
    // then force V8 to run interrupts by compiling and running an empty script
451
    // so as not to leak memory.
452
10
    *interrupt_data = nullptr;
453
454
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
455
20
    HandleScope handle_scope(isolate());
456
20
    TryCatch try_catch(isolate());
457
10
    Context::Scope context_scope(context());
458
459
#ifdef DEBUG
460
    bool consistency_check = false;
461
    isolate()->RequestInterrupt([](Isolate*, void* data) {
462
      *static_cast<bool*>(data) = true;
463
    }, &consistency_check);
464
#endif
465
466
    Local<Script> script;
467
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
468
20
      USE(script->Run(context()));
469
470
    DCHECK(consistency_check);
471
  }
472
473
  // FreeEnvironment() should have set this.
474
4567
  CHECK(is_stopping());
475
476
4567
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
477
1
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
478
1
                                          0);
479
  }
480
481
4567
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
482
4567
      BuildEmbedderGraph, this);
483
484
9134
  HandleScope handle_scope(isolate());
485
486
#if HAVE_INSPECTOR
487
  // Destroy inspector agent before erasing the context. The inspector
488
  // destructor depends on the context still being accessible.
489
4566
  inspector_agent_.reset();
490
#endif
491
492
13701
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
493
4567
                                             nullptr);
494
495
4567
  if (trace_state_observer_) {
496
4567
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
497
4567
    CHECK_NOT_NULL(writer);
498
4567
    if (TracingController* tracing_controller = writer->GetTracingController())
499
4526
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
500
  }
501
502
4567
  TRACE_EVENT_NESTABLE_ASYNC_END0(
503
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
504
505
4146
  // Do not unload addons on the main thread. Some addons need to retain memory
506
4567
  // beyond the Environment's lifetime, and unloading them early would break
507
  // them; with Worker threads, we have the opportunity to be stricter.
508
7
  // Also, since the main thread usually stops just before the process exits,
509
7
  // this is far less relevant here.
510
14
  if (!is_main_thread()) {
511
    // Dereference all addons that were loaded into this environment.
512
407
    for (binding::DLib& addon : loaded_addons_) {
513
14
      addon.Close();
514
    }
515
  }
516
517
4567
  CHECK_EQ(base_object_count_, 0);
518
9133
}
519
520
5005
void Environment::InitializeLibuv() {
521
10010
  HandleScope handle_scope(isolate());
522
5005
  Context::Scope context_scope(context());
523
524
5005
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
525
5005
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
526
527
5005
  uv_check_init(event_loop(), immediate_check_handle());
528
5005
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
529
530
5005
  uv_idle_init(event_loop(), immediate_idle_handle());
531
532
5005
  uv_check_start(immediate_check_handle(), CheckImmediate);
533
534
10010
  uv_async_init(
535
      event_loop(),
536
      &task_queues_async_,
537
13455
      [](uv_async_t* async) {
538
8450
        Environment* env = ContainerOf(
539
4225
            &Environment::task_queues_async_, async);
540
4225
        env->RunAndClearNativeImmediates();
541
18456
      });
542
5005
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
543
544
  {
545
10010
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
546
5005
    task_queues_async_initialized_ = true;
547

10010
    if (native_immediates_threadsafe_.size() > 0 ||
548
5005
        native_immediates_interrupts_.size() > 0) {
549
4587
      uv_async_send(&task_queues_async_);
550
    }
551
  }
552
553
  // Register clean-up cb to be called to clean up the handles
554
  // when the environment is freed, note that they are not cleaned in
555
  // the one environment per process setup, but will be called in
556
  // FreeEnvironment.
557
5005
  RegisterHandleCleanups();
558
5005
}
559
560
97
void Environment::ExitEnv() {
561
97
  set_can_call_into_js(false);
562
97
  set_stopping(true);
563
97
  isolate_->TerminateExecution();
564
194
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
565
97
}
566
567
5005
void Environment::RegisterHandleCleanups() {
568
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
569
41271
                                        void* arg) {
570
18133
    handle->data = env;
571
572
36266
    env->CloseHandle(handle, [](uv_handle_t* handle) {
573
#ifdef DEBUG
574
      memset(handle, 0xab, uv_handle_size(handle->type));
575
#endif
576
36264
    });
577
46278
  };
578
579
20020
  auto register_handle = [&](uv_handle_t* handle) {
580
20020
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
581
25025
  };
582
5005
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
583
5005
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
584
5005
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
585
5005
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
586
5005
}
587
588
9126
void Environment::CleanupHandles() {
589
  {
590
18253
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
591
9127
    task_queues_async_initialized_ = false;
592
  }
593
594
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
595
18252
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
596
597
9127
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
598
599
9142
  for (ReqWrapBase* request : req_wrap_queue_)
600
16
    request->Cancel();
601
602
11518
  for (HandleWrap* handle : handle_wrap_queue_)
603
4778
    handle->Close();
604
605
27261
  for (HandleCleanup& hc : handle_cleanup_queue_)
606
18134
    hc.cb_(this, hc.handle_, hc.arg_);
607
9126
  handle_cleanup_queue_.clear();
608
609

53557
  while (handle_cleanup_waiting_ != 0 ||
610

26978
         request_waiting_ != 0 ||
611
9128
         !handle_wrap_queue_.IsEmpty()) {
612
8725
    uv_run(event_loop(), UV_RUN_ONCE);
613
  }
614
9127
}
615
616
432400
void Environment::PrintSyncTrace() const {
617
432400
  if (!trace_sync_io_) return;
618
619
2
  HandleScope handle_scope(isolate());
620
621
1
  fprintf(
622
1
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
623
1
  PrintStackTrace(isolate(),
624
                  StackTrace::CurrentStackTrace(
625
1
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
626
}
627
628
4567
void Environment::RunCleanup() {
629
4567
  started_cleanup_ = true;
630
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
631
9133
                              "RunCleanup", this);
632
4566
  bindings_.clear();
633
4567
  initial_base_object_count_ = 0;
634
4567
  CleanupHandles();
635
636

27378
  while (!cleanup_hooks_.empty() ||
637
9135
         native_immediates_.size() > 0 ||
638

18258
         native_immediates_threadsafe_.size() > 0 ||
639
4566
         native_immediates_interrupts_.size() > 0) {
640
    // Copy into a vector, since we can't sort an unordered_set in-place.
641
    std::vector<CleanupHookCallback> callbacks(
642
9119
        cleanup_hooks_.begin(), cleanup_hooks_.end());
643
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
644
    // need to be able to check whether they were un-scheduled by another hook.
645
646
9120
    std::sort(callbacks.begin(), callbacks.end(),
647
942903
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
648
      // Sort in descending order so that the most recently inserted callbacks
649
      // are run first.
650
942903
      return a.insertion_order_counter_ > b.insertion_order_counter_;
651
947463
    });
652
653
117373
    for (const CleanupHookCallback& cb : callbacks) {
654
112812
      if (cleanup_hooks_.count(cb) == 0) {
655
        // This hook was removed from the `cleanup_hooks_` set during another
656
        // hook that was run earlier. Nothing to do here.
657
724
        continue;
658
      }
659
660
112091
      cb.fn_(cb.arg_);
661
112095
      cleanup_hooks_.erase(cb);
662
    }
663
4560
    CleanupHandles();
664
  }
665
666
4569
  for (const int fd : unmanaged_fds_) {
667
    uv_fs_t close_req;
668
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
669
3
    uv_fs_req_cleanup(&close_req);
670
  }
671
4567
}
672
673
5106
void Environment::RunAtExitCallbacks() {
674
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
675
10213
                              "AtExit", this);
676
15149
  for (ExitCallback at_exit : at_exit_functions_) {
677
10042
    at_exit.cb_(at_exit.arg_);
678
  }
679
5107
  at_exit_functions_.clear();
680
5107
}
681
682
10062
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
683
10062
  at_exit_functions_.push_front(ExitCallback{cb, arg});
684
10062
}
685
686
504608
void Environment::RunAndClearInterrupts() {
687
512677
  while (native_immediates_interrupts_.size() > 0) {
688
16138
    NativeImmediateQueue queue;
689
    {
690
16138
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
691
8069
      queue.ConcatMove(std::move(native_immediates_interrupts_));
692
    }
693
8069
    DebugSealHandleScope seal_handle_scope(isolate());
694
695
24213
    while (auto head = queue.Shift())
696
16144
      head->Call(this);
697
  }
698
496548
}
699
700
488642
void Environment::RunAndClearNativeImmediates(bool only_refed) {
701
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
702
977285
                              "RunAndClearNativeImmediates", this);
703
977288
  HandleScope handle_scope(isolate_);
704
977293
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
705
706
488645
  size_t ref_count = 0;
707
708
  // Handle interrupts first. These functions are not allowed to throw
709
  // exceptions, so we do not need to handle that.
710
488645
  RunAndClearInterrupts();
711
712
977285
  auto drain_list = [&](NativeImmediateQueue* queue) {
713
2011015
    TryCatchScope try_catch(this);
714
977296
    DebugSealHandleScope seal_handle_scope(isolate());
715
1090495
    while (auto head = queue->Shift()) {
716
56607
      bool is_refed = head->flags() & CallbackFlags::kRefed;
717
56607
      if (is_refed)
718
34368
        ref_count++;
719
720

56607
      if (is_refed || !only_refed)
721
112866
        head->Call(this);
722
723
56605
      head.reset();  // Destroy now so that this is also observed by try_catch.
724
725
56605
      if (UNLIKELY(try_catch.HasCaught())) {
726

6
        if (!try_catch.HasTerminated() && can_call_into_js())
727
3
          errors::TriggerUncaughtException(isolate(), try_catch);
728
729
1
        return true;
730
      }
731
56602
    }
732
977290
    return false;
733
488648
  };
734
488648
  while (drain_list(&native_immediates_)) {}
735
736
488649
  immediate_info()->ref_count_dec(ref_count);
737
738
488649
  if (immediate_info()->ref_count() == 0)
739
387702
    ToggleImmediateRef(false);
740
741
  // It is safe to check .size() first, because there is a causal relationship
742
  // between pushes to the threadsafe immediate list and this function being
743
  // called. For the common case, it's worth checking the size first before
744
  // establishing a mutex lock.
745
  // This is intentionally placed after the `ref_count` handling, because when
746
  // refed threadsafe immediates are created, they are not counted towards the
747
  // count in immediate_info() either.
748
977287
  NativeImmediateQueue threadsafe_immediates;
749
488643
  if (native_immediates_threadsafe_.size() > 0) {
750
1218
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
751
609
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
752
  }
753
488648
  while (drain_list(&threadsafe_immediates)) {}
754
488642
}
755
756
8076
void Environment::RequestInterruptFromV8() {
757
  // The Isolate may outlive the Environment, so some logic to handle the
758
  // situation in which the Environment is destroyed before the handler runs
759
  // is required.
760
761
  // We allocate a new pointer to a pointer to this Environment instance, and
762
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
763
  // callbacks are already scheduled to run and we can delete our own pointer
764
  // and just return. If it was nullptr previously, the Environment** is stored;
765
  // ~Environment sets the Environment* contained in it to nullptr, so that
766
  // the callback can check whether ~Environment has already run and it is thus
767
  // not safe to access the Environment instance itself.
768
8076
  Environment** interrupt_data = new Environment*(this);
769
8076
  Environment** dummy = nullptr;
770
8076
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
771
288
    delete interrupt_data;
772
288
    return;  // Already scheduled.
773
  }
774
775
38924
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
776
15550
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
777
7780
    Environment* env = *env_ptr;
778
7780
    if (env == nullptr) {
779
      // The Environment has already been destroyed. That should be okay; any
780
      // callback added before the Environment shuts down would have been
781
      // handled during cleanup.
782
10
      return;
783
    }
784
7770
    env->interrupt_data_.store(nullptr);
785
7770
    env->RunAndClearInterrupts();
786
23356
  }, interrupt_data);
787
}
788
789
6351
void Environment::ScheduleTimer(int64_t duration_ms) {
790
6351
  if (started_cleanup_) return;
791
6351
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
792
}
793
794
1270
void Environment::ToggleTimerRef(bool ref) {
795
1270
  if (started_cleanup_) return;
796
797
1270
  if (ref) {
798
844
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
799
  } else {
800
426
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
801
  }
802
}
803
804
5230
void Environment::RunTimers(uv_timer_t* handle) {
805
5230
  Environment* env = Environment::from_timer_handle(handle);
806
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
807
10445
                              "RunTimers", env);
808
809
5230
  if (!env->can_call_into_js())
810
    return;
811
812
10445
  HandleScope handle_scope(env->isolate());
813
10445
  Context::Scope context_scope(env->context());
814
815
5230
  Local<Object> process = env->process_object();
816
10445
  InternalCallbackScope scope(env, process, {0, 0});
817
818
5230
  Local<Function> cb = env->timers_callback_function();
819
  MaybeLocal<Value> ret;
820
5230
  Local<Value> arg = env->GetNow();
821
  // This code will loop until all currently due timers will process. It is
822
  // impossible for us to end up in an infinite loop due to how the JS-side
823
  // is structured.
824
5251
  do {
825
10512
    TryCatchScope try_catch(env);
826
5261
    try_catch.SetVerbose(true);
827
10522
    ret = cb->Call(env->context(), process, 1, &arg);
828

5251
  } while (ret.IsEmpty() && env->can_call_into_js());
829
830
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
831
  // is reset back to `true` after being previously set to `false` then this
832
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
833
  // timers corruption will occur and all timers behaviour will become
834
  // entirely unpredictable.
835
5220
  if (ret.IsEmpty())
836
5
    return;
837
838
  // To allow for less JS-C++ boundary crossing, the value returned from JS
839
  // serves a few purposes:
840
  // 1. If it's 0, no more timers exist and the handle should be unrefed
841
  // 2. If it's > 0, the value represents the next timer's expiry and there
842
  //    is at least one timer remaining that is refed.
843
  // 3. If it's < 0, the absolute value represents the next timer's expiry
844
  //    and there are no timers that are refed.
845
  int64_t expiry_ms =
846
20860
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
847
848
5215
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
849
850
5215
  if (expiry_ms != 0) {
851
    int64_t duration_ms =
852
4887
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
853
854
4887
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
855
856
4887
    if (expiry_ms > 0)
857
4596
      uv_ref(h);
858
    else
859
291
      uv_unref(h);
860
  } else {
861
328
    uv_unref(h);
862
  }
863
}
864
865
866
475294
void Environment::CheckImmediate(uv_check_t* handle) {
867
475294
  Environment* env = Environment::from_immediate_check_handle(handle);
868
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
869
575908
                              "CheckImmediate", env);
870
871
575905
  HandleScope scope(env->isolate());
872
575907
  Context::Scope context_scope(env->context());
873
874
475298
  env->RunAndClearNativeImmediates();
875
876

475297
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
877
374679
    return;
878
879
101550
  do {
880
203107
    MakeCallback(env->isolate(),
881
                 env->process_object(),
882
                 env->immediate_callback_function(),
883
                 0,
884
                 nullptr,
885
101558
                 {0, 0}).ToLocalChecked();
886

101550
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
887
888
100610
  if (env->immediate_info()->ref_count() == 0)
889
4557
    env->ToggleImmediateRef(false);
890
}
891
892
516058
void Environment::ToggleImmediateRef(bool ref) {
893
516058
  if (started_cleanup_) return;
894
895
506935
  if (ref) {
896
    // Idle handle is needed only to stop the event loop from blocking in poll.
897
441722
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
898
  } else {
899
383155
    uv_idle_stop(immediate_idle_handle());
900
  }
901
}
902
903
904
22926
Local<Value> Environment::GetNow() {
905
22926
  uv_update_time(event_loop());
906
22926
  uint64_t now = uv_now(event_loop());
907
22926
  CHECK_GE(now, timer_base());
908
22926
  now -= timer_base();
909
22926
  if (now <= 0xffffffff)
910
45852
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
911
  else
912
    return Number::New(isolate(), static_cast<double>(now));
913
}
914
915
28
void CollectExceptionInfo(Environment* env,
916
                          Local<Object> obj,
917
                          int errorno,
918
                          const char* err_string,
919
                          const char* syscall,
920
                          const char* message,
921
                          const char* path,
922
                          const char* dest) {
923
56
  obj->Set(env->context(),
924
           env->errno_string(),
925
140
           Integer::New(env->isolate(), errorno)).Check();
926
927
56
  obj->Set(env->context(), env->code_string(),
928
140
           OneByteString(env->isolate(), err_string)).Check();
929
930
28
  if (message != nullptr) {
931
56
    obj->Set(env->context(), env->message_string(),
932
140
             OneByteString(env->isolate(), message)).Check();
933
  }
934
935
  Local<Value> path_buffer;
936
28
  if (path != nullptr) {
937
    path_buffer =
938
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
939
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
940
  }
941
942
  Local<Value> dest_buffer;
943
28
  if (dest != nullptr) {
944
    dest_buffer =
945
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
946
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
947
  }
948
949
28
  if (syscall != nullptr) {
950
56
    obj->Set(env->context(), env->syscall_string(),
951
140
             OneByteString(env->isolate(), syscall)).Check();
952
  }
953
28
}
954
955
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
956
                                         int errorno,
957
                                         const char* syscall,
958
                                         const char* message,
959
                                         const char* path,
960
                                         const char* dest) {
961

28
  if (!object->IsObject() || errorno == 0)
962
    return;
963
964
28
  Local<Object> obj = object.As<Object>();
965
28
  const char* err_string = uv_err_name(errorno);
966
967

28
  if (message == nullptr || message[0] == '\0') {
968
28
    message = uv_strerror(errorno);
969
  }
970
971
  node::CollectExceptionInfo(this, obj, errorno, err_string,
972
28
                             syscall, message, path, dest);
973
}
974
975
5038
ImmediateInfo::ImmediateInfo(v8::Isolate* isolate, const SerializeInfo* info)
976
5038
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
977
978
8
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
979
    v8::Local<v8::Context> context, v8::SnapshotCreator* creator) {
980
8
  return {fields_.Serialize(context, creator)};
981
}
982
983
4593
void ImmediateInfo::Deserialize(Local<Context> context) {
984
4593
  fields_.Deserialize(context);
985
4593
}
986
987
8
std::ostream& operator<<(std::ostream& output,
988
                         const ImmediateInfo::SerializeInfo& i) {
989
8
  output << "{ " << i.fields << " }";
990
8
  return output;
991
}
992
993
22
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
994
22
  tracker->TrackField("fields", fields_);
995
22
}
996
997
8
TickInfo::SerializeInfo TickInfo::Serialize(v8::Local<v8::Context> context,
998
                                            v8::SnapshotCreator* creator) {
999
8
  return {fields_.Serialize(context, creator)};
1000
}
1001
1002
4593
void TickInfo::Deserialize(Local<Context> context) {
1003
4593
  fields_.Deserialize(context);
1004
4593
}
1005
1006
8
std::ostream& operator<<(std::ostream& output,
1007
                         const TickInfo::SerializeInfo& i) {
1008
8
  output << "{ " << i.fields << " }";
1009
8
  return output;
1010
}
1011
1012
22
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1013
22
  tracker->TrackField("fields", fields_);
1014
22
}
1015
1016
5038
TickInfo::TickInfo(v8::Isolate* isolate, const SerializeInfo* info)
1017
    : fields_(
1018
5038
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1019
1020
5038
AsyncHooks::AsyncHooks(v8::Isolate* isolate, const SerializeInfo* info)
1021
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1022
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1023
      async_id_fields_(
1024
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1025

10076
      info_(info) {
1026
10076
  v8::HandleScope handle_scope(isolate);
1027
5038
  if (info == nullptr) {
1028
445
    clear_async_id_stack();
1029
1030
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1031
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1032
    // See discussion in https://github.com/nodejs/node/pull/15454
1033
    // When removing this, do it by reverting the commit. Otherwise the test
1034
    // and flag changes won't be included.
1035
445
    fields_[kCheck] = 1;
1036
1037
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1038
    // specified default value and it should fallback to the executionAsyncId.
1039
    // 0 is not used as the magic value, because that indicates a missing
1040
    // context which is different from a default context.
1041
445
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1042
1043
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1044
    // context during bootstrap (code that runs before entering uv_run()).
1045
445
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1046
  }
1047
5038
}
1048
1049
4593
void AsyncHooks::Deserialize(Local<Context> context) {
1050
4593
  async_ids_stack_.Deserialize(context);
1051
4593
  fields_.Deserialize(context);
1052
4593
  async_id_fields_.Deserialize(context);
1053
4593
  if (info_->js_execution_async_resources != 0) {
1054
    v8::Local<v8::Array> arr = context
1055
9186
                                   ->GetDataFromSnapshotOnce<v8::Array>(
1056
9186
                                       info_->js_execution_async_resources)
1057
4593
                                   .ToLocalChecked();
1058
4593
    js_execution_async_resources_.Reset(context->GetIsolate(), arr);
1059
  }
1060
1061
4593
  native_execution_async_resources_.resize(
1062
9186
      info_->native_execution_async_resources.size());
1063
4593
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1064
    v8::Local<v8::Object> obj =
1065
        context
1066
            ->GetDataFromSnapshotOnce<v8::Object>(
1067
                info_->native_execution_async_resources[i])
1068
            .ToLocalChecked();
1069
    native_execution_async_resources_[i].Reset(context->GetIsolate(), obj);
1070
  }
1071
4593
  info_ = nullptr;
1072
4593
}
1073
1074
8
std::ostream& operator<<(std::ostream& output,
1075
                         const std::vector<SnapshotIndex>& v) {
1076
8
  output << "{ ";
1077
8
  for (const SnapshotIndex i : v) {
1078
    output << i << ", ";
1079
  }
1080
8
  output << " }";
1081
8
  return output;
1082
}
1083
1084
8
std::ostream& operator<<(std::ostream& output,
1085
                         const AsyncHooks::SerializeInfo& i) {
1086
  output << "{\n"
1087
8
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1088
16
         << "  " << i.fields << ",  // fields\n"
1089
16
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1090
16
         << "  " << i.js_execution_async_resources
1091
         << ",  // js_execution_async_resources\n"
1092
16
         << "  " << i.native_execution_async_resources
1093
         << ",  // native_execution_async_resources\n"
1094
8
         << "}";
1095
8
  return output;
1096
}
1097
1098
8
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1099
                                                SnapshotCreator* creator) {
1100
8
  SerializeInfo info;
1101
8
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1102
8
  info.fields = fields_.Serialize(context, creator);
1103
8
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1104
16
  if (!js_execution_async_resources_.IsEmpty()) {
1105
16
    info.js_execution_async_resources = creator->AddData(
1106
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1107
8
    CHECK_NE(info.js_execution_async_resources, 0);
1108
  } else {
1109
    info.js_execution_async_resources = 0;
1110
  }
1111
1112
8
  info.native_execution_async_resources.resize(
1113
8
      native_execution_async_resources_.size());
1114
8
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1115
    info.native_execution_async_resources[i] = creator->AddData(
1116
        context,
1117
        native_execution_async_resources_[i].Get(context->GetIsolate()));
1118
  }
1119
1120
8
  return info;
1121
}
1122
1123
22
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1124
22
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1125
22
  tracker->TrackField("fields", fields_);
1126
22
  tracker->TrackField("async_id_fields", async_id_fields_);
1127
22
}
1128
1129
10
void AsyncHooks::grow_async_ids_stack() {
1130
10
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1131
1132
30
  env()->async_hooks_binding()->Set(
1133
      env()->context(),
1134
      env()->async_ids_stack_string(),
1135
50
      async_ids_stack_.GetJSArray()).Check();
1136
10
}
1137
1138
521
void Environment::Exit(int exit_code) {
1139
521
  if (options()->trace_exit) {
1140
4
    HandleScope handle_scope(isolate());
1141
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1142
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1143
1144
2
    if (is_main_thread()) {
1145
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1146
    } else {
1147
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1148
1
              uv_os_getpid(), thread_id());
1149
    }
1150
1151
    fprintf(
1152
2
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1153
2
    PrintStackTrace(isolate(),
1154
                    StackTrace::CurrentStackTrace(
1155
2
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1156
  }
1157
521
  process_exit_handler_(this, exit_code);
1158
55
}
1159
1160
5058
void Environment::stop_sub_worker_contexts() {
1161
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1162
1163
5084
  while (!sub_worker_contexts_.empty()) {
1164
26
    Worker* w = *sub_worker_contexts_.begin();
1165
26
    remove_sub_worker_context(w);
1166
26
    w->Exit(1);
1167
26
    w->JoinThread();
1168
  }
1169
5033
}
1170
1171
4
Environment* Environment::worker_parent_env() const {
1172
4
  if (worker_context() == nullptr) return nullptr;
1173
  return worker_context()->env();
1174
}
1175
1176
52480
void Environment::AddUnmanagedFd(int fd) {
1177
52480
  if (!tracks_unmanaged_fds()) return;
1178
508
  auto result = unmanaged_fds_.insert(fd);
1179
508
  if (!result.second) {
1180
    ProcessEmitWarning(
1181
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1182
  }
1183
}
1184
1185
52108
void Environment::RemoveUnmanagedFd(int fd) {
1186
52108
  if (!tracks_unmanaged_fds()) return;
1187
505
  size_t removed_count = unmanaged_fds_.erase(fd);
1188
505
  if (removed_count == 0) {
1189
    ProcessEmitWarning(
1190
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1191
  }
1192
}
1193
1194
void Environment::PrintAllBaseObjects() {
1195
  size_t i = 0;
1196
  std::cout << "BaseObjects\n";
1197
  ForEachBaseObject([&](BaseObject* obj) {
1198
    std::cout << "#" << i++ << " " << obj << ": " <<
1199
      obj->MemoryInfoName() << "\n";
1200
  });
1201
}
1202
1203
4445
void Environment::VerifyNoStrongBaseObjects() {
1204
  // When a process exits cleanly, i.e. because the event loop ends up without
1205
  // things to wait for, the Node.js objects that are left on the heap should
1206
  // be:
1207
  //
1208
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1209
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1210
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1211
  //   4. an inactive libuv handle (essentially the same here)
1212
  //
1213
  // There are a few exceptions to this rule, but generally, if there are
1214
  // C++-backed Node.js objects on the heap that do not fall into the above
1215
  // categories, we may be looking at a potential memory leak. Most likely,
1216
  // the cause is a missing MakeWeak() call on the corresponding object.
1217
  //
1218
  // In order to avoid this kind of problem, we check the list of BaseObjects
1219
  // for these criteria. Currently, we only do so when explicitly instructed to
1220
  // or when in debug mode (where --verify-base-objects is always-on).
1221
1222
4445
  if (!options()->verify_base_objects) return;
1223
1224
  ForEachBaseObject([](BaseObject* obj) {
1225
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1226
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1227
            obj->MemoryInfoName().c_str());
1228
    fflush(stderr);
1229
    ABORT();
1230
  });
1231
}
1232
1233
8
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1234
8
  EnvSerializeInfo info;
1235
8
  Local<Context> ctx = context();
1236
1237
  // Currently all modules are compiled without cache in builtin snapshot
1238
  // builder.
1239
16
  info.native_modules = std::vector<std::string>(
1240
8
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1241
1242
8
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1243
8
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1244
8
  info.tick_info = tick_info_.Serialize(ctx, creator);
1245
8
  info.performance_state = performance_state_->Serialize(ctx, creator);
1246
8
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1247
8
  info.should_abort_on_uncaught_toggle =
1248
8
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1249
1250
8
  size_t id = 0;
1251
#define V(PropertyName, TypeName)                                              \
1252
  do {                                                                         \
1253
    Local<TypeName> field = PropertyName();                                    \
1254
    if (!field.IsEmpty()) {                                                    \
1255
      size_t index = creator->AddData(field);                                  \
1256
      info.persistent_templates.push_back({#PropertyName, id, index});         \
1257
    }                                                                          \
1258
    id++;                                                                      \
1259
  } while (0);
1260








168
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1261
8
#undef V
1262
16
1263
8
  id = 0;
1264
24
#define V(PropertyName, TypeName)                                              \
1265
8
  do {                                                                         \
1266
32
    Local<TypeName> field = PropertyName();                                    \
1267
24
    if (!field.IsEmpty()) {                                                    \
1268
8
      size_t index = creator->AddData(ctx, field);                             \
1269
16
      info.persistent_values.push_back({#PropertyName, id, index});            \
1270
    }                                                                          \
1271
16
    id++;                                                                      \
1272
  } while (0);
1273


















416
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1274
8
#undef V
1275

40
1276
32
  info.context = creator->AddData(ctx, context());
1277

56
  return info;
1278

40
}
1279
32
1280

56
std::ostream& operator<<(std::ostream& output,
1281
16
                         const std::vector<PropInfo>& vec) {
1282

48
  output << "{\n";
1283
272
  for (const auto& info : vec) {
1284

536
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1285
752
           << std::to_string(info.index) << " },\n";
1286

48
  }
1287
40
  output << "}";
1288
40
  return output;
1289
16
}
1290
32
1291
32
std::ostream& operator<<(std::ostream& output,
1292
                         const std::vector<std::string>& vec) {
1293
24
  output << "{\n";
1294
416
  for (const auto& info : vec) {
1295
424
    output << "  \"" << info << "\",\n";
1296
  }
1297
24
  output << "}";
1298
8
  return output;
1299
24
}
1300
8
1301
32
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1302
8
  output << "{\n"
1303
24
         << "// -- native_modules begins --\n"
1304
24
         << i.native_modules << ",\n"
1305
         << "// -- native_modules ends --\n"
1306
8
         << "// -- async_hooks begins --\n"
1307
16
         << i.async_hooks << ",\n"
1308
8
         << "// -- async_hooks ends --\n"
1309
16
         << i.tick_info << ",  // tick_info\n"
1310
16
         << i.immediate_info << ",  // immediate_info\n"
1311
8
         << "// -- performance_state begins --\n"
1312
16
         << i.performance_state << ",\n"
1313
8
         << "// -- performance_state ends --\n"
1314
16
         << i.stream_base_state << ",  // stream_base_state\n"
1315
16
         << i.should_abort_on_uncaught_toggle
1316
         << ",  // should_abort_on_uncaught_toggle\n"
1317
8
         << "// -- persistent_templates begins --\n"
1318
16
         << i.persistent_templates << ",\n"
1319
         << "// persistent_templates ends --\n"
1320
8
         << "// -- persistent_values begins --\n"
1321
16
         << i.persistent_values << ",\n"
1322
8
         << "// -- persistent_values ends --\n"
1323
16
         << i.context << ",  // context\n"
1324
8
         << "}";
1325
8
  return output;
1326
}
1327
1328
4593
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1329
4593
  Local<Context> ctx = context();
1330
1331
4593
  native_modules_in_snapshot = info->native_modules;
1332
4593
  async_hooks_.Deserialize(ctx);
1333
4593
  immediate_info_.Deserialize(ctx);
1334
4593
  tick_info_.Deserialize(ctx);
1335
4593
  performance_state_->Deserialize(ctx);
1336
4593
  stream_base_state_.Deserialize(ctx);
1337
4593
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1338
1339
4593
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1340
    fprintf(stderr, "deserializing...\n");
1341
    std::cerr << *info << "\n";
1342
  }
1343
1344
4593
  const std::vector<PropInfo>& templates = info->persistent_templates;
1345
4593
  size_t i = 0;  // index to the array
1346
4593
  size_t id = 0;
1347
#define V(PropertyName, TypeName)                                              \
1348
  do {                                                                         \
1349
    if (templates.size() > i && id == templates[i].id) {                       \
1350
      const PropInfo& d = templates[i];                                        \
1351
      DCHECK_EQ(d.name, #PropertyName);                                        \
1352
      MaybeLocal<TypeName> maybe_field =                                       \
1353
          isolate_->GetDataFromSnapshotOnce<TypeName>(d.index);                \
1354
      Local<TypeName> field;                                                   \
1355
      if (!maybe_field.ToLocal(&field)) {                                      \
1356
        fprintf(stderr,                                                        \
1357
                "Failed to deserialize environment template " #PropertyName    \
1358
                "\n");                                                         \
1359
      }                                                                        \
1360
      set_##PropertyName(field);                                               \
1361
      i++;                                                                     \
1362
    }                                                                          \
1363
  } while (0);                                                                 \
1364
  id++;
1365
































































78081
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1366
#undef V
1367
1368
4593
  i = 0;  // index to the array
1369
4593
  id = 0;
1370
4593
  const std::vector<PropInfo>& values = info->persistent_values;
1371
#define V(PropertyName, TypeName)                                              \
1372
  do {                                                                         \
1373
    if (values.size() > i && id == values[i].id) {                             \
1374
      const PropInfo& d = values[i];                                           \
1375
      DCHECK_EQ(d.name, #PropertyName);                                        \
1376
      MaybeLocal<TypeName> maybe_field =                                       \
1377
          ctx->GetDataFromSnapshotOnce<TypeName>(d.index);                     \
1378
      Local<TypeName> field;                                                   \
1379
      if (!maybe_field.ToLocal(&field)) {                                      \
1380
        fprintf(stderr,                                                        \
1381
                "Failed to deserialize environment value " #PropertyName       \
1382
                "\n");                                                         \
1383
      }                                                                        \
1384
      set_##PropertyName(field);                                               \
1385
      i++;                                                                     \
1386
    }                                                                          \
1387
  } while (0);                                                                 \
1388
  id++;
1389






































































































321510
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1390
#undef V
1391
1392
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1393
13779
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1394
  Local<Context> ctx_from_snapshot;
1395
4593
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1396
    fprintf(stderr,
1397
            "Failed to deserialize context back reference from the snapshot\n");
1398
  }
1399
4593
  CHECK_EQ(ctx_from_snapshot, ctx);
1400
4593
}
1401
1402
1
uint64_t GuessMemoryAvailableToTheProcess() {
1403
1
  uint64_t free_in_system = uv_get_free_memory();
1404
1
  size_t allowed = uv_get_constrained_memory();
1405
1
  if (allowed == 0) {
1406
    return free_in_system;
1407
  }
1408
  size_t rss;
1409
1
  int err = uv_resident_set_memory(&rss);
1410
1
  if (err) {
1411
    return free_in_system;
1412
  }
1413
1
  if (allowed < rss) {
1414
    // Something is probably wrong. Fallback to the free memory.
1415
    return free_in_system;
1416
  }
1417
  // There may still be room for swap, but we will just leave it here.
1418
1
  return allowed - rss;
1419
}
1420
1421
22
void Environment::BuildEmbedderGraph(Isolate* isolate,
1422
                                     EmbedderGraph* graph,
1423
                                     void* data) {
1424
44
  MemoryTracker tracker(isolate, graph);
1425
22
  Environment* env = static_cast<Environment*>(data);
1426
22
  tracker.Track(env);
1427
428
  env->ForEachBaseObject([&](BaseObject* obj) {
1428
384
    if (obj->IsDoneInitializing())
1429
381
      tracker.Track(obj);
1430
406
  });
1431
22
}
1432
1433
1
size_t Environment::NearHeapLimitCallback(void* data,
1434
                                          size_t current_heap_limit,
1435
                                          size_t initial_heap_limit) {
1436
1
  Environment* env = static_cast<Environment*>(data);
1437
1438
1
  Debug(env,
1439
        DebugCategory::DIAGNOSTICS,
1440
        "Invoked NearHeapLimitCallback, processing=%d, "
1441
        "current_limit=%" PRIu64 ", "
1442
        "initial_limit=%" PRIu64 "\n",
1443
        env->is_processing_heap_limit_callback_,
1444
2
        static_cast<uint64_t>(current_heap_limit),
1445
2
        static_cast<uint64_t>(initial_heap_limit));
1446
1447
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1448
1
  size_t young_gen_size = 0;
1449
1
  size_t old_gen_size = 0;
1450
1451
1
  v8::HeapSpaceStatistics stats;
1452
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1453
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1454
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1455

15
    if (strcmp(stats.space_name(), "new_space") == 0 ||
1456
7
        strcmp(stats.space_name(), "new_large_object_space") == 0) {
1457
2
      young_gen_size += stats.space_used_size();
1458
    } else {
1459
6
      old_gen_size += stats.space_used_size();
1460
    }
1461
  }
1462
1463
  Debug(env,
1464
        DebugCategory::DIAGNOSTICS,
1465
        "max_young_gen_size=%" PRIu64 ", "
1466
        "young_gen_size=%" PRIu64 ", "
1467
        "old_gen_size=%" PRIu64 ", "
1468
        "total_size=%" PRIu64 "\n",
1469
2
        static_cast<uint64_t>(max_young_gen_size),
1470
2
        static_cast<uint64_t>(young_gen_size),
1471
2
        static_cast<uint64_t>(old_gen_size),
1472
2
        static_cast<uint64_t>(young_gen_size + old_gen_size));
1473
1474
1
  uint64_t available = GuessMemoryAvailableToTheProcess();
1475
  // TODO(joyeecheung): get a better estimate about the native memory
1476
  // usage into the overhead, e.g. based on the count of objects.
1477
1
  uint64_t estimated_overhead = max_young_gen_size;
1478
  Debug(env,
1479
        DebugCategory::DIAGNOSTICS,
1480
        "Estimated available memory=%" PRIu64 ", "
1481
        "estimated overhead=%" PRIu64 "\n",
1482
2
        static_cast<uint64_t>(available),
1483
2
        static_cast<uint64_t>(estimated_overhead));
1484
1485
  // This might be hit when the snapshot is being taken in another
1486
  // NearHeapLimitCallback invocation.
1487
  // When taking the snapshot, objects in the young generation may be
1488
  // promoted to the old generation, result in increased heap usage,
1489
  // but it should be no more than the young generation size.
1490
  // Ideally, this should be as small as possible - the heap limit
1491
  // can only be restored when the heap usage falls down below the
1492
  // new limit, so in a heap with unbounded growth the isolate
1493
  // may eventually crash with this new limit - effectively raising
1494
  // the heap limit to the new one.
1495
1
  if (env->is_processing_heap_limit_callback_) {
1496
    size_t new_limit = initial_heap_limit + max_young_gen_size;
1497
    Debug(env,
1498
          DebugCategory::DIAGNOSTICS,
1499
          "Not generating snapshots in nested callback. "
1500
          "new_limit=%" PRIu64 "\n",
1501
          static_cast<uint64_t>(new_limit));
1502
    return new_limit;
1503
  }
1504
1505
  // Estimate whether the snapshot is going to use up all the memory
1506
  // available to the process. If so, just give up to prevent the system
1507
  // from killing the process for a system OOM.
1508
1
  if (estimated_overhead > available) {
1509
    Debug(env,
1510
          DebugCategory::DIAGNOSTICS,
1511
          "Not generating snapshots because it's too risky.\n");
1512
    env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1513
                                                initial_heap_limit);
1514
    return current_heap_limit;
1515
  }
1516
1517
  // Take the snapshot synchronously.
1518
1
  env->is_processing_heap_limit_callback_ = true;
1519
1520
2
  std::string dir = env->options()->diagnostic_dir;
1521
1
  if (dir.empty()) {
1522
1
    dir = env->GetCwd();
1523
  }
1524
2
  DiagnosticFilename name(env, "Heap", "heapsnapshot");
1525
2
  std::string filename = dir + kPathSeparator + (*name);
1526
1527
2
  Debug(env, DebugCategory::DIAGNOSTICS, "Start generating %s...\n", *name);
1528
1529
  // Remove the callback first in case it's triggered when generating
1530
  // the snapshot.
1531
1
  env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1532
1
                                              initial_heap_limit);
1533
1534
1
  heap::WriteSnapshot(env->isolate(), filename.c_str());
1535
1
  env->heap_limit_snapshot_taken_ += 1;
1536
1537
  // Don't take more snapshots than the number specified by
1538
  // --heapsnapshot-near-heap-limit.
1539
2
  if (env->heap_limit_snapshot_taken_ <
1540
1
      env->options_->heap_snapshot_near_heap_limit) {
1541
    env->isolate()->AddNearHeapLimitCallback(NearHeapLimitCallback, env);
1542
  }
1543
1544
1
  FPrintF(stderr, "Wrote snapshot to %s\n", filename.c_str());
1545
  // Tell V8 to reset the heap limit once the heap usage falls down to
1546
  // 95% of the initial limit.
1547
1
  env->isolate()->AutomaticallyRestoreInitialHeapLimit(0.95);
1548
1549
1
  env->is_processing_heap_limit_callback_ = false;
1550
1
  return initial_heap_limit;
1551
}
1552
1553
22
inline size_t Environment::SelfSize() const {
1554
22
  size_t size = sizeof(*this);
1555
  // Remove non pointer fields that will be tracked in MemoryInfo()
1556
  // TODO(joyeecheung): refactor the MemoryTracker interface so
1557
  // this can be done for common types within the Track* calls automatically
1558
  // if a certain scope is entered.
1559
22
  size -= sizeof(async_hooks_);
1560
22
  size -= sizeof(tick_info_);
1561
22
  size -= sizeof(immediate_info_);
1562
22
  return size;
1563
}
1564
1565
22
void Environment::MemoryInfo(MemoryTracker* tracker) const {
1566
  // Iteratable STLs have their own sizes subtracted from the parent
1567
  // by default.
1568
22
  tracker->TrackField("isolate_data", isolate_data_);
1569
22
  tracker->TrackField("native_modules_with_cache", native_modules_with_cache);
1570
22
  tracker->TrackField("native_modules_without_cache",
1571
22
                      native_modules_without_cache);
1572
22
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
1573
22
  tracker->TrackField("exec_argv", exec_argv_);
1574
22
  tracker->TrackField("should_abort_on_uncaught_toggle",
1575
22
                      should_abort_on_uncaught_toggle_);
1576
22
  tracker->TrackField("stream_base_state", stream_base_state_);
1577
22
  tracker->TrackFieldWithSize(
1578
44
      "cleanup_hooks", cleanup_hooks_.size() * sizeof(CleanupHookCallback));
1579
22
  tracker->TrackField("async_hooks", async_hooks_);
1580
22
  tracker->TrackField("immediate_info", immediate_info_);
1581
22
  tracker->TrackField("tick_info", tick_info_);
1582
1583
#define V(PropertyName, TypeName)                                              \
1584
  tracker->TrackField(#PropertyName, PropertyName());
1585
44
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1586
44
#undef V
1587
44
1588
22
  // FIXME(joyeecheung): track other fields in Environment.
1589
22
  // Currently MemoryTracker is unable to track these
1590
22
  // correctly:
1591
22
  // - Internal types that do not implement MemoryRetainer yet
1592
22
  // - STL containers with MemoryRetainer* inside
1593
22
  // - STL containers with numeric types inside that should not have their
1594
22
  //   nodes elided e.g. numeric keys in maps.
1595
22
  // We also need to make sure that when we add a non-pointer field as its own
1596
22
  // node, we shift its sizeof() size out of the Environment node.
1597
44
}
1598
22
1599
1160319
void Environment::RunWeakRefCleanup() {
1600
1160319
  isolate()->ClearKeptObjects();
1601
1160322
}
1602
22
1603
22
// Not really any better place than env.cc at this moment.
1604
107140
void BaseObject::DeleteMe(void* data) {
1605
107140
  BaseObject* self = static_cast<BaseObject*>(data);
1606

111135
  if (self->has_pointer_data() &&
1607
4017
      self->pointer_data()->strong_ptr_count > 0) {
1608
291
    return self->Detach();
1609
22
  }
1610
106873
  delete self;
1611
22
}
1612
22
1613
341
bool BaseObject::IsDoneInitializing() const { return true; }
1614
22
1615
403
Local<Object> BaseObject::WrappedObject() const {
1616
403
  return object();
1617
}
1618
1619
762
bool BaseObject::IsRootNode() const {
1620
1524
  return !persistent_handle_.IsWeak();
1621
}
1622
1623
42374
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1624
42374
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1625
42374
  if (tmpl.IsEmpty()) {
1626
445
    tmpl = env->NewFunctionTemplate(nullptr);
1627
890
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1628
445
    env->set_base_object_ctor_template(tmpl);
1629
  }
1630
42374
  return tmpl;
1631
}
1632
1633
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1634
  return IsWeakOrDetached();
1635
}
1636
1637

14034
}  // namespace node