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: 829 881 94.1 %
Date: 2021-01-16 04:10:54 Branches: 915 1723 53.1 %

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
1696
  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
4623
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
91
4623
  size_t i = 0;
92
9190
  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




110016
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
108






165012
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
109
































































































































3533517
  PER_ISOLATE_STRING_PROPERTIES(VS)
110
24
#undef V
111
#undef VY
112
#undef VS
113
#undef VP
114
115
284146
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
116
    MaybeLocal<String> maybe_field =
117
559126
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
118
    Local<String> field;
119
279563
    if (!maybe_field.ToLocal(&field)) {
120
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
121
    }
122
279563
    async_wrap_providers_[j].Set(isolate_, field);
123
  }
124
4583
}
125
126
454
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
908
  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
1362
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
151
#undef V
152
1362
#define V(PropertyName, StringValue)                                           \
153
  PropertyName##_.Set(                                                         \
154
1362
      isolate_,                                                                \
155
      Symbol::New(isolate_,                                                    \
156
1362
                  String::NewFromOneByte(                                      \
157
454
                      isolate_,                                                \
158
1362
                      reinterpret_cast<const uint8_t*>(StringValue),           \
159
454
                      NewStringType::kInternalized,                            \
160
908
                      sizeof(StringValue) - 1)                                 \
161
1362
                      .ToLocalChecked()));
162
1362
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
163
1816
#undef V
164
1362
#define V(PropertyName, StringValue)                                           \
165
454
  PropertyName##_.Set(                                                         \
166
908
      isolate_,                                                                \
167
454
      String::NewFromOneByte(isolate_,                                         \
168
908
                             reinterpret_cast<const uint8_t*>(StringValue),    \
169
454
                             NewStringType::kInternalized,                     \
170
908
                             sizeof(StringValue) - 1)                          \
171
454
          .ToLocalChecked());
172
234718
  PER_ISOLATE_STRING_PROPERTIES(V)
173
1362
#undef V
174
175
1362
  // 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
1362
  // strings can be retrieved quickly.
178
454
#define V(Provider)                                                           \
179
908
  async_wrap_providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                \
180
1362
      isolate_,                                                               \
