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: 2020-12-12 04:11:07 Branches: 911 1711 53.2 %

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




110568
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
108






165840
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
109
































































































































3537432
  PER_ISOLATE_STRING_PROPERTIES(VS)
110
24
#undef V
111
#undef VY
112
#undef VS
113
#undef VP
114
115
285572
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
116
    MaybeLocal<String> maybe_field =
117
561932
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
118
    Local<String> field;
119
280966
    if (!maybe_field.ToLocal(&field)) {
120
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
121
    }
122
280966
    async_wrap_providers_[j].Set(isolate_, field);
123
  }
124
4606
}
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
458
      String::NewFromOneByte(isolate_,                                         \
168
918
                             reinterpret_cast<const uint8_t*>(StringValue),    \
169
459
                             NewStringType::kInternalized,                     \
170
918
                             sizeof(StringValue) - 1)                          \
171
459
          .ToLocalChecked());
172
236384
  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
41310
  NODE_ASYNC_PROVIDER_TYPES(V)
187
#undef V
188
1836
}
189
459
190
5983
IsolateData::IsolateData(Isolate* isolate,
191
1377
                         uv_loop_t* event_loop,
192
                         MultiIsolatePlatform* platform,
193
1377
                         ArrayBufferAllocator* node_allocator,
194
5065
                         const std::vector<size_t>* indexes)
195
1377
    : isolate_(isolate),
196
      event_loop_(event_loop),
197
11462
      node_allocator_(node_allocator == nullptr ? nullptr
198
5479
                                                : node_allocator->GetImpl()),
199
1408988
      platform_(platform) {
200
10589
  options_.reset(
201
16113
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
202
1377
203
5065
  if (indexes == nullptr) {
204
1836
    CreateProperties();
205
  } else {
206
5983
    DeserializeProperties(indexes);
207
  }
208
6442
}
209
210
1399
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
211
459
#define V(PropertyName, StringValue)                                           \
212
918
  tracker->TrackField(#PropertyName, PropertyName());
213
1399
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
214
22
215
1443
  PER_ISOLATE_STRING_PROPERTIES(V)
216
44
#undef V
217
1421
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
445
void Environment::CreateProperties() {
255
890
  HandleScope handle_scope(isolate_);
256
445
  Local<Context> ctx = context();
257
258
  {
259
    Context::Scope context_scope(ctx);
260
445
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
261
1335
    templ->InstanceTemplate()->SetInternalFieldCount(
262
445
        BaseObject::kInternalFieldCount);
263
890
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
264
265
445
    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
890
      GetPerContextExports(ctx).ToLocalChecked();
271
  Local<Value> primordials =
272
1335
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
273
445
  CHECK(primordials->IsObject());
274
445
  set_primordials(primordials.As<Object>());
275
276
  Local<Object> process_object =
277
890
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
278
445
  set_process_object(process_object);
279
445
}
280
281
5050
std::string GetExecPath(const std::vector<std::string>& argv) {
282
  char exec_path_buf[2 * PATH_MAX];
283
5050
  size_t exec_path_len = sizeof(exec_path_buf);
284
5050
  std::string exec_path;
285
5050
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
286
5050
    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
5050
  return exec_path;
305
}
306
307
5050
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
5050
                         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
5050
      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
5050
          isolate_,
325
          1,
326
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
327
5050
      stream_base_state_(isolate_,
328
                         StreamBase::kNumStreamBaseStateFields,
329
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
330
5050
      environment_start_time_(PERFORMANCE_NOW()),
331
      flags_(flags),
332
5050
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
333
5050
                     ? AllocateEnvironmentThreadId().id
334


454500
                     : thread_id.id) {
335
  // We'll be creating new objects so make sure we've entered the context.
336
10100
  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
5050
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
341
9312
    flags_ = flags_ |
342
4656
        EnvironmentFlags::kOwnsProcessState |
343
        EnvironmentFlags::kOwnsInspector;
344
  }
345
346
5050
  set_env_vars(per_process::system_environment);
347
  // TODO(joyeecheung): pass Isolate* and env_vars to it instead of the entire
348
  // env
349
5050
  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
5050
  options_.reset(new EnvironmentOptions(*isolate_data->options()->per_env));
356
10100
  inspector_host_port_.reset(
357
15150
      new ExclusiveAccess<HostPort>(options_->debug_options().host_port));
358
359
5050
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
360
394
    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
5050
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
366
#endif
367
368
5050
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
369
5050
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
370
5050
    if (TracingController* tracing_controller = writer->GetTracingController())
371
5006
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
372
  }
373
374
5050
  destroy_async_id_list_.reserve(512);
375
376
10100
  performance_state_ = std::make_unique<performance::PerformanceState>(
377
15150
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
378
379
5050
  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
5050
  initial_base_object_count_ = base_object_count();
398
5050
}
399
400
444
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
444
                         ThreadId thread_id)
407
    : Environment(isolate_data,
408
                  context->GetIsolate(),
409
                  args,
410
                  exec_args,
411
                  env_info,
412
                  flags,
413
444
                  thread_id) {
414
444
  InitializeMainContext(context, env_info);
415
444
}
416
417
5051
void Environment::InitializeMainContext(Local<Context> context,
418
                                        const EnvSerializeInfo* env_info) {
419
5051
  context_.Reset(context->GetIsolate(), context);
420
5051
  AssignToContext(context, ContextInfo(""));
421
5051
  if (env_info != nullptr) {
422
4606
    DeserializeProperties(env_info);
423
  } else {
424
445
    CreateProperties();
425
  }
426
427
5051
  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
5051
  should_abort_on_uncaught_toggle_[0] = 1;
433
434
5051
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
435
5051
                           environment_start_time_);
436
5051
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
437
10102
                           per_process::node_start_time);
