GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 966 1051 91.9 %
Date: 2022-08-06 04:16:36 Branches: 1143 2108 54.2 %

Line Branch Exec Source
1
#include "env.h"
2
#include "async_wrap.h"
3
#include "base_object-inl.h"
4
#include "debug_utils-inl.h"
5
#include "diagnosticfilename-inl.h"
6
#include "memory_tracker-inl.h"
7
#include "node_buffer.h"
8
#include "node_context_data.h"
9
#include "node_errors.h"
10
#include "node_internals.h"
11
#include "node_options-inl.h"
12
#include "node_process-inl.h"
13
#include "node_v8_platform-inl.h"
14
#include "node_worker.h"
15
#include "req_wrap-inl.h"
16
#include "stream_base.h"
17
#include "tracing/agent.h"
18
#include "tracing/traced_value.h"
19
#include "util-inl.h"
20
#include "v8-profiler.h"
21
22
#include <algorithm>
23
#include <atomic>
24
#include <cinttypes>
25
#include <cstdio>
26
#include <iostream>
27
#include <limits>
28
#include <memory>
29
30
namespace node {
31
32
using errors::TryCatchScope;
33
using v8::Array;
34
using v8::Boolean;
35
using v8::Context;
36
using v8::EmbedderGraph;
37
using v8::EscapableHandleScope;
38
using v8::Function;
39
using v8::FunctionCallbackInfo;
40
using v8::FunctionTemplate;
41
using v8::HandleScope;
42
using v8::HeapSpaceStatistics;
43
using v8::Integer;
44
using v8::Isolate;
45
using v8::Local;
46
using v8::MaybeLocal;
47
using v8::NewStringType;
48
using v8::Number;
49
using v8::Object;
50
using v8::Private;
51
using v8::Script;
52
using v8::SnapshotCreator;
53
using v8::StackTrace;
54
using v8::String;
55
using v8::Symbol;
56
using v8::TracingController;
57
using v8::TryCatch;
58
using v8::Undefined;
59
using v8::Value;
60
using v8::WeakCallbackInfo;
61
using v8::WeakCallbackType;
62
using worker::Worker;
63
64
int const Environment::kNodeContextTag = 0x6e6f64;
65
void* const Environment::kNodeContextTagPtr = const_cast<void*>(
66
    static_cast<const void*>(&Environment::kNodeContextTag));
67
68
15600
void AsyncHooks::SetJSPromiseHooks(Local<Function> init,
69
                                   Local<Function> before,
70
                                   Local<Function> after,
71
                                   Local<Function> resolve) {
72
15600
  js_promise_hooks_[0].Reset(env()->isolate(), init);
73
15600
  js_promise_hooks_[1].Reset(env()->isolate(), before);
74
15600
  js_promise_hooks_[2].Reset(env()->isolate(), after);
75
15600
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
76
31545
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
77
15945
    if (it->IsEmpty()) {
78
      contexts_.erase(it--);
79
      continue;
80
    }
81
31890
    PersistentToLocal::Weak(env()->isolate(), *it)
82
15945
        ->SetPromiseHooks(init, before, after, resolve);
83
  }
84
15600
}
85
86
// Remember to keep this code aligned with pushAsyncContext() in JS.
87
773412
void AsyncHooks::push_async_context(double async_id,
88
                                    double trigger_async_id,
89
                                    Local<Object> resource) {
90
  // Since async_hooks is experimental, do only perform the check
91
  // when async_hooks is enabled.
92
773412
  if (fields_[kCheck] > 0) {
93
773408
    CHECK_GE(async_id, -1);
94
773408
    CHECK_GE(trigger_async_id, -1);
95
  }
96
97
773412
  uint32_t offset = fields_[kStackLength];
98
773412
  if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack();
99
773412
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
100
773412
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
101
773412
  fields_[kStackLength] += 1;
102
773412
  async_id_fields_[kExecutionAsyncId] = async_id;
103
773412
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
104
105
#ifdef DEBUG
106
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
107
    CHECK(native_execution_async_resources_[i].IsEmpty());
108
#endif
109
110
  // When this call comes from JS (as a way of increasing the stack size),
111
  // `resource` will be empty, because JS caches these values anyway.
112
773412
  if (!resource.IsEmpty()) {
113
773408
    native_execution_async_resources_.resize(offset + 1);
114
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
115
773408
    native_execution_async_resources_[offset] = resource;
116
  }
117
773412
}
118
119
// Remember to keep this code aligned with popAsyncContext() in JS.
120
773019
bool AsyncHooks::pop_async_context(double async_id) {
121
  // In case of an exception then this may have already been reset, if the
122
  // stack was multiple MakeCallback()'s deep.
123
773019
  if (UNLIKELY(fields_[kStackLength] == 0)) return false;
124
125
  // Ask for the async_id to be restored as a check that the stack
126
  // hasn't been corrupted.
127
1543918
  if (UNLIKELY(fields_[kCheck] > 0 &&
128

1543918
               async_id_fields_[kExecutionAsyncId] != async_id)) {
129
4
    FailWithCorruptedAsyncStack(async_id);
130
  }
131
132
771957
  uint32_t offset = fields_[kStackLength] - 1;
133
771957
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
134
771957
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
135
771957
  fields_[kStackLength] = offset;
136
137
1543914
  if (LIKELY(offset < native_execution_async_resources_.size() &&
138

1543914
             !native_execution_async_resources_[offset].IsEmpty())) {
139
#ifdef DEBUG
140
    for (uint32_t i = offset + 1; i < native_execution_async_resources_.size();
141
         i++) {
142
      CHECK(native_execution_async_resources_[i].IsEmpty());
143
    }
144
#endif
145
771957
    native_execution_async_resources_.resize(offset);
146
771957
    if (native_execution_async_resources_.size() <
147

992246
            native_execution_async_resources_.capacity() / 2 &&
148
220289
        native_execution_async_resources_.size() > 16) {
149
      native_execution_async_resources_.shrink_to_fit();
150
    }
151
  }
152
153
1543914
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
154
28986
    HandleScope handle_scope(env()->isolate());
155
57972
    USE(js_execution_async_resources()->Set(
156
        env()->context(),
157
        env()->length_string(),
158
115944
        Integer::NewFromUnsigned(env()->isolate(), offset)));
159
  }
160
161
771957
  return fields_[kStackLength] > 0;
162
}
163
164
2297
void AsyncHooks::clear_async_id_stack() {
165
2297
  Isolate* isolate = env()->isolate();
166
2297
  HandleScope handle_scope(isolate);
167
2297
  if (!js_execution_async_resources_.IsEmpty()) {
168
3032
    USE(PersistentToLocal::Strong(js_execution_async_resources_)
169
3032
            ->Set(env()->context(),
170
                  env()->length_string(),
171
6064
                  Integer::NewFromUnsigned(isolate, 0)));
172
  }
173
2297
  native_execution_async_resources_.clear();
174
2297
  native_execution_async_resources_.shrink_to_fit();
175
176
2297
  async_id_fields_[kExecutionAsyncId] = 0;
177
2297
  async_id_fields_[kTriggerAsyncId] = 0;
178
2297
  fields_[kStackLength] = 0;
179
2297
}
180
181
6704
void AsyncHooks::AddContext(Local<Context> ctx) {
182
20112
  ctx->SetPromiseHooks(js_promise_hooks_[0].IsEmpty()
183
6704
                           ? Local<Function>()
184
205
                           : PersistentToLocal::Strong(js_promise_hooks_[0]),
185
6704
                       js_promise_hooks_[1].IsEmpty()
186
6704
                           ? Local<Function>()
187
205
                           : PersistentToLocal::Strong(js_promise_hooks_[1]),
188
6704
                       js_promise_hooks_[2].IsEmpty()
189
6704
                           ? Local<Function>()
190
205
                           : PersistentToLocal::Strong(js_promise_hooks_[2]),
191
6704
                       js_promise_hooks_[3].IsEmpty()
192
6704
                           ? Local<Function>()
193
                           : PersistentToLocal::Strong(js_promise_hooks_[3]));
194
195
6704
  size_t id = contexts_.size();
196
6704
  contexts_.resize(id + 1);
197
6704
  contexts_[id].Reset(env()->isolate(), ctx);
198
6704
  contexts_[id].SetWeak();
199
6704
}
200
201
498
void AsyncHooks::RemoveContext(Local<Context> ctx) {
202
498
  Isolate* isolate = env()->isolate();
203
996
  HandleScope handle_scope(isolate);
204
498
  contexts_.erase(std::remove_if(contexts_.begin(),
205
                                 contexts_.end(),
206
3610
                                 [&](auto&& el) { return el.IsEmpty(); }),
207
996
                  contexts_.end());
208
3547
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
209
3049
    Local<Context> saved_context = PersistentToLocal::Weak(isolate, *it);
210
3049
    if (saved_context == ctx) {
211
      it->Reset();
212
      contexts_.erase(it);
213
      break;
214
    }
215
  }
216
498
}
217
218
238728
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
219
238728
    Environment* env, double default_trigger_async_id)
220
238728
    : async_hooks_(env->async_hooks()) {
221
238728
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
222
238728
    CHECK_GE(default_trigger_async_id, 0);
223
  }
224
225
238728
  old_default_trigger_async_id_ =
226
238728
      async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
227
238728
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
228
238728
      default_trigger_async_id;
229
238728
}
230
231
477454
AsyncHooks::DefaultTriggerAsyncIdScope::~DefaultTriggerAsyncIdScope() {
232
238727
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
238727
      old_default_trigger_async_id_;
234
238727
}
235
236
238728
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
237
238728
    AsyncWrap* async_wrap)
238
    : DefaultTriggerAsyncIdScope(async_wrap->env(),
239
238728
                                 async_wrap->get_async_id()) {}
