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-09-16 22:31:04 Branches: 78 108 72.2 %

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
19347
static void PlatformWorkerThread(void* data) {
30
  std::unique_ptr<PlatformWorkerData>
31
19347
      worker_data(static_cast<PlatformWorkerData*>(data));
32
33
19525
  TaskQueue<Task>* pending_worker_tasks = worker_data->task_queue;
34

38986
  TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
35
                        "PlatformWorkerThread");
36
37
  // Notify the main thread that the platform worker is ready.
38
  {
39
19500
    Mutex::ScopedLock lock(*worker_data->platform_workers_mutex);
40
19578
    (*worker_data->pending_platform_workers)--;
41
19578
    worker_data->platform_workers_ready->Signal(lock);
42
  }
43
44
385670
  while (std::unique_ptr<Task> task = pending_worker_tasks->BlockingPop()) {
45
365808
    task->Run();
46
365695
    pending_worker_tasks->NotifyOfCompletion();
47
366103
  }
48
19562
}
49
50
}  // namespace
51
52
4889
class WorkerThreadsTaskRunner::DelayedTaskScheduler {
53
 public:
54
4893
  explicit DelayedTaskScheduler(TaskQueue<Task>* tasks)
55
4893
    : pending_worker_tasks_(tasks) {}
56
57
4893
  std::unique_ptr<uv_thread_t> Start() {
58
14679
    auto start_thread = [](void* data) {
59
4893
      static_cast<DelayedTaskScheduler*>(data)->Run();
60
14675
    };
61
4893
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
62
4893
    uv_sem_init(&ready_, 0);
63
4893
    CHECK_EQ(0, uv_thread_create(t.get(), start_thread, this));
64
4893
    uv_sem_wait(&ready_);
65
4893
    uv_sem_destroy(&ready_);
66
4893
    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
4889
  void Stop() {
76
4889
    tasks_.Push(std::unique_ptr<Task>(new StopTask(this)));
77
4889
    uv_async_send(&flush_tasks_);
78
4889
  }
79
80
 private:
81
4893
  void Run() {
82

9786
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
83
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
84
4893
    loop_.data = this;
85
4893
    CHECK_EQ(0, uv_loop_init(&loop_));
86
4893
    flush_tasks_.data = this;
87
4893
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
88
4893
    uv_sem_post(&ready_);
89
90
4893
    uv_run(&loop_, UV_RUN_DEFAULT);
91
4889
    CheckedUvLoopClose(&loop_);
92
4889
  }
93
94
4890
  static void FlushTasks(uv_async_t* flush_tasks) {
95
    DelayedTaskScheduler* scheduler =
96
4890
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
97
9780
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
98
4890
      task->Run();
99
4890
  }
100
101
9778
  class StopTask : public Task {
102
   public:
103
4889
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
104
105
4889
    void Run() override {
106
4889
      std::vector<uv_timer_t*> timers;
107
4889
      for (uv_timer_t* timer : scheduler_->timers_)
108
        timers.push_back(timer);
109
4889
      for (uv_timer_t* timer : timers)
110
        scheduler_->TakeTimerTask(timer);
111
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
112
19556
               [](uv_handle_t* handle) {});
113
4889
    }
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
4893
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
169
4893
  Mutex platform_workers_mutex;
170
9786
  ConditionVariable platform_workers_ready;
171
172
9786
  Mutex::ScopedLock lock(platform_workers_mutex);
173
4893
  int pending_platform_workers = thread_pool_size;
174
175
9786
  delayed_task_scheduler_ = std::make_unique<DelayedTaskScheduler>(
176
4893
      &pending_worker_tasks_);
177
4893
  threads_.push_back(delayed_task_scheduler_->Start());
178
179
24471
  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
19578
    };
184
19578
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
185
19578
    if (uv_thread_create(t.get(), PlatformWorkerThread,
186
19578
                         worker_data) != 0) {
187
      break;
188
    }
189
19578
    threads_.push_back(std::move(t));
190
19578
  }
191
192
  // Wait for platform workers to initialize before continuing with the
193
  // bootstrap.
194
25886
  while (pending_platform_workers > 0) {
195
16100
    platform_workers_ready.Wait(lock);
196
4893
  }
197
4893
}
198
199
366145
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
200
366145
  pending_worker_tasks_.Push(std::move(task));
