Repository navigation
Expand file tree
/
Copy pathWasmDebugServerUtilities.cpp
More file actions
459 lines (403 loc) · 19.3 KB
/
Copy pathWasmDebugServerUtilities.cpp
File metadata and controls
459 lines (403 loc) · 19.3 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
/*
* 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 "WasmDebugServerUtilities.h"
#if ENABLE(WEBASSEMBLY_DEBUGGER)
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
#include "CallFrame.h"
#include "CodeBlock.h"
#include "InlineCallFrame.h"
#include "JSFunction.h"
#include "JSWebAssemblyInstance.h"
#include "NativeCallee.h"
#include "NativeExecutable.h"
#include "VM.h"
#include "VMEntryRecord.h"
#include "WasmCallee.h"
#include "WasmIPIntGenerator.h"
#include "WasmOps.h"
#include "WasmVirtualAddress.h"
#include <cstring>
#include <wtf/ASCIICType.h>
#include <wtf/DataLog.h>
#include <wtf/HexNumber.h>
#include <wtf/RawHex.h>
#include <wtf/StdLibExtras.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/Vector.h>
#include <wtf/text/StringToIntegerConversion.h>
namespace JSC {
namespace Wasm {
WTF_MAKE_TZONE_ALLOCATED_IMPL(Breakpoint);
WTF_MAKE_STRUCT_TZONE_ALLOCATED_IMPL(DebugState);
WTF_MAKE_STRUCT_TZONE_ALLOCATED_IMPL(StopData);
String stringToHex(StringView str)
{
StringBuilder result;
auto utf8 = str.utf8();
for (auto c : utf8.span())
result.append(hex(byteCast<uint8_t>(c), 2, Lowercase));
return result.toString();
}
void logWasmLocalValue(size_t index, const JSC::IPInt::IPIntLocal& local, const Wasm::Type& localType)
{
dataLog(" Local[", index, "] (", localType, "): ");
switch (localType.kind()) {
case TypeKind::I32:
dataLogLn("i32=", local.i32, " [index ", index, "]");
break;
case TypeKind::I64:
dataLogLn("i64=", local.i64, " [index ", index, "]");
break;
case TypeKind::F32:
dataLogLn("f32=", local.f32, " [index ", index, "]");
break;
case TypeKind::F64:
dataLogLn("f64=", local.f64, " [index ", index, "]");
break;
case TypeKind::V128:
dataLogLn("v128=0x", hex(local.v128.u64x2[1], 16, Lowercase), hex(local.v128.u64x2[0], 16, Lowercase), " [index ", index, "]");
break;
case TypeKind::Ref:
case TypeKind::RefNull:
dataLogLn("ref=", local.ref, " [index ", index, "]");
break;
default:
dataLogLn("raw=0x", hex(local.i64, 16, Lowercase), " [index ", index, "]");
break;
}
}
std::optional<uint64_t> parseHexStrict(StringView str)
{
// An RSP hex field is hex digits only; parseInteger() would also take whitespace and a
// leading '+', which is the ack character.
if (str.isEmpty() || !str.containsOnly<isASCIIHexDigit>())
return std::nullopt;
return parseInteger<uint64_t>(str, 16);
}
uint32_t parseDecimal(StringView str, uint32_t defaultValue)
{
if (str.isEmpty())
return defaultValue;
auto result = parseInteger<uint32_t>(str, 10);
return result.value_or(defaultValue);
}
// Splits a string using a sequence of delimiters with exact matching.
// Returns empty vector if any delimiter is missing.
//
// Examples:
// splitWithDelimiters("Z0,400000000000018b,1", ",,") -> ["Z0", "400000000000018b", "1"]
// splitWithDelimiters("qWasmLocal:0:5", "::") -> ["qWasmLocal", "0", "5"]
// splitWithDelimiters("invalid", ",,") -> [] (missing delimiters)
Vector<StringView> splitWithDelimiters(StringView packet, StringView delimiters)
{
Vector<StringView> result;
if (packet.isEmpty() || delimiters.isEmpty())
return result;
StringView current = packet;
// Split on each delimiter in sequence - must find ALL delimiters for exact matching
for (size_t i = 0; i < delimiters.length(); ++i) {
char delimiter = delimiters[i];
size_t pos = current.find(delimiter);
if (pos == notFound)
return Vector<StringView>();
result.append(current.substring(0, pos));
current = current.substring(pos + 1);
}
result.append(current);
return result;
}
// Raw call-site return PC stored at frame−8 by IPInt's saveIPIntRegisters().
static const uint8_t* savedWasmToWasmPC(CallFrame* frame)
{
return WTF::unalignedLoad<const uint8_t*>(reinterpret_cast<const uint8_t*>(frame) - sizeof(Register));
}
// IPInt PC saved at WasmToJSIPIntReturnPCSlot[cfr] by both the JIT and no-JIT WasmToJS stubs.
static const uint8_t* savedWasmToJSPC(CallFrame* wasmToJSFrame)
{
return WTF::unalignedLoad<const uint8_t*>(reinterpret_cast<const uint8_t*>(wasmToJSFrame) + Wasm::WasmToJSIPIntReturnPCSlot);
}
static String hostFunctionNameOf(CallFrame* frame)
{
auto* callee = frame->jsCallee();
if (callee && callee->inherits<JSFunction>()) {
auto* function = uncheckedDowncast<JSFunction>(callee);
if (function->isHostFunction())
return uncheckedDowncast<NativeExecutable>(function->executable())->name();
}
return "<no code block>"_str;
}
// Null for a JS frame including a host function, which is an ordinary cell callee -- or an IC.
static RefPtr<Wasm::Callee> wasmCalleeOf(CallFrame* frame)
{
if (!frame->callee().isNativeCallee())
return nullptr;
RefPtr callee = frame->callee().asNativeCallee();
if (callee->category() != NativeCallee::Category::Wasm)
return nullptr;
return uncheckedDowncast<const Wasm::Callee>(callee.get());
}
// Null if not IPInt: a tail call replaces the frame that made a call, so handle it, do not assert.
static RefPtr<IPIntCallee> ipintCalleeOf(CallFrame* frame)
{
RefPtr callee = wasmCalleeOf(frame);
if (!callee || callee->compilationMode() != Wasm::CompilationMode::IPIntMode)
return nullptr;
return uncheckedDowncast<const Wasm::IPIntCallee>(callee.get());
}
// Synthetic frame a cross-instance tail call splices in (.ipint_tail_call_common). Every step of the
// walk skips it, including above a WasmToJS stub: call_indirect/call_ref can target another instance.
static bool isRestoreFrame(CallFrame* frame)
{
RefPtr callee = wasmCalleeOf(frame);
return callee && callee->compilationMode() == Wasm::CompilationMode::RestoreFrameMode;
}
static CallFrame* skipRestoreFrames(CallFrame* frame)
{
while (frame && isRestoreFrame(frame))
frame = frame->callerFrame();
return frame;
}
static CallFrame* skipRestoreFrames(CallFrame* frame, EntryFrame*& entryFrame)
{
while (frame && isRestoreFrame(frame))
frame = frame->callerFrame(entryFrame);
return frame;
}
WasmReturnSite getWasmReturnPC(CallFrame* currentFrame)
{
// Safe to use the non-EntryFrame overload: IPInt WASM frames are always entered via a JSToWasm
// trampoline (a normal CallFrame), never directly from C++, so no EntryFrame boundary can appear
// immediately above an IPInt frame -- nor above a restore frame, which is also a normal CallFrame.
CallFrame* callerFrame = skipRestoreFrames(currentFrame->callerFrame());
if (!callerFrame || !ipintCalleeOf(callerFrame))
return { };
return { const_cast<uint8_t*>(savedWasmToWasmPC(currentFrame)), callerFrame->wasmInstance() };
}
// wasm -> wasm: MC spilled at -2 * SlotSize[cfr] by saveIPIntRegisters(); an IPInt caller's callee is always WASM.
static size_t inFlightCallFrameSize(CallFrame* calleeFrame)
{
RELEASE_ASSERT(calleeFrame->callee().isNativeCallee());
RefPtr nativeCallee = calleeFrame->callee().asNativeCallee();
RELEASE_ASSERT(nativeCallee->category() == NativeCallee::Category::Wasm);
RefPtr wasmCallee = uncheckedDowncast<const Wasm::Callee>(nativeCallee.get());
RELEASE_ASSERT(wasmCallee->compilationMode() == Wasm::CompilationMode::IPIntMode);
auto* savedMC = WTF::unalignedLoad<const IPInt::CallReturnMetadata*>(reinterpret_cast<const uint8_t*>(calleeFrame) - 2 * sizeof(Register));
RELEASE_ASSERT(savedMC);
return savedMC->stackFrameSize;
}
// wasm -> JS: the stub spills MC into a scratch slot instead.
static size_t importedCallFrameSize(CallFrame* stubFrame)
{
auto* savedMC = WTF::unalignedLoad<const IPInt::CallReturnMetadata*>(reinterpret_cast<const uint8_t*>(stubFrame) + Wasm::WasmToJSIPIntMCSlot);
RELEASE_ASSERT(savedMC);
return savedMC->stackFrameSize;
}
// Walk the full CallFrame chain from a WASM breakpoint, collecting virtual addresses for
// every WASM and JS frame. The result is consumed by qWasmCallStack to give LLDB a
// complete backtrace even when WASM and JS frames are interleaved.
//
// Supported call chain topologies (-> = calls, W = IPInt WASM, J = JS, JW = JSToWasm*, WJ = WasmToJS):
//
// J -> JW -> W (WASM called from JS)
// J -> JW -> W -> W (WASM->WASM, called from JS)
// J -> JW -> W -> WJ -> J -> JW -> W -> ... (WASM<->JS interleaved)
// J -> JW -> W -> WJ -> J -> J -> J -> JW -> W (multiple JS frames between WASM segments)
//
// Algorithm — three steps per iteration:
//
// Step A: emit `frame` if it is a JS frame (one per inline depth for DFG/FTL; one otherwise).
// WASM frames are naturally skipped since their callee().isNativeCallee() is true.
// Step B: advance to caller = frame->callerFrame(), stepping over any restore frame. Stop if null.
// Step C: dispatch on the caller's type — JS, IPIntMode (WASM->WASM), JSToWasm* (skip
// trampoline), WasmToJS (recover outer WASM call-site PC from WasmToJSIPIntReturnPCSlot).
// Both the JIT and no-JIT WasmToJS stubs save the IPInt PC into
// WasmToJSIPIntReturnPCSlot[cfr] on entry, before JS JIT can clobber the register.
Vector<FrameInfo> collectCallStack(VirtualAddress stopAddress, CallFrame* startFrame, VM& vm, unsigned maxFrames)
{
Vector<FrameInfo> frames;
// Frame 0 — the breakpoint frame. startFrame is always an IPInt WASM frame.
{
RELEASE_ASSERT(startFrame->callee().isNativeCallee());
RefPtr startNativeCallee = startFrame->callee().asNativeCallee();
RELEASE_ASSERT(startNativeCallee->category() == NativeCallee::Category::Wasm);
RefPtr startWasmCallee = uncheckedDowncast<const Wasm::Callee>(startNativeCallee.get());
RELEASE_ASSERT(startWasmCallee->compilationMode() == Wasm::CompilationMode::IPIntMode);
RefPtr startIPIntCallee = uncheckedDowncast<const Wasm::IPIntCallee>(startWasmCallee.get());
frames.append({ stopAddress, startFrame, WTF::move(startIPIntCallee), 0 });
}
if (Options::verboseWasmDebugger()) {
dataLogLn("[collectCallStack] frames:");
dataLog(" [0] ");
if (stopAddress.value() == VirtualAddress::JS_FRAME_BASE)
dataLog("[JS] ");
else if (stopAddress.value() == VirtualAddress::INVALID_BASE)
dataLog("[System] ");
else
dataLog("[WASM] ");
dataLogLn(stopAddress);
}
EntryFrame* entryFrame = vm.topEntryFrame;
CallFrame* frame = startFrame;
while (frames.size() < maxFrames) {
// Step A — emit `frame` if it is a JS frame.
// startFrame (WASM) is naturally skipped because its callee().isNativeCallee() is true.
// Every path in Step C changes `frame`, so Step A always processes a fresh unemitted frame.
if (!frame->callee().isNativeCallee()) {
#if ENABLE(DFG_JIT)
if (frame->codeBlock() && frame->codeBlock()->canGetCodeOrigin(frame->callSiteIndex())) {
// DFG/FTL: emit one JS_FRAME_BASE per inline depth (innermost to outermost).
frame->codeBlock()->codeOrigin(frame->callSiteIndex()).walkUpInlineStack([&](CodeOrigin origin) {
if (frames.size() < maxFrames) {
if (Options::verboseWasmDebugger()) {
if (auto* inlineCallFrame = origin.inlineCallFrame())
dataLogLn(" [", frames.size(), "] [JS][Inlined] ", inlineCallFrame->inferredNameWithHash());
else
dataLogLn(" [", frames.size(), "] [JS] ", frame->codeBlock()->inferredNameWithHash());
}
frames.append({ VirtualAddress(VirtualAddress::JS_FRAME_BASE), nullptr, { }, 0 });
}
});
} else {
#endif
if (Options::verboseWasmDebugger()) [[unlikely]] {
if (auto* codeBlock = frame->codeBlock())
dataLogLn(" [", frames.size(), "] [JS] ", codeBlock->inferredNameWithHash());
else
dataLogLn(" [", frames.size(), "] [JS][Host] ", hostFunctionNameOf(frame));
}
frames.append({ VirtualAddress(VirtualAddress::JS_FRAME_BASE), nullptr, { }, 0 });
#if ENABLE(DFG_JIT)
}
#endif
}
// Step B — advance to the caller. callerFrame() updates callerEntryFrame when it crosses a VM
// entry, so every arm below commits entryFrame only once `frame` is final.
EntryFrame* callerEntryFrame = entryFrame;
CallFrame* caller = skipRestoreFrames(frame->callerFrame(callerEntryFrame), callerEntryFrame);
if (!caller)
break;
// Step C — dispatch on the caller's type.
if (!caller->callee().isNativeCallee()) {
// JS frame above — advance; Step A will emit it next iteration.
entryFrame = callerEntryFrame;
frame = caller;
continue;
}
RefPtr wasmCallerCallee = wasmCalleeOf(caller);
if (!wasmCallerCallee)
break; // C++ entry or InlineCache — stop.
switch (wasmCallerCallee->compilationMode()) {
case Wasm::CompilationMode::IPIntMode: {
// WASM->WASM: emit exact bytecode return PC saved at frame−8 by IPInt.
RefPtr ipintCaller = uncheckedDowncast<const Wasm::IPIntCallee>(wasmCallerCallee.get());
VirtualAddress virtualReturnPC = VirtualAddress::toVirtual(caller->wasmInstance(), ipintCaller->functionIndex(), savedWasmToWasmPC(frame));
dataLogLnIf(Options::verboseWasmDebugger(), " [", frames.size(), "] [WASM][IPInt] ", virtualReturnPC);
frames.append({ virtualReturnPC, caller, ipintCaller, inFlightCallFrameSize(frame) });
entryFrame = callerEntryFrame;
frame = caller;
break;
}
case Wasm::CompilationMode::JSToWasmMode:
case Wasm::CompilationMode::JSToWasmICMode:
case Wasm::CompilationMode::WasmBuiltinMode:
// JSToWasm trampoline or WasmBuiltin — skip; advance to the frame beyond it.
// Step A will emit it in the next iteration if it is a JS frame.
dataLogLnIf(Options::verboseWasmDebugger(), " [WASM][", wasmCallerCallee->compilationMode(), "][SKIPPED]");
frame = skipRestoreFrames(caller->callerFrame(callerEntryFrame), callerEntryFrame);
if (!frame)
return frames;
entryFrame = callerEntryFrame;
break;
case Wasm::CompilationMode::WasmToJSMode: {
// WasmToJS trampoline — `frame` (the JS frame directly below it) was already
// emitted by Step A. Recover the outer WASM call-site PC from the dedicated slot
// saved by both the JIT and no-JIT WasmToJS stubs before the JS call: this value
// is the IPInt PC advanced past the 'call' opcode, stored at
// WasmToJSIPIntReturnPCSlot[cfr] of the WasmToJS frame.
CallFrame* outerFrame = skipRestoreFrames(caller->callerFrame(callerEntryFrame), callerEntryFrame);
if (!outerFrame)
return frames;
// A tail call into the import replaces the caller, so the stub's caller need not be a WASM
// frame at all. Only IPInt has a bytecode PC to attribute the call site to; skip the rest.
if (RefPtr outerIPIntCallee = ipintCalleeOf(outerFrame)) {
VirtualAddress callSiteAddr = VirtualAddress::toVirtual(outerFrame->wasmInstance(), outerIPIntCallee->functionIndex(), savedWasmToJSPC(caller));
dataLogLnIf(Options::verboseWasmDebugger(), " [", frames.size(), "] [WASM][WasmToJS]", callSiteAddr);
frames.append({ callSiteAddr, outerFrame, WTF::move(outerIPIntCallee), importedCallFrameSize(caller) });
} else if (RefPtr outerWasmCallee = wasmCalleeOf(outerFrame))
dataLogLnIf(Options::verboseWasmDebugger(), " [WASM][WasmToJS][outer ", outerWasmCallee->compilationMode(), "][SKIPPED]");
else
dataLogLnIf(Options::verboseWasmDebugger(), " [WASM][WasmToJS][outer JS][SKIPPED]");
entryFrame = callerEntryFrame;
frame = outerFrame;
break;
}
default:
// BBQ/OMG/OMGForOSREntry: disabled when the WASM debugger is active; stop.
RELEASE_ASSERT_NOT_REACHED();
break;
}
}
return frames;
}
StopData::StopData(IPIntCallee* callee, JSWebAssemblyInstance* instance, CallFrame* callFrame)
: address(VirtualAddress::toVirtual(instance, callee->functionIndex(), callee->bytecode()))
, callee(callee)
, instance(instance)
, callFrame(callFrame)
{
}
StopData::StopData(VirtualAddress address, OpType originalBytecode, uint8_t* pc, uint8_t* mc, IPInt::IPIntStackEntry* stack, IPIntCallee* callee, JSWebAssemblyInstance* instance, CallFrame* callFrame)
: address(address)
, originalBytecode(originalBytecode)
, pc(pc)
, mc(mc)
, stack(stack)
, callee(callee)
, instance(instance)
, callFrame(callFrame)
{
}
StopData::StopData(IPIntCallee* callee, JSWebAssemblyInstance* instance, CallFrame* callFrame, uint8_t* pc, uint8_t* mc, IPInt::IPIntStackEntry* stack, Wasm::ExceptionType type)
: StopData(VirtualAddress::toVirtual(instance, callee->functionIndex(), pc), OpType::Unreachable, pc, mc, stack, callee, instance, callFrame)
{
wasmTrapType = type;
}
StopData::~StopData() = default;
void StopData::dump(PrintStream& out) const
{
out.print("StopData(address:", address);
out.print(", originalBytecode:", RawHex(static_cast<unsigned>(originalBytecode)));
out.print(", pc:", RawPointer(pc));
out.print(", mc:", RawPointer(mc));
out.print(", stack:", RawPointer(stack));
out.print(", callee:", RawPointer(callee.get()));
out.print(", instance:", RawPointer(instance));
out.print(", callFrame:", RawPointer(callFrame), ")");
}
} // namespace Wasm
} // namespace JSC
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
#endif // ENABLE(WEBASSEMBLY_DEBUGGER)