GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_platform.cc Lines: 330 338 97.6 %
Date: 2019-10-08 22:34:21 Branches: 76 104 73.1 %

Line Branch Exec Source
1
#include "node_platform.h"
2
#include "node_internals.h"
3
4
#include "env-inl.h"
5
#include "debug_utils.h"
6
#include <algorithm>
7
#include <cmath>
8
#include <memory>
9
10
namespace node {
11
12
using v8::Isolate;
13
using v8::Local;
14
using v8::Object;
15
using v8::Platform;
16
using v8::Task;
17
using node::tracing::TracingController;
18
19
namespace {
20
21
struct PlatformWorkerData {
22
  TaskQueue<Task>* task_queue;
23
  Mutex* platform_workers_mutex;
24
  ConditionVariable* platform_workers_ready;
25
  int* pending_platform_workers;
26
  int id;
27
};
28
29
19606
static void PlatformWorkerThread(void* data) {
30
  std::unique_ptr<PlatformWorkerData>
31
19606
      worker_data(static_cast<PlatformWorkerData*>(data));
32
33
19635
  TaskQueue<Task>* pending_worker_tasks = worker_data->task_queue;
34

39044
  TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
35
                        "PlatformWorkerThread");
36
37
  // Notify the main thread that the platform worker is ready.
38
  {
39
19579
    Mutex::ScopedLock lock(*worker_data->platform_workers_mutex);
40
19706
    (*worker_data->pending_platform_workers)--;
41
19706
    worker_data->platform_workers_ready->Signal(lock);
42
  }
43
44
418891
  while (std::unique_ptr<Task> task = pending_worker_tasks->BlockingPop()) {
45
398704
    task->Run();
46
398701
    pending_worker_tasks->NotifyOfCompletion();
47
399195
  }
48
19690
}
49
50
}  // namespace
51
52
4921
class WorkerThreadsTaskRunner::DelayedTaskScheduler {
53
 public:
54
4925
  explicit DelayedTaskScheduler(TaskQueue<Task>* tasks)
55
4925
    : pending_worker_tasks_(tasks) {}
56
57
4925
  std::unique_ptr<uv_thread_t> Start() {
58
14775
    auto start_thread = [](void* data) {
59
4925
      static_cast<DelayedTaskScheduler*>(data)->Run();
60
14771
    };
61
4925
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
62
4925
    uv_sem_init(&ready_, 0);
63
4925
    CHECK_EQ(0, uv_thread_create(t.get(), start_thread, this));
64
4925
    uv_sem_wait(&ready_);
65
4925
    uv_sem_destroy(&ready_);
66
4925
    return t;
67
  }
68
69
1
  void PostDelayedTask(std::unique_ptr<Task> task, double delay_in_seconds) {
70
1
    tasks_.Push(std::unique_ptr<Task>(new ScheduleTask(this, std::move(task),
71
1
                                                       delay_in_seconds)));
72
1
    uv_async_send(&flush_tasks_);
73
1
  }
74
75
4921
  void Stop() {
76
4921
    tasks_.Push(std::unique_ptr<Task>(new StopTask(this)));
77
4921
    uv_async_send(&flush_tasks_);
78
4921
  }
79
80
 private:
81
4925
  void Run() {
82

9850
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
83
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
84
4925
    loop_.data = this;
85
4925
    CHECK_EQ(0, uv_loop_init(&loop_));
86
4925
    flush_tasks_.data = this;
87
4925
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
88
4925
    uv_sem_post(&ready_);
89
90
4925
    uv_run(&loop_, UV_RUN_DEFAULT);
91
4921
    CheckedUvLoopClose(&loop_);
92
4921
  }
93
94
4922
  static void FlushTasks(uv_async_t* flush_tasks) {
95
    DelayedTaskScheduler* scheduler =
96
4922
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
97
9844
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
98
4922
      task->Run();
99
4922
  }
100
101
9842
  class StopTask : public Task {
102
   public:
103
4921
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
104
105
4921
    void Run() override {
106
4921
      std::vector<uv_timer_t*> timers;
107
4921
      for (uv_timer_t* timer : scheduler_->timers_)
108
        timers.push_back(timer);
109
4921
      for (uv_timer_t* timer : timers)
110
        scheduler_->TakeTimerTask(timer);
111
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
112
19684
               [](uv_handle_t* handle) {});
113
4921
    }
114
115
   private:
116
     DelayedTaskScheduler* scheduler_;
117
  };
