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: 657 691 95.1 %
Date: 2020-09-06 22:14:11 Branches: 860 1643 52.3 %

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




140864
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
105






211296
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
106




















































































































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

119
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
234
    // Ideally, we’d have a consistent story that treats all threads/Environment
235
    // instances equally here. However, tracing is essentially global, and this
236
    // callback is called from whichever thread calls `StartTracing()` or
237
    // `StopTracing()`. The only way to do this in a threadsafe fashion
238
    // seems to be only tracking this from the main thread, and only allowing
239
    // these state modifications from the main thread.
240
68
    return;
241
  }
242
243
111
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
244
111
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
245
246
111
  Isolate* isolate = env_->isolate();
247
170
  HandleScope handle_scope(isolate);
248
111
  Local<Function> cb = env_->trace_category_state_function();
249
111
  if (cb.IsEmpty())
250
52
    return;
251
118
  TryCatchScope try_catch(env_);
252
59
  try_catch.SetVerbose(true);
253
118
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
254
177
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
255
}
256
257
454
void Environment::CreateProperties() {
258
908
  HandleScope handle_scope(isolate_);
259
454
  Local<Context> ctx = context();
260
261
  {
262
    Context::Scope context_scope(ctx);
263
454
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
264
1362
    templ->InstanceTemplate()->SetInternalFieldCount(
265
454
        BaseObject::kInternalFieldCount);
266
908
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
267
268
454
    set_binding_data_ctor_template(templ);
269
  }
270
271
  // Store primordials setup by the per-context script in the environment.
272
  Local<Object> per_context_bindings =
273
908
      GetPerContextExports(ctx).ToLocalChecked();
274
  Local<Value> primordials =
275
1362
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
276
454
  CHECK(primordials->IsObject());
277
454
  set_primordials(primordials.As<Object>());
278
279
  Local<Object> process_object =
280
908
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
281
454
  set_process_object(process_object);
282
454
}
283
284
4855
std::string GetExecPath(const std::vector<std::string>& argv) {
285
  char exec_path_buf[2 * PATH_MAX];
286
4855
  size_t exec_path_len = sizeof(exec_path_buf);
287
4855
  std::string exec_path;
288
4855
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
289
4855
    exec_path = std::string(exec_path_buf, exec_path_len);
290
  } else {
291
    exec_path = argv[0];
292
  }
293
294
  // On OpenBSD process.execPath will be relative unless we
295
  // get the full path before process.execPath is used.
296
#if defined(__OpenBSD__)
297
  uv_fs_t req;
298
  req.ptr = nullptr;
299
  if (0 ==
300
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
301
    CHECK_NOT_NULL(req.ptr);
302
    exec_path = std::string(static_cast<char*>(req.ptr));
303
  }
304
  uv_fs_req_cleanup(&req);
305
#endif
306
307
4855
  return exec_path;
308
}
309
310
4855
Environment::Environment(IsolateData* isolate_data,
311
                         Isolate* isolate,
312
                         const std::vector<std::string>& args,
313
                         const std::vector<std::string>& exec_args,
314
                         const EnvSerializeInfo* env_info,
315
                         EnvironmentFlags::Flags flags,
316
4855
                         ThreadId thread_id)
317
    : isolate_(isolate),
318
      isolate_data_(isolate_data),
319
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
320
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
321
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
322
4855
      timer_base_(uv_now(isolate_data->event_loop())),
323
      exec_argv_(exec_args),
324
      argv_(args),
325
      exec_path_(GetExecPath(args)),
326
      should_abort_on_uncaught_toggle_(
327
4855
          isolate_,
328
          1,
329
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
330
4855
      stream_base_state_(isolate_,
331
                         StreamBase::kNumStreamBaseStateFields,
332
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
333
4855
      environment_start_time_(PERFORMANCE_NOW()),
334
      flags_(flags),
335
4855
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
336
4855
                     ? AllocateEnvironmentThreadId().id
337


436950
                     : thread_id.id) {
338
  // We'll be creating new objects so make sure we've entered the context.
339
9710
  HandleScope handle_scope(isolate);
340
341
  // Set some flags if only kDefaultFlags was passed. This can make API version
342
  // transitions easier for embedders.
343
4855
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
344
8886
    flags_ = flags_ |
345
4443
        EnvironmentFlags::kOwnsProcessState |
346
        EnvironmentFlags::kOwnsInspector;
347
  }
348
349
4855
  set_env_vars(per_process::system_environment);
350
  // TODO(joyeecheung): pass Isolate* and env_vars to it instead of the entire
351
  // env
352
4855
  enabled_debug_list_.Parse(this);
353
354
  // We create new copies of the per-Environment option sets, so that it is
355
  // easier to modify them after Environment creation. The defaults are
356
  // part of the per-Isolate option set, for which in turn the defaults are
357
  // part of the per-process option set.
358
4855
  options_.reset(new EnvironmentOptions(*isolate_data->options()->per_env));
359
9710
  inspector_host_port_.reset(
360
14565
      new ExclusiveAccess<HostPort>(options_->debug_options().host_port));
361
362
4855
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
363
412
    set_abort_on_uncaught_exception(false);
364
  }
365
366
#if HAVE_INSPECTOR
367
  // We can only create the inspector agent after having cloned the options.
368
4855
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
369
#endif
370
371
  static uv_once_t init_once = UV_ONCE_INIT;
372
4855
  uv_once(&init_once, InitThreadLocalOnce);
373
4855
  uv_key_set(&thread_local_env, this);
374
375
4855
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
376
4855
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
377
4855
    if (TracingController* tracing_controller = writer->GetTracingController())
378
4813
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
379
  }
380
381
4855
  destroy_async_id_list_.reserve(512);
