GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 966 1051 91.9 %
Date: 2022-08-05 04:16:08 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
796016
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
796016
  if (fields_[kCheck] > 0) {
93
796012
    CHECK_GE(async_id, -1);
94
796012
    CHECK_GE(trigger_async_id, -1);
95
  }
96
97
796016
  uint32_t offset = fields_[kStackLength];
98
796016
  if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack();
99
796016
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
100
796016
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
101
796016
  fields_[kStackLength] += 1;
102
796016
  async_id_fields_[kExecutionAsyncId] = async_id;
103
796016
  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
796016
  if (!resource.IsEmpty()) {
113
796012
    native_execution_async_resources_.resize(offset + 1);
114
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
115
796012
    native_execution_async_resources_[offset] = resource;
116
  }
117
796016
}
118
119
// Remember to keep this code aligned with popAsyncContext() in JS.
120
795615
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
795615
  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
1589112
  if (UNLIKELY(fields_[kCheck] > 0 &&
128

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

1589108
             !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
794554
    native_execution_async_resources_.resize(offset);
146
794554
    if (native_execution_async_resources_.size() <
147

1026627
            native_execution_async_resources_.capacity() / 2 &&
148
232073
        native_execution_async_resources_.size() > 16) {
149
      native_execution_async_resources_.shrink_to_fit();
150
    }
151
  }
152
153
1589108
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
154
31355
    HandleScope handle_scope(env()->isolate());
155
62710
    USE(js_execution_async_resources()->Set(
156
        env()->context(),
157
        env()->length_string(),
158
125420
        Integer::NewFromUnsigned(env()->isolate(), offset)));
159
  }
160
161
794554
  return fields_[kStackLength] > 0;
162
}
163
164
3316
void AsyncHooks::clear_async_id_stack() {
165
3316
  Isolate* isolate = env()->isolate();
166
3316
  HandleScope handle_scope(isolate);
167
3316
  if (!js_execution_async_resources_.IsEmpty()) {
168
4022
    USE(PersistentToLocal::Strong(js_execution_async_resources_)
169
4022
            ->Set(env()->context(),
170
                  env()->length_string(),
171
8044
                  Integer::NewFromUnsigned(isolate, 0)));
172
  }
173
3316
  native_execution_async_resources_.clear();
174
3316
  native_execution_async_resources_.shrink_to_fit();
175
176
3316
  async_id_fields_[kExecutionAsyncId] = 0;
177
3316
  async_id_fields_[kTriggerAsyncId] = 0;
178
3316
  fields_[kStackLength] = 0;
179
3316
}
180
181
7238
void AsyncHooks::AddContext(Local<Context> ctx) {
182
21714
  ctx->SetPromiseHooks(js_promise_hooks_[0].IsEmpty()
183
7238
                           ? Local<Function>()
184
205
                           : PersistentToLocal::Strong(js_promise_hooks_[0]),
185
7238
                       js_promise_hooks_[1].IsEmpty()
186
7238
                           ? Local<Function>()
187
205
                           : PersistentToLocal::Strong(js_promise_hooks_[1]),
188
7238
                       js_promise_hooks_[2].IsEmpty()
189
7238
                           ? Local<Function>()
190
205
                           : PersistentToLocal::Strong(js_promise_hooks_[2]),
191
7238
                       js_promise_hooks_[3].IsEmpty()
192
7238
                           ? Local<Function>()
193
                           : PersistentToLocal::Strong(js_promise_hooks_[3]));
194
195
7238
  size_t id = contexts_.size();
196
7238
  contexts_.resize(id + 1);
197
7238
  contexts_[id].Reset(env()->isolate(), ctx);
198
7238
  contexts_[id].SetWeak();
199
7238
}
200
201
514
void AsyncHooks::RemoveContext(Local<Context> ctx) {
202
514
  Isolate* isolate = env()->isolate();
203
1028
  HandleScope handle_scope(isolate);
204
514
  contexts_.erase(std::remove_if(contexts_.begin(),
205
                                 contexts_.end(),
206
3898
                                 [&](auto&& el) { return el.IsEmpty(); }),
207
1028
                  contexts_.end());
208
3835
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
209
3321
    Local<Context> saved_context = PersistentToLocal::Weak(isolate, *it);
210
3321
    if (saved_context == ctx) {
211
      it->Reset();
212
      contexts_.erase(it);
213
      break;
214
    }
215
  }
