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: 527 556 94.8 %
Date: 2020-02-19 22:14:06 Branches: 656 1039 63.1 %

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



115444
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
99


82460
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
100
















































































































3694208
  PER_ISOLATE_STRING_PROPERTIES(VS)
101
#undef V
102
#undef VY
103
#undef VS
104
#undef VP
105
4123
}
106
107
257
void IsolateData::CreateProperties() {
108
  // Create string and private symbol properties as internalized one byte
109
  // strings after the platform is properly initialized.
110
  //
111
  // Internalized because it makes property lookups a little faster and
112
  // because the string is created in the old space straight away.  It's going
113
  // to end up in the old space sooner or later anyway but now it doesn't go
114
  // through v8::Eternal's new space handling first.
115
  //
116
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
117
  // decoding step.
118
119
514
  HandleScope handle_scope(isolate_);
120
121
#define V(PropertyName, StringValue)                                           \
122
  PropertyName##_.Set(                                                         \
123
      isolate_,                                                                \
124
      Private::New(isolate_,                                                   \
125
                   String::NewFromOneByte(                                     \
126
                       isolate_,                                               \
127
                       reinterpret_cast<const uint8_t*>(StringValue),          \
128
                       NewStringType::kInternalized,                           \
129
                       sizeof(StringValue) - 1)                                \
130
                       .ToLocalChecked()));
131
3855
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
132
#undef V
133
#define V(PropertyName, StringValue)                                           \
134
  PropertyName##_.Set(                                                         \
135
      isolate_,                                                                \
136
      Symbol::New(isolate_,                                                    \
137
                  String::NewFromOneByte(                                      \
138
                      isolate_,                                                \
139
                      reinterpret_cast<const uint8_t*>(StringValue),           \
140
                      NewStringType::kInternalized,                            \
141
                      sizeof(StringValue) - 1)                                 \
142
                      .ToLocalChecked()));
143
2827
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
144
#undef V
145
#define V(PropertyName, StringValue)                                           \
146
  PropertyName##_.Set(                                                         \
147
      isolate_,                                                                \
148
      String::NewFromOneByte(isolate_,                                         \
149
                             reinterpret_cast<const uint8_t*>(StringValue),    \
150
                             NewStringType::kInternalized,                     \
151
                             sizeof(StringValue) - 1)                          \
152
          .ToLocalChecked());
153
115386
  PER_ISOLATE_STRING_PROPERTIES(V)
154
#undef V
155
257
}
156
157
4380
IsolateData::IsolateData(Isolate* isolate,
158
                         uv_loop_t* event_loop,
159
                         MultiIsolatePlatform* platform,
160
                         ArrayBufferAllocator* node_allocator,
161
4380
                         const std::vector<size_t>* indexes)
162
    : isolate_(isolate),
163
      event_loop_(event_loop),
164
4380
      allocator_(isolate->GetArrayBufferAllocator()),
165
8733
      node_allocator_(node_allocator == nullptr ? nullptr
166
4353
                                                : node_allocator->GetImpl()),
167
4380
      uses_node_allocator_(allocator_ == node_allocator_),
