Skip to content

Commit fbda060

Browse files
authored
fix(inspector): serve source map streams the way Chromium does (#2091)
IO.read cut the stream every 1 MB without regard for UTF-8, always sent base64 and ignored the offset argument, and loadNetworkResource sent no headers. VS Code's js-debug decodes each chunk on its own, so a character straddling a chunk boundary came out as two U+FFFD in the map's sourcesContent. Because the reply had no Content-Length, js-debug also never sent IO.close, and every map it loaded stayed in memory until the debugger disconnected. The IO domain now follows Chromium's DevToolsStreamFile and IOHandler: - a chunk longer than 6 bytes is trimmed back to the end of its last whole character (base::TruncateUTF8ToByteSize); - valid UTF-8 (base::IsStringUTF8) is sent as text, anything else as base64; - offset is honored, and a missing or negative one continues from the last read; a read past the end is eof; - offset and size must be int32, as in Chromium's protocol bindings, and a size <= 0 is rejected; IO.close on an unknown handle is an error; - a stream lives until IO.close or until its frontend disconnects. loadNetworkResource now sends Content-Length and Content-Type, as an HTTP server would for the file, so js-debug reads exactly that many bytes and closes the stream itself. A text chunk that cuts a character (a read that starts inside one, or one of 6 bytes or fewer) is sent as base64 with its exact bytes, where Chromium's JSON encoder would drop them. The default chunk stays at 1 MB (Chromium uses 10 MB) to keep socket frames small on device.
1 parent 1fd6b65 commit fbda060

2 files changed

Lines changed: 189 additions & 33 deletions

File tree

‎test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp‎

Lines changed: 179 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#include "JsV8InspectorClient.h"
22
#include <algorithm>
3+
#include <cmath>
4+
#include <cstdint>
35
#include <cstring>
46
#include <include/libplatform/libplatform.h>
57
#include <src/inspector/string-util.h>
@@ -106,6 +108,88 @@ std::string Base64Encode(const char* data, size_t length) {
106108
return encoded;
107109
}
108110

111+
// The IO stream helpers below follow Chromium (base::IsStringUTF8,
112+
// base::TruncateUTF8ToByteSize, DevToolsStreamFile) so IO.read behaves the
113+
// same as in Chrome for every client.
114+
115+
// Length of the well-formed UTF-8 sequence starting at data[i] (no overlongs,
116+
// surrogates or code points past U+10FFFF), or 0 if it is ill-formed or cut
117+
// off at `length`.
118+
size_t DecodeUtf8(const uint8_t* data, size_t i, size_t length, uint32_t& codePoint) {
119+
uint8_t lead = data[i];
120+
if (lead < 0x80) {
121+
codePoint = lead;
122+
return 1;
123+
}
124+
if (lead < 0xC2 || lead > 0xF4) {
125+
return 0;
126+
}
127+
static constexpr uint32_t kMinCodePoint[] = {0, 0, 0x80, 0x800, 0x10000};
128+
size_t count = lead >= 0xF0 ? 4 : lead >= 0xE0 ? 3 : 2;
129+
uint32_t min = kMinCodePoint[count];
130+
codePoint = lead & (0x7F >> count);
131+
if (length - i < count) {
132+
return 0;
133+
}
134+
for (size_t k = 1; k < count; ++k) {
135+
uint8_t trail = data[i + k];
136+
if ((trail & 0xC0) != 0x80) {
137+
return 0;
138+
}
139+
codePoint = (codePoint << 6) | (trail & 0x3F);
140+
}
141+
if (codePoint < min || codePoint > 0x10FFFF || (codePoint >= 0xD800 && codePoint <= 0xDFFF)) {
142+
return 0;
143+
}
144+
return count;
145+
}
146+
147+
// base::IsValidCharacter: excludes noncharacters as well as surrogates.
148+
bool IsValidCharacter(uint32_t c) {
149+
return c < 0xD800 || (c >= 0xE000 && c < 0xFDD0) ||
150+
(c > 0xFDEF && c <= 0x10FFFF && (c & 0xFFFE) != 0xFFFE);
151+
}
152+
153+
bool IsStringUTF8(const std::string& value) {
154+
const auto* data = reinterpret_cast<const uint8_t*>(value.data());
155+
for (size_t i = 0; i < value.size();) {
156+
uint32_t codePoint;
157+
size_t count = DecodeUtf8(data, i, value.size(), codePoint);
158+
if (count == 0 || !IsValidCharacter(codePoint)) {
159+
return false;
160+
}
161+
i += count;
162+
}
163+
return true;
164+
}
165+
166+
// base::TruncateUTF8ToByteSize: the length of the longest prefix of
167+
// data[0, length) that ends right after a valid character, or 0 if none does.
168+
size_t TruncateUTF8ToByteSize(const uint8_t* data, size_t length) {
169+
for (size_t i = length; i-- > 0;) {
170+
uint32_t codePoint;
171+
size_t count = DecodeUtf8(data, i, length, codePoint);
172+
if (count != 0 && IsValidCharacter(codePoint)) {
173+
return i + count;
174+
}
175+
}
176+
return 0;
177+
}
178+
179+
// CDP integers are int32: Chromium's protocol bindings reject anything else,
180+
// though an integral double such as 5.0 still counts.
181+
bool GetInt32(const json& value, long long& out) {
182+
if (!value.is_number()) {
183+
return false;
184+
}
185+
double number = value.get<double>();
186+
if (number != std::trunc(number) || number < INT32_MIN || number > INT32_MAX) {
187+
return false;
188+
}
189+
out = static_cast<long long>(number);
190+
return true;
191+
}
192+
109193
// Opt-out via nativescript.config.ts (serialized into the bundled
110194
// package.json): `android: { disableSourceMapURLRewrite: true }`, or the same
111195
// key at the top level.
@@ -440,19 +524,36 @@ bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message
440524

441525
if (method == "IO.read" || method == "IO.close") {
442526
std::string handle;
443-
int size = 0;
444-
if (parsed.contains("params")) {
527+
std::optional<long long> offset;
528+
std::optional<long long> size;
529+
bool validParams = true;
530+
if (parsed.contains("params") && parsed["params"].is_object()) {
445531
const auto& params = parsed["params"];
446-
if (params.contains("handle") && params["handle"].is_string()) {
447-
handle = params["handle"].get<std::string>();
532+
if (params.contains("handle")) {
533+
validParams &= params["handle"].is_string();
534+
if (params["handle"].is_string()) {
535+
handle = params["handle"].get<std::string>();
536+
}
448537
}
449-
if (params.contains("size") && params["size"].is_number_integer()) {
450-
size = params["size"].get<int>();
538+
for (auto [name, value] : {std::pair{"offset", &offset}, std::pair{"size", &size}}) {
539+
if (params.contains(name)) {
540+
long long parsedValue = 0;
541+
validParams &= GetInt32(params[name], parsedValue);
542+
*value = parsedValue;
543+
}
451544
}
452545
}
453-
response = method == "IO.read"
454-
? HandleIORead(msgId, handle, size, sessionId)
455-
: HandleIOClose(msgId, handle, sessionId);
546+
if (!validParams) {
547+
json error = {
548+
{"id", msgId},
549+
{"error", {{"code", -32602}, {"message", "Invalid parameters"}}}
550+
};
551+
response = FinishResponse(error, sessionId);
552+
} else {
553+
response = method == "IO.read"
554+
? HandleIORead(msgId, handle, offset, size, sessionId)
555+
: HandleIOClose(msgId, handle, sessionId);
556+
}
456557
return true;
457558
}
458559

@@ -770,13 +871,22 @@ std::string JsV8InspectorClient::HandleLoadNetworkResource(long long msgId, cons
770871

771872
json resource;
772873
if (loaded) {
874+
// The headers an HTTP server would send for the file. With
875+
// Content-Length, js-debug stops reading at the exact byte count and
876+
// sends IO.close itself; without it, it never closes the stream.
877+
json headers = {{"Content-Length", std::to_string(content.size())},
878+
{"Content-Type", "application/json"}};
879+
bool binary = !IsStringUTF8(content);
773880
std::string handle;
774881
{
775882
std::lock_guard<std::mutex> lock(resourceStreamsMutex_);
776883
handle = "ns-network-resource-" + std::to_string(++lastStreamId_);
777-
resourceStreams_[handle] = {std::move(content), 0};
884+
resourceStreams_[handle] = {std::move(content), binary, 0};
778885
}
779-
resource = {{"success", true}, {"httpStatusCode", 200}, {"stream", handle}};
886+
resource = {{"success", true},
887+
{"httpStatusCode", 200},
888+
{"headers", std::move(headers)},
889+
{"stream", handle}};
780890
} else {
781891
resource = {{"success", false},
782892
{"netError", -6},
@@ -788,45 +898,84 @@ std::string JsV8InspectorClient::HandleLoadNetworkResource(long long msgId, cons
788898
return FinishResponse(response, sessionId);
789899
}
790900

791-
std::string JsV8InspectorClient::HandleIORead(long long msgId, const std::string& handle, int size, const std::string& sessionId) {
792-
std::lock_guard<std::mutex> lock(resourceStreamsMutex_);
793-
auto it = resourceStreams_.find(handle);
794-
if (it == resourceStreams_.end()) {
901+
std::string JsV8InspectorClient::HandleIORead(long long msgId, const std::string& handle,
902+
std::optional<long long> offset,
903+
std::optional<long long> size,
904+
const std::string& sessionId) {
905+
auto error = [&](const char* message) {
795906
json error = {
796907
{"id", msgId},
797-
{"error", {{"code", -32602}, {"message", "Invalid stream handle"}}}
908+
{"error", {{"code", -32602}, {"message", message}}}
798909
};
799910
return FinishResponse(error, sessionId);
911+
};
912+
913+
// Chromium defaults to 10 MB; smaller chunks keep socket frames and peak
914+
// memory down on device.
915+
constexpr long long kDefaultChunkSize = 1024 * 1024;
916+
long long maxSize = size.value_or(kDefaultChunkSize);
917+
if (maxSize <= 0) {
918+
return error("Invalid max read size");
919+
}
920+
921+
std::lock_guard<std::mutex> lock(resourceStreamsMutex_);
922+
auto it = resourceStreams_.find(handle);
923+
if (it == resourceStreams_.end()) {
924+
return error("Invalid stream handle");
800925
}
801926

802927
ResourceStream& stream = it->second;
803-
constexpr size_t kDefaultChunkSize = 1024 * 1024;
804-
size_t chunkSize = size > 0 ? static_cast<size_t>(size) : kDefaultChunkSize;
805-
size_t remaining = stream.data.size() - stream.offset;
806-
chunkSize = std::min(chunkSize, remaining);
928+
// A missing or negative offset continues from the previous read.
929+
size_t position = offset.value_or(-1) >= 0 ? static_cast<size_t>(*offset) : stream.lastReadPos;
807930

808931
json result;
809-
if (chunkSize == 0) {
810-
// DevTools ignores any data sent alongside eof, so only signal it once
811-
// the whole stream has been delivered.
812-
result = {{"data", ""}, {"eof", true}, {"base64Encoded", false}};
932+
if (position >= stream.data.size()) {
933+
// DevTools ignores any data sent alongside eof, so it only comes on the
934+
// read after the last bytes.
935+
result = {{"data", ""}, {"eof", true}, {"base64Encoded", stream.binary}};
813936
} else {
814-
// Base64 keeps arbitrary file bytes intact through the JSON transport.
815-
std::string encoded = Base64Encode(stream.data.data() + stream.offset, chunkSize);
816-
stream.offset += chunkSize;
817-
result = {{"data", encoded}, {"eof", false}, {"base64Encoded", true}};
937+
const auto* bytes = reinterpret_cast<const uint8_t*>(stream.data.data()) + position;
938+
size_t count = std::min(static_cast<size_t>(maxSize), stream.data.size() - position);
939+
// Don't end a sufficiently large chunk inside a UTF-8 character:
940+
// js-debug decodes every chunk on its own and advances its offset by
941+
// the decoded length, so a split character is both garbled and skews
942+
// that offset.
943+
if (count > 6 && (bytes[count - 1] & 0x80) != 0) {
944+
size_t truncated = TruncateUTF8ToByteSize(bytes, count);
945+
// Nothing valid to cut at means binary data; leave it as is.
946+
if (truncated != 0) {
947+
count = truncated;
948+
}
949+
}
950+
stream.lastReadPos = position + count;
951+
952+
// A read that starts inside a character, or one of 6 bytes or fewer,
953+
// can cut a character at an end. Chromium's JSON encoder would drop
954+
// those bytes; sending that one chunk as base64 keeps them.
955+
bool wholeCharacters =
956+
(bytes[0] & 0xC0) != 0x80 && TruncateUTF8ToByteSize(bytes, count) == count;
957+
const char* chunk = reinterpret_cast<const char*>(bytes);
958+
if (stream.binary || !wholeCharacters) {
959+
result = {{"data", Base64Encode(chunk, count)}, {"eof", false}, {"base64Encoded", true}};
960+
} else {
961+
result = {{"data", std::string(chunk, count)}, {"eof", false}, {"base64Encoded", false}};
962+
}
818963
}
819964

820965
json response = {{"id", msgId}, {"result", result}};
821966
return FinishResponse(response, sessionId);
822967
}
823968

824969
std::string JsV8InspectorClient::HandleIOClose(long long msgId, const std::string& handle, const std::string& sessionId) {
970+
bool closed;
825971
{
826972
std::lock_guard<std::mutex> lock(resourceStreamsMutex_);
827-
resourceStreams_.erase(handle);
973+
closed = resourceStreams_.erase(handle) != 0;
828974
}
829-
json response = {{"id", msgId}, {"result", json::object()}};
975+
json response = closed
976+
? json{{"id", msgId}, {"result", json::object()}}
977+
: json{{"id", msgId},
978+
{"error", {{"code", -32602}, {"message", "Invalid stream handle"}}}};
830979
return FinishResponse(response, sessionId);
831980
}
832981

‎test-app/runtime/src/main/cpp/JsV8InspectorClient.h‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <atomic>
55
#include <map>
66
#include <mutex>
7+
#include <optional>
78
#include <string>
89
#include <vector>
910
#include <src/inspector/v8-console-message.h>
@@ -92,10 +93,14 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe
9293

9394
// Streams backing Network.loadNetworkResource responses, read by the
9495
// frontend through IO.read/IO.close (how Chrome DevTools fetches source
95-
// maps from the target). Accessed from the websocket read thread.
96+
// maps from the target). Accessed from the websocket read thread. Like
97+
// Chromium's DevToolsIOContext, a stream lives until IO.close or until
98+
// its frontend disconnects.
9699
struct ResourceStream {
97100
std::string data;
98-
size_t offset = 0;
101+
// Chromium sends valid UTF-8 as text and everything else as base64.
102+
bool binary = false;
103+
size_t lastReadPos = 0;
99104
};
100105

101106
// Live worker inspectors, keyed by their flat-protocol sessionId
@@ -122,7 +127,9 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe
122127
// Source map delivery to Chrome DevTools (Network.loadNetworkResource +
123128
// IO domain). V8's inspector doesn't implement these embedder domains.
124129
std::string HandleLoadNetworkResource(long long msgId, const std::string& url, const std::string& sessionId);
125-
std::string HandleIORead(long long msgId, const std::string& handle, int size, const std::string& sessionId);
130+
std::string HandleIORead(long long msgId, const std::string& handle,
131+
std::optional<long long> offset, std::optional<long long> size,
132+
const std::string& sessionId);
126133
std::string HandleIOClose(long long msgId, const std::string& handle, const std::string& sessionId);
127134

128135
std::map<std::string, ResourceStream> resourceStreams_;

0 commit comments

Comments
 (0)