382
383
9710
  performance_state_ = std::make_unique<performance::PerformanceState>(
384
14565
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
385
386
4855
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
387
          TRACING_CATEGORY_NODE1(environment)) != 0) {
388
16
    auto traced_value = tracing::TracedValue::Create();
389
8
    traced_value->BeginArray("args");
390
8
    for (const std::string& arg : args) traced_value->AppendString(arg);
391
8
    traced_value->EndArray();
392
8
    traced_value->BeginArray("exec_args");
393
8
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
394
8
    traced_value->EndArray();
395

16
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
396
                                      "Environment",
397
                                      this,
398
                                      "args",
399
                                      std::move(traced_value));
400
  }
401
402
  // This adjusts the return value of base_object_count() so that tests that
403
  // check the count do not have to account for internally created BaseObjects.
404
4855
  initial_base_object_count_ = base_object_count();
405
4855
}
406
407
453
Environment::Environment(IsolateData* isolate_data,
408
                         Local<Context> context,
409
                         const std::vector<std::string>& args,
410
                         const std::vector<std::string>& exec_args,
411
                         const EnvSerializeInfo* env_info,
412
                         EnvironmentFlags::Flags flags,
413
453
                         ThreadId thread_id)
414
    : Environment(isolate_data,
415
                  context->GetIsolate(),
416
                  args,
417
                  exec_args,
418
                  env_info,
419
                  flags,
420
453
                  thread_id) {
421
453
  InitializeMainContext(context, env_info);
422
453
}
423
424
4856
void Environment::InitializeMainContext(Local<Context> context,
425
                                        const EnvSerializeInfo* env_info) {
426
4856
  context_.Reset(context->GetIsolate(), context);
427
4856
  AssignToContext(context, ContextInfo(""));
428
4856
  if (env_info != nullptr) {
429
4402
    DeserializeProperties(env_info);
430
  } else {
431
454
    CreateProperties();
432
  }
433
434
4856
  if (options_->no_force_async_hooks_checks) {
435
1
    async_hooks_.no_force_checks();
436
  }
437
438
  // By default, always abort when --abort-on-uncaught-exception was passed.
439
4856
  should_abort_on_uncaught_toggle_[0] = 1;
440
441
4856
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
442
4856
                           environment_start_time_);
443
4856
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
444
9712
                           per_process::node_start_time);
445
4856
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
446
9712
                           performance::performance_v8_start);
447
448
  // This adjusts the return value of base_object_count() so that tests that
449
  // check the count do not have to account for internally created BaseObjects.
450
4856
  initial_base_object_count_ = base_object_count();
451
4856
}
452
453
381316
Environment::~Environment() {
454
4388
  if (Environment** interrupt_data = interrupt_data_.load()) {
455
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
456
    // then force V8 to run interrupts by compiling and running an empty script
457
    // so as not to leak memory.
458
11
    *interrupt_data = nullptr;
459
460
22
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
461
22
    HandleScope handle_scope(isolate());
462
22
    TryCatch try_catch(isolate());
463
11
    Context::Scope context_scope(context());
464
465
#ifdef DEBUG
466
    bool consistency_check = false;
467
    isolate()->RequestInterrupt([](Isolate*, void* data) {
468
      *static_cast<bool*>(data) = true;
469
    }, &consistency_check);
470
#endif
471
472
    Local<Script> script;
473
33
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
474
22
      USE(script->Run(context()));
475
476
    DCHECK(consistency_check);
477
  }
478
479
  // FreeEnvironment() should have set this.
480
4388
  CHECK(is_stopping());
481
482
4388
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
483
4388
      BuildEmbedderGraph, this);
484
485
8776
  HandleScope handle_scope(isolate());
486
487
#if HAVE_INSPECTOR
488
  // Destroy inspector agent before erasing the context. The inspector
489
  // destructor depends on the context still being accessible.
490
4388
  inspector_agent_.reset();
491
#endif
492
493
13164
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
494
4388
                                             nullptr);
495
496
4388
  if (trace_state_observer_) {
497
4388
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
498
4387
    CHECK_NOT_NULL(writer);
499
4387
    if (TracingController* tracing_controller = writer->GetTracingController())
500
4347
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
501
  }
502
503

8776
  TRACE_EVENT_NESTABLE_ASYNC_END0(
504
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
505
506
  // Do not unload addons on the main thread. Some addons need to retain memory
507
  // beyond the Environment's lifetime, and unloading them early would break
508
  // them; with Worker threads, we have the opportunity to be stricter.
509
  // Also, since the main thread usually stops just before the process exits,
510
  // this is far less relevant here.
511
4388
  if (!is_main_thread()) {
512
    // Dereference all addons that were loaded into this environment.
513
423
    for (binding::DLib& addon : loaded_addons_) {
514
14
      addon.Close();
515
    }
516
  }
517
518
4388
  CHECK_EQ(base_object_count_, 0);
519
8775
}
520
521
4827
void Environment::InitializeLibuv() {
522
9654
  HandleScope handle_scope(isolate());
523
4827
  Context::Scope context_scope(context());
524
525
4827
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
526
4827
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
527
528
4827
  uv_check_init(event_loop(), immediate_check_handle());
529
4827
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
530
531
4827
  uv_idle_init(event_loop(), immediate_idle_handle());
532
533
4827
  uv_check_start(immediate_check_handle(), CheckImmediate);
534
535
9654
  uv_async_init(
536
      event_loop(),
537
      &task_queues_async_,
538
12525
      [](uv_async_t* async) {
539
7698
        Environment* env = ContainerOf(
540
3849
            &Environment::task_queues_async_, async);
541
3849
        env->RunAndClearNativeImmediates();
542
17349
      });
543
4827
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
544
545
  {
546
9654
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
547
4827
    task_queues_async_initialized_ = true;
548

9654
    if (native_immediates_threadsafe_.size() > 0 ||
549
4827
        native_immediates_interrupts_.size() > 0) {
550
4396
      uv_async_send(&task_queues_async_);
551
    }
552
  }
553
554
  // Register clean-up cb to be called to clean up the handles
555
  // when the environment is freed, note that they are not cleaned in
556
  // the one environment per process setup, but will be called in
557
  // FreeEnvironment.
558
4827
  RegisterHandleCleanups();
559
4827
}
560
561
96
void Environment::ExitEnv() {
562
96
  set_can_call_into_js(false);
563
96
  set_stopping(true);
564
96
  isolate_->TerminateExecution();
565
192
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
566
96
}
567
568
4827
void Environment::RegisterHandleCleanups() {
569
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
570
39694
                                        void* arg) {
571
17433
    handle->data = env;
572
573
34868
    env->CloseHandle(handle, [](uv_handle_t* handle) {
574
#ifdef DEBUG
575
      memset(handle, 0xab, uv_handle_size(handle->type));
576
#endif
577
34867
    });
578
44522
  };