168
1051200
      platform_(platform) {
169
4380
  CHECK_NOT_NULL(allocator_);
170
171
8760
  options_.reset(
172
13140
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
173
174
4380
  if (indexes == nullptr) {
175
257
    CreateProperties();
176
  } else {
177
4123
    DeserializeProperties(indexes);
178
  }
179
4380
}
180
181
19
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
182
#define V(PropertyName, StringValue)                                           \
183
  tracker->TrackField(#PropertyName, PropertyName(isolate()));
184
19
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
185
#undef V
186
187
#define V(PropertyName, StringValue)                                           \
188
  tracker->TrackField(#PropertyName, PropertyName(isolate()));
189
19
  PER_ISOLATE_STRING_PROPERTIES(V)
190
#undef V
191
192
19
  if (node_allocator_ != nullptr) {
193
    tracker->TrackFieldWithSize(
194
19
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
195
  } else {
196
    tracker->TrackFieldWithSize(
197
        "allocator", sizeof(*allocator_), "v8::ArrayBuffer::Allocator");
198
  }
199
  tracker->TrackFieldWithSize(
200
19
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
201
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
202
19
}
203
204
4125
void InitThreadLocalOnce() {
205
4125
  CHECK_EQ(0, uv_key_create(&Environment::thread_local_env));
206
4125
}
207
208
119
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
209
119
  if (!env_->owns_process_state()) {
210
    // Ideally, we’d have a consistent story that treats all threads/Environment
211
    // instances equally here. However, tracing is essentially global, and this
212
    // callback is called from whichever thread calls `StartTracing()` or
213
    // `StopTracing()`. The only way to do this in a threadsafe fashion
214
    // seems to be only tracking this from the main thread, and only allowing
215
    // these state modifications from the main thread.
216
56
    return;
217
  }
218
219
234
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
220
234
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
221
222
117
  Isolate* isolate = env_->isolate();
223
182
  HandleScope handle_scope(isolate);
224
117
  Local<Function> cb = env_->trace_category_state_function();
225
117
  if (cb.IsEmpty())
226
52
    return;
227
130
  TryCatchScope try_catch(env_);
228
65
  try_catch.SetVerbose(true);
229
130
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
230
260
  cb->Call(env_->context(), Undefined(isolate), arraysize(args), args)
231
      .ToLocalChecked();
232
}
233
234
static std::atomic<uint64_t> next_thread_id{0};
235
236
4380
uint64_t Environment::AllocateThreadId() {
237
4380
  return next_thread_id++;
238
}
239
240
4378
void Environment::CreateProperties() {
241
8756
  HandleScope handle_scope(isolate_);
242
4378
  Local<Context> ctx = context();
243
4378
  Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
244
8756
  templ->InstanceTemplate()->SetInternalFieldCount(1);
245
8756
  Local<Object> obj = templ->GetFunction(ctx)
246
8756
                          .ToLocalChecked()
247
8756
                          ->NewInstance(ctx)
248
4378
                          .ToLocalChecked();
249
4378
  obj->SetAlignedPointerInInternalField(0, this);
250
4378
  set_as_callback_data(obj);
251
4378
  set_as_callback_data_template(templ);
252
253
  // Store primordials setup by the per-context script in the environment.
254
  Local<Object> per_context_bindings =
255
8756
      GetPerContextExports(ctx).ToLocalChecked();
256
  Local<Value> primordials =
257
13134
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
258
4378
  CHECK(primordials->IsObject());
259
4378
  set_primordials(primordials.As<Object>());
260
261
  Local<Object> process_object =
262
8756
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
263
4378
  set_process_object(process_object);
264
4378
}
265
266
4378
std::string GetExecPath(const std::vector<std::string>& argv) {
267
  char exec_path_buf[2 * PATH_MAX];
268
4378
  size_t exec_path_len = sizeof(exec_path_buf);
269
4378
  std::string exec_path;
270
4378
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
271
4378
    exec_path = std::string(exec_path_buf, exec_path_len);
272
  } else {
273
    exec_path = argv[0];
274
  }
275
276
  // On OpenBSD process.execPath will be relative unless we
277
  // get the full path before process.execPath is used.
278
#if defined(__OpenBSD__)
279
  uv_fs_t req;
280
  req.ptr = nullptr;
281
  if (0 ==
282
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
283
    CHECK_NOT_NULL(req.ptr);
284
    exec_path = std::string(static_cast<char*>(req.ptr));
285
  }
286
  uv_fs_req_cleanup(&req);
287
#endif
288
289
4378
  return exec_path;
290
}
291
292
4378
Environment::Environment(IsolateData* isolate_data,
293
                         Local<Context> context,
294
                         const std::vector<std::string>& args,
295
                         const std::vector<std::string>& exec_args,
296
                         Flags flags,
297
4378
                         uint64_t thread_id)
298
4378
    : isolate_(context->GetIsolate()),
299
      isolate_data_(isolate_data),
300
      immediate_info_(context->GetIsolate()),
301
      tick_info_(context->GetIsolate()),
302
4378
      timer_base_(uv_now(isolate_data->event_loop())),
303
      exec_argv_(exec_args),
304
      argv_(args),
305
      exec_path_(GetExecPath(args)),
306
4378
      should_abort_on_uncaught_toggle_(isolate_, 1),
307
4378
      stream_base_state_(isolate_, StreamBase::kNumStreamBaseStateFields),
308
      flags_(flags),
309
4378
      thread_id_(thread_id == kNoThreadId ? AllocateThreadId() : thread_id),
310
4378
      fs_stats_field_array_(isolate_, kFsStatsBufferLength),
311
4378
      fs_stats_field_bigint_array_(isolate_, kFsStatsBufferLength),
312
358996
      context_(context->GetIsolate(), context) {
313
  // We'll be creating new objects so make sure we've entered the context.
314
8756
  HandleScope handle_scope(isolate());
315
  Context::Scope context_scope(context);
316
317
4378
  set_env_vars(per_process::system_environment);
318
319
  // We create new copies of the per-Environment option sets, so that it is
320
  // easier to modify them after Environment creation. The defaults are
321
  // part of the per-Isolate option set, for which in turn the defaults are
322
  // part of the per-process option set.
323
4378
  options_.reset(new EnvironmentOptions(*isolate_data->options()->per_env));
324
8756
  inspector_host_port_.reset(
325
13134
      new ExclusiveAccess<HostPort>(options_->debug_options().host_port));
326
327
#if HAVE_INSPECTOR
328
  // We can only create the inspector agent after having cloned the options.
329
4378
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
330
#endif
331
332
4378
  AssignToContext(context, ContextInfo(""));
333
334
4378
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
335
4378
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
336
4378
    if (TracingController* tracing_controller = writer->GetTracingController())
337
4352
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
338
  }
339
340
4378
  destroy_async_id_list_.reserve(512);
341
8756
  BeforeExit(
342
12167
      [](void* arg) {
343
3895
        Environment* env = static_cast<Environment*>(arg);
344
3895
        if (!env->destroy_async_id_list()->empty())
345
146
          AsyncWrap::DestroyAsyncIdsCallback(env);
346
12166
      },
347
4378
      this);
348
349
  performance_state_ =
350
4378
      std::make_unique<performance::performance_state>(isolate());
351
4378
  performance_state_->Mark(
352
4378
      performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT);
353
4378
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
354
8756
                           per_process::node_start_time);
355
4378
  performance_state_->Mark(
356
      performance::NODE_PERFORMANCE_MILESTONE_V8_START,
357
8756
      performance::performance_v8_start);
358
359
8756
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
360
4378
          TRACING_CATEGORY_NODE1(environment)) != 0) {
361
16
    auto traced_value = tracing::TracedValue::Create();
362
8
    traced_value->BeginArray("args");
363
8
    for (const std::string& arg : args) traced_value->AppendString(arg);
364
8
    traced_value->EndArray();
365
8
    traced_value->BeginArray("exec_args");
366
8
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
367
8
    traced_value->EndArray();
368

16
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
369
                                      "Environment",
370
                                      this,
371
                                      "args",
372
                                      std::move(traced_value));
