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: 79 170 46.5 %
Date: 2019-02-01 22:03:38 Branches: 18 62 29.0 %

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
  explicit DeletableWrapper(std::unique_ptr<T> object)
21
                        : object_(std::move(object)) {}
22
  ~DeletableWrapper() override = default;
23
24
  static T* get(MainThreadInterface* thread, int id) {
25
    return
26
        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
std::unique_ptr<Deletable> WrapInDeletable(std::unique_ptr<T> object) {
35
  return std::unique_ptr<DeletableWrapper<T>>(
36
      new DeletableWrapper<T>(std::move(object)));
37
}
38
39
template <typename Factory>
40
class CreateObjectRequest : public Request {
41
 public:
42
  CreateObjectRequest(int object_id, Factory factory)
43
                      : object_id_(object_id), factory_(std::move(factory)) {}
44
45
  void Call(MainThreadInterface* thread) {
46
    thread->AddObject(object_id_, WrapInDeletable(factory_(thread)));
47
  }
48
49
 private:
50
  int object_id_;
51
  Factory factory_;
52
};
53
54
template <typename Factory>
55
std::unique_ptr<Request> NewCreateRequest(int object_id, Factory factory) {
56
  return std::unique_ptr<Request>(
57
      new CreateObjectRequest<Factory>(object_id, std::move(factory)));
58
}
59
60
class DeleteRequest : public Request {
61
 public:
62
  explicit DeleteRequest(int object_id) : object_id_(object_id) {}
63
64
  void Call(MainThreadInterface* thread) override {
65
    thread->RemoveObject(object_id_);
66
  }
67
68
 private:
69
  int object_id_;
70
};
71
72
template <typename Target, typename Fn>
73
class CallRequest : public Request {
74
 public:
75
  CallRequest(int id, Fn fn) : id_(id), fn_(std::move(fn)) {}
76
77
  void Call(MainThreadInterface* thread) override {
78
    fn_(DeletableWrapper<Target>::get(thread, id_));
79
  }
80
81
 private:
82
  int id_;
83
  Fn fn_;
84
};
85
86
632
class DispatchMessagesTask : public v8::Task {
87
 public:
88
326
  explicit DispatchMessagesTask(MainThreadInterface* thread)
89
326
                                : thread_(thread) {}
90
91
316
  void Run() override {
92
316
    thread_->DispatchMessages();
93
316
  }
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
  AnotherThreadObjectReference(
110
      std::shared_ptr<MainThreadHandle> thread, int object_id)
111
      : thread_(thread), object_id_(object_id) {}
112
113
  template <typename Factory>
114
  AnotherThreadObjectReference(
115
      std::shared_ptr<MainThreadHandle> thread, Factory factory)
116
      : AnotherThreadObjectReference(thread, thread->newObjectId()) {
117
    thread_->Post(NewCreateRequest(object_id_, std::move(factory)));
118
  }
119
  AnotherThreadObjectReference(AnotherThreadObjectReference&) = delete;
120
121
  ~AnotherThreadObjectReference() {
122
    // Disappearing thread may cause a memory leak
123
    thread_->Post(
124
        std::unique_ptr<DeleteRequest>(new DeleteRequest(object_id_)));
125
  }
126
127
  template <typename Fn>
128
  void Call(Fn fn) const {
129
    using Request = CallRequest<T, Fn>;
130
    thread_->Post(std::unique_ptr<Request>(
131
        new Request(object_id_, std::move(fn))));
132
  }
133
134
  template <typename Arg>
135
  void Call(void (T::*fn)(Arg), Arg argument) const {
136
    Call(std::bind(Apply<Arg>, std::placeholders::_1, fn, std::move(argument)));
137
  }
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
  static void Apply(T* target, void (T::*fn)(Argument),
144
    /* NOLINT (runtime/references) */ Argument& argument) {
145
    (target->*fn)(std::move(argument));
146
  }
147
148
  std::shared_ptr<MainThreadHandle> thread_;
149
  const int object_id_;
150
};
151
152
class MainThreadSessionState {
153
 public:
154
  MainThreadSessionState(MainThreadInterface* thread, bool prevent_shutdown)
155
                         : thread_(thread),
156
                           prevent_shutdown_(prevent_shutdown) {}
157
158
  static std::unique_ptr<MainThreadSessionState> Create(
159
      MainThreadInterface* thread, bool prevent_shutdown) {
160
    return std::unique_ptr<MainThreadSessionState>(
161
        new MainThreadSessionState(thread, prevent_shutdown));
162
  }
163
164
  void Connect(std::unique_ptr<InspectorSessionDelegate> delegate) {
165
    Agent* agent = thread_->inspector_agent();
166
    if (agent != nullptr)
167
      session_ = agent->Connect(std::move(delegate), prevent_shutdown_);
168
  }
169
170
  void Dispatch(std::unique_ptr<StringBuffer> message) {
171
    session_->Dispatch(message->string());
172
  }
173
174
 private:
175
  MainThreadInterface* thread_;
176
  bool prevent_shutdown_;
177
  std::unique_ptr<InspectorSession> session_;
178
};
179
180
class CrossThreadInspectorSession : public InspectorSession {
181
 public:
182
  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
                                 prevent_shutdown)) {
190
    state_.Call(&MainThreadSessionState::Connect, std::move(delegate));
191
  }
