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: 826 878 94.1 %
Date: 2021-02-11 04:11:15 Branches: 949 1793 52.9 %

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
1712
  PER_ISOLATE_STRING_PROPERTIES(VS)
80
104
#undef V
81
96
#undef VY
82
80
#undef VS
83
48
#undef VP
84
520
  for (size_t i = 0; i < AsyncWrap::PROVIDERS_LENGTH; i++)
85
960
    indexes.push_back(creator->AddData(async_wrap_provider(i)));
86
40
87
40
  return indexes;
88
24
}
89
32
90
4653
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
91
4653
  size_t i = 0;
92
9250
  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> maybe_field =                                         \
100
24
        isolate_->GetDataFromSnapshotOnce<TypeName>((*indexes)[i++]);          \
101
24
    Local<TypeName> field;                                                     \
102
24
    if (!maybe_field.ToLocal(&field)) {                                        \
103
32
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
104
40
    }                                                                          \
105
40
    PropertyName##_.Set(isolate_, field);                                      \
106
40
  } while (0);
107




110736
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
108






166092
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
109

































































































































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

141
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
231
22
    // Ideally, we’d have a consistent story that treats all threads/Environment
232
22
    // instances equally here. However, tracing is essentially global, and this
233
22
    // callback is called from whichever thread calls `StartTracing()` or
234
22
    // `StopTracing()`. The only way to do this in a threadsafe fashion
235
22
    // seems to be only tracking this from the main thread, and only allowing
236
44
    // these state modifications from the main thread.
237
112
    return;
238
22
  }
239
22
240
155
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
241
155
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
242
22
243
133
  Isolate* isolate = env_->isolate();
244
192
  HandleScope handle_scope(isolate);
245
133
  Local<Function> cb = env_->trace_category_state_function();
246
133
  if (cb.IsEmpty())
247
52
    return;
248
118
  TryCatchScope try_catch(env_);
249
59
  try_catch.SetVerbose(true);
250
118
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
251
177
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
252
}
253
254
444
void Environment::CreateProperties() {
255
888
  HandleScope handle_scope(isolate_);
256
444
  Local<Context> ctx = context();
257
258
  {
259
    Context::Scope context_scope(ctx);
260
444
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
261
1332
    templ->InstanceTemplate()->SetInternalFieldCount(
262
444
        BaseObject::kInternalFieldCount);
263
888
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
264
265
444
    set_binding_data_ctor_template(templ);
266
  }
267
268
  // Store primordials setup by the per-context script in the environment.
269
  Local<Object> per_context_bindings =
270
888
      GetPerContextExports(ctx).ToLocalChecked();
271
  Local<Value> primordials =
272
1332
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
273
444
  CHECK(primordials->IsObject());
274
444
  set_primordials(primordials.As<Object>());
275
276
  Local<String> prototype_string =
277
444
      FIXED_ONE_BYTE_STRING(isolate(), "prototype");
278
279
#define V(EnvPropertyName, PrimordialsPropertyName)                            \
280
  {                                                                            \
281
    Local<Value> ctor =                                                        \
282
        primordials.As<Object>()                                               \
283
            ->Get(ctx,                                                         \
284
                  FIXED_ONE_BYTE_STRING(isolate(), PrimordialsPropertyName))   \
285
            .ToLocalChecked();                                                 \
286
    CHECK(ctor->IsObject());                                                   \
287
    Local<Value> prototype =                                                   \
288
        ctor.As<Object>()->Get(ctx, prototype_string).ToLocalChecked();        \
289
    CHECK(prototype->IsObject());                                              \
290
    set_##EnvPropertyName(prototype.As<Object>());                             \
291
  }
292
293
1776
  V(primordials_safe_map_prototype_object, "SafeMap");
294
2220
  V(primordials_safe_set_prototype_object, "SafeSet");
295
2220
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
296

3996
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
297

2220
#undef V
298
2220
299
2220
  Local<Object> process_object =
300
1332
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
301
888
  set_process_object(process_object);
302
444
}
303
304
5057
std::string GetExecPath(const std::vector<std::string>& argv) {
305
  char exec_path_buf[2 * PATH_MAX];
306
5057
  size_t exec_path_len = sizeof(exec_path_buf);
307
5057
  std::string exec_path;
308
5057
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
309
5057
    exec_path = std::string(exec_path_buf, exec_path_len);
310
  } else {
311
    exec_path = argv[0];
312
  }
