GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 745 822 90.6 %
Date: 2022-06-20 04:16:14 Branches: 1038 1966 52.8 %

Line Branch Exec Source
1
#include "env.h"
2
#include "async_wrap.h"
3
#include "base_object-inl.h"
4
#include "debug_utils-inl.h"
5
#include "diagnosticfilename-inl.h"
6
#include "memory_tracker-inl.h"
7
#include "node_buffer.h"
8
#include "node_context_data.h"
9
#include "node_errors.h"
10
#include "node_internals.h"
11
#include "node_options-inl.h"
12
#include "node_process-inl.h"
13
#include "node_v8_platform-inl.h"
14
#include "node_worker.h"
15
#include "req_wrap-inl.h"
16
#include "stream_base.h"
17
#include "tracing/agent.h"
18
#include "tracing/traced_value.h"
19
#include "util-inl.h"
20
#include "v8-profiler.h"
21
22
#include <algorithm>
23
#include <atomic>
24
#include <cinttypes>
25
#include <cstdio>
26
#include <iostream>
27
#include <limits>
28
#include <memory>
29
30
namespace node {
31
32
using errors::TryCatchScope;
33
using v8::Array;
34
using v8::Boolean;
35
using v8::Context;
36
using v8::EmbedderGraph;
37
using v8::EscapableHandleScope;
38
using v8::Function;
39
using v8::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
78
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
81
1656
  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
5207
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
93
5207
  size_t i = 0;
94
10414
  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




88519
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
110






130175
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
111









































































































































2869057
  PER_ISOLATE_STRING_PROPERTIES(VS)
112
#undef V
113
#undef VY
114
#undef VS
115
#undef VP
116
117
307213
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
118
    MaybeLocal<String> maybe_field =
119
604012
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
120
    Local<String> field;
121
302006
    if (!maybe_field.ToLocal(&field)) {
122
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
123
    }
124
302006
    async_wrap_providers_[j].Set(isolate_, field);
125
  }
126
5207
}
127
128
1280
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
1280
  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
11520
  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
16640
  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
353280
  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
75520
  NODE_ASYNC_PROVIDER_TYPES(V)
189
#undef V
190
1280
}
191
192
6487
IsolateData::IsolateData(Isolate* isolate,
193
                         uv_loop_t* event_loop,
194
                         MultiIsolatePlatform* platform,
195
                         ArrayBufferAllocator* node_allocator,
196
6487
                         const std::vector<size_t>* indexes)
197
    : isolate_(isolate),
198
      event_loop_(event_loop),
199
47
      node_allocator_(node_allocator == nullptr ? nullptr
200
6440
                                                : node_allocator->GetImpl()),