201
366146
}
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
4889
void WorkerThreadsTaskRunner::Shutdown() {
213
4889
  pending_worker_tasks_.Stop();
214
4889
  delayed_task_scheduler_->Stop();
215
29340
  for (size_t i = 0; i < threads_.size(); i++) {
216
24451
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
217
  }
218
4889
}
219
220
5494
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
221
5494
  return threads_.size();
222
}
223
224
5110
PerIsolatePlatformData::PerIsolatePlatformData(
225
    Isolate* isolate, uv_loop_t* loop)
226
5110
  : loop_(loop) {
227
5110
  flush_tasks_ = new uv_async_t();
228
5110
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
229
5110
  flush_tasks_->data = static_cast<void*>(this);
230
5110
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
231
5110
}
232
233
6371
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
234
6371
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
235
6371
  platform_data->FlushForegroundTasksInternal();
236
6371
}
237
238
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
239
  UNREACHABLE();
240
}
241
242
7883
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
243
7883
  CHECK_NOT_NULL(flush_tasks_);
244
7883
  foreground_tasks_.Push(std::move(task));
245
7883
  uv_async_send(flush_tasks_);
246
7883
}
247
248
5195
void PerIsolatePlatformData::PostDelayedTask(
249
    std::unique_ptr<Task> task, double delay_in_seconds) {
250
5195
  CHECK_NOT_NULL(flush_tasks_);
251
5195
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
252
5195
  delayed->task = std::move(task);
253
5195
  delayed->platform_data = shared_from_this();
254
5195
  delayed->timeout = delay_in_seconds;
255
5195
  foreground_delayed_tasks_.Push(std::move(delayed));
256
5195
  uv_async_send(flush_tasks_);
257
5195
}
258
259
529
void PerIsolatePlatformData::PostNonNestableTask(std::unique_ptr<Task> task) {
260
529
  PostTask(std::move(task));
261
529
}
262
263
219
void PerIsolatePlatformData::PostNonNestableDelayedTask(
264
    std::unique_ptr<Task> task,
265
    double delay_in_seconds) {
266
219
  PostDelayedTask(std::move(task), delay_in_seconds);
267
219
}
268
269
598
PerIsolatePlatformData::~PerIsolatePlatformData() {
270
299
  Shutdown();
271
299
}
272
273
217
void PerIsolatePlatformData::AddShutdownCallback(void (*callback)(void*),
274
                                                 void* data) {
275
217
  shutdown_callbacks_.emplace_back(ShutdownCallback { callback, data });
276
217
}
277
278
5003
void PerIsolatePlatformData::Shutdown() {
279
5003
  if (flush_tasks_ == nullptr)
280
5302
    return;
281
282
4704
  CHECK_NULL(foreground_delayed_tasks_.Pop());
283
4704
  CHECK_NULL(foreground_tasks_.Pop());
284
4704
  CancelPendingDelayedTasks();
285
286
4704
  ShutdownCbList* copy = new ShutdownCbList(std::move(shutdown_callbacks_));
287
4704
  flush_tasks_->data = copy;
288
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
289
5138
           [](uv_handle_t* handle) {
290
    std::unique_ptr<ShutdownCbList> callbacks(
291
217
        static_cast<ShutdownCbList*>(handle->data));
292
434
    for (const auto& callback : *callbacks)
293
217
      callback.cb(callback.data);
294
217
    delete reinterpret_cast<uv_async_t*>(handle);
295
9842
  });
296
4704
  flush_tasks_ = nullptr;
297
}
298
299
4893
NodePlatform::NodePlatform(int thread_pool_size,
300
4893
                           TracingController* tracing_controller) {
301
4893
  if (tracing_controller) {
302
4893
    tracing_controller_ = tracing_controller;
303
  } else {
304
    tracing_controller_ = new TracingController();
305
  }
306
9786
  worker_thread_task_runner_ =
307
4893
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
308
4893
}
309
310
5110
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
311
5110
  Mutex::ScopedLock lock(per_isolate_mutex_);
312
10220
  std::shared_ptr<PerIsolatePlatformData> existing = per_isolate_[isolate];
313
5110
  CHECK(!existing);
314
10220
  per_isolate_[isolate] =
315
10220
      std::make_shared<PerIsolatePlatformData>(isolate, loop);
316
5110
}
317
318
4704
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
319
4704
  Mutex::ScopedLock lock(per_isolate_mutex_);
