Skip to content

Commit ec4fc40

Browse files
committed
fix(inspector): pause workers and busy JS, drain on the runtime's thread
Debugger.pause never paused a worker that was not running JS when it arrived. V8 keeps "break on the next function call" per thread, and releasing a thread's outermost Locker frees that state; a worker takes one Locker per task. The main thread escapes it because UIApplicationMain runs inside a Locker and an Unlocker, but loses the pause when another thread takes the Locker meanwhile. InspectorSessions now tracks a pending pause and sets it again whenever JS is entered. The same state crashed the app: a step that ran off the end of its task outlived its JS frames, and restoring it after another thread had taken the Locker dereferenced a missing frame (Debug::RestoreDebug). Such a step is now cleared and becomes a pending pause, so stepping past the end still stops in the next function called, on workers too. Debugger.pause also failed on JS that was busy, on any isolate, unless it called functions: the interrupt asked V8 to break on the next call. The command itself is now dispatched, once, by whichever comes first: the drain, or a V8 interrupt. Breakpoint commands get the same, as in Chromium, so they apply while JS is busy. A pause requested while paused no longer pauses again after the resume. The main isolate's drain was posted to the main queue, which is right only when the runtime lives there. It is now posted to the runtime's EventLoop, so it also stops when the runtime is destroyed. JS can pause on any thread that takes the isolate's Locker. The drains took a message, and touched the sessions, before taking it, so one message could be stuck behind a pause on another thread while the pause loop handled later ones; a new client could lose its first commands. The Locker now comes first. Also: - A session whose client leaves during a pause is destroyed after the pause. V8 may hold it on the stack outside a dispatch, e.g. while serializing a value whose getter paused. - A client is closed for not reading for 30 s with 256 MB pending, rather than for the size alone, which cut off large heap snapshots on slow links. - A client that leaves while a JS domain's enable handler is paused no longer holds that domain enabled. - A non-string url or non-boolean autoAttach no longer crashes the app.
1 parent 65befcf commit ec4fc40

10 files changed

Lines changed: 547 additions & 290 deletions
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#ifndef InspectorQueue_h
2+
#define InspectorQueue_h
3+
4+
#include <dispatch/dispatch.h>
5+
6+
#include <cstdint>
7+
#include <deque>
8+
#include <mutex>
9+
#include <string>
10+
#include <vector>
11+
12+
namespace v8_inspector {
13+
14+
// Frontend messages waiting for an isolate, in arrival order. Push from any
15+
// thread; take only while holding the isolate's Locker, so that a pause loop
16+
// on another thread (which holds it throughout) and the isolate's own drain
17+
// never split a frontend's messages between them.
18+
class InspectorQueue {
19+
public:
20+
struct Item {
21+
enum class Kind { kConnect, kDisconnect, kMessage };
22+
uint64_t connectionId;
23+
Kind kind;
24+
std::string method;
25+
std::string message;
26+
// See Interrupts and IsBarrier.
27+
bool interrupting = false;
28+
bool barrier = false;
29+
};
30+
31+
InspectorQueue();
32+
33+
// Whether a command runs no JS, so it may be dispatched from an interrupt
34+
// in the middle of the isolate's JS and ahead of the frontend's earlier
35+
// commands. Chromium's list (ShouldInterruptForMethod), without the domains
36+
// V8 does not implement and without Runtime.terminateExecution, which would
37+
// unwind the app's own frames.
38+
static bool Interrupts(const std::string& method);
39+
40+
// Whether an interrupting command must stay behind this one: it creates or
41+
// destroys what the command acts on.
42+
static bool IsBarrier(const std::string& method);
43+
44+
static Item Message(uint64_t connectionId, const std::string& method,
45+
std::string message);
46+
47+
void Push(Item item);
48+
49+
// Takes the oldest item. Returns false when there is none.
50+
bool Take(Item& item);
51+
52+
// Takes the interrupting commands that no barrier of their frontend
53+
// precedes.
54+
std::vector<Item> TakeInterrupting();
55+
56+
// Waits briefly for a Push.
57+
void Wait();
58+
59+
// Ends a Wait in progress.
60+
void Wake();
61+
62+
private:
63+
std::mutex mutex_;
64+
std::deque<Item> items_;
65+
dispatch_semaphore_t pushed_;
66+
};
67+
68+
} // namespace v8_inspector
69+
70+
#endif /* InspectorQueue_h */
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#include "InspectorQueue.h"
2+
3+
#include <algorithm>
4+
#include <iterator>
5+
#include <set>
6+
7+
namespace v8_inspector {
8+
9+
InspectorQueue::InspectorQueue() : pushed_(dispatch_semaphore_create(0)) {}
10+
11+
bool InspectorQueue::Interrupts(const std::string& method) {
12+
static constexpr const char* kMethods[] = {
13+
"Debugger.getPossibleBreakpoints", "Debugger.getScriptSource",
14+
"Debugger.getStackTrace", "Debugger.pause",
15+
"Debugger.removeBreakpoint", "Debugger.resume",
16+
"Debugger.setBreakpoint", "Debugger.setBreakpointByUrl",
17+
"Debugger.setBreakpointsActive",
18+
};
19+
return std::any_of(std::begin(kMethods), std::end(kMethods),
20+
[&](const char* name) { return method == name; });
21+
}
22+
23+
bool InspectorQueue::IsBarrier(const std::string& method) {
24+
return method == "Debugger.enable" || method == "Debugger.disable";
25+
}
26+
27+
InspectorQueue::Item InspectorQueue::Message(uint64_t connectionId, const std::string& method,
28+
std::string message) {
29+
return {connectionId, Item::Kind::kMessage, method,
30+
std::move(message), Interrupts(method), IsBarrier(method)};
31+
}
32+
33+
void InspectorQueue::Push(Item item) {
34+
if (item.kind != Item::Kind::kMessage) {
35+
item.barrier = true;
36+
}
37+
{
38+
std::lock_guard<std::mutex> lock(mutex_);
39+
items_.push_back(std::move(item));
40+
}
41+
dispatch_semaphore_signal(pushed_);
42+
}
43+
44+
bool InspectorQueue::Take(Item& item) {
45+
std::lock_guard<std::mutex> lock(mutex_);
46+
if (items_.empty()) {
47+
return false;
48+
}
49+
item = std::move(items_.front());
50+
items_.pop_front();
51+
return true;
52+
}
53+
54+
std::vector<InspectorQueue::Item> InspectorQueue::TakeInterrupting() {
55+
std::vector<Item> taken;
56+
std::set<uint64_t> blocked;
57+
std::lock_guard<std::mutex> lock(mutex_);
58+
for (auto it = items_.begin(); it != items_.end();) {
59+
if (it->barrier) {
60+
blocked.insert(it->connectionId);
61+
}
62+
if (it->interrupting && blocked.count(it->connectionId) == 0) {
63+
taken.push_back(std::move(*it));
64+
it = items_.erase(it);
65+
} else {
66+
++it;
67+
}
68+
}
69+
return taken;
70+
}
71+
72+
void InspectorQueue::Wait() {
73+
dispatch_semaphore_wait(pushed_, dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_MSEC));
74+
}
75+
76+
void InspectorQueue::Wake() { dispatch_semaphore_signal(pushed_); }
77+
78+
} // namespace v8_inspector