216
514
}
217
218
245437
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
219
245437
    Environment* env, double default_trigger_async_id)
220
245437
    : async_hooks_(env->async_hooks()) {
221
245437
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
222
245437
    CHECK_GE(default_trigger_async_id, 0);
223
  }
224
225
245437
  old_default_trigger_async_id_ =
226
245437
      async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
227
245437
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
228
245437
      default_trigger_async_id;
229
245437
}
230
231
490872
AsyncHooks::DefaultTriggerAsyncIdScope::~DefaultTriggerAsyncIdScope() {
232
245436
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
245436
      old_default_trigger_async_id_;
234
245436
}
235
236
245437
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
237
245437
    AsyncWrap* async_wrap)
238
    : DefaultTriggerAsyncIdScope(async_wrap->env(),
239
245437
                                 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
5307
void IsolateData::DeserializeProperties(const IsolateDataSerializeInfo* info) {
307
5307
  size_t i = 0;
308
5307
  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




100833
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
325






132675
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
326









































































































































2924157
  PER_ISOLATE_STRING_PROPERTIES(VS)
327
#undef V
328
#undef VY
329
#undef VS
330
#undef VP
331
332
313113
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
333
    MaybeLocal<String> maybe_field =
334
615612
        isolate_->GetDataFromSnapshotOnce<String>(info->primitive_values[i++]);
335
    Local<String> field;
336
307806
    if (!maybe_field.ToLocal(&field)) {
337
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
338
    }
339
307806
    async_wrap_providers_[j].Set(isolate_, field);
340
  }
341
342
5307
  const std::vector<PropInfo>& values = info->template_values;
343
5307
  i = 0;  // index to the array
344
5307
  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








































































206973
  PER_ISOLATE_TEMPLATE_PROPERTIES(V);
365
#undef V
366
5307
}
367
368
1316
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
1316
  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
13160
  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
17108
  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
363216
  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
77644
  NODE_ASYNC_PROVIDER_TYPES(V)
429
#undef V
430
431
  // TODO(legendecas): eagerly create per isolate templates.
432
1316
}
433
434
6623
IsolateData::IsolateData(Isolate* isolate,
435
                         uv_loop_t* event_loop,
436
                         MultiIsolatePlatform* platform,
437
                         ArrayBufferAllocator* node_allocator,
438
6623
                         const IsolateDataSerializeInfo* isolate_data_info)
439
    : isolate_(isolate),
440
      event_loop_(event_loop),
441
48
      node_allocator_(node_allocator == nullptr ? nullptr
442
6575
                                                : node_allocator->GetImpl()),
443
13246
      platform_(platform) {
444
6623
  options_.reset(
445
6623
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
446
447
6623
  if (isolate_data_info == nullptr) {
448
1316
    CreateProperties();
449
  } else {
450
5307
    DeserializeProperties(isolate_data_info);
451
  }
452
6623
}
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
122
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
474

122
  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
64
    return;
482
  }
483
484
111
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
485
111
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
486
487
111
  Isolate* isolate = env_->isolate();
488
111
  HandleScope handle_scope(isolate);
489
111
  Local<Function> cb = env_->trace_category_state_function();
490
111
  if (cb.IsEmpty())
491
53
    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
7238
void Environment::AssignToContext(Local<v8::Context> context,
499
                                  const ContextInfo& info) {
500
7238
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
501
                                           this);
502
  // Used by Environment::GetCurrent to know that we are on a node context.
503
7238
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kContextTag,
504
                                           Environment::kNodeContextTagPtr);