118
119
2
  class ScheduleTask : public Task {
120
   public:
121
1
    ScheduleTask(DelayedTaskScheduler* scheduler,
122
                 std::unique_ptr<Task> task,
123
                 double delay_in_seconds)
124
      : scheduler_(scheduler),
125
1
        task_(std::move(task)),
126
2
        delay_in_seconds_(delay_in_seconds) {}
127
128
1
    void Run() override {
129
1
      uint64_t delay_millis = llround(delay_in_seconds_ * 1000);
130
1
      std::unique_ptr<uv_timer_t> timer(new uv_timer_t());
131
1
      CHECK_EQ(0, uv_timer_init(&scheduler_->loop_, timer.get()));
132
1
      timer->data = task_.release();
133
1
      CHECK_EQ(0, uv_timer_start(timer.get(), RunTask, delay_millis, 0));
134
1
      scheduler_->timers_.insert(timer.release());
135
1
    }
136
137
   private:
138
    DelayedTaskScheduler* scheduler_;
139
    std::unique_ptr<Task> task_;
140
    double delay_in_seconds_;
141
  };
142
143
1
  static void RunTask(uv_timer_t* timer) {
144
    DelayedTaskScheduler* scheduler =
145
1
        ContainerOf(&DelayedTaskScheduler::loop_, timer->loop);
146
1
    scheduler->pending_worker_tasks_->Push(scheduler->TakeTimerTask(timer));
147
1
  }
148
149
1
  std::unique_ptr<Task> TakeTimerTask(uv_timer_t* timer) {
150
1
    std::unique_ptr<Task> task(static_cast<Task*>(timer->data));
151
1
    uv_timer_stop(timer);
152
3
    uv_close(reinterpret_cast<uv_handle_t*>(timer), [](uv_handle_t* handle) {
153
1
      delete reinterpret_cast<uv_timer_t*>(handle);
154
4
    });
155
1
    timers_.erase(timer);
156
1
    return task;
157
  }
158
159
  uv_sem_t ready_;
160
  TaskQueue<Task>* pending_worker_tasks_;
161
162
  TaskQueue<Task> tasks_;
163
  uv_loop_t loop_;
164
  uv_async_t flush_tasks_;
165
  std::unordered_set<uv_timer_t*> timers_;
166
};
167
168
4925
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
169
4925
  Mutex platform_workers_mutex;
170
9850
  ConditionVariable platform_workers_ready;
171
172
9850
  Mutex::ScopedLock lock(platform_workers_mutex);
173
4925
  int pending_platform_workers = thread_pool_size;
174
175
9850
  delayed_task_scheduler_ = std::make_unique<DelayedTaskScheduler>(
176
4925
      &pending_worker_tasks_);
177
4925
  threads_.push_back(delayed_task_scheduler_->Start());
178
179
24631
  for (int i = 0; i < thread_pool_size; i++) {
180
    PlatformWorkerData* worker_data = new PlatformWorkerData{
181
      &pending_worker_tasks_, &platform_workers_mutex,
182
      &platform_workers_ready, &pending_platform_workers, i
183
19706
    };
184
19706
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
185
19706
    if (uv_thread_create(t.get(), PlatformWorkerThread,
186
19706
                         worker_data) != 0) {
187
      break;
188
    }
189
19706
    threads_.push_back(std::move(t));
190
19706
  }
191
192
  // Wait for platform workers to initialize before continuing with the
193
  // bootstrap.
194
26746
  while (pending_platform_workers > 0) {
195
16896
    platform_workers_ready.Wait(lock);
196
4925
  }
197
4925
}
198
199
399260
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
200
399260
  pending_worker_tasks_.Push(std::move(task));
201
399260
}
202
203
1
void WorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<Task> task,
204
                                              double delay_in_seconds) {
205
1
  delayed_task_scheduler_->PostDelayedTask(std::move(task), delay_in_seconds);
206
1
}
207
208
11987
void WorkerThreadsTaskRunner::BlockingDrain() {
209
11987
  pending_worker_tasks_.BlockingDrain();
210
11987
}
211
212
4921
void WorkerThreadsTaskRunner::Shutdown() {
213
4921
  pending_worker_tasks_.Stop();
214
4921
  delayed_task_scheduler_->Stop();
215
29532
  for (size_t i = 0; i < threads_.size(); i++) {
216
24611
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
217
  }
218
4921
}
219
220
5556
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
221
5556
  return threads_.size();
