GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 1023 1108 92.3 %
Date: 2022-07-31 04:16:25 Branches: 1142 2106 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
15594
void AsyncHooks::SetJSPromiseHooks(Local<Function> init,
69
                                   Local<Function> before,
70
                                   Local<Function> after,
71
                                   Local<Function> resolve) {
72
15594
  js_promise_hooks_[0].Reset(env()->isolate(), init);
73
15594
  js_promise_hooks_[1].Reset(env()->isolate(), before);
74
15594
  js_promise_hooks_[2].Reset(env()->isolate(), after);
75
15594
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
76
31533
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
77
15939
    if (it->IsEmpty()) {
78
      contexts_.erase(it--);
79
      continue;
80
    }
81
31878
    PersistentToLocal::Weak(env()->isolate(), *it)
82
15939
        ->SetPromiseHooks(init, before, after, resolve);
83
  }
84
15594
}
85
86
// Remember to keep this code aligned with pushAsyncContext() in JS.
87
787160
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
787160
  if (fields_[kCheck] > 0) {
93
787156
    CHECK_GE(async_id, -1);
94
787156
    CHECK_GE(trigger_async_id, -1);
95
  }
96
97
787160
  uint32_t offset = fields_[kStackLength];
98
787160
  if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack();
99
787160
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
100
787160
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
101
787160
  fields_[kStackLength] += 1;
102
787160
  async_id_fields_[kExecutionAsyncId] = async_id;
103
787160
  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
787160
  if (!resource.IsEmpty()) {
113
787156
    native_execution_async_resources_.resize(offset + 1);
114
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
115
787156
    native_execution_async_resources_[offset] = resource;
116
  }
117
787160
}
118
119
// Remember to keep this code aligned with popAsyncContext() in JS.
120
786753
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
786753
  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
1571392
  if (UNLIKELY(fields_[kCheck] > 0 &&
128

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

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

1018769
            native_execution_async_resources_.capacity() / 2 &&
148
233075
        native_execution_async_resources_.size() > 16) {
149
      native_execution_async_resources_.shrink_to_fit();
150
    }
151
  }
152
153
1571388
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
154
27546
    HandleScope handle_scope(env()->isolate());
155
55092
    USE(js_execution_async_resources()->Set(
156
        env()->context(),
157
        env()->length_string(),
158
110184
        Integer::NewFromUnsigned(env()->isolate(), offset)));
159
  }
160
161
785694
  return fields_[kStackLength] > 0;
162
}
163
164
3328
void AsyncHooks::clear_async_id_stack() {
165
3328
  Isolate* isolate = env()->isolate();
166
3328
  HandleScope handle_scope(isolate);
167
3328
  if (!js_execution_async_resources_.IsEmpty()) {
168
4050
    USE(PersistentToLocal::Strong(js_execution_async_resources_)
169
4050
            ->Set(env()->context(),
170
                  env()->length_string(),
171
8100
                  Integer::NewFromUnsigned(isolate, 0)));
172
  }
173
3328
  native_execution_async_resources_.clear();
174
3328
  native_execution_async_resources_.shrink_to_fit();
175
176
3328
  async_id_fields_[kExecutionAsyncId] = 0;
177
3328
  async_id_fields_[kTriggerAsyncId] = 0;
178
3328
  fields_[kStackLength] = 0;
179
3328
}
180
181
7201
void AsyncHooks::AddContext(Local<Context> ctx) {
182
21603
  ctx->SetPromiseHooks(js_promise_hooks_[0].IsEmpty()
183
7201
                           ? Local<Function>()
184
205
                           : PersistentToLocal::Strong(js_promise_hooks_[0]),
185
7201
                       js_promise_hooks_[1].IsEmpty()
186
7201
                           ? Local<Function>()
187
205
                           : PersistentToLocal::Strong(js_promise_hooks_[1]),
188
7201
                       js_promise_hooks_[2].IsEmpty()
189
7201
                           ? Local<Function>()
190
205
                           : PersistentToLocal::Strong(js_promise_hooks_[2]),
191
7201
                       js_promise_hooks_[3].IsEmpty()
192
7201
                           ? Local<Function>()
193
                           : PersistentToLocal::Strong(js_promise_hooks_[3]));
194
195
7201
  size_t id = contexts_.size();
196
7201
  contexts_.resize(id + 1);
197
7201
  contexts_[id].Reset(env()->isolate(), ctx);
198
7201
  contexts_[id].SetWeak();
199
7201
}
200
201
504
void AsyncHooks::RemoveContext(Local<Context> ctx) {
202
504
  Isolate* isolate = env()->isolate();
203
1008
  HandleScope handle_scope(isolate);
204
504
  contexts_.erase(std::remove_if(contexts_.begin(),
205
                                 contexts_.end(),
206
3650
                                 [&](auto&& el) { return el.IsEmpty(); }),
207
1008
                  contexts_.end());
208
3587
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
209
3083
    Local<Context> saved_context = PersistentToLocal::Weak(isolate, *it);
210
3083
    if (saved_context == ctx) {
211
      it->Reset();
212
      contexts_.erase(it);
213
      break;
214
    }
215
  }
216
504
}
217
218
245412
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
219
245412
    Environment* env, double default_trigger_async_id)
220
245412
    : async_hooks_(env->async_hooks()) {
221
245412
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
222
245412
    CHECK_GE(default_trigger_async_id, 0);
223
  }
224
225
245412
  old_default_trigger_async_id_ =
226
245412
      async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
227
245412
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
228
245412
      default_trigger_async_id;
229
245412
}
230
231
490822
AsyncHooks::DefaultTriggerAsyncIdScope::~DefaultTriggerAsyncIdScope() {
232
245411
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
245411
      old_default_trigger_async_id_;
234
245411
}
235
236
245412
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
237
245412
    AsyncWrap* async_wrap)
238
    : DefaultTriggerAsyncIdScope(async_wrap->env(),
239
245412
                                 async_wrap->get_async_id()) {}
