GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 745 804 92.7 %
Date: 2021-10-26 04:13:54 Branches: 987 1870 52.8 %

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




82416
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
110





111504
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
111









































































































































2661552
  PER_ISOLATE_STRING_PROPERTIES(VS)
112
#undef V
113
#undef VY
114
#undef VS
115
#undef VP
116
117
286032
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
118
    MaybeLocal<String> maybe_field =
119
562368
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
120
    Local<String> field;
121
281184
    if (!maybe_field.ToLocal(&field)) {
122
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
123
    }
124
281184
    async_wrap_providers_[j].Set(isolate_, field);
125
  }
126
4848
}
127
128
628
void IsolateData::CreateProperties() {
129
  // Create string and private symbol properties as internalized one byte
130
  // strings after the platform is properly initialized.
131
  //
132
  // Internalized because it makes property lookups a little faster and
133
  // because the string is created in the old space straight away.  It's going
134
  // to end up in the old space sooner or later anyway but now it doesn't go
135
  // through v8::Eternal's new space handling first.
136
  //
137
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
138
  // decoding step.
139
140
628
  HandleScope handle_scope(isolate_);
141
142
#define V(PropertyName, StringValue)                                           \
143
  PropertyName##_.Set(                                                         \
144
      isolate_,                                                                \
145
      Private::New(isolate_,                                                   \
146
                   String::NewFromOneByte(                                     \
147
                       isolate_,                                               \
148
                       reinterpret_cast<const uint8_t*>(StringValue),          \
149
                       NewStringType::kInternalized,                           \
150
                       sizeof(StringValue) - 1)                                \
151
                       .ToLocalChecked()));
152
5652
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
153
#undef V
154
#define V(PropertyName, StringValue)                                           \
155
  PropertyName##_.Set(                                                         \
156
      isolate_,                                                                \
157
      Symbol::New(isolate_,                                                    \
158
                  String::NewFromOneByte(                                      \
159
                      isolate_,                                                \
160
                      reinterpret_cast<const uint8_t*>(StringValue),           \
161
                      NewStringType::kInternalized,                            \
162
                      sizeof(StringValue) - 1)                                 \
163
                      .ToLocalChecked()));
164
7536
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
165
#undef V
166
#define V(PropertyName, StringValue)                                           \
167
  PropertyName##_.Set(                                                         \
168
      isolate_,                                                                \
169
      String::NewFromOneByte(isolate_,                                         \
170
                             reinterpret_cast<const uint8_t*>(StringValue),    \
171
                             NewStringType::kInternalized,                     \
172
                             sizeof(StringValue) - 1)                          \
173
          .ToLocalChecked());
174
172700
  PER_ISOLATE_STRING_PROPERTIES(V)
175
#undef V
176
177
  // Create all the provider strings that will be passed to JS. Place them in
178
  // an array so the array index matches the PROVIDER id offset. This way the
179
  // strings can be retrieved quickly.
180
#define V(Provider)                                                           \
181
  async_wrap_providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                \
182
      isolate_,                                                               \
183
      String::NewFromOneByte(                                                 \
184
        isolate_,                                                             \
185
        reinterpret_cast<const uint8_t*>(#Provider),                          \
186
        NewStringType::kInternalized,                                         \
187
        sizeof(#Provider) - 1).ToLocalChecked());
188
37052
  NODE_ASYNC_PROVIDER_TYPES(V)
189
#undef V
190
628
}
191
192
5476
IsolateData::IsolateData(Isolate* isolate,
193
                         uv_loop_t* event_loop,
194
                         MultiIsolatePlatform* platform,
195
                         ArrayBufferAllocator* node_allocator,
196
5476
                         const std::vector<size_t>* indexes)
197
    : isolate_(isolate),
198
      event_loop_(event_loop),
199
47
      node_allocator_(node_allocator == nullptr ? nullptr
200
5429
                                                : node_allocator->GetImpl()),
201
10952
      platform_(platform) {
202
5476
  options_.reset(
203
5476
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
204
205
5476
  if (indexes == nullptr) {
206
628
    CreateProperties();
207
  } else {
208
4848
    DeserializeProperties(indexes);
209
  }
210
5476
}
211
212
22
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
213
#define V(PropertyName, StringValue)                                           \
214
  tracker->TrackField(#PropertyName, PropertyName());
215
22
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
216
217
22
  PER_ISOLATE_STRING_PROPERTIES(V)
218
#undef V
219
220
22
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
221
222
22
  if (node_allocator_ != nullptr) {
223
22
    tracker->TrackFieldWithSize(
224
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
225
  }
226
22
  tracker->TrackFieldWithSize(
227
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
228
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
229
22
}
230
231
121
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
232

121
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
233
    // Ideally, we’d have a consistent story that treats all threads/Environment
234
    // instances equally here. However, tracing is essentially global, and this
235
    // callback is called from whichever thread calls `StartTracing()` or
236
    // `StopTracing()`. The only way to do this in a threadsafe fashion
237
    // seems to be only tracking this from the main thread, and only allowing
238
    // these state modifications from the main thread.
239
63
    return;
240
  }
241
242
110
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
243
110
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
244
245
110
  Isolate* isolate = env_->isolate();
246
110
  HandleScope handle_scope(isolate);
247
110
  Local<Function> cb = env_->trace_category_state_function();
248
110
  if (cb.IsEmpty())
249
52
    return;
250
58
  TryCatchScope try_catch(env_);
251
58
  try_catch.SetVerbose(true);
252
116
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
253
116
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
254
}
255
256
613
void Environment::CreateProperties() {
257
1226
  HandleScope handle_scope(isolate_);
258
613
  Local<Context> ctx = context();
259
260
  {
261
613
    Context::Scope context_scope(ctx);
262
613
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
263
1226
    templ->InstanceTemplate()->SetInternalFieldCount(
264
        BaseObject::kInternalFieldCount);
265
613
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
266
267
613
    set_binding_data_ctor_template(templ);
268
  }
269
270
  // Store primordials setup by the per-context script in the environment.
271
  Local<Object> per_context_bindings =
272
1226
      GetPerContextExports(ctx).ToLocalChecked();
273
  Local<Value> primordials =
274
1839
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
275
613
  CHECK(primordials->IsObject());
276
613
  set_primordials(primordials.As<Object>());
277
278
  Local<String> prototype_string =
279
613
      FIXED_ONE_BYTE_STRING(isolate(), "prototype");
280
281
#define V(EnvPropertyName, PrimordialsPropertyName)                            \
282
  {                                                                            \
283
    Local<Value> ctor =                                                        \
284
        primordials.As<Object>()                                               \
285
            ->Get(ctx,                                                         \
286
                  FIXED_ONE_BYTE_STRING(isolate(), PrimordialsPropertyName))   \
287
            .ToLocalChecked();                                                 \
288
    CHECK(ctor->IsObject());                                                   \
289
    Local<Value> prototype =                                                   \
290
        ctor.As<Object>()->Get(ctx, prototype_string).ToLocalChecked();        \
291
    CHECK(prototype->IsObject());                                              \
292
    set_##EnvPropertyName(prototype.As<Object>());                             \
293
  }
294
295

3678
  V(primordials_safe_map_prototype_object, "SafeMap");
296

3678
  V(primordials_safe_set_prototype_object, "SafeSet");
297

3678
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
298

3678
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
299
#undef V
300
301
  Local<Object> process_object =
302
613
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
303
613
  set_process_object(process_object);
304
613
}
305
306
5461
std::string GetExecPath(const std::vector<std::string>& argv) {
307
  char exec_path_buf[2 * PATH_MAX];
308
5461
  size_t exec_path_len = sizeof(exec_path_buf);
309
5461
  std::string exec_path;
310
5461
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
311
5461
    exec_path = std::string(exec_path_buf, exec_path_len);
312
  } else {
313
    exec_path = argv[0];
314
  }
315
316
  // On OpenBSD process.execPath will be relative unless we
317
  // get the full path before process.execPath is used.
318
#if defined(__OpenBSD__)
319
  uv_fs_t req;
320
  req.ptr = nullptr;
321
  if (0 ==
322
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
323
    CHECK_NOT_NULL(req.ptr);
324
    exec_path = std::string(static_cast<char*>(req.ptr));
325
  }
326
  uv_fs_req_cleanup(&req);
327
#endif
328
329
5461
  return exec_path;
330
}
331
332
5461
Environment::Environment(IsolateData* isolate_data,
333
                         Isolate* isolate,
334
                         const std::vector<std::string>& args,
335
                         const std::vector<std::string>& exec_args,
336
                         const EnvSerializeInfo* env_info,
337
                         EnvironmentFlags::Flags flags,
338
5461
                         ThreadId thread_id)
339
    : isolate_(isolate),
340
      isolate_data_(isolate_data),
341
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
342
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
343
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
344
5461
      timer_base_(uv_now(isolate_data->event_loop())),
345
      exec_argv_(exec_args),
346
      argv_(args),
347
      exec_path_(GetExecPath(args)),
348
      should_abort_on_uncaught_toggle_(
349
5461
          isolate_,
350
          1,
351
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
352
5461
      stream_base_state_(isolate_,
353
                         StreamBase::kNumStreamBaseStateFields,
354
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
355
5461
      environment_start_time_(PERFORMANCE_NOW()),
356
      flags_(flags),
357
5461
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
358
5461
                     ? AllocateEnvironmentThreadId().id
359



21844
                     : thread_id.id) {
360
  // We'll be creating new objects so make sure we've entered the context.
361
10922
  HandleScope handle_scope(isolate);
362
363
  // Set some flags if only kDefaultFlags was passed. This can make API version
364
  // transitions easier for embedders.
365
5461
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
366
9800
    flags_ = flags_ |
367
4900
        EnvironmentFlags::kOwnsProcessState |
368
        EnvironmentFlags::kOwnsInspector;
369
  }
370
371
5461
  set_env_vars(per_process::system_environment);
372
  // TODO(joyeecheung): pass Isolate* and env_vars to it instead of the entire
373
  // env, when the recursive dependency inclusion in "debug-utils.h" is
374
  // resolved.
375
5461
  enabled_debug_list_.Parse(this);
376
377
  // We create new copies of the per-Environment option sets, so that it is
378
  // easier to modify them after Environment creation. The defaults are
379
  // part of the per-Isolate option set, for which in turn the defaults are
380
  // part of the per-process option set.
381
10922
  options_ = std::make_shared<EnvironmentOptions>(
382
16383
      *isolate_data->options()->per_env);
383
5461
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
384
5461
      options_->debug_options().host_port);
385
386
5461
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
387
561
    set_abort_on_uncaught_exception(false);
388
  }
389
390
#if HAVE_INSPECTOR
391
  // We can only create the inspector agent after having cloned the options.
392
5461
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
393
#endif
394
395
5461
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
396
5461
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
397
5461
    if (TracingController* tracing_controller = writer->GetTracingController())
398
5413
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
399
  }