438
5051
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
439
10102
                           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
5051
  initial_base_object_count_ = base_object_count();
444
5051
}
445
446
398286
Environment::~Environment() {
447
4578
  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
4578
  CHECK(is_stopping());
474
475
4578
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
476
1
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
477
1
                                          0);
478
  }
479
480
4578
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
481
4578
      BuildEmbedderGraph, this);
482
483
9156
  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
4578
  inspector_agent_.reset();
489
#endif
490
491
13734
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
492
4578
                                             nullptr);
493
494
4578
  if (trace_state_observer_) {
495
4578
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
496
4578
    CHECK_NOT_NULL(writer);
497
4578
    if (TracingController* tracing_controller = writer->GetTracingController())
498
4536
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
499
  }
500
501
4578
  TRACE_EVENT_NESTABLE_ASYNC_END0(
502
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
503
504
4158
  // Do not unload addons on the main thread. Some addons need to retain memory
505
4578
  // 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
405
    for (binding::DLib& addon : loaded_addons_) {
512
14
      addon.Close();
513
    }
514
  }
515
516
4578
  CHECK_EQ(base_object_count_, 0);
517
9156
}
518
519
5017
void Environment::InitializeLibuv() {
520
10034
  HandleScope handle_scope(isolate());
521
5017
  Context::Scope context_scope(context());
522
523
5017
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
524
5017
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
525
526
5017
  uv_check_init(event_loop(), immediate_check_handle());
527
5017
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
528
529
5017
  uv_idle_init(event_loop(), immediate_idle_handle());
530
531
5017
  uv_check_start(immediate_check_handle(), CheckImmediate);
532
533
10034
  uv_async_init(
534
      event_loop(),
535
      &task_queues_async_,
536
13449
      [](uv_async_t* async) {
537
8432
        Environment* env = ContainerOf(
538
4216
            &Environment::task_queues_async_, async);
539
8428
        HandleScope handle_scope(env->isolate());
540
4216
        Context::Scope context_scope(env->context());
541
4216
        env->RunAndClearNativeImmediates();
542
18462
      });
543
5017
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
544
545
  {
546
10034
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
547
5017
    task_queues_async_initialized_ = true;
548

10034
    if (native_immediates_threadsafe_.size() > 0 ||
549
5017
        native_immediates_interrupts_.size() > 0) {
550
4600
      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
5017
  RegisterHandleCleanups();
559
5017
}
560
561
97
void Environment::ExitEnv() {
562
97
  set_can_call_into_js(false);
563
97
  set_stopping(true);
564
97
  isolate_->TerminateExecution();
565
194
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
566
97
}
567
568
5017
void Environment::RegisterHandleCleanups() {
569
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
570
41371
                                        void* arg) {
571
18177
    handle->data = env;
572
573
36357
    env->CloseHandle(handle, [](uv_handle_t* handle) {
574
#ifdef DEBUG
575
      memset(handle, 0xab, uv_handle_size(handle->type));
576
#endif
577
36357
    });
578
46388
  };
579
580
20068
  auto register_handle = [&](uv_handle_t* handle) {
581
20068
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
582
25085
  };
583
5017
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
584
5017
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
585
5017
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
586
5017
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
587
5017
}
588
589
9146
void Environment::CleanupHandles() {
590
  {
591
18295
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
592
9149
    task_queues_async_initialized_ = false;
593
  }
594
595
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
596
18297
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
597
598
9148
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
599
600
9164
  for (ReqWrapBase* request : req_wrap_queue_)
601
16
    request->Cancel();
602
603
11542
  for (HandleWrap* handle : handle_wrap_queue_)
604
4788
    handle->Close();
605
606
27326
  for (HandleCleanup& hc : handle_cleanup_queue_)
607
18177
    hc.cb_(this, hc.handle_, hc.arg_);
608
9148
  handle_cleanup_queue_.clear();
609
610

53692
  while (handle_cleanup_waiting_ != 0 ||
611

27046
         request_waiting_ != 0 ||
612
9150
         !handle_wrap_queue_.IsEmpty()) {
613
8748
    uv_run(event_loop(), UV_RUN_ONCE);
614
  }
615
9149
}
616
617
431879
void Environment::PrintSyncTrace() const {
618
431879
  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
4577
void Environment::RunCleanup() {
630
4577
  started_cleanup_ = true;
631
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
632
9154
                              "RunCleanup", this);
633
4576
  bindings_.clear();
634
4577
  initial_base_object_count_ = 0;
635
4577
  CleanupHandles();
636
637

27448
  while (!cleanup_hooks_.empty() ||
638
9158
         native_immediates_.size() > 0 ||
639

18304
         native_immediates_threadsafe_.size() > 0 ||
640
4578
         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
9141
        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
9141
    std::sort(callbacks.begin(), callbacks.end(),
648
945075
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
649
      // Sort in descending order so that the most recently inserted callbacks
650
      // are run first.
651
945075
      return a.insertion_order_counter_ > b.insertion_order_counter_;
652
949646
    });
653
654
118186
    for (const CleanupHookCallback& cb : callbacks) {
655
113617
      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
729
        continue;
659
      }
660
661
112891
      cb.fn_(cb.arg_);
662
112895
      cleanup_hooks_.erase(cb);
663
    }
664
4570
    CleanupHandles();
665
  }