240
241
12
std::ostream& operator<<(std::ostream& output,
242
                         const std::vector<SnapshotIndex>& v) {
243
12
  output << "{ ";
244
2130
  for (const SnapshotIndex i : v) {
245
2118
    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
54
  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
5282
void IsolateData::DeserializeProperties(const IsolateDataSerializeInfo* info) {
318
5282
  size_t i = 0;
319
5282
  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




89794
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
336






132050
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
337









































































































































2910382
  PER_ISOLATE_STRING_PROPERTIES(VS)
338
#undef V
339
#undef VY
340
#undef VS
341
#undef VP
342
343
311638
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
344
    MaybeLocal<String> maybe_field =
345
612712
        isolate_->GetDataFromSnapshotOnce<String>(info->primitive_values[i++]);
346
    Local<String> field;
347
306356
    if (!maybe_field.ToLocal(&field)) {
348
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
349
    }
350
306356
    async_wrap_providers_[j].Set(isolate_, field);
351
  }
352
353
5282
  const std::vector<PropInfo>& values = info->template_values;
354
5282
  i = 0;  // index to the array
355
5282
  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








































































205998
  PER_ISOLATE_TEMPLATE_PROPERTIES(V);
376
#undef V
377
5282
}
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
11826
  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
6596
IsolateData::IsolateData(Isolate* isolate,
446
                         uv_loop_t* event_loop,
447
                         MultiIsolatePlatform* platform,
448
                         ArrayBufferAllocator* node_allocator,
449
6596
                         const IsolateDataSerializeInfo* isolate_data_info)
450
    : isolate_(isolate),
451
      event_loop_(event_loop),
452
47
      node_allocator_(node_allocator == nullptr ? nullptr
453
6549
                                                : node_allocator->GetImpl()),
454
13192
      platform_(platform) {
455
6596
  options_.reset(
456
6596
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
457
458
6596
  if (isolate_data_info == nullptr) {
459
1314
    CreateProperties();
460
  } else {
461
5282
    DeserializeProperties(isolate_data_info);
462
  }
463
6596
}
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
7201
void Environment::AssignToContext(Local<v8::Context> context,
510
                                  const ContextInfo& info) {
511
7201
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
512
                                           this);
513
  // Used by Environment::GetCurrent to know that we are on a node context.
514
7201
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kContextTag,
515
                                           Environment::kNodeContextTagPtr);
516
  // Used to retrieve bindings
517
14402
  context->SetAlignedPointerInEmbedderData(
518
7201
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
519
520
#if HAVE_INSPECTOR
521
7201
  inspector_agent()->ContextCreated(context, info);
522
#endif  // HAVE_INSPECTOR
523
524
7201
  this->async_hooks()->AddContext(context);
525
7201
}
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
68322
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
563
136644
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
564
  std::unique_ptr<v8::BackingStore> bs =
565
68322
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
566
68322
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
567
68322
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
568
68322
  return buf;
569
}
570
571
83213
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
572
    const uv_buf_t& buf) {
573
83213
  std::unique_ptr<v8::BackingStore> bs;
574
83213
  if (buf.base != nullptr) {
575
68322
    auto it = released_allocated_buffers_.find(buf.base);
576
68322
    CHECK_NE(it, released_allocated_buffers_.end());
577
68322
    bs = std::move(it->second);
578
68322
    released_allocated_buffers_.erase(it);
579
  }
580
83213
  return bs;
581
}
582
583
1475220
Local<v8::FunctionTemplate> Environment::NewFunctionTemplate(
584
    v8::FunctionCallback callback,
585
    Local<v8::Signature> signature,
586
    v8::ConstructorBehavior behavior,
587
    v8::SideEffectType side_effect_type,
588
    const v8::CFunction* c_function) {
589
  return v8::FunctionTemplate::New(isolate(),
590
                                   callback,
591
                                   Local<v8::Value>(),
592
                                   signature,
593
                                   0,
594
                                   behavior,
595
                                   side_effect_type,
596
1475220
                                   c_function);
597
}
598
599
377063
void Environment::SetMethod(Local<v8::Object> that,
600
                            const char* name,
601
                            v8::FunctionCallback callback) {
602
377063
  Local<v8::Context> context = isolate()->GetCurrentContext();
603
  Local<v8::Function> function =
604
377063
      NewFunctionTemplate(callback,
605
                          Local<v8::Signature>(),
606
                          v8::ConstructorBehavior::kThrow,
607
377063
                          v8::SideEffectType::kHasSideEffect)
608
377063
          ->GetFunction(context)
609
377063
          .ToLocalChecked();
610
  // kInternalized strings are created in the old space.
611
377063
  const v8::NewStringType type = v8::NewStringType::kInternalized;
612
  Local<v8::String> name_string =
613
754126
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
614
754126
  that->Set(context, name_string, function).Check();
615
377063
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
616
377063
}
617
618
2606
void Environment::SetFastMethod(Local<v8::Object> that,
619
                                const char* name,
620
                                v8::FunctionCallback slow_callback,
621
                                const v8::CFunction* c_function) {
622
2606
  Local<v8::Context> context = isolate()->GetCurrentContext();
623
  Local<v8::Function> function =
624
2606
      NewFunctionTemplate(slow_callback,
625
                          Local<v8::Signature>(),
626
                          v8::ConstructorBehavior::kThrow,
627
                          v8::SideEffectType::kHasNoSideEffect,
628
2606
                          c_function)
629
2606
          ->GetFunction(context)
630
2606
          .ToLocalChecked();
631
2606
  const v8::NewStringType type = v8::NewStringType::kInternalized;
632
  Local<v8::String> name_string =
633
5212
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
634
2606
  that->Set(context, name_string, function).Check();
635
2606
}
636
637
113541
void Environment::SetMethodNoSideEffect(Local<v8::Object> that,
638
                                        const char* name,
639
                                        v8::FunctionCallback callback) {
640
113541
  Local<v8::Context> context = isolate()->GetCurrentContext();
641
  Local<v8::Function> function =
642
113541
      NewFunctionTemplate(callback,
643
                          Local<v8::Signature>(),
644
                          v8::ConstructorBehavior::kThrow,
645
113541
                          v8::SideEffectType::kHasNoSideEffect)
646
113541
          ->GetFunction(context)
647
113541
          .ToLocalChecked();
648
  // kInternalized strings are created in the old space.
649
113541
  const v8::NewStringType type = v8::NewStringType::kInternalized;
650
  Local<v8::String> name_string =
651
227082
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
652
227082
  that->Set(context, name_string, function).Check();
653
113541
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
654
113541
}
655
656
675220
void Environment::SetProtoMethod(Local<v8::FunctionTemplate> that,
657
                                 const char* name,
658
                                 v8::FunctionCallback callback) {
659
675220
  Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
660
  Local<v8::FunctionTemplate> t =
661
      NewFunctionTemplate(callback,
662
                          signature,
663
                          v8::ConstructorBehavior::kThrow,
664
675220
                          v8::SideEffectType::kHasSideEffect);
665
  // kInternalized strings are created in the old space.
666
675220
  const v8::NewStringType type = v8::NewStringType::kInternalized;
667
  Local<v8::String> name_string =
668
1350440
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
669
1350440
  that->PrototypeTemplate()->Set(name_string, t);
670
675220
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
671
675220
}
672
673
98496
void Environment::SetProtoMethodNoSideEffect(Local<v8::FunctionTemplate> that,
674
                                             const char* name,
675
                                             v8::FunctionCallback callback) {
676
98496
  Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
677
  Local<v8::FunctionTemplate> t =
678
      NewFunctionTemplate(callback,
679
                          signature,
680
                          v8::ConstructorBehavior::kThrow,
681
98496
                          v8::SideEffectType::kHasNoSideEffect);
682
  // kInternalized strings are created in the old space.
683
98496
  const v8::NewStringType type = v8::NewStringType::kInternalized;
684
  Local<v8::String> name_string =
685
196992
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
686
196992
  that->PrototypeTemplate()->Set(name_string, t);
687
98496
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
688
98496
}
689
690
33
void Environment::SetInstanceMethod(Local<v8::FunctionTemplate> that,
691
                                    const char* name,
692
                                    v8::FunctionCallback callback) {
693
33
  Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
694
  Local<v8::FunctionTemplate> t =
695
      NewFunctionTemplate(callback,
696
                          signature,
697
                          v8::ConstructorBehavior::kThrow,
698
33
                          v8::SideEffectType::kHasSideEffect);
699
  // kInternalized strings are created in the old space.
700
33
  const v8::NewStringType type = v8::NewStringType::kInternalized;
701
  Local<v8::String> name_string =
702
66
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
703
66
  that->InstanceTemplate()->Set(name_string, t);
704
33
  t->SetClassName(name_string);
705
33
}
706
707
134567
void Environment::SetConstructorFunction(Local<v8::Object> that,
708
                                         const char* name,
709
                                         Local<v8::FunctionTemplate> tmpl,
710
                                         SetConstructorFunctionFlag flag) {
711
134567
  SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag);
712
134567
}
713
714
141082
void Environment::SetConstructorFunction(Local<v8::Object> that,
715
                                         Local<v8::String> name,
716
                                         Local<v8::FunctionTemplate> tmpl,
717
                                         SetConstructorFunctionFlag flag) {
718
141082
  if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
719
126679
    tmpl->SetClassName(name);
720
282164
  that->Set(context(), name, tmpl->GetFunction(context()).ToLocalChecked())
721
      .Check();
722
141082
}
723
724
1303
void Environment::CreateProperties() {
725
2606
  HandleScope handle_scope(isolate_);
726
1303
  Local<Context> ctx = context();
727
728
  {
729
1303
    Context::Scope context_scope(ctx);
730
1303
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
731
2606
    templ->InstanceTemplate()->SetInternalFieldCount(
732
        BaseObject::kInternalFieldCount);
733
1303
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
734
735
1303
    set_binding_data_ctor_template(templ);
736
  }
737
738
  // Store primordials setup by the per-context script in the environment.
739
  Local<Object> per_context_bindings =
740
2606
      GetPerContextExports(ctx).ToLocalChecked();
741
  Local<Value> primordials =
742
3909
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
743
1303
  CHECK(primordials->IsObject());
744
1303
  set_primordials(primordials.As<Object>());
745
746
  Local<String> prototype_string =
747
1303
      FIXED_ONE_BYTE_STRING(isolate(), "prototype");
748
749
#define V(EnvPropertyName, PrimordialsPropertyName)                            \
750
  {                                                                            \
751
    Local<Value> ctor =                                                        \
752
        primordials.As<Object>()                                               \
753
            ->Get(ctx,                                                         \
754
                  FIXED_ONE_BYTE_STRING(isolate(), PrimordialsPropertyName))   \
755
            .ToLocalChecked();                                                 \
756
    CHECK(ctor->IsObject());                                                   \
757
    Local<Value> prototype =                                                   \
758
        ctor.As<Object>()->Get(ctx, prototype_string).ToLocalChecked();        \
759
    CHECK(prototype->IsObject());                                              \
760
    set_##EnvPropertyName(prototype.As<Object>());                             \
761
  }
762
763

7818
  V(primordials_safe_map_prototype_object, "SafeMap");
764

7818
  V(primordials_safe_set_prototype_object, "SafeSet");
765

7818
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
766

7818
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
767
#undef V
768
769
  Local<Object> process_object =
770
1303
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
771
1303
  set_process_object(process_object);
772
1303
}
773
774
6585
std::string GetExecPath(const std::vector<std::string>& argv) {
775
  char exec_path_buf[2 * PATH_MAX];
776
6585
  size_t exec_path_len = sizeof(exec_path_buf);
777
6585
  std::string exec_path;
778
6585
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
779
6585
    exec_path = std::string(exec_path_buf, exec_path_len);
780
  } else {
781
    exec_path = argv[0];
782
  }
783
784
  // On OpenBSD process.execPath will be relative unless we
785
  // get the full path before process.execPath is used.
786
#if defined(__OpenBSD__)
787
  uv_fs_t req;
788
  req.ptr = nullptr;
789
  if (0 ==
790
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
791
    CHECK_NOT_NULL(req.ptr);
792
    exec_path = std::string(static_cast<char*>(req.ptr));
793
  }
794
  uv_fs_req_cleanup(&req);
795
#endif
796
797
6585
  return exec_path;
798
}
799
800
6585
Environment::Environment(IsolateData* isolate_data,
801
                         Isolate* isolate,
802
                         const std::vector<std::string>& args,
803
                         const std::vector<std::string>& exec_args,
804
                         const EnvSerializeInfo* env_info,
805
                         EnvironmentFlags::Flags flags,
806
6585
                         ThreadId thread_id)
807
    : isolate_(isolate),
808
      isolate_data_(isolate_data),
809
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
810
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
811
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
812
6585
      timer_base_(uv_now(isolate_data->event_loop())),
813
      exec_argv_(exec_args),
814
      argv_(args),
815
      exec_path_(GetExecPath(args)),