201
12974
      platform_(platform) {
202
6487
  options_.reset(
203
6487
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
204
205
6487
  if (indexes == nullptr) {
206
1280
    CreateProperties();
207
  } else {
208
5207
    DeserializeProperties(indexes);
209
  }
210
6487
}
211
212
24
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
213
#define V(PropertyName, StringValue)                                           \
214
  tracker->TrackField(#PropertyName, PropertyName());
215
24
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
216
217
24
  PER_ISOLATE_STRING_PROPERTIES(V)
218
#undef V
219
220
24
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
221
222
24
  if (node_allocator_ != nullptr) {
223
24
    tracker->TrackFieldWithSize(
224
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
225
  }
226
24
  tracker->TrackFieldWithSize(
227
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
228
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
229
24
}
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
1269
void Environment::CreateProperties() {
257
2538
  HandleScope handle_scope(isolate_);
258
1269
  Local<Context> ctx = context();
259
260
  {
261
1269
    Context::Scope context_scope(ctx);
262
1269
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
263
2538
    templ->InstanceTemplate()->SetInternalFieldCount(
264
        BaseObject::kInternalFieldCount);
265
1269
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
266
267
1269
    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
2538
      GetPerContextExports(ctx).ToLocalChecked();
273
  Local<Value> primordials =
274
3807
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
275
1269
  CHECK(primordials->IsObject());
276
1269
  set_primordials(primordials.As<Object>());
277
278
  Local<String> prototype_string =
279
1269
      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

7614
  V(primordials_safe_map_prototype_object, "SafeMap");
296

7614
  V(primordials_safe_set_prototype_object, "SafeSet");
297

7614
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
298

7614
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
299
#undef V
300
301
  Local<Object> process_object =
302
1269
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
303
1269
  set_process_object(process_object);
304
1269
}
305
306
6476
std::string GetExecPath(const std::vector<std::string>& argv) {
307
  char exec_path_buf[2 * PATH_MAX];
308
6476
  size_t exec_path_len = sizeof(exec_path_buf);
309
6476
  std::string exec_path;
310
6476
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
311
6476
    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
6476
  return exec_path;
330
}
331
332
6476
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
6476
                         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
6476
      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
6476
          isolate_,
350
          1,
351
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
352
6476
      stream_base_state_(isolate_,
353
                         StreamBase::kNumStreamBaseStateFields,
354
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
355
6476
      environment_start_time_(PERFORMANCE_NOW()),
356
      flags_(flags),
357
6476
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
358
6476
                     ? AllocateEnvironmentThreadId().id
359



25904
                     : thread_id.id) {
360
  // We'll be creating new objects so make sure we've entered the context.
361
12952
  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
6476
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
366
10520
    flags_ = flags_ |
367
5260
        EnvironmentFlags::kOwnsProcessState |
368
        EnvironmentFlags::kOwnsInspector;
369
  }
370
371
6476
  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
6476
  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
12952
  options_ = std::make_shared<EnvironmentOptions>(
382
19428
      *isolate_data->options()->per_env);
383
6476
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
384
6476
      options_->debug_options().host_port);
385
386
6476
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
387
1216
    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
6476
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
393
#endif
394
395
6476
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
396
6476
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
397
6476
    if (TracingController* tracing_controller = writer->GetTracingController())
398
6428
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
399
  }
400
401
6476
  destroy_async_id_list_.reserve(512);
402
403
6476
  performance_state_ = std::make_unique<performance::PerformanceState>(
404
6476
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
405
406
6476
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
407
6476
          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
6476
}
422
423
1269
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
1269
                         ThreadId thread_id)
430
    : Environment(isolate_data,
431
                  context->GetIsolate(),
432
                  args,
433
                  exec_args,
434
                  env_info,
435
                  flags,
436
1269
                  thread_id) {
437
1269
  InitializeMainContext(context, env_info);
438
1269
}
439
440
6476
void Environment::InitializeMainContext(Local<Context> context,
441
                                        const EnvSerializeInfo* env_info) {
442
6476
  context_.Reset(context->GetIsolate(), context);
443
6476
  AssignToContext(context, ContextInfo(""));
444
6476
  if (env_info != nullptr) {
445
5207
    DeserializeProperties(env_info);
446
  } else {
447
1269
    CreateProperties();
448
  }
449
450
6476
  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
6476
  should_abort_on_uncaught_toggle_[0] = 1;
456
457
6476
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
458
                           environment_start_time_);
459
6476
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
460
                           per_process::node_start_time);
461
462
6476
  if (per_process::v8_initialized) {
463
6428
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
464
                            performance::performance_v8_start);
465
  }
466
6476
}
467
468
1204930
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
5965
  CHECK(is_stopping());
496
497
5965
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
498
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
499
                                          0);
500
  }
501
502
5965
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
503
      BuildEmbedderGraph, this);
504
505
11930
  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
5965
  inspector_agent_.reset();
511
#endif
512
513
11930
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
514
                                             nullptr);
