GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/env.cc Lines: 864 928 93.1 %
Date: 2021-05-27 04:11:47 Branches: 982 1845 53.2 %

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




114408
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
110






171600
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
111







































































































































3860484
  PER_ISOLATE_STRING_PROPERTIES(VS)
112
24
#undef V
113
#undef VY
114
#undef VS
115
#undef VP
116
117
281194
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
118
    MaybeLocal<String> maybe_field =
119
552856
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
120
    Local<String> field;
121
276428
    if (!maybe_field.ToLocal(&field)) {
122
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
123
    }
124
276428
    async_wrap_providers_[j].Set(isolate_, field);
125
  }
126
4766
}
127
128
479
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
958
  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
1437
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
153
#undef V
154
1437
#define V(PropertyName, StringValue)                                           \
155
  PropertyName##_.Set(                                                         \
156
1437
      isolate_,                                                                \
157
      Symbol::New(isolate_,                                                    \
158
1437
                  String::NewFromOneByte(                                      \
159
479
                      isolate_,                                                \
160
1437
                      reinterpret_cast<const uint8_t*>(StringValue),           \
161
479
                      NewStringType::kInternalized,                            \
162
958
                      sizeof(StringValue) - 1)                                 \
163
1437
                      .ToLocalChecked()));
164
1437
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
165
1916
#undef V
166
1437
#define V(PropertyName, StringValue)                                           \
167
479
  PropertyName##_.Set(                                                         \
168
958
      isolate_,                                                                \
169
479
      String::NewFromOneByte(isolate_,                                         \
170
958
                             reinterpret_cast<const uint8_t*>(StringValue),    \
171
479
                             NewStringType::kInternalized,                     \
172
958
                             sizeof(StringValue) - 1)                          \
173
479
          .ToLocalChecked());
174
260094
  PER_ISOLATE_STRING_PROPERTIES(V)
175
1437
#undef V
176
177
1437
  // 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
1437
  // strings can be retrieved quickly.
180
479
#define V(Provider)                                                           \
181
958
  async_wrap_providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                \
182
1437
      isolate_,                                                               \