816
      should_abort_on_uncaught_toggle_(
817
6585
          isolate_,
818
          1,
819
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
820
6585
      stream_base_state_(isolate_,
821
                         StreamBase::kNumStreamBaseStateFields,
822
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
823
6585
      time_origin_(PERFORMANCE_NOW()),
824
6585
      time_origin_timestamp_(GetCurrentTimeInMicroseconds()),
825
      flags_(flags),
826
6585
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
827
6585
                     ? AllocateEnvironmentThreadId().id
828



26340
                     : thread_id.id) {
829
  // We'll be creating new objects so make sure we've entered the context.
830
13170
  HandleScope handle_scope(isolate);
831
832
  // Set some flags if only kDefaultFlags was passed. This can make API version
833
  // transitions easier for embedders.
834
6585
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
835
10670
    flags_ = flags_ |
836
5335
        EnvironmentFlags::kOwnsProcessState |
837
        EnvironmentFlags::kOwnsInspector;
838
  }
839
840
6585
  set_env_vars(per_process::system_environment);
841
6585
  enabled_debug_list_.Parse(env_vars(), isolate);
842
843
  // We create new copies of the per-Environment option sets, so that it is
844
  // easier to modify them after Environment creation. The defaults are
845
  // part of the per-Isolate option set, for which in turn the defaults are
846
  // part of the per-process option set.
847
13170
  options_ = std::make_shared<EnvironmentOptions>(
848
19755
      *isolate_data->options()->per_env);
849
6585
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
850
6585
      options_->debug_options().host_port);
851
852
6585
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
853
1250
    set_abort_on_uncaught_exception(false);
854
  }
855
856
#if HAVE_INSPECTOR
857
  // We can only create the inspector agent after having cloned the options.
858
6585
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
859
#endif
860
861
6585
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
862
6585
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
863
6585
    if (TracingController* tracing_controller = writer->GetTracingController())
864
6537
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
865
  }
866
867
6585
  destroy_async_id_list_.reserve(512);
868
869
6585
  performance_state_ = std::make_unique<performance::PerformanceState>(
870
6585
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
871
872
6585
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
873
6585
          TRACING_CATEGORY_NODE1(environment)) != 0) {
874
16
    auto traced_value = tracing::TracedValue::Create();
875
8
    traced_value->BeginArray("args");
876
18
    for (const std::string& arg : args) traced_value->AppendString(arg);
877
8
    traced_value->EndArray();
878
8
    traced_value->BeginArray("exec_args");
879
33
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
880
8
    traced_value->EndArray();
881

15
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
882
                                      "Environment",
883
                                      this,
884
                                      "args",
885
                                      std::move(traced_value));
886
  }
887
6585
}
888
889
1303
Environment::Environment(IsolateData* isolate_data,
890
                         Local<Context> context,
891
                         const std::vector<std::string>& args,
892
                         const std::vector<std::string>& exec_args,
893
                         const EnvSerializeInfo* env_info,
894
                         EnvironmentFlags::Flags flags,
895
1303
                         ThreadId thread_id)
896
    : Environment(isolate_data,
897
                  context->GetIsolate(),
898
                  args,
899
                  exec_args,
900
                  env_info,
901
                  flags,
902
1303
                  thread_id) {
903
1303
  InitializeMainContext(context, env_info);
904
1303
}
905
906
6585
void Environment::InitializeMainContext(Local<Context> context,
907
                                        const EnvSerializeInfo* env_info) {
908
6585
  context_.Reset(context->GetIsolate(), context);
909
6585
  AssignToContext(context, ContextInfo(""));
910
6585
  if (env_info != nullptr) {
911
5282
    DeserializeProperties(env_info);
912
  } else {
913
1303
    CreateProperties();
914
  }
915
916
6585
  if (!options_->force_async_hooks_checks) {
917
1
    async_hooks_.no_force_checks();
918
  }
919
920
  // By default, always abort when --abort-on-uncaught-exception was passed.
921
6585
  should_abort_on_uncaught_toggle_[0] = 1;
922
923
6585
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
924
                           time_origin_);
925
6585
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
926
                           per_process::node_start_time);
927
928
6585
  if (per_process::v8_initialized) {
929
6537
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
930
                            performance::performance_v8_start);
931
  }
932
6585
}
933
934
812308
Environment::~Environment() {
935
  if (Environment** interrupt_data = interrupt_data_.load()) {
936
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
937
    // then force V8 to run interrupts by compiling and running an empty script
938
    // so as not to leak memory.
939
10
    *interrupt_data = nullptr;
940
941
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
942
20
    HandleScope handle_scope(isolate());
943
20
    TryCatch try_catch(isolate());
944
20
    Context::Scope context_scope(context());
945
946
#ifdef DEBUG
947
    bool consistency_check = false;
948
    isolate()->RequestInterrupt([](Isolate*, void* data) {
949
      *static_cast<bool*>(data) = true;
950
    }, &consistency_check);
951
#endif
952
953
    Local<Script> script;
954
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
955
10
      USE(script->Run(context()));
956
957
    DCHECK(consistency_check);
958
  }
959
960
  // FreeEnvironment() should have set this.
961
6062
  CHECK(is_stopping());
962
963
6062
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
964
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
965
                                          0);
966
  }
967
968
6062
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
969
      BuildEmbedderGraph, this);
970
971
12124
  HandleScope handle_scope(isolate());
972
973
#if HAVE_INSPECTOR
974
  // Destroy inspector agent before erasing the context. The inspector
975
  // destructor depends on the context still being accessible.
976
6062
  inspector_agent_.reset();
977
#endif
978
979
12124
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
980
                                             nullptr);
981
982
6062
  if (trace_state_observer_) {
983
6062
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
984
6062
    CHECK_NOT_NULL(writer);
985
6062
    if (TracingController* tracing_controller = writer->GetTracingController())
986
6016
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
987
  }
988
989

10845
  TRACE_EVENT_NESTABLE_ASYNC_END0(
990
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
991
992
  // Do not unload addons on the main thread. Some addons need to retain memory
993
  // beyond the Environment's lifetime, and unloading them early would break
994
  // them; with Worker threads, we have the opportunity to be stricter.
995
  // Also, since the main thread usually stops just before the process exits,
996
  // this is far less relevant here.
997
6062
  if (!is_main_thread()) {
998
    // Dereference all addons that were loaded into this environment.
999
1261
    for (binding::DLib& addon : loaded_addons_) {
1000
14
      addon.Close();
1001
    }
1002
  }
1003
1004
6062
  CHECK_EQ(base_object_count_, 0);
1005
6062
}
1006
1007
6552
void Environment::InitializeLibuv() {
1008
13104
  HandleScope handle_scope(isolate());
1009
6552
  Context::Scope context_scope(context());
1010
1011
6552
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
1012
6552
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1013
1014
6552
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
1015
6552
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
1016
1017
6552
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
1018
1019
6552
  CHECK_EQ(0, uv_check_start(immediate_check_handle(), CheckImmediate));
1020
1021
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
1022
  // but not all samples are created equal; mark the wall clock time spent in
1023
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
1024
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
1025
6552
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
1026
6552
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
1027
1028
30444
  CHECK_EQ(0, uv_async_init(
1029
      event_loop(),
1030
      &task_queues_async_,
1031
      [](uv_async_t* async) {
1032
        Environment* env = ContainerOf(
1033
            &Environment::task_queues_async_, async);
1034
        HandleScope handle_scope(env->isolate());
1035
        Context::Scope context_scope(env->context());
1036
        env->RunAndClearNativeImmediates();
1037
      }));
1038
6552
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
1039
6552
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
1040
6552
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
1041
1042
  {
1043
13104
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1044
6552
    task_queues_async_initialized_ = true;
1045

13104
    if (native_immediates_threadsafe_.size() > 0 ||
1046
6552
        native_immediates_interrupts_.size() > 0) {
1047
5277
      uv_async_send(&task_queues_async_);
1048
    }
1049
  }
1050
1051
  // Register clean-up cb to be called to clean up the handles
1052
  // when the environment is freed, note that they are not cleaned in
1053
  // the one environment per process setup, but will be called in
1054
  // FreeEnvironment.
1055
6552
  RegisterHandleCleanups();
1056
1057
6552
  StartProfilerIdleNotifier();
1058
6552
}
1059
1060
838
void Environment::ExitEnv() {
1061
838
  set_can_call_into_js(false);
1062
838
  set_stopping(true);
1063
838
  isolate_->TerminateExecution();
1064
1676
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
1065
838
}
1066
1067
6552
void Environment::RegisterHandleCleanups() {
1068
6552
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
1069
36174
                                        void* arg) {
1070
36174
    handle->data = env;
1071
1072
36174
    env->CloseHandle(handle, [](uv_handle_t* handle) {
1073
#ifdef DEBUG
1074
      memset(handle, 0xab, uv_handle_size(handle->type));
1075
#endif
1076
36174
    });
1077
36174
  };
1078
1079
39312
  auto register_handle = [&](uv_handle_t* handle) {
1080
39312
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
1081
45864
  };
