GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/inspector_agent.cc Lines: 475 502 94.6 %
Date: 2019-07-27 22:37:30 Branches: 147 204 72.1 %

Line Branch Exec Source
1
#include "inspector_agent.h"
2
3
#include "env-inl.h"
4
#include "inspector/main_thread_interface.h"
5
#include "inspector/node_string.h"
6
#include "inspector/runtime_agent.h"
7
#include "inspector/tracing_agent.h"
8
#include "inspector/worker_agent.h"
9
#include "inspector/worker_inspector.h"
10
#include "inspector_io.h"
11
#include "node/inspector/protocol/Protocol.h"
12
#include "node_errors.h"
13
#include "node_internals.h"
14
#include "node_options-inl.h"
15
#include "node_process.h"
16
#include "node_url.h"
17
#include "util-inl.h"
18
#include "v8-inspector.h"
19
#include "v8-platform.h"
20
21
#include "libplatform/libplatform.h"
22
23
#ifdef __POSIX__
24
#include <pthread.h>
25
#include <climits>  // PTHREAD_STACK_MIN
26
#endif  // __POSIX__
27
28
#include <algorithm>
29
#include <cstring>
30
#include <sstream>
31
#include <unordered_map>
32
#include <vector>
33
34
namespace node {
35
namespace inspector {
36
namespace {
37
38
using node::FatalError;
39
40
using v8::Context;
41
using v8::Function;
42
using v8::Global;
43
using v8::HandleScope;
44
using v8::Isolate;
45
using v8::Local;
46
using v8::Message;
47
using v8::Object;
48
using v8::String;
49
using v8::Task;
50
using v8::TaskRunner;
51
using v8::Value;
52
53
using v8_inspector::StringBuffer;
54
using v8_inspector::StringView;
55
using v8_inspector::V8Inspector;
56
using v8_inspector::V8InspectorClient;
57
58
static uv_sem_t start_io_thread_semaphore;
59
static uv_async_t start_io_thread_async;
60
// This is just an additional check to make sure start_io_thread_async
61
// is not accidentally re-used or used when uninitialized.
62
static std::atomic_bool start_io_thread_async_initialized { false };
63
64
2
class StartIoTask : public Task {
65
 public:
66
1
  explicit StartIoTask(Agent* agent) : agent(agent) {}
67
68
1
  void Run() override {
69
1
    agent->StartIoThread();
70
1
  }
71
72
 private:
73
  Agent* agent;
74
};
75
76
6
std::unique_ptr<StringBuffer> ToProtocolString(Isolate* isolate,
77
                                               Local<Value> value) {
78
6
  TwoByteValue buffer(isolate, value);
79
6
  return StringBuffer::create(StringView(*buffer, buffer.length()));
80
}
81
82
// Called on the main thread.
83
1
void StartIoThreadAsyncCallback(uv_async_t* handle) {
84
1
  static_cast<Agent*>(handle->data)->StartIoThread();
85
1
}
86
87
1
void StartIoInterrupt(Isolate* isolate, void* agent) {
88
1
  static_cast<Agent*>(agent)->StartIoThread();
89
1
}
90
91
92
#ifdef __POSIX__
93
1
static void StartIoThreadWakeup(int signo, siginfo_t* info, void* ucontext) {
94
1
  uv_sem_post(&start_io_thread_semaphore);
95
1
}
96
97
4773
inline void* StartIoThreadMain(void* unused) {
98
  for (;;) {
99
4773
    uv_sem_wait(&start_io_thread_semaphore);
100
1
    CHECK(start_io_thread_async_initialized);
101
1
    Agent* agent = static_cast<Agent*>(start_io_thread_async.data);
102
1
    if (agent != nullptr)
103
1
      agent->RequestIoThreadStart();
104
1
  }
105
  return nullptr;
106
}
107
108
4772
static int StartDebugSignalHandler() {
109
  // Start a watchdog thread for calling v8::Debug::DebugBreak() because
110
  // it's not safe to call directly from the signal handler, it can
111
  // deadlock with the thread it interrupts.
112
4772
  CHECK_EQ(0, uv_sem_init(&start_io_thread_semaphore, 0));
113
  pthread_attr_t attr;
114
4772
  CHECK_EQ(0, pthread_attr_init(&attr));
115
#if defined(PTHREAD_STACK_MIN) && !defined(__FreeBSD__)
116
  // PTHREAD_STACK_MIN is 2 KB with musl libc, which is too small to safely
117
  // receive signals. PTHREAD_STACK_MIN + MINSIGSTKSZ is 8 KB on arm64, which
118
  // is the musl architecture with the biggest MINSIGSTKSZ so let's use that
119
  // as a lower bound and let's quadruple it just in case. The goal is to avoid
120
  // creating a big 2 or 4 MB address space gap (problematic on 32 bits
121
  // because of fragmentation), not squeeze out every last byte.
122
  // Omitted on FreeBSD because it doesn't seem to like small stacks.
123
  const size_t stack_size = std::max(static_cast<size_t>(4 * 8192),
124
4772
                                     static_cast<size_t>(PTHREAD_STACK_MIN));
125
4772
  CHECK_EQ(0, pthread_attr_setstacksize(&attr, stack_size));
126
#endif  // defined(PTHREAD_STACK_MIN) && !defined(__FreeBSD__)
127
4772
  CHECK_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
128
  sigset_t sigmask;
129
  // Mask all signals.
130
4772
  sigfillset(&sigmask);
131
  sigset_t savemask;
132
4772
  CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, &savemask));
133
4772
  sigmask = savemask;
134
  pthread_t thread;
135
  const int err = pthread_create(&thread, &attr,
136
4772
                                 StartIoThreadMain, nullptr);
137
  // Restore original mask
138
4772
  CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, nullptr));