222
}
223
224
5143
PerIsolatePlatformData::PerIsolatePlatformData(
225
    Isolate* isolate, uv_loop_t* loop)
226
5143
  : loop_(loop) {
227
5143
  flush_tasks_ = new uv_async_t();
228
5143
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
229
5143
  flush_tasks_->data = static_cast<void*>(this);
230
5143
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
231
5143
}
232
233
6349
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
234
6349
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
235
6349
  platform_data->FlushForegroundTasksInternal();
236
6348
}
237
238
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
239
  UNREACHABLE();
240
}
241
242
8132
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
243
8132
  CHECK_NOT_NULL(flush_tasks_);
244
8132
  foreground_tasks_.Push(std::move(task));
245
8132
  uv_async_send(flush_tasks_);
246
8132
}
247
248
5273
void PerIsolatePlatformData::PostDelayedTask(
249
    std::unique_ptr<Task> task, double delay_in_seconds) {
250
5273
  CHECK_NOT_NULL(flush_tasks_);
251
5273
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
252
5273
  delayed->task = std::move(task);
253
5273
  delayed->platform_data = shared_from_this();
254
5273
  delayed->timeout = delay_in_seconds;
255
5273
  foreground_delayed_tasks_.Push(std::move(delayed));
256
5273
  uv_async_send(flush_tasks_);
257
5273
}
258
259
582
void PerIsolatePlatformData::PostNonNestableTask(std::unique_ptr<Task> task) {
260
582
  PostTask(std::move(task));
261
582
}
262
263
245
void PerIsolatePlatformData::PostNonNestableDelayedTask(
264
    std::unique_ptr<Task> task,
265
    double delay_in_seconds) {
266
245
  PostDelayedTask(std::move(task), delay_in_seconds);
267
245
}
268
269
574
PerIsolatePlatformData::~PerIsolatePlatformData() {
270
287
  Shutdown();
271
287
}
272
273
511
void PerIsolatePlatformData::AddShutdownCallback(void (*callback)(void*),
274
                                                 void* data) {
275
511
  shutdown_callbacks_.emplace_back(ShutdownCallback { callback, data });
276
511
}
277
278
5014
void PerIsolatePlatformData::Shutdown() {
279
5014
  if (flush_tasks_ == nullptr)
280
5301
    return;
281
282
  // While there should be no V8 tasks in the queues at this point, it is
283
  // possible that Node.js-internal tasks from e.g. the inspector are still
284
  // lying around. We clear these queues and ignore the return value,
285
  // effectively deleting the tasks instead of running them.
286
4727
  foreground_delayed_tasks_.PopAll();
287
4727
  foreground_tasks_.PopAll();
288
289
4727
  CancelPendingDelayedTasks();
290
291
4727
  ShutdownCbList* copy = new ShutdownCbList(std::move(shutdown_callbacks_));
292
4727
  flush_tasks_->data = copy;
293
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
294
5163
           [](uv_handle_t* handle) {
295
    std::unique_ptr<ShutdownCbList> callbacks(
296
218
        static_cast<ShutdownCbList*>(handle->data));
297
641
    for (const auto& callback : *callbacks)
298
423
      callback.cb(callback.data);
299
218
    delete reinterpret_cast<uv_async_t*>(handle);
300
9890
  });
301
4727
  flush_tasks_ = nullptr;
302
}
303
304
4925
NodePlatform::NodePlatform(int thread_pool_size,
305
4925
                           TracingController* tracing_controller) {
306
4925
  if (tracing_controller) {
307
4925
    tracing_controller_ = tracing_controller;
308
  } else {
309
    tracing_controller_ = new TracingController();
310
  }
311
9850
  worker_thread_task_runner_ =
312
4925
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
313
4925
}
314
315
5143
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
316
5143
  Mutex::ScopedLock lock(per_isolate_mutex_);
317
10286
  std::shared_ptr<PerIsolatePlatformData> existing = per_isolate_[isolate];
318
5143
  CHECK(!existing);
319
10286
  per_isolate_[isolate] =
320
10286
      std::make_shared<PerIsolatePlatformData>(isolate, loop);
321
5143
}
322
323
4727
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
324
4727
  Mutex::ScopedLock lock(per_isolate_mutex_);