515
516
5965
  if (trace_state_observer_) {
517
5965
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
518
5965
    CHECK_NOT_NULL(writer);
519
5965
    if (TracingController* tracing_controller = writer->GetTracingController())
520
5919
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
521
  }
522
523

10684
  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
5965
  if (!is_main_thread()) {
532
    // Dereference all addons that were loaded into this environment.
533
1227
    for (binding::DLib& addon : loaded_addons_) {
534
14
      addon.Close();
535
    }
536
  }
537
538
5965
  CHECK_EQ(base_object_count_, 0);
539
5965
}
540
541
6443
void Environment::InitializeLibuv() {
542
12886
  HandleScope handle_scope(isolate());
543
6443
  Context::Scope context_scope(context());
544
545
6443
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
546
6443
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
547
548
6443
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
549
6443
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
550
551
6443
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
552
553
6443
  CHECK_EQ(0, 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
6443
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
560
6443
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
561
562
30017
  CHECK_EQ(0, uv_async_init(
563
      event_loop(),
564
      &task_queues_async_,
565
      [](uv_async_t* async) {
566
        Environment* env = ContainerOf(
567
            &Environment::task_queues_async_, async);
568
        HandleScope handle_scope(env->isolate());
569
        Context::Scope context_scope(env->context());
570
        env->RunAndClearNativeImmediates();
571
      }));
572
6443
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
573
6443
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
574
6443
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
575
576
  {
577
12886
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
578
6443
    task_queues_async_initialized_ = true;
579

12886
    if (native_immediates_threadsafe_.size() > 0 ||
580
6443
        native_immediates_interrupts_.size() > 0) {
581
5202
      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
6443
  RegisterHandleCleanups();
590
591
6443
  StartProfilerIdleNotifier();
592
6443
}
593
594
825
void Environment::ExitEnv() {
595
825
  set_can_call_into_js(false);
596
825
  set_stopping(true);
597
825
  isolate_->TerminateExecution();
598
1650
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
599
825
}
600
601
6443
void Environment::RegisterHandleCleanups() {
602
6443
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
603
35592
                                        void* arg) {
604
35592
    handle->data = env;
605
606
35592
    env->CloseHandle(handle, [](uv_handle_t* handle) {
607
#ifdef DEBUG
608
      memset(handle, 0xab, uv_handle_size(handle->type));
609
#endif
610
35592
    });
611
35592
  };
612
613
38658
  auto register_handle = [&](uv_handle_t* handle) {
614
38658
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
615
45101
  };
616
6443
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
617
6443
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
618
6443
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
619
6443
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
620
6443
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
621
6443
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
622
6443
}
623
624
11924
void Environment::CleanupHandles() {
625
  {
626
11924
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
627
11924
    task_queues_async_initialized_ = false;
628
  }
629
630
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
631
23848
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
632
633
11924
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
634
635
12736
  for (ReqWrapBase* request : req_wrap_queue_)
636
812
    request->Cancel();
637
638
16266
  for (HandleWrap* handle : handle_wrap_queue_)
639
8684
    handle->Close();
640
641
47516
  for (HandleCleanup& hc : handle_cleanup_queue_)
642
35592
    hc.cb_(this, hc.handle_, hc.arg_);
643
11924
  handle_cleanup_queue_.clear();
644
645
10722
  while (handle_cleanup_waiting_ != 0 ||
646

34572
         request_waiting_ != 0 ||
647
11926
         !handle_wrap_queue_.IsEmpty()) {
648
10722
    uv_run(event_loop(), UV_RUN_ONCE);
649
  }
650
11924
}
651
652
6443
void Environment::StartProfilerIdleNotifier() {
653
6443
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
654
186623
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
655
186623
    env->isolate()->SetIdle(true);
656
186623
  });
657
6443
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
658
186447
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
659
186447
    env->isolate()->SetIdle(false);
660
186447
  });
