### Initialize and execute PS2 runtime Source: https://github.com/ran-j/ps2recomp/wiki/Ps2xRuntime Demonstrates the minimal setup required to initialize the PS2 runtime, register recompiled functions, load an ELF file, and start execution. This serves as the primary entry point for host applications. ```cpp #include "ps2_runtime.h" #include "register_functions.h" #include #include int main(int argc, char *argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " " << std::endl; return 1; } std::string elfPath = argv[1]; PS2Runtime runtime; if (!runtime.initialize("ps2xRuntime (Raylib host)")) { std::cerr << "Failed to initialize PS2 runtime" << std::endl; return 1; } // Generated by the recompiler output revied by you registerAllFunctions(runtime); if (!runtime.loadELF(elfPath)) { std::cerr << "Failed to load ELF file: " << elfPath << std::endl; return 1; } runtime.run(); return 0; } ``` -------------------------------- ### CMake Project Setup and Dependency Fetching Source: https://github.com/ran-j/ps2recomp/blob/main/ps2xRuntime/CMakeLists.txt Initializes the CMake project, sets the C++ standard, and fetches the raylib library from GitHub. It configures build options for examples and games. ```cmake cmake_minimum_required(VERSION 3.20) project(PS2Runtime VERSION 0.1.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) include(FetchContent) set(FETCHCONTENT_QUIET FALSE) set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(BUILD_GAMES OFF CACHE BOOL "" FORCE) FetchContent_Declare( raylib GIT_REPOSITORY "https://github.com/raysan5/raylib.git" GIT_TAG "5.5" # we will migrate to 4.2.0 later, trust me it will be better GIT_PROGRESS TRUE ) FetchContent_MakeAvailable(raylib) ``` -------------------------------- ### PS2Recomp Workflow Example: Analyze, Recompile, Run Source: https://context7.com/ran-j/ps2recomp/llms.txt This bash script provides a comprehensive example of the PS2Recomp workflow, from analyzing a PS2 ELF file to recompiling and running the game on PC. It covers using the analyzer tool, manual configuration edits, recompilation, integrating generated code into the runtime, building the runtime, and finally running the game. ```bash # Step 1: Analyze ELF (quick method for debug builds) ./ps2_analyzer SLUS_203.12 config.toml # Step 1 (alternative): Use Ghidra for retail games # - Open SLUS_203.12 in Ghidra with Emotion Engine loader # - Run ps2xRecomp/tools/ghidra/ExportPS2Functions.java # - Use exported config.toml and functions.csv # Step 2: Edit config.toml as needed # - Add stubs for library functions # - Add skip for problematic functions # - Add patches for specific instructions # Step 3: Recompile ./ps2_recomp config.toml # Step 4: Integrate generated code # - Copy output/*.cpp to ps2xRuntime/src/runner/ # - Copy output/*.h to ps2xRuntime/include/ # Step 5: Build runtime with game code cd ps2xRuntime cmake -S . -B build cmake --build build --config Release # Step 6: Run ./build/ps2_runner SLUS_203.12 ``` -------------------------------- ### Example: PS2 ELF Analyzer Command Source: https://github.com/ran-j/ps2recomp/wiki/Ps2xAnalyzer An example demonstrating how to use the PS2 ELF Analyzer command-line tool. It specifies a sample input ELF file ('SLUS_203.12') and an output TOML file ('game_config.toml'). ```bash ps2_analyzer SLUS_203.12 game_config.toml ``` -------------------------------- ### Configure Function Stubs and Mappings Source: https://github.com/ran-j/ps2recomp/wiki/PS2Recomp-Stripped-Game-Walkthrough-For-LLMs Example TOML configuration for mapping function names to specific memory addresses. This is critical for resolving calls in stripped binaries. ```toml [general] stubs = [ "sceCdRead@0x00123456", "SifLoadModule@0x00127890", "ret0@0x001D9410", "ret1@0x001D5BC8", "reta0@0x0024B7C0" ] ``` -------------------------------- ### CMake Installation Rules Source: https://github.com/ran-j/ps2recomp/blob/main/ps2xRuntime/CMakeLists.txt Defines installation rules for the built targets. The 'ps2_runtime' library is installed to 'lib' directories, and the 'include' directory is installed to the system's include path. ```cmake install(TARGETS ps2_runtime LIBRARY DESTINATION lib ARCHIVE DESTINATION lib ) install(DIRECTORY include/ DESTINATION include ) ``` -------------------------------- ### TOML Configuration Structure (Example) Source: https://github.com/ran-j/ps2recomp/wiki/Ps2xAnalyzer This TOML snippet illustrates the expected structure of the configuration file generated by the PS2 ELF Analyzer. It includes sections for general settings, function stubs, functions to skip, and instruction patches. ```toml [general] input_elf = "path/to/your/elf.elf" output_toml = "path/to/your/config.toml" ghidra_output = "path/to/map.csv" [stubs] # List of library functions to be replaced by stubs "scePower_V0" = "Power" "sceCdRead_V0" = "CdRead" [skip] # List of functions to ignore (e.g., startup code) "_start" = "" "main_init" = "" [patches] # Specific instruction patches "0x80001000" = "syscall" "0x80001004" = "cop0_mfc0" ``` -------------------------------- ### CMake Project Setup and Standards Source: https://github.com/ran-j/ps2recomp/blob/main/ps2xRecomp/CMakeLists.txt Initializes CMake version, sets project name and version, and defines C++ and C standards for the project. Ensures required standards are enforced. ```cmake cmake_minimum_required(VERSION 3.20) project(PS2Recomp VERSION 0.1.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) ``` -------------------------------- ### PS2 Runtime Initialization and Execution (C++) Source: https://context7.com/ran-j/ps2recomp/llms.txt Details the setup and execution of the PS2Runtime class, which provides the execution environment for recompiled code. It covers runtime initialization, registering functions, loading an ELF file, and starting execution. ```cpp #include "ps2_runtime.h" #include "register_functions.h" int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " " << std::endl; return 1; } PS2Runtime runtime; // Initialize runtime (allocates memory, sets up subsystems) if (!runtime.initialize("My PS2 Game")) { std::cerr << "Failed to initialize PS2 runtime" << std::endl; return 1; } // Register all generated functions (from recompiler output) registerAllFunctions(runtime); // Load ELF into memory and set entry point if (!runtime.loadELF(argv[1])) { std::cerr << "Failed to load ELF: " << argv[1] << std::endl; return 1; } // Start execution runtime.run(); return 0; } ``` -------------------------------- ### Configure ps2recomp project settings Source: https://github.com/ran-j/ps2recomp/blob/main/README.md Example TOML configuration for ps2recomp, defining input paths, output preferences, function stubs, and instruction-level patches. ```toml [general] input = "path/to/game.elf" ghidra_output = "" output = "output/" single_file_output = true patch_syscalls = false patch_cop0 = true patch_cache = true stubs = ["printf", "malloc", "free"] # stripped function binding by address: # stubs = ["sceCdRead@0x00123456", "SifLoadModule@0x00127890"] # temporary return handlers: # stubs = ["ret0@0x001D9410", "ret1@0x001D5BC8", "reta0@0x0024B7C0"] # mixed example: # stubs = ["printf", "sceCdRead@0x00123456", "SifLoadModule@0x00127890"] skip = ["abort", "exit"] [patches] instructions = [ { address = "0x100004", value = "0x00000000" } ] ``` -------------------------------- ### Defining PS2Recomp Executable and Installation Source: https://github.com/ran-j/ps2recomp/blob/main/ps2xRecomp/CMakeLists.txt Defines the main executable 'ps2_recomp' using source files from 'src/runner'. It links against the previously defined 'ps2_recomp_lib'. Finally, it sets up installation rules for the executable and library, placing them in 'bin' and 'lib' directories respectively, and installs the include directory. ```cmake file(GLOB_RECURSE PS2RECOMP_EXE_SOURCES CONFIGURE_DEPENDS src/runner/*.cpp ) add_executable(ps2_recomp ${PS2RECOMP_EXE_SOURCES}) target_link_libraries(ps2_recomp PRIVATE ps2_recomp_lib ) install(TARGETS ps2_recomp ps2_recomp_lib RUNTIME DESTINATION bin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib ) install(DIRECTORY include/ DESTINATION include ) ``` -------------------------------- ### PS2 Stub Function Implementations (C++) Source: https://context7.com/ran-j/ps2recomp/llms.txt Provides example implementations for stub functions that replace standard library functions with runtime equivalents. Requires 'ps2_stubs.h' and 'ps2_runtime.h'. Handles common functions like printf and malloc, with a placeholder for unimplemented stubs. ```cpp #include "ps2_stubs.h" // Standard stub signature void myStub(uint8_t* rdram, R5900Context* ctx, PS2Runtime* runtime); // Example stubs in ps2_stubs namespace namespace ps2_stubs { // Printf stub void printf(uint8_t* rdram, R5900Context* ctx, PS2Runtime* runtime) { uint32_t fmtAddr = getRegU32(ctx, 4); const char* fmt = (const char*)getMemPtr(rdram, fmtAddr); std::printf("%s", fmt); setReturnS32(ctx, 0); } // Malloc stub void malloc(uint8_t* rdram, R5900Context* ctx, PS2Runtime* runtime) { uint32_t size = getRegU32(ctx, 4); uint32_t guestPtr = runtime->guestMalloc(size, 16); setReturnU32(ctx, guestPtr); } // TODO placeholder for unimplemented stubs void TODO_NAMED(const char* name, uint8_t* rdram, R5900Context* ctx, PS2Runtime* runtime) { std::cerr << "Warning: Unimplemented stub: " << name << std::endl; setReturnS32(ctx, 0); } } ``` -------------------------------- ### Configure PS2 Runtime I/O Paths Source: https://context7.com/ran-j/ps2recomp/llms.txt This C++ snippet demonstrates how to get, set, and auto-configure I/O paths for the PS2 runtime. It shows how to access current paths, manually set new paths, and use an ELF path to automatically configure the runtime's file system mappings. ```cpp #include "ps2_runtime.h" // Get current I/O paths const PS2Runtime::IoPaths& paths = PS2Runtime::getIoPaths(); std::cout << "ELF: " << paths.elfPath << std::endl; std::cout << "CD Root: " << paths.cdRoot << std::endl; std::cout << "Host Root: " << paths.hostRoot << std::endl; // Configure paths manually PS2Runtime::IoPaths newPaths; newPaths.elfPath = "/games/mygame/SLUS_123.45"; newPaths.elfDirectory = "/games/mygame"; newPaths.hostRoot = "/games/mygame"; newPaths.cdRoot = "/games/mygame/cd"; newPaths.mcRoot = "/saves/memcard"; newPaths.cdImage = ""; // Optional ISO path PS2Runtime::setIoPaths(newPaths); // Auto-configure from ELF path PS2Runtime::configureIoPathsFromElf("/games/mygame/SLUS_123.45"); // PS2 path translation examples: // "cdrom0:\\DATA\\FILE.DAT" -> "/games/mygame/cd/DATA/FILE.DAT" // "host0:debug.txt" -> "/games/mygame/debug.txt" // "mc0:SAVE/DATA" -> "/saves/memcard/SAVE/DATA" ``` -------------------------------- ### C++ Game Override Example for PS2Recomp Source: https://github.com/ran-j/ps2recomp/wiki/Game-Override-Hooks This C++ code demonstrates how to implement game overrides in PS2Recomp. It shows how to bind stripped addresses to existing handlers and register fully custom function replacements using the `PS2_REGISTER_GAME_OVERRIDE` macro and `ps2_game_overrides::bindAddressHandler` helper. ```cpp #include "game_overrides.h" #include "ps2_runtime.h" namespace { void applyObscureOverrides(PS2Runtime &runtime) { // Route stripped addresses to existing handlers. ps2_game_overrides::bindAddressHandler(runtime, 0x00123456u, "sceCdRead"); ps2_game_overrides::bindAddressHandler(runtime, 0x00127890u, "SifLoadModule"); // Temporary triage routing. ps2_game_overrides::bindAddressHandler(runtime, 0x0031D5F8u, "ret0"); // You can also register fully custom replacements by address. runtime.registerFunction(0x0031DD28u, [](uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime) { setReturnS32(ctx, 0); ctx->pc = getRegU32(ctx, 31); }); } } PS2_REGISTER_GAME_OVERRIDE( "obscure-us", "SLES_527.37", 0x00100008u, // entry (0 disables entry matching) 0u, // CRC32 (0 disables CRC matching) applyObscureOverrides); ``` -------------------------------- ### Command Line Usage for PS2 ELF Analyzer (Bash) Source: https://context7.com/ran-j/ps2recomp/llms.txt This bash script demonstrates the command-line usage of the `ps2_analyzer` tool. It shows basic invocation for analyzing an ELF file and generating a TOML configuration, with an example for a retail game. The output configuration includes sections for general settings, stubs, skips, and patches. ```bash # Basic usage - analyze ELF and generate TOML config ps2_analyzer your_game.elf config.toml # Example with retail game ps2_analyzer SLUS_203.12 game_config.toml # The generated config.toml contains: # - [general] section with paths # - stubs list for library functions # - skip list for initialization routines # - [patches] for problematic instructions ``` -------------------------------- ### Configure CMake Build for PS2Analyzer Source: https://github.com/ran-j/ps2recomp/blob/main/ps2xAnalyzer/CMakeLists.txt This CMake script sets up the project environment, including C++20 standard enforcement, library creation from source files, and linking against the ps2_recomp_lib dependency. It also defines the installation rules for the generated executable and library components. ```cmake cmake_minimum_required(VERSION 3.20) project(PS2Analyzer VERSION 0.1.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(PS2ANALYZER_LIB_SOURCES src/elf_analyzer.cpp ) add_library(ps2_analyzer_lib STATIC ${PS2ANALYZER_LIB_SOURCES}) target_include_directories(ps2_analyzer_lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/ps2xRecomp/include ) target_link_libraries(ps2_analyzer_lib PUBLIC ps2_recomp_lib ) add_executable(ps2_analyzer src/analyzer_main.cpp ) target_link_libraries(ps2_analyzer PRIVATE ps2_analyzer_lib ) install(TARGETS ps2_analyzer ps2_analyzer_lib RUNTIME DESTINATION bin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib ) ``` -------------------------------- ### MIPS Instruction to C++ Translation Example Source: https://github.com/ran-j/ps2recomp/blob/main/README.md Illustrates the literal translation of a MIPS R5900 instruction to its C++ equivalent within the PS2Recomp framework. This shows how basic arithmetic operations are mapped to function calls that operate on the execution context's registers. ```cpp // MIPS instruction: addiu $r4, $r4, 0x20 ctx->r4 = ADD32(ctx->r4, 0X20); ``` -------------------------------- ### Utilize PS2 Runtime Macros for Generated Code Source: https://context7.com/ran-j/ps2recomp/llms.txt Provides examples of using runtime macros for common operations in generated PS2 code, including MIPS arithmetic, register access, memory I/O, PS2 MMI SIMD instructions, VU SIMD operations, and FPU instructions. ```cpp #include "ps2_runtime_macros.h" void example_function(uint8_t* rdram, R5900Context* ctx, PS2Runtime* runtime) { // Basic MIPS arithmetic (32-bit) uint32_t sum = ADD32(a, b); uint32_t diff = SUB32(a, b); uint32_t product = MUL32(a, b); uint32_t sll = SLL32(value, 5); // Shift left logical uint32_t sra = SRA32(value, 5); // Shift right arithmetic uint32_t cmp = SLT32(a, b); // Set less than // Register access macros uint32_t a0 = GPR_U32(ctx, 4); // Get $a0 int32_t s0 = GPR_S32(ctx, 16); // Get $s0 (signed) __m128i vec = GPR_VEC(ctx, 4); // Get full 128-bit SET_GPR_U32(ctx, 2, result); // Set $v0 SET_GPR_VEC(ctx, 4, vec128); // Set 128-bit // Memory access (fast path for normal RAM) uint32_t val = FAST_READ32(addr); FAST_WRITE32(addr, val); // Memory access (handles special addresses) uint32_t io_val = READ32(0x10000000); // I/O register WRITE32(0x10000000, 0x1234); // PS2 MMI operations (128-bit SIMD) __m128i packed = PS2_PADDW(a, b); // Packed add word __m128i unpacked = PS2_PEXTLW(a, b); // Unpack low words __m128i cmpgt = PS2_PCGTW(a, b); // Packed compare GT // VU operations (float SIMD) __m128 vadd = PS2_VADD(a, b); // Vector add __m128 vmul = PS2_VMUL(a, b); // Vector multiply // FPU operations (COP1) float fadd = FPU_ADD_S(a, b); float fsqrt = FPU_SQRT_S(a); int32_t cvt = FPU_CVT_W_S(fval); // Float to int } ``` -------------------------------- ### Ghidra Integration for PS2Recomp (Bash) Source: https://context7.com/ran-j/ps2recomp/llms.txt This bash script outlines the steps for integrating Ghidra with PS2Recomp, particularly for retail or stripped games. It involves installing a Ghidra plugin, opening the ELF with the Emotion Engine loader, running an export script to generate function maps and configuration files, and then using these outputs with the `ps2_recomp` command. ```bash # 1. Install ghidra-emotionengine-reloaded plugin # 2. Open ELF in Ghidra with Emotion Engine loader # 3. Run the export script from Script Manager: # ps2xRecomp/tools/ghidra/ExportPS2Functions.java # 4. The script generates: # - functions.csv (function addresses and names) # - config.toml (recompiler configuration) # 5. Use exported files with recompiler ./ps2_recomp config.toml ``` -------------------------------- ### Unhandled Instruction Markers Source: https://github.com/ran-j/ps2recomp/wiki/Ps2xRecomp Examples of comments generated by the recompiler in the output C++ code when it encounters instructions that cannot be automatically translated. ```cpp // Unhandled opcode: // Unhandled FPU.S instruction: // Unhandled PMTHL instruction: ``` -------------------------------- ### Execute Recompilation Cycle Source: https://github.com/ran-j/ps2recomp/wiki/PS2Recomp-Stripped-Game-Walkthrough-For-LLMs The sequence of commands to analyze an ELF, recompile it into C++ code, and build the final executable. This process requires a game.toml configuration file. ```powershell .\out\build\ps2xAnalyzer\Debug\ps2_analyzer.exe game.elf game.toml .\out\build\ps2xRecomp\Debug\ps2_recomp.exe game.toml cmake --build out/build --config Debug --target ps2EntryRunner .\out\build\ps2xRuntime\Debug\ps2EntryRunner.exe game.elf ``` -------------------------------- ### Run Recompiler via CLI Source: https://github.com/ran-j/ps2recomp/wiki/Ps2xRecomp Executes the recompiler binary using a specified TOML configuration file to process an ELF and generate C++ source code. ```bash ./ps2_recomp config.toml ``` -------------------------------- ### Run PS2 ELF Analyzer (Command Line) Source: https://github.com/ran-j/ps2recomp/wiki/Ps2xAnalyzer This command executes the PS2 ELF Analyzer tool. It takes the input PS2 ELF file and the desired output TOML configuration file path as arguments. This is the primary way to use the analyzer from the command line. ```bash ps2_analyzer ``` -------------------------------- ### Fetching External Dependencies with FetchContent Source: https://github.com/ran-j/ps2recomp/blob/main/ps2xRecomp/CMakeLists.txt Uses CMake's FetchContent module to download and make available external libraries from Git repositories. This includes elfio, toml11, fmt, libdwarf, and rabbitizer. Dependencies are fetched using specific Git tags or branches. ```cmake include(FetchContent) FetchContent_Declare( elfio GIT_REPOSITORY https://github.com/serge1/ELFIO.git GIT_TAG 7d30a22fc5aac06adfe7887ae57f3701b6b5f913 GIT_SHALLOW TRUE ) FetchContent_MakeAvailable(elfio) FetchContent_Declare( toml11 GIT_REPOSITORY https://github.com/ToruNiina/toml11.git GIT_TAG master ) FetchContent_MakeAvailable(toml11) FetchContent_Declare( fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 12.1.0 ) FetchContent_MakeAvailable(fmt) FetchContent_Declare( libdwarf GIT_REPOSITORY https://github.com/davea42/libdwarf-code.git GIT_TAG v2.2.0 GIT_SHALLOW TRUE ) FetchContent_Declare( libdwarf GIT_REPOSITORY https://github.com/davea42/libdwarf-code.git GIT_TAG v2.2.0 GIT_SHALLOW TRUE ) set(BUILD_DWARFDUMP OFF CACHE BOOL "" FORCE) set(BUILD_DWARFEXAMPLE OFF CACHE BOOL "" FORCE) set(BUILD_DWARFGEN OFF CACHE BOOL "" FORCE) set(BUILD_SHARED OFF CACHE BOOL "" FORCE) set(BUILD_NON_SHARED ON CACHE BOOL "" FORCE) FetchContent_MakeAvailable(libdwarf) set(LIBDWARF_INCLUDE_DIR "${libdwarf_SOURCE_DIR}/src/lib/libdwarf") FetchContent_Declare( rabbitizer GIT_REPOSITORY https://github.com/Decompollaborate/rabbitizer.git GIT_TAG 1.14.3 ) FetchContent_MakeAvailable(rabbitizer) ``` -------------------------------- ### PS2 Recompiler Class Initialization and Recompilation (C++) Source: https://context7.com/ran-j/ps2recomp/llms.txt Demonstrates the initialization and recompilation process using the PS2Recompiler class. It reads a TOML configuration, parses an ELF file, and translates MIPS instructions to C++ code. Dependencies include the 'ps2recomp/ps2_recompiler.h' header. ```cpp #include "ps2recomp/ps2_recompiler.h" // Create recompiler with config path ps2recomp::PS2Recompiler recompiler("config.toml"); // Initialize - loads config, parses ELF, sets up decoder if (!recompiler.initialize()) { std::cerr << "Initialization failed" << std::endl; return 1; } // Recompile - translates MIPS to C++ if (!recompiler.recompile()) { std::cerr << "Recompilation failed" << std::endl; return 1; } // Generate output files recompiler.generateOutput(); // Example MIPS to C++ translation: // MIPS: addiu $r4, $r4, 0x20 // C++: ctx->r4 = ADD32(ctx->r4, 0x20); // MIPS: lw $t0, 0x10($a0) // C++: SET_GPR_S32(ctx, 8, READ32(GPR_U32(ctx, 4) + 0x10)); ``` -------------------------------- ### Build PS2Recomp Project Source: https://github.com/ran-j/ps2recomp/wiki/PS2Recomp-Stripped-Game-Walkthrough-For-LLMs Commands to configure and build the PS2Recomp toolchain using CMake. This generates the analyzer, recompiler, and runtime runner binaries. ```powershell cmake -S . -B out/build cmake --build out/build --config Debug --target ps2_analyzer ps2_recomp ps2EntryRunner ``` -------------------------------- ### PS2 Guest Memory Allocation and Management (C++) Source: https://context7.com/ran-j/ps2recomp/llms.txt Details the runtime's capabilities for managing guest memory, including heap configuration, allocation, reallocation, and freeing. Also shows how to obtain a host pointer from a guest address. Requires 'ps2_runtime.h'. ```cpp #include "ps2_runtime.h" // Configure guest heap region runtime.configureGuestHeap( 0x00200000, // Base address PS2_RAM_SIZE // Limit (32MB) ); // Allocate memory in guest address space uint32_t guestPtr = runtime.guestMalloc(1024, 16); // size, alignment if (guestPtr == 0) { // Allocation failed } // Allocate zeroed memory uint32_t guestArray = runtime.guestCalloc(100, sizeof(uint32_t), 16); // Reallocate uint32_t newPtr = runtime.guestRealloc(guestPtr, 2048, 16); // Free runtime.guestFree(guestPtr); // Get host pointer from guest address uint8_t* hostPtr = getMemPtr(rdram, guestPtr); ``` -------------------------------- ### Build PS2Recomp Project with CMake Source: https://github.com/ran-j/ps2recomp/blob/main/README.md This snippet demonstrates how to clone the PS2Recomp repository and build the project using CMake. It requires Git for cloning and CMake version 3.20 or higher for the build process. The output is placed in the 'out/build' directory. ```bash git clone --recurse-submodules https://github.com/ran-j/PS2Recomp.git cd PS2Recomp cmake -S . -B out/build cmake --build out/build --config Debug ``` -------------------------------- ### Build PS2Recomp Project with CMake Source: https://context7.com/ran-j/ps2recomp/llms.txt This bash script outlines the steps to build the PS2Recomp project using CMake. It includes cloning the repository with submodules, configuring the build, and building all targets. It also lists the build outputs and system requirements. ```bash # Clone with submodules git clone --recurse-submodules https://github.com/ran-j/PS2Recomp.git cd PS2Recomp # Configure build cmake -S . -B out/build # Build all targets cmake --build out/build --config Release # Build outputs: # out/build/ps2xAnalyzer/ps2_analyzer - ELF analyzer tool # out/build/ps2xRecomp/ps2_recomp - Recompiler tool # out/build/ps2xRuntime/libps2runtime.a - Runtime library # Requirements: # - CMake 3.20+ # - C++20 compiler (MSVC, GCC, Clang) # - SSE4/AVX support (or USE_SSE2NEON for ARM) ``` -------------------------------- ### Function Registration and Lookup in PS2 Runtime (C++) Source: https://context7.com/ran-j/ps2recomp/llms.txt Explains how the PS2 runtime manages function mapping between guest addresses and recompiled C++ functions. It shows how to define recompiled functions, register them with the runtime, and look them up for execution. ```cpp #include "ps2_runtime.h" // Signature for all recompiled functions using RecompiledFunction = void (*)(uint8_t* rdram, R5900Context* ctx, PS2Runtime* runtime); // Example recompiled function void sub_00100000(uint8_t* rdram, R5900Context* ctx, PS2Runtime* runtime) { // Generated code from recompiler ctx->r[4] = ADD32(GPR_U32(ctx, 4), 0x20); ctx->pc = GPR_U32(ctx, 31); // Return } // Register function with runtime void registerAllFunctions(PS2Runtime& runtime) { runtime.registerFunction(0x00100000, sub_00100000); runtime.registerFunction(0x00100100, sub_00100100); // ... more functions } // Look up function at runtime PS2Runtime::RecompiledFunction func = runtime.lookupFunction(0x00100000); if (func) { func(runtime.memory().getRDRAM(), &runtime.cpu(), &runtime); } // Check if function exists if (runtime.hasFunction(0x00100000)) { // Function is registered } ``` -------------------------------- ### Command Line Recompiler Usage (Bash) Source: https://context7.com/ran-j/ps2recomp/llms.txt Shows how to use the `ps2_recomp` command-line tool to perform the full recompilation pipeline. It accepts a TOML configuration file and demonstrates different output structures based on the `single_file_output` setting. ```bash # Run recompiler with TOML config ./ps2_recomp config.toml # Output structure (single_file_output = false): # output/ # recompiled_funcs.h # Function declarations # recompiled_stubs.h # Stub declarations # func_main.cpp # main function # func_printf.cpp # printf stub wrapper # sub_00100000.cpp # Unnamed function at 0x00100000 # ... # Output structure (single_file_output = true): # output/ # recompiled_funcs.h # recompiled_stubs.h # recompiled_all.cpp # All functions in one file ``` -------------------------------- ### Analyze PS2 ELF Binary and Generate TOML Configuration (C++) Source: https://context7.com/ran-j/ps2recomp/llms.txt This C++ code snippet demonstrates how to use the ElfAnalyzer class to parse a PS2 ELF binary, extract its components, and generate a TOML configuration file for the recompiler. It includes error handling and options for importing Ghidra maps. ```cpp #include "ps2recomp/elf_analyzer.h" // Create analyzer with path to PS2 ELF ps2recomp::ElfAnalyzer analyzer("path/to/game.elf"); // Analyze the ELF (extracts functions, symbols, patches) if (!analyzer.analyze()) { std::cerr << "Analysis failed" << std::endl; return 1; } // Generate TOML configuration for recompiler if (!analyzer.generateToml("config.toml")) { std::cerr << "Failed to generate TOML" << std::endl; return 1; } // Optionally import Ghidra function map for better accuracy analyzer.importGhidraMap("ghidra_functions.csv"); // Access discovered functions const std::vector& functions = analyzer.getFunctions(); for (const auto& func : functions) { std::cout << "Function: " << func.name << " at 0x" << std::hex << func.start << " - 0x" << func.end << std::endl; } ``` -------------------------------- ### Minimal C++ Game Override Module Template Source: https://github.com/ran-j/ps2recomp/wiki/PS2Recomp-Stripped-Game-Walkthrough-For-LLMs A basic C++ template for creating game override modules. It includes necessary headers, a function to register custom handlers, and the PS2_REGISTER_GAME_OVERRIDE macro for game-specific configuration. This allows for custom logic and function hooking during runtime. ```cpp #include "game_overrides.h" #include "ps2_runtime.h" #include "ps2_stubs.h" #include "ps2_syscalls.h" namespace { void applyMyGameOverrides(PS2Runtime &runtime) { // Safe direct custom wrapper that auto-returns if callee did not move PC. runtime.registerFunction(0x00123456u, [](uint8_t *rdram, R5900Context *ctx, PS2Runtime *rt) { const uint32_t entryPc = ctx->pc; ps2_stubs::sceCdRead(rdram, ctx, rt); if (ctx->pc == entryPc) { ctx->pc = getRegU32(ctx, 31); } }); // Good for explicit triage handlers that already return. ps2_game_overrides::bindAddressHandler(runtime, 0x0031D5F8u, "ret0"); } } PS2_REGISTER_GAME_OVERRIDE( "my-game-us", "SLUS_XXXX.XX", 0x00100008u, 0u, applyMyGameOverrides); ``` -------------------------------- ### Configure CMake Build and ARM64 Dependencies Source: https://github.com/ran-j/ps2recomp/blob/main/CMakeLists.txt This CMake script defines the project environment, handles conditional fetching of the sse2neon library for ARM64 systems, and applies platform-specific compiler flags for Linux, macOS, and Windows. It concludes by including the primary project subdirectories for compilation. ```cmake cmake_minimum_required(VERSION 3.21) project("PS2 Retro X") set(CMAKE_EXPORT_COMPILE_COMMANDS ON) option(PS2X_RUNTIME OFF) # ARM64 support using sse2neon if(CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64|ARM64") message(STATUS "ARM64 detected, fetching sse2neon") include(FetchContent) FetchContent_Declare( sse2neon GIT_REPOSITORY https://github.com/DLTcollab/sse2neon.git GIT_TAG v1.9.1 GIT_SHALLOW TRUE ) FetchContent_MakeAvailable(sse2neon) include_directories(${sse2neon_SOURCE_DIR}) add_compile_definitions(USE_SSE2NEON) if(APPLE) message(STATUS "macOS ARM64 - using default compiler flags") elseif(MSVC) message(STATUS "Windows ARM64 (MSVC) - using default compiler flags") else() message(STATUS "Non-Apple ARM64 - adding NEON compiler flags") add_compile_options(-march=armv8-a+fp+simd) include(CheckCXXCompilerFlag) check_cxx_compiler_flag("-march=armv8-a+fp+simd+crypto+crc" COMPILER_SUPPORTS_CRYPTO_CRC) if(COMPILER_SUPPORTS_CRYPTO_CRC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=armv8-a+fp+simd+crypto+crc") message(STATUS "Crypto and CRC extensions enabled") endif() endif() endif() add_subdirectory("ps2xRecomp") add_subdirectory("ps2xRuntime") add_subdirectory("ps2xAnalyzer") add_subdirectory("ps2xTest") add_subdirectory("ps2xStudio") ``` -------------------------------- ### Register Custom PS2 Function Implementations Source: https://github.com/ran-j/ps2recomp/blob/main/ps2xRuntime/Readme.md Defines the signature required for custom function implementations and demonstrates how to register them with the PS2Runtime instance. This allows developers to override or implement specific PS2 system calls or game functions. ```cpp void function_name(uint8_t* rdram, R5900Context* ctx, PS2Runtime *runtime); // Registering the function with the runtime runtime.registerFunction(address, function_name); ``` -------------------------------- ### C++ Runtime Override with PC Fallback Source: https://github.com/ran-j/ps2recomp/wiki/PS2Recomp-Stripped-Game-Walkthrough-For-LLMs Demonstrates registering a function with a lambda in C++ for runtime overrides. It includes a crucial safety check to prevent infinite loops by ensuring the program counter (PC) advances. If the PC remains unchanged after the handler call, it defaults to the return address (register 31). ```cpp runtime.registerFunction(0x00123456u, [](uint8_t *rdram, R5900Context *ctx, PS2Runtime *rt) { const uint32_t entryPc = ctx->pc; ps2_stubs::sceCdRead(rdram, ctx, rt); if (ctx->pc == entryPc) { ctx->pc = getRegU32(ctx, 31); } }); ``` -------------------------------- ### Access PS2 VU1 and Graphics Interfaces Source: https://context7.com/ran-j/ps2recomp/llms.txt This C++ code provides access to the PS2 runtime's VU1 (Vector Unit 1) interpreter, GS (Graphics Synthesizer), GIF arbiter, and memory interfaces. It shows how to retrieve pointers to VU1 memory, VRAM, and how to submit GIF packets and process VIF1 data. ```cpp #include "ps2_runtime.h" // Access VU1 interpreter VU1Interpreter& vu1 = runtime.vu1(); // Access GS (Graphics Synthesizer) GS& gs = runtime.gs(); // Access GIF arbiter (GIF packet routing) GifArbiter& gif = runtime.gifArbiter(); // Memory interface for graphics data PS2Memory& mem = runtime.memory(); // VU1 memory regions uint8_t* vu1Code = mem.getVU1Code(); // 16KB micro memory uint8_t* vu1Data = mem.getVU1Data(); // 16KB data memory // GS VRAM uint8_t* vram = mem.getGSVRAM(); // 4MB // Submit GIF packet mem.submitGifPacket(GifPathId::PATH3, data, sizeBytes, true); // Process VIF1 data (uploads to VU1) mem.processVIF1Data(sourcePhysAddr, sizeBytes); // Set callbacks for GIF packet processing mem.setGifPacketCallback([](const uint8_t* data, uint32_t size) { // Process GIF packet }); // Set callback for VU1 microprogram execution mem.setVu1MscalCallback([](uint32_t startPC, uint32_t itop) { // VU1 microprogram started at startPC }); ``` -------------------------------- ### PowerShell Command to Find Runtime Handler References Source: https://github.com/ran-j/ps2recomp/wiki/PS2Recomp-Stripped-Game-Walkthrough-For-LLMs A PowerShell command using 'rg' (ripgrep) to locate references to common runtime handlers within specified header and source files. This helps in understanding where specific functionalities like CD reading or module loading are invoked. ```powershell rg -n "sceCdRead|SifLoadModule|ret0|ret1|reta0" ps2xRuntime/include/ps2_call_list.h ps2xRuntime/src/lib ``` -------------------------------- ### Debug Unresolved Function Dispatches Source: https://github.com/ran-j/ps2recomp/wiki/PS2Recomp-Stripped-Game-Walkthrough-For-LLMs A command to search the generated runtime code for unresolved function lookups, which helps identify missing address bindings. ```powershell rg -n "lookupFunction\\(0x" ps2xRuntime/src/runner ``` -------------------------------- ### Analyze PS2 ELF with Native Analyzer Source: https://github.com/ran-j/ps2recomp/blob/main/README.md This command uses the native PS2Recomp analyzer to process a PS2 ELF file and generate a TOML configuration. This is a fallback method for quick local experiments or ELFs with debug symbols, and is generally less accurate on stripped retail games compared to the Ghidra workflow. ```bash ./ps2_analyzer your_game.elf config.toml ```