Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathWasmDebugServer.cpp
More file actions
493 lines (433 loc) · 17.1 KB
/
WasmDebugServer.cpp
File metadata and controls
493 lines (433 loc) · 17.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
/*
* 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 "WasmDebugServer.h"
#if ENABLE(WEBASSEMBLY_DEBUGGER)
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
#include "CallFrame.h"
#include "JSWebAssemblyInstance.h"
#include "JSWebAssemblyModule.h"
#include "Options.h"
#include "VM.h"
#include "VMManager.h"
#include "WasmBreakpointManager.h"
#include "WasmExecutionHandler.h"
#include "WasmIPIntSlowPaths.h"
#include "WasmMemoryHandler.h"
#include "WasmModule.h"
#include "WasmModuleManager.h"
#include "WasmQueryHandler.h"
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <wtf/Compiler.h>
#if OS(WINDOWS)
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <wtf/ASCIICType.h>
#include <wtf/Assertions.h>
#include <wtf/DataLog.h>
#include <wtf/HexNumber.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/Scope.h>
#include <wtf/Threading.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringBuilder.h>
namespace JSC {
namespace Wasm {
DebugServer& DebugServer::singleton()
{
static NeverDestroyed<DebugServer> instance;
return instance.get();
}
DebugServer::DebugServer()
: m_queryHandler(makeUnique<QueryHandler>(*this))
, m_memoryHandler(makeUnique<MemoryHandler>(*this))
{
}
bool DebugServer::start()
{
if (!createAndBindServerSocket())
return false;
RELEASE_ASSERT(isSocketValid(m_serverSocket));
m_moduleManager = makeUnique<ModuleManager>();
m_executionHandler = makeUnique<ExecutionHandler>(*this, *m_moduleManager);
setIsInService();
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Wasm Debug Server listening. Connect with: lldb -o 'gdb-remote localhost:", m_port, "'");
startAcceptThread();
return true;
}
#if ENABLE(REMOTE_INSPECTOR)
void DebugServer::startRWI(Function<bool(const String&)>&& rwiResponseHandler)
{
m_moduleManager = makeUnique<ModuleManager>();
m_executionHandler = makeUnique<ExecutionHandler>(*this, *m_moduleManager);
m_rwiResponseHandler = WTF::move(rwiResponseHandler);
setIsInService();
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Wasm Debug Server started in RWI mode (WorkQueue-based)");
}
#endif
union SocketAddress {
sockaddr_in in;
sockaddr generic;
SocketAddress()
: in {}
{
}
explicit SocketAddress(const sockaddr_in& addr)
: in(addr)
{
}
};
bool DebugServer::createAndBindServerSocket()
{
// 1. Create socket
m_serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (!isSocketValid(m_serverSocket)) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Failed to create socket");
return false;
}
// 2. Set socket options for better reusability
int opt = 1;
#if OS(WINDOWS)
const char* optPtr = reinterpret_cast<const char*>(&opt);
#else
const void* optPtr = &opt;
#endif
if (setsockopt(m_serverSocket, SOL_SOCKET, SO_REUSEADDR, optPtr, sizeof(opt)) < 0) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Warning: Failed to set SO_REUSEADDR");
// Continue anyway, this is not critical
}
// 3. Bind to address and port
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // Bind to localhost only
address.sin_port = htons(m_port);
SocketAddress bindAddress(address);
if (bind(m_serverSocket, &bindAddress.generic, sizeof(sockaddr_in)) < 0) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Failed to bind socket to port ", m_port);
closeSocket(m_serverSocket);
return false;
}
// 4. Start listening
if (listen(m_serverSocket, 1) < 0) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Failed to listen on socket");
closeSocket(m_serverSocket);
return false;
}
return true;
}
void DebugServer::startAcceptThread()
{
m_acceptThread = WTF::Thread::create("WasmDebugServer", [this]() {
m_executionHandler->setDebugServerThreadId(Thread::currentSingleton().uid());
while (isInService()) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Waiting for client connections...");
SocketAddress clientAddress;
socklen_t clientLen = sizeof(clientAddress.in);
SocketType clientSocket = accept(m_serverSocket, &clientAddress.generic, &clientLen);
if (isSocketValid(clientSocket)) {
m_clientSocket = clientSocket;
handleClient();
} else
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Accept failed, continuing...");
}
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Accept thread exiting");
});
}
void DebugServer::closeSocket(SocketType& socket)
{
ASSERT(&socket == &m_serverSocket || &socket == &m_clientSocket);
if (isSocketValid(socket)) {
#if OS(WINDOWS)
::closesocket(socket);
#else
::close(socket);
#endif
socket = invalidSocketValue;
}
}
void DebugServer::reset()
{
// Reset to the init state without stopping the debug server.
m_isDebuggerReady.store(false, std::memory_order_release);
m_hasContinued.store(false, std::memory_order_release);
m_noAckMode = false;
m_packetParser.reset();
// m_isDebuggerReady=false before reset() gates new traps; socket closed after so
// hasDebugger() stays true for wasmDebuggerOnResumeCallback() during resumeImpl().
m_executionHandler->reset();
closeSocket(m_clientSocket);
}
static void dumpReceivedBytes(std::span<const uint8_t> buffer)
{
dataLog("[Debugger] recv() returned ", buffer.size(), " bytes: ");
GDBPacketParser::dumpBuffer(buffer);
dataLogLn();
}
void DebugServer::handleClient()
{
RELEASE_ASSERT(isSocketValid(m_clientSocket));
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Client connected (TCP socket mode), starting handler - process continues running normally");
// Send initial acknowledgment - client expects this immediately.
sendAck();
m_packetParser.reset();
constexpr size_t RECV_BUFFER_SIZE = 4096;
std::array<char, RECV_BUFFER_SIZE> recvBuffer;
while (true) {
auto bytesRead = recv(m_clientSocket, recvBuffer.data(), RECV_BUFFER_SIZE, 0);
if (bytesRead <= 0) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Client disconnected (bytesRead=", bytesRead, ")");
break;
}
if (Options::verboseWasmDebugger())
dumpReceivedBytes({ byteCast<uint8_t>(recvBuffer.data()), static_cast<size_t>(bytesRead) });
for (std::ptrdiff_t i = 0; i < bytesRead; i++) {
auto result = m_packetParser.processByte(static_cast<uint8_t>(recvBuffer[i]));
switch (result) {
case GDBPacketParser::ParseResult::CompletePacket: {
StringView packet = m_packetParser.getCompletedPacket();
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Complete packet received: ", packet);
handlePacket(packet);
break;
}
case GDBPacketParser::ParseResult::Error:
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Parse error - disconnecting client");
goto clientDisconnect;
case GDBPacketParser::ParseResult::Incomplete:
break;
}
}
if (!m_packetParser.isIdle())
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] After recv: incomplete packet (", m_packetParser, ")");
}
clientDisconnect:
// FIXME: Currently client disconnect, kill, and quit commands just stop the client session only for easy debugging purposes.
// Eventually we need to introduce various stop states, e.g., termination.
reset();
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Client disconnected (TCP socket mode)");
}
void DebugServer::handlePacket(StringView packet)
{
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Processing packet: ", packet);
#if ENABLE(REMOTE_INSPECTOR)
if (isRWIMode())
m_executionHandler->setDebugServerThreadId(Thread::currentSingleton().uid());
#endif
sendAck();
if (packet.isEmpty()) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Empty packet received");
sendErrorReply(ProtocolError::InvalidPacket);
return;
}
if (packet.length() == 1 && packet[0] == 0x03) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Received Ctrl+C interrupt - triggering stack overflow");
m_executionHandler->interrupt();
return;
}
switch (packet[0]) {
case 'q':
case 'Q':
case 'j':
// Handle all query packets (q*, Q*) and JSON packets (j*)
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Routing query packet to QueryHandler");
m_queryHandler->handleGeneralQuery(packet);
break;
// See reference [3] in wasm/debugger/README.md
case 'm':
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Routing memory read packet to MemoryHandler");
m_memoryHandler->read(packet);
break;
case 'M':
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Routing memory write packet to MemoryHandler");
m_memoryHandler->write(packet);
break;
case 'c':
case 'C':
// 'C' is ContinueWithSignal — LLDB sends C<sig> instead of 'c' when resuming from a
// signal stop (e.g. T05/SIGTRAP). Signal re-delivery is a ptrace concept; we have no
// OS-level signal injection so the signal number is irrelevant — treat identically to 'c'.
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Routing continue packet to ExecutionHandler");
m_executionHandler->resume();
m_hasContinued.store(true, std::memory_order_release);
break;
case 's':
case 'S':
// 'S' is StepWithSignal — same reasoning as 'C': signal re-delivery does not apply
// to our WASM VM, so ignore the signal number and treat identically to plain 's'.
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Routing step packet to ExecutionHandler");
m_executionHandler->step();
break;
case 'Z':
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Routing set breakpoint packet to ExecutionHandler");
m_executionHandler->setBreakpoint(packet);
break;
case 'z':
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Routing remove breakpoint packet to ExecutionHandler");
m_executionHandler->removeBreakpoint(packet);
break;
case 'H':
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Routing thread management packet to handleThreadManagement");
handleThreadManagement(packet);
break;
case '?':
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Routing halt reason query to ExecutionHandler");
m_executionHandler->interrupt();
break;
case 'k':
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Kill request");
// FIXME: Currently just closes the debug session without actually terminating the WebAssembly process.
// Per GDB Remote Protocol, kill should terminate the target process if possible.
reset();
break;
case 'D':
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Detach request");
sendReplyOK();
reset();
break;
default:
sendReplyNotSupported(packet);
}
}
void DebugServer::sendReply(StringView reply) { m_executionHandler->sendReply(reply); }
void DebugServer::sendAck()
{
// Send '+' ACK character to acknowledge packet receipt
// Reference: [2] in wasm/debugger/README.md
if (m_noAckMode)
return;
sendReply("+"_s);
}
void DebugServer::sendReplyOK()
{
// Send 'OK' reply to indicate successful completion
// Reference: [3] and [4] in wasm/debugger/README.md
sendReply("OK"_s);
}
void DebugServer::sendReplyNotSupported(StringView packet)
{
// Send empty reply to indicate feature/command not supported
// Reference: [5] in wasm/debugger/README.md
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Unsupported packet: ", packet);
sendReply(""_s);
}
void DebugServer::sendErrorReply(ProtocolError error)
{
// Send 'E NN' error reply with specific error code
// Reference: [5] in wasm/debugger/README.md
sendReply(getErrorReply(error));
}
void DebugServer::handleThreadManagement(StringView packet)
{
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Processing thread management packet (Hg, Hc, Hp): ", packet);
if (packet.length() < 2) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Invalid H packet - too short");
sendErrorReply(ProtocolError::InvalidPacket);
return;
}
char operation = packet[1];
StringView threadSpec = packet.substring(2);
switch (operation) {
case 'c': {
// Hc<thread-id>: Set thread for step and continue operations
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Hc (set continue thread): ", threadSpec);
if (threadSpec == "-1" || threadSpec == "0") {
// -1 = all threads, 0 = any thread, 1 = thread 1
// All are valid for our single-threaded WebAssembly context
sendReplyOK();
} else {
execution().switchTarget(parseHex(threadSpec));
sendReplyOK();
}
break;
}
case 'g': {
// Hg<thread-id>: Set thread for other operations (register access, etc.)
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Hg (set general thread): ", threadSpec);
sendErrorReply(ProtocolError::InvalidAddress);
break;
}
default:
sendReplyNotSupported(packet);
break;
}
}
void DebugServer::trackInstance(JSWebAssemblyInstance* instance)
{
if (!m_moduleManager)
return;
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Tracking WebAssembly instance: ", RawPointer(instance));
// Notify the debugger here (trackInstance) rather than in trackModule for two reasons:
// 1. Module::create covers both the synchronous and streaming-async compilation paths.
// In the async path the JS thread is not at a JS safepoint when the module is created,
// so a stop-the-world request would only fire at the next safepoint — too late for the
// debugger to intercept the load. By the time trackInstance is called the JS thread is
// back at a safepoint and we can stop immediately.
// 2. A Module can be compiled speculatively without ever being instantiated (e.g. via
// WebAssembly.compile). Only when a JSWebAssemblyInstance is created do we know the
// module will actually be used, making this the right moment to notify LLDB.
m_moduleManager->registerInstance(instance);
if (isDebuggerReady() && m_moduleManager->needsNewModuleNotification(instance))
m_executionHandler->notifyDebuggerOfNewModule(instance->vm());
}
void DebugServer::trackModule(Module& module)
{
if (!m_moduleManager)
return;
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Tracking WebAssembly module: ", RawPointer(&module));
m_moduleManager->registerModule(module);
}
void DebugServer::untrackModule(Module& module)
{
if (!m_moduleManager)
return;
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Untracking WebAssembly module: ", RawPointer(&module));
m_moduleManager->unregisterModule(module);
}
bool DebugServer::hasDebugger() const
{
if (!isInService())
return false;
#if ENABLE(REMOTE_INSPECTOR)
if (isRWIMode())
return true;
#endif
return isSocketValid(m_clientSocket);
}
ModuleManager& DebugServer::moduleManager() const
{
RELEASE_ASSERT(m_moduleManager);
return *m_moduleManager;
}
}
} // namespace JSC::Wasm
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
#endif // ENABLE(WEBASSEMBLY_DEBUGGER)
You can’t perform that action at this time.