666
667
4581
  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
4577
}
673
674
5119
void Environment::RunAtExitCallbacks() {
675
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
676
10239
                              "AtExit", this);
677
15186
  for (ExitCallback at_exit : at_exit_functions_) {
678
10065
    at_exit.cb_(at_exit.arg_);
679
  }
680
5120
  at_exit_functions_.clear();
681
5120
}
682
683
10085
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
684
10085
  at_exit_functions_.push_front(ExitCallback{cb, arg});
685
10086
}
686
687
503789
void Environment::RunAndClearInterrupts() {
688
511865
  while (native_immediates_interrupts_.size() > 0) {
689
16152
    NativeImmediateQueue queue;
690
    {
691
16152
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
692
8076
      queue.ConcatMove(std::move(native_immediates_interrupts_));
693
    }
694
8076
    DebugSealHandleScope seal_handle_scope(isolate());
695
696
24232
    while (auto head = queue.Shift())
697
16156
      head->Call(this);
698
  }
699
495713
}
700
701
487829
void Environment::RunAndClearNativeImmediates(bool only_refed) {
702
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
703
975653
                              "RunAndClearNativeImmediates", this);
704
975652
  HandleScope handle_scope(isolate_);
705
975652
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
706
707
487829
  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
487829
  RunAndClearInterrupts();
712
713
975653
  auto drain_list = [&](NativeImmediateQueue* queue) {
714
2008026
    TryCatchScope try_catch(this);
715
975652
    DebugSealHandleScope seal_handle_scope(isolate());
716
1089431
    while (auto head = queue->Shift()) {
717
56894
      bool is_refed = head->flags() & CallbackFlags::kRefed;
718
56894
      if (is_refed)
719
34639
        ref_count++;
720
721

56894
      if (is_refed || !only_refed)
722
113434
        head->Call(this);
723
724
56892
      head.reset();  // Destroy now so that this is also observed by try_catch.
725
726
56892
      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
56889
    }
733
975649
    return false;
734
487830
  };
735
487830
  while (drain_list(&native_immediates_)) {}