661
6443
}
662
663
719562
void Environment::PrintSyncTrace() const {
664
719562
  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
5137
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
676
5137
  EscapableHandleScope handle_scope(isolate());
677
10274
  if (!snapshot_serialize_callback().IsEmpty()) {
678
    Context::Scope context_scope(context());
679
    return handle_scope.EscapeMaybe(snapshot_serialize_callback()->Call(
680
        context(), v8::Undefined(isolate()), 0, nullptr));
681
  }
682
10274
  return handle_scope.Escape(Undefined(isolate()));
683
}
684
685
MaybeLocal<Value> Environment::RunSnapshotDeserializeMain() const {
686
  EscapableHandleScope handle_scope(isolate());
687
  if (!snapshot_deserialize_main().IsEmpty()) {
688
    Context::Scope context_scope(context());
689
    return handle_scope.EscapeMaybe(snapshot_deserialize_main()->Call(
690
        context(), v8::Undefined(isolate()), 0, nullptr));
691
  }
692
  return handle_scope.Escape(Undefined(isolate()));
693
}
694
695
5965
void Environment::RunCleanup() {
696
5965
  started_cleanup_ = true;
697

16650
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
698
5965
  bindings_.clear();
699
5965
  CleanupHandles();
700
701
17891
  while (!cleanup_hooks_.empty() ||
702
11932
         native_immediates_.size() > 0 ||
703

23856
         native_immediates_threadsafe_.size() > 0 ||
704
5965
         native_immediates_interrupts_.size() > 0) {
705
    // Copy into a vector, since we can't sort an unordered_set in-place.
706
    std::vector<CleanupHookCallback> callbacks(
707
11918
        cleanup_hooks_.begin(), cleanup_hooks_.end());
708
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
709
    // need to be able to check whether they were un-scheduled by another hook.
710
711
5959
    std::sort(callbacks.begin(), callbacks.end(),
712
1000652
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
713
      // Sort in descending order so that the most recently inserted callbacks
714
      // are run first.
715
1000652
      return a.insertion_order_counter_ > b.insertion_order_counter_;
716
    });
717
718
161096
    for (const CleanupHookCallback& cb : callbacks) {
719
155137
      if (cleanup_hooks_.count(cb) == 0) {
720
        // This hook was removed from the `cleanup_hooks_` set during another
721
        // hook that was run earlier. Nothing to do here.
722
1154
        continue;
723
      }
724
725
153983
      cb.fn_(cb.arg_);
726
153983
      cleanup_hooks_.erase(cb);
727
    }
728
5959
    CleanupHandles();
729
  }
730
731
5968
  for (const int fd : unmanaged_fds_) {
732
    uv_fs_t close_req;
733
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
734
3
    uv_fs_req_cleanup(&close_req);
735
  }
736
5965
}
737
738
6563
void Environment::RunAtExitCallbacks() {
739

18337
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
740
19481
  for (ExitCallback at_exit : at_exit_functions_) {
741
12918
    at_exit.cb_(at_exit.arg_);
742
  }
743
6563
  at_exit_functions_.clear();
744
6563
}
745
746
12942
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
747
12942
  at_exit_functions_.push_front(ExitCallback{cb, arg});
748
12942
}
749
750
229151
void Environment::RunAndClearInterrupts() {
751
229151
  while (native_immediates_interrupts_.size() > 0) {
752
11759
    NativeImmediateQueue queue;
753
    {
754
23518
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
755
11759
      queue.ConcatMove(std::move(native_immediates_interrupts_));
756
    }
757
11759
    DebugSealHandleScope seal_handle_scope(isolate());
758
759
23530
    while (auto head = queue.Shift())
760
23542
      head->Call(this);
761
  }
762
217392
}
763
764
206231
void Environment::RunAndClearNativeImmediates(bool only_refed) {
765

417375
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
766
               "RunAndClearNativeImmediates");
767
412456
  HandleScope handle_scope(isolate_);
768
412456
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
769
770
206231
  size_t ref_count = 0;
