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: 450 480 93.8 %
Date: 2021-05-28 04:11:57 Branches: 149 208 71.6 %

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-inl.h"
16
#include "node_url.h"
17
#include "util-inl.h"
18
#include "timer_wrap.h"
19
#include "v8-inspector.h"
20
#include "v8-platform.h"
21
22
#include "libplatform/libplatform.h"
23
24
#ifdef __POSIX__
25
#include <pthread.h>
26
#include <climits>  // PTHREAD_STACK_MIN
27
#endif  // __POSIX__
28
29
#include <algorithm>
30
#include <cstring>
31
#include <sstream>
32
#include <unordered_map>
33
#include <vector>
34
35
namespace node {
36
namespace inspector {
37
namespace {
38
39
using node::FatalError;
40
41
using v8::Context;
42
using v8::Function;
43
using v8::Global;
44
using v8::HandleScope;
45
using v8::Isolate;
46
using v8::Local;
47
using v8::Message;
48
using v8::Object;
49
using v8::Value;
50
51
using v8_inspector::StringBuffer;
52
using v8_inspector::StringView;
53
using v8_inspector::V8Inspector;
54
using v8_inspector::V8InspectorClient;
55
56
static uv_sem_t start_io_thread_semaphore;
57
static uv_async_t start_io_thread_async;
58
// This is just an additional check to make sure start_io_thread_async
59
// is not accidentally re-used or used when uninitialized.
60
static std::atomic_bool start_io_thread_async_initialized { false };
61
// Protects the Agent* stored in start_io_thread_async.data.
62
4840
static Mutex start_io_thread_async_mutex;
63
64
4
std::unique_ptr<StringBuffer> ToProtocolString(Isolate* isolate,
65
                                               Local<Value> value) {
66
8
  TwoByteValue buffer(isolate, value);
67
8
  return StringBuffer::create(StringView(*buffer, buffer.length()));
68
}
69
70
// Called on the main thread.
71
void StartIoThreadAsyncCallback(uv_async_t* handle) {
72
  static_cast<Agent*>(handle->data)->StartIoThread();
73
}
74
75
76
#ifdef __POSIX__
77
1
static void StartIoThreadWakeup(int signo, siginfo_t* info, void* ucontext) {
78
1
  uv_sem_post(&start_io_thread_semaphore);
79
1
}
80
81
4810
inline void* StartIoThreadMain(void* unused) {
82
  for (;;) {
83
4810
    uv_sem_wait(&start_io_thread_semaphore);
84
2
    Mutex::ScopedLock lock(start_io_thread_async_mutex);
85
86
1
    CHECK(start_io_thread_async_initialized);
87
1
    Agent* agent = static_cast<Agent*>(start_io_thread_async.data);
88
1
    if (agent != nullptr)
89
1
      agent->RequestIoThreadStart();
90
1
  }
91
  return nullptr;
92
}
93
94
4809
static int StartDebugSignalHandler() {
95
  // Start a watchdog thread for calling v8::Debug::DebugBreak() because
96
  // it's not safe to call directly from the signal handler, it can
97
  // deadlock with the thread it interrupts.
98
4809
  CHECK_EQ(0, uv_sem_init(&start_io_thread_semaphore, 0));
99
  pthread_attr_t attr;
100
4809
  CHECK_EQ(0, pthread_attr_init(&attr));
101
#if defined(PTHREAD_STACK_MIN) && !defined(__FreeBSD__)
102
  // PTHREAD_STACK_MIN is 2 KB with musl libc, which is too small to safely
103
  // receive signals. PTHREAD_STACK_MIN + MINSIGSTKSZ is 8 KB on arm64, which
104
  // is the musl architecture with the biggest MINSIGSTKSZ so let's use that
105
  // as a lower bound and let's quadruple it just in case. The goal is to avoid
106
  // creating a big 2 or 4 MB address space gap (problematic on 32 bits
107
  // because of fragmentation), not squeeze out every last byte.
108
  // Omitted on FreeBSD because it doesn't seem to like small stacks.
109
  const size_t stack_size = std::max(static_cast<size_t>(4 * 8192),
110
4809
                                     static_cast<size_t>(PTHREAD_STACK_MIN));
111
4809
  CHECK_EQ(0, pthread_attr_setstacksize(&attr, stack_size));
112
#endif  // defined(PTHREAD_STACK_MIN) && !defined(__FreeBSD__)
113
4809
  CHECK_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
114
  sigset_t sigmask;
115
  // Mask all signals.
116
4809
  sigfillset(&sigmask);
117
  sigset_t savemask;
118
4809
  CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, &savemask));
119
4809
  sigmask = savemask;
120
  pthread_t thread;
121
  const int err = pthread_create(&thread, &attr,
122
4809
                                 StartIoThreadMain, nullptr);
123
  // Restore original mask
124
4809
  CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, nullptr));
125
4809
  CHECK_EQ(0, pthread_attr_destroy(&attr));