400
401
5461
  destroy_async_id_list_.reserve(512);
402
403
5461
  performance_state_ = std::make_unique<performance::PerformanceState>(
404
5461
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
405
406
5461
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
407
5461
          TRACING_CATEGORY_NODE1(environment)) != 0) {
408
16
    auto traced_value = tracing::TracedValue::Create();
409
8
    traced_value->BeginArray("args");
410
18
    for (const std::string& arg : args) traced_value->AppendString(arg);
411
8
    traced_value->EndArray();
412
8
    traced_value->BeginArray("exec_args");
413
33
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
414
8
    traced_value->EndArray();
415

15
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
416
                                      "Environment",
417
                                      this,
418
                                      "args",
419
                                      std::move(traced_value));
420
  }
421
5461
}
422
423
613
Environment::Environment(IsolateData* isolate_data,
424
                         Local<Context> context,
425
                         const std::vector<std::string>& args,
426
                         const std::vector<std::string>& exec_args,
427
                         const EnvSerializeInfo* env_info,
428
                         EnvironmentFlags::Flags flags,
429
613
                         ThreadId thread_id)
430
    : Environment(isolate_data,
431
                  context->GetIsolate(),
432
                  args,
433
                  exec_args,
434
                  env_info,
435
                  flags,
436
613
                  thread_id) {
437
613
  InitializeMainContext(context, env_info);
438
613
}
439
440
5461
void Environment::InitializeMainContext(Local<Context> context,
441
                                        const EnvSerializeInfo* env_info) {
442
5461
  context_.Reset(context->GetIsolate(), context);
443
5461
  AssignToContext(context, ContextInfo(""));
444
5461
  if (env_info != nullptr) {
445
4848
    DeserializeProperties(env_info);
446
  } else {
447
613
    CreateProperties();
448
  }
449
450
5461
  if (!options_->force_async_hooks_checks) {
451
1
    async_hooks_.no_force_checks();
452
  }
453
454
  // By default, always abort when --abort-on-uncaught-exception was passed.
455
5461
  should_abort_on_uncaught_toggle_[0] = 1;
456
457
5461
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
458
                           environment_start_time_);
459
5461
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
460
                           per_process::node_start_time);
461
462
5461
  if (per_process::v8_initialized) {
463
5413
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
464
                            performance::performance_v8_start);
465
  }
466
5461
}
467
468
955584
Environment::~Environment() {
469
  if (Environment** interrupt_data = interrupt_data_.load()) {
470
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
471
    // then force V8 to run interrupts by compiling and running an empty script
472
    // so as not to leak memory.
473
10
    *interrupt_data = nullptr;
474
475
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
476
20
    HandleScope handle_scope(isolate());
477
20
    TryCatch try_catch(isolate());
478
20
    Context::Scope context_scope(context());
479
480
#ifdef DEBUG
481
    bool consistency_check = false;
482
    isolate()->RequestInterrupt([](Isolate*, void* data) {
483
      *static_cast<bool*>(data) = true;
484
    }, &consistency_check);
485
#endif
486
487
    Local<Script> script;
488
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
489
10
      USE(script->Run(context()));
490
491
    DCHECK(consistency_check);
492
  }
493
494
  // FreeEnvironment() should have set this.
495
4977
  CHECK(is_stopping());
496
497
4977
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
498
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
499
                                          0);
500
  }
501
502
4977
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
503
      BuildEmbedderGraph, this);
504
505
9954
  HandleScope handle_scope(isolate());
506
507
#if HAVE_INSPECTOR
508
  // Destroy inspector agent before erasing the context. The inspector
509
  // destructor depends on the context still being accessible.
510
4977
  inspector_agent_.reset();
511
#endif
512
513
9954
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
514
                                             nullptr);
515
516
4977
  if (trace_state_observer_) {
517
4977
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
518
4977
    CHECK_NOT_NULL(writer);
519
4977
    if (TracingController* tracing_controller = writer->GetTracingController())
520
4931
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
521
  }
522
523

