GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/inspector_io.cc Lines: 165 165 100.0 %
Date: 2019-08-17 22:35:23 Branches: 34 48 70.8 %

Line Branch Exec Source
1
#include "inspector_io.h"
2
3
#include "inspector_socket_server.h"
4
#include "inspector/main_thread_interface.h"
5
#include "inspector/node_string.h"
6
#include "base_object-inl.h"
7
#include "debug_utils.h"
8
#include "node.h"
9
#include "node_crypto.h"
10
#include "node_internals.h"
11
#include "node_mutex.h"
12
#include "v8-inspector.h"
13
#include "util-inl.h"
14
#include "zlib.h"
15
16
#include <deque>
17
#include <cstring>
18
#include <vector>
19
20
namespace node {
21
namespace inspector {
22
namespace {
23
using v8_inspector::StringBuffer;
24
using v8_inspector::StringView;
25
26
// kKill closes connections and stops the server, kStop only stops the server
27
enum class TransportAction { kKill, kSendMessage, kStop };
28
29
79
std::string ScriptPath(uv_loop_t* loop, const std::string& script_name) {
30
79
  std::string script_path;
31
32
79
  if (!script_name.empty()) {
33
    uv_fs_t req;
34
60
    req.ptr = nullptr;
35
60
    if (0 == uv_fs_realpath(loop, &req, script_name.c_str(), nullptr)) {
36
59
      CHECK_NOT_NULL(req.ptr);
37
59
      script_path = std::string(static_cast<char*>(req.ptr));
38
    }
39
60
    uv_fs_req_cleanup(&req);
40
  }
41
42
79
  return script_path;
43
}
44
45
// UUID RFC: https://www.ietf.org/rfc/rfc4122.txt
46
// Used ver 4 - with numbers
47
79
std::string GenerateID() {
48
  uint16_t buffer[8];
49
79
  CHECK(crypto::EntropySource(reinterpret_cast<unsigned char*>(buffer),
50
                              sizeof(buffer)));
51
52
  char uuid[256];
53
  snprintf(uuid, sizeof(uuid), "%04x%04x-%04x-%04x-%04x-%04x%04x%04x",
54
79
           buffer[0],  // time_low
55
79
           buffer[1],  // time_mid
56
79
           buffer[2],  // time_low
57
79
           (buffer[3] & 0x0fff) | 0x4000,  // time_hi_and_version
58
79
           (buffer[4] & 0x3fff) | 0x8000,  // clk_seq_hi clk_seq_low
59
79
           buffer[5],  // node
60
79
           buffer[6],
61
632
           buffer[7]);
62
79
  return uuid;
63
}
64
65
921
class RequestToServer {
66
 public:
67
921
  RequestToServer(TransportAction action,
68
                  int session_id,
69
                  std::unique_ptr<v8_inspector::StringBuffer> message)
70
                  : action_(action),
71
                    session_id_(session_id),
72
921
                    message_(std::move(message)) {}
73
74
919
  void Dispatch(InspectorSocketServer* server) const {
75

919
    switch (action_) {
76
      case TransportAction::kKill:
77
14
        server->TerminateConnections();
78
        // Fallthrough
79
      case TransportAction::kStop:
80
88
        server->Stop();
81
88
        break;
82
      case TransportAction::kSendMessage:
83
        server->Send(
84
            session_id_,
85
831
            protocol::StringUtil::StringViewToUtf8(message_->string()));
86
831
        break;
87
    }
88
919
  }
89
90
 private:
91
  TransportAction action_;
92
  int session_id_;
93
  std::unique_ptr<v8_inspector::StringBuffer> message_;
94
};
95
96
class RequestQueueData {
97
 public:
98
  using MessageQueue = std::deque<RequestToServer>;
99
100
79
  explicit RequestQueueData(uv_loop_t* loop)
101
79
                            : handle_(std::make_shared<RequestQueue>(this)) {
102
1723
    int err = uv_async_init(loop, &async_, [](uv_async_t* async) {
103
      RequestQueueData* wrapper =
104
822
          node::ContainerOf(&RequestQueueData::async_, async);
105
822
      wrapper->DoDispatch();
106
1802
    });
107
79
    CHECK_EQ(0, err);
108
79
  }
109
110
  static void CloseAndFree(RequestQueueData* queue);
111
112
921
  void Post(int session_id,
113
            TransportAction action,
114
            std::unique_ptr<StringBuffer> message) {
115
921
    Mutex::ScopedLock scoped_lock(state_lock_);
116
921
    bool notify = messages_.empty();
117
921
    messages_.emplace_back(action, session_id, std::move(message));
118
921
    if (notify) {
119
824
      CHECK_EQ(0, uv_async_send(&async_));
120
824
      incoming_message_cond_.Broadcast(scoped_lock);
121
921
    }
122
921
  }
123
124
  void Wait() {
125
    Mutex::ScopedLock scoped_lock(state_lock_);
126
    if (messages_.empty()) {
127
      incoming_message_cond_.Wait(scoped_lock);
128
    }
129
  }
130
131
79
  void SetServer(InspectorSocketServer* server) {
132
79
    server_ = server;
133
79
  }
134
135
96
  std::shared_ptr<RequestQueue> handle() {
136
96
    return handle_;
137
  }
138
139
 private:
140
79
  ~RequestQueueData() = default;
141
142
822
  MessageQueue GetMessages() {
143
822
    Mutex::ScopedLock scoped_lock(state_lock_);
144
822
    MessageQueue messages;
145
822
    messages_.swap(messages);
146
822
    return messages;
147
  }
148
149
822
  void DoDispatch() {
150
822
    if (server_ == nullptr)
151
822
      return;
152
1741
    for (const auto& request : GetMessages()) {
153
919
      request.Dispatch(server_);
154
822
    }
155
  }
156
157
  std::shared_ptr<RequestQueue> handle_;
158
  uv_async_t async_;
159
  InspectorSocketServer* server_ = nullptr;
160
  MessageQueue messages_;
161
  Mutex state_lock_;  // Locked before mutating the queue.
162
  ConditionVariable incoming_message_cond_;
163
};
164
}  // namespace
165
166
45
class RequestQueue {
167
 public:
168
79
  explicit RequestQueue(RequestQueueData* data) : data_(data) {}
169
170
79
  void Reset() {
171
79
    Mutex::ScopedLock scoped_lock(lock_);
172
79
    data_ = nullptr;
173
79
  }
174
175
950
  void Post(int session_id,
176
            TransportAction action,
177
            std::unique_ptr<StringBuffer> message) {
178
950
    Mutex::ScopedLock scoped_lock(lock_);
179
950
    if (data_ != nullptr)
180
921
      data_->Post(session_id, action, std::move(message));
181
950
  }
182
183
79
  bool Expired() {
184
79
    Mutex::ScopedLock scoped_lock(lock_);
185
79
    return data_ == nullptr;
186
  }
187
188
 private:
189
  RequestQueueData* data_;
190
  Mutex lock_;
191
};
192
193
34
class IoSessionDelegate : public InspectorSessionDelegate {
194
 public:
195
17
  explicit IoSessionDelegate(std::shared_ptr<RequestQueue> queue, int id)
196
17
                             : request_queue_(queue), id_(id) { }
197
831
  void SendMessageToFrontend(const v8_inspector::StringView& message) override {
198
    request_queue_->Post(id_, TransportAction::kSendMessage,
199
831
                         StringBuffer::create(message));
200
831
  }
201
202
 private:
203
  std::shared_ptr<RequestQueue> request_queue_;
204
  int id_;
205
};
206
207
// Passed to InspectorSocketServer to handle WS inspector protocol events,
208
// mostly session start, message received, and session end.
209
class InspectorIoDelegate: public node::inspector::SocketServerDelegate {
210
 public:
211
  InspectorIoDelegate(std::shared_ptr<RequestQueueData> queue,
212
                      std::shared_ptr<MainThreadHandle> main_threade,
213
                      const std::string& target_id,
214
                      const std::string& script_path,
215
                      const std::string& script_name);
216
158
  ~InspectorIoDelegate() override = default;
217
218
  void StartSession(int session_id, const std::string& target_id) override;
219
  void MessageReceived(int session_id, const std::string& message) override;
220
  void EndSession(int session_id) override;
221
222
  std::vector<std::string> GetTargetIds() override;
223
  std::string GetTargetTitle(const std::string& id) override;
224
  std::string GetTargetUrl(const std::string& id) override;
225
79
  void AssignServer(InspectorSocketServer* server) override {
226
79
    request_queue_->SetServer(server);
227
79
  }
228
229
 private:
230
  std::shared_ptr<RequestQueueData> request_queue_;
231
  std::shared_ptr<MainThreadHandle> main_thread_;
232
  std::unordered_map<int, std::unique_ptr<InspectorSession>> sessions_;
233
  const std::string script_name_;
234
  const std::string script_path_;
235
  const std::string target_id_;
236
};
237
238
// static
239
79
std::unique_ptr<InspectorIo> InspectorIo::Start(
240
    std::shared_ptr<MainThreadHandle> main_thread,
241
    const std::string& path,
242
    std::shared_ptr<HostPort> host_port,
243
    const InspectPublishUid& inspect_publish_uid) {
244
  auto io = std::unique_ptr<InspectorIo>(
245
      new InspectorIo(main_thread,
246
                      path,
247
                      host_port,
248
79
                      inspect_publish_uid));
249
79
  if (io->request_queue_->Expired()) {  // Thread is not running
250
1
    return nullptr;
251
  }
252
78
  return io;
253
}
254
255
79
InspectorIo::InspectorIo(std::shared_ptr<MainThreadHandle> main_thread,
256
                         const std::string& path,
257
                         std::shared_ptr<HostPort> host_port,
258
                         const InspectPublishUid& inspect_publish_uid)
259
    : main_thread_(main_thread),
260
      host_port_(host_port),
261
      inspect_publish_uid_(inspect_publish_uid),
262
      thread_(),
263
      script_name_(path),
264
79
      id_(GenerateID()) {
265
79
  Mutex::ScopedLock scoped_lock(thread_start_lock_);
266
79
  CHECK_EQ(uv_thread_create(&thread_, InspectorIo::ThreadMain, this), 0);
267
79
  thread_start_condition_.Wait(scoped_lock);
268
79
}
269
270
90
InspectorIo::~InspectorIo() {
271
45
  request_queue_->Post(0, TransportAction::kKill, nullptr);
272
45
  int err = uv_thread_join(&thread_);
273
45
  CHECK_EQ(err, 0);
274
45
}
275
276
74
void InspectorIo::StopAcceptingNewConnections() {
277
74
  request_queue_->Post(0, TransportAction::kStop, nullptr);
278
74
}
279
280
// static
281
79
void InspectorIo::ThreadMain(void* io) {
282
79
  static_cast<InspectorIo*>(io)->ThreadMain();
283
79
}
284
285
79
void InspectorIo::ThreadMain() {
286
  uv_loop_t loop;
287
79
  loop.data = nullptr;
288
79
  int err = uv_loop_init(&loop);
289
79
  CHECK_EQ(err, 0);
290
79
  std::shared_ptr<RequestQueueData> queue(new RequestQueueData(&loop),
291
158
                                          RequestQueueData::CloseAndFree);
292
158
  std::string script_path = ScriptPath(&loop, script_name_);
293
  std::unique_ptr<InspectorIoDelegate> delegate(
294
      new InspectorIoDelegate(queue, main_thread_, id_,
295
158
                              script_path, script_name_));
296
79
  InspectorSocketServer server(std::move(delegate),
297
                               &loop,
298
79
                               host_port_->host(),
299
                               host_port_->port(),
300
237
                               inspect_publish_uid_);
301
79
  request_queue_ = queue->handle();
302
  // Its lifetime is now that of the server delegate
303
79
  queue.reset();
304
  {
305
79
    Mutex::ScopedLock scoped_lock(thread_start_lock_);
306
79
    if (server.Start()) {
307
78
      host_port_->set_port(server.Port());
308
    }
309
79
    thread_start_condition_.Broadcast(scoped_lock);
310
  }
311
79
  uv_run(&loop, UV_RUN_DEFAULT);
312
158
  CheckedUvLoopClose(&loop);
313
79
}
314
315
7
std::string InspectorIo::GetWsUrl() const {
316
7
  return FormatWsAddress(host_port_->host(), host_port_->port(), id_, true);
317
}
318
319
79
InspectorIoDelegate::InspectorIoDelegate(
320
    std::shared_ptr<RequestQueueData> queue,
321
    std::shared_ptr<MainThreadHandle> main_thread,
322
    const std::string& target_id,
323
    const std::string& script_path,
324
    const std::string& script_name)
325
    : request_queue_(queue), main_thread_(main_thread),
326
      script_name_(script_name), script_path_(script_path),
327
79
      target_id_(target_id) {}
328
329
17
void InspectorIoDelegate::StartSession(int session_id,
330
                                       const std::string& target_id) {
331
  auto session = main_thread_->Connect(
332
      std::unique_ptr<InspectorSessionDelegate>(
333
17
          new IoSessionDelegate(request_queue_->handle(), session_id)), true);
334
17
  if (session) {
335
17
    sessions_[session_id] = std::move(session);
336
17
    fprintf(stderr, "Debugger attached.\n");
337
17
  }
338
17
}
339
340
122
void InspectorIoDelegate::MessageReceived(int session_id,
341
                                          const std::string& message) {
342
122
  auto session = sessions_.find(session_id);
343
122
  if (session != sessions_.end())
344
122
    session->second->Dispatch(Utf8ToStringView(message)->string());
345
122
}
346
347
17
void InspectorIoDelegate::EndSession(int session_id) {
348
17
  sessions_.erase(session_id);
349
17
}
350
351
117
std::vector<std::string> InspectorIoDelegate::GetTargetIds() {
352
117
  return { target_id_ };
353
}
354
355
21
std::string InspectorIoDelegate::GetTargetTitle(const std::string& id) {
356
21
  return script_name_.empty() ? GetHumanReadableProcessName() : script_name_;
357
}
358
359
21
std::string InspectorIoDelegate::GetTargetUrl(const std::string& id) {
360
21
  return "file://" + script_path_;
361
}
362
363
// static
364
79
void RequestQueueData::CloseAndFree(RequestQueueData* queue) {
365
79
  queue->handle_->Reset();
366
79
  queue->handle_.reset();
367
  uv_close(reinterpret_cast<uv_handle_t*>(&queue->async_),
368
237
           [](uv_handle_t* handle) {
369
79
    uv_async_t* async = reinterpret_cast<uv_async_t*>(handle);
370
    RequestQueueData* wrapper =
371
79
        node::ContainerOf(&RequestQueueData::async_, async);
372
79
    delete wrapper;
373
316
  });
374
79
}
375
}  // namespace inspector
376
}  // namespace node