373
  }
374
375
  // By default, always abort when --abort-on-uncaught-exception was passed.
376
4378
  should_abort_on_uncaught_toggle_[0] = 1;
377
378
8756
  std::string debug_cats;
379
4378
  credentials::SafeGetenv("NODE_DEBUG_NATIVE", &debug_cats, this);
380
4378
  set_debug_categories(debug_cats, true);
381
382
4378
  if (options_->no_force_async_hooks_checks) {
383
1
    async_hooks_.no_force_checks();
384
  }
385
386
  // TODO(joyeecheung): deserialize when the snapshot covers the environment
387
  // properties.
388
4378
  CreateProperties();
389
4378
}
390
391
301944
Environment::~Environment() {
392
3971
  if (interrupt_data_ != nullptr) *interrupt_data_ = nullptr;
393
394
3971
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
395
3973
      BuildEmbedderGraph, this);
396
397
  // Make sure there are no re-used libuv wrapper objects.
398
  // CleanupHandles() should have removed all of them.
399
3973
  CHECK(file_handle_read_wrap_freelist_.empty());
400
401
7946
  HandleScope handle_scope(isolate());
402
403
#if HAVE_INSPECTOR
404
  // Destroy inspector agent before erasing the context. The inspector
405
  // destructor depends on the context still being accessible.
406
3973
  inspector_agent_.reset();
407
#endif
408
409
11918
  context()->SetAlignedPointerInEmbedderData(
410
3973
      ContextEmbedderIndex::kEnvironment, nullptr);
411
412
3973
  if (trace_state_observer_) {
413
3973
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
414
3973
    CHECK_NOT_NULL(writer);
415
3973
    if (TracingController* tracing_controller = writer->GetTracingController())
416
3947
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
417
  }
418
419
3973
  delete[] http_parser_buffer_;
420
421

7946
  TRACE_EVENT_NESTABLE_ASYNC_END0(
422
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
423
424
  // Do not unload addons on the main thread. Some addons need to retain memory
425
  // beyond the Environment's lifetime, and unloading them early would break
426
  // them; with Worker threads, we have the opportunity to be stricter.
427
  // Also, since the main thread usually stops just before the process exits,
428
  // this is far less relevant here.
429
3973
  if (!is_main_thread()) {
430
    // Dereference all addons that were loaded into this environment.
431
239
    for (binding::DLib& addon : loaded_addons_) {
432
11
      addon.Close();
433
    }
434
  }
435
436
3973
  CHECK_EQ(base_object_count(), 0);
437
7944
}
438
439
4378
void Environment::InitializeLibuv(bool start_profiler_idle_notifier) {
440
8756
  HandleScope handle_scope(isolate());
441
4378
  Context::Scope context_scope(context());
442
443
4378
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
444
4378
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
445
446
4378
  uv_check_init(event_loop(), immediate_check_handle());
447
4378
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
448
449
4378
  uv_idle_init(event_loop(), immediate_idle_handle());
450
451
4378
  uv_check_start(immediate_check_handle(), CheckImmediate);
452
453
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
454
  // but not all samples are created equal; mark the wall clock time spent in
455
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
456
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
457
  // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
458
  // probably fortify in the API contract, namely that the last started prepare
459
  // or check watcher runs first.  It's not 100% foolproof; if an add-on starts
460
  // a prepare or check watcher after us, any samples attributed to its callback
461
  // will be recorded with state=IDLE.
462
4378
  uv_prepare_init(event_loop(), &idle_prepare_handle_);
463
4378
  uv_check_init(event_loop(), &idle_check_handle_);
464
8756
  uv_async_init(
465
      event_loop(),
466
      &task_queues_async_,
467
4840
      [](uv_async_t* async) {
468
462
        Environment* env = ContainerOf(
469
231
            &Environment::task_queues_async_, async);
470
231
        env->CleanupFinalizationGroups();
471
231
        env->RunAndClearNativeImmediates();
472
9214
      });
473
4378
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
474
4378
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
475
4378
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
476
477
  // Register clean-up cb to be called to clean up the handles
478
  // when the environment is freed, note that they are not cleaned in
479
  // the one environment per process setup, but will be called in
480
  // FreeEnvironment.
481
4378
  RegisterHandleCleanups();
482
483
4378
  if (start_profiler_idle_notifier) {
484
3
    StartProfilerIdleNotifier();
485
  }
486
487
  static uv_once_t init_once = UV_ONCE_INIT;
488
4378
  uv_once(&init_once, InitThreadLocalOnce);
489
4378
  uv_key_set(&thread_local_env, this);
490
4378
}
491
492
61
void Environment::ExitEnv() {
493
61
  set_can_call_into_js(false);
494
61
  set_stopping(true);
495
61
  isolate_->TerminateExecution();
496
117
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
497
61
}
498
499
4378
void Environment::RegisterHandleCleanups() {
500
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
501
52053
                                        void* arg) {
502
23838
    handle->data = env;
503
504
47675
    env->CloseHandle(handle, [](uv_handle_t* handle) {
505
#ifdef DEBUG
506
      memset(handle, 0xab, uv_handle_size(handle->type));
507
#endif
508
47676
    });
509
56430
  };
