GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 741 808 91.7 %
Date: 2022-05-16 04:15:04 Branches: 1003 1908 52.6 %

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::Function;
38
using v8::FunctionTemplate;
39
using v8::HandleScope;
40
using v8::HeapSpaceStatistics;
41
using v8::Integer;
42
using v8::Isolate;
43
using v8::Local;
44
using v8::MaybeLocal;
45
using v8::NewStringType;
46
using v8::Number;
47
using v8::Object;
48
using v8::Private;
49
using v8::Script;
50
using v8::SnapshotCreator;
51
using v8::StackTrace;
52
using v8::String;
53
using v8::Symbol;
54
using v8::TracingController;
55
using v8::TryCatch;
56
using v8::Undefined;
57
using v8::Value;
58
using worker::Worker;
59
60
int const Environment::kNodeContextTag = 0x6e6f64;
61
void* const Environment::kNodeContextTagPtr = const_cast<void*>(
62
    static_cast<const void*>(&Environment::kNodeContextTag));
63
64
6
std::vector<size_t> IsolateData::Serialize(SnapshotCreator* creator) {
65
6
  Isolate* isolate = creator->GetIsolate();
66
6
  std::vector<size_t> indexes;
67
12
  HandleScope handle_scope(isolate);
68
  // XXX(joyeecheung): technically speaking, the indexes here should be
69
  // consecutive and we could just return a range instead of an array,
70
  // but that's not part of the V8 API contract so we use an array
71
  // just to be safe.
72
73
#define VP(PropertyName, StringValue) V(Private, PropertyName)
74
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
75
#define VS(PropertyName, StringValue) V(String, PropertyName)
76
#define V(TypeName, PropertyName)                                              \
77
  indexes.push_back(creator->AddData(PropertyName##_.Get(isolate)));
78
54
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
79
78
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
80
1644
  PER_ISOLATE_STRING_PROPERTIES(VS)
81
#undef V
82
#undef VY
83
#undef VS
84
#undef VP
85
354
  for (size_t i = 0; i < AsyncWrap::PROVIDERS_LENGTH; i++)
86
696
    indexes.push_back(creator->AddData(async_wrap_provider(i)));
87
88
6
  return indexes;
89
}
90
91
5172
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
92
5172
  size_t i = 0;
93
10344
  HandleScope handle_scope(isolate_);
94
95
#define VP(PropertyName, StringValue) V(Private, PropertyName)
96
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
97
#define VS(PropertyName, StringValue) V(String, PropertyName)
98
#define V(TypeName, PropertyName)                                              \
99
  do {                                                                         \
100
    MaybeLocal<TypeName> maybe_field =                                         \
101
        isolate_->GetDataFromSnapshotOnce<TypeName>((*indexes)[i++]);          \
102
    Local<TypeName> field;                                                     \
103
    if (!maybe_field.ToLocal(&field)) {                                        \
104
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
105
    }                                                                          \
106
    PropertyName##_.Set(isolate_, field);                                      \
107
  } while (0);
108




87924
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
109






129300
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
110








































































































































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

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

5160
  V(primordials_safe_map_prototype_object, "SafeMap");
295

5160
  V(primordials_safe_set_prototype_object, "SafeSet");
296

5160
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
297

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



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

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

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

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

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

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

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

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

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

184075
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
922
140292
    return;
923
924
946
  do {
925
44722
    MakeCallback(env->isolate(),
926
                 env->process_object(),
927
                 env->immediate_callback_function(),
928
                 0,
929
                 nullptr,
930
44729
                 {0, 0}).ToLocalChecked();
931

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

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

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

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

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


















336
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1356
#undef V
1357
1358
6
  id = 0;
1359
#define V(PropertyName, TypeName)                                              \
1360
  do {                                                                         \
1361
    Local<TypeName> field = PropertyName();                                    \
1362
    if (!field.IsEmpty()) {                                                    \
1363
      size_t index = creator->AddData(ctx, field);                             \
1364
      info.persistent_values.push_back({#PropertyName, id, index});            \
1365
    }                                                                          \
1366
    id++;                                                                      \
1367
  } while (0);
1368





























564
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1369
#undef V
1370
1371
6
  info.context = creator->AddData(ctx, context());
1372
6
  return info;
1373
}
1374
1375
18
std::ostream& operator<<(std::ostream& output,
1376
                         const std::vector<PropInfo>& vec) {
1377
18
  output << "{\n";
1378
360
  for (const auto& info : vec) {
1379
684
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1380
684
           << std::to_string(info.index) << " },\n";
1381
  }
1382
18
  output << "}";
1383
18
  return output;
1384
}
1385
1386
6
std::ostream& operator<<(std::ostream& output,
1387
                         const std::vector<std::string>& vec) {
1388
6
  output << "{\n";
1389
684
  for (const auto& info : vec) {
1390
678
    output << "  \"" << info << "\",\n";
1391
  }
1392
6
  output << "}";
1393
6
  return output;
1394
}
1395
1396
6
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1397
  output << "{\n"
1398
6
         << "// -- bindings begins --\n"
1399
6
         << i.bindings << ",\n"
1400
         << "// -- bindings ends --\n"
1401
6
         << "// -- native_modules begins --\n"
1402
6
         << i.native_modules << ",\n"
1403
         << "// -- native_modules ends --\n"
1404
6
         << "// -- async_hooks begins --\n"
1405
6
         << i.async_hooks << ",\n"
1406
6
         << "// -- async_hooks ends --\n"
1407
6
         << i.tick_info << ",  // tick_info\n"
1408
6
         << i.immediate_info << ",  // immediate_info\n"
1409
6
         << "// -- performance_state begins --\n"
1410
6
         << i.performance_state << ",\n"
1411
6
         << "// -- performance_state ends --\n"
1412
6
         << i.stream_base_state << ",  // stream_base_state\n"
1413
6
         << i.should_abort_on_uncaught_toggle
1414
         << ",  // should_abort_on_uncaught_toggle\n"
1415
6
         << "// -- persistent_templates begins --\n"
1416
6
         << i.persistent_templates << ",\n"
1417
         << "// persistent_templates ends --\n"
1418
6
         << "// -- persistent_values begins --\n"
1419
6
         << i.persistent_values << ",\n"
1420
6
         << "// -- persistent_values ends --\n"
1421
6
         << i.context << ",  // context\n"
1422
6
         << "}";
1423
6
  return output;
1424
}
1425
1426
20688
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1427
                                            Local<Object> holder,
1428
                                            int index,
1429
                                            InternalFieldInfo* info) {
1430
41376
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1431
20688
  deserialize_requests_.push_back(std::move(request));
1432
20688
}
1433
1434
5172
void Environment::RunDeserializeRequests() {
1435
10344
  HandleScope scope(isolate());
1436
5172
  Local<Context> ctx = context();
1437
5172
  Isolate* is = isolate();
1438
25860
  while (!deserialize_requests_.empty()) {
1439
41376
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1440
20688
    deserialize_requests_.pop_front();
1441
20688
    Local<Object> holder = request.holder.Get(is);
1442
20688
    request.cb(ctx, holder, request.index, request.info);
1443
    request.holder.Reset();
1444
20688
    request.info->Delete();
1445
  }
1446
5172
}
1447
1448
5172
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1449
5172
  Local<Context> ctx = context();
1450
1451
5172
  RunDeserializeRequests();
1452
1453
5172
  native_modules_in_snapshot = info->native_modules;
1454
5172
  async_hooks_.Deserialize(ctx);
1455
5172
  immediate_info_.Deserialize(ctx);
1456
5172
  tick_info_.Deserialize(ctx);
1457
5172
  performance_state_->Deserialize(ctx);
1458
5172
  stream_base_state_.Deserialize(ctx);
1459
5172
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1460
1461
5172
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1462
    fprintf(stderr, "deserializing...\n");
1463
    std::cerr << *info << "\n";
1464
  }
1465
1466
5172
  const std::vector<PropInfo>& templates = info->persistent_templates;
1467
5172
  size_t i = 0;  // index to the array
1468
5172
  size_t id = 0;
1469
#define SetProperty(PropertyName, TypeName, vector, type, from)                \
1470
  do {                                                                         \
1471
    if (vector.size() > i && id == vector[i].id) {                             \
1472
      const PropInfo& d = vector[i];                                           \
1473
      DCHECK_EQ(d.name, #PropertyName);                                        \
1474
      MaybeLocal<TypeName> maybe_field =                                       \
1475
          from->GetDataFromSnapshotOnce<TypeName>(d.index);                    \
1476
      Local<TypeName> field;                                                   \
1477
      if (!maybe_field.ToLocal(&field)) {                                      \
1478
        fprintf(stderr,                                                        \
1479
                "Failed to deserialize environment " #type " " #PropertyName   \
1480
                "\n");                                                         \
1481
      }                                                                        \
1482
      set_##PropertyName(field);                                               \
1483
      i++;                                                                     \
1484
    }                                                                          \
1485
  } while (0);                                                                 \
1486
  id++;
1487
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1488
                                              templates, template, isolate_)
1489








































































201708
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1490
#undef V
1491
1492
5172
  i = 0;  // index to the array
1493
5172
  id = 0;
1494
5172
  const std::vector<PropInfo>& values = info->persistent_values;
1495
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1496
                                              values, value, ctx)
