Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions NativeScript/inspector/InspectorQueue.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#ifndef InspectorQueue_h
#define InspectorQueue_h

#include <dispatch/dispatch.h>

#include <cstdint>
#include <deque>
#include <mutex>
#include <string>
#include <vector>

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, Debugger.enable and
// Debugger.setSkipAllPauses, 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<Item> TakeInterrupting();

// Waits briefly for a Push.
void Wait();

// Ends a Wait in progress.
void Wake();

private:
std::mutex mutex_;
std::deque<Item> items_;
dispatch_semaphore_t pushed_;
};

} // namespace v8_inspector

#endif /* InspectorQueue_h */
95 changes: 95 additions & 0 deletions NativeScript/inspector/InspectorQueue.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#include "InspectorQueue.h"

#include <algorithm>
#include <iterator>
#include <map>
#include <set>

namespace v8_inspector {

namespace {
bool IsPrerequisite(const InspectorQueue::Item& item) {
return item.kind == InspectorQueue::Item::Kind::kConnect || item.method == "Debugger.enable" ||
item.method == "Debugger.setSkipAllPauses";
}

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)) {}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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<std::mutex> lock(mutex_);
items_.push_back(std::move(item));
}
dispatch_semaphore_signal(pushed_);
}

bool InspectorQueue::Take(Item& item) {
std::lock_guard<std::mutex> lock(mutex_);
if (items_.empty()) {
return false;
}
item = std::move(items_.front());
items_.pop_front();
return true;
}

std::vector<InspectorQueue::Item> InspectorQueue::TakeInterrupting() {
std::vector<Item> taken;
std::lock_guard<std::mutex> lock(mutex_);

// The index after each frontend's last command to take.
std::map<uint64_t, size_t> ends;
std::set<uint64_t> 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
10 changes: 4 additions & 6 deletions NativeScript/inspector/InspectorServer.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<void(uint64_t connectionId, Sender sender)>
onClientConnected,
Expand Down
118 changes: 97 additions & 21 deletions NativeScript/inspector/InspectorServer.mm
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,48 @@

#include <atomic>
#include <memory>
#include <mutex>

namespace v8_inspector {

namespace {

std::atomic<uint64_t> 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<bool> open{true};
std::atomic<size_t> pendingWriteBytes{0};
std::atomic<uint64_t> lastWriteProgressNs{0};
// Makes a send that starts the pending output and its timestamp one step
// for the stall check.
std::mutex pendingStartMutex;
std::atomic<bool> watchingForStall{false};
std::function<void(uint64_t)> onDisconnected;
std::function<void(uint64_t, const std::string&)> 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>& connection) {
if (!connection->open.exchange(false)) {
return;
Expand All @@ -46,7 +72,7 @@ void ReadExactly(std::shared_ptr<Connection> 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);
Expand All @@ -56,6 +82,33 @@ void ReadExactly(std::shared_ptr<Connection> 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> 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;
{
std::lock_guard<std::mutex> lock(connection->pendingStartMutex);
progress = connection->lastWriteProgressNs;
}
uint64_t stalled = now > progress ? now - progress : 0;
if (stalled >= kWriteStallNs) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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> connection) {
ReadExactly(connection, sizeof(uint32_t), ^(dispatch_data_t header) {
Expand All @@ -70,6 +123,11 @@ void ReadNextMessage(std::shared_ptr<Connection> 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);
Expand Down Expand Up @@ -99,19 +157,42 @@ void Send(std::shared_ptr<Connection> 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;
{
std::lock_guard<std::mutex> lock(connection->pendingStartMutex);
pending = connection->pendingWriteBytes.fetch_add(size);
if (pending == 0) {
connection->lastWriteProgressNs = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
}
}
if (pending + size > kMaxPendingWriteBytes) {
// Checks now, and then when the stall would be long enough.
WatchForStall(connection, 0);
}

// Bytes of this message not yet written; only touched on the connection's
// queue.
__block size_t unwritten = size;
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) {
^(bool done, dispatch_data_t remaining, int error) {
// `remaining` is what is still to be written; on done,
// nothing is left to count, written or not.
size_t left =
done || remaining == nullptr ? 0 : dispatch_data_get_size(remaining);
connection->pendingWriteBytes.fetch_sub(unwritten - left);
unwritten = left;
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);
});
}
Expand Down Expand Up @@ -145,10 +226,6 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) {
assert(false);
}

// Only touched by the accept handler, which libdispatch never runs
// concurrently with itself.
__block std::weak_ptr<Connection> 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 =
Expand Down Expand Up @@ -189,14 +266,13 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) {
close(clientSocket);
continue;
}
dispatch_io_set_high_water(connection->channel, kWriteProgressBytes);
// Otherwise a slow reader's progress may go unreported until a whole
// high-water chunk is through.
dispatch_io_set_low_water(connection->channel, 1);

// The accept handler is serial, so back-to-back accepts take over in
// order and the newest client stays active.
std::shared_ptr<Connection> 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.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
onClientConnected(connection->id,
[connection](const std::string& message) { Send(connection, message); });

Expand Down
Loading
Loading