313
314
  // On OpenBSD process.execPath will be relative unless we
315
  // get the full path before process.execPath is used.
316
#if defined(__OpenBSD__)
317
  uv_fs_t req;
318
  req.ptr = nullptr;
319
  if (0 ==
320
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
321
    CHECK_NOT_NULL(req.ptr);
322
    exec_path = std::string(static_cast<char*>(req.ptr));
323
  }
324
  uv_fs_req_cleanup(&req);
325
#endif
326
327
5057
  return exec_path;
328
}
329
330
5057
Environment::Environment(IsolateData* isolate_data,
331
                         Isolate* isolate,
332
                         const std::vector<std::string>& args,
333
                         const std::vector<std::string>& exec_args,
334
                         const EnvSerializeInfo* env_info,
335
                         EnvironmentFlags::Flags flags,
336
5057
                         ThreadId thread_id)
337
    : isolate_(isolate),
338
      isolate_data_(isolate_data),
339
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
340
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
341
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
342
5057
      timer_base_(uv_now(isolate_data->event_loop())),
343
      exec_argv_(exec_args),
344
      argv_(args),
345
      exec_path_(GetExecPath(args)),
346
      should_abort_on_uncaught_toggle_(
347
5057
          isolate_,
348
          1,
349
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
350
5057
      stream_base_state_(isolate_,
351
                         StreamBase::kNumStreamBaseStateFields,
352
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
353
5057
      environment_start_time_(PERFORMANCE_NOW()),
354
      flags_(flags),
355
5057
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
356
5057
                     ? AllocateEnvironmentThreadId().id
357


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

10048
    if (native_immediates_threadsafe_.size() > 0 ||
566
5024
        native_immediates_interrupts_.size() > 0) {
567
4607
      uv_async_send(&task_queues_async_);
568
    }
569
  }
570
571
  // Register clean-up cb to be called to clean up the handles
572
  // when the environment is freed, note that they are not cleaned in
573
  // the one environment per process setup, but will be called in
574
  // FreeEnvironment.
575
5024
  RegisterHandleCleanups();
576
5024
}
577
578
99
void Environment::ExitEnv() {
579
99
  set_can_call_into_js(false);
580
99
  set_stopping(true);
581
99
  isolate_->TerminateExecution();
582
198
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
583
99
}
584
585
5024
void Environment::RegisterHandleCleanups() {
586
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
587
41772
                                        void* arg) {
588
18374
    handle->data = env;
589
590
36754
    env->CloseHandle(handle, [](uv_handle_t* handle) {
591
#ifdef DEBUG
592
      memset(handle, 0xab, uv_handle_size(handle->type));
593
#endif
594
36750
    });
595
46800
  };
596
597
20096
  auto register_handle = [&](uv_handle_t* handle) {
598
20096
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
599
25120
  };
