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: 317 328 96.6 %
Date: 2019-02-13 22:28:58 Branches: 76 102 74.5 %

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 "util.h"
7
#include <algorithm>
8
9
namespace node {
10
11
using v8::HandleScope;
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
16908
static void PlatformWorkerThread(void* data) {
30
  std::unique_ptr<PlatformWorkerData>
31
16908
      worker_data(static_cast<PlatformWorkerData*>(data));
32
33
17052
  TaskQueue<Task>* pending_worker_tasks = worker_data->task_queue;
34

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

4269
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
83
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
84
4269
    loop_.data = this;
85
4269
    CHECK_EQ(0, uv_loop_init(&loop_));
86
4269
    flush_tasks_.data = this;
87
4269
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
88
4269
    uv_sem_post(&ready_);
89
90
4269
    uv_run(&loop_, UV_RUN_DEFAULT);
91
4264
    CheckedUvLoopClose(&loop_);
92
4264
  }
93
94
4265
  static void FlushTasks(uv_async_t* flush_tasks) {
95
    DelayedTaskScheduler* scheduler =
96
4265
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
97
8530
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
98
4265
      task->Run();
99
4265
  }
100
101
8528
  class StopTask : public Task {
102
   public:
103
4264
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
104
105
4264
    void Run() override {
106
4264
      std::vector<uv_timer_t*> timers;
107
4264
      for (uv_timer_t* timer : scheduler_->timers_)
108
        timers.push_back(timer);
109
4264
      for (uv_timer_t* timer : timers)
110
        scheduler_->TakeTimerTask(timer);
111
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
112
17056
               [](uv_handle_t* handle) {});
113
4264
    }
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
      uint64_t delay_millis =
130
1
          static_cast<uint64_t>(delay_in_seconds_ + 0.5) * 1000;
131
1
      std::unique_ptr<uv_timer_t> timer(new uv_timer_t());
132
1
      CHECK_EQ(0, uv_timer_init(&scheduler_->loop_, timer.get()));
133
1
      timer->data = task_.release();
134
1
      CHECK_EQ(0, uv_timer_start(timer.get(), RunTask, delay_millis, 0));
135
1
      scheduler_->timers_.insert(timer.release());
136
1
    }
137
138
   private:
139
    DelayedTaskScheduler* scheduler_;
140
    std::unique_ptr<Task> task_;
141
    double delay_in_seconds_;
142
  };
143
144
1
  static void RunTask(uv_timer_t* timer) {
145
    DelayedTaskScheduler* scheduler =
146
1
        ContainerOf(&DelayedTaskScheduler::loop_, timer->loop);
147
1
    scheduler->pending_worker_tasks_->Push(scheduler->TakeTimerTask(timer));
148
1
  }
149
150
1
  std::unique_ptr<Task> TakeTimerTask(uv_timer_t* timer) {
151
1
    std::unique_ptr<Task> task(static_cast<Task*>(timer->data));
152
1
    uv_timer_stop(timer);
153
3
    uv_close(reinterpret_cast<uv_handle_t*>(timer), [](uv_handle_t* handle) {
154
1
      delete reinterpret_cast<uv_timer_t*>(handle);
155
4
    });
156
1
    timers_.erase(timer);
157
1
    return task;
158
  }
159
160
  uv_sem_t ready_;
161
  TaskQueue<v8::Task>* pending_worker_tasks_;
162
163
  TaskQueue<v8::Task> tasks_;
164
  uv_loop_t loop_;
165
  uv_async_t flush_tasks_;
166
  std::unordered_set<uv_timer_t*> timers_;
167
};
168
169
4269
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
170
4269
  Mutex platform_workers_mutex;
171
8538
  ConditionVariable platform_workers_ready;
172
173
8538
  Mutex::ScopedLock lock(platform_workers_mutex);
174
4269
  int pending_platform_workers = thread_pool_size;
175
176
  delayed_task_scheduler_.reset(
177
4269
      new DelayedTaskScheduler(&pending_worker_tasks_));
178
4269
  threads_.push_back(delayed_task_scheduler_->Start());
179
180
21351
  for (int i = 0; i < thread_pool_size; i++) {
181
    PlatformWorkerData* worker_data = new PlatformWorkerData{
182
      &pending_worker_tasks_, &platform_workers_mutex,
183
      &platform_workers_ready, &pending_platform_workers, i
184
17082
    };
185
17082
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
186
17082
    if (uv_thread_create(t.get(), PlatformWorkerThread,
187
17082
                         worker_data) != 0) {
188
      break;
189
    }
190
17082
    threads_.push_back(std::move(t));
191
17082
  }