505
  // Used to retrieve bindings
506
14476
  context->SetAlignedPointerInEmbedderData(
507
7238
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
508
509
#if HAVE_INSPECTOR
510
7238
  inspector_agent()->ContextCreated(context, info);
511
#endif  // HAVE_INSPECTOR
512
513
7238
  this->async_hooks()->AddContext(context);
514
7238
}
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
2947
void Environment::add_refs(int64_t diff) {
543
2947
  task_queues_async_refs_ += diff;
544
2947
  CHECK_GE(task_queues_async_refs_, 0);
545
2947
  if (task_queues_async_refs_ == 0)
546
196
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
547
  else
548
2751
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
549
2947
}
550
551
68598
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
552
137196
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
553
  std::unique_ptr<v8::BackingStore> bs =
554
68598
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
555
68598
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
556
68598
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
557
68598
  return buf;
558
}
559
560
83544
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
561
    const uv_buf_t& buf) {
562
83544
  std::unique_ptr<v8::BackingStore> bs;
563
83544
  if (buf.base != nullptr) {
564
68598
    auto it = released_allocated_buffers_.find(buf.base);
565
68598
    CHECK_NE(it, released_allocated_buffers_.end());
566
68598
    bs = std::move(it->second);
567
68598
    released_allocated_buffers_.erase(it);
568
  }
569
83544
  return bs;
570
}
571
572
1305
void Environment::CreateProperties() {
573
2610
  HandleScope handle_scope(isolate_);
574
1305
  Local<Context> ctx = context();
575
576
  {
577
1305
    Context::Scope context_scope(ctx);
578
1305
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
579
2610
    templ->InstanceTemplate()->SetInternalFieldCount(
580
        BaseObject::kInternalFieldCount);
581
1305
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
582
583
1305
    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
2610
      GetPerContextExports(ctx).ToLocalChecked();
589
  Local<Value> primordials =
590
3915
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
591
1305
  CHECK(primordials->IsObject());
592
1305
  set_primordials(primordials.As<Object>());
593
594
  Local<String> prototype_string =
595
1305
      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

7830
  V(primordials_safe_map_prototype_object, "SafeMap");
612

7830
  V(primordials_safe_set_prototype_object, "SafeSet");
613

7830
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
614

7830
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
615
#undef V
616
617
  Local<Object> process_object =
618
1305
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
619
1305
  set_process_object(process_object);
620
1305
}
621
622
6612
std::string GetExecPath(const std::vector<std::string>& argv) {
623
  char exec_path_buf[2 * PATH_MAX];
624
6612
  size_t exec_path_len = sizeof(exec_path_buf);
625
6612
  std::string exec_path;
626
6612
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
627
6612
    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
6612
  return exec_path;
646
}
647
648
6612
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
6612
                         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
6612
      timer_base_(uv_now(isolate_data->event_loop())),
661
      exec_argv_(exec_args),
662
      argv_(args),
663
      exec_path_(GetExecPath(args)),
664
6612
      exiting_(isolate_, 1, MAYBE_FIELD_PTR(env_info, exiting)),
665
      should_abort_on_uncaught_toggle_(
666
6612
          isolate_,
667
          1,
668
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
669
6612
      stream_base_state_(isolate_,
670
                         StreamBase::kNumStreamBaseStateFields,
671
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
672
6612
      time_origin_(PERFORMANCE_NOW()),
673
6612
      time_origin_timestamp_(GetCurrentTimeInMicroseconds()),
674
      flags_(flags),
675
6612
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
676
6612
                     ? AllocateEnvironmentThreadId().id
677



26448
                     : thread_id.id) {
678
  // We'll be creating new objects so make sure we've entered the context.
679
13224
  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
6612
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
684
10722
    flags_ = flags_ |
685
5361
        EnvironmentFlags::kOwnsProcessState |
686
        EnvironmentFlags::kOwnsInspector;
687
  }
688
689
6612
  set_env_vars(per_process::system_environment);
690
6612
  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
13224
  options_ = std::make_shared<EnvironmentOptions>(
697
19836
      *isolate_data->options()->per_env);
698
6612
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
699
6612
      options_->debug_options().host_port);
700
701
6612
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
702
1251
    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
6612
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
708
#endif
709
710
6612
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
711
6612
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
712
6612
    if (TracingController* tracing_controller = writer->GetTracingController())
713
6564
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
714
  }