1082
6552
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
1083
6552
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
1084
6552
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
1085
6552
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
1086
6552
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
1087
6552
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
1088
6552
}
1089
1090
12118
void Environment::CleanupHandles() {
1091
  {
1092
12118
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1093
12118
    task_queues_async_initialized_ = false;
1094
  }
1095
1096
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
1097
24236
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
1098
1099
12118
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
1100
1101
12930
  for (ReqWrapBase* request : req_wrap_queue_)
1102
812
    request->Cancel();
1103
1104
17444
  for (HandleWrap* handle : handle_wrap_queue_)
1105
10652
    handle->Close();
1106
1107
48292
  for (HandleCleanup& hc : handle_cleanup_queue_)
1108
36174
    hc.cb_(this, hc.handle_, hc.arg_);
1109
12118
  handle_cleanup_queue_.clear();
1110
1111
10882
  while (handle_cleanup_waiting_ != 0 ||
1112

35120
         request_waiting_ != 0 ||
1113
12120
         !handle_wrap_queue_.IsEmpty()) {
1114
10882
    uv_run(event_loop(), UV_RUN_ONCE);
1115
  }
1116
12118
}
1117
1118
6552
void Environment::StartProfilerIdleNotifier() {
1119
6552
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
1120
185158
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
1121
185158
    env->isolate()->SetIdle(true);
1122
185158
  });
1123
6552
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
1124
184975
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
1125
184975
    env->isolate()->SetIdle(false);
1126
184975
  });
1127
6552
}
1128
1129
729460
void Environment::PrintSyncTrace() const {
1130
729460
  if (!trace_sync_io_) return;
1131
1132
2
  HandleScope handle_scope(isolate());
1133
1134
1
  fprintf(
1135
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
1136
1
  PrintStackTrace(isolate(),
1137
                  StackTrace::CurrentStackTrace(
1138
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
1139
}
1140
1141
5224
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
1142
5224
  EscapableHandleScope handle_scope(isolate());
1143
10448
  if (!snapshot_serialize_callback().IsEmpty()) {
1144
    Context::Scope context_scope(context());
1145
    return handle_scope.EscapeMaybe(snapshot_serialize_callback()->Call(
1146
        context(), v8::Undefined(isolate()), 0, nullptr));
1147
  }
1148
10448
  return handle_scope.Escape(Undefined(isolate()));
1149
}
1150
1151
MaybeLocal<Value> Environment::RunSnapshotDeserializeMain() const {
1152
  EscapableHandleScope handle_scope(isolate());
1153
  if (!snapshot_deserialize_main().IsEmpty()) {
1154
    Context::Scope context_scope(context());
1155
    return handle_scope.EscapeMaybe(snapshot_deserialize_main()->Call(
1156
        context(), v8::Undefined(isolate()), 0, nullptr));
1157
  }
1158
  return handle_scope.Escape(Undefined(isolate()));
1159
}
1160
1161
6062
void Environment::RunCleanup() {
1162
6062
  started_cleanup_ = true;
1163

16907
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1164
6062
  bindings_.clear();
1165
6062
  CleanupHandles();
1166
1167
18182
  while (!cleanup_hooks_.empty() ||
1168
12126
         native_immediates_.size() > 0 ||
1169

24244
         native_immediates_threadsafe_.size() > 0 ||
1170
6062
         native_immediates_interrupts_.size() > 0) {
1171
    // Copy into a vector, since we can't sort an unordered_set in-place.
1172
    std::vector<CleanupHookCallback> callbacks(
1173
12112
        cleanup_hooks_.begin(), cleanup_hooks_.end());
1174
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
1175
    // need to be able to check whether they were un-scheduled by another hook.
1176
1177
6056
    std::sort(callbacks.begin(), callbacks.end(),
1178
1232185
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1179
      // Sort in descending order so that the most recently inserted callbacks
1180
      // are run first.
1181
1232185
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1182
    });
1183
1184
190591
    for (const CleanupHookCallback& cb : callbacks) {
1185
184535
      if (cleanup_hooks_.count(cb) == 0) {
1186
        // This hook was removed from the `cleanup_hooks_` set during another
1187
        // hook that was run earlier. Nothing to do here.
1188
1178
        continue;
1189
      }
1190
1191
183357
      cb.fn_(cb.arg_);
1192
183357
      cleanup_hooks_.erase(cb);
1193
    }
1194
6056
    CleanupHandles();
1195
  }
1196
1197
6065
  for (const int fd : unmanaged_fds_) {
1198
    uv_fs_t close_req;
1199
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
1200
3
    uv_fs_req_cleanup(&close_req);
1201
  }
1202
6062
}
1203
1204
6677
void Environment::RunAtExitCallbacks() {
1205

18640
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1206
19813
  for (ExitCallback at_exit : at_exit_functions_) {
1207
13136
    at_exit.cb_(at_exit.arg_);
1208
  }
1209
6677
  at_exit_functions_.clear();
1210
6677
}
1211
1212
13160
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1213
13160
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1214
13160
}
1215
1216
228287
void Environment::RunAndClearInterrupts() {
1217
228287
  while (native_immediates_interrupts_.size() > 0) {
1218
11929
    NativeImmediateQueue queue;
1219
    {
1220
23858
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1221
11929
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1222
    }
1223
11929
    DebugSealHandleScope seal_handle_scope(isolate());
1224
1225
23867
    while (auto head = queue.Shift())
1226
23876
      head->Call(this);
1227
  }
1228
216358
}
1229
1230
205059
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1231

415104
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1232
               "RunAndClearNativeImmediates");
1233
410112
  HandleScope handle_scope(isolate_);
1234
410112
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
1235
1236
205059
  size_t ref_count = 0;
1237
1238
  // Handle interrupts first. These functions are not allowed to throw
1239
  // exceptions, so we do not need to handle that.
1240
205059
  RunAndClearInterrupts();
1241
1242
410116
  auto drain_list = [&](NativeImmediateQueue* queue) {
1243
820226
    TryCatchScope try_catch(this);
1244
410116
    DebugSealHandleScope seal_handle_scope(isolate());
1245
472278
    while (auto head = queue->Shift()) {
1246
62169
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1247
62169
      if (is_refed)
1248
37343
        ref_count++;
1249
1250

62169
      if (is_refed || !only_refed)
1251
61926
        head->Call(this);
1252
1253
62164
      head.reset();  // Destroy now so that this is also observed by try_catch.
1254
1255
62164
      if (UNLIKELY(try_catch.HasCaught())) {
1256

2
        if (!try_catch.HasTerminated() && can_call_into_js())
1257
2
          errors::TriggerUncaughtException(isolate(), try_catch);
1258
1259
1
        return true;
1260
      }
1261
62162
    }
1262
410109
    return false;
1263
205059
  };
1264
205059
  while (drain_list(&native_immediates_)) {}
1265
1266
205056
  immediate_info()->ref_count_dec(ref_count);
1267
1268
205056
  if (immediate_info()->ref_count() == 0)
1269
163247
    ToggleImmediateRef(false);
1270
1271
  // It is safe to check .size() first, because there is a causal relationship
1272
  // between pushes to the threadsafe immediate list and this function being
1273
  // called. For the common case, it's worth checking the size first before
1274
  // establishing a mutex lock.
1275
  // This is intentionally placed after the `ref_count` handling, because when
1276
  // refed threadsafe immediates are created, they are not counted towards the
1277
  // count in immediate_info() either.
1278
205053
  NativeImmediateQueue threadsafe_immediates;
1279
205056
  if (native_immediates_threadsafe_.size() > 0) {
1280
4146
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1281
2073
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1282
  }
1283
205057
  while (drain_list(&threadsafe_immediates)) {}
1284
205053
}
1285
1286
11943
void Environment::RequestInterruptFromV8() {
1287
  // The Isolate may outlive the Environment, so some logic to handle the
1288
  // situation in which the Environment is destroyed before the handler runs
1289
  // is required.
1290
1291
  // We allocate a new pointer to a pointer to this Environment instance, and
1292
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
1293
  // callbacks are already scheduled to run and we can delete our own pointer
1294
  // and just return. If it was nullptr previously, the Environment** is stored;
1295
  // ~Environment sets the Environment* contained in it to nullptr, so that
1296
  // the callback can check whether ~Environment has already run and it is thus
1297
  // not safe to access the Environment instance itself.
1298
11943
  Environment** interrupt_data = new Environment*(this);
1299
11943
  Environment** dummy = nullptr;
1300
11943
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1301
739
    delete interrupt_data;
1302
739
    return;  // Already scheduled.
1303
  }
1304
1305
11204
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1306
11195
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1307
11195
    Environment* env = *env_ptr;
1308
11195
    if (env == nullptr) {
1309
      // The Environment has already been destroyed. That should be okay; any
1310
      // callback added before the Environment shuts down would have been
1311
      // handled during cleanup.
1312
10
      return;
1313
    }
1314
11185
    env->interrupt_data_.store(nullptr);
1315
11185
    env->RunAndClearInterrupts();
1316
  }, interrupt_data);