240
241
12
std::ostream& operator<<(std::ostream& output,
242
                         const std::vector<SnapshotIndex>& v) {
243
12
  output << "{ ";
244
2136
  for (const SnapshotIndex i : v) {
245
2124
    output << i << ", ";
246
  }
247
12
  output << " }";
248
12
  return output;
249
}
250
251
6
std::ostream& operator<<(std::ostream& output,
252
                         const IsolateDataSerializeInfo& i) {
253
  output << "{\n"
254
6
         << "// -- primitive begins --\n"
255
6
         << i.primitive_values << ",\n"
256
         << "// -- primitive ends --\n"
257
6
         << "// -- template_values begins --\n"
258
6
         << i.template_values << ",\n"
259
         << "// -- template_values ends --\n"
260
6
         << "}";
261
6
  return output;
262
}
263
264
6
IsolateDataSerializeInfo IsolateData::Serialize(SnapshotCreator* creator) {
265
6
  Isolate* isolate = creator->GetIsolate();
266
6
  IsolateDataSerializeInfo info;
267
12
  HandleScope handle_scope(isolate);
268
  // XXX(joyeecheung): technically speaking, the indexes here should be
269
  // consecutive and we could just return a range instead of an array,
270
  // but that's not part of the V8 API contract so we use an array
271
  // just to be safe.
272
273
#define VP(PropertyName, StringValue) V(Private, PropertyName)
274
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
275
#define VS(PropertyName, StringValue) V(String, PropertyName)
276
#define V(TypeName, PropertyName)                                              \
277
  info.primitive_values.push_back(                                             \
278
      creator->AddData(PropertyName##_.Get(isolate)));
279
60
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
280
78
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
281
1656
  PER_ISOLATE_STRING_PROPERTIES(VS)
282
#undef V
283
#undef VY
284
#undef VS
285
#undef VP
286
287
354
  for (size_t i = 0; i < AsyncWrap::PROVIDERS_LENGTH; i++)
288
696
    info.primitive_values.push_back(creator->AddData(async_wrap_provider(i)));
289
290
6
  uint32_t id = 0;
291
#define V(PropertyName, TypeName)                                              \
292
  do {                                                                         \
293
    Local<TypeName> field = PropertyName();                                    \
294
    if (!field.IsEmpty()) {                                                    \
295
      size_t index = creator->AddData(field);                                  \
296
      info.template_values.push_back({#PropertyName, id, index});              \
297
    }                                                                          \
298
    id++;                                                                      \
299
  } while (0);
300


















336
  PER_ISOLATE_TEMPLATE_PROPERTIES(V)
301
#undef V
302
303
6
  return info;
304
}
305
306
5313
void IsolateData::DeserializeProperties(const IsolateDataSerializeInfo* info) {
307
5313
  size_t i = 0;
308
5313
  HandleScope handle_scope(isolate_);
309
310
#define VP(PropertyName, StringValue) V(Private, PropertyName)
311
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
312
#define VS(PropertyName, StringValue) V(String, PropertyName)
313
#define V(TypeName, PropertyName)                                              \
314
  do {                                                                         \
315
    MaybeLocal<TypeName> maybe_field =                                         \
316
        isolate_->GetDataFromSnapshotOnce<TypeName>(                           \
317
            info->primitive_values[i++]);                                      \
318
    Local<TypeName> field;                                                     \
319
    if (!maybe_field.ToLocal(&field)) {                                        \
320
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
321
    }                                                                          \
322
    PropertyName##_.Set(isolate_, field);                                      \
323
  } while (0);
324




100947
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
325






132825
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
326









































































































































2927463
  PER_ISOLATE_STRING_PROPERTIES(VS)
327
#undef V
328
#undef VY
329
#undef VS
330
#undef VP
331
332
313467
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
333
    MaybeLocal<String> maybe_field =
334
616308
        isolate_->GetDataFromSnapshotOnce<String>(info->primitive_values[i++]);
335
    Local<String> field;
336
308154
    if (!maybe_field.ToLocal(&field)) {
337
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
338
    }
339
308154
    async_wrap_providers_[j].Set(isolate_, field);
340
  }
341
342
5313
  const std::vector<PropInfo>& values = info->template_values;
343
5313
  i = 0;  // index to the array
344
5313
  uint32_t id = 0;
345
#define V(PropertyName, TypeName)                                              \
346
  do {                                                                         \
347
    if (values.size() > i && id == values[i].id) {                             \
348
      const PropInfo& d = values[i];                                           \
349
      DCHECK_EQ(d.name, #PropertyName);                                        \
350
      MaybeLocal<TypeName> maybe_field =                                       \
351
          isolate_->GetDataFromSnapshotOnce<TypeName>(d.index);                \
352
      Local<TypeName> field;                                                   \
353
      if (!maybe_field.ToLocal(&field)) {                                      \
354
        fprintf(stderr,                                                        \
355
                "Failed to deserialize isolate data template " #PropertyName   \
356
                "\n");                                                         \
357
      }                                                                        \
358
      set_##PropertyName(field);                                               \
359
      i++;                                                                     \
360
    }                                                                          \
361
    id++;                                                                      \
362
  } while (0);
363
364








































































207207
  PER_ISOLATE_TEMPLATE_PROPERTIES(V);
365
#undef V
366
5313
}
367
368
788
void IsolateData::CreateProperties() {
369
  // Create string and private symbol properties as internalized one byte
370
  // strings after the platform is properly initialized.
371
  //
372
  // Internalized because it makes property lookups a little faster and
373
  // because the string is created in the old space straight away.  It's going
374
  // to end up in the old space sooner or later anyway but now it doesn't go
375
  // through v8::Eternal's new space handling first.
376
  //
377
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
378
  // decoding step.
379
380
788
  HandleScope handle_scope(isolate_);
381
382
#define V(PropertyName, StringValue)                                           \
383
  PropertyName##_.Set(                                                         \
384
      isolate_,                                                                \
385
      Private::New(isolate_,                                                   \
386
                   String::NewFromOneByte(                                     \
387
                       isolate_,                                               \
388
                       reinterpret_cast<const uint8_t*>(StringValue),          \
389
                       NewStringType::kInternalized,                           \
390
                       sizeof(StringValue) - 1)                                \
391
                       .ToLocalChecked()));
392
7880
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
393
#undef V
394
#define V(PropertyName, StringValue)                                           \
395
  PropertyName##_.Set(                                                         \
396
      isolate_,                                                                \
397
      Symbol::New(isolate_,                                                    \
398
                  String::NewFromOneByte(                                      \
399
                      isolate_,                                                \
400
                      reinterpret_cast<const uint8_t*>(StringValue),           \
401
                      NewStringType::kInternalized,                            \
402
                      sizeof(StringValue) - 1)                                 \
403
                      .ToLocalChecked()));
404
10244
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
405
#undef V
406
#define V(PropertyName, StringValue)                                           \
407
  PropertyName##_.Set(                                                         \
408
      isolate_,                                                                \
409
      String::NewFromOneByte(isolate_,                                         \
410
                             reinterpret_cast<const uint8_t*>(StringValue),    \
411
                             NewStringType::kInternalized,                     \
412
                             sizeof(StringValue) - 1)                          \
413
          .ToLocalChecked());
414
217488
  PER_ISOLATE_STRING_PROPERTIES(V)
415
#undef V
416
417
  // Create all the provider strings that will be passed to JS. Place them in
418
  // an array so the array index matches the PROVIDER id offset. This way the
419
  // strings can be retrieved quickly.
420
#define V(Provider)                                                           \
421
  async_wrap_providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                \
422
      isolate_,                                                               \
423
      String::NewFromOneByte(                                                 \
424
        isolate_,                                                             \
425
        reinterpret_cast<const uint8_t*>(#Provider),                          \
426
        NewStringType::kInternalized,                                         \
427
        sizeof(#Provider) - 1).ToLocalChecked());
428
46492
  NODE_ASYNC_PROVIDER_TYPES(V)
429
#undef V
430
431
  // TODO(legendecas): eagerly create per isolate templates.
432
788
}
433
434
6101
IsolateData::IsolateData(Isolate* isolate,
435
                         uv_loop_t* event_loop,
436
                         MultiIsolatePlatform* platform,
437
                         ArrayBufferAllocator* node_allocator,
438
6101
                         const IsolateDataSerializeInfo* isolate_data_info)
439
    : isolate_(isolate),
440
      event_loop_(event_loop),
441
48
      node_allocator_(node_allocator == nullptr ? nullptr
442
6053
                                                : node_allocator->GetImpl()),
443
12202
      platform_(platform) {
444
6101
  options_.reset(
445
6101
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
446
447
6101
  if (isolate_data_info == nullptr) {
448
788
    CreateProperties();
449
  } else {
450
5313
    DeserializeProperties(isolate_data_info);
451
  }
452
6101
}
453
454
24
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
455
#define V(PropertyName, StringValue)                                           \
456
  tracker->TrackField(#PropertyName, PropertyName());
457
24
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
458
459
24
  PER_ISOLATE_STRING_PROPERTIES(V)
460
#undef V
461
462
24
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
463
464
24
  if (node_allocator_ != nullptr) {
465
24
    tracker->TrackFieldWithSize(
466
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
467
  }
468
24
  tracker->TrackFieldWithSize(
469
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
470
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
471
24
}
472
473
123
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
474

123
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
475
    // Ideally, we’d have a consistent story that treats all threads/Environment
476
    // instances equally here. However, tracing is essentially global, and this
477
    // callback is called from whichever thread calls `StartTracing()` or
478
    // `StopTracing()`. The only way to do this in a threadsafe fashion
479
    // seems to be only tracking this from the main thread, and only allowing
480
    // these state modifications from the main thread.
481
65
    return;
482
  }
483
484
112
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
485
112
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
486
487
112
  Isolate* isolate = env_->isolate();
488
112
  HandleScope handle_scope(isolate);
489
112
  Local<Function> cb = env_->trace_category_state_function();
490
112
  if (cb.IsEmpty())
491
54
    return;
492
58
  TryCatchScope try_catch(env_);
493
58
  try_catch.SetVerbose(true);
494
116
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
495
116
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
496
}
497
498
6704
void Environment::AssignToContext(Local<v8::Context> context,
499
                                  const ContextInfo& info) {
500
6704
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
501
                                           this);
502
  // Used by Environment::GetCurrent to know that we are on a node context.
503
6704
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kContextTag,
504
                                           Environment::kNodeContextTagPtr);
505
  // Used to retrieve bindings
506
13408
  context->SetAlignedPointerInEmbedderData(
507
6704
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
508
509
#if HAVE_INSPECTOR
510
6704
  inspector_agent()->ContextCreated(context, info);
511
#endif  // HAVE_INSPECTOR
512
513
6704
  this->async_hooks()->AddContext(context);
514
6704
}
515
516
170
void Environment::TryLoadAddon(
517
    const char* filename,
518
    int flags,
519
    const std::function<bool(binding::DLib*)>& was_loaded) {
520
170
  loaded_addons_.emplace_back(filename, flags);
521
170
  if (!was_loaded(&loaded_addons_.back())) {
522
8
    loaded_addons_.pop_back();
523
  }
524
170
}
525
526
11
std::string Environment::GetCwd() {
527
  char cwd[PATH_MAX_BYTES];
528
11
  size_t size = PATH_MAX_BYTES;
529
11
  const int err = uv_cwd(cwd, &size);
530
531
11
  if (err == 0) {
532
11
    CHECK_GT(size, 0);
533
11
    return cwd;
534
  }
535
536
  // This can fail if the cwd is deleted. In that case, fall back to
537
  // exec_path.
538
  const std::string& exec_path = exec_path_;
539
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
540
}
541
542
1903
void Environment::add_refs(int64_t diff) {
543
1903
  task_queues_async_refs_ += diff;
544
1903
  CHECK_GE(task_queues_async_refs_, 0);
545
1903
  if (task_queues_async_refs_ == 0)
546
196
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
547
  else
548
1707
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
549
1903
}
550
551
66065
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
552
132130
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
553
  std::unique_ptr<v8::BackingStore> bs =
554
66065
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
555
66065
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
556
66065
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
557
66065
  return buf;
558
}
559
560
80935
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
561
    const uv_buf_t& buf) {
562
80935
  std::unique_ptr<v8::BackingStore> bs;
563
80935
  if (buf.base != nullptr) {
564
66065
    auto it = released_allocated_buffers_.find(buf.base);
565
66065
    CHECK_NE(it, released_allocated_buffers_.end());
566
66065
    bs = std::move(it->second);
567
66065
    released_allocated_buffers_.erase(it);
568
  }
569
80935
  return bs;
570
}
571
572
781
void Environment::CreateProperties() {
573
1562
  HandleScope handle_scope(isolate_);
574
781
  Local<Context> ctx = context();
575
576
  {
577
781
    Context::Scope context_scope(ctx);
578
781
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
579
1562
    templ->InstanceTemplate()->SetInternalFieldCount(
580
        BaseObject::kInternalFieldCount);
581
781
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
582
583
781
    set_binding_data_ctor_template(templ);
584
  }
585
586
  // Store primordials setup by the per-context script in the environment.
587
  Local<Object> per_context_bindings =
588
1562
      GetPerContextExports(ctx).ToLocalChecked();
589
  Local<Value> primordials =
590
2343
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
591
781
  CHECK(primordials->IsObject());
592
781
  set_primordials(primordials.As<Object>());
593
594
  Local<String> prototype_string =
595
781
      FIXED_ONE_BYTE_STRING(isolate(), "prototype");
596
597
#define V(EnvPropertyName, PrimordialsPropertyName)                            \
598
  {                                                                            \
599
    Local<Value> ctor =                                                        \
600
        primordials.As<Object>()                                               \
601
            ->Get(ctx,                                                         \
602
                  FIXED_ONE_BYTE_STRING(isolate(), PrimordialsPropertyName))   \
603
            .ToLocalChecked();                                                 \
604
    CHECK(ctor->IsObject());                                                   \
605
    Local<Value> prototype =                                                   \
606
        ctor.As<Object>()->Get(ctx, prototype_string).ToLocalChecked();        \
607
    CHECK(prototype->IsObject());                                              \
608
    set_##EnvPropertyName(prototype.As<Object>());                             \
609
  }
610
611

4686
  V(primordials_safe_map_prototype_object, "SafeMap");
612

4686
  V(primordials_safe_set_prototype_object, "SafeSet");
613

4686
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
614

4686
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
615
#undef V
616
617
  Local<Object> process_object =
618
781
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
619
781
  set_process_object(process_object);
620
781
}
621
622
6094
std::string GetExecPath(const std::vector<std::string>& argv) {
623
  char exec_path_buf[2 * PATH_MAX];
624
6094
  size_t exec_path_len = sizeof(exec_path_buf);
625
6094
  std::string exec_path;
626
6094
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
627
6094
    exec_path = std::string(exec_path_buf, exec_path_len);
628
  } else {
629
    exec_path = argv[0];
630
  }
631
632
  // On OpenBSD process.execPath will be relative unless we
633
  // get the full path before process.execPath is used.
634
#if defined(__OpenBSD__)
635
  uv_fs_t req;
636
  req.ptr = nullptr;
637
  if (0 ==
638
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
639
    CHECK_NOT_NULL(req.ptr);
640
    exec_path = std::string(static_cast<char*>(req.ptr));
641
  }
642
  uv_fs_req_cleanup(&req);
643
#endif
644
645
6094
  return exec_path;
646
}
647
648
6094
Environment::Environment(IsolateData* isolate_data,
649
                         Isolate* isolate,
650
                         const std::vector<std::string>& args,
651
                         const std::vector<std::string>& exec_args,
652
                         const EnvSerializeInfo* env_info,
653
                         EnvironmentFlags::Flags flags,
654
6094
                         ThreadId thread_id)
655
    : isolate_(isolate),
656
      isolate_data_(isolate_data),
657
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
658
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
659
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
660
6094
      timer_base_(uv_now(isolate_data->event_loop())),
661
      exec_argv_(exec_args),
662
      argv_(args),
663
      exec_path_(GetExecPath(args)),
664
6094
      exiting_(isolate_, 1, MAYBE_FIELD_PTR(env_info, exiting)),
665
      should_abort_on_uncaught_toggle_(
666
6094
          isolate_,
667
          1,
668
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
669
6094
      stream_base_state_(isolate_,
670
                         StreamBase::kNumStreamBaseStateFields,
671
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
672
6094
      time_origin_(PERFORMANCE_NOW()),
673
6094
      time_origin_timestamp_(GetCurrentTimeInMicroseconds()),
674
      flags_(flags),
675
6094
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
676
6094
                     ? AllocateEnvironmentThreadId().id
677



24376
                     : thread_id.id) {
678
  // We'll be creating new objects so make sure we've entered the context.
679
12188
  HandleScope handle_scope(isolate);
680
681
  // Set some flags if only kDefaultFlags was passed. This can make API version
682
  // transitions easier for embedders.
683
6094
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
684
10734
    flags_ = flags_ |
685
5367
        EnvironmentFlags::kOwnsProcessState |
686
        EnvironmentFlags::kOwnsInspector;
687
  }
688
689
6094
  set_env_vars(per_process::system_environment);
690
6094
  enabled_debug_list_.Parse(env_vars(), isolate);
691
692
  // We create new copies of the per-Environment option sets, so that it is
693
  // easier to modify them after Environment creation. The defaults are
694
  // part of the per-Isolate option set, for which in turn the defaults are
695
  // part of the per-process option set.
696
12188
  options_ = std::make_shared<EnvironmentOptions>(
697
18282
      *isolate_data->options()->per_env);
698
6094
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
699
6094
      options_->debug_options().host_port);
700
701
6094
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
702
727
    set_abort_on_uncaught_exception(false);
703
  }