771
772
  // Handle interrupts first. These functions are not allowed to throw
773
  // exceptions, so we do not need to handle that.
774
206231
  RunAndClearInterrupts();
775
776
412460
  auto drain_list = [&](NativeImmediateQueue* queue) {
777
824914
    TryCatchScope try_catch(this);
778
412460
    DebugSealHandleScope seal_handle_scope(isolate());
779
473835
    while (auto head = queue->Shift()) {
780
61382
      bool is_refed = head->flags() & CallbackFlags::kRefed;
781
61382
      if (is_refed)
782
36982
        ref_count++;
783
784

61382
      if (is_refed || !only_refed)
785
61185
        head->Call(this);
786
787
61377
      head.reset();  // Destroy now so that this is also observed by try_catch.
788
789
61377
      if (UNLIKELY(try_catch.HasCaught())) {
790

2
        if (!try_catch.HasTerminated() && can_call_into_js())
791
2
          errors::TriggerUncaughtException(isolate(), try_catch);
792
793
1
        return true;
794
      }
795
61375
    }
796
412453
    return false;
797
206231
  };
798
206231
  while (drain_list(&native_immediates_)) {}
799
800
206228
  immediate_info()->ref_count_dec(ref_count);
801
802
206228
  if (immediate_info()->ref_count() == 0)
803
163283
    ToggleImmediateRef(false);
804
805
  // It is safe to check .size() first, because there is a causal relationship
806
  // between pushes to the threadsafe immediate list and this function being
807
  // called. For the common case, it's worth checking the size first before
808
  // establishing a mutex lock.
809
  // This is intentionally placed after the `ref_count` handling, because when
810
  // refed threadsafe immediates are created, they are not counted towards the
811
  // count in immediate_info() either.
812
206225
  NativeImmediateQueue threadsafe_immediates;
813
206228
  if (native_immediates_threadsafe_.size() > 0) {
814
4056
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
815
2028
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
816
  }
817
206229
  while (drain_list(&threadsafe_immediates)) {}
818
206225
}
819
820
11775
void Environment::RequestInterruptFromV8() {
821
  // The Isolate may outlive the Environment, so some logic to handle the
822
  // situation in which the Environment is destroyed before the handler runs
823
  // is required.
824
825
  // We allocate a new pointer to a pointer to this Environment instance, and
826
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
827
  // callbacks are already scheduled to run and we can delete our own pointer
828
  // and just return. If it was nullptr previously, the Environment** is stored;
829
  // ~Environment sets the Environment* contained in it to nullptr, so that
830
  // the callback can check whether ~Environment has already run and it is thus
831
  // not safe to access the Environment instance itself.
832
11775
  Environment** interrupt_data = new Environment*(this);
833
11775
  Environment** dummy = nullptr;
834
11775
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
835
712
    delete interrupt_data;
836
712
    return;  // Already scheduled.
837
  }
838
839
11063
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
840
11055
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
841
11055
    Environment* env = *env_ptr;
842
11055
    if (env == nullptr) {
843
      // The Environment has already been destroyed. That should be okay; any
844
      // callback added before the Environment shuts down would have been
845
      // handled during cleanup.
846
10
      return;
847
    }
848
11045
    env->interrupt_data_.store(nullptr);
849
11045
    env->RunAndClearInterrupts();
850
  }, interrupt_data);