600
5024
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
601
5024
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
602
5024
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
603
5024
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
604
5024
}
605
606
9248
void Environment::CleanupHandles() {
607
  {
608
18495
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
609
9247
    task_queues_async_initialized_ = false;
610
  }
611
612
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
613
18497
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
614
615
9248
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
616
617
9264
  for (ReqWrapBase* request : req_wrap_queue_)
618
16
    request->Cancel();
619
620
11643
  for (HandleWrap* handle : handle_wrap_queue_)
621
4788
    handle->Close();
622
623
27626
  for (HandleCleanup& hc : handle_cleanup_queue_)
624
18374
    hc.cb_(this, hc.handle_, hc.arg_);
625
9249
  handle_cleanup_queue_.clear();
626
627

54302
  while (handle_cleanup_waiting_ != 0 ||
628

27350
         request_waiting_ != 0 ||
629
9251
         !handle_wrap_queue_.IsEmpty()) {
630
8850
    uv_run(event_loop(), UV_RUN_ONCE);
631
  }
632
9249
}
633
634
433139
void Environment::PrintSyncTrace() const {
635
433139
  if (!trace_sync_io_) return;
636
637
2
  HandleScope handle_scope(isolate());
638
639
1
  fprintf(
640
1
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
641
1
  PrintStackTrace(isolate(),
642
                  StackTrace::CurrentStackTrace(
643
1
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
644
}
645
646
4627
void Environment::RunCleanup() {
647
4627
  started_cleanup_ = true;
648
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
649
9255
                              "RunCleanup", this);
650
4625
  bindings_.clear();
651
4627
  CleanupHandles();
652
653

27748
  while (!cleanup_hooks_.empty() ||
654
9258
         native_immediates_.size() > 0 ||
655

18504
         native_immediates_threadsafe_.size() > 0 ||
656
4628
         native_immediates_interrupts_.size() > 0) {
657
    // Copy into a vector, since we can't sort an unordered_set in-place.
658
    std::vector<CleanupHookCallback> callbacks(
659
9241
        cleanup_hooks_.begin(), cleanup_hooks_.end());
660
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
661
    // need to be able to check whether they were un-scheduled by another hook.
662
663
9240
    std::sort(callbacks.begin(), callbacks.end(),
664
960814
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
665
      // Sort in descending order so that the most recently inserted callbacks
666
      // are run first.
667
960814
      return a.insertion_order_counter_ > b.insertion_order_counter_;
668
965435
    });
669
670
120008
    for (const CleanupHookCallback& cb : callbacks) {
671
115385
      if (cleanup_hooks_.count(cb) == 0) {
672
        // This hook was removed from the `cleanup_hooks_` set during another
673
        // hook that was run earlier. Nothing to do here.
674
743
        continue;
675
      }
676
677
114644
      cb.fn_(cb.arg_);
678
114659
      cleanup_hooks_.erase(cb);
679
    }
680
4621
    CleanupHandles();
681
  }
682
683
4631
  for (const int fd : unmanaged_fds_) {
684
    uv_fs_t close_req;
685
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
686
3
    uv_fs_req_cleanup(&close_req);
687
  }
688
4628
}
689
690
5128
void Environment::RunAtExitCallbacks() {
691
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
692
10254
                              "AtExit", this);
693
15207
  for (ExitCallback at_exit : at_exit_functions_) {
694
10080
    at_exit.cb_(at_exit.arg_);
695
  }
696
5128
  at_exit_functions_.clear();
697
5126
}
698
699
10099
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
700
10099
  at_exit_functions_.push_front(ExitCallback{cb, arg});
701
10099
}
702
703
511785
void Environment::RunAndClearInterrupts() {
704
520101
  while (native_immediates_interrupts_.size() > 0) {
705
16631
    NativeImmediateQueue queue;
706
    {
707
16631
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
708
8315
      queue.ConcatMove(std::move(native_immediates_interrupts_));
709
    }
710
8316
    DebugSealHandleScope seal_handle_scope(isolate());
711
712
24958
    while (auto head = queue.Shift())
713
16642
      head->Call(this);
714
  }
715
503472
}
716
717
495322
void Environment::RunAndClearNativeImmediates(bool only_refed) {
718
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
719
990644
                              "RunAndClearNativeImmediates", this);
720
990648
  HandleScope handle_scope(isolate_);
721
990652
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
722
723
495327
  size_t ref_count = 0;
724
725
  // Handle interrupts first. These functions are not allowed to throw
726
  // exceptions, so we do not need to handle that.
727
495327
  RunAndClearInterrupts();
728
729
990653
  auto drain_list = [&](NativeImmediateQueue* queue) {
730
2038106
    TryCatchScope try_catch(this);
731
990654
    DebugSealHandleScope seal_handle_scope(isolate());
732
1104602
    while (auto head = queue->Shift()) {
733
56979
      bool is_refed = head->flags() & CallbackFlags::kRefed;
734
56979
      if (is_refed)
735
34603
        ref_count++;
736
737

56979
      if (is_refed || !only_refed)
738
113590
        head->Call(this);
739
740
56977
      head.reset();  // Destroy now so that this is also observed by try_catch.
741
742
56977
      if (UNLIKELY(try_catch.HasCaught())) {
743

6
        if (!try_catch.HasTerminated() && can_call_into_js())
744
3
          errors::TriggerUncaughtException(isolate(), try_catch);
745
746
1
        return true;
747
      }
748
56974
    }
749
990651
    return false;
750
495329
  };