704
705
#if HAVE_INSPECTOR
706
  // We can only create the inspector agent after having cloned the options.
707
6094
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
708
#endif
709
710
6094
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
711
6094
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
712
6094
    if (TracingController* tracing_controller = writer->GetTracingController())
713
6046
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
714
  }
715
716
6094
  destroy_async_id_list_.reserve(512);
717
718
6094
  performance_state_ = std::make_unique<performance::PerformanceState>(
719
6094
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
720
721
6094
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
722
6094
          TRACING_CATEGORY_NODE1(environment)) != 0) {
723
16
    auto traced_value = tracing::TracedValue::Create();
724
8
    traced_value->BeginArray("args");
725
18
    for (const std::string& arg : args) traced_value->AppendString(arg);
726
8
    traced_value->EndArray();
727
8
    traced_value->BeginArray("exec_args");
728
33
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
729
8
    traced_value->EndArray();
730

15
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
731
                                      "Environment",
732
                                      this,
733
                                      "args",
734
                                      std::move(traced_value));
735
  }
736
6094
}
737
738
781
Environment::Environment(IsolateData* isolate_data,
739
                         Local<Context> context,
740
                         const std::vector<std::string>& args,
741
                         const std::vector<std::string>& exec_args,
742
                         const EnvSerializeInfo* env_info,
743
                         EnvironmentFlags::Flags flags,
744
781
                         ThreadId thread_id)
745
    : Environment(isolate_data,
746
                  context->GetIsolate(),
747
                  args,
748
                  exec_args,
749
                  env_info,
750
                  flags,
751
781
                  thread_id) {
752
781
  InitializeMainContext(context, env_info);
753
781
}
754
755
6094
void Environment::InitializeMainContext(Local<Context> context,
756
                                        const EnvSerializeInfo* env_info) {
757
6094
  context_.Reset(context->GetIsolate(), context);
758
6094
  AssignToContext(context, ContextInfo(""));
759
6094
  if (env_info != nullptr) {
760
5313
    DeserializeProperties(env_info);
761
  } else {
762
781
    CreateProperties();
763
  }
764
765
6094
  if (!options_->force_async_hooks_checks) {
766
1
    async_hooks_.no_force_checks();
767
  }
768
769
  // By default, always abort when --abort-on-uncaught-exception was passed.
770
6094
  should_abort_on_uncaught_toggle_[0] = 1;
771
772
  // The process is not exiting by default.
773
6094
  set_exiting(false);
774
775
6094
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
776
                           time_origin_);
777
6094
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
778
                           per_process::node_start_time);
779
780
6094
  if (per_process::v8_initialized) {
781
6053
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
782
                            performance::performance_v8_start);
783
  }
784
6094
}
785
786
745308
Environment::~Environment() {
787
  if (Environment** interrupt_data = interrupt_data_.load()) {
788
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
789
    // then force V8 to run interrupts by compiling and running an empty script
790
    // so as not to leak memory.
791
10
    *interrupt_data = nullptr;
792
793
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
794
20
    HandleScope handle_scope(isolate());
795
20
    TryCatch try_catch(isolate());
796
20
    Context::Scope context_scope(context());
797
798
#ifdef DEBUG
799
    bool consistency_check = false;
800
    isolate()->RequestInterrupt([](Isolate*, void* data) {
801
      *static_cast<bool*>(data) = true;
802
    }, &consistency_check);
803
#endif
804
805
    Local<Script> script;
806
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
807
10
      USE(script->Run(context()));
808
809
    DCHECK(consistency_check);
810
  }
811
812
  // FreeEnvironment() should have set this.
813
5562
  CHECK(is_stopping());
814
815
5562
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
816
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
817
                                          0);
818
  }