1317
}
1318
1319
9870
void Environment::ScheduleTimer(int64_t duration_ms) {
1320
9870
  if (started_cleanup_) return;
1321
9870
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1322
}
1323
1324
3675
void Environment::ToggleTimerRef(bool ref) {
1325
3675
  if (started_cleanup_) return;
1326
1327
3675
  if (ref) {
1328
2409
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1329
  } else {
1330
1266
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1331
  }
1332
}
1333
1334
7703
void Environment::RunTimers(uv_timer_t* handle) {
1335
7703
  Environment* env = Environment::from_timer_handle(handle);
1336

8219
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1337
1338
7703
  if (!env->can_call_into_js())
1339
    return;
1340
1341
7703
  HandleScope handle_scope(env->isolate());
1342
7703
  Context::Scope context_scope(env->context());
1343
1344
7703
  Local<Object> process = env->process_object();
1345
7703
  InternalCallbackScope scope(env, process, {0, 0});
1346
1347
7703
  Local<Function> cb = env->timers_callback_function();
1348
  MaybeLocal<Value> ret;
1349
7703
  Local<Value> arg = env->GetNow();
1350
  // This code will loop until all currently due timers will process. It is
1351
  // impossible for us to end up in an infinite loop due to how the JS-side
1352
  // is structured.
1353
32
  do {
1354
7735
    TryCatchScope try_catch(env);
1355
7735
    try_catch.SetVerbose(true);
1356
7735
    ret = cb->Call(env->context(), process, 1, &arg);
1357

7725
  } while (ret.IsEmpty() && env->can_call_into_js());
1358
1359
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
1360
  // is reset back to `true` after being previously set to `false` then this
1361
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
1362
  // timers corruption will occur and all timers behaviour will become
1363
  // entirely unpredictable.
1364
7693
  if (ret.IsEmpty())
1365
9
    return;
1366
1367
  // To allow for less JS-C++ boundary crossing, the value returned from JS
1368
  // serves a few purposes:
1369
  // 1. If it's 0, no more timers exist and the handle should be unrefed
1370
  // 2. If it's > 0, the value represents the next timer's expiry and there
1371
  //    is at least one timer remaining that is refed.
1372
  // 3. If it's < 0, the absolute value represents the next timer's expiry
1373
  //    and there are no timers that are refed.
1374
  int64_t expiry_ms =
1375
7684
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1376
1377
7684
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1378
1379
7684
  if (expiry_ms != 0) {
1380
    int64_t duration_ms =
1381
6728
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1382
1383
6728
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1384
1385
6728
    if (expiry_ms > 0)
1386
6040
      uv_ref(h);
1387
    else
1388
688
      uv_unref(h);
1389
  } else {
1390
956
    uv_unref(h);
1391
  }
1392
}
1393
1394
1395
184975
void Environment::CheckImmediate(uv_check_t* handle) {
1396
184975
  Environment* env = Environment::from_immediate_check_handle(handle);
1397

187975
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1398
1399
184975
  HandleScope scope(env->isolate());
1400
184975
  Context::Scope context_scope(env->context());
1401
1402
184975
  env->RunAndClearNativeImmediates();
1403
1404

184975
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1405
144431
    return;
1406
1407
952
  do {
1408
41488
    MakeCallback(env->isolate(),
1409
                 env->process_object(),
1410
                 env->immediate_callback_function(),
1411
                 0,
1412
                 nullptr,
1413
41496
                 {0, 0}).ToLocalChecked();
1414

41488
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
1415
1416
40536
  if (env->immediate_info()->ref_count() == 0)
1417
4993
    env->ToggleImmediateRef(false);
1418
}
1419
1420
231983
void Environment::ToggleImmediateRef(bool ref) {
1421
231983
  if (started_cleanup_) return;
1422
1423
220298
  if (ref) {
1424
    // Idle handle is needed only to stop the event loop from blocking in poll.
1425
63719
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
1426
  } else {
1427
156579
    uv_idle_stop(immediate_idle_handle());
1428
  }
1429
}
1430
1431
1432
46948
Local<Value> Environment::GetNow() {
1433
46948
  uv_update_time(event_loop());
1434
46948
  uint64_t now = uv_now(event_loop());
1435
46948
  CHECK_GE(now, timer_base());
1436
46948
  now -= timer_base();
1437
46948
  if (now <= 0xffffffff)
1438
93896
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
1439
  else
1440
    return Number::New(isolate(), static_cast<double>(now));
1441
}
1442
1443
28
void CollectExceptionInfo(Environment* env,
1444
                          Local<Object> obj,
1445
                          int errorno,
1446
                          const char* err_string,
1447
                          const char* syscall,
1448
                          const char* message,
1449
                          const char* path,
1450
                          const char* dest) {
1451
28
  obj->Set(env->context(),
1452
           env->errno_string(),
1453
112
           Integer::New(env->isolate(), errorno)).Check();
1454
1455
28
  obj->Set(env->context(), env->code_string(),
1456
84
           OneByteString(env->isolate(), err_string)).Check();
1457
1458
28
  if (message != nullptr) {
1459
28
    obj->Set(env->context(), env->message_string(),
1460
112
             OneByteString(env->isolate(), message)).Check();
1461
  }
1462
1463
  Local<Value> path_buffer;
1464
28
  if (path != nullptr) {
1465
    path_buffer =
1466
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
1467
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
1468
  }
1469
1470
  Local<Value> dest_buffer;
1471
28
  if (dest != nullptr) {
1472
    dest_buffer =
1473
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
1474
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
1475
  }
1476
1477
28
  if (syscall != nullptr) {
1478
28
    obj->Set(env->context(), env->syscall_string(),
1479
112
             OneByteString(env->isolate(), syscall)).Check();
1480
  }
1481
28
}
1482
1483
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
1484
                                         int errorno,
1485
                                         const char* syscall,
1486
                                         const char* message,
1487
                                         const char* path,
1488
                                         const char* dest) {
1489

28
  if (!object->IsObject() || errorno == 0)
1490
    return;
1491
1492
28
  Local<Object> obj = object.As<Object>();
1493
28
  const char* err_string = uv_err_name(errorno);
1494
1495

28
  if (message == nullptr || message[0] == '\0') {
1496
28
    message = uv_strerror(errorno);
1497
  }
1498
1499
28
  node::CollectExceptionInfo(this, obj, errorno, err_string,
1500
                             syscall, message, path, dest);
1501
}
1502
1503
6585
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1504
6585
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
1505
1506
6
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
1507
    Local<Context> context, SnapshotCreator* creator) {
1508
6
  return {fields_.Serialize(context, creator)};
1509
}
1510
1511
5282
void ImmediateInfo::Deserialize(Local<Context> context) {
1512
5282
  fields_.Deserialize(context);
1513
5282
}
1514
1515
6
std::ostream& operator<<(std::ostream& output,
1516
                         const ImmediateInfo::SerializeInfo& i) {
1517
6
  output << "{ " << i.fields << " }";
1518
6
  return output;
1519
}
1520
1521
24
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1522
24
  tracker->TrackField("fields", fields_);
1523
24
}
1524
1525
6
TickInfo::SerializeInfo TickInfo::Serialize(Local<Context> context,
1526
                                            SnapshotCreator* creator) {
1527
6
  return {fields_.Serialize(context, creator)};
1528
}
1529
1530
5282
void TickInfo::Deserialize(Local<Context> context) {
1531
5282
  fields_.Deserialize(context);
1532
5282
}
1533
1534
6
std::ostream& operator<<(std::ostream& output,
1535
                         const TickInfo::SerializeInfo& i) {
1536
6
  output << "{ " << i.fields << " }";
1537
6
  return output;
1538
}
1539
1540
24
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1541
24
  tracker->TrackField("fields", fields_);
1542
24
}
1543
1544
6585
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1545
    : fields_(
1546
6585
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1547
1548
6585
AsyncHooks::AsyncHooks(Isolate* isolate, const SerializeInfo* info)
1549
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1550
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1551
      async_id_fields_(
1552
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1553

6585
      info_(info) {
1554
13170
  HandleScope handle_scope(isolate);
1555
6585
  if (info == nullptr) {
1556
1303
    clear_async_id_stack();
1557
1558
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1559
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1560
    // See discussion in https://github.com/nodejs/node/pull/15454
1561
    // When removing this, do it by reverting the commit. Otherwise the test
1562
    // and flag changes won't be included.
1563
1303
    fields_[kCheck] = 1;
1564
1565
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1566
    // specified default value and it should fallback to the executionAsyncId.
1567
    // 0 is not used as the magic value, because that indicates a missing
1568
    // context which is different from a default context.
1569
1303
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1570
1571
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1572
    // context during bootstrap (code that runs before entering uv_run()).
1573
1303
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1574
  }
1575
6585
}
1576
1577
5282
void AsyncHooks::Deserialize(Local<Context> context) {
1578
5282
  async_ids_stack_.Deserialize(context);
1579
5282
  fields_.Deserialize(context);
1580
5282
  async_id_fields_.Deserialize(context);
1581
1582
  Local<Array> js_execution_async_resources;
1583
5282
  if (info_->js_execution_async_resources != 0) {
1584
    js_execution_async_resources =
1585
5282
        context->GetDataFromSnapshotOnce<Array>(
1586
15846
            info_->js_execution_async_resources).ToLocalChecked();
1587
  } else {
1588
    js_execution_async_resources = Array::New(context->GetIsolate());
1589
  }
1590
5282
  js_execution_async_resources_.Reset(
1591
      context->GetIsolate(), js_execution_async_resources);
1592
1593
  // The native_execution_async_resources_ field requires v8::Local<> instances
1594
  // for async calls whose resources were on the stack as JS objects when they
1595
  // were entered. We cannot recreate this here; however, storing these values
1596
  // on the JS equivalent gives the same result, so we do that instead.
1597
5282
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1598
    if (info_->native_execution_async_resources[i] == SIZE_MAX)
1599
      continue;
1600
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1601
                                   info_->native_execution_async_resources[i])
1602
                               .ToLocalChecked();
1603
    js_execution_async_resources->Set(context, i, obj).Check();
1604
  }
1605
5282
  info_ = nullptr;
1606
5282
}
1607
1608
6
std::ostream& operator<<(std::ostream& output,
1609
                         const AsyncHooks::SerializeInfo& i) {
1610
  output << "{\n"
1611
6
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1612
6
         << "  " << i.fields << ",  // fields\n"
1613
6
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1614
6
         << "  " << i.js_execution_async_resources
1615
         << ",  // js_execution_async_resources\n"
1616
6
         << "  " << i.native_execution_async_resources
1617
         << ",  // native_execution_async_resources\n"
1618
6
         << "}";
1619
6
  return output;
1620
}
1621
1622
6
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1623
                                                SnapshotCreator* creator) {
1624
6
  SerializeInfo info;
1625
6
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1626
6
  info.fields = fields_.Serialize(context, creator);
1627
6
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1628
6
  if (!js_execution_async_resources_.IsEmpty()) {
1629
6
    info.js_execution_async_resources = creator->AddData(
1630
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1631
6
    CHECK_NE(info.js_execution_async_resources, 0);
1632
  } else {
1633
    info.js_execution_async_resources = 0;
1634
  }
1635
1636
6
  info.native_execution_async_resources.resize(
1637
      native_execution_async_resources_.size());
1638
6
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1639
    info.native_execution_async_resources[i] =
1640
        native_execution_async_resources_[i].IsEmpty() ? SIZE_MAX :
1641
            creator->AddData(
1642
                context,
1643
                native_execution_async_resources_[i]);
1644
  }
1645
6
  CHECK_EQ(contexts_.size(), 1);
1646

12
  CHECK_EQ(contexts_[0], env()->context());
1647
6
  CHECK(js_promise_hooks_[0].IsEmpty());
1648
6
  CHECK(js_promise_hooks_[1].IsEmpty());
1649
6
  CHECK(js_promise_hooks_[2].IsEmpty());
1650
6
  CHECK(js_promise_hooks_[3].IsEmpty());
1651
1652
6
  return info;
1653
}
1654
1655
24
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1656
24
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1657
24
  tracker->TrackField("fields", fields_);