‎NativeScript/inspector/InspectorServer.mm‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,17 @@
1212

1313
std::atomic<uint64_t> gLastConnectionId{0};
1414

15-
// A client this far behind is assumed gone (e.g. a half-open socket whose
16-
// peer vanished without a FIN): every client receives broadcast events, so
17-
// its unsent output would otherwise grow without bound. Large enough for a
18-
// heap snapshot streamed over a slow link.
15+
// A client this far behind that has also read nothing for this long is
16+
// assumed gone (e.g. a half-open socket whose peer vanished without a FIN):
17+
// every client receives broadcast events, so its unsent output would otherwise
18+
// grow without bound. Size alone does not tell: V8 produces a heap snapshot
19+
// much faster than a slow link takes it.
1920
constexpr size_t kMaxPendingWriteBytes = 256 * 1024 * 1024;
21+
constexpr uint64_t kWriteStallNs = 30 * NSEC_PER_SEC;
22+
23+
// How often a write in progress reports back, so that one large message on a
24+
// slow link still counts as progress.
25+
constexpr size_t kWriteProgressBytes = 256 * 1024;
2026

2127
struct Connection {
2228
uint64_t id;
@@ -25,6 +31,7 @@
2531
// Only changes on `queue`.
2632
std::atomic<bool> open{true};
2733
std::atomic<size_t> pendingWriteBytes{0};
34+
std::atomic<uint64_t> lastWriteProgressNs{0};
2835
std::function<void(uint64_t)> onDisconnected;
2936
std::function<void(uint64_t, const std::string&)> onMessage;
3037
};
@@ -123,7 +130,13 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) {
123130
free(buffer);
124131
});
125132