192
193
  // Wait for platform workers to initialize before continuing with the
194
  // bootstrap.
195
22481
  while (pending_platform_workers > 0) {
196
13943
    platform_workers_ready.Wait(lock);
197
4269
  }
198
4269
}
199
200
156940
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
201
156940
  pending_worker_tasks_.Push(std::move(task));
202
156940
}
203
204
1
void WorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<v8::Task> task,
205
                                              double delay_in_seconds) {
206
1
  delayed_task_scheduler_->PostDelayedTask(std::move(task), delay_in_seconds);
207
1
}
208
209
9966
void WorkerThreadsTaskRunner::BlockingDrain() {
210
9966
  pending_worker_tasks_.BlockingDrain();
211
9966
}
212
213
4264
void WorkerThreadsTaskRunner::Shutdown() {
214
4264
  pending_worker_tasks_.Stop();
215
4264
  delayed_task_scheduler_->Stop();
216
25590
  for (size_t i = 0; i < threads_.size(); i++) {
217
21326
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
218
  }
219
4264
}
220
221
4752
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
222
4752
  return threads_.size();
223
}
224
225
4423
PerIsolatePlatformData::PerIsolatePlatformData(
226
    v8::Isolate* isolate, uv_loop_t* loop)
227
4423
  : loop_(loop) {
228
4423
  flush_tasks_ = new uv_async_t();
229
4423
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
230
4423
  flush_tasks_->data = static_cast<void*>(this);
231
4423
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
232
4423
}
233
234
7713
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
235
7713
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
236
7713
  platform_data->FlushForegroundTasksInternal();
237
7712
}
238
239
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
240
  UNREACHABLE();
241
}
242
243
11085
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
244
11085
  CHECK_NOT_NULL(flush_tasks_);
245
11085
  foreground_tasks_.Push(std::move(task));
246
11085
  uv_async_send(flush_tasks_);
247
11085
}
248
249
176
void PerIsolatePlatformData::PostDelayedTask(
250
    std::unique_ptr<Task> task, double delay_in_seconds) {
251
176
  CHECK_NOT_NULL(flush_tasks_);
252
176
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
253
176
  delayed->task = std::move(task);
254
176
  delayed->platform_data = shared_from_this();
255
176
  delayed->timeout = delay_in_seconds;
256
176
  foreground_delayed_tasks_.Push(std::move(delayed));
257
176
  uv_async_send(flush_tasks_);
258
176
}
259
260
7768
PerIsolatePlatformData::~PerIsolatePlatformData() {
261
3884
  Shutdown();
262
3884
}
263
264
7936
void PerIsolatePlatformData::Shutdown() {
265
7936
  if (flush_tasks_ == nullptr)
266
11820
    return;
267
268
4052
  CHECK_NULL(foreground_delayed_tasks_.Pop());
269
4052
  CHECK_NULL(foreground_tasks_.Pop());
270
4052
  CancelPendingDelayedTasks();
271
272
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
273
4360
           [](uv_handle_t* handle) {
274
154
    delete reinterpret_cast<uv_async_t*>(handle);
275
8412
  });
276
4052
  flush_tasks_ = nullptr;
277
}
278
279
4420
void PerIsolatePlatformData::ref() {
280
4420
  ref_count_++;
281
4420
}
282
283
8104
int PerIsolatePlatformData::unref() {
284
8104
  return --ref_count_;
285
}
286
287
4269
NodePlatform::NodePlatform(int thread_pool_size,
288
4269
                           TracingController* tracing_controller) {
289
4269
  if (tracing_controller) {
290
4269
    tracing_controller_ = tracing_controller;
291
  } else {
292
    tracing_controller_ = new TracingController();
293
  }
294
8538
  worker_thread_task_runner_ =
295
4269
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
296
4269
}
297
298
8843
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
299
8843
  Mutex::ScopedLock lock(per_isolate_mutex_);
300
17686
  std::shared_ptr<PerIsolatePlatformData> existing = per_isolate_[isolate];
301
8843
  if (existing) {
302
4420
    CHECK_EQ(loop, existing->event_loop());
303
4420
    existing->ref();
304
  } else {
305
8846
    per_isolate_[isolate] =
306
4423
        std::make_shared<PerIsolatePlatformData>(isolate, loop);
307
8843
  }
308
8843
}
309
310
8104
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
311
8104
  Mutex::ScopedLock lock(per_isolate_mutex_);
