GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 829 895 92.6 %
Date: 2022-09-29 04:23:51 Branches: 799 1394 57.3 %

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_contextify.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::EscapableHandleScope;
39
using v8::Function;
40
using v8::FunctionTemplate;
41
using v8::HandleScope;
42
using v8::HeapSpaceStatistics;
43
using v8::Integer;
44
using v8::Isolate;
45
using v8::Local;
46
using v8::MaybeLocal;
47
using v8::NewStringType;
48
using v8::Number;
49
using v8::Object;
50
using v8::Private;
51
using v8::Script;
52
using v8::SnapshotCreator;
53
using v8::StackTrace;
54
using v8::String;
55
using v8::Symbol;
56
using v8::TracingController;
57
using v8::TryCatch;
58
using v8::Undefined;
59
using v8::Value;
60
using worker::Worker;
61
62
int const ContextEmbedderTag::kNodeContextTag = 0x6e6f64;
63
void* const ContextEmbedderTag::kNodeContextTagPtr = const_cast<void*>(
64
    static_cast<const void*>(&ContextEmbedderTag::kNodeContextTag));
65
66
15816
void AsyncHooks::SetJSPromiseHooks(Local<Function> init,
67
                                   Local<Function> before,
68
                                   Local<Function> after,
69
                                   Local<Function> resolve) {
70
15816
  js_promise_hooks_[0].Reset(env()->isolate(), init);
71
15816
  js_promise_hooks_[1].Reset(env()->isolate(), before);
72
15816
  js_promise_hooks_[2].Reset(env()->isolate(), after);
73
15816
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
74
31977
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
75
16161
    if (it->IsEmpty()) {
76
      contexts_.erase(it--);
77
      continue;
78
    }
79
32322
    PersistentToLocal::Weak(env()->isolate(), *it)
80
16161
        ->SetPromiseHooks(init, before, after, resolve);
81
  }
82
15816
}
83
84
// Remember to keep this code aligned with pushAsyncContext() in JS.
85
843617
void AsyncHooks::push_async_context(double async_id,
86
                                    double trigger_async_id,
87
                                    Local<Object> resource) {
88
  // Since async_hooks is experimental, do only perform the check
89
  // when async_hooks is enabled.
90
843617
  if (fields_[kCheck] > 0) {
91
843613
    CHECK_GE(async_id, -1);
92
843613
    CHECK_GE(trigger_async_id, -1);
93
  }
94
95
843617
  uint32_t offset = fields_[kStackLength];
96
843617
  if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack();
97
843617
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
98
843617
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
99
843617
  fields_[kStackLength] += 1;
100
843617
  async_id_fields_[kExecutionAsyncId] = async_id;
101
843617
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
102
103
#ifdef DEBUG
104
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
105
    CHECK(native_execution_async_resources_[i].IsEmpty());
106
#endif
107
108
  // When this call comes from JS (as a way of increasing the stack size),
109
  // `resource` will be empty, because JS caches these values anyway.
110
843617
  if (!resource.IsEmpty()) {
111
843613
    native_execution_async_resources_.resize(offset + 1);
112
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
113
843613
    native_execution_async_resources_[offset] = resource;
114
  }
115
843617
}
116
117
// Remember to keep this code aligned with popAsyncContext() in JS.
118
843206
bool AsyncHooks::pop_async_context(double async_id) {
119
  // In case of an exception then this may have already been reset, if the
120
  // stack was multiple MakeCallback()'s deep.
121
843206
  if (UNLIKELY(fields_[kStackLength] == 0)) return false;
122
123
  // Ask for the async_id to be restored as a check that the stack
124
  // hasn't been corrupted.
125
1684298
  if (UNLIKELY(fields_[kCheck] > 0 &&
126

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

1684294
             !native_execution_async_resources_[offset].IsEmpty())) {
137
#ifdef DEBUG
138
    for (uint32_t i = offset + 1; i < native_execution_async_resources_.size();
139
         i++) {
140
      CHECK(native_execution_async_resources_[i].IsEmpty());
141
    }
142
#endif
143
842147
    native_execution_async_resources_.resize(offset);
144
842147
    if (native_execution_async_resources_.size() <
145

1103711
            native_execution_async_resources_.capacity() / 2 &&
146
261564
        native_execution_async_resources_.size() > 16) {
147
      native_execution_async_resources_.shrink_to_fit();
148
    }
149
  }
150
151
1684294
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
152
43911
    HandleScope handle_scope(env()->isolate());
153
87822
    USE(js_execution_async_resources()->Set(
154
        env()->context(),
155
        env()->length_string(),
156
175644
        Integer::NewFromUnsigned(env()->isolate(), offset)));
157
  }
158
159
842147
  return fields_[kStackLength] > 0;
160
}
161
162
2331
void AsyncHooks::clear_async_id_stack() {
163
2331
  if (env()->can_call_into_js()) {
164
1366
    Isolate* isolate = env()->isolate();
165
2732
    HandleScope handle_scope(isolate);
166
1366
    if (!js_execution_async_resources_.IsEmpty()) {
167
2580
      USE(PersistentToLocal::Strong(js_execution_async_resources_)
168
2580
              ->Set(env()->context(),
169
                    env()->length_string(),
170
5160
                    Integer::NewFromUnsigned(isolate, 0)));
171
    }
172
  }
173
174
2331
  native_execution_async_resources_.clear();
175
2331
  native_execution_async_resources_.shrink_to_fit();
176
177
2331
  async_id_fields_[kExecutionAsyncId] = 0;
178
2331
  async_id_fields_[kTriggerAsyncId] = 0;
179
2331
  fields_[kStackLength] = 0;
180
2331
}
181
182
6944
void AsyncHooks::AddContext(Local<Context> ctx) {
183
20832
  ctx->SetPromiseHooks(js_promise_hooks_[0].IsEmpty()
184
6944
                           ? Local<Function>()
185
205
                           : PersistentToLocal::Strong(js_promise_hooks_[0]),
186
6944
                       js_promise_hooks_[1].IsEmpty()
187
6944
                           ? Local<Function>()
188
205
                           : PersistentToLocal::Strong(js_promise_hooks_[1]),
189
6944
                       js_promise_hooks_[2].IsEmpty()
190
6944
                           ? Local<Function>()
191
205
                           : PersistentToLocal::Strong(js_promise_hooks_[2]),
192
6944
                       js_promise_hooks_[3].IsEmpty()
193
6944
                           ? Local<Function>()
194
                           : PersistentToLocal::Strong(js_promise_hooks_[3]));
195
196
6944
  size_t id = contexts_.size();
197
6944
  contexts_.resize(id + 1);
198
6944
  contexts_[id].Reset(env()->isolate(), ctx);
199
6944
  contexts_[id].SetWeak();
200
6944
}
201
202
527
void AsyncHooks::RemoveContext(Local<Context> ctx) {
203
527
  Isolate* isolate = env()->isolate();
204
1054
  HandleScope handle_scope(isolate);
205
527
  contexts_.erase(std::remove_if(contexts_.begin(),
206
                                 contexts_.end(),
207
4567
                                 [&](auto&& el) { return el.IsEmpty(); }),
208
1054
                  contexts_.end());
209
4505
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
210
3978
    Local<Context> saved_context = PersistentToLocal::Weak(isolate, *it);
211
3978
    if (saved_context == ctx) {
212
      it->Reset();
213
      contexts_.erase(it);
214
      break;
215
    }
216
  }
217
527
}
218
219
239491
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
220
239491
    Environment* env, double default_trigger_async_id)
221
239491
    : async_hooks_(env->async_hooks()) {
222
239491
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
223
239491
    CHECK_GE(default_trigger_async_id, 0);
224
  }
225
226
239491
  old_default_trigger_async_id_ =
227
239491
      async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
228
239491
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
229
239491
      default_trigger_async_id;
230
239491
}
231
232
478980
AsyncHooks::DefaultTriggerAsyncIdScope::~DefaultTriggerAsyncIdScope() {
233
239490
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
234
239490
      old_default_trigger_async_id_;
235
239490
}
236
237
239491
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
238
239491
    AsyncWrap* async_wrap)
239
    : DefaultTriggerAsyncIdScope(async_wrap->env(),
240
239491
                                 async_wrap->get_async_id()) {}