192
193
  void Dispatch(const StringView& message) override {
194
    state_.Call(&MainThreadSessionState::Dispatch,
195
                StringBuffer::create(message));
196
  }
197
198
 private:
199
  AnotherThreadObjectReference<MainThreadSessionState> state_;
200
};
201
202
class ThreadSafeDelegate : public InspectorSessionDelegate {
203
 public:
204
  ThreadSafeDelegate(std::shared_ptr<MainThreadHandle> thread, int object_id)
205
                     : thread_(thread), delegate_(thread, object_id) {}
206
207
  void SendMessageToFrontend(const v8_inspector::StringView& message) override {
208
    delegate_.Call(
209
        [m = StringBuffer::create(message)]
210
        (InspectorSessionDelegate* delegate) {
211
      delegate->SendMessageToFrontend(m->string());
212
    });
213
  }
214
215
 private:
216
  std::shared_ptr<MainThreadHandle> thread_;
217
  AnotherThreadObjectReference<InspectorSessionDelegate> delegate_;
218
};
219
}  // namespace
220
221
222
163
MainThreadInterface::MainThreadInterface(Agent* agent, uv_loop_t* loop,
223
                                         v8::Isolate* isolate,
224
                                         v8::Platform* platform)
225
                                         : agent_(agent), isolate_(isolate),
226
163
                                           platform_(platform) {
227
163
  main_thread_request_.reset(new AsyncAndInterface(uv_async_t(), this));
228
163
  CHECK_EQ(0, uv_async_init(loop, &main_thread_request_->first,
229
                            DispatchMessagesAsyncCallback));
230
  // Inspector uv_async_t should not prevent main loop shutdown.
231
163
  uv_unref(reinterpret_cast<uv_handle_t*>(&main_thread_request_->first));
232
163
}
233
234
306
MainThreadInterface::~MainThreadInterface() {
235
153
  if (handle_)
236
153
    handle_->Reset();
237
153
}
238
239
// static
240
263
void MainThreadInterface::DispatchMessagesAsyncCallback(uv_async_t* async) {
241
  AsyncAndInterface* asyncAndInterface =
242
263
      node::ContainerOf(&AsyncAndInterface::first, async);
243
263
  asyncAndInterface->second->DispatchMessages();
244
263
}
245
246
// static
247
153
void MainThreadInterface::CloseAsync(AsyncAndInterface* pair) {
248
153
  uv_close(reinterpret_cast<uv_handle_t*>(&pair->first), DisposePairCallback);
249
153
}
250
251
326
void MainThreadInterface::Post(std::unique_ptr<Request> request) {
252
326
  Mutex::ScopedLock scoped_lock(requests_lock_);
253
326
  bool needs_notify = requests_.empty();
254
326
  requests_.push_back(std::move(request));
255
326
  if (needs_notify) {
256
326
    CHECK_EQ(0, uv_async_send(&main_thread_request_->first));
257

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