751
495329
  while (drain_list(&native_immediates_)) {}
752
753
495328
  immediate_info()->ref_count_dec(ref_count);
754
755
495327
  if (immediate_info()->ref_count() == 0)
756
388238
    ToggleImmediateRef(false);
757
758
  // It is safe to check .size() first, because there is a causal relationship
759
  // between pushes to the threadsafe immediate list and this function being
760
  // called. For the common case, it's worth checking the size first before
761
  // establishing a mutex lock.
762
  // This is intentionally placed after the `ref_count` handling, because when
763
  // refed threadsafe immediates are created, they are not counted towards the
764
  // count in immediate_info() either.
765
990651
  NativeImmediateQueue threadsafe_immediates;
766
495326
  if (native_immediates_threadsafe_.size() > 0) {
767
1230
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
768
615
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
769
  }
770
495328
  while (drain_list(&threadsafe_immediates)) {}
771
495321
}
772
773
8324
void Environment::RequestInterruptFromV8() {
774
  // The Isolate may outlive the Environment, so some logic to handle the
775
  // situation in which the Environment is destroyed before the handler runs
776
  // is required.
777
778
  // We allocate a new pointer to a pointer to this Environment instance, and
779
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
780
  // callbacks are already scheduled to run and we can delete our own pointer
781
  // and just return. If it was nullptr previously, the Environment** is stored;
782
  // ~Environment sets the Environment* contained in it to nullptr, so that
783
  // the callback can check whether ~Environment has already run and it is thus
784
  // not safe to access the Environment instance itself.
785
8324
  Environment** interrupt_data = new Environment*(this);
786
8324
  Environment** dummy = nullptr;
787
8324
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
788
292
    delete interrupt_data;
789
292
    return;  // Already scheduled.
790
  }
791
792
40146
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
793
16040
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
794
8025
    Environment* env = *env_ptr;
795
8025
    if (env == nullptr) {
796
      // The Environment has already been destroyed. That should be okay; any
797
      // callback added before the Environment shuts down would have been
798
      // handled during cleanup.
799
10
      return;
800
    }
801
8015
    env->interrupt_data_.store(nullptr);
802
8015
    env->RunAndClearInterrupts();
803
24089
  }, interrupt_data);
804
}
805
806
6364
void Environment::ScheduleTimer(int64_t duration_ms) {
807
6364
  if (started_cleanup_) return;
808
6364
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
809
}
810
811
1311
void Environment::ToggleTimerRef(bool ref) {
812
1311
  if (started_cleanup_) return;
813
814
1311
  if (ref) {
815
869
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
816
  } else {
817
442
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
818
  }
819
}
820
821
5216
void Environment::RunTimers(uv_timer_t* handle) {
822
5216
  Environment* env = Environment::from_timer_handle(handle);
823
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
824
10418
                              "RunTimers", env);
825
826
5216
  if (!env->can_call_into_js())
827
    return;
828
829
10418
  HandleScope handle_scope(env->isolate());
830
10418
  Context::Scope context_scope(env->context());
831
832
5216
  Local<Object> process = env->process_object();
833
10418
  InternalCallbackScope scope(env, process, {0, 0});
834
835
5216
  Local<Function> cb = env->timers_callback_function();
836
  MaybeLocal<Value> ret;
837
5216
  Local<Value> arg = env->GetNow();
838
  // This code will loop until all currently due timers will process. It is
839
  // impossible for us to end up in an infinite loop due to how the JS-side
840
  // is structured.
841
5237
  do {
842
10484
    TryCatchScope try_catch(env);
843
5247
    try_catch.SetVerbose(true);
844
10494
    ret = cb->Call(env->context(), process, 1, &arg);
845

5237
  } while (ret.IsEmpty() && env->can_call_into_js());