1658
24
  tracker->TrackField("async_id_fields", async_id_fields_);
1659
24
  tracker->TrackField("js_promise_hooks", js_promise_hooks_);
1660
24
}
1661
1662
4
void AsyncHooks::grow_async_ids_stack() {
1663
4
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1664
1665
4
  env()->async_hooks_binding()->Set(
1666
      env()->context(),
1667
      env()->async_ids_stack_string(),
1668
12
      async_ids_stack_.GetJSArray()).Check();
1669
4
}
1670
1671
4
void AsyncHooks::FailWithCorruptedAsyncStack(double expected_async_id) {
1672
4
  fprintf(stderr,
1673
          "Error: async hook stack has become corrupted ("
1674
          "actual: %.f, expected: %.f)\n",
1675
          async_id_fields_.GetValue(kExecutionAsyncId),
1676
          expected_async_id);
1677
4
  DumpBacktrace(stderr);
1678
4
  fflush(stderr);
1679
4
  if (!env()->abort_on_uncaught_exception())
1680
4
    exit(1);
1681
  fprintf(stderr, "\n");
1682
  fflush(stderr);
1683
  ABORT_NO_BACKTRACE();
1684
}
1685
1686
598
void Environment::Exit(int exit_code) {
1687
598
  if (options()->trace_exit) {
1688
4
    HandleScope handle_scope(isolate());
1689
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1690
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1691
1692
2
    if (is_main_thread()) {
1693
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1694
    } else {
1695
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1696
              uv_os_getpid(), thread_id());
1697
    }
1698
1699
2
    fprintf(
1700
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1701
2
    PrintStackTrace(isolate(),
1702
                    StackTrace::CurrentStackTrace(
1703
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1704
  }
1705
598
  process_exit_handler_(this, exit_code);
1706
80
}
1707
1708
6608
void Environment::stop_sub_worker_contexts() {
1709
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1710
1711
6608
  while (!sub_worker_contexts_.empty()) {
1712
28
    Worker* w = *sub_worker_contexts_.begin();
1713
28
    remove_sub_worker_context(w);
1714
28
    w->Exit(1);
1715
28
    w->JoinThread();
1716
  }
1717
6580
}
1718
1719
10
Environment* Environment::worker_parent_env() const {
1720
10
  if (worker_context() == nullptr) return nullptr;
1721
  return worker_context()->env();
1722
}
1723
1724
68303
void Environment::AddUnmanagedFd(int fd) {
1725
68303
  if (!tracks_unmanaged_fds()) return;
1726
4994
  auto result = unmanaged_fds_.insert(fd);
1727
4994
  if (!result.second) {
1728
    ProcessEmitWarning(
1729
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1730
  }
1731
}
1732
1733
67924
void Environment::RemoveUnmanagedFd(int fd) {
1734
67924
  if (!tracks_unmanaged_fds()) return;
1735
4991
  size_t removed_count = unmanaged_fds_.erase(fd);
1736
4991
  if (removed_count == 0) {
1737
    ProcessEmitWarning(
1738
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1739
  }
1740
}
1741
1742
5201
void Environment::PrintInfoForSnapshotIfDebug() {
1743
5201
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1744
    fprintf(stderr, "BaseObjects at the exit of the Environment:\n");
1745
    PrintAllBaseObjects();
1746
    fprintf(stderr, "\nNative modules without cache:\n");
1747
    for (const auto& s : native_modules_without_cache) {
1748
      fprintf(stderr, "%s\n", s.c_str());
1749
    }
1750
    fprintf(stderr, "\nNative modules with cache:\n");
1751
    for (const auto& s : native_modules_with_cache) {
1752
      fprintf(stderr, "%s\n", s.c_str());
1753
    }
1754
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1755
    for (const auto mod : internal_bindings) {
1756
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1757
    }
1758
  }
1759
5201
}
1760
1761
void Environment::PrintAllBaseObjects() {
1762
  size_t i = 0;
1763
  std::cout << "BaseObjects\n";
1764
  ForEachBaseObject([&](BaseObject* obj) {
1765
    std::cout << "#" << i++ << " " << obj << ": " <<
1766
      obj->MemoryInfoName() << "\n";
1767
  });
1768
}
1769
1770
5201
void Environment::VerifyNoStrongBaseObjects() {
1771
  // When a process exits cleanly, i.e. because the event loop ends up without
1772
  // things to wait for, the Node.js objects that are left on the heap should
1773
  // be:
1774
  //
1775
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1776
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1777
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1778
  //   4. an inactive libuv handle (essentially the same here)
1779
  //
1780
  // There are a few exceptions to this rule, but generally, if there are
1781
  // C++-backed Node.js objects on the heap that do not fall into the above
1782
  // categories, we may be looking at a potential memory leak. Most likely,
1783
  // the cause is a missing MakeWeak() call on the corresponding object.
1784
  //
1785
  // In order to avoid this kind of problem, we check the list of BaseObjects
1786
  // for these criteria. Currently, we only do so when explicitly instructed to
1787
  // or when in debug mode (where --verify-base-objects is always-on).
1788
1789
5201
  if (!options()->verify_base_objects) return;
1790
1791
  ForEachBaseObject([](BaseObject* obj) {
1792
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1793
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1794
            obj->MemoryInfoName().c_str());
1795
    fflush(stderr);
1796
    ABORT();
1797
  });
1798
}
1799
1800
6
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1801
6
  EnvSerializeInfo info;
1802
6
  Local<Context> ctx = context();
1803
1804
6
  SerializeBindingData(this, creator, &info);
1805
  // Currently all modules are compiled without cache in builtin snapshot
1806
  // builder.
1807
12
  info.native_modules = std::vector<std::string>(
1808
6
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1809
1810
6
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1811
6
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1812
6
  info.tick_info = tick_info_.Serialize(ctx, creator);
1813
6
  info.performance_state = performance_state_->Serialize(ctx, creator);
1814
6
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1815
6
  info.should_abort_on_uncaught_toggle =
1816
6
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1817
1818
6
  size_t id = 0;
1819
#define V(PropertyName, TypeName)                                              \
1820
  do {                                                                         \
1821
    Local<TypeName> field = PropertyName();                                    \
1822
    if (!field.IsEmpty()) {                                                    \
1823
      size_t index = creator->AddData(ctx, field);                             \
1824
      info.persistent_values.push_back({#PropertyName, id, index});            \
1825
    }                                                                          \
1826
    id++;                                                                      \
1827
  } while (0);
1828
































594
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1829
#undef V
1830
1831
6
  info.context = creator->AddData(ctx, context());
1832
6
  return info;
1833
}
1834
1835
6
std::ostream& operator<<(std::ostream& output,
1836
                         const std::vector<std::string>& vec) {
1837
6
  output << "{\n";
1838
702
  for (const auto& info : vec) {
1839
696
    output << "  \"" << info << "\",\n";
1840
  }
1841
6
  output << "}";
1842
6
  return output;
1843
}
1844
1845
6
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1846
  output << "{\n"
1847
6
         << "// -- bindings begins --\n"
1848
6
         << i.bindings << ",\n"
1849
         << "// -- bindings ends --\n"
1850
6
         << "// -- native_modules begins --\n"
1851
6
         << i.native_modules << ",\n"
1852
         << "// -- native_modules ends --\n"
1853
6
         << "// -- async_hooks begins --\n"
1854
6
         << i.async_hooks << ",\n"
1855
6
         << "// -- async_hooks ends --\n"
1856
6
         << i.tick_info << ",  // tick_info\n"
1857
6
         << i.immediate_info << ",  // immediate_info\n"
1858
6
         << "// -- performance_state begins --\n"
1859
6
         << i.performance_state << ",\n"
1860
6
         << "// -- performance_state ends --\n"
1861
6
         << i.stream_base_state << ",  // stream_base_state\n"
1862
6
         << i.should_abort_on_uncaught_toggle
1863
         << ",  // should_abort_on_uncaught_toggle\n"
1864
6
         << "// -- persistent_values begins --\n"
1865
6
         << i.persistent_values << ",\n"
1866
6
         << "// -- persistent_values ends --\n"
1867
6
         << i.context << ",  // context\n"
1868
6
         << "}";
1869
6
  return output;
1870
}
1871
1872
21128
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1873
                                            Local<Object> holder,
1874
                                            int index,
1875
                                            InternalFieldInfo* info) {
1876
42256
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1877
21128
  deserialize_requests_.push_back(std::move(request));
1878
21128
}
1879
1880
5282
void Environment::RunDeserializeRequests() {
1881
10564
  HandleScope scope(isolate());
1882
5282
  Local<Context> ctx = context();
1883
5282
  Isolate* is = isolate();
1884
26410
  while (!deserialize_requests_.empty()) {
1885
42256
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1886
21128
    deserialize_requests_.pop_front();
1887
21128
    Local<Object> holder = request.holder.Get(is);
1888
21128
    request.cb(ctx, holder, request.index, request.info);
1889
    request.holder.Reset();
1890
21128
    request.info->Delete();
1891
  }
1892
5282
}
1893
1894
5282
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1895
5282
  Local<Context> ctx = context();
1896
1897
5282
  RunDeserializeRequests();
1898
1899
5282
  native_modules_in_snapshot = info->native_modules;
1900
5282
  async_hooks_.Deserialize(ctx);
1901
5282
  immediate_info_.Deserialize(ctx);
1902
5282
  tick_info_.Deserialize(ctx);
1903
5282
  performance_state_->Deserialize(ctx);
1904
5282
  stream_base_state_.Deserialize(ctx);
1905
5282
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1906
1907
5282
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1908
    fprintf(stderr, "deserializing...\n");
1909
    std::cerr << *info << "\n";
1910
  }
1911
1912
5282
  const std::vector<PropInfo>& values = info->persistent_values;
1913
5282
  size_t i = 0;  // index to the array
1914
5282
  size_t id = 0;
1915
#define V(PropertyName, TypeName)                                              \
1916
  do {                                                                         \
1917
    if (values.size() > i && id == values[i].id) {                             \
1918
      const PropInfo& d = values[i];                                           \
1919
      DCHECK_EQ(d.name, #PropertyName);                                        \
1920
      MaybeLocal<TypeName> maybe_field =                                       \
1921
          ctx->GetDataFromSnapshotOnce<TypeName>(d.index);                     \
1922
      Local<TypeName> field;                                                   \
1923
      if (!maybe_field.ToLocal(&field)) {                                      \
1924
        fprintf(stderr,                                                        \
1925
                "Failed to deserialize environment value " #PropertyName       \
1926
                "\n");                                                         \
1927
      }                                                                        \
1928
      set_##PropertyName(field);                                               \
1929
      i++;                                                                     \
1930
    }                                                                          \
1931
    id++;                                                                      \
1932
  } while (0);
1933
1934
































































































































544046
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1935
#undef V
1936
1937
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1938
10564
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1939
  Local<Context> ctx_from_snapshot;
1940
5282
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1941
    fprintf(stderr,
1942
            "Failed to deserialize context back reference from the snapshot\n");
1943
  }
1944
5282
  CHECK_EQ(ctx_from_snapshot, ctx);
1945
5282
}
1946
1947
1
uint64_t GuessMemoryAvailableToTheProcess() {
1948
1
  uint64_t free_in_system = uv_get_free_memory();
1949
1
  size_t allowed = uv_get_constrained_memory();
1950
1
  if (allowed == 0) {
1951
    return free_in_system;
1952
  }
1953
  size_t rss;
1954
1
  int err = uv_resident_set_memory(&rss);
1955
1
  if (err) {
1956
    return free_in_system;
1957
  }
1958
1
  if (allowed < rss) {
1959
    // Something is probably wrong. Fallback to the free memory.
1960
    return free_in_system;
1961
  }
1962
  // There may still be room for swap, but we will just leave it here.
1963
1
  return allowed - rss;
1964
}
1965
1966
24
void Environment::BuildEmbedderGraph(Isolate* isolate,
1967
                                     EmbedderGraph* graph,
1968
                                     void* data) {
1969
24
  MemoryTracker tracker(isolate, graph);
1970
24
  Environment* env = static_cast<Environment*>(data);
1971
24
  tracker.Track(env);
1972
24
  env->ForEachBaseObject([&](BaseObject* obj) {
1973
587
    if (obj->IsDoneInitializing())
1974
586
      tracker.Track(obj);
1975
587
  });
1976
24
}
1977
1978
1
size_t Environment::NearHeapLimitCallback(void* data,
1979
                                          size_t current_heap_limit,
1980
                                          size_t initial_heap_limit) {
1981
1
  Environment* env = static_cast<Environment*>(data);
1982
1983
  Debug(env,
1984
        DebugCategory::DIAGNOSTICS,
1985
        "Invoked NearHeapLimitCallback, processing=%d, "
1986
        "current_limit=%" PRIu64 ", "
1987
        "initial_limit=%" PRIu64 "\n",
1988
1
        env->is_processing_heap_limit_callback_,
1989
2
        static_cast<uint64_t>(current_heap_limit),
1990
1
        static_cast<uint64_t>(initial_heap_limit));
1991
1992
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1993
1
  size_t young_gen_size = 0;
1994
1
  size_t old_gen_size = 0;
1995
1996
1
  HeapSpaceStatistics stats;
1997
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1998
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1999
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
2000

15
    if (strcmp(stats.space_name(), "new_space") == 0 ||
2001
7
        strcmp(stats.space_name(), "new_large_object_space") == 0) {
2002
2
      young_gen_size += stats.space_used_size();
2003
    } else {
2004
6
      old_gen_size += stats.space_used_size();
2005
    }
2006
  }
