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

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

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

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


















336
  PER_ISOLATE_TEMPLATE_PROPERTIES(V)
312
#undef V
313
314
6
  return info;
315
}
316
317
5293
void IsolateData::DeserializeProperties(const IsolateDataSerializeInfo* info) {
318
5293
  size_t i = 0;
319
5293
  HandleScope handle_scope(isolate_);
320
321
#define VP(PropertyName, StringValue) V(Private, PropertyName)
322
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
323
#define VS(PropertyName, StringValue) V(String, PropertyName)
324
#define V(TypeName, PropertyName)                                              \
325
  do {                                                                         \
326
    MaybeLocal<TypeName> maybe_field =                                         \
327
        isolate_->GetDataFromSnapshotOnce<TypeName>(                           \
328
            info->primitive_values[i++]);                                      \
329
    Local<TypeName> field;                                                     \
330
    if (!maybe_field.ToLocal(&field)) {                                        \
331
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
332
    }                                                                          \
333
    PropertyName##_.Set(isolate_, field);                                      \
334
  } while (0);
335




100567
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
336






132325
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
337









































































































































2916443
  PER_ISOLATE_STRING_PROPERTIES(VS)
338
#undef V
339
#undef VY
340
#undef VS
341
#undef VP
342
343
312287
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
344
    MaybeLocal<String> maybe_field =
345
613988
        isolate_->GetDataFromSnapshotOnce<String>(info->primitive_values[i++]);
346
    Local<String> field;
347
306994
    if (!maybe_field.ToLocal(&field)) {
348
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
349
    }
350
306994
    async_wrap_providers_[j].Set(isolate_, field);
351
  }
352
353
5293
  const std::vector<PropInfo>& values = info->template_values;
354
5293
  i = 0;  // index to the array
355
5293
  size_t id = 0;
356
#define V(PropertyName, TypeName)                                              \
357
  do {                                                                         \
358
    if (values.size() > i && id == values[i].id) {                             \
359
      const PropInfo& d = values[i];                                           \
360
      DCHECK_EQ(d.name, #PropertyName);                                        \
361
      MaybeLocal<TypeName> maybe_field =                                       \
362
          isolate_->GetDataFromSnapshotOnce<TypeName>(d.index);                \
363
      Local<TypeName> field;                                                   \
364
      if (!maybe_field.ToLocal(&field)) {                                      \
365
        fprintf(stderr,                                                        \
366
                "Failed to deserialize isolate data template " #PropertyName   \
367
                "\n");                                                         \
368
      }                                                                        \
369
      set_##PropertyName(field);                                               \
370
      i++;                                                                     \
371
    }                                                                          \
372
    id++;                                                                      \
373
  } while (0);
374
375








































































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

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

7818
  V(primordials_safe_map_prototype_object, "SafeMap");
623

7818
  V(primordials_safe_set_prototype_object, "SafeSet");
624

7818
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
625

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



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

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

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

13124
    if (native_immediates_threadsafe_.size() > 0 ||
909
6562
        native_immediates_interrupts_.size() > 0) {
910
5288
      uv_async_send(&task_queues_async_);
911
    }
912
  }
913
914
  // Register clean-up cb to be called to clean up the handles
915
  // when the environment is freed, note that they are not cleaned in
916
  // the one environment per process setup, but will be called in
917
  // FreeEnvironment.
918
6562
  RegisterHandleCleanups();
919
920
6562
  StartProfilerIdleNotifier();
921
6562
}
922
923
828
void Environment::ExitEnv() {
924
828
  set_can_call_into_js(false);
925
828
  set_stopping(true);
926
828
  isolate_->TerminateExecution();
927
1656
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
928
828
}
929
930
6562
void Environment::RegisterHandleCleanups() {
931
6562
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
932
36228
                                        void* arg) {
933
36228
    handle->data = env;
934
935
36228
    env->CloseHandle(handle, [](uv_handle_t* handle) {
936
#ifdef DEBUG
937
      memset(handle, 0xab, uv_handle_size(handle->type));
938
#endif
939
36228
    });
940
36228
  };
941
942
39372
  auto register_handle = [&](uv_handle_t* handle) {
943
39372
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
944
45934
  };
