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: 413 441 93.7 %
Date: 2019-02-26 22:23:30 Branches: 352 486 72.4 %

Line Branch Exec Source
1
#include "async_wrap.h"
2
#include "node_buffer.h"
3
#include "node_context_data.h"
4
#include "node_errors.h"
5
#include "node_file.h"
6
#include "node_internals.h"
7
#include "node_native_module.h"
8
#include "node_options-inl.h"
9
#include "node_platform.h"
10
#include "node_process.h"
11
#include "node_v8_platform-inl.h"
12
#include "node_worker.h"
13
#include "tracing/agent.h"
14
#include "tracing/traced_value.h"
15
#include "v8-profiler.h"
16
17
#include <stdio.h>
18
#include <algorithm>
19
#include <atomic>
20
21
namespace node {
22
23
using errors::TryCatchScope;
24
using v8::ArrayBuffer;
25
using v8::Boolean;
26
using v8::Context;
27
using v8::EmbedderGraph;
28
using v8::External;
29
using v8::Function;
30
using v8::HandleScope;
31
using v8::Integer;
32
using v8::Isolate;
33
using v8::Local;
34
using v8::Message;
35
using v8::NewStringType;
36
using v8::Number;
37
using v8::Object;
38
using v8::Private;
39
using v8::Promise;
40
using v8::PromiseHookType;
41
using v8::StackFrame;
42
using v8::StackTrace;
43
using v8::String;
44
using v8::Symbol;
45
using v8::TracingController;
46
using v8::Undefined;
47
using v8::Value;
48
using worker::Worker;
49
50
#define kTraceCategoryCount 1
51
52
// TODO(@jasnell): Likely useful to move this to util or node_internal to
53
// allow reuse. But since we're not reusing it yet...
54
class TraceEventScope {
55
 public:
56
637173
  TraceEventScope(const char* category,
57
                  const char* name,
58
637173
                  void* id) : category_(category), name_(name), id_(id) {
59

1274346
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(category_, name_, id_);
60
637173
  }
61
637142
  ~TraceEventScope() {
62

1274284
    TRACE_EVENT_NESTABLE_ASYNC_END0(category_, name_, id_);
63
637142
  }
64
65
 private:
66
  const char* category_;
67
  const char* name_;
68
  void* id_;
69
};
70
71
int const Environment::kNodeContextTag = 0x6e6f64;
72
void* const Environment::kNodeContextTagPtr = const_cast<void*>(
73
    static_cast<const void*>(&Environment::kNodeContextTag));
74
75
4404
IsolateData::IsolateData(Isolate* isolate,
76
                         uv_loop_t* event_loop,
77
                         MultiIsolatePlatform* platform,
78
                         ArrayBufferAllocator* node_allocator)
79
    : isolate_(isolate),
80
      event_loop_(event_loop),
81
4404
      allocator_(isolate->GetArrayBufferAllocator()),
82
      node_allocator_(node_allocator),
83
4404
      uses_node_allocator_(allocator_ == node_allocator_),
84
924840
      platform_(platform) {
85
4404
  CHECK_NOT_NULL(allocator_);
86
4404
  if (platform_ != nullptr)
87
4404
    platform_->RegisterIsolate(isolate_, event_loop);
88
89
  options_.reset(
90
4404
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
91
92
  // Create string and private symbol properties as internalized one byte
93
  // strings after the platform is properly initialized.
94
  //
95
  // Internalized because it makes property lookups a little faster and
96
  // because the string is created in the old space straight away.  It's going
97
  // to end up in the old space sooner or later anyway but now it doesn't go
98
  // through v8::Eternal's new space handling first.
99
  //
100
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
101
  // decoding step.
102
103
#define V(PropertyName, StringValue)                                        \
104
    PropertyName ## _.Set(                                                  \
105
        isolate,                                                            \
106
        Private::New(                                                       \
107
            isolate,                                                        \
108
            String::NewFromOneByte(                                         \
109
                isolate,                                                    \
110
                reinterpret_cast<const uint8_t*>(StringValue),              \
111
                NewStringType::kInternalized,                               \
112
                sizeof(StringValue) - 1).ToLocalChecked()));
113
74868
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
114
#undef V
115
#define V(PropertyName, StringValue)                                        \
116
    PropertyName ## _.Set(                                                  \
117
        isolate,                                                            \
118
        Symbol::New(                                                        \
119
            isolate,                                                        \
120
            String::NewFromOneByte(                                         \
121
                isolate,                                                    \
122
                reinterpret_cast<const uint8_t*>(StringValue),              \
123
                NewStringType::kInternalized,                               \
124
                sizeof(StringValue) - 1).ToLocalChecked()));
125
30828
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
126
#undef V
127
#define V(PropertyName, StringValue)                                        \
128
    PropertyName ## _.Set(                                                  \
129
        isolate,                                                            \
130
        String::NewFromOneByte(                                             \
131
            isolate,                                                        \
132
            reinterpret_cast<const uint8_t*>(StringValue),                  \
133
            NewStringType::kInternalized,                                   \
134
            sizeof(StringValue) - 1).ToLocalChecked());