9363
  TRACE_EVENT_NESTABLE_ASYNC_END0(
524
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
525
526
  // Do not unload addons on the main thread. Some addons need to retain memory
527
  // beyond the Environment's lifetime, and unloading them early would break
528
  // them; with Worker threads, we have the opportunity to be stricter.
529
  // Also, since the main thread usually stops just before the process exits,
530
  // this is far less relevant here.
531
4977
  if (!is_main_thread()) {
532
    // Dereference all addons that were loaded into this environment.
533
572
    for (binding::DLib& addon : loaded_addons_) {
534
14
      addon.Close();
535
    }
536
  }
537
538
4977
  CHECK_EQ(base_object_count_, 0);
539
4977
}
540
541
5428
void Environment::InitializeLibuv() {
542
10856
  HandleScope handle_scope(isolate());
543
5428
  Context::Scope context_scope(context());
544
545
5428
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
546
5428
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
547
548
5428
  uv_check_init(event_loop(), immediate_check_handle());
549
5428
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
550
551
5428
  uv_idle_init(event_loop(), immediate_idle_handle());
552
553
5428
  uv_check_start(immediate_check_handle(), CheckImmediate);
554
555
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
556
  // but not all samples are created equal; mark the wall clock time spent in
557
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
558
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
559
5428
  uv_prepare_init(event_loop(), &idle_prepare_handle_);
560
5428
  uv_check_init(event_loop(), &idle_check_handle_);
561
562
5428
  uv_async_init(
563
      event_loop(),
564
      &task_queues_async_,
565
5090
      [](uv_async_t* async) {
566
5090
        Environment* env = ContainerOf(
567
5090
            &Environment::task_queues_async_, async);
568
10174
        HandleScope handle_scope(env->isolate());
569
5090
        Context::Scope context_scope(env->context());
570
5090
        env->RunAndClearNativeImmediates();
571
5084
      });
572
5428
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
573
5428
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
574
5428
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
575
576
  {
577
10856
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
578
5428
    task_queues_async_initialized_ = true;
579

10856
    if (native_immediates_threadsafe_.size() > 0 ||
580
5428
        native_immediates_interrupts_.size() > 0) {
581
4843
      uv_async_send(&task_queues_async_);
582
    }
583
  }
584
585
  // Register clean-up cb to be called to clean up the handles
586
  // when the environment is freed, note that they are not cleaned in
587
  // the one environment per process setup, but will be called in
588
  // FreeEnvironment.
589
5428
  RegisterHandleCleanups();
590
591
5428
  StartProfilerIdleNotifier();
592
5428
}
593
594
174
void Environment::ExitEnv() {
595
174
  set_can_call_into_js(false);
596
174
  set_stopping(true);
597
174
  isolate_->TerminateExecution();
598
348
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
599
174
}
600
601
5428
void Environment::RegisterHandleCleanups() {
602
5428
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
603
29664
                                        void* arg) {
604
29664
    handle->data = env;
605
606
29664
    env->CloseHandle(handle, [](uv_handle_t* handle) {
607
#ifdef DEBUG
608
      memset(handle, 0xab, uv_handle_size(handle->type));
609
#endif
610
29664
    });
611
29664
  };
612
613
32568
  auto register_handle = [&](uv_handle_t* handle) {
614
32568
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
615
37996
  };
616
5428
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
617
5428
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
618
5428
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
619
5428
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
620
5428
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
621
5428
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
622
5428
}
623
624
9948
void Environment::CleanupHandles() {
625
  {
626
9948
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
627
9948
    task_queues_async_initialized_ = false;
628
  }
629
630
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
631
19896
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
632
633
9948
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
634
635
9964
  for (ReqWrapBase* request : req_wrap_queue_)
636
16
    request->Cancel();
637
638
12714
  for (HandleWrap* handle : handle_wrap_queue_)
639
5532
    handle->Close();
640
641
39612
  for (HandleCleanup& hc : handle_cleanup_queue_)
642
29664
    hc.cb_(this, hc.handle_, hc.arg_);
643
9948
  handle_cleanup_queue_.clear();
644
645
9403
  while (handle_cleanup_waiting_ != 0 ||
646

29301
         request_waiting_ != 0 ||
647
9950
         !handle_wrap_queue_.IsEmpty()) {
648
9403
    uv_run(event_loop(), UV_RUN_ONCE);
649
  }
650
9948
}
651
652
5428
void Environment::StartProfilerIdleNotifier() {
653
5428
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
654
177441
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
655
177441
    env->isolate()->SetIdle(true);
656
177441
  });
657
5428
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
658
177283
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
659
177283
    env->isolate()->SetIdle(false);
660
177283
  });
661
5428
}
662
663
499018
void Environment::PrintSyncTrace() const {
664
499018
  if (!trace_sync_io_) return;
665
666
2
  HandleScope handle_scope(isolate());
667
668
1
  fprintf(
669
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
670
1
  PrintStackTrace(isolate(),
671
                  StackTrace::CurrentStackTrace(
672
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
673
}
674
675
4977
void Environment::RunCleanup() {
676
4977
  started_cleanup_ = true;
677
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
678
9954
                              "RunCleanup", this);
679
4977
  bindings_.clear();
680
4977
  CleanupHandles();
681
682
14927
  while (!cleanup_hooks_.empty() ||
683
9956
         native_immediates_.size() > 0 ||
684

19904
         native_immediates_threadsafe_.size() > 0 ||
685
4977
         native_immediates_interrupts_.size() > 0) {
686
    // Copy into a vector, since we can't sort an unordered_set in-place.
687
    std::vector<CleanupHookCallback> callbacks(
688
9942
        cleanup_hooks_.begin(), cleanup_hooks_.end());
689
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
690
    // need to be able to check whether they were un-scheduled by another hook.
691
692
4971
    std::sort(callbacks.begin(), callbacks.end(),
693
676653
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
694
      // Sort in descending order so that the most recently inserted callbacks
695
      // are run first.
696
676653
      return a.insertion_order_counter_ > b.insertion_order_counter_;
697
    });
698
699
115575
    for (const CleanupHookCallback& cb : callbacks) {
700
110604
      if (cleanup_hooks_.count(cb) == 0) {
701
        // This hook was removed from the `cleanup_hooks_` set during another
702
        // hook that was run earlier. Nothing to do here.
703
763
        continue;
704
      }
705
706
109841
      cb.fn_(cb.arg_);
707
109841
      cleanup_hooks_.erase(cb);
708
    }
709
4971
    CleanupHandles();
710
  }
711
712
4981
  for (const int fd : unmanaged_fds_) {
713
    uv_fs_t close_req;
714
4
    uv_fs_close(nullptr, &close_req, fd, nullptr);
715
4
    uv_fs_req_cleanup(&close_req);
716
  }
717
4977
}
718
719
5546
void Environment::RunAtExitCallbacks() {
720
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
721
11092
                              "AtExit", this);
722
16434
  for (ExitCallback at_exit : at_exit_functions_) {
723
10888
    at_exit.cb_(at_exit.arg_);
724
  }
725
5546
  at_exit_functions_.clear();
726
5546
}
727
728
10912
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
729
10912
  at_exit_functions_.push_front(ExitCallback{cb, arg});
730
10912
}
731
732
210654
void Environment::RunAndClearInterrupts() {
733
210654
  while (native_immediates_interrupts_.size() > 0) {
734
9269
    NativeImmediateQueue queue;
735
    {
736
18538
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
737
9269
      queue.ConcatMove(std::move(native_immediates_interrupts_));
738
    }
739
9269
    DebugSealHandleScope seal_handle_scope(isolate());
740
741
18541
    while (auto head = queue.Shift())
742
18544
      head->Call(this);
743
  }
744
201385
}
745
746
192321
void Environment::RunAndClearNativeImmediates(bool only_refed) {
747
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
748
384636
                              "RunAndClearNativeImmediates", this);
