Repository navigation
Expand file tree
/
Copy pathWasmExecutionHandler.cpp
More file actions
1032 lines (886 loc) · 42.1 KB
/
Copy pathWasmExecutionHandler.cpp
File metadata and controls
1032 lines (886 loc) · 42.1 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
/*
* Copyright (C) 2025 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WasmExecutionHandler.h"
#if ENABLE(WEBASSEMBLY_DEBUGGER)
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
#include "JSWebAssemblyInstance.h"
#include "JSWebAssemblyModule.h"
#include "Options.h"
#include "SubspaceInlines.h"
#include "VM.h"
#include "VMManager.h"
#include "WasmBreakpointManager.h"
#include "WasmCallee.h"
#include "WasmDebugServer.h"
#include "WasmDebugServerUtilities.h"
#include "WasmExceptionType.h"
#include "WasmIPIntGenerator.h"
#include "WasmIPIntSlowPaths.h"
#include "WasmModuleManager.h"
#include "WasmOps.h"
#include "WasmVirtualAddress.h"
#include <cstdlib>
#include <cstring>
#if OS(WINDOWS)
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif
#include <wtf/Assertions.h>
#include <wtf/DataLog.h>
#include <wtf/HexNumber.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/WTFString.h>
namespace JSC {
namespace Wasm {
WTF_MAKE_TZONE_ALLOCATED_IMPL(ExecutionHandler);
struct StopReasonInfo {
String reasonString;
StringView reasonSuffix;
};
// GDB RSP stop reply: T<AA> where AA is the POSIX signal number in two-digit hex.
// "reason:<suffix>" is an LLDB extension (not in the GDB RSP spec).
// Reference: https://sourceware.org/gdb/current/onlinedocs/gdb/Stop-Reply-Packets.html
static String signalStopString(int signo)
{
return makeString('T', hex(signo, 2, WTF::Uppercase));
}
// Maps DebugState::Reason to GDB RSP T-packet signal and reason suffix.
// Reference: https://sourceware.org/gdb/current/onlinedocs/gdb/Stop-Reply-Packets.html
static inline StopReasonInfo stopReasonToInfo(const DebugState& state)
{
RELEASE_ASSERT(state.stopReason.has_value());
switch (*state.stopReason) {
case DebugState::Reason::Interrupted:
return { signalStopString(SIGSTOP), "signal"_s };
case DebugState::Reason::Breakpoint:
return { signalStopString(SIGTRAP), "breakpoint"_s };
case DebugState::Reason::Step:
return { signalStopString(SIGTRAP), "trace"_s };
case DebugState::Reason::WasmTrap:
return { signalStopString(SIGTRAP), "exception"_s };
}
RELEASE_ASSERT_NOT_REACHED();
}
ExecutionHandler::ExecutionHandler(DebugServer& debugServer, ModuleManager& instanceManager)
: m_debugServer(debugServer)
, m_moduleManager(instanceManager)
, m_breakpointManager(makeUnique<BreakpointManager>())
{
}
void ExecutionHandler::stopTheWorld(VM& debuggee, StopTheWorldEvent event)
{
auto info = VMManager::info();
dataLogLnIf(Options::verboseWasmDebugger(), "[stopTheWorld] debuggee:", RawPointer(&debuggee), " event:", event, " ", info);
{
Locker locker { m_lock };
switch (event) {
case StopTheWorldEvent::WasmStepIntoSiteReached:
RELEASE_ASSERT(m_debuggee == info.targetVM && info.targetVM == info.servingVM && info.worldMode == VMManager::Mode::RunOne);
break;
case StopTheWorldEvent::WasmProgramStop:
RELEASE_ASSERT(info.worldMode != VMManager::Mode::Stopped);
break;
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
// Wait for previous resume all to prevent reenter notifyVMStop.
while (m_awaitingResumeNotification)
m_debuggeeContinue.wait(m_lock);
m_debuggee = &debuggee;
}
VMManager::requestStopAll(VMManager::StopReason::WasmDebugger);
VMManager::singleton().notifyVMStop(debuggee, event);
}
// Instances of a module share the bytecode a breakpoint patches, so the patch cannot be lifted to
// let one of them past it. Resuming dispatches the opcode the breakpoint displaced instead of
// re-reading the patched bytecode, which keeps the breakpoint armed for every other instance.
OpType ExecutionHandler::handleDebuggerTrapIfNeeded(CallFrame* callFrame, JSWebAssemblyInstance* instance, IPIntCallee* callee, uint8_t* pc, uint8_t* mc, IPInt::IPIntStackEntry* stack, Wasm::ExceptionType exceptionType)
{
VM& debuggee = instance->vm();
if (exceptionType == Wasm::ExceptionType::Unreachable) {
VirtualAddress address = VirtualAddress::toVirtual(instance, callee->functionIndex(), pc);
if (auto action = m_breakpointManager->trapActionFor(pc, address)) {
if (action->stopReason) {
debuggee.debugState()->setBreakpointStopData(*action->stopReason, address, action->displacedOpcode, pc, mc, stack, callee, instance, callFrame);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][handleDebuggerTrapIfNeeded] Breakpoint with ", *debuggee.debugState()->stopData);
stopTheWorld(debuggee, StopTheWorldEvent::WasmProgramStop);
} else {
// A sibling instance's site patched this byte, and a site only speaks for the
// instance it names.
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][handleDebuggerTrapIfNeeded] No site for ", address, ", resuming through the patch");
}
// The patch displaced Unreachable only where the bytecode really is an `unreachable`,
// so fall through and report that trap too: returning it here would throw a trap LLDB
// was never told about. Otherwise resuming dispatches the displaced opcode.
if (action->displacedOpcode != OpType::Unreachable)
return action->displacedOpcode;
}
}
if (!m_debugServer.hasSentLibraryList())
return OpType::Unreachable; // Throw; LLDB has no module list to resolve a stop against
if (exceptionType == Wasm::ExceptionType::StackOverflow || exceptionType == Wasm::ExceptionType::Termination) {
// Prologue trap: pc/mc/stack are caller's, not the overflowing function's.
// handleTrapsIfNeeded() may have already processed a NeedStopTheWorld trap,
// serving a debugger stop and clearing stopData via clearStop(); re-establish
// prologue context if needed.
if (!debuggee.debugState()->stopData)
debuggee.debugState()->setPrologueStopData(instance, callee, callFrame);
debuggee.debugState()->stopReason = DebugState::Reason::WasmTrap;
debuggee.debugState()->stopData->wasmTrapType = exceptionType;
} else
debuggee.debugState()->setTrapStopData(callee, instance, callFrame, pc, mc, stack, exceptionType);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][handleDebuggerTrapIfNeeded] Wasm trap at ", *debuggee.debugState()->stopData);
stopTheWorld(debuggee, StopTheWorldEvent::WasmProgramStop);
return OpType::Unreachable; // Throw; trap was reported, now propagate it
}
ExecutionHandler::ResumeMode ExecutionHandler::stopCode(Locker<Lock>& locker, StopTheWorldEvent event)
{
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop] Start with event:", event);
auto notifyDebuggerOfStop = [&]() WTF_REQUIRES_LOCK(m_lock) {
if (m_debuggerState == DebuggerState::ContinueRequested) {
sendStopReply(locker);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop] Sent a stop reply and waiting...");
} else {
RELEASE_ASSERT(requiresStopConfirmation());
m_debuggerContinue.notifyOne(); // Notify debugger that code stopped.
}
};
// Handle stop event and notify debugger
switch (event) {
case StopTheWorldEvent::VMStopped:
case StopTheWorldEvent::VMCreated:
case StopTheWorldEvent::VMActivated:
case StopTheWorldEvent::AtomicsWaitBlocked:
RELEASE_ASSERT(m_debuggerState == DebuggerState::InterruptRequested || m_debuggerState == DebuggerState::SwitchRequested);
// A prologue has no instruction to report, so arm the function's first and let the
// debuggee reach it rather than advertising one it has not run.
if (event == StopTheWorldEvent::VMStopped && m_debuggee->debugState()->isStoppedAtPrologue()) {
auto& stopData = *m_debuggee->debugState()->stopData;
setOneTimeBreakpointAtEntry<DebugStopReason::Interrupted>(stopData.callee.get(), stopData.instance->moduleInformation());
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop] Interrupt at a prologue; running on to the first instruction");
return ResumeMode::One;
}
m_breakpointManager->clearAllOneTimeBreakpoints();
notifyDebuggerOfStop();
break;
case StopTheWorldEvent::WasmProgramStop:
// InterruptRequested reaches here once an interrupt has been forwarded out of a prologue.
RELEASE_ASSERT(m_debuggerState == DebuggerState::StepRequested || m_debuggerState == DebuggerState::ContinueRequested || m_debuggerState == DebuggerState::SwitchRequested || m_debuggerState == DebuggerState::InterruptRequested);
// FIXME: For module-load stops (isNewModuleLoad), step breakpoints should be preserved
// so the in-progress step can complete after LLDB resumes. Clearing them here silently
// cancels any active step. This also affects future LLDB expression evaluation, which can
// trigger module loads internally and should not interrupt a step.
m_breakpointManager->clearAllOneTimeBreakpoints();
notifyDebuggerOfStop();
break;
case StopTheWorldEvent::WasmStepIntoSiteReached:
RELEASE_ASSERT(m_debuggerState == DebuggerState::StepRequested);
m_debuggerContinue.notifyOne(); // Notify that breakpoint is set.
break;
default:
RELEASE_ASSERT_NOT_REACHED();
}
// Wait for debugger command
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop] Waiting for debugger command...");
m_debuggeeContinue.wait(locker); // Wait for resume mode to be set.
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop] Unblocked and running...");
// Only a resume command wakes the wait above, each having set the state below.
switch (m_debuggerState) {
case DebuggerState::SwitchRequested:
return ResumeMode::Switch;
case DebuggerState::StepRequested:
return ResumeMode::One;
case DebuggerState::ContinueRequested:
// Defer debugger notification until after VMs resume to prevent interrupt() race.
m_awaitingResumeNotification = true;
// 'c' after Hc<id> runs only that VM (RunOne); Hc-1 clears m_continueDebuggeeOnly to resume all.
return m_continueDebuggeeOnly ? ResumeMode::One : ResumeMode::All;
case DebuggerState::Replied:
case DebuggerState::InterruptRequested:
break;
}
RELEASE_ASSERT_NOT_REACHED();
return ResumeMode::All;
}
StopTheWorldStatus ExecutionHandler::handleStopTheWorld(VM& debuggee, StopTheWorldEvent event)
{
dataLogLnIf(Options::verboseWasmDebugger(), "[STW] handleStopTheWorld() begin with event:", event, " debuggee:", RawPointer(&debuggee));
Locker locker { m_lock };
selectDebuggeeIfNeeded(debuggee);
RELEASE_ASSERT(m_debuggee);
// If debuggee differs from candidate, switch to debuggee.
if (m_debuggee != &debuggee) {
dataLogLnIf(Options::verboseWasmDebugger(), "[STW] Context switch to debuggee VM");
return STW_CONTEXT_SWITCH(m_debuggee);
}
// Stop the code and let debugger decide resume mode.
ExecutionHandler::ResumeMode mode = stopCode(locker, event);
switch (mode) {
case ExecutionHandler::ResumeMode::One:
return STW_RESUME_ONE(m_debuggee);
case ExecutionHandler::ResumeMode::All:
m_debuggee = nullptr;
return STW_RESUME_ALL();
case ExecutionHandler::ResumeMode::Switch:
RELEASE_ASSERT(m_debuggee != &debuggee);
RELEASE_ASSERT(debuggee.debugState()->isStopped);
RELEASE_ASSERT(m_debuggee->debugState()->isStopped);
return STW_CONTEXT_SWITCH(m_debuggee);
}
RELEASE_ASSERT_NOT_REACHED();
return STW_RESUME_ALL();
}
void ExecutionHandler::selectDebuggeeIfNeeded(VM& fallbackVM) WTF_REQUIRES_LOCK(m_lock)
{
if (m_debuggee) {
dataLogLnIf(Options::verboseWasmDebugger(), "[STW] Already have debuggee VM:", RawPointer(m_debuggee));
return;
}
// Prefer any non-system call.
// FIXME: We should prioritize with WASM traps > non-system calls > system calls.
VM* selectedVM = nullptr;
VMManager::forEachVM([&](VM& vm) {
auto* debugState = vm.debugState();
if (vm.debugState()->isStopped && !debugState->isStoppedAtSystemCall()) {
selectedVM = &vm;
return IterationStatus::Done;
}
return IterationStatus::Continue;
});
m_debuggee = selectedVM ? selectedVM : &fallbackVM;
dataLogLnIf(Options::verboseWasmDebugger(), "[STW] Selected debuggee VM:", RawPointer(m_debuggee));
}
// Called by VMManager when ALL VMs are stopped at safe points.
// Returns resume mode (ResumeOne/ResumeAll/ContextSwitch) to coordinate execution.
StopTheWorldStatus wasmDebuggerOnStopCallback(VM& debuggee, StopTheWorldEvent event)
{
dataLogLnIf(Options::verboseWasmDebugger(), "[STW] Callback invoked with event:", event);
auto& server = DebugServer::singleton();
if (!server.isConnected()) {
dataLogLnIf(Options::verboseWasmDebugger(), "[STW] Not connected, resuming all");
return STW_RESUME_ALL();
}
return server.execution().handleStopTheWorld(debuggee, event);
}
void ExecutionHandler::handlePostResume()
{
Locker locker { m_lock };
if (takeAwaitingResumeNotification()) {
RELEASE_ASSERT(m_debuggerState == DebuggerState::ContinueRequested);
dataLogLnIf(Options::verboseWasmDebugger(), "[PostResume] Notify debugger to continue");
m_debuggerContinue.notifyOne(); // Notify that resume is complete.
m_debuggeeContinue.notifyAll(); // Release resume barrier for VMs blocked in stopTheWorld().
}
}
// Called by VMManager after ALL VMs have resumed (when m_numberOfStoppedVMs reaches 0).
// This is the safe point to notify debugger that resume is complete and release barriers in stopTheWorld().
void wasmDebuggerOnResumeCallback()
{
auto& server = DebugServer::singleton();
if (!server.isConnected()) {
dataLogLnIf(Options::verboseWasmDebugger(), "[STW][PostResume] Not connected, resuming all");
return;
}
server.execution().handlePostResume();
}
void ExecutionHandler::resume()
{
Locker locker { m_lock };
resumeImpl(locker);
}
void ExecutionHandler::resumeImpl(Locker<Lock>& locker)
{
RELEASE_ASSERT(Thread::currentSingleton().uid() == debugServerThreadId());
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Continue] Start");
RELEASE_ASSERT(debuggeeState()->isStopped);
m_debuggerState = DebuggerState::ContinueRequested;
m_debuggeeContinue.notifyOne(); // Notify debuggee VM with resume all command.
// Wait for resume to complete to prevent interrupt() from acquiring lock before VMs resume.
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Continue] Notified code to continue and waiting...");
m_debuggerContinue.wait(locker); // Wait for resume to complete.
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Continue] Confirmed that code is running...");
}
void ExecutionHandler::notifyDebuggerOfNewInstance(VM& vm)
{
vm.debugState()->isNewModuleLoad = true;
stopTheWorld(vm, StopTheWorldEvent::WasmProgramStop);
}
static inline VM* findVM(uint64_t vmId)
{
VM* result = nullptr;
VMManager::forEachVM([&](VM& vm) {
if (vm.debugState()->isStopped && vmId == vm.identifier().toUInt64()) {
result = &vm;
return IterationStatus::Done;
}
return IterationStatus::Continue;
});
return result;
}
bool ExecutionHandler::switchTarget(uint64_t vmId)
{
RELEASE_ASSERT(Thread::currentSingleton().uid() == debugServerThreadId());
Locker locker { m_lock };
VM* newDebuggee = findVM(vmId);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][SwitchVM] current debuggee=", RawPointer(m_debuggee), " new debuggee=", RawPointer(newDebuggee));
if (!newDebuggee)
return false;
if (m_debuggee == newDebuggee)
return true;
RELEASE_ASSERT(debuggeeState()->isStopped);
m_debuggee = newDebuggee;
m_debuggerState = DebuggerState::SwitchRequested;
m_debuggeeContinue.notifyOne(); // Notify to switch VM context.
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][SwitchVM] Notified code to continue and switch VM, waiting...");
m_debuggerContinue.wait(locker); // Wait for new debuggee VM to stop.
RELEASE_ASSERT(debuggeeState()->isStopped);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][SwitchVM] Code is stopped");
return true;
}
void ExecutionHandler::requestStopAllAndWait(Locker<Lock>& locker)
{
RELEASE_ASSERT(!m_debuggee || !debuggeeState()->isStopped);
m_debuggerState = DebuggerState::InterruptRequested;
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][StopAll] Calling VMManager::requestStopAll()...");
VMManager::singleton().requestStopAll(VMManager::StopReason::WasmDebugger);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][StopAll] VMManager::requestStopAll() returned, waiting...");
m_debuggerContinue.wait(locker); // Wait for the serving VM to stop.
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][StopAll] Code is stopped");
}
// FIXME: In RunOne, a debuggee blocked in a wait (VMBlockingScope) leaves no VM to serve this stop:
// the other VMs stay parked by RunOne.
void ExecutionHandler::interrupt()
{
RELEASE_ASSERT(Thread::currentSingleton().uid() == debugServerThreadId());
Locker locker { m_lock };
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Interrupt] Start");
// LLDB implements interrupt flood prevention: once LLDB sends the first interrupt packet,
// no matter how many Ctrl+C the user types, LLDB will not send additional interrupt packets
// until it receives a stop reply. This prevents packet flooding and ensures clean protocol behavior.
// Our WebKit implementation handles each interrupt request by activating StopWorld via VM traps.
requestStopAllAndWait(locker);
sendStopReply(locker);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Interrupt] Code is stopped and debugger replied");
}
void ExecutionHandler::step()
{
RELEASE_ASSERT(Thread::currentSingleton().uid() == debugServerThreadId());
Locker locker { m_lock };
auto* state = debuggeeState();
RELEASE_ASSERT(m_debuggerState == DebuggerState::Replied && state->isStopped);
bool resumeAll = false;
if (state->isStoppedAtSystemCall() || state->isStoppedDueToWasmTrap()) {
// There is no valid next WASM instruction to step to in either case.
// For traps (including StackOverflow at prologue), execution unwinds back to JS —
// resuming all is the right behavior.
resumeAll = true;
} else if (state->isStoppedAtBytecode())
resumeAll = stepAtBytecode(locker, state);
else {
RELEASE_ASSERT(state->isStoppedAtPrologue());
setOneTimeBreakpointAtEntry<DebugStopReason::Step>(state->stopData->callee.get(), state->stopData->instance->moduleInformation());
}
if (resumeAll) {
resumeImpl(locker);
return;
}
RELEASE_ASSERT(m_breakpointManager->hasOneTimeBreakpoints());
m_debuggerState = DebuggerState::StepRequested;
m_debuggeeContinue.notifyOne(); // Notify to resume until next breakpoint.
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Step] Notified code to continue and expected a stop, waiting...");
m_debuggerContinue.wait(locker); // Wait for one-time breakpoint hit.
sendStopReply(locker);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Step] Code is stopped and debugger replied");
}
bool ExecutionHandler::stepAtBytecode(Locker<Lock>& locker, DebugState* state)
{
RELEASE_ASSERT(state->isStoppedAtBytecode());
auto& stopData = *state->stopData;
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Step] Start with ", stopData);
uint8_t* currentPC = stopData.pc;
auto setStepBreakpoint = [&](const uint8_t* nextPC) WTF_REQUIRES_LOCK(m_lock) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Step][SetOneTimeBreakpoint] current PC=", RawPointer(currentPC), "(", stopData.address, "), next PC=", RawPointer(nextPC));
m_breakpointManager->setOneTimeBreakpoint<DebugStopReason::Step>(stopData.instance->moduleInformation(), const_cast<uint8_t*>(nextPC));
};
auto setStepBreakpointAtCaller = [&]() WTF_REQUIRES_LOCK(m_lock) {
if (WasmReturnSite returnSite = getWasmReturnPC(stopData.callFrame))
m_breakpointManager->setOneTimeBreakpoint<DebugStopReason::Step>(returnSite.instance->moduleInformation(), returnSite.pc);
};
auto setStepBreakpointsFromDebugInfo = [&]() WTF_REQUIRES_LOCK(m_lock) {
const auto& moduleInfo = stopData.instance->moduleInformation();
auto functionIndex = stopData.callee->functionIndex();
uint32_t offset = stopData.address.offset();
const auto* nextInstructions = moduleInfo.ensureFunctionDebugInfo(functionIndex).findNextInstructions(offset);
RELEASE_ASSERT(nextInstructions, "Didn't find nextInstructions");
for (uint32_t nextOffset : *nextInstructions)
setStepBreakpoint(stopData.pc + (static_cast<ptrdiff_t>(nextOffset) - static_cast<ptrdiff_t>(offset)));
};
switch (stopData.originalBytecode) {
case Unreachable:
// Unreachable has no successor.
break;
case Nop:
case Drop:
case Select:
setStepBreakpoint(currentPC + 1);
break;
case End:
if (currentPC != stopData.callee->bytecodeEnd()) {
setStepBreakpoint(currentPC + 1);
break;
}
[[fallthrough]];
case Return:
setStepBreakpointAtCaller();
break;
// Step-into design: Set event flag and let runtime resolve callee/handler naturally to avoid duplicating
// complex resolution logic. Runtime calls setStepIntoBreakpointForCall/Throw() with resolved target.
// FIXME: Resolve target once in step() and cache for runtime reuse to eliminate two-phase protocol.
case Throw:
case Rethrow:
case ThrowRef:
case Delegate:
state->setStepIntoThrow();
break;
case TailCall:
case TailCallIndirect:
case TailCallRef:
// Tail calls: Set step-into event for Wasm callees, then set breakpoint at caller
// (for non-Wasm callees or as fallback, since tail calls don't return to next instruction).
state->setStepIntoCall();
setStepBreakpointAtCaller();
break;
case Call:
case CallIndirect:
case CallRef:
// Regular calls: Set step-into event for Wasm callees, then fallthrough to
// set step-over breakpoint at next instruction (for non-Wasm callees or as fallback).
state->setStepIntoCall();
[[fallthrough]];
default: {
setStepBreakpointsFromDebugInfo();
break;
}
}
if (state->hasStepIntoEvent()) {
m_debuggerState = DebuggerState::StepRequested;
m_debuggeeContinue.notifyOne(); // Notify to run and set breakpoints if possible.
m_debuggerContinue.wait(locker); // Wait for call/throw one-time breakpoint to be registered.
}
// If no one-time breakpoints registered, or stopped at memory.atomic.wait (must resumeAll
// so notifier threads can run), then resume all VMs instead of using RunOne.
return !m_breakpointManager->hasOneTimeBreakpoints() || state->isAtomicsWaitStop();
}
void ExecutionHandler::setStepIntoBreakpointForCall(VM& callerVM, CalleeBits boxedCallee, JSWebAssemblyInstance* calleeInstance)
{
if (!callerVM.debugState()->takeStepIntoCall())
return;
[&]() {
Locker locker { m_lock };
RELEASE_ASSERT(m_debuggee == &callerVM);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][StepIntoEvent] Start for call");
RELEASE_ASSERT(m_debuggerState == DebuggerState::StepRequested);
RELEASE_ASSERT(calleeInstance);
if (!boxedCallee.isNativeCallee())
return;
RefPtr wasmCallee = downcast<Wasm::Callee>(boxedCallee.asNativeCallee());
if (wasmCallee->compilationMode() != Wasm::CompilationMode::IPIntMode)
return;
RELEASE_ASSERT(&calleeInstance->vm() == &callerVM);
setOneTimeBreakpointAtEntry<DebugStopReason::Step>(downcast<IPIntCallee>(wasmCallee.get()), calleeInstance->moduleInformation());
}();
stopTheWorld(callerVM, StopTheWorldEvent::WasmStepIntoSiteReached);
}
void ExecutionHandler::setStepIntoBreakpointForThrow(VM& throwVM)
{
if (!throwVM.debugState()->takeStepIntoThrow())
return;
[&]() {
Locker locker { m_lock };
RELEASE_ASSERT(m_debuggee == &throwVM);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][StepIntoEvent] Start for throw");
RELEASE_ASSERT(m_debuggerState == DebuggerState::StepRequested);
if (!throwVM.callFrameForCatch)
return;
if (!throwVM.callFrameForCatch->callee().isNativeCallee())
return;
RefPtr wasmCallee = downcast<Wasm::Callee>(throwVM.callFrameForCatch->callee().asNativeCallee());
if (wasmCallee->compilationMode() != Wasm::CompilationMode::IPIntMode)
return;
RefPtr catchCallee = downcast<IPIntCallee>(wasmCallee.get());
ASSERT(std::holds_alternative<uintptr_t>(throwVM.targetInterpreterPCForThrow));
uintptr_t handlerOffset = std::get<uintptr_t>(throwVM.targetInterpreterPCForThrow);
const uint8_t* handlerPC = catchCallee->bytecode() + handlerOffset;
if (m_breakpointManager->originalOpcodeAt(handlerPC) == Wasm::OpType::TryTable && throwVM.targetInterpreterMetadataPCForThrow) {
const uint8_t* metadataPtr = catchCallee->metadata() + throwVM.targetInterpreterMetadataPCForThrow;
metadataPtr += sizeof(IPInt::CatchMetadata);
const IPInt::BlockMetadata* blockMetadata = reinterpret_cast<const IPInt::BlockMetadata*>(metadataPtr);
handlerPC = handlerPC + blockMetadata->deltaPC;
}
JSWebAssemblyInstance* catchInstance = throwVM.callFrameForCatch->wasmInstance();
RELEASE_ASSERT(&catchInstance->vm() == &throwVM);
m_breakpointManager->setOneTimeBreakpoint<DebugStopReason::Step>(catchInstance->moduleInformation(), const_cast<uint8_t*>(handlerPC));
}();
stopTheWorld(throwVM, StopTheWorldEvent::WasmStepIntoSiteReached);
}
template<DebugStopReason reason>
void ExecutionHandler::setOneTimeBreakpointAtEntry(IPIntCallee* callee, const ModuleInformation& owner)
{
m_breakpointManager->setOneTimeBreakpoint<reason>(owner, const_cast<uint8_t*>(callee->bytecode()));
}
bool ExecutionHandler::requireModuleAddress(VirtualAddress address)
{
VirtualAddress::Type addressType = address.type();
if (addressType == VirtualAddress::Type::Module)
return true;
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Breakpoint must be in module code region, got type: ", static_cast<int>(addressType));
sendErrorReply(ProtocolError::InvalidAddress);
return false;
}
void ExecutionHandler::setBreakpoint(StringView packet)
{
if (packet.isEmpty())
return;
// Parse packet format: Z0,<address>,<length>
if (packet.isEmpty() || packet[0] != 'Z') {
sendErrorReply(ProtocolError::InvalidPacket);
return;
}
StringView params = packet.substring(1);
auto parts = splitWithDelimiters(params, ",,"_s);
if (parts.size() != 3) {
sendErrorReply(ProtocolError::InvalidPacket);
return;
}
auto parsedAddress = parseHexStrict(parts[1]);
if (!parsedAddress) {
sendErrorReply(ProtocolError::InvalidPacket);
return;
}
uint32_t type = parseDecimal(parts[0]);
VirtualAddress address = VirtualAddress(*parsedAddress);
uint32_t length = parseDecimal(parts[2]);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][SetBreakpoint] Setting breakpoint: type=", static_cast<int>(type), ", address=", address, ", length=", length);
// Only support type 0 (software breakpoint)
if (type) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][SetBreakpoint] Unsupported breakpoint type: ", static_cast<int>(type));
sendErrorReply(ProtocolError::UnknownCommand);
return;
}
if (!requireModuleAddress(address))
return;
JSWebAssemblyInstance* instance = m_moduleManager.jsInstance(address.instanceId());
if (!instance) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] No live instance for ", address);
sendErrorReply(ProtocolError::InvalidAddress);
return;
}
uint8_t* pc = address.toPhysicalPC(*instance);
if (!pc) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] No module bytecode at ", address);
sendErrorReply(ProtocolError::InvalidAddress);
return;
}
if (!instance->moduleInformation().isInstructionStart(address.offset())) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Not an instruction boundary: ", address);
sendErrorReply(ProtocolError::InvalidAddress);
return;
}
// Idempotent: LLDB sends one Z0 per instance for shared bytecode. The address is
// recorded so the patch survives until all sites referring to it are removed.
m_breakpointManager->setBreakpointAt(address, instance->moduleInformation(), pc);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][SetBreakpoint] Successfully set breakpoint at ", address, " (physical: ", RawPointer(pc), ")");
sendReplyOK();
}
void ExecutionHandler::removeBreakpoint(StringView packet)
{
if (packet.isEmpty())
return;
// Format: z0,<address>,<length>
if (packet.isEmpty() || packet[0] != 'z') {
sendErrorReply(ProtocolError::InvalidPacket);
return;
}
StringView params = packet.substring(1);
auto parts = splitWithDelimiters(params, ",,"_s);
if (parts.size() != 3) {
sendErrorReply(ProtocolError::InvalidPacket);
return;
}
auto parsedAddress = parseHexStrict(parts[1]);
if (!parsedAddress) {
sendErrorReply(ProtocolError::InvalidPacket);
return;
}
uint32_t type = parseDecimal(parts[0]);
VirtualAddress address = VirtualAddress(*parsedAddress);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Removing breakpoint: type=", static_cast<int>(type), ", address=", address);
// Only support type 0 (software breakpoint)
if (type) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Unsupported breakpoint type for removal: ", static_cast<int>(type));
sendErrorReply(ProtocolError::UnknownCommand);
return;
}
if (!requireModuleAddress(address))
return;
// Resolved from the installed address so removal works even after an instance is collected.
if (!m_breakpointManager->removeBreakpointAt(address))
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] No breakpoint to remove at ", address);
sendReplyOK();
}
void ExecutionHandler::handleThreadStopInfo(StringView packet)
{
// Format: qThreadStopInfo<thread-id-in-hex>
// Parse the thread ID
StringView threadIdStr = packet.substring(strlen("qThreadStopInfo"));
auto vmId = parseHexStrict(threadIdStr);
if (!vmId) {
sendErrorReply(ProtocolError::InvalidPacket);
return;
}
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Handling qThreadStopInfo for thread: ", *vmId);
Locker locker { m_lock };
sendStopReplyForThread(locker, *vmId);
}
static uint64_t LEGACY_NODELETE getStopPC(const DebugState& state)
{
if (state.isStoppedAtSystemCall())
return VirtualAddress(VirtualAddress::INVALID_BASE).value();
RELEASE_ASSERT(state.stopData);
return state.stopData->address;
}
static String getThreadName(const DebugState& state, uint64_t vmId)
{
StringView stateName;
if (state.isStoppedAtPrologue())
stateName = "wasm-prologue"_s;
else if (state.isStoppedAtBytecode())
stateName = "wasm-call"_s;
else {
RELEASE_ASSERT(state.isStoppedAtSystemCall());
stateName = "system-call"_s;
}
return makeString(stateName, " tid:0x"_s, hex(vmId, Lowercase));
}
struct ThreadInfo {
uint64_t vmId;
uint64_t pc;
String name;
StringView stopReason;
};
void ExecutionHandler::sendStopReply(AbstractLocker& locker) WTF_REQUIRES_LOCK(m_lock)
{
sendStopReplyForThread(locker, m_debuggee->identifier().toUInt64());
}
void ExecutionHandler::sendStopReplyForThread(AbstractLocker& locker, uint64_t vmId) WTF_REQUIRES_LOCK(m_lock)
{
VM* vm = findVM(vmId);
if (!vm) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] sendStopReplyForThread: thread ", vmId, " not found");
sendReplyImpl(locker, getErrorReply(ProtocolError::InvalidAddress));
return;
}
DebugState* state = vm->debugState();
if (!state) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] sendStopReplyForThread: thread ", vmId, " not found");
sendReplyImpl(locker, getErrorReply(ProtocolError::InvalidAddress));
return;
}
RELEASE_ASSERT(state->isStopped);
// Collect all stopped threads; swap event thread to index 0 so thread-pcs[i] aligns with threads[i].
Vector<ThreadInfo> allThreads;
VMManager::forEachVM([&](VM& vm) {
auto* state = vm.debugState();
if (!state->isStopped)
return IterationStatus::Continue;
uint64_t tid = vm.identifier().toUInt64();
allThreads.append({ tid, getStopPC(*state), getThreadName(*state, tid), stopReasonToInfo(*state).reasonSuffix });
if (tid == vmId)
std::swap(allThreads[0], allThreads.last());
return IterationStatus::Continue;
});
// A "passive thread" is a VM that was collaterally stopped when the world was halted (its
// stopReason set to Interrupted by setStopped()), as opposed to the debuggee thread that
// actually triggered the stop event (breakpoint/step/trap/interrupt/new-module-load).
// Passive threads get signal 0 so LLDB's ShouldSelect() returns false for them, allowing
// the event thread to win thread selection in HandleProcessStateChangedEvent.
bool isPassiveThread = state->stopReason == DebugState::Reason::Interrupted && m_debuggee && vmId != m_debuggee->identifier().toUInt64();
auto stopInfo = isPassiveThread
? StopReasonInfo { signalStopString(0), "signal"_s }
: stopReasonToInfo(*state);
// Build packet with target thread
StringBuilder reply;
reply.append(stopInfo.reasonString);
reply.append("thread:"_s, hex(vmId, Lowercase), ';');
reply.append("name:"_s, getThreadName(*state, vmId), ';');
// All thread IDs
reply.append("threads:"_s);
for (size_t i = 0; i < allThreads.size(); ++i) {
if (i > 0)
reply.append(',');
reply.append(hex(allThreads[i].vmId, Lowercase));
}
reply.append(';');
// All thread PCs
reply.append("thread-pcs:"_s);
for (size_t i = 0; i < allThreads.size(); ++i) {
if (i > 0)
reply.append(',');
reply.append(hex(allThreads[i].pc, 16, Lowercase));
}
reply.append(';');
reply.append("00:"_s, toNativeEndianHex(getStopPC(*state)), ';');
reply.append("reason:"_s, stopInfo.reasonSuffix, ';');
// Sweeps collected instances, so drain what they left behind before using the result. The
// world is stopped here, which is what makes unpatching bytecode safe.
bool requeryLibraries = m_moduleManager.needsLibraryRequery();
for (uint32_t instanceId : m_moduleManager.takeCollectedInstanceIds())
m_breakpointManager->removeSitesForInstance(instanceId);
// Prompt LLDB to re-query libraries on new instances or instance teardown.
// Gated on hasSentLibraryList() to avoid sending library:; in the ? reply before the initial
// qXfer:libraries:read handshake completes.
if (requeryLibraries && m_debugServer.hasSentLibraryList()) {
reply.append("library:;"_s);
// Include a human-readable description only for dedicated new-instance-load stops.
if (state->isNewModuleLoad) {
RELEASE_ASSERT(state->isStoppedAtSystemCall());
reply.append("description:"_s);
StringBuilder description;
description.append("loaded new wasm module instance with ids: "_s);
auto ids = m_moduleManager.unnotifiedInstanceIds();
for (size_t i = 0; i < ids.size(); ++i) {
if (i)
description.append(", "_s);
description.append(ids[i]);
}
for (UChar c : StringView(description.toString()).codeUnits())
reply.append(hex(static_cast<uint8_t>(c), 2, Lowercase));
reply.append(';');
}
}
// For trap stops, include a hex-encoded description so LLDB can display the trap reason.
if (state->isStoppedDueToWasmTrap()) {
reply.append("description:"_s);
for (UChar c : StringView(Wasm::errorMessageForExceptionType(*state->stopData->wasmTrapType)).codeUnits())
reply.append(hex(static_cast<uint8_t>(c), 2, Lowercase));
reply.append(';');
}
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Sending stop reply: target thread="_s, hex(vmId), ", total threads="_s, allThreads.size(), ", packet="_s, reply.toString());
sendReplyImpl(locker, reply.toString());
}
void ExecutionHandler::sendReply(StringView reply)
{
Locker locker { m_lock };
sendReplyImpl(locker, reply);
}
void ExecutionHandler::sendReplyImpl(AbstractLocker&, StringView reply) WTF_REQUIRES_LOCK(m_lock)
{
uint8_t checksum = 0;
for (auto character : reply.codeUnits())
checksum += character;
String packet = makeString('$', reply, '#', hex(checksum, 2, Lowercase));
#if ENABLE(REMOTE_INSPECTOR)
if (m_debugServer.isRWIMode()) {
RELEASE_ASSERT(!!m_debugServer.m_rwiResponseHandler);
if (m_debugServer.m_rwiResponseHandler(packet)) {
m_debuggerState = DebuggerState::Replied;
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Sent reply via RWI: ", packet);
} else
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Failed to send packet via RWI: ", packet);
return;
}
#endif
auto packetData = packet.utf8();
auto packetBytes = packetData.span();
int sent = static_cast<int>(send(m_debugServer.m_clientSocket, packetBytes.data(), packetBytes.size(), 0));
if (sent < 0)
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Failed to send packet: ", packetData, " sent: ", sent);
else {
m_debuggerState = DebuggerState::Replied;
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Sent reply: ", packetData);
}
}
void ExecutionHandler::reset()
{
Locker locker { m_lock };
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Handling client disconnection in ExecutionHandler");
// Clear before resuming: resumeImpl() transiently releases m_lock, and the
// VM must not re-hit a breakpoint in that window.
m_breakpointManager->clearAllBreakpoints();
// A lone 'c'-after-Hc VM is still running and holds the others stopped; stop it so resume frees all.
if (m_debuggee && !debuggeeState()->isStopped && m_continueDebuggeeOnly)
requestStopAllAndWait(locker);
m_continueDebuggeeOnly = false;
// FIXME: In RunOne, a debuggee blocked in a wait (VMBlockingScope) has isStopped set but is not in
// stopCode, so resumeImpl() would wait forever; this needs to resume every VM instead.
if (m_debuggee && debuggeeState()->isStopped)
resumeImpl(locker);
m_debuggerState = DebuggerState::Replied;
takeAwaitingResumeNotification();
m_debuggee = nullptr;
}
void ExecutionHandler::sendReplyOK() { m_debugServer.sendReplyOK(); }
void ExecutionHandler::sendErrorReply(ProtocolError error) { m_debugServer.sendErrorReply(error); }
DebugState* ExecutionHandler::debuggeeState() const { return m_debuggee->debugState(); }
DebugState* ExecutionHandler::debuggeeStateForTest() const
{
Locker locker { m_lock };
RELEASE_ASSERT(m_debuggee);
return m_debuggee->debugState();
}
String ExecutionHandler::callStackStringFor(uint64_t vmId)
{
Locker locker { m_lock };
VM* targetVM = m_debuggee;
RELEASE_ASSERT(targetVM);
if (targetVM->identifier().toUInt64() != vmId)
targetVM = findVM(vmId);