183
      String::NewFromOneByte(                                                 \
184
1437
        isolate_,                                                             \
185
        reinterpret_cast<const uint8_t*>(#Provider),                          \
186
        NewStringType::kInternalized,                                         \
187
        sizeof(#Provider) - 1).ToLocalChecked());
188
56043
  NODE_ASYNC_PROVIDER_TYPES(V)
189
#undef V
190
479
}
191
192
5245
IsolateData::IsolateData(Isolate* isolate,
193
                         uv_loop_t* event_loop,
194
                         MultiIsolatePlatform* platform,
195
                         ArrayBufferAllocator* node_allocator,
196
5245
                         const std::vector<size_t>* indexes)
197
    : isolate_(isolate),
198
      event_loop_(event_loop),
199
10444
      node_allocator_(node_allocator == nullptr ? nullptr
200
5199
                                                : node_allocator->GetImpl()),
201
1531540
      platform_(platform) {
202
10490
  options_.reset(
203
15735
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
204
205
5245
  if (indexes == nullptr) {
206
479
    CreateProperties();
207
  } else {
208
4766
    DeserializeProperties(indexes);
209
  }
210
5245
}
211
212
22
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
213
#define V(PropertyName, StringValue)                                           \
214
  tracker->TrackField(#PropertyName, PropertyName());
215
22
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
216
22
217
66
  PER_ISOLATE_STRING_PROPERTIES(V)
218
44
#undef V
219
44
220
66
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
221
44
222
44
  if (node_allocator_ != nullptr) {
223
22
    tracker->TrackFieldWithSize(
224
44
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
225
22
  }
226
22
  tracker->TrackFieldWithSize(
227
44
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
228
22
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
229
44
}
230
22
231
143
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
232

143
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
233
22
    // Ideally, we’d have a consistent story that treats all threads/Environment
234
22
    // instances equally here. However, tracing is essentially global, and this
235
22
    // callback is called from whichever thread calls `StartTracing()` or
236
22
    // `StopTracing()`. The only way to do this in a threadsafe fashion
237
22
    // seems to be only tracking this from the main thread, and only allowing
238
44
    // these state modifications from the main thread.
239
118
    return;
240
22
  }
241
22
242
154
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
243
154
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
244
22
245
132
  Isolate* isolate = env_->isolate();
246
190
  HandleScope handle_scope(isolate);
247
132
  Local<Function> cb = env_->trace_category_state_function();
248
132
  if (cb.IsEmpty())
249
52
    return;
250
116
  TryCatchScope try_catch(env_);
251
58
  try_catch.SetVerbose(true);
252
116
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
253
174
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
254
}
255
256
464
void Environment::CreateProperties() {
257
928
  HandleScope handle_scope(isolate_);
258
464
  Local<Context> ctx = context();
259
260
  {
261
    Context::Scope context_scope(ctx);
262
464
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
263
1392
    templ->InstanceTemplate()->SetInternalFieldCount(
264
464
        BaseObject::kInternalFieldCount);
265
928
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
266
267
464
    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
928
      GetPerContextExports(ctx).ToLocalChecked();
273
  Local<Value> primordials =
274
1392
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
275
464
  CHECK(primordials->IsObject());
276
464
  set_primordials(primordials.As<Object>());
277
278
  Local<String> prototype_string =
279
464
      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
1856
  V(primordials_safe_map_prototype_object, "SafeMap");
296
2320
  V(primordials_safe_set_prototype_object, "SafeSet");
297
2320
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
298

4176
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
299

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


512540
                     : thread_id.id) {
360
  // We'll be creating new objects so make sure we've entered the context.
361
10460
  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
5230
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
366
9634
    flags_ = flags_ |
367
4817
        EnvironmentFlags::kOwnsProcessState |
368
        EnvironmentFlags::kOwnsInspector;
369
  }
370
371
5230
  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
5230
  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
10460
  options_ = std::make_shared<EnvironmentOptions>(
382
15690
      *isolate_data->options()->per_env);
383
10460
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
384
10460
      options_->debug_options().host_port);
385
386
5230
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
387
413
    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
5230
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
393
#endif
394
395
5230
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
396
5230
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
397
5230
    if (TracingController* tracing_controller = writer->GetTracingController())
398
5185
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
399
  }
400
401
5230
  destroy_async_id_list_.reserve(512);
402
403
10460
  performance_state_ = std::make_unique<performance::PerformanceState>(
404
15690
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
405
406
5230
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
407
          TRACING_CATEGORY_NODE1(environment)) != 0) {
408
16
    auto traced_value = tracing::TracedValue::Create();
409
8
    traced_value->BeginArray("args");
410
8
    for (const std::string& arg : args) traced_value->AppendString(arg);
411
8
    traced_value->EndArray();
412
8
    traced_value->BeginArray("exec_args");
413
8
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
414
8
    traced_value->EndArray();
415
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
416
8
                                      "Environment",
417
                                      this,
418
7
                                      "args",
419
8
                                      std::move(traced_value));
420
  }
421
5238
}
422
8
423
480
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
464
                         ThreadId thread_id)
430
    : Environment(isolate_data,
431
                  context->GetIsolate(),
432
                  args,
433
                  exec_args,
434
                  env_info,
435
                  flags,
436
464
                  thread_id) {
437
464
  InitializeMainContext(context, env_info);
438
464
}
439
440
5230
void Environment::InitializeMainContext(Local<Context> context,
441
                                        const EnvSerializeInfo* env_info) {
442
5230
  context_.Reset(context->GetIsolate(), context);
443
5230
  AssignToContext(context, ContextInfo(""));
444
5230
  if (env_info != nullptr) {
445
4766
    DeserializeProperties(env_info);
446
  } else {
447
464
    CreateProperties();
448
  }
449
450
5230
  if (options_->no_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
5230
  should_abort_on_uncaught_toggle_[0] = 1;
456
457
5230
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
458
5230
                           environment_start_time_);
459
5230
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
460
10460
                           per_process::node_start_time);
461
5230
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
462
10460
                           performance::performance_v8_start);