135
1730772
  PER_ISOLATE_STRING_PROPERTIES(V)
136
#undef V
137
4404
}
138
139
8072
IsolateData::~IsolateData() {
140
4036
  if (platform_ != nullptr)
141
4036
    platform_->UnregisterIsolate(isolate_);
142
4036
}
143
144
145
4234
void InitThreadLocalOnce() {
146
4234
  CHECK_EQ(0, uv_key_create(&Environment::thread_local_env));
147
4234
}
148
149
134
void Environment::TrackingTraceStateObserver::UpdateTraceCategoryState() {
150
134
  if (!env_->owns_process_state()) {
151
    // Ideally, we’d have a consistent story that treats all threads/Environment
152
    // instances equally here. However, tracing is essentially global, and this
153
    // callback is called from whichever thread calls `StartTracing()` or
154
    // `StopTracing()`. The only way to do this in a threadsafe fashion
155
    // seems to be only tracking this from the main thread, and only allowing
156
    // these state modifications from the main thread.
157
71
    return;
158
  }
159
160
132
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
161
132
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
162
163
132
  Isolate* isolate = env_->isolate();
164
132
  HandleScope handle_scope(isolate);
165
132
  Local<Function> cb = env_->trace_category_state_function();
166
132
  if (cb.IsEmpty())
167
67
    return;
168
130
  TryCatchScope try_catch(env_);
169
65
  try_catch.SetVerbose(true);
170
130
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
171
260
  cb->Call(env_->context(), Undefined(isolate), arraysize(args), args)
172
195
      .ToLocalChecked();
173
}
174
175
static std::atomic<uint64_t> next_thread_id{0};
176
177
4405
uint64_t Environment::AllocateThreadId() {
178
4405
  return next_thread_id++;
179
}
180
181
4403
Environment::Environment(IsolateData* isolate_data,
182
                         Local<Context> context,
183
                         Flags flags,
184
                         uint64_t thread_id)
185
4403
    : isolate_(context->GetIsolate()),
186
      isolate_data_(isolate_data),
187
      immediate_info_(context->GetIsolate()),
188
      tick_info_(context->GetIsolate()),
189
4403
      timer_base_(uv_now(isolate_data->event_loop())),
190
      should_abort_on_uncaught_toggle_(isolate_, 1),
191
      stream_base_state_(isolate_, StreamBase::kNumStreamBaseStateFields),
192
      flags_(flags),
193
      thread_id_(thread_id == kNoThreadId ? AllocateThreadId() : thread_id),
194
      fs_stats_field_array_(isolate_, kFsStatsBufferLength),
195
      fs_stats_field_bigint_array_(isolate_, kFsStatsBufferLength),
196
317016
      context_(context->GetIsolate(), context) {
197
  // We'll be creating new objects so make sure we've entered the context.
198
4403
  HandleScope handle_scope(isolate());
199
  Context::Scope context_scope(context);
200
4403
  set_as_external(External::New(isolate(), this));
201
202
  // We create new copies of the per-Environment option sets, so that it is
203
  // easier to modify them after Environment creation. The defaults are
204
  // part of the per-Isolate option set, for which in turn the defaults are
205
  // part of the per-process option set.
206
4403
  options_.reset(new EnvironmentOptions(*isolate_data->options()->per_env));
207
4403
  inspector_host_port_.reset(new HostPort(options_->debug_options().host_port));
208
209
#if HAVE_INSPECTOR
210
  // We can only create the inspector agent after having cloned the options.
211
13209
  inspector_agent_ =
212
8806
      std::unique_ptr<inspector::Agent>(new inspector::Agent(this));
213
#endif
214
215
4403
  AssignToContext(context, ContextInfo(""));
216
217
4403
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
218
4403
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
219
4403
    TracingController* tracing_controller = writer->GetTracingController();
220
4403
    tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
221
  }
222
223
4403
  destroy_async_id_list_.reserve(512);