945
6562
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
946
6562
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
947
6562
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
948
6562
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
949
6562
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
950
6562
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
951
6562
}
952
953
12137
void Environment::CleanupHandles() {
954
  {
955
12137
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
956
12137
    task_queues_async_initialized_ = false;
957
  }
958
959
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
960
24274
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
961
962
12137
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
963
964
12913
  for (ReqWrapBase* request : req_wrap_queue_)
965
776
    request->Cancel();
966
967
17473
  for (HandleWrap* handle : handle_wrap_queue_)
968
10672
    handle->Close();
969
970
48365
  for (HandleCleanup& hc : handle_cleanup_queue_)
971
36228
    hc.cb_(this, hc.handle_, hc.arg_);
972
12137
  handle_cleanup_queue_.clear();
973
974
10896
  while (handle_cleanup_waiting_ != 0 ||
975

35172
         request_waiting_ != 0 ||
976
12139
         !handle_wrap_queue_.IsEmpty()) {
977
10896
    uv_run(event_loop(), UV_RUN_ONCE);
978
  }
979
12137
}
980
981
6562
void Environment::StartProfilerIdleNotifier() {
982
6562
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
983
190850
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
984
190850
    env->isolate()->SetIdle(true);
985
190850
  });
986
6562
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
987
190666
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
988
190666
    env->isolate()->SetIdle(false);
989
190666
  });
990
6562
}
991
992
731038
void Environment::PrintSyncTrace() const {
993
731038
  if (!trace_sync_io_) return;
994
995
2
  HandleScope handle_scope(isolate());
996
997
1
  fprintf(
998
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
999
1
  PrintStackTrace(isolate(),
1000
                  StackTrace::CurrentStackTrace(
1001
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
1002
}
1003
1004
5242
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
1005
5242
  EscapableHandleScope handle_scope(isolate());
1006
10484
  if (!snapshot_serialize_callback().IsEmpty()) {
1007
    Context::Scope context_scope(context());
1008
    return handle_scope.EscapeMaybe(snapshot_serialize_callback()->Call(
1009
        context(), v8::Undefined(isolate()), 0, nullptr));
1010
  }
1011
10484
  return handle_scope.Escape(Undefined(isolate()));
1012
}
1013
1014
MaybeLocal<Value> Environment::RunSnapshotDeserializeMain() const {
1015
  EscapableHandleScope handle_scope(isolate());
1016
  if (!snapshot_deserialize_main().IsEmpty()) {
1017
    Context::Scope context_scope(context());
1018
    return handle_scope.EscapeMaybe(snapshot_deserialize_main()->Call(
1019
        context(), v8::Undefined(isolate()), 0, nullptr));
1020
  }
1021
  return handle_scope.Escape(Undefined(isolate()));
1022
}
1023
1024
6072
void Environment::RunCleanup() {
1025
6072
  started_cleanup_ = true;
1026

16937
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1027
6072
  bindings_.clear();
1028
6072
  CleanupHandles();
1029
1030
18211
  while (!cleanup_hooks_.empty() ||
1031
12146
         native_immediates_.size() > 0 ||
1032

24283
         native_immediates_threadsafe_.size() > 0 ||
1033
6072
         native_immediates_interrupts_.size() > 0) {
1034
    // Copy into a vector, since we can't sort an unordered_set in-place.
1035
    std::vector<CleanupHookCallback> callbacks(
1036
12130
        cleanup_hooks_.begin(), cleanup_hooks_.end());
1037
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
1038
    // need to be able to check whether they were un-scheduled by another hook.
1039
1040
6065
    std::sort(callbacks.begin(), callbacks.end(),
1041
1269723
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1042
      // Sort in descending order so that the most recently inserted callbacks
1043
      // are run first.
1044
1269723
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1045
    });
1046
1047
193638
    for (const CleanupHookCallback& cb : callbacks) {
1048
187573
      if (cleanup_hooks_.count(cb) == 0) {
1049
        // This hook was removed from the `cleanup_hooks_` set during another
1050
        // hook that was run earlier. Nothing to do here.
1051
1193
        continue;
1052
      }
1053
1054
186380
      cb.fn_(cb.arg_);
1055
186380
      cleanup_hooks_.erase(cb);
1056
    }
1057
6065
    CleanupHandles();
1058
  }
1059
1060
6075
  for (const int fd : unmanaged_fds_) {
1061
    uv_fs_t close_req;
1062
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
1063
3
    uv_fs_req_cleanup(&close_req);
1064
  }
1065
6072
}
1066
1067
6688
void Environment::RunAtExitCallbacks() {
1068

18673
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1069
19846
  for (ExitCallback at_exit : at_exit_functions_) {
1070
13158
    at_exit.cb_(at_exit.arg_);
1071
  }
1072
6688
  at_exit_functions_.clear();
1073
6688
}
1074
1075
13182
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1076
13182
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1077
13182
}
1078
1079
233721
void Environment::RunAndClearInterrupts() {
1080
233721
  while (native_immediates_interrupts_.size() > 0) {
1081
11818
    NativeImmediateQueue queue;
1082
    {
1083
23636
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1084
11818
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1085
    }
1086
11818
    DebugSealHandleScope seal_handle_scope(isolate());
1087
1088
23645
    while (auto head = queue.Shift())
1089
23654
      head->Call(this);
1090
  }
1091
221903
}
1092
1093
210681
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1094