579
580
19308
  auto register_handle = [&](uv_handle_t* handle) {
581
19308
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
582
24135
  };
583
4827
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
584
4827
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
585
4827
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
586
4827
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
587
4827
}
588
589
8771
void Environment::CleanupHandles() {
590
  {
591
17544
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
592
8773
    task_queues_async_initialized_ = false;
593
  }
594
595
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
596
17543
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
597
598
8770
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
599
600
8811
  for (ReqWrapBase* request : req_wrap_queue_)
601
39
    request->Cancel();
602
603
11169
  for (HandleWrap* handle : handle_wrap_queue_)
604
4802
    handle->Close();
605
606
26204
  for (HandleCleanup& hc : handle_cleanup_queue_)
607
17435
    hc.cb_(this, hc.handle_, hc.arg_);
608
8770
  handle_cleanup_queue_.clear();
609
610

51394
  while (handle_cleanup_waiting_ != 0 ||
611

25903
         request_waiting_ != 0 ||
612
8773
         !handle_wrap_queue_.IsEmpty()) {
613
8360
    uv_run(event_loop(), UV_RUN_ONCE);
614
  }
615
8773
}
616
617
320666
void Environment::PrintSyncTrace() const {
618
320666
  if (!trace_sync_io_) return;
619
620
2
  HandleScope handle_scope(isolate());
621
622
1
  fprintf(
623
1
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
624
1
  PrintStackTrace(isolate(),
625
                  StackTrace::CurrentStackTrace(
626
1
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
627
}
628
629
4386
void Environment::RunCleanup() {
630
4386
  started_cleanup_ = true;
631
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
632
8773
                              "RunCleanup", this);
633
4386
  bindings_.clear();
634
4388
  initial_base_object_count_ = 0;
635
4388
  CleanupHandles();
636
637

26316
  while (!cleanup_hooks_.empty() ||
638
8777
         native_immediates_.size() > 0 ||
639

17546
         native_immediates_threadsafe_.size() > 0 ||
640
4388
         native_immediates_interrupts_.size() > 0) {
641
    // Copy into a vector, since we can't sort an unordered_set in-place.
642
    std::vector<CleanupHookCallback> callbacks(
643
8769
        cleanup_hooks_.begin(), cleanup_hooks_.end());
644
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
645
    // need to be able to check whether they were un-scheduled by another hook.
646
647
8770
    std::sort(callbacks.begin(), callbacks.end(),
648
775102
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
649
      // Sort in descending order so that the most recently inserted callbacks
650
      // are run first.
651
775102
      return a.insertion_order_counter_ > b.insertion_order_counter_;
652
779487
    });
653
654
100504
    for (const CleanupHookCallback& cb : callbacks) {
655
96120
      if (cleanup_hooks_.count(cb) == 0) {
656
        // This hook was removed from the `cleanup_hooks_` set during another
657
        // hook that was run earlier. Nothing to do here.
658
647
        continue;
659
      }
660
661
95472
      cb.fn_(cb.arg_);
662
95471
      cleanup_hooks_.erase(cb);
663
    }
664
4385
    CleanupHandles();
665
  }
666
667
4391
  for (const int fd : unmanaged_fds_) {
668
    uv_fs_t close_req;
669
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
670
3
    uv_fs_req_cleanup(&close_req);
671
  }
672
4388
}
673
674
4919
void Environment::RunAtExitCallbacks() {
675
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
676
9842
                              "AtExit", this);
677
14610
  for (ExitCallback at_exit : at_exit_functions_) {
678
9690
    at_exit.cb_(at_exit.arg_);
679
  }
680
4923
  at_exit_functions_.clear();
681
4923
}
682
683
9710
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
684
9710
  at_exit_functions_.push_front(ExitCallback{cb, arg});
685
9711
}
686
687
430207
void Environment::RunAndClearInterrupts() {
688
437967
  while (native_immediates_interrupts_.size() > 0) {
689
15520
    NativeImmediateQueue queue;
690
    {
691
15520
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
692
7760
      queue.ConcatMove(std::move(native_immediates_interrupts_));
693
    }
694
7760
    DebugSealHandleScope seal_handle_scope(isolate());
695
696
23290
    while (auto head = queue.Shift())
697
15530
      head->Call(this);
698
  }
699
422455
}
700
701
414864
void Environment::RunAndClearNativeImmediates(bool only_refed) {
702
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
703
829734
                              "RunAndClearNativeImmediates", this);
704
829740
  HandleScope handle_scope(isolate_);
705
829745
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
706
707
414869
  size_t ref_count = 0;
708
709
  // Handle interrupts first. These functions are not allowed to throw
710
  // exceptions, so we do not need to handle that.
711
414869
  RunAndClearInterrupts();