320
9408
  std::shared_ptr<PerIsolatePlatformData> existing = per_isolate_[isolate];
321
4704
  CHECK(existing);
322
4704
  existing->Shutdown();
323
9408
  per_isolate_.erase(isolate);
324
4704
}
325
326
217
void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate,
327
                                              void (*cb)(void*), void* data) {
328
217
  Mutex::ScopedLock lock(per_isolate_mutex_);
329
217
  auto it = per_isolate_.find(isolate);
330
217
  if (it == per_isolate_.end()) {
331
    CHECK(it->second);
332
    cb(data);
333
217
    return;
334
  }
335
217
  it->second->AddShutdownCallback(cb, data);
336
}
337
338
4889
void NodePlatform::Shutdown() {
339
4889
  worker_thread_task_runner_->Shutdown();
340
341
  {
342
4889
    Mutex::ScopedLock lock(per_isolate_mutex_);
343
4889
    per_isolate_.clear();
344
  }
345
4889
}
346
347
5494
int NodePlatform::NumberOfWorkerThreads() {
348
5494
  return worker_thread_task_runner_->NumberOfWorkerThreads();
349
}
350
351
7839
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
352
7839
  Isolate* isolate = Isolate::GetCurrent();
353
7839
  DebugSealHandleScope scope(isolate);
354
7839
  Environment* env = Environment::GetCurrent(isolate);
355
7839
  if (env != nullptr) {
356
    InternalCallbackScope cb_scope(env, Local<Object>(), { 0, 0 },
357
15676
                                   InternalCallbackScope::kAllowEmptyResource);
358
7838
    task->Run();
359
  } else {
360
1
    task->Run();
361
  }
362
7838
}
363
364
238
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
365
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
366
                         scheduled_delayed_tasks_.end(),
367
405
                         [task](const DelayedTaskPointer& delayed) -> bool {
368
405
          return delayed.get() == task;
369
238
      });
370
238
  CHECK_NE(it, scheduled_delayed_tasks_.end());
371
238
  scheduled_delayed_tasks_.erase(it);
372
238
}
373
374
238
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
375
238
  DelayedTask* delayed = static_cast<DelayedTask*>(handle->data);
376
238
  RunForegroundTask(std::move(delayed->task));
377
238
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
378
238
}
379
380
9407
void PerIsolatePlatformData::CancelPendingDelayedTasks() {
381
9407
  scheduled_delayed_tasks_.clear();
382
9407
}
383
384
9352
void NodePlatform::DrainTasks(Isolate* isolate) {
385
9352
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForIsolate(isolate);
386
387
11987
  do {
388
    // Worker tasks aren't associated with an Isolate.
389
11987
    worker_thread_task_runner_->BlockingDrain();
390
21339
  } while (per_isolate->FlushForegroundTasksInternal());
391
9352
}
392
393
18659
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
394
18659
  bool did_work = false;
395
396
  while (std::unique_ptr<DelayedTask> delayed =
397
23667
      foreground_delayed_tasks_.Pop()) {
398
5008
    did_work = true;
399
5008
    uint64_t delay_millis = llround(delayed->timeout * 1000);
400
401
5008
    delayed->timer.data = static_cast<void*>(delayed.get());
402
5008
    uv_timer_init(loop_, &delayed->timer);
403
    // Timers may not guarantee queue ordering of events with the same delay if
404
    // the delay is non-zero. This should not be a problem in practice.
405
5008
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
406
5008
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
407
408
5008
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
409
4860
                                          [](DelayedTask* delayed) {
410
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
411
5748
               [](uv_handle_t* handle) {
412
444
        delete static_cast<DelayedTask*>(handle->data);
413
10608
      });
414
9869
    });
415
5008
  }
416
  // Move all foreground tasks into a separate queue and flush that queue.
417
  // This way tasks that are posted while flushing the queue will be run on the
418
  // next call of FlushForegroundTasksInternal.
419
18658
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
420
44916
  while (!tasks.empty()) {
421
7601
    std::unique_ptr<Task> task = std::move(tasks.front());
422
7601
    tasks.pop();
423
7601
    did_work = true;
424
7601
    RunForegroundTask(std::move(task));
425
7600
  }
426
23666
  return did_work;
427
}
428
429
366145
void NodePlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
430
366145
  worker_thread_task_runner_->PostTask(std::move(task));