241
242
12
std::ostream& operator<<(std::ostream& output,
243
                         const std::vector<SnapshotIndex>& v) {
244
12
  output << "{ ";
245
2142
  for (const SnapshotIndex i : v) {
246
2130
    output << i << ", ";
247
  }
248
12
  output << " }";
249
12
  return output;
250
}
251
252
6
std::ostream& operator<<(std::ostream& output,
253
                         const IsolateDataSerializeInfo& i) {
254
  output << "{\n"
255
6
         << "// -- primitive begins --\n"
256
6
         << i.primitive_values << ",\n"
257
         << "// -- primitive ends --\n"
258
6
         << "// -- template_values begins --\n"
259
6
         << i.template_values << ",\n"
260
         << "// -- template_values ends --\n"
261
6
         << "}";
262
6
  return output;
263
}
264
265
6
std::ostream& operator<<(std::ostream& output, const SnapshotMetadata& i) {
266
  output << "{\n"
267
         << "  "
268
6
         << (i.type == SnapshotMetadata::Type::kDefault
269
                 ? "SnapshotMetadata::Type::kDefault"
270
                 : "SnapshotMetadata::Type::kFullyCustomized")
271
         << ", // type\n"
272
6
         << "  \"" << i.node_version << "\", // node_version\n"
273
6
         << "  \"" << i.node_arch << "\", // node_arch\n"
274
6
         << "  \"" << i.node_platform << "\", // node_platform\n"
275
6
         << "  " << i.v8_cache_version_tag << ", // v8_cache_version_tag\n"
276
6
         << "}";
277
6
  return output;
278
}
279
280
6
IsolateDataSerializeInfo IsolateData::Serialize(SnapshotCreator* creator) {
281
6
  Isolate* isolate = creator->GetIsolate();
282
6
  IsolateDataSerializeInfo info;
283
12
  HandleScope handle_scope(isolate);
284
  // XXX(joyeecheung): technically speaking, the indexes here should be
285
  // consecutive and we could just return a range instead of an array,
286
  // but that's not part of the V8 API contract so we use an array
287
  // just to be safe.
288
289
#define VP(PropertyName, StringValue) V(Private, PropertyName)
290
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
291
#define VS(PropertyName, StringValue) V(String, PropertyName)
292
#define V(TypeName, PropertyName)                                              \
293
  info.primitive_values.push_back(                                             \
294
      creator->AddData(PropertyName##_.Get(isolate)));
295
60
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
296
78
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
297
1662
  PER_ISOLATE_STRING_PROPERTIES(VS)
298
#undef V
299
#undef VY
300
#undef VS
301
#undef VP
302
303
354
  for (size_t i = 0; i < AsyncWrap::PROVIDERS_LENGTH; i++)
304
696
    info.primitive_values.push_back(creator->AddData(async_wrap_provider(i)));
305
306
6
  uint32_t id = 0;
307
#define V(PropertyName, TypeName)                                              \
308
  do {                                                                         \
309
    Local<TypeName> field = PropertyName();                                    \
310
    if (!field.IsEmpty()) {                                                    \
311
      size_t index = creator->AddData(field);                                  \
312
      info.template_values.push_back({#PropertyName, id, index});              \
313
    }                                                                          \
314
    id++;                                                                      \
315
  } while (0);
316


















348
  PER_ISOLATE_TEMPLATE_PROPERTIES(V)
317
#undef V
318
319
6
  return info;
320
}
321
322
5523
void IsolateData::DeserializeProperties(const IsolateDataSerializeInfo* info) {
323
5523
  size_t i = 0;
324
5523
  HandleScope handle_scope(isolate_);
325
326
#define VP(PropertyName, StringValue) V(Private, PropertyName)
327
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
328
#define VS(PropertyName, StringValue) V(String, PropertyName)
329
#define V(TypeName, PropertyName)                                              \
330
  do {                                                                         \
331
    MaybeLocal<TypeName> maybe_field =                                         \
332
        isolate_->GetDataFromSnapshotOnce<TypeName>(                           \
333
            info->primitive_values[i++]);                                      \
334
    Local<TypeName> field;                                                     \
335
    if (!maybe_field.ToLocal(&field)) {                                        \
336
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
337
    }                                                                          \
338
    PropertyName##_.Set(isolate_, field);                                      \
339
  } while (0);
340




104937
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
341






138075
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
342










































































































































3054219
  PER_ISOLATE_STRING_PROPERTIES(VS)
343
#undef V
344
#undef VY
345
#undef VS
346
#undef VP
347
348
325857
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
349
    MaybeLocal<String> maybe_field =
350
640668
        isolate_->GetDataFromSnapshotOnce<String>(info->primitive_values[i++]);
351
    Local<String> field;
352
320334
    if (!maybe_field.ToLocal(&field)) {
353
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
354
    }
355
320334
    async_wrap_providers_[j].Set(isolate_, field);
356
  }
357
358
5523
  const std::vector<PropInfo>& values = info->template_values;
359
5523
  i = 0;  // index to the array
360
5523
  uint32_t id = 0;
361
#define V(PropertyName, TypeName)                                              \
362
  do {                                                                         \
363
    if (values.size() > i && id == values[i].id) {                             \
364
      const PropInfo& d = values[i];                                           \
365
      DCHECK_EQ(d.name, #PropertyName);                                        \
366
      MaybeLocal<TypeName> maybe_field =                                       \
367
          isolate_->GetDataFromSnapshotOnce<TypeName>(d.index);                \
368
      Local<TypeName> field;                                                   \
369
      if (!maybe_field.ToLocal(&field)) {                                      \
370
        fprintf(stderr,                                                        \
371
                "Failed to deserialize isolate data template " #PropertyName   \
372
                "\n");                                                         \
373
      }                                                                        \
374
      set_##PropertyName(field);                                               \
375
      i++;                                                                     \
376
    }                                                                          \
377
    id++;                                                                      \
378
  } while (0);
379
380










































































226443
  PER_ISOLATE_TEMPLATE_PROPERTIES(V);
381
#undef V
382
5523
}
383
384
792
void IsolateData::CreateProperties() {
385
  // Create string and private symbol properties as internalized one byte
386
  // strings after the platform is properly initialized.
387
  //
388
  // Internalized because it makes property lookups a little faster and
389
  // because the string is created in the old space straight away.  It's going
390
  // to end up in the old space sooner or later anyway but now it doesn't go
391
  // through v8::Eternal's new space handling first.
392
  //
393
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
394
  // decoding step.
395
396
1584
  HandleScope handle_scope(isolate_);
397
398
#define V(PropertyName, StringValue)                                           \
399
  PropertyName##_.Set(                                                         \
400
      isolate_,                                                                \
401
      Private::New(isolate_,                                                   \
402
                   String::NewFromOneByte(                                     \
403
                       isolate_,                                               \
404
                       reinterpret_cast<const uint8_t*>(StringValue),          \
405
                       NewStringType::kInternalized,                           \
406
                       sizeof(StringValue) - 1)                                \
407
                       .ToLocalChecked()));
408
7920
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
409
#undef V
410
#define V(PropertyName, StringValue)                                           \
411
  PropertyName##_.Set(                                                         \
412
      isolate_,                                                                \
413
      Symbol::New(isolate_,                                                    \
414
                  String::NewFromOneByte(                                      \
415
                      isolate_,                                                \
416
                      reinterpret_cast<const uint8_t*>(StringValue),           \
417
                      NewStringType::kInternalized,                            \
418
                      sizeof(StringValue) - 1)                                 \
419
                      .ToLocalChecked()));
420
10296
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
421
#undef V
422
#define V(PropertyName, StringValue)                                           \
423
  PropertyName##_.Set(                                                         \
424
      isolate_,                                                                \
425
      String::NewFromOneByte(isolate_,                                         \
426
                             reinterpret_cast<const uint8_t*>(StringValue),    \
427
                             NewStringType::kInternalized,                     \
428
                             sizeof(StringValue) - 1)                          \
429
          .ToLocalChecked());
430
219384
  PER_ISOLATE_STRING_PROPERTIES(V)
431
#undef V
432
433
  // Create all the provider strings that will be passed to JS. Place them in
434
  // an array so the array index matches the PROVIDER id offset. This way the
435
  // strings can be retrieved quickly.
436
#define V(Provider)                                                           \
437
  async_wrap_providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                \
438
      isolate_,                                                               \
439
      String::NewFromOneByte(                                                 \
440
        isolate_,                                                             \
441
        reinterpret_cast<const uint8_t*>(#Provider),                          \
442
        NewStringType::kInternalized,                                         \
443
        sizeof(#Provider) - 1).ToLocalChecked());
444
46728
  NODE_ASYNC_PROVIDER_TYPES(V)
445
#undef V
446
447
  // TODO(legendecas): eagerly create per isolate templates.
448
792
  Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
449
1584
  templ->InstanceTemplate()->SetInternalFieldCount(
450
      BaseObject::kInternalFieldCount);
451
792
  templ->Inherit(BaseObject::GetConstructorTemplate(this));
452
792
  set_binding_data_ctor_template(templ);
453
454
792
  set_contextify_global_template(
455
792
      contextify::ContextifyContext::CreateGlobalTemplate(isolate_));
456
792
}
457
458
6315
IsolateData::IsolateData(Isolate* isolate,
459
                         uv_loop_t* event_loop,
460
                         MultiIsolatePlatform* platform,
461
                         ArrayBufferAllocator* node_allocator,
462
6315
                         const IsolateDataSerializeInfo* isolate_data_info)
463
    : isolate_(isolate),
464
      event_loop_(event_loop),
465
51
      node_allocator_(node_allocator == nullptr ? nullptr
466
6264
                                                : node_allocator->GetImpl()),
467
12630
      platform_(platform) {
468
6315
  options_.reset(
469
6315
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
470
471
6315
  if (isolate_data_info == nullptr) {
472
792
    CreateProperties();
473
  } else {
474
5523
    DeserializeProperties(isolate_data_info);
475
  }
476
6315
}
477
478
25
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
479
#define V(PropertyName, StringValue)                                           \
480
  tracker->TrackField(#PropertyName, PropertyName());
481
25
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
482
483
25
  PER_ISOLATE_STRING_PROPERTIES(V)
484
#undef V
485
486
25
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
487
488
25
  if (node_allocator_ != nullptr) {
489
25
    tracker->TrackFieldWithSize(
490
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
491
  }
492
25
  tracker->TrackFieldWithSize(
493
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
494
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
495
25
}
496
497
154
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
498

154
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
499
    // Ideally, we’d have a consistent story that treats all threads/Environment
500
    // instances equally here. However, tracing is essentially global, and this
501
    // callback is called from whichever thread calls `StartTracing()` or
502
    // `StopTracing()`. The only way to do this in a threadsafe fashion
503
    // seems to be only tracking this from the main thread, and only allowing
504
    // these state modifications from the main thread.
505
96
    return;
506
  }
507
508
143
  if (env_->principal_realm() == nullptr) {
509
85
    return;
510
  }
511
512
58
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
513
58
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
514
515
58
  Isolate* isolate = env_->isolate();
516
58
  HandleScope handle_scope(isolate);
517
58
  Local<Function> cb = env_->trace_category_state_function();
518
58
  if (cb.IsEmpty())
519
    return;
520
58
  TryCatchScope try_catch(env_);
521
58
  try_catch.SetVerbose(true);
522
116
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
523
116
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
524
}
525
526
6944
void Environment::AssignToContext(Local<v8::Context> context,
527
                                  Realm* realm,
528
                                  const ContextInfo& info) {
529
6944
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
530
                                           this);
531
6944
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kRealm, realm);
532
  // Used to retrieve bindings
533
13888
  context->SetAlignedPointerInEmbedderData(
534
6944
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
535
536
  // ContextifyContexts will update this to a pointer to the native object.
537
6944
  context->SetAlignedPointerInEmbedderData(
538
      ContextEmbedderIndex::kContextifyContext, nullptr);
539
540
  // This must not be done before other context fields are initialized.
541
6944
  ContextEmbedderTag::TagNodeContext(context);
542
543
#if HAVE_INSPECTOR
544
6944
  inspector_agent()->ContextCreated(context, info);
545
#endif  // HAVE_INSPECTOR
546
547
6944
  this->async_hooks()->AddContext(context);
548
6944
}
549
550
186
void Environment::TryLoadAddon(
551
    const char* filename,
552
    int flags,
553
    const std::function<bool(binding::DLib*)>& was_loaded) {
554
186
  loaded_addons_.emplace_back(filename, flags);
555
186
  if (!was_loaded(&loaded_addons_.back())) {
556
10
    loaded_addons_.pop_back();
557
  }
558
186
}
559
560
12
std::string Environment::GetCwd() {
561
  char cwd[PATH_MAX_BYTES];
562
12
  size_t size = PATH_MAX_BYTES;
563
12
  const int err = uv_cwd(cwd, &size);
564
565
12
  if (err == 0) {
566
12
    CHECK_GT(size, 0);
567
12
    return cwd;
568
  }
569
570
  // This can fail if the cwd is deleted. In that case, fall back to
571
  // exec_path.
572
  const std::string& exec_path = exec_path_;
573
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
574
}
575
576
1903
void Environment::add_refs(int64_t diff) {
577
1903
  task_queues_async_refs_ += diff;
578
1903
  CHECK_GE(task_queues_async_refs_, 0);
579
1903
  if (task_queues_async_refs_ == 0)
580
421
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
581
  else
582
1482
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
583
1903
}
584
585
66451
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
586
132902
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
587
  std::unique_ptr<v8::BackingStore> bs =
588
66451
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
589
66451
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
590
66451
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
591
66451
  return buf;
592
}
593
594
81394
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
595
    const uv_buf_t& buf) {
596
81394
  std::unique_ptr<v8::BackingStore> bs;
597
81394
  if (buf.base != nullptr) {
598
66451
    auto it = released_allocated_buffers_.find(buf.base);
599
66451
    CHECK_NE(it, released_allocated_buffers_.end());
600
66451
    bs = std::move(it->second);
601
66451
    released_allocated_buffers_.erase(it);
602
  }
603
81394
  return bs;
604
}
605
606
6304
std::string GetExecPath(const std::vector<std::string>& argv) {
607
  char exec_path_buf[2 * PATH_MAX];
608
6304
  size_t exec_path_len = sizeof(exec_path_buf);
609
6304
  std::string exec_path;
610
6304
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
611
6304
    exec_path = std::string(exec_path_buf, exec_path_len);
612
  } else {
613
    exec_path = argv[0];
614
  }
615
616
  // On OpenBSD process.execPath will be relative unless we
617
  // get the full path before process.execPath is used.
618
#if defined(__OpenBSD__)
619
  uv_fs_t req;
620
  req.ptr = nullptr;
621
  if (0 ==
622
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
623
    CHECK_NOT_NULL(req.ptr);
624
    exec_path = std::string(static_cast<char*>(req.ptr));
625
  }
626
  uv_fs_req_cleanup(&req);
627
#endif
628
629
6304
  return exec_path;
630
}
631
632
6304
Environment::Environment(IsolateData* isolate_data,
633
                         Isolate* isolate,
634
                         const std::vector<std::string>& args,
635
                         const std::vector<std::string>& exec_args,
636
                         const EnvSerializeInfo* env_info,
637
                         EnvironmentFlags::Flags flags,
638
6304
                         ThreadId thread_id)
639
    : isolate_(isolate),
640
      isolate_data_(isolate_data),
641
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
642
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
643
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
644
6304
      timer_base_(uv_now(isolate_data->event_loop())),
645
      exec_argv_(exec_args),
646
      argv_(args),
647
      exec_path_(GetExecPath(args)),
648
6304
      exiting_(isolate_, 1, MAYBE_FIELD_PTR(env_info, exiting)),
649
      should_abort_on_uncaught_toggle_(
650
6304
          isolate_,
651
          1,
652
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
653
6304
      stream_base_state_(isolate_,
654
                         StreamBase::kNumStreamBaseStateFields,
655
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
656
6304
      time_origin_(PERFORMANCE_NOW()),
657
6304
      time_origin_timestamp_(GetCurrentTimeInMicroseconds()),
658
      flags_(flags),
659
6304
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
660
6304
                     ? AllocateEnvironmentThreadId().id
661



25216
                     : thread_id.id) {
662
  // We'll be creating new objects so make sure we've entered the context.
663
12608
  HandleScope handle_scope(isolate);
664
665
  // Set some flags if only kDefaultFlags was passed. This can make API version
666
  // transitions easier for embedders.
667
6304
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
668
11160
    flags_ = flags_ |
669
5580
        EnvironmentFlags::kOwnsProcessState |
670
        EnvironmentFlags::kOwnsInspector;
671
  }
672
673
6304
  set_env_vars(per_process::system_environment);
674
6304
  enabled_debug_list_.Parse(env_vars(), isolate);
675
676
  // We create new copies of the per-Environment option sets, so that it is
677
  // easier to modify them after Environment creation. The defaults are
678
  // part of the per-Isolate option set, for which in turn the defaults are
679
  // part of the per-process option set.
680
12608
  options_ = std::make_shared<EnvironmentOptions>(
681
18912
      *isolate_data->options()->per_env);
682
6304
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
683
6304
      options_->debug_options().host_port);
684
685
6304
  heap_snapshot_near_heap_limit_ =
686
6304
      static_cast<uint32_t>(options_->heap_snapshot_near_heap_limit);
687
688
6304
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
689
724
    set_abort_on_uncaught_exception(false);
690
  }
