Add GDB stub for debugging (#657)

* Implement GDB stub debugger

Can be enabled by using the "--enable-gdbstub" option (and the debugger GUI, although that's untested) which'll pause any game you launch at start-up. Will start at port 1337 although it'll eventually be user-editable. The code is a bit weirdly sorted and also just needs a general cleanup, so expect that eventually too. And uses egyptian braces but formatting was easier to do at the end, so that's also something to do.

It has been tested to work with IDA Pro, Clion and the standalone interface for now, but I plan on writing some instructions in the PR to follow for people who want to use this. Memory breakpoints aren't possible yet, only execution breakpoints.

This code was aimed to be decoupled from the existing debugger to be able to be ported to the Wii U for an equal debugging experience. That's also why it uses the Cafe OS's thread sleep and resuming functions whenever possible instead of using recompiler/interpreter controls.

* Add memory writing and floating point registers support

* Reformat code a bit

* Format code to adhere to Cemu's coding style

* Rework GDB Stub settings in GUI

* Small styling fixes

* Rework execution breakpoints

Should work better in some edge cases now. But this should also allow for adding access breakpoints since it's now more separated.

* Implement access breakpoints

* Fix some issues with breakpoints

* Fix includes for Linux

* Fix unnecessary include

* Tweaks for Linux compatibility

* Use std::thread instead of std::jthread to fix MacOS support

* Enable GDB read/write breakpoints on x86 only

* Fix compilation for GCC compilers at least

The thread type varies on some platforms, so supporting this is hell... but let's get it to compile on MacOS first.

* Disable them for MacOS due to lack of ptrace

---------

Co-authored-by: Exzap <13877693+Exzap@users.noreply.github.com>
This commit is contained in:
Crementif
2023-02-19 15:41:49 +01:00
committed by GitHub
co-authored by Exzap
parent 05d82b09e9
commit 6d75776b28
28 changed files with 1765 additions and 59 deletions
+1
View File
@@ -17,6 +17,7 @@
.idea/
build/
cmake-build-*-*/
out/
.cache/
bin/Cemu_*
+2 -2
View File
@@ -10,13 +10,13 @@ It's written in C/C++ and is being actively developed with new features and fixe
Cemu is currently only available for 64-bit Windows, Linux & macOS devices.
### Links:
- [Original 2.0 announcement post](https://www.reddit.com/r/cemu/comments/wwa22c/cemu_20_announcement_linux_builds_opensource_and/)
- [Open Source Announcement](https://www.reddit.com/r/cemu/comments/wwa22c/cemu_20_announcement_linux_builds_opensource_and/)
- [Official Website](https://cemu.info)
- [Compatibility List/Wiki](https://wiki.cemu.info/wiki/Main_Page)
- [Official Subreddit](https://reddit.com/r/Cemu)
- [Official Discord](https://discord.gg/5psYsup)
- [Official Matrix Server](https://matrix.to/#/#cemu:cemu.info)
- [Unofficial Setup Guide](https://cemu.cfw.guide)
- [Setup Guide](https://cemu.cfw.guide)
#### Other relevant repositories:
- [Cemu-Language](https://github.com/cemu-project/Cemu-Language)
+3
View File
@@ -38,6 +38,9 @@ add_library(CemuCafe
HW/Espresso/Debugger/Debugger.h
HW/Espresso/Debugger/DebugSymbolStorage.cpp
HW/Espresso/Debugger/DebugSymbolStorage.h
HW/Espresso/Debugger/GDBStub.h
HW/Espresso/Debugger/GDBStub.cpp
HW/Espresso/Debugger/GDBBreakpoints.h
HW/Espresso/EspressoISA.h
HW/Espresso/Interpreter/PPCInterpreterALU.hpp
HW/Espresso/Interpreter/PPCInterpreterFPU.cpp
+6
View File
@@ -30,6 +30,7 @@
#include "GamePatch.h"
#include <time.h>
#include "HW/Espresso/Debugger/GDBStub.h"
#include "Cafe/IOSU/legacy/iosu_ioctl.h"
#include "Cafe/IOSU/legacy/iosu_act.h"
@@ -398,6 +399,11 @@ void cemu_initForGame()
InfoLog_PrintActiveSettings();
Latte_Start();
// check for debugger entrypoint bp
if (g_gdbstub)
{
g_gdbstub->HandleEntryStop(_entryPoint);
g_gdbstub->Initialize();
}
debugger_handleEntryBreakpoint(_entryPoint);
// load graphic packs
forceLog_printf("------- Activate graphic packs -------");
+20 -9
View File
@@ -103,7 +103,7 @@ void debugger_updateExecutionBreakpoint(uint32 address, bool forceRestore)
if (bpItr->enabled && forceRestore == false)
{
// write TW instruction to memory
debugger_updateMemoryU32(address, (31 << 26) | (4 << 1));
debugger_updateMemoryU32(address, DEBUGGER_BP_T_DEBUGGER_TW);
return;
}
else
@@ -171,14 +171,25 @@ void debugger_updateMemoryBreakpoint(DebuggerBreakpoint* bp)
{
ctx.Dr0 = (DWORD64)memory_getPointerFromVirtualOffset(bp->address);
ctx.Dr1 = (DWORD64)memory_getPointerFromVirtualOffset(bp->address);
ctx.Dr7 = 1 | (1 << 16) | (3 << 18); // enable dr0, track write, 4 byte length
ctx.Dr7 |= (4 | (3 << 20) | (3 << 22)); // enable dr1, track read+write, 4 byte length
// breakpoint 0
SetBits(ctx.Dr7, 0, 1, 1); // breakpoint #0 enabled: true
SetBits(ctx.Dr7, 16, 2, 1); // breakpoint #0 condition: 1 (write)
SetBits(ctx.Dr7, 18, 2, 3); // breakpoint #0 length: 3 (4 bytes)
// breakpoint 1
SetBits(ctx.Dr7, 2, 1, 1); // breakpoint #1 enabled: true
SetBits(ctx.Dr7, 20, 2, 3); // breakpoint #1 condition: 3 (read & write)
SetBits(ctx.Dr7, 22, 2, 3); // breakpoint #1 length: 3 (4 bytes)
}
else
{
ctx.Dr0 = (DWORD64)0;
ctx.Dr1 = (DWORD64)0;
ctx.Dr7 = 0; // disable dr0
// breakpoint 0
SetBits(ctx.Dr7, 0, 1, 0); // breakpoint #0 enabled: false
SetBits(ctx.Dr7, 16, 2, 0); // breakpoint #0 condition: 1 (write)
SetBits(ctx.Dr7, 18, 2, 0); // breakpoint #0 length: 3 (4 bytes)
// breakpoint 1
SetBits(ctx.Dr7, 2, 1, 0); // breakpoint #1 enabled: false
SetBits(ctx.Dr7, 20, 2, 0); // breakpoint #1 condition: 3 (read & write)
SetBits(ctx.Dr7, 22, 2, 0); // breakpoint #1 length: 3 (4 bytes)
}
SetThreadContext(hThread, &ctx);
ResumeThread(hThread);
@@ -188,10 +199,10 @@ void debugger_updateMemoryBreakpoint(DebuggerBreakpoint* bp)
#endif
}
void debugger_handleSingleStepException(uint32 drMask)
void debugger_handleSingleStepException(uint64 dr6)
{
bool triggeredDR0 = (drMask & (1 << 0)) != 0; // write
bool triggeredDR1 = (drMask & (1 << 1)) != 0; // read
bool triggeredDR0 = GetBits(dr6, 0, 1); // write
bool triggeredDR1 = GetBits(dr6, 1, 1); // read and write
bool catchBP = false;
if (triggeredDR0 && triggeredDR1)
{
+3 -5
View File
@@ -3,11 +3,6 @@
#include <set>
#include "Cafe/HW/Espresso/PPCState.h"
//#define DEBUGGER_BP_TYPE_NORMAL (1<<0) // normal breakpoint
//#define DEBUGGER_BP_TYPE_ONE_SHOT (1<<1) // normal breakpoint
//#define DEBUGGER_BP_TYPE_MEMORY_READ (1<<2) // memory breakpoint
//#define DEBUGGER_BP_TYPE_MEMORY_WRITE (1<<3) // memory breakpoint
#define DEBUGGER_BP_T_NORMAL 0 // normal breakpoint
#define DEBUGGER_BP_T_ONE_SHOT 1 // normal breakpoint, deletes itself after trigger (used for stepping)
#define DEBUGGER_BP_T_MEMORY_READ 2 // memory breakpoint
@@ -16,6 +11,9 @@
#define DEBUGGER_BP_T_GDBSTUB 1 // breakpoint created by GDBStub
#define DEBUGGER_BP_T_DEBUGGER 2 // breakpoint created by Cemu's debugger
#define DEBUGGER_BP_T_GDBSTUB_TW 0x7C010008
#define DEBUGGER_BP_T_DEBUGGER_TW 0x7C020008
struct DebuggerBreakpoint
{
@@ -0,0 +1,286 @@
#include <utility>
#if BOOST_OS_LINUX
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <sys/user.h>
// helpers for accessing debug register
typedef unsigned long DRType;
DRType _GetDR(pid_t tid, int drIndex)
{
unsigned long v;
v = ptrace (PTRACE_PEEKUSER, tid, offsetof (struct user, u_debugreg[drIndex]), 0);
return (DRType)v;
}
void _SetDR(pid_t tid, int drIndex, DRType newValue)
{
unsigned long v = newValue;
ptrace (PTRACE_POKEUSER, tid, offsetof (struct user, u_debugreg[drIndex]), v);
}
#endif
namespace coreinit
{
std::vector<std::thread::native_handle_type>& OSGetSchedulerThreads();
}
enum class BreakpointType
{
BP_SINGLE,
BP_PERSISTENT,
BP_RESTORE_POINT,
BP_STEP_POINT
};
class GDBServer::ExecutionBreakpoint {
public:
ExecutionBreakpoint(MPTR address, BreakpointType type, bool visible, std::string reason)
: m_address(address), m_removedAfterInterrupt(false), m_reason(std::move(reason))
{
if (type == BreakpointType::BP_SINGLE)
{
this->m_pauseThreads = true;
this->m_restoreAfterInterrupt = false;
this->m_deleteAfterAnyInterrupt = false;
this->m_pauseOnNextInterrupt = false;
this->m_visible = visible;
}
else if (type == BreakpointType::BP_PERSISTENT)
{
this->m_pauseThreads = true;
this->m_restoreAfterInterrupt = true;
this->m_deleteAfterAnyInterrupt = false;
this->m_pauseOnNextInterrupt = false;
this->m_visible = visible;
}
else if (type == BreakpointType::BP_RESTORE_POINT)
{
this->m_pauseThreads = false;
this->m_restoreAfterInterrupt = false;
this->m_deleteAfterAnyInterrupt = false;
this->m_pauseOnNextInterrupt = false;
this->m_visible = false;
}
else if (type == BreakpointType::BP_STEP_POINT)
{
this->m_pauseThreads = false;
this->m_restoreAfterInterrupt = false;
this->m_deleteAfterAnyInterrupt = true;
this->m_pauseOnNextInterrupt = true;
this->m_visible = false;
}
this->m_origOpCode = memory_readU32(address);
memory_writeU32(address, DEBUGGER_BP_T_GDBSTUB_TW);
PPCRecompiler_invalidateRange(address, address + 4);
};
~ExecutionBreakpoint()
{
memory_writeU32(this->m_address, this->m_origOpCode);
PPCRecompiler_invalidateRange(this->m_address, this->m_address + 4);
};
[[nodiscard]] uint32 GetVisibleOpCode() const
{
if (this->m_visible)
return memory_readU32(this->m_address);
else
return this->m_origOpCode;
};
[[nodiscard]] bool ShouldBreakThreads() const
{
return this->m_pauseThreads;
};
[[nodiscard]] bool ShouldBreakThreadsOnNextInterrupt()
{
bool shouldPause = this->m_pauseOnNextInterrupt;
this->m_pauseOnNextInterrupt = false;
return shouldPause;
};
[[nodiscard]] bool IsPersistent() const
{
return this->m_restoreAfterInterrupt;
};
[[nodiscard]] bool IsSkipBreakpoint() const
{
return this->m_deleteAfterAnyInterrupt;
};
[[nodiscard]] bool IsRemoved() const
{
return this->m_removedAfterInterrupt;
};
[[nodiscard]] std::string GetReason() const
{
return m_reason;
};
void RemoveTemporarily()
{
memory_writeU32(this->m_address, this->m_origOpCode);
PPCRecompiler_invalidateRange(this->m_address, this->m_address + 4);
this->m_restoreAfterInterrupt = true;
};
void Restore()
{
memory_writeU32(this->m_address, DEBUGGER_BP_T_GDBSTUB_TW);
PPCRecompiler_invalidateRange(this->m_address, this->m_address + 4);
this->m_restoreAfterInterrupt = false;
};
void PauseOnNextInterrupt()
{
this->m_pauseOnNextInterrupt = true;
};
void WriteNewOpCode(uint32 newOpCode)
{
this->m_origOpCode = newOpCode;
};
private:
const MPTR m_address;
std::string m_reason;
uint32 m_origOpCode;
bool m_visible;
bool m_pauseThreads;
// type
bool m_pauseOnNextInterrupt;
bool m_restoreAfterInterrupt;
bool m_deleteAfterAnyInterrupt;
bool m_removedAfterInterrupt;
};
enum class AccessPointType
{
BP_WRITE = 2,
BP_READ = 3,
BP_BOTH = 4
};
class GDBServer::AccessBreakpoint {
public:
AccessBreakpoint(MPTR address, AccessPointType type)
: m_address(address), m_type(type)
{
#if defined(ARCH_X86_64) && BOOST_OS_WINDOWS
for (auto& hThreadNH : coreinit::OSGetSchedulerThreads())
{
HANDLE hThread = (HANDLE)hThreadNH;
CONTEXT ctx{};
ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
SuspendThread(hThread);
GetThreadContext(hThread, &ctx);
// use BP 2/3 for gdb stub since cemu's internal debugger uses BP 0/1 already
ctx.Dr2 = (DWORD64)memory_getPointerFromVirtualOffset(address);
ctx.Dr3 = (DWORD64)memory_getPointerFromVirtualOffset(address);
// breakpoint 2
SetBits(ctx.Dr7, 4, 1, 1); // breakpoint #3 enabled: true
SetBits(ctx.Dr7, 24, 2, 1); // breakpoint #3 condition: 1 (write)
SetBits(ctx.Dr7, 26, 2, 3); // breakpoint #3 length: 3 (4 bytes)
// breakpoint 3
SetBits(ctx.Dr7, 6, 1, 1); // breakpoint #4 enabled: true
SetBits(ctx.Dr7, 28, 2, 3); // breakpoint #4 condition: 3 (read & write)
SetBits(ctx.Dr7, 30, 2, 3); // breakpoint #4 length: 3 (4 bytes)
SetThreadContext(hThread, &ctx);
ResumeThread(hThread);
}
#elif defined(ARCH_X86_64) && BOOST_OS_LINUX
for (auto& hThreadNH : coreinit::OSGetSchedulerThreads())
{
pid_t pid = (pid_t)(uintptr_t)hThreadNH;
ptrace(PTRACE_ATTACH, pid, nullptr, nullptr);
waitpid(pid, nullptr, 0);
DRType dr7 = _GetDR(pid, 7);
// use BP 2/3 for gdb stub since cemu's internal debugger uses BP 0/1 already
DRType dr2 = (uint64)memory_getPointerFromVirtualOffset(address);
DRType dr3 = (uint64)memory_getPointerFromVirtualOffset(address);
// breakpoint 2
SetBits(dr7, 4, 1, 1); // breakpoint #3 enabled: true
SetBits(dr7, 24, 2, 1); // breakpoint #3 condition: 1 (write)
SetBits(dr7, 26, 2, 3); // breakpoint #3 length: 3 (4 bytes)
// breakpoint 3
SetBits(dr7, 6, 1, 1); // breakpoint #4 enabled: true
SetBits(dr7, 28, 2, 3); // breakpoint #4 condition: 3 (read & write)
SetBits(dr7, 30, 2, 3); // breakpoint #4 length: 3 (4 bytes)
_SetDR(pid, 2, dr2);
_SetDR(pid, 3, dr3);
_SetDR(pid, 7, dr7);
ptrace(PTRACE_DETACH, pid, nullptr, nullptr);
}
#else
cemuLog_log(LogType::Force, "Debugger read/write breakpoints are not supported on non-x86 CPUs yet.");
#endif
};
~AccessBreakpoint()
{
#if defined(ARCH_X86_64) && BOOST_OS_WINDOWS
for (auto& hThreadNH : coreinit::OSGetSchedulerThreads())
{
HANDLE hThread = (HANDLE)hThreadNH;
CONTEXT ctx{};
ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
SuspendThread(hThread);
GetThreadContext(hThread, &ctx);
// reset BP 2/3 to zero
ctx.Dr2 = (DWORD64)0;
ctx.Dr3 = (DWORD64)0;
// breakpoint 2
SetBits(ctx.Dr7, 4, 1, 0);
SetBits(ctx.Dr7, 24, 2, 0);
SetBits(ctx.Dr7, 26, 2, 0);
// breakpoint 3
SetBits(ctx.Dr7, 6, 1, 0);
SetBits(ctx.Dr7, 28, 2, 0);
SetBits(ctx.Dr7, 30, 2, 0);
SetThreadContext(hThread, &ctx);
ResumeThread(hThread);
}
#elif defined(ARCH_X86_64) && BOOST_OS_LINUX
for (auto& hThreadNH : coreinit::OSGetSchedulerThreads())
{
pid_t pid = (pid_t)(uintptr_t)hThreadNH;
ptrace(PTRACE_ATTACH, pid, nullptr, nullptr);
waitpid(pid, nullptr, 0);
DRType dr7 = _GetDR(pid, 7);
// reset BP 2/3 to zero
DRType dr2 = 0;
DRType dr3 = 0;
// breakpoint 2
SetBits(dr7, 4, 1, 0);
SetBits(dr7, 24, 2, 0);
SetBits(dr7, 26, 2, 0);
// breakpoint 3
SetBits(dr7, 6, 1, 0);
SetBits(dr7, 28, 2, 0);
SetBits(dr7, 30, 2, 0);
_SetDR(pid, 2, dr2);
_SetDR(pid, 3, dr3);
_SetDR(pid, 7, dr7);
ptrace(PTRACE_DETACH, pid, nullptr, nullptr);
}
#endif
};
MPTR GetAddress() const
{
return m_address;
};
AccessPointType GetType() const
{
return m_type;
};
private:
const MPTR m_address;
const AccessPointType m_type;
};
File diff suppressed because it is too large Load Diff
+316
View File
@@ -0,0 +1,316 @@
#pragma once
#include "Common/precompiled.h"
#include "Common/socket.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include <numeric>
class GDBServer {
public:
explicit GDBServer(uint16 port);
~GDBServer();
bool Initialize();
bool IsConnected()
{
return m_client_connected;
}
void HandleEntryStop(uint32 entryAddress);
void HandleTrapInstruction(PPCInterpreter_t* hCPU);
void HandleAccessException(uint64 dr6);
enum class CMDType : char
{
INVALID = '\0',
// Extended commands
QUERY_GET = 'q',
QUERY_SET = 'Q',
VCONT = 'v',
// Normal commands
CONTINUE = 'c',
IS_THREAD_RUNNING = 'T',
SET_ACTIVE_THREAD = 'H',
ACTIVE_THREAD_STATUS = '?',
ACTIVE_THREAD_STEP = 's',
REGISTER_READ = 'p',
REGISTER_SET = 'P',
REGISTERS_READ = 'g',
REGISTERS_WRITE = 'G',
MEMORY_READ = 'm',
MEMORY_WRITE = 'M',
BREAKPOINT_SET = 'Z',
BREAKPOINT_REMOVE = 'z',
};
class CommandContext {
public:
CommandContext(const GDBServer* server, const std::string& command)
: m_server(server), m_command(command)
{
std::smatch matches;
std::regex_match(command, matches, m_regex);
for (size_t i = 1; i < matches.size(); i++)
{
auto matchStr = matches[i].str();
if (!matchStr.empty())
m_args.emplace_back(std::move(matchStr));
}
// send acknowledgement ahead of response
send(m_server->m_client_socket, RESPONSE_ACK.data(), (int)RESPONSE_ACK.size(), 0);
};
~CommandContext()
{
// cemuLog_logDebug(LogType::Force, "[GDBStub] Received: {}", m_command);
// cemuLog_logDebug(LogType::Force, "[GDBStub] Responded: +{}", m_response);
auto response_data = EscapeMessage(m_response);
auto response_full = fmt::format("${}#{:02x}", response_data, CalculateChecksum(response_data));
send(m_server->m_client_socket, response_full.c_str(), (int)response_full.size(), 0);
}
CommandContext(const CommandContext&) = delete;
[[nodiscard]] const std::string& GetCommand() const
{
return m_command;
};
[[nodiscard]] const std::vector<std::string>& GetArgs() const
{
return m_args;
};
[[nodiscard]] bool IsValid() const
{
return !m_args.empty();
};
[[nodiscard]] CMDType GetType() const
{
return static_cast<CMDType>(m_command[0]);
};
// Respond Utils
static uint8 CalculateChecksum(std::string_view message_data)
{
return std::accumulate(message_data.begin(), message_data.end(), (uint8)0, std::plus<>());
}
static std::string EscapeXMLString(std::string_view xml_data)
{
std::string escaped;
escaped.reserve(xml_data.size());
for (char c : xml_data)
{
switch (c)
{
case '<': escaped += "&lt;"; break;
case '>': escaped += "&gt;"; break;
case '&': escaped += "&amp;"; break;
case '"': escaped += "&quot;"; break;
case '\'': escaped += "&apos;"; break;
default: escaped += c; break;
}
}
return escaped;
}
static std::string EscapeMessage(std::string_view message)
{
std::string escaped;
escaped.reserve(message.size());
for (char c : message)
{
if (c == '#' || c == '$' || c == '}' || c == '*')
{
escaped.push_back('}');
escaped.push_back((char)(c ^ 0x20));
}
else
escaped.push_back(c);
}
return escaped;
}
void QueueResponse(std::string_view data)
{
m_response += data;
}
private:
const std::regex m_regex{
R"((?:)"
R"((\?))"
R"(|(vCont\?))"
R"(|(vCont;)([a-zA-Z0-9-+=,\+:;]+))"
R"(|(qAttached))"
R"(|(qSupported):([a-zA-Z0-9-+=,\+;]+))"
R"(|(qTStatus))"
R"(|(qC))"
R"(|(qXfer):((?:features)|(?:threads)|(?:libraries)):read:([\w\.]*):([0-9a-zA-Z]+),([0-9a-zA-Z]+))"
R"(|(qfThreadInfo))"
R"(|(qsThreadInfo))"
R"(|(T)((?:-1)|(?:[0-9A-Fa-f]+)))"
R"(|(D))" // Detach
R"(|(H)(c|g)((?:-1)|(?:[0-9A-Fa-f]+)))" // Set active thread for other operations (not c)
R"(|(c)([0-9A-Fa-f]+)?)" // (Legacy, supported by vCont) Continue all for active thread
R"(|([Zz])([0-4]),([0-9A-Fa-f]+),([0-9]))" // Insert/delete breakpoints
R"(|(g))" // Read registers for active thread
R"(|(G)([0-9A-Fa-f]+))" // Write registers for active thread
R"(|(p)([0-9A-Fa-f]+))" // Read register for active thread
R"(|(P)([0-9A-Fa-f]+)=([0-9A-Fa-f]+))" // Write register for active thread
R"(|(m)([0-9A-Fa-f]+),([0-9A-Fa-f]+))" // Read memory
R"(|(M)([0-9A-Fa-f]+),([0-9A-Fa-f]+):([0-9A-Fa-f]+))" // Write memory
// R"(|(X)([0-9A-Fa-f]+),([0-9A-Fa-f]+):([0-9A-Fa-f]+))" // Write memory
R"())"};
const GDBServer* m_server;
const std::string m_command;
std::vector<std::string> m_args;
std::string m_response;
};
class ExecutionBreakpoint;
std::map<MPTR, ExecutionBreakpoint> m_patchedInstructions;
class AccessBreakpoint;
std::unique_ptr<AccessBreakpoint> m_watch_point;
private:
static constexpr int s_maxGDBClients = 1;
static constexpr std::string_view s_supportedFeatures = "PacketSize=4096;qXfer:features:read+;qXfer:threads:read+;qXfer:libraries:read+;swbreak+;hwbreak+;vContSupported+";
static constexpr size_t s_maxPacketSize = 1024 * 4;
const uint16 m_port;
enum RegisterID
{
R0_START = 0,
R31_END = R0_START + 31,
PC = 64,
MSR = 65,
CR = 66,
LR = 67,
CTR = 68,
XER = 69,
F0_START = 71,
F31_END = F0_START + 31,
FPSCR = 103
};
static constexpr std::string_view RESPONSE_EMPTY = "";
static constexpr std::string_view RESPONSE_ACK = "+";
static constexpr std::string_view RESPONSE_NACK = "-";
static constexpr std::string_view RESPONSE_OK = "OK";
static constexpr std::string_view RESPONSE_ERROR = "E01";
void ThreadFunc();
std::atomic_bool m_stopRequested;
void HandleCommand(const std::string& command_str);
void HandleQuery(std::unique_ptr<CommandContext>& context) const;
void HandleVCont(std::unique_ptr<CommandContext>& context);
// Commands
sint64 m_activeThreadSelector = 0;
sint64 m_activeThreadContinueSelector = 0;
void CMDContinue(std::unique_ptr<CommandContext>& context);
void CMDNotFound(std::unique_ptr<CommandContext>& context);
void CMDIsThreadActive(std::unique_ptr<CommandContext>& context);
void CMDSetActiveThread(std::unique_ptr<CommandContext>& context);
void CMDGetThreadStatus(std::unique_ptr<CommandContext>& context);
void CMDReadRegister(std::unique_ptr<CommandContext>& context) const;
void CMDWriteRegister(std::unique_ptr<CommandContext>& context) const;
void CMDReadRegisters(std::unique_ptr<CommandContext>& context) const;
void CMDWriteRegisters(std::unique_ptr<CommandContext>& context) const;
void CMDReadMemory(std::unique_ptr<CommandContext>& context);
void CMDWriteMemory(std::unique_ptr<CommandContext>& context);
void CMDInsertBreakpoint(std::unique_ptr<CommandContext>& context);
void CMDDeleteBreakpoint(std::unique_ptr<CommandContext>& context);
std::thread m_thread;
std::atomic_bool m_resume_startup = false;
MPTR m_entry_point{};
std::unique_ptr<CommandContext> m_resumed_context;
std::atomic_bool m_client_connected;
SOCKET m_server_socket = INVALID_SOCKET;
sockaddr_in m_server_addr{};
SOCKET m_client_socket = INVALID_SOCKET;
sockaddr_in m_client_addr{};
};
static constexpr std::string_view GDBTargetXML = R"(<?xml version="1.0"?>
<!DOCTYPE target SYSTEM "gdb-target.dtd">
<target version="1.0">
<architecture>powerpc:common</architecture>
<feature name="org.gnu.gdb.power.core">
<reg name="r0" bitsize="32" type="uint32"/>
<reg name="r1" bitsize="32" type="uint32"/>
<reg name="r2" bitsize="32" type="uint32"/>
<reg name="r3" bitsize="32" type="uint32"/>
<reg name="r4" bitsize="32" type="uint32"/>
<reg name="r5" bitsize="32" type="uint32"/>
<reg name="r6" bitsize="32" type="uint32"/>
<reg name="r7" bitsize="32" type="uint32"/>
<reg name="r8" bitsize="32" type="uint32"/>
<reg name="r9" bitsize="32" type="uint32"/>
<reg name="r10" bitsize="32" type="uint32"/>
<reg name="r11" bitsize="32" type="uint32"/>
<reg name="r12" bitsize="32" type="uint32"/>
<reg name="r13" bitsize="32" type="uint32"/>
<reg name="r14" bitsize="32" type="uint32"/>
<reg name="r15" bitsize="32" type="uint32"/>
<reg name="r16" bitsize="32" type="uint32"/>
<reg name="r17" bitsize="32" type="uint32"/>
<reg name="r18" bitsize="32" type="uint32"/>
<reg name="r19" bitsize="32" type="uint32"/>
<reg name="r20" bitsize="32" type="uint32"/>
<reg name="r21" bitsize="32" type="uint32"/>
<reg name="r22" bitsize="32" type="uint32"/>
<reg name="r23" bitsize="32" type="uint32"/>
<reg name="r24" bitsize="32" type="uint32"/>
<reg name="r25" bitsize="32" type="uint32"/>
<reg name="r26" bitsize="32" type="uint32"/>
<reg name="r27" bitsize="32" type="uint32"/>
<reg name="r28" bitsize="32" type="uint32"/>
<reg name="r29" bitsize="32" type="uint32"/>
<reg name="r30" bitsize="32" type="uint32"/>
<reg name="r31" bitsize="32" type="uint32"/>
<reg name="pc" bitsize="32" type="code_ptr" regnum="64"/>
<reg name="msr" bitsize="32" type="uint32"/>
<reg name="cr" bitsize="32" type="uint32"/>
<reg name="lr" bitsize="32" type="code_ptr"/>
<reg name="ctr" bitsize="32" type="uint32"/>
<reg name="xer" bitsize="32" type="uint32"/>
</feature>
<feature name="org.gnu.gdb.power.fpu">
<reg name="f0" bitsize="64" type="ieee_double" regnum="71"/>
<reg name="f1" bitsize="64" type="ieee_double"/>
<reg name="f2" bitsize="64" type="ieee_double"/>
<reg name="f3" bitsize="64" type="ieee_double"/>
<reg name="f4" bitsize="64" type="ieee_double"/>
<reg name="f5" bitsize="64" type="ieee_double"/>
<reg name="f6" bitsize="64" type="ieee_double"/>
<reg name="f7" bitsize="64" type="ieee_double"/>
<reg name="f8" bitsize="64" type="ieee_double"/>
<reg name="f9" bitsize="64" type="ieee_double"/>
<reg name="f10" bitsize="64" type="ieee_double"/>
<reg name="f11" bitsize="64" type="ieee_double"/>
<reg name="f12" bitsize="64" type="ieee_double"/>
<reg name="f13" bitsize="64" type="ieee_double"/>
<reg name="f14" bitsize="64" type="ieee_double"/>
<reg name="f15" bitsize="64" type="ieee_double"/>
<reg name="f16" bitsize="64" type="ieee_double"/>
<reg name="f17" bitsize="64" type="ieee_double"/>
<reg name="f18" bitsize="64" type="ieee_double"/>
<reg name="f19" bitsize="64" type="ieee_double"/>
<reg name="f20" bitsize="64" type="ieee_double"/>
<reg name="f21" bitsize="64" type="ieee_double"/>
<reg name="f22" bitsize="64" type="ieee_double"/>
<reg name="f23" bitsize="64" type="ieee_double"/>
<reg name="f24" bitsize="64" type="ieee_double"/>
<reg name="f25" bitsize="64" type="ieee_double"/>
<reg name="f26" bitsize="64" type="ieee_double"/>
<reg name="f27" bitsize="64" type="ieee_double"/>
<reg name="f28" bitsize="64" type="ieee_double"/>
<reg name="f29" bitsize="64" type="ieee_double"/>
<reg name="f30" bitsize="64" type="ieee_double"/>
<reg name="f31" bitsize="64" type="ieee_double"/>
<reg name="fpscr" bitsize="32" group="float"/>
</feature>
</target>)";
extern std::unique_ptr<GDBServer> g_gdbstub;
@@ -1,6 +1,7 @@
#include "PPCInterpreterInternal.h"
#include "PPCInterpreterHelper.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "Cafe/HW/Espresso/Debugger/GDBStub.h"
class PPCItpCafeOSUsermode
{
@@ -65,9 +65,12 @@ static void PPCInterpreter_MFTB(PPCInterpreter_t* hCPU, uint32 opcode)
static void PPCInterpreter_TW(PPCInterpreter_t* hCPU, uint32 opcode)
{
sint32 to, rA, rB;
PPC_OPC_TEMPL_X(opcode, to, rB, rA);
PPC_OPC_TEMPL_X(opcode, to, rA, rB);
cemu_assert_debug(to == 0);
debugger_enterTW(hCPU);
if (rA == DEBUGGER_BP_T_DEBUGGER)
debugger_enterTW(hCPU);
else if (rA == DEBUGGER_BP_T_GDBSTUB)
g_gdbstub->HandleTrapInstruction(hCPU);
}
+18 -1
View File
@@ -671,6 +671,11 @@ namespace coreinit
__OSUnlockScheduler();
}
void __OSSuspendThreadNolock(OSThread_t* thread)
{
__OSSuspendThreadInternal(thread);
}
void OSSleepThread(OSThreadQueue* threadQueue)
{
__OSLockScheduler();
@@ -798,7 +803,18 @@ namespace coreinit
return suspendCounter > 0;
}
void OSCancelThread(OSThread_t* thread)
bool OSIsThreadRunning(OSThread_t* thread)
{
bool isRunning = false;
__OSLockScheduler();
if (thread->state == OSThread_t::THREAD_STATE::STATE_RUNNING)
isRunning = true;
__OSUnlockScheduler();
return isRunning;
}
void OSCancelThread(OSThread_t* thread)
{
__OSLockScheduler();
cemu_assert_debug(thread->requestFlags == 0 || thread->requestFlags == OSThread_t::REQUEST_FLAG_CANCEL); // todo - how to handle cases where other flags are already set?
@@ -1315,6 +1331,7 @@ namespace coreinit
cafeExportRegister("coreinit", OSResumeThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSContinueThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSuspendThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", __OSSuspendThreadNolock, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSleepThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSWakeupThread, LogType::CoreinitThread);
+6 -4
View File
@@ -461,10 +461,10 @@ struct OSThread_t
/* +0x628 */ uint64 wakeTimeRelatedUkn2;
// set via OSSetExceptionCallback
/* +0x630 */ MPTR ukn630Callback[Espresso::CORE_COUNT];
/* +0x63C */ MPTR ukn63CCallback[Espresso::CORE_COUNT];
/* +0x648 */ MPTR ukn648Callback[Espresso::CORE_COUNT];
/* +0x654 */ MPTR ukn654Callback[Espresso::CORE_COUNT];
/* +0x630 */ MPTR dsiCallback[Espresso::CORE_COUNT];
/* +0x63C */ MPTR isiCallback[Espresso::CORE_COUNT];
/* +0x648 */ MPTR programCallback[Espresso::CORE_COUNT];
/* +0x654 */ MPTR perfMonCallback[Espresso::CORE_COUNT];
/* +0x660 */ uint32 ukn660;
@@ -514,6 +514,7 @@ namespace coreinit
sint32 OSResumeThread(OSThread_t* thread);
void OSContinueThread(OSThread_t* thread);
void __OSSuspendThreadInternal(OSThread_t* thread);
void __OSSuspendThreadNolock(OSThread_t* thread);
void OSSuspendThread(OSThread_t* thread);
void OSSleepThread(OSThreadQueue* threadQueue);
void OSWakeupThread(OSThreadQueue* threadQueue);
@@ -525,6 +526,7 @@ namespace coreinit
bool OSIsThreadTerminated(OSThread_t* thread);
bool OSIsThreadSuspended(OSThread_t* thread);
bool OSIsThreadRunning(OSThread_t* thread);
// OSThreadQueue
void OSInitThreadQueue(OSThreadQueue* threadQueue);
@@ -135,7 +135,7 @@ namespace coreinit
while (OSThread_t* thread = takeFirstFromQueue(offsetof(OSThread_t, waitQueueLink)))
{
cemu_assert_debug(thread->state == OSThread_t::THREAD_STATE::STATE_WAITING);
cemu_assert_debug(thread->suspendCounter == 0);
//cemu_assert_debug(thread->suspendCounter == 0);
thread->state = OSThread_t::THREAD_STATE::STATE_READY;
thread->currentWaitQueue = nullptr;
coreinit::__OSAddReadyThreadToRunQueue(thread);
+10
View File
@@ -73,6 +73,15 @@ void nsysnetExport_socket_lib_init(PPCInterpreter_t* hCPU)
osLib_returnFromFunction(hCPU, 0); // 0 -> Success
}
void nsysnetExport_socket_lib_finish(PPCInterpreter_t* hCPU)
{
sockLibReady = false;
#if BOOST_OS_WINDOWS
WSACleanup();
#endif // BOOST_OS_WINDOWS
osLib_returnFromFunction(hCPU, 0); // 0 -> Success
}
uint32* __gh_errno_ptr()
{
OSThread_t* osThread = coreinitThread_getCurrentThreadDepr(PPCInterpreter_getCurrentInstance());
@@ -2120,6 +2129,7 @@ void nsysnet_load()
{
osLib_addFunction("nsysnet", "socket_lib_init", nsysnetExport_socket_lib_init);
osLib_addFunction("nsysnet", "socket_lib_finish", nsysnetExport_socket_lib_finish);
// socket API
osLib_addFunction("nsysnet", "socket", nsysnetExport_socket);
@@ -9,6 +9,7 @@
#include "Config/CemuConfig.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/HW/Espresso/PPCState.h"
#include "Cafe/HW/Espresso/Debugger/GDBStub.h"
extern uint32 currentBaseApplicationHash;
extern uint32 currentUpdatedApplicationHash;
@@ -378,7 +379,8 @@ int crashlogThread(void* exceptionInfoRawPtr)
return 0;
}
void debugger_handleSingleStepException(uint32 drMask);
void debugger_handleSingleStepException(uint64 dr6);
LONG WINAPI VectoredExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)
{
@@ -387,7 +389,11 @@ LONG WINAPI VectoredExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)
LONG r = handleException_SINGLE_STEP(pExceptionInfo);
if (r != EXCEPTION_CONTINUE_SEARCH)
return r;
debugger_handleSingleStepException(pExceptionInfo->ContextRecord->Dr6 & 0xF);
if (GetBits(pExceptionInfo->ContextRecord->Dr6, 0, 1) || GetBits(pExceptionInfo->ContextRecord->Dr6, 1, 1))
debugger_handleSingleStepException(pExceptionInfo->ContextRecord->Dr6);
else if (GetBits(pExceptionInfo->ContextRecord->Dr6, 2, 1) || GetBits(pExceptionInfo->ContextRecord->Dr6, 3, 1))
g_gdbstub->HandleAccessException(pExceptionInfo->ContextRecord->Dr6);
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
+18 -2
View File
@@ -69,11 +69,12 @@
#include <filesystem>
#include <memory>
#include <chrono>
#include <time.h>
#include <ctime>
#include <regex>
#include <type_traits>
#include <optional>
#include <span>
#include <ranges>
#include <boost/predef.h>
#include <boost/nowide/convert.hpp>
@@ -208,6 +209,21 @@ typedef union _LARGE_INTEGER {
inline T& operator^= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) ^= static_cast<std::underlying_type<T>::type>(b) ); }
#endif
template<typename T>
inline T GetBits(T value, uint32 index, uint32 numBits)
{
T mask = (1<<numBits)-1;
return (value>>index) & mask;
}
template<typename T>
inline void SetBits(T& value, uint32 index, uint32 numBits, uint32 bitValue)
{
T mask = (1<<numBits)-1;
value &= ~(mask << index);
value |= (bitValue << index);
}
#if !defined(_MSC_VER) || defined(__clang__) // clang-cl does not have built-in _udiv128
inline uint64 _udiv128(uint64 highDividend, uint64 lowDividend, uint64 divisor, uint64 *remainder)
{
@@ -255,7 +271,7 @@ inline uint64 _udiv128(uint64 highDividend, uint64 lowDividend, uint64 divisor,
inline void _mm_pause()
{
asm volatile("yield");
asm volatile("yield");
}
inline uint64 __rdtsc()
+2
View File
@@ -336,6 +336,7 @@ void CemuConfig::Load(XMLConfigParser& parser)
#elif BOOST_OS_UNIX
crash_dump = debug.get("CrashDumpUnix", crash_dump);
#endif
gdb_port = debug.get("GDBPort", 1337);
// input
auto input = parser.get("Input");
@@ -515,6 +516,7 @@ void CemuConfig::Save(XMLConfigParser& parser)
#elif BOOST_OS_UNIX
debug.set("CrashDumpUnix", crash_dump.GetValue());
#endif
debug.set("GDBPort", gdb_port);
// input
auto input = config.set("Input");
+1
View File
@@ -484,6 +484,7 @@ struct CemuConfig
// debug
ConfigValueBounds<CrashDump> crash_dump{ CrashDump::Disabled };
ConfigValue<uint16> gdb_port{ 1337 };
void Load(XMLConfigParser& parser);
void Save(XMLConfigParser& parser);
+4
View File
@@ -68,6 +68,7 @@ bool LaunchSettings::HandleCommandline(const std::vector<std::wstring>& args)
("account,a", po::value<std::string>(), "Persistent id of account")
("force-interpreter", po::value<bool>()->implicit_value(true), "Force interpreter CPU emulation, disables recompiler")
("enable-gdbstub", po::value<bool>()->implicit_value(true), "Enable GDB stub to debug executables inside Cemu using an external debugger")
("act-url", po::value<std::string>(), "URL prefix for account server")
("ecs-url", po::value<std::string>(), "URL for ECS service");
@@ -162,6 +163,9 @@ bool LaunchSettings::HandleCommandline(const std::vector<std::wstring>& args)
if(vm.count("force-interpreter"))
s_force_interpreter = vm["force-interpreter"].as<bool>();
if (vm.count("enable-gdbstub"))
s_enable_gdbstub = vm["enable-gdbstub"].as<bool>();
std::wstring extract_path, log_path;
std::string output_path;

Some files were not shown because too many files have changed in this diff Show More