749
384636
  HandleScope handle_scope(isolate_);
750
384636
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
751
752
192321
  size_t ref_count = 0;
753
754
  // Handle interrupts first. These functions are not allowed to throw
755
  // exceptions, so we do not need to handle that.
756
192321
  RunAndClearInterrupts();
757
758
384640
  auto drain_list = [&](NativeImmediateQueue* queue) {
759
769274
    TryCatchScope try_catch(this);
760
384640
    DebugSealHandleScope seal_handle_scope(isolate());
761
444002
    while (auto head = queue->Shift()) {
762
59369
      bool is_refed = head->flags() & CallbackFlags::kRefed;
763
59369
      if (is_refed)
764
35647
        ref_count++;
765
766

59369
      if (is_refed || !only_refed)
767
59194
        head->Call(this);
768
769
59365
      head.reset();  // Destroy now so that this is also observed by try_catch.
770
771
59365
      if (UNLIKELY(try_catch.HasCaught())) {
772

3
        if (!try_catch.HasTerminated() && can_call_into_js())
773
3
          errors::TriggerUncaughtException(isolate(), try_catch);
774
775
1
        return true;
776
      }
777
59362
    }
778
384633
    return false;
779
192321
  };
780
192321
  while (drain_list(&native_immediates_)) {}
781
782
192318
  immediate_info()->ref_count_dec(ref_count);
783
784
192318
  if (immediate_info()->ref_count() == 0)
785
150953
    ToggleImmediateRef(false);
786
787
  // It is safe to check .size() first, because there is a causal relationship
788
  // between pushes to the threadsafe immediate list and this function being
789
  // called. For the common case, it's worth checking the size first before
790
  // establishing a mutex lock.
791
  // This is intentionally placed after the `ref_count` handling, because when
792
  // refed threadsafe immediates are created, they are not counted towards the
793
  // count in immediate_info() either.
794
192315
  NativeImmediateQueue threadsafe_immediates;
795
192318
  if (native_immediates_threadsafe_.size() > 0) {
796
1718
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
797
859
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
798
  }
799
192319
  while (drain_list(&threadsafe_immediates)) {}
800
192315
}
801
802
9276
void Environment::RequestInterruptFromV8() {
803
  // The Isolate may outlive the Environment, so some logic to handle the
804
  // situation in which the Environment is destroyed before the handler runs
805
  // is required.
806
807
  // We allocate a new pointer to a pointer to this Environment instance, and
808
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
809
  // callbacks are already scheduled to run and we can delete our own pointer
810
  // and just return. If it was nullptr previously, the Environment** is stored;
811
  // ~Environment sets the Environment* contained in it to nullptr, so that
812
  // the callback can check whether ~Environment has already run and it is thus
813
  // not safe to access the Environment instance itself.
814
9276
  Environment** interrupt_data = new Environment*(this);
815
9276
  Environment** dummy = nullptr;
816
9276
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
817
325
    delete interrupt_data;
818
325
    return;  // Already scheduled.
819
  }
820
821
8951
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
822
8943
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
823
8943
    Environment* env = *env_ptr;
824
8943
    if (env == nullptr) {
825
      // The Environment has already been destroyed. That should be okay; any
826
      // callback added before the Environment shuts down would have been
827
      // handled during cleanup.
828
10
      return;
829
    }
830
8933
    env->interrupt_data_.store(nullptr);
831
8933
    env->RunAndClearInterrupts();
832
  }, interrupt_data);
833
}
834
835
8684
void Environment::ScheduleTimer(int64_t duration_ms) {
836
8684
  if (started_cleanup_) return;
837
8684
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
838
}
839
840
2286
void Environment::ToggleTimerRef(bool ref) {
841
2286
  if (started_cleanup_) return;
842
843
2286
  if (ref) {
844
1678
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
845
  } else {
846
608
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
847
  }
848
}
849
850
7450
void Environment::RunTimers(uv_timer_t* handle) {
851
7450
  Environment* env = Environment::from_timer_handle(handle);
852
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
853
7450
                              "RunTimers", env);
854
855
7450
  if (!env->can_call_into_js())
856
    return;
857
858
7450
  HandleScope handle_scope(env->isolate());
859
7450
  Context::Scope context_scope(env->context());
860
861
7450
  Local<Object> process = env->process_object();
862
7450
  InternalCallbackScope scope(env, process, {0, 0});
863
864
7450
  Local<Function> cb = env->timers_callback_function();
865
  MaybeLocal<Value> ret;
866
7450
  Local<Value> arg = env->GetNow();
867
  // This code will loop until all currently due timers will process. It is
868
  // impossible for us to end up in an infinite loop due to how the JS-side
869
  // is structured.
870
31
  do {
871
7481
    TryCatchScope try_catch(env);
872
7481
    try_catch.SetVerbose(true);
873
7481
    ret = cb->Call(env->context(), process, 1, &arg);
874

7471
  } while (ret.IsEmpty() && env->can_call_into_js());
875
876
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
877
  // is reset back to `true` after being previously set to `false` then this
878
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
879
  // timers corruption will occur and all timers behaviour will become
880
  // entirely unpredictable.
881
7440
  if (ret.IsEmpty())
882
8
    return;
883
884
  // To allow for less JS-C++ boundary crossing, the value returned from JS
885
  // serves a few purposes:
886
  // 1. If it's 0, no more timers exist and the handle should be unrefed
887
  // 2. If it's > 0, the value represents the next timer's expiry and there
888
  //    is at least one timer remaining that is refed.
889
  // 3. If it's < 0, the absolute value represents the next timer's expiry
890
  //    and there are no timers that are refed.
891
  int64_t expiry_ms =
892
7432
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
893
894
7432
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
895
896
7432
  if (expiry_ms != 0) {
897
    int64_t duration_ms =
898
6490
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
899
900
6490
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
901
902
6490
    if (expiry_ms > 0)
903
6071
      uv_ref(h);
904
    else
905
419
      uv_unref(h);
906
  } else {
907
942
    uv_unref(h);
908
  }
909
}
910
911
912
177283
void Environment::CheckImmediate(uv_check_t* handle) {
913
177283
  Environment* env = Environment::from_immediate_check_handle(handle);
914
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
915
177283
                              "CheckImmediate", env);
916
917
177283
  HandleScope scope(env->isolate());
918
177283
  Context::Scope context_scope(env->context());
919
920
177283
  env->RunAndClearNativeImmediates();
921
922

177283
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
923
136323
    return;