431
366146
}
432
433
1
void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
434
                                             double delay_in_seconds) {
435
1
  worker_thread_task_runner_->PostDelayedTask(std::move(task),
436
1
                                              delay_in_seconds);
437
1
}
438
439
440
std::shared_ptr<PerIsolatePlatformData>
441
37785
NodePlatform::ForIsolate(Isolate* isolate) {
442
37785
  Mutex::ScopedLock lock(per_isolate_mutex_);
443
37785
  std::shared_ptr<PerIsolatePlatformData> data = per_isolate_[isolate];
444
37785
  CHECK(data);
445
37785
  return data;
446
}
447
448
300
bool NodePlatform::FlushForegroundTasks(Isolate* isolate) {
449
300
  return ForIsolate(isolate)->FlushForegroundTasksInternal();
450
}
451
452
4703
void NodePlatform::CancelPendingDelayedTasks(Isolate* isolate) {
453
4703
  ForIsolate(isolate)->CancelPendingDelayedTasks();
454
4703
}
455
456
52592
bool NodePlatform::IdleTasksEnabled(Isolate* isolate) { return false; }
457
458
std::shared_ptr<v8::TaskRunner>
459
23430
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
460
23430
  return ForIsolate(isolate);
461
}
462
463
2750948
double NodePlatform::MonotonicallyIncreasingTime() {
464
  // Convert nanos to seconds.
465
2750948
  return uv_hrtime() / 1e9;
466
}
467
468
183177226
double NodePlatform::CurrentClockTimeMillis() {
469
183177226
  return SystemClockTimeMillis();
470
}
471
472
344290
TracingController* NodePlatform::GetTracingController() {
473
344290
  CHECK_NOT_NULL(tracing_controller_);
474
344290
  return tracing_controller_;
475
}
476
477
template <class T>
478
20006
TaskQueue<T>::TaskQueue()
479
    : lock_(), tasks_available_(), tasks_drained_(),
480
20006
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
481
482
template <class T>
483
384114
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
484
384114
  Mutex::ScopedLock scoped_lock(lock_);
485
384115
  outstanding_tasks_++;
486
384115
  task_queue_.push(std::move(task));
487
384115
  tasks_available_.Signal(scoped_lock);
488
384115
}
489
490
template <class T>
491
42854
std::unique_ptr<T> TaskQueue<T>::Pop() {
492
42854
  Mutex::ScopedLock scoped_lock(lock_);
493

42855
  if (task_queue_.empty()) {
494
32956
    return std::unique_ptr<T>(nullptr);
495
  }
496
19796
  std::unique_ptr<T> result = std::move(task_queue_.front());
497
9898
  task_queue_.pop();
498
52753
  return result;
499
}
500
501
template <class T>
502
385649
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
503
385649
  Mutex::ScopedLock scoped_lock(lock_);
504

1095970
  while (task_queue_.empty() && !stopped_) {
505
324536
    tasks_available_.Wait(scoped_lock);
506
  }
507
385709
  if (stopped_) {
508
19562
    return std::unique_ptr<T>(nullptr);
509
  }
510
732294
  std::unique_ptr<T> result = std::move(task_queue_.front());
511
366147
  task_queue_.pop();
512
751856
  return result;
513
}
514
515
template <class T>
516
365680
void TaskQueue<T>::NotifyOfCompletion() {
517
365680
  Mutex::ScopedLock scoped_lock(lock_);
518
366147
  if (--outstanding_tasks_ == 0) {
519
196562
    tasks_drained_.Broadcast(scoped_lock);
520
366147
  }
521
366007
}
522
523
template <class T>
524
11987
void TaskQueue<T>::BlockingDrain() {
525
11987
  Mutex::ScopedLock scoped_lock(lock_);
526
24846
  while (outstanding_tasks_ > 0) {
527
872
    tasks_drained_.Wait(scoped_lock);
528
11987
  }
529
11987
}
530
531
template <class T>
532
4889
void TaskQueue<T>::Stop() {
533
4889
  Mutex::ScopedLock scoped_lock(lock_);
534
4889
  stopped_ = true;
535
4889
  tasks_available_.Broadcast(scoped_lock);
536
4889
}
537
538
template <class T>
539
18658
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
540
18658
  Mutex::ScopedLock scoped_lock(lock_);
541
18659
  std::queue<std::unique_ptr<T>> result;
542
18659
  result.swap(task_queue_);
543
18659
  return result;
544
}
545
546
}  // namespace node