819
820
5562
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
821
      BuildEmbedderGraph, this);
822
823
11124
  HandleScope handle_scope(isolate());
824
825
#if HAVE_INSPECTOR
826
  // Destroy inspector agent before erasing the context. The inspector
827
  // destructor depends on the context still being accessible.
828
5562
  inspector_agent_.reset();
829
#endif
830
831
11124
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
832
                                             nullptr);
833
834
5562
  if (trace_state_observer_) {
835
5562
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
836
5562
    CHECK_NOT_NULL(writer);
837
5562
    if (TracingController* tracing_controller = writer->GetTracingController())
838
5516
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
839
  }
840
841

10368
  TRACE_EVENT_NESTABLE_ASYNC_END0(
842
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
843
844
  // Do not unload addons on the main thread. Some addons need to retain memory
845
  // beyond the Environment's lifetime, and unloading them early would break
846
  // them; with Worker threads, we have the opportunity to be stricter.
847
  // Also, since the main thread usually stops just before the process exits,
848
  // this is far less relevant here.
849
5562
  if (!is_main_thread()) {
850
    // Dereference all addons that were loaded into this environment.
851
738
    for (binding::DLib& addon : loaded_addons_) {
852
14
      addon.Close();
853
    }
854
  }
855
856
5562
  CHECK_EQ(base_object_count_, 0);
857
5562
}
858
859
6057
void Environment::InitializeLibuv() {
860
12114
  HandleScope handle_scope(isolate());
861
6057
  Context::Scope context_scope(context());
862
863
6057
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
864
6057
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
865
866
6057
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
867
6057
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
868
869
6057
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
870
871
6057
  CHECK_EQ(0, uv_check_start(immediate_check_handle(), CheckImmediate));
872
873
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
874
  // but not all samples are created equal; mark the wall clock time spent in
875
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
876
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
877
6057
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
878
6057
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
879
880
23934
  CHECK_EQ(0, uv_async_init(
881
      event_loop(),
882
      &task_queues_async_,
883
      [](uv_async_t* async) {
884
        Environment* env = ContainerOf(
885
            &Environment::task_queues_async_, async);
886
        HandleScope handle_scope(env->isolate());
887
        Context::Scope context_scope(env->context());
888
        env->RunAndClearNativeImmediates();
889
      }));
890
6057
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
891
6057
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
892
6057
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
893
894
  {
895
12114
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
896
6057
    task_queues_async_initialized_ = true;
897

12114
    if (native_immediates_threadsafe_.size() > 0 ||
898
6057
        native_immediates_interrupts_.size() > 0) {
899
5309
      uv_async_send(&task_queues_async_);
900
    }
901
  }
902
903
  // Register clean-up cb to be called to clean up the handles
904
  // when the environment is freed, note that they are not cleaned in
905
  // the one environment per process setup, but will be called in
906
  // FreeEnvironment.
907
6057
  RegisterHandleCleanups();
908
909
6057
  StartProfilerIdleNotifier();
910
6057
}
911
912
317
void Environment::ExitEnv() {
913
317
  set_can_call_into_js(false);
914
317
  set_stopping(true);
915
317
  isolate_->TerminateExecution();
916
634
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
917
317
}
918
919
6057
void Environment::RegisterHandleCleanups() {
920
6057
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
921
33150
                                        void* arg) {
922
33150
    handle->data = env;
923
924
33150
    env->CloseHandle(handle, [](uv_handle_t* handle) {
925
#ifdef DEBUG
926
      memset(handle, 0xab, uv_handle_size(handle->type));
927
#endif
928
33150
    });
929
33150
  };
930
931
36342
  auto register_handle = [&](uv_handle_t* handle) {
932
36342
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
933
42399
  };
934
6057
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
935
6057
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
936
6057
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
937
6057
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
938
6057
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
939
6057
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
940
6057
}
941
942
11113
void Environment::CleanupHandles() {
943
  {
944
11113
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
945
11113
    task_queues_async_initialized_ = false;
946
  }
947
948
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
949
22226
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
950
951
11113
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
952
953
11252
  for (ReqWrapBase* request : req_wrap_queue_)
954
139
    request->Cancel();
955
956
15397
  for (HandleWrap* handle : handle_wrap_queue_)
957
8568
    handle->Close();
958
959
44263
  for (HandleCleanup& hc : handle_cleanup_queue_)
960
33150
    hc.cb_(this, hc.handle_, hc.arg_);
961
11113
  handle_cleanup_queue_.clear();
962
963
10400
  while (handle_cleanup_waiting_ != 0 ||
964

32628
         request_waiting_ != 0 ||
965
11115
         !handle_wrap_queue_.IsEmpty()) {
966
10400
    uv_run(event_loop(), UV_RUN_ONCE);
967
  }
968
11113
}
969
970
6057
void Environment::StartProfilerIdleNotifier() {
971
6057
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
972
181152
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
973
181152
    env->isolate()->SetIdle(true);
974
181152
  });
975
6057
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
976
180967
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
977
180967
    env->isolate()->SetIdle(false);
978
180967
  });
979
6057
}
980
981
683655
void Environment::PrintSyncTrace() const {
982
683655
  if (!trace_sync_io_) return;
983
984
2
  HandleScope handle_scope(isolate());
985
986
1
  fprintf(
987
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
988
1
  PrintStackTrace(isolate(),
989
                  StackTrace::CurrentStackTrace(
990
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
991
}
992
993
5239
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
994
5239
  EscapableHandleScope handle_scope(isolate());
995
10478
  if (!snapshot_serialize_callback().IsEmpty()) {
996
    Context::Scope context_scope(context());
997
    return handle_scope.EscapeMaybe(snapshot_serialize_callback()->Call(
998
        context(), v8::Undefined(isolate()), 0, nullptr));
999
  }
1000
10478
  return handle_scope.Escape(Undefined(isolate()));
1001
}
1002
1003
MaybeLocal<Value> Environment::RunSnapshotDeserializeMain() const {
1004
  EscapableHandleScope handle_scope(isolate());
1005
  if (!snapshot_deserialize_main().IsEmpty()) {
1006
    Context::Scope context_scope(context());
1007
    return handle_scope.EscapeMaybe(snapshot_deserialize_main()->Call(
1008
        context(), v8::Undefined(isolate()), 0, nullptr));
1009
  }
1010
  return handle_scope.Escape(Undefined(isolate()));
1011
}
1012
1013
5562
void Environment::RunCleanup() {
1014
5562
  started_cleanup_ = true;
1015

15930
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1016
5562
  bindings_.clear();
1017
5562
  CleanupHandles();
1018
1019
16677
  while (!cleanup_hooks_.empty() ||
1020
11126
         native_immediates_.size() > 0 ||
1021

22239
         native_immediates_threadsafe_.size() > 0 ||
1022
5562
         native_immediates_interrupts_.size() > 0) {
1023
    // Copy into a vector, since we can't sort an unordered_set in-place.
1024
    std::vector<CleanupHookCallback> callbacks(
1025
11102
        cleanup_hooks_.begin(), cleanup_hooks_.end());
1026
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
1027
    // need to be able to check whether they were un-scheduled by another hook.
1028
1029
5551
    std::sort(callbacks.begin(), callbacks.end(),
1030
1087670
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1031
      // Sort in descending order so that the most recently inserted callbacks
1032
      // are run first.
1033
1087670
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1034
    });
1035
1036
165744
    for (const CleanupHookCallback& cb : callbacks) {
1037
160193
      if (cleanup_hooks_.count(cb) == 0) {
1038
        // This hook was removed from the `cleanup_hooks_` set during another
1039
        // hook that was run earlier. Nothing to do here.
1040
1007
        continue;
1041
      }
1042
1043
159186
      cb.fn_(cb.arg_);
1044
159186
      cleanup_hooks_.erase(cb);
1045
    }
1046
5551
    CleanupHandles();
1047
  }
1048
1049
5565
  for (const int fd : unmanaged_fds_) {
1050
    uv_fs_t close_req;
1051
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
1052
3
    uv_fs_req_cleanup(&close_req);
1053
  }
1054
5562
}
1055
1056
6185
void Environment::RunAtExitCallbacks() {
1057

17688
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1058
18339
  for (ExitCallback at_exit : at_exit_functions_) {
1059
12154
    at_exit.cb_(at_exit.arg_);
1060
  }
1061
6185
  at_exit_functions_.clear();
1062
6185
}
1063
1064
12178
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1065
12178
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1066
12178
}
1067
1068
218440
void Environment::RunAndClearInterrupts() {
1069
218440
  while (native_immediates_interrupts_.size() > 0) {
1070
10357
    NativeImmediateQueue queue;
1071
    {
1072
20714
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1073
10357
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1074
    }
1075
10357
    DebugSealHandleScope seal_handle_scope(isolate());
1076
1077
20723
    while (auto head = queue.Shift())
1078
20732
      head->Call(this);
1079
  }
1080
208083
}
1081
1082
198041
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1083

401094
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1084
               "RunAndClearNativeImmediates");
1085
396076
  HandleScope handle_scope(isolate_);
1086
396076
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
1087
1088
198041
  size_t ref_count = 0;
1089
1090
  // Handle interrupts first. These functions are not allowed to throw
1091
  // exceptions, so we do not need to handle that.
1092
198041
  RunAndClearInterrupts();
1093
1094
396080
  auto drain_list = [&](NativeImmediateQueue* queue) {
1095
792154
    TryCatchScope try_catch(this);
1096
396080
    DebugSealHandleScope seal_handle_scope(isolate());
1097
456045
    while (auto head = queue->Shift()) {
1098
59972
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1099
59972
      if (is_refed)
1100
35148
        ref_count++;
1101
1102

59972
      if (is_refed || !only_refed)
1103
59731
        head->Call(this);
1104
1105
59967
      head.reset();  // Destroy now so that this is also observed by try_catch.
1106
1107
59967
      if (UNLIKELY(try_catch.HasCaught())) {
1108

2
        if (!try_catch.HasTerminated() && can_call_into_js())
1109
2
          errors::TriggerUncaughtException(isolate(), try_catch);
1110
1111
1
        return true;
1112
      }
1113
59965
    }
1114
396073
    return false;
1115
198041
  };
1116
198041
  while (drain_list(&native_immediates_)) {}
1117
1118
198038
  immediate_info()->ref_count_dec(ref_count);
1119
1120
198038
  if (immediate_info()->ref_count() == 0)
1121
155550
    ToggleImmediateRef(false);