224
  BeforeExit(
225
12145
      [](void* arg) {
226
3871
        Environment* env = static_cast<Environment*>(arg);
227
3871
        if (!env->destroy_async_id_list()->empty())
228
141
          AsyncWrap::DestroyAsyncIdsCallback(env, nullptr);
229
12145
      },
230
4403
      this);
231
232
4403
  performance_state_.reset(new performance::performance_state(isolate()));
233
  performance_state_->Mark(
234
4403
      performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT);
235
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
236
4403
                           per_process::node_start_time);
237
  performance_state_->Mark(
238
      performance::NODE_PERFORMANCE_MILESTONE_V8_START,
239
4403
      performance::performance_v8_start);
240
241
  // By default, always abort when --abort-on-uncaught-exception was passed.
242
4403
  should_abort_on_uncaught_toggle_[0] = 1;
243
244
8806
  std::string debug_cats;
245
4403
  credentials::SafeGetenv("NODE_DEBUG_NATIVE", &debug_cats);
246
4403
  set_debug_categories(debug_cats, true);
247
248
  isolate()->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
249
4403
      BuildEmbedderGraph, this);
250
4403
  if (options_->no_force_async_hooks_checks) {
251
1
    async_hooks_.no_force_checks();
252
  }
253
254
  // TODO(addaleax): the per-isolate state should not be controlled by
255
  // a single Environment.
256
8806
  isolate()->SetPromiseRejectCallback(task_queue::PromiseRejectCallback);
257
4403
}
258
259
41431
CompileFnEntry::CompileFnEntry(Environment* env, uint32_t id)
260
41431
    : env(env), id(id) {
261
41431
  env->compile_fn_entries.insert(this);
262
41431
}
263
264
282450
Environment::~Environment() {
265
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
266
4035
      BuildEmbedderGraph, this);
267
268
  // Make sure there are no re-used libuv wrapper objects.
269
  // CleanupHandles() should have removed all of them.
270
4035
  CHECK(file_handle_read_wrap_freelist_.empty());
271
272
  // dispose the Persistent references to the compileFunction
273
  // wrappers used in the dynamic import callback
274
22849
  for (auto& entry : compile_fn_entries) {
275
18814
    delete entry;
276
  }
277
278
4035
  HandleScope handle_scope(isolate());
279
280
#if HAVE_INSPECTOR
281
  // Destroy inspector agent before erasing the context. The inspector
282
  // destructor depends on the context still being accessible.
283
4035
  inspector_agent_.reset();
284
#endif
285
286
  context()->SetAlignedPointerInEmbedderData(
287
8070
      ContextEmbedderIndex::kEnvironment, nullptr);
288
289
4035
  if (trace_state_observer_) {
290
4035
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
291
4035
    CHECK_NOT_NULL(writer);
292
4035
    TracingController* tracing_controller = writer->GetTracingController();
293
4035
    tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
294
  }
295
296
4035
  delete[] heap_statistics_buffer_;
297
4035
  delete[] heap_space_statistics_buffer_;
298
4035
  delete[] http_parser_buffer_;
299
300