691
692
#if HAVE_INSPECTOR
693
  // We can only create the inspector agent after having cloned the options.
694
6304
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
695
#endif
696
697
6304
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
698
6304
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
699
6304
    if (TracingController* tracing_controller = writer->GetTracingController())
700
6253
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
701
  }
702
703
6304
  destroy_async_id_list_.reserve(512);
704
705
6304
  performance_state_ = std::make_unique<performance::PerformanceState>(
706
6304
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
707
708
6304
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
709
6304
          TRACING_CATEGORY_NODE1(environment)) != 0) {
710
16
    auto traced_value = tracing::TracedValue::Create();
711
8
    traced_value->BeginArray("args");
712
18
    for (const std::string& arg : args) traced_value->AppendString(arg);
713
8
    traced_value->EndArray();
714
8
    traced_value->BeginArray("exec_args");
715
33
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
716
8
    traced_value->EndArray();
717

15
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
718
                                      "Environment",
719
                                      this,
720
                                      "args",
721
                                      std::move(traced_value));
722
  }
723
6304
}
724
725
781
Environment::Environment(IsolateData* isolate_data,
726
                         Local<Context> context,
727
                         const std::vector<std::string>& args,
728
                         const std::vector<std::string>& exec_args,
729
                         const EnvSerializeInfo* env_info,
730
                         EnvironmentFlags::Flags flags,
731
781
                         ThreadId thread_id)