463
5230
}
464
465
450870
Environment::~Environment() {
466
4746
  if (Environment** interrupt_data = interrupt_data_.load()) {
467
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
468
    // then force V8 to run interrupts by compiling and running an empty script
469
    // so as not to leak memory.
470
10
    *interrupt_data = nullptr;
471
472
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
473
20
    HandleScope handle_scope(isolate());
474
20
    TryCatch try_catch(isolate());
475
10
    Context::Scope context_scope(context());
476
477
#ifdef DEBUG
478
    bool consistency_check = false;
479
    isolate()->RequestInterrupt([](Isolate*, void* data) {
480
      *static_cast<bool*>(data) = true;
481
    }, &consistency_check);
482
#endif
483
484
    Local<Script> script;
485
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
486
20
      USE(script->Run(context()));
487
488
    DCHECK(consistency_check);
489
  }
490
491
  // FreeEnvironment() should have set this.
492
4746
  CHECK(is_stopping());
493
494
4746
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
495
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
496
                                          0);
497
  }
498
499
4746
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
500
4746
      BuildEmbedderGraph, this);
501
502
9492
  HandleScope handle_scope(isolate());
503
504
#if HAVE_INSPECTOR
505
  // Destroy inspector agent before erasing the context. The inspector
506
  // destructor depends on the context still being accessible.
507
4746
  inspector_agent_.reset();
508
#endif
509
510
14238
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
511
4746
                                             nullptr);
512
513
4746
  if (trace_state_observer_) {
514
4746
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
515
4746
    CHECK_NOT_NULL(writer);
516
4746
    if (TracingController* tracing_controller = writer->GetTracingController())
517
4703
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
518
  }
519
520
4746
  TRACE_EVENT_NESTABLE_ASYNC_END0(
521
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
522
523
4306
  // Do not unload addons on the main thread. Some addons need to retain memory
524
4746
  // beyond the Environment's lifetime, and unloading them early would break
525
  // them; with Worker threads, we have the opportunity to be stricter.
526
7
  // Also, since the main thread usually stops just before the process exits,
527
7
  // this is far less relevant here.
528
14
  if (!is_main_thread()) {
529
    // Dereference all addons that were loaded into this environment.
530
424
    for (binding::DLib& addon : loaded_addons_) {
531
14
      addon.Close();
532
    }
533
  }
534
535
4746
  CHECK_EQ(base_object_count_, 0);
536
9492
}
537
538
5197
void Environment::InitializeLibuv() {
539
10394
  HandleScope handle_scope(isolate());
540
5197
  Context::Scope context_scope(context());
541
542
5197
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
543
5197
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
544
545
5197
  uv_check_init(event_loop(), immediate_check_handle());
546
5197
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
547
548
5197
  uv_idle_init(event_loop(), immediate_idle_handle());
549
550
5197
  uv_check_start(immediate_check_handle(), CheckImmediate);
551
552
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
553
  // but not all samples are created equal; mark the wall clock time spent in
554
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
555
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
556
5197
  uv_prepare_init(event_loop(), &idle_prepare_handle_);
557
5197
  uv_check_init(event_loop(), &idle_check_handle_);
558
559
10394
  uv_async_init(
560
      event_loop(),
561
      &task_queues_async_,
562
14353
      [](uv_async_t* async) {
563
9156
        Environment* env = ContainerOf(
564
4578
            &Environment::task_queues_async_, async);
565
9150
        HandleScope handle_scope(env->isolate());
566
4578
        Context::Scope context_scope(env->context());
567
4578
        env->RunAndClearNativeImmediates();
568
19544
      });
569
5197
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
570
5197
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
571
5197
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
572
573
  {
574
10394
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
575
5197
    task_queues_async_initialized_ = true;
576

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

55656
  while (handle_cleanup_waiting_ != 0 ||
643

28034
         request_waiting_ != 0 ||
644
9485
         !handle_wrap_queue_.IsEmpty()) {
645
9068
    uv_run(event_loop(), UV_RUN_ONCE);
646
  }
647
9482
}
648
649
5197
void Environment::StartProfilerIdleNotifier() {
650
413272
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
651
198840
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
652
198842
    env->isolate()->SetIdle(true);
653
408077
  });
