Repository navigation
Expand file tree
/
Copy pathWasmMemoryHandler.cpp
More file actions
383 lines (329 loc) · 15.8 KB
/
Copy pathWasmMemoryHandler.cpp
File metadata and controls
383 lines (329 loc) · 15.8 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
/*
* 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 "WasmMemoryHandler.h"
#if ENABLE(WEBASSEMBLY_DEBUGGER)
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
#include "JSWebAssemblyInstance.h"
#include "Options.h"
#include "WasmDebugServer.h"
#include "WasmDebugServerUtilities.h"
#include "WasmExecutionHandler.h"
#include "WasmModuleManager.h"
#include "WasmVirtualAddress.h"
#include <cstdlib>
#include <cstring>
#include <wtf/ASCIICType.h>
#include <wtf/CheckedArithmetic.h>
#include <wtf/DataLog.h>
#include <wtf/HexNumber.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/ASCIILiteral.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/WTFString.h>
namespace JSC {
namespace Wasm {
WTF_MAKE_TZONE_ALLOCATED_IMPL(MemoryHandler);
void MemoryHandler::read(StringView packet)
{
// Format: m<addr>,<length>
// LLDB: Read memory at specified address and length
// Reference: [3] in wasm/debugger/README.md
// WebAssembly Context: Read WASM module bytecode or memory data
// Only allows access to WASM-specific virtual addresses for security
if (packet.isEmpty() || packet[0] != 'm') {
m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
return;
}
StringView params = packet.substring(1);
auto parts = splitWithDelimiters(params, ","_s);
if (parts.size() != 2) {
m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
return;
}
auto parsedAddress = parseHexStrict(parts[0]);
auto parsedLength = parseHexStrict(parts[1]);
if (!parsedAddress || !parsedLength) {
m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
return;
}
VirtualAddress address = VirtualAddress(*parsedAddress);
size_t length = static_cast<size_t>(*parsedLength);
StringBuilder data;
VirtualAddress::Type addressType = address.type();
bool success = false;
if (addressType == VirtualAddress::Type::Module)
success = readModuleData(address, length, data);
else if (addressType == VirtualAddress::Type::Memory)
success = readMemoryData(address, length, data);
else
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] Rejecting non-WASM address for security: ", address);
if (success)
m_debugServer.sendReply(data.toString());
else
m_debugServer.sendErrorReply(ProtocolError::InvalidAddress);
}
bool MemoryHandler::readModuleData(VirtualAddress address, size_t length, StringBuilder& data)
{
uint32_t instanceId = address.instanceId();
uint32_t offset = address.offset();
JSWebAssemblyInstance* jsInstance = m_debugServer.m_moduleManager->jsInstance(instanceId);
if (!jsInstance)
return false;
const auto& source = jsInstance->moduleInformation().debugInfo->source;
if (!offset && source.size() < length) {
// FIXME: This is a workaround for tiny modules - clamp initial read at offset 0.
// Cannot clamp at non-zero offsets as it corrupts DWARF debug info in LLDB.
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] - clamping read from ", length, " to ", source.size(), " bytes (module size: ", source.size(), ")");
length = source.size();
} else {
CheckedSize end = offset;
end += length;
if (end.hasOverflowed() || end > source.size()) {
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] - read beyond module boundary. Address: ", address, " offset: ", offset, " size: ", length, " module size: ", source.size());
return false;
}
}
for (size_t i = 0; i < length; ++i)
data.append(hex(source[offset + i], 2, Lowercase));
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] - read ", length, " bytes at offset: ", offset, " from instance ID: ", instanceId);
return true;
}
bool MemoryHandler::readMemoryData(VirtualAddress address, size_t length, StringBuilder& data)
{
uint32_t instanceId = address.instanceId();
uint32_t offset = address.offset();
JSWebAssemblyInstance* jsInstance = m_debugServer.m_moduleManager->jsInstance(instanceId);
if (!jsInstance) {
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] - instance not found for ID: ", instanceId);
return false;
}
// FIXME(wasm-multimemory): Should the debugger eventually support multiple linear memories?
void* memoryBase = jsInstance->memory(0)->basePointer();
size_t size = jsInstance->memory(0)->memory().size();
CheckedSize readEnd = offset;
readEnd += length;
if (!memoryBase || readEnd.hasOverflowed() || readEnd > size) {
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] - memory access out of bounds. Instance ID: ", instanceId, " offset: ", offset, " size: ", length, " memory size: ", size);
return false;
}
uint8_t* memPtr = static_cast<uint8_t*>(memoryBase) + offset;
for (size_t i = 0; i < length; i++)
data.append(hex(memPtr[i], 2, Lowercase));
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] - read ", length, " bytes at offset: ", offset, " from instance ID: ", instanceId);
return true;
}
void MemoryHandler::handleMemoryRegionInfo(StringView packet)
{
// Format: qMemoryRegionInfo:<addr>
// LLDB: Get information about the memory region containing the specified address
// Reference: [17] in wasm/debugger/README.md
// WebAssembly Context: Provide memory region info for WASM modules, memory, stack, and globals
// Return region info with start, size, permissions, and name
StringView addressStr = packet.substring(strlen("qMemoryRegionInfo:"));
auto parsedAddress = parseHexStrict(addressStr);
if (!parsedAddress) {
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] Malformed qMemoryRegionInfo packet");
m_debugServer.sendErrorReply(ProtocolError::InvalidAddress);
return;
}
VirtualAddress address = VirtualAddress(*parsedAddress);
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] qMemoryRegionInfo for address: ", address);
VirtualAddress::Type addressType = address.type();
uint32_t instanceId = address.instanceId();
uint32_t offset = address.offset();
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] qMemoryRegionInfo: address=", address, ", type=", (int)addressType, ", instance=", instanceId, ", offset=0x", hex(offset, Lowercase));
switch (addressType) {
case VirtualAddress::Type::Memory:
handleWasmMemoryRegionInfo(address, instanceId, offset);
break;
case VirtualAddress::Type::Module:
handleWasmModuleRegionInfo(address, instanceId, offset);
break;
default:
// Never error: one reply latches region-info off in LLDB for the whole session.
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] Unmapped address type for memory region: ", (int)addressType);
RELEASE_ASSERT(address.value() >= VirtualAddress::INVALID_BASE);
sendUnmappedRegionReply(address.value(), VirtualAddress::INVALID_END - address.value() + 1);
break;
}
}
void MemoryHandler::handleWasmMemoryRegionInfo(VirtualAddress address, uint32_t instanceId, uint32_t offset)
{
JSWebAssemblyInstance* instance = m_debugServer.m_moduleManager->jsInstance(instanceId);
if (instance) {
// FIXME(wasm-multimemory): Should the debugger eventually support multiple linear memories?
size_t memorySize = instance->memory(0)->memory().size();
if (offset < memorySize) {
// Address is within WASM memory - return the memory region
String name = makeString("wasm_memory_"_s, instanceId);
sendMemoryRegionReply(VirtualAddress::createMemory(instanceId).value(), memorySize, "rw"_s, name);
return;
}
}
uint32_t idUpperBoundary = m_debugServer.m_moduleManager->nextInstanceId();
uint32_t nextValidID = instanceId;
do {
if (++nextValidID >= idUpperBoundary) {
// No more instances - return unmapped region
uint64_t unmappedSize = VirtualAddress::MODULE_BASE - address.value();
sendUnmappedRegionReply(address, unmappedSize);
return;
}
} while (!m_debugServer.m_moduleManager->jsInstance(nextValidID));
// Address is beyond this module - return unmapped region to next module
VirtualAddress nextMemoryAddress = VirtualAddress::createMemory(nextValidID);
uint64_t unmappedSize = nextMemoryAddress.value() - address.value();
sendUnmappedRegionReply(address, unmappedSize);
}
void MemoryHandler::handleWasmModuleRegionInfo(VirtualAddress address, uint32_t instanceId, uint32_t offset)
{
JSWebAssemblyInstance* instance = m_debugServer.m_moduleManager->jsInstance(instanceId);
if (instance) {
const auto& source = instance->moduleInformation().debugInfo->source;
if (offset < source.size()) {
// Address is within module bounds - return info for the entire WASM module region
String name = makeString("wasm_module_"_s, instanceId);
sendMemoryRegionReply(VirtualAddress::createModule(instanceId).value(), source.size(), "rx"_s, name, "module"_s);
return;
}
}
uint32_t idUpperBoundary = m_debugServer.m_moduleManager->nextInstanceId();
uint32_t nextValidID = instanceId;
do {
if (++nextValidID >= idUpperBoundary) {
// No more instances - unmapped to the end. INVALID_END is the last byte, hence +1.
uint64_t unmappedSize = VirtualAddress::INVALID_END - address.value() + 1;
sendUnmappedRegionReply(address, unmappedSize);
return;
}
} while (!m_debugServer.m_moduleManager->jsInstance(nextValidID));
// Address is beyond this module - return unmapped region to next module
VirtualAddress nextModuleAddress = VirtualAddress::createModule(nextValidID);
uint64_t unmappedSize = nextModuleAddress.value() - address.value();
sendUnmappedRegionReply(address, unmappedSize);
}
void MemoryHandler::sendMemoryRegionReply(uint64_t start, uint64_t size, StringView permissions, StringView name)
{
String response = makeString(
"start:"_s, hex(start, Lowercase),
";size:"_s, hex(size, Lowercase),
";permissions:"_s, permissions,
";name:"_s, stringToHex(name),
";"_s);
m_debugServer.sendReply(response);
}
void MemoryHandler::sendMemoryRegionReply(uint64_t start, uint64_t size, StringView permissions, StringView name, StringView type)
{
String response = makeString(
"start:"_s, hex(start, Lowercase),
";size:"_s, hex(size, Lowercase),
";permissions:"_s, permissions,
";name:"_s, stringToHex(name),
";type:"_s, type,
";"_s);
m_debugServer.sendReply(response);
}
void MemoryHandler::sendUnmappedRegionReply(uint64_t start, uint64_t size)
{
String response = makeString(
"start:"_s, hex(start, Lowercase),
";size:"_s, hex(size, Lowercase),
";permissions:;name:;"_s);
m_debugServer.sendReply(response);
}
void MemoryHandler::write(StringView packet)
{
// Format: M<addr>,<length>:<hex-data>
// LLDB: Write memory at specified address and length
// Reference: [3] in wasm/debugger/README.md
// WebAssembly Context: Write to WASM linear memory only
// Module bytecode is read-only; only linear memory (Type::Memory) is writable
if (packet.isEmpty() || packet[0] != 'M') {
m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
return;
}
StringView params = packet.substring(1);
auto parts = splitWithDelimiters(params, ",:"_s);
if (parts.size() != 3) {
m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
return;
}
auto parsedAddress = parseHexStrict(parts[0]);
auto parsedLength = parseHexStrict(parts[1]);
if (!parsedAddress || !parsedLength) {
m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
return;
}
VirtualAddress address = VirtualAddress(*parsedAddress);
size_t length = static_cast<size_t>(*parsedLength);
StringView hexData = parts[2];
// Validate hex data length (2 hex chars per byte)
if (hexData.length() != length * 2) {
m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
return;
}
// toASCIIHexValue() asserts on non-hex input, so check before decoding or writing anything.
if (!hexData.containsOnly<isASCIIHexDigit>()) {
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] Write rejected: non-hex payload");
m_debugServer.sendErrorReply(ProtocolError::InvalidPacket);
return;
}
VirtualAddress::Type addressType = address.type();
// Only allow writes to WASM linear memory for security; module bytecode is read-only
if (addressType != VirtualAddress::Type::Memory) {
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] Write rejected: only WASM linear memory is writable, address: ", address);
m_debugServer.sendErrorReply(ProtocolError::InvalidAddress);
return;
}
uint32_t instanceId = address.instanceId();
uint32_t offset = address.offset();
JSWebAssemblyInstance* jsInstance = m_debugServer.m_moduleManager->jsInstance(instanceId);
if (!jsInstance) {
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] Write failed: instance not found for ID: ", instanceId);
m_debugServer.sendErrorReply(ProtocolError::InvalidAddress);
return;
}
// FIXME(wasm-multimemory): Should the debugger eventually support multiple linear memories?
void* memoryBase = jsInstance->memory(0)->basePointer();
size_t memorySize = jsInstance->memory(0)->memory().size();
CheckedSize writeEnd = offset;
writeEnd += length;
if (!memoryBase || writeEnd.hasOverflowed() || writeEnd > memorySize) {
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] Write out of bounds. Instance ID: ", instanceId, " offset: ", offset, " size: ", length, " memory size: ", memorySize);
m_debugServer.sendErrorReply(ProtocolError::MemoryError);
return;
}
// Decode hex data and write to WASM linear memory
uint8_t* memPtr = static_cast<uint8_t*>(memoryBase) + offset;
for (size_t i = 0; i < length; i++)
memPtr[i] = toASCIIHexValue(hexData[i * 2], hexData[i * 2 + 1]);
dataLogLnIf(Options::verboseWasmDebugger(), "[MemoryHandler] - wrote ", length, " bytes at offset: ", offset, " to instance ID: ", instanceId);
m_debugServer.sendReply("OK"_s);
}
} // namespace Wasm
} // namespace JSC
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
#endif // ENABLE(WEBASSEMBLY_DEBUGGER)