126
4809
  if (err != 0) {
127
    fprintf(stderr, "node[%u]: pthread_create: %s\n",
128
            uv_os_getpid(), strerror(err));
129
    fflush(stderr);
130
    // Leave SIGUSR1 blocked.  We don't install a signal handler,
131
    // receiving the signal would terminate the process.
132
    return -err;
133
  }
134
4809
  RegisterSignalHandler(SIGUSR1, StartIoThreadWakeup);
135
  // Unblock SIGUSR1.  A pending SIGUSR1 signal will now be delivered.
136
4809
  sigemptyset(&sigmask);
137
4809
  sigaddset(&sigmask, SIGUSR1);
138
4809
  CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sigmask, nullptr));
139
4809
  return 0;
140
}
141
#endif  // __POSIX__
142
143
144
#ifdef _WIN32
145
DWORD WINAPI StartIoThreadProc(void* arg) {
146
  Mutex::ScopedLock lock(start_io_thread_async_mutex);
147
  CHECK(start_io_thread_async_initialized);
148
  Agent* agent = static_cast<Agent*>(start_io_thread_async.data);
149
  if (agent != nullptr)
150
    agent->RequestIoThreadStart();
151
  return 0;
152
}
153
154
static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
155
                                            size_t buf_len) {
156
  return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
157
}
158
159
static int StartDebugSignalHandler() {
160
  wchar_t mapping_name[32];
161
  HANDLE mapping_handle;
162
  DWORD pid;
163
  LPTHREAD_START_ROUTINE* handler;
164
165
  pid = uv_os_getpid();
166
167
  if (GetDebugSignalHandlerMappingName(pid,
168
                                       mapping_name,
169
                                       arraysize(mapping_name)) < 0) {
170
    return -1;
171
  }
172
173
  mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
174
                                      nullptr,
175
                                      PAGE_READWRITE,
176
                                      0,
177
                                      sizeof *handler,
178
                                      mapping_name);
179
  if (mapping_handle == nullptr) {
180
    return -1;
181
  }
182
183
  handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
184
      MapViewOfFile(mapping_handle,
185
                    FILE_MAP_ALL_ACCESS,
186
                    0,
187
                    0,
188
                    sizeof *handler));
189
  if (handler == nullptr) {
190
    CloseHandle(mapping_handle);
191
    return -1;
192
  }
193
194
  *handler = StartIoThreadProc;
195
196
  UnmapViewOfFile(static_cast<void*>(handler));
197
198
  return 0;