654
412971
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
655
198690
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
656
198690
    env->isolate()->SetIdle(false);
657
407774
  });
658
5197
}
659
660
450531
void Environment::PrintSyncTrace() const {
661
450531
  if (!trace_sync_io_) return;
662
663
2
  HandleScope handle_scope(isolate());
664
665
1
  fprintf(
666
1
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
667
1
  PrintStackTrace(isolate(),
668
                  StackTrace::CurrentStackTrace(
669
1
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
670
}
671
672
4744
void Environment::RunCleanup() {
673
4744
  started_cleanup_ = true;
674
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
675
9489
                              "RunCleanup", this);
676
4746
  bindings_.clear();
677
4746
  CleanupHandles();
678
679

28448
  while (!cleanup_hooks_.empty() ||
680
9491
         native_immediates_.size() > 0 ||
681

18974
         native_immediates_threadsafe_.size() > 0 ||
682
4745
         native_immediates_interrupts_.size() > 0) {
683
    // Copy into a vector, since we can't sort an unordered_set in-place.
684
    std::vector<CleanupHookCallback> callbacks(
685
9474
        cleanup_hooks_.begin(), cleanup_hooks_.end());
686
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
687
    // need to be able to check whether they were un-scheduled by another hook.
688
689
9477
    std::sort(callbacks.begin(), callbacks.end(),
690
643864
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
691
      // Sort in descending order so that the most recently inserted callbacks
692
      // are run first.
693
643864
      return a.insertion_order_counter_ > b.insertion_order_counter_;
694
648602
    });
695
696
108152
    for (const CleanupHookCallback& cb : callbacks) {
697
103412
      if (cleanup_hooks_.count(cb) == 0) {
698
        // This hook was removed from the `cleanup_hooks_` set during another
699
        // hook that was run earlier. Nothing to do here.
700
759
        continue;
701
      }
702
703
102637
      cb.fn_(cb.arg_);
704
102682
      cleanup_hooks_.erase(cb);
705
    }
706
4739
    CleanupHandles();
707
  }
708
709
4748
  for (const int fd : unmanaged_fds_) {
710
    uv_fs_t close_req;
711
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
712
3
    uv_fs_req_cleanup(&close_req);
713
  }
714
4744
}
715
716
5297
void Environment::RunAtExitCallbacks() {
717
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
718
10597
                              "AtExit", this);
719
15719
  for (ExitCallback at_exit : at_exit_functions_) {
720
10419
    at_exit.cb_(at_exit.arg_);
721
  }
722
5300
  at_exit_functions_.clear();
723
5300
}
724
725
10446
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
726
10446
  at_exit_functions_.push_front(ExitCallback{cb, arg});
727
10446
}
728
729
229855
void Environment::RunAndClearInterrupts() {
730
238516
  while (native_immediates_interrupts_.size() > 0) {
731
17322
    NativeImmediateQueue queue;
732
    {
733
17322
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
734
8661
      queue.ConcatMove(std::move(native_immediates_interrupts_));
735
    }
736
8661
    DebugSealHandleScope seal_handle_scope(isolate());
737
738
25991
    while (auto head = queue.Shift())
739
17330
      head->Call(this);
740
  }
741
221195
}
742
743
212751
void Environment::RunAndClearNativeImmediates(bool only_refed) {
744
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
745
425492
                              "RunAndClearNativeImmediates", this);
746
425492
  HandleScope handle_scope(isolate_);
747
425496
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
748
749
212745
  size_t ref_count = 0;
750
751
  // Handle interrupts first. These functions are not allowed to throw
752
  // exceptions, so we do not need to handle that.
753
212745
  RunAndClearInterrupts();
