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

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

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

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

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

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

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

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

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