File: WasmQueryHandler.cpp

package info (click to toggle)
webkit2gtk 2.51.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 455,340 kB
  • sloc: cpp: 3,865,253; javascript: 197,710; ansic: 165,177; python: 49,241; asm: 21,868; ruby: 18,095; perl: 16,926; xml: 4,623; sh: 2,409; yacc: 2,356; java: 2,019; lex: 1,330; pascal: 372; makefile: 210
file content (423 lines) | stat: -rw-r--r-- 16,778 bytes parent folder | download
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
/*
 * 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 "WasmQueryHandler.h"

#if ENABLE(WEBASSEMBLY)

WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN

#include "CallFrame.h"
#include "JSWebAssemblyInstance.h"
#include "JSWebAssemblyModule.h"
#include "NativeCallee.h"
#include "Options.h"
#include "StackVisitor.h"
#include "VM.h"
#include "WasmCallee.h"
#include "WasmDebugServer.h"
#include "WasmDebugServerUtilities.h"
#include "WasmExecutionHandler.h"
#include "WasmIPIntGenerator.h"
#include "WasmIPIntSlowPaths.h"
#include "WasmMemoryHandler.h"
#include "WasmModuleInformation.h"
#include "WasmModuleManager.h"
#include "WasmVirtualAddress.h"
#include <cstring>
#include <wtf/DataLog.h>
#include <wtf/HexNumber.h>
#include <wtf/StdLibExtras.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/WTFString.h>

namespace JSC {
namespace Wasm {

WTF_MAKE_TZONE_ALLOCATED_IMPL(QueryHandler);

void QueryHandler::handleGeneralQuery(StringView packet)
{
    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Handling query: ", packet);

    if (packet.startsWith("QStartNoAckMode"_s))
        handleStartNoAckMode();
    else if (packet.startsWith("qSupported"_s))
        handleSupported();
    else if (packet.startsWith("QListThreadsInStopReply"_s))
        handleListThreadsInStopReply();
    else if (packet.startsWith("QEnableErrorStrings"_s))
        handleEnableErrorStrings();
    else if (packet.startsWith("qThreadStopInfo"_s))
        handleThreadStopInfo(packet);
    else if (packet.startsWith("qHostInfo"_s))
        handleHostInfo();
    else if (packet.startsWith("qProcessInfo"_s))
        handleProcessInfo();
    else if (packet.startsWith("qRegisterInfo"_s))
        handleRegisterInfo(packet);
    else if (packet.startsWith("qXfer:libraries:read::"_s))
        handleLibrariesRead(packet);
    else if (packet.startsWith("qWasmCallStack:"_s))
        handleWasmCallStack(packet);
    else if (packet.startsWith("qWasmLocal:"_s))
        handleWasmLocal(packet);
    else if (packet.startsWith("qMemoryRegionInfo:"_s))
        m_debugServer.m_memoryHandler->handleMemoryRegionInfo(packet);
    else
        m_debugServer.sendReplyNotSupported(packet);
}

void QueryHandler::handleProcessInfo()
{
    // Format: qProcessInfo
    // LLDB: Query process information for debugging context
    // Reference: [8] in wasm/debugger/README.md

    // WebAssembly Context: Provide WASM process info with simulated PID and WASI target
    // This helps LLDB understand the WebAssembly execution environment
    String tripleHex = stringToHex("wasm32-webkit-wasi"_s);
    String processInfo = makeString(
        "pid:1;"_s, // Process ID (simulated for WASM debugging)
        "parent-pid:1;"_s, // Parent process ID (simulated)
        "vendor:webkit;"_s, // WebKit/JavaScriptCore (identifies JSC's WASM debugger)
        "ostype:wasi;"_s, // WASI (WebAssembly System Interface)
        "arch:wasm32;"_s, // WebAssembly 32-bit architecture
        "triple:"_s, tripleHex, ";"_s, // Target triple: wasm32-webkit-wasi (hex encoded)
        "endian:little;"_s, // Little-endian byte order
        "ptrsize:4;"_s // 32-bit pointers
    );
    m_debugServer.sendReply(processInfo);
}

void QueryHandler::handleHostInfo()
{
    // Format: qHostInfo
    // LLDB: Query host system information for debugging setup
    // Reference: [9] in wasm/debugger/README.md

    // WebAssembly Context: Provide host info for WASM execution environment
    // This tells LLDB about the WebAssembly runtime characteristics
    String tripleHex = stringToHex("wasm32-webkit-wasi"_s);
    String hostInfo = makeString(
        "vendor:webkit;"_s, // WebKit/JavaScriptCore (identifies JSC's WASM debugger)
        "ostype:wasi;"_s, // WASI (WebAssembly System Interface)
        "arch:wasm32;"_s, // WebAssembly 32-bit architecture
        "triple:"_s, tripleHex, ";"_s, // Target triple: wasm32-webkit-wasi-wasm (hex encoded)
        "endian:little;"_s, // Little-endian byte order
        "ptrsize:4;"_s // 32-bit pointers
    );
    m_debugServer.sendReply(hostInfo);
}

void QueryHandler::handleRegisterInfo(StringView packet)
{
    // Format: qRegisterInfo<hex-reg-id>
    // LLDB: Query register information for specific register ID
    // Reference: [10] in wasm/debugger/README.md

    // WebAssembly Context: WASM only exposes PC register for debugging
    // Other registers are internal to the WASM runtime and not accessible
    StringView regNumStr = packet.substring(strlen("qRegisterInfo"));
    int regNum = static_cast<int>(parseHex(regNumStr));

    if (!regNum) {
        // PC register definition for WebAssembly debugging
        String registerInfo = makeString(
            "name:pc;"_s, // Program Counter register name
            "alt-name:pc;"_s, // Alternative name (same as primary)
            "bitsize:64;"_s, // 64-bit register size
            "offset:0;"_s, // Located at byte offset 0 in register context
            "encoding:uint;"_s, // Interpret contents as unsigned integer
            "format:hex;"_s, // Display in hexadecimal format by default
            "set:General Purpose Registers;"_s, // Belongs to GP register group
            "gcc:16;"_s, // GCC compiler register number
            "dwarf:16;"_s, // DWARF debug info register number
            "generic:pc;"_s // Generic register type (program counter)
        );
        m_debugServer.sendReply(registerInfo);
    } else {
        // Only PC register is supported - return error for all others
        dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Returning error for register ", regNum, " (only PC supported)");
        m_debugServer.sendErrorReply(ProtocolError::InvalidRegister);
    }
}

bool QueryHandler::parseLibrariesReadPacket(StringView packet, size_t& offset, size_t& maxSize)
{
    StringView offsetPart = packet.substring(strlen("qXfer:libraries:read::"));

    // Use splitWithDelimiters for consistent parsing
    auto parts = splitWithDelimiters(offsetPart, ","_s);
    if (parts.size() != 2)
        return false;

    offset = parseHex(parts[0]);
    maxSize = parseHex(parts[1]);
    return true;
}

bool QueryHandler::handleChunkedLibrariesResponse(size_t offset, size_t maxSize, String& response)
{
    String xmlData = m_debugServer.m_instanceManager->generateLibrariesXML();

    // Handle chunked response according to GDB Remote Protocol
    // 'm' prefix = more data follows
    // 'l' prefix = last chunk
    if (offset >= xmlData.length()) {
        response = "l"_s;
        return true;
    }

    size_t availableData = xmlData.length() - offset;
    size_t chunkSize = std::min(maxSize, availableData);

    String chunk = xmlData.substring(offset, chunkSize);
    bool isLastChunk = (offset + chunkSize >= xmlData.length());

    StringBuilder result;
    result.append(isLastChunk ? 'l' : 'm');
    result.append(chunk);
    response = result.toString();
    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Chunked library response: ", (isLastChunk ? 'l' : 'm'), " offset=", offset, ", chunk_size=", chunkSize, ", total=", xmlData.length());
    return true;
}

String QueryHandler::buildWasmCallStackResponse()
{
    auto stopReason = m_debugServer.m_executionHandler->stopReason();
    RELEASE_ASSERT(stopReason.isValid() && stopReason.callFrame);
    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] buildWasmCallStackResponse: starting manual stack walk from CallFrame ", RawPointer(stopReason.callFrame));

    Vector<VirtualAddress> frameAddresses;
    frameAddresses.append(stopReason.address);
    CallFrame* currentFrame = stopReason.callFrame;
    uint8_t* returnPC = nullptr;
    VirtualAddress virtualReturnPC;
    unsigned frameIndex = 0;

    while (getWasmReturnPC(currentFrame, returnPC, virtualReturnPC) && frameIndex < 100) {
        frameAddresses.append(virtualReturnPC);
        currentFrame = currentFrame->callerFrame();
        frameIndex++;
    }

    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] CallStack: finished walking call stack, processed ", frameIndex, " frames");

    StringBuilder result;
    for (VirtualAddress address : frameAddresses)
        result.append(toNativeEndianHex(address));
    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] buildWasmCallStackResponse: collected ", frameAddresses.size(), " frames, response length: ", result.length());
    return result.toString();
}

void QueryHandler::handleStartNoAckMode()
{
    // Format: QStartNoAckMode
    // LLDB: Ask to disable ACK mode - acknowledge this
    // Reference: [6] in wasm/debugger/README.md

    // OK - WASM debugger supports no-ACK mode for better performance
    m_debugServer.sendReplyOK();
    m_debugServer.m_noAckMode = true;
}

void QueryHandler::handleSupported()
{
    // Format: qSupported[:feature[;feature]...]
    // LLDB: Query supported features and packet size
    // Reference: [7] in wasm/debugger/README.md

    // WebAssembly Context: We support qXfer:libraries:read+ to let LLDB discover WASM modules
    // This allows LLDB to see loaded WebAssembly modules as "libraries" for debugging
    String supportedFeatures = makeString(
        "qXfer:libraries:read+;"_s, // Support library list transfer for WASM modules
        "PacketSize=1000;"_s // Maximum packet size for data transfer
    );
    m_debugServer.sendReply(supportedFeatures);
}

void QueryHandler::handleListThreadsInStopReply()
{
    // Format: QListThreadsInStopReply
    // LLDB: Ask to include thread list in stop replies for better debugging
    // Reference: [11] in wasm/debugger/README.md

    // WebAssembly Context: WASM typically runs in single thread, so this is simple to support
    // We can easily include our single main thread in stop replies
    m_debugServer.sendReplyOK();
}

void QueryHandler::handleEnableErrorStrings()
{
    // Format: QEnableErrorStrings
    // LLDB: Enable error strings in replies for better debugging experience
    // Reference: [12] in wasm/debugger/README.md

    // WebAssembly Context: Error strings help debug WASM execution issues
    // Useful for reporting WASM trap conditions and runtime errors
    m_debugServer.sendReplyOK();
}

void QueryHandler::handleThreadStopInfo(StringView packet)
{
    // Format: qThreadStopInfo<thread-id>
    // LLDB: Get stop info for specific thread (needed for frame variable)
    // Reference: [13] in wasm/debugger/README.md

    // WebAssembly Context: Provide stop reason for WASM thread
    // Handled by execution handler for proper thread state management
    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Handling qThreadStopInfo for frame variable support");
    m_debugServer.m_executionHandler->handleThreadStopInfo(packet);
}

void QueryHandler::handleLibrariesRead(StringView packet)
{
    // Format: qXfer:libraries:read::<offset>,<length>
    // LLDB: Transfer library list XML for module discovery
    // Reference: [14] in wasm/debugger/README.md

    // WebAssembly Context: Provide WASM modules as "libraries" for LLDB
    // This allows LLDB to discover and debug loaded WebAssembly modules
    size_t offset, maxSize;
    if (!parseLibrariesReadPacket(packet, offset, maxSize)) {
        m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
        return;
    }

    String response;
    if (handleChunkedLibrariesResponse(offset, maxSize, response)) {
        dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Sending library list chunk: offset=", offset, ", maxSize=", maxSize);
        m_debugServer.sendReply(response);
    } else {
        dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Failed to generate library list chunk");
        m_debugServer.sendErrorReply(ProtocolError::MemoryError);
    }
}

void QueryHandler::handleWasmCallStack(StringView packet)
{
    // Format: qWasmCallStack:<thread-id-in-hex>
    // LLDB: Get WebAssembly call stack information for disassembly display
    // Reference: [15] in wasm/debugger/README.md

    // WebAssembly Context: This packet is essential for LLDB to show proper WASM disassembly
    // with source lines, instruction details, and frame information
    auto strings = splitWithDelimiters(packet, ":"_s);
    if (strings.size() != 2) {
        m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
        return;
    }

    StringView threadIdStr = strings[1];
    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] qWasmCallStack thread ID: ", threadIdStr);

    uint64_t threadId = parseHex(threadIdStr);
    uint64_t mutatorThreadId = m_debugServer.mutatorThreadId();
    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Parsed qWasmCallStack thread ID: ", threadId, ", mutator ID: ", RawPointer((void*)mutatorThreadId));

    RELEASE_ASSERT(threadId == mutatorThreadId);
    String response = buildWasmCallStackResponse();
    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] qWasmCallStack response: ", response);
    m_debugServer.sendReply(response);
}

static constexpr uint32_t typeKindToWidth(TypeKind kind)
{
    switch (kind) {
#define CREATE_CASE(name, id, b3type, inc, wasmName, width, ...) \
    case TypeKind::name:                                         \
        return width;
        FOR_EACH_WASM_TYPE(CREATE_CASE)
#undef CREATE_CASE
    }
    return 0;
}

void QueryHandler::handleWasmLocal(StringView packet)
{
    // Format: qWasmLocal:<frame-index>;<variable-index>
    // LLDB: Get value of WebAssembly local variable (function argument or local)
    // Reference: [16] in wasm/debugger/README.md

    // WebAssembly Context: Access function locals and parameters for debugging
    // Return local value or address based on variable type
    auto parts = splitWithDelimiters(packet, ":;"_s);
    if (parts.size() != 3) {
        m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
        return;
    }

    uint32_t frameIndex = parseDecimal(parts[1]);
    uint32_t localIndex = parseDecimal(parts[2]);

    dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] qWasmLocal frame=", frameIndex, ", variable=", localIndex);

    // For now, only support frame 0 (current frame)
    if (frameIndex) {
        m_debugServer.sendErrorReply(ProtocolError::UnknownCommand);
        return;
    }

    auto stopReason = m_debugServer.m_executionHandler->stopReason();
    auto functionIndex = stopReason.callee->functionIndex();
    const auto& moduleInfo = stopReason.instance->module().moduleInformation();
    const Vector<Type>& localTypes = moduleInfo.debugInfo->ensureFunctionDebugInfo(functionIndex).locals;

    IPInt::IPIntLocal& local = stopReason.locals[localIndex];
    Type localType = localTypes[localIndex];
    logWasmLocalValue(localIndex, local, localType);

    String response;
    uint32_t width = typeKindToWidth(localType.kind);
    switch (width) {
    case 32: {
        response = toNativeEndianHex(local.i32);
        break;
    }
    case 64: {
        response = toNativeEndianHex(local.i64);
        break;
    }
    case 128: {
        RELEASE_ASSERT(localType.kind == TypeKind::V128, "Expected V128 for 128-bit type");
        response = toNativeEndianHex(local.v128);
        break;
    }
    default:
        RELEASE_ASSERT(false, "Unsupported TypeKind bit size: ", width, " for TypeKind: ", localType.kind);
        break;
    }
    m_debugServer.sendReply(response);
}

} // namespace Wasm
} // namespace JSC

WTF_ALLOW_UNSAFE_BUFFER_USAGE_END

#endif // ENABLE(WEBASSEMBLY)