732
    : Environment(isolate_data,
733
                  context->GetIsolate(),
734
                  args,
735
                  exec_args,
736
                  env_info,
737
                  flags,
738
781
                  thread_id) {
739
781
  InitializeMainContext(context, env_info);
740
781
}
741
742
6304
void Environment::InitializeMainContext(Local<Context> context,
743
                                        const EnvSerializeInfo* env_info) {
744
6304
  principal_realm_ = std::make_unique<Realm>(
745
6304
      this, context, MAYBE_FIELD_PTR(env_info, principal_realm));
746
6304
  AssignToContext(context, principal_realm_.get(), ContextInfo(""));
747
6304
  if (env_info != nullptr) {
748
5523
    DeserializeProperties(env_info);
749
  }
750
751
6304
  if (!options_->force_async_hooks_checks) {
752
1
    async_hooks_.no_force_checks();
753
  }
754
755
  // By default, always abort when --abort-on-uncaught-exception was passed.
756
6304
  should_abort_on_uncaught_toggle_[0] = 1;
757
758
  // The process is not exiting by default.
759
6304
  set_exiting(false);
760
761
6304
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
762
                           time_origin_);
763
6304
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
764
                           per_process::node_start_time);
765
766
6304
  if (per_process::v8_initialized) {
767
6260
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
768
                            performance::performance_v8_start);
769
  }
770
6304
}
771
772
22908
Environment::~Environment() {
773
  HandleScope handle_scope(isolate());
774
5727
  Local<Context> ctx = context();
775
776
5727
  if (Environment** interrupt_data = interrupt_data_.load()) {
777
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
778
    // then force V8 to run interrupts by compiling and running an empty script
779
    // so as not to leak memory.
780
11
    *interrupt_data = nullptr;
781
782
22
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
783
22
    TryCatch try_catch(isolate());
784
11
    Context::Scope context_scope(ctx);
785
786
#ifdef DEBUG
787
    bool consistency_check = false;
788
    isolate()->RequestInterrupt([](Isolate*, void* data) {
789
      *static_cast<bool*>(data) = true;
790
    }, &consistency_check);
791
#endif
792
793
    Local<Script> script;
794
33
    if (Script::Compile(ctx, String::Empty(isolate())).ToLocal(&script))
795
11
      USE(script->Run(ctx));
796
797
    DCHECK(consistency_check);
798
  }
799
800
  // FreeEnvironment() should have set this.
801
5727
  CHECK(is_stopping());
802
803
5727
  if (heapsnapshot_near_heap_limit_callback_added_) {
804
    RemoveHeapSnapshotNearHeapLimitCallback(0);
805
  }
806
807
5727
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
808
      BuildEmbedderGraph, this);
809
810
#if HAVE_INSPECTOR
811
  // Destroy inspector agent before erasing the context. The inspector
812
  // destructor depends on the context still being accessible.
813
5727
  inspector_agent_.reset();
814
#endif
815
816
5727
  ctx->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
817
                                       nullptr);
818
5727
  ctx->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kRealm, nullptr);
819
820
5727
  if (trace_state_observer_) {
821
5727
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
822
5727
    CHECK_NOT_NULL(writer);
823
5727
    if (TracingController* tracing_controller = writer->GetTracingController())
824
5678
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
825
  }
826
827

10699
  TRACE_EVENT_NESTABLE_ASYNC_END0(
828
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
829
830
  // Do not unload addons on the main thread. Some addons need to retain memory
831
  // beyond the Environment's lifetime, and unloading them early would break
832
  // them; with Worker threads, we have the opportunity to be stricter.
833
  // Also, since the main thread usually stops just before the process exits,
834
  // this is far less relevant here.
835
5727
  if (!is_main_thread()) {
836
    // Dereference all addons that were loaded into this environment.
837
735
    for (binding::DLib& addon : loaded_addons_) {
838
14
      addon.Close();
839
    }
840
  }
841
5727
}
842
843
6270
void Environment::InitializeLibuv() {
844
12540
  HandleScope handle_scope(isolate());
845
6270
  Context::Scope context_scope(context());
846
847
6270
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
848
6270
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
849
850
6270
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
851
6270
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
852
853
6270
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
854
855
6270
  CHECK_EQ(0, uv_check_start(immediate_check_handle(), CheckImmediate));
856
857
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
858
  // but not all samples are created equal; mark the wall clock time spent in
859
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
860
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
861
6270
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
862
6270
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
863
864
25399
  CHECK_EQ(0, uv_async_init(
865
      event_loop(),
866
      &task_queues_async_,
867
      [](uv_async_t* async) {
868
        Environment* env = ContainerOf(
869
            &Environment::task_queues_async_, async);
870
        HandleScope handle_scope(env->isolate());
871
        Context::Scope context_scope(env->context());
872
        env->RunAndClearNativeImmediates();
873
      }));
874
6270
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
875
6270
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
876
6270
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
877
878
  {
879
12540
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
880
6270
    task_queues_async_initialized_ = true;
881

12540
    if (native_immediates_threadsafe_.size() > 0 ||
882
6270
        native_immediates_interrupts_.size() > 0) {
883
5519
      uv_async_send(&task_queues_async_);
884
    }
885
  }
886
887
  // Register clean-up cb to be called to clean up the handles
888
  // when the environment is freed, note that they are not cleaned in
889
  // the one environment per process setup, but will be called in
890
  // FreeEnvironment.
891
6270
  RegisterHandleCleanups();
892
893
6270
  StartProfilerIdleNotifier();
894
6270
}
895
896
373
void Environment::ExitEnv() {
897
373
  set_can_call_into_js(false);
898
373
  set_stopping(true);
899
373
  isolate_->TerminateExecution();
900
746
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
901
373
}
902
903
6270
void Environment::RegisterHandleCleanups() {
904
6270
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
905
34158
                                        void* arg) {
906
34158
    handle->data = env;
907
908
34158
    env->CloseHandle(handle, [](uv_handle_t* handle) {
909
#ifdef DEBUG
910
      memset(handle, 0xab, uv_handle_size(handle->type));
911
#endif
912
34158
    });
913
34158
  };
914
915
37620
  auto register_handle = [&](uv_handle_t* handle) {
916
37620
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
917
43890
  };
918
6270
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
919
6270
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
920
6270
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
921
6270
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
922
6270
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
923
6270
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
924
6270
}
925
926
11448
void Environment::CleanupHandles() {
927
  {
928
11448
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
929
11448
    task_queues_async_initialized_ = false;
930
  }
931
932
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
933
22896
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
934
935
11448
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
936
937
11609
  for (ReqWrapBase* request : req_wrap_queue_)
938
161
    request->Cancel();
939
940
16032
  for (HandleWrap* handle : handle_wrap_queue_)
941
9168
    handle->Close();
942
943
45606
  for (HandleCleanup& hc : handle_cleanup_queue_)
944
34158
    hc.cb_(this, hc.handle_, hc.arg_);
945
11448
  handle_cleanup_queue_.clear();
946
947
10754
  while (handle_cleanup_waiting_ != 0 ||
948

33652
         request_waiting_ != 0 ||
949
11450
         !handle_wrap_queue_.IsEmpty()) {
950
10754
    uv_run(event_loop(), UV_RUN_ONCE);
951
  }
952
11448
}
953
954
6270
void Environment::StartProfilerIdleNotifier() {
955
6270
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
956
214835
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
957
214835
    env->isolate()->SetIdle(true);
958
214835
  });
959
6270
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
960
214633
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
961
214633
    env->isolate()->SetIdle(false);
962
214633
  });