846
847
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
848
  // is reset back to `true` after being previously set to `false` then this
849
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
850
  // timers corruption will occur and all timers behaviour will become
851
  // entirely unpredictable.
852
5206
  if (ret.IsEmpty())
853
4
    return;
854
855
  // To allow for less JS-C++ boundary crossing, the value returned from JS
856
  // serves a few purposes:
857
  // 1. If it's 0, no more timers exist and the handle should be unrefed
858
  // 2. If it's > 0, the value represents the next timer's expiry and there
859
  //    is at least one timer remaining that is refed.
860
  // 3. If it's < 0, the absolute value represents the next timer's expiry
861
  //    and there are no timers that are refed.
862
  int64_t expiry_ms =
863
20808
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
864
865
5202
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
866
867
5202
  if (expiry_ms != 0) {
868
    int64_t duration_ms =
869
4869
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
870
871
4869
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
872
873
4869
    if (expiry_ms > 0)
874
4590
      uv_ref(h);
875
    else
876
279
      uv_unref(h);
877
  } else {
878
333
    uv_unref(h);
879
  }
880
}
881
882
883
481745
void Environment::CheckImmediate(uv_check_t* handle) {
884
481745
  Environment* env = Environment::from_immediate_check_handle(handle);
885
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
886
588437
                              "CheckImmediate", env);
887
888
588437
  HandleScope scope(env->isolate());
889
588434
  Context::Scope context_scope(env->context());
890
891
481748
  env->RunAndClearNativeImmediates();
892
893

481747
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
894
375045
    return;
895
896
107631
  do {
897
215269
    MakeCallback(env->isolate(),
898
                 env->process_object(),
899
                 env->immediate_callback_function(),
900
                 0,
901
                 nullptr,
902
107643
                 {0, 0}).ToLocalChecked();
903

107631
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
904
905
106691
  if (env->immediate_info()->ref_count() == 0)
906
4574
    env->ToggleImmediateRef(false);
907
}
908
909
522842
void Environment::ToggleImmediateRef(bool ref) {
910
522842
  if (started_cleanup_) return;
911
912
513597
  if (ref) {
913
    // Idle handle is needed only to stop the event loop from blocking in poll.
914
466344
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
915
  } else {
916
383585
    uv_idle_stop(immediate_idle_handle());
917
  }
918
}
919
920
921
23460
Local<Value> Environment::GetNow() {
922
23460
  uv_update_time(event_loop());
923
23460
  uint64_t now = uv_now(event_loop());
924
23460
  CHECK_GE(now, timer_base());
925
23460
  now -= timer_base();
926
23460
  if (now <= 0xffffffff)
927
46920
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
928
  else
929
    return Number::New(isolate(), static_cast<double>(now));
930
}
931
932
28
void CollectExceptionInfo(Environment* env,
933
                          Local<Object> obj,
934
                          int errorno,
935
                          const char* err_string,
936
                          const char* syscall,
937
                          const char* message,
938
                          const char* path,
939
                          const char* dest) {
940
56
  obj->Set(env->context(),
941
           env->errno_string(),
942
140
           Integer::New(env->isolate(), errorno)).Check();
943
944
56
  obj->Set(env->context(), env->code_string(),
945
140
           OneByteString(env->isolate(), err_string)).Check();
946
947
28
  if (message != nullptr) {
948
56
    obj->Set(env->context(), env->message_string(),
949
140
             OneByteString(env->isolate(), message)).Check();
950
  }
951
952
  Local<Value> path_buffer;
953
28
  if (path != nullptr) {
954
    path_buffer =
955
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
956
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
957
  }
958
959
  Local<Value> dest_buffer;
960
28
  if (dest != nullptr) {
961
    dest_buffer =
962
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
963
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
964
  }
965
966
28
  if (syscall != nullptr) {
967
56
    obj->Set(env->context(), env->syscall_string(),
968
140
             OneByteString(env->isolate(), syscall)).Check();
969
  }
970
28
}
971
972
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
973
                                         int errorno,
974
                                         const char* syscall,
975
                                         const char* message,
976
                                         const char* path,