126-
if (connection->pendingWriteBytes.fetch_add(size) + size > kMaxPendingWriteBytes) {
133+
uint64_t now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
134+
size_t pending = connection->pendingWriteBytes.fetch_add(size);
135+
if (pending == 0) {
136+
connection->lastWriteProgressNs = now;
137+
}
138+
uint64_t progress = connection->lastWriteProgressNs;
139+
if (pending + size > kMaxPendingWriteBytes && now > progress && now - progress > kWriteStallNs) {
127140
NSLog(@"InspectorServer: closing a client that stopped reading");
128141
// Closed on its own queue to keep onDisconnected ordered after onMessage.
129142
dispatch_async(connection->queue, ^{
@@ -137,6 +150,7 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) {
137150
if (done) {
138151
connection->pendingWriteBytes.fetch_sub(size);
139152
}
153+
connection->lastWriteProgressNs = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
140154
if (error == 0) {
141155
return;
142156
}
@@ -216,6 +230,7 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) {
216230
close(clientSocket);
217231
continue;
218232
}
233+
dispatch_io_set_high_water(connection->channel, kWriteProgressBytes);
219234

220235
// Reads start only after this returns, so the client's first message
221236
// cannot overtake its own connect.

‎NativeScript/inspector/InspectorSessions.h‎

Lines changed: 42 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,7 @@
55
#include <functional>
66
#include <map>
77
#include <memory>
8-
#include <mutex>
98
#include <string>
10-
#include <vector>
119

1210
#include "include/v8-inspector.h"
1311

@@ -16,10 +14,9 @@ namespace v8_inspector {
1614
// One V8InspectorSession per connected frontend, all on one isolate and
1715
// context group. Each session's output goes only to its own frontend.
1816
//
19-
// Except for RequestPause and ClearPauseRequests, call only from the one
20-
// thread at a time that feeds the isolate's inspector messages (its message
21-
// drain or pause loop), or from an interrupt on the thread running its JS.
22-
// The methods take the isolate's Locker themselves (v8::Locker is reentrant).
17+
// Every method requires the isolate's Locker. JS may run on any thread that
18+
// takes it, so a pause loop and an interrupt can feed the sessions from
19+
// another thread than the isolate's own.
2320
class InspectorSessions {
2421
public:
2522
using Output =
@@ -32,28 +29,32 @@ class InspectorSessions {
3229
void Connect(V8Inspector* inspector, uint64_t connectionId);
3330

3431
// Ignored for a frontend without a session or one being closed.
35-
void Dispatch(uint64_t connectionId, const std::string& message);
32+
void Dispatch(uint64_t connectionId, const std::string& method,
33+
const std::string& message);
3634

3735
// Destroys the frontend's session. Its destructor disables its agents, so
3836
// a pause ends only if no other frontend still has the debugger enabled.
39-
// A session cannot be destroyed while it is dispatching (a pause loop can
40-
// sit under its dispatchProtocolMessage); it then gets Debugger.disable
41-
// right away and is destroyed once that dispatch returns.
37+
// A session with V8 frames on the stack cannot be destroyed: it may be
38+
// dispatching (a pause loop can sit under its dispatchProtocolMessage), or
39+
// serializing an object whose getter paused. It then gets Debugger.disable
40+
// right away and is destroyed once its dispatch returns or the pause is
41+
// over.
4242
void Disconnect(uint64_t connectionId);
4343

44+
// Brackets the isolate's pause loop.
45+
void PauseStarted();
46+
void PauseEnded();
47+
48+
// Destroys the sessions whose frontend left during a pause. V8 still uses
49+
// the sessions after the pause loop returns, so call this from the first
50+
// drain after it.
51+
void DestroyClosed();
52+
4453
// Destroys every session. Never while any of them is dispatching.
4554
void DisconnectAll();
4655

4756
bool Has(uint64_t connectionId) const;
4857

49-
// Any thread. Records that the frontend asked to pause; TakePauseRequests,
50-
// called from an isolate interrupt, schedules the pause in its session.
51-
void RequestPause(uint64_t connectionId);
52-
void TakePauseRequests();
53-
// Any thread. Called when a pause starts, so a request whose interrupt is
54-
// still pending cannot pause again after the resume.
55-
void ClearPauseRequests();
56-
5758
void SchedulePauseInAll();
5859

5960
private:
@@ -63,18 +64,38 @@ class InspectorSessions {
6364
std::unique_ptr<V8InspectorSession> session;
6465
int dispatchDepth = 0;
6566
bool closing = false;
67+
bool debuggerEnabled = false;
68+
// Asked for a pause that has not happened yet.
69+
bool pausePending = false;
6670
};
6771

72+
// V8 keeps a pending pause, and the step in progress, per thread, and that
73+
// state does not survive here. Releasing a thread's outermost Locker frees
74+
// it, which a worker does after every task, and another thread's Locker
75+
// turns off the hook it depends on. It is also unsafe to leave behind: a
76+
// step that outlives its JS frames crashes Debug::RestoreDebug when the
77+
// thread's state is restored from an archive (another thread having held
78+
// the Locker). So a pending pause is set again whenever JS is entered, and
79+
// a step that ran off the end of its JS becomes a pending pause.
80+
static void OnCallEntered(v8::Isolate* isolate);
81+
static void OnCallCompleted(v8::Isolate* isolate);
82+
static void OnMicrotasksCompleted(v8::Isolate* isolate, void* data);
83+
void FinishStep();
84+
void TrackPause(uint64_t connectionId, Session* session,
85+
const std::string& method);
86+
6887
void DispatchTo(Session* session, const std::string& message);
6988
void Destroy(uint64_t connectionId);
7089

7190
v8::Isolate* isolate_;
7291
int contextGroupId_;
7392
Output output_;
7493
std::map<uint64_t, std::unique_ptr<Session>> sessions_;
75-
76-
std::mutex pauseRequestsMutex_;
77-
std::vector<uint64_t> pauseRequests_; // guarded by pauseRequestsMutex_
94+
bool paused_ = false;
95+
// A step was requested and nothing has paused since.
96+
bool stepping_ = false;
97+
// Who to pause for once the step runs off the end, 0 for nobody.
98+
uint64_t stepper_ = 0;
7899
};
79100

80101
} // namespace v8_inspector

0 commit comments

Comments
 (0)