1497






















































































































532716
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1498
#undef V
1499
#undef SetProperty
1500
1501
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1502
10344
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1503
  Local<Context> ctx_from_snapshot;
1504
5172
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1505
    fprintf(stderr,
1506
            "Failed to deserialize context back reference from the snapshot\n");
1507
  }
1508
5172
  CHECK_EQ(ctx_from_snapshot, ctx);
1509
5172
}
1510
1511
1
uint64_t GuessMemoryAvailableToTheProcess() {
1512
1
  uint64_t free_in_system = uv_get_free_memory();
1513
1
  size_t allowed = uv_get_constrained_memory();
1514
1
  if (allowed == 0) {
1515
    return free_in_system;
1516
  }
1517
  size_t rss;
1518
1
  int err = uv_resident_set_memory(&rss);
1519
1
  if (err) {
1520
    return free_in_system;
1521
  }
1522
1
  if (allowed < rss) {
1523
    // Something is probably wrong. Fallback to the free memory.
1524
    return free_in_system;
1525
  }
1526
  // There may still be room for swap, but we will just leave it here.
1527
1
  return allowed - rss;
1528
}
1529
1530
23
void Environment::BuildEmbedderGraph(Isolate* isolate,
1531
                                     EmbedderGraph* graph,
1532
                                     void* data) {
1533
23
  MemoryTracker tracker(isolate, graph);
1534
23
  Environment* env = static_cast<Environment*>(data);
1535
23
  tracker.Track(env);
1536
23
  env->ForEachBaseObject([&](BaseObject* obj) {
1537
493
    if (obj->IsDoneInitializing())
1538
492
      tracker.Track(obj);
1539
493
  });
1540
23
}
1541
1542
1
size_t Environment::NearHeapLimitCallback(void* data,
1543
                                          size_t current_heap_limit,
1544
                                          size_t initial_heap_limit) {
1545
1
  Environment* env = static_cast<Environment*>(data);
1546
1547
  Debug(env,
1548
        DebugCategory::DIAGNOSTICS,
1549
        "Invoked NearHeapLimitCallback, processing=%d, "
1550
        "current_limit=%" PRIu64 ", "
1551
        "initial_limit=%" PRIu64 "\n",
1552
1
        env->is_processing_heap_limit_callback_,
1553
2
        static_cast<uint64_t>(current_heap_limit),
1554
1
        static_cast<uint64_t>(initial_heap_limit));
1555
1556
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1557
1
  size_t young_gen_size = 0;
1558
1
  size_t old_gen_size = 0;
1559
1560
1
  HeapSpaceStatistics stats;
1561
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1562
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1563
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1564

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

150785
  if (self->has_pointer_data() &&
1721
7859
      self->pointer_data()->strong_ptr_count > 0) {
1722
3426
    return self->Detach();
1723
  }
1724
139500
  delete self;
1725
}
1726
1727
437
bool BaseObject::IsDoneInitializing() const { return true; }
1728
1729
492
Local<Object> BaseObject::WrappedObject() const {
1730
492
  return object();
1731
}
1732
1733
984
bool BaseObject::IsRootNode() const {
1734
1968
  return !persistent_handle_.IsWeak();
1735
}
1736
1737
56939
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1738
56939
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1739
56939
  if (tmpl.IsEmpty()) {
1740
860
    tmpl = env->NewFunctionTemplate(nullptr);
1741
860
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1742
860
    env->set_base_object_ctor_template(tmpl);
1743
  }
1744
56939
  return tmpl;
1745
}
1746
1747
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1748
  return IsWeakOrDetached();
1749
}
1750
1751
}  // namespace node