715
716
6612
  destroy_async_id_list_.reserve(512);
717
718
6612
  performance_state_ = std::make_unique<performance::PerformanceState>(
719
6612
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
720
721
6612
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
722
6612
          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
6612
}
737
738
1305
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
1305
                         ThreadId thread_id)
745
    : Environment(isolate_data,
746
                  context->GetIsolate(),
747
                  args,
748
                  exec_args,
749
                  env_info,
750
                  flags,
751
1305
                  thread_id) {
752
1305
  InitializeMainContext(context, env_info);
753
1305
}
754
755
6612
void Environment::InitializeMainContext(Local<Context> context,
756
                                        const EnvSerializeInfo* env_info) {
757
6612
  context_.Reset(context->GetIsolate(), context);
758
6612
  AssignToContext(context, ContextInfo(""));
759
6612
  if (env_info != nullptr) {
760
5307
    DeserializeProperties(env_info);
761
  } else {
762
1305
    CreateProperties();
763
  }
764
765
6612
  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
6612
  should_abort_on_uncaught_toggle_[0] = 1;
771
772
  // The process is not exiting by default.
773
6612
  set_exiting(false);
774
775
6612
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
776
                           time_origin_);
777
6612
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
778
                           per_process::node_start_time);
779
780
6612
  if (per_process::v8_initialized) {
781
6564
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
782
                            performance::performance_v8_start);
783
  }
784
6612
}
785
786
802928
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
5992
  CHECK(is_stopping());
814
815
5992
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
816
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
817
                                          0);
818
  }
819
820
5992
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
821
      BuildEmbedderGraph, this);
822
823
11984
  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
5992
  inspector_agent_.reset();
829
#endif
830
831
11984
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
832
                                             nullptr);
833
834
5992
  if (trace_state_observer_) {
835
5992
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
836
5992
    CHECK_NOT_NULL(writer);
837
5992
    if (TracingController* tracing_controller = writer->GetTracingController())
838
5946
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
839
  }
840
841

10704
  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
5992
  if (!is_main_thread()) {
850
    // Dereference all addons that were loaded into this environment.
851
1262
    for (binding::DLib& addon : loaded_addons_) {
852
14
      addon.Close();
853
    }
854
  }
855
856
5992
  CHECK_EQ(base_object_count_, 0);