312
16208
  std::shared_ptr<PerIsolatePlatformData> existing = per_isolate_[isolate];
313
8104
  CHECK(existing);
314
8104
  if (existing->unref() == 0) {
315
4052
    existing->Shutdown();
316
4052
    per_isolate_.erase(isolate);
317
8104
  }
318
8104
}
319
320
4264
void NodePlatform::Shutdown() {
321
4264
  worker_thread_task_runner_->Shutdown();
322
323
  {
324
4264
    Mutex::ScopedLock lock(per_isolate_mutex_);
325
4264
    per_isolate_.clear();
326
  }
327
4264
}
328
329
4752
int NodePlatform::NumberOfWorkerThreads() {
330
4752
  return worker_thread_task_runner_->NumberOfWorkerThreads();
331
}
332
333
10477
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
334
10477
  Isolate* isolate = Isolate::GetCurrent();
335
10477
  HandleScope scope(isolate);
336
10477
  Environment* env = Environment::GetCurrent(isolate);
337
  InternalCallbackScope cb_scope(env, Local<Object>(), { 0, 0 },
338
31431
                                 InternalCallbackScope::kAllowEmptyResource);
339
20951
  task->Run();
340
10474
}
341
342
3
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
343
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
344
                         scheduled_delayed_tasks_.end(),
345
3
                         [task](const DelayedTaskPointer& delayed) -> bool {
346
3
          return delayed.get() == task;
347
3
      });
348
3
  CHECK_NE(it, scheduled_delayed_tasks_.end());
349
3
  scheduled_delayed_tasks_.erase(it);
350
3
}
351
352
3
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
353
3
  DelayedTask* delayed = static_cast<DelayedTask*>(handle->data);
354
3
  RunForegroundTask(std::move(delayed->task));
355
3
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
356
3
}
357
358
8103
void PerIsolatePlatformData::CancelPendingDelayedTasks() {
359
8103
  scheduled_delayed_tasks_.clear();
360
8103
}
361
362
8094
void NodePlatform::DrainTasks(Isolate* isolate) {
363
8094
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForIsolate(isolate);
364
365
9966
  do {
366
    // Worker tasks aren't associated with an Isolate.
367
9966
    worker_thread_task_runner_->BlockingDrain();
368
18058
  } while (per_isolate->FlushForegroundTasksInternal());
369
8092
}
370
371
169883
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
372
169883
  bool did_work = false;
373
374
  while (std::unique_ptr<DelayedTask> delayed =
375
170059
      foreground_delayed_tasks_.Pop()) {
376
176
    did_work = true;
377
    uint64_t delay_millis =
378
176
        static_cast<uint64_t>(delayed->timeout + 0.5) * 1000;
379
176
    delayed->timer.data = static_cast<void*>(delayed.get());
380
176
    uv_timer_init(loop_, &delayed->timer);
381
    // Timers may not guarantee queue ordering of events with the same delay if
382
    // the delay is non-zero. This should not be a problem in practice.
383
176
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
384
176
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
385
386
176
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
387
172
                                          [](DelayedTask* delayed) {
388
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
389
180
               [](uv_handle_t* handle) {
390
4
        delete static_cast<DelayedTask*>(handle->data);
391
352
      });
392
348
    });
393
176
  }
394
  // Move all foreground tasks into a separate queue and flush that queue.
395
  // This way tasks that are posted while flushing the queue will be run on the
396
  // next call of FlushForegroundTasksInternal.
397
169883
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
398
350237
  while (!tasks.empty()) {
399
10474
    std::unique_ptr<Task> task = std::move(tasks.front());
400
10474
    tasks.pop();
401
10474
    did_work = true;
402
10474
    RunForegroundTask(std::move(task));
403
10471
  }
404
170056
  return did_work;
