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/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.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/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/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/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/Debugger/LineInfo.cpp b/Core/Debugger/LineInfo.cpp new file mode 100644 index 0000000000..412ff99bec --- /dev/null +++ b/Core/Debugger/LineInfo.cpp @@ -0,0 +1,422 @@ +// 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, 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 + // 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 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 = finalAddress; + 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, u32 addressDelta) { + 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, addressDelta)) + 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..4e3993b29b --- /dev/null +++ b/Core/Debugger/LineInfo.h @@ -0,0 +1,87 @@ +// 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. 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); + + // 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(); + + 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/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/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..770bc7f155 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" @@ -829,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)) @@ -914,11 +930,16 @@ 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; - 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; @@ -930,13 +951,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(); + + 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/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/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index fefd8bb69b..da425070ea 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,14 @@ PSPModule::~PSPModule() { userMemory.Free(memoryBlockAddr); } g_symbolMap->UnloadModule(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) { @@ -305,6 +314,10 @@ 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); if (g_Config.bAutoSaveLoadSymbols) { int idx = g_symbolMap->GetModuleIndexByName(moduleName); @@ -1368,15 +1381,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); } } 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/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/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(); 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) 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..3d1e8a5e6b 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" @@ -1022,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); @@ -1030,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++) { @@ -1072,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(); } @@ -1102,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(); } @@ -1116,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(); @@ -1133,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(); } @@ -1891,13 +1904,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 +1935,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++; @@ -2934,6 +2951,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/ImDisasmView.cpp b/UI/ImDebugger/ImDisasmView.cpp index 7b325298c5..108b07b89e 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" @@ -64,7 +65,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 +75,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 +589,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? @@ -775,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(); } @@ -818,7 +835,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 +949,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(); } @@ -962,6 +985,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) { @@ -1129,10 +1159,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()); } @@ -1296,6 +1326,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 +1341,39 @@ 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); + } + // 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())) { 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..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_; }; @@ -221,6 +224,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]{}; }; 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; 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/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; } } 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 f3e789ee47..7ad9503a3d 100644 --- a/docs/WebSocketDebugger.md +++ b/docs/WebSocketDebugger.md @@ -132,6 +132,69 @@ 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: + +```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 @@ -173,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"`: @@ -206,7 +270,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` | 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 \