325
9454
  std::shared_ptr<PerIsolatePlatformData> existing = per_isolate_[isolate];
326
4727
  CHECK(existing);
327
4727
  existing->Shutdown();
328
9454
  per_isolate_.erase(isolate);
329
4727
}
330
331
511
void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate,
332
                                              void (*cb)(void*), void* data) {
333
511
  Mutex::ScopedLock lock(per_isolate_mutex_);
334
511
  auto it = per_isolate_.find(isolate);
335
511
  if (it == per_isolate_.end()) {
336
    CHECK(it->second);
337
    cb(data);
338
511
    return;
339
  }
340
511
  it->second->AddShutdownCallback(cb, data);
341
}
342
343
4921
void NodePlatform::Shutdown() {
344
4921
  worker_thread_task_runner_->Shutdown();
345
346
  {
347
4921
    Mutex::ScopedLock lock(per_isolate_mutex_);
348
4921
    per_isolate_.clear();
349
  }
350
4921
}
351
352
5556
int NodePlatform::NumberOfWorkerThreads() {
353
5556
  return worker_thread_task_runner_->NumberOfWorkerThreads();
354
}
355
356
8103
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
357
8103
  Isolate* isolate = Isolate::GetCurrent();
358
8103
  DebugSealHandleScope scope(isolate);
359
8103
  Environment* env = Environment::GetCurrent(isolate);
360
8103
  if (env != nullptr) {
361
    InternalCallbackScope cb_scope(env, Local<Object>(), { 0, 0 },
362
16204
                                   InternalCallbackScope::kAllowEmptyResource);
363
8102
    task->Run();
364
  } else {
365
1
    task->Run();
366
  }
367
8102
}
368
369
257
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
370
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
371
                         scheduled_delayed_tasks_.end(),
372
451
                         [task](const DelayedTaskPointer& delayed) -> bool {
373
451
          return delayed.get() == task;
374
257
      });
375
257
  CHECK_NE(it, scheduled_delayed_tasks_.end());
376
257
  scheduled_delayed_tasks_.erase(it);
377
257
}
378
379
257
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
380
257
  DelayedTask* delayed = static_cast<DelayedTask*>(handle->data);
381
257
  RunForegroundTask(std::move(delayed->task));
382
257
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
383
257
}
384
385
9453
void PerIsolatePlatformData::CancelPendingDelayedTasks() {
386
9453
  scheduled_delayed_tasks_.clear();
387
9453
}
388
389
9395
void NodePlatform::DrainTasks(Isolate* isolate) {
390
9395
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForIsolate(isolate);
391
392
11987
  do {
393
    // Worker tasks aren't associated with an Isolate.
394
11987
    worker_thread_task_runner_->BlockingDrain();
395
21382
  } while (per_isolate->FlushForegroundTasksInternal());
396
9395
}
397
398
18635
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
399
18635
  bool did_work = false;
400
401
  while (std::unique_ptr<DelayedTask> delayed =
402
23706
      foreground_delayed_tasks_.Pop()) {
403
5071
    did_work = true;
404
5071
    uint64_t delay_millis = llround(delayed->timeout * 1000);
405
406
5071
    delayed->timer.data = static_cast<void*>(delayed.get());
407
5071
    uv_timer_init(loop_, &delayed->timer);
408
    // Timers may not guarantee queue ordering of events with the same delay if
409
    // the delay is non-zero. This should not be a problem in practice.
410
5071
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
411
5071
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
412
413
5071
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
414
4922
                                          [](DelayedTask* delayed) {
415
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
416
5846
               [](uv_handle_t* handle) {
417
462
        delete static_cast<DelayedTask*>(handle->data);
418
10768
      });
419
9993
    });
420
5071
  }
421
  // Move all foreground tasks into a separate queue and flush that queue.
422
  // This way tasks that are posted while flushing the queue will be run on the
423
  // next call of FlushForegroundTasksInternal.
424
18635
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
425
45115
  while (!tasks.empty()) {
426
7846
    std::unique_ptr<Task> task = std::move(tasks.front());
427
7846
    tasks.pop();
428
7846
    did_work = true;
429
7846
    RunForegroundTask(std::move(task));
430
7845
  }
431
23704
  return did_work;
432
}
433
434
399260
void NodePlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
435
399260
  worker_thread_task_runner_->PostTask(std::move(task));