963
6270
}
964
965
731823
void Environment::PrintSyncTrace() const {
966
731823
  if (!trace_sync_io_) return;
967
968
2
  HandleScope handle_scope(isolate());
969
970
1
  fprintf(
971
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
972
1
  PrintStackTrace(isolate(),
973
                  StackTrace::CurrentStackTrace(
974
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
975
}
976
977
5372
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
978
5372
  EscapableHandleScope handle_scope(isolate());
979
10744
  if (!snapshot_serialize_callback().IsEmpty()) {
980
    Context::Scope context_scope(context());
981
    return handle_scope.EscapeMaybe(snapshot_serialize_callback()->Call(
982
        context(), v8::Undefined(isolate()), 0, nullptr));
983
  }
984
10744
  return handle_scope.Escape(Undefined(isolate()));
985
}
986
987
MaybeLocal<Value> Environment::RunSnapshotDeserializeMain() const {
988
  EscapableHandleScope handle_scope(isolate());
989
  if (!snapshot_deserialize_main().IsEmpty()) {
990
    Context::Scope context_scope(context());
991
    return handle_scope.EscapeMaybe(snapshot_deserialize_main()->Call(
992
        context(), v8::Undefined(isolate()), 0, nullptr));
993
  }
994
  return handle_scope.Escape(Undefined(isolate()));
995
}
996
997
5727
void Environment::RunCleanup() {
998
5727
  started_cleanup_ = true;
999

16426
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1000
5727
  bindings_.clear();
1001
  // Only BaseObject's cleanups are registered as per-realm cleanup hooks now.
1002
  // Defer the BaseObject cleanup after handles are cleaned up.
1003
5727
  CleanupHandles();
1004
1005

23598
  while (!cleanup_queue_.empty() || principal_realm_->HasCleanupHooks() ||
1006
11456
         native_immediates_.size() > 0 ||
1007

23596
         native_immediates_threadsafe_.size() > 0 ||
1008
5727
         native_immediates_interrupts_.size() > 0) {
1009
    // TODO(legendecas): cleanup handles in per-realm cleanup hooks as well.
1010
5721
    principal_realm_->RunCleanup();
1011
5721
    cleanup_queue_.Drain();
1012
5721
    CleanupHandles();
1013
  }
1014
1015
5730
  for (const int fd : unmanaged_fds_) {
1016
    uv_fs_t close_req;
1017
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
1018
3
    uv_fs_req_cleanup(&close_req);
1019
  }
1020
5727
}
1021
1022
6377
void Environment::RunAtExitCallbacks() {
1023

18280
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1024
18947
  for (ExitCallback at_exit : at_exit_functions_) {
1025
12570
    at_exit.cb_(at_exit.arg_);
1026
  }
1027
6377
  at_exit_functions_.clear();
1028
6377
}
1029
1030
12598
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1031
12598
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1032
12598
}
1033
1034
253648
void Environment::RunAndClearInterrupts() {
1035
253648
  while (native_immediates_interrupts_.size() > 0) {
1036
10735
    NativeImmediateQueue queue;
1037
    {
1038
21474
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1039
10737
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1040
    }
1041
10737
    DebugSealHandleScope seal_handle_scope(isolate());
1042
1043
21484
    while (auto head = queue.Shift())
1044
21496
      head->Call(this);
1045
  }
1046
242911
}
1047
1048
232460
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1049

470113
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1050
               "RunAndClearNativeImmediates");
1051
464912
  HandleScope handle_scope(isolate_);
1052
  // In case the Isolate is no longer accessible just use an empty Local. This
1053
  // is not an issue for InternalCallbackScope as this case is already handled
1054
  // in its constructor but we avoid calls into v8 which can crash the process
1055
  // in debug builds.
1056
  Local<Object> obj =
1057
232460
      can_call_into_js() ? Object::New(isolate_) : Local<Object>();
1058
464912
  InternalCallbackScope cb_scope(this, obj, {0, 0});
1059
1060
232460
  size_t ref_count = 0;
1061
1062
  // Handle interrupts first. These functions are not allowed to throw
1063
  // exceptions, so we do not need to handle that.
1064
232460
  RunAndClearInterrupts();
1065
1066
464916
  auto drain_list = [&](NativeImmediateQueue* queue) {
1067
929825
    TryCatchScope try_catch(this);
1068
464916
    DebugSealHandleScope seal_handle_scope(isolate());
1069
525146
    while (auto head = queue->Shift()) {
1070
60238
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1071
60238
      if (is_refed)
1072
35171
        ref_count++;
1073
1074

60238
      if (is_refed || !only_refed)
1075
59966
        head->Call(this);
1076
1077
60233
      head.reset();  // Destroy now so that this is also observed by try_catch.
1078
1079
60233
      if (UNLIKELY(try_catch.HasCaught())) {
1080

3
        if (!try_catch.HasTerminated() && can_call_into_js())
1081
3
          errors::TriggerUncaughtException(isolate(), try_catch);
1082
1083
1
        return true;
1084
      }
1085
60230
    }
1086
464908
    return false;
1087
232459
  };
1088
232459
  while (drain_list(&native_immediates_)) {}
1089
1090
232456
  immediate_info()->ref_count_dec(ref_count);
1091
1092
232456
  if (immediate_info()->ref_count() == 0)
1093
176421
    ToggleImmediateRef(false);
1094
1095
  // It is safe to check .size() first, because there is a causal relationship
1096
  // between pushes to the threadsafe immediate list and this function being
1097
  // called. For the common case, it's worth checking the size first before
1098
  // establishing a mutex lock.
1099
  // This is intentionally placed after the `ref_count` handling, because when
1100
  // refed threadsafe immediates are created, they are not counted towards the
1101
  // count in immediate_info() either.
1102
232452
  NativeImmediateQueue threadsafe_immediates;
1103
232456
  if (native_immediates_threadsafe_.size() > 0) {
1104
2182
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1105
1091
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1106
  }
1107
232457
  while (drain_list(&threadsafe_immediates)) {}
1108
232452
}
1109
1110
10754
void Environment::RequestInterruptFromV8() {
1111
  // The Isolate may outlive the Environment, so some logic to handle the
1112
  // situation in which the Environment is destroyed before the handler runs
1113
  // is required.
1114
1115
  // We allocate a new pointer to a pointer to this Environment instance, and
1116
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
1117
  // callbacks are already scheduled to run and we can delete our own pointer
1118
  // and just return. If it was nullptr previously, the Environment** is stored;
1119
  // ~Environment sets the Environment* contained in it to nullptr, so that
1120
  // the callback can check whether ~Environment has already run and it is thus
1121
  // not safe to access the Environment instance itself.
1122
10754
  Environment** interrupt_data = new Environment*(this);
1123
10754
  Environment** dummy = nullptr;
1124
10754
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1125
397
    delete interrupt_data;
1126
397
    return;  // Already scheduled.
1127
  }
1128
1129
10357
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1130
10347
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1131
10347
    Environment* env = *env_ptr;
1132
10347
    if (env == nullptr) {
1133
      // The Environment has already been destroyed. That should be okay; any
1134
      // callback added before the Environment shuts down would have been
1135
      // handled during cleanup.
1136
11
      return;
1137
    }
1138
10336
    env->interrupt_data_.store(nullptr);
1139
10336
    env->RunAndClearInterrupts();
1140
  }, interrupt_data);