8070
  TRACE_EVENT_NESTABLE_ASYNC_END0(
301
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
302
303
  // Do not unload addons on the main thread. Some addons need to retain memory
304
  // beyond the Environment's lifetime, and unloading them early would break
305
  // them; with Worker threads, we have the opportunity to be stricter.
306
  // Also, since the main thread usually stops just before the process exits,
307
  // this is far less relevant here.
308
4035
  if (!is_main_thread()) {
309
    // Dereference all addons that were loaded into this environment.
310
176
    for (binding::DLib& addon : loaded_addons_) {
311
7
      addon.Close();
312
    }
313
4035
  }
314
4035
}
315
316
4403
void Environment::Start(bool start_profiler_idle_notifier) {
317
4403
  HandleScope handle_scope(isolate());
318
4403
  Context::Scope context_scope(context());
319
320
4403
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
321
4403
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
322
323
4403
  uv_check_init(event_loop(), immediate_check_handle());
324
4403
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
325
326
4403
  uv_idle_init(event_loop(), immediate_idle_handle());
327
328
4403
  uv_check_start(immediate_check_handle(), CheckImmediate);
329
330
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
331
  // but not all samples are created equal; mark the wall clock time spent in
332
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
333
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
334
  // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
335
  // probably fortify in the API contract, namely that the last started prepare
336
  // or check watcher runs first.  It's not 100% foolproof; if an add-on starts
337
  // a prepare or check watcher after us, any samples attributed to its callback
338
  // will be recorded with state=IDLE.
339
4403
  uv_prepare_init(event_loop(), &idle_prepare_handle_);
340
4403
  uv_check_init(event_loop(), &idle_check_handle_);
341
4403
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
342
4403
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
343
344
  // Register clean-up cb to be called to clean up the handles
345
  // when the environment is freed, note that they are not cleaned in
346
  // the one environment per process setup, but will be called in
347
  // FreeEnvironment.
348
4403
  RegisterHandleCleanups();
349
350
4403
  if (start_profiler_idle_notifier) {
351
3
    StartProfilerIdleNotifier();
352
  }
353
354
  static uv_once_t init_once = UV_ONCE_INIT;
355
4403
  uv_once(&init_once, InitThreadLocalOnce);
356
8806
  uv_key_set(&thread_local_env, this);
357
4403
}
358
359
4403
MaybeLocal<Object> Environment::ProcessCliArgs(
360
    const std::vector<std::string>& args,
361
    const std::vector<std::string>& exec_args) {
362
4403
  if (args.size() > 1) {
363
3932
    std::string first_arg = args[1];
364
3932
    if (first_arg == "inspect") {
365
2
      execution_mode_ = ExecutionMode::kInspect;
366
3930
    } else if (first_arg == "debug") {
367
2
      execution_mode_ = ExecutionMode::kDebug;
368
3928
    } else if (first_arg != "-") {
369
3926
      execution_mode_ = ExecutionMode::kRunMainModule;
370
3932
    }
371
  }
372
373
8806
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
374
4403
          TRACING_CATEGORY_NODE1(environment)) != 0) {
375
8
    auto traced_value = tracing::TracedValue::Create();
376
8
    traced_value->BeginArray("args");
377
8
    for (const std::string& arg : args) traced_value->AppendString(arg);
378
8
    traced_value->EndArray();
379
8
    traced_value->BeginArray("exec_args");
380
8
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
381
8
    traced_value->EndArray();
382

16
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
383
                                      "Environment",
384
                                      this,
385
                                      "args",
386
8
                                      std::move(traced_value));
387
  }
388
389
  Local<Object> process_object =
390
      node::CreateProcessObject(this, args, exec_args)
391
8806
          .FromMaybe(Local<Object>());
392
4403
  set_process_object(process_object);
393
4403
  return process_object;
394
}
395
396
4403
void Environment::RegisterHandleCleanups() {
397
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
398
44743
                                        void* arg) {
399
20170
    handle->data = env;
400
401
40340
    env->CloseHandle(handle, [](uv_handle_t* handle) {});
402
49146
  };
403
404
  RegisterHandleCleanup(
405
4403
      reinterpret_cast<uv_handle_t*>(timer_handle()),
406
      close_and_finish,
407
4403
      nullptr);
408
  RegisterHandleCleanup(
409
4403
      reinterpret_cast<uv_handle_t*>(immediate_check_handle()),
410
      close_and_finish,
411
4403
      nullptr);
412
  RegisterHandleCleanup(
413
4403
      reinterpret_cast<uv_handle_t*>(immediate_idle_handle()),
414
      close_and_finish,
415
4403
      nullptr);
416
  RegisterHandleCleanup(
417
      reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_),
418
      close_and_finish,
419
4403
      nullptr);
420
  RegisterHandleCleanup(
421
      reinterpret_cast<uv_handle_t*>(&idle_check_handle_),
422
      close_and_finish,
423
4403
      nullptr);
424
4403
}
425
426
8235
void Environment::CleanupHandles() {
427
8268
  for (ReqWrapBase* request : req_wrap_queue_)
428
33
    request->Cancel();
429
430
10428
  for (HandleWrap* handle : handle_wrap_queue_)
431
4386
    handle->Close();
432
433
28405
  for (HandleCleanup& hc : handle_cleanup_queue_)
434
20170
    hc.cb_(this, hc.handle_, hc.arg_);
435
8235
  handle_cleanup_queue_.clear();
436
437

41020
  while (handle_cleanup_waiting_ != 0 ||
438

20510
         request_waiting_ != 0 ||
439
8235
         !handle_wrap_queue_.IsEmpty()) {
440
4040
    uv_run(event_loop(), UV_RUN_ONCE);
441
  }
442
443
8235
  file_handle_read_wrap_freelist_.clear();
444
8235
}
445
446
3
void Environment::StartProfilerIdleNotifier() {
447
3
  if (profiler_idle_notifier_started_)
448
3
    return;
449
450
3
  profiler_idle_notifier_started_ = true;
451
452
15
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
453
6
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
454
6
    env->isolate()->SetIdle(true);
455
18
  });