181
      String::NewFromOneByte(                                                 \
182
1362
        isolate_,                                                             \
183
        reinterpret_cast<const uint8_t*>(#Provider),                          \
184
        NewStringType::kInternalized,                                         \
185
        sizeof(#Provider) - 1).ToLocalChecked());
186
40860
  NODE_ASYNC_PROVIDER_TYPES(V)
187
#undef V
188
1816
}
189
454
190
5945
IsolateData::IsolateData(Isolate* isolate,
191
1362
                         uv_loop_t* event_loop,
192
                         MultiIsolatePlatform* platform,
193
1362
                         ArrayBufferAllocator* node_allocator,
194
5037
                         const std::vector<size_t>* indexes)
195
1362
    : isolate_(isolate),
196
      event_loop_(event_loop),
197
11390
      node_allocator_(node_allocator == nullptr ? nullptr
198
5445
                                                : node_allocator->GetImpl()),
199
1406231
      platform_(platform) {
200
10528
  options_.reset(
201
16019
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
202
1362
203
5037
  if (indexes == nullptr) {
204
1816
    CreateProperties();
205
  } else {
206
5945
    DeserializeProperties(indexes);
207
  }
208
6399
}
209
210
1384
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
211
454
#define V(PropertyName, StringValue)                                           \
212
908
  tracker->TrackField(#PropertyName, PropertyName());
213
1384
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
214
22
215
1428
  PER_ISOLATE_STRING_PROPERTIES(V)
216
44
#undef V
217
1406
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
440
void Environment::CreateProperties() {
255
880
  HandleScope handle_scope(isolate_);
256
440
  Local<Context> ctx = context();
257
258
  {
259
    Context::Scope context_scope(ctx);
260
440
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
261
1320
    templ->InstanceTemplate()->SetInternalFieldCount(
262
440
        BaseObject::kInternalFieldCount);
263
880
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
264
265
440
    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
880
      GetPerContextExports(ctx).ToLocalChecked();
271
  Local<Value> primordials =
272
1320
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
273
440
  CHECK(primordials->IsObject());
274
440
  set_primordials(primordials.As<Object>());
275
276
  Local<Object> process_object =
277
880
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
278
440
  set_process_object(process_object);
279
440
}
280
281
5022
std::string GetExecPath(const std::vector<std::string>& argv) {
282
  char exec_path_buf[2 * PATH_MAX];
283
5022
  size_t exec_path_len = sizeof(exec_path_buf);
284
5022
  std::string exec_path;
285
5022
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
286
5022
    exec_path = std::string(exec_path_buf, exec_path_len);
287
  } else {
288
    exec_path = argv[0];
289
  }
290
291
  // On OpenBSD process.execPath will be relative unless we
292
  // get the full path before process.execPath is used.
293
#if defined(__OpenBSD__)
294
  uv_fs_t req;
295
  req.ptr = nullptr;
296
  if (0 ==
297
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
298
    CHECK_NOT_NULL(req.ptr);
299
    exec_path = std::string(static_cast<char*>(req.ptr));
300
  }
301
  uv_fs_req_cleanup(&req);
302
#endif
303
304
5022
  return exec_path;
305
}
306
307
5022
Environment::Environment(IsolateData* isolate_data,
308
                         Isolate* isolate,
309
                         const std::vector<std::string>& args,
310
                         const std::vector<std::string>& exec_args,
311
                         const EnvSerializeInfo* env_info,
312
                         EnvironmentFlags::Flags flags,
313
5022
                         ThreadId thread_id)
314
    : isolate_(isolate),
315
      isolate_data_(isolate_data),
316
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
317
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
318
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
319
5022
      timer_base_(uv_now(isolate_data->event_loop())),
320
      exec_argv_(exec_args),
321
      argv_(args),
322
      exec_path_(GetExecPath(args)),
323
      should_abort_on_uncaught_toggle_(
324
5022
          isolate_,
325
          1,
326
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
327
5022
      stream_base_state_(isolate_,
328
                         StreamBase::kNumStreamBaseStateFields,
329
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
330
5022
      environment_start_time_(PERFORMANCE_NOW()),
331
      flags_(flags),
332
5022
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
333
5022
                     ? AllocateEnvironmentThreadId().id
334


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

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

51992
  while (handle_cleanup_waiting_ != 0 ||
611

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

26581
  while (!cleanup_hooks_.empty() ||
638
8871
         native_immediates_.size() > 0 ||
639

17727
         native_immediates_threadsafe_.size() > 0 ||
640
4435
         native_immediates_interrupts_.size() > 0) {
641
    // Copy into a vector, since we can't sort an unordered_set in-place.
642
    std::vector<CleanupHookCallback> callbacks(
643
8853
        cleanup_hooks_.begin(), cleanup_hooks_.end());
644
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
645
    // need to be able to check whether they were un-scheduled by another hook.
646
647
8855
    std::sort(callbacks.begin(), callbacks.end(),
648
959432
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
649
      // Sort in descending order so that the most recently inserted callbacks
650
      // are run first.
651
959432
      return a.insertion_order_counter_ > b.insertion_order_counter_;
652
963860
    });
653
654
117075
    for (const CleanupHookCallback& cb : callbacks) {
655
112640
      if (cleanup_hooks_.count(cb) == 0) {
656
        // This hook was removed from the `cleanup_hooks_` set during another
657
        // hook that was run earlier. Nothing to do here.
658
737
        continue;
659
      }
660
661
111905
      cb.fn_(cb.arg_);
662
111914
      cleanup_hooks_.erase(cb);
663
    }
664
4428
    CleanupHandles();
665
  }
666
667
4438
  for (const int fd : unmanaged_fds_) {
668
    uv_fs_t close_req;
669
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
670
3
    uv_fs_req_cleanup(&close_req);
671
  }
672
4433
}
673
674
5090
void Environment::RunAtExitCallbacks() {
675
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
676
10183
                              "AtExit", this);
677
15100
  for (ExitCallback at_exit : at_exit_functions_) {
678
10008
    at_exit.cb_(at_exit.arg_);
679
  }
680
5093
  at_exit_functions_.clear();
681
5093
}
682
683
10030
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
684
10030
  at_exit_functions_.push_front(ExitCallback{cb, arg});
685
10030
}
686
687
504312
void Environment::RunAndClearInterrupts() {
688
512360
  while (native_immediates_interrupts_.size() > 0) {
689
16096
    NativeImmediateQueue queue;
690
    {
691
16096
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
692
8048
      queue.ConcatMove(std::move(native_immediates_interrupts_));
693
    }
694
8048
    DebugSealHandleScope seal_handle_scope(isolate());
695
696
24150
    while (auto head = queue.Shift())
697
16102
      head->Call(this);
698
  }
699
496266
}
700
701
488400
void Environment::RunAndClearNativeImmediates(bool only_refed) {
702
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
703
976801
                              "RunAndClearNativeImmediates", this);
704
976801
  HandleScope handle_scope(isolate_);
705
976803
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
706
707
488404
  size_t ref_count = 0;
708
709
  // Handle interrupts first. These functions are not allowed to throw
710
  // exceptions, so we do not need to handle that.
711
488404
  RunAndClearInterrupts();
712
713
976802
  auto drain_list = [&](NativeImmediateQueue* queue) {
714
2010115
    TryCatchScope try_catch(this);
715
976805
    DebugSealHandleScope seal_handle_scope(isolate());
716
1090157
    while (auto head = queue->Shift()) {
717
56683
      bool is_refed = head->flags() & CallbackFlags::kRefed;
718
56683
      if (is_refed)
719
34430
        ref_count++;
720
721

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

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

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

475293
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
878
369612
    return;
879
880
106613
  do {
881
213229
    MakeCallback(env->isolate(),
882
                 env->process_object(),
883
                 env->immediate_callback_function(),
884
                 0,
885
                 nullptr,
886
106621
                 {0, 0}).ToLocalChecked();
887

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

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

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

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








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


















416
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1275
8
#undef V
1276

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

56
  return info;
1279

40
}
1280
32
1281

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

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

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

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


































































77911
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1369
#undef V
1370
1371
4583
  i = 0;  // index to the array
1372
4583
  id = 0;
1373
4583
  const std::vector<PropInfo>& values = info->persistent_values;
1374
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1375
                                              values, value, ctx)
1376






































































































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

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

111117
  if (self->has_pointer_data() &&
1595
4049
      self->pointer_data()->strong_ptr_count > 0) {
1596
283
    return self->Detach();
1597
22
  }
1598
106833
  delete self;
1599
22
}
1600
22
1601
341
bool BaseObject::IsDoneInitializing() const { return true; }
1602
22
1603
403
Local<Object> BaseObject::WrappedObject() const {
1604
403
  return object();
1605
}
1606
1607
762
bool BaseObject::IsRootNode() const {
1608
1524
  return !persistent_handle_.IsWeak();
1609
}
1610
1611
42508
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1612
42508
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1613
42508
  if (tmpl.IsEmpty()) {
1614
439
    tmpl = env->NewFunctionTemplate(nullptr);
1615
878
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1616
439
    env->set_base_object_ctor_template(tmpl);
1617
  }
1618
42508
  return tmpl;
1619
}
1620
1621
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1622
  return IsWeakOrDetached();
1623
}
1624
1625

13995
}  // namespace node