510
511
  RegisterHandleCleanup(
512
4378
      reinterpret_cast<uv_handle_t*>(timer_handle()),
513
      close_and_finish,
514
4378
      nullptr);
515
  RegisterHandleCleanup(
516
4378
      reinterpret_cast<uv_handle_t*>(immediate_check_handle()),
517
      close_and_finish,
518
4378
      nullptr);
519
  RegisterHandleCleanup(
520
4378
      reinterpret_cast<uv_handle_t*>(immediate_idle_handle()),
521
      close_and_finish,
522
4378
      nullptr);
523
  RegisterHandleCleanup(
524
4378
      reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_),
525
      close_and_finish,
526
4378
      nullptr);
527
  RegisterHandleCleanup(
528
4378
      reinterpret_cast<uv_handle_t*>(&idle_check_handle_),
529
      close_and_finish,
530
4378
      nullptr);
531
  RegisterHandleCleanup(
532
4378
      reinterpret_cast<uv_handle_t*>(&task_queues_async_),
533
      close_and_finish,
534
4378
      nullptr);
535
4378
}
536
537
8143
void Environment::CleanupHandles() {
538
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
539
16286
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
540
541
8146
  RunAndClearNativeImmediates(true /* skip SetUnrefImmediate()s */);
542
543
8185
  for (ReqWrapBase* request : req_wrap_queue_)
544
38
    request->Cancel();
545
546
10128
  for (HandleWrap* handle : handle_wrap_queue_)
547
3964
    handle->Close();
548
549
31983
  for (HandleCleanup& hc : handle_cleanup_queue_)
550
23837
    hc.cb_(this, hc.handle_, hc.arg_);
551
8145
  handle_cleanup_queue_.clear();
552
553

47523
  while (handle_cleanup_waiting_ != 0 ||
554

23987
         request_waiting_ != 0 ||
555
8146
         !handle_wrap_queue_.IsEmpty()) {
556
7697
    uv_run(event_loop(), UV_RUN_ONCE);
557
  }
558
559
8144
  file_handle_read_wrap_freelist_.clear();
560
8147
}
561
562
3
void Environment::StartProfilerIdleNotifier() {
563
3
  if (profiler_idle_notifier_started_)
564
    return;
565
566
3
  profiler_idle_notifier_started_ = true;
567
568
4121
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
569
2056
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
570
2056
    env->isolate()->SetIdle(true);
571
4118
  });
572
573
4119
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
574
2055
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
575
2055
    env->isolate()->SetIdle(false);
576
4116
  });
577
}
578
579
void Environment::StopProfilerIdleNotifier() {
580
  profiler_idle_notifier_started_ = false;
581
  uv_prepare_stop(&idle_prepare_handle_);
582
  uv_check_stop(&idle_check_handle_);
583
}
584
585
311207
void Environment::PrintSyncTrace() const {
586
311207
  if (!trace_sync_io_) return;
587
588
2
  HandleScope handle_scope(isolate());
589
590
1
  fprintf(
591
1
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
592
1
  PrintStackTrace(isolate(),
593
                  StackTrace::CurrentStackTrace(
594
1
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
595
}
596
597
4198
void Environment::RunCleanup() {
598
4198
  started_cleanup_ = true;
599
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
600
8397
                              "RunCleanup", this);
601
4200
  CleanupHandles();
602
603
12092
  while (!cleanup_hooks_.empty()) {
604
    // Copy into a vector, since we can't sort an unordered_set in-place.
605
    std::vector<CleanupHookCallback> callbacks(
606
7892
        cleanup_hooks_.begin(), cleanup_hooks_.end());
607
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
608
    // need to be able to check whether they were un-scheduled by another hook.
609
610
7892
    std::sort(callbacks.begin(), callbacks.end(),
611
735311
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
612
      // Sort in descending order so that the most recently inserted callbacks
613
      // are run first.
614
735311
      return a.insertion_order_counter_ > b.insertion_order_counter_;
615
739257
    });
616
617
91190
    for (const CleanupHookCallback& cb : callbacks) {
618
87244
      if (cleanup_hooks_.count(cb) == 0) {
619
        // This hook was removed from the `cleanup_hooks_` set during another
620
        // hook that was run earlier. Nothing to do here.
621
        continue;
622
      }
623
624
87244
      cb.fn_(cb.arg_);
625
87243
      cleanup_hooks_.erase(cb);
626
    }
627
3946
    CleanupHandles();
628
  }
629
4199
}
630
631
3908
void Environment::RunBeforeExitCallbacks() {
632
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
633
7816
                              "BeforeExit", this);
634
7802
  for (ExitCallback before_exit : before_exit_functions_) {
635
3894
    before_exit.cb_(before_exit.arg_);
636
  }
637
3908
  before_exit_functions_.clear();
638
3909
}
639
640
4378
void Environment::BeforeExit(void (*cb)(void* arg), void* arg) {
641
4378
  before_exit_functions_.push_back(ExitCallback{cb, arg});
642
4378
}
643
644
4396
void Environment::RunAtExitCallbacks() {
645
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
646
8793
                              "AtExit", this);