1122
1123
  // It is safe to check .size() first, because there is a causal relationship
1124
  // between pushes to the threadsafe immediate list and this function being
1125
  // called. For the common case, it's worth checking the size first before
1126
  // establishing a mutex lock.
1127
  // This is intentionally placed after the `ref_count` handling, because when
1128
  // refed threadsafe immediates are created, they are not counted towards the
1129
  // count in immediate_info() either.
1130
198035
  NativeImmediateQueue threadsafe_immediates;
1131
198038
  if (native_immediates_threadsafe_.size() > 0) {
1132
2068
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1133
1034
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1134
  }
1135
198039
  while (drain_list(&threadsafe_immediates)) {}
1136
198035
}
1137
1138
10371
void Environment::RequestInterruptFromV8() {
1139
  // The Isolate may outlive the Environment, so some logic to handle the
1140
  // situation in which the Environment is destroyed before the handler runs
1141
  // is required.
1142
1143
  // We allocate a new pointer to a pointer to this Environment instance, and
1144
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
1145
  // callbacks are already scheduled to run and we can delete our own pointer
1146
  // and just return. If it was nullptr previously, the Environment** is stored;
1147
  // ~Environment sets the Environment* contained in it to nullptr, so that
1148
  // the callback can check whether ~Environment has already run and it is thus
1149
  // not safe to access the Environment instance itself.
1150
10371
  Environment** interrupt_data = new Environment*(this);
1151
10371
  Environment** dummy = nullptr;
1152
10371
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1153
427
    delete interrupt_data;
1154
427
    return;  // Already scheduled.
1155
  }
1156
1157
9944
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1158
9935
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1159
9935
    Environment* env = *env_ptr;
1160
9935
    if (env == nullptr) {
1161
      // The Environment has already been destroyed. That should be okay; any
1162
      // callback added before the Environment shuts down would have been
1163
      // handled during cleanup.
1164
10
      return;
1165
    }
1166
9925
    env->interrupt_data_.store(nullptr);
1167
9925
    env->RunAndClearInterrupts();
1168
  }, interrupt_data);
1169
}
1170
1171
9784
void Environment::ScheduleTimer(int64_t duration_ms) {
1172
9784
  if (started_cleanup_) return;
1173
9784
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1174
}
1175
1176
3672
void Environment::ToggleTimerRef(bool ref) {
1177
3672
  if (started_cleanup_) return;
1178
1179
3672
  if (ref) {
1180
2408
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1181
  } else {
1182
1264
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1183
  }
1184
}
1185
1186
7800
void Environment::RunTimers(uv_timer_t* handle) {
1187
7800
  Environment* env = Environment::from_timer_handle(handle);
1188

8316
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1189
1190
7800
  if (!env->can_call_into_js())
1191
    return;
1192
1193
7800
  HandleScope handle_scope(env->isolate());
1194
7800
  Context::Scope context_scope(env->context());
1195
1196
7800
  Local<Object> process = env->process_object();
1197
7800
  InternalCallbackScope scope(env, process, {0, 0});
1198
1199
7800
  Local<Function> cb = env->timers_callback_function();
1200
  MaybeLocal<Value> ret;
1201
7800
  Local<Value> arg = env->GetNow();
1202
  // This code will loop until all currently due timers will process. It is
1203
  // impossible for us to end up in an infinite loop due to how the JS-side
1204
  // is structured.
1205
33
  do {
1206
7833
    TryCatchScope try_catch(env);
1207
7833
    try_catch.SetVerbose(true);
1208
7833
    ret = cb->Call(env->context(), process, 1, &arg);
1209

7823
  } while (ret.IsEmpty() && env->can_call_into_js());
1210
1211
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
1212
  // is reset back to `true` after being previously set to `false` then this
1213
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
1214
  // timers corruption will occur and all timers behaviour will become
1215
  // entirely unpredictable.
1216
7790
  if (ret.IsEmpty())
1217
11
    return;
1218
1219
  // To allow for less JS-C++ boundary crossing, the value returned from JS
1220
  // serves a few purposes:
1221
  // 1. If it's 0, no more timers exist and the handle should be unrefed
1222
  // 2. If it's > 0, the value represents the next timer's expiry and there
1223
  //    is at least one timer remaining that is refed.
1224
  // 3. If it's < 0, the absolute value represents the next timer's expiry
1225
  //    and there are no timers that are refed.
1226
  int64_t expiry_ms =
1227
7779
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1228
1229
7779
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1230
1231
7779
  if (expiry_ms != 0) {
1232
    int64_t duration_ms =
1233
6822
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1234
1235
6822
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1236
1237
6822
    if (expiry_ms > 0)
1238
6128
      uv_ref(h);
1239
    else
1240
694
      uv_unref(h);
1241
  } else {
1242
957
    uv_unref(h);
1243
  }
1244
}
1245
1246
1247
180967
void Environment::CheckImmediate(uv_check_t* handle) {
1248
180967
  Environment* env = Environment::from_immediate_check_handle(handle);
1249

183985
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1250
1251
180967
  HandleScope scope(env->isolate());
1252
180967
  Context::Scope context_scope(env->context());
1253
1254
180967
  env->RunAndClearNativeImmediates();
1255
1256

180967
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1257
139068
    return;
1258
1259
952
  do {
1260
42843
    MakeCallback(env->isolate(),
1261
                 env->process_object(),
1262
                 env->immediate_callback_function(),
1263
                 0,
1264
                 nullptr,
1265
42851
                 {0, 0}).ToLocalChecked();
1266

42843
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
1267
1268
41891
  if (env->immediate_info()->ref_count() == 0)
1269
4827
    env->ToggleImmediateRef(false);
1270
}
1271
1272
225696
void Environment::ToggleImmediateRef(bool ref) {
1273
225696
  if (started_cleanup_) return;
1274
1275
214674
  if (ref) {
1276
    // Idle handle is needed only to stop the event loop from blocking in poll.
1277
65295
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
1278
  } else {
1279
149379
    uv_idle_stop(immediate_idle_handle());
1280
  }
1281
}
1282
1283
1284
46965
Local<Value> Environment::GetNow() {
1285
46965
  uv_update_time(event_loop());
1286
46965
  uint64_t now = uv_now(event_loop());
1287
46965
  CHECK_GE(now, timer_base());
1288
46965
  now -= timer_base();
1289
46965
  if (now <= 0xffffffff)
1290
93930
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
1291
  else
1292
    return Number::New(isolate(), static_cast<double>(now));
1293
}
1294
1295
28
void CollectExceptionInfo(Environment* env,
1296
                          Local<Object> obj,
1297
                          int errorno,
1298
                          const char* err_string,
1299
                          const char* syscall,
1300
                          const char* message,
1301
                          const char* path,
1302
                          const char* dest) {
1303
28
  obj->Set(env->context(),
1304
           env->errno_string(),
1305
112
           Integer::New(env->isolate(), errorno)).Check();
1306
1307
28
  obj->Set(env->context(), env->code_string(),
1308
84
           OneByteString(env->isolate(), err_string)).Check();
1309
1310
28
  if (message != nullptr) {
1311
28
    obj->Set(env->context(), env->message_string(),
1312
112
             OneByteString(env->isolate(), message)).Check();
1313
  }
1314
1315
  Local<Value> path_buffer;
1316
28
  if (path != nullptr) {
1317
    path_buffer =
1318
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
1319
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
1320
  }
1321
1322
  Local<Value> dest_buffer;
1323
28
  if (dest != nullptr) {
1324
    dest_buffer =
1325
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
1326
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
1327
  }
1328
1329
28
  if (syscall != nullptr) {
1330
28
    obj->Set(env->context(), env->syscall_string(),
1331
112
             OneByteString(env->isolate(), syscall)).Check();
1332
  }
1333
28
}
1334
1335
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
1336
                                         int errorno,
1337
                                         const char* syscall,
1338
                                         const char* message,
1339
                                         const char* path,
1340
                                         const char* dest) {
1341

28
  if (!object->IsObject() || errorno == 0)
1342
    return;
1343
1344
28
  Local<Object> obj = object.As<Object>();
1345
28
  const char* err_string = uv_err_name(errorno);
1346
1347

28
  if (message == nullptr || message[0] == '\0') {
1348
28
    message = uv_strerror(errorno);
1349
  }
1350
1351
28
  node::CollectExceptionInfo(this, obj, errorno, err_string,
1352
                             syscall, message, path, dest);
1353
}
1354
1355
6094
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1356
6094
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
1357
1358
6
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
1359
    Local<Context> context, SnapshotCreator* creator) {
1360
6
  return {fields_.Serialize(context, creator)};
1361
}
1362
1363
5313
void ImmediateInfo::Deserialize(Local<Context> context) {
1364
5313
  fields_.Deserialize(context);
1365
5313
}
1366
1367
6
std::ostream& operator<<(std::ostream& output,
1368
                         const ImmediateInfo::SerializeInfo& i) {
1369
6
  output << "{ " << i.fields << " }";
1370
6
  return output;
1371
}
1372
1373
24
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1374
24
  tracker->TrackField("fields", fields_);
1375
24
}
1376
1377
6
TickInfo::SerializeInfo TickInfo::Serialize(Local<Context> context,
1378
                                            SnapshotCreator* creator) {
1379
6
  return {fields_.Serialize(context, creator)};
1380
}
1381
1382
5313
void TickInfo::Deserialize(Local<Context> context) {
1383
5313
  fields_.Deserialize(context);
1384
5313
}
1385
1386
6
std::ostream& operator<<(std::ostream& output,
1387
                         const TickInfo::SerializeInfo& i) {
1388
6
  output << "{ " << i.fields << " }";
1389
6
  return output;
1390
}
1391
1392
24
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1393
24
  tracker->TrackField("fields", fields_);