139
4772
  CHECK_EQ(0, pthread_attr_destroy(&attr));
140
4772
  if (err != 0) {
141
    fprintf(stderr, "node[%u]: pthread_create: %s\n",
142
            uv_os_getpid(), strerror(err));
143
    fflush(stderr);
144
    // Leave SIGUSR1 blocked.  We don't install a signal handler,
145
    // receiving the signal would terminate the process.
146
    return -err;
147
  }
148
4772
  RegisterSignalHandler(SIGUSR1, StartIoThreadWakeup);
149
  // Unblock SIGUSR1.  A pending SIGUSR1 signal will now be delivered.
150
4772
  sigemptyset(&sigmask);
151
4772
  sigaddset(&sigmask, SIGUSR1);
152
4772
  CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sigmask, nullptr));
153
4772
  return 0;
154
}
155
#endif  // __POSIX__
156
157
158
#ifdef _WIN32
159
DWORD WINAPI StartIoThreadProc(void* arg) {
160
  CHECK(start_io_thread_async_initialized);
161
  Agent* agent = static_cast<Agent*>(start_io_thread_async.data);
162
  if (agent != nullptr)
163
    agent->RequestIoThreadStart();
164
  return 0;
165
}
166
167
static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
168
                                            size_t buf_len) {
169
  return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
170
}
171
172
static int StartDebugSignalHandler() {
173
  wchar_t mapping_name[32];
174
  HANDLE mapping_handle;
175
  DWORD pid;
176
  LPTHREAD_START_ROUTINE* handler;
177
178
  pid = uv_os_getpid();
179
180
  if (GetDebugSignalHandlerMappingName(pid,
181
                                       mapping_name,
182
                                       arraysize(mapping_name)) < 0) {
183
    return -1;
184
  }
185
186
  mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
187
                                      nullptr,
188
                                      PAGE_READWRITE,
189
                                      0,
190
                                      sizeof *handler,
191
                                      mapping_name);
192
  if (mapping_handle == nullptr) {
193
    return -1;
194
  }
195
196
  handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
197
      MapViewOfFile(mapping_handle,
198
                    FILE_MAP_ALL_ACCESS,
199
                    0,
200
                    0,
201
                    sizeof *handler));
202
  if (handler == nullptr) {
203
    CloseHandle(mapping_handle);
204
    return -1;
205
  }
206
207
  *handler = StartIoThreadProc;
208
209
  UnmapViewOfFile(static_cast<void*>(handler));
210
211
  return 0;