647
13083
  for (ExitCallback at_exit : at_exit_functions_) {
648
8687
    at_exit.cb_(at_exit.arg_);
649
  }
650
4397
  at_exit_functions_.clear();
651
4397
}
652
653
8707
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
654
8707
  at_exit_functions_.push_front(ExitCallback{cb, arg});
655
8707
}
656
657
407333
void Environment::RunAndClearInterrupts() {
658
407335
  while (native_immediates_interrupts_.size() > 0) {
659
4
    NativeImmediateQueue queue;
660
    {
661
4
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
662
2
      queue.ConcatMove(std::move(native_immediates_interrupts_));
663
    }
664
2
    DebugSealHandleScope seal_handle_scope(isolate());
665
666
6
    while (std::unique_ptr<NativeImmediateCallback> head = queue.Shift())
667
4
      head->Call(this);
668
  }
669
407335
}
670
671
407327
void Environment::RunAndClearNativeImmediates(bool only_refed) {
672
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
673
814651
                              "RunAndClearNativeImmediates", this);
674
407332
  size_t ref_count = 0;
675
676
  // Handle interrupts first. These functions are not allowed to throw
677
  // exceptions, so we do not need to handle that.
678
407332
  RunAndClearInterrupts();
679
680
  // It is safe to check .size() first, because there is a causal relationship
681
  // between pushes to the threadsafe and this function being called.
682
  // For the common case, it's worth checking the size first before establishing
683
  // a mutex lock.
684
407332
  if (native_immediates_threadsafe_.size() > 0) {
685
538
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
686
269
    native_immediates_.ConcatMove(std::move(native_immediates_threadsafe_));
687
  }
688
689
407330
  auto drain_list = [&]() {
690
1332157
    TryCatchScope try_catch(this);
691
407333
    DebugSealHandleScope seal_handle_scope(isolate());
692
    while (std::unique_ptr<NativeImmediateCallback> head =
693
517647
               native_immediates_.Shift()) {
694
55162
      if (head->is_refed())
695
32549
        ref_count++;
696
697

55162
      if (head->is_refed() || !only_refed)
698
109998
        head->Call(this);
699
700
55158
      head.reset();  // Destroy now so that this is also observed by try_catch.
701
702
55158
      if (UNLIKELY(try_catch.HasCaught())) {
703

5
        if (!try_catch.HasTerminated() && can_call_into_js())
704
2
          errors::TriggerUncaughtException(isolate(), try_catch);
705
706
3
        return true;
707
      }
708
55155
    }
709
407329
    return false;
710
407330
  };
711
407333
  while (drain_list()) {}
712
713
407324
  immediate_info()->ref_count_dec(ref_count);
714
715
407328
  if (immediate_info()->ref_count() == 0)
716
377467
    ToggleImmediateRef(false);
717
407328
}
718
719
2
void Environment::RequestInterruptFromV8() {
720
2
  if (interrupt_data_ != nullptr) return;  // Already scheduled.
721
722
  // The Isolate may outlive the Environment, so some logic to handle the
723
  // situation in which the Environment is destroyed before the handler runs
724
  // is required.
725
2
  interrupt_data_ = new Environment*(this);
726
727
10
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
728
4
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
729
2
    Environment* env = *env_ptr;
730
2
    if (env == nullptr) {
731
      // The Environment has already been destroyed. That should be okay; any
732
      // callback added before the Environment shuts down would have been
733
      // handled during cleanup.
734
      return;
735
    }
736
2
    env->interrupt_data_ = nullptr;
737
2
    env->RunAndClearInterrupts();
738
8
  }, interrupt_data_);
739
}
740
741
5753
void Environment::ScheduleTimer(int64_t duration_ms) {
742
5753
  if (started_cleanup_) return;
743
5753
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
744
}
745
746
1048
void Environment::ToggleTimerRef(bool ref) {
747
1048
  if (started_cleanup_) return;
748
749
1048
  if (ref) {
750
731
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
751
  } else {
752
317
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
753
  }
754
}
755
756
4687
void Environment::RunTimers(uv_timer_t* handle) {
757
4687
  Environment* env = Environment::from_timer_handle(handle);
758
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
759
9366
                              "RunTimers", env);