1394
24
}
1395
1396
6094
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1397
    : fields_(
1398
6094
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1399
1400
6094
AsyncHooks::AsyncHooks(Isolate* isolate, const SerializeInfo* info)
1401
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1402
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1403
      async_id_fields_(
1404
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1405

6094
      info_(info) {
1406
12188
  HandleScope handle_scope(isolate);
1407
6094
  if (info == nullptr) {
1408
781
    clear_async_id_stack();
1409
1410
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1411
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1412
    // See discussion in https://github.com/nodejs/node/pull/15454
1413
    // When removing this, do it by reverting the commit. Otherwise the test
1414
    // and flag changes won't be included.
1415
781
    fields_[kCheck] = 1;
1416
1417
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1418
    // specified default value and it should fallback to the executionAsyncId.
1419
    // 0 is not used as the magic value, because that indicates a missing
1420
    // context which is different from a default context.
1421
781
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1422
1423
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1424
    // context during bootstrap (code that runs before entering uv_run()).
1425
781
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1426
  }
1427
6094
}
1428
1429
5313
void AsyncHooks::Deserialize(Local<Context> context) {
1430
5313
  async_ids_stack_.Deserialize(context);
1431
5313
  fields_.Deserialize(context);
1432
5313
  async_id_fields_.Deserialize(context);
1433
1434
  Local<Array> js_execution_async_resources;
1435
5313
  if (info_->js_execution_async_resources != 0) {
1436
    js_execution_async_resources =
1437
5313
        context->GetDataFromSnapshotOnce<Array>(
1438
15939
            info_->js_execution_async_resources).ToLocalChecked();
1439
  } else {
1440
    js_execution_async_resources = Array::New(context->GetIsolate());
1441
  }
1442
5313
  js_execution_async_resources_.Reset(
1443
      context->GetIsolate(), js_execution_async_resources);
1444
1445
  // The native_execution_async_resources_ field requires v8::Local<> instances
1446
  // for async calls whose resources were on the stack as JS objects when they
1447
  // were entered. We cannot recreate this here; however, storing these values
1448
  // on the JS equivalent gives the same result, so we do that instead.
1449
5313
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1450
    if (info_->native_execution_async_resources[i] == SIZE_MAX)
1451
      continue;
1452
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1453
                                   info_->native_execution_async_resources[i])
1454
                               .ToLocalChecked();
1455
    js_execution_async_resources->Set(context, i, obj).Check();
1456
  }
1457
5313
  info_ = nullptr;
1458
5313
}
1459
1460
6
std::ostream& operator<<(std::ostream& output,
1461
                         const AsyncHooks::SerializeInfo& i) {
1462
  output << "{\n"
1463
6
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1464
6
         << "  " << i.fields << ",  // fields\n"
1465
6
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1466
6
         << "  " << i.js_execution_async_resources
1467
         << ",  // js_execution_async_resources\n"
1468
6
         << "  " << i.native_execution_async_resources
1469
         << ",  // native_execution_async_resources\n"
1470
6
         << "}";
1471
6
  return output;
1472
}
1473
1474
6
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1475
                                                SnapshotCreator* creator) {
1476
6
  SerializeInfo info;
1477
  // TODO(joyeecheung): some of these probably don't need to be serialized.
1478
6
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1479
6
  info.fields = fields_.Serialize(context, creator);
1480
6
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1481
6
  if (!js_execution_async_resources_.IsEmpty()) {
1482
6
    info.js_execution_async_resources = creator->AddData(
1483
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1484
6
    CHECK_NE(info.js_execution_async_resources, 0);
1485
  } else {
1486
    info.js_execution_async_resources = 0;
1487
  }
1488
1489
6
  info.native_execution_async_resources.resize(
1490
      native_execution_async_resources_.size());
1491
6
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1492
    info.native_execution_async_resources[i] =
1493
        native_execution_async_resources_[i].IsEmpty() ? SIZE_MAX :
1494
            creator->AddData(
1495
                context,
1496
                native_execution_async_resources_[i]);
1497
  }
1498
6
  CHECK_EQ(contexts_.size(), 1);
1499

12
  CHECK_EQ(contexts_[0], env()->context());
1500
6
  CHECK(js_promise_hooks_[0].IsEmpty());
1501
6
  CHECK(js_promise_hooks_[1].IsEmpty());
1502
6
  CHECK(js_promise_hooks_[2].IsEmpty());
1503
6
  CHECK(js_promise_hooks_[3].IsEmpty());
1504
1505
6
  return info;
1506
}
1507
1508
24
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1509
24
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1510
24
  tracker->TrackField("fields", fields_);
1511
24
  tracker->TrackField("async_id_fields", async_id_fields_);
1512
24
  tracker->TrackField("js_promise_hooks", js_promise_hooks_);