405
}
406
407
156940
void NodePlatform::CallOnWorkerThread(std::unique_ptr<v8::Task> task) {
408
156940
  worker_thread_task_runner_->PostTask(std::move(task));
409
156940
}
410
411
1
void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<v8::Task> task,
412
                                             double delay_in_seconds) {
413
1
  worker_thread_task_runner_->PostDelayedTask(std::move(task),
414
1
                                              delay_in_seconds);
415
1
}
416
417
418
std::shared_ptr<PerIsolatePlatformData>
419
184308
NodePlatform::ForIsolate(Isolate* isolate) {
420
184308
  Mutex::ScopedLock lock(per_isolate_mutex_);
421
184308
  std::shared_ptr<PerIsolatePlatformData> data = per_isolate_[isolate];
422
184308
  CHECK(data);
423
184308
  return data;
424
}
425
426
void NodePlatform::CallOnForegroundThread(Isolate* isolate, Task* task) {
427
  ForIsolate(isolate)->PostTask(std::unique_ptr<Task>(task));
428
}
429
430
void NodePlatform::CallDelayedOnForegroundThread(Isolate* isolate,
431
                                                 Task* task,
432
                                                 double delay_in_seconds) {
433
  ForIsolate(isolate)->PostDelayedTask(
434
    std::unique_ptr<Task>(task), delay_in_seconds);
435
}
436
437
152204
bool NodePlatform::FlushForegroundTasks(v8::Isolate* isolate) {
438
152204
  return ForIsolate(isolate)->FlushForegroundTasksInternal();
439
}
440
441
4051
void NodePlatform::CancelPendingDelayedTasks(v8::Isolate* isolate) {
442
4051
  ForIsolate(isolate)->CancelPendingDelayedTasks();
443
4051
}
444
445
36716
bool NodePlatform::IdleTasksEnabled(Isolate* isolate) { return false; }
446
447
std::shared_ptr<v8::TaskRunner>
448
19959
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
449
19959
  return ForIsolate(isolate);
450
}
451
452
1406700
double NodePlatform::MonotonicallyIncreasingTime() {
453
  // Convert nanos to seconds.
454
1406700
  return uv_hrtime() / 1e9;
455
}
456
457
102677445
double NodePlatform::CurrentClockTimeMillis() {
458
102677445
  return SystemClockTimeMillis();
459
}
460
461
229839
TracingController* NodePlatform::GetTracingController() {
462
229839
  CHECK_NOT_NULL(tracing_controller_);
463
229839
  return tracing_controller_;
464
}
465
466
template <class T>
467
17384
TaskQueue<T>::TaskQueue()
468
    : lock_(), tasks_available_(), tasks_drained_(),
469
17384
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
470
471
template <class T>
472
172467
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
473
172467
  Mutex::ScopedLock scoped_lock(lock_);
474
172467
  outstanding_tasks_++;
475
172467
  task_queue_.push(std::move(task));
476
172467
  tasks_available_.Signal(scoped_lock);
477
172467
}
478
479
template <class T>
480
186693
std::unique_ptr<T> TaskQueue<T>::Pop() {
481
186693
  Mutex::ScopedLock scoped_lock(lock_);
482

186693
  if (task_queue_.empty()) {
483
182252
    return std::unique_ptr<T>(nullptr);
484
  }
485
8882
  std::unique_ptr<T> result = std::move(task_queue_.front());
486
4441
  task_queue_.pop();
487
191134
  return result;
488
}
489
490
template <class T>
491
173997
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
492
173997
  Mutex::ScopedLock scoped_lock(lock_);
493

505181
  while (task_queue_.empty() && !stopped_) {
494
157155
    tasks_available_.Wait(scoped_lock);
495
  }
496
174003
  if (stopped_) {
497
17062
    return std::unique_ptr<T>(nullptr);
498
  }
499
313882
  std::unique_ptr<T> result = std::move(task_queue_.front());
500
156941
  task_queue_.pop();
501
330944
  return result;
502
}
503
504
template <class T>
505
156713
void TaskQueue<T>::NotifyOfCompletion() {
506
156713
  Mutex::ScopedLock scoped_lock(lock_);
507
156941
  if (--outstanding_tasks_ == 0) {
508
104772
    tasks_drained_.Broadcast(scoped_lock);
509
156941
  }
510
156908
}
511
512
template <class T>
513
9966
void TaskQueue<T>::BlockingDrain() {
514
9966
  Mutex::ScopedLock scoped_lock(lock_);
515
20026
  while (outstanding_tasks_ > 0) {
516
94
    tasks_drained_.Wait(scoped_lock);
517
9966
  }
518
9966
}
519
520
template <class T>
521
4264
void TaskQueue<T>::Stop() {
522
4264
  Mutex::ScopedLock scoped_lock(lock_);
523
4264
  stopped_ = true;
524
4264
  tasks_available_.Broadcast(scoped_lock);
525
4264
}
526
527
template <class T>
528
169883
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
529
169883
  Mutex::ScopedLock scoped_lock(lock_);
530
169883
  std::queue<std::unique_ptr<T>> result;
531
169883
  result.swap(task_queue_);
532
169883
  return result;
533
}
534
535
}  // namespace node