GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/inspector/main_thread_interface.cc Lines: 168 177 94.9 %
Date: 2019-02-23 22:23:05 Branches: 36 58 62.1 %

Line Branch Exec Source
1
#include "main_thread_interface.h"
2
3
#include "node_mutex.h"
4
#include "v8-inspector.h"
5
6
#include <functional>
7
#include <unicode/unistr.h>
8
#include "util-inl.h"
9
10
namespace node {
11
namespace inspector {
12
namespace {
13
14
using v8_inspector::StringView;
15
using v8_inspector::StringBuffer;
16
17
template <typename T>
18
class DeletableWrapper : public Deletable {
19
 public:
20
21
  explicit DeletableWrapper(std::unique_ptr<T> object)
21
21
                        : object_(std::move(object)) {}
22

42
  ~DeletableWrapper() override = default;
23
24
228
  static T* get(MainThreadInterface* thread, int id) {
25
    return
26
228
        static_cast<DeletableWrapper<T>*>(thread->GetObject(id))->object_.get();
27
  }
28
29
 private:
30
  std::unique_ptr<T> object_;
31
};
32
33
template <typename T>
34
21
std::unique_ptr<Deletable> WrapInDeletable(std::unique_ptr<T> object) {
35
  return std::unique_ptr<DeletableWrapper<T>>(
36
21
      new DeletableWrapper<T>(std::move(object)));
37
}
38
39
template <typename Factory>
40
34
class CreateObjectRequest : public Request {
41
 public:
42
17
  CreateObjectRequest(int object_id, Factory factory)
43
17
                      : object_id_(object_id), factory_(std::move(factory)) {}
44
45
17
  void Call(MainThreadInterface* thread) override {
46
17
    thread->AddObject(object_id_, WrapInDeletable(factory_(thread)));
47
17
  }
48
49
 private:
50
  int object_id_;
51
  Factory factory_;
52
};
53
54
template <typename Factory>
55
17
std::unique_ptr<Request> NewCreateRequest(int object_id, Factory factory) {
56
  return std::unique_ptr<Request>(
57
17
      new CreateObjectRequest<Factory>(object_id, std::move(factory)));
58
}
59
60
42
class DeleteRequest : public Request {
61
 public:
62
21
  explicit DeleteRequest(int object_id) : object_id_(object_id) {}
63
64
17
  void Call(MainThreadInterface* thread) override {
65
17
    thread->RemoveObject(object_id_);
66
17
  }
67
68
 private:
69
  int object_id_;
70
};
71
72
template <typename Target, typename Fn>
73

456
class CallRequest : public Request {
74
 public:
75
228
  CallRequest(int id, Fn fn) : id_(id), fn_(std::move(fn)) {}
76
77
228
  void Call(MainThreadInterface* thread) override {
78
228
    fn_(DeletableWrapper<Target>::get(thread, id_));
79
228
  }
80
81
 private:
82
  int id_;
83
  Fn fn_;
84
};
85
86
18238
class DispatchMessagesTask : public v8::Task {
87
 public:
88
9380
  explicit DispatchMessagesTask(MainThreadInterface* thread)
89
9380
                                : thread_(thread) {}
90
91
9122
  void Run() override {
92
9122
    thread_->DispatchMessages();
93
9121
  }
94
95
 private:
96
  MainThreadInterface* thread_;
97
};
98
99
void DisposePairCallback(uv_handle_t* ref) {
100
  using AsyncAndInterface = std::pair<uv_async_t, MainThreadInterface*>;
101
  AsyncAndInterface* pair = node::ContainerOf(
102
      &AsyncAndInterface::first, reinterpret_cast<uv_async_t*>(ref));
103
  delete pair;
104
}
105
106
template <typename T>
107
class AnotherThreadObjectReference {
108
 public:
109
21
  AnotherThreadObjectReference(
110
      std::shared_ptr<MainThreadHandle> thread, int object_id)
111
21
      : thread_(thread), object_id_(object_id) {}
112
113
  template <typename Factory>
114
17
  AnotherThreadObjectReference(
115
      std::shared_ptr<MainThreadHandle> thread, Factory factory)
116
17
      : AnotherThreadObjectReference(thread, thread->newObjectId()) {
117
17
    thread_->Post(NewCreateRequest(object_id_, std::move(factory)));
118
17
  }
119
  AnotherThreadObjectReference(AnotherThreadObjectReference&) = delete;
120
121
21
  ~AnotherThreadObjectReference() {
122
    // Disappearing thread may cause a memory leak
123
21
    thread_->Post(
124
42
        std::unique_ptr<DeleteRequest>(new DeleteRequest(object_id_)));
125
21
  }
126
127
  template <typename Fn>
128
228
  void Call(Fn fn) const {
129
    using Request = CallRequest<T, Fn>;
130
228
    thread_->Post(std::unique_ptr<Request>(
131
228
        new Request(object_id_, std::move(fn))));
132
228
  }
133
134
  template <typename Arg>
135
136
  void Call(void (T::*fn)(Arg), Arg argument) const {
136
136
    Call(std::bind(Apply<Arg>, std::placeholders::_1, fn, std::move(argument)));
137
136
  }
138
139
 private:
140
  // This has to use non-const reference to support std::bind with non-copyable
141
  // types
142
  template <typename Argument>
143
136
  static void Apply(T* target, void (T::*fn)(Argument),
144
    /* NOLINT (runtime/references) */ Argument& argument) {
145

136
    (target->*fn)(std::move(argument));
146
136
  }
147
148
  std::shared_ptr<MainThreadHandle> thread_;
149
  const int object_id_;
150
};
151
152
17
class MainThreadSessionState {
153
 public:
154
17
  MainThreadSessionState(MainThreadInterface* thread, bool prevent_shutdown)
155
                         : thread_(thread),
156
17
                           prevent_shutdown_(prevent_shutdown) {}
157
158
17
  static std::unique_ptr<MainThreadSessionState> Create(
159
      MainThreadInterface* thread, bool prevent_shutdown) {
160
    return std::unique_ptr<MainThreadSessionState>(
161
17
        new MainThreadSessionState(thread, prevent_shutdown));
162
  }
163
164
17
  void Connect(std::unique_ptr<InspectorSessionDelegate> delegate) {
165
17
    Agent* agent = thread_->inspector_agent();
166
17
    if (agent != nullptr)
167
17
      session_ = agent->Connect(std::move(delegate), prevent_shutdown_);
168
17
  }
169
170
119
  void Dispatch(std::unique_ptr<StringBuffer> message) {
171
119
    session_->Dispatch(message->string());
172
119
  }
173
174
 private:
175
  MainThreadInterface* thread_;
176
  bool prevent_shutdown_;
177
  std::unique_ptr<InspectorSession> session_;
178
};
179
180
34
class CrossThreadInspectorSession : public InspectorSession {
181
 public:
182
17
  CrossThreadInspectorSession(
183
      int id,
184
      std::shared_ptr<MainThreadHandle> thread,
185
      std::unique_ptr<InspectorSessionDelegate> delegate,
186
      bool prevent_shutdown)
187
      : state_(thread, std::bind(MainThreadSessionState::Create,
188
                                 std::placeholders::_1,
189
17
                                 prevent_shutdown)) {
190
17
    state_.Call(&MainThreadSessionState::Connect, std::move(delegate));
191
17
  }
192
193
119
  void Dispatch(const StringView& message) override {
194
    state_.Call(&MainThreadSessionState::Dispatch,
195
119
                StringBuffer::create(message));
196
119
  }
197
198
 private:
199
  AnotherThreadObjectReference<MainThreadSessionState> state_;
200
};
201
202
8
class ThreadSafeDelegate : public InspectorSessionDelegate {
203
 public:
204
4
  ThreadSafeDelegate(std::shared_ptr<MainThreadHandle> thread, int object_id)
205
4
                     : thread_(thread), delegate_(thread, object_id) {}
206
207
92
  void SendMessageToFrontend(const v8_inspector::StringView& message) override {
208
    delegate_.Call(
209
460
        [m = StringBuffer::create(message)]
210
92
        (InspectorSessionDelegate* delegate) {
211
92
      delegate->SendMessageToFrontend(m->string());
212
184
    });
213
92
  }
214
215
 private:
216
  std::shared_ptr<MainThreadHandle> thread_;
217
  AnotherThreadObjectReference<InspectorSessionDelegate> delegate_;
218
};
219
}  // namespace
220
221
222
4403
MainThreadInterface::MainThreadInterface(Agent* agent, uv_loop_t* loop,
223
                                         v8::Isolate* isolate,
224
                                         v8::Platform* platform)
225
                                         : agent_(agent), isolate_(isolate),
226
4403
                                           platform_(platform) {
227
4403
}
228
229
8068
MainThreadInterface::~MainThreadInterface() {
230
4034
  if (handle_)
231
4034
    handle_->Reset();
232
4034
}
233
234
// static
235
void MainThreadInterface::DispatchMessagesAsyncCallback(uv_async_t* async) {
236
  AsyncAndInterface* asyncAndInterface =
237
      node::ContainerOf(&AsyncAndInterface::first, async);
238
  asyncAndInterface->second->DispatchMessages();
239
}
240
241
// static
242
void MainThreadInterface::CloseAsync(AsyncAndInterface* pair) {
243
  uv_close(reinterpret_cast<uv_handle_t*>(&pair->first), DisposePairCallback);
244
}
245
246
9442
void MainThreadInterface::Post(std::unique_ptr<Request> request) {
247
9442
  Mutex::ScopedLock scoped_lock(requests_lock_);
248
9442
  bool needs_notify = requests_.empty();
249
9442
  requests_.push_back(std::move(request));
250
9442
  if (needs_notify) {
251

9380
    if (isolate_ != nullptr && platform_ != nullptr) {
252
      std::shared_ptr<v8::TaskRunner> taskrunner =
253
9380
        platform_->GetForegroundTaskRunner(isolate_);
254
9380
      taskrunner->PostTask(std::make_unique<DispatchMessagesTask>(this));
255
20034
      isolate_->RequestInterrupt([](v8::Isolate* isolate, void* thread) {
256
5327
        static_cast<MainThreadInterface*>(thread)->DispatchMessages();
257
29414
      }, this);
258
    }
259
  }
260
9442
  incoming_message_cond_.Broadcast(scoped_lock);
261
9442
}
262
263
74
bool MainThreadInterface::WaitForFrontendEvent() {
264
  // We allow DispatchMessages reentry as we enter the pause. This is important
265
  // to support debugging the code invoked by an inspector call, such
266
  // as Runtime.evaluate
267
74
  dispatching_messages_ = false;
268
74
  if (dispatching_message_queue_.empty()) {
269
74
    Mutex::ScopedLock scoped_lock(requests_lock_);
270
74
    while (requests_.empty()) incoming_message_cond_.Wait(scoped_lock);
271
  }
272
74
  return true;
273
}
274
275
14449
void MainThreadInterface::DispatchMessages() {
276
14449
  if (dispatching_messages_)
277
14572
    return;
278
14324
  dispatching_messages_ = true;
279
14324
  bool had_messages = false;
280
23703
  do {
281
23705
    if (dispatching_message_queue_.empty()) {
282
23704
      Mutex::ScopedLock scoped_lock(requests_lock_);
283
23704
      requests_.swap(dispatching_message_queue_);
284
    }
285
23704
    had_messages = !dispatching_message_queue_.empty();
286
56850
    while (!dispatching_message_queue_.empty()) {
287
9436
      MessageQueue::value_type task;
288
9436
      std::swap(dispatching_message_queue_.front(), task);
289
9424
      dispatching_message_queue_.pop_front();
290
9437
      task->Call(this);
291
9441
    }
292
  } while (had_messages);
293
14322
  dispatching_messages_ = false;
294
}
295
296
9247
std::shared_ptr<MainThreadHandle> MainThreadInterface::GetHandle() {
297
9247
  if (handle_ == nullptr)
298
4403
    handle_ = std::make_shared<MainThreadHandle>(this);
299
9247
  return handle_;
300
}
301
302
4628
void MainThreadInterface::AddObject(int id,
303
                                    std::unique_ptr<Deletable> object) {
304
4628
  CHECK_NOT_NULL(object);
305
4628
  managed_objects_[id] = std::move(object);
306
4628
}
307
308
4251
void MainThreadInterface::RemoveObject(int id) {
309
4251
  CHECK_EQ(1, managed_objects_.erase(id));
310
4251
}
311
312
228
Deletable* MainThreadInterface::GetObject(int id) {
313
228
  Deletable* pointer = GetObjectIfExists(id);
314
  // This would mean the object is requested after it was disposed, which is
315
  // a coding error.
316
228
  CHECK_NOT_NULL(pointer);
317
228
  return pointer;
318
}
319
320
232
Deletable* MainThreadInterface::GetObjectIfExists(int id) {
321
232
  auto iterator = managed_objects_.find(id);
322
232
  if (iterator == managed_objects_.end()) {
323
    return nullptr;
324
  }
325
232
  return iterator->second.get();
326
}
327
328
82650
std::unique_ptr<StringBuffer> Utf8ToStringView(const std::string& message) {
329
  icu::UnicodeString utf16 = icu::UnicodeString::fromUTF8(
330
82650
      icu::StringPiece(message.data(), message.length()));
331
82650
  StringView view(reinterpret_cast<const uint16_t*>(utf16.getBuffer()),
332
165300
                  utf16.length());
333
82650
  return StringBuffer::create(view);
334
}
335
336
17
std::unique_ptr<InspectorSession> MainThreadHandle::Connect(
337
    std::unique_ptr<InspectorSessionDelegate> delegate,
338
    bool prevent_shutdown) {
339
  return std::unique_ptr<InspectorSession>(
340
      new CrossThreadInspectorSession(++next_session_id_,
341
                                      shared_from_this(),
342
17
                                      std::move(delegate),
343
34
                                      prevent_shutdown));
344
}
345
346
9450
bool MainThreadHandle::Post(std::unique_ptr<Request> request) {
347
9450
  Mutex::ScopedLock scoped_lock(block_lock_);
348
9450
  if (!main_thread_)
349
8
    return false;
350
9442
  main_thread_->Post(std::move(request));
351
9442
  return true;
352
}
353
354
4034
void MainThreadHandle::Reset() {
355
4034
  Mutex::ScopedLock scoped_lock(block_lock_);
356
4034
  main_thread_ = nullptr;
357
4034
}
358
359
std::unique_ptr<InspectorSessionDelegate>
360
4
MainThreadHandle::MakeDelegateThreadSafe(
361
    std::unique_ptr<InspectorSessionDelegate> delegate) {
362
4
  int id = newObjectId();
363
4
  main_thread_->AddObject(id, WrapInDeletable(std::move(delegate)));
364
  return std::unique_ptr<InspectorSessionDelegate>(
365
4
      new ThreadSafeDelegate(shared_from_this(), id));
366
}
367
368
165
bool MainThreadHandle::Expired() {
369
165
  Mutex::ScopedLock scoped_lock(block_lock_);
370
165
  return main_thread_ == nullptr;
371
}
372
}  // namespace inspector
373
}  // namespace node