924
925
941
  do {
926
41894
    MakeCallback(env->isolate(),
927
                 env->process_object(),
928
                 env->immediate_callback_function(),
929
                 0,
930
                 nullptr,
931
41901
                 {0, 0}).ToLocalChecked();
932

41894
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
933
934
40953
  if (env->immediate_info()->ref_count() == 0)
935
4623
    env->ToggleImmediateRef(false);
936
}
937
938
219715
void Environment::ToggleImmediateRef(bool ref) {
939
219715
  if (started_cleanup_) return;
940
941
209770
  if (ref) {
942
    // Idle handle is needed only to stop the event loop from blocking in poll.
943
64116
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
944
  } else {
945
145654
    uv_idle_stop(immediate_idle_handle());
946
  }
947
}
948
949
950
27665
Local<Value> Environment::GetNow() {
951
27665
  uv_update_time(event_loop());
952
27665
  uint64_t now = uv_now(event_loop());
953
27665
  CHECK_GE(now, timer_base());
954
27665
  now -= timer_base();
955
27665
  if (now <= 0xffffffff)
956
55330
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
957
  else
958
    return Number::New(isolate(), static_cast<double>(now));
959
}
960
961
28
void CollectExceptionInfo(Environment* env,
962
                          Local<Object> obj,
963
                          int errorno,
964
                          const char* err_string,
965
                          const char* syscall,
966
                          const char* message,
967
                          const char* path,
968
                          const char* dest) {
969
28
  obj->Set(env->context(),
970
           env->errno_string(),
971
112
           Integer::New(env->isolate(), errorno)).Check();
972
973
28
  obj->Set(env->context(), env->code_string(),
974
84
           OneByteString(env->isolate(), err_string)).Check();
975
976
28
  if (message != nullptr) {
977
28
    obj->Set(env->context(), env->message_string(),
978
112
             OneByteString(env->isolate(), message)).Check();
979
  }
980
981
  Local<Value> path_buffer;
982
28
  if (path != nullptr) {
983
    path_buffer =
984
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
985
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
986
  }
987
988
  Local<Value> dest_buffer;
989
28
  if (dest != nullptr) {
990
    dest_buffer =
991
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
992
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
993
  }
994
995
28
  if (syscall != nullptr) {
996
28
    obj->Set(env->context(), env->syscall_string(),
997
112
             OneByteString(env->isolate(), syscall)).Check();
998
  }
999
28
}
1000
1001
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
1002
                                         int errorno,
1003
                                         const char* syscall,
1004
                                         const char* message,
1005
                                         const char* path,
1006
                                         const char* dest) {
1007

28
  if (!object->IsObject() || errorno == 0)
1008
    return;
1009
1010
28
  Local<Object> obj = object.As<Object>();
1011
28
  const char* err_string = uv_err_name(errorno);
1012
1013

28
  if (message == nullptr || message[0] == '\0') {
1014
28
    message = uv_strerror(errorno);
1015
  }
1016
1017
28
  node::CollectExceptionInfo(this, obj, errorno, err_string,
1018
                             syscall, message, path, dest);
1019
}
1020
1021
5461
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1022
5461
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
1023
1024
6
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
1025
    Local<Context> context, SnapshotCreator* creator) {
1026
6
  return {fields_.Serialize(context, creator)};
1027
}
1028
1029
4848
void ImmediateInfo::Deserialize(Local<Context> context) {
1030
4848
  fields_.Deserialize(context);
1031
4848
}
1032
1033
6
std::ostream& operator<<(std::ostream& output,
1034
                         const ImmediateInfo::SerializeInfo& i) {
1035
6
  output << "{ " << i.fields << " }";
1036
6
  return output;
1037
}
1038
1039
22
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1040
22
  tracker->TrackField("fields", fields_);
1041
22
}
1042
1043
6
TickInfo::SerializeInfo TickInfo::Serialize(Local<Context> context,
1044
                                            SnapshotCreator* creator) {
1045
6
  return {fields_.Serialize(context, creator)};
1046
}
1047
1048
4848
void TickInfo::Deserialize(Local<Context> context) {
1049
4848
  fields_.Deserialize(context);
1050
4848
}
1051
1052
6
std::ostream& operator<<(std::ostream& output,
1053
                         const TickInfo::SerializeInfo& i) {
1054
6
  output << "{ " << i.fields << " }";
1055
6
  return output;
1056
}
1057
1058
22
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1059
22
  tracker->TrackField("fields", fields_);
1060
22
}
1061
1062
5461
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1063
    : fields_(
1064
5461
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1065
1066
5461
AsyncHooks::AsyncHooks(Isolate* isolate, const SerializeInfo* info)
1067
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1068
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1069
      async_id_fields_(
1070
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1071

5461
      info_(info) {
1072
10922
  HandleScope handle_scope(isolate);
1073
5461
  if (info == nullptr) {
1074
613
    clear_async_id_stack();
1075
1076
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1077
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1078
    // See discussion in https://github.com/nodejs/node/pull/15454
1079
    // When removing this, do it by reverting the commit. Otherwise the test
1080
    // and flag changes won't be included.
1081
613
    fields_[kCheck] = 1;
1082
1083
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1084
    // specified default value and it should fallback to the executionAsyncId.
1085
    // 0 is not used as the magic value, because that indicates a missing
1086
    // context which is different from a default context.
1087
613
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1088
1089
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1090
    // context during bootstrap (code that runs before entering uv_run()).
1091
613
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1092
  }
1093
5461
}
1094
1095
4848
void AsyncHooks::Deserialize(Local<Context> context) {
1096
4848
  async_ids_stack_.Deserialize(context);
1097
4848
  fields_.Deserialize(context);
1098
4848
  async_id_fields_.Deserialize(context);
1099
4848
  if (info_->js_execution_async_resources != 0) {
1100
4848
    Local<Array> arr = context->GetDataFromSnapshotOnce<Array>(
1101
9696
                                  info_->js_execution_async_resources)
1102
4848
                              .ToLocalChecked();
1103
4848
    js_execution_async_resources_.Reset(context->GetIsolate(), arr);
1104
  }
1105
1106
4848
  native_execution_async_resources_.resize(
1107
4848
      info_->native_execution_async_resources.size());
1108
4848
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1109
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1110
                                   info_->native_execution_async_resources[i])
1111
                               .ToLocalChecked();
1112
    native_execution_async_resources_[i].Reset(context->GetIsolate(), obj);
1113
  }
1114
4848
  info_ = nullptr;
1115
4848
}
1116
1117
6
std::ostream& operator<<(std::ostream& output,
1118
                         const std::vector<SnapshotIndex>& v) {
1119
6
  output << "{ ";
1120
6
  for (const SnapshotIndex i : v) {
1121
    output << i << ", ";
1122
  }
1123
6
  output << " }";
1124
6
  return output;
1125
}
1126
1127
6
std::ostream& operator<<(std::ostream& output,
1128
                         const AsyncHooks::SerializeInfo& i) {
1129
  output << "{\n"
1130
6
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1131
6
         << "  " << i.fields << ",  // fields\n"
1132
6
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1133
6
         << "  " << i.js_execution_async_resources
1134
         << ",  // js_execution_async_resources\n"
1135
6
         << "  " << i.native_execution_async_resources
1136
         << ",  // native_execution_async_resources\n"
1137
6
         << "}";
1138
6
  return output;
1139
}
1140
1141
6
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1142
                                                SnapshotCreator* creator) {
1143
6
  SerializeInfo info;
1144
6
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1145
6
  info.fields = fields_.Serialize(context, creator);
1146
6
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1147
6
  if (!js_execution_async_resources_.IsEmpty()) {
1148
6
    info.js_execution_async_resources = creator->AddData(
1149
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1150
6
    CHECK_NE(info.js_execution_async_resources, 0);
1151
  } else {
1152
    info.js_execution_async_resources = 0;
1153
  }
1154
1155
6
  info.native_execution_async_resources.resize(
1156
      native_execution_async_resources_.size());
1157
6
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1158
    info.native_execution_async_resources[i] = creator->AddData(
1159
        context,
1160
        native_execution_async_resources_[i].Get(context->GetIsolate()));
1161
  }
1162
6
  CHECK_EQ(contexts_.size(), 1);
1163

12
  CHECK_EQ(contexts_[0], env()->context());
1164
6
  CHECK(js_promise_hooks_[0].IsEmpty());
1165
6
  CHECK(js_promise_hooks_[1].IsEmpty());
1166
6
  CHECK(js_promise_hooks_[2].IsEmpty());
1167
6
  CHECK(js_promise_hooks_[3].IsEmpty());
1168
1169
6
  return info;
1170
}
1171
1172
22
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1173
22
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1174
22
  tracker->TrackField("fields", fields_);