1513
24
}
1514
1515
4
void AsyncHooks::grow_async_ids_stack() {
1516
4
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1517
1518
4
  env()->async_hooks_binding()->Set(
1519
      env()->context(),
1520
      env()->async_ids_stack_string(),
1521
12
      async_ids_stack_.GetJSArray()).Check();
1522
4
}
1523
1524
4
void AsyncHooks::FailWithCorruptedAsyncStack(double expected_async_id) {
1525
4
  fprintf(stderr,
1526
          "Error: async hook stack has become corrupted ("
1527
          "actual: %.f, expected: %.f)\n",
1528
          async_id_fields_.GetValue(kExecutionAsyncId),
1529
          expected_async_id);
1530
4
  DumpBacktrace(stderr);
1531
4
  fflush(stderr);
1532
4
  if (!env()->abort_on_uncaught_exception())
1533
4
    exit(1);
1534
  fprintf(stderr, "\n");
1535
  fflush(stderr);
1536
  ABORT_NO_BACKTRACE();
1537
}
1538
1539
606
void Environment::Exit(int exit_code) {
1540
606
  if (options()->trace_exit) {
1541
4
    HandleScope handle_scope(isolate());
1542
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1543
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1544
1545
2
    if (is_main_thread()) {
1546
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1547
    } else {
1548
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1549
              uv_os_getpid(), thread_id());
1550
    }
1551
1552
2
    fprintf(
1553
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1554
2
    PrintStackTrace(isolate(),
1555
                    StackTrace::CurrentStackTrace(
1556
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1557
  }
1558
606
  process_exit_handler_(this, exit_code);
1559
79
}
1560
1561
6116
void Environment::stop_sub_worker_contexts() {
1562
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1563
1564
6116
  while (!sub_worker_contexts_.empty()) {
1565
27
    Worker* w = *sub_worker_contexts_.begin();
1566
27
    remove_sub_worker_context(w);
1567
27
    w->Exit(1);
1568
27
    w->JoinThread();
1569
  }
1570
6089
}
1571
1572
10
Environment* Environment::worker_parent_env() const {
1573
10
  if (worker_context() == nullptr) return nullptr;
1574
  return worker_context()->env();
1575
}
1576
1577
62916
void Environment::AddUnmanagedFd(int fd) {
1578
62916
  if (!tracks_unmanaged_fds()) return;
1579
2728
  auto result = unmanaged_fds_.insert(fd);
1580
2728
  if (!result.second) {
1581
    ProcessEmitWarning(
1582
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1583
  }
1584
}
1585
1586
62537
void Environment::RemoveUnmanagedFd(int fd) {
1587
62537
  if (!tracks_unmanaged_fds()) return;
1588
2725
  size_t removed_count = unmanaged_fds_.erase(fd);
1589
2725
  if (removed_count == 0) {
1590
    ProcessEmitWarning(
1591
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1592
  }
1593
}
1594
1595
5218
void Environment::PrintInfoForSnapshotIfDebug() {
1596
5218
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1597
    fprintf(stderr, "BaseObjects at the exit of the Environment:\n");
1598
    PrintAllBaseObjects();
1599
    fprintf(stderr, "\nNative modules without cache:\n");
1600
    for (const auto& s : native_modules_without_cache) {
1601
      fprintf(stderr, "%s\n", s.c_str());
1602
    }
1603
    fprintf(stderr, "\nNative modules with cache:\n");
1604
    for (const auto& s : native_modules_with_cache) {
1605
      fprintf(stderr, "%s\n", s.c_str());
1606
    }
1607
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1608
    for (const auto mod : internal_bindings) {
1609
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1610
    }
1611
  }
1612
5218
}
1613
1614
void Environment::PrintAllBaseObjects() {
1615
  size_t i = 0;
1616
  std::cout << "BaseObjects\n";
1617
  ForEachBaseObject([&](BaseObject* obj) {
1618
    std::cout << "#" << i++ << " " << obj << ": " <<
1619
      obj->MemoryInfoName() << "\n";
1620
  });
1621
}
1622
1623
5218
void Environment::VerifyNoStrongBaseObjects() {
1624
  // When a process exits cleanly, i.e. because the event loop ends up without
1625
  // things to wait for, the Node.js objects that are left on the heap should
1626
  // be:
1627
  //
1628
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1629
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1630
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1631
  //   4. an inactive libuv handle (essentially the same here)
1632
  //
1633
  // There are a few exceptions to this rule, but generally, if there are
1634
  // C++-backed Node.js objects on the heap that do not fall into the above
1635
  // categories, we may be looking at a potential memory leak. Most likely,
1636
  // the cause is a missing MakeWeak() call on the corresponding object.
1637
  //
1638
  // In order to avoid this kind of problem, we check the list of BaseObjects
1639
  // for these criteria. Currently, we only do so when explicitly instructed to
1640
  // or when in debug mode (where --verify-base-objects is always-on).
1641
1642
5218
  if (!options()->verify_base_objects) return;
1643
1644
  ForEachBaseObject([](BaseObject* obj) {
1645
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1646
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1647
            obj->MemoryInfoName().c_str());
1648
    fflush(stderr);
1649
    ABORT();
1650
  });
1651
}
1652
1653
6
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1654
6
  EnvSerializeInfo info;
1655
6
  Local<Context> ctx = context();
1656
1657
6
  SerializeBindingData(this, creator, &info);
1658
  // Currently all modules are compiled without cache in builtin snapshot
1659
  // builder.
1660
12
  info.native_modules = std::vector<std::string>(
1661
6
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1662
1663
6
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1664
6
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1665
6
  info.tick_info = tick_info_.Serialize(ctx, creator);
1666
6
  info.performance_state = performance_state_->Serialize(ctx, creator);
1667
6
  info.exiting = exiting_.Serialize(ctx, creator);
1668
6
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1669
6
  info.should_abort_on_uncaught_toggle =
1670
6
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1671
1672
6
  uint32_t id = 0;
1673
#define V(PropertyName, TypeName)                                              \
1674
  do {                                                                         \
1675
    Local<TypeName> field = PropertyName();                                    \
1676
    if (!field.IsEmpty()) {                                                    \
1677
      size_t index = creator->AddData(ctx, field);                             \
1678
      info.persistent_values.push_back({#PropertyName, id, index});            \
1679
    }                                                                          \
1680
    id++;                                                                      \
1681
  } while (0);
1682
































594
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1683
#undef V
1684
1685
6
  info.context = creator->AddData(ctx, context());
1686
6
  return info;
1687
}
1688
1689
18
std::ostream& operator<<(std::ostream& output,
1690
                         const std::vector<PropInfo>& vec) {
1691
18
  output << "{\n";
1692
360
  for (const auto& info : vec) {
1693
342
    output << "  " << info << ",\n";
1694
  }
1695
18
  output << "}";
1696
18
  return output;
1697
}
1698
1699
342
std::ostream& operator<<(std::ostream& output, const PropInfo& info) {
1700
342
  output << "{ \"" << info.name << "\", " << std::to_string(info.id) << ", "
1701
684
         << std::to_string(info.index) << " }";
1702
342
  return output;
1703
}
1704
1705
6
std::ostream& operator<<(std::ostream& output,
1706
                         const std::vector<std::string>& vec) {
1707
6
  output << "{\n";
1708
702
  for (const auto& info : vec) {
1709
696
    output << "  \"" << info << "\",\n";
1710
  }
1711
6
  output << "}";
1712
6
  return output;
1713
}
1714
1715
6
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1716
  output << "{\n"
1717
6
         << "// -- bindings begins --\n"
1718
6
         << i.bindings << ",\n"
1719
         << "// -- bindings ends --\n"
1720
6
         << "// -- native_modules begins --\n"
1721
6
         << i.native_modules << ",\n"
1722
         << "// -- native_modules ends --\n"
1723
6
         << "// -- async_hooks begins --\n"
1724
6
         << i.async_hooks << ",\n"
1725
6
         << "// -- async_hooks ends --\n"
1726
6
         << i.tick_info << ",  // tick_info\n"
1727
6
         << i.immediate_info << ",  // immediate_info\n"
1728
6
         << "// -- performance_state begins --\n"
1729
6
         << i.performance_state << ",\n"
1730
6
         << "// -- performance_state ends --\n"
1731
6
         << i.exiting << ",  // exiting\n"
1732
6
         << i.stream_base_state << ",  // stream_base_state\n"
1733
6
         << i.should_abort_on_uncaught_toggle
1734
         << ",  // should_abort_on_uncaught_toggle\n"
1735
6
         << "// -- persistent_values begins --\n"
1736
6
         << i.persistent_values << ",\n"
1737
6
         << "// -- persistent_values ends --\n"
1738
6
         << i.context << ",  // context\n"
1739
6
         << "}";
1740
6
  return output;
1741
}
1742
1743
21252
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1744
                                            Local<Object> holder,
1745
                                            int index,
1746
                                            InternalFieldInfo* info) {
1747
42504
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1748
21252
  deserialize_requests_.push_back(std::move(request));
1749
21252
}
1750
1751
5313
void Environment::RunDeserializeRequests() {
1752
10626
  HandleScope scope(isolate());
1753
5313
  Local<Context> ctx = context();
1754
5313
  Isolate* is = isolate();
1755
26565
  while (!deserialize_requests_.empty()) {
1756
42504
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1757
21252
    deserialize_requests_.pop_front();
1758
21252
    Local<Object> holder = request.holder.Get(is);
1759
21252
    request.cb(ctx, holder, request.index, request.info);
1760
    request.holder.Reset();
1761
21252
    request.info->Delete();
1762
  }
1763
5313
}
1764
1765
5313
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1766
5313
  Local<Context> ctx = context();
1767
1768
5313
  RunDeserializeRequests();
1769
1770
5313
  native_modules_in_snapshot = info->native_modules;
1771
5313
  async_hooks_.Deserialize(ctx);
1772
5313
  immediate_info_.Deserialize(ctx);
1773
5313
  tick_info_.Deserialize(ctx);
1774
5313
  performance_state_->Deserialize(ctx);
1775
5313
  exiting_.Deserialize(ctx);
1776
5313
  stream_base_state_.Deserialize(ctx);
1777
5313
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1778
1779
5313
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1780
    fprintf(stderr, "deserializing...\n");
1781
    std::cerr << *info << "\n";
1782
  }
1783
1784
5313
  const std::vector<PropInfo>& values = info->persistent_values;
1785
5313
  size_t i = 0;  // index to the array
1786
5313
  uint32_t id = 0;
1787
#define V(PropertyName, TypeName)                                              \
1788
  do {                                                                         \
1789
    if (values.size() > i && id == values[i].id) {                             \
1790
      const PropInfo& d = values[i];                                           \
1791
      DCHECK_EQ(d.name, #PropertyName);                                        \
1792
      MaybeLocal<TypeName> maybe_field =                                       \
1793
          ctx->GetDataFromSnapshotOnce<TypeName>(d.index);                     \
1794
      Local<TypeName> field;                                                   \
1795
      if (!maybe_field.ToLocal(&field)) {                                      \
1796
        fprintf(stderr,                                                        \
1797
                "Failed to deserialize environment value " #PropertyName       \
1798
                "\n");                                                         \
1799
      }                                                                        \
1800
      set_##PropertyName(field);                                               \
1801
      i++;                                                                     \
1802
    }                                                                          \
1803
    id++;                                                                      \
1804
  } while (0);
1805
1806
































































































































547239
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1807
#undef V
1808
1809
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1810
10626
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1811
  Local<Context> ctx_from_snapshot;
1812
5313
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1813
    fprintf(stderr,
1814
            "Failed to deserialize context back reference from the snapshot\n");
1815
  }
1816
5313
  CHECK_EQ(ctx_from_snapshot, ctx);
1817
5313
}
1818
1819
1
uint64_t GuessMemoryAvailableToTheProcess() {
1820
1
  uint64_t free_in_system = uv_get_free_memory();
1821
1
  size_t allowed = uv_get_constrained_memory();
1822
1
  if (allowed == 0) {
1823
    return free_in_system;
1824
  }
1825
  size_t rss;
1826
1
  int err = uv_resident_set_memory(&rss);
1827
1
  if (err) {
1828
    return free_in_system;
1829
  }
1830
1
  if (allowed < rss) {
1831
    // Something is probably wrong. Fallback to the free memory.
1832
    return free_in_system;
1833
  }
1834
  // There may still be room for swap, but we will just leave it here.
1835
1
  return allowed - rss;
1836
}
1837
1838
24
void Environment::BuildEmbedderGraph(Isolate* isolate,
1839
                                     EmbedderGraph* graph,
1840
                                     void* data) {
1841
24
  MemoryTracker tracker(isolate, graph);
1842
24
  Environment* env = static_cast<Environment*>(data);
1843
24
  tracker.Track(env);
1844
24
  env->ForEachBaseObject([&](BaseObject* obj) {
1845
543
    if (obj->IsDoneInitializing())
1846
542
      tracker.Track(obj);
1847
543
  });
1848
24
}
1849
1850
1
size_t Environment::NearHeapLimitCallback(void* data,
1851
                                          size_t current_heap_limit,
1852
                                          size_t initial_heap_limit) {
1853
1
  Environment* env = static_cast<Environment*>(data);
1854
1855
  Debug(env,
1856
        DebugCategory::DIAGNOSTICS,
1857
        "Invoked NearHeapLimitCallback, processing=%d, "
1858
        "current_limit=%" PRIu64 ", "
1859
        "initial_limit=%" PRIu64 "\n",
1860
1
        env->is_processing_heap_limit_callback_,
1861
2
        static_cast<uint64_t>(current_heap_limit),
1862
1
        static_cast<uint64_t>(initial_heap_limit));
1863
1864
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1865
1
  size_t young_gen_size = 0;
1866
1
  size_t old_gen_size = 0;
1867
1868
1
  HeapSpaceStatistics stats;
1869
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1870
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1871
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1872

15
    if (strcmp(stats.space_name(), "new_space") == 0 ||
1873
7
        strcmp(stats.space_name(), "new_large_object_space") == 0) {
1874
2
      young_gen_size += stats.space_used_size();
1875
    } else {
1876
6
      old_gen_size += stats.space_used_size();
1877
    }
1878
  }
1879
1880
  Debug(env,
1881
        DebugCategory::DIAGNOSTICS,
1882
        "max_young_gen_size=%" PRIu64 ", "
1883
        "young_gen_size=%" PRIu64 ", "
1884
        "old_gen_size=%" PRIu64 ", "
1885
        "total_size=%" PRIu64 "\n",
1886
2
        static_cast<uint64_t>(max_young_gen_size),
1887
2
        static_cast<uint64_t>(young_gen_size),
1888
2
        static_cast<uint64_t>(old_gen_size),
1889
1
        static_cast<uint64_t>(young_gen_size + old_gen_size));
1890
1891
1
  uint64_t available = GuessMemoryAvailableToTheProcess();
1892
  // TODO(joyeecheung): get a better estimate about the native memory
1893
  // usage into the overhead, e.g. based on the count of objects.
1894
1
  uint64_t estimated_overhead = max_young_gen_size;
1895
  Debug(env,
1896
        DebugCategory::DIAGNOSTICS,
1897
        "Estimated available memory=%" PRIu64 ", "
1898
        "estimated overhead=%" PRIu64 "\n",
1899
2
        static_cast<uint64_t>(available),
1900
1
        static_cast<uint64_t>(estimated_overhead));
1901
1902
  // This might be hit when the snapshot is being taken in another
1903
  // NearHeapLimitCallback invocation.
1904
  // When taking the snapshot, objects in the young generation may be
1905
  // promoted to the old generation, result in increased heap usage,
1906
  // but it should be no more than the young generation size.
1907
  // Ideally, this should be as small as possible - the heap limit
1908
  // can only be restored when the heap usage falls down below the
1909
  // new limit, so in a heap with unbounded growth the isolate
1910
  // may eventually crash with this new limit - effectively raising
1911
  // the heap limit to the new one.
1912
1
  if (env->is_processing_heap_limit_callback_) {
1913
    size_t new_limit = current_heap_limit + max_young_gen_size;
1914
    Debug(env,
1915
          DebugCategory::DIAGNOSTICS,
1916
          "Not generating snapshots in nested callback. "
1917
          "new_limit=%" PRIu64 "\n",
1918
          static_cast<uint64_t>(new_limit));
1919
    return new_limit;
1920
  }
1921
1922
  // Estimate whether the snapshot is going to use up all the memory
1923
  // available to the process. If so, just give up to prevent the system
1924
  // from killing the process for a system OOM.
1925
1
  if (estimated_overhead > available) {
1926
    Debug(env,
1927
          DebugCategory::DIAGNOSTICS,
1928
          "Not generating snapshots because it's too risky.\n");
1929
    env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1930
                                                initial_heap_limit);