1141
}
1142
1143
11144
void Environment::ScheduleTimer(int64_t duration_ms) {
1144
11144
  if (started_cleanup_) return;
1145
11144
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1146
}
1147
1148
3958
void Environment::ToggleTimerRef(bool ref) {
1149
3958
  if (started_cleanup_) return;
1150
1151
3958
  if (ref) {
1152
2651
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1153
  } else {
1154
1307
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1155
  }
1156
}
1157
1158
9120
void Environment::RunTimers(uv_timer_t* handle) {
1159
9120
  Environment* env = Environment::from_timer_handle(handle);
1160

9642
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1161
1162
9120
  if (!env->can_call_into_js())
1163
    return;
1164
1165
9120
  HandleScope handle_scope(env->isolate());
1166
9120
  Context::Scope context_scope(env->context());
1167
1168
9120
  Local<Object> process = env->process_object();
1169
9120
  InternalCallbackScope scope(env, process, {0, 0});
1170
1171
9120
  Local<Function> cb = env->timers_callback_function();
1172
  MaybeLocal<Value> ret;
1173
9120
  Local<Value> arg = env->GetNow();
1174
  // This code will loop until all currently due timers will process. It is
1175
  // impossible for us to end up in an infinite loop due to how the JS-side
1176
  // is structured.
1177
33
  do {
1178
9153
    TryCatchScope try_catch(env);
1179
9153
    try_catch.SetVerbose(true);
1180
9153
    ret = cb->Call(env->context(), process, 1, &arg);
1181

9143
  } while (ret.IsEmpty() && env->can_call_into_js());
1182
1183
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
1184
  // is reset back to `true` after being previously set to `false` then this
1185
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
1186
  // timers corruption will occur and all timers behaviour will become
1187
  // entirely unpredictable.
1188
9110
  if (ret.IsEmpty())
1189
6
    return;
1190
1191
  // To allow for less JS-C++ boundary crossing, the value returned from JS
1192
  // serves a few purposes:
1193
  // 1. If it's 0, no more timers exist and the handle should be unrefed
1194
  // 2. If it's > 0, the value represents the next timer's expiry and there
1195
  //    is at least one timer remaining that is refed.
1196
  // 3. If it's < 0, the absolute value represents the next timer's expiry
1197
  //    and there are no timers that are refed.
1198
  int64_t expiry_ms =
1199
9104
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1200
1201
9104
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1202
1203
9104
  if (expiry_ms != 0) {
1204
    int64_t duration_ms =
1205
7940
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1206
1207
7940
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1208
1209
7940
    if (expiry_ms > 0)
1210
7294
      uv_ref(h);
1211
    else
1212
646
      uv_unref(h);
1213
  } else {
1214
1164
    uv_unref(h);
1215
  }
1216
}
1217
1218
1219
214633
void Environment::CheckImmediate(uv_check_t* handle) {
1220
214633
  Environment* env = Environment::from_immediate_check_handle(handle);
1221

217760
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1222
1223
214633
  HandleScope scope(env->isolate());
1224
214633
  Context::Scope context_scope(env->context());
1225
1226
214633
  env->RunAndClearNativeImmediates();
1227
1228

214633
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1229
159178
    return;
1230
1231
951
  do {
1232
56394
    MakeCallback(env->isolate(),
1233
                 env->process_object(),
1234
                 env->immediate_callback_function(),
1235
                 0,
1236
                 nullptr,
1237
56406
                 {0, 0}).ToLocalChecked();
1238

56394
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
1239
1240
55443
  if (env->immediate_info()->ref_count() == 0)
1241
4707
    env->ToggleImmediateRef(false);
1242
}
1243
1244
260024
void Environment::ToggleImmediateRef(bool ref) {
1245
260024
  if (started_cleanup_) return;
1246
1247
248657
  if (ref) {
1248
    // Idle handle is needed only to stop the event loop from blocking in poll.
1249
78872
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
1250
  } else {
1251
169785
    uv_idle_stop(immediate_idle_handle());
1252
  }
1253
}
1254
1255
1256
50127
Local<Value> Environment::GetNow() {
1257
50127
  uv_update_time(event_loop());
1258
50127
  uint64_t now = uv_now(event_loop());
1259
50127
  CHECK_GE(now, timer_base());
1260
50127
  now -= timer_base();
1261
50127
  if (now <= 0xffffffff)
1262
100254
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
1263
  else
1264
    return Number::New(isolate(), static_cast<double>(now));
1265
}
1266
1267
28
void CollectExceptionInfo(Environment* env,
1268
                          Local<Object> obj,
1269
                          int errorno,
1270
                          const char* err_string,
1271
                          const char* syscall,
1272
                          const char* message,
1273
                          const char* path,
1274
                          const char* dest) {
1275
28
  obj->Set(env->context(),
1276
           env->errno_string(),
1277
112
           Integer::New(env->isolate(), errorno)).Check();
1278
1279
28
  obj->Set(env->context(), env->code_string(),
1280
84
           OneByteString(env->isolate(), err_string)).Check();
1281
1282
28
  if (message != nullptr) {
1283
28
    obj->Set(env->context(), env->message_string(),
1284
112
             OneByteString(env->isolate(), message)).Check();
1285
  }
1286
1287
  Local<Value> path_buffer;
1288
28
  if (path != nullptr) {
1289
    path_buffer =
1290
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
1291
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
1292
  }
1293
1294
  Local<Value> dest_buffer;
1295
28
  if (dest != nullptr) {
1296
    dest_buffer =
1297
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
1298
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
1299
  }
1300
1301
28
  if (syscall != nullptr) {
1302
28
    obj->Set(env->context(), env->syscall_string(),
1303
112
             OneByteString(env->isolate(), syscall)).Check();
1304
  }
1305
28
}
1306
1307
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
1308
                                         int errorno,
1309
                                         const char* syscall,
1310
                                         const char* message,
1311
                                         const char* path,
1312
                                         const char* dest) {
1313

28
  if (!object->IsObject() || errorno == 0)
1314
    return;
1315
1316
28
  Local<Object> obj = object.As<Object>();
1317
28
  const char* err_string = uv_err_name(errorno);
1318
1319

28
  if (message == nullptr || message[0] == '\0') {
1320
28
    message = uv_strerror(errorno);
1321
  }
1322
1323
28
  node::CollectExceptionInfo(this, obj, errorno, err_string,
1324
                             syscall, message, path, dest);
1325
}
1326
1327
6304
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1328
6304
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
1329
1330
6
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
1331
    Local<Context> context, SnapshotCreator* creator) {
1332
6
  return {fields_.Serialize(context, creator)};
1333
}
1334
1335
5523
void ImmediateInfo::Deserialize(Local<Context> context) {
1336
5523
  fields_.Deserialize(context);
1337
5523
}
1338
1339
6
std::ostream& operator<<(std::ostream& output,
1340
                         const ImmediateInfo::SerializeInfo& i) {
1341
6
  output << "{ " << i.fields << " }";
1342
6
  return output;
1343
}
1344
1345
25
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1346
25
  tracker->TrackField("fields", fields_);
1347
25
}
1348
1349
6
TickInfo::SerializeInfo TickInfo::Serialize(Local<Context> context,
1350
                                            SnapshotCreator* creator) {
1351
6
  return {fields_.Serialize(context, creator)};
1352
}
1353
1354
5523
void TickInfo::Deserialize(Local<Context> context) {
1355
5523
  fields_.Deserialize(context);
1356
5523
}
1357
1358
6
std::ostream& operator<<(std::ostream& output,
1359
                         const TickInfo::SerializeInfo& i) {
1360
6
  output << "{ " << i.fields << " }";
1361
6
  return output;
1362
}
1363
1364
25
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1365
25
  tracker->TrackField("fields", fields_);
1366
25
}
1367
1368
6304
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1369
    : fields_(
1370
6304
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1371
1372
6304
AsyncHooks::AsyncHooks(Isolate* isolate, const SerializeInfo* info)
1373
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1374
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1375
      async_id_fields_(
1376
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1377

6304
      info_(info) {
1378
12608
  HandleScope handle_scope(isolate);
1379
6304
  if (info == nullptr) {
1380
781
    clear_async_id_stack();
1381
1382
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1383
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1384
    // See discussion in https://github.com/nodejs/node/pull/15454
1385
    // When removing this, do it by reverting the commit. Otherwise the test
1386
    // and flag changes won't be included.
1387
781
    fields_[kCheck] = 1;
1388
1389
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1390
    // specified default value and it should fallback to the executionAsyncId.
1391
    // 0 is not used as the magic value, because that indicates a missing
1392
    // context which is different from a default context.
1393
781
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1394
1395
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1396
    // context during bootstrap (code that runs before entering uv_run()).
1397
781
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1398
  }
1399
6304
}
1400
1401
5523
void AsyncHooks::Deserialize(Local<Context> context) {
1402
5523
  async_ids_stack_.Deserialize(context);
1403
5523
  fields_.Deserialize(context);
1404
5523
  async_id_fields_.Deserialize(context);
1405
1406
  Local<Array> js_execution_async_resources;
1407
5523
  if (info_->js_execution_async_resources != 0) {
1408
    js_execution_async_resources =
1409
5523
        context->GetDataFromSnapshotOnce<Array>(
1410
16569
            info_->js_execution_async_resources).ToLocalChecked();
1411
  } else {
1412
    js_execution_async_resources = Array::New(context->GetIsolate());
1413
  }
1414
5523
  js_execution_async_resources_.Reset(
1415
      context->GetIsolate(), js_execution_async_resources);
1416
1417
  // The native_execution_async_resources_ field requires v8::Local<> instances
1418
  // for async calls whose resources were on the stack as JS objects when they
1419
  // were entered. We cannot recreate this here; however, storing these values
1420
  // on the JS equivalent gives the same result, so we do that instead.
1421
5523
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1422
    if (info_->native_execution_async_resources[i] == SIZE_MAX)
1423
      continue;
1424
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1425
                                   info_->native_execution_async_resources[i])
1426
                               .ToLocalChecked();
1427
    js_execution_async_resources->Set(context, i, obj).Check();
1428
  }
1429
5523
  info_ = nullptr;
1430
5523
}
1431
1432
6
std::ostream& operator<<(std::ostream& output,
1433
                         const AsyncHooks::SerializeInfo& i) {
1434
  output << "{\n"
1435
6
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1436
6
         << "  " << i.fields << ",  // fields\n"
1437
6
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1438
6
         << "  " << i.js_execution_async_resources
1439
         << ",  // js_execution_async_resources\n"
1440
6
         << "  " << i.native_execution_async_resources
1441
         << ",  // native_execution_async_resources\n"
1442
6
         << "}";
1443
6
  return output;
1444
}
1445
1446
6
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1447
                                                SnapshotCreator* creator) {
1448
6
  SerializeInfo info;
1449
  // TODO(joyeecheung): some of these probably don't need to be serialized.
1450
6
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1451
6
  info.fields = fields_.Serialize(context, creator);
1452
6
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1453
6
  if (!js_execution_async_resources_.IsEmpty()) {
1454
6
    info.js_execution_async_resources = creator->AddData(
1455
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1456
6
    CHECK_NE(info.js_execution_async_resources, 0);
1457
  } else {
1458
    info.js_execution_async_resources = 0;
1459
  }
1460
1461
6
  info.native_execution_async_resources.resize(
1462
      native_execution_async_resources_.size());
1463
6
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1464
    info.native_execution_async_resources[i] =
1465
        native_execution_async_resources_[i].IsEmpty() ? SIZE_MAX :
1466
            creator->AddData(
1467
                context,
1468
                native_execution_async_resources_[i]);
1469
  }
1470
6
  CHECK_EQ(contexts_.size(), 1);
1471

12
  CHECK_EQ(contexts_[0], env()->context());
1472
6
  CHECK(js_promise_hooks_[0].IsEmpty());
1473
6
  CHECK(js_promise_hooks_[1].IsEmpty());
1474
6
  CHECK(js_promise_hooks_[2].IsEmpty());
1475
6
  CHECK(js_promise_hooks_[3].IsEmpty());
1476
1477
6
  return info;
1478
}
1479
1480
25
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1481
25
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1482
25
  tracker->TrackField("fields", fields_);