1175
22
  tracker->TrackField("async_id_fields", async_id_fields_);
1176
22
  tracker->TrackField("js_promise_hooks", js_promise_hooks_);
1177
22
}
1178
1179
4
void AsyncHooks::grow_async_ids_stack() {
1180
4
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1181
1182
4
  env()->async_hooks_binding()->Set(
1183
      env()->context(),
1184
      env()->async_ids_stack_string(),
1185
12
      async_ids_stack_.GetJSArray()).Check();
1186
4
}
1187
1188
552
void Environment::Exit(int exit_code) {
1189
552
  if (options()->trace_exit) {
1190
4
    HandleScope handle_scope(isolate());
1191
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1192
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1193
1194
2
    if (is_main_thread()) {
1195
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1196
    } else {
1197
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1198
              uv_os_getpid(), thread_id());
1199
    }
1200
1201
2
    fprintf(
1202
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1203
2
    PrintStackTrace(isolate(),
1204
                    StackTrace::CurrentStackTrace(
1205
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1206
  }
1207
552
  process_exit_handler_(this, exit_code);
1208
73
}
1209
1210
5483
void Environment::stop_sub_worker_contexts() {
1211
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1212
1213
5483
  while (!sub_worker_contexts_.empty()) {
1214
27
    Worker* w = *sub_worker_contexts_.begin();
1215
27
    remove_sub_worker_context(w);
1216
27
    w->Exit(1);
1217
27
    w->JoinThread();
1218
  }
1219
5456
}
1220
1221
10
Environment* Environment::worker_parent_env() const {
1222
10
  if (worker_context() == nullptr) return nullptr;
1223
  return worker_context()->env();
1224
}
1225
1226
56787
void Environment::AddUnmanagedFd(int fd) {
1227
56787
  if (!tracks_unmanaged_fds()) return;
1228
2014
  auto result = unmanaged_fds_.insert(fd);
1229
2014
  if (!result.second) {
1230
    ProcessEmitWarning(
1231
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1232
  }
1233
}
1234
1235
56417
void Environment::RemoveUnmanagedFd(int fd) {
1236
56417
  if (!tracks_unmanaged_fds()) return;
1237
2010
  size_t removed_count = unmanaged_fds_.erase(fd);
1238
2010
  if (removed_count == 0) {
1239
    ProcessEmitWarning(
1240
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1241
  }
1242
}
1243
1244
4781
void Environment::PrintInfoForSnapshotIfDebug() {
1245
4781
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1246
    fprintf(stderr, "BaseObjects at the exit of the Environment:\n");
1247
    PrintAllBaseObjects();
1248
    fprintf(stderr, "\nNative modules without cache:\n");
1249
    for (const auto& s : native_modules_without_cache) {
1250
      fprintf(stderr, "%s\n", s.c_str());
1251
    }
1252
    fprintf(stderr, "\nNative modules with cache:\n");
1253
    for (const auto& s : native_modules_with_cache) {
1254
      fprintf(stderr, "%s\n", s.c_str());
1255
    }
1256
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1257
    for (const auto mod : internal_bindings) {
1258
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1259
    }
1260
  }
1261
4781
}
1262
1263
void Environment::PrintAllBaseObjects() {
1264
  size_t i = 0;
1265
  std::cout << "BaseObjects\n";
1266
  ForEachBaseObject([&](BaseObject* obj) {
1267
    std::cout << "#" << i++ << " " << obj << ": " <<
1268
      obj->MemoryInfoName() << "\n";
1269
  });
1270
}
1271
1272
4781
void Environment::VerifyNoStrongBaseObjects() {
1273
  // When a process exits cleanly, i.e. because the event loop ends up without
1274
  // things to wait for, the Node.js objects that are left on the heap should
1275
  // be:
1276
  //
1277
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1278
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1279
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1280
  //   4. an inactive libuv handle (essentially the same here)
1281
  //
1282
  // There are a few exceptions to this rule, but generally, if there are
1283
  // C++-backed Node.js objects on the heap that do not fall into the above
1284
  // categories, we may be looking at a potential memory leak. Most likely,
1285
  // the cause is a missing MakeWeak() call on the corresponding object.
1286
  //
1287
  // In order to avoid this kind of problem, we check the list of BaseObjects
1288
  // for these criteria. Currently, we only do so when explicitly instructed to
1289
  // or when in debug mode (where --verify-base-objects is always-on).
1290
1291
4781
  if (!options()->verify_base_objects) return;
1292
1293
  ForEachBaseObject([](BaseObject* obj) {
1294
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1295
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1296
            obj->MemoryInfoName().c_str());
1297
    fflush(stderr);
1298
    ABORT();
1299
  });
1300
}
1301
1302
6
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1303
6
  EnvSerializeInfo info;
1304
6
  Local<Context> ctx = context();
1305
1306
6
  SerializeBindingData(this, creator, &info);
1307
  // Currently all modules are compiled without cache in builtin snapshot
1308
  // builder.
1309
12
  info.native_modules = std::vector<std::string>(
1310
6
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1311
1312
6
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1313
6
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1314
6
  info.tick_info = tick_info_.Serialize(ctx, creator);
1315
6
  info.performance_state = performance_state_->Serialize(ctx, creator);
1316
6
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1317
6
  info.should_abort_on_uncaught_toggle =
1318
6
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1319
1320
6
  size_t id = 0;
1321
#define V(PropertyName, TypeName)                                              \
1322
  do {                                                                         \
1323
    Local<TypeName> field = PropertyName();                                    \
1324
    if (!field.IsEmpty()) {                                                    \
1325
      size_t index = creator->AddData(field);                                  \
1326
      info.persistent_templates.push_back({#PropertyName, id, index});         \
1327
    }                                                                          \
1328
    id++;                                                                      \
1329
  } while (0);
1330


















336
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1331
#undef V
1332
1333
6
  id = 0;
1334
#define V(PropertyName, TypeName)                                              \
1335
  do {                                                                         \
1336
    Local<TypeName> field = PropertyName();                                    \
1337
    if (!field.IsEmpty()) {                                                    \
1338
      size_t index = creator->AddData(ctx, field);                             \
1339
      info.persistent_values.push_back({#PropertyName, id, index});            \
1340
    }                                                                          \
1341
    id++;                                                                      \
1342
  } while (0);
1343




























534
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1344
#undef V
1345
1346
6
  info.context = creator->AddData(ctx, context());
1347
6
  return info;
1348
}
1349
1350
18
std::ostream& operator<<(std::ostream& output,
1351
                         const std::vector<PropInfo>& vec) {
1352
18
  output << "{\n";
1353
336
  for (const auto& info : vec) {
1354
636
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1355
636
           << std::to_string(info.index) << " },\n";
1356
  }
1357
18
  output << "}";
1358
18
  return output;
1359
}
1360
1361
6
std::ostream& operator<<(std::ostream& output,
1362
                         const std::vector<std::string>& vec) {
1363
6
  output << "{\n";
1364
504
  for (const auto& info : vec) {
1365
498
    output << "  \"" << info << "\",\n";
1366
  }
1367
6
  output << "}";
1368
6
  return output;
1369
}
1370
1371
6
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1372
  output << "{\n"
1373
6
         << "// -- bindings begins --\n"
1374
6
         << i.bindings << ",\n"
1375
         << "// -- bindings ends --\n"
1376
6
         << "// -- native_modules begins --\n"
1377
6
         << i.native_modules << ",\n"
1378
         << "// -- native_modules ends --\n"
1379
6
         << "// -- async_hooks begins --\n"
1380
6
         << i.async_hooks << ",\n"
1381
6
         << "// -- async_hooks ends --\n"
1382
6
         << i.tick_info << ",  // tick_info\n"
1383
6
         << i.immediate_info << ",  // immediate_info\n"
1384
6
         << "// -- performance_state begins --\n"
1385
6
         << i.performance_state << ",\n"
1386
6
         << "// -- performance_state ends --\n"
1387
6
         << i.stream_base_state << ",  // stream_base_state\n"
1388
6
         << i.should_abort_on_uncaught_toggle
1389
         << ",  // should_abort_on_uncaught_toggle\n"
1390
6
         << "// -- persistent_templates begins --\n"
1391
6
         << i.persistent_templates << ",\n"
1392
         << "// persistent_templates ends --\n"
1393
6
         << "// -- persistent_values begins --\n"
1394
6
         << i.persistent_values << ",\n"
1395
6
         << "// -- persistent_values ends --\n"
1396
6
         << i.context << ",  // context\n"
1397
6
         << "}";
1398
6
  return output;
1399
}
1400
1401
14544
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1402
                                            Local<Object> holder,
1403
                                            int index,
1404
                                            InternalFieldInfo* info) {
1405
29088
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1406
14544
  deserialize_requests_.push_back(std::move(request));
1407
14544
}
1408
1409
4848
void Environment::RunDeserializeRequests() {
1410
9696
  HandleScope scope(isolate());
1411
4848
  Local<Context> ctx = context();
1412
4848
  Isolate* is = isolate();
1413
19392
  while (!deserialize_requests_.empty()) {
1414
29088
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1415
14544
    deserialize_requests_.pop_front();
1416
14544
    Local<Object> holder = request.holder.Get(is);
1417
14544
    request.cb(ctx, holder, request.index, request.info);
1418
    request.holder.Reset();
1419
14544
    request.info->Delete();
1420
  }
1421
4848
}
1422
1423
4848
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1424
4848
  Local<Context> ctx = context();
1425
1426
4848
  RunDeserializeRequests();
1427
1428
4848
  native_modules_in_snapshot = info->native_modules;
1429
4848
  async_hooks_.Deserialize(ctx);
1430
4848
  immediate_info_.Deserialize(ctx);
1431
4848
  tick_info_.Deserialize(ctx);
1432
4848
  performance_state_->Deserialize(ctx);
1433
4848
  stream_base_state_.Deserialize(ctx);
1434
4848
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1435
1436
4848
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1437
    fprintf(stderr, "deserializing...\n");
1438
    std::cerr << *info << "\n";
1439
  }
1440
1441
4848
  const std::vector<PropInfo>& templates = info->persistent_templates;
1442
4848
  size_t i = 0;  // index to the array
1443
4848
  size_t id = 0;
1444
#define SetProperty(PropertyName, TypeName, vector, type, from)                \
1445
  do {                                                                         \
1446
    if (vector.size() > i && id == vector[i].id) {                             \
1447
      const PropInfo& d = vector[i];                                           \
1448
      DCHECK_EQ(d.name, #PropertyName);                                        \
1449
      MaybeLocal<TypeName> maybe_field =                                       \
1450
          from->GetDataFromSnapshotOnce<TypeName>(d.index);                    \
1451
      Local<TypeName> field;                                                   \
1452
      if (!maybe_field.ToLocal(&field)) {                                      \
1453
        fprintf(stderr,                                                        \
1454
                "Failed to deserialize environment " #type " " #PropertyName   \
1455
                "\n");                                                         \
1456
      }                                                                        \
1457
      set_##PropertyName(field);                                               \
1458
      i++;                                                                     \
1459
    }                                                                          \
1460
  } while (0);                                                                 \
1461
  id++;
1462
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1463
                                              templates, template, isolate_)
1464








































































189072
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1465
#undef V
1466
1467
4848
  i = 0;  // index to the array
1468
4848
  id = 0;
1469
4848
  const std::vector<PropInfo>& values = info->persistent_values;
1470
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1471
                                              values, value, ctx)
1472


















































































































455712
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1473
#undef V
1474
#undef SetProperty
1475
1476
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1477
9696
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1478
  Local<Context> ctx_from_snapshot;
1479
4848
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1480
    fprintf(stderr,
1481
            "Failed to deserialize context back reference from the snapshot\n");
1482
  }
1483
4848
  CHECK_EQ(ctx_from_snapshot, ctx);
1484
4848
}
1485
1486
1
uint64_t GuessMemoryAvailableToTheProcess() {
1487
1
  uint64_t free_in_system = uv_get_free_memory();
1488
1
  size_t allowed = uv_get_constrained_memory();
1489
1
  if (allowed == 0) {
1490
    return free_in_system;
1491
  }
1492
  size_t rss;
1493
1
  int err = uv_resident_set_memory(&rss);
1494
1
  if (err) {
1495
    return free_in_system;
1496
  }
1497
1
  if (allowed < rss) {
1498
    // Something is probably wrong. Fallback to the free memory.
1499
    return free_in_system;
1500
  }
1501
  // There may still be room for swap, but we will just leave it here.
1502
1
  return allowed - rss;
1503
}
1504
1505
22
void Environment::BuildEmbedderGraph(Isolate* isolate,
1506
                                     EmbedderGraph* graph,
1507
                                     void* data) {
1508
22
  MemoryTracker tracker(isolate, graph);
1509
22
  Environment* env = static_cast<Environment*>(data);
1510
22
  tracker.Track(env);
1511
22
  env->ForEachBaseObject([&](BaseObject* obj) {
1512
440
    if (obj->IsDoneInitializing())
1513
439
      tracker.Track(obj);
1514
440
  });
1515
22
}
1516
1517
1
size_t Environment::NearHeapLimitCallback(void* data,
1518
                                          size_t current_heap_limit,
1519
                                          size_t initial_heap_limit) {
1520
1
  Environment* env = static_cast<Environment*>(data);
1521
1522
  Debug(env,
1523
        DebugCategory::DIAGNOSTICS,
1524
        "Invoked NearHeapLimitCallback, processing=%d, "
1525
        "current_limit=%" PRIu64 ", "
1526
        "initial_limit=%" PRIu64 "\n",
1527
1
        env->is_processing_heap_limit_callback_,
1528
2
        static_cast<uint64_t>(current_heap_limit),
1529
1
        static_cast<uint64_t>(initial_heap_limit));
1530
1531
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1532
1
  size_t young_gen_size = 0;
1533
1
  size_t old_gen_size = 0;
1534
1535
1
  HeapSpaceStatistics stats;
1536
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1537
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1538
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1539

15
    if (strcmp(stats.space_name(), "new_space") == 0 ||
1540
7
        strcmp(stats.space_name(), "new_large_object_space") == 0) {
1541
2
      young_gen_size += stats.space_used_size();
1542
    } else {
1543
6
      old_gen_size += stats.space_used_size();
1544
    }
1545
  }