456
457
15
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
458
6
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
459
6
    env->isolate()->SetIdle(false);
460
18
  });
461
}
462
463
void Environment::StopProfilerIdleNotifier() {
464
  profiler_idle_notifier_started_ = false;
465
  uv_prepare_stop(&idle_prepare_handle_);
466
  uv_check_stop(&idle_check_handle_);
467
}
468
469
511259
void Environment::PrintSyncTrace() const {
470
511259
  if (!options_->trace_sync_io)
471
1022478
    return;
472
473
40
  HandleScope handle_scope(isolate());
474
  Local<StackTrace> stack =
475
40
      StackTrace::CurrentStackTrace(isolate(), 10, StackTrace::kDetailed);
476
477
  fprintf(stderr, "(node:%d) WARNING: Detected use of sync API\n",
478
40
          uv_os_getpid());
479
480
640
  for (int i = 0; i < stack->GetFrameCount() - 1; i++) {
481
560
    Local<StackFrame> stack_frame = stack->GetFrame(isolate(), i);
482
560
    node::Utf8Value fn_name_s(isolate(), stack_frame->GetFunctionName());
483
840
    node::Utf8Value script_name(isolate(), stack_frame->GetScriptName());
484
280
    const int line_number = stack_frame->GetLineNumber();
485
280
    const int column = stack_frame->GetColumn();
486
487
280
    if (stack_frame->IsEval()) {
488
      if (stack_frame->GetScriptId() == Message::kNoScriptIdInfo) {
489
        fprintf(stderr, "    at [eval]:%i:%i\n", line_number, column);
490
      } else {
491
        fprintf(stderr,
492
                "    at [eval] (%s:%i:%i)\n",
493
                *script_name,
494
                line_number,
495
                column);
496
      }
497
      break;
498
    }
499
500
280
    if (fn_name_s.length() == 0) {
501
21
      fprintf(stderr, "    at %s:%i:%i\n", *script_name, line_number, column);
502
    } else {
503
      fprintf(stderr,
504
              "    at %s (%s:%i:%i)\n",
505
              *fn_name_s,
506
              *script_name,
507
              line_number,
508
259
              column);
509
    }
510
280
  }
511
40
  fflush(stderr);
512
}
513
514
4203
void Environment::RunCleanup() {
515
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
516
4203
                              "RunCleanup", this);
517
4203
  CleanupHandles();
518
519
12438
  while (!cleanup_hooks_.empty()) {
520
    // Copy into a vector, since we can't sort an unordered_set in-place.
521
    std::vector<CleanupHookCallback> callbacks(
522
4032
        cleanup_hooks_.begin(), cleanup_hooks_.end());
523
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
524
    // need to be able to check whether they were un-scheduled by another hook.
525
526
    std::sort(callbacks.begin(), callbacks.end(),
527
486757
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
528
      // Sort in descending order so that the most recently inserted callbacks
529
      // are run first.
530
486757
      return a.insertion_order_counter_ > b.insertion_order_counter_;
531
490789
    });
532
533
44602
    for (const CleanupHookCallback& cb : callbacks) {
534
40570
      if (cleanup_hooks_.count(cb) == 0) {
535
        // This hook was removed from the `cleanup_hooks_` set during another
536
        // hook that was run earlier. Nothing to do here.
537
        continue;
538
      }
539
540
40570
      cb.fn_(cb.arg_);
541
40570
      cleanup_hooks_.erase(cb);
542
    }
543
4032
    CleanupHandles();
544
8235
  }
545
4203
}
546
547
3884
void Environment::RunBeforeExitCallbacks() {
548
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
549
3884
                              "BeforeExit", this);
550
7755
  for (ExitCallback before_exit : before_exit_functions_) {
551
3871
    before_exit.cb_(before_exit.arg_);
552
  }
553
3884
  before_exit_functions_.clear();
554
3884
}
555
556
4403
void Environment::BeforeExit(void (*cb)(void* arg), void* arg) {
557
4403
  before_exit_functions_.push_back(ExitCallback{cb, arg});
558
4403
}
559
560
4034
void Environment::RunAtExitCallbacks() {
561
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
562
4034
                              "AtExit", this);
563
4041
  for (ExitCallback at_exit : at_exit_functions_) {
564
7
    at_exit.cb_(at_exit.arg_);
565
  }
566
4034
  at_exit_functions_.clear();
567
4034
}
568
569
7
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
570
7
  at_exit_functions_.push_back(ExitCallback{cb, arg});