736
737
487829
  immediate_info()->ref_count_dec(ref_count);
738
739
487829
  if (immediate_info()->ref_count() == 0)
740
387303
    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
975653
  NativeImmediateQueue threadsafe_immediates;
750
487829
  if (native_immediates_threadsafe_.size() > 0) {
751
1214
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
752
607
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
753
  }
754
487828
  while (drain_list(&threadsafe_immediates)) {}
755
487824
}
756
757
8082
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
8082
  Environment** interrupt_data = new Environment*(this);
770
8082
  Environment** dummy = nullptr;
771
8082
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
772
310
    delete interrupt_data;
773
310
    return;  // Already scheduled.
774
  }
775
776
38843
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
777
15518
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
778
7764
    Environment* env = *env_ptr;
779
7764
    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
7754
    env->interrupt_data_.store(nullptr);
786
7754
    env->RunAndClearInterrupts();
787
23306
  }, interrupt_data);
788
}
789
790
6350
void Environment::ScheduleTimer(int64_t duration_ms) {
791
6350
  if (started_cleanup_) return;
792
6350
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
793
}
794
795
1280
void Environment::ToggleTimerRef(bool ref) {
796
1280
  if (started_cleanup_) return;
797
798
1280
  if (ref) {
799
850
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
800
  } else {
801
430
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
802
  }
803
}
804
805
5229
void Environment::RunTimers(uv_timer_t* handle) {
806
5229
  Environment* env = Environment::from_timer_handle(handle);
807
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
808
10445
                              "RunTimers", env);
809
810
5229
  if (!env->can_call_into_js())
811
    return;
812
813
10445
  HandleScope handle_scope(env->isolate());
814
10445
  Context::Scope context_scope(env->context());
815
816
5229
  Local<Object> process = env->process_object();
817
10445
  InternalCallbackScope scope(env, process, {0, 0});
818
819
5229
  Local<Function> cb = env->timers_callback_function();
820
  MaybeLocal<Value> ret;
821
5229
  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
5250
  do {
826
10510
    TryCatchScope try_catch(env);
827
5260
    try_catch.SetVerbose(true);
828
10520
    ret = cb->Call(env->context(), process, 1, &arg);
829

5250
  } 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
5219
  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
20864
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
848
849
5216
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
850
851
5216
  if (expiry_ms != 0) {
852
    int64_t duration_ms =
853
4890
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
854
855
4890
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
856
857
4890
    if (expiry_ms > 0)
858
4595
      uv_ref(h);
859
    else
860
295
      uv_unref(h);
861
  } else {
862
326
    uv_unref(h);
863
  }
864
}
865
866
867
474465
void Environment::CheckImmediate(uv_check_t* handle) {
868
474465
  Environment* env = Environment::from_immediate_check_handle(handle);
869
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
870
574654
                              "CheckImmediate", env);
871
872
574654
  HandleScope scope(env->isolate());
873
574654
  Context::Scope context_scope(env->context());
874
875
474465
  env->RunAndClearNativeImmediates();
876
877

474465
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
878
374269
    return;