851
}
852
853
10030
void Environment::ScheduleTimer(int64_t duration_ms) {
854
10030
  if (started_cleanup_) return;
855
10030
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
856
}
857
858
3610
void Environment::ToggleTimerRef(bool ref) {
859
3610
  if (started_cleanup_) return;
860
861
3610
  if (ref) {
862
2369
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
863
  } else {
864
1241
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
865
  }
866
}
867
868
8186
void Environment::RunTimers(uv_timer_t* handle) {
869
8186
  Environment* env = Environment::from_timer_handle(handle);
870

8638
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
871
872
8186
  if (!env->can_call_into_js())
873
    return;
874
875
8186
  HandleScope handle_scope(env->isolate());
876
8186
  Context::Scope context_scope(env->context());
877
878
8186
  Local<Object> process = env->process_object();
879
8186
  InternalCallbackScope scope(env, process, {0, 0});
880
881
8186
  Local<Function> cb = env->timers_callback_function();
882
  MaybeLocal<Value> ret;
883
8186
  Local<Value> arg = env->GetNow();
884
  // This code will loop until all currently due timers will process. It is
885
  // impossible for us to end up in an infinite loop due to how the JS-side
886
  // is structured.
887
32
  do {
888
8218
    TryCatchScope try_catch(env);
889
8218
    try_catch.SetVerbose(true);
890
8218
    ret = cb->Call(env->context(), process, 1, &arg);
891

8208
  } while (ret.IsEmpty() && env->can_call_into_js());
892
893
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
894
  // is reset back to `true` after being previously set to `false` then this
895
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
896
  // timers corruption will occur and all timers behaviour will become
897
  // entirely unpredictable.
898
8176
  if (ret.IsEmpty())
899
8
    return;
900
901
  // To allow for less JS-C++ boundary crossing, the value returned from JS
902
  // serves a few purposes:
903
  // 1. If it's 0, no more timers exist and the handle should be unrefed
904
  // 2. If it's > 0, the value represents the next timer's expiry and there
905
  //    is at least one timer remaining that is refed.
906
  // 3. If it's < 0, the absolute value represents the next timer's expiry
907
  //    and there are no timers that are refed.
908
  int64_t expiry_ms =
909
8168
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
910
911
8168
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
912
913
8168
  if (expiry_ms != 0) {
914
    int64_t duration_ms =
915
7202
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
916
917
7202
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
918
919
7202
    if (expiry_ms > 0)
920
6591
      uv_ref(h);
921
    else
922
611
      uv_unref(h);
923
  } else {
924
966
    uv_unref(h);
925
  }
926
}
927
928
929
186447
void Environment::CheckImmediate(uv_check_t* handle) {
930
186447
  Environment* env = Environment::from_immediate_check_handle(handle);
931

189392
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
932
933
186447
  HandleScope scope(env->isolate());
934
186447
  Context::Scope context_scope(env->context());
935
936
186447
  env->RunAndClearNativeImmediates();
937
938

186447
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
939
144773
    return;
940
941
945
  do {
942
42612
    MakeCallback(env->isolate(),
943
                 env->process_object(),
944
                 env->immediate_callback_function(),
945
                 0,
946
                 nullptr,
947
42619
                 {0, 0}).ToLocalChecked();
948

42612
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
949
950
41667
  if (env->immediate_info()->ref_count() == 0)
951
4962
    env->ToggleImmediateRef(false);
952
}
953
954
233084
void Environment::ToggleImmediateRef(bool ref) {
955
233084
  if (started_cleanup_) return;
956
957
221601
  if (ref) {
958
    // Idle handle is needed only to stop the event loop from blocking in poll.
959
64815
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
960
  } else {
961
156786
    uv_idle_stop(immediate_idle_handle());
962
  }
963
}
964
965
966
30195
Local<Value> Environment::GetNow() {
967
30195
  uv_update_time(event_loop());
968
30195
  uint64_t now = uv_now(event_loop());
969
30195
  CHECK_GE(now, timer_base());
970
30195
  now -= timer_base();
971
30195
  if (now <= 0xffffffff)
972
60390
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
973
  else
974
    return Number::New(isolate(), static_cast<double>(now));
975
}
976
977
28
void CollectExceptionInfo(Environment* env,
978
                          Local<Object> obj,
979
                          int errorno,
980
                          const char* err_string,
981
                          const char* syscall,
982
                          const char* message,
983
                          const char* path,
984
                          const char* dest) {
985
28
  obj->Set(env->context(),
986
           env->errno_string(),
987
112
           Integer::New(env->isolate(), errorno)).Check();
988
989
28
  obj->Set(env->context(), env->code_string(),
990
84
           OneByteString(env->isolate(), err_string)).Check();
991
992
28
  if (message != nullptr) {
993
28
    obj->Set(env->context(), env->message_string(),
994
112
             OneByteString(env->isolate(), message)).Check();
995
  }
996
997
  Local<Value> path_buffer;
998
28
  if (path != nullptr) {
999
    path_buffer =
1000
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
1001
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
1002
  }
1003
1004
  Local<Value> dest_buffer;
1005
28
  if (dest != nullptr) {
1006
    dest_buffer =
1007
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
1008
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
1009
  }
1010
1011
28
  if (syscall != nullptr) {
1012
28
    obj->Set(env->context(), env->syscall_string(),
1013
112
             OneByteString(env->isolate(), syscall)).Check();
1014
  }
1015
28
}
1016
1017
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
1018
                                         int errorno,
1019
                                         const char* syscall,
1020
                                         const char* message,
1021
                                         const char* path,
1022
                                         const char* dest) {
1023

28
  if (!object->IsObject() || errorno == 0)
1024
    return;
1025
1026
28
  Local<Object> obj = object.As<Object>();
1027
28
  const char* err_string = uv_err_name(errorno);
1028
1029

28
  if (message == nullptr || message[0] == '\0') {
1030
28
    message = uv_strerror(errorno);
1031
  }
1032
1033
28
  node::CollectExceptionInfo(this, obj, errorno, err_string,
1034
                             syscall, message, path, dest);
1035
}
1036
1037
6476
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1038
6476
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
1039
1040
6
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
1041
    Local<Context> context, SnapshotCreator* creator) {
1042
6
  return {fields_.Serialize(context, creator)};
1043
}
1044
1045
5207
void ImmediateInfo::Deserialize(Local<Context> context) {
1046
5207
  fields_.Deserialize(context);
1047
5207
}
1048
1049
6
std::ostream& operator<<(std::ostream& output,
1050
                         const ImmediateInfo::SerializeInfo& i) {
1051
6
  output << "{ " << i.fields << " }";
1052
6
  return output;
1053
}
1054
1055
24
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1056
24
  tracker->TrackField("fields", fields_);