754
755
425491
  auto drain_list = [&](NativeImmediateQueue* queue) {
756
908665
    TryCatchScope try_catch(this);
757
425494
    DebugSealHandleScope seal_handle_scope(isolate());
758
541192
    while (auto head = queue->Shift()) {
759
57856
      bool is_refed = head->flags() & CallbackFlags::kRefed;
760
57856
      if (is_refed)
761
34590
        ref_count++;
762
763

57856
      if (is_refed || !only_refed)
764
115354
        head->Call(this);
765
766
57852
      head.reset();  // Destroy now so that this is also observed by try_catch.
767
768
57852
      if (UNLIKELY(try_catch.HasCaught())) {
769

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

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

198689
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
920
133767
    return;
921
922
65854
  do {
923
131715
    MakeCallback(env->isolate(),
924
                 env->process_object(),
925
                 env->immediate_callback_function(),
926
                 0,
927
                 nullptr,
928
65861
                 {0, 0}).ToLocalChecked();
929

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

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

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

10460
      info_(info) {
1069
10460
  HandleScope handle_scope(isolate);
1070
5230
  if (info == nullptr) {
1071
464
    clear_async_id_stack();
1072
1073
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1074
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1075
    // See discussion in https://github.com/nodejs/node/pull/15454
1076
    // When removing this, do it by reverting the commit. Otherwise the test
1077
    // and flag changes won't be included.
1078
464
    fields_[kCheck] = 1;
1079
1080
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1081
    // specified default value and it should fallback to the executionAsyncId.
1082
    // 0 is not used as the magic value, because that indicates a missing
1083
    // context which is different from a default context.
1084
464
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1085
1086
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1087
    // context during bootstrap (code that runs before entering uv_run()).
1088
464
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1089
  }
1090
5230
}
1091
1092
4766
void AsyncHooks::Deserialize(Local<Context> context) {
1093
4766
  async_ids_stack_.Deserialize(context);
1094
4766
  fields_.Deserialize(context);
1095
4766
  async_id_fields_.Deserialize(context);
1096
4766
  if (info_->js_execution_async_resources != 0) {
1097
9532
    Local<Array> arr = context->GetDataFromSnapshotOnce<Array>(
1098
9532
                                  info_->js_execution_async_resources)
1099
4766
                              .ToLocalChecked();
1100
4766
    js_execution_async_resources_.Reset(context->GetIsolate(), arr);
1101
  }
1102
1103
4766
  native_execution_async_resources_.resize(
1104
9532
      info_->native_execution_async_resources.size());
1105
4766
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1106
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1107
                                   info_->native_execution_async_resources[i])
1108
                               .ToLocalChecked();
1109
    native_execution_async_resources_[i].Reset(context->GetIsolate(), obj);
1110
  }
1111
4766
  info_ = nullptr;
1112
4766
}
1113
1114
8
std::ostream& operator<<(std::ostream& output,
1115
                         const std::vector<SnapshotIndex>& v) {
1116
8
  output << "{ ";
1117
8
  for (const SnapshotIndex i : v) {
1118
    output << i << ", ";
1119
  }
1120
8
  output << " }";
1121
8
  return output;
1122
}
1123
1124
8
std::ostream& operator<<(std::ostream& output,
1125
                         const AsyncHooks::SerializeInfo& i) {
1126
  output << "{\n"
1127
8
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1128
16
         << "  " << i.fields << ",  // fields\n"
1129
16
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1130
16
         << "  " << i.js_execution_async_resources
1131
         << ",  // js_execution_async_resources\n"
1132
16
         << "  " << i.native_execution_async_resources
1133
         << ",  // native_execution_async_resources\n"
1134
8
         << "}";
1135
8
  return output;
1136
}
1137
1138
8
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1139
                                                SnapshotCreator* creator) {
1140
8
  SerializeInfo info;
1141
8
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1142
8
  info.fields = fields_.Serialize(context, creator);
1143
8
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1144
16
  if (!js_execution_async_resources_.IsEmpty()) {
1145
16
    info.js_execution_async_resources = creator->AddData(
1146
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1147
8
    CHECK_NE(info.js_execution_async_resources, 0);
1148
  } else {
1149
    info.js_execution_async_resources = 0;
1150
  }
1151
1152
8
  info.native_execution_async_resources.resize(
1153
8
      native_execution_async_resources_.size());
1154
8
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1155
    info.native_execution_async_resources[i] = creator->AddData(
1156
        context,
1157
        native_execution_async_resources_[i].Get(context->GetIsolate()));
1158
  }
1159
1160
8
  return info;
1161
}
1162
1163
22
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1164
22
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1165
22
  tracker->TrackField("fields", fields_);
1166
22
  tracker->TrackField("async_id_fields", async_id_fields_);
1167
22
}
1168
1169
10
void AsyncHooks::grow_async_ids_stack() {
1170
10
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1171
1172
30
  env()->async_hooks_binding()->Set(
1173
      env()->context(),
1174
      env()->async_ids_stack_string(),
1175
50
      async_ids_stack_.GetJSArray()).Check();
1176
10
}
1177
1178
537
void Environment::Exit(int exit_code) {
1179
537
  if (options()->trace_exit) {
1180
4
    HandleScope handle_scope(isolate());
1181
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1182
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1183
1184
2
    if (is_main_thread()) {
1185
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1186
    } else {
1187
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1188
1
              uv_os_getpid(), thread_id());
1189
    }
1190
1191
    fprintf(
1192
2
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1193
2
    PrintStackTrace(isolate(),
1194
                    StackTrace::CurrentStackTrace(
1195
2
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1196
  }
1197
537
  process_exit_handler_(this, exit_code);
1198
58
}
1199
1200
5250
void Environment::stop_sub_worker_contexts() {
1201
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1202
1203
5276
  while (!sub_worker_contexts_.empty()) {
1204
26
    Worker* w = *sub_worker_contexts_.begin();
1205
26
    remove_sub_worker_context(w);
1206
26
    w->Exit(1);
1207
26
    w->JoinThread();
1208
  }
1209
5224
}
1210
1211
4
Environment* Environment::worker_parent_env() const {
1212
4
  if (worker_context() == nullptr) return nullptr;
1213
  return worker_context()->env();
1214
}
1215
1216
52974
void Environment::AddUnmanagedFd(int fd) {
1217
52974
  if (!tracks_unmanaged_fds()) return;
1218
1580
  auto result = unmanaged_fds_.insert(fd);
1219
1580
  if (!result.second) {
1220
    ProcessEmitWarning(
1221
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1222
  }
1223
}
1224
1225
52603
void Environment::RemoveUnmanagedFd(int fd) {
1226
52603
  if (!tracks_unmanaged_fds()) return;
1227
1577
  size_t removed_count = unmanaged_fds_.erase(fd);
1228
1577
  if (removed_count == 0) {
1229
    ProcessEmitWarning(
1230
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1231
  }
1232
}
1233
1234
4594
void Environment::PrintInfoForSnapshotIfDebug() {
1235
4594
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1236
    fprintf(stderr, "BaseObjects at the exit of the Environment:\n");
1237
    PrintAllBaseObjects();
1238
    fprintf(stderr, "\nNative modules without cache:\n");
1239
    for (const auto& s : native_modules_without_cache) {
1240
      fprintf(stderr, "%s\n", s.c_str());
1241
    }
1242
    fprintf(stderr, "\nNative modules with cache:\n");
1243
    for (const auto& s : native_modules_with_cache) {
1244
      fprintf(stderr, "%s\n", s.c_str());
1245
    }
1246
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1247
    for (const auto mod : internal_bindings) {
1248
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1249
    }
1250
  }
1251
4597
}
1252
1253
void Environment::PrintAllBaseObjects() {
1254
  size_t i = 0;
1255
  std::cout << "BaseObjects\n";
1256
  ForEachBaseObject([&](BaseObject* obj) {
1257
    std::cout << "#" << i++ << " " << obj << ": " <<
1258
      obj->MemoryInfoName() << "\n";
1259
  });
1260
}
1261
1262
4595
void Environment::VerifyNoStrongBaseObjects() {
1263
  // When a process exits cleanly, i.e. because the event loop ends up without
1264
  // things to wait for, the Node.js objects that are left on the heap should
1265
  // be:
1266
  //
1267
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1268
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1269
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1270
  //   4. an inactive libuv handle (essentially the same here)
1271
  //
1272
  // There are a few exceptions to this rule, but generally, if there are
1273
  // C++-backed Node.js objects on the heap that do not fall into the above
1274
  // categories, we may be looking at a potential memory leak. Most likely,
1275
  // the cause is a missing MakeWeak() call on the corresponding object.
1276
  //
1277
  // In order to avoid this kind of problem, we check the list of BaseObjects
1278
  // for these criteria. Currently, we only do so when explicitly instructed to
1279
  // or when in debug mode (where --verify-base-objects is always-on).
1280
1281
4595
  if (!options()->verify_base_objects) return;
1282
1283
  ForEachBaseObject([](BaseObject* obj) {
1284
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1285
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1286
            obj->MemoryInfoName().c_str());
1287
    fflush(stderr);
1288
    ABORT();
1289
  });
1290
}
1291
1292
8
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1293
8
  EnvSerializeInfo info;
1294
8
  Local<Context> ctx = context();
1295
1296
8
  SerializeBindingData(this, creator, &info);
1297
  // Currently all modules are compiled without cache in builtin snapshot
1298
  // builder.
1299
16
  info.native_modules = std::vector<std::string>(
1300
8
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1301
1302
8
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1303
8
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1304
8
  info.tick_info = tick_info_.Serialize(ctx, creator);
1305
8
  info.performance_state = performance_state_->Serialize(ctx, creator);
1306
8
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1307
8
  info.should_abort_on_uncaught_toggle =
1308
8
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1309
1310
8
  size_t id = 0;
1311
#define V(PropertyName, TypeName)                                              \
1312
  do {                                                                         \
1313
    Local<TypeName> field = PropertyName();                                    \
1314
    if (!field.IsEmpty()) {                                                    \
1315
      size_t index = creator->AddData(field);                                  \
1316
      info.persistent_templates.push_back({#PropertyName, id, index});         \
1317
    }                                                                          \
1318
    id++;                                                                      \
1319
  } while (0);
1320










240
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1321
8
#undef V
1322
16
1323
8
  id = 0;
1324
24
#define V(PropertyName, TypeName)                                              \
1325
8
  do {                                                                         \
1326
32
    Local<TypeName> field = PropertyName();                                    \
1327
24
    if (!field.IsEmpty()) {                                                    \
1328
8
      size_t index = creator->AddData(ctx, field);                             \
1329
16
      info.persistent_values.push_back({#PropertyName, id, index});            \
1330
    }                                                                          \
1331
16
    id++;                                                                      \
1332
8
  } while (0);
1333




















496
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1334
16
#undef V
1335

48
1336
32
  info.context = creator->AddData(ctx, context());
1337

72
  return info;
1338

48
}
1339
48
1340

72
std::ostream& operator<<(std::ostream& output,
1341
16
                         const std::vector<PropInfo>& vec) {
1342

56
  output << "{\n";
1343
432
  for (const auto& info : vec) {
1344

824
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1345
1184
           << std::to_string(info.index) << " },\n";
1346

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








































































176342
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1455
#undef V
1456
1457
4766
  i = 0;  // index to the array
1458
4766
  id = 0;
1459
4766
  const std::vector<PropInfo>& values = info->persistent_values;
1460
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1461
                                              values, value, ctx)
1462














































































































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

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

101645
  if (self->has_pointer_data() &&
1681
4111
      self->pointer_data()->strong_ptr_count > 0) {
1682
293
    return self->Detach();
1683
22
  }
1684
97287
  delete self;
1685
22
}
1686
22
1687
386
bool BaseObject::IsDoneInitializing() const { return true; }
1688
22
1689
448
Local<Object> BaseObject::WrappedObject() const {
1690
448
  return object();
1691
}
1692
1693
852
bool BaseObject::IsRootNode() const {
1694
1704
  return !persistent_handle_.IsWeak();
1695
}
1696
1697
82867
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1698
82867
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1699
82867
  if (tmpl.IsEmpty()) {
1700
464
    tmpl = env->NewFunctionTemplate(nullptr);
1701
928
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1702
464
    env->set_base_object_ctor_template(tmpl);
1703
  }
1704
82867
  return tmpl;
1705
}
1706
1707
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1708
  return IsWeakOrDetached();
1709
}
1710
1711

14520
}  // namespace node