1546
1547
  Debug(env,
1548
        DebugCategory::DIAGNOSTICS,
1549
        "max_young_gen_size=%" PRIu64 ", "
1550
        "young_gen_size=%" PRIu64 ", "
1551
        "old_gen_size=%" PRIu64 ", "
1552
        "total_size=%" PRIu64 "\n",
1553
2
        static_cast<uint64_t>(max_young_gen_size),
1554
2
        static_cast<uint64_t>(young_gen_size),
1555
2
        static_cast<uint64_t>(old_gen_size),
1556
1
        static_cast<uint64_t>(young_gen_size + old_gen_size));
1557
1558
1
  uint64_t available = GuessMemoryAvailableToTheProcess();
1559
  // TODO(joyeecheung): get a better estimate about the native memory
1560
  // usage into the overhead, e.g. based on the count of objects.
1561
1
  uint64_t estimated_overhead = max_young_gen_size;
1562
  Debug(env,
1563
        DebugCategory::DIAGNOSTICS,
1564
        "Estimated available memory=%" PRIu64 ", "
1565
        "estimated overhead=%" PRIu64 "\n",
1566
2
        static_cast<uint64_t>(available),
1567
1
        static_cast<uint64_t>(estimated_overhead));
1568
1569
  // This might be hit when the snapshot is being taken in another