436
399260
}
437
438
1
void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
439
                                             double delay_in_seconds) {
440
1
  worker_thread_task_runner_->PostDelayedTask(std::move(task),
441
1
                                              delay_in_seconds);
442
1
}
443
444
445
std::shared_ptr<PerIsolatePlatformData>
446
38223
NodePlatform::ForIsolate(Isolate* isolate) {
447
38223
  Mutex::ScopedLock lock(per_isolate_mutex_);
448
38224
  std::shared_ptr<PerIsolatePlatformData> data = per_isolate_[isolate];
449
38224
  CHECK(data);
450
38224
  return data;
451
}
452
453
299
bool NodePlatform::FlushForegroundTasks(Isolate* isolate) {
454
299
  return ForIsolate(isolate)->FlushForegroundTasksInternal();
455
}
456
457
4726
void NodePlatform::CancelPendingDelayedTasks(Isolate* isolate) {
458
4726
  ForIsolate(isolate)->CancelPendingDelayedTasks();
459
4726
}
460
461
54479
bool NodePlatform::IdleTasksEnabled(Isolate* isolate) { return false; }
462
463
std::shared_ptr<v8::TaskRunner>
464
23803
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
465
23803
  return ForIsolate(isolate);
466
}
467
468
3436739
double NodePlatform::MonotonicallyIncreasingTime() {
469
  // Convert nanos to seconds.
470
3436739
  return uv_hrtime() / 1e9;
471
}
472
473
146657701
double NodePlatform::CurrentClockTimeMillis() {
474
146657701
  return SystemClockTimeMillis();
475
}
476
477
345143
TracingController* NodePlatform::GetTracingController() {
478
345143
  CHECK_NOT_NULL(tracing_controller_);
479
345143
  return tracing_controller_;
480
}
481
482
template <class T>
483
20136
TaskQueue<T>::TaskQueue()
484
    : lock_(), tasks_available_(), tasks_drained_(),
485
20136
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
486
487
template <class T>
488
417588
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
489
417588
  Mutex::ScopedLock scoped_lock(lock_);
490
417588
  outstanding_tasks_++;
491
417588
  task_queue_.push(std::move(task));
492
417588
  tasks_available_.Signal(scoped_lock);
493
417588
}
494
495
template <class T>
496
33550
std::unique_ptr<T> TaskQueue<T>::Pop() {
497
33550
  Mutex::ScopedLock scoped_lock(lock_);
498

33550
  if (task_queue_.empty()) {
499
23557
    return std::unique_ptr<T>(nullptr);
500
  }
501
19986
  std::unique_ptr<T> result = std::move(task_queue_.front());
502
9993
  task_queue_.pop();
503
43543
  return result;
504
}
505
506
template <class T>
507
418867
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
508
418867
  Mutex::ScopedLock scoped_lock(lock_);
509

1199709
  while (task_queue_.empty() && !stopped_) {
510
361795
    tasks_available_.Wait(scoped_lock);
511
  }
512
418949
  if (stopped_) {
513
19690
    return std::unique_ptr<T>(nullptr);
514
  }
515
798518
  std::unique_ptr<T> result = std::move(task_queue_.front());
516
399259
  task_queue_.pop();
517
818208
  return result;
518
}
519
520
template <class T>
521
398668
void TaskQueue<T>::NotifyOfCompletion() {
522
398668
  Mutex::ScopedLock scoped_lock(lock_);
523
399259
  if (--outstanding_tasks_ == 0) {
524
224174
    tasks_drained_.Broadcast(scoped_lock);
525
399259
  }
526
399129
}
527
528
template <class T>
529
11987
void TaskQueue<T>::BlockingDrain() {
530
11987
  Mutex::ScopedLock scoped_lock(lock_);
531
24856
  while (outstanding_tasks_ > 0) {
532
882
    tasks_drained_.Wait(scoped_lock);
533
11987
  }
534
11987
}
535
536
template <class T>
537
4921
void TaskQueue<T>::Stop() {
538
4921
  Mutex::ScopedLock scoped_lock(lock_);
539
4921
  stopped_ = true;
540
4921
  tasks_available_.Broadcast(scoped_lock);
541
4921
}
542
543
template <class T>
544
28089
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
545
28089
  Mutex::ScopedLock scoped_lock(lock_);
546
28089
  std::queue<std::unique_ptr<T>> result;
547
28088
  result.swap(task_queue_);
548
28089
  return result;
549
}
550
551
}  // namespace node