571
7
}
572
573
249
void Environment::AddPromiseHook(promise_hook_func fn, void* arg) {
574
  auto it = std::find_if(
575
      promise_hooks_.begin(), promise_hooks_.end(),
576
3
      [&](const PromiseHookCallback& hook) {
577

3
        return hook.cb_ == fn && hook.arg_ == arg;
578
252
      });
579
249
  if (it != promise_hooks_.end()) {
580
3
    it->enable_count_++;
581
252
    return;
582
  }
583
246
  promise_hooks_.push_back(PromiseHookCallback{fn, arg, 1});
584
585
246
  if (promise_hooks_.size() == 1) {
586
246
    isolate_->SetPromiseHook(EnvPromiseHook);
587
  }
588
}
589
590
211
bool Environment::RemovePromiseHook(promise_hook_func fn, void* arg) {
591
  auto it = std::find_if(
592
      promise_hooks_.begin(), promise_hooks_.end(),
593
211
      [&](const PromiseHookCallback& hook) {
594

211
        return hook.cb_ == fn && hook.arg_ == arg;
595
422
      });
596
597
211
  if (it == promise_hooks_.end()) return false;
598
599
211
  if (--it->enable_count_ > 0) return true;
600
601
208
  promise_hooks_.erase(it);
602
208
  if (promise_hooks_.empty()) {
603
208
    isolate_->SetPromiseHook(nullptr);
604
  }
605
606
208
  return true;
607
}
608
609
3977
void Environment::EnvPromiseHook(PromiseHookType type,
610
                                 Local<Promise> promise,
611
                                 Local<Value> parent) {
612
3977
  Local<Context> context = promise->CreationContext();
613
614
3977
  Environment* env = Environment::GetCurrent(context);
615
7954
  if (env == nullptr) return;
616
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
617
3977
                              "EnvPromiseHook", env);
618
7954
  for (const PromiseHookCallback& hook : env->promise_hooks_) {
619
3977
    hook.cb_(type, promise, parent, hook.arg_);
620
3977
  }
621
}
622
623
51916
void Environment::RunAndClearNativeImmediates() {
624
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
625
51916
                              "RunAndClearNativeImmediates", this);
626
51916
  size_t count = native_immediate_callbacks_.size();
627
51916
  if (count > 0) {
628
46271
    size_t ref_count = 0;
629
46271
    std::vector<NativeImmediateCallback> list;
630
46271
    native_immediate_callbacks_.swap(list);
631
46271
    auto drain_list = [&]() {
632
46271
      TryCatchScope try_catch(this);
633
95738
      for (auto it = list.begin(); it != list.end(); ++it) {
634
#ifdef DEBUG
635
        v8::SealHandleScope seal_handle_scope(isolate());
636
#endif
637
49468
        it->cb_(this, it->data_);
638
49467
        if (it->refed_)
639
27447
          ref_count++;
640
49467
        if (UNLIKELY(try_catch.HasCaught())) {
641
          if (!try_catch.HasTerminated())
642
            FatalException(isolate(), try_catch);
643
644
          // Bail out, remove the already executed callbacks from list
645
          // and set up a new TryCatch for the other pending callbacks.
646
          std::move_backward(it, list.end(), list.begin() + (list.end() - it));
647
          list.resize(list.end() - it);
648
          return true;
649
        }
650
      }
651
46270
      return false;
652
92541
    };
653
46271
    while (drain_list()) {}
654
655
    DCHECK_GE(immediate_info()->count(), count);
656
46270
    immediate_info()->count_dec(count);
657
46270
    immediate_info()->ref_count_dec(ref_count);
658
51915
  }
659
51915
}
660
661
662
7258
void Environment::ScheduleTimer(int64_t duration_ms) {
663
7258
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
664
7258
}
665
666
1265
void Environment::ToggleTimerRef(bool ref) {
667
1265
  if (ref) {
668
954
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
669
  } else {
670
311
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
671
  }
672
1265
}
673
674
5759
void Environment::RunTimers(uv_timer_t* handle) {
675
5759
  Environment* env = Environment::from_timer_handle(handle);
676
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
677
5759
                              "RunTimers", env);
678
679
5759
  if (!env->can_call_into_js())
680
    return;
681
682
11490
  HandleScope handle_scope(env->isolate());
683
11490
  Context::Scope context_scope(env->context());
684
685
5759
  Local<Object> process = env->process_object();
686
11490
  InternalCallbackScope scope(env, process, {0, 0});
687
688
5759
  Local<Function> cb = env->timers_callback_function();