977
                                         const char* dest) {
978

28
  if (!object->IsObject() || errorno == 0)
979
    return;
980
981
28
  Local<Object> obj = object.As<Object>();
982
28
  const char* err_string = uv_err_name(errorno);
983
984

28
  if (message == nullptr || message[0] == '\0') {
985
28
    message = uv_strerror(errorno);
986
  }
987
988
  node::CollectExceptionInfo(this, obj, errorno, err_string,
989
28
                             syscall, message, path, dest);
990
}
991
992
5057
ImmediateInfo::ImmediateInfo(v8::Isolate* isolate, const SerializeInfo* info)
993
5057
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
994
995
8
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
996
    v8::Local<v8::Context> context, v8::SnapshotCreator* creator) {
997
8
  return {fields_.Serialize(context, creator)};
998
}
999
1000
4613
void ImmediateInfo::Deserialize(Local<Context> context) {
1001
4613
  fields_.Deserialize(context);
1002
4613
}
1003
1004
8
std::ostream& operator<<(std::ostream& output,
1005
                         const ImmediateInfo::SerializeInfo& i) {
1006
8
  output << "{ " << i.fields << " }";
1007
8
  return output;
1008
}
1009
1010
22
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1011
22
  tracker->TrackField("fields", fields_);
1012
22
}
1013
1014
8
TickInfo::SerializeInfo TickInfo::Serialize(v8::Local<v8::Context> context,
1015
                                            v8::SnapshotCreator* creator) {
1016
8
  return {fields_.Serialize(context, creator)};
1017
}
1018
1019
4613
void TickInfo::Deserialize(Local<Context> context) {
1020
4613
  fields_.Deserialize(context);
1021
4613
}
1022
1023
8
std::ostream& operator<<(std::ostream& output,
1024
                         const TickInfo::SerializeInfo& i) {
1025
8
  output << "{ " << i.fields << " }";
1026
8
  return output;
1027
}
1028
1029
22
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1030
22
  tracker->TrackField("fields", fields_);