712
713
829725
  auto drain_list = [&](NativeImmediateQueue* queue) {
714
1715522
    TryCatchScope try_catch(this);
715
829739
    DebugSealHandleScope seal_handle_scope(isolate());
716
942161
    while (auto head = queue->Shift()) {
717
56222
      bool is_refed = head->flags() & CallbackFlags::kRefed;
718
56222
      if (is_refed)
719
34045
        ref_count++;
720
721

56222
      if (is_refed || !only_refed)
722
112100
        head->Call(this);
723
724
56220
      head.reset();  // Destroy now so that this is also observed by try_catch.
725
726
56220
      if (UNLIKELY(try_catch.HasCaught())) {
727

4
        if (!try_catch.HasTerminated() && can_call_into_js())
728
2
          errors::TriggerUncaughtException(isolate(), try_catch);
729
730
1
        return true;
731
      }
732
56218
    }
733
829742
    return false;
734
414865
  };
735
414865
  while (drain_list(&native_immediates_)) {}
736
737
414870
  immediate_info()->ref_count_dec(ref_count);
738
739
414871
  if (immediate_info()->ref_count() == 0)
740
384428
    ToggleImmediateRef(false);
741
742
  // It is safe to check .size() first, because there is a causal relationship
743
  // between pushes to the threadsafe immediate list and this function being
744
  // called. For the common case, it's worth checking the size first before
745
  // establishing a mutex lock.
746
  // This is intentionally placed after the `ref_count` handling, because when
747
  // refed threadsafe immediates are created, they are not counted towards the
748
  // count in immediate_info() either.
749
829743
  NativeImmediateQueue threadsafe_immediates;
750
414876
  if (native_immediates_threadsafe_.size() > 0) {
751
1122
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
752
561
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
753
  }
754
414869
  while (drain_list(&threadsafe_immediates)) {}
755
414864
}
756
757
7766
void Environment::RequestInterruptFromV8() {
758
  // The Isolate may outlive the Environment, so some logic to handle the
759
  // situation in which the Environment is destroyed before the handler runs
760
  // is required.
761
762
  // We allocate a new pointer to a pointer to this Environment instance, and
763
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
764
  // callbacks are already scheduled to run and we can delete our own pointer
765
  // and just return. If it was nullptr previously, the Environment** is stored;
766
  // ~Environment sets the Environment* contained in it to nullptr, so that
767
  // the callback can check whether ~Environment has already run and it is thus
768
  // not safe to access the Environment instance itself.
769
7766
  Environment** interrupt_data = new Environment*(this);
770
7768
  Environment** dummy = nullptr;
771
7768
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
772
297
    delete interrupt_data;
773
297
    return;  // Already scheduled.
774
  }
775
776
37340
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
777
14917
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
778
7464
    Environment* env = *env_ptr;
779
7464
    if (env == nullptr) {
780
      // The Environment has already been destroyed. That should be okay; any
781
      // callback added before the Environment shuts down would have been
782
      // handled during cleanup.
783
11
      return;
784
    }
785
7453
    env->interrupt_data_.store(nullptr);
786
7453
    env->RunAndClearInterrupts();
787
22405
  }, interrupt_data);
788
}
789
790
6209
void Environment::ScheduleTimer(int64_t duration_ms) {
791
6209
  if (started_cleanup_) return;
792
6209
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
793
}
794
795
1172
void Environment::ToggleTimerRef(bool ref) {
796
1172
  if (started_cleanup_) return;
797
798
1172
  if (ref) {
799
812
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
800
  } else {
801
360
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
802
  }
803
}
804
805
5126
void Environment::RunTimers(uv_timer_t* handle) {
806
5126
  Environment* env = Environment::from_timer_handle(handle);
807
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
808
10240
                              "RunTimers", env);
809
810
5127
  if (!env->can_call_into_js())
811
    return;
812
813
10241
  HandleScope handle_scope(env->isolate());
814
10240
  Context::Scope context_scope(env->context());
815
816
5127
  Local<Object> process = env->process_object();
817
10240
  InternalCallbackScope scope(env, process, {0, 0});
818
819
5127
  Local<Function> cb = env->timers_callback_function();
820
  MaybeLocal<Value> ret;
821
5127
  Local<Value> arg = env->GetNow();
822
  // This code will loop until all currently due timers will process. It is
823
  // impossible for us to end up in an infinite loop due to how the JS-side
824
  // is structured.
825
5148
  do {
826
10306
    TryCatchScope try_catch(env);
827
5157
    try_catch.SetVerbose(true);
828
10314
    ret = cb->Call(env->context(), process, 1, &arg);
829

5148
  } while (ret.IsEmpty() && env->can_call_into_js());
830
831
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
832
  // is reset back to `true` after being previously set to `false` then this
833
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
834
  // timers corruption will occur and all timers behaviour will become
835
  // entirely unpredictable.
836
5117
  if (ret.IsEmpty())
837
3
    return;
838
839
  // To allow for less JS-C++ boundary crossing, the value returned from JS
840
  // serves a few purposes:
841
  // 1. If it's 0, no more timers exist and the handle should be unrefed
842
  // 2. If it's > 0, the value represents the next timer's expiry and there
843
  //    is at least one timer remaining that is refed.
844
  // 3. If it's < 0, the absolute value represents the next timer's expiry
845
  //    and there are no timers that are refed.
846
  int64_t expiry_ms =
847
20456
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
848
849
5114
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
850
851
5114
  if (expiry_ms != 0) {
852
    int64_t duration_ms =
853
4757
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
854
855
4757
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
856
857
4757
    if (expiry_ms > 0)
858
4485
      uv_ref(h);
859
    else
860
272
      uv_unref(h);
861
  } else {
862
357
    uv_unref(h);
863
  }
864
}
865
866
867
402225
void Environment::CheckImmediate(uv_check_t* handle) {
868
402225
  Environment* env = Environment::from_immediate_check_handle(handle);
869
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
870
432339
                              "CheckImmediate", env);