857
5992
}
858
859
6579
void Environment::InitializeLibuv() {
860
13158
  HandleScope handle_scope(isolate());
861
6579
  Context::Scope context_scope(context());
862
863
6579
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
864
6579
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
865
866
6579
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
867
6579
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
868
869
6579
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
870
871
6579
  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
6579
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
878
6579
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
879
880
30531
  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
6579
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
891
6579
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
892
6579
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
893
894
  {
895
13158
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
896
6579
    task_queues_async_initialized_ = true;
897

13158
    if (native_immediates_threadsafe_.size() > 0 ||
898
6579
        native_immediates_interrupts_.size() > 0) {
899
5303
      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
6579
  RegisterHandleCleanups();
908
909
6579
  StartProfilerIdleNotifier();
910
6579
}
911
912
825
void Environment::ExitEnv() {
913
825
  set_can_call_into_js(false);
914
825
  set_stopping(true);
915
825
  isolate_->TerminateExecution();
916
1650
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
917
825
}
918
919
6579
void Environment::RegisterHandleCleanups() {
920
6579
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
921
35754
                                        void* arg) {
922
35754
    handle->data = env;
923
924
35754
    env->CloseHandle(handle, [](uv_handle_t* handle) {
925
#ifdef DEBUG
926
      memset(handle, 0xab, uv_handle_size(handle->type));
927
#endif
928
35754
    });
929
35754
  };
930
931
39474
  auto register_handle = [&](uv_handle_t* handle) {
932
39474
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
933
46053
  };
934
6579
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
935
6579
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
936
6579
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
937
6579
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
938
6579
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
939
6579
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
940
6579
}
941
942
11978
void Environment::CleanupHandles() {
943
  {
944
11978
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
945
11978
    task_queues_async_initialized_ = false;
946
  }
947
948
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
949
23956
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
950
951
11978
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
952
953
12763
  for (ReqWrapBase* request : req_wrap_queue_)
954
785
    request->Cancel();
955
956
17320
  for (HandleWrap* handle : handle_wrap_queue_)
957
10684
    handle->Close();
958
959
47732
  for (HandleCleanup& hc : handle_cleanup_queue_)
960
35754
    hc.cb_(this, hc.handle_, hc.arg_);
961
11978
  handle_cleanup_queue_.clear();
962
963
10735
  while (handle_cleanup_waiting_ != 0 ||
964

34693
         request_waiting_ != 0 ||
965
11980
         !handle_wrap_queue_.IsEmpty()) {
966
10735
    uv_run(event_loop(), UV_RUN_ONCE);
967
  }
968
11978
}
969
970
6579
void Environment::StartProfilerIdleNotifier() {
971
6579
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
972
189194
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
973
189194
    env->isolate()->SetIdle(true);
974
189194
  });
975
6579
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
976
188921
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
977
188921
    env->isolate()->SetIdle(false);
978
188921
  });
979
6579
}
980
981
731534
void Environment::PrintSyncTrace() const {
982
731534
  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
5165
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
994
5165
  EscapableHandleScope handle_scope(isolate());
995
10330
  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
10330
  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
5992
void Environment::RunCleanup() {
1014
5992
  started_cleanup_ = true;
1015

16697
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1016
5992
  bindings_.clear();
1017
5992
  CleanupHandles();
1018
1019
17972
  while (!cleanup_hooks_.empty() ||
1020
11986
         native_immediates_.size() > 0 ||
1021

23964
         native_immediates_threadsafe_.size() > 0 ||
1022
5992
         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
11972
        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
5986
    std::sort(callbacks.begin(), callbacks.end(),
1030
1151591
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1031
      // Sort in descending order so that the most recently inserted callbacks
1032
      // are run first.
1033
1151591
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1034
    });
1035
1036
177623
    for (const CleanupHookCallback& cb : callbacks) {
1037
171637
      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
1188
        continue;
1041
      }
1042
1043
170449
      cb.fn_(cb.arg_);
1044
170449
      cleanup_hooks_.erase(cb);
1045
    }
1046
5986
    CleanupHandles();
1047
  }
1048
1049
5995
  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
5992
}
1055
1056
6703
void Environment::RunAtExitCallbacks() {
1057

18719
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1058
19893
  for (ExitCallback at_exit : at_exit_functions_) {
1059
13190
    at_exit.cb_(at_exit.arg_);
1060
  }
1061
6703
  at_exit_functions_.clear();
1062
6703
}
1063
1064
13214
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1065
13214
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1066
13214
}
1067
1068
232245
void Environment::RunAndClearInterrupts() {
1069
232245
  while (native_immediates_interrupts_.size() > 0) {
1070
12002
    NativeImmediateQueue queue;
1071
    {
1072
24004
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1073
12002
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1074
    }
1075
12002
    DebugSealHandleScope seal_handle_scope(isolate());
1076
1077
24016
    while (auto head = queue.Shift())
1078
24028
      head->Call(this);
1079
  }
1080
220243
}
1081
1082
208885
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1083

422776
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1084
               "RunAndClearNativeImmediates");
1085
417764
  HandleScope handle_scope(isolate_);
1086
417764
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
1087
1088
208885
  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
208885
  RunAndClearInterrupts();