2007
2008
  Debug(env,
2009
        DebugCategory::DIAGNOSTICS,
2010
        "max_young_gen_size=%" PRIu64 ", "
2011
        "young_gen_size=%" PRIu64 ", "
2012
        "old_gen_size=%" PRIu64 ", "
2013
        "total_size=%" PRIu64 "\n",
2014
2
        static_cast<uint64_t>(max_young_gen_size),
2015
2
        static_cast<uint64_t>(young_gen_size),
2016
2
        static_cast<uint64_t>(old_gen_size),
2017
1
        static_cast<uint64_t>(young_gen_size + old_gen_size));
2018
2019
1
  uint64_t available = GuessMemoryAvailableToTheProcess();
2020
  // TODO(joyeecheung): get a better estimate about the native memory
2021
  // usage into the overhead, e.g. based on the count of objects.
2022
1
  uint64_t estimated_overhead = max_young_gen_size;
2023
  Debug(env,
2024
        DebugCategory::DIAGNOSTICS,
2025
        "Estimated available memory=%" PRIu64 ", "
2026
        "estimated overhead=%" PRIu64 "\n",
2027
2
        static_cast<uint64_t>(available),
2028
1
        static_cast<uint64_t>(estimated_overhead));
2029
2030
  // This might be hit when the snapshot is being taken in another
2031
  // NearHeapLimitCallback invocation.
2032
  // When taking the snapshot, objects in the young generation may be
2033
  // promoted to the old generation, result in increased heap usage,
2034
  // but it should be no more than the young generation size.
2035
  // Ideally, this should be as small as possible - the heap limit
2036
  // can only be restored when the heap usage falls down below the
2037
  // new limit, so in a heap with unbounded growth the isolate
2038
  // may eventually crash with this new limit - effectively raising
2039
  // the heap limit to the new one.
2040
1
  if (env->is_processing_heap_limit_callback_) {
2041
    size_t new_limit = current_heap_limit + max_young_gen_size;
2042
    Debug(env,
2043
          DebugCategory::DIAGNOSTICS,
2044
          "Not generating snapshots in nested callback. "
2045
          "new_limit=%" PRIu64 "\n",
2046
          static_cast<uint64_t>(new_limit));
2047
    return new_limit;
2048
  }
2049
2050
  // Estimate whether the snapshot is going to use up all the memory
2051
  // available to the process. If so, just give up to prevent the system
2052
  // from killing the process for a system OOM.
2053
1
  if (estimated_overhead > available) {
2054
    Debug(env,
2055
          DebugCategory::DIAGNOSTICS,
2056
          "Not generating snapshots because it's too risky.\n");
2057
    env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
2058
                                                initial_heap_limit);
2059
    // The new limit must be higher than current_heap_limit or V8 might
2060
    // crash.
2061
    return current_heap_limit + 1;
2062
  }
2063
2064
  // Take the snapshot synchronously.
2065
1
  env->is_processing_heap_limit_callback_ = true;
2066
2067
2
  std::string dir = env->options()->diagnostic_dir;
2068
1
  if (dir.empty()) {
2069
1
    dir = env->GetCwd();
2070
  }
2071
2
  DiagnosticFilename name(env, "Heap", "heapsnapshot");
2072
1
  std::string filename = dir + kPathSeparator + (*name);
2073
2074
1
  Debug(env, DebugCategory::DIAGNOSTICS, "Start generating %s...\n", *name);
2075
2076
  // Remove the callback first in case it's triggered when generating
2077
  // the snapshot.
2078
1
  env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