760
761
4689
  if (!env->can_call_into_js())
762
    return;
763
764
9366
  HandleScope handle_scope(env->isolate());
765
9367
  Context::Scope context_scope(env->context());
766
767
4689
  Local<Object> process = env->process_object();
768
9366
  InternalCallbackScope scope(env, process, {0, 0});
769
770
4689
  Local<Function> cb = env->timers_callback_function();
771
  MaybeLocal<Value> ret;
772
4688
  Local<Value> arg = env->GetNow();
773
  // This code will loop until all currently due timers will process. It is
774
  // impossible for us to end up in an infinite loop due to how the JS-side
775
  // is structured.
776
4711
  do {
777
9430
    TryCatchScope try_catch(env);
778
4718
    try_catch.SetVerbose(true);
779
9438
    ret = cb->Call(env->context(), process, 1, &arg);
780

4711
  } while (ret.IsEmpty() && env->can_call_into_js());
781
782
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
783
  // is reset back to `true` after being previously set to `false` then this
784
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
785
  // timers corruption will occur and all timers behaviour will become
786
  // entirely unpredictable.
787
4681
  if (ret.IsEmpty())
788
3
    return;
789
790
  // To allow for less JS-C++ boundary crossing, the value returned from JS
791
  // serves a few purposes:
792
  // 1. If it's 0, no more timers exist and the handle should be unrefed
793
  // 2. If it's > 0, the value represents the next timer's expiry and there
794
  //    is at least one timer remaining that is refed.
795
  // 3. If it's < 0, the absolute value represents the next timer's expiry
796
  //    and there are no timers that are refed.
797
  int64_t expiry_ms =
798
18712
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
799
800
4678
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
801
802
4678
  if (expiry_ms != 0) {
803
    int64_t duration_ms =
804
4363
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
805
806
4363
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
807
808
4363
    if (expiry_ms > 0)
809
4038
      uv_ref(h);
810
    else
811
325
      uv_unref(h);
812
  } else {
813
315
    uv_unref(h);
814
  }
815
}
816
817
818
398954
void Environment::CheckImmediate(uv_check_t* handle) {
819
398954
  Environment* env = Environment::from_immediate_check_handle(handle);
820
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
821
428793
                              "CheckImmediate", env);
822
823
428792
  HandleScope scope(env->isolate());
824
428792
  Context::Scope context_scope(env->context());
825
826
398956
  env->RunAndClearNativeImmediates();
827
828

398954
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
829
369102
    return;
830
831
30358
  do {
832
60727
    MakeCallback(env->isolate(),
833
                 env->process_object(),
834
                 env->immediate_callback_function(),
835
                 0,
836
                 nullptr,
837
30372
                 {0, 0}).ToLocalChecked();
838

30358
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
839
840
29838
  if (env->immediate_info()->ref_count() == 0)
841
4289
    env->ToggleImmediateRef(false);
842
}
843
844
433699
void Environment::ToggleImmediateRef(bool ref) {
845
433699
  if (started_cleanup_) return;
846
847
425563
  if (ref) {
848
    // Idle handle is needed only to stop the event loop from blocking in poll.
849
156812
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
850
  } else {
851
373630
    uv_idle_stop(immediate_idle_handle());
852
  }
853
}
854
855
856
21152
Local<Value> Environment::GetNow() {
857
21152
  uv_update_time(event_loop());
858
21153
  uint64_t now = uv_now(event_loop());
859
21153
  CHECK_GE(now, timer_base());
860
21153
  now -= timer_base();
861
21153
  if (now <= 0xffffffff)
862
42305
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
863
  else
864
    return Number::New(isolate(), static_cast<double>(now));
865
}
866
867
4378
void Environment::set_debug_categories(const std::string& cats, bool enabled) {
868
8756
  std::string debug_categories = cats;
869
4378
  while (!debug_categories.empty()) {
870
42
    std::string::size_type comma_pos = debug_categories.find(',');
871
42
    std::string wanted = ToLower(debug_categories.substr(0, comma_pos));
872
873
#define V(name)                                                          \
874
    {                                                                    \
875
      static const std::string available_category = ToLower(#name);      \
876
      if (available_category.find(wanted) != std::string::npos)          \
877
        set_debug_enabled(DebugCategory::name, enabled);                 \
878
    }
879
880











































































42
    DEBUG_CATEGORY_NAMES(V)
881
#undef V
882
883
42
    if (comma_pos == std::string::npos)
884
42
      break;
885
    // Use everything after the `,` as the list for the next iteration.
886
    debug_categories = debug_categories.substr(comma_pos + 1);
887
  }
888
4378
}
889
890
28
void CollectExceptionInfo(Environment* env,
891
                          Local<Object> obj,
892
                          int errorno,
893
                          const char* err_string,
894
                          const char* syscall,
895
                          const char* message,
896
                          const char* path,
897
                          const char* dest) {
898
56
  obj->Set(env->context(),
899
           env->errno_string(),
900
140
           Integer::New(env->isolate(), errorno)).Check();
901
902
56
  obj->Set(env->context(), env->code_string(),
903
140
           OneByteString(env->isolate(), err_string)).Check();
904
905
28
  if (message != nullptr) {
906
56
    obj->Set(env->context(), env->message_string(),
907
140
             OneByteString(env->isolate(), message)).Check();
908
  }
909
910
  Local<Value> path_buffer;
911
28
  if (path != nullptr) {
912
    path_buffer =
913
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
914
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
915
  }
916
917
  Local<Value> dest_buffer;
918
28
  if (dest != nullptr) {
919
    dest_buffer =
920
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
921
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
922
  }
923
924
28
  if (syscall != nullptr) {
925
56
    obj->Set(env->context(), env->syscall_string(),
926
140
             OneByteString(env->isolate(), syscall)).Check();
927
  }
928
28
}
929
930
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
931
                                         int errorno,
932
                                         const char* syscall,
933
                                         const char* message,
934
                                         const char* path,
935
                                         const char* dest) {
936

28
  if (!object->IsObject() || errorno == 0)
937
    return;
938
939
28
  Local<Object> obj = object.As<Object>();
940
28
  const char* err_string = uv_err_name(errorno);
941
942

28
  if (message == nullptr || message[0] == '\0') {
943
28
    message = uv_strerror(errorno);
944
  }
945
946
  node::CollectExceptionInfo(this, obj, errorno, err_string,
947
28
                             syscall, message, path, dest);
948
}
949
950
19
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
951
19
  tracker->TrackField("fields", fields_);