689
  MaybeLocal<Value> ret;
690
5759
  Local<Value> arg = env->GetNow();
691
  // This code will loop until all currently due timers will process. It is
692
  // impossible for us to end up in an infinite loop due to how the JS-side
693
  // is structured.
694
5763
  do {
695
5788
    TryCatchScope try_catch(env);
696
5788
    try_catch.SetVerbose(true);
697
11576
    ret = cb->Call(env->context(), process, 1, &arg);
698

5763
  } while (ret.IsEmpty() && env->can_call_into_js());
699
700
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
701
  // is reset back to `true` after being previously set to `false` then this
702
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
703
  // timers corruption will occur and all timers behaviour will become
704
  // entirely unpredictable.
705
5734
  if (ret.IsEmpty())
706
3
    return;
707
708
  // To allow for less JS-C++ boundary crossing, the value returned from JS
709
  // serves a few purposes:
710
  // 1. If it's 0, no more timers exist and the handle should be unrefed
711
  // 2. If it's > 0, the value represents the next timer's expiry and there
712
  //    is at least one timer remaining that is refed.
713
  // 3. If it's < 0, the absolute value represents the next timer's expiry
714
  //    and there are no timers that are refed.
715
  int64_t expiry_ms =
716
22924
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
717
718
5731
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
719
720
5731
  if (expiry_ms != 0) {
721
    int64_t duration_ms =
722
5226
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
723
724
5226
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
725
726
5226
    if (expiry_ms > 0)
727
4852
      uv_ref(h);
728
    else
729
374
      uv_unref(h);
730
  } else {
731
505
    uv_unref(h);
732
5731
  }
733
}
734
735
736
563400
void Environment::CheckImmediate(uv_check_t* handle) {
737
563400
  Environment* env = Environment::from_immediate_check_handle(handle);
738
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
739
563401
                              "CheckImmediate", env);
740
741
563400
  if (env->immediate_info()->count() == 0)
742
511486
    return;
743
744
103825
  HandleScope scope(env->isolate());
745
103825
  Context::Scope context_scope(env->context());
746
747
51916
  env->RunAndClearNativeImmediates();
748
749
51915
  if (!env->can_call_into_js())
750
1
    return;
