From f9703217fc32cf614df34f76d4175ae5157c45a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 11:13:33 +0200 Subject: [PATCH 01/12] ImDebugger: right-click menu on memory blocks, with copy and breakpoint The block list in the memory windows was navigation-only - click to jump there, and that was it. Right-clicking a block now offers the two things you actually want once you've found one: - Copy info to clipboard. More than the status bar shows (range, size, the PC that allocated it, ticks, flags, allocated state), since the reason to copy it is to keep it - for a bug report or to compare two runs. - Add memory breakpoint, covering the whole block rather than a single address. That's the point of doing it from this list: you want to catch anything touching the allocation, not one byte of it. Read and write, pause and log. It then opens and focuses the Breakpoints window, via a new SHOW_IN_BREAKPOINTS command so window activation stays with the other ImCmds rather than poking at the config from here. Only on the blocks themselves, not on the synthetic "(start)" and "(end)" entries, which have no block info behind them to copy or watch. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- UI/ImDebugger/ImCommand.h | 1 + UI/ImDebugger/ImDebugger.cpp | 6 +++++ UI/ImDebugger/ImMemView.cpp | 43 ++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/UI/ImDebugger/ImCommand.h b/UI/ImDebugger/ImCommand.h index 978a4eb881..d488de9760 100644 --- a/UI/ImDebugger/ImCommand.h +++ b/UI/ImDebugger/ImCommand.h @@ -10,6 +10,7 @@ enum class ImCmd { SHOW_IN_MEMORY_VIEWER, // param is address, param2 is viewer index SHOW_IN_PIXEL_VIEWER, // param is address, param2 is stride, |0x80000000 if depth, param3 is w/h SHOW_IN_MEMORY_DUMPER, // param is address, param2 is size, param3 is mode + SHOW_IN_BREAKPOINTS, // no params, just opens and focuses the breakpoint list }; struct ImCommand { diff --git a/UI/ImDebugger/ImDebugger.cpp b/UI/ImDebugger/ImDebugger.cpp index 33304a6f69..df86bb6b5c 100644 --- a/UI/ImDebugger/ImDebugger.cpp +++ b/UI/ImDebugger/ImDebugger.cpp @@ -2934,6 +2934,12 @@ void ImDebugger::Frame(MIPSDebugInterface *mipsDebug, GPUCommon *gpuDebug, Draw: ImGui::SetWindowFocus(ImMemWindow::Title(index)); break; } + case ImCmd::SHOW_IN_BREAKPOINTS: + { + cfg_.breakpointsOpen = true; + ImGui::SetWindowFocus("Breakpoints"); + break; + } case ImCmd::SHOW_IN_MEMORY_DUMPER: { cfg_.memDumpOpen = true; diff --git a/UI/ImDebugger/ImMemView.cpp b/UI/ImDebugger/ImMemView.cpp index ce182b664d..85da5f27ab 100644 --- a/UI/ImDebugger/ImMemView.cpp +++ b/UI/ImDebugger/ImMemView.cpp @@ -16,6 +16,8 @@ #include "Core/Reporting.h" #include "Core/RetroAchievements.h" #include "Common/System/Display.h" +#include "Common/System/System.h" +#include "Core/Debugger/Breakpoints.h" #include "Core/System.h" #include "UI/ImDebugger/ImDebugger.h" @@ -587,6 +589,33 @@ void ImMemView::onMouseMove(float x, float y, int button) { } } +// Everything the block list knows about a block, in a form worth pasting into a bug report. +// Deliberately more than the status bar shows - the whole reason to copy it is to keep it. +static std::string DescribeMemBlockInfo(const MemBlockInfo &info) { + std::string flags; + auto addFlag = [&flags, &info](MemBlockFlags flag, const char *name) { + if ((uint32_t)(info.flags & flag) == 0) + return; + if (!flags.empty()) + flags += "|"; + flags += name; + }; + addFlag(MemBlockFlags::ALLOC, "ALLOC"); + addFlag(MemBlockFlags::FREE, "FREE"); + addFlag(MemBlockFlags::SUB_ALLOC, "SUB_ALLOC"); + addFlag(MemBlockFlags::SUB_FREE, "SUB_FREE"); + addFlag(MemBlockFlags::WRITE, "WRITE"); + addFlag(MemBlockFlags::READ, "READ"); + addFlag(MemBlockFlags::TEXTURE, "TEXTURE"); + if (flags.empty()) + flags = "none"; + + return StringFromFormat( + "%s\n%08x-%08x (%d bytes)\nPC: %08x\nTicks: %lld\nFlags: %s\nAllocated: %s\n", + info.tag.c_str(), info.start, info.start + info.size, (int)info.size, info.pc, + (long long)info.ticks, flags.c_str(), info.allocated ? "yes" : "no"); +} + void ImMemView::updateStatusBarText() { std::vector memRangeInfo = FindMemInfoByFlag(highlightFlags_, curAddress_, 1); char text[512]; @@ -1141,6 +1170,20 @@ void ImMemWindow::Draw(MIPSDebugInterface *mipsDebug, ImConfig &cfg, ImControl & cfg.selectedMemoryBlock = iter.start; GotoAddr(iter.start); } + if (ImGui::BeginPopupContextItem("blockinfo")) { + ImGui::TextUnformatted(iter.tag.c_str()); + ImGui::Separator(); + if (ImGui::MenuItem("Copy info to clipboard")) { + System_CopyStringToClipboard(DescribeMemBlockInfo(iter)); + } + if (ImGui::MenuItem("Add memory breakpoint")) { + // Covers the whole block rather than a single address - the point of doing + // this from the block list is to catch anything touching the allocation. + g_breakpoints.AddMemCheck(iter.start, iter.start + iter.size, MEMCHECK_READWRITE, BREAK_ACTION_PAUSE | BREAK_ACTION_LOG); + control.command = { ImCmd::SHOW_IN_BREAKPOINTS }; + } + ImGui::EndPopup(); + } ImGui::PopID(); } const u32 end = start + len; From a0fbf324696ddda41a954c1fd9672751fd235644 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 11:13:33 +0200 Subject: [PATCH 02/12] ImDebugger: add a filter box above the symbol list A game with symbols loaded puts a few thousand functions in that list, and the only way to reach one was to scroll. Typing part of a name now narrows it, case-insensitively. The filter produces a list of indices into the symbol cache rather than a filtered copy of it, so selectedSymbol_ keeps meaning the same thing whether or not a filter is active - the Edit Symbol box above the list needs it to index the cache. Rebuilt when the filter text changes or the symbol map reloads, not per frame, and the list clipper works off the match list so a filter that matches everything costs no more to draw than before. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- UI/ImDebugger/ImDisasmView.cpp | 23 +++++++++++++++++++++-- UI/ImDebugger/ImDisasmView.h | 6 ++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/UI/ImDebugger/ImDisasmView.cpp b/UI/ImDebugger/ImDisasmView.cpp index 7b325298c5..fbecad6498 100644 --- a/UI/ImDebugger/ImDisasmView.cpp +++ b/UI/ImDebugger/ImDisasmView.cpp @@ -1296,6 +1296,7 @@ void ImDisasmWindow::Draw(MIPSDebugInterface *mipsDebug, ImConfig &cfg, ImContro if (symCache_.empty() || symsDirty_) { symCache_ = g_symbolMap->GetAllActiveSymbols(SymbolType::ST_FUNCTION); symsDirty_ = false; + symMatchesDirty_ = true; } if (selectedSymbol_ >= 0 && selectedSymbol_ < symCache_.size()) { @@ -1310,11 +1311,29 @@ void ImDisasmWindow::Draw(MIPSDebugInterface *mipsDebug, ImConfig &cfg, ImContro } } + ImGui::SetNextItemWidth(-1.0f); + if (ImGui::InputTextWithHint("##symfilter", "Filter symbols", symFilter_, sizeof(symFilter_))) { + symMatchesDirty_ = true; + } + + if (symMatchesDirty_) { + symMatchesDirty_ = false; + symMatches_.clear(); + // An empty filter still builds the index list, so the draw loop below has only one + // path to get wrong. These lists run to a few thousand entries, and this only reruns + // when the filter or the symbol map changes, not per frame. + for (int i = 0; i < (int)symCache_.size(); i++) { + if (symFilter_[0] == '\0' || containsNoCase(symCache_[i].name, symFilter_)) + symMatches_.push_back(i); + } + } + if (ImGui::BeginListBox("##symbols", ImGui::GetContentRegionAvail())) { ImGuiListClipper clipper; - clipper.Begin((int)symCache_.size(), -1); + clipper.Begin((int)symMatches_.size(), -1); while (clipper.Step()) { - for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { + for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; row++) { + const int i = symMatches_[row]; if (ImGui::Selectable(symCache_[i].name.c_str(), selectedSymbol_ == i)) { disasmView_.gotoAddr(symCache_[i].address); disasmView_.scrollAddressIntoView(); diff --git a/UI/ImDebugger/ImDisasmView.h b/UI/ImDebugger/ImDisasmView.h index 8e331f3e31..1412158717 100644 --- a/UI/ImDebugger/ImDisasmView.h +++ b/UI/ImDebugger/ImDisasmView.h @@ -221,6 +221,12 @@ private: int selectedSymbol_ = -1; char selectedSymbolName_[128]; + // Filter over symCache_. Held as indices into it rather than a filtered copy, so + // selectedSymbol_ keeps meaning the same thing whether or not a filter is active. + char symFilter_[64]{}; + std::vector symMatches_; + bool symMatchesDirty_ = true; + ImDisasmView disasmView_; char searchTerm_[64]{}; }; From 44b832f7557b32bd5addf37c6317a998fa7ecfae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 12:03:07 +0200 Subject: [PATCH 03/12] Debugger: add game.speed.get/set for fast-forward and a speed percentage Both mechanisms already existed and just weren't reachable from the WebSocket API: PSP_CoreParameter().fastForward for unlimited, and an FPSLimit mode plus a target frame rate for everything else. FrameTimingLimit() in sceDisplay.cpp is where they all resolve to a single number. The one thing worth being careful about is which knob to drive. Reusing CUSTOM1/CUSTOM2 - the user's own alternative speeds - would have meant writing g_Config.iFpsLimit1, which is persisted per game, so a debugger session would permanently overwrite whatever speed the user had configured. Same class of mistake as a debug setting leaking into the saved config. So this gets its own FPSLimit::DEBUGGER mode and a debuggerFpsLimit field on CoreParameter, which isn't persisted and is value-initialized on every boot. Two things fall out for free: the analog-speed handler already backs off for any mode it doesn't own (EmuScreen.cpp), and a debugger can't leave a game slowed down after a restart. Percentages are relative to 60 FPS, the same convention GameSettingsScreen uses when presenting the alternative speeds, so "200%" means one thing across the app. Unlimited is fastForward rather than percent 0, so there's a single way to express it. The response reports limitFps straight from FrameTimingLimit(), exposed for the purpose. That's the number the frame timing actually consumes, so a client never has to reconstruct the interaction between fast-forward, this override and the user's own hotkeys - which is exactly the sort of thing that goes stale. Requests fail rather than being quietly ignored when something else owns the speed: achievements hardcore mode, or netplay without the "allow speed control while connected" option. Being ignored with a successful response is the worst outcome for an automation client. Verified against a running headless instance: percent 200 with fast-forward off resolves to limitFps 120, fast-forward takes it to 0 while remembering the 200 underneath, an explicit null clears it, and out-of-range or empty requests are rejected. The throttle *behaviour* is not verified end to end - a debug, software-rendered headless build runs this game at about 1% of real time, so it never reaches any of these targets and the limit can't be observed. That path is shared with the existing CUSTOM1/CUSTOM2 speeds and unchanged. sceNet.h is forward-declared rather than included: it reaches windows.h through proAdhoc.h, which redefines the OPTIONAL macro that collides with DebuggerParamType::OPTIONAL - the hazard this file's header comment already warns about. pspautotests 314/314, UnitTest 55/55. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- Core/CoreParameter.h | 8 ++ Core/Debugger/WebSocket/GameSubscriber.cpp | 125 +++++++++++++++++++++ Core/Debugger/WebSocket/GameSubscriber.h | 2 + Core/HLE/sceDisplay.cpp | 6 + Core/HLE/sceDisplay.h | 4 + docs/WebSocketDebugger.md | 40 ++++++- 6 files changed, 184 insertions(+), 1 deletion(-) diff --git a/Core/CoreParameter.h b/Core/CoreParameter.h index 2e8e0c090b..f09f9d0c55 100644 --- a/Core/CoreParameter.h +++ b/Core/CoreParameter.h @@ -35,6 +35,10 @@ enum class FPSLimit { CUSTOM1 = 1, CUSTOM2 = 2, ANALOG = 3, + // Set over the WebSocket debugger (game.speed.set). Deliberately its own mode instead of + // reusing CUSTOM1/2: those read their rate from g_Config, which is persisted per game, so a + // debugger session would permanently overwrite the user's configured alternative speed. + DEBUGGER = 4, }; class FileLoader; @@ -77,6 +81,10 @@ struct CoreParameter { bool fastForward = false; FPSLimit fpsLimit = FPSLimit::NORMAL; int analogFpsLimit = 0; + // Target FPS for FPSLimit::DEBUGGER. Lives here rather than in g_Config on purpose - see the + // enum. Resets with the rest of this struct on every boot, so a debugger can't leave a game + // permanently slowed down. + int debuggerFpsLimit = 0; bool updateRecent = true; diff --git a/Core/Debugger/WebSocket/GameSubscriber.cpp b/Core/Debugger/WebSocket/GameSubscriber.cpp index cf958709aa..a9c1c8508d 100644 --- a/Core/Debugger/WebSocket/GameSubscriber.cpp +++ b/Core/Debugger/WebSocket/GameSubscriber.cpp @@ -36,8 +36,15 @@ #include "Core/Debugger/WebSocket/GameSubscriber.h" #include "Core/Debugger/WebSocket/WebSocketUtils.h" #include "Core/ELF/ParamSFO.h" +#include "Core/HLE/sceDisplay.h" +#include "Core/RetroAchievements.h" #include "Core/System.h" +// Declared rather than included from Core/HLE/sceNet.h, which reaches winsock and so windows.h +// through proAdhoc.h - and that redefines the OPTIONAL macro that collides with +// DebuggerParamType::OPTIONAL, exactly the problem the note above is avoiding. +bool NetworkAllowSpeedControl(); + static uint32_t GetOwnProcessID() { #if PPSSPP_PLATFORM(UWP) return (uint32_t)GetCurrentProcessId(); @@ -51,6 +58,8 @@ static uint32_t GetOwnProcessID() { DebuggerSubscriber *WebSocketGameInit(DebuggerEventHandlerMap &map) { map["game.reset"] = &WebSocketGameReset; map["game.status"] = &WebSocketGameStatus; + map["game.speed.get"] = &WebSocketGameSpeedGet; + map["game.speed.set"] = &WebSocketGameSpeedSet; map["version"] = &WebSocketVersion; return nullptr; @@ -116,6 +125,122 @@ void WebSocketGameStatus(DebuggerRequest &req) { }); } +// Percentages are relative to 60 FPS, matching how the in-app settings present the alternative +// speeds (see GameSettingsScreen.cpp) - so a client and the UI agree on what "200%" means. +static int PercentToFps(int percent) { + return (percent * 60) / 100; +} + +static int FpsToPercent(int fps) { + return (fps * 100) / 60; +} + +// Fails the request if something else owns the speed right now, rather than accepting it and +// having FrameTimingLimit() quietly ignore it - silently doing nothing is the worst outcome for +// an automation client. +static bool CheckSpeedControlAllowed(DebuggerRequest &req) { + if (Achievements::HardcoreModeActive()) { + req.Fail("Speed control is not allowed in RetroAchievements hardcore mode"); + return false; + } + if (!NetworkAllowSpeedControl()) { + req.Fail("Speed control is not allowed while connected to a network game"); + return false; + } + return true; +} + +static void WriteSpeedState(JsonWriter &json) { + json.writeBool("fastForward", PSP_CoreParameter().fastForward); + if (PSP_CoreParameter().fpsLimit == FPSLimit::DEBUGGER) + json.writeInt("percent", FpsToPercent(PSP_CoreParameter().debuggerFpsLimit)); + else + json.writeNull("percent"); + json.writeInt("limitFps", __DisplayGetFrameTimingLimit()); +} + +// Request the current emulation speed (game.speed.get) +// +// No parameters. +// +// Response (same event name): +// - fastForward: boolean, whether unlimited fast-forward is on. +// - percent: null, or the debugger's speed override as a percentage of 60 FPS. +// - limitFps: the frame rate throttling is actually aiming for, after fastForward, percent, the +// user's own alternative-speed hotkeys and any restrictions have all been applied. 0 means +// unlimited. This is the ground truth - prefer it over inferring from the other two. +void WebSocketGameSpeedGet(DebuggerRequest &req) { + // Route the reads to the CPU thread - these are what the frame timing consumes there. + Core_RunOnCPUThread([&] { + JsonWriter &json = req.Respond(); + WriteSpeedState(json); + }); +} + +// Change the emulation speed (game.speed.set) +// +// Parameters (at least one required): +// - fastForward: optional boolean, run unlimited. Wins over 'percent' while on, same as the +// in-app fast-forward key. +// - percent: optional integer percentage of 60 FPS (100 = normal, 200 = double speed, 50 = half), +// or null to drop the override and go back to the game's normal rate. Must be at least 1 - +// use fastForward for unlimited rather than 0, so there's one way to say it. +// +// Response (same event name): the same fields as game.speed.get, after applying the change. +// +// Fails if RetroAchievements hardcore mode is active, or if connected to a network game without +// "allow speed control while connected" - in either case the setting would be ignored. +// +// Note this is a separate channel from the user's own alternative speeds (the CUSTOM1/CUSTOM2 +// hotkeys and their settings): it deliberately doesn't touch g_Config, which is persisted per +// game, so a debugger session can't permanently change what the user configured. +void WebSocketGameSpeedSet(DebuggerRequest &req) { + const bool hasFastForward = req.HasParam("fastForward"); + const bool hasPercent = req.HasParam("percent"); + if (!hasFastForward && !hasPercent) + return req.Fail("Need at least one of 'fastForward' or 'percent'"); + + bool fastForward = false; + if (hasFastForward && !req.ParamBool("fastForward", &fastForward)) + return; + + // An explicit null clears the override; the parameter being absent leaves it alone. + const bool clearPercent = hasPercent && !req.HasParam("percent", true); + uint32_t percent = 0; + if (hasPercent && !clearPercent) { + if (!req.ParamU32("percent", &percent)) + return; + if (percent < 1 || percent > 10000) + return req.Fail("Parameter 'percent' must be between 1 and 10000"); + if (PercentToFps((int)percent) < 1) + return req.Fail("Parameter 'percent' is too small to produce a frame rate"); + } + + if (!CheckSpeedControlAllowed(req)) + return; + + // Route the writes to the CPU thread instead of poking at them directly from this WebSocket + // handler thread - see Core_RunOnCPUThread() in Core.h. + Core_RunOnCPUThread([&] { + if (hasFastForward) + PSP_CoreParameter().fastForward = fastForward; + + if (clearPercent) { + // Only stand down from a limit we set ourselves - the user may have an alternative + // speed of their own active, and that isn't ours to cancel. + if (PSP_CoreParameter().fpsLimit == FPSLimit::DEBUGGER) + PSP_CoreParameter().fpsLimit = FPSLimit::NORMAL; + PSP_CoreParameter().debuggerFpsLimit = 0; + } else if (hasPercent) { + PSP_CoreParameter().debuggerFpsLimit = PercentToFps((int)percent); + PSP_CoreParameter().fpsLimit = FPSLimit::DEBUGGER; + } + + JsonWriter &json = req.Respond(); + WriteSpeedState(json); + }); +} + // Notify debugger version info (version) // // Parameters: diff --git a/Core/Debugger/WebSocket/GameSubscriber.h b/Core/Debugger/WebSocket/GameSubscriber.h index af43c692d0..68943c1af7 100644 --- a/Core/Debugger/WebSocket/GameSubscriber.h +++ b/Core/Debugger/WebSocket/GameSubscriber.h @@ -23,4 +23,6 @@ DebuggerSubscriber *WebSocketGameInit(DebuggerEventHandlerMap &map); void WebSocketGameReset(DebuggerRequest &req); void WebSocketGameStatus(DebuggerRequest &req); +void WebSocketGameSpeedGet(DebuggerRequest &req); +void WebSocketGameSpeedSet(DebuggerRequest &req); void WebSocketVersion(DebuggerRequest &req); diff --git a/Core/HLE/sceDisplay.cpp b/Core/HLE/sceDisplay.cpp index decd6a36aa..54b1400033 100644 --- a/Core/HLE/sceDisplay.cpp +++ b/Core/HLE/sceDisplay.cpp @@ -384,9 +384,15 @@ static int FrameTimingLimit() { return fixRate(g_Config.iFpsLimit2); if (PSP_CoreParameter().fpsLimit == FPSLimit::ANALOG) return fixRate(PSP_CoreParameter().analogFpsLimit); + if (PSP_CoreParameter().fpsLimit == FPSLimit::DEBUGGER) + return fixRate(PSP_CoreParameter().debuggerFpsLimit); return framerate; } +int __DisplayGetFrameTimingLimit() { + return FrameTimingLimit(); +} + static bool FrameTimingThrottled() { return FrameTimingLimit() != 0; } diff --git a/Core/HLE/sceDisplay.h b/Core/HLE/sceDisplay.h index eef5d2c9da..edb3bc6b23 100644 --- a/Core/HLE/sceDisplay.h +++ b/Core/HLE/sceDisplay.h @@ -34,6 +34,10 @@ void __DisplaySetFramebuf(u32 topaddr, int linesize, int pixelformat, int sync); // Call this when resuming to avoid a small speedup burst void __DisplaySetWasPaused(); +// The frame rate throttling is actually aiming for right now, after fast-forward, the alternative +// speeds, and the netplay/achievement restrictions have all had their say. 0 means unlimited. +int __DisplayGetFrameTimingLimit(); + void Register_sceDisplay_driver(); void __DisplayWaitForVblanks(const char* reason, int vblanks, bool callbacks = false); diff --git a/docs/WebSocketDebugger.md b/docs/WebSocketDebugger.md index f3e789ee47..f259aab430 100644 --- a/docs/WebSocketDebugger.md +++ b/docs/WebSocketDebugger.md @@ -132,6 +132,44 @@ way for periodic GPU stats. `client.config.set` in the same file carries per-connection settings that aren't about broadcasts - currently just `acknowledgeDeferred`, described under "Message protocol" above. +### Emulation speed + +`game.speed.set` drives two independent things: + +```json +-> { "event": "game.speed.set", "fastForward": true } // unlimited +-> { "event": "game.speed.set", "percent": 200 } // double speed +-> { "event": "game.speed.set", "percent": 25 } // quarter speed +-> { "event": "game.speed.set", "percent": null } // drop the override +<- { "event": "game.speed.set", "fastForward": false, "percent": 200, "limitFps": 120 } +``` + +Percentages are relative to 60 FPS, matching how the in-app settings present the +alternative speeds - so `200` means the same thing in both places. `percent` +must be at least 1; use `fastForward` for unlimited rather than `0`, so there's +only one way to say it. `fastForward` wins while it is on, and `percent` is +remembered underneath it. + +`limitFps` in the response is the frame rate throttling is actually aiming for +once everything - fast-forward, this override, the user's own alternative-speed +hotkeys - has been taken into account, with `0` meaning unlimited. It comes +straight from the function the frame timing itself consumes, so prefer reading +it over inferring the result from the other two fields. + +This is a **separate channel** from the user's own alternative speeds. It +deliberately never touches `g_Config`, whose speed settings are persisted per +game, so a debugger session can't permanently change what the user configured. +Clearing the override also only stands down from a limit set through this event, +never from one the user set themselves. It resets on every game boot. + +The request **fails** rather than being silently ignored when something else +owns the speed: RetroAchievements hardcore mode, or being connected to a network +game without "allow speed control while connected". + +Headless sets fast-forward at startup and never turns it off on its own, so +`game.speed.set` works there too - turning fast-forward off makes headless +throttle to real time, which is occasionally useful for a wall-clock repro. + ### Breakpoint hits `cpu.breakpoint.hit` fires every time a breakpoint's condition passes and it has @@ -206,7 +244,7 @@ file - this is just an index. | Category | Events | File | |---|---|---| -| Game/version | `game.reset`, `game.status`, `version` | `GameSubscriber.cpp` | +| Game/version | `game.reset`, `game.status`, `game.speed.get/set` (emulation speed - unlimited fast-forward, or a percentage of 60 FPS; see below), `version` | `GameSubscriber.cpp` | | CPU core | `cpu.stepping`, `cpu.resume`, `cpu.status` (reports `ticks` plus `us`, emulated microseconds, and `clockHz` - use `us` to line up with wall-clock timings, since games change the clock frequency and the ticks-per-second ratio isn't fixed), `cpu.getAllRegs`, `cpu.getReg`, `cpu.setReg`, `cpu.evaluate` | `CPUCoreSubscriber.cpp` | | Stepping | `cpu.stepInto`, `cpu.stepOver`, `cpu.stepOut`, `cpu.runUntil`, `cpu.runUntilTime` (run until a point in emulated time - `us` absolute or `relativeUs` from now - and break there; this is how to get a scripted repro reproducibly "N seconds into the game" instead of polling `cpu.status` in a loop), `cpu.nextHLE` | `SteppingSubscriber.cpp` | | Breakpoints | `cpu.breakpoint.add/update/remove/list`, `memory.breakpoint.add/update/remove/list`, `cpu.regBreakpoint.add/update/remove/list` (break when a register is written to, by any instruction anywhere - currently GPRs only; interpreter-only, no effect under a JIT backend) | `BreakpointSubscriber.cpp` | From ebd2b4757f07e10f1fd22ab9876af1c291800da9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 12:07:13 +0200 Subject: [PATCH 04/12] ImDebugger: prefill the assemble box with the instruction that's there Assembling started from an empty box, so replacing an instruction meant reading it off the screen and retyping it, and tweaking one operand meant typing the whole thing. It now opens with the current instruction already in it, selected, so typing replaces it and editing is just editing. Disassembled without symbol substitution for this, unlike what the view itself shows: a branch displayed as a function name doesn't assemble back, and the whole point of the prefill is that it's valid input. Selection is only applied on this path. onChar() also seeds the box - with the character the user just typed over an instruction - and there the text is the start of what they're writing, not something to overwrite. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- UI/ImDebugger/ImDisasmView.cpp | 27 +++++++++++++++++++++------ UI/ImDebugger/ImDisasmView.h | 7 +++++-- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/UI/ImDebugger/ImDisasmView.cpp b/UI/ImDebugger/ImDisasmView.cpp index fbecad6498..0442d6e3a9 100644 --- a/UI/ImDebugger/ImDisasmView.cpp +++ b/UI/ImDebugger/ImDisasmView.cpp @@ -64,7 +64,7 @@ bool ImDisasmView::getDisasmAddressText(u32 address, char *dest, size_t bufSize, return GetDisasmAddressText(address, dest, bufSize, abbreviateLabels, showData, displaySymbols_); } -void ImDisasmView::assembleOpcode(u32 address, std::string_view defaultText) { +void ImDisasmView::assembleOpcode(u32 address, std::string_view defaultText, bool selectAll) { if (!Core_IsStepping()) { statusBarText_ = "Can't assemble while the core is running - pause it first."; return; @@ -74,10 +74,19 @@ void ImDisasmView::assembleOpcode(u32 address, std::string_view defaultText) { // frame that draws it, which is PopupMenu() - see the "assemble" popup there. assembleAddress_ = address; truncate_cpy(assembleTemp_, defaultText); + assembleSelectAll_ = selectAll; assembleError_.clear(); assemblePopup_ = true; } +// The existing instruction, in a form meant to be fed straight back to the assembler - so without +// symbol substitution, since a branch to a named function doesn't assemble back. +void ImDisasmView::assembleCurrentOpcode(u32 address) { + char text[256]; + getOpcodeText(address, text, sizeof(text), false); + assembleOpcode(address, text, true); +} + void ImDisasmView::RunToAddress(u32 address, bool nextFrame) { g_breakpoints.SetTempBreakPoint(address); @@ -579,7 +588,7 @@ void ImDisasmView::ProcessKeyboardShortcuts(bool focused) { // disassembleToFile(); } if (ImGui::IsKeyPressed(ImGuiKey_A)) { - assembleOpcode(curAddress_, ""); + assembleCurrentOpcode(curAddress_); } if (ImGui::IsKeyPressed(ImGuiKey_G)) { // Goto. should just focus on the goto input? @@ -818,7 +827,7 @@ void ImDisasmView::PopupMenu(MIPSState *mips, ImControl &control) { } ImGui::Separator(); if (ImGui::MenuItem("Assemble")) { - assembleOpcode(curAddress_, ""); + assembleCurrentOpcode(curAddress_); } if (ImGui::MenuItem("NOP instructions (destructive)")) { if (Memory::IsValid4AlignedRange(selectRangeStart_, selectRangeEnd_ - selectRangeStart_)) { @@ -932,7 +941,13 @@ void ImDisasmView::PopupMenu(MIPSState *mips, ImControl &control) { if (ImGui::IsWindowAppearing()) { ImGui::SetKeyboardFocusHere(); } - if (ImGui::InputText("Opcode", assembleTemp_, sizeof(assembleTemp_), ImGuiInputTextFlags_EnterReturnsTrue)) { + // AutoSelectAll only when we prefilled with the existing instruction, so it's overwritten + // by just typing. Not when onChar() seeded it with the character the user typed - that one + // is the start of what they're writing, not something to replace. + ImGuiInputTextFlags inputFlags = ImGuiInputTextFlags_EnterReturnsTrue; + if (assembleSelectAll_) + inputFlags |= ImGuiInputTextFlags_AutoSelectAll; + if (ImGui::InputText("Opcode", assembleTemp_, sizeof(assembleTemp_), inputFlags)) { if (applyAssembly(assembleAddress_, assembleTemp_)) { ImGui::CloseCurrentPopup(); } @@ -1129,10 +1144,10 @@ void ImDisasmView::disassembleToFile() { // get size */ } -void ImDisasmView::getOpcodeText(u32 address, char* dest, int bufsize) { +void ImDisasmView::getOpcodeText(u32 address, char *dest, int bufsize, bool insertSymbols) { DisassemblyLineInfo line; address = g_disassemblyManager.getStartAddress(address); - g_disassemblyManager.getLine(address, displaySymbols_, line, debugger_); + g_disassemblyManager.getLine(address, insertSymbols, line, debugger_); snprintf(dest, bufsize, "%s %s", line.name.c_str(), line.params.c_str()); } diff --git a/UI/ImDebugger/ImDisasmView.h b/UI/ImDebugger/ImDisasmView.h index 1412158717..6aa850b94a 100644 --- a/UI/ImDebugger/ImDisasmView.h +++ b/UI/ImDebugger/ImDisasmView.h @@ -44,7 +44,7 @@ public: void ScanVisibleFunctions(); void clearFunctions() { g_disassemblyManager.clear(); }; - void getOpcodeText(u32 address, char *dest, int bufsize); + void getOpcodeText(u32 address, char *dest, int bufsize, bool insertSymbols); u32 yToAddress(float y); void setDebugger(MIPSDebugInterface *deb) { @@ -131,7 +131,9 @@ private: void RunToAddress(u32 address, bool nextFrame); // Requests the assemble popup - the actual input happens in PopupMenu(), since ImGui popups // can only be opened and drawn from inside the frame that owns them. - void assembleOpcode(u32 address, std::string_view defaultText); + void assembleOpcode(u32 address, std::string_view defaultText, bool selectAll = false); + // Same, prefilled with the instruction that's already there, selected so typing replaces it. + void assembleCurrentOpcode(u32 address); // Applies what was typed into that popup. Returns false and fills in assembleError_ if it // couldn't be assembled, so the popup can stay open and show why. bool applyAssembly(u32 address, std::string_view op); @@ -186,6 +188,7 @@ private: bool assemblePopup_ = false; u32 assembleAddress_ = 0; char assembleTemp_[256]{}; + bool assembleSelectAll_ = false; std::string assembleError_; }; From c5e7c4890ab61ddf2370dcef404823ff9d3707cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 12:31:42 +0200 Subject: [PATCH 05/12] Debugger: decode DWARF line info, and show source locations Homebrew commonly ships its unstripped ELF next to the EBOOT, which is already how the symbol loader turns z_un_08841f98 into a function name. That same ELF carries a DWARF .debug_line section, so the addresses can be mapped to source files and lines too - and a backtrace stops being four hex numbers: 08841f98 move sp,fp mesh.zig:163 0883afa4 li v0,0x0 MenuState.zig:821 088260d8 andi at,v0,0xFFFF State.zig:40 0882a27c andi at,v0,0xFFFF engine.zig:468 Surfaced in three places: per frame in hle.backtrace, in the "hit" object that cpu.breakpoint.hit and cpu.stepping share, and appended to the disassembly window's status bar. The breakpoint case keys on the pc rather than the address, since for a memory breakpoint the useful source location is the instruction that did the access, not the data it touched. Storage is a plain sorted table of absolute addresses per module. SymbolMap keeps module-relative addresses because its .ppsym files are meant to be reloaded by a different game that pulls in the same module; none of this is ever written anywhere - it's regenerated from the ELF each boot - so there'd be nothing for relative addresses to buy. Each module owns its own rows and file names outright and is keyed the way SymbolMap::UnloadModule is, so unloading one module drops its lines and nobody else's. The subtle part is end-of-sequence markers. Without them a lookup for an address in a gap - a compilation unit built without debug info - confidently reports the last line of an unrelated file. A prototype run over one test binary mis-attributed 70 of its 349 functions that way, so sequence ends are recorded as rows with line 0 and a lookup landing on one reports nothing instead. DWARF 2 through 4 are decoded (psp-gcc emits 2, Zig 4). Version 5 re-encoded the file table, so those units are skipped with a warning rather than mis-parsed - nothing targeting the PSP produces it today. Scope, since it's narrower than it sounds: PRX conversion strips every .debug section. I checked all 437 pspautotests .prx and CrossCraft's own app.prx - none have any. Of 24 installed homebrew EBOOTs, zero carry debug info; CrossCraft only does because it ships app.elf separately. So this helps someone developing homebrew, and does nothing at all for a commercial game. Costs about 1.2 MB for a large Zig binary (98383 rows, 438 files) and nothing for anything without debug info. Follows bAutoSaveLoadSymbols like the symbols do. pspautotests 314/314, UnitTest 55/55, CoreUWP builds. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- Core/CMakeLists.txt | 2 + Core/Core.vcxproj | 2 + Core/Core.vcxproj.filters | 6 + Core/Debugger/LineInfo.cpp | 421 ++++++++++++++++++ Core/Debugger/LineInfo.h | 81 ++++ .../WebSocket/BreakpointSubscriber.cpp | 14 + Core/Debugger/WebSocket/HLESubscriber.cpp | 17 + Core/ELF/ElfReader.cpp | 4 + Core/HLE/sceKernelModule.cpp | 3 + UI/ImDebugger/ImDisasmView.cpp | 8 + UWP/CoreUWP/CoreUWP.vcxproj | 2 + UWP/CoreUWP/CoreUWP.vcxproj.filters | 2 + android/jni/Android.mk | 1 + docs/WebSocketDebugger.md | 26 ++ libretro/Makefile.common | 1 + 15 files changed, 590 insertions(+) create mode 100644 Core/Debugger/LineInfo.cpp create mode 100644 Core/Debugger/LineInfo.h diff --git a/Core/CMakeLists.txt b/Core/CMakeLists.txt index f2106e43a5..59eb9c83f1 100644 --- a/Core/CMakeLists.txt +++ b/Core/CMakeLists.txt @@ -284,6 +284,8 @@ add_library(Core STATIC Debugger/Breakpoints.cpp Debugger/Breakpoints.h Debugger/DebugInterface.h + Debugger/LineInfo.cpp + Debugger/LineInfo.h Debugger/MemBlockInfo.cpp Debugger/MemBlockInfo.h Debugger/SymbolMap.cpp diff --git a/Core/Core.vcxproj b/Core/Core.vcxproj index 2b4c3acb22..c9694ce3fb 100644 --- a/Core/Core.vcxproj +++ b/Core/Core.vcxproj @@ -441,6 +441,7 @@ + @@ -982,6 +983,7 @@ + diff --git a/Core/Core.vcxproj.filters b/Core/Core.vcxproj.filters index 83ea1b310b..94946d503c 100644 --- a/Core/Core.vcxproj.filters +++ b/Core/Core.vcxproj.filters @@ -967,6 +967,9 @@ MIPS\fake + + Debugger + Debugger @@ -2112,6 +2115,9 @@ MIPS\fake + + Debugger + Debugger diff --git a/Core/Debugger/LineInfo.cpp b/Core/Debugger/LineInfo.cpp new file mode 100644 index 0000000000..16526b4b2a --- /dev/null +++ b/Core/Debugger/LineInfo.cpp @@ -0,0 +1,421 @@ +// Copyright (c) 2026- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include +#include +#include + +#include "Common/Log.h" +#include "Common/StringUtils.h" +#include "Core/Debugger/LineInfo.h" +#include "Core/ELF/ElfReader.h" + +LineInfoMap g_lineInfo; + +namespace { + +// Bounds-checked cursor over the section. Everything here is parsing a file we didn't produce, so +// a truncated or malformed one has to fail rather than read past the end - Fail() latches, and +// every read after it returns zero, which lets the parse loops check once at the end instead of +// after every field. +class Reader { +public: + Reader(const uint8_t *data, size_t size) : data_(data), size_(size) {} + + bool ok() const { return ok_; } + size_t pos() const { return pos_; } + void Seek(size_t pos) { + if (pos > size_) + Fail(); + else + pos_ = pos; + } + bool AtEnd(size_t limit) const { return pos_ >= limit; } + + uint8_t U8() { + if (pos_ + 1 > size_) + return Fail(); + return data_[pos_++]; + } + uint16_t U16() { + if (pos_ + 2 > size_) + return Fail(); + uint16_t v; + memcpy(&v, data_ + pos_, 2); + pos_ += 2; + return v; + } + uint32_t U32() { + if (pos_ + 4 > size_) + return Fail(); + uint32_t v; + memcpy(&v, data_ + pos_, 4); + pos_ += 4; + return v; + } + uint64_t ULEB() { + uint64_t result = 0; + int shift = 0; + for (int i = 0; i < 10; i++) { + const uint8_t b = U8(); + if (!ok_) + return 0; + if (shift < 64) + result |= (uint64_t)(b & 0x7f) << shift; + shift += 7; + if (!(b & 0x80)) + return result; + } + return Fail(); + } + int64_t SLEB() { + int64_t result = 0; + int shift = 0; + for (int i = 0; i < 10; i++) { + const uint8_t b = U8(); + if (!ok_) + return 0; + if (shift < 64) + result |= (int64_t)(b & 0x7f) << shift; + shift += 7; + if (!(b & 0x80)) { + if (shift < 64 && (b & 0x40)) + result -= (int64_t)1 << shift; + return result; + } + } + return Fail(); + } + std::string Str() { + const size_t start = pos_; + while (pos_ < size_ && data_[pos_]) + pos_++; + if (pos_ >= size_) { + Fail(); + return std::string(); + } + std::string s((const char *)data_ + start, pos_ - start); + pos_++; + return s; + } + +private: + uint32_t Fail() { + ok_ = false; + pos_ = size_; + return 0; + } + + const uint8_t *data_; + size_t size_; + size_t pos_ = 0; + bool ok_ = true; +}; + +// Standard opcode numbers we act on. The rest are skipped generically using the header's operand +// counts, which is what makes an unknown-but-well-formed producer harmless. +enum { + DW_LNS_copy = 1, + DW_LNS_advance_pc = 2, + DW_LNS_advance_line = 3, + DW_LNS_set_file = 4, + DW_LNS_set_column = 5, + DW_LNS_negate_stmt = 6, + DW_LNS_set_basic_block = 7, + DW_LNS_const_add_pc = 8, + DW_LNS_fixed_advance_pc = 9, + DW_LNE_end_sequence = 1, + DW_LNE_set_address = 2, + DW_LNE_define_file = 3, +}; + +} // namespace + +// One .debug_line unit: header, then a bytecode program that walks a virtual machine whose output +// rows are (address, file, line). See the DWARF spec, "Line Number Information". +static bool ParseUnit(Reader &r, size_t unitEnd, std::vector *entries, + std::vector *files, std::map *fileIndex, u32 moduleStart, u32 moduleSize) { + const uint16_t version = r.U16(); + if (version < 2 || version > 4) { + // v5 rewrote the file table to use form-coded entries, which is a different parser. Nothing + // that targets the PSP emits it today (psp-gcc is on 2, Zig on 4), so skip rather than + // risk decoding it wrong. + return false; + } + + const uint32_t headerLength = r.U32(); + const size_t programStart = r.pos() + headerLength; + + const uint8_t minInstLength = r.U8(); + if (version >= 4) + r.U8(); // maximum_operations_per_instruction + const uint8_t defaultIsStmt = r.U8(); + (void)defaultIsStmt; + const int8_t lineBase = (int8_t)r.U8(); + const uint8_t lineRange = r.U8(); + const uint8_t opcodeBase = r.U8(); + if (!r.ok() || lineRange == 0 || minInstLength == 0 || opcodeBase == 0) + return false; + + std::vector stdOpcodeLengths(opcodeBase > 0 ? opcodeBase - 1 : 0); + for (size_t i = 0; i < stdOpcodeLengths.size(); i++) + stdOpcodeLengths[i] = r.U8(); + + // include_directories, then file_names - each a list terminated by an empty string. We only + // keep the names; the directory index is ignored, since a bare file name is what's actually + // readable in a status bar or a backtrace. + while (r.ok() && !r.Str().empty()) { + } + // Index 0 is unused in DWARF < 5; entries start at 1. + std::vector unitFiles{ 0 }; + while (r.ok()) { + const std::string name = r.Str(); + if (name.empty()) + break; + r.ULEB(); // directory index + r.ULEB(); // modification time + r.ULEB(); // length + // Deduped across units so a header included by 500 files is stored once. + auto it = fileIndex->find(name); + if (it == fileIndex->end()) { + it = fileIndex->insert({ name, (u32)files->size() }).first; + files->push_back(name); + } + unitFiles.push_back(it->second); + } + if (!r.ok()) + return false; + + r.Seek(programStart); + + u32 address = 0; + u32 file = 1; + int line = 1; + bool sawAddress = false; + + auto emit = [&](u32 lineNo) { + // Rows before a DW_LNE_set_address belong to no real code; and anything outside the module + // we're relocating into would only produce bogus lookups. + if (!sawAddress || address > moduleSize) + return; + LineEntry e; + e.address = moduleStart + address; + e.line = lineNo; + e.fileIndex = file < unitFiles.size() ? unitFiles[file] : 0; + entries->push_back(e); + }; + + while (r.ok() && !r.AtEnd(unitEnd)) { + const uint8_t op = r.U8(); + if (op >= opcodeBase) { + // Special opcode: one byte encoding both an address advance and a line delta. + const uint8_t adjusted = op - opcodeBase; + address += (adjusted / lineRange) * minInstLength; + line += lineBase + (adjusted % lineRange); + emit(line > 0 ? (u32)line : 1); + } else if (op == 0) { + // Extended opcode, length-prefixed so unknown ones can be skipped. + const uint64_t length = r.ULEB(); + const size_t next = r.pos() + (size_t)length; + const uint8_t sub = r.U8(); + if (sub == DW_LNE_end_sequence) { + // line 0 terminates the sequence - see the comment on LineEntry::line. + emit(0); + address = 0; + file = 1; + line = 1; + sawAddress = false; + } else if (sub == DW_LNE_set_address) { + address = r.U32(); + sawAddress = true; + } + r.Seek(next); + } else { + switch (op) { + case DW_LNS_copy: + emit(line > 0 ? (u32)line : 1); + break; + case DW_LNS_advance_pc: + address += (u32)r.ULEB() * minInstLength; + break; + case DW_LNS_advance_line: + line += (int)r.SLEB(); + break; + case DW_LNS_set_file: + file = (u32)r.ULEB(); + break; + case DW_LNS_set_column: + r.ULEB(); + break; + case DW_LNS_negate_stmt: + case DW_LNS_set_basic_block: + break; + case DW_LNS_const_add_pc: + address += ((255 - opcodeBase) / lineRange) * minInstLength; + break; + case DW_LNS_fixed_advance_pc: + address += r.U16(); + break; + default: + // Known length, unknown meaning - skip its operands and carry on. + for (uint8_t i = 0; op - 1 < (int)stdOpcodeLengths.size() && i < stdOpcodeLengths[op - 1]; i++) + r.ULEB(); + break; + } + } + } + + return r.ok(); +} + +int LineInfoMap::AddModule(std::string_view elfData, u32 moduleStart, u32 moduleSize) { + RemoveModule(moduleStart, moduleSize); + + const uint8_t *data = (const uint8_t *)elfData.data(); + const size_t size = elfData.size(); + if (size < sizeof(Elf32_Ehdr)) + return 0; + if (data[0] != ELFMAG0 || data[1] != ELFMAG1 || data[2] != ELFMAG2 || data[3] != ELFMAG3) + return 0; + + const Elf32_Ehdr *header = (const Elf32_Ehdr *)data; + if (header->e_shoff == 0 || header->e_shnum == 0 || header->e_shentsize < sizeof(Elf32_Shdr)) + return 0; + if ((size_t)header->e_shoff + (size_t)header->e_shnum * header->e_shentsize > size) + return 0; + if (header->e_shstrndx >= header->e_shnum) + return 0; + + auto section = [&](int i) { + return (const Elf32_Shdr *)(data + header->e_shoff + (size_t)i * header->e_shentsize); + }; + + const Elf32_Shdr *shstr = section(header->e_shstrndx); + if ((size_t)shstr->sh_offset + shstr->sh_size > size) + return 0; + + const Elf32_Shdr *debugLine = nullptr; + for (int i = 0; i < header->e_shnum; i++) { + const Elf32_Shdr *s = section(i); + if (s->sh_name >= shstr->sh_size) + continue; + const char *name = (const char *)data + shstr->sh_offset + s->sh_name; + if (!strcmp(name, ".debug_line")) { + debugLine = s; + break; + } + } + if (!debugLine || debugLine->sh_size == 0) + return 0; + if ((size_t)debugLine->sh_offset + debugLine->sh_size > size) + return 0; + + ModuleLines mod; + mod.start = moduleStart; + mod.size = moduleSize; + mod.files.push_back(""); + std::map fileIndex; + + Reader r(data + debugLine->sh_offset, debugLine->sh_size); + int skippedUnits = 0; + while (r.ok() && !r.AtEnd(debugLine->sh_size)) { + const size_t unitStart = r.pos(); + const uint32_t unitLength = r.U32(); + if (!r.ok() || unitLength == 0) + break; + // 0xfffffff0 and up are reserved; 0xffffffff introduces 64-bit DWARF, which nothing here + // produces, and misreading it would walk off into nonsense. + if (unitLength >= 0xfffffff0) + break; + const size_t unitEnd = unitStart + 4 + unitLength; + if (unitEnd > debugLine->sh_size) + break; + + if (!ParseUnit(r, unitEnd, &mod.entries, &mod.files, &fileIndex, moduleStart, moduleSize)) + skippedUnits++; + r.Seek(unitEnd); + } + + if (skippedUnits > 0) { + WARN_LOG(Log::Loader, "Line info: skipped %d compilation unit(s) - unsupported DWARF version?", skippedUnits); + } + if (mod.entries.empty()) + return 0; + + // Sorted for binary search. Rows at the same address are collapsed to the last one, which is + // what a debugger wants: the innermost/most recent statement wins, and an end-of-sequence + // marker sharing an address with the next sequence's first row loses to it. + std::stable_sort(mod.entries.begin(), mod.entries.end(), [](const LineEntry &a, const LineEntry &b) { + return a.address < b.address; + }); + mod.entries.erase(std::unique(mod.entries.begin(), mod.entries.end(), [](const LineEntry &a, const LineEntry &b) { + return a.address == b.address; + }), mod.entries.end()); + + const int count = (int)mod.entries.size(); + INFO_LOG(Log::Loader, "Line info: %d rows across %d files for module at %08x", + count, (int)mod.files.size() - 1, moduleStart); + modules_.push_back(std::move(mod)); + return count; +} + +void LineInfoMap::RemoveModule(u32 moduleStart, u32 moduleSize) { + modules_.erase(std::remove_if(modules_.begin(), modules_.end(), [&](const ModuleLines &m) { + return m.start == moduleStart && m.size == moduleSize; + }), modules_.end()); +} + +void LineInfoMap::Clear() { + modules_.clear(); +} + +const LineInfoMap::ModuleLines *LineInfoMap::FindModule(u32 address) const { + for (const ModuleLines &m : modules_) { + if (address >= m.start && address < m.start + m.size) + return &m; + } + return nullptr; +} + +bool LineInfoMap::Lookup(u32 address, std::string *file, int *line) const { + const ModuleLines *mod = FindModule(address); + if (!mod) + return false; + + // The row describing an address is the last one at or before it. + auto it = std::upper_bound(mod->entries.begin(), mod->entries.end(), address, + [](u32 addr, const LineEntry &e) { return addr < e.address; }); + if (it == mod->entries.begin()) + return false; + --it; + if (it->line == 0) + return false; // Past the end of that sequence - see LineEntry::line. + + if (file) + *file = it->fileIndex < mod->files.size() ? mod->files[it->fileIndex] : mod->files[0]; + if (line) + *line = (int)it->line; + return true; +} + +std::string LineInfoMap::LookupString(u32 address) const { + std::string file; + int line = 0; + if (!Lookup(address, &file, &line)) + return std::string(); + return StringFromFormat("%s:%d", file.c_str(), line); +} diff --git a/Core/Debugger/LineInfo.h b/Core/Debugger/LineInfo.h new file mode 100644 index 0000000000..61f013fe18 --- /dev/null +++ b/Core/Debugger/LineInfo.h @@ -0,0 +1,81 @@ +// Copyright (c) 2026- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include +#include +#include + +#include "Common/CommonTypes.h" + +// Source line information decoded from an ELF's DWARF .debug_line section. +// +// Only available where an unstripped ELF is: PRX conversion drops every .debug section, so this +// never applies to a commercial game, and in practice it means homebrew that ships its app.elf +// next to the EBOOT (the same thing the companion symbol loader relies on). +// +// Addresses are stored absolute, relocated to wherever the module was loaded. Unlike SymbolMap, +// which keeps module-relative addresses so a saved .ppsym can be reloaded by a different game that +// pulls in the same module, none of this is ever written anywhere - it's regenerated from the ELF +// on every boot - so there'd be nothing for relative addresses to buy. +struct LineEntry { + u32 address; + // 0 marks the end of a sequence: the address is one past the last instruction the preceding + // rows describe. Without these, a lookup for an address in a gap (a compilation unit built + // without debug info, say) silently reports the last line of an unrelated source file - it + // mis-attributed 70 of 349 functions in one test binary before they were recorded. + u32 line; + u32 fileIndex; +}; + +class LineInfoMap { +public: + // Parses .debug_line out of an unstripped ELF image and relocates it to moduleStart. + // Returns the number of rows kept, or 0 if the ELF has nothing usable. Replaces whatever was + // held for the same module. + int AddModule(std::string_view elfData, u32 moduleStart, u32 moduleSize); + + // Keyed the same way SymbolMap::UnloadModule is, so that unloading one module drops only its + // own lines. Each module owns its rows and its file names outright - there's no shared table + // for an unload to have to pick apart. + void RemoveModule(u32 moduleStart, u32 moduleSize); + void Clear(); + + bool IsEmpty() const { return modules_.empty(); } + + // The source location of the instruction at this address. False when no loaded module owns the + // address, or when it falls in a gap between sequences. + bool Lookup(u32 address, std::string *file, int *line) const; + + // "file.c:123", or empty if unknown. For status bars and log lines. + std::string LookupString(u32 address) const; + +private: + struct ModuleLines { + u32 start = 0; + u32 size = 0; + std::vector files; + std::vector entries; // Sorted by address. + }; + + const ModuleLines *FindModule(u32 address) const; + + std::vector modules_; +}; + +extern LineInfoMap g_lineInfo; diff --git a/Core/Debugger/WebSocket/BreakpointSubscriber.cpp b/Core/Debugger/WebSocket/BreakpointSubscriber.cpp index 4dbe2d43d0..99071cb1cf 100644 --- a/Core/Debugger/WebSocket/BreakpointSubscriber.cpp +++ b/Core/Debugger/WebSocket/BreakpointSubscriber.cpp @@ -19,6 +19,7 @@ #include "Core/Core.h" #include "Core/Debugger/Breakpoints.h" #include "Core/Debugger/DisassemblyManager.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Debugger/SymbolMap.h" #include "Core/Debugger/WebSocket/BreakpointSubscriber.h" #include "Core/Debugger/WebSocket/WebSocketUtils.h" @@ -54,6 +55,19 @@ void WriteBreakpointHit(JsonWriter &json, const BreakpointHit &hit) { else json.writeString("symbol", symbol); + // Only when the game shipped an unstripped ELF with DWARF in it - see LineInfo.h. Keyed on pc + // rather than address, since for a memory breakpoint the interesting source location is the + // instruction that did the access, not the data it touched. + std::string file; + int line = 0; + if (g_lineInfo.Lookup(hit.pc, &file, &line)) { + json.writeString("file", file); + json.writeInt("line", line); + } else { + json.writeNull("file"); + json.writeNull("line"); + } + if (hit.kind == BreakpointKind::Memory) { json.writeInt("size", hit.size); json.writeString("access", hit.write ? "write" : "read"); diff --git a/Core/Debugger/WebSocket/HLESubscriber.cpp b/Core/Debugger/WebSocket/HLESubscriber.cpp index 1278c6c880..9a54963d85 100644 --- a/Core/Debugger/WebSocket/HLESubscriber.cpp +++ b/Core/Debugger/WebSocket/HLESubscriber.cpp @@ -23,6 +23,7 @@ #include "Core/ELF/ParamSFO.h" #include "Common/File/FileUtil.h" #include "Core/Debugger/DisassemblyManager.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Debugger/SymbolMap.h" #include "Core/Debugger/WebSocket/HLESubscriber.h" #include "Core/Debugger/WebSocket/WebSocketUtils.h" @@ -815,6 +816,9 @@ void WebSocketHLEGameLoadSymbols(DebuggerRequest &req) { // - sp: unsigned integer stack address in this func (beware of alloca().) // - stackSize: integer size of stack frame. // - code: string disassembly of pc, empty if pc isn't readable. +// - file: string source file name, or null when there's no line info for this address. +// - line: integer source line number, or null. Only ever available when the game shipped an +// unstripped ELF - PRX conversion drops DWARF, so this is a homebrew-only luxury. // // A real stack walk needs to recognize the function it starts in, so it comes back empty exactly // when execution has gone somewhere unexpected - a jump through a bad pointer, say - which is @@ -896,6 +900,19 @@ void WebSocketHLEBacktrace(DebuggerRequest &req) { json.writeString("code", ""); } + // Only present when the game shipped an unstripped ELF to read DWARF out of, which in + // practice means homebrew - see Core/Debugger/LineInfo.h. A backtrace is where this + // pays off most: four addresses versus four source locations. + std::string file; + int line = 0; + if (g_lineInfo.Lookup(f.pc, &file, &line)) { + json.writeString("file", file); + json.writeInt("line", line); + } else { + json.writeNull("file"); + json.writeNull("line"); + } + json.pop(); } json.pop(); diff --git a/Core/ELF/ElfReader.cpp b/Core/ELF/ElfReader.cpp index b95940b781..961a83b9bd 100644 --- a/Core/ELF/ElfReader.cpp +++ b/Core/ELF/ElfReader.cpp @@ -27,6 +27,7 @@ #include "Core/MIPS/MIPSTables.h" #include "Core/ELF/ElfReader.h" #include "Core/Debugger/MemBlockInfo.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Debugger/SymbolMap.h" #include "Core/HLE/ErrorCodes.h" #include "Core/HLE/sceKernelMemory.h" @@ -934,6 +935,9 @@ int LoadCompanionElfSymbols(const Path &gameFile, u32 moduleBase, u32 moduleSize if (added > 0) { INFO_LOG(Log::Loader, "Loaded %d symbols from companion ELF '%s'", added, file.name.c_str()); g_symbolMap->SortSymbols(); + // Same file, already validated as belonging to this module, so its DWARF line table + // relocates the same way. Absent from anything built without -g, which is fine. + g_lineInfo.AddModule(data, moduleBase, moduleSize); return added; } DEBUG_LOG(Log::Loader, "Companion ELF '%s' skipped: %s", file.name.c_str(), why); diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index fefd8bb69b..1483864e16 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -56,6 +56,7 @@ #include "Core/PSPLoaders.h" #include "Core/System.h" #include "Core/MemMapHelpers.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Debugger/SymbolMap.h" #include "Core/HLE/sceKernel.h" #include "Core/HLE/sceKernelModule.h" @@ -210,6 +211,8 @@ PSPModule::~PSPModule() { userMemory.Free(memoryBlockAddr); } g_symbolMap->UnloadModule(memoryBlockAddr, memoryBlockSize); + // Keyed identically, so a module going away takes its own line info and nothing else's. + g_lineInfo.RemoveModule(memoryBlockAddr, memoryBlockSize); } if (modulePtr.ptr) { diff --git a/UI/ImDebugger/ImDisasmView.cpp b/UI/ImDebugger/ImDisasmView.cpp index 0442d6e3a9..a5d061e23b 100644 --- a/UI/ImDebugger/ImDisasmView.cpp +++ b/UI/ImDebugger/ImDisasmView.cpp @@ -16,6 +16,7 @@ #include "Core/MIPS/MIPSAsm.h" #include "Core/HW/Display.h" #include "Core/Reporting.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Debugger/SymbolMap.h" #include "Core/MemMap.h" #include "Common/System/Request.h" @@ -977,6 +978,13 @@ void ImDisasmView::updateStatusBarText() { if (!label.empty()) { statusBarText_ = label; } + + // Appended rather than replacing, since knowing which instruction you're on is still the point. + // Empty for anything without an unstripped ELF to read DWARF from - see LineInfo.h. + const std::string source = g_lineInfo.LookupString(curAddress_); + if (!source.empty()) { + statusBarText_ += " " + source; + } } u32 ImDisasmView::yToAddress(float y) { diff --git a/UWP/CoreUWP/CoreUWP.vcxproj b/UWP/CoreUWP/CoreUWP.vcxproj index 386a560f9f..da01877e66 100644 --- a/UWP/CoreUWP/CoreUWP.vcxproj +++ b/UWP/CoreUWP/CoreUWP.vcxproj @@ -98,6 +98,7 @@ + @@ -375,6 +376,7 @@ + diff --git a/UWP/CoreUWP/CoreUWP.vcxproj.filters b/UWP/CoreUWP/CoreUWP.vcxproj.filters index 7d65f6d17d..5834076ba8 100644 --- a/UWP/CoreUWP/CoreUWP.vcxproj.filters +++ b/UWP/CoreUWP/CoreUWP.vcxproj.filters @@ -11,6 +11,7 @@ + @@ -431,6 +432,7 @@ + diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 9847580b1d..b3d9294826 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -654,6 +654,7 @@ EXEC_AND_LIB_FILES := \ $(SRC)/Core/WebServer.cpp \ $(SRC)/Core/Debugger/Breakpoints.cpp \ $(SRC)/Core/Debugger/DisassemblyManager.cpp \ + $(SRC)/Core/Debugger/LineInfo.cpp \ $(SRC)/Core/Debugger/MemBlockInfo.cpp \ $(SRC)/Core/Debugger/SymbolMap.cpp \ $(SRC)/Core/Debugger/WebSocket.cpp \ diff --git a/docs/WebSocketDebugger.md b/docs/WebSocketDebugger.md index f259aab430..7ad9503a3d 100644 --- a/docs/WebSocketDebugger.md +++ b/docs/WebSocketDebugger.md @@ -132,6 +132,31 @@ way for periodic GPU stats. `client.config.set` in the same file carries per-connection settings that aren't about broadcasts - currently just `acknowledgeDeferred`, described under "Message protocol" above. +### Source line info + +Where a game shipped an unstripped ELF, PPSSPP decodes its DWARF `.debug_line` +and can map an address to a source file and line. `cpu.breakpoint.hit` and +`cpu.stepping` carry `file`/`line` in the `hit` object, and `hle.backtrace` +carries them per frame - which is where it pays off most: + +``` +08841f98 move sp,fp mesh.zig:163 +0883afa4 li v0,0x0 MenuState.zig:821 +088260d8 andi at,v0,0xFFFF State.zig:40 +0882a27c andi at,v0,0xFFFF engine.zig:468 +``` + +Both fields are `null` when there's no line info for that address, which is the +common case: **PRX conversion strips every `.debug` section**, so this never +applies to a commercial game. In practice it means homebrew that ships its +`app.elf` next to the EBOOT - the same file the companion symbol loader uses - +or a plain `.elf` you built yourself. It follows `bAutoSaveLoadSymbols` along +with the symbols. + +DWARF 2, 3 and 4 are decoded; version 5 units are skipped with a log line rather +than mis-parsed, since it re-encoded the file table. Nothing targeting the PSP +emits it today (psp-gcc produces 2, Zig 4). + ### Emulation speed `game.speed.set` drives two independent things: @@ -211,6 +236,7 @@ Fields common to every kind: | `logged` / `paused` | Which actions it had - `paused` false means the CPU kept running | | `condition` | The condition expression, or `null` | | `symbol` | Symbol at `address`, or `null` - resolved here to save a round trip | +| `file` / `line` | Source location of `pc`, or `null`. See "Source line info" below | | `breakpoint` | `{start, end}` identifying which breakpoint fired. Absent for `"register"`, whose identity is the register, not an address | Extra fields for `"memory"`: diff --git a/libretro/Makefile.common b/libretro/Makefile.common index e0b3ca3dbf..6c49b5bc10 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -725,6 +725,7 @@ SOURCES_CXX += \ $(COREDIR)/Instance.cpp \ $(COREDIR)/Debugger/Breakpoints.cpp \ $(COREDIR)/Debugger/SymbolMap.cpp \ + $(COREDIR)/Debugger/LineInfo.cpp \ $(COREDIR)/Debugger/MemBlockInfo.cpp \ $(COREDIR)/Dialog/PSPDialog.cpp \ $(COREDIR)/Dialog/PSPGamedataInstallDialog.cpp \ From 3f0c2da5a9eebcf03346de4944c98af38a78a30e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 13:18:04 +0200 Subject: [PATCH 06/12] Debugger: surface source line info in six more places Following on from the DWARF line table: the lookup was only reachable from hle.backtrace, the breakpoint hit object and the ImGui disassembly status bar. Now also in - the ImDebugger call stack (new Source column), - the Win32 call stack (new Source column), - the Win32 disassembly status bar, matching the ImGui one, - the ImDisasmView right-click menu, which showed a bare address as its heading and now leads with "mesh.zig:163 (08841f98)" when there's a line for it, - breakpoint log lines - a log-only breakpoint's entire output is those lines, and "BKP PC=08841f98 mesh.zig:163" reads a great deal better than an address when you're scanning a few thousand of them, - crash stack traces, via FormatStackTrace, which is what the crash screen and crash reporting both use. That last one is where it earns its keep, and it needed the invalid-jump path to produce a stack trace at all - it was the one exec exception that didn't. It's also the one that most deserves it: the address it jumped to tells you nothing, the callers tell you everything. Execution has already moved to the bad address by the time it's noticed, so a walk from pc finds no function to start from; WalkCurrentStack takes an explicit starting pc now, and falling back to ra recovers the chain. Reproducing the original CrossCraft bug: CPU Jump: Invalid jump to ae870000 from PC ae870000(invalid) RA 08841f98 MIPS call stack: rendering.mesh.Mesh(PspVertex).draw at mesh.zig:163 (08841c30+368, ...) state.MenuState.draw at MenuState.zig:821 (0883ab90+414, ...) engine.Engine.stepFrameInternal at State.zig:40 (08820f74+5164, ...) utils.module._module_main_thread at engine.zig:468 (088272c4+2fb8, ...) Fixed a pre-existing double-report while in there: every case in Core_ExecException sent its message and then fell through to an unconditional send of the same message, so each exec exception was logged twice. The message is built in the switch and sent once at the end now. pspautotests 314/314, UnitTest 55/55. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- Core/Core.cpp | 28 +++++++++++++++++++--------- Core/Debugger/Breakpoints.cpp | 10 ++++++++-- Core/MemFault.cpp | 17 ++++++++++++----- Core/MemFault.h | 5 ++++- UI/ImDebugger/ImDebugger.cpp | 9 +++++++-- UI/ImDebugger/ImDisasmView.cpp | 9 ++++++++- Windows/Debugger/CtrlDisAsmView.cpp | 8 +++++++- Windows/Debugger/Debugger_Lists.cpp | 15 ++++++++++++--- 8 files changed, 77 insertions(+), 24 deletions(-) diff --git a/Core/Core.cpp b/Core/Core.cpp index cb5a5f8d79..f662e9ffad 100644 --- a/Core/Core.cpp +++ b/Core/Core.cpp @@ -898,36 +898,46 @@ void Core_ExecException(u32 address, u32 pc, ExecExceptionType type) { snprintf(pcStr, sizeof(pcStr), "[%08x]", Memory::ReadUnchecked_U32(pc)); } + // Each case fills in msg, and a stack trace where one is worth having. Sent once at the end - + // the cases used to send it themselves *and* fall through to the send below, so every exec + // exception was reported twice. char msg[512]; + std::string stackTrace; switch (type) { case ExecExceptionType::JUMP: { snprintf(msg, sizeof(msg), "%s: Invalid jump to %08x%s from PC %08x%s %s RA %08x%s", desc, address, ModuleAddressSuffix(address).c_str(), pc, pcStr, ModuleAddressSuffix(pc).c_str(), currentMIPS->r[MIPS_REG_RA], ModuleAddressSuffix(currentMIPS->r[MIPS_REG_RA]).c_str()); - Core_SendDebugOutput(LogLevel::LERROR, msg); + // A jump through a bad pointer is where a stack trace is worth the most - the address it + // landed on tells you nothing, the callers tell you everything. Execution has already moved + // to the bad address by the time this is noticed, so a walk from pc finds no function to + // start from; ra still points into the caller, and that recovers the whole chain. + std::vector frames = WalkCurrentStack(-1); + if (frames.empty()) + frames = WalkCurrentStack(-1, currentMIPS->r[MIPS_REG_RA]); + stackTrace = FormatStackTrace(frames); break; } case ExecExceptionType::THREAD: - { snprintf(msg, sizeof(msg), "%s: Invalid thread switch to %08x%s from PC %08x%s RA %08x%s", desc, address, ModuleAddressSuffix(address).c_str(), pc, ModuleAddressSuffix(pc).c_str(), currentMIPS->r[MIPS_REG_RA], ModuleAddressSuffix(currentMIPS->r[MIPS_REG_RA]).c_str()); - Core_SendDebugOutput(LogLevel::LERROR, msg); break; - } case ExecExceptionType::ILLEGAL: - { snprintf(msg, sizeof(msg), "%s: Illegal instruction at %08x%s %s RA %08x%s", desc, pc, pcStr, ModuleAddressSuffix(pc).c_str(), currentMIPS->r[MIPS_REG_RA], ModuleAddressSuffix(currentMIPS->r[MIPS_REG_RA]).c_str()); // For illegal instructions, there might be a useful stack trace. - const std::string stackTrace = FormatStackTrace(WalkCurrentStack(-1)); - Core_SendDebugOutput(LogLevel::LERROR, StringFromFormat("%s\n%s", msg, stackTrace.c_str())); + stackTrace = FormatStackTrace(WalkCurrentStack(-1)); break; - } default: truncate_cpy(msg, sizeof(msg), "Unknown exec exception"); break; } - Core_SendDebugOutput(LogLevel::LERROR, msg); + + if (stackTrace.empty()) { + Core_SendDebugOutput(LogLevel::LERROR, msg); + } else { + Core_SendDebugOutput(LogLevel::LERROR, StringFromFormat("%s\nMIPS call stack:\n%s", msg, stackTrace.c_str())); + } MIPSExceptionInfo &e = g_exceptionInfo; e = {}; diff --git a/Core/Debugger/Breakpoints.cpp b/Core/Debugger/Breakpoints.cpp index 9282a0d7c8..67981bf320 100644 --- a/Core/Debugger/Breakpoints.cpp +++ b/Core/Debugger/Breakpoints.cpp @@ -22,6 +22,7 @@ #include "Core/Core.h" #include "Core/Debugger/WebSocket.h" #include "Core/Debugger/Breakpoints.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Debugger/MemBlockInfo.h" #include "Core/Debugger/SymbolMap.h" #include "Core/MemMap.h" @@ -383,12 +384,17 @@ BreakAction BreakpointManager::ExecBreakPoint(u32 addr) { } if (action & BREAK_ACTION_LOG) { + // Empty unless the game shipped an unstripped ELF - see Core/Debugger/LineInfo.h. + // Worth the lookup even on this path: a log-only breakpoint's whole output is these + // lines, and "mesh.zig:163" beats an address for reading a few thousand of them. + const std::string source = g_lineInfo.LookupString(addr); + const std::string at = source.empty() ? std::string() : " " + source; if (info.logFormat.empty()) { - NOTICE_LOG(Log::JIT, "BKP PC=%08x (%s)", addr, g_symbolMap->GetDescription(addr).c_str()); + NOTICE_LOG(Log::JIT, "BKP PC=%08x%s (%s)", addr, at.c_str(), g_symbolMap->GetDescription(addr).c_str()); } else { std::string formatted; BreakpointManager::EvaluateLogFormat(currentDebugMIPS, info.logFormat, formatted); - NOTICE_LOG(Log::JIT, "BKP PC=%08x: %s", addr, formatted.c_str()); + NOTICE_LOG(Log::JIT, "BKP PC=%08x%s: %s", addr, at.c_str(), formatted.c_str()); } } diff --git a/Core/MemFault.cpp b/Core/MemFault.cpp index 478b1a6c5c..43b82fef7b 100644 --- a/Core/MemFault.cpp +++ b/Core/MemFault.cpp @@ -43,6 +43,7 @@ #include "Core/MemFault.h" #include "Core/MemMap.h" #include "Core/MIPS/JitCommon/JitCommon.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Debugger/SymbolMap.h" // Stack walking stuff @@ -295,11 +296,13 @@ bool HandleFault(uintptr_t hostAddress, void *ctx) { } // namespace Memory -std::vector WalkCurrentStack(int threadID) { +std::vector WalkCurrentStack(int threadID, uint32_t startPC) { DebugInterface *cpuDebug = currentDebugMIPS; + if (startPC == 0) + startPC = cpuDebug->GetPC(); auto threads = GetThreadsInfo(); - uint32_t entry = cpuDebug->GetPC(); + uint32_t entry = startPC; uint32_t stackTop = 0; for (const DebugThreadInfo &th : threads) { if ((threadID == -1 && th.isCurrent) || th.id == threadID) { @@ -311,7 +314,7 @@ std::vector WalkCurrentStack(int threadID) { uint32_t ra = cpuDebug->GetRegValue(0, MIPS_REG_RA); uint32_t sp = cpuDebug->GetRegValue(0, MIPS_REG_SP); - return MIPSStackWalk::Walk(cpuDebug->GetPC(), ra, sp, entry, stackTop); + return MIPSStackWalk::Walk(startPC, ra, sp, entry, stackTop); } std::string FormatStackTrace(const std::vector &frames) { @@ -319,11 +322,15 @@ std::string FormatStackTrace(const std::vector &frame for (const auto &frame : frames) { const u32 frameEntry = frame.entry == 0xFFFFFFFF ? 0 : frame.entry; std::string desc = g_symbolMap->GetDescription(frame.entry); + // Empty unless the game shipped an unstripped ELF - see Core/Debugger/LineInfo.h. A crash + // report is the single place this is worth the most, so it goes first on the line. + const std::string source = g_lineInfo.LookupString(frame.pc); + const std::string at = source.empty() ? std::string() : " at " + source; char moduleDesc[96]; if (DescribeModuleAddress(frame.entry, moduleDesc, sizeof(moduleDesc))) { - str << StringFromFormat("%s [%s] (%08x+%03x, pc: %08x sp: %08x)\n", desc.c_str(), moduleDesc, frameEntry, frame.pc - frameEntry, frame.pc, frame.sp); + str << StringFromFormat("%s%s [%s] (%08x+%03x, pc: %08x sp: %08x)\n", desc.c_str(), at.c_str(), moduleDesc, frameEntry, frame.pc - frameEntry, frame.pc, frame.sp); } else { - str << StringFromFormat("%s (%08x+%03x, pc: %08x sp: %08x)\n", desc.c_str(), frameEntry, frame.pc - frameEntry, frame.pc, frame.sp); + str << StringFromFormat("%s%s (%08x+%03x, pc: %08x sp: %08x)\n", desc.c_str(), at.c_str(), frameEntry, frame.pc - frameEntry, frame.pc, frame.sp); } } return str.str(); diff --git a/Core/MemFault.h b/Core/MemFault.h index 3e825d2e53..546064dddd 100644 --- a/Core/MemFault.h +++ b/Core/MemFault.h @@ -25,6 +25,9 @@ bool HandleFault(uintptr_t hostAddress, void *context); // Stack walk utility function, walks from the current state. Useful in the debugger and crash report screens etc. // Doesn't exactly belong here maybe, but can think of worse locations. // threadID can be -1 for current. -std::vector WalkCurrentStack(int threadID); +// startPC of 0 means "wherever the CPU is now". Pass one explicitly when the current pc is the +// problem - a jump to a bad address leaves it pointing at nothing walkable, and starting from ra +// instead still recovers the callers. +std::vector WalkCurrentStack(int threadID, uint32_t startPC = 0); std::string FormatStackTrace(const std::vector &frames); diff --git a/UI/ImDebugger/ImDebugger.cpp b/UI/ImDebugger/ImDebugger.cpp index df86bb6b5c..127c268dfb 100644 --- a/UI/ImDebugger/ImDebugger.cpp +++ b/UI/ImDebugger/ImDebugger.cpp @@ -17,6 +17,7 @@ #include "Core/SaveState.h" #include "Core/WebServer.h" #include "Core/Debugger/MemBlockInfo.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Core.h" #include "Core/Debugger/DebugInterface.h" #include "Core/Debugger/DisassemblyManager.h" @@ -1891,13 +1892,14 @@ static void DrawCallStacks(const MIPSDebugInterface *debug, ImConfig &config, Im } } - if (entry != 0 && ImGui::BeginTable("frames", 6, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersH)) { + if (entry != 0 && ImGui::BeginTable("frames", 7, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersH)) { ImGui::TableSetupColumn("Entry", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("EntryAddr", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("CurPC", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("CurOpCode", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("CurSP", ImGuiTableColumnFlags_WidthFixed); - ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("Source", ImGuiTableColumnFlags_WidthStretch); ImGui::TableHeadersRow(); @@ -1921,6 +1923,9 @@ static void DrawCallStacks(const MIPSDebugInterface *debug, ImConfig &config, Im ImClickableValue("framepc", frame.sp, control, ImCmd::SHOW_IN_MEMORY_VIEWER); ImGui::TableSetColumnIndex(5); ImGui::Text("%d", frame.stackSize); + ImGui::TableSetColumnIndex(6); + // Empty unless the game shipped an unstripped ELF - see Core/Debugger/LineInfo.h. + ImGui::TextUnformatted(g_lineInfo.LookupString(frame.pc).c_str()); // TODO: More fields? ImGui::PopID(); i++; diff --git a/UI/ImDebugger/ImDisasmView.cpp b/UI/ImDebugger/ImDisasmView.cpp index a5d061e23b..3842da2682 100644 --- a/UI/ImDebugger/ImDisasmView.cpp +++ b/UI/ImDebugger/ImDisasmView.cpp @@ -785,7 +785,14 @@ void ImDisasmView::CopyInstructions(u32 startAddr, u32 endAddr, CopyInstructions void ImDisasmView::PopupMenu(MIPSState *mips, ImControl &control) { bool renameFunctionPopup = false; if (ImGui::BeginPopup("context")) { - ImGui::Text("Address: %08x", curAddress_); + // The source location is the more useful heading when there is one, but keep the address: + // it's what you paste into a bug report or another debugger. + const std::string source = g_lineInfo.LookupString(curAddress_); + if (source.empty()) { + ImGui::Text("Address: %08x", curAddress_); + } else { + ImGui::Text("%s (%08x)", source.c_str(), curAddress_); + } if (ImGui::MenuItem("Toggle breakpoint", "F9")) { toggleBreakpoint(); } diff --git a/Windows/Debugger/CtrlDisAsmView.cpp b/Windows/Debugger/CtrlDisAsmView.cpp index 92bc260672..ff03709ad3 100644 --- a/Windows/Debugger/CtrlDisAsmView.cpp +++ b/Windows/Debugger/CtrlDisAsmView.cpp @@ -12,6 +12,7 @@ #include "Core/MIPS/MIPSTables.h" #include "Core/Config.h" #include "Core/Debugger/Breakpoints.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Debugger/SymbolMap.h" #include "Core/Reporting.h" #include "Common/StringUtils.h" @@ -1208,7 +1209,12 @@ void CtrlDisAsmView::updateStatusBarText() SendMessage(GetParent(wnd),WM_DEB_SETSTATUSBARTEXT,0,(LPARAM)text); - const std::string label = g_symbolMap->GetLabelString(line.info.opcodeAddress); + // Empty unless the game shipped an unstripped ELF - see Core/Debugger/LineInfo.h. + const std::string source = g_lineInfo.LookupString(curAddress); + std::string label = g_symbolMap->GetLabelString(line.info.opcodeAddress); + if (!source.empty()) { + label = label.empty() ? source : label + " " + source; + } if (!label.empty()) { SendMessage(GetParent(wnd),WM_DEB_SETSTATUSBARTEXT,1,(LPARAM)label.c_str()); } diff --git a/Windows/Debugger/Debugger_Lists.cpp b/Windows/Debugger/Debugger_Lists.cpp index dd93398f4f..c31b0874cd 100644 --- a/Windows/Debugger/Debugger_Lists.cpp +++ b/Windows/Debugger/Debugger_Lists.cpp @@ -12,12 +12,13 @@ #include "Windows/main.h" #include "Common/Data/Encoding/Utf8.h" #include "Core/Core.h" +#include "Core/Debugger/LineInfo.h" #include "Core/MemMap.h" #include "Core/HLE/sceKernelThread.h" enum { TL_NAME, TL_PROGRAMCOUNTER, TL_ENTRYPOINT, TL_PRIORITY, TL_STATE, TL_WAITTYPE, TL_COLUMNCOUNT }; enum { BPL_ENABLED, BPL_TYPE, BPL_OFFSET, BPL_SIZELABEL, BPL_OPCODE, BPL_CONDITION, BPL_HITS, BPL_COLUMNCOUNT }; -enum { SF_ENTRY, SF_ENTRYNAME, SF_CURPC, SF_CUROPCODE, SF_CURSP, SF_FRAMESIZE, SF_COLUMNCOUNT }; +enum { SF_ENTRY, SF_ENTRYNAME, SF_CURPC, SF_CUROPCODE, SF_CURSP, SF_FRAMESIZE, SF_SOURCE, SF_COLUMNCOUNT }; enum { ML_NAME, ML_ADDRESS, ML_SIZE, ML_ACTIVE, ML_COLUMNCOUNT }; enum { WL_NAME, WL_EXPRESSION, WL_VALUE, WL_COLUMNCOUNT }; @@ -53,8 +54,9 @@ GenericListViewColumn stackTraceColumns[SF_COLUMNCOUNT] = { { L"Name", 0.24f }, { L"PC", 0.12f }, { L"Opcode", 0.28f }, - { L"SP", 0.12f }, - { L"Frame Size", 0.12f } + { L"SP", 0.10f }, + { L"Frame Size", 0.10f }, + { L"Source", 0.16f } }; GenericListViewDef stackTraceListDef = { @@ -737,6 +739,13 @@ void CtrlStackTraceView::GetColumnText(wchar_t* dest, size_t destSize, int row, case SF_FRAMESIZE: wsprintf(dest,L"%08X",frames[row].stackSize); break; + case SF_SOURCE: + { + // Empty unless the game shipped an unstripped ELF - see Core/Debugger/LineInfo.h. + const std::string source = g_lineInfo.LookupString(frames[row].pc); + wcscpy(dest, source.empty() ? L"-" : ConvertUTF8ToWString(source).c_str()); + } + break; } } From 14b6623330150c29ed5fa30546ff09f89f77c953 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 13:39:07 +0200 Subject: [PATCH 07/12] ImDebugger: Source column on the breakpoint list, and record learnings Adds the source location column to the breakpoint list, the last of the places worth surfacing line info. Exec breakpoints get a real location; memchecks and register breakpoints get "-", since a watched data range and a register aren't tied to a code address. Fixed a pre-existing misalignment found while adding the column: the register breakpoint row never emitted a cell for the Log column, so every following cell sat one to the left - the register name appeared under "Type", the condition under "OpCode" and the hit count under "Cond", with the last column left blank. It has a Log checkbox now like the other two rows (register breakpoints do support the log action), and the register name moved to Size/Label where the memcheck row puts its size. AGENTS.md gets what this stretch of work turned up: - Most files here are CRLF, including every .vcxproj, Android.mk, Makefile.common and AGENTS.md itself. Patching one with a script that reads with universal newlines and writes with newline='' silently rewrites the whole file - it turned a two-line addition into a 5000-line diff, which is invisible in an editor and obvious in git diff --stat. - Don't pipe Python containing backslashes through a bash heredoc; the quoting mangles them and anchors just fail to match for no visible reason. - Headless registers its own debug-output listener, so exception and crash messages never reach the log - they go to stdout, block-buffered when redirected, and taskkill //F discards the buffer instead of flushing. Give the run a short --timeout and let it exit if you need to read a crash trace. - 0xFFFFFFFF decodes to vflush, a real VFPU instruction, so it's useless as "garbage" for testing illegal-instruction handling. - A wsdbg script has to stay connected long enough for what it asked for; ending with :quit straight after cpu.runUntilTime looks exactly like a broken feature. - Where DWARF line info is and isn't available, since it's much narrower than it sounds. - Corrected the note claiming broadcast.config.set only accepts logger and input; it takes all five categories now. UnitTest 55/55. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- AGENTS.md | 35 +++++++++++++++++++++++++++++++++-- UI/ImDebugger/ImDebugger.cpp | 22 +++++++++++++++++----- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0de18cd3e1..4969747446 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,6 +9,16 @@ Ignore the folder ai_instructions in the root directory, it's old stuff from con 1. Keep style changes minimal unless requested. Follow existing code patterns and conventions. 2. Keep cross-platform parity in mind when changing shared code. See below for more multiplatform tips 3. Never `git push` (to any remote) without asking the user first. Committing locally is fine when asked; pushing requires explicit approval. +4. **Most files in this repo are CRLF** - `.vcxproj`, `.vcxproj.filters`, `android/jni/Android.mk`, + `libretro/Makefile.common`, `AGENTS.md`, and much of the source. If you patch one with a script, read *and* + write with `newline=''`; reading with Python's default universal-newline translation and writing with + `newline=''` silently converts the whole file, turning a two-line addition into a 5000-line diff. Check + `git diff --stat` before committing - a whole-file rewrite is obvious there and invisible in the editor. + Prefer the Edit tool, which does exact string replacement and can't do this. +5. **Don't feed Python to `bash -c` via a heredoc when the code contains backslashes.** The quoting mangles them, + and an anchor string like `'...MemBlockInfo.cpp \\\r\n'` silently fails to match, so the patch reports + "anchor missing" for reasons that aren't visible. Write the script to a file and run that instead, building + separators with `chr(92)` if need be. ## Core Safety Checks @@ -341,8 +351,20 @@ A working invocation, and the traps around it: - Response field names are not uniform: `memory.read_u32` answers with `value`, while `cpu.getReg` answers with `uintValue`. A parser defaulting a missing key to 0 will quietly report zeroes - read the handler's comment in `Core/Debugger/WebSocket/*Subscriber.cpp` rather than guessing. -- `broadcast.config.set` currently rejects the `game` and `stepping` keys that `docs/WebSocketDebugger.md` lists, - erroring with "Unsupported 'disallowed' object key". Only `logger` and `input` work. +- `broadcast.config.set` accepts all five categories now (`logger`, `input`, `game`, `stepping`, `breakpoint`); + it used to reject `game` and `stepping` until each had happened to fire once. +- **A script has to keep the connection open long enough for what it asked for to happen.** `cpu.runUntilTime` + followed immediately by `:quit` disconnects before the run even starts, and it looks exactly like the feature + not working. End with a `:wait cpu.stepping `. +- **Exception and crash messages do not reach the log in headless.** It registers its own debug-output listener + (`SendDebugOutput` in `headless/Headless.cpp`) that `fwrite`s to stdout, which is block-buffered when you + redirect it to a file - so the output sits in the CRT buffer while the process runs, and `taskkill //F` throws + it away rather than flushing. To actually read a crash trace, give that run a short `--timeout` and `wait` for + the process to exit on its own. +- **`0xFFFFFFFF` is not an invalid instruction** - it decodes to `vflush`, a real Allegrex VFPU op, so writing it + over code to test illegal-instruction handling just runs it. Check what an encoding actually is with + `memory.disasm` before assuming it's garbage; the interpreter raises `ExecExceptionType::ILLEGAL` only when + `MIPSGetInstruction` has no interpreter for it (`tge`/`tlt`/`teq` and friends). - **To line input injection up with a wall-clock repro, use `cpu.status`'s `us` field** (emulated microseconds), not `ticks`. The PSP's clock frequency is changeable and games do change it - CrossCraft Classic runs at 333MHz, so `ticks / 222000000` is off by a factor of 1.5. `clockHz` is reported alongside. @@ -354,6 +376,15 @@ unstripped ELF next to the EBOOT (`app.elf` alongside `app.prx`, common for Zig/ the function and data names out of it, so the disassembly reads `world.init_empty` instead of `z_un_088c00f0`. prxgen strips the symbol table on the way to the PRX, which is why the loaded module has none of its own. +The same flag also loads DWARF line info from that ELF (`Core/Debugger/LineInfo.h`), so addresses turn into +`mesh.zig:163` in backtraces, crash traces, breakpoint hits and log lines, both call stack views, and the +disassembly status bar. Availability is narrow and worth knowing before relying on it: **PRX conversion strips +every `.debug` section**, verified across all 437 pspautotests `.prx` and CrossCraft's own `app.prx`, and of 24 +installed homebrew EBOOTs *none* carry debug info - CrossCraft only does because it ships `app.elf` separately. +So it's there for homebrew you're developing (or a plain `.elf` you built), never for a commercial game. DWARF 2 +through 4 are decoded (psp-gcc emits 2, Zig 4); v5 re-encoded the file table and its units are skipped with a +warning rather than mis-parsed. + That same file is also a ground-truth oracle for anything the loader computes. It still has the symbol table (so an address can be turned into a function name) and the full `.rel.*` sections *with symbol indices*, which the PRX format throws away. That makes it diff --git a/UI/ImDebugger/ImDebugger.cpp b/UI/ImDebugger/ImDebugger.cpp index 127c268dfb..3d1e8a5e6b 100644 --- a/UI/ImDebugger/ImDebugger.cpp +++ b/UI/ImDebugger/ImDebugger.cpp @@ -1023,7 +1023,7 @@ static void DrawBreakpointsView(MIPSDebugInterface *mipsDebug, ImConfig &cfg) { cfg.selectedBreakpoint = -1; } - if (ImGui::BeginTable("breakpoints", 8, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersH)) { + if (ImGui::BeginTable("breakpoints", 9, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersH)) { ImGui::TableSetupColumn("Enabled", ImGuiTableColumnFlags_WidthFixed); // Really means action is to pause ImGui::TableSetupColumn("Log", ImGuiTableColumnFlags_WidthFixed); // Really means action is to pause ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed); @@ -1031,7 +1031,8 @@ static void DrawBreakpointsView(MIPSDebugInterface *mipsDebug, ImConfig &cfg) { ImGui::TableSetupColumn("Size/Label", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("OpCode", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("Cond", ImGuiTableColumnFlags_WidthFixed); - ImGui::TableSetupColumn("Hits", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Hits", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("Source", ImGuiTableColumnFlags_WidthStretch); ImGui::TableHeadersRow(); for (int i = 0; i < (int)bps.size(); i++) { @@ -1073,6 +1074,9 @@ static void DrawBreakpointsView(MIPSDebugInterface *mipsDebug, ImConfig &cfg) { } ImGui::TableNextColumn(); ImGui::Text("-"); // hits not available on exec bps yet + ImGui::TableNextColumn(); + // Empty unless the game shipped an unstripped ELF - see Core/Debugger/LineInfo.h. + ImGui::TextUnformatted(g_lineInfo.LookupString(bp.addr).c_str()); ImGui::PopID(); } @@ -1103,6 +1107,8 @@ static void DrawBreakpointsView(MIPSDebugInterface *mipsDebug, ImConfig &cfg) { ImGui::TextUnformatted("-"); // cond ImGui::TableNextColumn(); ImGui::Text("%d", mc.numHits); + ImGui::TableNextColumn(); + ImGui::TextUnformatted("-"); // A watched range is data - there's no source line for it. ImGui::PopID(); } @@ -1117,13 +1123,17 @@ static void DrawBreakpointsView(MIPSDebugInterface *mipsDebug, ImConfig &cfg) { cfg.selectedRegBreakpoint = &rbp - &g_breakpoints.GetRegBreakpoints()[0]; } ImGui::SameLine(); - ImGui::CheckboxFlags("", (int *)&rbp.result, BREAK_ACTION_PAUSE); + ImGui::CheckboxFlags("##enabled", (int *)&rbp.result, BREAK_ACTION_PAUSE); + ImGui::TableNextColumn(); + // This row used to skip the Log column entirely, which shifted every following cell + // one to the left - the register name landed under "Type" and Hits under "Cond". + ImGui::CheckboxFlags("##log", (int *)&rbp.result, (int)BREAK_ACTION_LOG); ImGui::TableNextColumn(); ImGui::TextUnformatted("Reg"); ImGui::TableNextColumn(); - ImGui::TextUnformatted(mipsDebug->GetRegName(0, rbp.reg).c_str()); + ImGui::TextUnformatted("-"); // A register breakpoint isn't tied to an address. ImGui::TableNextColumn(); - ImGui::TextUnformatted("-"); // size/label + ImGui::TextUnformatted(mipsDebug->GetRegName(0, rbp.reg).c_str()); // size/label ImGui::TableNextColumn(); ImGui::TextUnformatted("-"); // opcode ImGui::TableNextColumn(); @@ -1134,6 +1144,8 @@ static void DrawBreakpointsView(MIPSDebugInterface *mipsDebug, ImConfig &cfg) { } ImGui::TableNextColumn(); ImGui::Text("%d", rbp.numHits); + ImGui::TableNextColumn(); + ImGui::TextUnformatted("-"); // No address, so no source line either. ImGui::PopID(); } From a6dd949df44371a85d82ea5873ae5c929cf0de6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 13:58:03 +0200 Subject: [PATCH 08/12] Load ELF debug info regardless of the symbol auto-save setting bAutoSaveLoadSymbols is about writing .ppsym files back out and reading them in again. It had also come to gate reading debug info that's simply sitting next to the game, which is a different thing and shouldn't need asking for: the main ELF's own symbols were already loaded unconditionally, but the companion ELF's symbols and all line info were not. Now the ELF is always the baseline - main or companion, symbols and line info - and the setting only adds the .ppsym half on top of it. Line info also loads from the module being loaded, not just from a companion, so an ELF launched directly brings its own. A PRX has no .debug section for it to find (prxgen strips them), so that's a cheap no-op for the usual EBOOT case, which the companion path still covers. That second source needs the two shapes distinguished, so AddModule takes an explicit address delta rather than assuming a base: a companion links at zero and wants the module's base added, while an ELF loaded at the addresses it asked for already has final ones (bRelocate is just e_type != ET_EXEC). Rows that don't land inside the module after that are dropped either way, which is a better check than the old "offset smaller than the module" one. Splitting the companion's identity check out of the symbol loader lets line info reuse it, and drops an accidental requirement along the way: it used to reject any companion without a symbol table, so an ELF built with -g but stripped of its symbols would have contributed no line numbers either. Verified with --auto-save-load-symbols off: CrossCraft's companion app.elf loads 3734 symbols and 98383 line rows where it previously loaded neither. The direct-ELF path is not verified at runtime - it needs a bootable ELF that carries DWARF, and there isn't one to hand. Both candidates here (pspautotests' .elf builds and CrossCraft's own app.elf) are linked at address 0 and fail to boot on that alone, which is pre-existing loader behaviour and nothing to do with this. pspautotests 314/314, UnitTest 55/55. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- Core/Debugger/LineInfo.cpp | 15 ++++---- Core/Debugger/LineInfo.h | 12 ++++--- Core/ELF/ElfReader.cpp | 68 ++++++++++++++++++++++++------------ Core/ELF/ElfReader.h | 8 +++-- Core/HLE/sceKernelModule.cpp | 21 ++++++++--- 5 files changed, 84 insertions(+), 40 deletions(-) diff --git a/Core/Debugger/LineInfo.cpp b/Core/Debugger/LineInfo.cpp index 16526b4b2a..412ff99bec 100644 --- a/Core/Debugger/LineInfo.cpp +++ b/Core/Debugger/LineInfo.cpp @@ -148,7 +148,7 @@ enum { // One .debug_line unit: header, then a bytecode program that walks a virtual machine whose output // rows are (address, file, line). See the DWARF spec, "Line Number Information". static bool ParseUnit(Reader &r, size_t unitEnd, std::vector *entries, - std::vector *files, std::map *fileIndex, u32 moduleStart, u32 moduleSize) { + std::vector *files, std::map *fileIndex, u32 moduleStart, u32 moduleSize, u32 addressDelta) { const uint16_t version = r.U16(); if (version < 2 || version > 4) { // v5 rewrote the file table to use form-coded entries, which is a different parser. Nothing @@ -208,12 +208,13 @@ static bool ParseUnit(Reader &r, size_t unitEnd, std::vector *entries bool sawAddress = false; auto emit = [&](u32 lineNo) { - // Rows before a DW_LNE_set_address belong to no real code; and anything outside the module - // we're relocating into would only produce bogus lookups. - if (!sawAddress || address > moduleSize) + // Rows before a DW_LNE_set_address belong to no real code, and anything that doesn't land + // inside the module after relocation would only produce bogus lookups. + const u32 finalAddress = addressDelta + address; + if (!sawAddress || finalAddress < moduleStart || finalAddress - moduleStart >= moduleSize) return; LineEntry e; - e.address = moduleStart + address; + e.address = finalAddress; e.line = lineNo; e.fileIndex = file < unitFiles.size() ? unitFiles[file] : 0; entries->push_back(e); @@ -282,7 +283,7 @@ static bool ParseUnit(Reader &r, size_t unitEnd, std::vector *entries return r.ok(); } -int LineInfoMap::AddModule(std::string_view elfData, u32 moduleStart, u32 moduleSize) { +int LineInfoMap::AddModule(std::string_view elfData, u32 moduleStart, u32 moduleSize, u32 addressDelta) { RemoveModule(moduleStart, moduleSize); const uint8_t *data = (const uint8_t *)elfData.data(); @@ -345,7 +346,7 @@ int LineInfoMap::AddModule(std::string_view elfData, u32 moduleStart, u32 module if (unitEnd > debugLine->sh_size) break; - if (!ParseUnit(r, unitEnd, &mod.entries, &mod.files, &fileIndex, moduleStart, moduleSize)) + if (!ParseUnit(r, unitEnd, &mod.entries, &mod.files, &fileIndex, moduleStart, moduleSize, addressDelta)) skippedUnits++; r.Seek(unitEnd); } diff --git a/Core/Debugger/LineInfo.h b/Core/Debugger/LineInfo.h index 61f013fe18..e42bebad4f 100644 --- a/Core/Debugger/LineInfo.h +++ b/Core/Debugger/LineInfo.h @@ -45,10 +45,14 @@ struct LineEntry { class LineInfoMap { public: - // Parses .debug_line out of an unstripped ELF image and relocates it to moduleStart. - // Returns the number of rows kept, or 0 if the ELF has nothing usable. Replaces whatever was - // held for the same module. - int AddModule(std::string_view elfData, u32 moduleStart, u32 moduleSize); + // Parses .debug_line out of an unstripped ELF image. Returns the number of rows kept, or 0 if + // the ELF has nothing usable. Replaces whatever was held for the same module. + // + // addressDelta is added to every address in the table, and rows that don't then land inside + // the module are dropped. That covers both shapes this arrives in: a companion ELF links at + // zero, so the delta is the module's base; an ELF launched directly and loaded where it asked + // to be already has final addresses, so the delta is zero. + int AddModule(std::string_view elfData, u32 moduleStart, u32 moduleSize, u32 addressDelta); // Keyed the same way SymbolMap::UnloadModule is, so that unloading one module drops only its // own lines. Each module owns its rows and its file names outright - there's no shared table diff --git a/Core/ELF/ElfReader.cpp b/Core/ELF/ElfReader.cpp index 961a83b9bd..068e06c3cb 100644 --- a/Core/ELF/ElfReader.cpp +++ b/Core/ELF/ElfReader.cpp @@ -830,47 +830,62 @@ bool ElfReader::LoadSymbols() // Adds the STT_FUNC/STT_OBJECT symbols from one candidate ELF, if it looks like it belongs to a // module of this size. Returns the number added, 0 if it doesn't match or has nothing to offer. -static int LoadSymbolsFromCompanion(const std::string &data, u32 moduleBase, u32 moduleSize, const char **why) { +// Does this ELF describe the module we just loaded? Split out from the symbol loader so line info +// can reuse it: the two want the same identity check but different sections, and an ELF built with +// -g but stripped of its symbol table still has usable line numbers. +static bool CompanionElfMatchesModule(const std::string &data, u32 moduleSize, const char **why) { *why = "too small"; if (data.size() < sizeof(Elf32_Ehdr)) - return 0; + return false; const Elf32_Ehdr *header = (const Elf32_Ehdr *)data.data(); *why = "not an ELF"; if (header->e_ident[EI_MAG0] != ELFMAG0 || header->e_ident[EI_MAG1] != ELFMAG1 || header->e_ident[EI_MAG2] != ELFMAG2 || header->e_ident[EI_MAG3] != ELFMAG3) - return 0; + return false; if (header->e_ident[EI_CLASS] != ELFCLASS32) - return 0; + return false; *why = "no section headers"; if (!header->e_shoff || header->e_shentsize < sizeof(Elf32_Shdr)) - return 0; + return false; if ((size_t)header->e_shoff + (size_t)header->e_shnum * header->e_shentsize > data.size()) - return 0; - - auto section = [&](int i) { - return (const Elf32_Shdr *)(data.data() + header->e_shoff + (size_t)i * header->e_shentsize); - }; + return false; // Identity check. The companion links at base 0 and covers the same image the module was // built into, so the top of its highest section should land within a page of the module's // size. Without this an unrelated ELF sitting in the same folder would happily contribute // nonsense names at real addresses, which is worse than having none. u32 top = 0; - int symtabIndex = -1; for (int i = 0; i < header->e_shnum; i++) { - const Elf32_Shdr *s = section(i); + const Elf32_Shdr *s = (const Elf32_Shdr *)(data.data() + header->e_shoff + (size_t)i * header->e_shentsize); if (s->sh_addr) top = std::max(top, s->sh_addr + s->sh_size); - if (s->sh_type == SHT_SYMTAB) + } + *why = "image size doesn't match the loaded module"; + if (top > moduleSize || top + 0x1000 < moduleSize) + return false; + + *why = "ok"; + return true; +} + +static int LoadSymbolsFromCompanion(const std::string &data, u32 moduleBase, u32 moduleSize, const char **why) { + if (!CompanionElfMatchesModule(data, moduleSize, why)) + return 0; + + const Elf32_Ehdr *header = (const Elf32_Ehdr *)data.data(); + auto section = [&](int i) { + return (const Elf32_Shdr *)(data.data() + header->e_shoff + (size_t)i * header->e_shentsize); + }; + + int symtabIndex = -1; + for (int i = 0; i < header->e_shnum; i++) { + if (section(i)->sh_type == SHT_SYMTAB) symtabIndex = i; } *why = "no symbol table"; if (symtabIndex < 0) return 0; - *why = "image size doesn't match the loaded module"; - if (top > moduleSize || top + 0x1000 < moduleSize) - return 0; const Elf32_Shdr *symtab = section(symtabIndex); if (symtab->sh_link >= header->e_shnum || symtab->sh_entsize < sizeof(Elf32_Sym)) @@ -915,7 +930,7 @@ static int LoadSymbolsFromCompanion(const std::string &data, u32 moduleBase, u32 return added; } -int LoadCompanionElfSymbols(const Path &gameFile, u32 moduleBase, u32 moduleSize) { +int LoadCompanionElfDebugInfo(const Path &gameFile, u32 moduleBase, u32 moduleSize) { if (gameFile.empty() || gameFile.Type() != PathType::NATIVE) return 0; @@ -931,16 +946,23 @@ int LoadCompanionElfSymbols(const Path &gameFile, u32 moduleBase, u32 moduleSize if (!File::ReadBinaryFileToString(file.fullName, &data)) continue; const char *why = ""; + if (!CompanionElfMatchesModule(data, moduleSize, &why)) { + DEBUG_LOG(Log::Loader, "Companion ELF '%s' skipped: %s", file.name.c_str(), why); + continue; + } + + // A companion links at base 0, so its line table needs the module's base added. + const int lines = g_lineInfo.AddModule(data, moduleBase, moduleSize, moduleBase); + const int added = LoadSymbolsFromCompanion(data, moduleBase, moduleSize, &why); - if (added > 0) { - INFO_LOG(Log::Loader, "Loaded %d symbols from companion ELF '%s'", added, file.name.c_str()); + if (added > 0) g_symbolMap->SortSymbols(); - // Same file, already validated as belonging to this module, so its DWARF line table - // relocates the same way. Absent from anything built without -g, which is fine. - g_lineInfo.AddModule(data, moduleBase, moduleSize); + + if (lines > 0 || added > 0) { + INFO_LOG(Log::Loader, "Companion ELF '%s': %d symbols, %d line rows", file.name.c_str(), added, lines); return added; } - DEBUG_LOG(Log::Loader, "Companion ELF '%s' skipped: %s", file.name.c_str(), why); + DEBUG_LOG(Log::Loader, "Companion ELF '%s' matched but had nothing usable: %s", file.name.c_str(), why); } return 0; } diff --git a/Core/ELF/ElfReader.h b/Core/ELF/ElfReader.h index 2ded92d77f..132a7f8669 100644 --- a/Core/ELF/ElfReader.h +++ b/Core/ELF/ElfReader.h @@ -174,5 +174,9 @@ private: // This looks for such a companion in the game's own directory and, if one plausibly belongs to // this module, adds its function and data symbols at the module's load address. // -// Returns the number of symbols added, 0 if no matching ELF was found. -int LoadCompanionElfSymbols(const Path &gameFile, u32 moduleBase, u32 moduleSize); +// Symbols and DWARF line info both come out of that file, and both load unconditionally - +// bAutoSaveLoadSymbols governs writing .ppsym files back out, not reading debug info that's +// already sitting next to the game. Same reason the main ELF's own symbols aren't gated either. +// +// Returns the number of symbols added, 0 if none were or no matching ELF was found. +int LoadCompanionElfDebugInfo(const Path &gameFile, u32 moduleBase, u32 moduleSize); diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index 1483864e16..9adbc9f92f 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -1371,15 +1371,28 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load if (module->memoryBlockAddr != 0) { g_symbolMap->AddModule(moduleName, module->memoryBlockAddr, module->memoryBlockSize, module->crc); + + // Line info out of the module we just loaded. That covers an ELF launched directly - + // pspautotests' .elf builds, or homebrew you built yourself - where the debug sections are + // right here in the file. A PRX has none (prxgen strips every .debug section), so it's a + // cheap no-op for the usual EBOOT case, which the companion below handles instead. + // A relocated module's ELF addresses are relative to where it ended up; one loaded at the + // addresses it asked for already has final ones. + const u32 lineDelta = reader.DidRelocate() ? reader.GetVaddr() : 0; + g_lineInfo.AddModule(std::string_view((const char *)ptr, elfSize), module->memoryBlockAddr, module->memoryBlockSize, lineDelta); + + // Homebrew commonly ships the unstripped ELF next to the EBOOT; prxgen strips the symbols + // out of the PRX we actually load, so without this every function in it is just + // z_un_
. See LoadCompanionElfDebugInfo. + LoadCompanionElfDebugInfo(PSP_CoreParameter().fileToStart, module->memoryBlockAddr, module->memoryBlockSize); + + // Only the .ppsym files follow the setting - it's about writing symbols back out, not about + // reading debug info that's already sitting next to the game. if (g_Config.bAutoSaveLoadSymbols) { int idx = g_symbolMap->GetModuleIndexByName(moduleName); if (idx > 0) { g_symbolMap->LoadModuleSymbols(idx, SymbolMap::GetModuleSymbolsPath(moduleName, module->crc)); } - // Homebrew commonly ships the unstripped ELF next to the EBOOT; prxgen strips the - // symbols out of the PRX we actually load, so without this every function in it is - // just z_un_
. See LoadCompanionElfSymbols. - LoadCompanionElfSymbols(PSP_CoreParameter().fileToStart, module->memoryBlockAddr, module->memoryBlockSize); } } From 4ffbe80d76723bacc91ade76a43b24b450a0c150 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 14:07:57 +0200 Subject: [PATCH 09/12] Reload companion ELF debug info after a savestate load too Modules are torn down and re-registered from PSPModule::DoState when a state is loaded, which takes their symbols and line info with them. That path read the per-module .ppsym file and nothing else, so coming back from a savestate lost everything the companion ELF had contributed - every function back to z_un_
, and no line numbers at all - with no way to get it back short of rebooting the game. It reads the companion again now, on the same terms as the initial load: unconditionally, since the file is still sitting next to the game and only the .ppsym half was ever meant to depend on the setting. Costs a re-read and re-parse of the companion on every state load for games that have one (CrossCraft: 3734 symbols and 98383 line rows), which is the price of not silently losing them. Line info that came from the main ELF rather than a companion still doesn't survive a state load - those bytes aren't around at that point. Nothing to do about that here, and it doesn't apply to the EBOOT case, where the companion is the only source anyway. pspautotests 314/314, UnitTest 55/55. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- Core/HLE/sceKernelModule.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index 9adbc9f92f..063140197f 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -309,6 +309,10 @@ void PSPModule::DoState(PointerWrap &p) { truncate_cpy(moduleName, nm.name); if (memoryBlockAddr != 0) { g_symbolMap->AddModule(moduleName, memoryBlockAddr, memoryBlockSize, crc); + // Loading a state tears the old module down and re-registers it here, which takes its + // symbols and line info with it. The companion ELF is still sitting next to the game, + // so read it again rather than coming back from a savestate with none. + LoadCompanionElfDebugInfo(PSP_CoreParameter().fileToStart, memoryBlockAddr, memoryBlockSize); if (g_Config.bAutoSaveLoadSymbols) { int idx = g_symbolMap->GetModuleIndexByName(moduleName); if (idx > 0) { From 34637895970b09b7a96834dfffd3d3d478417635 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 14:19:58 +0200 Subject: [PATCH 10/12] Find the companion ELF when a game is launched by folder, and keep line info Two things kept the companion ELF from doing its job. The first is the one that mattered: fileToStart is the game's own *directory* for folder-launched homebrew (IdentifiedFileType::PSP_PBP_DIRECTORY), which is the normal case when you pick a homebrew in the UI. The search navigated up from it regardless, landing in PSP/GAME and listing sibling games - all directories, all skipped - so app.elf sitting right next to the EBOOT was never found. It only ever worked when the path pointed at the EBOOT itself, which is how headless is invoked, which is why it looked fine from there. Searches the directory itself now when that's what it's given. The second: line info didn't survive loading a savestate. Modules aren't just re-registered there, they're destroyed and rebuilt (KernelObjectPool::Clear), so removing a module's lines in ~PSPModule threw the table away on every state load. The previous commit worked around it by re-reading the companion, which was both wasteful and no help at all to an ELF launched directly - those bytes are long gone by then. SymbolMap already solves this and line info now does it the same way: keep what you have, and let whatever next claims the address range replace it. AddModule replaces by key and is called for every module load, including ones with no line info of their own, so a range gets retired when it's genuinely reused. The whole table goes when the game does, in PSP_Shutdown. That also means the savestate path has nothing to re-read, so state loads no longer pay to re-parse a multi-megabyte ELF. The tradeoff is a window between a module unloading and its range being reclaimed where a lookup can still answer for it. For a debugger that's a stale file:line on an address nothing owns, against certain and total loss on every state load. Verified with --auto-save-load-symbols off, launched both ways: by directory (the case that was broken) and by EBOOT path, both give 3734 symbols and 98383 line rows. pspautotests 314/314, UnitTest 55/55. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- Core/Debugger/LineInfo.h | 8 +++++--- Core/ELF/ElfReader.cpp | 7 ++++++- Core/HLE/sceKernelModule.cpp | 18 ++++++++++++------ Core/System.cpp | 4 ++++ 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/Core/Debugger/LineInfo.h b/Core/Debugger/LineInfo.h index e42bebad4f..4e3993b29b 100644 --- a/Core/Debugger/LineInfo.h +++ b/Core/Debugger/LineInfo.h @@ -54,9 +54,11 @@ public: // to be already has final addresses, so the delta is zero. int AddModule(std::string_view elfData, u32 moduleStart, u32 moduleSize, u32 addressDelta); - // Keyed the same way SymbolMap::UnloadModule is, so that unloading one module drops only its - // own lines. Each module owns its rows and its file names outright - there's no shared table - // for an unload to have to pick apart. + // Each module owns its rows and its file names outright, so dropping one can never disturb + // another's. Note this isn't called when a module unloads: a savestate load destroys and + // rebuilds every kernel object, and doing it there discarded the table every time - AddModule + // replacing by key is what retires a range instead, when something else claims it. See + // ~PSPModule. void RemoveModule(u32 moduleStart, u32 moduleSize); void Clear(); diff --git a/Core/ELF/ElfReader.cpp b/Core/ELF/ElfReader.cpp index 068e06c3cb..770bc7f155 100644 --- a/Core/ELF/ElfReader.cpp +++ b/Core/ELF/ElfReader.cpp @@ -934,7 +934,12 @@ int LoadCompanionElfDebugInfo(const Path &gameFile, u32 moduleBase, u32 moduleSi if (gameFile.empty() || gameFile.Type() != PathType::NATIVE) return 0; - const Path dir = gameFile.NavigateUp(); + // fileToStart is the game's own directory for folder-launched homebrew + // (IdentifiedFileType::PSP_PBP_DIRECTORY - the normal case when you pick one in the UI), and + // the EBOOT/ISO itself otherwise. Navigating up from a directory lands in PSP/GAME and lists + // sibling *games*, so the companion right there next to the EBOOT was never found - which is + // exactly the interactive case this exists for. + const Path dir = File::IsDirectory(gameFile) ? gameFile : gameFile.NavigateUp(); std::vector files; if (!File::GetFilesInDir(dir, &files, "elf:")) return 0; diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index 063140197f..da425070ea 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -211,8 +211,14 @@ PSPModule::~PSPModule() { userMemory.Free(memoryBlockAddr); } g_symbolMap->UnloadModule(memoryBlockAddr, memoryBlockSize); - // Keyed identically, so a module going away takes its own line info and nothing else's. - g_lineInfo.RemoveModule(memoryBlockAddr, memoryBlockSize); + // Deliberately *not* dropping this module's line info here. Loading a savestate deletes + // every kernel object and rebuilds it (KernelObjectPool::Clear), so removing on destruction + // threw the line table away every time a state was loaded - and for an ELF launched + // directly there's no file left to read it back from. SymbolMap has the same problem and + // solves it the same way: keep what you have, and let the module that next claims the + // address range replace it (LineInfoMap::AddModule replaces by key, and it's called for + // every module load whether or not that module has any line info to add). The whole thing + // is dropped when the game does, in PSP_Shutdown. } if (modulePtr.ptr) { @@ -308,11 +314,11 @@ void PSPModule::DoState(PointerWrap &p) { char moduleName[29] = { 0 }; truncate_cpy(moduleName, nm.name); if (memoryBlockAddr != 0) { + // Re-registering is enough to bring both back: SymbolMap keeps every symbol it has ever + // seen and just rebuilds its active view from the loaded modules, and line info is no + // longer dropped when a module is destroyed (see ~PSPModule). So there's nothing to + // re-read here, and a state load doesn't pay for re-parsing the companion ELF. g_symbolMap->AddModule(moduleName, memoryBlockAddr, memoryBlockSize, crc); - // Loading a state tears the old module down and re-registers it here, which takes its - // symbols and line info with it. The companion ELF is still sitting next to the game, - // so read it again rather than coming back from a savestate with none. - LoadCompanionElfDebugInfo(PSP_CoreParameter().fileToStart, memoryBlockAddr, memoryBlockSize); if (g_Config.bAutoSaveLoadSymbols) { int idx = g_symbolMap->GetModuleIndexByName(moduleName); if (idx > 0) { diff --git a/Core/System.cpp b/Core/System.cpp index 84ad473695..721b41e6d0 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -50,6 +50,7 @@ #include "Core/MIPS/MIPS.h" #include "Core/MIPS/MIPSAnalyst.h" #include "Core/MIPS/MIPSVFPUUtils.h" +#include "Core/Debugger/LineInfo.h" #include "Core/Debugger/SymbolMap.h" #include "Core/System.h" #include "Core/HLE/HLE.h" @@ -626,6 +627,9 @@ void CPU_Shutdown(bool success) { g_CoreParameter.mountIsoLoader = nullptr; delete g_symbolMap; g_symbolMap = nullptr; + // Line info outlives individual modules on purpose (see ~PSPModule), so the game going away is + // what ends it. + g_lineInfo.Clear(); g_lua.Shutdown(); From 82dd963df6bfaa4bef689c3ce0708464c358a672 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 14:26:09 +0200 Subject: [PATCH 11/12] ImDebugger: sort the symbol list by name The symbol map hands symbols over in address order, which is fine for the disassembly but meaningless to browse - CrossCraft has 3734 functions and scrolling for one is just a wall of text. Sorted where you suggested, in the match list that already backs the filter: it's rebuilt only when the filter text or the symbol map changes, so this costs nothing per frame, and sorting the indices rather than symCache_ itself leaves selectedSymbol_ pointing at the cache, so a selection survives filtering and the Edit Symbol box above the list keeps working. Case-insensitive, with ties broken by address so the order can't wobble between rebuilds. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GZq8ZtJmFY7bkX5FVkr3P9 --- UI/ImDebugger/ImDisasmView.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/UI/ImDebugger/ImDisasmView.cpp b/UI/ImDebugger/ImDisasmView.cpp index 3842da2682..108b07b89e 100644 --- a/UI/ImDebugger/ImDisasmView.cpp +++ b/UI/ImDebugger/ImDisasmView.cpp @@ -1356,6 +1356,16 @@ void ImDisasmWindow::Draw(MIPSDebugInterface *mipsDebug, ImConfig &cfg, ImContro if (symFilter_[0] == '\0' || containsNoCase(symCache_[i].name, symFilter_)) symMatches_.push_back(i); } + // By name, because that's what you're reading when you scroll this. The symbol map + // hands them over in address order, which is meaningless to browse - a game with a few + // thousand functions is just a wall. Sorting the match list rather than symCache_ + // leaves selectedSymbol_ indexing the cache, so a selection survives filtering, and + // this only runs on a rebuild rather than per frame. + std::sort(symMatches_.begin(), symMatches_.end(), [this](int a, int b) { + const int cmp = strcasecmp(symCache_[a].name.c_str(), symCache_[b].name.c_str()); + // Ties broken by address so the order can't wobble between rebuilds. + return cmp != 0 ? cmp < 0 : symCache_[a].address < symCache_[b].address; + }); } if (ImGui::BeginListBox("##symbols", ImGui::GetContentRegionAvail())) { From cd5cf87120f172d762f37a1fbf7258305836eade Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 18 Aug 2026 14:31:13 +0200 Subject: [PATCH 12/12] Fix performance bug in IRJit when using rewind states --- Core/MIPS/IR/IRFrontend.cpp | 4 +++- GPU/ge_constants.h | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Core/MIPS/IR/IRFrontend.cpp b/Core/MIPS/IR/IRFrontend.cpp index bfd334ca88..4f14d4aa60 100644 --- a/Core/MIPS/IR/IRFrontend.cpp +++ b/Core/MIPS/IR/IRFrontend.cpp @@ -51,7 +51,9 @@ void IRFrontend::DoState(PointerWrap &p) { Do(p, js.startDefaultPrefix); if (s >= 2) { Do(p, js.hasSetRounding); - js.lastSetRounding = 0; + if (p.mode == p.MODE_READ) { + js.lastSetRounding = 0; + } } else { js.hasSetRounding = 1; } diff --git a/GPU/ge_constants.h b/GPU/ge_constants.h index c065bb5a99..779faa6e81 100644 --- a/GPU/ge_constants.h +++ b/GPU/ge_constants.h @@ -336,7 +336,7 @@ enum GEVertexType : uint32_t { }; #define GE_CLEARMODE_COLOR (1<<8) -#define GE_CLEARMODE_ALPHA (1<<9) //or stencil? +#define GE_CLEARMODE_ALPHA (1<<9) // and stencil #define GE_CLEARMODE_Z (1<<10) #define GE_CLEARMODE_ALL (GE_CLEARMODE_COLOR|GE_CLEARMODE_ALPHA|GE_CLEARMODE_Z)