879
880
101129
  do {
881
202265
    MakeCallback(env->isolate(),
882
                 env->process_object(),
883
                 env->immediate_callback_function(),
884
                 0,
885
                 nullptr,
886
101136
                 {0, 0}).ToLocalChecked();
887

101129
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
888
889
100189
  if (env->immediate_info()->ref_count() == 0)
890
4561
    env->ToggleImmediateRef(false);
891
}
892
893
515386
void Environment::ToggleImmediateRef(bool ref) {
894
515386
  if (started_cleanup_) return;
895
896
506241
  if (ref) {
897
    // Idle handle is needed only to stop the event loop from blocking in poll.
898
440328
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
899
  } else {
900
382742
    uv_idle_stop(immediate_idle_handle());
901
  }
902
}
903
904
905
22990
Local<Value> Environment::GetNow() {
906
22990
  uv_update_time(event_loop());
907
22990
  uint64_t now = uv_now(event_loop());
908
22990
  CHECK_GE(now, timer_base());
909
22990
  now -= timer_base();
910
22990
  if (now <= 0xffffffff)
911
45980
    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
5050
ImmediateInfo::ImmediateInfo(v8::Isolate* isolate, const SerializeInfo* info)
977
5050
    : 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
4606
void ImmediateInfo::Deserialize(Local<Context> context) {
985
4606
  fields_.Deserialize(context);
986
4606
}
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
4606
void TickInfo::Deserialize(Local<Context> context) {
1004
4606
  fields_.Deserialize(context);
1005
4606
}
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
5050
TickInfo::TickInfo(v8::Isolate* isolate, const SerializeInfo* info)
1018
    : fields_(
1019
5050
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1020
1021
5050
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

10100
      info_(info) {
1027
10100
  v8::HandleScope handle_scope(isolate);
1028
5050
  if (info == nullptr) {
1029
444
    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
444
    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
444
    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
444
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1047
  }
1048
5050
}
1049
1050
4606
void AsyncHooks::Deserialize(Local<Context> context) {
1051
4606
  async_ids_stack_.Deserialize(context);
1052
4606
  fields_.Deserialize(context);
1053
4606
  async_id_fields_.Deserialize(context);
1054
4606
  if (info_->js_execution_async_resources != 0) {
1055
    v8::Local<v8::Array> arr = context
1056
9212
                                   ->GetDataFromSnapshotOnce<v8::Array>(
1057
9212
                                       info_->js_execution_async_resources)
1058
4606
                                   .ToLocalChecked();
1059
4606
    js_execution_async_resources_.Reset(context->GetIsolate(), arr);
1060
  }
1061
1062
4606
  native_execution_async_resources_.resize(
1063
9212
      info_->native_execution_async_resources.size());
1064
4606
  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
4606
  info_ = nullptr;
1073
4606
}
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
522
void Environment::Exit(int exit_code) {
1140
522
  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
522
  process_exit_handler_(this, exit_code);
1159
55
}
1160
1161
5070
void Environment::stop_sub_worker_contexts() {
1162
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1163
1164
5096
  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
5045
}
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
52165
void Environment::AddUnmanagedFd(int fd) {
1178
52165
  if (!tracks_unmanaged_fds()) return;
1179
511
  auto result = unmanaged_fds_.insert(fd);
1180
511
  if (!result.second) {
1181
    ProcessEmitWarning(
1182
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1183
  }
1184
}
1185
1186
51793
void Environment::RemoveUnmanagedFd(int fd) {
1187
51793
  if (!tracks_unmanaged_fds()) return;
1188
508
  size_t removed_count = unmanaged_fds_.erase(fd);
1189
508
  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
4455
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
4455
  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








168
  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
4606
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1330
4606
  Local<Context> ctx = context();
1331
1332
4606
  native_modules_in_snapshot = info->native_modules;
1333
4606
  async_hooks_.Deserialize(ctx);
1334
4606
  immediate_info_.Deserialize(ctx);
1335
4606
  tick_info_.Deserialize(ctx);
1336
4606
  performance_state_->Deserialize(ctx);
1337
4606
  stream_base_state_.Deserialize(ctx);
1338
4606
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1339
1340
4606
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1341
    fprintf(stderr, "deserializing...\n");
1342
    std::cerr << *info << "\n";
1343
  }
1344
1345
4606
  const std::vector<PropInfo>& templates = info->persistent_templates;
1346
4606
  size_t i = 0;  // index to the array
1347
4606
  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
































































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






































































































322420
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1377
#undef V
1378
#undef SetProperty
1379
1380
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1381
13818
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1382
  Local<Context> ctx_from_snapshot;
1383
4606
  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
4606
  CHECK_EQ(ctx_from_snapshot, ctx);
1388
4606
}
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
1160881
void Environment::RunWeakRefCleanup() {
1588
1160881
  isolate()->ClearKeptObjects();
1589
1160891
}
1590
22
1591
22
// Not really any better place than env.cc at this moment.
1592
107953
void BaseObject::DeleteMe(void* data) {
1593
107953
  BaseObject* self = static_cast<BaseObject*>(data);
1594

111949
  if (self->has_pointer_data() &&
1595
4018
      self->pointer_data()->strong_ptr_count > 0) {
1596
277
    return self->Detach();
1597
22
  }
1598
107701
  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
42476
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1612
42476
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1613
42476
  if (tmpl.IsEmpty()) {
1614
444
    tmpl = env->NewFunctionTemplate(nullptr);
1615
888
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1616
444
    env->set_base_object_ctor_template(tmpl);
1617
  }
1618
42476
  return tmpl;
1619
}
1620
1621
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1622
  return IsWeakOrDetached();
1623
}
1624
1625

14073
}  // namespace node