1483
25
  tracker->TrackField("async_id_fields", async_id_fields_);
1484
25
  tracker->TrackField("js_promise_hooks", js_promise_hooks_);
1485
25
}
1486
1487
4
void AsyncHooks::grow_async_ids_stack() {
1488
4
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1489
1490
4
  env()->async_hooks_binding()->Set(
1491
      env()->context(),
1492
      env()->async_ids_stack_string(),
1493
12
      async_ids_stack_.GetJSArray()).Check();
1494
4
}
1495
1496
4
void AsyncHooks::FailWithCorruptedAsyncStack(double expected_async_id) {
1497
4
  fprintf(stderr,
1498
          "Error: async hook stack has become corrupted ("
1499
          "actual: %.f, expected: %.f)\n",
1500
          async_id_fields_.GetValue(kExecutionAsyncId),
1501
          expected_async_id);
1502
4
  DumpBacktrace(stderr);
1503
4
  fflush(stderr);
1504
4
  if (!env()->abort_on_uncaught_exception())
1505
4
    exit(1);
1506
  fprintf(stderr, "\n");
1507
  fflush(stderr);
1508
  ABORT_NO_BACKTRACE();
1509
}
1510
1511
633
void Environment::Exit(int exit_code) {
1512
633
  if (options()->trace_exit) {
1513
4
    HandleScope handle_scope(isolate());
1514
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1515
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1516
1517
2
    if (is_main_thread()) {
1518
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1519
    } else {
1520
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1521
              uv_os_getpid(), thread_id());
1522
    }
1523
1524
2
    fprintf(
1525
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1526
2
    PrintStackTrace(isolate(),
1527
                    StackTrace::CurrentStackTrace(
1528
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1529
  }
1530
633
  process_exit_handler_(this, exit_code);
1531
63
}
1532
1533
6324
void Environment::stop_sub_worker_contexts() {
1534
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1535
1536
6324
  while (!sub_worker_contexts_.empty()) {
1537
27
    Worker* w = *sub_worker_contexts_.begin();
1538
27
    remove_sub_worker_context(w);
1539
27
    w->Exit(1);
1540
27
    w->JoinThread();
1541
  }
1542
6297
}
1543
1544
10
Environment* Environment::worker_parent_env() const {
1545
10
  if (worker_context() == nullptr) return nullptr;
1546
  return worker_context()->env();
1547
}
1548
1549
65536
void Environment::AddUnmanagedFd(int fd) {
1550
65536
  if (!tracks_unmanaged_fds()) return;
1551
2725
  auto result = unmanaged_fds_.insert(fd);
1552
2725
  if (!result.second) {
1553
    ProcessEmitWarning(
1554
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1555
  }
1556
}
1557
1558
65147
void Environment::RemoveUnmanagedFd(int fd) {
1559
65147
  if (!tracks_unmanaged_fds()) return;
1560
2722
  size_t removed_count = unmanaged_fds_.erase(fd);
1561
2722
  if (removed_count == 0) {
1562
    ProcessEmitWarning(
1563
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1564
  }
1565
}
1566
1567
5344
void Environment::PrintInfoForSnapshotIfDebug() {
1568
10688
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1569
    fprintf(stderr, "At the exit of the Environment:\n");
1570
    principal_realm()->PrintInfoForSnapshot();
1571
    fprintf(stderr, "\nNative modules without cache:\n");
1572
    for (const auto& s : builtins_without_cache) {
1573
      fprintf(stderr, "%s\n", s.c_str());
1574
    }
1575
    fprintf(stderr, "\nNative modules with cache:\n");
1576
    for (const auto& s : builtins_with_cache) {
1577
      fprintf(stderr, "%s\n", s.c_str());
1578
    }
1579
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1580
    for (const auto mod : internal_bindings) {
1581
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1582
    }
1583
  }
1584
5344
}
1585
1586
6
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1587
6
  EnvSerializeInfo info;
1588
6
  Local<Context> ctx = context();
1589
1590
  // Currently all modules are compiled without cache in builtin snapshot
1591
  // builder.
1592
12
  info.builtins = std::vector<std::string>(builtins_without_cache.begin(),
1593
6
                                           builtins_without_cache.end());
1594
1595
6
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1596
6
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1597
6
  info.tick_info = tick_info_.Serialize(ctx, creator);
1598
6
  info.performance_state = performance_state_->Serialize(ctx, creator);
1599
6
  info.exiting = exiting_.Serialize(ctx, creator);
1600
6
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1601
6
  info.should_abort_on_uncaught_toggle =
1602
6
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1603
1604
6
  info.principal_realm = principal_realm_->Serialize(creator);
1605
6
  return info;
1606
}
1607
1608
22092
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1609
                                            Local<Object> holder,
1610
                                            int index,
1611
                                            InternalFieldInfoBase* info) {
1612
  DCHECK_EQ(index, BaseObject::kEmbedderType);
1613
44184
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1614
22092
  deserialize_requests_.push_back(std::move(request));
1615
22092
}
1616
1617
5523
void Environment::RunDeserializeRequests() {
1618
11046
  HandleScope scope(isolate());
1619
5523
  Local<Context> ctx = context();
1620
5523
  Isolate* is = isolate();
1621
27615
  while (!deserialize_requests_.empty()) {
1622
44184
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1623
22092
    deserialize_requests_.pop_front();
1624
22092
    Local<Object> holder = request.holder.Get(is);
1625
22092
    request.cb(ctx, holder, request.index, request.info);
1626
    request.holder.Reset();
1627
22092
    request.info->Delete();
1628
  }
1629
5523
}
1630
1631
5523
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1632
5523
  Local<Context> ctx = context();
1633
1634
5523
  RunDeserializeRequests();
1635
1636
5523
  builtins_in_snapshot = info->builtins;
1637
5523
  async_hooks_.Deserialize(ctx);
1638
5523
  immediate_info_.Deserialize(ctx);
1639
5523
  tick_info_.Deserialize(ctx);
1640
5523
  performance_state_->Deserialize(ctx);
1641
5523
  exiting_.Deserialize(ctx);
1642
5523
  stream_base_state_.Deserialize(ctx);
1643
5523
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1644
1645
5523
  principal_realm_->DeserializeProperties(&info->principal_realm);
1646
1647
5523
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1648
    fprintf(stderr, "deserializing...\n");
1649
    std::cerr << *info << "\n";
1650
  }