871
872
432323
  HandleScope scope(env->isolate());
873
432336
  Context::Scope context_scope(env->context());
874
875
402252
  env->RunAndClearNativeImmediates();
876
877

402239
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
878
372127
    return;
879
880
31028
  do {
881
62066
    MakeCallback(env->isolate(),
882
                 env->process_object(),
883
                 env->immediate_callback_function(),
884
                 0,
885
                 nullptr,
886
31062
                 {0, 0}).ToLocalChecked();
887

31028
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
888
889
30088
  if (env->immediate_info()->ref_count() == 0)
890
5242
    env->ToggleImmediateRef(false);
891
}
892
893
442886
void Environment::ToggleImmediateRef(bool ref) {
894
442886
  if (started_cleanup_) return;
895
896
434117
  if (ref) {
897
    // Idle handle is needed only to stop the event loop from blocking in poll.
898
158102
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
899
  } else {
900
380923
    uv_idle_stop(immediate_idle_handle());
901
  }
902
}
903
904
905
22182
Local<Value> Environment::GetNow() {
906
22182
  uv_update_time(event_loop());
907
22182
  uint64_t now = uv_now(event_loop());
908
22181
  CHECK_GE(now, timer_base());
909
22181
  now -= timer_base();
910
22182
  if (now <= 0xffffffff)
911
44364
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
912
  else
913
    return Number::New(isolate(), static_cast<double>(now));
914
}
915
916
28
void CollectExceptionInfo(Environment* env,
917
                          Local<Object> obj,
918
                          int errorno,
919
                          const char* err_string,
920
                          const char* syscall,
921
                          const char* message,
922
                          const char* path,
923
                          const char* dest) {
924
56
  obj->Set(env->context(),
925
           env->errno_string(),
926
140
           Integer::New(env->isolate(), errorno)).Check();
927
928
56
  obj->Set(env->context(), env->code_string(),
929
140
           OneByteString(env->isolate(), err_string)).Check();
930
931
28
  if (message != nullptr) {
932
56
    obj->Set(env->context(), env->message_string(),
933
140
             OneByteString(env->isolate(), message)).Check();
934
  }
935
936
  Local<Value> path_buffer;
937
28
  if (path != nullptr) {
938
    path_buffer =
939
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
940
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
941
  }
942
943
  Local<Value> dest_buffer;
944
28
  if (dest != nullptr) {
945
    dest_buffer =
946
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
947
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
948
  }
949
950
28
  if (syscall != nullptr) {
951
56
    obj->Set(env->context(), env->syscall_string(),
952
140
             OneByteString(env->isolate(), syscall)).Check();
953
  }
954
28
}
955
956
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
957
                                         int errorno,
958
                                         const char* syscall,
959
                                         const char* message,
960
                                         const char* path,
961
                                         const char* dest) {
962

28
  if (!object->IsObject() || errorno == 0)
963
    return;
964
965
28
  Local<Object> obj = object.As<Object>();
966
28
  const char* err_string = uv_err_name(errorno);
967
968

28
  if (message == nullptr || message[0] == '\0') {
969
28
    message = uv_strerror(errorno);
970
  }
971
972
  node::CollectExceptionInfo(this, obj, errorno, err_string,
973
28
                             syscall, message, path, dest);
974
}
975
976
4855
ImmediateInfo::ImmediateInfo(v8::Isolate* isolate, const SerializeInfo* info)
977
4855
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
978
979
1
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
980
    v8::Local<v8::Context> context, v8::SnapshotCreator* creator) {
981
1
  return {fields_.Serialize(context, creator)};
982
}
983
984
4402
void ImmediateInfo::Deserialize(Local<Context> context) {
985
4402
  fields_.Deserialize(context);
986
4402
}
987
988
1
std::ostream& operator<<(std::ostream& output,
989
                         const ImmediateInfo::SerializeInfo& i) {
990
1
  output << "{ " << i.fields << " }";
991
1
  return output;
992
}
993
994
19
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
995
19
  tracker->TrackField("fields", fields_);
996
19
}
997
998
1
TickInfo::SerializeInfo TickInfo::Serialize(v8::Local<v8::Context> context,
999
                                            v8::SnapshotCreator* creator) {
1000
1
  return {fields_.Serialize(context, creator)};
1001
}
1002
1003
4402
void TickInfo::Deserialize(Local<Context> context) {
1004
4402
  fields_.Deserialize(context);
1005
4402
}
1006
1007
1
std::ostream& operator<<(std::ostream& output,
1008
                         const TickInfo::SerializeInfo& i) {
1009
1
  output << "{ " << i.fields << " }";
1010
1
  return output;
1011
}
1012
1013
19
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1014
19
  tracker->TrackField("fields", fields_);
