From 5c9eda7cd8349f6bfdcac4882946f696717bc141 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 18 Sep 2026 16:26:41 -0600 Subject: [PATCH] KDebugForKernel: implement Kprintf Outrun 2006's USB kernel module calls it on a failed sceUsbbdRegister, so booting the game printed "Unimplemented function Kprintf". It's the kernel's debug printf - on hardware it goes to whatever sceKernelRegisterKprintfHandler() installed, which on a retail PSP is the serial port, so this is just debug output the game shipped with. We format it and log it, which is the useful thing to do with it. The vararg walker that sysclib's sprintf/snprintf already had is now HLEFormatPrintf() in HLE.cpp, so there's one of these rather than a second copy. It takes the index of the first vararg (counting a0 as 0) instead of an offset from a2, which is the same mapping written in absolute terms - sprintf passes 2 and snprintf 3, where they passed 0 and 1 before. Kprintf replaces the existing nullptr entry in the KDebugForKernel table, so no indices move and savestates are unaffected. --- Core/HLE/HLE.cpp | 127 +++++++++++++++++++++++++++ Core/HLE/HLE.h | 5 ++ Core/HLE/HLETables.cpp | 20 ++++- Core/HLE/sceKernelInterrupt.cpp | 146 ++------------------------------ 4 files changed, 157 insertions(+), 141 deletions(-) diff --git a/Core/HLE/HLE.cpp b/Core/HLE/HLE.cpp index 9ad242e31b..7b23506309 100644 --- a/Core/HLE/HLE.cpp +++ b/Core/HLE/HLE.cpp @@ -1218,6 +1218,133 @@ void hlePushFuncDesc(std::string_view module, std::string_view funcName) { } } +// Fetches one word of a variadic argument list. Note that this is not the o32 layout - psp-gcc +// builds for the MIPS EABI, where the first eight arguments go in a0-a3 and t0-t3, and the rest +// on the stack starting at sp+0 (o32 would pass four in registers and start the stack at sp+16). +static bool ReadVarArgWord(int index, u32 *value) { + if (index < 4) { + *value = currentMIPS->r[MIPS_REG_A0 + index]; + return true; + } + if (index < 8) { + *value = currentMIPS->r[MIPS_REG_T0 + index - 4]; + return true; + } + const u32 addr = currentMIPS->r[MIPS_REG_SP] + (index - 8) * 4; + if (!Memory::IsValid4AlignedAddress(addr)) { + ERROR_LOG(Log::HLE, "printf: bad stack pointer %08x", addr); + return false; + } + *value = Memory::ReadUnchecked_U32(addr); + return true; +} + +bool HLEFormatPrintf(u32 fmtAddr, int firstVarArg, std::string *result) { + if (!Memory::IsValidNullTerminatedString(fmtAddr)) { + ERROR_LOG(Log::HLE, "printf: bad format string at %08x", fmtAddr); + return false; + } + + VERBOSE_LOG(Log::HLE, "printf fmt: %s", Memory::GetCharPointerUnchecked(fmtAddr)); + VERBOSE_LOG(Log::HLE, "printf a0-a3, t0-t3: %08x %08x %08x %08x %08x %08x %08x %08x", + currentMIPS->r[MIPS_REG_A0], currentMIPS->r[MIPS_REG_A1], + currentMIPS->r[MIPS_REG_A2], currentMIPS->r[MIPS_REG_A3], + currentMIPS->r[MIPS_REG_T0], currentMIPS->r[MIPS_REG_T1], + currentMIPS->r[MIPS_REG_T2], currentMIPS->r[MIPS_REG_T3]); + + bool processingSpecifier = false; + std::string specifier; + int bytesToRead = 0; + int argIndex = firstVarArg; + result->clear(); + for (const char *c = Memory::GetCharPointerUnchecked(fmtAddr); *c != '\0'; c++) { + if (!processingSpecifier) { + if (*c == '%') { + specifier = "%"; + processingSpecifier = true; + bytesToRead = 0; + } else { + result->append(1, *c); + } + continue; + } + + specifier.append(1, *c); + + // Going by https://cplusplus.com/reference/cstdio/printf/#compatibility - no idea what the + // kernel module really supports. + switch (*c) { + case '%': + result->append(specifier); + processingSpecifier = false; + break; + + case 's': + { + u32 val = 0; + if (!ReadVarArgWord(argIndex++, &val)) { + return false; + } + if (!Memory::IsValidNullTerminatedString(val)) { + ERROR_LOG(Log::HLE, "printf: bad string reference at %08x", val); + return false; + } + result->append(Memory::GetCharPointerUnchecked(val)); + processingSpecifier = false; + break; + } + + case 'd': + case 'i': + case 'u': + case 'o': + case 'x': + case 'X': + case 'f': + case 'e': + case 'E': + case 'g': + case 'G': + case 'c': + case 'p': + case 'n': + { + u64 val = 0; + if (bytesToRead == 0) { + bytesToRead = 4; + } + int readCount = 0; + while (bytesToRead != 0) { + u32 word = 0; + if (!ReadVarArgWord(argIndex++, &word)) { + return false; + } + val = val | ((u64)word << (readCount * 32)); + bytesToRead -= 4; + readCount++; + } + char buf[128]{}; + snprintf(buf, sizeof(buf), specifier.c_str(), val); + buf[sizeof(buf) - 1] = '\0'; + result->append(buf); + processingSpecifier = false; + break; + } + + case 'h': + // The allegrex calling convention is 4 byte aligned. + bytesToRead = 4; + break; + + case 'l': + bytesToRead = bytesToRead + 4; + break; + } + } + + return true; +} + // TODO: Also add support for argument names. size_t HLEFormatLogArgs(const MIPSState *mips, char *message, size_t sz, const char *argmask) { char *p = message; diff --git a/Core/HLE/HLE.h b/Core/HLE/HLE.h index 09f294b207..09933620c2 100644 --- a/Core/HLE/HLE.h +++ b/Core/HLE/HLE.h @@ -192,6 +192,11 @@ void HLEDoState(PointerWrap &p); void HLEShutdown(); const HLEFunction *HLEGetFunctionBeingCalled(); size_t HLEFormatLogArgs(const MIPSState *mips, char *message, size_t sz, const char *argmask); +// Runs a printf-style format string from the emulated program, pulling the varargs out of the PSP's +// registers and stack. firstVarArg is the index of the first vararg, counting a0 as 0 - so 1 for a +// printf(fmt, ...), 2 for an sprintf(dst, fmt, ...). Returns false, having logged why, if the format +// string or an argument couldn't be read; the caller shouldn't use the result then. +bool HLEFormatPrintf(u32 fmtAddr, int firstVarArg, std::string *result); u32 GetSyscallOp(std::string_view module, u32 nib); bool WriteHLESyscall(std::string_view module, u32 nib, u32 address); void CallSyscall(MIPSOpcode op); diff --git a/Core/HLE/HLETables.cpp b/Core/HLE/HLETables.cpp index eddb1b028b..110b6709ac 100644 --- a/Core/HLE/HLETables.cpp +++ b/Core/HLE/HLETables.cpp @@ -175,13 +175,31 @@ static u32 sceKernelSm1ReferOperations() { return hleLogDebug(Log::sceKernel, 0); } +// The kernel's debug printf. On hardware it formats the string and hands it to whatever +// sceKernelRegisterKprintfHandler() installed, which on a retail PSP means the serial port - +// so nothing a player ever sees, and games that call it are just leaving debug output in. +// We format it and put it in the log, which is the useful thing to do with it. +// Declared void in the SDK headers, so the return value doesn't matter, but 0 is what the +// firmware leaves in v0. +static u32 Kprintf(u32 fmtAddr) { + std::string formatted; + if (!HLEFormatPrintf(fmtAddr, 1, &formatted)) { + return hleLogError(Log::Printf, 0, "bad format string or args"); + } + // Each log line is already a line, so don't double space. + if (!formatted.empty() && formatted.back() == '\n') { + formatted.pop_back(); + } + return hleLogInfo(Log::Printf, 0, "\"%s\"", formatted.c_str()); +} + static const HLEFunction KDebugForKernel[] = { {0XE7A3874D, nullptr, "sceKernelRegisterAssertHandler", '?', "" }, {0X2FF4E9F9, nullptr, "sceKernelAssert", '?', "" }, {0X9B868276, nullptr, "sceKernelGetDebugPutchar", '?', "" }, {0XE146606D, nullptr, "sceKernelRegisterDebugPutchar", '?', "" }, {0X7CEB2C09, &WrapU_V, "sceKernelRegisterKprintfHandler", 'x', "", HLE_KERNEL_SYSCALL }, - {0X84F370BC, nullptr, "Kprintf", '?', "" }, + {0X84F370BC, &WrapU_U, "Kprintf", 'x', "x", HLE_KERNEL_SYSCALL }, {0X5CE9838B, nullptr, "sceKernelDebugWrite", '?', "" }, {0X66253C4E, nullptr, "sceKernelRegisterDebugWrite", '?', "" }, {0XDBB5597F, nullptr, "sceKernelDebugRead", '?', "" }, diff --git a/Core/HLE/sceKernelInterrupt.cpp b/Core/HLE/sceKernelInterrupt.cpp index 9783294b98..88b409398f 100644 --- a/Core/HLE/sceKernelInterrupt.cpp +++ b/Core/HLE/sceKernelInterrupt.cpp @@ -737,146 +737,12 @@ static int sysclib_memcmp(u32 dst, u32 src, u32 size) { } } -// NOTE: This doesn't yet obey the limit parameter, needed for correct snprintf behavior. -static int sysclib_sprintf_impl(u32 dst, int limit, u32 fmt, int paramOffset) { - if (!Memory::IsValidNullTerminatedString(fmt)) { - ERROR_LOG(Log::sceKernel, "sysclib_sprintf bad fmt"); +static int sysclib_sprintf_impl(u32 dst, int limit, u32 fmt, int firstVarArg) { + std::string result; + if (!HLEFormatPrintf(fmt, firstVarArg, &result)) { return 0; } - VERBOSE_LOG(Log::sceKernel, "sysclib_sprintf fmt: %s", Memory::GetCharPointerUnchecked(fmt)); - VERBOSE_LOG(Log::sceKernel, "sysclib_sprintf a0-a4, t0-t4: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x", - currentMIPS->r[MIPS_REG_A0], - currentMIPS->r[MIPS_REG_A1], - currentMIPS->r[MIPS_REG_A2], - currentMIPS->r[MIPS_REG_A3], - currentMIPS->r[MIPS_REG_T0], - currentMIPS->r[MIPS_REG_T1], - currentMIPS->r[MIPS_REG_T2], - currentMIPS->r[MIPS_REG_T3] - ); - - bool processing_specifier = false; - std::string specifier = ""; - int bytes_to_read = 0; - int arg_idx = paramOffset; - std::string result = ""; - for (const char *c = Memory::GetCharPointerUnchecked(fmt); *c != '\0'; c++) { - if (!processing_specifier) { - if (*c == '%') { - specifier = "%"; - processing_specifier = true; - bytes_to_read = 0; - } else { - result.append(1, *c); - } - } else { - specifier.append(1, *c); - - // going by https://cplusplus.com/reference/cstdio/printf/#compatibility - // no idea what the kernel module really supports as of writing this - switch (*c) { - case '%': - { - result.append(specifier); - processing_specifier = false; - break; - } - case 's': - { - // consume 4 bytes from arguments - u32 val = 0; - if (arg_idx <= 1) { - val = currentMIPS->r[MIPS_REG_A2 + arg_idx]; - } else if(arg_idx <= 5) { - val = currentMIPS->r[MIPS_REG_T0 + arg_idx - 2]; - } else { - int stack_idx = arg_idx - 6; - u32 stack_cur = currentMIPS->r[MIPS_REG_SP] + stack_idx * 4; - - if (!Memory::IsValid4AlignedAddress(stack_cur)) { - ERROR_LOG(Log::sceKernel, "sysclib_sprintf bad stack pointer %08x", stack_cur); - return 0; - } - val = Memory::ReadUnchecked_U32(stack_cur); - VERBOSE_LOG(Log::sceKernel, "sysclib_sprintf fetching %08x from sp + %u", val, stack_idx * 4); - } - arg_idx++; - - if (!Memory::IsValidNullTerminatedString(val)) { - ERROR_LOG(Log::sceKernel, "sysclib_sprintf bad string reference at %08x", val); - return 0; - } - result.append(Memory::GetCharPointerUnchecked(val)); - processing_specifier = false; - break; - } - case 'd': - case 'i': - case 'u': - case 'o': - case 'x': - case 'X': - case 'f': - case 'e': - case 'E': - case 'g': - case 'G': - case 'c': - case 'p': - case 'n': - { - u64 val = 0; - if (bytes_to_read == 0) { - bytes_to_read = 4; - } - int read_cnt = 0; - while (bytes_to_read != 0) { - u32 val_from_arg = 0; - if (arg_idx <= 1) { - val_from_arg = currentMIPS->r[MIPS_REG_A2 + arg_idx]; - } else if (arg_idx <= 5) { - val_from_arg = currentMIPS->r[MIPS_REG_T0 + arg_idx - 2]; - } else { - int stack_idx = arg_idx - 6; - u32 stack_cur = currentMIPS->r[MIPS_REG_SP] + stack_idx * 4; - - if (!Memory::IsValid4AlignedAddress(stack_cur)) { - ERROR_LOG(Log::sceKernel, "sysclib_sprintf bad stack pointer %08x", stack_cur); - return 0; - } - val_from_arg = Memory::ReadUnchecked_U32(stack_cur); - DEBUG_LOG(Log::sceKernel, "sysclib_sprintf fetching %08x from sp + %u", val_from_arg, stack_idx * 4); - } - arg_idx++; - - val = val | ((u64)val_from_arg << (read_cnt * 32)); - - bytes_to_read = bytes_to_read - 4; - read_cnt++; - } - char buf[128] = {0}; - snprintf(buf, sizeof(buf), specifier.c_str(), val); - buf[sizeof(buf) - 1] = '\0'; - result.append(buf); - processing_specifier = false; - break; - } - case 'h': - { - // allegrex calling convention is 4 bytes aligned - bytes_to_read = 4; - break; - } - case 'l': - { - bytes_to_read = bytes_to_read + 4; - break; - } - } - } - } - const size_t retval = result.size(); // Implement the snprintf length check. @@ -888,7 +754,6 @@ static int sysclib_sprintf_impl(u32 dst, int limit, u32 fmt, int paramOffset) { VERBOSE_LOG(Log::sceKernel, "sysclib_sprintf result string has length %d (retval: %d), content:", (int)result.length(), (int)retval); VERBOSE_LOG(Log::sceKernel, "%s", result.c_str()); // Since this is a sprintf function and not an actual printf, we don't log to the Sprintf log. - // INFO_LOG(Log::Printf, "%s", result.c_str()); if (!Memory::IsValidRange(dst, (u32)result.length() + 1)) { ERROR_LOG(Log::sceKernel, "sysclib_sprintf result string is too long or dst is invalid"); return 0; @@ -899,12 +764,13 @@ static int sysclib_sprintf_impl(u32 dst, int limit, u32 fmt, int paramOffset) { static int sysclib_sprintf(u32 dst, u32 fmt) { DEBUG_LOG(Log::sceKernel, "Not fully implemented: sysclib_sprintf(dst=%08x, fmt=%08x)", dst, fmt); - return hleLogDebug(Log::sceKernel, sysclib_sprintf_impl(dst, 0, fmt, 0)); + // dst is a0 and fmt a1, so the varargs start at a2. + return hleLogDebug(Log::sceKernel, sysclib_sprintf_impl(dst, 0, fmt, 2)); } static int sysclib_snprintf(u32 dst, int size, u32 fmt) { DEBUG_LOG(Log::sceKernel, "Not fully implemented: sysclib_snprintf(dst=%08x, fmt=%08x)", dst, fmt); - return hleLogDebug(Log::sceKernel, sysclib_sprintf_impl(dst, size, fmt, 1)); + return hleLogDebug(Log::sceKernel, sysclib_sprintf_impl(dst, size, fmt, 3)); } static u32 sysclib_memset(u32 destAddr, int data, int size) {