751
752
52430
  do {
753
    MakeCallback(env->isolate(),
754
                 env->process_object(),
755
                 env->immediate_callback_function(),
756
                 0,
757
                 nullptr,
758
104865
                 {0, 0}).ToLocalChecked();
759

52430
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
760
761
51909
  if (env->immediate_info()->ref_count() == 0)
762
77928
    env->ToggleImmediateRef(false);
763
}
764
765
73822
void Environment::ToggleImmediateRef(bool ref) {
766
73822
  if (ref) {
767
    // Idle handle is needed only to stop the event loop from blocking in poll.
768
149184
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
769
  } else {
770
26033
    uv_idle_stop(immediate_idle_handle());
771
  }
772
73822
}
773
774
775
340278
Local<Value> Environment::GetNow() {
776
340278
  uv_update_time(event_loop());
777
340278
  uint64_t now = uv_now(event_loop());
778
340278
  CHECK_GE(now, timer_base());
779
340278
  now -= timer_base();
780
340278
  if (now <= 0xffffffff)
781
680556
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
782
  else
783
    return Number::New(isolate(), static_cast<double>(now));
784
}
785
786
787
4403
void Environment::set_debug_categories(const std::string& cats, bool enabled) {
788
4403
  std::string debug_categories = cats;
789
4403
  while (!debug_categories.empty()) {
790
4
    std::string::size_type comma_pos = debug_categories.find(',');
791
4
    std::string wanted = ToLower(debug_categories.substr(0, comma_pos));
792
793
#define V(name)                                                          \
794
    {                                                                    \
795
      static const std::string available_category = ToLower(#name);      \
796
      if (available_category.find(wanted) != std::string::npos)          \
797
        set_debug_enabled(DebugCategory::name, enabled);                 \
798
    }
799
800
































































4
    DEBUG_CATEGORY_NAMES(V)
801
802
4
    if (comma_pos == std::string::npos)
803
4
      break;
804
    // Use everything after the `,` as the list for the next iteration.
805
    debug_categories = debug_categories.substr(comma_pos + 1);
806
4403
  }
807
4403
}
808
809
28
void CollectExceptionInfo(Environment* env,
810
                          Local<Object> obj,
811
                          int errorno,
812
                          const char* err_string,
813
                          const char* syscall,
814
                          const char* message,
815
                          const char* path,
816
                          const char* dest) {
817
  obj->Set(env->context(),
818
           env->errno_string(),
819
140
           Integer::New(env->isolate(), errorno)).FromJust();
820
821
  obj->Set(env->context(), env->code_string(),
822
140
           OneByteString(env->isolate(), err_string)).FromJust();
823
824
28
  if (message != nullptr) {
825
    obj->Set(env->context(), env->message_string(),
826
140
             OneByteString(env->isolate(), message)).FromJust();
827
  }
828
829
  Local<Value> path_buffer;
830
28
  if (path != nullptr) {
831
    path_buffer =
832
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
833
    obj->Set(env->context(), env->path_string(), path_buffer).FromJust();
834
  }
835
836
  Local<Value> dest_buffer;
837
28
  if (dest != nullptr) {
838
    dest_buffer =
839
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
840
    obj->Set(env->context(), env->dest_string(), dest_buffer).FromJust();
841
  }
842
843
28
  if (syscall != nullptr) {
844
    obj->Set(env->context(), env->syscall_string(),
845
140
             OneByteString(env->isolate(), syscall)).FromJust();
846
  }
847
28
}
848
849
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
850
                                         int errorno,
851
                                         const char* syscall,
852
                                         const char* message,
853
                                         const char* path,
854
                                         const char* dest) {
855

28
  if (!object->IsObject() || errorno == 0)
856
28
    return;
857
858
28
  Local<Object> obj = object.As<Object>();
859
28
  const char* err_string = uv_err_name(errorno);
860
861

28
  if (message == nullptr || message[0] == '\0') {
862
28
    message = uv_strerror(errorno);
863
  }
864
865
  node::CollectExceptionInfo(this, obj, errorno, err_string,
866
28
                             syscall, message, path, dest);
867
}
868
869
870
8
void Environment::AsyncHooks::grow_async_ids_stack() {
871
8
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
872
873
8
  env()->async_hooks_binding()->Set(
874
      env()->context(),
875
      env()->async_ids_stack_string(),
876
48
      async_ids_stack_.GetJSArray()).FromJust();
877
8
}
878
879
uv_key_t Environment::thread_local_env = {};
880
881
385
void Environment::Exit(int exit_code) {
882
385
  if (is_main_thread()) {
883
365
    stop_sub_worker_contexts();
884
364
    DisposePlatform();
885
364
    exit(exit_code);
886
  } else {
887
20
    worker_context_->Exit(exit_code);
888
  }
889
20
}
890
891
4399
void Environment::stop_sub_worker_contexts() {
892
8820
  while (!sub_worker_contexts_.empty()) {
893
23
    Worker* w = *sub_worker_contexts_.begin();
894
23
    remove_sub_worker_context(w);
895
23
    w->Exit(1);
896
23
    w->JoinThread();
897
  }
898
4398
}
899
900
32
void Environment::BuildEmbedderGraph(Isolate* isolate,
901
                                     EmbedderGraph* graph,
902
                                     void* data) {
903
32
  MemoryTracker tracker(isolate, graph);
904
93
  static_cast<Environment*>(data)->ForEachBaseObject([&](BaseObject* obj) {
905
93
    tracker.Track(obj);
906
125
  });
907
32
}
908
909
398876
char* Environment::Reallocate(char* data, size_t old_size, size_t size) {
910
  // If we know that the allocator is our ArrayBufferAllocator, we can let
911
  // if reallocate directly.
912
398876
  if (isolate_data()->uses_node_allocator()) {
913
    return static_cast<char*>(
914
398876
        isolate_data()->node_allocator()->Reallocate(data, old_size, size));
915
  }
916
  // Generic allocators do not provide a reallocation method; we need to
917
  // allocate a new chunk of memory and copy the data over.
918
  char* new_data = AllocateUnchecked(size);
919
  if (new_data == nullptr) return nullptr;
920
  memcpy(new_data, data, std::min(size, old_size));
921
  if (size > old_size)
922
    memset(new_data + old_size, 0, size - old_size);
923
  Free(data, old_size);
924
  return new_data;
925
}
926
927
// Not really any better place than env.cc at this moment.
928
40495
void BaseObject::DeleteMe(void* data) {
929
40495
  BaseObject* self = static_cast<BaseObject*>(data);
930
40495
  delete self;
931
40495
}
932
933
93
Local<Object> BaseObject::WrappedObject() const {
934
93
  return object();
935
}
936
937
93
bool BaseObject::IsRootNode() const {
938
186
  return !persistent_handle_.IsWeak();
939
}
940
941
}  // namespace node