1015
19
}
1016
1017
4855
TickInfo::TickInfo(v8::Isolate* isolate, const SerializeInfo* info)
1018
    : fields_(
1019
4855
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1020
1021
4855
AsyncHooks::AsyncHooks(v8::Isolate* isolate, const SerializeInfo* info)
1022
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1023
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1024
      async_id_fields_(
1025
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1026

9710
      info_(info) {
1027
9710
  v8::HandleScope handle_scope(isolate);
1028
4855
  if (info == nullptr) {
1029
453
    clear_async_id_stack();
1030
1031
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1032
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1033
    // See discussion in https://github.com/nodejs/node/pull/15454
1034
    // When removing this, do it by reverting the commit. Otherwise the test
1035
    // and flag changes won't be included.
1036
453
    fields_[kCheck] = 1;
1037
1038
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1039
    // specified default value and it should fallback to the executionAsyncId.
1040
    // 0 is not used as the magic value, because that indicates a missing
1041
    // context which is different from a default context.
1042
453
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1043
1044
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1045
    // context during bootstrap (code that runs before entering uv_run()).
1046
453
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1047
  }
1048
4855
}
1049
1050
4402
void AsyncHooks::Deserialize(Local<Context> context) {
1051
4402
  async_ids_stack_.Deserialize(context);
1052
4402
  fields_.Deserialize(context);
1053
4402
  async_id_fields_.Deserialize(context);
1054
4402
  if (info_->js_execution_async_resources != 0) {
1055
    v8::Local<v8::Array> arr = context
1056
8804
                                   ->GetDataFromSnapshotOnce<v8::Array>(
1057
8804
                                       info_->js_execution_async_resources)
1058
4402
                                   .ToLocalChecked();
1059
4402
    js_execution_async_resources_.Reset(context->GetIsolate(), arr);
1060
  }
1061
1062
4402
  native_execution_async_resources_.resize(
1063
8804
      info_->native_execution_async_resources.size());
1064
4402
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1065
    v8::Local<v8::Object> obj =
1066
        context
1067
            ->GetDataFromSnapshotOnce<v8::Object>(
1068
                info_->native_execution_async_resources[i])
1069
            .ToLocalChecked();
1070
    native_execution_async_resources_[i].Reset(context->GetIsolate(), obj);
1071
  }
1072
4402
  info_ = nullptr;
1073
4402
}
1074
1075
1
std::ostream& operator<<(std::ostream& output,
1076
                         const std::vector<SnapshotIndex>& v) {
1077
1
  output << "{ ";
1078
1
  for (const SnapshotIndex i : v) {
1079
    output << i << ", ";
1080
  }
1081
1
  output << " }";
1082
1
  return output;
1083
}
1084
1085
1
std::ostream& operator<<(std::ostream& output,
1086
                         const AsyncHooks::SerializeInfo& i) {
1087
  output << "{\n"
1088
1
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1089
2
         << "  " << i.fields << ",  // fields\n"
1090
2
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1091
2
         << "  " << i.js_execution_async_resources
1092
         << ",  // js_execution_async_resources\n"
1093
2
         << "  " << i.native_execution_async_resources
1094
         << ",  // native_execution_async_resources\n"
1095
1
         << "}";
1096
1
  return output;
1097
}
1098
1099
1
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1100
                                                SnapshotCreator* creator) {
1101
1
  SerializeInfo info;
1102
1
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1103
1
  info.fields = fields_.Serialize(context, creator);
1104
1
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1105
2
  if (!js_execution_async_resources_.IsEmpty()) {
1106
2
    info.js_execution_async_resources = creator->AddData(
1107
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1108
1
    CHECK_NE(info.js_execution_async_resources, 0);
1109
  } else {
1110
    info.js_execution_async_resources = 0;
1111
  }
1112
1113
1
  info.native_execution_async_resources.resize(
1114
1
      native_execution_async_resources_.size());
1115
1
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1116
    info.native_execution_async_resources[i] = creator->AddData(
1117
        context,
1118
        native_execution_async_resources_[i].Get(context->GetIsolate()));
1119
  }
1120
1121
1
  return info;
1122
}
1123
1124
19
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1125
19
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1126
19
  tracker->TrackField("fields", fields_);
1127
19
  tracker->TrackField("async_id_fields", async_id_fields_);