199
}
200
#endif  // _WIN32
201
202
203
const int CONTEXT_GROUP_ID = 1;
204
205
415
std::string GetWorkerLabel(node::Environment* env) {
206
830
  std::ostringstream result;
207
415
  result << "Worker[" << env->thread_id() << "]";
208
830
  return result.str();
209
}
210
211
class ChannelImpl final : public v8_inspector::V8Inspector::Channel,
212
                          public protocol::FrontendChannel {
213
 public:
214
6200
  explicit ChannelImpl(Environment* env,
215
                       const std::unique_ptr<V8Inspector>& inspector,
216
                       std::shared_ptr<WorkerManager> worker_manager,
217
                       std::unique_ptr<InspectorSessionDelegate> delegate,
218
                       std::shared_ptr<MainThreadHandle> main_thread_,
219
                       bool prevent_shutdown)
220
12400
      : delegate_(std::move(delegate)), prevent_shutdown_(prevent_shutdown),
221
12400
        retaining_context_(false) {
222
6200
    session_ = inspector->connect(CONTEXT_GROUP_ID, this, StringView());
223
6200
    node_dispatcher_ = std::make_unique<protocol::UberDispatcher>(this);
224
    tracing_agent_ =
225
6199
        std::make_unique<protocol::TracingAgent>(env, main_thread_);
226
6199
    tracing_agent_->Wire(node_dispatcher_.get());
227
6198
    if (worker_manager) {
228
5770
      worker_agent_ = std::make_unique<protocol::WorkerAgent>(worker_manager);
229
5770
      worker_agent_->Wire(node_dispatcher_.get());
230
    }
231
6198
    runtime_agent_ = std::make_unique<protocol::RuntimeAgent>();
232
6200
    runtime_agent_->Wire(node_dispatcher_.get());
233
6199
  }
234
235
16881
  ~ChannelImpl() override {
236
5627
    tracing_agent_->disable();
237
5627
    tracing_agent_.reset();  // Dispose before the dispatchers
238
5627
    if (worker_agent_) {
239
5197
      worker_agent_->disable();
240
5197
      worker_agent_.reset();  // Dispose before the dispatchers
241
    }
242
5626
    runtime_agent_->disable();
243
5627
    runtime_agent_.reset();  // Dispose before the dispatchers
244
11254
  }
245
246
17107
  void dispatchProtocolMessage(const StringView& message) {
247
34217
    std::string raw_message = protocol::StringUtil::StringViewToUtf8(message);
248
    std::unique_ptr<protocol::DictionaryValue> value =
249
34219
        protocol::DictionaryValue::cast(protocol::StringUtil::parseMessage(
250
34217
            raw_message, false));
251
    int call_id;
252
34218
    std::string method;
253
17109
    node_dispatcher_->parseCommand(value.get(), &call_id, &method);
254
34220
    if (v8_inspector::V8InspectorSession::canDispatchMethod(
255
34220
            Utf8ToStringView(method)->string())) {
256
17071
      session_->dispatchProtocolMessage(message);
257
    } else {
258
117
      node_dispatcher_->dispatch(call_id, method, std::move(value),
259
78
                                 raw_message);
260
    }
261
17110
  }
262
263
38
  void schedulePauseOnNextStatement(const std::string& reason) {
264
76
    std::unique_ptr<StringBuffer> buffer = Utf8ToStringView(reason);
265
38
    session_->schedulePauseOnNextStatement(buffer->string(), buffer->string());
266
38
  }
267
268
5493
  bool preventShutdown() {
269
5493
    return prevent_shutdown_;
270
  }
271
272
5270
  bool notifyWaitingForDisconnect() {
273
5270
    retaining_context_ = runtime_agent_->notifyWaitingForDisconnect();
274
5270
    return retaining_context_;
275
  }
276
277
940
  bool retainingContext() {
278
940
    return retaining_context_;
279
  }
280
281
 private:
282
17069
  void sendResponse(
283
      int callId,
284
      std::unique_ptr<v8_inspector::StringBuffer> message) override {
285
17069
    sendMessageToFrontend(message->string());
286
17071
  }
287
288
6454
  void sendNotification(
289
      std::unique_ptr<v8_inspector::StringBuffer> message) override {
290
6454
    sendMessageToFrontend(message->string());
291
6454
  }
292
293
1325
  void flushProtocolNotifications() override { }
294
295
23860
  void sendMessageToFrontend(const StringView& message) {
296
23860
    delegate_->SendMessageToFrontend(message);
297
23862
  }
298
299
337
  void sendMessageToFrontend(const std::string& message) {
300
337
    sendMessageToFrontend(Utf8ToStringView(message)->string());
301
337
  }
302
303
  using Serializable = protocol::Serializable;
304
305
39
  void sendProtocolResponse(int callId,
306
                            std::unique_ptr<Serializable> message) override {
307
39
    sendMessageToFrontend(message->serializeToJSON());
308
39
  }
309
298
  void sendProtocolNotification(
310
      std::unique_ptr<Serializable> message) override {
311
298
    sendMessageToFrontend(message->serializeToJSON());
312
298
  }
313
314
  void fallThrough(int callId,
315
                   const std::string& method,
316
                   const std::string& message) override {
317
    DCHECK(false);
318
  }
319
320
  std::unique_ptr<protocol::RuntimeAgent> runtime_agent_;
321
  std::unique_ptr<protocol::TracingAgent> tracing_agent_;
322
  std::unique_ptr<protocol::WorkerAgent> worker_agent_;
323
  std::unique_ptr<InspectorSessionDelegate> delegate_;
324
  std::unique_ptr<v8_inspector::V8InspectorSession> session_;
325
  std::unique_ptr<protocol::UberDispatcher> node_dispatcher_;
326
  bool prevent_shutdown_;
327
  bool retaining_context_;
328
};
329
330
class SameThreadInspectorSession : public InspectorSession {
331
 public:
332
6199
  SameThreadInspectorSession(
333
      int session_id, std::shared_ptr<NodeInspectorClient> client)
334
6199
      : session_id_(session_id), client_(client) {}
335
  ~SameThreadInspectorSession() override;
336
  void Dispatch(const v8_inspector::StringView& message) override;
337
338
 private:
339
  int session_id_;
340
  std::weak_ptr<NodeInspectorClient> client_;
341
};
342
343
77
void NotifyClusterWorkersDebugEnabled(Environment* env) {
344
77
  Isolate* isolate = env->isolate();
345
154
  HandleScope handle_scope(isolate);
346
77
  Local<Context> context = env->context();
347
348
  // Send message to enable debug in cluster workers
349
77
  Local<Object> message = Object::New(isolate);
350
154
  message->Set(context, FIXED_ONE_BYTE_STRING(isolate, "cmd"),
351
308
               FIXED_ONE_BYTE_STRING(isolate, "NODE_DEBUG_ENABLED")).Check();
352
77
  ProcessEmit(env, "internalMessage", message);
353
77
}
354
355
#ifdef _WIN32
356
bool IsFilePath(const std::string& path) {
357
  // '\\'
358
  if (path.length() > 2 && path[0] == '\\' && path[1] == '\\')
359
    return true;
360
  // '[A-Z]:[/\\]'
361
  if (path.length() < 3)
362
    return false;
363
  if ((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z'))
364
    return path[1] == ':' && (path[2] == '/' || path[2] == '\\');
365
  return false;
366
}
367
#else
368
580144
bool IsFilePath(const std::string& path) {
369

580144
  return !path.empty() && path[0] == '/';
370
}
371
#endif  // __POSIX__
372
373
}  // namespace
374
375
4654
class NodeInspectorClient : public V8InspectorClient {
376
 public:
377
5226
  explicit NodeInspectorClient(node::Environment* env, bool is_main)
378
5226
      : env_(env), is_main_(is_main) {
379
5226
    client_ = V8Inspector::create(env->isolate(), this);
380
    // TODO(bnoordhuis) Make name configurable from src/node.cc.
381
    std::string name =
382
10452
        is_main_ ? GetHumanReadableProcessName() : GetWorkerLabel(env);
383
10452
    ContextInfo info(name);
384
5226
    info.is_default = true;
385
5226
    contextCreated(env->context(), info);
386
5226
  }
387
388
40
  void runMessageLoopOnPause(int context_group_id) override {
389
40
    waiting_for_resume_ = true;
390
40
    runMessageLoop();
391
40
  }
392
393
77
  void waitForSessionsDisconnect() {
394
77
    waiting_for_sessions_disconnect_ = true;
395
77
    runMessageLoop();
396
77
  }
397
398
19
  void waitForFrontend() {
399
19
    waiting_for_frontend_ = true;
400
19
    runMessageLoop();
401
19
  }
402
403
13
  void maxAsyncCallStackDepthChanged(int depth) override {
404
13
    if (waiting_for_sessions_disconnect_) {
405
      // V8 isolate is mostly done and is only letting Inspector protocol
406
      // clients gather data.
407
4
      return;
408
    }
409
9
    if (auto agent = env_->inspector_agent()) {
410
9
      if (depth == 0) {
411
3
        agent->DisableAsyncHook();
412
      } else {
413
6
        agent->EnableAsyncHook();
414
      }
415
    }
416
  }
417
418
5806
  void contextCreated(Local<Context> context, const ContextInfo& info) {
419
11612
    auto name_buffer = Utf8ToStringView(info.name);
420
11612
    auto origin_buffer = Utf8ToStringView(info.origin);
421
11612
    std::unique_ptr<StringBuffer> aux_data_buffer;
422
423
    v8_inspector::V8ContextInfo v8info(
424
5806
        context, CONTEXT_GROUP_ID, name_buffer->string());
425
5806
    v8info.origin = origin_buffer->string();
426
427
5806
    if (info.is_default) {
428
5226
      aux_data_buffer = Utf8ToStringView("{\"isDefault\":true}");
429
    } else {
430
580
      aux_data_buffer = Utf8ToStringView("{\"isDefault\":false}");
431
    }
432
5806
    v8info.auxData = aux_data_buffer->string();
433
434
5806
    client_->contextCreated(v8info);
435
5806
  }
436
437
5210
  void contextDestroyed(Local<Context> context) {
438
5210
    client_->contextDestroyed(context);
439
5210
  }
440
441
28
  void quitMessageLoopOnPause() override {
442
28
    waiting_for_resume_ = false;
443
28
  }
444
445
20
  void runIfWaitingForDebugger(int context_group_id) override {
446
20
    waiting_for_frontend_ = false;
447
20
  }
448
449
6200
  int connectFrontend(std::unique_ptr<InspectorSessionDelegate> delegate,
450
                      bool prevent_shutdown) {
451
6200
    int session_id = next_session_id_++;
452
12400
    channels_[session_id] = std::make_unique<ChannelImpl>(env_,
453
                                                          client_,
454
12400
                                                          getWorkerManager(),
455
6200
                                                          std::move(delegate),
456
12399
                                                          getThreadHandle(),
457
6199
                                                          prevent_shutdown);
458
6200
    return session_id;
459
  }
460
461
937
  void disconnectFrontend(int session_id) {
462
937
    auto it = channels_.find(session_id);
463
937
    if (it == channels_.end())
464
      return;
465
937
    bool retaining_context = it->second->retainingContext();
466
937
    channels_.erase(it);
467
937
    if (retaining_context) {
468
6
      for (const auto& id_channel : channels_) {
469
3
        if (id_channel.second->retainingContext())
470
          return;
471
      }
472
3
      contextDestroyed(env_->context());
473
    }
474

937
    if (waiting_for_sessions_disconnect_ && !is_main_)
475
2
      waiting_for_sessions_disconnect_ = false;
476
  }
477
478
17107
  void dispatchMessageFromFrontend(int session_id, const StringView& message) {
479
17107
    channels_[session_id]->dispatchProtocolMessage(message);
480
17108
  }
481
482
324
  Local<Context> ensureDefaultContextInGroup(int contextGroupId) override {
483
324
    return env_->context();
484
  }
485
486
3
  void installAdditionalCommandLineAPI(Local<Context> context,
487
                                       Local<Object> target) override {
488
3
    Local<Function> installer = env_->inspector_console_extension_installer();
489
3
    if (!installer.IsEmpty()) {
490
6
      Local<Value> argv[] = {target};
491
      // If there is an exception, proceed in JS land
492
6
      USE(installer->Call(context, target, arraysize(argv), argv));
493
    }
494
3
  }
495
496
2
  void ReportUncaughtException(Local<Value> error, Local<Message> message) {
497
2
    Isolate* isolate = env_->isolate();
498
2
    Local<Context> context = env_->context();
499
500
4
    int script_id = message->GetScriptOrigin().ScriptId();
501
502
2
    Local<v8::StackTrace> stack_trace = message->GetStackTrace();
503
504


6
    if (!stack_trace.IsEmpty() && stack_trace->GetFrameCount() > 0 &&
505
4
        script_id == stack_trace->GetFrame(isolate, 0)->GetScriptId()) {
506
1
      script_id = 0;
507
    }
508
509
2
    const uint8_t DETAILS[] = "Uncaught";
510
511
12
    client_->exceptionThrown(
512
        context,
513
        StringView(DETAILS, sizeof(DETAILS) - 1),
514
        error,
515
6
        ToProtocolString(isolate, message->Get())->string(),
516
4
        ToProtocolString(isolate, message->GetScriptResourceName())->string(),
517
8
        message->GetLineNumber(context).FromMaybe(0),
518
8
        message->GetStartColumn(context).FromMaybe(0),
519
4
        client_->createStackTrace(stack_trace),
520
4
        script_id);
521
2
  }
522
523
2
  void startRepeatingTimer(double interval_s,
524
                           TimerCallback callback,
525
                           void* data) override {
526
    auto result =
527
2
        timers_.emplace(std::piecewise_construct, std::make_tuple(data),
528
10
                        std::make_tuple(env_, [=]() { callback(data); }));
529
2
    CHECK(result.second);
530
2
    uint64_t interval = static_cast<uint64_t>(1000 * interval_s);
531
2
    result.first->second.Update(interval, interval);
532
2
  }
533
534
2
  void cancelTimer(void* data) override {
535
2
    timers_.erase(data);
536
2
  }
537
538
  // Async stack traces instrumentation.
539
1
  void AsyncTaskScheduled(const StringView& task_name, void* task,
540
                          bool recurring) {
541
1
    client_->asyncTaskScheduled(task_name, task, recurring);
542
1
  }
543
544
1
  void AsyncTaskCanceled(void* task) {
545
1
    client_->asyncTaskCanceled(task);
546
1
  }
547
548
4
  void AsyncTaskStarted(void* task) {
549
4
    client_->asyncTaskStarted(task);
550
4
  }
551
552
1
  void AsyncTaskFinished(void* task) {
553
1
    client_->asyncTaskFinished(task);
554
1
  }
555
556
  void AllAsyncTasksCanceled() {
557
    client_->allAsyncTasksCanceled();
558
  }
559
560
19
  void schedulePauseOnNextStatement(const std::string& reason) {
561
57
    for (const auto& id_channel : channels_) {
562
38
      id_channel.second->schedulePauseOnNextStatement(reason);
563
    }
564
19
  }
565
566
5366
  bool hasConnectedSessions() {
567
10765
    for (const auto& id_channel : channels_) {
568
      // Other sessions are "invisible" more most purposes
569
5493
      if (id_channel.second->preventShutdown())
570
94
        return true;
571
    }
572
5272
    return false;
573
  }
574
575
5210
  bool notifyWaitingForDisconnect() {
576
5210
    bool retaining_context = false;
577
10480
    for (const auto& id_channel : channels_) {
578
5270
      if (id_channel.second->notifyWaitingForDisconnect())
579
3
        retaining_context = true;
580
    }
581
5210
    return retaining_context;
582
  }
583
584
11499
  std::shared_ptr<MainThreadHandle> getThreadHandle() {
585
11499
    if (!interface_) {
586
10444
      interface_ = std::make_shared<MainThreadInterface>(
587
15666
          env_->inspector_agent());
588
    }
589
11499
    return interface_->GetHandle();
590
  }
591
592
7896
  std::shared_ptr<WorkerManager> getWorkerManager() {
593
7896
    if (!is_main_) {
594
430
      return nullptr;
595
    }
596
7466
    if (worker_manager_ == nullptr) {
597
      worker_manager_ =
598
4805
          std::make_shared<WorkerManager>(getThreadHandle());
599
    }
600
7466
    return worker_manager_;
601
  }
602
603
28029
  bool IsActive() {
604
28029
    return !channels_.empty();
605
  }
606
607
 private:
608
265
  bool shouldRunMessageLoop() {
609
265
    if (waiting_for_frontend_)
610
60
      return true;
611

205
    if (waiting_for_sessions_disconnect_ || waiting_for_resume_) {
612
156
      return hasConnectedSessions();
613
    }
614
49
    return false;
615
  }
616
617
136
  void runMessageLoop() {
618
136
    if (running_nested_loop_)
619
      return;
620
621
136
    running_nested_loop_ = true;
622
623
394
    while (shouldRunMessageLoop()) {
624
129
      if (interface_) interface_->WaitForFrontendEvent();
625
129
      env_->RunAndClearInterrupts();
626
    }
627
136
    running_nested_loop_ = false;
628
  }
629
630
22940
  double currentTimeMS() override {
631
22940
    return env_->isolate_data()->platform()->CurrentClockTimeMillis();
632
  }
633
634
580152
  std::unique_ptr<StringBuffer> resourceNameToUrl(
635
      const StringView& resource_name_view) override {
636
    std::string resource_name =
637
1160292
        protocol::StringUtil::StringViewToUtf8(resource_name_view);
638
580146
    if (!IsFilePath(resource_name))
639
547426
      return nullptr;
640
65438
    node::url::URL url = node::url::URL::FromFilePath(resource_name);
641
32719
    return Utf8ToStringView(url.href());
642
  }
643
644
  node::Environment* env_;
645
  bool is_main_;
646
  bool running_nested_loop_ = false;
647
  std::unique_ptr<V8Inspector> client_;
648
  // Note: ~ChannelImpl may access timers_ so timers_ has to come first.
649
  std::unordered_map<void*, TimerWrapHandle> timers_;
650
  std::unordered_map<int, std::unique_ptr<ChannelImpl>> channels_;
651
  int next_session_id_ = 1;
652
  bool waiting_for_resume_ = false;
653
  bool waiting_for_frontend_ = false;
654
  bool waiting_for_sessions_disconnect_ = false;
655
  // Allows accessing Inspector from non-main threads
656
  std::shared_ptr<MainThreadInterface> interface_;
657
  std::shared_ptr<WorkerManager> worker_manager_;
658
};
659
660
5234
Agent::Agent(Environment* env)
661
    : parent_env_(env),
662
10468
      debug_options_(env->options()->debug_options()),
663
26170
      host_port_(env->inspector_host_port()) {}
664
665
13986
Agent::~Agent() {}
666
667
5226
bool Agent::Start(const std::string& path,
668
                  const DebugOptions& options,
669
                  std::shared_ptr<ExclusiveAccess<HostPort>> host_port,
670
                  bool is_main) {
671
5226
  path_ = path;
672
5226
  debug_options_ = options;
673
5226
  CHECK_NOT_NULL(host_port);
674
5226
  host_port_ = host_port;
675
676
5226
  client_ = std::make_shared<NodeInspectorClient>(parent_env_, is_main);
677
5226
  if (parent_env_->owns_inspector()) {
678
9618
    Mutex::ScopedLock lock(start_io_thread_async_mutex);
679
4809
    CHECK_EQ(start_io_thread_async_initialized.exchange(true), false);
680
4809
    CHECK_EQ(0, uv_async_init(parent_env_->event_loop(),
681
                              &start_io_thread_async,
682
                              StartIoThreadAsyncCallback));
683
4809
    uv_unref(reinterpret_cast<uv_handle_t*>(&start_io_thread_async));
684
4809
    start_io_thread_async.data = this;
685
    // Ignore failure, SIGUSR1 won't work, but that should not block node start.
686
4809
    StartDebugSignalHandler();
687
688
22901
    parent_env_->AddCleanupHook([](void* data) {
689
4237
      Environment* env = static_cast<Environment*>(data);
690
691
      {
692
8474
        Mutex::ScopedLock lock(start_io_thread_async_mutex);
693
4237
        start_io_thread_async.data = nullptr;
694
      }
695
696
      // This is global, will never get freed
697
8474
      env->CloseHandle(&start_io_thread_async, [](uv_async_t*) {
698
4237
        CHECK(start_io_thread_async_initialized.exchange(false));
699
8474
      });
700
22901
    }, parent_env_);
701
  }
702
703
26106
  AtExit(parent_env_, [](void* env) {
704
5214
    Agent* agent = static_cast<Environment*>(env)->inspector_agent();
705
5214
    if (agent->IsActive()) {
706
5208
      agent->WaitForDisconnect();
707
    }
708
26106
  }, parent_env_);
709
710
5226
  bool wait_for_connect = options.wait_for_connect();
711
5226
  if (parent_handle_) {
712
415
    wait_for_connect = parent_handle_->WaitForConnect();
713
415
    parent_handle_->WorkerStarted(client_->getThreadHandle(), wait_for_connect);
714

4811
  } else if (!options.inspector_enabled || !StartIoThread()) {
715
4735
    return false;
716
  }
717
718
  // Patch the debug options to implement waitForDebuggerOnStart for
719
  // the NodeWorker.enable method.
720
491
  if (wait_for_connect) {
721
19
    CHECK(!parent_env_->has_serialized_options());
722
19
    debug_options_.EnableBreakFirstLine();
723
19
    parent_env_->options()->get_debug_options()->EnableBreakFirstLine();
724
19
    client_->waitForFrontend();
725
  }
726
491
  return true;
727
}
728
729
78
bool Agent::StartIoThread() {
730
78
  if (io_ != nullptr)
731
    return true;
732
733
78
  CHECK_NOT_NULL(client_);
734
735
156
  io_ = InspectorIo::Start(client_->getThreadHandle(),
736
                           path_,
737
                           host_port_,
738
78
                           debug_options_.inspect_publish_uid);
739
78
  if (io_ == nullptr) {
740
1
    return false;
741
  }
742
77
  NotifyClusterWorkersDebugEnabled(parent_env_);
743
77
  return true;
744
}
745
746
4
void Agent::Stop() {
747
4
  io_.reset();
748
4
}
749
750
6200
std::unique_ptr<InspectorSession> Agent::Connect(
751
    std::unique_ptr<InspectorSessionDelegate> delegate,
752
    bool prevent_shutdown) {
753
6200
  CHECK_NOT_NULL(client_);
754
12400
  int session_id = client_->connectFrontend(std::move(delegate),
755
6199
                                            prevent_shutdown);
756
  return std::unique_ptr<InspectorSession>(
757
6200
      new SameThreadInspectorSession(session_id, client_));
758
}
759
760
2
std::unique_ptr<InspectorSession> Agent::ConnectToMainThread(
761
    std::unique_ptr<InspectorSessionDelegate> delegate,
762
    bool prevent_shutdown) {
763
2
  CHECK_NOT_NULL(parent_handle_);
764
2
  CHECK_NOT_NULL(client_);
765
  auto thread_safe_delegate =
766
4
      client_->getThreadHandle()->MakeDelegateThreadSafe(std::move(delegate));
767
2
  return parent_handle_->Connect(std::move(thread_safe_delegate),
768
6
                                 prevent_shutdown);
769
}
770
771
5210
void Agent::WaitForDisconnect() {
772
5210
  CHECK_NOT_NULL(client_);
773
5210
  bool is_worker = parent_handle_ != nullptr;
774
5210
  parent_handle_.reset();
775

5210
  if (client_->hasConnectedSessions() && !is_worker) {
776
13
    fprintf(stderr, "Waiting for the debugger to disconnect...\n");
777
13
    fflush(stderr);
778
  }
779
5210
  if (!client_->notifyWaitingForDisconnect()) {
780
5207
    client_->contextDestroyed(parent_env_->context());
781
3
  } else if (is_worker) {
782
2
    client_->waitForSessionsDisconnect();
783
  }
784
5210
  if (io_ != nullptr) {
785
75
    io_->StopAcceptingNewConnections();
786
75
    client_->waitForSessionsDisconnect();
787
  }
788
5210
}
789
790
226
void Agent::ReportUncaughtException(Local<Value> error,
791
                                    Local<Message> message) {
792
226
  if (!IsListening())
793
224
    return;
794
2
  client_->ReportUncaughtException(error, message);
795
2
  WaitForDisconnect();
796
}
797
798
19
void Agent::PauseOnNextJavascriptStatement(const std::string& reason) {
799
19
  client_->schedulePauseOnNextStatement(reason);
800
19
}
801
802
5202
void Agent::RegisterAsyncHook(Isolate* isolate,
803
                              Local<Function> enable_function,
804
                              Local<Function> disable_function) {
805
5202
  enable_async_hook_function_.Reset(isolate, enable_function);
806
5202
  disable_async_hook_function_.Reset(isolate, disable_function);
807
5202
  if (pending_enable_async_hook_) {
808
2
    CHECK(!pending_disable_async_hook_);
809
2
    pending_enable_async_hook_ = false;
810
2
    EnableAsyncHook();
811
5200
  } else if (pending_disable_async_hook_) {
812
    CHECK(!pending_enable_async_hook_);
813
    pending_disable_async_hook_ = false;
814
    DisableAsyncHook();
815
  }
816
5202
}
817
818
8
void Agent::EnableAsyncHook() {
819
16
  if (!enable_async_hook_function_.IsEmpty()) {
820
6
    ToggleAsyncHook(parent_env_->isolate(), enable_async_hook_function_);
821
2
  } else if (pending_disable_async_hook_) {
822
    CHECK(!pending_enable_async_hook_);
823
    pending_disable_async_hook_ = false;
824
  } else {
825
2
    pending_enable_async_hook_ = true;
826
  }
827
8
}
828
829
3
void Agent::DisableAsyncHook() {
830
6
  if (!disable_async_hook_function_.IsEmpty()) {
831
3
    ToggleAsyncHook(parent_env_->isolate(), disable_async_hook_function_);
832
  } else if (pending_enable_async_hook_) {
833
    CHECK(!pending_disable_async_hook_);
834
    pending_enable_async_hook_ = false;
835
  } else {
836
    pending_disable_async_hook_ = true;
837
  }
838
3
}
839
840
9
void Agent::ToggleAsyncHook(Isolate* isolate,
841
                            const Global<Function>& fn) {
842
  // Guard against running this during cleanup -- no async events will be
843
  // emitted anyway at that point anymore, and calling into JS is not possible.
844
  // This should probably not be something we're attempting in the first place,
845
  // Refs: https://github.com/nodejs/node/pull/34362#discussion_r456006039
846
9
  if (!parent_env_->can_call_into_js()) return;
847
9
  CHECK(parent_env_->has_run_bootstrapping_code());
848
18
  HandleScope handle_scope(isolate);
849
18
  CHECK(!fn.IsEmpty());
850
9
  auto context = parent_env_->context();
851
18
  v8::TryCatch try_catch(isolate);
852
27
  USE(fn.Get(isolate)->Call(context, Undefined(isolate), 0, nullptr));
853

9
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
854
    PrintCaughtException(isolate, context, try_catch);
855
    FatalError("\nnode::inspector::Agent::ToggleAsyncHook",
856
               "Cannot toggle Inspector's AsyncHook, please report this.");
857
  }
858
}
859
860
1
void Agent::AsyncTaskScheduled(const StringView& task_name, void* task,
861
                               bool recurring) {
862
1
  client_->AsyncTaskScheduled(task_name, task, recurring);
863
1
}
864
865
1
void Agent::AsyncTaskCanceled(void* task) {
866
1
  client_->AsyncTaskCanceled(task);
867
1
}
868
869
4
void Agent::AsyncTaskStarted(void* task) {
870
4
  client_->AsyncTaskStarted(task);
871
4
}
872
873
1
void Agent::AsyncTaskFinished(void* task) {
874
1
  client_->AsyncTaskFinished(task);
875
1
}
876
877
void Agent::AllAsyncTasksCanceled() {
878
  client_->AllAsyncTasksCanceled();
879
}
880
881
1
void Agent::RequestIoThreadStart() {
882
  // We need to attempt to interrupt V8 flow (in case Node is running
883
  // continuous JS code) and to wake up libuv thread (in case Node is waiting
884
  // for IO events)
885
1
  CHECK(start_io_thread_async_initialized);
886
1
  uv_async_send(&start_io_thread_async);
887
3
  parent_env_->RequestInterrupt([this](Environment*) {
888
1
    StartIoThread();
889
2
  });
890
891
1
  CHECK(start_io_thread_async_initialized);
892
1
  uv_async_send(&start_io_thread_async);
893
1
}
894
895
5814
void Agent::ContextCreated(Local<Context> context, const ContextInfo& info) {
896
5814
  if (client_ == nullptr)  // This happens for a main context
897
5234
    return;
898
580
  client_->contextCreated(context, info);
899
}
900
901
28139
bool Agent::IsActive() {
902
28139
  if (client_ == nullptr)
903
    return false;
904

28139
  return io_ != nullptr || client_->IsActive();
905
}
906
907
415
void Agent::SetParentHandle(
908
    std::unique_ptr<ParentInspectorHandle> parent_handle) {
909
415
  parent_handle_ = std::move(parent_handle);
910
415
}
911
912
656
std::unique_ptr<ParentInspectorHandle> Agent::GetParentHandle(
913
    uint64_t thread_id, const std::string& url) {
914
656
  if (!parent_handle_) {
915
646
    return client_->getWorkerManager()->NewParentHandle(thread_id, url);
916
  } else {
917
10
    return parent_handle_->NewParentInspectorHandle(thread_id, url);
918
  }
919
}
920
921
void Agent::WaitForConnect() {
922
  CHECK_NOT_NULL(client_);
923
  client_->waitForFrontend();
924
}
925
926
1050
std::shared_ptr<WorkerManager> Agent::GetWorkerManager() {
927
1050
  CHECK_NOT_NULL(client_);
928
1050
  return client_->getWorkerManager();
929
}
930
931
6
std::string Agent::GetWsUrl() const {
932
6
  if (io_ == nullptr)
933
1
    return "";
934
5
  return io_->GetWsUrl();
935
}
936
937
16879
SameThreadInspectorSession::~SameThreadInspectorSession() {
938
11253
  auto client = client_.lock();
939
5626
  if (client)
940
937
    client->disconnectFrontend(session_id_);
941
11253
}
942
943
17105
void SameThreadInspectorSession::Dispatch(
944
    const v8_inspector::StringView& message) {
945
34213
  auto client = client_.lock();
946
17108
  if (client)
947
17108
    client->dispatchMessageFromFrontend(session_id_, message);
948
17110
}
949
950
}  // namespace inspector
951

14520
}  // namespace node