1093
1094
417768
  auto drain_list = [&](NativeImmediateQueue* queue) {
1095
835530
    TryCatchScope try_catch(this);
1096
417768
    DebugSealHandleScope seal_handle_scope(isolate());
1097
479523
    while (auto head = queue->Shift()) {
1098
61762
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1099
61762
      if (is_refed)
1100
37016
        ref_count++;
1101
1102

61762
      if (is_refed || !only_refed)
1103
61521
        head->Call(this);
1104
1105
61757
      head.reset();  // Destroy now so that this is also observed by try_catch.
1106
1107
61757
      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
61755
    }
1114
417761
    return false;
1115
208885
  };
1116
208885
  while (drain_list(&native_immediates_)) {}
1117
1118
208882
  immediate_info()->ref_count_dec(ref_count);
1119
1120
208882
  if (immediate_info()->ref_count() == 0)
1121
163162
    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
208879
  NativeImmediateQueue threadsafe_immediates;
1131
208882
  if (native_immediates_threadsafe_.size() > 0) {
1132
4102
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1133
2051
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1134
  }
1135
208883
  while (drain_list(&threadsafe_immediates)) {}
1136
208879
}
1137
1138
12019
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
12019
  Environment** interrupt_data = new Environment*(this);
1151
12019
  Environment** dummy = nullptr;
1152
12019
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1153
757
    delete interrupt_data;
1154
757
    return;  // Already scheduled.
1155
  }
1156
1157
11262
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1158
11253
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1159
11253
    Environment* env = *env_ptr;
1160
11253
    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
11243
    env->interrupt_data_.store(nullptr);
1167
11243
    env->RunAndClearInterrupts();
1168
  }, interrupt_data);