1128
19
}
1129
1130
8
void AsyncHooks::grow_async_ids_stack() {
1131
8
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1132
1133
24
  env()->async_hooks_binding()->Set(
1134
      env()->context(),
1135
      env()->async_ids_stack_string(),
1136
40
      async_ids_stack_.GetJSArray()).Check();
1137
8
}
1138
1139
uv_key_t Environment::thread_local_env = {};
1140
1141
515
void Environment::Exit(int exit_code) {
1142
515
  if (options()->trace_exit) {
1143
4
    HandleScope handle_scope(isolate());
1144
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1145
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1146
1147
2
    if (is_main_thread()) {
1148
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1149
    } else {
1150
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1151
1
              uv_os_getpid(), thread_id());
1152
    }
1153
1154
    fprintf(
1155
2
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1156
2
    PrintStackTrace(isolate(),
1157
                    StackTrace::CurrentStackTrace(
1158
2
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1159
  }
1160
515
  process_exit_handler_(this, exit_code);
1161
53
}
1162
1163
4871
void Environment::stop_sub_worker_contexts() {
1164
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1165
1166
4896
  while (!sub_worker_contexts_.empty()) {
1167
25
    Worker* w = *sub_worker_contexts_.begin();
1168
25
    remove_sub_worker_context(w);
1169
25
    w->Exit(1);
1170
25
    w->JoinThread();
1171
  }
1172
4848
}
1173
1174
2
Environment* Environment::worker_parent_env() const {
1175
2
  if (worker_context() == nullptr) return nullptr;
1176
  return worker_context()->env();
1177
}
1178
1179
45114
void Environment::AddUnmanagedFd(int fd) {
1180
45114
  if (!tracks_unmanaged_fds()) return;
1181
498
  auto result = unmanaged_fds_.insert(fd);
1182
498
  if (!result.second) {
1183
    ProcessEmitWarning(
1184
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1185
  }
1186
}
1187
1188
44749
void Environment::RemoveUnmanagedFd(int fd) {
1189
44749
  if (!tracks_unmanaged_fds()) return;
1190
495
  size_t removed_count = unmanaged_fds_.erase(fd);
1191
495
  if (removed_count == 0) {
1192
    ProcessEmitWarning(
1193
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1194
  }
1195
}
1196
1197
void Environment::ForEachBaseObject(BaseObjectIterator iterator) {
1198
  size_t i = 0;
1199
  for (const auto& hook : cleanup_hooks_) {
1200
    BaseObject* obj = hook.GetBaseObject();
1201
    if (obj != nullptr) iterator(i, obj);
1202
    i++;
1203
  }
1204
}
1205
1206
void PrintBaseObject(size_t i, BaseObject* obj) {
1207
  std::cout << "#" << i << " " << obj << ": " << obj->MemoryInfoName() << "\n";
1208
}
1209
1210
void Environment::PrintAllBaseObjects() {
1211
  std::cout << "BaseObjects\n";
1212
  ForEachBaseObject(PrintBaseObject);
1213
}
1214
1215
1
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1216
1
  EnvSerializeInfo info;
1217
1
  Local<Context> ctx = context();
1218
1219
  // Currently all modules are compiled without cache in builtin snapshot
1220
  // builder.
1221
2
  info.native_modules = std::vector<std::string>(
1222
1
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1223
1224
1
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1225
1
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1226
1
  info.tick_info = tick_info_.Serialize(ctx, creator);
1227
1
  info.performance_state = performance_state_->Serialize(ctx, creator);
1228
1
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1229
1
  info.should_abort_on_uncaught_toggle =
1230
1
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1231
1232
1
  size_t id = 0;
1233
#define V(PropertyName, TypeName)                                              \
1234
  do {                                                                         \
1235
    Local<TypeName> field = PropertyName();                                    \
1236
    if (!field.IsEmpty()) {                                                    \
1237
      size_t index = creator->AddData(field);                                  \
1238
      info.persistent_templates.push_back({#PropertyName, id, index});         \
1239
    }                                                                          \
1240
    id++;                                                                      \
1241
  } while (0);
1242
















41
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1243
#undef V
1244
1245
1
  id = 0;
1246
#define V(PropertyName, TypeName)                                              \
1247
  do {                                                                         \
1248
    Local<TypeName> field = PropertyName();                                    \
1249
    if (!field.IsEmpty()) {                                                    \
1250
      size_t index = creator->AddData(ctx, field);                             \
1251
      info.persistent_values.push_back({#PropertyName, id, index});            \
1252
    }                                                                          \
1253
    id++;                                                                      \
1254
  } while (0);
1255

























75
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1256
#undef V
1257
1258
2
  info.context = creator->AddData(ctx, context());
1259
1
  return info;
1260
}
1261
1262
2
std::ostream& operator<<(std::ostream& output,
1263
                         const std::vector<PropInfo>& vec) {
1264
2
  output << "{\n";
1265
33
  for (const auto& info : vec) {
1266
62
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1267
93
           << std::to_string(info.index) << " },\n";
1268
  }
1269
2
  output << "}";
1270
2
  return output;
1271
}
1272
1273
1
std::ostream& operator<<(std::ostream& output,
1274
                         const std::vector<std::string>& vec) {
1275
1
  output << "{\n";
1276
39
  for (const auto& info : vec) {
1277
38
    output << "  \"" << info << "\",\n";
1278
  }
1279
1
  output << "}";
1280
1
  return output;
1281
}
1282
1283
1
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1284
  output << "{\n"
1285
1
         << "// -- native_modules begins --\n"
1286
2
         << i.native_modules << ",\n"
1287
         << "// -- native_modules ends --\n"
1288
1
         << "// -- async_hooks begins --\n"
1289
2
         << i.async_hooks << ",\n"
1290
1
         << "// -- async_hooks ends --\n"
1291
2
         << i.tick_info << ",  // tick_info\n"
1292
2
         << i.immediate_info << ",  // immediate_info\n"
1293
1
         << "// -- performance_state begins --\n"
1294
2
         << i.performance_state << ",\n"
1295
1
         << "// -- performance_state ends --\n"
1296
2
         << i.stream_base_state << ",  // stream_base_state\n"
1297
2
         << i.should_abort_on_uncaught_toggle
1298
         << ",  // should_abort_on_uncaught_toggle\n"
1299
1
         << "// -- persistent_templates begins --\n"
1300
2
         << i.persistent_templates << ",\n"
1301
         << "// persistent_templates ends --\n"
1302
1
         << "// -- persistent_values begins --\n"
1303
2
         << i.persistent_values << ",\n"
1304
1
         << "// -- persistent_values ends --\n"
1305
2
         << i.context << ",  // context\n"
1306
1
         << "}";
1307
1
  return output;
1308
}
1309
1310
4402
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1311
4402
  Local<Context> ctx = context();
1312
1313
4402
  native_modules_in_snapshot = info->native_modules;
1314
4402
  async_hooks_.Deserialize(ctx);
1315
4402
  immediate_info_.Deserialize(ctx);
1316
4402
  tick_info_.Deserialize(ctx);
1317
4402
  performance_state_->Deserialize(ctx);
1318
4402
  stream_base_state_.Deserialize(ctx);
1319
4402
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1320
1321
4402
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1322
    fprintf(stderr, "deserializing...\n");
1323
    std::cerr << *info << "\n";
1324
  }
1325
1326
4402
  const std::vector<PropInfo>& templates = info->persistent_templates;
1327
4402
  size_t i = 0;  // index to the array
1328
4402
  size_t id = 0;
1329
#define V(PropertyName, TypeName)                                              \
1330
  do {                                                                         \
1331
    if (templates.size() > i && id == templates[i].id) {                       \
1332
      const PropInfo& d = templates[i];                                        \
1333
      DCHECK_EQ(d.name, #PropertyName);                                        \
1334
      MaybeLocal<TypeName> maybe_field =                                       \
1335
          isolate_->GetDataFromSnapshotOnce<TypeName>(d.index);                \
1336
      Local<TypeName> field;                                                   \
1337
      if (!maybe_field.ToLocal(&field)) {                                      \
1338
        fprintf(stderr,                                                        \
1339
                "Failed to deserialize environment template " #PropertyName    \
1340
                "\n");                                                         \
1341
      }                                                                        \
1342
      set_##PropertyName(field);                                               \
1343
      i++;                                                                     \
1344
    }                                                                          \
1345
  } while (0);                                                                 \
1346
  id++;
1347
































































74834
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1348
#undef V
1349
1350
4402
  i = 0;  // index to the array
1351
4402
  id = 0;
1352
4402
  const std::vector<PropInfo>& values = info->persistent_values;
1353
#define V(PropertyName, TypeName)                                              \
1354
  do {                                                                         \
1355
    if (values.size() > i && id == values[i].id) {                             \
1356
      const PropInfo& d = values[i];                                           \
1357
      DCHECK_EQ(d.name, #PropertyName);                                        \
1358
      MaybeLocal<TypeName> maybe_field =                                       \
1359
          ctx->GetDataFromSnapshotOnce<TypeName>(d.index);                     \
1360
      Local<TypeName> field;                                                   \
1361
      if (!maybe_field.ToLocal(&field)) {                                      \
1362
        fprintf(stderr,                                                        \
1363
                "Failed to deserialize environment value " #PropertyName       \
1364
                "\n");                                                         \
1365
      }                                                                        \
1366
      set_##PropertyName(field);                                               \
1367
      i++;                                                                     \
1368
    }                                                                          \
1369
  } while (0);                                                                 \
1370
  id++;
1371






































































































308140
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1372
#undef V
1373
1374
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1375
13206
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1376
  Local<Context> ctx_from_snapshot;
1377
4402
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1378
    fprintf(stderr,
1379
            "Failed to deserialize context back reference from the snapshot\n");
1380
  }
1381
4402
  CHECK_EQ(ctx_from_snapshot, ctx);
1382
4402
}
1383
1384
19
void Environment::BuildEmbedderGraph(Isolate* isolate,
1385
                                     EmbedderGraph* graph,
1386
                                     void* data) {
1387
38
  MemoryTracker tracker(isolate, graph);
1388
19
  Environment* env = static_cast<Environment*>(data);
1389
19
  tracker.Track(env);
1390
385
  env->ForEachBaseObject([&](BaseObject* obj) {
1391
347
    if (obj->IsDoneInitializing())
1392
344
      tracker.Track(obj);
1393
366
  });
1394
19
}
1395
1396
19
inline size_t Environment::SelfSize() const {
1397
19
  size_t size = sizeof(*this);
1398
  // Remove non pointer fields that will be tracked in MemoryInfo()
1399
  // TODO(joyeecheung): refactor the MemoryTracker interface so
1400
  // this can be done for common types within the Track* calls automatically
1401
  // if a certain scope is entered.
1402
19
  size -= sizeof(async_hooks_);
1403
19
  size -= sizeof(tick_info_);
1404
19
  size -= sizeof(immediate_info_);
1405
19
  return size;
1406
}
1407
1408
19
void Environment::MemoryInfo(MemoryTracker* tracker) const {
1409
  // Iteratable STLs have their own sizes subtracted from the parent
1410
  // by default.
1411
19
  tracker->TrackField("isolate_data", isolate_data_);
1412
19
  tracker->TrackField("native_modules_with_cache", native_modules_with_cache);
1413
19
  tracker->TrackField("native_modules_without_cache",
1414
19
                      native_modules_without_cache);
1415
19
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
1416
19
  tracker->TrackField("exec_argv", exec_argv_);
1417
19
  tracker->TrackField("should_abort_on_uncaught_toggle",
1418
19
                      should_abort_on_uncaught_toggle_);
1419
19
  tracker->TrackField("stream_base_state", stream_base_state_);
1420
19
  tracker->TrackFieldWithSize(
1421
38
      "cleanup_hooks", cleanup_hooks_.size() * sizeof(CleanupHookCallback));
1422
19
  tracker->TrackField("async_hooks", async_hooks_);
1423
19
  tracker->TrackField("immediate_info", immediate_info_);
1424
19
  tracker->TrackField("tick_info", tick_info_);
1425
1426
#define V(PropertyName, TypeName)                                              \
1427
  tracker->TrackField(#PropertyName, PropertyName());
1428
19
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1429
#undef V
1430
1431
  // FIXME(joyeecheung): track other fields in Environment.
1432
  // Currently MemoryTracker is unable to track these
1433
  // correctly:
1434
  // - Internal types that do not implement MemoryRetainer yet
1435
  // - STL containers with MemoryRetainer* inside
1436
  // - STL containers with numeric types inside that should not have their
1437
  //   nodes elided e.g. numeric keys in maps.
1438
  // We also need to make sure that when we add a non-pointer field as its own
1439
  // node, we shift its sizeof() size out of the Environment node.
1440
19
}
1441
1442
1018781
void Environment::RunWeakRefCleanup() {
1443
1018781
  isolate()->ClearKeptObjects();
1444
1018833
}
1445
1446
// Not really any better place than env.cc at this moment.
1447
90606
void BaseObject::DeleteMe(void* data) {
1448
90606
  BaseObject* self = static_cast<BaseObject*>(data);
1449

93113
  if (self->has_pointer_data() &&
1450
2507
      self->pointer_data()->strong_ptr_count > 0) {
1451
241
    return self->Detach();
1452
  }
1453
90369
  delete self;
1454
}
1455
1456
284
bool BaseObject::IsDoneInitializing() const { return true; }
1457
1458
344
Local<Object> BaseObject::WrappedObject() const {
1459
344
  return object();
1460
}
1461
1462
688
bool BaseObject::IsRootNode() const {
1463
1376
  return !persistent_handle_.IsWeak();
1464
}
1465
1466
37310
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1467
37310
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1468
37310
  if (tmpl.IsEmpty()) {
1469
453
    tmpl = env->NewFunctionTemplate(nullptr);
1470
906
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1471
453
    env->set_base_object_ctor_template(tmpl);
1472
  }
1473
37309
  return tmpl;
1474
}
1475
1476

13419
}  // namespace node