2079
                                              initial_heap_limit);
2080
2081
1
  heap::WriteSnapshot(env, filename.c_str());
2082
1
  env->heap_limit_snapshot_taken_ += 1;
2083
2084
  // Don't take more snapshots than the number specified by
2085
  // --heapsnapshot-near-heap-limit.
2086
2
  if (env->heap_limit_snapshot_taken_ <
2087
1
      env->options_->heap_snapshot_near_heap_limit) {
2088
    env->isolate()->AddNearHeapLimitCallback(NearHeapLimitCallback, env);
2089
  }
2090
2091
1
  FPrintF(stderr, "Wrote snapshot to %s\n", filename.c_str());
2092
  // Tell V8 to reset the heap limit once the heap usage falls down to
2093
  // 95% of the initial limit.
2094
1
  env->isolate()->AutomaticallyRestoreInitialHeapLimit(0.95);
2095
2096
1
  env->is_processing_heap_limit_callback_ = false;
2097
2098
  // The new limit must be higher than current_heap_limit or V8 might
2099
  // crash.
2100
1
  return current_heap_limit + 1;
2101
}
2102
2103
24
inline size_t Environment::SelfSize() const {
2104
24
  size_t size = sizeof(*this);
2105
  // Remove non pointer fields that will be tracked in MemoryInfo()
2106
  // TODO(joyeecheung): refactor the MemoryTracker interface so
2107
  // this can be done for common types within the Track* calls automatically
2108
  // if a certain scope is entered.
2109
24
  size -= sizeof(async_hooks_);
2110
24
  size -= sizeof(tick_info_);
2111
24
  size -= sizeof(immediate_info_);
2112
24
  return size;
2113
}
2114
2115
24
void Environment::MemoryInfo(MemoryTracker* tracker) const {
2116
  // Iteratable STLs have their own sizes subtracted from the parent
2117
  // by default.
2118
24
  tracker->TrackField("isolate_data", isolate_data_);
2119
24
  tracker->TrackField("native_modules_with_cache", native_modules_with_cache);
2120
24
  tracker->TrackField("native_modules_without_cache",
2121
24
                      native_modules_without_cache);
2122
24
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
2123
24
  tracker->TrackField("exec_argv", exec_argv_);
2124
24
  tracker->TrackField("should_abort_on_uncaught_toggle",
2125
24
                      should_abort_on_uncaught_toggle_);
2126
24
  tracker->TrackField("stream_base_state", stream_base_state_);
2127
24
  tracker->TrackFieldWithSize(
2128
24
      "cleanup_hooks", cleanup_hooks_.size() * sizeof(CleanupHookCallback));
2129
24
  tracker->TrackField("async_hooks", async_hooks_);
2130
24
  tracker->TrackField("immediate_info", immediate_info_);
2131
24
  tracker->TrackField("tick_info", tick_info_);
2132
2133
#define V(PropertyName, TypeName)                                              \
2134
  tracker->TrackField(#PropertyName, PropertyName());
2135
24
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
2136
#undef V
2137
2138
  // FIXME(joyeecheung): track other fields in Environment.
2139
  // Currently MemoryTracker is unable to track these
2140
  // correctly:
2141
  // - Internal types that do not implement MemoryRetainer yet
2142
  // - STL containers with MemoryRetainer* inside
2143
  // - STL containers with numeric types inside that should not have their
2144
  //   nodes elided e.g. numeric keys in maps.
2145
  // We also need to make sure that when we add a non-pointer field as its own
2146
  // node, we shift its sizeof() size out of the Environment node.
2147
24
}
2148
2149
708230
void Environment::RunWeakRefCleanup() {
2150
708230
  isolate()->ClearKeptObjects();
2151
708230
}
2152
2153
// Not really any better place than env.cc at this moment.
2154
1451805
BaseObject::BaseObject(Environment* env, Local<Object> object)
2155
2903610
    : persistent_handle_(env->isolate(), object), env_(env) {
2156
1451805
  CHECK_EQ(false, object.IsEmpty());
2157
1451805
  CHECK_GT(object->InternalFieldCount(), 0);
2158
1451805
  object->SetAlignedPointerInInternalField(BaseObject::kSlot,
2159
                                           static_cast<void*>(this));
2160
1451805
  env->AddCleanupHook(DeleteMe, static_cast<void*>(this));
2161
1451805
  env->modify_base_object_count(1);
2162
1451805
}
2163
2164

7902182
BaseObject::~BaseObject() {
2165
2880502
  env()->modify_base_object_count(-1);
2166
2880502
  env()->RemoveCleanupHook(DeleteMe, static_cast<void*>(this));
2167
2168
2880502
  if (UNLIKELY(has_pointer_data())) {
2169
386330
    PointerData* metadata = pointer_data();
2170
386330
    CHECK_EQ(metadata->strong_ptr_count, 0);
2171
386330
    metadata->self = nullptr;
2172
386330
    if (metadata->weak_ptr_count == 0) delete metadata;
2173
  }
2174
2175
2880502
  if (persistent_handle_.IsEmpty()) {
2176
    // This most likely happened because the weak callback below cleared it.
2177
2141178
    return;
2178
  }
2179
2180
  {
2181
739324
    HandleScope handle_scope(env()->isolate());
2182
1478648
    object()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2183
  }
2184
}
2185
2186
1239571
void BaseObject::MakeWeak() {
2187
1239571
  if (has_pointer_data()) {
2188
45834
    pointer_data()->wants_weak_jsobj = true;
2189
45834
    if (pointer_data()->strong_ptr_count > 0) return;
2190
  }
2191
2192
2479140
  persistent_handle_.SetWeak(
2193
      this,
2194
1070588
      [](const WeakCallbackInfo<BaseObject>& data) {
2195
1070588
        BaseObject* obj = data.GetParameter();
2196
        // Clear the persistent handle so that ~BaseObject() doesn't attempt
2197
        // to mess with internal fields, since the JS object may have
2198
        // transitioned into an invalid state.
2199
        // Refs: https://github.com/nodejs/node/issues/18897
2200
1070588
        obj->persistent_handle_.Reset();
2201

1070588
        CHECK_IMPLIES(obj->has_pointer_data(),
2202
                      obj->pointer_data()->strong_ptr_count == 0);
2203
1070588
        obj->OnGCCollect();
2204
1070588
      },
2205
      WeakCallbackType::kParameter);
2206
}
2207
2208
23533
void BaseObject::LazilyInitializedJSTemplateConstructor(
2209
    const FunctionCallbackInfo<Value>& args) {
2210
  DCHECK(args.IsConstructCall());
2211
  DCHECK_GT(args.This()->InternalFieldCount(), 0);
2212
23533
  args.This()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2213
23533
}
2214
2215
23439
Local<FunctionTemplate> BaseObject::MakeLazilyInitializedJSTemplate(
2216
    Environment* env) {
2217
  Local<FunctionTemplate> t =
2218
23439
      env->NewFunctionTemplate(LazilyInitializedJSTemplateConstructor);
2219
23439
  t->Inherit(BaseObject::GetConstructorTemplate(env));
2220
46878
  t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
2221
23439
  return t;
2222
}
2223
2224
3043754
BaseObject::PointerData* BaseObject::pointer_data() {
2225
3043754
  if (!has_pointer_data()) {
2226
195348
    PointerData* metadata = new PointerData();
2227
195348
    metadata->wants_weak_jsobj = persistent_handle_.IsWeak();
2228
195348
    metadata->self = this;
2229
195348
    pointer_data_ = metadata;
2230
  }
2231
3043754
  CHECK(has_pointer_data());
2232
3043754
  return pointer_data_;
2233
}
2234
2235
779568
void BaseObject::decrease_refcount() {
2236
779568
  CHECK(has_pointer_data());
2237
779568
  PointerData* metadata = pointer_data();
2238
779568
  CHECK_GT(metadata->strong_ptr_count, 0);
2239
779568
  unsigned int new_refcount = --metadata->strong_ptr_count;
2240
779568
  if (new_refcount == 0) {
2241
264244
    if (metadata->is_detached) {
2242
186906
      OnGCCollect();
2243

77338
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
2244
45833
      MakeWeak();
2245
    }
2246
  }
2247
779568
}
2248
2249
781840
void BaseObject::increase_refcount() {
2250
781840
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2251

781840
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2252
266413
    persistent_handle_.ClearWeak();
2253
781840
}
2254
2255
167997
void BaseObject::DeleteMe(void* data) {
2256
167997
  BaseObject* self = static_cast<BaseObject*>(data);
2257

176105
  if (self->has_pointer_data() &&
2258
8108
      self->pointer_data()->strong_ptr_count > 0) {
2259
3549
    return self->Detach();
2260
  }
2261
164448
  delete self;
2262
}
2263
2264
530
bool BaseObject::IsDoneInitializing() const { return true; }
2265
2266
586
Local<Object> BaseObject::WrappedObject() const {
2267
586
  return object();
2268
}
2269
2270
1172
bool BaseObject::IsRootNode() const {
2271
2344
  return !persistent_handle_.IsWeak();
2272
}
2273
2274
69203
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
2275
69203
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
2276
69203
  if (tmpl.IsEmpty()) {
2277
1303
    tmpl = env->NewFunctionTemplate(nullptr);
2278
1303
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
2279
1303
    env->set_base_object_ctor_template(tmpl);
2280
  }
2281
69203
  return tmpl;
2282
}
2283
2284
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2285
  return IsWeakOrDetached();
2286
}
2287
2288
}  // namespace node