426360
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1095
               "RunAndClearNativeImmediates");
1096
421356
  HandleScope handle_scope(isolate_);
1097
421356
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
1098
1099
210681
  size_t ref_count = 0;
1100
1101
  // Handle interrupts first. These functions are not allowed to throw
1102
  // exceptions, so we do not need to handle that.
1103
210681
  RunAndClearInterrupts();
1104
1105
421360
  auto drain_list = [&](NativeImmediateQueue* queue) {
1106
842714
    TryCatchScope try_catch(this);
1107
421360
    DebugSealHandleScope seal_handle_scope(isolate());
1108
483173
    while (auto head = queue->Shift()) {
1109
61820
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1110
61820
      if (is_refed)
1111
36889
        ref_count++;
1112
1113

61820
      if (is_refed || !only_refed)
1114
61575
        head->Call(this);
1115
1116
61815
      head.reset();  // Destroy now so that this is also observed by try_catch.
1117
1118
61815
      if (UNLIKELY(try_catch.HasCaught())) {
1119

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

9839
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1200
1201
9322
  if (!env->can_call_into_js())
1202
    return;
1203
1204
9322
  HandleScope handle_scope(env->isolate());
1205
9322
  Context::Scope context_scope(env->context());
1206
1207
9322
  Local<Object> process = env->process_object();
1208
9322
  InternalCallbackScope scope(env, process, {0, 0});
1209
1210
9322
  Local<Function> cb = env->timers_callback_function();
1211
  MaybeLocal<Value> ret;
1212
9322
  Local<Value> arg = env->GetNow();
1213
  // This code will loop until all currently due timers will process. It is
1214
  // impossible for us to end up in an infinite loop due to how the JS-side
1215
  // is structured.
1216
32
  do {
1217
9354
    TryCatchScope try_catch(env);
1218
9354
    try_catch.SetVerbose(true);
1219
9354
    ret = cb->Call(env->context(), process, 1, &arg);
1220

9344
  } while (ret.IsEmpty() && env->can_call_into_js());
1221
1222
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
1223
  // is reset back to `true` after being previously set to `false` then this
1224
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
1225
  // timers corruption will occur and all timers behaviour will become
1226
  // entirely unpredictable.
1227
9312
  if (ret.IsEmpty())
1228
9
    return;
1229
1230
  // To allow for less JS-C++ boundary crossing, the value returned from JS
1231
  // serves a few purposes:
1232
  // 1. If it's 0, no more timers exist and the handle should be unrefed
1233
  // 2. If it's > 0, the value represents the next timer's expiry and there
1234
  //    is at least one timer remaining that is refed.
1235
  // 3. If it's < 0, the absolute value represents the next timer's expiry
1236
  //    and there are no timers that are refed.
1237
  int64_t expiry_ms =
1238
9303
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1239
1240
9303
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1241
1242
9303
  if (expiry_ms != 0) {
1243
    int64_t duration_ms =
1244
8347
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1245
1246
8347
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1247
1248
8347
    if (expiry_ms > 0)
1249
7456
      uv_ref(h);
1250
    else
1251
891
      uv_unref(h);
1252
  } else {
1253
956
    uv_unref(h);
1254
  }
1255
}
1256
1257
1258
190666
void Environment::CheckImmediate(uv_check_t* handle) {
1259
190666
  Environment* env = Environment::from_immediate_check_handle(handle);
1260

193678
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1261
1262
190666
  HandleScope scope(env->isolate());
1263
190666
  Context::Scope context_scope(env->context());
1264
1265
190666
  env->RunAndClearNativeImmediates();
1266
1267

190666
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1268
146874
    return;
1269
1270
951
  do {
1271
44735
    MakeCallback(env->isolate(),
1272
                 env->process_object(),
1273
                 env->immediate_callback_function(),
1274
                 0,
1275
                 nullptr,
1276
44743
                 {0, 0}).ToLocalChecked();
1277

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

28
  if (!object->IsObject() || errorno == 0)
1353
    return;
1354
1355
28
  Local<Object> obj = object.As<Object>();
1356
28
  const char* err_string = uv_err_name(errorno);
1357
1358

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

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

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
































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
































































































































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

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

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

1071456
        CHECK_IMPLIES(obj->has_pointer_data(),
2069
                      obj->pointer_data()->strong_ptr_count == 0);
2070
1071456
        obj->OnGCCollect();
2071
1071456
      },
2072
      WeakCallbackType::kParameter);
2073
}
2074
2075
23767
void BaseObject::LazilyInitializedJSTemplateConstructor(
2076
    const FunctionCallbackInfo<Value>& args) {
2077
  DCHECK(args.IsConstructCall());
2078
  DCHECK_GT(args.This()->InternalFieldCount(), 0);
2079
23767
  args.This()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2080
23767
}
2081
2082
23450
Local<FunctionTemplate> BaseObject::MakeLazilyInitializedJSTemplate(
2083
    Environment* env) {
2084
  Local<FunctionTemplate> t = NewFunctionTemplate(
2085
23450
      env->isolate(), LazilyInitializedJSTemplateConstructor);
2086
23450
  t->Inherit(BaseObject::GetConstructorTemplate(env));
2087
46900
  t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
2088
23450
  return t;
2089
}
2090
2091
3028833
BaseObject::PointerData* BaseObject::pointer_data() {
2092
3028833
  if (!has_pointer_data()) {
2093
195050
    PointerData* metadata = new PointerData();
2094
195050
    metadata->wants_weak_jsobj = persistent_handle_.IsWeak();
2095
195050
    metadata->self = this;
2096
195050
    pointer_data_ = metadata;
2097
  }
2098
3028833
  CHECK(has_pointer_data());
2099
3028833
  return pointer_data_;
2100
}
2101
2102
775260
void BaseObject::decrease_refcount() {
2103
775260
  CHECK(has_pointer_data());
2104
775260
  PointerData* metadata = pointer_data();
2105
775260
  CHECK_GT(metadata->strong_ptr_count, 0);
2106
775260
  unsigned int new_refcount = --metadata->strong_ptr_count;
2107
775260
  if (new_refcount == 0) {
2108
263471
    if (metadata->is_detached) {
2109
186612
      OnGCCollect();
2110

76859
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
2111
45419
      MakeWeak();
2112
    }
2113
  }
2114
775260
}
2115
2116
777537
void BaseObject::increase_refcount() {
2117
777537
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2118

777537
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2119
265644
    persistent_handle_.ClearWeak();
2120
777537
}
2121
2122
170886
void BaseObject::DeleteMe(void* data) {
2123
170886
  BaseObject* self = static_cast<BaseObject*>(data);
2124

178796
  if (self->has_pointer_data() &&
2125
7910
      self->pointer_data()->strong_ptr_count > 0) {
2126
3448
    return self->Detach();
2127
  }
2128
167438
  delete self;
2129
}
2130
2131
530
bool BaseObject::IsDoneInitializing() const { return true; }
2132
2133
586
Local<Object> BaseObject::WrappedObject() const {
2134
586
  return object();
2135
}
2136
2137
1172
bool BaseObject::IsRootNode() const {
2138
2344
  return !persistent_handle_.IsWeak();
2139
}
2140
2141
69244
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
2142
69244
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
2143
69244
  if (tmpl.IsEmpty()) {
2144
1303
    tmpl = NewFunctionTemplate(env->isolate(), nullptr);
2145
1303
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
2146
1303
    env->set_base_object_ctor_template(tmpl);
2147
  }
2148
69244
  return tmpl;
2149
}
2150
2151
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2152
  return IsWeakOrDetached();
2153
}
2154
2155
}  // namespace node