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
|
/*
* 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)
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
#include "JSWebAssemblyInstance.h"
#include "JSWebAssemblyModule.h"
#include "Options.h"
#include "SubspaceInlines.h"
#include "VM.h"
#include "WasmBreakpointManager.h"
#include "WasmCallee.h"
#include "WasmDebugServer.h"
#include "WasmDebugServerUtilities.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/TZoneMallocInlines.h>
#include <wtf/text/StringParsingBuffer.h>
#include <wtf/text/WTFString.h>
namespace JSC {
namespace Wasm {
WTF_MAKE_TZONE_ALLOCATED_IMPL(ExecutionHandler);
// FIXME: This current implementation only stops a single VM. In real-world browser debugging,
// when ANY VM hits a WASM breakpoint, we should stop ALL execution across ALL VMs in the process.
//
// COMPREHENSIVE STOP-THE-WORLD APPROACH:
// - Single VM with WASM: Current implementation works (but should be consistent)
// - TODO: Multiple VMs, only one running WASM: Stop ALL VMs (WASM + non-WASM mutators)
// - TODO: Multiple VMs, multiple running WASM: Stop ALL VMs (all WASM + all non-WASM mutators)
class StopWorld {
public:
explicit StopWorld(VM& vm)
: m_vm(vm)
{
}
~StopWorld()
{
if (m_vm.isWasmStopWorldActive())
deactivateStopWorld();
}
void activateStopWorld()
{
m_vm.traps().requestStop();
m_vm.setIsWasmStopWorldActive(true);
}
void deactivateStopWorld()
{
m_vm.traps().cancelStop();
m_vm.setIsWasmStopWorldActive(false);
}
private:
VM& m_vm;
};
struct StopReasonInfo {
String reasonString;
StringView reasonSuffix;
};
static inline StopReasonInfo stopReasonCodeToInfo(ExecutionHandler::StopReason::Code code)
{
switch (code) {
case ExecutionHandler::StopReason::Code::Signal:
return { "T02"_s, "signal"_s }; // SIGINT - Interrupt signal
case ExecutionHandler::StopReason::Code::Trace:
return { "T05"_s, "trace"_s }; // SIGTRAP - Trace/single step
case ExecutionHandler::StopReason::Code::Breakpoint:
return { "T05"_s, "breakpoint"_s }; // SIGTRAP - Breakpoint hit
default:
RELEASE_ASSERT_NOT_REACHED();
return { String(), "trace"_s };
}
}
ExecutionHandler::ExecutionHandler(DebugServer& debugServer, ModuleManager& moduleManager, BreakpointManager& breakpointManager)
: m_debugServer(debugServer)
, m_moduleManager(moduleManager)
, m_breakpointManager(breakpointManager)
{
}
void ExecutionHandler::stopImpl(StopReason&& stopReason)
{
RELEASE_ASSERT(Thread::currentSingleton().uid() == m_debugServer.mutatorThreadId());
Locker locker { m_lock };
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop][Breakpoint] Start");
m_stopReason = stopReason;
m_mutatorState = MutatorState::Stopped;
m_breakpointManager.clearAllOneTimeBreakpoints();
if (m_debuggerState == DebuggerState::ContinueRequested) {
sendStopReply(locker);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop][Breakpoint] Currently in continue. Sent a stop reply and waiting...");
} else {
RELEASE_ASSERT(m_debuggerState == DebuggerState::StopRequested);
m_debuggerContinue.notifyOne();
}
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop][Breakpoint] Updated stop reason and waiting...");
m_mutatorContinue.wait(locker);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop][Breakpoint] Unblocked and running...");
m_stopReason.reset();
m_mutatorState = MutatorState::Running;
if (m_debuggerState == DebuggerState::ContinueRequested)
m_debuggerContinue.notifyOne();
}
bool ExecutionHandler::stopCode(CallFrame* callFrame, JSWebAssemblyInstance* instance, IPIntCallee* callee, uint8_t* pc, uint8_t* mc, IPInt::IPIntLocal* locals, IPInt::IPIntStackEntry* stack)
{
RELEASE_ASSERT(Thread::currentSingleton().uid() == m_debugServer.mutatorThreadId());
VirtualAddress address = VirtualAddress::toVirtual(instance, callee->functionIndex(), pc);
if (auto* breakpoint = m_breakpointManager.findBreakpoint(address)) {
StopReason stopReason(breakpoint->type, address, breakpoint->originalBytecode, pc, mc, locals, stack, callee, instance, callFrame);
dataLogLnIf(Options::verboseWasmDebugger(), "[Code][Stop] Going to stop at ", *breakpoint, " with ", stopReason);
stopImpl(WTFMove(stopReason));
return true;
}
return false;
}
void ExecutionHandler::resume()
{
Locker locker { m_lock };
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Continue] Start");
RELEASE_ASSERT(Thread::currentSingleton().uid() == m_debugServer.debugServerThreadId());
RELEASE_ASSERT(m_debuggerState == DebuggerState::Replied && m_mutatorState == MutatorState::Stopped);
m_mutatorContinue.notifyOne();
// This is to simplify implementation. If we don't wait here, we may have a race condition that
// after above notification, interrupt() may acquire the locker first.
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Continue] Notified code to continue and waiting...");
m_debuggerState = DebuggerState::ContinueRequested;
m_debuggerContinue.wait(m_lock);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Continue] Confirmed that code is running...");
}
void ExecutionHandler::interrupt()
{
RELEASE_ASSERT(Thread::currentSingleton().uid() == m_debugServer.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.
StopWorld stopWorld(*m_debugServer.vm());
{
RELEASE_ASSERT(m_mutatorState == MutatorState::Running);
m_debuggerState = DebuggerState::StopRequested;
stopWorld.activateStopWorld();
}
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Interrupt] Notified code to stop and waiting...");
m_debuggerContinue.wait(m_lock);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Interrupt] Confirmed that code is stoped");
{
stopWorld.deactivateStopWorld();
sendStopReply(locker);
}
}
void ExecutionHandler::step()
{
RELEASE_ASSERT(Thread::currentSingleton().uid() == m_debugServer.debugServerThreadId());
Locker locker { m_lock };
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Step] Start with ", m_stopReason);
uint8_t* currentPC = m_stopReason.pc;
auto setStepBreakpoint = [&](const uint8_t* nextPC) WTF_REQUIRES_LOCK(m_lock) {
VirtualAddress nextAddress = VirtualAddress(m_stopReason.address.value() + (nextPC - currentPC));
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Step][SetOneTimeBreakpoint] current PC=", RawPointer(currentPC), "(", m_stopReason.address, "), next PC=", RawPointer(nextPC), "(", nextAddress, ")");
if (m_breakpointManager.findBreakpoint(nextAddress))
return;
m_breakpointManager.setBreakpoint(nextAddress, Breakpoint(const_cast<uint8_t*>(nextPC), Breakpoint::Type::Step));
};
auto setStepBreakpointAtCaller = [&]() WTF_REQUIRES_LOCK(m_lock) {
uint8_t* returnPC = nullptr;
VirtualAddress virtualReturnPC;
if (getWasmReturnPC(m_stopReason.callFrame, returnPC, virtualReturnPC))
m_breakpointManager.setBreakpoint(virtualReturnPC, Breakpoint(const_cast<uint8_t*>(returnPC), Breakpoint::Type::Step));
};
auto setStepBreakpointsFromDebugInfo = [&]() WTF_REQUIRES_LOCK(m_lock) {
const auto& moduleInfo = m_stopReason.instance->moduleInformation();
auto functionIndex = m_stopReason.callee->functionIndex();
uint32_t offset = m_stopReason.address.offset();
const auto* nextInstructions = moduleInfo.debugInfo->ensureFunctionDebugInfo(functionIndex).findNextInstructions(offset);
RELEASE_ASSERT(nextInstructions, "Didn't find nextInstructions");
uint8_t* const basePC = m_stopReason.pc - offset;
for (uint32_t nextOffset : *nextInstructions)
setStepBreakpoint(basePC + nextOffset);
};
switch (m_stopReason.originalBytecode) {
case Nop:
case Drop:
case Select:
setStepBreakpoint(currentPC + 1);
break;
case End:
if (currentPC != m_stopReason.callee->bytecodeEnd()) {
setStepBreakpoint(currentPC + 1);
break;
}
[[fallthrough]];
case Return:
setStepBreakpointAtCaller();
break;
case Throw:
case Rethrow:
case ThrowRef:
case Delegate:
m_debugServer.vm()->setStepIntoWasmThrow();
break;
case TailCall:
case TailCallIndirect:
case TailCallRef:
// The tail calls have two debugging behaviors:
// 2. Step-into: If the callee is a Wasm call.
// 1. Back to caller: If the callee is a non-Wasm call.
m_debugServer.vm()->setStepIntoWasmCall();
setStepBreakpointAtCaller();
break;
case Call:
case CallIndirect:
case CallRef:
// The calls have two debugging behaviors:
// 2. Step-into: If the callee is a Wasm call.
// 1. Step-over: If the callee is a non-Wasm call.
m_debugServer.vm()->setStepIntoWasmCall();
[[fallthrough]];
default: {
setStepBreakpointsFromDebugInfo();
break;
}
}
RELEASE_ASSERT(m_debuggerState == DebuggerState::Replied && m_mutatorState == MutatorState::Stopped);
m_mutatorContinue.notifyOne();
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Step] Notified code to continue and waiting...");
m_debuggerState = DebuggerState::ContinueRequested;
m_debuggerContinue.wait(m_lock);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][Step] Confirmed that code is running...");
}
void ExecutionHandler::setBreakpointAtEntry(JSWebAssemblyInstance* instance, IPIntCallee* callee, Breakpoint::Type type)
{
setBreakpointAtPC(instance, callee->functionIndex(), type, callee->bytecode());
}
void ExecutionHandler::setBreakpointAtPC(JSWebAssemblyInstance* instance, FunctionCodeIndex functionIndex, Breakpoint::Type type, const uint8_t* pc)
{
RELEASE_ASSERT(pc);
VirtualAddress address = VirtualAddress::toVirtual(instance, functionIndex, pc);
if (m_breakpointManager.findBreakpoint(address))
return;
m_breakpointManager.setBreakpoint(address, Breakpoint(const_cast<uint8_t*>(pc), type));
}
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;
}
uint32_t type = parseDecimal(parts[0]);
VirtualAddress address = VirtualAddress(parseHex(parts[1]));
uint32_t length = parseDecimal(parts[2]);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][SetBreakpoint] Setting breakpoint: type=", static_cast<int>(type), ", address=", address, ", length=", length);
// Only support software breakpoints for now
// 0 = Software breakpoint
if (type) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][SetBreakpoint] Unsupported breakpoint type: ", static_cast<int>(type));
sendErrorReply(ProtocolError::UnknownCommand);
return;
}
VirtualAddress::Type addressType = address.type();
if (addressType != VirtualAddress::Type::Module) {
dataLogLnIf(Options::verboseWasmDebugger(), "[ExecutionHandler] Breakpoint must be in module code region, got type: ", (int)addressType);
sendErrorReply(ProtocolError::InvalidAddress);
return;
}
if (m_breakpointManager.findBreakpoint(address)) {
dataLogLnIf(Options::verboseWasmDebugger(), "[ExecutionHandler] Breakpoint already exists at address: ", address);
sendErrorReply(ProtocolError::InvalidAddress);
return;
}
uint8_t* pc = address.toPhysicalPC(m_moduleManager);
if (!pc) {
dataLogLnIf(Options::verboseWasmDebugger(), "[ExecutionHandler] Failed to convert virtual address to physical: ", address);
sendErrorReply(ProtocolError::InvalidAddress);
return;
}
m_breakpointManager.setBreakpoint(address, Breakpoint(pc, Breakpoint::Type::Regular));
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger][SetBreakpoint] Successfully set breakpoint at ", address, " (physical: ", RawPointer(pc), ", original: 0x", hex(*pc, 2, Lowercase), ")");
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;
}
uint32_t type = parseDecimal(parts[0]);
VirtualAddress address = VirtualAddress(parseHex(parts[1]));
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Removing breakpoint: type=", static_cast<int>(type), ", address=", address);
// Only support software breakpoints for now
// 0 = Software breakpoint
if (type) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Unsupported breakpoint type for removal: ", static_cast<int>(type));
sendErrorReply(ProtocolError::UnknownCommand);
return;
}
// Delegate to breakpoint manager
if (m_breakpointManager.removeBreakpoint(address)) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Breakpoint removed successfully from ", address);
sendReplyOK();
} else {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Breakpoint not found at address: ", address);
sendErrorReply(ProtocolError::InvalidAddress);
}
}
void ExecutionHandler::handleThreadStopInfo(StringView packet)
{
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Handling qThreadStopInfo: ", packet);
Locker locker { m_lock };
sendStopReply(locker);
}
void ExecutionHandler::sendStopReply(AbstractLocker& locker) WTF_REQUIRES_LOCK(m_lock)
{
RELEASE_ASSERT(m_mutatorState == MutatorState::Stopped && m_stopReason.isValid());
uint64_t pc = m_stopReason.address;
auto stopInfo = stopReasonCodeToInfo(m_stopReason.code);
String reasonString = stopInfo.reasonString;
StringView reasonSuffix = stopInfo.reasonSuffix;
String pcBytes = toNativeEndianHex(pc);
uint64_t mutatorThreadId = m_debugServer.mutatorThreadId();
String stopReplyStr = makeString(
reasonString,
"thread:"_s, hex(mutatorThreadId, Lowercase),
";name:JSC-mutator;threads:"_s, hex(mutatorThreadId, Lowercase),
";thread-pcs:"_s, hex(pc, 16, Lowercase),
";00:"_s,
pcBytes,
";reason:"_s,
reasonSuffix,
";"_s);
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Sending stop reply: ", stopReplyStr);
sendReplyImpl(locker, stopReplyStr);
}
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 = ExecutionHandler::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
CString packetData = packet.utf8();
int sent = static_cast<int>(send(m_debugServer.m_clientSocket, packetData.data(), packetData.length(), 0));
if (sent < 0)
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Failed to send packet: ", packetData.data(), " sent: ", sent);
else {
m_debuggerState = ExecutionHandler::DebuggerState::Replied;
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Sent reply: ", packetData.data());
}
}
void ExecutionHandler::reset()
{
Locker locker { m_lock };
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Handling client disconnection in ExecutionHandler");
m_debuggerState = DebuggerState::Replied;
if (m_mutatorState == MutatorState::Stopped) {
dataLogLnIf(Options::verboseWasmDebugger(), "[Debugger] Resuming stopped WebAssembly execution due to client disconnection");
m_mutatorState = MutatorState::Running;
m_stopReason.reset();
m_mutatorContinue.notifyAll();
}
}
void ExecutionHandler::sendReplyOK() { m_debugServer.sendReplyOK(); }
void ExecutionHandler::sendErrorReply(ProtocolError error) { m_debugServer.sendErrorReply(error); }
ExecutionHandler::StopReason ExecutionHandler::stopReason() const WTF_IGNORES_THREAD_SAFETY_ANALYSIS
{
RELEASE_ASSERT(m_stopReason.isValid());
return m_stopReason;
}
} // namespace Wasm
} // namespace JSC
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
#endif // ENABLE(WEBASSEMBLY)
|