patch.c
2322 bytes ยท Original / download
/*
* Copyright (C) 2023 Volodymyr Atamanenko
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
/**
* @file patch.c
* @brief Patching some of the .so internal functions or bridging them to native
* for better compatibility.
*/
#include <kubridge.h>
#include <so_util/so_util.h>
#include <stdio.h>
#include <string.h>
#include <vitasdk.h>
#ifdef __cplusplus
extern "C"
{
#endif
extern so_module so_mod;
#ifdef __cplusplus
};
#endif
#define SCE_KERNEL_MEMBLOCK_TYPE_USER_RX (0x0C20D050)
#include "utils/logger.h"
#include "utils/dialog.h"
#include "reimpl/sys.h"
#include <stdbool.h>
void __kuser_memory_barrier(void) {
__sync_synchronize();
}
void kuser_patch(void) {
SceKernelAllocMemBlockKernelOpt opt;
memset(&opt, 0, sizeof(SceKernelAllocMemBlockKernelOpt));
opt.size = sizeof(SceKernelAllocMemBlockKernelOpt);
opt.attr = 0x1;
opt.field_C = (SceUInt32)0x9A000000;
if (kuKernelAllocMemBlock("atomic", SCE_KERNEL_MEMBLOCK_TYPE_USER_RX, 0x1000, &opt) < 0)
fatal_error("Error could not allocate atomic block.");
kuKernelMemProtect((void *)0x9A000000, (SceSize)0x1000, KU_KERNEL_PROT_EXEC | KU_KERNEL_PROT_READ | KU_KERNEL_PROT_WRITE);
hook_addr(0x9A000FA0, (uintptr_t)__kuser_memory_barrier);
hook_addr(0x9A000FC0, (uintptr_t)__atomic_cmpxchg);
uint32_t patched_addr;
for (uint32_t addr = so_mod.text_base; addr < so_mod.text_base + so_mod.text_size; addr += 4) {
uint32_t *a = (uint32_t *)addr;
if (*a == 0xFFFF0FC0) {
l_debug("Patching 0x%x -> __kuser_cmpxchg", a);
patched_addr = 0x9A000FC0;
kuKernelCpuUnrestrictedMemcpy((void *)(addr), &patched_addr, sizeof(uint32_t));
}
else if (*a == 0xFFFF0FA0) {
l_debug("Patching 0x%x -> __kuser_memory_barrier", a);
patched_addr = 0x9A000FA0;
kuKernelCpuUnrestrictedMemcpy((void *)(addr), &patched_addr, sizeof(uint32_t));
}
}
}
void so_patch(void) {
kuser_patch();
// Sample hook with symbol name
// hook_addr((uintptr_t)so_symbol(&so_mod, "_ZN6glitch2os7Printer5printEPKcz"), (uintptr_t)&hookedFunction);
// Or with offset
// hook_addr((uintptr_t)so_mod.text_base + 0xdeadbabe, (uintptr_t)&hookedFunction);
// If you use SO_CONTINUE, define a so_hook before the function and assign to it
// function_hook = hook_addr(...);
}