1651
5523
}
1652
1653
4
uint64_t GuessMemoryAvailableToTheProcess() {
1654
4
  uint64_t free_in_system = uv_get_free_memory();
1655
4
  size_t allowed = uv_get_constrained_memory();
1656
4
  if (allowed == 0) {
1657
    return free_in_system;
1658
  }
1659
  size_t rss;
1660
4
  int err = uv_resident_set_memory(&rss);
1661
4
  if (err) {
1662
    return free_in_system;
1663
  }
1664
4
  if (allowed < rss) {
1665
    // Something is probably wrong. Fallback to the free memory.
1666
    return free_in_system;
1667
  }
1668
  // There may still be room for swap, but we will just leave it here.
1669
4
  return allowed - rss;
1670
}
1671
1672
25
void Environment::BuildEmbedderGraph(Isolate* isolate,
1673
                                     EmbedderGraph* graph,
1674
                                     void* data) {
1675
50
  MemoryTracker tracker(isolate, graph);
1676
25
  Environment* env = static_cast<Environment*>(data);
1677
  // Start traversing embedder objects from the root Environment object.
1678
25
  tracker.Track(env);
1679
25
}
1680
1681
4
size_t Environment::NearHeapLimitCallback(void* data,
1682
                                          size_t current_heap_limit,
1683
                                          size_t initial_heap_limit) {
1684
4
  Environment* env = static_cast<Environment*>(data);
1685
1686
  Debug(env,
1687
        DebugCategory::DIAGNOSTICS,
1688
        "Invoked NearHeapLimitCallback, processing=%d, "
1689
        "current_limit=%" PRIu64 ", "
1690
        "initial_limit=%" PRIu64 "\n",
1691
4
        env->is_in_heapsnapshot_heap_limit_callback_,
1692
8
        static_cast<uint64_t>(current_heap_limit),
1693
4
        static_cast<uint64_t>(initial_heap_limit));
1694
1695
4
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1696
4
  size_t young_gen_size = 0;
1697
4
  size_t old_gen_size = 0;
1698
1699
4
  HeapSpaceStatistics stats;
1700
4
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1701
36
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1702
32
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1703

60
    if (strcmp(stats.space_name(), "new_space") == 0 ||
1704
28
        strcmp(stats.space_name(), "new_large_object_space") == 0) {
1705
8
      young_gen_size += stats.space_used_size();
1706
    } else {
1707
24
      old_gen_size += stats.space_used_size();
1708
    }
1709
  }
1710
1711
  Debug(env,
1712
        DebugCategory::DIAGNOSTICS,
1713
        "max_young_gen_size=%" PRIu64 ", "
1714
        "young_gen_size=%" PRIu64 ", "
1715
        "old_gen_size=%" PRIu64 ", "
1716
        "total_size=%" PRIu64 "\n",
1717
8
        static_cast<uint64_t>(max_young_gen_size),
1718
8
        static_cast<uint64_t>(young_gen_size),
1719
8
        static_cast<uint64_t>(old_gen_size),
1720
4
        static_cast<uint64_t>(young_gen_size + old_gen_size));
1721
1722
4
  uint64_t available = GuessMemoryAvailableToTheProcess();
1723
  // TODO(joyeecheung): get a better estimate about the native memory
1724
  // usage into the overhead, e.g. based on the count of objects.
1725
4
  uint64_t estimated_overhead = max_young_gen_size;
1726
  Debug(env,
1727
        DebugCategory::DIAGNOSTICS,
1728
        "Estimated available memory=%" PRIu64 ", "
1729
        "estimated overhead=%" PRIu64 "\n",
1730
8
        static_cast<uint64_t>(available),
1731
4
        static_cast<uint64_t>(estimated_overhead));
1732
1733
  // This might be hit when the snapshot is being taken in another
1734
  // NearHeapLimitCallback invocation.
1735
  // When taking the snapshot, objects in the young generation may be
1736
  // promoted to the old generation, result in increased heap usage,
1737
  // but it should be no more than the young generation size.
1738
  // Ideally, this should be as small as possible - the heap limit
1739
  // can only be restored when the heap usage falls down below the
1740
  // new limit, so in a heap with unbounded growth the isolate
1741
  // may eventually crash with this new limit - effectively raising
1742
  // the heap limit to the new one.
1743
4
  size_t new_limit = current_heap_limit + max_young_gen_size;
1744
4
  if (env->is_in_heapsnapshot_heap_limit_callback_) {
1745
    Debug(env,
1746
          DebugCategory::DIAGNOSTICS,
1747
          "Not generating snapshots in nested callback. "
1748
          "new_limit=%" PRIu64 "\n",
1749
2
          static_cast<uint64_t>(new_limit));
1750
2
    return new_limit;
1751
  }
1752
1753
  // Estimate whether the snapshot is going to use up all the memory
1754
  // available to the process. If so, just give up to prevent the system
1755
  // from killing the process for a system OOM.
1756
2
  if (estimated_overhead > available) {
1757
    Debug(env,
1758
          DebugCategory::DIAGNOSTICS,
1759
          "Not generating snapshots because it's too risky.\n");
1760
    env->RemoveHeapSnapshotNearHeapLimitCallback(0);
1761
    // The new limit must be higher than current_heap_limit or V8 might
1762
    // crash.
1763
    return new_limit;
1764
  }
1765
1766
  // Take the snapshot synchronously.
1767
2
  env->is_in_heapsnapshot_heap_limit_callback_ = true;
1768
1769
4
  std::string dir = env->options()->diagnostic_dir;
1770
2
  if (dir.empty()) {
1771
2
    dir = env->GetCwd();
1772
  }
1773
4
  DiagnosticFilename name(env, "Heap", "heapsnapshot");
1774
2
  std::string filename = dir + kPathSeparator + (*name);
1775
1776
2
  Debug(env, DebugCategory::DIAGNOSTICS, "Start generating %s...\n", *name);
1777
1778
2
  heap::WriteSnapshot(env, filename.c_str());
1779
2
  env->heap_limit_snapshot_taken_ += 1;
1780
1781
  Debug(env,
1782
        DebugCategory::DIAGNOSTICS,
1783
        "%" PRIu32 "/%" PRIu32 " snapshots taken.\n",
1784
2
        env->heap_limit_snapshot_taken_,
1785
2
        env->heap_snapshot_near_heap_limit_);
1786
1787
  // Don't take more snapshots than the limit specified.
1788
2
  if (env->heap_limit_snapshot_taken_ == env->heap_snapshot_near_heap_limit_) {
1789
    Debug(env,
1790
          DebugCategory::DIAGNOSTICS,
1791
          "Removing the near heap limit callback");
1792
2
    env->RemoveHeapSnapshotNearHeapLimitCallback(0);
1793
  }
1794
1795
2
  FPrintF(stderr, "Wrote snapshot to %s\n", filename.c_str());
1796
  // Tell V8 to reset the heap limit once the heap usage falls down to
1797
  // 95% of the initial limit.
1798
2
  env->isolate()->AutomaticallyRestoreInitialHeapLimit(0.95);
1799
1800
2
  env->is_in_heapsnapshot_heap_limit_callback_ = false;
1801
1802
  // The new limit must be higher than current_heap_limit or V8 might
1803
  // crash.
1804
2
  return new_limit;
1805
}
1806
1807
25
inline size_t Environment::SelfSize() const {
1808
25
  size_t size = sizeof(*this);
1809
  // Remove non pointer fields that will be tracked in MemoryInfo()
1810
  // TODO(joyeecheung): refactor the MemoryTracker interface so
1811
  // this can be done for common types within the Track* calls automatically
1812
  // if a certain scope is entered.
1813
25
  size -= sizeof(async_hooks_);
1814
25
  size -= sizeof(cleanup_queue_);
1815
25
  size -= sizeof(tick_info_);
1816
25
  size -= sizeof(immediate_info_);
1817
25
  return size;
1818
}
1819
1820
25
void Environment::MemoryInfo(MemoryTracker* tracker) const {
1821
  // Iteratable STLs have their own sizes subtracted from the parent
1822
  // by default.
1823
25
  tracker->TrackField("isolate_data", isolate_data_);
1824
25
  tracker->TrackField("builtins_with_cache", builtins_with_cache);
1825
25
  tracker->TrackField("builtins_without_cache", builtins_without_cache);
1826
25
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
1827
25
  tracker->TrackField("exec_argv", exec_argv_);
1828
25
  tracker->TrackField("exiting", exiting_);
1829
25
  tracker->TrackField("should_abort_on_uncaught_toggle",
1830
25
                      should_abort_on_uncaught_toggle_);
1831
25
  tracker->TrackField("stream_base_state", stream_base_state_);
1832
25
  tracker->TrackField("cleanup_queue", cleanup_queue_);
1833
25
  tracker->TrackField("async_hooks", async_hooks_);
1834
25
  tracker->TrackField("immediate_info", immediate_info_);
1835
25
  tracker->TrackField("tick_info", tick_info_);
1836
25
  tracker->TrackField("principal_realm", principal_realm_);
1837
1838
  // FIXME(joyeecheung): track other fields in Environment.
1839
  // Currently MemoryTracker is unable to track these
1840
  // correctly:
1841
  // - Internal types that do not implement MemoryRetainer yet
1842
  // - STL containers with MemoryRetainer* inside
1843
  // - STL containers with numeric types inside that should not have their
1844
  //   nodes elided e.g. numeric keys in maps.
1845
  // We also need to make sure that when we add a non-pointer field as its own
1846
  // node, we shift its sizeof() size out of the Environment node.
1847
25
}
1848
1849
769910
void Environment::RunWeakRefCleanup() {
1850
769910
  isolate()->ClearKeptObjects();
1851
769910
}
1852
}  // namespace node