1057
24
}
1058
1059
6
TickInfo::SerializeInfo TickInfo::Serialize(Local<Context> context,
1060
                                            SnapshotCreator* creator) {
1061
6
  return {fields_.Serialize(context, creator)};
1062
}
1063
1064
5207
void TickInfo::Deserialize(Local<Context> context) {
1065
5207
  fields_.Deserialize(context);
1066
5207
}
1067
1068
6
std::ostream& operator<<(std::ostream& output,
1069
                         const TickInfo::SerializeInfo& i) {
1070
6
  output << "{ " << i.fields << " }";
1071
6
  return output;
1072
}
1073
1074
24
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1075
24
  tracker->TrackField("fields", fields_);
1076
24
}
1077
1078
6476
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1079
    : fields_(
1080
6476
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1081
1082
6476
AsyncHooks::AsyncHooks(Isolate* isolate, const SerializeInfo* info)
1083
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1084
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1085
      async_id_fields_(
1086
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1087

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

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


















336
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1373
#undef V
1374
1375
6
  id = 0;
1376
#define V(PropertyName, TypeName)                                              \
1377
  do {                                                                         \
1378
    Local<TypeName> field = PropertyName();                                    \
1379
    if (!field.IsEmpty()) {                                                    \
1380
      size_t index = creator->AddData(ctx, field);                             \
1381
      info.persistent_values.push_back({#PropertyName, id, index});            \
1382
    }                                                                          \
1383
    id++;                                                                      \
1384
  } while (0);
1385































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








































































203073
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1507
#undef V
1508
1509
5207
  i = 0;  // index to the array
1510
5207
  id = 0;
1511
5207
  const std::vector<PropInfo>& values = info->persistent_values;
1512
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1513
                                              values, value, ctx)
1514




























































































































536321
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1515
#undef V
1516
#undef SetProperty
1517
1518
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1519
10414
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1520
  Local<Context> ctx_from_snapshot;
1521
5207
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1522
    fprintf(stderr,
1523
            "Failed to deserialize context back reference from the snapshot\n");
1524
  }
1525
5207
  CHECK_EQ(ctx_from_snapshot, ctx);
1526
5207
}
1527
1528
1
uint64_t GuessMemoryAvailableToTheProcess() {
1529
1
  uint64_t free_in_system = uv_get_free_memory();
1530
1
  size_t allowed = uv_get_constrained_memory();
1531
1
  if (allowed == 0) {
1532
    return free_in_system;
1533
  }
1534
  size_t rss;
1535
1
  int err = uv_resident_set_memory(&rss);
1536
1
  if (err) {
1537
    return free_in_system;
1538
  }
1539
1
  if (allowed < rss) {
1540
    // Something is probably wrong. Fallback to the free memory.
1541
    return free_in_system;
1542
  }
1543
  // There may still be room for swap, but we will just leave it here.
1544
1
  return allowed - rss;
1545
}
1546
1547
24
void Environment::BuildEmbedderGraph(Isolate* isolate,
1548
                                     EmbedderGraph* graph,
1549
                                     void* data) {
1550
24
  MemoryTracker tracker(isolate, graph);
1551
24
  Environment* env = static_cast<Environment*>(data);
1552
24
  tracker.Track(env);
1553
24
  env->ForEachBaseObject([&](BaseObject* obj) {
1554
513
    if (obj->IsDoneInitializing())
1555
512
      tracker.Track(obj);
1556
513
  });
1557
24
}
1558
1559
1
size_t Environment::NearHeapLimitCallback(void* data,
1560
                                          size_t current_heap_limit,
1561
                                          size_t initial_heap_limit) {
1562
1
  Environment* env = static_cast<Environment*>(data);
1563
1564
  Debug(env,
1565
        DebugCategory::DIAGNOSTICS,
1566
        "Invoked NearHeapLimitCallback, processing=%d, "
1567
        "current_limit=%" PRIu64 ", "
1568
        "initial_limit=%" PRIu64 "\n",
1569
1
        env->is_processing_heap_limit_callback_,
1570
2
        static_cast<uint64_t>(current_heap_limit),
1571
1
        static_cast<uint64_t>(initial_heap_limit));
1572
1573
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1574
1
  size_t young_gen_size = 0;
1575
1
  size_t old_gen_size = 0;
1576
1577
1
  HeapSpaceStatistics stats;
1578
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1579
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1580
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1581

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

156124
  if (self->has_pointer_data() &&
1738
7997
      self->pointer_data()->strong_ptr_count > 0) {
1739
3481
    return self->Detach();
1740
  }
1741
144646
  delete self;
1742
}
1743
1744
456
bool BaseObject::IsDoneInitializing() const { return true; }
1745
1746
512
Local<Object> BaseObject::WrappedObject() const {
1747
512
  return object();
1748
}
1749
1750
1024
bool BaseObject::IsRootNode() const {
1751
2048
  return !persistent_handle_.IsWeak();
1752
}
1753
1754
67834
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1755
67834
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1756
67834
  if (tmpl.IsEmpty()) {
1757
1269
    tmpl = env->NewFunctionTemplate(nullptr);
1758
1269
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1759
1269
    env->set_base_object_ctor_template(tmpl);
1760
  }
1761
67834
  return tmpl;
1762
}
1763
1764
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1765
  return IsWeakOrDetached();
1766
}
1767
1768
}  // namespace node