Repository navigation
Expand file tree
/
Copy pathJsV8InspectorClient.cpp
More file actions
1186 lines (1006 loc) · 45.4 KB
/
Copy pathJsV8InspectorClient.cpp
File metadata and controls
1186 lines (1006 loc) · 45.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "JsV8InspectorClient.h"
#include <algorithm>
#include <cstring>
#include <include/libplatform/libplatform.h>
#include <src/inspector/string-util.h>
#include <src/inspector/v8-console-message.h>
#include <src/inspector/v8-inspector-impl.h>
#include <src/inspector/v8-inspector-session-impl.h>
#include <src/inspector/v8-runtime-agent-impl.h>
#include <src/inspector/v8-stack-trace-impl.h>
#include "Runtime.h"
#include "NativeScriptException.h"
#include "NativeScriptAssert.h"
#include "NativeScriptPlatform.h"
#include "ArgConverter.h"
#include "Constants.h"
#include "File.h"
#include "Util.h"
#include "Utils.h"
#include "WorkerInspectorClient.h"
#include "WorkerWrapper.h"
#include "ada/ada.h"
#include "third_party/json.hpp"
using namespace std;
using namespace tns;
using namespace v8;
using namespace v8_inspector;
using namespace inspector;
using json = nlohmann::json;
// Utility functions for converting between inspector StringView and UTF8 string
static inline v8_inspector::StringView stringToStringView(const std::string &str) {
auto* chars = reinterpret_cast<const uint8_t*>(str.c_str());
return { chars, str.length() };
}
namespace {
// Scheme advertised to the frontend for source maps the runtime can serve.
// Chrome DevTools never loads `file:` (or `data:`/`devtools:`) resources
// through the target -- PageResourceLoader routes those to the frontend host
// machine, which cannot see files on the device. Any other scheme is fetched
// with Network.loadNetworkResource, which we answer from disk.
constexpr const char* kSourceMapScheme = "nsruntime://";
std::string JsonDump(const json& value) {
// replace invalid UTF-8 instead of throwing across the JNI boundary
return value.dump(-1, ' ', false, json::error_handler_t::replace);
}
std::string FinishResponse(json& response, const std::string& sessionId) {
if (!sessionId.empty()) {
response["sessionId"] = sessionId;
}
return JsonDump(response);
}
// Target.attachedToTarget event announcing a worker as a child target.
std::string BuildWorkerAttachedEvent(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}}}};
return JsonDump(attached);
}
std::string Base64Encode(const char* data, size_t length) {
static const char* kAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string encoded;
encoded.reserve(((length + 2) / 3) * 4);
size_t i = 0;
for (; i + 2 < length; i += 3) {
uint32_t chunk = (static_cast<uint8_t>(data[i]) << 16) |
(static_cast<uint8_t>(data[i + 1]) << 8) |
static_cast<uint8_t>(data[i + 2]);
encoded.push_back(kAlphabet[(chunk >> 18) & 0x3F]);
encoded.push_back(kAlphabet[(chunk >> 12) & 0x3F]);
encoded.push_back(kAlphabet[(chunk >> 6) & 0x3F]);
encoded.push_back(kAlphabet[chunk & 0x3F]);
}
if (i < length) {
uint32_t chunk = static_cast<uint8_t>(data[i]) << 16;
bool hasSecond = i + 1 < length;
if (hasSecond) {
chunk |= static_cast<uint8_t>(data[i + 1]) << 8;
}
encoded.push_back(kAlphabet[(chunk >> 18) & 0x3F]);
encoded.push_back(kAlphabet[(chunk >> 12) & 0x3F]);
encoded.push_back(hasSecond ? kAlphabet[(chunk >> 6) & 0x3F] : '=');
encoded.push_back('=');
}
return encoded;
}
// Opt-out via nativescript.config.ts (serialized into the bundled
// package.json): `android: { disableSourceMapURLRewrite: true }`, or the same
// key at the top level.
bool ShouldRewriteSourceMapURLs() {
static bool disabled = []() {
int length = 0;
auto* data = static_cast<uint8_t*>(File::ReadBinary(Constants::APP_ROOT_FOLDER_PATH + "package.json", length));
if (data == nullptr) {
return false;
}
std::string content(reinterpret_cast<const char*>(data), length);
delete[] data;
auto parsed = json::parse(content, nullptr, false);
if (parsed.is_discarded() || !parsed.is_object()) {
return false;
}
const json* value = nullptr;
if (parsed.contains("android") && parsed["android"].contains("disableSourceMapURLRewrite")) {
value = &parsed["android"]["disableSourceMapURLRewrite"];
} else if (parsed.contains("disableSourceMapURLRewrite")) {
value = &parsed["disableSourceMapURLRewrite"];
}
return value != nullptr && value->is_boolean() && value->get<bool>();
}();
return !disabled;
}
// Rewrites the sourceMapURL of outgoing Debugger.scriptParsed /
// Debugger.scriptFailedToParse events from a file url (or a url relative to
// the script's file url) to an absolute nsruntime:// url, so DevTools
// requests the map through the target instead of the frontend host.
std::string MaybeRewriteSourceMapURL(const std::string& message) {
if (message.find("\"Debugger.scriptParsed\"") == std::string::npos &&
message.find("\"Debugger.scriptFailedToParse\"") == std::string::npos) {
return message;
}
if (!ShouldRewriteSourceMapURLs()) {
return message;
}
auto parsed = json::parse(message, nullptr, false);
if (parsed.is_discarded() || !parsed.contains("params") || !parsed["params"].is_object()) {
return message;
}
auto& params = parsed["params"];
std::string sourceMapURL = params.value("sourceMapURL", "");
if (sourceMapURL.empty() || sourceMapURL.rfind("data:", 0) == 0 ||
sourceMapURL.rfind("http:", 0) == 0 || sourceMapURL.rfind("https:", 0) == 0 ||
sourceMapURL.rfind(kSourceMapScheme, 0) == 0) {
return message;
}
std::string path;
if (sourceMapURL.rfind("file://", 0) == 0) {
path = sourceMapURL.substr(strlen("file://"));
} else if (sourceMapURL[0] == '/') {
path = sourceMapURL;
} else {
// Relative to the script url, e.g. "bundle.js.map".
std::string scriptUrl = params.value("url", "");
if (scriptUrl.rfind("file://", 0) != 0) {
return message;
}
std::string scriptPath = scriptUrl.substr(strlen("file://"));
auto lastSlash = scriptPath.rfind('/');
if (lastSlash == std::string::npos) {
return message;
}
path = scriptPath.substr(0, lastSlash + 1) + sourceMapURL;
}
if (path.empty()) {
return message;
}
params["sourceMapURL"] = kSourceMapScheme + path;
return JsonDump(parsed);
}
} // namespace
JsV8InspectorClient::JsV8InspectorClient(v8::Isolate* isolate)
: tracing_agent_(new tns::inspector::TracingAgentImpl()),
isolate_(isolate),
inspector_(nullptr),
session_(nullptr),
connection_(nullptr),
context_(),
terminated_(true),
running_nested_loop_(false),
isConnected_(false) {
JEnv env;
inspectorClass_ = env.FindClass("com/tns/AndroidJsV8Inspector");
NS_CHECK(inspectorClass_ != nullptr);
sendMethod_ = env.GetStaticMethodID(inspectorClass_, "send", "(Ljava/lang/Object;Ljava/lang/String;)V");
NS_CHECK(sendMethod_ != nullptr);
sendToDevToolsConsoleMethod_ = env.GetStaticMethodID(inspectorClass_, "sendToDevToolsConsole", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)V");
NS_CHECK(sendToDevToolsConsoleMethod_ != nullptr);
getInspectorMessageMethod_ = env.GetStaticMethodID(inspectorClass_, "getInspectorMessage", "(Ljava/lang/Object;)Ljava/lang/String;");
NS_CHECK(getInspectorMessageMethod_ != nullptr);
}
void JsV8InspectorClient::connect(jobject connection) {
JEnv env;
std::lock_guard<std::mutex> lock(connectionMutex_);
connection_ = env.NewGlobalRef(connection);
isConnected_ = true;
}
void JsV8InspectorClient::scheduleBreak() {
v8::Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handleScope(isolate_);
auto context = Runtime::GetRuntime(isolate_)->GetContext();
Context::Scope context_scope(context);
session_->schedulePauseOnNextStatement({}, {});
}
void JsV8InspectorClient::createInspectorSession() {
session_ = inspector_->connect(JsV8InspectorClient::contextGroupId, this, {},
v8_inspector::V8Inspector::kFullyTrusted);
}
void JsV8InspectorClient::disconnect() {
{
// Streams only have meaning to the frontend that opened them; drop any
// the old connection never read to the end (or never IO.close-d).
std::lock_guard<std::mutex> lock(resourceStreamsMutex_);
resourceStreams_.clear();
}
// Nothing will ever ask for a trace the disconnected frontend started, and
// leaving it running keeps the ring buffer filling forever.
tracing_agent_->stopAndDiscard();
// Reset worker sessions first and without the main-isolate Locker: if the
// main isolate is paused, its nested loop owns the Locker and this thread
// blocks below — workers must still get a clean slate (resume if paused,
// fresh session) so the reconnecting frontend can re-attach to them.
{
std::lock_guard<std::mutex> lock(workerTargetsMutex_);
autoAttach_ = false;
for (auto& entry : workerTargets_) {
entry.second.announced = false;
entry.second.client->PushMessage(WorkerInspectorClient::kResetSessionMessage);
}
}
{
std::lock_guard<std::mutex> lock(connectionMutex_);
if (connection_ == nullptr) {
return;
}
JEnv env;
env.DeleteGlobalRef(connection_);
connection_ = nullptr;
isConnected_ = false;
}
v8::Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handleScope(isolate_);
session_->resume();
session_.reset();
createInspectorSession();
}
void JsV8InspectorClient::dispatchMessage(const std::string& message) {
v8::Locker locker(isolate_);
Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handleScope(isolate_);
auto context = Runtime::GetRuntime(isolate_)->GetContext();
Context::Scope context_scope(context);
bool success;
/*
// livesync uses the inspector socket for HMR/LiveSync...
if(message.find("Page.reload") != std::string::npos) {
success = tns::LiveSync(this->isolate_);
if (!success) {
NSLog(@"LiveSync failed");
}
// todo: should we return here, or is it OK to pass onto a possible Page.reload domain handler?
}
*/
// Note: the Tracing domain is handled in handleMessageOnSocketThread, so it
// never waits on this queue or takes the Locker above.
// parse incoming message as JSON
Local<Value> arg;
success = v8::JSON::Parse(context, tns::ArgConverter::ConvertToV8String(isolate_, message)).ToLocal(&arg);
// stop processing invalid messages
if(!success) {
// NSLog(@"Inspector failed to parse incoming message: %s", message.c_str());
// ignore failures to parse.
return;
}
// Pass incoming message to a registerd domain handler if any
if(!arg.IsEmpty() && arg->IsObject()) {
Local<Object> domainDebugger;
Local<Object> argObject = arg.As<Object>();
Local<v8::Function> domainMethodFunc = GetDebuggerFunctionFromObject(context, argObject, domainDebugger);
Local<Value> result;
success = this->CallDomainHandlerFunction(context, domainMethodFunc, argObject, domainDebugger, result);
if(success) {
auto requestId = arg.As<Object>()->Get(context, tns::ArgConverter::ConvertToV8String(isolate_, "id")).ToLocalChecked();
auto returnString = GetReturnMessageFromDomainHandlerResult(result, requestId);
if(returnString.size() > 0) {
std::vector<uint16_t> vector_ = tns::Util::ToVector(returnString);
StringView messageView_(vector_.data(), vector_.size());
auto msg = StringBuffer::create(messageView_);
this->sendNotification(std::move(msg));
}
return;
}
}
doDispatchMessage(message);
// TODO: check why this is needed (it should trigger automatically when script depth is 0)
isolate_->PerformMicrotaskCheckpoint();
}
void JsV8InspectorClient::runMessageLoopOnPause(int context_group_id) {
if (running_nested_loop_) {
return;
}
JEnv env;
terminated_ = false;
running_nested_loop_ = true;
isPausedNestedLoop_.store(true, std::memory_order_release);
while (!terminated_) {
JniLocalRef msg(env.CallStaticObjectMethod(inspectorClass_, getInspectorMessageMethod_, connection_));
if (!msg.IsNull()) {
auto inspectorMessage = ArgConverter::jstringToString(msg);
doDispatchMessage(inspectorMessage);
}
// JS frames are on the stack, so only nestable v8 foreground tasks
// may run; everything else fires from its own wakeup after resume
tns::NativeScriptPlatform::Instance()
->GetEventLoop(isolate_)
->RunNestableV8Tasks();
}
isPausedNestedLoop_.store(false, std::memory_order_release);
terminated_ = false;
running_nested_loop_ = false;
}
void JsV8InspectorClient::quitMessageLoopOnPause() {
terminated_ = true;
}
v8::Local<v8::Context> JsV8InspectorClient::ensureDefaultContextInGroup(int contextGroupId) {
return context_.Get(isolate_);
}
void JsV8InspectorClient::doDispatchMessage(const std::string& message) {
if (session_ == nullptr) {
return;
}
v8_inspector::StringView message_view = stringToStringView(message);
session_->dispatchProtocolMessage(message_view);
}
// Chrome DevTools fetches source maps through the target: it sends
// Network.loadNetworkResource for the resolved sourceMappingURL and reads the
// returned stream with IO.read/IO.close. Neither domain is implemented by
// V8's inspector, so they are served here, on the websocket read thread --
// the main thread may be blocked in the pause message loop or busy running
// JS. The Target domain and worker-session routing live here for the same
// reason: messages received while the main isolate is paused are dispatched
// by doDispatchMessage straight into the V8 session, so dispatchMessage's
// method handling never runs, and a worker must stay debuggable while the
// main isolate is paused (and vice versa). None of this touches V8 except
// the thread-safe RequestInterrupt.
bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message, std::string& response) {
auto parsed = json::parse(message, nullptr, false);
if (parsed.is_discarded() || !parsed.is_object()) {
return false;
}
std::string method = parsed.contains("method") && parsed["method"].is_string()
? parsed["method"].get<std::string>()
: "";
long long msgId = parsed.contains("id") && parsed["id"].is_number()
? parsed["id"].get<long long>()
: -1;
std::string sessionId = parsed.contains("sessionId") && parsed["sessionId"].is_string()
? parsed["sessionId"].get<std::string>()
: "";
// Network/IO first: they serve any session (sessionId echoed), including
// worker source maps.
if (method == "Network.loadNetworkResource") {
std::string url;
if (parsed.contains("params") && parsed["params"].contains("url") && parsed["params"]["url"].is_string()) {
url = parsed["params"]["url"].get<std::string>();
}
response = HandleLoadNetworkResource(msgId, url, sessionId);
return true;
}
if (method == "IO.read" || method == "IO.close") {
std::string handle;
int size = 0;
if (parsed.contains("params")) {
const auto& params = parsed["params"];
if (params.contains("handle") && params["handle"].is_string()) {
handle = params["handle"].get<std::string>();
}
if (params.contains("size") && params["size"].is_number_integer()) {
size = params["size"].get<int>();
}
}
response = method == "IO.read"
? HandleIORead(msgId, handle, size, sessionId)
: HandleIOClose(msgId, handle, sessionId);
return true;
}
// The Tracing domain never touches the isolate, so it is answered here
// instead of on the main-thread dispatch queue: flushing a large trace to
// the 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.
if (sessionId.empty() && method == "Tracing.start") {
std::vector<std::string> categories;
double bufferSizeInKb = 0;
const json* traceConfig = nullptr;
if (parsed.contains("params") && parsed["params"].is_object()) {
const auto& params = parsed["params"];
if (params.contains("traceConfig") && params["traceConfig"].is_object()) {
traceConfig = ¶ms["traceConfig"];
} else if (params.contains("categories") && params["categories"].is_array()) {
// deprecated flat format
traceConfig = ¶ms;
}
}
if (traceConfig != nullptr) {
const char* categoriesKey =
traceConfig->contains("includedCategories") ? "includedCategories" : "categories";
if (traceConfig->contains(categoriesKey) && (*traceConfig)[categoriesKey].is_array()) {
for (const auto& category : (*traceConfig)[categoriesKey]) {
if (category.is_string()) {
categories.push_back(category.get<std::string>());
}
}
}
if (traceConfig->contains("traceBufferSizeInKb") &&
(*traceConfig)["traceBufferSizeInKb"].is_number()) {
bufferSizeInKb = (*traceConfig)["traceBufferSizeInKb"].get<double>();
}
}
json reply = {{"id", msgId}};
if (tracing_agent_->start(categories, bufferSizeInKb)) {
reply["result"] = json::object();
} else {
reply["error"] = {{"code", -32000}, {"message", "Tracing is already started"}};
}
response = JsonDump(reply);
return true;
}
if (sessionId.empty() && method == "Tracing.end") {
tns::inspector::TracingAgentImpl::Result trace;
if (!tracing_agent_->end(trace)) {
json error = {{"id", msgId},
{"error", {{"code", -32000}, {"message", "Tracing is not started"}}}};
response = JsonDump(error);
return true;
}
// The ack must reach the frontend before the events it asked for, so it
// is sent here rather than through `response`.
json ack = {{"id", msgId}, {"result", json::object()}};
this->SendRawToFrontend(JsonDump(ack));
for (const auto& traceMessage : trace.messages) {
this->SendRawToFrontend(traceMessage);
}
json complete = {{"method", "Tracing.tracingComplete"},
{"params", {{"dataLossOccurred", trace.dataLossOccurred}}}};
this->SendRawToFrontend(JsonDump(complete));
return true;
}
// DevTools discovers worker targets through the Target domain: its
// ChildTargetManager sends Target.setAutoAttach {flatten: true} right
// after connecting, and from then on expects Target.attachedToTarget /
// Target.detachedFromTarget events.
if (method == "Target.setAutoAttach") {
bool autoAttach = parsed.contains("params") && parsed["params"].contains("autoAttach") &&
parsed["params"]["autoAttach"].is_boolean() &&
parsed["params"]["autoAttach"].get<bool>();
if (sessionId.empty()) {
{
std::lock_guard<std::mutex> lock(workerTargetsMutex_);
autoAttach_ = autoAttach;
}
// The ack must reach the frontend before any attachedToTarget
// events, so it is sent here instead of through `response` (which
// the socket only writes after this method returns).
json ack = {{"id", msgId}, {"result", json::object()}};
this->SendToFrontend(JsonDump(ack));
if (autoAttach) {
this->AnnounceWorkerTargets();
}
} else {
// Workers have no child targets of their own; just ack.
json ack = {{"id", msgId}, {"result", json::object()}};
this->SendToFrontend(FinishResponse(ack, sessionId));
}
return true;
}
if (method == "Target.setDiscoverTargets" || method == "Target.setRemoteLocations" ||
method == "Target.detachFromTarget") {
json ack = {{"id", msgId}, {"result", json::object()}};
response = FinishResponse(ack, sessionId);
return true;
}
// Flat-session protocol: a top-level sessionId addresses a worker target.
if (!sessionId.empty()) {
this->RouteToWorker(sessionId, method, msgId, message);
return true;
}
// Debugger.pause needs to interrupt V8 even if the main thread is busy
// executing JS; RequestInterrupt fires at the next safe bytecode boundary.
// The message still flows through the dispatch queue so V8 answers the
// request id. Skip it while paused in the nested message loop: no JS is
// running, so the interrupt would only fire after the user resumes,
// causing a spurious re-pause.
if (method == "Debugger.pause" && !isPausedNestedLoop_.load(std::memory_order_acquire)) {
isolate_->RequestInterrupt(
[](v8::Isolate* isolate, void* data) {
auto* client = static_cast<JsV8InspectorClient*>(data);
if (client->session_ != nullptr) {
client->session_->schedulePauseOnNextStatement({}, {});
}
},
this);
}
return false;
}
void JsV8InspectorClient::RouteToWorker(const std::string& sessionId, const std::string& method,
long long msgId, const std::string& message) {
// Built under the lock, sent after releasing it: a blocking socket write
// must not stall worker register/unregister on other threads.
std::string errorPayload;
{
std::lock_guard<std::mutex> lock(workerTargetsMutex_);
auto it = workerTargets_.find(sessionId);
if (it == workerTargets_.end()) {
// The worker died (or never existed): answer commands so the
// frontend does not wait forever.
if (msgId >= 0) {
json error = {{"id", msgId},
{"sessionId", sessionId},
{"error", {{"code", -32001}, {"message", "Session not found"}}}};
errorPayload = JsonDump(error);
}
} else {
// The lock keeps the client alive against a concurrent
// UnregisterWorkerTarget + delete on the worker thread; both calls
// below are non-blocking (queue push / RequestInterrupt), so they
// never hold the lock across a socket write.
WorkerInspectorClient* client = it->second.client;
// Debugger.pause must interrupt a busy worker; skip it while the
// worker sits in its nested pause loop (no JS running - the
// interrupt would only fire after resume, causing a spurious
// re-pause). The message is still pushed so V8 answers the id.
if (method == "Debugger.pause" && !client->IsRunningPauseLoop()) {
client->RequestPauseInterrupt();
}
client->PushMessage(message);
}
}
if (!errorPayload.empty()) {
this->SendToFrontend(errorPayload);
}
}
void JsV8InspectorClient::RegisterWorkerTarget(int workerId, WorkerInspectorClient* client) {
std::string attachedPayload;
{
std::lock_guard<std::mutex> lock(workerTargetsMutex_);
WorkerTarget target{workerId, client, false};
if (isConnected_ && autoAttach_) {
target.announced = true;
attachedPayload = BuildWorkerAttachedEvent(client);
}
workerTargets_.emplace(client->SessionId(), target);
}
if (!attachedPayload.empty()) {
this->SendToFrontend(attachedPayload);
}
}
void JsV8InspectorClient::UnregisterWorkerTarget(int workerId) {
std::string detachedPayload;
{
std::lock_guard<std::mutex> lock(workerTargetsMutex_);
for (auto it = workerTargets_.begin(); it != workerTargets_.end(); ++it) {
if (it->second.workerId != workerId) {
continue;
}
if (it->second.announced && isConnected_) {
json detached = {{"method", "Target.detachedFromTarget"},
{"params",
{{"sessionId", it->second.client->SessionId()},
{"targetId", it->second.client->TargetId()}}}};
detachedPayload = JsonDump(detached);
}
workerTargets_.erase(it);
break;
}
}
if (!detachedPayload.empty()) {
this->SendToFrontend(detachedPayload);
}
}
void JsV8InspectorClient::AnnounceWorkerTargets() {
std::vector<std::string> pending;
{
std::lock_guard<std::mutex> lock(workerTargetsMutex_);
for (auto& entry : workerTargets_) {
WorkerTarget& target = entry.second;
if (target.announced) {
continue;
}
target.announced = true;
pending.push_back(BuildWorkerAttachedEvent(target.client));
}
}
for (const auto& payload : pending) {
this->SendToFrontend(payload);
}
}
void JsV8InspectorClient::SchedulePauseInWorker(int workerId) {
// Runs on the worker's own thread from a V8 interrupt; re-resolved through
// the registry so a late interrupt after the worker died is a no-op.
std::lock_guard<std::mutex> lock(workerTargetsMutex_);
for (auto& entry : workerTargets_) {
if (entry.second.workerId == workerId) {
entry.second.client->SchedulePauseFromInterrupt();
return;
}
}
}
std::string JsV8InspectorClient::HandleLoadNetworkResource(long long msgId, const std::string& url, const std::string& sessionId) {
std::string path;
if (url.rfind(kSourceMapScheme, 0) == 0) {
path = url.substr(strlen(kSourceMapScheme));
} else if (url.rfind("file://", 0) == 0) {
path = url.substr(strlen("file://"));
} else {
// Reply with a protocol error (not success:false) so DevTools falls
// back to loading the resource from the frontend host, which is the
// pre-existing behavior for http(s) urls.
json error = {
{"id", msgId},
{"error", {{"code", -32000}, {"message", "Unsupported URL scheme"}}}
};
return FinishResponse(error, sessionId);
}
std::string content;
bool loaded = false;
if (!path.empty()) {
std::vector<std::string> candidates;
auto addCandidate = [&candidates](const std::string& candidate) {
if (!candidate.empty() &&
std::find(candidates.begin(), candidates.end(), candidate) == candidates.end()) {
candidates.push_back(candidate);
}
};
auto addVariants = [&addCandidate](const std::string& p) {
addCandidate(p);
if (p[0] != '/') {
addCandidate(Constants::APP_ROOT_FOLDER_PATH + p);
}
// /data/data/<pkg> and /data/user/0/<pkg> alias the same files;
// urls may use either spelling depending on who built them.
constexpr const char* kDataData = "/data/data/";
constexpr const char* kDataUser0 = "/data/user/0/";
if (p.rfind(kDataData, 0) == 0) {
addCandidate(kDataUser0 + p.substr(strlen(kDataData)));
} else if (p.rfind(kDataUser0, 0) == 0) {
addCandidate(kDataData + p.substr(strlen(kDataUser0)));
}
};
addVariants(path);
// fall back to percent-decoded variants for urls the frontend encoded
std::string decoded = ada::unicode::percent_decode(path, path.find('%'));
if (decoded != path) {
addVariants(decoded);
}
for (const auto& candidate : candidates) {
int length = 0;
auto* data = static_cast<uint8_t*>(File::ReadBinary(candidate, length));
if (data != nullptr) {
content.assign(reinterpret_cast<const char*>(data), length);
delete[] data;
loaded = true;
break;
}
}
}
json resource;
if (loaded) {
std::string handle;
{
std::lock_guard<std::mutex> lock(resourceStreamsMutex_);
handle = "ns-network-resource-" + std::to_string(++lastStreamId_);
resourceStreams_[handle] = {std::move(content), 0};
}
resource = {{"success", true}, {"httpStatusCode", 200}, {"stream", handle}};
} else {
resource = {{"success", false},
{"netError", -6},
{"netErrorName", "net::ERR_FILE_NOT_FOUND"},
{"httpStatusCode", 404}};
}
json response = {{"id", msgId}, {"result", {{"resource", resource}}}};
return FinishResponse(response, sessionId);
}
std::string JsV8InspectorClient::HandleIORead(long long msgId, const std::string& handle, int size, const std::string& sessionId) {
std::lock_guard<std::mutex> lock(resourceStreamsMutex_);
auto it = resourceStreams_.find(handle);
if (it == resourceStreams_.end()) {
json error = {
{"id", msgId},
{"error", {{"code", -32602}, {"message", "Invalid stream handle"}}}
};
return FinishResponse(error, sessionId);
}
ResourceStream& stream = it->second;
constexpr size_t kDefaultChunkSize = 1024 * 1024;
size_t chunkSize = size > 0 ? static_cast<size_t>(size) : kDefaultChunkSize;
size_t remaining = stream.data.size() - stream.offset;
chunkSize = std::min(chunkSize, remaining);
json result;
if (chunkSize == 0) {
// DevTools ignores any data sent alongside eof, so only signal it once
// the whole stream has been delivered.
result = {{"data", ""}, {"eof", true}, {"base64Encoded", false}};
} else {
// Base64 keeps arbitrary file bytes intact through the JSON transport.
std::string encoded = Base64Encode(stream.data.data() + stream.offset, chunkSize);
stream.offset += chunkSize;
result = {{"data", encoded}, {"eof", false}, {"base64Encoded", true}};
}
json response = {{"id", msgId}, {"result", result}};
return FinishResponse(response, sessionId);
}
std::string JsV8InspectorClient::HandleIOClose(long long msgId, const std::string& handle, const std::string& sessionId) {
{
std::lock_guard<std::mutex> lock(resourceStreamsMutex_);
resourceStreams_.erase(handle);
}
json response = {{"id", msgId}, {"result", json::object()}};
return FinishResponse(response, sessionId);
}
void JsV8InspectorClient::sendResponse(int callId, std::unique_ptr<StringBuffer> message) {
sendNotification(std::move(message));
}
void JsV8InspectorClient::sendNotification(std::unique_ptr<StringBuffer> message) {
this->SendToFrontend(v8_inspector::toString16(message->string()).utf8());
}
void JsV8InspectorClient::SendToFrontend(const std::string& message) {
SendRawToFrontend(MaybeRewriteSourceMapURL(message));
}
void JsV8InspectorClient::SendRawToFrontend(const std::string& msg) {
JEnv env;
JniLocalRef connection;
{
std::lock_guard<std::mutex> lock(connectionMutex_);
if (connection_ == nullptr) {
return;
}
// A local ref keeps the websocket reachable after disconnect() drops
// the global ref; the (synchronized, possibly blocking) socket write
// must not run under the mutex or it would block disconnect().
connection = JniLocalRef(env.NewLocalRef(connection_));
}
try {
// TODO: Pete: Check if we can use a wide (utf 16) string here
JniLocalRef str(env.NewStringUTF(msg.c_str()));
env.CallStaticVoidMethod(inspectorClass_, sendMethod_, (jobject) connection, (jstring) str);
} catch (NativeScriptException& e) {
// The socket died mid-send; the frontend is gone anyway. This must not
// unwind into V8 inspector internals or a worker's pause loop.
env.ExceptionClear();
}
}
void JsV8InspectorClient::flushProtocolNotifications() {
}
void JsV8InspectorClient::init() {
if (inspector_ != nullptr) {
return;
}
v8::Locker locker(isolate_);
v8::Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handle_scope(isolate_);
v8::Local<Context> context = Runtime::GetRuntime(isolate_)->GetContext();
inspector_ = V8Inspector::create(isolate_, this);
// Name the context: the DevTools console context selector labels entries
// with the context's name; workers are labeled with their script url.
static const std::string mainContextName = "main";
inspector_->contextCreated(v8_inspector::V8ContextInfo(
context, JsV8InspectorClient::contextGroupId, stringToStringView(mainContextName)));
context_.Reset(isolate_, context);
createInspectorSession();
try {
this->registerModules();
} catch (NativeScriptException& e) {
// we don't want to throw if registering modules failed.
// e.ReThrowToV8();
}
}
JsV8InspectorClient* JsV8InspectorClient::GetInstance() {
JsV8InspectorClient* client = instance.load(std::memory_order_acquire);
if (client != nullptr) {
return client;
}
// handleMessageOnSocketThread also calls this from the socket thread, so a
// concurrent first call is possible: construct, then publish with a CAS and
// discard our copy if another thread won the race.
Runtime* mainRuntime = Runtime::GetMainRuntime();
if (mainRuntime == nullptr) {
throw NativeScriptException("Cannot create the inspector: the main runtime is not initialized");
}
auto* created = new JsV8InspectorClient(mainRuntime->GetIsolate());
JsV8InspectorClient* expected = nullptr;
if (!instance.compare_exchange_strong(expected, created, std::memory_order_acq_rel,
std::memory_order_acquire)) {
delete created;
return expected;
}
return created;
}
JsV8InspectorClient* JsV8InspectorClient::GetInstanceIfCreated() {
return instance.load(std::memory_order_acquire);
}
void JsV8InspectorClient::inspectorSendEventCallback(const FunctionCallbackInfo<Value>& args) {
JsV8InspectorClient* client = GetInstanceIfCreated();
if (client == nullptr || !client->isConnected_) {
return;
}
Local<v8::String> arg = args[0].As<v8::String>();
std::string message = ArgConverter::ConvertToString(arg);
client->SendToFrontend(message);
// TODO: ios uses this method, but doesn't work on android
// so I'm just sending directly to the socket (which seems to work)
client->dispatchMessage(message);
}
void JsV8InspectorClient::sendToFrontEndCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
JsV8InspectorClient* client = GetInstanceIfCreated();
if (client == nullptr) {
return;
}
try {
auto isolate = args.GetIsolate();
if ((args.Length() > 0) && args[0]->IsString()) {
auto context = isolate->GetCurrentContext();
std::string message = ArgConverter::ConvertToString(args[0]->ToString(context).ToLocalChecked());
std::string level = "log";
if (args.Length() > 1 && args[1]->IsString()) {
level = ArgConverter::ConvertToString(args[1]->ToString(context).ToLocalChecked());
}
JEnv env;
JniLocalRef connection;
{
std::lock_guard<std::mutex> lock(client->connectionMutex_);
if (client->connection_ == nullptr) {
return;
}
connection = JniLocalRef(env.NewLocalRef(client->connection_));
}
JniLocalRef str(env.NewStringUTF(message.c_str()));
JniLocalRef lev(env.NewStringUTF(level.c_str()));
env.CallStaticVoidMethod(client->inspectorClass_, client->sendToDevToolsConsoleMethod_, (jobject) connection, (jstring) str, (jstring)lev);
}
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void JsV8InspectorClient::consoleLogCallback(Isolate* isolate, ConsoleAPIType method, const std::vector<v8::Local<v8::Value>>& args) {
// Worker isolates route to their own inspector (we're on the worker's
// thread here). Checked first so worker logging never lazily constructs
// the root client.
WorkerWrapper* worker = WorkerWrapper::FromIsolate(isolate);
if (worker != nullptr) {
worker->ConsoleLog(method, args);
return;
}