1931
    // The new limit must be higher than current_heap_limit or V8 might
1932
    // crash.
1933
    return current_heap_limit + 1;
1934
  }
1935
1936
  // Take the snapshot synchronously.
1937
1
  env->is_processing_heap_limit_callback_ = true;
1938
1939
2
  std::string dir = env->options()->diagnostic_dir;
1940
1
  if (dir.empty()) {
1941
1
    dir = env->GetCwd();
1942
  }
1943
2
  DiagnosticFilename name(env, "Heap", "heapsnapshot");
1944
1
  std::string filename = dir + kPathSeparator + (*name);
1945
1946
1
  Debug(env, DebugCategory::DIAGNOSTICS, "Start generating %s...\n", *name);
1947
1948
  // Remove the callback first in case it's triggered when generating
1949
  // the snapshot.
1950
1
  env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1951
                                              initial_heap_limit);
1952
1953
1
  heap::WriteSnapshot(env, filename.c_str());
1954
1
  env->heap_limit_snapshot_taken_ += 1;
1955
1956
  // Don't take more snapshots than the number specified by
1957
  // --heapsnapshot-near-heap-limit.
1958
2
  if (env->heap_limit_snapshot_taken_ <
1959
1
      env->options_->heap_snapshot_near_heap_limit) {
1960
    env->isolate()->AddNearHeapLimitCallback(NearHeapLimitCallback, env);
1961
  }
1962
1963
1
  FPrintF(stderr, "Wrote snapshot to %s\n", filename.c_str());
1964
  // Tell V8 to reset the heap limit once the heap usage falls down to
1965
  // 95% of the initial limit.
1966
1
  env->isolate()->AutomaticallyRestoreInitialHeapLimit(0.95);
1967
1968
1
  env->is_processing_heap_limit_callback_ = false;
1969
1970
  // The new limit must be higher than current_heap_limit or V8 might
1971
  // crash.
1972
1
  return current_heap_limit + 1;
1973
}
1974
1975
24
inline size_t Environment::SelfSize() const {
1976
24
  size_t size = sizeof(*this);
1977
  // Remove non pointer fields that will be tracked in MemoryInfo()
1978
  // TODO(joyeecheung): refactor the MemoryTracker interface so
1979
  // this can be done for common types within the Track* calls automatically
1980
  // if a certain scope is entered.
1981
24
  size -= sizeof(async_hooks_);
1982
24
  size -= sizeof(tick_info_);
1983
24
  size -= sizeof(immediate_info_);
1984
24
  return size;
1985
}
1986
1987
24
void Environment::MemoryInfo(MemoryTracker* tracker) const {
1988
  // Iteratable STLs have their own sizes subtracted from the parent
1989
  // by default.
1990
24
  tracker->TrackField("isolate_data", isolate_data_);
1991
24
  tracker->TrackField("native_modules_with_cache", native_modules_with_cache);
1992
24
  tracker->TrackField("native_modules_without_cache",
1993
24
                      native_modules_without_cache);
1994
24
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
1995
24
  tracker->TrackField("exec_argv", exec_argv_);
1996
24
  tracker->TrackField("exiting", exiting_);
1997
24
  tracker->TrackField("should_abort_on_uncaught_toggle",
1998
24
                      should_abort_on_uncaught_toggle_);
1999
24
  tracker->TrackField("stream_base_state", stream_base_state_);
2000
24
  tracker->TrackFieldWithSize(
2001
24
      "cleanup_hooks", cleanup_hooks_.size() * sizeof(CleanupHookCallback));
2002
24
  tracker->TrackField("async_hooks", async_hooks_);
2003
24
  tracker->TrackField("immediate_info", immediate_info_);
2004
24
  tracker->TrackField("tick_info", tick_info_);
2005
2006
#define V(PropertyName, TypeName)                                              \
2007
  tracker->TrackField(#PropertyName, PropertyName());
2008
24
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
2009
#undef V
2010
2011
  // FIXME(joyeecheung): track other fields in Environment.
2012
  // Currently MemoryTracker is unable to track these
2013
  // correctly:
2014
  // - Internal types that do not implement MemoryRetainer yet
2015
  // - STL containers with MemoryRetainer* inside
2016
  // - STL containers with numeric types inside that should not have their
2017
  //   nodes elided e.g. numeric keys in maps.
2018
  // We also need to make sure that when we add a non-pointer field as its own
2019
  // node, we shift its sizeof() size out of the Environment node.
2020
24
}
2021
2022
699761
void Environment::RunWeakRefCleanup() {
2023
699761
  isolate()->ClearKeptObjects();
2024
699761
}
2025
2026
// Not really any better place than env.cc at this moment.
2027
1415260
BaseObject::BaseObject(Environment* env, Local<Object> object)
2028
2830520
    : persistent_handle_(env->isolate(), object), env_(env) {
2029
1415260
  CHECK_EQ(false, object.IsEmpty());
2030
1415260
  CHECK_GT(object->InternalFieldCount(), 0);
2031
1415260
  object->SetAlignedPointerInInternalField(BaseObject::kSlot,
2032
                                           static_cast<void*>(this));
2033
1415260
  env->AddCleanupHook(DeleteMe, static_cast<void*>(this));
2034
1415260
  env->modify_base_object_count(1);
2035
1415260
}
2036
2037

7752296
BaseObject::~BaseObject() {
2038
2808706
  env()->modify_base_object_count(-1);
2039
2808706
  env()->RemoveCleanupHook(DeleteMe, static_cast<void*>(this));
2040
2041
2808706
  if (UNLIKELY(has_pointer_data())) {
2042
364642
    PointerData* metadata = pointer_data();
2043
364642
    CHECK_EQ(metadata->strong_ptr_count, 0);
2044
364642
    metadata->self = nullptr;
2045
364642
    if (metadata->weak_ptr_count == 0) delete metadata;
2046
  }
2047
2048
2808706
  if (persistent_handle_.IsEmpty()) {
2049
    // This most likely happened because the weak callback below cleared it.
2050
2134884
    return;
2051
  }
2052
2053
  {
2054
673822
    HandleScope handle_scope(env()->isolate());
2055
1347644
    object()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2056
  }
2057
}
2058
2059
1212138
void BaseObject::MakeWeak() {
2060
1212138
  if (has_pointer_data()) {
2061
42646
    pointer_data()->wants_weak_jsobj = true;
2062
42646
    if (pointer_data()->strong_ptr_count > 0) return;
2063
  }
2064
2065
2424274
  persistent_handle_.SetWeak(
2066
      this,
2067
1067441
      [](const WeakCallbackInfo<BaseObject>& data) {
2068
1067441
        BaseObject* obj = data.GetParameter();
2069
        // Clear the persistent handle so that ~BaseObject() doesn't attempt
2070
        // to mess with internal fields, since the JS object may have
2071
        // transitioned into an invalid state.
2072
        // Refs: https://github.com/nodejs/node/issues/18897
2073
1067441
        obj->persistent_handle_.Reset();
2074

1067441
        CHECK_IMPLIES(obj->has_pointer_data(),
2075
                      obj->pointer_data()->strong_ptr_count == 0);
2076
1067441
        obj->OnGCCollect();
2077
1067441
      },
2078
      WeakCallbackType::kParameter);
2079
}
2080
2081
23541
void BaseObject::LazilyInitializedJSTemplateConstructor(
2082
    const FunctionCallbackInfo<Value>& args) {
2083
  DCHECK(args.IsConstructCall());
2084
  DCHECK_GT(args.This()->InternalFieldCount(), 0);
2085
23541
  args.This()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2086
23541
}
2087
2088
21235
Local<FunctionTemplate> BaseObject::MakeLazilyInitializedJSTemplate(
2089
    Environment* env) {
2090
  Local<FunctionTemplate> t = NewFunctionTemplate(
2091
21235
      env->isolate(), LazilyInitializedJSTemplateConstructor);
2092
21235
  t->Inherit(BaseObject::GetConstructorTemplate(env));
2093
42470
  t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
2094
21235
  return t;
2095
}
2096
2097
2890788
BaseObject::PointerData* BaseObject::pointer_data() {
2098
2890788
  if (!has_pointer_data()) {
2099
184540
    PointerData* metadata = new PointerData();
2100
184540
    metadata->wants_weak_jsobj = persistent_handle_.IsWeak();
2101
184540
    metadata->self = this;
2102
184540
    pointer_data_ = metadata;
2103
  }
2104
2890788
  CHECK(has_pointer_data());
2105
2890788
  return pointer_data_;
2106
}
2107
2108
743348
void BaseObject::decrease_refcount() {
2109
743348
  CHECK(has_pointer_data());
2110
743348
  PointerData* metadata = pointer_data();
2111
743348
  CHECK_GT(metadata->strong_ptr_count, 0);
2112
743348
  unsigned int new_refcount = --metadata->strong_ptr_count;
2113
743348
  if (new_refcount == 0) {
2114
249477
    if (metadata->is_detached) {
2115
176419
      OnGCCollect();
2116

73058
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
2117
42645
      MakeWeak();
2118
    }
2119
  }
2120
743348
}
2121
2122
745658
void BaseObject::increase_refcount() {
2123
745658
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2124

745658
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2125
251682
    persistent_handle_.ClearWeak();
2126
745658
}
2127
2128
143582
void BaseObject::DeleteMe(void* data) {
2129
143582
  BaseObject* self = static_cast<BaseObject*>(data);
2130

148622
  if (self->has_pointer_data() &&
2131
5040
      self->pointer_data()->strong_ptr_count > 0) {
2132
826
    return self->Detach();
2133
  }
2134
142756
  delete self;
2135
}
2136
2137
486
bool BaseObject::IsDoneInitializing() const { return true; }
2138
2139
542
Local<Object> BaseObject::WrappedObject() const {
2140
542
  return object();
2141
}
2142
2143
1084
bool BaseObject::IsRootNode() const {
2144
2168
  return !persistent_handle_.IsWeak();
2145
}
2146
2147
55068
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
2148
55068
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
2149
55068
  if (tmpl.IsEmpty()) {
2150
781
    tmpl = NewFunctionTemplate(env->isolate(), nullptr);
2151
781
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
2152
781
    env->set_base_object_ctor_template(tmpl);
2153
  }
2154
55068
  return tmpl;
2155
}
2156
2157
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2158
  return IsWeakOrDetached();
2159
}
2160
2161
}  // namespace node