952
19
}
953
954
19
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
955
19
  tracker->TrackField("fields", fields_);
956
19
}
957
958
19
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
959
19
  tracker->TrackField("providers", providers_);
960
19
  tracker->TrackField("async_ids_stack", async_ids_stack_);
961
19
  tracker->TrackField("fields", fields_);
962
19
  tracker->TrackField("async_id_fields", async_id_fields_);
963
19
}
964
965
8
void AsyncHooks::grow_async_ids_stack() {
966
8
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
967
968
24
  env()->async_hooks_binding()->Set(
969
      env()->context(),
970
      env()->async_ids_stack_string(),
971
40
      async_ids_stack_.GetJSArray()).Check();
972
8
}
973
974
uv_key_t Environment::thread_local_env = {};
975
976
430
void Environment::Exit(int exit_code) {
977
430
  if (options()->trace_exit) {
978
2
    HandleScope handle_scope(isolate());
979
980
1
    if (is_main_thread()) {
981
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
982
    } else {
983
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
984
              uv_os_getpid(), thread_id());
985
    }
986
987
    fprintf(
988
1
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
989
1
    PrintStackTrace(isolate(),
990
                    StackTrace::CurrentStackTrace(
991
1
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
992
  }
993
430
  if (is_main_thread()) {
994
400
    stop_sub_worker_contexts();
995
400
    DisposePlatform();
996
400
    exit(exit_code);
997
  } else {
998
30
    worker_context_->Exit(exit_code);
999
  }
1000
30
}
1001
1002
4358
void Environment::stop_sub_worker_contexts() {
1003
4370
  while (!sub_worker_contexts_.empty()) {
1004
12
    Worker* w = *sub_worker_contexts_.begin();
1005
12
    remove_sub_worker_context(w);
1006
12
    w->Exit(1);
1007
12
    w->JoinThread();
1008
  }
1009
4347
}
1010
1011
2
Environment* Environment::worker_parent_env() const {
1012
2
  if (worker_context_ == nullptr) return nullptr;
1013
  return worker_context_->env();
1014
}
1015
1016
314
void MemoryTracker::TrackField(const char* edge_name,
1017
                               const CleanupHookCallback& value,
1018
                               const char* node_name) {
1019
628
  v8::HandleScope handle_scope(isolate_);
1020
  // Here, we utilize the fact that CleanupHookCallback instances
1021
  // are all unique and won't be tracked twice in one BuildEmbedderGraph
1022
  // callback.
1023
  MemoryRetainerNode* n =
1024
314
      PushNode("CleanupHookCallback", sizeof(value), edge_name);
1025
  // TODO(joyeecheung): at the moment only arguments of type BaseObject will be
1026
  // identified and tracked here (based on their deleters),
1027
  // but we may convert and track other known types here.
1028
314
  BaseObject* obj = value.GetBaseObject();
1029

314
  if (obj != nullptr && obj->IsDoneInitializing()) {
1030
291
    TrackField("arg", obj);
1031
  }
1032
314
  CHECK_EQ(CurrentNode(), n);
1033
314
  CHECK_NE(n->size_, 0);
1034
314
  PopNode();
1035
314
}
1036
1037
19
void Environment::BuildEmbedderGraph(Isolate* isolate,
1038
                                     EmbedderGraph* graph,
1039
                                     void* data) {
1040
38
  MemoryTracker tracker(isolate, graph);
1041
19
  Environment* env = static_cast<Environment*>(data);
1042
19
  tracker.Track(env);
1043
19
}
1044
1045
19
inline size_t Environment::SelfSize() const {
1046
19
  size_t size = sizeof(*this);
1047
  // Remove non pointer fields that will be tracked in MemoryInfo()
1048
  // TODO(joyeecheung): refactor the MemoryTracker interface so
1049
  // this can be done for common types within the Track* calls automatically
1050
  // if a certain scope is entered.
1051
19
  size -= sizeof(async_hooks_);
1052
19
  size -= sizeof(tick_info_);
1053
19
  size -= sizeof(immediate_info_);
1054
19
  return size;
1055
}
1056
1057
19
void Environment::MemoryInfo(MemoryTracker* tracker) const {
1058
  // Iteratable STLs have their own sizes subtracted from the parent
1059
  // by default.
1060
19
  tracker->TrackField("isolate_data", isolate_data_);
1061
19
  tracker->TrackField("native_modules_with_cache", native_modules_with_cache);
1062
19
  tracker->TrackField("native_modules_without_cache",
1063
19
                      native_modules_without_cache);
1064
19
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
1065
19
  tracker->TrackField("exec_argv", exec_argv_);
1066
19
  tracker->TrackField("should_abort_on_uncaught_toggle",
1067
19
                      should_abort_on_uncaught_toggle_);
1068
19
  tracker->TrackField("stream_base_state", stream_base_state_);
1069
19
  tracker->TrackField("fs_stats_field_array", fs_stats_field_array_);
1070
19
  tracker->TrackField("fs_stats_field_bigint_array",
1071
19
                      fs_stats_field_bigint_array_);
1072
19
  tracker->TrackField("cleanup_hooks", cleanup_hooks_);
1073
19
  tracker->TrackField("async_hooks", async_hooks_);
1074
19
  tracker->TrackField("immediate_info", immediate_info_);
1075
19
  tracker->TrackField("tick_info", tick_info_);
1076
1077
#define V(PropertyName, TypeName)                                              \
1078
  tracker->TrackField(#PropertyName, PropertyName());
1079
19
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1080
#undef V
1081
1082
  // FIXME(joyeecheung): track other fields in Environment.
1083
  // Currently MemoryTracker is unable to track these
1084
  // correctly:
1085
  // - Internal types that do not implement MemoryRetainer yet
1086
  // - STL containers with MemoryRetainer* inside
1087
  // - STL containers with numeric types inside that should not have their
1088
  //   nodes elided e.g. numeric keys in maps.
1089
  // We also need to make sure that when we add a non-pointer field as its own
1090
  // node, we shift its sizeof() size out of the Environment node.
1091
19
}
1092
1093
306283
char* Environment::Reallocate(char* data, size_t old_size, size_t size) {
1094
306283
  if (old_size == size) return data;
1095
  // If we know that the allocator is our ArrayBufferAllocator, we can let
1096
  // if reallocate directly.
1097
293145
  if (isolate_data()->uses_node_allocator()) {
1098
    return static_cast<char*>(
1099
293145
        isolate_data()->node_allocator()->Reallocate(data, old_size, size));
1100
  }
1101
  // Generic allocators do not provide a reallocation method; we need to
1102
  // allocate a new chunk of memory and copy the data over.
1103
  char* new_data = AllocateUnchecked(size);
1104
  if (new_data == nullptr) return nullptr;
1105
  memcpy(new_data, data, std::min(size, old_size));
1106
  if (size > old_size)
1107
    memset(new_data + old_size, 0, size - old_size);
1108
  Free(data, old_size);
1109
  return new_data;
1110
}
1111
1112
585678
void Environment::RunWeakRefCleanup() {
1113
585678
  isolate()->ClearKeptObjects();
1114
585677
}
1115
1116
231
void Environment::CleanupFinalizationGroups() {
1117
461
  HandleScope handle_scope(isolate());
1118
461
  Context::Scope context_scope(context());
1119
461
  TryCatchScope try_catch(this);
1120
1121


233
  while (!cleanup_finalization_groups_.empty() && can_call_into_js()) {
1122
    Local<FinalizationGroup> fg =
1123
4
        cleanup_finalization_groups_.front().Get(isolate());
1124
2
    cleanup_finalization_groups_.pop_front();
1125
4
    if (!FinalizationGroup::Cleanup(fg).FromMaybe(false)) {
1126

1
      if (try_catch.HasCaught() && !try_catch.HasTerminated())
1127
1
        errors::TriggerUncaughtException(isolate(), try_catch);
1128
      // Re-schedule the execution of the remainder of the queue.
1129
1
      uv_async_send(&task_queues_async_);
1130
1
      return;
1131
    }
1132
  }
1133
}
1134
1135
// Not really any better place than env.cc at this moment.
1136
82973
void BaseObject::DeleteMe(void* data) {
1137
82973
  BaseObject* self = static_cast<BaseObject*>(data);
1138

85244
  if (self->has_pointer_data() &&
1139
2271
      self->pointer_data()->strong_ptr_count > 0) {
1140
109
    return self->Detach();
1141
  }
1142
82866
  delete self;
1143
}
1144
1145
225
bool BaseObject::IsDoneInitializing() const { return true; }
1146
1147
291
Local<Object> BaseObject::WrappedObject() const {
1148
291
  return object();
1149
}
1150
1151

12558
}  // namespace node