1031
22
}
1032
1033
5057
TickInfo::TickInfo(v8::Isolate* isolate, const SerializeInfo* info)
1034
    : fields_(
1035
5057
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1036
1037
5057
AsyncHooks::AsyncHooks(v8::Isolate* isolate, const SerializeInfo* info)
1038
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1039
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1040
      async_id_fields_(
1041
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1042

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









192
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1278
8
#undef V
1279
16
1280
8
  id = 0;
1281
24
#define V(PropertyName, TypeName)                                              \
1282
8
  do {                                                                         \
1283
32
    Local<TypeName> field = PropertyName();                                    \
1284
24
    if (!field.IsEmpty()) {                                                    \
1285
8
      size_t index = creator->AddData(ctx, field);                             \
1286
16
      info.persistent_values.push_back({#PropertyName, id, index});            \
1287
    }                                                                          \
1288
16
    id++;                                                                      \
1289
  } while (0);
1290




















480
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1291
8
#undef V
1292

40
1293
32
  info.context = creator->AddData(ctx, context());
1294

48
  return info;
1295

40
}
1296
32
1297

56
std::ostream& operator<<(std::ostream& output,
1298
8
                         const std::vector<PropInfo>& vec) {
1299

48
  output << "{\n";
1300
312
  for (const auto& info : vec) {
1301

600
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1302
848
           << std::to_string(info.index) << " },\n";
1303

48
  }
1304
40
  output << "}";
1305
40
  return output;
1306
16
}
1307
24
1308
32
std::ostream& operator<<(std::ostream& output,
1309
                         const std::vector<std::string>& vec) {
1310
24
  output << "{\n";
1311
432
  for (const auto& info : vec) {
1312
440
    output << "  \"" << info << "\",\n";
1313
  }
1314
24
  output << "}";
1315
8
  return output;
1316
24
}
1317
8
1318
32
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1319
8
  output << "{\n"
1320
24
         << "// -- native_modules begins --\n"
1321
24
         << i.native_modules << ",\n"
1322
         << "// -- native_modules ends --\n"
1323
8
         << "// -- async_hooks begins --\n"
1324
16
         << i.async_hooks << ",\n"
1325
8
         << "// -- async_hooks ends --\n"
1326
16
         << i.tick_info << ",  // tick_info\n"
1327
16
         << i.immediate_info << ",  // immediate_info\n"
1328
8
         << "// -- performance_state begins --\n"
1329
16
         << i.performance_state << ",\n"
1330
8
         << "// -- performance_state ends --\n"
1331
16
         << i.stream_base_state << ",  // stream_base_state\n"
1332
16
         << i.should_abort_on_uncaught_toggle
1333
         << ",  // should_abort_on_uncaught_toggle\n"
1334
8
         << "// -- persistent_templates begins --\n"
1335
16
         << i.persistent_templates << ",\n"
1336
         << "// persistent_templates ends --\n"
1337
8
         << "// -- persistent_values begins --\n"
1338
16
         << i.persistent_values << ",\n"
1339
8
         << "// -- persistent_values ends --\n"
1340
16
         << i.context << ",  // context\n"
1341
8
         << "}";
1342
8
  return output;
1343
}
1344
1345
4613
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1346
4613
  Local<Context> ctx = context();
1347
1348
4613
  native_modules_in_snapshot = info->native_modules;
1349
4613
  async_hooks_.Deserialize(ctx);
1350
4613
  immediate_info_.Deserialize(ctx);
1351
4613
  tick_info_.Deserialize(ctx);
1352
4613
  performance_state_->Deserialize(ctx);
1353
4613
  stream_base_state_.Deserialize(ctx);
1354
4613
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1355
1356
4613
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1357
    fprintf(stderr, "deserializing...\n");
1358
    std::cerr << *info << "\n";
1359
  }
1360
1361
4613
  const std::vector<PropInfo>& templates = info->persistent_templates;
1362
4613
  size_t i = 0;  // index to the array
1363
4613
  size_t id = 0;
1364
#define SetProperty(PropertyName, TypeName, vector, type, from)                \
1365
  do {                                                                         \
1366
    if (vector.size() > i && id == vector[i].id) {                             \
1367
      const PropInfo& d = vector[i];                                           \
1368
      DCHECK_EQ(d.name, #PropertyName);                                        \
1369
      MaybeLocal<TypeName> maybe_field =                                       \
1370
          from->GetDataFromSnapshotOnce<TypeName>(d.index);                    \
1371
      Local<TypeName> field;                                                   \
1372
      if (!maybe_field.ToLocal(&field)) {                                      \
1373
        fprintf(stderr,                                                        \
1374
                "Failed to deserialize environment " #type " " #PropertyName   \
1375
                "\n");                                                         \
1376
      }                                                                        \
1377
      set_##PropertyName(field);                                               \
1378
      i++;                                                                     \
1379
    }                                                                          \
1380
  } while (0);                                                                 \
1381
  id++;
1382
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1383
                                              templates, template, isolate_)
1384




































































78421
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1385
#undef V
1386
1387
4613
  i = 0;  // index to the array
1388
4613
  id = 0;
1389
4613
  const std::vector<PropInfo>& values = info->persistent_values;
1390
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1391
                                              values, value, ctx)
1392














































































































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

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

113714
  if (self->has_pointer_data() &&
1611
4106
      self->pointer_data()->strong_ptr_count > 0) {
1612
290
    return self->Detach();
1613
22
  }
1614
109362
  delete self;
1615
22
}
1616
22
1617
341
bool BaseObject::IsDoneInitializing() const { return true; }
1618
22
1619
403
Local<Object> BaseObject::WrappedObject() const {
1620
403
  return object();
1621
}
1622
1623
762
bool BaseObject::IsRootNode() const {
1624
1524
  return !persistent_handle_.IsWeak();
1625
}
1626
1627
42676
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1628
42676
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1629
42676
  if (tmpl.IsEmpty()) {
1630
444
    tmpl = env->NewFunctionTemplate(nullptr);
1631
888
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1632
444
    env->set_base_object_ctor_template(tmpl);
1633
  }
1634
42676
  return tmpl;
1635
}
1636
1637
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1638
  return IsWeakOrDetached();
1639
}
1640
1641

14097
}  // namespace node