212
}
213
#endif  // _WIN32
214
215
216
const int CONTEXT_GROUP_ID = 1;
217
218
194
std::string GetWorkerLabel(node::Environment* env) {
219
194
  std::ostringstream result;
220
194
  result << "Worker[" << env->thread_id() << "]";
221
195
  return result.str();
222
}
223
224
class ChannelImpl final : public v8_inspector::V8Inspector::Channel,
225
                          public protocol::FrontendChannel {
226
 public:
227
5209
  explicit ChannelImpl(Environment* env,
228
                       const std::unique_ptr<V8Inspector>& inspector,
229
                       std::shared_ptr<WorkerManager> worker_manager,
230
                       std::unique_ptr<InspectorSessionDelegate> delegate,
231
                       std::shared_ptr<MainThreadHandle> main_thread_,
232
                       bool prevent_shutdown)
233
5208
      : delegate_(std::move(delegate)), prevent_shutdown_(prevent_shutdown),
234
10417
        retaining_context_(false) {
235
5208
    session_ = inspector->connect(1, this, StringView());
236
5209
    node_dispatcher_ = std::make_unique<protocol::UberDispatcher>(this);
237
10418
    tracing_agent_ =
238
5209
        std::make_unique<protocol::TracingAgent>(env, main_thread_);
239
5209
    tracing_agent_->Wire(node_dispatcher_.get());
240
5208
    worker_agent_ = std::make_unique<protocol::WorkerAgent>(worker_manager);
241
5208
    worker_agent_->Wire(node_dispatcher_.get());
242
5208
    runtime_agent_ = std::make_unique<protocol::RuntimeAgent>();
243
5209
    runtime_agent_->Wire(node_dispatcher_.get());
244
5209
  }
245
246
14439
  ~ChannelImpl() override {
247
4813
    tracing_agent_->disable();
248
4813
    tracing_agent_.reset();  // Dispose before the dispatchers
249
4813
    worker_agent_->disable();
250
4813
    worker_agent_.reset();  // Dispose before the dispatchers
251
4813
    runtime_agent_->disable();
252
4813
    runtime_agent_.reset();  // Dispose before the dispatchers
253
9626
  }
254
255
15329
  void dispatchProtocolMessage(const StringView& message) {
256
15329
    std::string raw_message = protocol::StringUtil::StringViewToUtf8(message);
257
    std::unique_ptr<protocol::DictionaryValue> value =
258
        protocol::DictionaryValue::cast(protocol::StringUtil::parseMessage(
259
30661
            raw_message, false));
260
    int call_id;
261
30660
    std::string method;
262
15330
    node_dispatcher_->parseCommand(value.get(), &call_id, &method);
263
30662
    if (v8_inspector::V8InspectorSession::canDispatchMethod(
264
30660
            Utf8ToStringView(method)->string())) {
265
15296
      session_->dispatchProtocolMessage(message);
266
    } else {
267
35
      node_dispatcher_->dispatch(call_id, method, std::move(value),
268
35
                                 raw_message);
269
15330
    }
270
15331
  }
271
272
30
  void schedulePauseOnNextStatement(const std::string& reason) {
273
30
    std::unique_ptr<StringBuffer> buffer = Utf8ToStringView(reason);
274
30
    session_->schedulePauseOnNextStatement(buffer->string(), buffer->string());
275
30
  }
276
277
5068
  bool preventShutdown() {
278
5068
    return prevent_shutdown_;
279
  }
280
281
4859
  bool notifyWaitingForDisconnect() {
282
4859
    retaining_context_ = runtime_agent_->notifyWaitingForDisconnect();
283
4859
    return retaining_context_;
284
  }
285
286
230
  bool retainingContext() {
287
230
    return retaining_context_;
288
  }
289
290
 private:
291
15295
  void sendResponse(
292
      int callId,
293
      std::unique_ptr<v8_inspector::StringBuffer> message) override {
294
15295
    sendMessageToFrontend(message->string());
295
15295
  }
296
297
4117
  void sendNotification(
298
      std::unique_ptr<v8_inspector::StringBuffer> message) override {
299
4117
    sendMessageToFrontend(message->string());
300
4117
  }
301
302
410
  void flushProtocolNotifications() override { }
303
304
19634
  void sendMessageToFrontend(const StringView& message) {
305
19634
    delegate_->SendMessageToFrontend(message);
306
19634
  }
307
308
222
  void sendMessageToFrontend(const std::string& message) {
309
222
    sendMessageToFrontend(Utf8ToStringView(message)->string());
310
222
  }
311
312
  using Serializable = protocol::Serializable;
313
314
35
  void sendProtocolResponse(int callId,
315
                            std::unique_ptr<Serializable> message) override {
316
35
    sendMessageToFrontend(message->serializeToJSON());
317
35
  }
318
187
  void sendProtocolNotification(
319
      std::unique_ptr<Serializable> message) override {
320
187
    sendMessageToFrontend(message->serializeToJSON());
321
187
  }
322
323
  void fallThrough(int callId,
324
                   const std::string& method,
325
                   const std::string& message) override {
326
    DCHECK(false);
327
  }
328
329
  std::unique_ptr<protocol::RuntimeAgent> runtime_agent_;
330
  std::unique_ptr<protocol::TracingAgent> tracing_agent_;
331
  std::unique_ptr<protocol::WorkerAgent> worker_agent_;
332
  std::unique_ptr<InspectorSessionDelegate> delegate_;
333
  std::unique_ptr<v8_inspector::V8InspectorSession> session_;
334
  std::unique_ptr<protocol::UberDispatcher> node_dispatcher_;
335
  bool prevent_shutdown_;
336
  bool retaining_context_;
337
};
338
339
class InspectorTimer {
340
 public:
341
2
  InspectorTimer(Environment* env,
342
                 double interval_s,
343
                 V8InspectorClient::TimerCallback callback,
344
                 void* data) : env_(env),
345
                               callback_(callback),
346
2
                               data_(data) {
347
2
    uv_timer_init(env->event_loop(), &timer_);
348
2
    int64_t interval_ms = 1000 * interval_s;
349
2
    uv_timer_start(&timer_, OnTimer, interval_ms, interval_ms);
350
2
    timer_.data = this;
351
352
2
    env->AddCleanupHook(CleanupHook, this);
353
2
  }
354
355
  InspectorTimer(const InspectorTimer&) = delete;
356
357
3
  void Stop() {
358
3
    env_->RemoveCleanupHook(CleanupHook, this);
359
360
3
    if (timer_.data == this) {
361
2
      timer_.data = nullptr;
362
2
      uv_timer_stop(&timer_);
363
2
      env_->CloseHandle(reinterpret_cast<uv_handle_t*>(&timer_), TimerClosedCb);
364
    }
365
3
  }
366
367
 private:
368
5
  static void OnTimer(uv_timer_t* uvtimer) {
369
5
    InspectorTimer* timer = node::ContainerOf(&InspectorTimer::timer_, uvtimer);
370
5
    timer->callback_(timer->data_);
371
5
  }
372
373
1
  static void CleanupHook(void* data) {
374
1
    static_cast<InspectorTimer*>(data)->Stop();
375
1
  }
376
377
2
  static void TimerClosedCb(uv_handle_t* uvtimer) {
378
    std::unique_ptr<InspectorTimer> timer(
379
        node::ContainerOf(&InspectorTimer::timer_,
380
2
                          reinterpret_cast<uv_timer_t*>(uvtimer)));
381
    // Unique_ptr goes out of scope here and pointer is deleted.
382
2
  }
383
384
  ~InspectorTimer() = default;
385
386
  Environment* env_;
387
  uv_timer_t timer_;
388
  V8InspectorClient::TimerCallback callback_;
389
  void* data_;
390
391
  friend std::unique_ptr<InspectorTimer>::deleter_type;
392
};
393
394
class InspectorTimerHandle {
395
 public:
396
2
  InspectorTimerHandle(Environment* env, double interval_s,
397
                       V8InspectorClient::TimerCallback callback, void* data) {
398
2
    timer_ = new InspectorTimer(env, interval_s, callback, data);
399
2
  }
400
401
  InspectorTimerHandle(const InspectorTimerHandle&) = delete;
402
403
2
  ~InspectorTimerHandle() {
404
2
    CHECK_NOT_NULL(timer_);
405
2
    timer_->Stop();
406
2
    timer_ = nullptr;
407
2
  }
408
 private:
409
  InspectorTimer* timer_;
410
};
411
412
class SameThreadInspectorSession : public InspectorSession {
413
 public:
414
5208
  SameThreadInspectorSession(
415
      int session_id, std::shared_ptr<NodeInspectorClient> client)
416
5208
      : session_id_(session_id), client_(client) {}
417
  ~SameThreadInspectorSession() override;
418
  void Dispatch(const v8_inspector::StringView& message) override;
419
420
 private:
421
  int session_id_;
422
  std::weak_ptr<NodeInspectorClient> client_;
423
};
424
425
78
void NotifyClusterWorkersDebugEnabled(Environment* env) {
426
78
  Isolate* isolate = env->isolate();
427
78
  HandleScope handle_scope(isolate);
428
78
  Local<Context> context = env->context();
429
430
  // Send message to enable debug in cluster workers
431
78
  Local<Object> message = Object::New(isolate);
432
  message->Set(context, FIXED_ONE_BYTE_STRING(isolate, "cmd"),
433
312
               FIXED_ONE_BYTE_STRING(isolate, "NODE_DEBUG_ENABLED")).Check();
434
78
  ProcessEmit(env, "internalMessage", message);
435
78
}
436
437
#ifdef _WIN32
438
bool IsFilePath(const std::string& path) {
439
  // '\\'
440
  if (path.length() > 2 && path[0] == '\\' && path[1] == '\\')
441
    return true;
442
  // '[A-Z]:[/\\]'
443
  if (path.length() < 3)
444
    return false;
445
  if ((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z'))
446
    return path[1] == ':' && (path[2] == '/' || path[2] == '\\');
447
  return false;
448
}
449
#else
450
431996
bool IsFilePath(const std::string& path) {
451

431996
  return path.length() && path[0] == '/';
452
}
453
#endif  // __POSIX__
454
455
}  // namespace
456
457
4572
class NodeInspectorClient : public V8InspectorClient {
458
 public:
459
4966
  explicit NodeInspectorClient(node::Environment* env, bool is_main)
460
4966
      : env_(env), is_main_(is_main) {
461
4967
    client_ = V8Inspector::create(env->isolate(), this);
462
    // TODO(bnoordhuis) Make name configurable from src/node.cc.
463
    std::string name =
464
4967
        is_main_ ? GetHumanReadableProcessName() : GetWorkerLabel(env);
465
9933
    ContextInfo info(name);
466
4966
    info.is_default = true;
467
9933
    contextCreated(env->context(), info);
468
4967
  }
469
470
34
  void runMessageLoopOnPause(int context_group_id) override {
471
34
    waiting_for_resume_ = true;
472
34
    runMessageLoop();
473
34
  }
474
475
76
  void waitForSessionsDisconnect() {
476
76
    waiting_for_sessions_disconnect_ = true;
477
76
    runMessageLoop();
478
76
  }
479
480
18
  void waitForFrontend() {
481
18
    waiting_for_frontend_ = true;
482
18
    runMessageLoop();
483
18
  }
484
485
14
  void maxAsyncCallStackDepthChanged(int depth) override {
486
14
    if (waiting_for_sessions_disconnect_) {
487
      // V8 isolate is mostly done and is only letting Inspector protocol
488
      // clients gather data.
489
18
      return;
490
    }
491
10
    if (auto agent = env_->inspector_agent()) {
492
10
      if (depth == 0) {
493
4
        agent->DisableAsyncHook();
494
      } else {
495
6
        agent->EnableAsyncHook();
496
      }
497
    }
498
  }
499
500
5426
  void contextCreated(Local<Context> context, const ContextInfo& info) {
501
5426
    auto name_buffer = Utf8ToStringView(info.name);
502
10853
    auto origin_buffer = Utf8ToStringView(info.origin);
503
10852
    std::unique_ptr<StringBuffer> aux_data_buffer;
504
505
    v8_inspector::V8ContextInfo v8info(
506
5427
        context, CONTEXT_GROUP_ID, name_buffer->string());
507
5427
    v8info.origin = origin_buffer->string();
508
509
5427
    if (info.is_default) {
510
4967
      aux_data_buffer = Utf8ToStringView("{\"isDefault\":true}");
511
    } else {
512
460
      aux_data_buffer = Utf8ToStringView("{\"isDefault\":false}");
513
    }
514
5426
    v8info.auxData = aux_data_buffer->string();
515
516
10853
    client_->contextCreated(v8info);
517
5427
  }
518
519
4814
  void contextDestroyed(Local<Context> context) {
520
4814
    client_->contextDestroyed(context);
521
4814
  }
522
523
23
  void quitMessageLoopOnPause() override {
524
23
    waiting_for_resume_ = false;
525
23
  }
526
527
20
  void runIfWaitingForDebugger(int context_group_id) override {
528
20
    waiting_for_frontend_ = false;
529
20
  }
530
531
5209
  int connectFrontend(std::unique_ptr<InspectorSessionDelegate> delegate,
532
                      bool prevent_shutdown) {
533
5209
    int session_id = next_session_id_++;
534
15627
    channels_[session_id] = std::make_unique<ChannelImpl>(env_,
535
                                                          client_,
536
                                                          getWorkerManager(),
537
5209
                                                          std::move(delegate),
538
                                                          getThreadHandle(),
539
5208
                                                          prevent_shutdown);
540
5209
    return session_id;
541
  }
542
543
227
  void disconnectFrontend(int session_id) {
544
227
    auto it = channels_.find(session_id);
545
227
    if (it == channels_.end())
546
      return;
547
227
    bool retaining_context = it->second->retainingContext();
548
227
    channels_.erase(it);
549
227
    if (retaining_context) {
550
6
      for (const auto& id_channel : channels_) {
551
3
        if (id_channel.second->retainingContext())
552
          return;
553
      }
554
3
      contextDestroyed(env_->context());
555
    }
556

227
    if (waiting_for_sessions_disconnect_ && !is_main_)
557
2
      waiting_for_sessions_disconnect_ = false;
558
  }
559
560
15329
  void dispatchMessageFromFrontend(int session_id, const StringView& message) {
561
15329
    channels_[session_id]->dispatchProtocolMessage(message);
562
15331
  }
563
564
16
  Local<Context> ensureDefaultContextInGroup(int contextGroupId) override {
565
16
    return env_->context();
566
  }
567
568
4
  void installAdditionalCommandLineAPI(Local<Context> context,
569
                                       Local<Object> target) override {
570
4
    Local<Function> installer = env_->inspector_console_extension_installer();
571
4
    if (!installer.IsEmpty()) {
572
8
      Local<Value> argv[] = {target};
573
      // If there is an exception, proceed in JS land
574
8
      USE(installer->Call(context, target, arraysize(argv), argv));
575
    }
576
4
  }
577
578
3
  void ReportUncaughtException(Local<Value> error, Local<Message> message) {
579
3
    Isolate* isolate = env_->isolate();
580
3
    Local<Context> context = env_->context();
581
582
9
    int script_id = message->GetScriptOrigin().ScriptID()->Value();
583
584
3
    Local<v8::StackTrace> stack_trace = message->GetStackTrace();
585
586


14
    if (!stack_trace.IsEmpty() && stack_trace->GetFrameCount() > 0 &&
587
6
        script_id == stack_trace->GetFrame(isolate, 0)->GetScriptId()) {
588
1
      script_id = 0;
589
    }
590
591
3
    const uint8_t DETAILS[] = "Uncaught";
592
593
3
    client_->exceptionThrown(
594
        context,
595
        StringView(DETAILS, sizeof(DETAILS) - 1),
596
        error,
597
9
        ToProtocolString(isolate, message->Get())->string(),
598
6
        ToProtocolString(isolate, message->GetScriptResourceName())->string(),
599
12
        message->GetLineNumber(context).FromMaybe(0),
600
12
        message->GetStartColumn(context).FromMaybe(0),
601
3
        client_->createStackTrace(stack_trace),
602
18
        script_id);
603
3
  }
604
605
2
  void startRepeatingTimer(double interval_s,
606
                           TimerCallback callback,
607
                           void* data) override {
608
    timers_.emplace(std::piecewise_construct, std::make_tuple(data),
609
                    std::make_tuple(env_, interval_s, callback,
610
2
                                    data));
611
2
  }
612
613
2
  void cancelTimer(void* data) override {
614
2
    timers_.erase(data);
615
2
  }
616
617
  // Async stack traces instrumentation.
618
1
  void AsyncTaskScheduled(const StringView& task_name, void* task,
619
                          bool recurring) {
620
1
    client_->asyncTaskScheduled(task_name, task, recurring);
621
1
  }
622
623
1
  void AsyncTaskCanceled(void* task) {
624
1
    client_->asyncTaskCanceled(task);
625
1
  }
626
627
4
  void AsyncTaskStarted(void* task) {
628
4
    client_->asyncTaskStarted(task);
629
4
  }
630
631
1
  void AsyncTaskFinished(void* task) {
632
1
    client_->asyncTaskFinished(task);
633
1
  }
634
635
  void AllAsyncTasksCanceled() {
636
    client_->allAsyncTasksCanceled();
637
  }
638
639
15
  void schedulePauseOnNextStatement(const std::string& reason) {
640
45
    for (const auto& id_channel : channels_) {
641
30
      id_channel.second->schedulePauseOnNextStatement(reason);
642
    }
643
15
  }
644
645
4960
  bool hasConnectedSessions() {
646
9949
    for (const auto& id_channel : channels_) {
647
      // Other sessions are "invisible" more most purposes
648
5068
      if (id_channel.second->preventShutdown())
649
79
        return true;
650
    }
651
4881
    return false;
652
  }
653
654
4814
  bool notifyWaitingForDisconnect() {
655
4814
    bool retaining_context = false;
656
9673
    for (const auto& id_channel : channels_) {
657
4859
      if (id_channel.second->notifyWaitingForDisconnect())
658
3
        retaining_context = true;
659
    }
660
4814
    return retaining_context;
661
  }
662
663
10443
  std::shared_ptr<MainThreadHandle> getThreadHandle() {
664
10443
    if (interface_ == nullptr) {
665
      interface_.reset(new MainThreadInterface(
666
14891
          env_->inspector_agent(), env_->event_loop(), env_->isolate(),
667
14891
          env_->isolate_data()->platform()));
668
    }
669
10444
    return interface_->GetHandle();
670
  }
671
672
5816
  std::shared_ptr<WorkerManager> getWorkerManager() {
673
5816
    if (worker_manager_ == nullptr) {
674
9922
      worker_manager_ =
675
4959
          std::make_shared<WorkerManager>(getThreadHandle());
676
    }
677
5816
    return worker_manager_;
678
  }
679
680
233440
  bool IsActive() {
681
233440
    return !channels_.empty();
682
  }
683
684
 private:
685
246
  bool shouldRunMessageLoop() {
686
246
    if (waiting_for_frontend_)
687
57
      return true;
688

189
    if (waiting_for_sessions_disconnect_ || waiting_for_resume_) {
689
146
      return hasConnectedSessions();
690
    }
691
43
    return false;
692
  }
693
694
128
  void runMessageLoop() {
695
128
    if (running_nested_loop_)
696
128
      return;
697
698
128
    running_nested_loop_ = true;
699
700
128
    MultiIsolatePlatform* platform = env_->isolate_data()->platform();
701
374
    while (shouldRunMessageLoop()) {
702
118
      if (interface_) interface_->WaitForFrontendEvent();
703
118
      while (platform->FlushForegroundTasks(env_->isolate())) {}
704
    }
705
128
    running_nested_loop_ = false;
706
  }
707
708
227949
  double currentTimeMS() override {
709
227949
    return env_->isolate_data()->platform()->CurrentClockTimeMillis();
710
  }
711
712
431996
  std::unique_ptr<StringBuffer> resourceNameToUrl(
713
      const StringView& resource_name_view) override {
714
    std::string resource_name =
715
431996
        protocol::StringUtil::StringViewToUtf8(resource_name_view);
716
431996
    if (!IsFilePath(resource_name))
717
392932
      return nullptr;
718
78128
    node::url::URL url = node::url::URL::FromFilePath(resource_name);
719
    // TODO(ak239spb): replace this code with url.href().
720
    // Refs: https://github.com/nodejs/node/issues/22610
721
471060
    return Utf8ToStringView(url.protocol() + "//" + url.path());
722
  }
723
724
  node::Environment* env_;
725
  bool is_main_;
726
  bool running_nested_loop_ = false;
727
  std::unique_ptr<V8Inspector> client_;
728
  std::unordered_map<int, std::unique_ptr<ChannelImpl>> channels_;
729
  std::unordered_map<void*, InspectorTimerHandle> timers_;
730
  int next_session_id_ = 1;
731
  bool waiting_for_resume_ = false;
732
  bool waiting_for_frontend_ = false;
733
  bool waiting_for_sessions_disconnect_ = false;
734
  // Allows accessing Inspector from non-main threads
735
  std::unique_ptr<MainThreadInterface> interface_;
736
  std::shared_ptr<WorkerManager> worker_manager_;
737
};
738
739
4967
Agent::Agent(Environment* env)
740
    : parent_env_(env),
741
9934
      debug_options_(env->options()->debug_options()),
742
24835
      host_port_(env->inspector_host_port()) {}
743
744
18288
Agent::~Agent() {
745
4572
  if (start_io_thread_async.data == this) {
746
4377
    CHECK(start_io_thread_async_initialized.exchange(false));
747
4377
    start_io_thread_async.data = nullptr;
748
    // This is global, will never get freed
749
4377
    uv_close(reinterpret_cast<uv_handle_t*>(&start_io_thread_async), nullptr);
750
  }
751
4572
}
752
753
4966
bool Agent::Start(const std::string& path,
754
                  const DebugOptions& options,
755
                  std::shared_ptr<HostPort> host_port,
756
                  bool is_main) {
757
4966
  path_ = path;
758
4967
  debug_options_ = options;
759
4967
  CHECK_NOT_NULL(host_port);
760
4967
  host_port_ = host_port;
761
762
4967
  client_ = std::make_shared<NodeInspectorClient>(parent_env_, is_main);
763
4967
  if (parent_env_->owns_inspector()) {
764
4772
    CHECK_EQ(start_io_thread_async_initialized.exchange(true), false);
765
4772
    CHECK_EQ(0, uv_async_init(parent_env_->event_loop(),
766
                              &start_io_thread_async,
767
                              StartIoThreadAsyncCallback));
768
4772
    uv_unref(reinterpret_cast<uv_handle_t*>(&start_io_thread_async));
769
4772
    start_io_thread_async.data = this;
770
    // Ignore failure, SIGUSR1 won't work, but that should not block node start.
771
4772
    StartDebugSignalHandler();
772
  }
773
774
4966
  bool wait_for_connect = options.wait_for_connect();
775
4966
  if (parent_handle_) {
776
195
    wait_for_connect = parent_handle_->WaitForConnect();
777
195
    parent_handle_->WorkerStarted(client_->getThreadHandle(), wait_for_connect);
778

4772
  } else if (!options.inspector_enabled || !StartIoThread()) {
779
4698
    return false;
780
  }
781
782
  // Patch the debug options to implement waitForDebuggerOnStart for
783
  // the NodeWorker.enable method.
784
269
  if (wait_for_connect) {
785
16
    CHECK(!parent_env_->has_serialized_options());
786
16
    debug_options_.EnableBreakFirstLine();
787
16
    parent_env_->options()->get_debug_options()->EnableBreakFirstLine();
788
16
    client_->waitForFrontend();
789
  }
790
269
  return true;
791
}
792
793
82
bool Agent::StartIoThread() {
794
82
  if (io_ != nullptr)
795
3
    return true;
796
797
79
  CHECK_NOT_NULL(client_);
798
799
158
  io_ = InspectorIo::Start(client_->getThreadHandle(),
800
                           path_,
801
                           host_port_,
802
79
                           debug_options_.inspect_publish_uid);
803
79
  if (io_ == nullptr) {
804
1
    return false;
805
  }
806
78
  NotifyClusterWorkersDebugEnabled(parent_env_);
807
78
  return true;
808
}
809
810
199
void Agent::Stop() {
811
199
  io_.reset();
812
199
}
813
814
5209
std::unique_ptr<InspectorSession> Agent::Connect(
815
    std::unique_ptr<InspectorSessionDelegate> delegate,
816
    bool prevent_shutdown) {
817
5209
  CHECK_NOT_NULL(client_);
818
5209
  int session_id = client_->connectFrontend(std::move(delegate),
819
10418
                                            prevent_shutdown);
820
  return std::unique_ptr<InspectorSession>(
821
5209
      new SameThreadInspectorSession(session_id, client_));
822
}
823
824
4814
void Agent::WaitForDisconnect() {
825
4814
  CHECK_NOT_NULL(client_);
826
4814
  bool is_worker = parent_handle_ != nullptr;
827
4814
  parent_handle_.reset();
828

4814
  if (client_->hasConnectedSessions() && !is_worker) {
829
12
    fprintf(stderr, "Waiting for the debugger to disconnect...\n");
830
12
    fflush(stderr);
831
  }
832
4814
  if (!client_->notifyWaitingForDisconnect()) {
833
4811
    client_->contextDestroyed(parent_env_->context());
834
3
  } else if (is_worker) {
835
2
    client_->waitForSessionsDisconnect();
836
  }
837
4814
  if (io_ != nullptr) {
838
74
    io_->StopAcceptingNewConnections();
839
74
    client_->waitForSessionsDisconnect();
840
  }
841
4814
}
842
843
171
void Agent::ReportUncaughtException(Local<Value> error,
844
                                    Local<Message> message) {
845
171
  if (!IsListening())
846
339
    return;
847
3
  client_->ReportUncaughtException(error, message);
848
3
  WaitForDisconnect();
849
}
850
851
15
void Agent::PauseOnNextJavascriptStatement(const std::string& reason) {
852
15
  client_->schedulePauseOnNextStatement(reason);
853
15
}
854
855
4965
void Agent::RegisterAsyncHook(Isolate* isolate,
856
                              Local<Function> enable_function,
857
                              Local<Function> disable_function) {
858
4965
  enable_async_hook_function_.Reset(isolate, enable_function);
859
4965
  disable_async_hook_function_.Reset(isolate, disable_function);
860
4965
  if (pending_enable_async_hook_) {
861
2
    CHECK(!pending_disable_async_hook_);
862
2
    pending_enable_async_hook_ = false;
863
2
    EnableAsyncHook();
864
4963
  } else if (pending_disable_async_hook_) {
865
    CHECK(!pending_enable_async_hook_);
866
    pending_disable_async_hook_ = false;
867
    DisableAsyncHook();
868
  }
869
4965
}
870
871
8
void Agent::EnableAsyncHook() {
872
16
  if (!enable_async_hook_function_.IsEmpty()) {
873
6
    ToggleAsyncHook(parent_env_->isolate(), enable_async_hook_function_);
874
2
  } else if (pending_disable_async_hook_) {
875
    CHECK(!pending_enable_async_hook_);
876
    pending_disable_async_hook_ = false;
877
  } else {
878
2
    pending_enable_async_hook_ = true;
879
  }
880
8
}
881
882
4
void Agent::DisableAsyncHook() {
883
8
  if (!disable_async_hook_function_.IsEmpty()) {
884
4
    ToggleAsyncHook(parent_env_->isolate(), disable_async_hook_function_);
885
  } else if (pending_enable_async_hook_) {
886
    CHECK(!pending_disable_async_hook_);
887
    pending_enable_async_hook_ = false;
888
  } else {
889
    pending_disable_async_hook_ = true;
890
  }
891
4
}
892
893
10
void Agent::ToggleAsyncHook(Isolate* isolate,
894
                            const Global<Function>& fn) {
895
10
  CHECK(parent_env_->has_run_bootstrapping_code());
896
10
  HandleScope handle_scope(isolate);
897
20
  CHECK(!fn.IsEmpty());
898
10
  auto context = parent_env_->context();
899
20
  v8::TryCatch try_catch(isolate);
900
30
  USE(fn.Get(isolate)->Call(context, Undefined(isolate), 0, nullptr));
901
10
  if (try_catch.HasCaught()) {
902
    PrintCaughtException(isolate, context, try_catch);
903
    FatalError("\nnode::inspector::Agent::ToggleAsyncHook",
904
               "Cannot toggle Inspector's AsyncHook, please report this.");
905
10
  }
906
10
}
907
908
1
void Agent::AsyncTaskScheduled(const StringView& task_name, void* task,
909
                               bool recurring) {
910
1
  client_->AsyncTaskScheduled(task_name, task, recurring);
911
1
}
912
913
1
void Agent::AsyncTaskCanceled(void* task) {
914
1
  client_->AsyncTaskCanceled(task);
915
1
}
916
917
4
void Agent::AsyncTaskStarted(void* task) {
918
4
  client_->AsyncTaskStarted(task);
919
4
}
920
921
1
void Agent::AsyncTaskFinished(void* task) {
922
1
  client_->AsyncTaskFinished(task);
923
1
}
924
925
void Agent::AllAsyncTasksCanceled() {
926
  client_->AllAsyncTasksCanceled();
927
}
928
929
1
void Agent::RequestIoThreadStart() {
930
  // We need to attempt to interrupt V8 flow (in case Node is running
931
  // continuous JS code) and to wake up libuv thread (in case Node is waiting
932
  // for IO events)
933
1
  CHECK(start_io_thread_async_initialized);
934
1
  uv_async_send(&start_io_thread_async);
935
1
  Isolate* isolate = parent_env_->isolate();
936
1
  v8::Platform* platform = parent_env_->isolate_data()->platform();
937
  std::shared_ptr<TaskRunner> taskrunner =
938
1
    platform->GetForegroundTaskRunner(isolate);
939
1
  taskrunner->PostTask(std::make_unique<StartIoTask>(this));
940
1
  isolate->RequestInterrupt(StartIoInterrupt, this);
941
1
  CHECK(start_io_thread_async_initialized);
942
1
  uv_async_send(&start_io_thread_async);
943
1
}
944
945
5427
void Agent::ContextCreated(Local<Context> context, const ContextInfo& info) {
946
5427
  if (client_ == nullptr)  // This happens for a main context
947
10394
    return;
948
460
  client_->contextCreated(context, info);
949
}
950
951
bool Agent::WillWaitForConnect() {
952
  if (debug_options_.wait_for_connect()) return true;
953
  if (parent_handle_)
954
    return parent_handle_->WaitForConnect();
955
  return false;
956
}
957
958
233552
bool Agent::IsActive() {
959
233552
  if (client_ == nullptr)
960
    return false;
961

233552
  return io_ != nullptr || client_->IsActive();
962
}
963
964
194
void Agent::SetParentHandle(
965
    std::unique_ptr<ParentInspectorHandle> parent_handle) {
966
194
  parent_handle_ = std::move(parent_handle);
967
195
}
968
969
206
std::unique_ptr<ParentInspectorHandle> Agent::GetParentHandle(
970
    int thread_id, const std::string& url) {
971
206
  return client_->getWorkerManager()->NewParentHandle(thread_id, url);
972
}
973
974
2
void Agent::WaitForConnect() {
975
2
  CHECK_NOT_NULL(client_);
976
2
  client_->waitForFrontend();
977
2
}
978
979
401
std::shared_ptr<WorkerManager> Agent::GetWorkerManager() {
980
401
  CHECK_NOT_NULL(client_);
981
401
  return client_->getWorkerManager();
982
}
983
984
9
std::string Agent::GetWsUrl() const {
985
9
  if (io_ == nullptr)
986
2
    return "";
987
7
  return io_->GetWsUrl();
988
}
989
990
14437
SameThreadInspectorSession::~SameThreadInspectorSession() {
991
4812
  auto client = client_.lock();
992
4813
  if (client)
993
227
    client->disconnectFrontend(session_id_);
994
9625
}
995
996
15329
void SameThreadInspectorSession::Dispatch(
997
    const v8_inspector::StringView& message) {
998
15329
  auto client = client_.lock();
999
15331
  if (client)
1000
15331
    client->dispatchMessageFromFrontend(session_id_, message);
1001
15331
}
1002
1003
}  // namespace inspector
1004
}  // namespace node