diff --git a/NativeScript/inspector/InspectorQueue.h b/NativeScript/inspector/InspectorQueue.h new file mode 100644 index 00000000..7f63b580 --- /dev/null +++ b/NativeScript/inspector/InspectorQueue.h @@ -0,0 +1,70 @@ +#ifndef InspectorQueue_h +#define InspectorQueue_h + +#include + +#include +#include +#include +#include +#include + +namespace v8_inspector { + +// Frontend messages waiting for an isolate, in arrival order. Push from any +// thread; take only while holding the isolate's Locker, so that a pause loop +// on another thread (which holds it throughout) and the isolate's own drain +// never split a frontend's messages between them. +class InspectorQueue { + public: + struct Item { + enum class Kind { kConnect, kDisconnect, kMessage }; + uint64_t connectionId; + Kind kind; + std::string method; + std::string message; + bool interrupting = false; // see Interrupts + }; + + InspectorQueue(); + ~InspectorQueue(); + InspectorQueue(const InspectorQueue&) = delete; + InspectorQueue& operator=(const InspectorQueue&) = delete; + + // Whether a command runs no JS, so it may be dispatched from an interrupt + // in the middle of the isolate's JS and ahead of the frontend's earlier + // commands. Chromium's list (ShouldInterruptForMethod), without the domains + // V8 does not implement and without Runtime.terminateExecution, which would + // unwind the app's own frames. + static bool Interrupts(const std::string& method); + + static Item Message(uint64_t connectionId, const std::string& method, + std::string message); + + void Push(Item item); + + // Takes the oldest item. Returns false when there is none. + bool Take(Item& item); + + // Takes the interrupting commands, and with them what they need of their + // frontend's earlier items: its connect and Debugger.enable, so that a + // frontend can pause an isolate that was busy before it attached. Those run + // no JS either, but overtake the frontend's other commands only for that. + // Nothing is taken past a disconnect or Debugger.disable. + std::vector TakeInterrupting(); + + // Waits briefly for a Push. + void Wait(); + + // Ends a Wait in progress. + void Wake(); + + private: + std::mutex mutex_; + std::deque items_; + dispatch_semaphore_t pushed_; +}; + +} // namespace v8_inspector + +#endif /* InspectorQueue_h */ diff --git a/NativeScript/inspector/InspectorQueue.mm b/NativeScript/inspector/InspectorQueue.mm new file mode 100644 index 00000000..a83fe37f --- /dev/null +++ b/NativeScript/inspector/InspectorQueue.mm @@ -0,0 +1,94 @@ +#include "InspectorQueue.h" + +#include +#include +#include +#include + +namespace v8_inspector { + +namespace { +bool IsPrerequisite(const InspectorQueue::Item& item) { + return item.kind == InspectorQueue::Item::Kind::kConnect || item.method == "Debugger.enable"; +} + +bool IsBarrier(const InspectorQueue::Item& item) { + return item.kind == InspectorQueue::Item::Kind::kDisconnect || item.method == "Debugger.disable"; +} +} // namespace + +InspectorQueue::InspectorQueue() : pushed_(dispatch_semaphore_create(0)) {} + +InspectorQueue::~InspectorQueue() { dispatch_release(pushed_); } + +bool InspectorQueue::Interrupts(const std::string& method) { + static constexpr const char* kMethods[] = { + "Debugger.getPossibleBreakpoints", "Debugger.getScriptSource", + "Debugger.getStackTrace", "Debugger.pause", + "Debugger.removeBreakpoint", "Debugger.resume", + "Debugger.setBreakpoint", "Debugger.setBreakpointByUrl", + "Debugger.setBreakpointsActive", + }; + return std::any_of(std::begin(kMethods), std::end(kMethods), + [&](const char* name) { return method == name; }); +} + +InspectorQueue::Item InspectorQueue::Message(uint64_t connectionId, const std::string& method, + std::string message) { + return {connectionId, Item::Kind::kMessage, method, std::move(message), Interrupts(method)}; +} + +void InspectorQueue::Push(Item item) { + { + std::lock_guard lock(mutex_); + items_.push_back(std::move(item)); + } + dispatch_semaphore_signal(pushed_); +} + +bool InspectorQueue::Take(Item& item) { + std::lock_guard lock(mutex_); + if (items_.empty()) { + return false; + } + item = std::move(items_.front()); + items_.pop_front(); + return true; +} + +std::vector InspectorQueue::TakeInterrupting() { + std::vector taken; + std::lock_guard lock(mutex_); + + // The index after each frontend's last command to take. + std::map ends; + std::set blocked; + for (size_t i = 0; i < items_.size(); i++) { + const Item& item = items_[i]; + if (IsBarrier(item)) { + blocked.insert(item.connectionId); + } else if (item.interrupting && blocked.count(item.connectionId) == 0) { + ends[item.connectionId] = i + 1; + } + } + + size_t index = 0; + for (auto it = items_.begin(); it != items_.end(); index++) { + auto end = ends.find(it->connectionId); + if (end != ends.end() && index < end->second && (it->interrupting || IsPrerequisite(*it))) { + taken.push_back(std::move(*it)); + it = items_.erase(it); + } else { + ++it; + } + } + return taken; +} + +void InspectorQueue::Wait() { + dispatch_semaphore_wait(pushed_, dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_MSEC)); +} + +void InspectorQueue::Wake() { dispatch_semaphore_signal(pushed_); } + +} // namespace v8_inspector diff --git a/NativeScript/inspector/InspectorServer.h b/NativeScript/inspector/InspectorServer.h index 41e65834..f3c2e4e1 100644 --- a/NativeScript/inspector/InspectorServer.h +++ b/NativeScript/inspector/InspectorServer.h @@ -18,12 +18,10 @@ class InspectorServer { // process-unique connection id: onClientConnected hands out its sender, // and onClientDisconnected fires once with the same id when the // connection closes, after which that sender drops every message. - // One client at a time: accepting a client closes the previous one, and - // that close reports onClientDisconnected before the new onClientConnected. - // A client that closed itself (EOF, read or write error) reports from its - // own queue, which can interleave with a new onClientConnected. A message - // the previous client had already read may reach onMessage after the - // takeover, so callers must check the connection id. + // Any number of clients may be connected at once. For one connection the + // callbacks are ordered: onClientConnected returns before its first + // onMessage, and onClientDisconnected comes after its last. Callbacks for + // different connections run concurrently. static in_port_t Init( std::function onClientConnected, diff --git a/NativeScript/inspector/InspectorServer.mm b/NativeScript/inspector/InspectorServer.mm index 5c539806..2c05bf1b 100644 --- a/NativeScript/inspector/InspectorServer.mm +++ b/NativeScript/inspector/InspectorServer.mm @@ -12,15 +12,37 @@ std::atomic gLastConnectionId{0}; +// A client this far behind that has also read nothing for this long is +// assumed gone (e.g. a half-open socket whose peer vanished without a FIN): +// every client receives broadcast events, so its unsent output would otherwise +// grow without bound. Size alone does not tell: V8 produces a heap snapshot +// much faster than a slow link takes it. +constexpr size_t kMaxPendingWriteBytes = 256 * 1024 * 1024; +constexpr uint64_t kWriteStallNs = 30 * NSEC_PER_SEC; + +// How often a write in progress reports back, so that one large message on a +// slow link still counts as progress. +constexpr size_t kWriteProgressBytes = 256 * 1024; + struct Connection { uint64_t id; dispatch_queue_t queue; dispatch_io_t channel; + // Only changes on `queue`. std::atomic open{true}; + std::atomic pendingWriteBytes{0}; + std::atomic lastWriteProgressNs{0}; + std::atomic watchingForStall{false}; std::function onDisconnected; std::function onMessage; }; +// The peer went away or we closed the channel ourselves (ECANCELED: an +// operation was still queued at close time); routine, not worth a log line. +bool IsDisconnectError(int error) { + return error == ECANCELED || error == ECONNRESET || error == EPIPE; +} + void CloseConnection(const std::shared_ptr& connection) { if (!connection->open.exchange(false)) { return; @@ -46,7 +68,7 @@ void ReadExactly(std::shared_ptr connection, size_t length, return; } if (error != 0 || dispatch_data_get_size(received) < length) { - if (error != 0 && error != ECANCELED) { + if (error != 0 && !IsDisconnectError(error)) { NSLog(@"InspectorServer read error: %s", strerror(error)); } CloseConnection(connection); @@ -56,6 +78,29 @@ void ReadExactly(std::shared_ptr connection, size_t length, }); } +// Closes the connection once it is too far behind and stalled; checks for as +// long as it is too far behind, since no other event need come. +void WatchForStall(std::shared_ptr connection, uint64_t delayNs) { + if (connection->watchingForStall.exchange(true)) { + return; + } + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayNs), connection->queue, ^{ + connection->watchingForStall = false; + if (!connection->open.load() || connection->pendingWriteBytes <= kMaxPendingWriteBytes) { + return; + } + uint64_t now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + uint64_t progress = connection->lastWriteProgressNs; + uint64_t stalled = now > progress ? now - progress : 0; + if (stalled >= kWriteStallNs) { + NSLog(@"InspectorServer: closing a client that stopped reading"); + CloseConnection(connection); + return; + } + WatchForStall(connection, kWriteStallNs - stalled); + }); +} + // Messages are a big-endian uint32 byte length followed by UTF-16LE text. void ReadNextMessage(std::shared_ptr connection) { ReadExactly(connection, sizeof(uint32_t), ^(dispatch_data_t header) { @@ -70,6 +115,11 @@ void ReadNextMessage(std::shared_ptr connection) { ReadExactly(connection, length, ^(dispatch_data_t body) { NSString* payload = [[NSString alloc] initWithData:(NSData*)body encoding:NSUTF16LittleEndianStringEncoding]; + // A write error may have closed the connection after this read + // completed; onMessage must never follow onDisconnected. + if (!connection->open.load()) { + return; + } const char* utf8 = [payload UTF8String]; if (utf8 != nullptr) { connection->onMessage(connection->id, utf8); @@ -99,19 +149,31 @@ void Send(std::shared_ptr connection, const std::string& message) { range:NSMakeRange(0, str.length) remainingRange:NULL]; - dispatch_data_t data = - dispatch_data_create(buffer, length + sizeof(uint32_t), connection->queue, ^{ - free(buffer); - }); + size_t size = length + sizeof(uint32_t); + dispatch_data_t data = dispatch_data_create(buffer, size, connection->queue, ^{ + free(buffer); + }); + + size_t pending = connection->pendingWriteBytes.fetch_add(size); + if (pending == 0) { + connection->lastWriteProgressNs = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + } + if (pending + size > kMaxPendingWriteBytes) { + WatchForStall(connection, kWriteStallNs); + } dispatch_io_write(connection->channel, 0, data, connection->queue, ^(bool done, dispatch_data_t data, int error) { - // ECANCELED: the write was still queued when the - // connection closed. - if (error == 0 || error == ECANCELED) { + if (done) { + connection->pendingWriteBytes.fetch_sub(size); + } + connection->lastWriteProgressNs = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + if (error == 0) { return; } - NSLog(@"InspectorServer::Send error: %s", strerror(error)); + if (!IsDisconnectError(error)) { + NSLog(@"InspectorServer::Send error: %s", strerror(error)); + } CloseConnection(connection); }); } @@ -145,10 +207,6 @@ void Send(std::shared_ptr connection, const std::string& message) { assert(false); } - // Only touched by the accept handler, which libdispatch never runs - // concurrently with itself. - __block std::weak_ptr activeConnection; - // Set up the dispatch source that will alert us to new incoming connections dispatch_queue_t q = dispatch_queue_create("server_queue", DISPATCH_QUEUE_CONCURRENT); dispatch_source_t acceptSource = @@ -189,14 +247,10 @@ void Send(std::shared_ptr connection, const std::string& message) { close(clientSocket); continue; } + dispatch_io_set_high_water(connection->channel, kWriteProgressBytes); - // The accept handler is serial, so back-to-back accepts take over in - // order and the newest client stays active. - std::shared_ptr previous = activeConnection.lock(); - activeConnection = connection; - if (previous != nullptr) { - CloseConnection(previous); - } + // Reads start only after this returns, so the client's first message + // cannot overtake its own connect. onClientConnected(connection->id, [connection](const std::string& message) { Send(connection, message); }); diff --git a/NativeScript/inspector/InspectorSessions.h b/NativeScript/inspector/InspectorSessions.h new file mode 100644 index 00000000..1088fc0d --- /dev/null +++ b/NativeScript/inspector/InspectorSessions.h @@ -0,0 +1,101 @@ +#ifndef InspectorSessions_h +#define InspectorSessions_h + +#include +#include +#include +#include +#include + +#include "include/v8-inspector.h" + +namespace v8_inspector { + +// One V8InspectorSession per connected frontend, all on one isolate and +// context group. Each session's output goes only to its own frontend. +// +// Every method requires the isolate's Locker. JS may run on any thread that +// takes it, so a pause loop and an interrupt can feed the sessions from +// another thread than the isolate's own. +class InspectorSessions { + public: + using Output = + std::function; + + InspectorSessions(v8::Isolate* isolate, int contextGroupId, Output output); + ~InspectorSessions(); + + // Creates the frontend's session unless it already has one. + void Connect(V8Inspector* inspector, uint64_t connectionId); + + // Ignored for a frontend without a session or one being closed. + void Dispatch(uint64_t connectionId, const std::string& method, + const std::string& message); + + // Destroys the frontend's session. Its destructor disables its agents, so + // a pause ends only if no other frontend still has the debugger enabled. + // A session with V8 frames on the stack cannot be destroyed: it may be + // dispatching (a pause loop can sit under its dispatchProtocolMessage), or + // serializing an object whose getter paused. It then gets Debugger.disable + // right away and is destroyed once its dispatch returns or the pause is + // over. + void Disconnect(uint64_t connectionId); + + // Brackets the isolate's pause loop. + void PauseStarted(); + void PauseEnded(); + + // Destroys the sessions whose frontend left during a pause. V8 still uses + // the sessions after the pause loop returns, so call this from the first + // drain after it. + void DestroyClosed(); + + // Destroys every session. Never while any of them is dispatching. + void DisconnectAll(); + + bool Has(uint64_t connectionId) const; + + private: + class Channel; + struct Session { + std::unique_ptr channel; + std::unique_ptr session; + int dispatchDepth = 0; + bool closing = false; + bool debuggerEnabled = false; + // Asked for a pause that has not happened yet. + bool pausePending = false; + }; + + // V8 keeps a pending pause, and the step in progress, per thread, and that + // state does not survive here. Releasing a thread's outermost Locker frees + // it, which a worker does after every task, and another thread's Locker + // turns off the hook it depends on. It is also unsafe to leave behind: a + // step that outlives its JS frames crashes Debug::RestoreDebug when the + // thread's state is restored from an archive (another thread having held + // the Locker). So a pending pause is set again whenever JS is entered, and + // a step that ran off the end of its JS becomes a pending pause. + static void OnCallEntered(v8::Isolate* isolate); + static void OnCallCompleted(v8::Isolate* isolate); + static void OnMicrotasksCompleted(v8::Isolate* isolate, void* data); + void FinishStep(); + void TrackPause(uint64_t connectionId, Session* session, + const std::string& method); + + void DispatchTo(Session* session, const std::string& message); + void Destroy(uint64_t connectionId); + + v8::Isolate* isolate_; + int contextGroupId_; + Output output_; + std::map> sessions_; + bool paused_ = false; + // A step was requested and nothing has paused since. + bool stepping_ = false; + // Who to pause for once the step runs off the end, 0 for nobody. + uint64_t stepper_ = 0; +}; + +} // namespace v8_inspector + +#endif /* InspectorSessions_h */ diff --git a/NativeScript/inspector/InspectorSessions.mm b/NativeScript/inspector/InspectorSessions.mm new file mode 100644 index 00000000..a2a45af6 --- /dev/null +++ b/NativeScript/inspector/InspectorSessions.mm @@ -0,0 +1,241 @@ +#include "InspectorSessions.h" + +#include "Caches.h" +#include "src/debug/debug-interface.h" +#include "utils.h" + +using namespace v8; + +namespace v8_inspector { + +namespace { +StringView Make8BitStringView(const std::string& value) { + return StringView(reinterpret_cast(value.data()), value.size()); +} + +// Finds an isolate's sessions from the V8 callbacks, which carry no data. +struct SessionsSlot { + InspectorSessions* sessions = nullptr; +}; + +constexpr const char* kDisableDebugger = "{\"id\":0,\"method\":\"Debugger.disable\"}"; +} // namespace + +class InspectorSessions::Channel final : public V8Inspector::Channel { + public: + Channel(const Output& output, uint64_t connectionId) + : output_(output), connectionId_(connectionId) {} + + void sendResponse(int callId, std::unique_ptr message) override { + output_(connectionId_, ToStdString(message->string())); + } + + void sendNotification(std::unique_ptr message) override { + output_(connectionId_, ToStdString(message->string())); + } + + void flushProtocolNotifications() override {} + + private: + const Output& output_; + uint64_t connectionId_; +}; + +InspectorSessions::InspectorSessions(Isolate* isolate, int contextGroupId, Output output) + : isolate_(isolate), contextGroupId_(contextGroupId), output_(std::move(output)) { + if (auto* slot = tns::Caches::StateFor(isolate_)) { + slot->sessions = this; + isolate_->AddBeforeCallEnteredCallback(OnCallEntered); + isolate_->AddCallCompletedCallback(OnCallCompleted); + isolate_->AddMicrotasksCompletedCallback(OnMicrotasksCompleted, this); + } +} + +InspectorSessions::~InspectorSessions() { + if (auto* slot = tns::Caches::ExistingStateFor(isolate_)) { + slot->sessions = nullptr; + } + isolate_->RemoveBeforeCallEnteredCallback(OnCallEntered); + isolate_->RemoveCallCompletedCallback(OnCallCompleted); + isolate_->RemoveMicrotasksCompletedCallback(OnMicrotasksCompleted, this); + this->DisconnectAll(); +} + +void InspectorSessions::OnCallEntered(Isolate* isolate) { + auto* slot = tns::Caches::ExistingStateFor(isolate); + if (slot == nullptr || slot->sessions == nullptr || slot->sessions->paused_) { + return; + } + for (const auto& entry : slot->sessions->sessions_) { + if (entry.second->pausePending) { + v8::debug::SetBreakOnNextFunctionCall(isolate); + return; + } + } +} + +void InspectorSessions::OnCallCompleted(Isolate* isolate) { + auto* slot = tns::Caches::ExistingStateFor(isolate); + if (slot != nullptr && slot->sessions != nullptr) { + slot->sessions->FinishStep(); + } +} + +void InspectorSessions::OnMicrotasksCompleted(Isolate* isolate, void* data) { + static_cast(data)->FinishStep(); +} + +void InspectorSessions::FinishStep() { + if (!stepping_ || paused_) { + return; + } + HandleScope handle_scope(isolate_); + if (StackTrace::CurrentStackTrace(isolate_, 1)->GetFrameCount() != 0) { + return; + } + stepping_ = false; + v8::debug::ClearStepping(isolate_); + auto it = sessions_.find(stepper_); + if (it != sessions_.end() && it->second->debuggerEnabled && !it->second->closing) { + it->second->pausePending = true; + } +} + +void InspectorSessions::TrackPause(uint64_t connectionId, Session* session, + const std::string& method) { + if (method == "Debugger.enable") { + session->debuggerEnabled = true; + } else if (method == "Debugger.disable") { + session->debuggerEnabled = false; + session->pausePending = false; + } else if (method == "Debugger.setSkipAllPauses" || method == "Debugger.setBreakpointsActive") { + // Either can cancel the pause. + session->pausePending = false; + } else if (method == "Debugger.pause") { + session->pausePending = session->debuggerEnabled && !paused_; + } else if (paused_ && (method == "Debugger.stepInto" || method == "Debugger.stepOver" || + method == "Debugger.stepOut")) { + stepping_ = true; + // Like V8, whose step over or into a return pauses in the next function + // called. + stepper_ = method == "Debugger.stepOut" ? 0 : connectionId; + } else if (paused_ && (method == "Debugger.resume" || method == "Debugger.continueToLocation" || + method == "Debugger.restartFrame")) { + // The pause goes on after a step only if V8 rejected it. + stepping_ = false; + stepper_ = 0; + } +} + +void InspectorSessions::Connect(V8Inspector* inspector, uint64_t connectionId) { + if (sessions_.count(connectionId) != 0) { + return; + } + + Isolate::Scope isolate_scope(isolate_); + HandleScope handle_scope(isolate_); + + auto entry = std::make_unique(); + entry->channel = std::make_unique(output_, connectionId); + entry->session = + inspector->connect(contextGroupId_, entry->channel.get(), {}, V8Inspector::kFullyTrusted); + sessions_.emplace(connectionId, std::move(entry)); +} + +void InspectorSessions::Dispatch(uint64_t connectionId, const std::string& method, + const std::string& message) { + auto it = sessions_.find(connectionId); + if (it == sessions_.end() || it->second->closing) { + return; + } + + Session* session = it->second.get(); + // Before the dispatch, which can pause. + this->TrackPause(connectionId, session, method); + this->DispatchTo(session, message); + if (session->closing && session->dispatchDepth == 0 && !paused_) { + this->Destroy(connectionId); + } +} + +void InspectorSessions::DispatchTo(Session* session, const std::string& message) { + Isolate::Scope isolate_scope(isolate_); + HandleScope handle_scope(isolate_); + + // Destroy never runs while this is above zero, so `session` stays valid + // across the call even if the frontend disconnects inside it. + session->dispatchDepth++; + session->session->dispatchProtocolMessage(Make8BitStringView(message)); + session->dispatchDepth--; +} + +void InspectorSessions::Disconnect(uint64_t connectionId) { + auto it = sessions_.find(connectionId); + if (it == sessions_.end()) { + return; + } + + Session* session = it->second.get(); + if (session->dispatchDepth == 0 && !paused_) { + this->Destroy(connectionId); + return; + } + + if (!session->closing) { + session->closing = true; + session->debuggerEnabled = false; + session->pausePending = false; + this->DispatchTo(session, kDisableDebugger); + } +} + +void InspectorSessions::PauseStarted() { + paused_ = true; + stepping_ = false; + stepper_ = 0; + for (auto& entry : sessions_) { + entry.second->pausePending = false; + } +} + +void InspectorSessions::PauseEnded() { paused_ = false; } + +void InspectorSessions::DestroyClosed() { + if (paused_) { + return; + } + for (auto it = sessions_.begin(); it != sessions_.end();) { + uint64_t connectionId = it->first; + bool destroy = it->second->closing && it->second->dispatchDepth == 0; + ++it; + if (destroy) { + this->Destroy(connectionId); + } + } +} + +void InspectorSessions::DisconnectAll() { + while (!sessions_.empty()) { + this->Destroy(sessions_.begin()->first); + } +} + +bool InspectorSessions::Has(uint64_t connectionId) const { + auto it = sessions_.find(connectionId); + return it != sessions_.end() && !it->second->closing; +} + +void InspectorSessions::Destroy(uint64_t connectionId) { + auto node = sessions_.extract(connectionId); + if (node.empty()) { + return; + } + + Isolate::Scope isolate_scope(isolate_); + HandleScope handle_scope(isolate_); + // The session uses its channel until its destructor returns. + node.mapped()->session.reset(); + node.mapped()->channel.reset(); +} + +} // namespace v8_inspector diff --git a/NativeScript/inspector/JsV8InspectorClient.h b/NativeScript/inspector/JsV8InspectorClient.h index 4e3d4bc6..28cea9e5 100644 --- a/NativeScript/inspector/JsV8InspectorClient.h +++ b/NativeScript/inspector/JsV8InspectorClient.h @@ -1,19 +1,23 @@ #ifndef JsV8InspectorClient_h #define JsV8InspectorClient_h -#include #include #include #include #include +#include #include #include +#include #include #include +#include "InspectorQueue.h" +#include "InspectorSessions.h" #include "include/v8-inspector.h" #include "ns-v8-tracing-agent-impl.h" +#include "runtime/IsolateWrapper.h" #include "runtime/Runtime.h" #include "src/inspector/v8-console-message.h" @@ -21,48 +25,44 @@ namespace v8_inspector { class WorkerInspectorClient; -class JsV8InspectorClient : V8InspectorClient, V8Inspector::Channel { +// Debugs the main isolate and routes worker sessions. Any number of frontends +// may be connected; each gets its own V8 session on the main isolate and on +// every worker, and only sees replies to its own commands. Pauses are shared, +// as in Chrome: every frontend with the debugger enabled sees them, and any +// of them can resume. Isolate-wide V8 state is shared too: heap object +// tracking and sampling (any frontend's HeapProfiler.disable, or its +// disconnect, stops them for all) and the pause-on-exceptions setting (last +// writer wins). +class JsV8InspectorClient : V8InspectorClient { public: JsV8InspectorClient(tns::Runtime* runtime); void init(); void connect(int argc, char** argv); - void dispatchMessage(const std::string& message); // The single instance debugging the main isolate (created when IsDebug); // also acts as the router for worker sessions. Null in release builds. static JsV8InspectorClient* GetInstance(); - // Thread-safe write to the connected frontend (no-op when disconnected). - void SendToFrontend(const std::string& message); + // Thread-safe write to one frontend; dropped once it has disconnected. + void SendToConnection(uint64_t connectionId, const std::string& message); - // As SendToFrontend, but skips the source map rewrite (and the full-message - // scan and copy it costs) for payloads that cannot contain a sourceMapURL. - void SendRawToFrontend(const std::string& message); - - // Bumped, atomically with the sender swap, whenever a frontend goes away - // or is replaced. A worker session records it when created, reset or - // registered; output it sends with a stale generation belongs to a - // departed frontend and is dropped instead of reaching the next one. - uint64_t FrontendGeneration(); - void SendWorkerOutput(uint64_t generation, const std::string& message); + // As SendToConnection, but skips the source map rewrite (and the + // full-message scan and copy it costs) for payloads that cannot contain a + // sourceMapURL. + void SendRawToConnection(uint64_t connectionId, const std::string& message); // Worker targets (Chrome DevTools Target domain, flat-session mode). // Register/Unregister are called on the worker's own thread. void RegisterWorkerTarget(int workerId, WorkerInspectorClient* client); void UnregisterWorkerTarget(int workerId); - // Called on a worker thread by the Debugger.pause interrupt. - void SchedulePauseInWorker(int workerId); - - // Overrides of V8Inspector::Channel - void sendResponse(int callId, std::unique_ptr message) override; - void sendNotification(std::unique_ptr message) override; - void flushProtocolNotifications() override; + // Called by the interrupt WorkerInspectorClient requests, on the thread + // running the worker's JS. + void DispatchInterruptingInWorker(int workerId); // Overrides of V8InspectorClient void runMessageLoopOnPause(int contextGroupId) override; void quitMessageLoopOnPause() override; - void scheduleBreak(); void registerModules(); void consoleLog(v8::Isolate* isolate, ConsoleAPIType method, @@ -73,50 +73,64 @@ class JsV8InspectorClient : V8InspectorClient, V8Inspector::Channel { private: static constexpr int contextGroupId = 1; - // Queued on every connect and disconnect, ahead of anything the new - // frontend sends. When dispatched it replaces the main session if it served - // another connection, then binds the session's output to the current one. - static constexpr const char* kSessionSyncMessage = - "{\"__nsInternal\":\"syncSession\"}"; - - std::atomic isConnected_{false}; - // Set when a reset arrives inside the pause loop (which may run on any - // thread holding the Locker), where the session may still be on the stack; - // the next drain after the loop exits performs it. - std::atomic pendingSessionReset_{false}; in_port_t listenPort_ = 0; // main queue only std::unique_ptr inspector_; v8::Persistent context_; - std::unique_ptr session_; + // Main isolate sessions, one per frontend; needs the isolate's Locker. + std::unique_ptr sessions_; tns::Runtime* runtime_; v8::Isolate* isolate_; - bool terminated_ = false; - std::queue messages_; - bool runningNestedLoops_; - dispatch_queue_t messagesQueue_; - dispatch_queue_t messageLoopQueue_; - dispatch_semaphore_t messageArrived_; - // The current connection; guarded by senderMutex_. - std::function sender_; - uint64_t connectionId_ = 0; - // The connection the main session serves, which lags the current one until - // the sync message is dispatched. Session output goes here, so replies to - // a replaced frontend's in-flight commands never reach its successor. - // Guarded by senderMutex_. - std::function sessionSender_; - uint64_t sessionConnectionId_ = 0; - uint64_t frontendGeneration_ = 0; // guarded by senderMutex_ - bool isWaitingForDebugger_ = false; - bool hasScheduledDebugBreak_ = false; + tns::IsolateWrapper isolateWrapper_; + // The runtime's loop. Outlives the runtime, after which it drops posts. + std::shared_ptr eventLoop_; + // Work for the main isolate. Connect and disconnect go through the same + // queue as messages so a frontend's session exists before its first message + // and outlives its last. Taken from only under the isolate's Locker. + InspectorQueue messages_; + // Written by the pause loop's thread. Read elsewhere only as a hint unless + // the Locker is held, which that thread keeps for the whole pause. + std::atomic runningPauseLoop_{false}; + bool pauseTerminated_ = false; // needs the Locker + bool draining_ = false; // runtime thread only + + // --nativescript-debug-brk: the app's start, held for frontends to get + // ready. + struct DebuggerWait { + bool waiting = false; + // Frontends that may still be setting up. + std::set holders; + // One was ready, so the last holder starts the app. Without it, a frontend + // that came and went (a probe, a reload) leaves the app waiting. + bool anyReady = false; + bool pauseBeforeApp = false; + }; + DebuggerWait debuggerWait_; // guarded by debuggerWaitMutex_ + std::mutex debuggerWaitMutex_; + + // Connected frontends' senders; guarded by frontendsMutex_, which is never + // held while taking another lock or calling a sender. + std::map> frontends_; + std::mutex frontendsMutex_; + // Frontends that sent .enable to a JS domain handler (DOM, CSS, + // Network, ... from @nativescript/core). Those handlers are global, so a + // .disable only reaches them once no other frontend wants the + // domain. Needs the isolate's Locker. + std::map> jsDomainEnablers_; + + // The process-global trace controller serves one frontend at a time. std::unique_ptr tracing_agent_; + uint64_t tracingOwner_ = 0; // guarded by tracingMutex_ + std::mutex tracingMutex_; // Streams backing Network.loadNetworkResource responses, read by the - // frontend through IO.read/IO.close (how Chrome DevTools fetches source - // maps from the target). Served on the socket thread for any session; - // guarded by resourceStreamsMutex_. Like Chromium's DevToolsIOContext, a - // stream lives until IO.close or until its frontend goes away. + // frontend that opened them through IO.read/IO.close (how Chrome DevTools + // fetches source maps from the target). Served on the socket thread for + // any session; guarded by resourceStreamsMutex_. Like Chromium's + // DevToolsIOContext, a stream lives until IO.close or until its frontend + // goes away. struct ResourceStream { + uint64_t connectionId; std::string data; // Chromium sends valid UTF-8 as text and everything else as base64. bool binary = false; @@ -126,64 +140,64 @@ class JsV8InspectorClient : V8InspectorClient, V8Inspector::Channel { int lastStreamId_ = 0; std::mutex resourceStreamsMutex_; - // Worker targets announced to the frontend via Target.attachedToTarget, - // keyed by their flat-protocol sessionId. Guarded by workerTargetsMutex_; - // a registered client pointer stays valid until UnregisterWorkerTarget - // (which runs on the worker's own thread, before the client is deleted). + // Worker targets, keyed by their flat-protocol sessionId. A registered + // client pointer stays valid until UnregisterWorkerTarget (which runs on + // the worker's own thread, before the client is deleted). struct WorkerTarget { int workerId; WorkerInspectorClient* client; - bool announced = false; }; + // Target domain state of one connected frontend. + struct TargetState { + bool autoAttach = false; + // sessionIds of the workers announced to this frontend. + std::set announced; + }; + // Both guarded by workerTargetsMutex_, which is taken before + // frontendsMutex_. A frontend has a TargetState exactly while it is + // connected, so nothing reaches a worker on its behalf after the worker + // was told it disconnected. std::map workerTargets_; + std::map targetStates_; std::mutex workerTargetsMutex_; - bool autoAttach_ = false; // guarded by workerTargetsMutex_ static JsV8InspectorClient* instance_; - std::mutex senderMutex_; - // Serializes onFrontendConnected/onFrontendDisconnected/ - // onFrontendMessageReceived, which run on different connection queues. - // Taken before senderMutex_, workerTargetsMutex_ and resourceStreamsMutex_, - // never while holding any of them. - std::mutex frontendLifecycleMutex_; - // Routes a frontend message carrying a sessionId to its worker session // (socket thread). msgId is -1 when the message has no id. - void RouteToWorker(const std::string& sessionId, const std::string& method, - long long msgId, const std::string& message); - // Announces all not-yet-announced workers (after Target.setAutoAttach). - void AnnounceWorkerTargets(); + void RouteToWorker(uint64_t connectionId, const std::string& sessionId, + const std::string& method, long long msgId, + const std::string& message); + // Announces every worker not yet announced to the frontend. Requires + // workerTargetsMutex_. + void AnnounceWorkerTargetsLocked(uint64_t connectionId, TargetState& state); + void SendAttachedToTarget(uint64_t connectionId, + WorkerInspectorClient* client); // Override of V8InspectorClient v8::Local ensureDefaultContextInGroup( int contextGroupId) override; void enableInspector(int argc, char** argv); - void createInspectorSession(); - void notify(std::unique_ptr message); - void notify(const std::string& message); + void StartDebuggerWait(); + bool IsWaitingForDebugger(); + // The frontend holds the app until it sends Runtime.runIfWaitingForDebugger, + // leaves, or runs out of time. + void HoldForDebugger(uint64_t connectionId); + void StopHolding(uint64_t connectionId, bool ready); + void PauseBeforeApp(); + void SendToAll(const std::string& message); void onFrontendConnected(uint64_t connectionId, std::function sender); void onFrontendDisconnected(uint64_t connectionId); void onFrontendMessageReceived(uint64_t connectionId, const std::string& message); - // Socket thread: drops the state owned by the departing frontend that does - // not need the main isolate (IO streams, tracing, worker sessions). - void ResetFrontendState(); - // Pause loop only: resumes and defers the session swap to the next drain. - void DeferSessionResetFromPauseLoop(); - void ResetMainSession(); - // Binds the session to the current connection unless it served another - // one, in which case it binds nothing and returns false. - bool TryBindSession(); - // Never inside the pause loop: replaces the session if needed, then binds. - void SyncSessionWithFrontend(); - bool SessionOwnsFrontend(); - void QueueSessionSync(); - void EnqueueMessage(const std::string& message); + void Enqueue(InspectorQueue::Item item); void ScheduleMessageDrain(); - std::string PumpMessage(); + void DrainMessages(); + void HandleQueued(const InspectorQueue::Item& item); + void DispatchFrontendMessage(uint64_t connectionId, + const std::string& message); static void registerDomainDispatcherCallback( const v8::FunctionCallbackInfo& args); static void inspectorSendEventCallback( @@ -195,14 +209,15 @@ class JsV8InspectorClient : V8InspectorClient, V8Inspector::Channel { // domain). V8's inspector doesn't implement these embedder domains. The // handlers are filesystem-only and thread-safe; they serve any session // (sessionId is echoed in the reply when non-empty). - void HandleLoadNetworkResource(int msgId, const std::string& url, + void HandleLoadNetworkResource(uint64_t connectionId, int msgId, + const std::string& url, const std::string& sessionId); - void HandleIORead(int msgId, const std::string& handle, + void HandleIORead(uint64_t connectionId, int msgId, const std::string& handle, std::optional offset, std::optional size, const std::string& sessionId); - void HandleIOClose(int msgId, const std::string& handle, - const std::string& sessionId); + void HandleIOClose(uint64_t connectionId, int msgId, + const std::string& handle, const std::string& sessionId); // {N} specific helpers bool CallDomainHandlerFunction(v8::Local context, diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 0a2eb325..fcd2578f 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -4,6 +4,7 @@ #include #include #include +#include #include "src/inspector/v8-console-message.h" #include "src/inspector/v8-inspector-impl.h" @@ -223,12 +224,10 @@ bool GetInt32(const json& value, long long& out) { [[NSBundle mainBundle] bundleIdentifier]) JsV8InspectorClient::JsV8InspectorClient(tns::Runtime* runtime) - : runtime_(runtime), isolate_(runtime_->GetIsolate()), messages_(), runningNestedLoops_(false) { - this->messagesQueue_ = - dispatch_queue_create("NativeScript.v8.inspector.message_queue", DISPATCH_QUEUE_SERIAL); - this->messageLoopQueue_ = - dispatch_queue_create("NativeScript.v8.inspector.message_loop_queue", DISPATCH_QUEUE_SERIAL); - this->messageArrived_ = dispatch_semaphore_create(0); + : runtime_(runtime), + isolate_(runtime_->GetIsolate()), + isolateWrapper_(isolate_), + eventLoop_(runtime_->GetEventLoop()) { instance_ = this; } @@ -239,23 +238,7 @@ bool GetInt32(const json& value, long long& out) { notify_register_dispatch( NOTIFICATION("WaitForDebugger"), &waitForDebuggerSubscription, dispatch_get_main_queue(), ^(int token) { - this->isWaitingForDebugger_ = YES; - - dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30); - dispatch_after(delay, dispatch_get_main_queue(), ^{ - if (this->isWaitingForDebugger_) { - this->isWaitingForDebugger_ = NO; - NSLog(@"NativeScript waiting for debugger timeout elapsed. Continuing execution."); - } - }); - - NSLog(@"NativeScript waiting for debugger."); - CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopDefaultMode, ^{ - do { - CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false); - } while (this->isWaitingForDebugger_); - }); - CFRunLoopWakeUp(CFRunLoopGetMain()); + this->StartDebuggerWait(); }); int attachRequestSubscription; @@ -303,91 +286,140 @@ bool GetInt32(const json& value, long long& out) { CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, false); notify_cancel(waitForDebuggerSubscription); -} - -void JsV8InspectorClient::onFrontendConnected(uint64_t connectionId, - std::function sender) { - std::lock_guard lifecycle(this->frontendLifecycleMutex_); - if (this->isWaitingForDebugger_) { - this->isWaitingForDebugger_ = NO; - CFRunLoopRef runloop = CFRunLoopGetMain(); - CFRunLoopPerformBlock(runloop, (__bridge CFTypeRef)(NSRunLoopCommonModes), ^{ - CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, false); - this->scheduleBreak(); - }); - CFRunLoopWakeUp(runloop); + while (this->IsWaitingForDebugger()) { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false); + } + bool pauseBeforeApp; + { + std::lock_guard lock(this->debuggerWaitMutex_); + pauseBeforeApp = this->debuggerWait_.pauseBeforeApp; } + if (pauseBeforeApp) { + this->PauseBeforeApp(); + } +} - bool replacesFrontend; +void JsV8InspectorClient::StartDebuggerWait() { { - std::lock_guard lock(this->senderMutex_); - replacesFrontend = this->connectionId_ != 0; - if (replacesFrontend) { - ++this->frontendGeneration_; + std::lock_guard lock(this->debuggerWaitMutex_); + if (this->debuggerWait_.waiting) { + return; } - this->sender_ = sender; - this->connectionId_ = connectionId; + this->debuggerWait_.waiting = true; } + NSLog(@"NativeScript waiting for debugger."); - // The frontend's Debugger.enable must land on a fresh session so it replays - // Debugger.scriptParsed etc. The sync is ahead of anything this connection - // sends, since its reads only start after this returns. Without a previous - // frontend the disconnect (serialized with us by frontendLifecycleMutex_) - // already reset the frontend state (IO streams, tracing, worker sessions). - if (replacesFrontend) { - this->ResetFrontendState(); + std::vector connected; + { + std::lock_guard lock(this->frontendsMutex_); + for (const auto& entry : this->frontends_) { + connected.push_back(entry.first); + } + } + for (uint64_t connectionId : connected) { + this->HoldForDebugger(connectionId); } - this->QueueSessionSync(); - this->isConnected_ = true; + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 30), dispatch_get_main_queue(), ^{ + std::lock_guard lock(this->debuggerWaitMutex_); + if (this->debuggerWait_.waiting && this->debuggerWait_.holders.empty()) { + this->debuggerWait_.waiting = false; + NSLog(@"NativeScript waiting for debugger timeout elapsed. Continuing execution."); + } + }); } -void JsV8InspectorClient::onFrontendDisconnected(uint64_t connectionId) { - std::lock_guard lifecycle(this->frontendLifecycleMutex_); +bool JsV8InspectorClient::IsWaitingForDebugger() { + std::lock_guard lock(this->debuggerWaitMutex_); + return this->debuggerWait_.waiting; +} +void JsV8InspectorClient::HoldForDebugger(uint64_t connectionId) { { - std::lock_guard lock(this->senderMutex_); - // A newer connection already took over. - if (this->connectionId_ != connectionId) { + std::lock_guard lock(this->debuggerWaitMutex_); + if (!this->debuggerWait_.waiting || !this->debuggerWait_.holders.insert(connectionId).second) { return; } - ++this->frontendGeneration_; - this->sender_ = nullptr; - this->connectionId_ = 0; } + // For frontends that never send Runtime.runIfWaitingForDebugger: long enough + // to enable the debugger. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 3), dispatch_get_main_queue(), ^{ + this->StopHolding(connectionId, true); + }); +} - // Nobody is left to resume a pause or read what the session emits. - this->isConnected_ = false; - this->ResetFrontendState(); - this->QueueSessionSync(); +void JsV8InspectorClient::StopHolding(uint64_t connectionId, bool ready) { + std::lock_guard lock(this->debuggerWaitMutex_); + DebuggerWait& wait = this->debuggerWait_; + if (!wait.waiting || wait.holders.erase(connectionId) == 0) { + return; + } + wait.anyReady |= ready; + if (wait.holders.empty() && wait.anyReady) { + wait.waiting = false; + wait.pauseBeforeApp = true; + } } -void JsV8InspectorClient::QueueSessionSync() { - // Everything still queued came from a departed frontend (or is an earlier - // sync, which this one supersedes). Dropping it keeps its replies, whose - // ids may collide with the next frontend's, from reaching that frontend. - dispatch_sync(this->messagesQueue_, ^{ - this->messages_ = {}; - this->messages_.push(kSessionSyncMessage); - dispatch_semaphore_signal(messageArrived_); - }); - this->ScheduleMessageDrain(); +void JsV8InspectorClient::onFrontendConnected(uint64_t connectionId, + std::function sender) { + { + std::lock_guard lock(this->frontendsMutex_); + this->frontends_[connectionId] = std::move(sender); + } + { + std::lock_guard lock(this->workerTargetsMutex_); + this->targetStates_[connectionId] = TargetState(); + } + // After frontends_ has it, so that StartDebuggerWait cannot miss it. + this->HoldForDebugger(connectionId); + + this->Enqueue({connectionId, InspectorQueue::Item::Kind::kConnect}); } -void JsV8InspectorClient::onFrontendMessageReceived(uint64_t connectionId, - const std::string& message) { - // Held through processing so a takeover cannot run between the check and - // the enqueue: its reset then drops anything this queued. - std::lock_guard lifecycle(this->frontendLifecycleMutex_); +void JsV8InspectorClient::onFrontendDisconnected(uint64_t connectionId) { + // Workers drop the frontend's sessions; their remaining output for it is + // dropped by SendToConnection. { - std::lock_guard lock(this->senderMutex_); - // Read before its connection was replaced; the reply would reach the new - // frontend. - if (this->connectionId_ != connectionId) { - return; + std::lock_guard lock(this->workerTargetsMutex_); + this->targetStates_.erase(connectionId); + for (auto& entry : this->workerTargets_) { + entry.second.client->PushDisconnect(connectionId); } } + { + std::lock_guard lock(this->frontendsMutex_); + this->frontends_.erase(connectionId); + } + // Resource stream handles only have meaning to the frontend that opened + // them, so drop any streams it never closed via IO.close. + { + std::lock_guard lock(this->resourceStreamsMutex_); + for (auto it = this->resourceStreams_.begin(); it != this->resourceStreams_.end();) { + if (it->second.connectionId == connectionId) { + it = this->resourceStreams_.erase(it); + } else { + ++it; + } + } + } + + // Free the process-global trace controller for other frontends. + { + std::lock_guard lock(this->tracingMutex_); + if (this->tracingOwner_ == connectionId) { + this->tracingOwner_ = 0; + tracing_agent_->stopAndDiscard(); + } + } + + this->Enqueue({connectionId, InspectorQueue::Item::Kind::kDisconnect}); +} + +void JsV8InspectorClient::onFrontendMessageReceived(uint64_t connectionId, + const std::string& message) { // Single parse, on the socket thread, used for routing and fast paths. auto parsed = json::parse(message, nullptr, false); std::string sessionId; @@ -411,10 +443,11 @@ bool GetInt32(const json& value, long long& out) { // for any session — even while the main isolate is paused. if (method == "Network.loadNetworkResource") { std::string url; - if (parsed.contains("params") && parsed["params"].contains("url")) { + if (parsed.contains("params") && parsed["params"].contains("url") && + parsed["params"]["url"].is_string()) { url = parsed["params"]["url"].get(); } - this->HandleLoadNetworkResource(static_cast(msgId), url, sessionId); + this->HandleLoadNetworkResource(connectionId, static_cast(msgId), url, sessionId); return; } @@ -443,11 +476,11 @@ bool GetInt32(const json& value, long long& out) { if (!validParams) { json error = {{"id", msgId}, {"error", {{"code", -32602}, {"message", "Invalid parameters"}}}}; - this->SendToFrontend(WithSessionId(error, sessionId).dump()); + this->SendToConnection(connectionId, WithSessionId(error, sessionId).dump()); } else if (method == "IO.read") { - this->HandleIORead(static_cast(msgId), handle, offset, size, sessionId); + this->HandleIORead(connectionId, static_cast(msgId), handle, offset, size, sessionId); } else { - this->HandleIOClose(static_cast(msgId), handle, sessionId); + this->HandleIOClose(connectionId, static_cast(msgId), handle, sessionId); } return; } @@ -457,7 +490,8 @@ bool GetInt32(const json& value, long long& out) { // frontend must not wait for (or block) JS. The dataCollected chunks are // pre-serialized by the trace writer and cannot carry a sessionId without // re-parsing them, so only the main session is served; V8 traces the whole - // process anyway. + // process anyway. The controller is process-global too, so one frontend + // owns it from Tracing.start until its Tracing.end or disconnect. if (sessionId.empty() && method == "Tracing.start") { std::vector categories; double bufferSizeInKb = 0; @@ -490,103 +524,155 @@ bool GetInt32(const json& value, long long& out) { } json reply = {{"id", msgId}}; - if (tracing_agent_->start(categories, bufferSizeInKb)) { - reply["result"] = json::object(); - } else { - reply["error"] = {{"code", -32000}, {"message", "Tracing is already started"}}; + { + std::lock_guard lock(this->tracingMutex_); + if (this->tracingOwner_ == 0 && tracing_agent_->start(categories, bufferSizeInKb)) { + this->tracingOwner_ = connectionId; + reply["result"] = json::object(); + } else { + reply["error"] = {{"code", -32000}, {"message", "Tracing is already started"}}; + } } - this->SendRawToFrontend(reply.dump()); + this->SendRawToConnection(connectionId, reply.dump()); return; } if (sessionId.empty() && method == "Tracing.end") { tns::inspector::TracingAgentImpl::Result trace; - if (!tracing_agent_->end(trace)) { + bool ended; + { + std::lock_guard lock(this->tracingMutex_); + ended = this->tracingOwner_ == connectionId && tracing_agent_->end(trace); + if (ended) { + this->tracingOwner_ = 0; + } + } + if (!ended) { json error = {{"id", msgId}, {"error", {{"code", -32000}, {"message", "Tracing is not started"}}}}; - this->SendRawToFrontend(error.dump()); + this->SendRawToConnection(connectionId, error.dump()); return; } // The ack must reach the frontend before the events it asked for. json ack = {{"id", msgId}, {"result", json::object()}}; - this->SendRawToFrontend(ack.dump()); + this->SendRawToConnection(connectionId, ack.dump()); for (const auto& traceMessage : trace.messages) { - this->SendRawToFrontend(traceMessage); + this->SendRawToConnection(connectionId, traceMessage); } json complete = {{"method", "Tracing.tracingComplete"}, {"params", {{"dataLossOccurred", trace.dataLossOccurred}}}}; - this->SendRawToFrontend(complete.dump()); + this->SendRawToConnection(connectionId, complete.dump()); return; } // Messages carrying a sessionId belong to a worker target (flat-session // protocol); route them to the worker's own thread. if (!sessionId.empty()) { - this->RouteToWorker(sessionId, method, msgId, message); + this->RouteToWorker(connectionId, sessionId, method, msgId, message); return; } - this->EnqueueMessage(message); + this->Enqueue(InspectorQueue::Message(connectionId, method, message)); +} - // Debugger.pause needs to interrupt V8 even if the main thread is busy - // executing JS. RequestInterrupt fires at the next safe bytecode boundary. - if (method == "Debugger.pause") { +void JsV8InspectorClient::Enqueue(InspectorQueue::Item item) { + // The runtime is gone, and nothing will drain the queue again. + if (eventLoop_->IsStopped()) { + return; + } + + bool interrupting = item.interrupting; + this->messages_.Push(std::move(item)); + this->ScheduleMessageDrain(); + + // Whichever comes first dispatches it: the drain, or JS that keeps the + // runtime thread too busy to drain. + if (interrupting) { + tns::IsolatePin pin = isolateWrapper_.Pin(); + if (!pin) { + return; + } isolate_->RequestInterrupt( [](Isolate* isolate, void* data) { - auto client = static_cast(data); - client->session_->schedulePauseOnNextStatement({}, {}); + auto* client = static_cast(data); + for (const auto& item : client->messages_.TakeInterrupting()) { + if (item.kind == InspectorQueue::Item::Kind::kConnect) { + client->sessions_->Connect(client->inspector_.get(), item.connectionId); + } else { + client->sessions_->Dispatch(item.connectionId, item.method, item.message); + } + } }, this); } +} - this->ScheduleMessageDrain(); +void JsV8InspectorClient::ScheduleMessageDrain() { + // Bare: the drain must not wait for the Locker when a pause on another + // thread will pump the queue anyway. + eventLoop_->PostInternalBare([this]() { this->DrainMessages(); }); } -void JsV8InspectorClient::EnqueueMessage(const std::string& message) { - dispatch_sync(this->messagesQueue_, ^{ - this->messages_.push(message); - dispatch_semaphore_signal(messageArrived_); - }); +void JsV8InspectorClient::DrainMessages() { + // A command can spin the runloop; what arrives meanwhile waits for it. + if (this->draining_) { + return; + } + this->draining_ = true; + // Also when a native exception from evaluated code unwinds the drain. + std::unique_ptr drained(&this->draining_, + [](bool* draining) { *draining = false; }); + + InspectorQueue::Item item; + while (true) { + // A running pause loop pumps the queue itself, and schedules a drain once + // it has exited for anything that arrives after its last pump. + if (runningPauseLoop_) { + break; + } + v8::Locker locker(isolate_); + // The Locker may have been lost to a thread that paused and then let go + // of it, e.g. in a native call evaluated while paused. + if (runningPauseLoop_) { + break; + } + sessions_->DestroyClosed(); + if (!this->messages_.Take(item)) { + break; + } + this->HandleQueued(item); + } } -void JsV8InspectorClient::ScheduleMessageDrain() { - tns::ExecuteOnMainThread([this]() { - // messageLoopQueue_ must not be held across dispatchMessage: the message - // may pause, and runMessageLoopOnPause/quitMessageLoopOnPause sync on it - // from this thread. A pause inside a dispatch can end in a deferred - // session reset, so the checks run before every pop. - while (true) { - __block bool pauseLoopRunning = false; - __block bool pauseLoopPumping = false; - dispatch_sync(this->messageLoopQueue_, ^{ - pauseLoopRunning = runningNestedLoops_; - pauseLoopPumping = runningNestedLoops_ && !terminated_; - }); - if (pauseLoopPumping) { - break; - } - if (this->pendingSessionReset_) { - // A pause loop (possibly on another thread) is still winding down; - // it schedules another drain once it has exited. - if (pauseLoopRunning) { - break; - } - this->pendingSessionReset_ = false; - this->SyncSessionWithFrontend(); - } - std::string message = this->PumpMessage(); - if (message.empty()) { - break; +void JsV8InspectorClient::HandleQueued(const InspectorQueue::Item& item) { + switch (item.kind) { + case InspectorQueue::Item::Kind::kConnect: + sessions_->Connect(inspector_.get(), item.connectionId); + break; + case InspectorQueue::Item::Kind::kDisconnect: + for (auto& entry : this->jsDomainEnablers_) { + entry.second.erase(item.connectionId); } - this->dispatchMessage(message); - } - }); + sessions_->Disconnect(item.connectionId); + this->StopHolding(item.connectionId, false); + break; + case InspectorQueue::Item::Kind::kMessage: + this->DispatchFrontendMessage(item.connectionId, item.message); + break; + } } -void JsV8InspectorClient::RouteToWorker(const std::string& sessionId, const std::string& method, - long long msgId, const std::string& message) { +void JsV8InspectorClient::RouteToWorker(uint64_t connectionId, const std::string& sessionId, + const std::string& method, long long msgId, + const std::string& message) { std::lock_guard lock(this->workerTargetsMutex_); + // The worker was already told this frontend disconnected; a message now + // would recreate its session. + if (this->targetStates_.count(connectionId) == 0) { + return; + } + auto it = this->workerTargets_.find(sessionId); if (it == this->workerTargets_.end()) { // The worker died (Target.detachedFromTarget was sent) or never existed. @@ -594,21 +680,14 @@ bool GetInt32(const json& value, long long& out) { json error = {{"id", msgId}, {"sessionId", sessionId}, {"error", {{"code", -32001}, {"message", "Session not found"}}}}; - this->SendToFrontend(error.dump()); + this->SendRawToConnection(connectionId, error.dump()); } return; } - WorkerInspectorClient* client = it->second.client; - - // Same fast path as the main session: pause a worker that is busy - // executing JS. The worker isolate is guaranteed alive while we hold the - // registry lock (teardown unregisters before disposing it). - if (method == "Debugger.pause") { - client->RequestPauseInterrupt(); - } - - client->PushMessage(message); + // The worker isolate is guaranteed alive while we hold the registry lock + // (teardown unregisters before disposing it). + it->second.client->PushMessage(connectionId, method, message); } void JsV8InspectorClient::init() { @@ -630,132 +709,32 @@ bool GetInt32(const json& value, long long& out) { context_.Reset(isolate, context); - this->createInspectorSession(); + sessions_ = std::make_unique( + isolate, JsV8InspectorClient::contextGroupId, + [this](uint64_t connectionId, const std::string& message) { + this->SendToConnection(connectionId, message); + }); tracing_agent_.reset(new tns::inspector::TracingAgentImpl()); } -void JsV8InspectorClient::connect(int argc, char** argv) { - this->isConnected_ = true; - this->enableInspector(argc, argv); -} - -void JsV8InspectorClient::createInspectorSession() { - this->session_ = this->inspector_->connect(JsV8InspectorClient::contextGroupId, this, {}, - v8_inspector::V8Inspector::kFullyTrusted); -} - -void JsV8InspectorClient::ResetFrontendState() { - // Resource stream handles only have meaning to the frontend that opened - // them, so drop any streams it never closed via IO.close. - { - std::lock_guard lock(this->resourceStreamsMutex_); - this->resourceStreams_.clear(); - } - - // Drop any trace the departing frontend left running so the process-global - // controller is free for the next frontend's Tracing.start. - tracing_agent_->stopAndDiscard(); - - // Reset worker sessions too: resume any paused worker and recreate its - // session so the (re)connecting frontend gets a clean slate, then forget - // the auto-attach state until it sends Target.setAutoAttach again. - { - std::lock_guard lock(this->workerTargetsMutex_); - this->autoAttach_ = false; - for (auto& entry : this->workerTargets_) { - entry.second.announced = false; - entry.second.client->PushMessage(WorkerInspectorClient::kResetSessionMessage); - } - } -} - -void JsV8InspectorClient::DeferSessionResetFromPauseLoop() { - // The pause loop may itself run under session_->dispatchProtocolMessage, - // and V8 touches every session right after the loop returns, so the swap - // must wait until the stack has unwound. Resume now and keep the old - // session from pausing again in the meantime. - this->pendingSessionReset_ = true; - Isolate* isolate = isolate_; - v8::Locker locker(isolate); - Isolate::Scope isolate_scope(isolate); - HandleScope handle_scope(isolate); - session_->setSkipAllPauses(true); - session_->resume(); -} - -void JsV8InspectorClient::ResetMainSession() { - Isolate* isolate = isolate_; - v8::Locker locker(isolate); - Isolate::Scope isolate_scope(isolate); - HandleScope handle_scope(isolate); - - session_->resume(); - session_.reset(); - - this->createInspectorSession(); -} - -bool JsV8InspectorClient::TryBindSession() { - std::lock_guard lock(this->senderMutex_); - if (this->sessionConnectionId_ != 0 && this->sessionConnectionId_ != this->connectionId_) { - return false; - } - this->sessionConnectionId_ = this->connectionId_; - this->sessionSender_ = this->sender_; - return true; -} - -void JsV8InspectorClient::SyncSessionWithFrontend() { - if (this->TryBindSession()) { - return; - } - - this->ResetMainSession(); - { - std::lock_guard lock(this->senderMutex_); - this->sessionConnectionId_ = 0; - this->sessionSender_ = nullptr; - } - this->TryBindSession(); -} - -bool JsV8InspectorClient::SessionOwnsFrontend() { - std::lock_guard lock(this->senderMutex_); - return this->sessionConnectionId_ != 0 && this->sessionConnectionId_ == this->connectionId_; -} +void JsV8InspectorClient::connect(int argc, char** argv) { this->enableInspector(argc, argv); } void JsV8InspectorClient::runMessageLoopOnPause(int contextGroupId) { - // The session that paused is about to be replaced; no frontend owns it. - if (this->pendingSessionReset_) { - return; - } - - __block auto loopsRunning = false; - dispatch_sync(this->messageLoopQueue_, ^{ - loopsRunning = runningNestedLoops_; - terminated_ = false; - if (runningNestedLoops_) { - return; - } - this->runningNestedLoops_ = true; - }); - - if (loopsRunning) { + if (runningPauseLoop_) { return; } + runningPauseLoop_ = true; + pauseTerminated_ = false; + sessions_->PauseStarted(); bool shouldWait = false; - while (!terminated_) { - std::string message = this->PumpMessage(); - if (message == kSessionSyncMessage) { - if (!this->TryBindSession()) { - this->DeferSessionResetFromPauseLoop(); - break; - } - shouldWait = false; - } else if (!message.empty()) { - this->dispatchMessage(message); + while (!pauseTerminated_) { + InspectorQueue::Item item; + if (this->messages_.Take(item)) { + // A disconnect here may end the pause: once no frontend has the + // debugger enabled, V8 calls quitMessageLoopOnPause. + this->HandleQueued(item); shouldWait = false; } else { shouldWait = true; @@ -769,104 +748,67 @@ bool GetInt32(const json& value, long long& out) { if (eventLoop != nullptr) { eventLoop->RunNestableV8Tasks(); } - if (shouldWait && !terminated_) { - dispatch_semaphore_wait(messageArrived_, - dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_MSEC)); // 1ms + if (shouldWait && !pauseTerminated_) { + this->messages_.Wait(); } } - dispatch_sync(this->messageLoopQueue_, ^{ - terminated_ = false; - runningNestedLoops_ = false; - }); - - if (this->pendingSessionReset_) { - this->ScheduleMessageDrain(); - } -} - -void JsV8InspectorClient::quitMessageLoopOnPause() { - dispatch_sync(this->messageLoopQueue_, ^{ - terminated_ = true; - }); -} - -void JsV8InspectorClient::sendResponse(int callId, std::unique_ptr message) { - this->notify(std::move(message)); -} - -void JsV8InspectorClient::sendNotification(std::unique_ptr message) { - this->notify(std::move(message)); -} - -void JsV8InspectorClient::flushProtocolNotifications() {} - -void JsV8InspectorClient::notify(std::unique_ptr message) { - StringView stringView = message->string(); - notify(ToStdString(stringView)); + sessions_->PauseEnded(); + runningPauseLoop_ = false; + this->ScheduleMessageDrain(); } -void JsV8InspectorClient::notify(const std::string& message) { - std::function sender; - { - std::lock_guard lock(this->senderMutex_); - sender = this->sessionSender_; - } - if (sender) { - sender(MaybeRewriteSourceMapURL(message)); - } -} +void JsV8InspectorClient::quitMessageLoopOnPause() { pauseTerminated_ = true; } -uint64_t JsV8InspectorClient::FrontendGeneration() { - std::lock_guard lock(this->senderMutex_); - return this->frontendGeneration_; +void JsV8InspectorClient::SendToConnection(uint64_t connectionId, const std::string& message) { + this->SendRawToConnection(connectionId, MaybeRewriteSourceMapURL(message)); } -void JsV8InspectorClient::SendWorkerOutput(uint64_t generation, const std::string& message) { +void JsV8InspectorClient::SendRawToConnection(uint64_t connectionId, const std::string& message) { std::function sender; { - std::lock_guard lock(this->senderMutex_); - if (generation != this->frontendGeneration_) { + std::lock_guard lock(this->frontendsMutex_); + auto it = this->frontends_.find(connectionId); + if (it == this->frontends_.end()) { return; } - sender = this->sender_; - } - if (sender) { - sender(MaybeRewriteSourceMapURL(message)); + sender = it->second; } + sender(message); } -void JsV8InspectorClient::SendToFrontend(const std::string& message) { - this->SendRawToFrontend(MaybeRewriteSourceMapURL(message)); -} - -void JsV8InspectorClient::SendRawToFrontend(const std::string& message) { - std::function sender; +void JsV8InspectorClient::SendToAll(const std::string& message) { + std::vector> senders; { - std::lock_guard lock(this->senderMutex_); - sender = this->sender_; + std::lock_guard lock(this->frontendsMutex_); + for (const auto& entry : this->frontends_) { + senders.push_back(entry.second); + } } - if (sender) { + for (const auto& sender : senders) { sender(message); } } -void JsV8InspectorClient::dispatchMessage(const std::string& message) { - // The pause loop intercepts this message, so here no session is on the stack. - if (message == kSessionSyncMessage) { - this->SyncSessionWithFrontend(); +void JsV8InspectorClient::DispatchFrontendMessage(uint64_t connectionId, + const std::string& message) { + // The frontend disconnected (or is disconnecting) after sending this. + if (!sessions_->Has(connectionId)) { return; } - auto json_message = json::parse(message); + auto json_message = json::parse(message, nullptr, false); + if (json_message.is_discarded() || !json_message.is_object() || + !json_message.contains("method") || !json_message["method"].is_string()) { + NSLog(@"Inspector failed to parse incoming message: %s", message.c_str()); + return; + } std::string method = json_message["method"]; // Note: the Tracing domain is handled in onFrontendMessageReceived, so it - // never waits on the message queue or takes the Locker below. + // never waits on the message queue or for the isolate. - StringView messageView = Make8BitStringView(message); Isolate* isolate = isolate_; - v8::Locker locker(isolate); Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); Local context = tns::Caches::Get(isolate)->GetContext(); @@ -896,24 +838,19 @@ bool GetInt32(const json& value, long long& out) { if (method == "Target.setAutoAttach") { bool autoAttach = json_message.contains("params") && json_message["params"].contains("autoAttach") && + json_message["params"]["autoAttach"].is_boolean() && json_message["params"]["autoAttach"].get(); - { - std::lock_guard lock(this->workerTargetsMutex_); - // A replaced frontend's in-flight request must not turn auto-attach on - // for its successor. Checked under the lock ResetFrontendState takes - // after the sender swap, so a stale value set here is reset there. - if (!this->SessionOwnsFrontend()) { - autoAttach = false; - } else { - this->autoAttach_ = autoAttach; - } - } json response = {{"id", json_message["id"]}, {"result", json::object()}}; - this->notify(response.dump()); + this->SendRawToConnection(connectionId, response.dump()); - if (autoAttach) { - this->AnnounceWorkerTargets(); + std::lock_guard lock(this->workerTargetsMutex_); + auto it = this->targetStates_.find(connectionId); + if (it != this->targetStates_.end()) { + it->second.autoAttach = autoAttach; + if (autoAttach) { + this->AnnounceWorkerTargetsLocked(connectionId, it->second); + } } return; } @@ -923,7 +860,7 @@ bool GetInt32(const json& value, long long& out) { if (method == "Target.setDiscoverTargets" || method == "Target.setRemoteLocations" || method == "Target.detachFromTarget") { json response = {{"id", json_message["id"]}, {"result", json::object()}}; - this->notify(response.dump()); + this->SendRawToConnection(connectionId, response.dump()); return; } @@ -945,9 +882,32 @@ bool GetInt32(const json& value, long long& out) { Local domainMethodFunc = v8_inspector::GetDebuggerFunctionFromObject(context, argObject, domainDebugger); + size_t dot = method.find('.'); + std::string domain = method.substr(0, dot); + std::string command = dot == std::string::npos ? std::string() : method.substr(dot + 1); + bool hasHandler = !domainMethodFunc.IsEmpty() && domainMethodFunc->IsFunction(); + + if (hasHandler && command == "disable") { + std::set& enablers = this->jsDomainEnablers_[domain]; + enablers.erase(connectionId); + if (!enablers.empty()) { + json response = {{"id", json_message["id"]}, {"result", json::object()}}; + this->SendRawToConnection(connectionId, response.dump()); + return; + } + } + + // Recorded before the call: the handler may pause, and during the pause + // another frontend may disable the domain, or this one leave. + bool enabling = hasHandler && command == "enable" && + this->jsDomainEnablers_[domain].insert(connectionId).second; + Local result; success = this->CallDomainHandlerFunction(context, domainMethodFunc, argObject, domainDebugger, result); + if (enabling && !success) { + this->jsDomainEnablers_[domain].erase(connectionId); + } if (success) { auto requestId = @@ -955,33 +915,26 @@ bool GetInt32(const json& value, long long& out) { auto returnString = GetReturnMessageFromDomainHandlerResult(result, requestId); if (returnString.size() > 0) { - StringView messageView = Make8BitStringView(returnString); - auto msg = StringBuffer::create(messageView); - this->sendNotification(std::move(msg)); + this->SendToConnection(connectionId, returnString); } return; } } // if no handler handled the message successfully, fall-through to the default V8 implementation - this->session_->dispatchProtocolMessage(messageView); - // if needed to test, disable the default handling and use this - // json error = { - // {"id", json_message["id"]}, - // {"error", { - // {"code", -32601}, - // { - // "message", "Method not found: " + method - // } - // }} - // }; - // notify(error.dump()); + sessions_->Dispatch(connectionId, method, message); + + // Follows the frontend's setup commands, Debugger.enable among them. + if (method == "Runtime.runIfWaitingForDebugger") { + this->StopHolding(connectionId, true); + } // TODO: check why this is needed (it should trigger automatically when script depth is 0) isolate->PerformMicrotaskCheckpoint(); } -void JsV8InspectorClient::HandleLoadNetworkResource(int msgId, const std::string& url, +void JsV8InspectorClient::HandleLoadNetworkResource(uint64_t connectionId, int msgId, + const std::string& url, const std::string& sessionId) { std::string path; if (url.rfind(kSourceMapScheme, 0) == 0) { @@ -994,7 +947,7 @@ bool GetInt32(const json& value, long long& out) { // pre-existing behavior for http(s) urls. json error = {{"id", msgId}, {"error", {{"code", -32000}, {"message", "Unsupported URL scheme"}}}}; - this->SendToFrontend(WithSessionId(error, sessionId).dump()); + this->SendToConnection(connectionId, WithSessionId(error, sessionId).dump()); return; } @@ -1043,7 +996,7 @@ bool GetInt32(const json& value, long long& out) { { std::lock_guard lock(this->resourceStreamsMutex_); handle = "ns-network-resource-" + std::to_string(++lastStreamId_); - resourceStreams_[handle] = {std::move(content), binary, 0}; + resourceStreams_[handle] = {connectionId, std::move(content), binary, 0}; } resource = {{"success", true}, {"httpStatusCode", 200}, @@ -1057,16 +1010,16 @@ bool GetInt32(const json& value, long long& out) { } json response = {{"id", msgId}, {"result", {{"resource", resource}}}}; - this->SendToFrontend(WithSessionId(response, sessionId).dump()); + this->SendToConnection(connectionId, WithSessionId(response, sessionId).dump()); } -void JsV8InspectorClient::HandleIORead(int msgId, const std::string& handle, +void JsV8InspectorClient::HandleIORead(uint64_t connectionId, int msgId, const std::string& handle, std::optional offset, std::optional size, const std::string& sessionId) { auto sendError = [&](const char* message) { json error = {{"id", msgId}, {"error", {{"code", -32602}, {"message", message}}}}; - this->SendToFrontend(WithSessionId(error, sessionId).dump()); + this->SendToConnection(connectionId, WithSessionId(error, sessionId).dump()); }; // Chromium defaults to 10 MB; smaller chunks keep socket frames (UTF-16 on @@ -1082,7 +1035,7 @@ bool GetInt32(const json& value, long long& out) { { std::lock_guard lock(this->resourceStreamsMutex_); auto it = resourceStreams_.find(handle); - if (it == resourceStreams_.end()) { + if (it == resourceStreams_.end() || it->second.connectionId != connectionId) { sendError("Invalid stream handle"); return; } @@ -1130,48 +1083,53 @@ bool GetInt32(const json& value, long long& out) { json response = {{"id", msgId}, {"result", result}}; // Raw: a reply is never a Debugger.scriptParsed whose sourceMapURL needs // rewriting. - this->SendRawToFrontend(WithSessionId(response, sessionId).dump()); + this->SendRawToConnection(connectionId, WithSessionId(response, sessionId).dump()); } -void JsV8InspectorClient::HandleIOClose(int msgId, const std::string& handle, +void JsV8InspectorClient::HandleIOClose(uint64_t connectionId, int msgId, const std::string& handle, const std::string& sessionId) { bool closed; { std::lock_guard lock(this->resourceStreamsMutex_); - closed = resourceStreams_.erase(handle) != 0; + auto it = resourceStreams_.find(handle); + closed = it != resourceStreams_.end() && it->second.connectionId == connectionId; + if (closed) { + resourceStreams_.erase(it); + } } json response = closed ? json{{"id", msgId}, {"result", json::object()}} : json{{"id", msgId}, {"error", {{"code", -32602}, {"message", "Invalid stream handle"}}}}; - this->SendToFrontend(WithSessionId(response, sessionId).dump()); + this->SendToConnection(connectionId, WithSessionId(response, sessionId).dump()); +} + +void JsV8InspectorClient::SendAttachedToTarget(uint64_t connectionId, + WorkerInspectorClient* client) { + json attached = {{"method", "Target.attachedToTarget"}, + {"params", + {{"sessionId", client->SessionId()}, + {"targetInfo", + {{"targetId", client->TargetId()}, + {"type", "worker"}, + {"title", client->Url()}, + {"url", client->Url()}, + {"attached", true}, + {"canAccessOpener", false}}}, + {"waitingForDebugger", false}}}}; + this->SendRawToConnection(connectionId, attached.dump()); } void JsV8InspectorClient::RegisterWorkerTarget(int workerId, WorkerInspectorClient* client) { std::lock_guard lock(this->workerTargetsMutex_); - WorkerTarget target{workerId, client, false}; - - // Under the lock ResetFrontendState takes after bumping the generation: - // either this sees the bumped value or the reset sweep sees this worker. - client->SetFrontendGeneration(this->FrontendGeneration()); - - if (this->isConnected_ && this->autoAttach_) { - target.announced = true; - json attached = {{"method", "Target.attachedToTarget"}, - {"params", - {{"sessionId", client->SessionId()}, - {"targetInfo", - {{"targetId", client->TargetId()}, - {"type", "worker"}, - {"title", client->Url()}, - {"url", client->Url()}, - {"attached", true}, - {"canAccessOpener", false}}}, - {"waitingForDebugger", false}}}}; - this->notify(attached.dump()); - } - - this->workerTargets_.emplace(client->SessionId(), target); + this->workerTargets_.emplace(client->SessionId(), WorkerTarget{workerId, client}); + + for (auto& entry : this->targetStates_) { + if (entry.second.autoAttach) { + entry.second.announced.insert(client->SessionId()); + this->SendAttachedToTarget(entry.first, client); + } + } } void JsV8InspectorClient::UnregisterWorkerTarget(int workerId) { @@ -1181,12 +1139,15 @@ bool GetInt32(const json& value, long long& out) { continue; } - if (it->second.announced && this->isConnected_) { - json detached = {{"method", "Target.detachedFromTarget"}, - {"params", - {{"sessionId", it->second.client->SessionId()}, - {"targetId", it->second.client->TargetId()}}}}; - this->notify(detached.dump()); + const std::string& sessionId = it->second.client->SessionId(); + json detached = { + {"method", "Target.detachedFromTarget"}, + {"params", {{"sessionId", sessionId}, {"targetId", it->second.client->TargetId()}}}}; + std::string detachedMessage = detached.dump(); + for (auto& entry : this->targetStates_) { + if (entry.second.announced.erase(sessionId) != 0) { + this->SendRawToConnection(entry.first, detachedMessage); + } } this->workerTargets_.erase(it); @@ -1194,81 +1155,53 @@ bool GetInt32(const json& value, long long& out) { } } -void JsV8InspectorClient::AnnounceWorkerTargets() { - std::lock_guard lock(this->workerTargetsMutex_); - // A frontend change since Target.setAutoAttach cleared this; marking - // workers announced now would hide them from the next frontend. - if (!this->autoAttach_) { - return; - } +void JsV8InspectorClient::AnnounceWorkerTargetsLocked(uint64_t connectionId, TargetState& state) { for (auto& entry : this->workerTargets_) { - WorkerTarget& target = entry.second; - if (target.announced) { - continue; + if (state.announced.insert(entry.first).second) { + this->SendAttachedToTarget(connectionId, entry.second.client); } - target.announced = true; - - json attached = {{"method", "Target.attachedToTarget"}, - {"params", - {{"sessionId", target.client->SessionId()}, - {"targetInfo", - {{"targetId", target.client->TargetId()}, - {"type", "worker"}, - {"title", target.client->Url()}, - {"url", target.client->Url()}, - {"attached", true}, - {"canAccessOpener", false}}}, - {"waitingForDebugger", false}}}}; - this->notify(attached.dump()); } } -void JsV8InspectorClient::SchedulePauseInWorker(int workerId) { - std::lock_guard lock(this->workerTargetsMutex_); - for (auto& entry : this->workerTargets_) { - if (entry.second.workerId == workerId) { - entry.second.client->SchedulePauseFromInterrupt(); - return; +void JsV8InspectorClient::DispatchInterruptingInWorker(int workerId) { + WorkerInspectorClient* client = nullptr; + { + std::lock_guard lock(this->workerTargetsMutex_); + for (auto& entry : this->workerTargets_) { + if (entry.second.workerId == workerId) { + client = entry.second.client; + break; + } } } + + // Stays alive for the call: its destructor needs the Locker this thread + // holds. + if (client != nullptr) { + client->DispatchInterrupting(); + } } Local JsV8InspectorClient::ensureDefaultContextInGroup(int contextGroupId) { return context_.Get(isolate_); } -std::string JsV8InspectorClient::PumpMessage() { - __block std::string result; - dispatch_sync(this->messagesQueue_, ^{ - if (this->messages_.size() > 0) { - result = this->messages_.front(); - this->messages_.pop(); - } - }); - - return result; -} - -void JsV8InspectorClient::scheduleBreak() { +void JsV8InspectorClient::PauseBeforeApp() { Isolate* isolate = isolate_; v8::Locker locker(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); - auto context = isolate->GetCurrentContext(); + Local context = tns::Caches::Get(isolate)->GetContext(); Context::Scope context_scope(context); - if (!this->hasScheduledDebugBreak_) { - this->hasScheduledDebugBreak_ = true; - // hack: force a debugger; statement in ModuleInternal to actually break before loading the next - // (main) script... - // FIXME: find a proper fix to not need to resort to this hack. - context->Global() - ->Set(context, tns::ToV8String(isolate, "__pauseOnNextRequire"), - v8::Boolean::New(isolate, true)) - .ToChecked(); + // A scheduled pause would not stop at the evaluation of the main module. A + // script of our own also stops before any app code has run, while its + // breakpoints can still be set. + ScriptOrigin origin(tns::ToV8String(isolate, "nativescript-debug-brk.js")); + Local