1169
}
1170
1171
9835
void Environment::ScheduleTimer(int64_t duration_ms) {
1172
9835
  if (started_cleanup_) return;
1173
9835
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1174
}
1175
1176
3670
void Environment::ToggleTimerRef(bool ref) {
1177
3670
  if (started_cleanup_) return;
1178
1179
3670
  if (ref) {
1180
2406
    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
7674
void Environment::RunTimers(uv_timer_t* handle) {
1187
7674
  Environment* env = Environment::from_timer_handle(handle);
1188

8196
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1189
1190
7674
  if (!env->can_call_into_js())
1191
    return;
1192
1193
7674
  HandleScope handle_scope(env->isolate());
1194
7674
  Context::Scope context_scope(env->context());
1195
1196
7674
  Local<Object> process = env->process_object();
1197
7674
  InternalCallbackScope scope(env, process, {0, 0});
1198
1199
7674
  Local<Function> cb = env->timers_callback_function();
1200
  MaybeLocal<Value> ret;
1201
7674
  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
7707
    TryCatchScope try_catch(env);
1207
7707
    try_catch.SetVerbose(true);
1208
7707
    ret = cb->Call(env->context(), process, 1, &arg);
1209

7697
  } 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
7664
  if (ret.IsEmpty())
1217
8
    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
7656
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1228
1229
7656
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1230
1231
7656
  if (expiry_ms != 0) {
1232
    int64_t duration_ms =
1233
6695
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1234
1235
6695
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1236
1237
6695
    if (expiry_ms > 0)
1238
6021
      uv_ref(h);
1239
    else
1240
674
      uv_unref(h);
1241
  } else {
1242
961
    uv_unref(h);
1243
  }
1244
}
1245
1246
1247
188921
void Environment::CheckImmediate(uv_check_t* handle) {
1248
188921
  Environment* env = Environment::from_immediate_check_handle(handle);
1249

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

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

45339
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
1267
1268
44387
  if (env->immediate_info()->ref_count() == 0)
1269
5392
    env->ToggleImmediateRef(false);
1270
}
1271
1272
236196
void Environment::ToggleImmediateRef(bool ref) {
1273
236196
  if (started_cleanup_) return;
1274
1275
224679
  if (ref) {
1276
    // Idle handle is needed only to stop the event loop from blocking in poll.
1277
67618
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
1278
  } else {
1279
157061
    uv_idle_stop(immediate_idle_handle());
1280
  }
1281
}
1282
1283
1284
47170
Local<Value> Environment::GetNow() {
1285
47170
  uv_update_time(event_loop());
1286
47170
  uint64_t now = uv_now(event_loop());
1287
47170
  CHECK_GE(now, timer_base());
1288
47170
  now -= timer_base();
1289
47170
  if (now <= 0xffffffff)
1290
94340
    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
6612
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1356
6612
    : 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
5307
void ImmediateInfo::Deserialize(Local<Context> context) {
1364
5307
  fields_.Deserialize(context);
1365
5307
}
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
5307
void TickInfo::Deserialize(Local<Context> context) {
1383
5307
  fields_.Deserialize(context);
1384
5307
}
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
6612
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1397
    : fields_(
1398
6612
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1399
1400
6612
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

6612
      info_(info) {
1406
13224
  HandleScope handle_scope(isolate);
1407
6612
  if (info == nullptr) {
1408
1305
    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
1305
    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
1305
    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
1305
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1426
  }
1427
6612
}
1428
1429
5307
void AsyncHooks::Deserialize(Local<Context> context) {
1430
5307
  async_ids_stack_.Deserialize(context);
1431
5307
  fields_.Deserialize(context);
1432
5307
  async_id_fields_.Deserialize(context);
1433
1434
  Local<Array> js_execution_async_resources;
1435
5307
  if (info_->js_execution_async_resources != 0) {
1436
    js_execution_async_resources =
1437
5307
        context->GetDataFromSnapshotOnce<Array>(
1438
15921
            info_->js_execution_async_resources).ToLocalChecked();
1439
  } else {
1440
    js_execution_async_resources = Array::New(context->GetIsolate());
1441
  }
1442
5307
  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
5307
  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
5307
  info_ = nullptr;
1458
5307
}
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
694
void Environment::Exit(int exit_code) {
1540
694
  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
694
  process_exit_handler_(this, exit_code);
1559
79
}
1560
1561
6634
void Environment::stop_sub_worker_contexts() {
1562
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1563
1564
6634
  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
6607
}
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
68493
void Environment::AddUnmanagedFd(int fd) {
1578
68493
  if (!tracks_unmanaged_fds()) return;
1579
4991
  auto result = unmanaged_fds_.insert(fd);
1580
4991
  if (!result.second) {
1581
    ProcessEmitWarning(
1582
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1583
  }
1584
}
1585
1586
68114
void Environment::RemoveUnmanagedFd(int fd) {
1587
68114
  if (!tracks_unmanaged_fds()) return;
1588
4988
  size_t removed_count = unmanaged_fds_.erase(fd);
1589
4988
  if (removed_count == 0) {
1590
    ProcessEmitWarning(
1591
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1592
  }
1593
}
1594
1595
5147
void Environment::PrintInfoForSnapshotIfDebug() {
1596
5147
  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
5147
}
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
5147
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
5147
  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
21228
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1744
                                            Local<Object> holder,
1745
                                            int index,
1746
                                            InternalFieldInfo* info) {
1747
42456
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1748
21228
  deserialize_requests_.push_back(std::move(request));
1749
21228
}
1750
1751
5307
void Environment::RunDeserializeRequests() {
1752
10614
  HandleScope scope(isolate());
1753
5307
  Local<Context> ctx = context();
1754
5307
  Isolate* is = isolate();
1755
26535
  while (!deserialize_requests_.empty()) {
1756
42456
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1757
21228
    deserialize_requests_.pop_front();
1758
21228
    Local<Object> holder = request.holder.Get(is);
1759
21228
    request.cb(ctx, holder, request.index, request.info);
1760
    request.holder.Reset();
1761
21228
    request.info->Delete();
1762
  }
1763
5307
}
1764
1765
5307
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1766
5307
  Local<Context> ctx = context();
1767
1768
5307
  RunDeserializeRequests();
1769
1770
5307
  native_modules_in_snapshot = info->native_modules;
1771
5307
  async_hooks_.Deserialize(ctx);
1772
5307
  immediate_info_.Deserialize(ctx);
1773
5307
  tick_info_.Deserialize(ctx);
1774
5307
  performance_state_->Deserialize(ctx);
1775
5307
  exiting_.Deserialize(ctx);
1776
5307
  stream_base_state_.Deserialize(ctx);
1777
5307
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1778
1779
5307
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1780
    fprintf(stderr, "deserializing...\n");
1781
    std::cerr << *info << "\n";
1782
  }
1783
1784
5307
  const std::vector<PropInfo>& values = info->persistent_values;
1785
5307
  size_t i = 0;  // index to the array
1786
5307
  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
































































































































546621
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1807
#undef V
1808
1809
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1810
10614
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1811
  Local<Context> ctx_from_snapshot;
1812
5307
  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
5307
  CHECK_EQ(ctx_from_snapshot, ctx);
1817
5307
}
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
717811
void Environment::RunWeakRefCleanup() {
2023
717811
  isolate()->ClearKeptObjects();
2024
717811
}
2025
2026
// Not really any better place than env.cc at this moment.
2027
1440543
BaseObject::BaseObject(Environment* env, Local<Object> object)
2028
2881086
    : persistent_handle_(env->isolate(), object), env_(env) {
2029
1440543
  CHECK_EQ(false, object.IsEmpty());
2030
1440543
  CHECK_GT(object->InternalFieldCount(), 0);
2031
1440543
  object->SetAlignedPointerInInternalField(BaseObject::kSlot,
2032
                                           static_cast<void*>(this));
2033
1440543
  env->AddCleanupHook(DeleteMe, static_cast<void*>(this));
2034
1440543
  env->modify_base_object_count(1);
2035
1440543
}
2036
2037

7852488
BaseObject::~BaseObject() {
2038
2855756
  env()->modify_base_object_count(-1);
2039
2855756
  env()->RemoveCleanupHook(DeleteMe, static_cast<void*>(this));
2040
2041
2855756
  if (UNLIKELY(has_pointer_data())) {
2042
386732
    PointerData* metadata = pointer_data();
2043
386732
    CHECK_EQ(metadata->strong_ptr_count, 0);
2044
386732
    metadata->self = nullptr;
2045
386732
    if (metadata->weak_ptr_count == 0) delete metadata;
2046
  }
2047
2048
2855756
  if (persistent_handle_.IsEmpty()) {
2049
    // This most likely happened because the weak callback below cleared it.
2050
2140976
    return;
2051
  }
2052
2053
  {
2054
714780
    HandleScope handle_scope(env()->isolate());
2055
1429560
    object()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2056
  }
2057
}
2058
2059
1226284
void BaseObject::MakeWeak() {
2060
1226284
  if (has_pointer_data()) {
2061
45579
    pointer_data()->wants_weak_jsobj = true;
2062
45579
    if (pointer_data()->strong_ptr_count > 0) return;
2063
  }
2064
2065
2452566
  persistent_handle_.SetWeak(
2066
      this,
2067
1070487
      [](const WeakCallbackInfo<BaseObject>& data) {
2068
1070487
        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
1070487
        obj->persistent_handle_.Reset();
2074

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

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

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

162897
  if (self->has_pointer_data() &&
2131
7900
      self->pointer_data()->strong_ptr_count > 0) {
2132
3440
    return self->Detach();
2133
  }
2134
151557
  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
69380
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
2148
69380
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
2149
69380
  if (tmpl.IsEmpty()) {
2150
1305
    tmpl = NewFunctionTemplate(env->isolate(), nullptr);
2151
1305
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
2152
1305
    env->set_base_object_ctor_template(tmpl);
2153
  }
2154
69380
  return tmpl;
2155
}
2156
2157
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2158
  return IsWeakOrDetached();
2159
}
2160
2161
}  // namespace node