1570
  // NearHeapLimitCallback invocation.
1571
  // When taking the snapshot, objects in the young generation may be
1572
  // promoted to the old generation, result in increased heap usage,
1573
  // but it should be no more than the young generation size.
1574
  // Ideally, this should be as small as possible - the heap limit
1575
  // can only be restored when the heap usage falls down below the
1576
  // new limit, so in a heap with unbounded growth the isolate
1577
  // may eventually crash with this new limit - effectively raising
1578
  // the heap limit to the new one.
1579
1
  if (env->is_processing_heap_limit_callback_) {
1580
    size_t new_limit = initial_heap_limit + max_young_gen_size;
1581
    Debug(env,
1582
          DebugCategory::DIAGNOSTICS,
1583
          "Not generating snapshots in nested callback. "
1584
          "new_limit=%" PRIu64 "\n",
1585
          static_cast<uint64_t>(new_limit));
1586
    return new_limit;
1587
  }
1588
1589
  // Estimate whether the snapshot is going to use up all the memory
1590
  // available to the process. If so, just give up to prevent the system
1591
  // from killing the process for a system OOM.
1592
1
  if (estimated_overhead > available) {
1593
    Debug(env,
1594
          DebugCategory::DIAGNOSTICS,
1595
          "Not generating snapshots because it's too risky.\n");
1596
    env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1597
                                                initial_heap_limit);
1598
    return current_heap_limit;
1599
  }
1600
1601
  // Take the snapshot synchronously.
1602
1
  env->is_processing_heap_limit_callback_ = true;
1603
1604
2
  std::string dir = env->options()->diagnostic_dir;
1605
1
  if (dir.empty()) {
1606
1
    dir = env->GetCwd();
1607
  }
1608
2
  DiagnosticFilename name(env, "Heap", "heapsnapshot");
1609
1
  std::string filename = dir + kPathSeparator + (*name);
1610
1611
1
  Debug(env, DebugCategory::DIAGNOSTICS, "Start generating %s...\n", *name);
1612
1613
  // Remove the callback first in case it's triggered when generating
1614
  // the snapshot.
1615
1
  env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1616
                                              initial_heap_limit);
1617
1618
1
  heap::WriteSnapshot(env->isolate(), filename.c_str());
1619
1
  env->heap_limit_snapshot_taken_ += 1;
1620
1621
  // Don't take more snapshots than the number specified by
1622
  // --heapsnapshot-near-heap-limit.
1623
2
  if (env->heap_limit_snapshot_taken_ <
1624
1
      env->options_->heap_snapshot_near_heap_limit) {
1625
    env->isolate()->AddNearHeapLimitCallback(NearHeapLimitCallback, env);
1626
  }
1627
1628
1
  FPrintF(stderr, "Wrote snapshot to %s\n", filename.c_str());
1629
  // Tell V8 to reset the heap limit once the heap usage falls down to
1630
  // 95% of the initial limit.
1631
1
  env->isolate()->AutomaticallyRestoreInitialHeapLimit(0.95);
1632
1633
1
  env->is_processing_heap_limit_callback_ = false;
1634
1
  return initial_heap_limit;
1635
}
1636
1637
22
inline size_t Environment::SelfSize() const {
1638
22
  size_t size = sizeof(*this);
1639
  // Remove non pointer fields that will be tracked in MemoryInfo()
1640
  // TODO(joyeecheung): refactor the MemoryTracker interface so
1641
  // this can be done for common types within the Track* calls automatically
1642
  // if a certain scope is entered.
1643
22
  size -= sizeof(async_hooks_);
1644
22
  size -= sizeof(tick_info_);
1645
22
  size -= sizeof(immediate_info_);
1646
22
  return size;
1647
}
1648
1649
22
void Environment::MemoryInfo(MemoryTracker* tracker) const {
1650
  // Iteratable STLs have their own sizes subtracted from the parent
1651
  // by default.
1652
22
  tracker->TrackField("isolate_data", isolate_data_);
1653
22
  tracker->TrackField("native_modules_with_cache", native_modules_with_cache);
1654
22
  tracker->TrackField("native_modules_without_cache",
1655
22
                      native_modules_without_cache);
1656
22
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
1657
22
  tracker->TrackField("exec_argv", exec_argv_);
1658
22
  tracker->TrackField("should_abort_on_uncaught_toggle",
1659
22
                      should_abort_on_uncaught_toggle_);
1660
22
  tracker->TrackField("stream_base_state", stream_base_state_);
1661
22
  tracker->TrackFieldWithSize(
1662
22
      "cleanup_hooks", cleanup_hooks_.size() * sizeof(CleanupHookCallback));
1663
22
  tracker->TrackField("async_hooks", async_hooks_);
1664
22
  tracker->TrackField("immediate_info", immediate_info_);
1665
22
  tracker->TrackField("tick_info", tick_info_);
1666
1667
#define V(PropertyName, TypeName)                                              \
1668
  tracker->TrackField(#PropertyName, PropertyName());
1669
22
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1670
#undef V
1671
1672
  // FIXME(joyeecheung): track other fields in Environment.
1673
  // Currently MemoryTracker is unable to track these
1674
  // correctly:
1675
  // - Internal types that do not implement MemoryRetainer yet
1676
  // - STL containers with MemoryRetainer* inside
1677
  // - STL containers with numeric types inside that should not have their
1678
  //   nodes elided e.g. numeric keys in maps.
1679
  // We also need to make sure that when we add a non-pointer field as its own
1680
  // node, we shift its sizeof() size out of the Environment node.
1681
22
}
1682
1683
694357
void Environment::RunWeakRefCleanup() {
1684
694357
  isolate()->ClearKeptObjects();
1685
694357
}
1686
1687
// Not really any better place than env.cc at this moment.
1688
103994
void BaseObject::DeleteMe(void* data) {
1689
103994
  BaseObject* self = static_cast<BaseObject*>(data);
1690

108039
  if (self->has_pointer_data() &&
1691
4045
      self->pointer_data()->strong_ptr_count > 0) {
1692
274
    return self->Detach();
1693
  }
1694
103720
  delete self;
1695
}
1696
1697
386
bool BaseObject::IsDoneInitializing() const { return true; }
1698
1699
439
Local<Object> BaseObject::WrappedObject() const {
1700
439
  return object();
1701
}
1702
1703
878
bool BaseObject::IsRootNode() const {
1704
1756
  return !persistent_handle_.IsWeak();
1705
}
1706
1707
82533
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1708
82533
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1709
82533
  if (tmpl.IsEmpty()) {
1710
613
    tmpl = env->NewFunctionTemplate(nullptr);
1711
613
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1712
613
    env->set_base_object_ctor_template(tmpl);
1713
  }
1714
82533
  return tmpl;
1715
}
1716
1717
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1718
  return IsWeakOrDetached();
1719
}
1720
1721
}  // namespace node