├── .github └── workflows │ └── validate.yml ├── .gitignore ├── .gitmodules ├── CMakeLists.txt ├── LICENSE ├── LiveRecomp ├── live_generator.cpp └── live_recompiler_test.cpp ├── OfflineModRecomp └── main.cpp ├── README.md ├── RSPRecomp └── src │ └── rsp_recomp.cpp ├── RecompModTool └── main.cpp ├── include ├── recomp.h └── recompiler │ ├── context.h │ ├── generator.h │ ├── live_recompiler.h │ └── operations.h └── src ├── analysis.cpp ├── analysis.h ├── cgenerator.cpp ├── config.cpp ├── config.h ├── elf.cpp ├── main.cpp ├── mod_symbols.cpp ├── operations.cpp ├── recompilation.cpp └── symbol_lists.cpp /.github/workflows/validate.yml: -------------------------------------------------------------------------------- 1 | name: validate 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | types: [opened, synchronize] 8 | concurrency: 9 | group: ${{ github.workflow }}-${{ github.ref }} 10 | cancel-in-progress: true 11 | jobs: 12 | build: 13 | runs-on: ${{ matrix.os }} 14 | strategy: 15 | matrix: 16 | type: [ Debug, Release ] 17 | # macos-13 is intel, macos-14 is arm, blaze/ubuntu-22.04 is arm 18 | os: [ ubuntu-latest, windows-latest, macos-13, macos-14, blaze/ubuntu-22.04 ] 19 | name: ${{ matrix.os }} (${{ (matrix.os == 'macos-14' || matrix.os == 'blaze/ubuntu-22.04') && 'arm64' || 'x64' }}, ${{ matrix.type }}) 20 | steps: 21 | - name: Checkout 22 | uses: actions/checkout@v4 23 | with: 24 | submodules: true 25 | - name: ccache 26 | uses: hendrikmuhs/ccache-action@v1.2 27 | with: 28 | key: ${{ matrix.os }}-N64Recomp-ccache-${{ matrix.type }} 29 | - name: Install Windows Dependencies 30 | if: runner.os == 'Windows' 31 | run: | 32 | choco install ninja 33 | Remove-Item -Path "C:\ProgramData\Chocolatey\bin\ccache.exe" -Force -ErrorAction SilentlyContinue 34 | - name: Install Linux Dependencies 35 | if: runner.os == 'Linux' 36 | run: | 37 | sudo apt-get update 38 | sudo apt-get install -y ninja-build 39 | - name: Install macOS Dependencies 40 | if: runner.os == 'macOS' 41 | run: | 42 | brew install ninja 43 | - name: Configure Developer Command Prompt 44 | if: runner.os == 'Windows' 45 | uses: ilammy/msvc-dev-cmd@v1 46 | - name: Build N64Recomp (Unix) 47 | if: runner.os != 'Windows' 48 | run: |- 49 | # enable ccache 50 | export PATH="/usr/lib/ccache:/usr/local/opt/ccache/libexec:$PATH" 51 | 52 | cmake -DCMAKE_BUILD_TYPE=${{ matrix.type }} -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_MAKE_PROGRAM=ninja -G Ninja -S . -B cmake-build 53 | cmake --build cmake-build --config ${{ matrix.type }} --target N64Recomp -j $(nproc) 54 | - name: Build N64Recomp (Windows) 55 | if: runner.os == 'Windows' 56 | run: |- 57 | # enable ccache 58 | set $env:PATH="$env:USERPROFILE/.cargo/bin;$env:PATH" 59 | $cpuCores = (Get-CimInstance -ClassName Win32_Processor).NumberOfLogicalProcessors 60 | 61 | # remove LLVM from PATH so it doesn't overshadow the one provided by VS 62 | $env:PATH = ($env:PATH -split ';' | Where-Object { $_ -ne 'C:\Program Files\LLVM\bin' }) -join ';' 63 | 64 | cmake -DCMAKE_BUILD_TYPE=${{ matrix.type }} -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_MAKE_PROGRAM=ninja -G Ninja -S . -B cmake-build 65 | cmake --build cmake-build --config ${{ matrix.type }} --target N64Recomp -j $cpuCores 66 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # VSCode file settings 2 | .vscode/settings.json 3 | .vscode/c_cpp_properties.json 4 | 5 | # Input elf and rom files 6 | *.elf 7 | *.z64 8 | 9 | # Local working data 10 | tests 11 | 12 | # Linux build output 13 | build/ 14 | *.o 15 | 16 | # Windows build output 17 | *.exe 18 | 19 | # User-specific files 20 | *.rsuser 21 | *.suo 22 | *.user 23 | *.userosscache 24 | *.sln.docstates 25 | 26 | # Build results 27 | [Dd]ebug/ 28 | [Dd]ebugPublic/ 29 | [Rr]elease/ 30 | [Rr]eleases/ 31 | x64/ 32 | x86/ 33 | [Ww][Ii][Nn]32/ 34 | [Aa][Rr][Mm]/ 35 | [Aa][Rr][Mm]64/ 36 | bld/ 37 | [Bb]in/ 38 | [Oo]bj/ 39 | [Ll]og/ 40 | [Ll]ogs/ 41 | 42 | # Visual Studio 2015/2017 cache/options directory 43 | .vs/ 44 | 45 | # Runtime files 46 | imgui.ini 47 | rt64.log 48 | .idea 49 | cmake-build* 50 | .DS_Store 51 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/rabbitizer"] 2 | path = lib/rabbitizer 3 | url = https://github.com/Decompollaborate/rabbitizer 4 | [submodule "lib/ELFIO"] 5 | path = lib/ELFIO 6 | url = https://github.com/serge1/ELFIO 7 | [submodule "lib/fmt"] 8 | path = lib/fmt 9 | url = https://github.com/fmtlib/fmt 10 | [submodule "lib/tomlplusplus"] 11 | path = lib/tomlplusplus 12 | url = https://github.com/marzer/tomlplusplus 13 | [submodule "lib/sljit"] 14 | path = lib/sljit 15 | url = https://github.com/zherczeg/sljit 16 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.20) 2 | set(CMAKE_C_STANDARD 17) 3 | set(CMAKE_CXX_STANDARD 20) 4 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 5 | set(CMAKE_CXX_EXTENSIONS OFF) 6 | # set(CMAKE_CXX_VISIBILITY_PRESET hidden) 7 | 8 | # Rabbitizer 9 | project(rabbitizer) 10 | add_library(rabbitizer STATIC) 11 | 12 | target_sources(rabbitizer PRIVATE 13 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/src/analysis/LoPairingInfo.cpp" 14 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/src/analysis/RegistersTracker.cpp" 15 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/src/instructions/InstrId.cpp" 16 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/src/instructions/InstrIdType.cpp" 17 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/src/instructions/InstructionBase.cpp" 18 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/src/instructions/InstructionCpu.cpp" 19 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/src/instructions/InstructionR3000GTE.cpp" 20 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/src/instructions/InstructionR5900.cpp" 21 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/src/instructions/InstructionRsp.cpp" 22 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/analysis/RabbitizerLoPairingInfo.c" 23 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/analysis/RabbitizerRegistersTracker.c" 24 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/analysis/RabbitizerTrackedRegisterState.c" 25 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/common/RabbitizerConfig.c" 26 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/common/RabbitizerVersion.c" 27 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/common/Utils.c" 28 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstrCategory.c" 29 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstrDescriptor.c" 30 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstrId.c" 31 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstrIdType.c" 32 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstrSuffix.c" 33 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionCpu/RabbitizerInstructionCpu_OperandType.c" 34 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionR3000GTE/RabbitizerInstructionR3000GTE.c" 35 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionR3000GTE/RabbitizerInstructionR3000GTE_OperandType.c" 36 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionR3000GTE/RabbitizerInstructionR3000GTE_ProcessUniqueId.c" 37 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionR5900/RabbitizerInstructionR5900.c" 38 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionR5900/RabbitizerInstructionR5900_OperandType.c" 39 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionR5900/RabbitizerInstructionR5900_ProcessUniqueId.c" 40 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionRsp/RabbitizerInstructionRsp.c" 41 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionRsp/RabbitizerInstructionRsp_OperandType.c" 42 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstructionRsp/RabbitizerInstructionRsp_ProcessUniqueId.c" 43 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstruction/RabbitizerInstruction.c" 44 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstruction/RabbitizerInstruction_Disassemble.c" 45 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstruction/RabbitizerInstruction_Examination.c" 46 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstruction/RabbitizerInstruction_Operand.c" 47 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerInstruction/RabbitizerInstruction_ProcessUniqueId.c" 48 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerRegister.c" 49 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/src/instructions/RabbitizerRegisterDescriptor.c") 50 | 51 | target_include_directories(rabbitizer PUBLIC 52 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/include" 53 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/cplusplus/include") 54 | 55 | target_include_directories(rabbitizer PRIVATE 56 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/rabbitizer/tables") 57 | 58 | # fmtlib 59 | add_subdirectory(lib/fmt) 60 | 61 | # tomlplusplus 62 | set(TOML_ENABLE_FORMATTERS OFF) 63 | add_subdirectory(lib/tomlplusplus) 64 | 65 | # Hardcoded symbol lists (separate library to not force a dependency on N64Recomp) 66 | project(SymbolLists) 67 | add_library(SymbolLists) 68 | 69 | target_sources(SymbolLists PRIVATE 70 | ${CMAKE_CURRENT_SOURCE_DIR}/src/symbol_lists.cpp 71 | ) 72 | 73 | target_include_directories(SymbolLists PUBLIC 74 | "${CMAKE_CURRENT_SOURCE_DIR}/include" 75 | ) 76 | 77 | # N64 recompiler core library 78 | project(N64Recomp) 79 | add_library(N64Recomp) 80 | 81 | target_sources(N64Recomp PRIVATE 82 | ${CMAKE_CURRENT_SOURCE_DIR}/src/analysis.cpp 83 | ${CMAKE_CURRENT_SOURCE_DIR}/src/operations.cpp 84 | ${CMAKE_CURRENT_SOURCE_DIR}/src/cgenerator.cpp 85 | ${CMAKE_CURRENT_SOURCE_DIR}/src/recompilation.cpp 86 | ${CMAKE_CURRENT_SOURCE_DIR}/src/mod_symbols.cpp 87 | ) 88 | 89 | target_include_directories(N64Recomp PUBLIC 90 | "${CMAKE_CURRENT_SOURCE_DIR}/include" 91 | ) 92 | 93 | target_link_libraries(N64Recomp SymbolLists fmt rabbitizer tomlplusplus::tomlplusplus) 94 | 95 | # N64 recompiler elf parsing 96 | project(N64RecompElf) 97 | add_library(N64RecompElf) 98 | 99 | target_sources(N64RecompElf PRIVATE 100 | ${CMAKE_CURRENT_SOURCE_DIR}/src/elf.cpp 101 | ${CMAKE_CURRENT_SOURCE_DIR}/src/symbol_lists.cpp 102 | ) 103 | 104 | target_include_directories(N64RecompElf PUBLIC 105 | "${CMAKE_CURRENT_SOURCE_DIR}/include" 106 | ) 107 | 108 | target_include_directories(N64RecompElf PRIVATE 109 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/ELFIO" 110 | ) 111 | 112 | target_link_libraries(N64RecompElf fmt) 113 | 114 | # N64 recompiler executable 115 | project(N64RecompCLI) 116 | add_executable(N64RecompCLI) 117 | 118 | target_sources(N64RecompCLI PRIVATE 119 | ${CMAKE_CURRENT_SOURCE_DIR}/src/config.cpp 120 | ${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp 121 | ) 122 | 123 | target_include_directories(N64RecompCLI PRIVATE 124 | "${CMAKE_CURRENT_SOURCE_DIR}/include" 125 | ) 126 | 127 | target_link_libraries(N64RecompCLI fmt rabbitizer tomlplusplus::tomlplusplus N64Recomp N64RecompElf) 128 | set_target_properties(N64RecompCLI PROPERTIES OUTPUT_NAME N64Recomp) 129 | 130 | # RSP recompiler 131 | project(RSPRecomp) 132 | add_executable(RSPRecomp) 133 | 134 | target_include_directories(RSPRecomp PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include") 135 | 136 | target_link_libraries(RSPRecomp fmt rabbitizer tomlplusplus::tomlplusplus) 137 | 138 | target_sources(RSPRecomp PRIVATE 139 | ${CMAKE_CURRENT_SOURCE_DIR}/RSPRecomp/src/rsp_recomp.cpp) 140 | 141 | # Mod tool 142 | project(RecompModTool) 143 | add_executable(RecompModTool) 144 | 145 | target_sources(RecompModTool PRIVATE 146 | ${CMAKE_CURRENT_SOURCE_DIR}/src/config.cpp 147 | ${CMAKE_CURRENT_SOURCE_DIR}/src/mod_symbols.cpp 148 | ${CMAKE_CURRENT_SOURCE_DIR}/RecompModTool/main.cpp 149 | ) 150 | 151 | target_include_directories(RecompModTool PRIVATE 152 | ${CMAKE_CURRENT_SOURCE_DIR}/lib/ELFIO 153 | ) 154 | 155 | target_link_libraries(RecompModTool fmt tomlplusplus::tomlplusplus N64RecompElf) 156 | 157 | # Offline mod recompiler 158 | project(OfflineModRecomp) 159 | add_executable(OfflineModRecomp) 160 | 161 | target_sources(OfflineModRecomp PRIVATE 162 | ${CMAKE_CURRENT_SOURCE_DIR}/src/config.cpp 163 | ${CMAKE_CURRENT_SOURCE_DIR}/OfflineModRecomp/main.cpp 164 | ) 165 | 166 | target_link_libraries(OfflineModRecomp fmt rabbitizer tomlplusplus::tomlplusplus N64Recomp) 167 | 168 | # Live recompiler 169 | project(LiveRecomp) 170 | add_library(LiveRecomp) 171 | 172 | target_sources(LiveRecomp PRIVATE 173 | ${CMAKE_CURRENT_SOURCE_DIR}/LiveRecomp/live_generator.cpp 174 | ${CMAKE_CURRENT_SOURCE_DIR}/lib/sljit/sljit_src/sljitLir.c 175 | ) 176 | 177 | target_include_directories(LiveRecomp PRIVATE 178 | ${CMAKE_CURRENT_SOURCE_DIR}/lib/sljit/sljit_src 179 | ) 180 | 181 | target_link_libraries(LiveRecomp N64Recomp) 182 | 183 | # Live recompiler test 184 | project(LiveRecompTest) 185 | add_executable(LiveRecompTest) 186 | 187 | target_sources(LiveRecompTest PRIVATE 188 | ${CMAKE_CURRENT_SOURCE_DIR}/LiveRecomp/live_recompiler_test.cpp 189 | ) 190 | 191 | target_include_directories(LiveRecompTest PRIVATE 192 | ${CMAKE_CURRENT_SOURCE_DIR}/lib/sljit/sljit_src 193 | ) 194 | 195 | target_link_libraries(LiveRecompTest LiveRecomp) 196 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2024 Wiseguy 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /LiveRecomp/live_recompiler_test.cpp: -------------------------------------------------------------------------------- 1 | #include <fstream> 2 | #include <chrono> 3 | #include <filesystem> 4 | #include <cinttypes> 5 | 6 | #include "sljitLir.h" 7 | #include "recompiler/live_recompiler.h" 8 | #include "recomp.h" 9 | 10 | static std::vector<uint8_t> read_file(const std::filesystem::path& path, bool& found) { 11 | std::vector<uint8_t> ret; 12 | found = false; 13 | 14 | std::ifstream file{ path, std::ios::binary}; 15 | 16 | if (file.good()) { 17 | file.seekg(0, std::ios::end); 18 | ret.resize(file.tellg()); 19 | file.seekg(0, std::ios::beg); 20 | 21 | file.read(reinterpret_cast<char*>(ret.data()), ret.size()); 22 | found = true; 23 | } 24 | 25 | return ret; 26 | } 27 | 28 | 29 | uint32_t read_u32_swap(const std::vector<uint8_t>& vec, size_t offset) { 30 | return byteswap(*reinterpret_cast<const uint32_t*>(&vec[offset])); 31 | } 32 | 33 | uint32_t read_u32(const std::vector<uint8_t>& vec, size_t offset) { 34 | return *reinterpret_cast<const uint32_t*>(&vec[offset]); 35 | } 36 | 37 | std::vector<uint8_t> rdram; 38 | 39 | void byteswap_copy(uint8_t* dst, uint8_t* src, size_t count) { 40 | for (size_t i = 0; i < count; i++) { 41 | dst[i ^ 3] = src[i]; 42 | } 43 | } 44 | 45 | bool byteswap_compare(uint8_t* a, uint8_t* b, size_t count) { 46 | for (size_t i = 0; i < count; i++) { 47 | if (a[i ^ 3] != b[i]) { 48 | return false; 49 | } 50 | } 51 | return true; 52 | } 53 | 54 | enum class TestError { 55 | Success, 56 | FailedToOpenInput, 57 | FailedToRecompile, 58 | UnknownStructType, 59 | DataDifference 60 | }; 61 | 62 | struct TestStats { 63 | TestError error; 64 | uint64_t codegen_microseconds; 65 | uint64_t execution_microseconds; 66 | uint64_t code_size; 67 | }; 68 | 69 | void write1(uint8_t* rdram, recomp_context* ctx) { 70 | MEM_B(0, ctx->r4) = 1; 71 | } 72 | 73 | recomp_func_t* test_get_function(int32_t vram) { 74 | if (vram == 0x80100000) { 75 | return write1; 76 | } 77 | assert(false); 78 | return nullptr; 79 | } 80 | 81 | void test_switch_error(const char* func, uint32_t vram, uint32_t jtbl) { 82 | printf(" Switch-case out of bounds in %s at 0x%08X for jump table at 0x%08X\n", func, vram, jtbl); 83 | } 84 | 85 | TestStats run_test(const std::filesystem::path& tests_dir, const std::string& test_name) { 86 | std::filesystem::path input_path = tests_dir / (test_name + "_data.bin"); 87 | std::filesystem::path data_dump_path = tests_dir / (test_name + "_data_out.bin"); 88 | 89 | bool found; 90 | std::vector<uint8_t> file_data = read_file(input_path, found); 91 | 92 | if (!found) { 93 | printf("Failed to open file: %s\n", input_path.string().c_str()); 94 | return { TestError::FailedToOpenInput }; 95 | } 96 | 97 | // Parse the test file. 98 | uint32_t text_offset = read_u32_swap(file_data, 0x00); 99 | uint32_t text_length = read_u32_swap(file_data, 0x04); 100 | uint32_t init_data_offset = read_u32_swap(file_data, 0x08); 101 | uint32_t good_data_offset = read_u32_swap(file_data, 0x0C); 102 | uint32_t data_length = read_u32_swap(file_data, 0x10); 103 | uint32_t text_address = read_u32_swap(file_data, 0x14); 104 | uint32_t data_address = read_u32_swap(file_data, 0x18); 105 | uint32_t next_struct_address = read_u32_swap(file_data, 0x1C); 106 | 107 | recomp_context ctx{}; 108 | 109 | byteswap_copy(&rdram[text_address - 0x80000000], &file_data[text_offset], text_length); 110 | byteswap_copy(&rdram[data_address - 0x80000000], &file_data[init_data_offset], data_length); 111 | 112 | // Build recompiler context. 113 | N64Recomp::Context context{}; 114 | 115 | // Move the file data into the context. 116 | context.rom = std::move(file_data); 117 | 118 | context.sections.resize(2); 119 | // Create a section for the function to exist in. 120 | context.sections[0].ram_addr = text_address; 121 | context.sections[0].rom_addr = text_offset; 122 | context.sections[0].size = text_length; 123 | context.sections[0].name = ".text"; 124 | context.sections[0].executable = true; 125 | context.sections[0].relocatable = true; 126 | context.section_functions.resize(context.sections.size()); 127 | // Create a section for .data (used for relocations) 128 | context.sections[1].ram_addr = data_address; 129 | context.sections[1].rom_addr = init_data_offset; 130 | context.sections[1].size = data_length; 131 | context.sections[1].name = ".data"; 132 | context.sections[1].executable = false; 133 | context.sections[1].relocatable = true; 134 | 135 | size_t start_func_index; 136 | uint32_t function_desc_address = 0; 137 | uint32_t reloc_desc_address = 0; 138 | 139 | // Read any extra structs. 140 | while (next_struct_address != 0) { 141 | uint32_t cur_struct_address = next_struct_address; 142 | uint32_t struct_type = read_u32_swap(context.rom, next_struct_address + 0x00); 143 | next_struct_address = read_u32_swap(context.rom, next_struct_address + 0x04); 144 | 145 | switch (struct_type) { 146 | case 1: // Function desc 147 | function_desc_address = cur_struct_address; 148 | break; 149 | case 2: // Relocation 150 | reloc_desc_address = cur_struct_address; 151 | break; 152 | default: 153 | printf("Unknown struct type %u\n", struct_type); 154 | return { TestError::UnknownStructType }; 155 | } 156 | } 157 | 158 | // Check if a function description exists. 159 | if (function_desc_address == 0) { 160 | // No function description, so treat the whole thing as one function. 161 | 162 | // Get the function's instruction words. 163 | std::vector<uint32_t> text_words{}; 164 | text_words.resize(text_length / sizeof(uint32_t)); 165 | for (size_t i = 0; i < text_words.size(); i++) { 166 | text_words[i] = read_u32(context.rom, text_offset + i * sizeof(uint32_t)); 167 | } 168 | 169 | // Add the function to the context. 170 | context.functions_by_vram[text_address].emplace_back(context.functions.size()); 171 | context.section_functions.emplace_back(context.functions.size()); 172 | context.sections[0].function_addrs.emplace_back(text_address); 173 | context.functions.emplace_back( 174 | text_address, 175 | text_offset, 176 | text_words, 177 | "test_func", 178 | 0 179 | ); 180 | start_func_index = 0; 181 | } 182 | else { 183 | // Use the function description. 184 | uint32_t num_funcs = read_u32_swap(context.rom, function_desc_address + 0x08); 185 | start_func_index = read_u32_swap(context.rom, function_desc_address + 0x0C); 186 | 187 | for (size_t func_index = 0; func_index < num_funcs; func_index++) { 188 | uint32_t cur_func_address = read_u32_swap(context.rom, function_desc_address + 0x10 + 0x00 + 0x08 * func_index); 189 | uint32_t cur_func_length = read_u32_swap(context.rom, function_desc_address + 0x10 + 0x04 + 0x08 * func_index); 190 | uint32_t cur_func_offset = cur_func_address - text_address + text_offset; 191 | 192 | // Get the function's instruction words. 193 | std::vector<uint32_t> text_words{}; 194 | text_words.resize(cur_func_length / sizeof(uint32_t)); 195 | for (size_t i = 0; i < text_words.size(); i++) { 196 | text_words[i] = read_u32(context.rom, cur_func_offset + i * sizeof(uint32_t)); 197 | } 198 | 199 | // Add the function to the context. 200 | context.functions_by_vram[cur_func_address].emplace_back(context.functions.size()); 201 | context.section_functions.emplace_back(context.functions.size()); 202 | context.sections[0].function_addrs.emplace_back(cur_func_address); 203 | context.functions.emplace_back( 204 | cur_func_address, 205 | cur_func_offset, 206 | std::move(text_words), 207 | "test_func_" + std::to_string(func_index), 208 | 0 209 | ); 210 | } 211 | } 212 | 213 | // Check if a relocation description exists. 214 | if (reloc_desc_address != 0) { 215 | uint32_t num_relocs = read_u32_swap(context.rom, reloc_desc_address + 0x08); 216 | for (uint32_t reloc_index = 0; reloc_index < num_relocs; reloc_index++) { 217 | uint32_t cur_desc_address = reloc_desc_address + 0x0C + reloc_index * 4 * sizeof(uint32_t); 218 | uint32_t reloc_type = read_u32_swap(context.rom, cur_desc_address + 0x00); 219 | uint32_t reloc_section = read_u32_swap(context.rom, cur_desc_address + 0x04); 220 | uint32_t reloc_address = read_u32_swap(context.rom, cur_desc_address + 0x08); 221 | uint32_t reloc_target_offset = read_u32_swap(context.rom, cur_desc_address + 0x0C); 222 | 223 | context.sections[0].relocs.emplace_back(N64Recomp::Reloc{ 224 | .address = reloc_address, 225 | .target_section_offset = reloc_target_offset, 226 | .symbol_index = 0, 227 | .target_section = static_cast<uint16_t>(reloc_section), 228 | .type = static_cast<N64Recomp::RelocType>(reloc_type), 229 | .reference_symbol = false 230 | }); 231 | } 232 | } 233 | 234 | std::vector<std::vector<uint32_t>> dummy_static_funcs{}; 235 | std::vector<int32_t> section_addresses{}; 236 | section_addresses.emplace_back(text_address); 237 | section_addresses.emplace_back(data_address); 238 | 239 | auto before_codegen = std::chrono::system_clock::now(); 240 | 241 | N64Recomp::LiveGeneratorInputs generator_inputs { 242 | .switch_error = test_switch_error, 243 | .get_function = test_get_function, 244 | .reference_section_addresses = nullptr, 245 | .local_section_addresses = section_addresses.data() 246 | }; 247 | 248 | // Create the sljit compiler and the generator. 249 | N64Recomp::LiveGenerator generator{ context.functions.size(), generator_inputs }; 250 | 251 | for (size_t func_index = 0; func_index < context.functions.size(); func_index++) { 252 | std::ostringstream dummy_ostream{}; 253 | 254 | //sljit_emit_op0(compiler, SLJIT_BREAKPOINT); 255 | 256 | if (!N64Recomp::recompile_function_live(generator, context, func_index, dummy_ostream, dummy_static_funcs, true)) { 257 | return { TestError::FailedToRecompile }; 258 | } 259 | } 260 | 261 | // Generate the code. 262 | N64Recomp::LiveGeneratorOutput output = generator.finish(); 263 | 264 | auto after_codegen = std::chrono::system_clock::now(); 265 | 266 | auto before_execution = std::chrono::system_clock::now(); 267 | 268 | int old_rounding = fegetround(); 269 | 270 | // Run the generated code. 271 | ctx.r29 = 0xFFFFFFFF80000000 + rdram.size() - 0x10; // Set the stack pointer. 272 | output.functions[start_func_index](rdram.data(), &ctx); 273 | 274 | fesetround(old_rounding); 275 | 276 | auto after_execution = std::chrono::system_clock::now(); 277 | 278 | // Check the result of running the code. 279 | bool good = byteswap_compare(&rdram[data_address - 0x80000000], &context.rom[good_data_offset], data_length); 280 | 281 | // Dump the data if the results don't match. 282 | if (!good) { 283 | std::ofstream data_dump_file{ data_dump_path, std::ios::binary }; 284 | std::vector<uint8_t> data_swapped; 285 | data_swapped.resize(data_length); 286 | byteswap_copy(data_swapped.data(), &rdram[data_address - 0x80000000], data_length); 287 | data_dump_file.write(reinterpret_cast<char*>(data_swapped.data()), data_length); 288 | return { TestError::DataDifference }; 289 | } 290 | 291 | // Return the test's stats. 292 | TestStats ret{}; 293 | ret.error = TestError::Success; 294 | ret.codegen_microseconds = std::chrono::duration_cast<std::chrono::microseconds>(after_codegen - before_codegen).count(); 295 | ret.execution_microseconds = std::chrono::duration_cast<std::chrono::microseconds>(after_execution - before_execution).count(); 296 | ret.code_size = output.code_size; 297 | 298 | return ret; 299 | } 300 | 301 | int main(int argc, const char** argv) { 302 | if (argc < 3) { 303 | printf("Usage: %s [test directory] [test 1] ...\n", argv[0]); 304 | return EXIT_SUCCESS; 305 | } 306 | 307 | N64Recomp::live_recompiler_init(); 308 | 309 | rdram.resize(0x8000000); 310 | 311 | // Skip the first argument (program name) and second argument (test directory). 312 | int count = argc - 1 - 1; 313 | int passed_count = 0; 314 | 315 | std::vector<size_t> failed_tests{}; 316 | 317 | for (size_t test_index = 0; test_index < count; test_index++) { 318 | const char* cur_test_name = argv[2 + test_index]; 319 | printf("Running test: %s\n", cur_test_name); 320 | TestStats stats = run_test(argv[1], cur_test_name); 321 | 322 | switch (stats.error) { 323 | case TestError::Success: 324 | printf(" Success\n"); 325 | printf(" Generated %" PRIu64 " bytes in %" PRIu64 " microseconds and ran in %" PRIu64 " microseconds\n", 326 | stats.code_size, stats.codegen_microseconds, stats.execution_microseconds); 327 | passed_count++; 328 | break; 329 | case TestError::FailedToOpenInput: 330 | printf(" Failed to open input data file\n"); 331 | break; 332 | case TestError::FailedToRecompile: 333 | printf(" Failed to recompile\n"); 334 | break; 335 | case TestError::UnknownStructType: 336 | printf(" Unknown additional data struct type in test data\n"); 337 | break; 338 | case TestError::DataDifference: 339 | printf(" Output data did not match, dumped to file\n"); 340 | break; 341 | } 342 | 343 | if (stats.error != TestError::Success) { 344 | failed_tests.emplace_back(test_index); 345 | } 346 | 347 | printf("\n"); 348 | } 349 | 350 | printf("Passed %d/%d tests\n", passed_count, count); 351 | if (!failed_tests.empty()) { 352 | printf(" Failed: "); 353 | for (size_t i = 0; i < failed_tests.size(); i++) { 354 | size_t test_index = failed_tests[i]; 355 | 356 | printf("%s", argv[2 + test_index]); 357 | if (i != failed_tests.size() - 1) { 358 | printf(", "); 359 | } 360 | } 361 | printf("\n"); 362 | } 363 | return 0; 364 | } 365 | -------------------------------------------------------------------------------- /OfflineModRecomp/main.cpp: -------------------------------------------------------------------------------- 1 | #include <filesystem> 2 | #include <fstream> 3 | #include <vector> 4 | #include <span> 5 | 6 | #include "recompiler/context.h" 7 | #include "rabbitizer.hpp" 8 | 9 | static std::vector<uint8_t> read_file(const std::filesystem::path& path, bool& found) { 10 | std::vector<uint8_t> ret; 11 | found = false; 12 | 13 | std::ifstream file{ path, std::ios::binary}; 14 | 15 | if (file.good()) { 16 | file.seekg(0, std::ios::end); 17 | ret.resize(file.tellg()); 18 | file.seekg(0, std::ios::beg); 19 | 20 | file.read(reinterpret_cast<char*>(ret.data()), ret.size()); 21 | found = true; 22 | } 23 | 24 | return ret; 25 | } 26 | 27 | int main(int argc, const char** argv) { 28 | if (argc != 5) { 29 | printf("Usage: %s [mod symbol file] [mod binary file] [recomp symbols file] [output C file]\n", argv[0]); 30 | return EXIT_SUCCESS; 31 | } 32 | bool found; 33 | std::vector<uint8_t> symbol_data = read_file(argv[1], found); 34 | if (!found) { 35 | fprintf(stderr, "Failed to open symbol file\n"); 36 | return EXIT_FAILURE; 37 | } 38 | 39 | std::vector<uint8_t> rom_data = read_file(argv[2], found); 40 | if (!found) { 41 | fprintf(stderr, "Failed to open ROM\n"); 42 | return EXIT_FAILURE; 43 | } 44 | 45 | std::span<const char> symbol_data_span { reinterpret_cast<const char*>(symbol_data.data()), symbol_data.size() }; 46 | 47 | std::vector<uint8_t> dummy_rom{}; 48 | N64Recomp::Context reference_context{}; 49 | if (!N64Recomp::Context::from_symbol_file(argv[3], std::move(dummy_rom), reference_context, false)) { 50 | printf("Failed to load provided function reference symbol file\n"); 51 | return EXIT_FAILURE; 52 | } 53 | 54 | //for (const std::filesystem::path& cur_data_sym_path : data_reference_syms_file_paths) { 55 | // if (!reference_context.read_data_reference_syms(cur_data_sym_path)) { 56 | // printf("Failed to load provided data reference symbol file\n"); 57 | // return EXIT_FAILURE; 58 | // } 59 | //} 60 | 61 | std::unordered_map<uint32_t, uint16_t> sections_by_vrom{}; 62 | for (uint16_t section_index = 0; section_index < reference_context.sections.size(); section_index++) { 63 | sections_by_vrom[reference_context.sections[section_index].rom_addr] = section_index; 64 | } 65 | 66 | N64Recomp::Context mod_context; 67 | 68 | N64Recomp::ModSymbolsError error = N64Recomp::parse_mod_symbols(symbol_data_span, rom_data, sections_by_vrom, mod_context); 69 | if (error != N64Recomp::ModSymbolsError::Good) { 70 | fprintf(stderr, "Error parsing mod symbols: %d\n", (int)error); 71 | return EXIT_FAILURE; 72 | } 73 | 74 | mod_context.import_reference_context(reference_context); 75 | 76 | // Populate R_MIPS_26 reloc symbol indices. Start by building a map of vram address to matching reference symbols. 77 | std::unordered_map<uint32_t, std::vector<size_t>> reference_symbols_by_vram{}; 78 | for (size_t reference_symbol_index = 0; reference_symbol_index < mod_context.num_regular_reference_symbols(); reference_symbol_index++) { 79 | const auto& sym = mod_context.get_regular_reference_symbol(reference_symbol_index); 80 | uint16_t section_index = sym.section_index; 81 | if (section_index != N64Recomp::SectionAbsolute) { 82 | uint32_t section_vram = mod_context.get_reference_section_vram(section_index); 83 | reference_symbols_by_vram[section_vram + sym.section_offset].push_back(reference_symbol_index); 84 | } 85 | } 86 | 87 | // Use the mapping to populate the symbol index for every R_MIPS_26 reference symbol reloc. 88 | for (auto& section : mod_context.sections) { 89 | for (auto& reloc : section.relocs) { 90 | if (reloc.type == N64Recomp::RelocType::R_MIPS_26 && reloc.reference_symbol) { 91 | if (mod_context.is_regular_reference_section(reloc.target_section)) { 92 | uint32_t section_vram = mod_context.get_reference_section_vram(reloc.target_section); 93 | uint32_t target_vram = section_vram + reloc.target_section_offset; 94 | 95 | auto find_funcs_it = reference_symbols_by_vram.find(target_vram); 96 | bool found = false; 97 | if (find_funcs_it != reference_symbols_by_vram.end()) { 98 | for (size_t symbol_index : find_funcs_it->second) { 99 | const auto& cur_symbol = mod_context.get_reference_symbol(reloc.target_section, symbol_index); 100 | if (cur_symbol.section_index == reloc.target_section) { 101 | reloc.symbol_index = symbol_index; 102 | found = true; 103 | break; 104 | } 105 | } 106 | } 107 | if (!found) { 108 | fprintf(stderr, "Failed to find R_MIPS_26 relocation target in section %d with vram 0x%08X\n", reloc.target_section, target_vram); 109 | return EXIT_FAILURE; 110 | } 111 | } 112 | } 113 | } 114 | } 115 | 116 | mod_context.rom = std::move(rom_data); 117 | 118 | std::vector<std::vector<uint32_t>> static_funcs_by_section{}; 119 | static_funcs_by_section.resize(mod_context.sections.size()); 120 | 121 | const char* output_file_path = argv[4]; 122 | std::ofstream output_file { output_file_path }; 123 | 124 | RabbitizerConfig_Cfg.pseudos.pseudoMove = false; 125 | RabbitizerConfig_Cfg.pseudos.pseudoBeqz = false; 126 | RabbitizerConfig_Cfg.pseudos.pseudoBnez = false; 127 | RabbitizerConfig_Cfg.pseudos.pseudoNot = false; 128 | RabbitizerConfig_Cfg.pseudos.pseudoBal = false; 129 | 130 | output_file << "#include \"mod_recomp.h\"\n\n"; 131 | 132 | // Write the API version. 133 | output_file << "RECOMP_EXPORT uint32_t recomp_api_version = 1;\n\n"; 134 | 135 | output_file << "// Values populated by the runtime:\n\n"; 136 | 137 | // Write import function pointer array and defines (i.e. `#define testmod_inner_import imported_funcs[0]`) 138 | output_file << "// Array of pointers to imported functions with defines to alias their names.\n"; 139 | size_t num_imports = mod_context.import_symbols.size(); 140 | for (size_t import_index = 0; import_index < num_imports; import_index++) { 141 | const auto& import = mod_context.import_symbols[import_index]; 142 | output_file << "#define " << import.base.name << " imported_funcs[" << import_index << "]\n"; 143 | } 144 | 145 | output_file << "RECOMP_EXPORT recomp_func_t* imported_funcs[" << std::max(size_t{1}, num_imports) << "] = {0};\n"; 146 | output_file << "\n"; 147 | 148 | // Use reloc list to write reference symbol function pointer array and defines (i.e. `#define func_80102468 reference_symbol_funcs[0]`) 149 | output_file << "// Array of pointers to functions from the original ROM with defines to alias their names.\n"; 150 | std::unordered_set<std::string> written_reference_symbols{}; 151 | size_t num_reference_symbols = 0; 152 | for (const auto& section : mod_context.sections) { 153 | for (const auto& reloc : section.relocs) { 154 | if (reloc.type == N64Recomp::RelocType::R_MIPS_26 && reloc.reference_symbol && mod_context.is_regular_reference_section(reloc.target_section)) { 155 | const auto& sym = mod_context.get_reference_symbol(reloc.target_section, reloc.symbol_index); 156 | 157 | // Prevent writing multiple of the same define. This means there are duplicate symbols in the array if a function is called more than once, 158 | // but only the first of each set of duplicates is referenced. This is acceptable, since offline mod recompilation is mainly meant for debug purposes. 159 | if (!written_reference_symbols.contains(sym.name)) { 160 | output_file << "#define " << sym.name << " reference_symbol_funcs[" << num_reference_symbols << "]\n"; 161 | written_reference_symbols.emplace(sym.name); 162 | } 163 | num_reference_symbols++; 164 | } 165 | } 166 | } 167 | // C doesn't allow 0-sized arrays, so always add at least one member to all arrays. The actual size will be pulled from the mod symbols. 168 | output_file << "RECOMP_EXPORT recomp_func_t* reference_symbol_funcs[" << std::max(size_t{1},num_reference_symbols) << "] = {0};\n\n"; 169 | 170 | // Write provided event array (maps internal event indices to global ones). 171 | output_file << "// Base global event index for this mod's events.\n"; 172 | output_file << "RECOMP_EXPORT uint32_t base_event_index;\n\n"; 173 | 174 | // Write the event trigger function pointer. 175 | output_file << "// Pointer to the runtime function for triggering events.\n"; 176 | output_file << "RECOMP_EXPORT void (*recomp_trigger_event)(uint8_t* rdram, recomp_context* ctx, uint32_t) = NULL;\n\n"; 177 | 178 | // Write the get_function pointer. 179 | output_file << "// Pointer to the runtime function for looking up functions from vram address.\n"; 180 | output_file << "RECOMP_EXPORT recomp_func_t* (*get_function)(int32_t vram) = NULL;\n\n"; 181 | 182 | // Write the cop0_status_write pointer. 183 | output_file << "// Pointer to the runtime function for performing a cop0 status register write.\n"; 184 | output_file << "RECOMP_EXPORT void (*cop0_status_write)(recomp_context* ctx, gpr value) = NULL;\n\n"; 185 | 186 | // Write the cop0_status_read pointer. 187 | output_file << "// Pointer to the runtime function for performing a cop0 status register read.\n"; 188 | output_file << "RECOMP_EXPORT gpr (*cop0_status_read)(recomp_context* ctx) = NULL;\n\n"; 189 | 190 | // Write the switch_error pointer. 191 | output_file << "// Pointer to the runtime function for reporting switch case errors.\n"; 192 | output_file << "RECOMP_EXPORT void (*switch_error)(const char* func, uint32_t vram, uint32_t jtbl) = NULL;\n\n"; 193 | 194 | // Write the do_break pointer. 195 | output_file << "// Pointer to the runtime function for handling the break instruction.\n"; 196 | output_file << "RECOMP_EXPORT void (*do_break)(uint32_t vram) = NULL;\n\n"; 197 | 198 | // Write the section_addresses pointer. 199 | output_file << "// Pointer to the runtime's array of loaded section addresses for the base ROM.\n"; 200 | output_file << "RECOMP_EXPORT int32_t* reference_section_addresses = NULL;\n\n"; 201 | 202 | // Write the local section addresses pointer array. 203 | size_t num_sections = mod_context.sections.size(); 204 | output_file << "// Array of this mod's loaded section addresses.\n"; 205 | output_file << "RECOMP_EXPORT int32_t section_addresses[" << std::max(size_t{1}, num_sections) << "] = {0};\n\n"; 206 | 207 | // Create a set of the export indices to avoid renaming them. 208 | std::unordered_set<size_t> export_indices{mod_context.exported_funcs.begin(), mod_context.exported_funcs.end()}; 209 | 210 | // Name all the functions in a first pass so function calls emitted in the second are correct. Also emit function prototypes. 211 | output_file << "// Function prototypes.\n"; 212 | for (size_t func_index = 0; func_index < mod_context.functions.size(); func_index++) { 213 | auto& func = mod_context.functions[func_index]; 214 | // Don't rename exports since they already have a name from the mod symbol file. 215 | if (!export_indices.contains(func_index)) { 216 | func.name = "mod_func_" + std::to_string(func_index); 217 | } 218 | output_file << "RECOMP_FUNC void " << func.name << "(uint8_t* rdram, recomp_context* ctx);\n"; 219 | } 220 | output_file << "\n"; 221 | 222 | // Perform a second pass for recompiling all the functions. 223 | for (size_t func_index = 0; func_index < mod_context.functions.size(); func_index++) { 224 | if (!N64Recomp::recompile_function(mod_context, func_index, output_file, static_funcs_by_section, true)) { 225 | output_file.close(); 226 | std::error_code ec; 227 | std::filesystem::remove(output_file_path, ec); 228 | return EXIT_FAILURE; 229 | } 230 | } 231 | 232 | return EXIT_SUCCESS; 233 | } 234 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # N64: Recompiled 2 | N64: Recompiled is a tool to statically recompile N64 binaries into C code that can be compiled for any platform. This can be used for ports or tools as well as for simulating behaviors significantly faster than interpreters or dynamic recompilation can. More widely, it can be used in any context where you want to run some part of an N64 binary in a standalone environment. 3 | 4 | This is not the first project that uses static recompilation on game console binaries. A well known example is [jamulator](https://github.com/andrewrk/jamulator), which targets NES binaries. Additionally, this is not even the first project to apply static recompilation to N64-related projects: the [IDO static recompilation](https://github.com/decompals/ido-static-recomp) recompiles the SGI IRIX IDO compiler on modern systems to faciliate matching decompilation of N64 games. This project works similarly to the IDO static recomp project in some ways, and that project was my main inspiration for making this. 5 | 6 | ## Table of Contents 7 | * [How it Works](#how-it-works) 8 | * [Overlays](#overlays) 9 | * [How to Use](#how-to-use) 10 | * [Single File Output Mode](#single-file-output-mode-for-patches) 11 | * [RSP Microcode Support](#rsp-microcode-support) 12 | * [Planned Features](#planned-features) 13 | * [Building](#building) 14 | 15 | ## How it Works 16 | The recompiler works by accepting a list of symbols and metadata alongside the binary with the goal of splitting the input binary into functions that are each individually recompiled into a C function, named according to the metadata. 17 | 18 | Instructions are processed one-by-one and corresponding C code is emitted as each one gets processed. This translation is very literal in order to keep complexity low. For example, the instruction `addiu $r4, $r4, 0x20`, which adds `0x20` to the 32-bit value in the low bytes of register `$r4` and stores the sign extended 64-bit result in `$r4`, gets recompiled into `ctx->r4 = ADD32(ctx->r4, 0X20);` The `jal` (jump-and-link) instruction is recompiled directly into a function call, and `j` or `b` instructions (unconditional jumps and branches) that can be identified as tail-call optimizations are also recompiled into function calls as well. Branch delay slots are handled by duplicating instructions as necessary. There are other specific behaviors for certain instructions, such as the recompiler attempting to turn a `jr` instruction into a switch-case statement if it can tell that it's being used with a jump table. The recompiler has mostly been tested on binaries built with old MIPS compilers (e.g. mips gcc 2.7.2 and IDO) as well as modern clang targeting mips. Modern mips gcc may trip up the recompiler due to certain optimizations it can do, but those cases can probably be avoided by setting specific compilation flags. 19 | 20 | Every output function created by the recompiler is currently emitted into its own file. An option may be provided in the future to group functions together into output files, which should help improve build times of the recompiler output by reducing file I/O in the build process. 21 | 22 | Recompiler output can be compiled with any C compiler (tested with msvc, gcc and clang). The output is expected to be used with a runtime that can provide the necessary functionality and macro implementations to run it. A runtime is provided in [N64ModernRuntime](https://github.com/N64Recomp/N64ModernRuntime) which can be seen in action in the [Zelda 64: Recompiled](https://github.com/Zelda64Recomp/Zelda64Recomp) project. 23 | 24 | ## Overlays 25 | Statically linked and relocatable overlays can both be handled by this tool. In both cases, the tool emits function lookups for jump-and-link-register (i.e. function pointers or virtual functions) which the provided runtime can implement using any sort of lookup table. For example, the instruction `jalr $25` would get recompiled as `LOOKUP_FUNC(ctx->r25)(rdram, ctx);` The runtime can then maintain a list of which program sections are loaded and at what address they are at in order to determine which function to run whenever a lookup is triggered during runtime. 26 | 27 | For relocatable overlays, the tool will modify supported instructions possessing relocation data (`lui`, `addiu`, load and store instructions) by emitting an extra macro that enables the runtime to relocate the instruction's immediate value field. For example, the instruction `lui $24, 0x80C0` in a section beginning at address `0x80BFA100` with a relocation against a symbol with an address of `0x80BFA730` will get recompiled as `ctx->r24 = S32(RELOC_HI16(1754, 0X630) << 16);`, where 1754 is the index of this section. The runtime can then implement the RELOC_HI16 and RELOC_LO16 macros in order to handle modifying the immediate based on the current loaded address of the section. 28 | 29 | Support for relocations for TLB mapping is coming in the future, which will add the ability to provide a list of MIPS32 relocations so that the runtime can relocate them on load. Combining this with the functionality used for relocatable overlays should allow running most TLB mapped code without incurring a performance penalty on every RAM access. 30 | 31 | ## How to Use 32 | The recompiler is configured by providing a toml file in order to configure the recompiler behavior, which is the first argument provided to the recompiler. The toml is where you specify input and output file paths, as well as optionally stub out specific functions, skip recompilation of specific functions, and patch single instructions in the target binary. There is also planned functionality to be able to emit hooks in the recompiler output by adding them to the toml (the `[[patches.func]]` and `[[patches.hook]]` sections of the linked toml below), but this is currently unimplemented. Documentation on every option that the recompiler provides is not currently available, but an example toml can be found in the Zelda 64: Recompiled project [here](https://github.com/Mr-Wiseguy/Zelda64Recomp/blob/dev/us.rev1.toml). 33 | 34 | Currently, the only way to provide the required metadata is by passing an elf file to this tool. The easiest way to get such an elf is to set up a disassembly or decompilation of the target binary, but there will be support for providing the metadata via a custom format to bypass the need to do so in the future. 35 | 36 | ## Single File Output Mode (for Patches) 37 | This tool can also be configured to recompile in "single file output" mode via an option in the configuration toml. This will emit all of the functions in the provided elf into a single output file. The purpose of this mode is to be able to compile patched versions of functions from the target binary. 38 | 39 | This mode can be combined with the functionality provided by almost all linkers (ld, lld, MSVC's link.exe, etc.) to replace functions from the original recompiler output with modified versions. Those linkers only look for symbols in a static library if they weren't already found in a previous input file, so providing the recompiled patches to the linker before providing the original recompiler output will result in the patches taking priority over functions with the same names from the original recompiler output. 40 | 41 | This saves a tremendous amount of time while iterating on patches for the target binary, as you can bypass rerunning the recompiler on the target binary as well as compiling the original recompiler output. An example of using this single file output mode for that purpose can be found in the Zelda 64: Recompiled project [here](https://github.com/Mr-Wiseguy/Zelda64Recomp/blob/dev/patches.toml), with the corresponding Makefile that gets used to build the elf for those patches [here](https://github.com/Mr-Wiseguy/Zelda64Recomp/blob/dev/patches/Makefile). 42 | 43 | ## RSP Microcode Support 44 | RSP microcode can also be recompiled with this tool. Currently there is no support for recompiling RSP overlays, but it may be added in the future if desired. Documentation on how to use this functionality will be coming soon. 45 | 46 | ## Planned Features 47 | * Custom metadata format to provide symbol names, relocations, and any other necessary data in order to operate without an elf 48 | * Emitting multiple functions per output file to speed up compilation 49 | * Support for recording MIPS32 relocations to allow runtimes to relocate them for TLB mapping 50 | * Ability to recompile into a dynamic language (such as Lua) to be able to load code at runtime for mod support 51 | 52 | ## Building 53 | This project can be built with CMake 3.20 or above and a C++ compiler that supports C++20. This repo uses git submodules, so be sure to clone recursively (`git clone --recurse-submodules`) or initialize submodules recursively after cloning (`git submodule update --init --recursive`). From there, building is identical to any other cmake project, e.g. run `cmake` in the target build folder and point it at the root of this repo, then run `cmake --build .` from that target folder. 54 | 55 | ## Libraries Used 56 | * [rabbitizer](https://github.com/Decompollaborate/rabbitizer) for instruction decoding/analysis 57 | * [ELFIO](https://github.com/serge1/ELFIO) for elf parsing 58 | * [toml11](https://github.com/ToruNiina/toml11) for toml parsing 59 | * [fmtlib](https://github.com/fmtlib/fmt) 60 | -------------------------------------------------------------------------------- /include/recomp.h: -------------------------------------------------------------------------------- 1 | #ifndef __RECOMP_H__ 2 | #define __RECOMP_H__ 3 | 4 | #include <stdlib.h> 5 | #include <stdint.h> 6 | #include <math.h> 7 | #include <fenv.h> 8 | #include <assert.h> 9 | 10 | // Compiler definition to disable inter-procedural optimization, allowing multiple functions to be in a single file without breaking interposition. 11 | #if defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) 12 | // MSVC's __declspec(noinline) seems to disable inter-procedural optimization entirely, so it's all that's needed. 13 | #define RECOMP_FUNC __declspec(noinline) 14 | 15 | // Use MSVC's fenv_access pragma. 16 | #define SET_FENV_ACCESS() _Pragma("fenv_access(on)") 17 | #elif defined(__clang__) 18 | // Clang has no dedicated IPO attribute, so we use a combination of other attributes to give the desired behavior. 19 | // The inline keyword allows multiple definitions during linking, and extern forces clang to emit an externally visible definition. 20 | // Weak forces Clang to not perform any IPO as the symbol can be interposed, which prevents actual inlining due to the inline keyword. 21 | // Add noinline on for good measure, which doesn't conflict with the inline keyword as they have different meanings. 22 | #define RECOMP_FUNC extern inline __attribute__((weak,noinline)) 23 | 24 | // Use the standard STDC FENV_ACCESS pragma. 25 | #define SET_FENV_ACCESS() _Pragma("STDC FENV_ACCESS ON") 26 | #elif defined(__GNUC__) && !defined(__INTEL_COMPILER) 27 | // Use GCC's attribute for disabling inter-procedural optimizations. Also enable the rounding-math compiler flag to disable 28 | // constant folding so that arithmetic respects the floating point environment. This is needed because gcc doesn't implement 29 | // any FENV_ACCESS pragma. 30 | #define RECOMP_FUNC __attribute__((noipa, optimize("rounding-math"))) 31 | 32 | // There's no FENV_ACCESS pragma in gcc, so this can be empty. 33 | #define SET_FENV_ACCESS() 34 | #else 35 | #error "No RECOMP_FUNC definition for this compiler" 36 | #endif 37 | 38 | // Implementation of 64-bit multiply and divide instructions 39 | #if defined(__SIZEOF_INT128__) 40 | 41 | static inline void DMULT(int64_t a, int64_t b, int64_t* lo64, int64_t* hi64) { 42 | __int128 full128 = ((__int128)a) * ((__int128)b); 43 | 44 | *hi64 = (int64_t)(full128 >> 64); 45 | *lo64 = (int64_t)(full128 >> 0); 46 | } 47 | 48 | static inline void DMULTU(uint64_t a, uint64_t b, uint64_t* lo64, uint64_t* hi64) { 49 | unsigned __int128 full128 = ((unsigned __int128)a) * ((unsigned __int128)b); 50 | 51 | *hi64 = (uint64_t)(full128 >> 64); 52 | *lo64 = (uint64_t)(full128 >> 0); 53 | } 54 | 55 | #elif defined(_MSC_VER) 56 | 57 | #include <intrin.h> 58 | #pragma intrinsic(_mul128) 59 | #pragma intrinsic(_umul128) 60 | 61 | static inline void DMULT(int64_t a, int64_t b, int64_t* lo64, int64_t* hi64) { 62 | *lo64 = _mul128(a, b, hi64); 63 | } 64 | 65 | static inline void DMULTU(uint64_t a, uint64_t b, uint64_t* lo64, uint64_t* hi64) { 66 | *lo64 = _umul128(a, b, hi64); 67 | } 68 | 69 | #else 70 | #error "128-bit integer type not found" 71 | #endif 72 | 73 | static inline void DDIV(int64_t a, int64_t b, int64_t* quot, int64_t* rem) { 74 | int overflow = ((uint64_t)a == 0x8000000000000000ull) && (b == -1ll); 75 | *quot = overflow ? a : (a / b); 76 | *rem = overflow ? 0 : (a % b); 77 | } 78 | 79 | static inline void DDIVU(uint64_t a, uint64_t b, uint64_t* quot, uint64_t* rem) { 80 | *quot = a / b; 81 | *rem = a % b; 82 | } 83 | 84 | typedef uint64_t gpr; 85 | 86 | #define SIGNED(val) \ 87 | ((int64_t)(val)) 88 | 89 | #define ADD32(a, b) \ 90 | ((gpr)(int32_t)((a) + (b))) 91 | 92 | #define SUB32(a, b) \ 93 | ((gpr)(int32_t)((a) - (b))) 94 | 95 | #define MEM_W(offset, reg) \ 96 | (*(int32_t*)(rdram + ((((reg) + (offset))) - 0xFFFFFFFF80000000))) 97 | 98 | #define MEM_H(offset, reg) \ 99 | (*(int16_t*)(rdram + ((((reg) + (offset)) ^ 2) - 0xFFFFFFFF80000000))) 100 | 101 | #define MEM_B(offset, reg) \ 102 | (*(int8_t*)(rdram + ((((reg) + (offset)) ^ 3) - 0xFFFFFFFF80000000))) 103 | 104 | #define MEM_HU(offset, reg) \ 105 | (*(uint16_t*)(rdram + ((((reg) + (offset)) ^ 2) - 0xFFFFFFFF80000000))) 106 | 107 | #define MEM_BU(offset, reg) \ 108 | (*(uint8_t*)(rdram + ((((reg) + (offset)) ^ 3) - 0xFFFFFFFF80000000))) 109 | 110 | #define SD(val, offset, reg) { \ 111 | *(uint32_t*)(rdram + ((((reg) + (offset) + 4)) - 0xFFFFFFFF80000000)) = (uint32_t)((gpr)(val) >> 0); \ 112 | *(uint32_t*)(rdram + ((((reg) + (offset) + 0)) - 0xFFFFFFFF80000000)) = (uint32_t)((gpr)(val) >> 32); \ 113 | } 114 | 115 | static inline uint64_t load_doubleword(uint8_t* rdram, gpr reg, gpr offset) { 116 | uint64_t ret = 0; 117 | uint64_t lo = (uint64_t)(uint32_t)MEM_W(reg, offset + 4); 118 | uint64_t hi = (uint64_t)(uint32_t)MEM_W(reg, offset + 0); 119 | ret = (lo << 0) | (hi << 32); 120 | return ret; 121 | } 122 | 123 | #define LD(offset, reg) \ 124 | load_doubleword(rdram, offset, reg) 125 | 126 | static inline gpr do_lwl(uint8_t* rdram, gpr initial_value, gpr offset, gpr reg) { 127 | // Calculate the overall address 128 | gpr address = (offset + reg); 129 | 130 | // Load the aligned word 131 | gpr word_address = address & ~0x3; 132 | uint32_t loaded_value = MEM_W(0, word_address); 133 | 134 | // Mask the existing value and shift the loaded value appropriately 135 | gpr misalignment = address & 0x3; 136 | gpr masked_value = initial_value & (gpr)(uint32_t)~(0xFFFFFFFFu << (misalignment * 8)); 137 | loaded_value <<= (misalignment * 8); 138 | 139 | // Cast to int32_t to sign extend first 140 | return (gpr)(int32_t)(masked_value | loaded_value); 141 | } 142 | 143 | static inline gpr do_lwr(uint8_t* rdram, gpr initial_value, gpr offset, gpr reg) { 144 | // Calculate the overall address 145 | gpr address = (offset + reg); 146 | 147 | // Load the aligned word 148 | gpr word_address = address & ~0x3; 149 | uint32_t loaded_value = MEM_W(0, word_address); 150 | 151 | // Mask the existing value and shift the loaded value appropriately 152 | gpr misalignment = address & 0x3; 153 | gpr masked_value = initial_value & (gpr)(uint32_t)~(0xFFFFFFFFu >> (24 - misalignment * 8)); 154 | loaded_value >>= (24 - misalignment * 8); 155 | 156 | // Cast to int32_t to sign extend first 157 | return (gpr)(int32_t)(masked_value | loaded_value); 158 | } 159 | 160 | static inline void do_swl(uint8_t* rdram, gpr offset, gpr reg, gpr val) { 161 | // Calculate the overall address 162 | gpr address = (offset + reg); 163 | 164 | // Get the initial value of the aligned word 165 | gpr word_address = address & ~0x3; 166 | uint32_t initial_value = MEM_W(0, word_address); 167 | 168 | // Mask the initial value and shift the input value appropriately 169 | gpr misalignment = address & 0x3; 170 | uint32_t masked_initial_value = initial_value & ~(0xFFFFFFFFu >> (misalignment * 8)); 171 | uint32_t shifted_input_value = ((uint32_t)val) >> (misalignment * 8); 172 | MEM_W(0, word_address) = masked_initial_value | shifted_input_value; 173 | } 174 | 175 | static inline void do_swr(uint8_t* rdram, gpr offset, gpr reg, gpr val) { 176 | // Calculate the overall address 177 | gpr address = (offset + reg); 178 | 179 | // Get the initial value of the aligned word 180 | gpr word_address = address & ~0x3; 181 | uint32_t initial_value = MEM_W(0, word_address); 182 | 183 | // Mask the initial value and shift the input value appropriately 184 | gpr misalignment = address & 0x3; 185 | uint32_t masked_initial_value = initial_value & ~(0xFFFFFFFFu << (24 - misalignment * 8)); 186 | uint32_t shifted_input_value = ((uint32_t)val) << (24 - misalignment * 8); 187 | MEM_W(0, word_address) = masked_initial_value | shifted_input_value; 188 | } 189 | 190 | static inline gpr do_ldl(uint8_t* rdram, gpr initial_value, gpr offset, gpr reg) { 191 | // Calculate the overall address 192 | gpr address = (offset + reg); 193 | 194 | // Load the aligned dword 195 | gpr dword_address = address & ~0x7; 196 | uint64_t loaded_value = load_doubleword(rdram, 0, dword_address); 197 | 198 | // Mask the existing value and shift the loaded value appropriately 199 | gpr misalignment = address & 0x7; 200 | gpr masked_value = initial_value & ~(0xFFFFFFFFFFFFFFFFu << (misalignment * 8)); 201 | loaded_value <<= (misalignment * 8); 202 | 203 | return masked_value | loaded_value; 204 | } 205 | 206 | static inline gpr do_ldr(uint8_t* rdram, gpr initial_value, gpr offset, gpr reg) { 207 | // Calculate the overall address 208 | gpr address = (offset + reg); 209 | 210 | // Load the aligned dword 211 | gpr dword_address = address & ~0x7; 212 | uint64_t loaded_value = load_doubleword(rdram, 0, dword_address); 213 | 214 | // Mask the existing value and shift the loaded value appropriately 215 | gpr misalignment = address & 0x7; 216 | gpr masked_value = initial_value & ~(0xFFFFFFFFFFFFFFFFu >> (56 - misalignment * 8)); 217 | loaded_value >>= (56 - misalignment * 8); 218 | 219 | return masked_value | loaded_value; 220 | } 221 | 222 | static inline void do_sdl(uint8_t* rdram, gpr offset, gpr reg, gpr val) { 223 | // Calculate the overall address 224 | gpr address = (offset + reg); 225 | 226 | // Get the initial value of the aligned dword 227 | gpr dword_address = address & ~0x7; 228 | uint64_t initial_value = load_doubleword(rdram, 0, dword_address); 229 | 230 | // Mask the initial value and shift the input value appropriately 231 | gpr misalignment = address & 0x7; 232 | uint64_t masked_initial_value = initial_value & ~(0xFFFFFFFFFFFFFFFFu >> (misalignment * 8)); 233 | uint64_t shifted_input_value = val >> (misalignment * 8); 234 | 235 | uint64_t ret = masked_initial_value | shifted_input_value; 236 | uint32_t lo = (uint32_t)ret; 237 | uint32_t hi = (uint32_t)(ret >> 32); 238 | 239 | MEM_W(0, dword_address + 4) = lo; 240 | MEM_W(0, dword_address + 0) = hi; 241 | } 242 | 243 | static inline void do_sdr(uint8_t* rdram, gpr offset, gpr reg, gpr val) { 244 | // Calculate the overall address 245 | gpr address = (offset + reg); 246 | 247 | // Get the initial value of the aligned dword 248 | gpr dword_address = address & ~0x7; 249 | uint64_t initial_value = load_doubleword(rdram, 0, dword_address); 250 | 251 | // Mask the initial value and shift the input value appropriately 252 | gpr misalignment = address & 0x7; 253 | uint64_t masked_initial_value = initial_value & ~(0xFFFFFFFFFFFFFFFFu << (56 - misalignment * 8)); 254 | uint64_t shifted_input_value = val << (56 - misalignment * 8); 255 | 256 | uint64_t ret = masked_initial_value | shifted_input_value; 257 | uint32_t lo = (uint32_t)ret; 258 | uint32_t hi = (uint32_t)(ret >> 32); 259 | 260 | MEM_W(0, dword_address + 4) = lo; 261 | MEM_W(0, dword_address + 0) = hi; 262 | } 263 | 264 | static inline uint32_t get_cop1_cs() { 265 | uint32_t rounding_mode = 0; 266 | switch (fegetround()) { 267 | // round to nearest value 268 | case FE_TONEAREST: 269 | default: 270 | rounding_mode = 0; 271 | break; 272 | // round to zero (truncate) 273 | case FE_TOWARDZERO: 274 | rounding_mode = 1; 275 | break; 276 | // round to positive infinity (ceil) 277 | case FE_UPWARD: 278 | rounding_mode = 2; 279 | break; 280 | // round to negative infinity (floor) 281 | case FE_DOWNWARD: 282 | rounding_mode = 3; 283 | break; 284 | } 285 | return rounding_mode; 286 | } 287 | 288 | static inline void set_cop1_cs(uint32_t val) { 289 | uint32_t rounding_mode = val & 0x3; 290 | int round = FE_TONEAREST; 291 | switch (rounding_mode) { 292 | case 0: // round to nearest value 293 | round = FE_TONEAREST; 294 | break; 295 | case 1: // round to zero (truncate) 296 | round = FE_TOWARDZERO; 297 | break; 298 | case 2: // round to positive infinity (ceil) 299 | round = FE_UPWARD; 300 | break; 301 | case 3: // round to negative infinity (floor) 302 | round = FE_DOWNWARD; 303 | break; 304 | } 305 | fesetround(round); 306 | } 307 | 308 | #define S32(val) \ 309 | ((int32_t)(val)) 310 | 311 | #define U32(val) \ 312 | ((uint32_t)(val)) 313 | 314 | #define S64(val) \ 315 | ((int64_t)(val)) 316 | 317 | #define U64(val) \ 318 | ((uint64_t)(val)) 319 | 320 | #define MUL_S(val1, val2) \ 321 | ((val1) * (val2)) 322 | 323 | #define MUL_D(val1, val2) \ 324 | ((val1) * (val2)) 325 | 326 | #define DIV_S(val1, val2) \ 327 | ((val1) / (val2)) 328 | 329 | #define DIV_D(val1, val2) \ 330 | ((val1) / (val2)) 331 | 332 | #define CVT_S_W(val) \ 333 | ((float)((int32_t)(val))) 334 | 335 | #define CVT_D_W(val) \ 336 | ((double)((int32_t)(val))) 337 | 338 | #define CVT_D_L(val) \ 339 | ((double)((int64_t)(val))) 340 | 341 | #define CVT_S_L(val) \ 342 | ((float)((int64_t)(val))) 343 | 344 | #define CVT_D_S(val) \ 345 | ((double)(val)) 346 | 347 | #define CVT_S_D(val) \ 348 | ((float)(val)) 349 | 350 | #define TRUNC_W_S(val) \ 351 | ((int32_t)(val)) 352 | 353 | #define TRUNC_W_D(val) \ 354 | ((int32_t)(val)) 355 | 356 | #define TRUNC_L_S(val) \ 357 | ((int64_t)(val)) 358 | 359 | #define TRUNC_L_D(val) \ 360 | ((int64_t)(val)) 361 | 362 | #define DEFAULT_ROUNDING_MODE 0 363 | 364 | static inline int32_t do_cvt_w_s(float val) { 365 | // Rounding mode aware float to 32-bit int conversion. 366 | return (int32_t)lrintf(val); 367 | } 368 | 369 | #define CVT_W_S(val) \ 370 | do_cvt_w_s(val) 371 | 372 | static inline int64_t do_cvt_l_s(float val) { 373 | // Rounding mode aware float to 64-bit int conversion. 374 | return (int64_t)llrintf(val); 375 | } 376 | 377 | #define CVT_L_S(val) \ 378 | do_cvt_l_s(val); 379 | 380 | static inline int32_t do_cvt_w_d(double val) { 381 | // Rounding mode aware double to 32-bit int conversion. 382 | return (int32_t)lrint(val); 383 | } 384 | 385 | #define CVT_W_D(val) \ 386 | do_cvt_w_d(val) 387 | 388 | static inline int64_t do_cvt_l_d(double val) { 389 | // Rounding mode aware double to 64-bit int conversion. 390 | return (int64_t)llrint(val); 391 | } 392 | 393 | #define CVT_L_D(val) \ 394 | do_cvt_l_d(val) 395 | 396 | #define NAN_CHECK(val) \ 397 | assert(val == val) 398 | 399 | //#define NAN_CHECK(val) 400 | 401 | typedef union { 402 | double d; 403 | struct { 404 | float fl; 405 | float fh; 406 | }; 407 | struct { 408 | uint32_t u32l; 409 | uint32_t u32h; 410 | }; 411 | uint64_t u64; 412 | } fpr; 413 | 414 | typedef struct { 415 | gpr r0, r1, r2, r3, r4, r5, r6, r7, 416 | r8, r9, r10, r11, r12, r13, r14, r15, 417 | r16, r17, r18, r19, r20, r21, r22, r23, 418 | r24, r25, r26, r27, r28, r29, r30, r31; 419 | fpr f0, f1, f2, f3, f4, f5, f6, f7, 420 | f8, f9, f10, f11, f12, f13, f14, f15, 421 | f16, f17, f18, f19, f20, f21, f22, f23, 422 | f24, f25, f26, f27, f28, f29, f30, f31; 423 | uint64_t hi, lo; 424 | uint32_t* f_odd; 425 | uint32_t status_reg; 426 | uint8_t mips3_float_mode; 427 | } recomp_context; 428 | 429 | // Checks if the target is an even float register or that mips3 float mode is enabled 430 | #define CHECK_FR(ctx, idx) \ 431 | assert(((idx) & 1) == 0 || (ctx)->mips3_float_mode) 432 | 433 | #ifdef __cplusplus 434 | extern "C" { 435 | #endif 436 | 437 | void cop0_status_write(recomp_context* ctx, gpr value); 438 | gpr cop0_status_read(recomp_context* ctx); 439 | void switch_error(const char* func, uint32_t vram, uint32_t jtbl); 440 | void do_break(uint32_t vram); 441 | 442 | // The function signature for all recompiler output functions. 443 | typedef void (recomp_func_t)(uint8_t* rdram, recomp_context* ctx); 444 | // The function signature for special functions that need a third argument. 445 | // These get called via generated shims to allow providing some information about the caller, such as mod id. 446 | typedef void (recomp_func_ext_t)(uint8_t* rdram, recomp_context* ctx, uintptr_t arg); 447 | 448 | recomp_func_t* get_function(int32_t vram); 449 | 450 | #define LOOKUP_FUNC(val) \ 451 | get_function((int32_t)(val)) 452 | 453 | extern int32_t* section_addresses; 454 | 455 | #define LO16(x) \ 456 | ((x) & 0xFFFF) 457 | 458 | #define HI16(x) \ 459 | (((x) >> 16) + (((x) >> 15) & 1)) 460 | 461 | #define RELOC_HI16(section_index, offset) \ 462 | HI16(section_addresses[section_index] + (offset)) 463 | 464 | #define RELOC_LO16(section_index, offset) \ 465 | LO16(section_addresses[section_index] + (offset)) 466 | 467 | void recomp_syscall_handler(uint8_t* rdram, recomp_context* ctx, int32_t instruction_vram); 468 | 469 | void pause_self(uint8_t *rdram); 470 | 471 | #ifdef __cplusplus 472 | } 473 | #endif 474 | 475 | #endif 476 | -------------------------------------------------------------------------------- /include/recompiler/context.h: -------------------------------------------------------------------------------- 1 | #ifndef __RECOMP_PORT__ 2 | #define __RECOMP_PORT__ 3 | 4 | #include <span> 5 | #include <string_view> 6 | #include <cstdint> 7 | #include <utility> 8 | #include <vector> 9 | #include <unordered_map> 10 | #include <unordered_set> 11 | #include <filesystem> 12 | #include <optional> 13 | 14 | #ifdef _MSC_VER 15 | inline uint32_t byteswap(uint32_t val) { 16 | return _byteswap_ulong(val); 17 | } 18 | #else 19 | constexpr uint32_t byteswap(uint32_t val) { 20 | return __builtin_bswap32(val); 21 | } 22 | #endif 23 | 24 | namespace N64Recomp { 25 | struct Function { 26 | uint32_t vram; 27 | uint32_t rom; 28 | std::vector<uint32_t> words; 29 | std::string name; 30 | uint16_t section_index; 31 | bool ignored; 32 | bool reimplemented; 33 | bool stubbed; 34 | std::unordered_map<int32_t, std::string> function_hooks; 35 | 36 | Function(uint32_t vram, uint32_t rom, std::vector<uint32_t> words, std::string name, uint16_t section_index, bool ignored = false, bool reimplemented = false, bool stubbed = false) 37 | : vram(vram), rom(rom), words(std::move(words)), name(std::move(name)), section_index(section_index), ignored(ignored), reimplemented(reimplemented), stubbed(stubbed) {} 38 | Function() = default; 39 | }; 40 | 41 | struct JumpTable { 42 | uint32_t vram; 43 | uint32_t addend_reg; 44 | uint32_t rom; 45 | uint32_t lw_vram; 46 | uint32_t addu_vram; 47 | uint32_t jr_vram; 48 | uint16_t section_index; 49 | std::optional<uint32_t> got_offset; 50 | std::vector<uint32_t> entries; 51 | 52 | JumpTable(uint32_t vram, uint32_t addend_reg, uint32_t rom, uint32_t lw_vram, uint32_t addu_vram, uint32_t jr_vram, uint16_t section_index, std::optional<uint32_t> got_offset, std::vector<uint32_t>&& entries) 53 | : vram(vram), addend_reg(addend_reg), rom(rom), lw_vram(lw_vram), addu_vram(addu_vram), jr_vram(jr_vram), section_index(section_index), got_offset(got_offset), entries(std::move(entries)) {} 54 | }; 55 | 56 | enum class RelocType : uint8_t { 57 | R_MIPS_NONE = 0, 58 | R_MIPS_16, 59 | R_MIPS_32, 60 | R_MIPS_REL32, 61 | R_MIPS_26, 62 | R_MIPS_HI16, 63 | R_MIPS_LO16, 64 | R_MIPS_GPREL16, 65 | }; 66 | 67 | struct Reloc { 68 | uint32_t address; 69 | uint32_t target_section_offset; 70 | uint32_t symbol_index; // Only used for reference symbols and special section symbols 71 | uint16_t target_section; 72 | RelocType type; 73 | bool reference_symbol; 74 | }; 75 | 76 | // Special section indices. 77 | constexpr uint16_t SectionAbsolute = (uint16_t)-2; 78 | constexpr uint16_t SectionImport = (uint16_t)-3; // Imported symbols for mods 79 | constexpr uint16_t SectionEvent = (uint16_t)-4; 80 | 81 | // Special section names. 82 | constexpr std::string_view PatchSectionName = ".recomp_patch"; 83 | constexpr std::string_view ForcedPatchSectionName = ".recomp_force_patch"; 84 | constexpr std::string_view ExportSectionName = ".recomp_export"; 85 | constexpr std::string_view EventSectionName = ".recomp_event"; 86 | constexpr std::string_view ImportSectionPrefix = ".recomp_import."; 87 | constexpr std::string_view CallbackSectionPrefix = ".recomp_callback."; 88 | constexpr std::string_view HookSectionPrefix = ".recomp_hook."; 89 | constexpr std::string_view HookReturnSectionPrefix = ".recomp_hook_return."; 90 | 91 | // Special dependency names. 92 | constexpr std::string_view DependencySelf = "."; 93 | constexpr std::string_view DependencyBaseRecomp = "*"; 94 | 95 | struct Section { 96 | uint32_t rom_addr = 0; 97 | uint32_t ram_addr = 0; 98 | uint32_t size = 0; 99 | uint32_t bss_size = 0; // not populated when using a symbol toml 100 | std::vector<uint32_t> function_addrs; // only used by the CLI (to find the size of static functions) 101 | std::vector<Reloc> relocs; 102 | std::string name; 103 | uint16_t bss_section_index = (uint16_t)-1; 104 | bool executable = false; 105 | bool relocatable = false; // TODO is this needed? relocs being non-empty should be an equivalent check. 106 | bool has_mips32_relocs = false; 107 | std::optional<uint32_t> got_ram_addr = std::nullopt; 108 | }; 109 | 110 | struct ReferenceSection { 111 | uint32_t rom_addr; 112 | uint32_t ram_addr; 113 | uint32_t size; 114 | bool relocatable; 115 | }; 116 | 117 | struct ReferenceSymbol { 118 | std::string name; 119 | uint16_t section_index; 120 | uint32_t section_offset; 121 | bool is_function; 122 | }; 123 | 124 | struct ElfParsingConfig { 125 | std::string bss_section_suffix; 126 | // Functions with manual size overrides 127 | std::unordered_map<std::string, size_t> manually_sized_funcs; 128 | // The section names that were specified as relocatable 129 | std::unordered_set<std::string> relocatable_sections; 130 | bool has_entrypoint; 131 | int32_t entrypoint_address; 132 | bool use_absolute_symbols; 133 | bool unpaired_lo16_warnings; 134 | bool all_sections_relocatable; 135 | }; 136 | 137 | struct DataSymbol { 138 | uint32_t vram; 139 | std::string name; 140 | 141 | DataSymbol(uint32_t vram, std::string&& name) : vram(vram), name(std::move(name)) {} 142 | }; 143 | 144 | using DataSymbolMap = std::unordered_map<uint16_t, std::vector<DataSymbol>>; 145 | 146 | extern const std::unordered_set<std::string> reimplemented_funcs; 147 | extern const std::unordered_set<std::string> ignored_funcs; 148 | extern const std::unordered_set<std::string> renamed_funcs; 149 | 150 | struct ImportSymbol { 151 | ReferenceSymbol base; 152 | size_t dependency_index; 153 | }; 154 | 155 | struct DependencyEvent { 156 | size_t dependency_index; 157 | std::string event_name; 158 | }; 159 | 160 | struct EventSymbol { 161 | ReferenceSymbol base; 162 | }; 163 | 164 | struct Callback { 165 | size_t function_index; 166 | size_t dependency_event_index; 167 | }; 168 | 169 | struct SymbolReference { 170 | // Reference symbol section index, or one of the special section indices such as SectionImport. 171 | uint16_t section_index; 172 | size_t symbol_index; 173 | }; 174 | 175 | enum class ReplacementFlags : uint32_t { 176 | Force = 1 << 0, 177 | }; 178 | inline ReplacementFlags operator&(ReplacementFlags lhs, ReplacementFlags rhs) { return ReplacementFlags(uint32_t(lhs) & uint32_t(rhs)); } 179 | inline ReplacementFlags operator|(ReplacementFlags lhs, ReplacementFlags rhs) { return ReplacementFlags(uint32_t(lhs) | uint32_t(rhs)); } 180 | 181 | struct FunctionReplacement { 182 | uint32_t func_index; 183 | uint32_t original_section_vrom; 184 | uint32_t original_vram; 185 | ReplacementFlags flags; 186 | }; 187 | 188 | enum class HookFlags : uint32_t { 189 | AtReturn = 1 << 0, 190 | }; 191 | inline HookFlags operator&(HookFlags lhs, HookFlags rhs) { return HookFlags(uint32_t(lhs) & uint32_t(rhs)); } 192 | inline HookFlags operator|(HookFlags lhs, HookFlags rhs) { return HookFlags(uint32_t(lhs) | uint32_t(rhs)); } 193 | 194 | struct FunctionHook { 195 | uint32_t func_index; 196 | uint32_t original_section_vrom; 197 | uint32_t original_vram; 198 | HookFlags flags; 199 | }; 200 | 201 | class Context { 202 | private: 203 | //// Reference symbols (used for populating relocations for patches) 204 | // A list of the sections that contain the reference symbols. 205 | std::vector<ReferenceSection> reference_sections; 206 | // A list of the reference symbols. 207 | std::vector<ReferenceSymbol> reference_symbols; 208 | // Mapping of symbol name to reference symbol index. 209 | std::unordered_map<std::string, SymbolReference> reference_symbols_by_name; 210 | // Whether all reference sections should be treated as relocatable (used in live recompilation). 211 | bool all_reference_sections_relocatable = false; 212 | public: 213 | std::vector<Section> sections; 214 | std::vector<Function> functions; 215 | // A list of the list of each function (by index in `functions`) in a given section 216 | std::vector<std::vector<size_t>> section_functions; 217 | // A mapping of vram address to every function with that address. 218 | std::unordered_map<uint32_t, std::vector<size_t>> functions_by_vram; 219 | // A mapping of bss section index to the corresponding non-bss section index. 220 | std::unordered_map<uint16_t, uint16_t> bss_section_to_section; 221 | // The target ROM being recompiled, TODO move this outside of the context to avoid making a copy for mod contexts. 222 | // Used for reading relocations and for the output binary feature. 223 | std::vector<uint8_t> rom; 224 | // Whether reference symbols should be validated when emitting function calls during recompilation. 225 | bool skip_validating_reference_symbols = true; 226 | // Whether all function calls (excluding reference symbols) should go through lookup. 227 | bool use_lookup_for_all_function_calls = false; 228 | 229 | //// Only used by the CLI, TODO move this to a struct in the internal headers. 230 | // A mapping of function name to index in the functions vector 231 | std::unordered_map<std::string, size_t> functions_by_name; 232 | 233 | //// Mod dependencies and their symbols 234 | 235 | //// Imported values 236 | // Dependency names. 237 | std::vector<std::string> dependencies; 238 | // Mapping of dependency name to dependency index. 239 | std::unordered_map<std::string, size_t> dependencies_by_name; 240 | // List of symbols imported from dependencies. 241 | std::vector<ImportSymbol> import_symbols; 242 | // List of events imported from dependencies. 243 | std::vector<DependencyEvent> dependency_events; 244 | // Mappings of dependency event name to the index in dependency_events, all indexed by dependency. 245 | std::vector<std::unordered_map<std::string, size_t>> dependency_events_by_name; 246 | // Mappings of dependency import name to index in import_symbols, all indexed by dependency. 247 | std::vector<std::unordered_map<std::string, size_t>> dependency_imports_by_name; 248 | 249 | //// Exported values 250 | // List of function replacements, which contains the original function to replace and the function index to replace it with. 251 | std::vector<FunctionReplacement> replacements; 252 | // Indices of every exported function. 253 | std::vector<size_t> exported_funcs; 254 | // List of callbacks, which contains the function for the callback and the dependency event it attaches to. 255 | std::vector<Callback> callbacks; 256 | // List of symbols from events, which contains the names of events that this context provides. 257 | std::vector<EventSymbol> event_symbols; 258 | // List of hooks, which contains the original function to hook and the function index to call at the hook. 259 | std::vector<FunctionHook> hooks; 260 | 261 | // Causes functions to print their name to the console the first time they're called. 262 | bool trace_mode; 263 | 264 | // Imports sections and function symbols from a provided context into this context's reference sections and reference functions. 265 | bool import_reference_context(const Context& reference_context); 266 | // Reads a data symbol file and adds its contents into this context's reference data symbols. 267 | bool read_data_reference_syms(const std::filesystem::path& data_syms_file_path); 268 | 269 | static bool from_symbol_file(const std::filesystem::path& symbol_file_path, std::vector<uint8_t>&& rom, Context& out, bool with_relocs); 270 | static bool from_elf_file(const std::filesystem::path& elf_file_path, Context& out, const ElfParsingConfig& flags, bool for_dumping_context, DataSymbolMap& data_syms_out, bool& found_entrypoint_out); 271 | 272 | Context() = default; 273 | 274 | bool add_dependency(const std::string& id) { 275 | if (dependencies_by_name.contains(id)) { 276 | return false; 277 | } 278 | 279 | size_t dependency_index = dependencies_by_name.size(); 280 | 281 | dependencies.emplace_back(id); 282 | dependencies_by_name.emplace(id, dependency_index); 283 | dependency_events_by_name.resize(dependencies_by_name.size()); 284 | dependency_imports_by_name.resize(dependencies_by_name.size()); 285 | 286 | return true; 287 | } 288 | 289 | bool add_dependencies(const std::vector<std::string>& new_dependencies) { 290 | dependencies_by_name.reserve(dependencies_by_name.size() + new_dependencies.size()); 291 | 292 | // Check if any of the dependencies already exist and fail if so. 293 | for (const std::string& dep : new_dependencies) { 294 | if (dependencies_by_name.contains(dep)) { 295 | return false; 296 | } 297 | } 298 | 299 | for (const std::string& dep : new_dependencies) { 300 | size_t dependency_index = dependencies_by_name.size(); 301 | dependencies.emplace_back(dep); 302 | dependencies_by_name.emplace(dep, dependency_index); 303 | } 304 | 305 | dependency_events_by_name.resize(dependencies_by_name.size()); 306 | dependency_imports_by_name.resize(dependencies_by_name.size()); 307 | return true; 308 | } 309 | 310 | bool find_dependency(const std::string& mod_id, size_t& dependency_index) { 311 | auto find_it = dependencies_by_name.find(mod_id); 312 | if (find_it != dependencies_by_name.end()) { 313 | dependency_index = find_it->second; 314 | } 315 | else { 316 | // Handle special dependency names. 317 | if (mod_id == DependencySelf || mod_id == DependencyBaseRecomp) { 318 | add_dependency(mod_id); 319 | dependency_index = dependencies_by_name[mod_id]; 320 | } 321 | else { 322 | return false; 323 | } 324 | } 325 | return true; 326 | } 327 | 328 | size_t find_function_by_vram_section(uint32_t vram, size_t section_index) const { 329 | auto find_it = functions_by_vram.find(vram); 330 | if (find_it == functions_by_vram.end()) { 331 | return (size_t)-1; 332 | } 333 | 334 | for (size_t function_index : find_it->second) { 335 | if (functions[function_index].section_index == section_index) { 336 | return function_index; 337 | } 338 | } 339 | 340 | return (size_t)-1; 341 | } 342 | 343 | bool has_reference_symbols() const { 344 | return !reference_symbols.empty() || !import_symbols.empty() || !event_symbols.empty(); 345 | } 346 | 347 | bool is_regular_reference_section(uint16_t section_index) const { 348 | return section_index != SectionImport && section_index != SectionEvent; 349 | } 350 | 351 | bool find_reference_symbol(const std::string& symbol_name, SymbolReference& ref_out) const { 352 | auto find_sym_it = reference_symbols_by_name.find(symbol_name); 353 | 354 | // Check if the symbol was found. 355 | if (find_sym_it == reference_symbols_by_name.end()) { 356 | return false; 357 | } 358 | 359 | ref_out = find_sym_it->second; 360 | return true; 361 | } 362 | 363 | bool reference_symbol_exists(const std::string& symbol_name) const { 364 | SymbolReference dummy_ref; 365 | return find_reference_symbol(symbol_name, dummy_ref); 366 | } 367 | 368 | bool find_regular_reference_symbol(const std::string& symbol_name, SymbolReference& ref_out) const { 369 | SymbolReference ref_found; 370 | if (!find_reference_symbol(symbol_name, ref_found)) { 371 | return false; 372 | } 373 | 374 | // Ignore reference symbols in special sections. 375 | if (!is_regular_reference_section(ref_found.section_index)) { 376 | return false; 377 | } 378 | 379 | ref_out = ref_found; 380 | return true; 381 | } 382 | 383 | const ReferenceSymbol& get_reference_symbol(uint16_t section_index, size_t symbol_index) const { 384 | if (section_index == SectionImport) { 385 | return import_symbols[symbol_index].base; 386 | } 387 | else if (section_index == SectionEvent) { 388 | return event_symbols[symbol_index].base; 389 | } 390 | return reference_symbols[symbol_index]; 391 | } 392 | 393 | size_t num_regular_reference_symbols() { 394 | return reference_symbols.size(); 395 | } 396 | 397 | const ReferenceSymbol& get_regular_reference_symbol(size_t index) const { 398 | return reference_symbols[index]; 399 | } 400 | 401 | const ReferenceSymbol& get_reference_symbol(const SymbolReference& ref) const { 402 | return get_reference_symbol(ref.section_index, ref.symbol_index); 403 | } 404 | 405 | bool is_reference_section_relocatable(uint16_t section_index) const { 406 | if (all_reference_sections_relocatable) { 407 | return true; 408 | } 409 | if (section_index == SectionAbsolute) { 410 | return false; 411 | } 412 | else if (section_index == SectionImport || section_index == SectionEvent) { 413 | return true; 414 | } 415 | return reference_sections[section_index].relocatable; 416 | } 417 | 418 | bool add_reference_symbol(const std::string& symbol_name, uint16_t section_index, uint32_t vram, bool is_function) { 419 | uint32_t section_vram; 420 | 421 | if (section_index == SectionAbsolute) { 422 | section_vram = 0; 423 | } 424 | else if (section_index < reference_sections.size()) { 425 | section_vram = reference_sections[section_index].ram_addr; 426 | } 427 | // Invalid section index. 428 | else { 429 | return false; 430 | } 431 | 432 | // TODO Check if reference_symbols_by_name already contains the name and show a conflict error if so. 433 | reference_symbols_by_name.emplace(symbol_name, N64Recomp::SymbolReference{ 434 | .section_index = section_index, 435 | .symbol_index = reference_symbols.size() 436 | }); 437 | 438 | reference_symbols.emplace_back(N64Recomp::ReferenceSymbol{ 439 | .name = symbol_name, 440 | .section_index = section_index, 441 | .section_offset = vram - section_vram, 442 | .is_function = is_function 443 | }); 444 | return true; 445 | } 446 | 447 | void add_import_symbol(const std::string& symbol_name, size_t dependency_index) { 448 | // TODO Check if dependency_imports_by_name[dependency_index] already contains the name and show a conflict error if so. 449 | dependency_imports_by_name[dependency_index][symbol_name] = import_symbols.size(); 450 | import_symbols.emplace_back( 451 | N64Recomp::ImportSymbol { 452 | .base = N64Recomp::ReferenceSymbol { 453 | .name = symbol_name, 454 | .section_index = N64Recomp::SectionImport, 455 | .section_offset = 0, 456 | .is_function = true 457 | }, 458 | .dependency_index = dependency_index, 459 | } 460 | ); 461 | } 462 | 463 | bool find_import_symbol(const std::string& symbol_name, size_t dependency_index, SymbolReference& ref_out) const { 464 | if (dependency_index >= dependencies_by_name.size()) { 465 | return false; 466 | } 467 | 468 | auto find_it = dependency_imports_by_name[dependency_index].find(symbol_name); 469 | if (find_it == dependency_imports_by_name[dependency_index].end()) { 470 | return false; 471 | } 472 | 473 | ref_out.section_index = SectionImport; 474 | ref_out.symbol_index = find_it->second; 475 | return true; 476 | } 477 | 478 | void add_event_symbol(const std::string& symbol_name) { 479 | // TODO Check if reference_symbols_by_name already contains the name and show a conflict error if so. 480 | reference_symbols_by_name[symbol_name] = N64Recomp::SymbolReference { 481 | .section_index = N64Recomp::SectionEvent, 482 | .symbol_index = event_symbols.size() 483 | }; 484 | event_symbols.emplace_back( 485 | N64Recomp::EventSymbol { 486 | .base = N64Recomp::ReferenceSymbol { 487 | .name = symbol_name, 488 | .section_index = N64Recomp::SectionEvent, 489 | .section_offset = 0, 490 | .is_function = true 491 | } 492 | } 493 | ); 494 | } 495 | 496 | bool find_event_symbol(const std::string& symbol_name, SymbolReference& ref_out) const { 497 | SymbolReference ref_found; 498 | if (!find_reference_symbol(symbol_name, ref_found)) { 499 | return false; 500 | } 501 | 502 | // Ignore reference symbols that aren't in the event section. 503 | if (ref_found.section_index != SectionEvent) { 504 | return false; 505 | } 506 | 507 | ref_out = ref_found; 508 | return true; 509 | } 510 | 511 | bool add_dependency_event(const std::string& event_name, size_t dependency_index, size_t& dependency_event_index) { 512 | if (dependency_index >= dependencies_by_name.size()) { 513 | return false; 514 | } 515 | 516 | // Prevent adding the same event to a dependency twice. This isn't an error, since a mod could register 517 | // multiple callbacks to the same event. 518 | auto find_it = dependency_events_by_name[dependency_index].find(event_name); 519 | if (find_it != dependency_events_by_name[dependency_index].end()) { 520 | dependency_event_index = find_it->second; 521 | return true; 522 | } 523 | 524 | dependency_event_index = dependency_events.size(); 525 | dependency_events.emplace_back(DependencyEvent{ 526 | .dependency_index = dependency_index, 527 | .event_name = event_name 528 | }); 529 | dependency_events_by_name[dependency_index][event_name] = dependency_event_index; 530 | return true; 531 | } 532 | 533 | bool add_callback(size_t dependency_event_index, size_t function_index) { 534 | callbacks.emplace_back(Callback{ 535 | .function_index = function_index, 536 | .dependency_event_index = dependency_event_index 537 | }); 538 | return true; 539 | } 540 | 541 | uint32_t get_reference_section_vram(uint16_t section_index) const { 542 | if (section_index == N64Recomp::SectionAbsolute) { 543 | return 0; 544 | } 545 | else if (!is_regular_reference_section(section_index)) { 546 | return 0; 547 | } 548 | else { 549 | return reference_sections[section_index].ram_addr; 550 | } 551 | } 552 | 553 | uint32_t get_reference_section_rom(uint16_t section_index) const { 554 | if (section_index == N64Recomp::SectionAbsolute) { 555 | return (uint32_t)-1; 556 | } 557 | else if (!is_regular_reference_section(section_index)) { 558 | return (uint32_t)-1; 559 | } 560 | else { 561 | return reference_sections[section_index].rom_addr; 562 | } 563 | } 564 | 565 | void copy_reference_sections_from(const Context& rhs) { 566 | reference_sections = rhs.reference_sections; 567 | } 568 | 569 | void set_all_reference_sections_relocatable() { 570 | all_reference_sections_relocatable = true; 571 | } 572 | 573 | }; 574 | 575 | class Generator; 576 | bool recompile_function(const Context& context, size_t function_index, std::ostream& output_file, std::span<std::vector<uint32_t>> static_funcs, bool tag_reference_relocs); 577 | bool recompile_function_custom(Generator& generator, const Context& context, size_t function_index, std::ostream& output_file, std::span<std::vector<uint32_t>> static_funcs_out, bool tag_reference_relocs); 578 | 579 | enum class ModSymbolsError { 580 | Good, 581 | NotASymbolFile, 582 | UnknownSymbolFileVersion, 583 | CorruptSymbolFile, 584 | FunctionOutOfBounds, 585 | }; 586 | 587 | ModSymbolsError parse_mod_symbols(std::span<const char> data, std::span<const uint8_t> binary, const std::unordered_map<uint32_t, uint16_t>& sections_by_vrom, Context& context_out); 588 | std::vector<uint8_t> symbols_to_bin_v1(const Context& mod_context); 589 | 590 | inline bool is_manual_patch_symbol(uint32_t vram) { 591 | // Zero-sized symbols between 0x8F000000 and 0x90000000 are manually specified symbols for use with patches. 592 | // TODO make this configurable or come up with a more sensible solution for dealing with manual symbols for patches. 593 | return vram >= 0x8F000000 && vram < 0x90000000; 594 | } 595 | 596 | // Locale-independent ASCII-only version of isalpha. 597 | inline bool isalpha_nolocale(char c) { 598 | return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); 599 | } 600 | 601 | // Locale-independent ASCII-only version of isalnum. 602 | inline bool isalnum_nolocale(char c) { 603 | return isalpha_nolocale(c) || (c >= '0' && c <= '9'); 604 | } 605 | 606 | inline bool validate_mod_id(std::string_view str) { 607 | // Disallow empty ids. 608 | if (str.size() == 0) { 609 | return false; 610 | } 611 | 612 | // Allow special dependency ids. 613 | if (str == N64Recomp::DependencySelf || str == N64Recomp::DependencyBaseRecomp) { 614 | return true; 615 | } 616 | 617 | // These following rules basically describe C identifiers. There's no specific reason to enforce them besides colon (currently), 618 | // so this is just to prevent "weird" mod ids. 619 | 620 | // Check the first character, which must be alphabetical or an underscore. 621 | if (!isalpha_nolocale(str[0]) && str[0] != '_') { 622 | return false; 623 | } 624 | 625 | // Check the remaining characters, which can be alphanumeric or underscore. 626 | for (char c : str.substr(1)) { 627 | if (!isalnum_nolocale(c) && c != '_') { 628 | return false; 629 | } 630 | } 631 | 632 | return true; 633 | } 634 | 635 | inline bool validate_mod_id(const std::string& str) { 636 | return validate_mod_id(std::string_view{str}); 637 | } 638 | } 639 | 640 | #endif 641 | -------------------------------------------------------------------------------- /include/recompiler/generator.h: -------------------------------------------------------------------------------- 1 | #ifndef __GENERATOR_H__ 2 | #define __GENERATOR_H__ 3 | 4 | #include "recompiler/context.h" 5 | #include "operations.h" 6 | 7 | namespace N64Recomp { 8 | struct InstructionContext { 9 | int rd; 10 | int rs; 11 | int rt; 12 | int sa; 13 | 14 | int fd; 15 | int fs; 16 | int ft; 17 | 18 | int cop1_cs; 19 | 20 | uint16_t imm16; 21 | 22 | bool reloc_tag_as_reference; 23 | RelocType reloc_type; 24 | uint32_t reloc_section_index; 25 | uint32_t reloc_target_section_offset; 26 | }; 27 | 28 | class Generator { 29 | public: 30 | virtual void process_binary_op(const BinaryOp& op, const InstructionContext& ctx) const = 0; 31 | virtual void process_unary_op(const UnaryOp& op, const InstructionContext& ctx) const = 0; 32 | virtual void process_store_op(const StoreOp& op, const InstructionContext& ctx) const = 0; 33 | virtual void emit_function_start(const std::string& function_name, size_t func_index) const = 0; 34 | virtual void emit_function_end() const = 0; 35 | virtual void emit_function_call_lookup(uint32_t addr) const = 0; 36 | virtual void emit_function_call_by_register(int reg) const = 0; 37 | // target_section_offset can each be deduced from symbol_index if the full context is available, 38 | // but for live recompilation the reference symbol list is unavailable so it's still provided. 39 | virtual void emit_function_call_reference_symbol(const Context& context, uint16_t section_index, size_t symbol_index, uint32_t target_section_offset) const = 0; 40 | virtual void emit_function_call(const Context& context, size_t function_index) const = 0; 41 | virtual void emit_named_function_call(const std::string& function_name) const = 0; 42 | virtual void emit_goto(const std::string& target) const = 0; 43 | virtual void emit_label(const std::string& label_name) const = 0; 44 | virtual void emit_jtbl_addend_declaration(const JumpTable& jtbl, int reg) const = 0; 45 | virtual void emit_branch_condition(const ConditionalBranchOp& op, const InstructionContext& ctx) const = 0; 46 | virtual void emit_branch_close() const = 0; 47 | virtual void emit_switch(const Context& recompiler_context, const JumpTable& jtbl, int reg) const = 0; 48 | virtual void emit_case(int case_index, const std::string& target_label) const = 0; 49 | virtual void emit_switch_error(uint32_t instr_vram, uint32_t jtbl_vram) const = 0; 50 | virtual void emit_switch_close() const = 0; 51 | virtual void emit_return(const Context& context, size_t func_index) const = 0; 52 | virtual void emit_check_fr(int fpr) const = 0; 53 | virtual void emit_check_nan(int fpr, bool is_double) const = 0; 54 | virtual void emit_cop0_status_read(int reg) const = 0; 55 | virtual void emit_cop0_status_write(int reg) const = 0; 56 | virtual void emit_cop1_cs_read(int reg) const = 0; 57 | virtual void emit_cop1_cs_write(int reg) const = 0; 58 | virtual void emit_muldiv(InstrId instr_id, int reg1, int reg2) const = 0; 59 | virtual void emit_syscall(uint32_t instr_vram) const = 0; 60 | virtual void emit_do_break(uint32_t instr_vram) const = 0; 61 | virtual void emit_pause_self() const = 0; 62 | virtual void emit_trigger_event(uint32_t event_index) const = 0; 63 | virtual void emit_comment(const std::string& comment) const = 0; 64 | }; 65 | 66 | class CGenerator final : Generator { 67 | public: 68 | CGenerator(std::ostream& output_file) : output_file(output_file) {}; 69 | void process_binary_op(const BinaryOp& op, const InstructionContext& ctx) const final; 70 | void process_unary_op(const UnaryOp& op, const InstructionContext& ctx) const final; 71 | void process_store_op(const StoreOp& op, const InstructionContext& ctx) const final; 72 | void emit_function_start(const std::string& function_name, size_t func_index) const final; 73 | void emit_function_end() const final; 74 | void emit_function_call_lookup(uint32_t addr) const final; 75 | void emit_function_call_by_register(int reg) const final; 76 | void emit_function_call_reference_symbol(const Context& context, uint16_t section_index, size_t symbol_index, uint32_t target_section_offset) const final; 77 | void emit_function_call(const Context& context, size_t function_index) const final; 78 | void emit_named_function_call(const std::string& function_name) const final; 79 | void emit_goto(const std::string& target) const final; 80 | void emit_label(const std::string& label_name) const final; 81 | void emit_jtbl_addend_declaration(const JumpTable& jtbl, int reg) const final; 82 | void emit_branch_condition(const ConditionalBranchOp& op, const InstructionContext& ctx) const final; 83 | void emit_branch_close() const final; 84 | void emit_switch(const Context& recompiler_context, const JumpTable& jtbl, int reg) const final; 85 | void emit_case(int case_index, const std::string& target_label) const final; 86 | void emit_switch_error(uint32_t instr_vram, uint32_t jtbl_vram) const final; 87 | void emit_switch_close() const final; 88 | void emit_return(const Context& context, size_t func_index) const final; 89 | void emit_check_fr(int fpr) const final; 90 | void emit_check_nan(int fpr, bool is_double) const final; 91 | void emit_cop0_status_read(int reg) const final; 92 | void emit_cop0_status_write(int reg) const final; 93 | void emit_cop1_cs_read(int reg) const final; 94 | void emit_cop1_cs_write(int reg) const final; 95 | void emit_muldiv(InstrId instr_id, int reg1, int reg2) const final; 96 | void emit_syscall(uint32_t instr_vram) const final; 97 | void emit_do_break(uint32_t instr_vram) const final; 98 | void emit_pause_self() const final; 99 | void emit_trigger_event(uint32_t event_index) const final; 100 | void emit_comment(const std::string& comment) const final; 101 | private: 102 | void get_operand_string(Operand operand, UnaryOpType operation, const InstructionContext& context, std::string& operand_string) const; 103 | void get_binary_expr_string(BinaryOpType type, const BinaryOperands& operands, const InstructionContext& ctx, const std::string& output, std::string& expr_string) const; 104 | void get_notation(BinaryOpType op_type, std::string& func_string, std::string& infix_string) const; 105 | std::ostream& output_file; 106 | }; 107 | } 108 | 109 | #endif 110 | -------------------------------------------------------------------------------- /include/recompiler/live_recompiler.h: -------------------------------------------------------------------------------- 1 | #ifndef __LIVE_RECOMPILER_H__ 2 | #define __LIVE_RECOMPILER_H__ 3 | 4 | #include <unordered_map> 5 | #include "recompiler/generator.h" 6 | #include "recomp.h" 7 | 8 | struct sljit_compiler; 9 | 10 | namespace N64Recomp { 11 | struct LiveGeneratorContext; 12 | struct ReferenceJumpDetails { 13 | uint16_t section; 14 | uint32_t section_offset; 15 | }; 16 | struct LiveGeneratorOutput { 17 | LiveGeneratorOutput() = default; 18 | LiveGeneratorOutput(const LiveGeneratorOutput& rhs) = delete; 19 | LiveGeneratorOutput(LiveGeneratorOutput&& rhs) { *this = std::move(rhs); } 20 | LiveGeneratorOutput& operator=(const LiveGeneratorOutput& rhs) = delete; 21 | LiveGeneratorOutput& operator=(LiveGeneratorOutput&& rhs) { 22 | good = rhs.good; 23 | string_literals = std::move(rhs.string_literals); 24 | jump_tables = std::move(rhs.jump_tables); 25 | code = rhs.code; 26 | code_size = rhs.code_size; 27 | functions = std::move(rhs.functions); 28 | reference_symbol_jumps = std::move(rhs.reference_symbol_jumps); 29 | import_jumps_by_index = std::move(rhs.import_jumps_by_index); 30 | executable_offset = rhs.executable_offset; 31 | 32 | rhs.good = false; 33 | rhs.code = nullptr; 34 | rhs.code_size = 0; 35 | rhs.reference_symbol_jumps.clear(); 36 | rhs.executable_offset = 0; 37 | 38 | return *this; 39 | } 40 | ~LiveGeneratorOutput(); 41 | size_t num_reference_symbol_jumps() const; 42 | void set_reference_symbol_jump(size_t jump_index, recomp_func_t* func); 43 | ReferenceJumpDetails get_reference_symbol_jump_details(size_t jump_index); 44 | void populate_import_symbol_jumps(size_t import_index, recomp_func_t* func); 45 | bool good = false; 46 | // Storage for string literals referenced by recompiled code. These are allocated as unique_ptr arrays 47 | // to prevent them from moving, as the referenced address is baked into the recompiled code. 48 | std::vector<std::unique_ptr<char[]>> string_literals; 49 | // Storage for jump tables referenced by recompiled code (vector of arrays of pointers). These are also 50 | // allocated as unique_ptr arrays for the same reason as strings. 51 | std::vector<std::unique_ptr<void*[]>> jump_tables; 52 | // Recompiled code. 53 | void* code; 54 | // Size of the recompiled code. 55 | size_t code_size; 56 | // Pointers to each individual function within the recompiled code. 57 | std::vector<recomp_func_t*> functions; 58 | private: 59 | // List of jump details and the corresponding jump instruction address. These jumps get populated after recompilation is complete 60 | // during dependency resolution. 61 | std::vector<std::pair<ReferenceJumpDetails, void*>> reference_symbol_jumps; 62 | // Mapping of import symbol index to any jumps to that import symbol. 63 | std::unordered_multimap<size_t, void*> import_jumps_by_index; 64 | // sljit executable offset. 65 | int64_t executable_offset; 66 | 67 | friend class LiveGenerator; 68 | }; 69 | struct LiveGeneratorInputs { 70 | uint32_t base_event_index; 71 | void (*cop0_status_write)(recomp_context* ctx, gpr value); 72 | gpr (*cop0_status_read)(recomp_context* ctx); 73 | void (*switch_error)(const char* func, uint32_t vram, uint32_t jtbl); 74 | void (*do_break)(uint32_t vram); 75 | recomp_func_t* (*get_function)(int32_t vram); 76 | void (*syscall_handler)(uint8_t* rdram, recomp_context* ctx, int32_t instruction_vram); 77 | void (*pause_self)(uint8_t* rdram); 78 | void (*trigger_event)(uint8_t* rdram, recomp_context* ctx, uint32_t event_index); 79 | int32_t *reference_section_addresses; 80 | int32_t *local_section_addresses; 81 | void (*run_hook)(uint8_t* rdram, recomp_context* ctx, size_t hook_table_index); 82 | // Maps function index in recompiler context to function's entry hook slot. 83 | std::unordered_map<size_t, size_t> entry_func_hooks; 84 | // Maps function index in recompiler context to function's return hook slot. 85 | std::unordered_map<size_t, size_t> return_func_hooks; 86 | // Maps section index in the generated code to original section index. Used by regenerated 87 | // code to relocate using the corresponding original section's address. 88 | std::vector<size_t> original_section_indices; 89 | }; 90 | class LiveGenerator final : public Generator { 91 | public: 92 | LiveGenerator(size_t num_funcs, const LiveGeneratorInputs& inputs); 93 | ~LiveGenerator(); 94 | // Prevent moving or copying. 95 | LiveGenerator(const LiveGenerator& rhs) = delete; 96 | LiveGenerator(LiveGenerator&& rhs) = delete; 97 | LiveGenerator& operator=(const LiveGenerator& rhs) = delete; 98 | LiveGenerator& operator=(LiveGenerator&& rhs) = delete; 99 | 100 | LiveGeneratorOutput finish(); 101 | void process_binary_op(const BinaryOp& op, const InstructionContext& ctx) const final; 102 | void process_unary_op(const UnaryOp& op, const InstructionContext& ctx) const final; 103 | void process_store_op(const StoreOp& op, const InstructionContext& ctx) const final; 104 | void emit_function_start(const std::string& function_name, size_t func_index) const final; 105 | void emit_function_end() const final; 106 | void emit_function_call_lookup(uint32_t addr) const final; 107 | void emit_function_call_by_register(int reg) const final; 108 | void emit_function_call_reference_symbol(const Context& context, uint16_t section_index, size_t symbol_index, uint32_t target_section_offset) const final; 109 | void emit_function_call(const Context& context, size_t function_index) const final; 110 | void emit_named_function_call(const std::string& function_name) const final; 111 | void emit_goto(const std::string& target) const final; 112 | void emit_label(const std::string& label_name) const final; 113 | void emit_jtbl_addend_declaration(const JumpTable& jtbl, int reg) const final; 114 | void emit_branch_condition(const ConditionalBranchOp& op, const InstructionContext& ctx) const final; 115 | void emit_branch_close() const final; 116 | void emit_switch(const Context& recompiler_context, const JumpTable& jtbl, int reg) const final; 117 | void emit_case(int case_index, const std::string& target_label) const final; 118 | void emit_switch_error(uint32_t instr_vram, uint32_t jtbl_vram) const final; 119 | void emit_switch_close() const final; 120 | void emit_return(const Context& context, size_t func_index) const final; 121 | void emit_check_fr(int fpr) const final; 122 | void emit_check_nan(int fpr, bool is_double) const final; 123 | void emit_cop0_status_read(int reg) const final; 124 | void emit_cop0_status_write(int reg) const final; 125 | void emit_cop1_cs_read(int reg) const final; 126 | void emit_cop1_cs_write(int reg) const final; 127 | void emit_muldiv(InstrId instr_id, int reg1, int reg2) const final; 128 | void emit_syscall(uint32_t instr_vram) const final; 129 | void emit_do_break(uint32_t instr_vram) const final; 130 | void emit_pause_self() const final; 131 | void emit_trigger_event(uint32_t event_index) const final; 132 | void emit_comment(const std::string& comment) const final; 133 | private: 134 | void get_operand_string(Operand operand, UnaryOpType operation, const InstructionContext& context, std::string& operand_string) const; 135 | void get_binary_expr_string(BinaryOpType type, const BinaryOperands& operands, const InstructionContext& ctx, const std::string& output, std::string& expr_string) const; 136 | void get_notation(BinaryOpType op_type, std::string& func_string, std::string& infix_string) const; 137 | // Loads the relocated address specified by the instruction context into the target register. 138 | void load_relocated_address(const InstructionContext& ctx, int reg) const; 139 | sljit_compiler* compiler; 140 | LiveGeneratorInputs inputs; 141 | mutable std::unique_ptr<LiveGeneratorContext> context; 142 | mutable bool errored; 143 | }; 144 | 145 | void live_recompiler_init(); 146 | bool recompile_function_live(LiveGenerator& generator, const Context& context, size_t function_index, std::ostream& output_file, std::span<std::vector<uint32_t>> static_funcs_out, bool tag_reference_relocs); 147 | 148 | class ShimFunction { 149 | private: 150 | void* code; 151 | recomp_func_t* func; 152 | public: 153 | ShimFunction(recomp_func_ext_t* to_shim, uintptr_t value); 154 | ~ShimFunction(); 155 | recomp_func_t* get_func() { return func; } 156 | }; 157 | } 158 | 159 | #endif -------------------------------------------------------------------------------- /include/recompiler/operations.h: -------------------------------------------------------------------------------- 1 | #ifndef __OPERATIONS_H__ 2 | #define __OPERATIONS_H__ 3 | 4 | #include <unordered_map> 5 | 6 | #include "rabbitizer.hpp" 7 | 8 | namespace N64Recomp { 9 | using InstrId = rabbitizer::InstrId::UniqueId; 10 | using Cop0Reg = rabbitizer::Registers::Cpu::Cop0; 11 | 12 | enum class StoreOpType { 13 | SD, 14 | SDL, 15 | SDR, 16 | SW, 17 | SWL, 18 | SWR, 19 | SH, 20 | SB, 21 | SDC1, 22 | SWC1 23 | }; 24 | 25 | enum class UnaryOpType { 26 | None, 27 | ToS32, 28 | ToU32, 29 | ToS64, 30 | ToU64, 31 | Lui, 32 | Mask5, // Mask to 5 bits 33 | Mask6, // Mask to 5 bits 34 | ToInt32, // Functionally equivalent to ToS32, only exists for parity with old codegen 35 | NegateFloat, 36 | NegateDouble, 37 | AbsFloat, 38 | AbsDouble, 39 | SqrtFloat, 40 | SqrtDouble, 41 | ConvertSFromW, 42 | ConvertWFromS, 43 | ConvertDFromW, 44 | ConvertWFromD, 45 | ConvertDFromS, 46 | ConvertSFromD, 47 | ConvertDFromL, 48 | ConvertLFromD, 49 | ConvertSFromL, 50 | ConvertLFromS, 51 | TruncateWFromS, 52 | TruncateWFromD, 53 | TruncateLFromS, 54 | TruncateLFromD, 55 | RoundWFromS, 56 | RoundWFromD, 57 | RoundLFromS, 58 | RoundLFromD, 59 | CeilWFromS, 60 | CeilWFromD, 61 | CeilLFromS, 62 | CeilLFromD, 63 | FloorWFromS, 64 | FloorWFromD, 65 | FloorLFromS, 66 | FloorLFromD 67 | }; 68 | 69 | enum class BinaryOpType { 70 | // Addition/subtraction 71 | Add32, 72 | Sub32, 73 | Add64, 74 | Sub64, 75 | // Float arithmetic 76 | AddFloat, 77 | AddDouble, 78 | SubFloat, 79 | SubDouble, 80 | MulFloat, 81 | MulDouble, 82 | DivFloat, 83 | DivDouble, 84 | // Bitwise 85 | And64, 86 | Or64, 87 | Nor64, 88 | Xor64, 89 | Sll32, 90 | Sll64, 91 | Srl32, 92 | Srl64, 93 | Sra32, 94 | Sra64, 95 | // Comparisons 96 | Equal, 97 | NotEqual, 98 | Less, 99 | LessEq, 100 | Greater, 101 | GreaterEq, 102 | EqualFloat, 103 | LessFloat, 104 | LessEqFloat, 105 | EqualDouble, 106 | LessDouble, 107 | LessEqDouble, 108 | // Loads 109 | LD, 110 | LW, 111 | LWU, 112 | LH, 113 | LHU, 114 | LB, 115 | LBU, 116 | LDL, 117 | LDR, 118 | LWL, 119 | LWR, 120 | // Fixed result 121 | True, 122 | False, 123 | 124 | COUNT, 125 | }; 126 | 127 | enum class Operand { 128 | Rd, // GPR 129 | Rs, // GPR 130 | Rt, // GPR 131 | Fd, // FPR 132 | Fs, // FPR 133 | Ft, // FPR 134 | FdDouble, // Double float in fd FPR 135 | FsDouble, // Double float in fs FPR 136 | FtDouble, // Double float in ft FPR 137 | // Raw low 32-bit values of FPRs with handling for mips3 float mode behavior 138 | FdU32L, 139 | FsU32L, 140 | FtU32L, 141 | // Raw high 32-bit values of FPRs with handling for mips3 float mode behavior 142 | FdU32H, 143 | FsU32H, 144 | FtU32H, 145 | // Raw 64-bit values of FPRs 146 | FdU64, 147 | FsU64, 148 | FtU64, 149 | ImmU16, // 16-bit immediate, unsigned 150 | ImmS16, // 16-bit immediate, signed 151 | Sa, // Shift amount 152 | Sa32, // Shift amount plus 32 153 | Cop1cs, // Coprocessor 1 Condition Signal 154 | Hi, 155 | Lo, 156 | Zero, 157 | 158 | Base = Rs, // Alias for Rs for loads 159 | }; 160 | 161 | struct StoreOp { 162 | StoreOpType type; 163 | Operand value_input; 164 | }; 165 | 166 | struct UnaryOp { 167 | UnaryOpType operation; 168 | Operand output; 169 | Operand input; 170 | // Whether the FR bit needs to be checked for odd float registers for this instruction. 171 | bool check_fr = false; 172 | // Whether the input need to be checked for being NaN. 173 | bool check_nan = false; 174 | }; 175 | 176 | struct BinaryOperands { 177 | // Operation to apply to each operand before applying the binary operation to them. 178 | UnaryOpType operand_operations[2]; 179 | // The source of the input operands. 180 | Operand operands[2]; 181 | }; 182 | 183 | struct BinaryOp { 184 | // The type of binary operation this represents. 185 | BinaryOpType type; 186 | // The output operand. 187 | Operand output; 188 | // The input operands. 189 | BinaryOperands operands; 190 | // Whether the FR bit needs to be checked for odd float registers for this instruction. 191 | bool check_fr = false; 192 | // Whether the inputs need to be checked for being NaN. 193 | bool check_nan = false; 194 | }; 195 | 196 | struct ConditionalBranchOp { 197 | // The type of binary operation to use for this compare 198 | BinaryOpType comparison; 199 | // The input operands. 200 | BinaryOperands operands; 201 | // Whether this jump should link for returns. 202 | bool link; 203 | // Whether this jump has "likely" behavior (doesn't execute the delay slot if skipped). 204 | bool likely; 205 | }; 206 | 207 | extern const std::unordered_map<InstrId, UnaryOp> unary_ops; 208 | extern const std::unordered_map<InstrId, BinaryOp> binary_ops; 209 | extern const std::unordered_map<InstrId, ConditionalBranchOp> conditional_branch_ops; 210 | extern const std::unordered_map<InstrId, StoreOp> store_ops; 211 | } 212 | 213 | #endif 214 | -------------------------------------------------------------------------------- /src/analysis.cpp: -------------------------------------------------------------------------------- 1 | #include <set> 2 | #include <algorithm> 3 | 4 | #include "rabbitizer.hpp" 5 | #include "fmt/format.h" 6 | 7 | #include "recompiler/context.h" 8 | #include "analysis.h" 9 | 10 | extern "C" const char* RabbitizerRegister_getNameGpr(uint8_t regValue); 11 | 12 | // If 64-bit addressing is ever implemented, these will need to be changed to 64-bit values 13 | struct RegState { 14 | // For tracking a register that will be used to load from RAM 15 | uint32_t prev_lui; 16 | uint32_t prev_addiu_vram; 17 | uint32_t prev_addu_vram; 18 | uint8_t prev_addend_reg; 19 | uint32_t prev_got_offset; // offset of lw rt,offset(gp) 20 | bool valid_lui; 21 | bool valid_addiu; 22 | bool valid_addend; 23 | bool valid_got_offset; 24 | // For tracking a register that has been loaded from RAM 25 | uint32_t loaded_lw_vram; 26 | uint32_t loaded_addu_vram; 27 | uint32_t loaded_address; 28 | uint8_t loaded_addend_reg; 29 | bool valid_loaded; 30 | bool valid_got_loaded; // valid load through the GOT 31 | 32 | RegState() = default; 33 | 34 | void invalidate() { 35 | prev_lui = 0; 36 | prev_addiu_vram = 0; 37 | prev_addu_vram = 0; 38 | prev_addend_reg = 0; 39 | prev_got_offset = 0; 40 | 41 | valid_lui = false; 42 | valid_addiu = false; 43 | valid_addend = false; 44 | valid_got_offset = false; 45 | 46 | loaded_lw_vram = 0; 47 | loaded_addu_vram = 0; 48 | loaded_address = 0; 49 | loaded_addend_reg = 0; 50 | 51 | valid_loaded = false; 52 | valid_got_loaded = false; 53 | } 54 | }; 55 | 56 | using InstrId = rabbitizer::InstrId::UniqueId; 57 | using RegId = rabbitizer::Registers::Cpu::GprO32; 58 | 59 | bool analyze_instruction(const rabbitizer::InstructionCpu& instr, const N64Recomp::Function& func, N64Recomp::FunctionStats& stats, 60 | RegState reg_states[32], std::vector<RegState>& stack_states, bool is_got_addr_defined) { 61 | // Temporary register state for tracking the register being operated on 62 | RegState temp{}; 63 | 64 | int rd = (int)instr.GetO32_rd(); 65 | int rs = (int)instr.GetO32_rs(); 66 | int base = rs; 67 | int rt = (int)instr.GetO32_rt(); 68 | int sa = (int)instr.Get_sa(); 69 | 70 | uint16_t imm = instr.Get_immediate(); 71 | 72 | auto check_move = [&]() { 73 | if (rs == 0) { 74 | // rs is zero so copy rt to rd 75 | reg_states[rd] = reg_states[rt]; 76 | } else if (rt == 0) { 77 | // rt is zero so copy rs to rd 78 | reg_states[rd] = reg_states[rs]; 79 | } else { 80 | // Not a move, invalidate rd 81 | reg_states[rd].invalidate(); 82 | } 83 | }; 84 | 85 | switch (instr.getUniqueId()) { 86 | case InstrId::cpu_lui: 87 | // rt has been completely overwritten, so invalidate it 88 | reg_states[rt].invalidate(); 89 | reg_states[rt].prev_lui = (int16_t)imm << 16; 90 | reg_states[rt].valid_lui = true; 91 | break; 92 | case InstrId::cpu_addiu: 93 | // The target reg is a copy of the source reg plus an immediate, so copy the source reg's state 94 | reg_states[rt] = reg_states[rs]; 95 | // Set the addiu state if and only if there hasn't been an addiu already 96 | if (!reg_states[rt].valid_addiu) { 97 | reg_states[rt].prev_addiu_vram = (int16_t)imm; 98 | reg_states[rt].valid_addiu = true; 99 | } else { 100 | // Otherwise, there have been 2 or more consecutive addius so invalidate the whole register 101 | reg_states[rt].invalidate(); 102 | } 103 | break; 104 | case InstrId::cpu_addu: 105 | // rd has been completely overwritten, so invalidate it 106 | temp.invalidate(); 107 | if (reg_states[rs].valid_got_offset != reg_states[rt].valid_got_offset) { 108 | // Track which of the two registers has the valid GOT offset state and which is the addend 109 | int valid_got_offset_reg = reg_states[rs].valid_got_offset ? rs : rt; 110 | int addend_reg = reg_states[rs].valid_got_offset ? rt : rs; 111 | 112 | // Copy the got offset reg's state into the destination reg, then set the destination reg's addend to the other operand 113 | temp = reg_states[valid_got_offset_reg]; 114 | temp.valid_addend = true; 115 | temp.prev_addend_reg = addend_reg; 116 | temp.prev_addu_vram = instr.getVram(); 117 | } else if (((rs == (int)RegId::GPR_O32_gp) || (rt == (int)RegId::GPR_O32_gp)) 118 | && reg_states[rs].valid_got_loaded != reg_states[rt].valid_got_loaded) { 119 | // `addu rd, rs, $gp` or `addu rd, $gp, rt` after valid GOT load, this is the last part of a position independent 120 | // jump table call. Keep the register state intact. 121 | int valid_got_loaded_reg = reg_states[rs].valid_got_loaded ? rs : rt; 122 | 123 | temp = reg_states[valid_got_loaded_reg]; 124 | } 125 | // Exactly one of the two addend register states should have a valid lui at this time 126 | else if (reg_states[rs].valid_lui != reg_states[rt].valid_lui) { 127 | // Track which of the two registers has the valid lui state and which is the addend 128 | int valid_lui_reg = reg_states[rs].valid_lui ? rs : rt; 129 | int addend_reg = reg_states[rs].valid_lui ? rt : rs; 130 | 131 | // Copy the lui reg's state into the destination reg, then set the destination reg's addend to the other operand 132 | temp = reg_states[valid_lui_reg]; 133 | temp.valid_addend = true; 134 | temp.prev_addend_reg = addend_reg; 135 | temp.prev_addu_vram = instr.getVram(); 136 | } else { 137 | // Check if this is a move 138 | check_move(); 139 | } 140 | reg_states[rd] = temp; 141 | break; 142 | case InstrId::cpu_daddu: 143 | case InstrId::cpu_or: 144 | check_move(); 145 | break; 146 | case InstrId::cpu_sw: 147 | // If this is a store to the stack, copy the state of rt into the stack at the given offset 148 | if (base == (int)RegId::GPR_O32_sp) { 149 | if ((imm & 0b11) != 0) { 150 | fmt::print(stderr, "Invalid alignment on offset for sw to stack: {}\n", (int16_t)imm); 151 | return false; 152 | } 153 | if (((int16_t)imm) < 0) { 154 | fmt::print(stderr, "Negative offset for sw to stack: {}\n", (int16_t)imm); 155 | return false; 156 | } 157 | size_t stack_offset = imm / 4; 158 | if (stack_offset >= stack_states.size()) { 159 | stack_states.resize(stack_offset + 1); 160 | } 161 | stack_states[stack_offset] = reg_states[rt]; 162 | } 163 | break; 164 | case InstrId::cpu_lw: 165 | // rt has been completely overwritten, so invalidate it 166 | temp.invalidate(); 167 | // If this is a load from the stack, copy the state of the stack at the given offset to rt 168 | if (base == (int)RegId::GPR_O32_sp) { 169 | if ((imm & 0b11) != 0) { 170 | fmt::print(stderr, "Invalid alignment on offset for lw from stack: {}\n", (int16_t)imm); 171 | return false; 172 | } 173 | if (((int16_t)imm) < 0) { 174 | fmt::print(stderr, "Negative offset for lw from stack: {}\n", (int16_t)imm); 175 | return false; 176 | } 177 | size_t stack_offset = imm / 4; 178 | if (stack_offset >= stack_states.size()) { 179 | stack_states.resize(stack_offset + 1); 180 | } 181 | temp = stack_states[stack_offset]; 182 | } 183 | // If the base register has a valid lui state and a valid addend before this, then this may be a load from a jump table 184 | else if (reg_states[base].valid_lui && reg_states[base].valid_addend) { 185 | // Exactly one of the lw and the base reg should have a valid lo16 value. However, the lo16 may end up just being zero by pure luck, 186 | // so allow the case where the lo16 immediate is zero and the register state doesn't have a valid addiu immediate. 187 | // This means the only invalid case is where they're both true. 188 | bool nonzero_immediate = imm != 0; 189 | if (!(nonzero_immediate && reg_states[base].valid_addiu)) { 190 | uint32_t lo16; 191 | if (nonzero_immediate) { 192 | lo16 = (int16_t)imm; 193 | } else { 194 | lo16 = reg_states[base].prev_addiu_vram; 195 | } 196 | 197 | uint32_t address = reg_states[base].prev_lui + lo16; 198 | temp.valid_loaded = true; 199 | temp.loaded_lw_vram = instr.getVram(); 200 | temp.loaded_address = address; 201 | temp.loaded_addend_reg = reg_states[base].prev_addend_reg; 202 | temp.loaded_addu_vram = reg_states[base].prev_addu_vram; 203 | } 204 | } 205 | // If the base register has a valid GOT offset and a valid addend before this, then this may be a load from a position independent jump table 206 | else if (reg_states[base].valid_got_offset && reg_states[base].valid_addend) { 207 | // At this point, we will have the offset from the value of the previously read GOT entry to the address being 208 | // loaded here as well as the GOT entry offset itself 209 | temp.valid_got_loaded = true; 210 | temp.loaded_lw_vram = instr.getVram(); 211 | temp.loaded_address = imm; // This address is relative for now, we'll calculate the absolute address later 212 | temp.loaded_addend_reg = reg_states[base].prev_addend_reg; 213 | temp.loaded_addu_vram = reg_states[base].prev_addu_vram; 214 | temp.prev_got_offset = reg_states[base].prev_got_offset; 215 | } else if (base == (int)RegId::GPR_O32_gp && is_got_addr_defined) { 216 | // lw from the $gp register implies a read from the global offset table 217 | temp.prev_got_offset = imm; 218 | temp.valid_got_offset = true; 219 | } 220 | reg_states[rt] = temp; 221 | break; 222 | case InstrId::cpu_jr: 223 | // Ignore jr $ra 224 | if (rs == (int)rabbitizer::Registers::Cpu::GprO32::GPR_O32_ra) { 225 | break; 226 | } 227 | // Check if the source reg has a valid loaded state and if so record that as a jump table 228 | if (reg_states[rs].valid_loaded) { 229 | stats.jump_tables.emplace_back( 230 | reg_states[rs].loaded_address, 231 | reg_states[rs].loaded_addend_reg, 232 | 0, 233 | reg_states[rs].loaded_lw_vram, 234 | reg_states[rs].loaded_addu_vram, 235 | instr.getVram(), 236 | 0, // section index gets filled in later 237 | std::nullopt, 238 | std::vector<uint32_t>{} 239 | ); 240 | } else if (reg_states[rs].valid_got_loaded) { 241 | stats.jump_tables.emplace_back( 242 | reg_states[rs].loaded_address, 243 | reg_states[rs].loaded_addend_reg, 244 | 0, 245 | reg_states[rs].loaded_lw_vram, 246 | reg_states[rs].loaded_addu_vram, 247 | instr.getVram(), 248 | 0, // section index gets filled in later 249 | reg_states[rs].prev_got_offset, 250 | std::vector<uint32_t>{} 251 | ); 252 | } 253 | // TODO stricter validation on tail calls, since not all indirect jumps can be treated as one. 254 | break; 255 | default: 256 | if (instr.modifiesRd()) { 257 | reg_states[rd].invalidate(); 258 | } 259 | if (instr.modifiesRt()) { 260 | reg_states[rt].invalidate(); 261 | } 262 | break; 263 | } 264 | return true; 265 | } 266 | 267 | bool N64Recomp::analyze_function(const N64Recomp::Context& context, const N64Recomp::Function& func, 268 | const std::vector<rabbitizer::InstructionCpu>& instructions, N64Recomp::FunctionStats& stats) { 269 | const Section* section = &context.sections[func.section_index]; 270 | std::optional<uint32_t> got_ram_addr = section->got_ram_addr; 271 | 272 | // Create a state to track each register (r0 won't be used) 273 | RegState reg_states[32] {}; 274 | std::vector<RegState> stack_states{}; 275 | 276 | // Look for jump tables 277 | // A linear search through the func won't be accurate due to not taking control flow into account, but it'll work for finding jtables 278 | for (const auto& instr : instructions) { 279 | if (!analyze_instruction(instr, func, stats, reg_states, stack_states, got_ram_addr.has_value())) { 280 | return false; 281 | } 282 | } 283 | 284 | // Calculate absolute addresses for position-independent jump tables 285 | if (got_ram_addr.has_value()) { 286 | uint32_t got_rom_addr = got_ram_addr.value() + func.rom - func.vram; 287 | 288 | for (size_t i = 0; i < stats.jump_tables.size(); i++) { 289 | JumpTable& cur_jtbl = stats.jump_tables[i]; 290 | 291 | if (cur_jtbl.got_offset.has_value()) { 292 | uint32_t got_word = byteswap(*reinterpret_cast<const uint32_t*>(&context.rom[got_rom_addr + cur_jtbl.got_offset.value()])); 293 | 294 | cur_jtbl.vram += (section->ram_addr + got_word); 295 | } 296 | } 297 | } 298 | 299 | // Sort jump tables by their address 300 | std::sort(stats.jump_tables.begin(), stats.jump_tables.end(), 301 | [](const JumpTable& a, const JumpTable& b) 302 | { 303 | return a.vram < b.vram; 304 | }); 305 | 306 | // Determine jump table sizes 307 | for (size_t i = 0; i < stats.jump_tables.size(); i++) { 308 | JumpTable& cur_jtbl = stats.jump_tables[i]; 309 | uint32_t end_address = (uint32_t)-1; 310 | uint32_t entry_count = 0; 311 | uint32_t vram = cur_jtbl.vram; 312 | 313 | if (i < stats.jump_tables.size() - 1) { 314 | end_address = stats.jump_tables[i + 1].vram; 315 | } 316 | 317 | // TODO this assumes that the jump table is in the same section as the function itself 318 | cur_jtbl.rom = cur_jtbl.vram + func.rom - func.vram; 319 | cur_jtbl.section_index = func.section_index; 320 | 321 | while (vram < end_address) { 322 | // Retrieve the current entry of the jump table 323 | // TODO same as above 324 | uint32_t rom_addr = vram + func.rom - func.vram; 325 | uint32_t jtbl_word = byteswap(*reinterpret_cast<const uint32_t*>(&context.rom[rom_addr])); 326 | 327 | if (cur_jtbl.got_offset.has_value() && got_ram_addr.has_value()) { 328 | // Position independent jump tables have values that are offsets from the GOT, 329 | // convert those to absolute addresses 330 | jtbl_word += got_ram_addr.value(); 331 | } 332 | 333 | // Check if the entry is a valid address in the current function 334 | if (jtbl_word < func.vram || jtbl_word >= func.vram + func.words.size() * sizeof(func.words[0])) { 335 | // If it's not then this is the end of the jump table 336 | break; 337 | } 338 | cur_jtbl.entries.push_back(jtbl_word); 339 | vram += 4; 340 | } 341 | 342 | if (cur_jtbl.entries.size() == 0) { 343 | fmt::print("Failed to determine size of jump table at 0x{:08X} for instruction at 0x{:08X}\n", cur_jtbl.vram, cur_jtbl.jr_vram); 344 | return false; 345 | } 346 | 347 | //fmt::print("Jtbl at 0x{:08X} (rom 0x{:08X}) with {} entries used by instr at 0x{:08X}\n", cur_jtbl.vram, cur_jtbl.rom, cur_jtbl.entries.size(), cur_jtbl.jr_vram); 348 | } 349 | 350 | return true; 351 | } 352 | -------------------------------------------------------------------------------- /src/analysis.h: -------------------------------------------------------------------------------- 1 | #ifndef __RECOMP_ANALYSIS_H__ 2 | #define __RECOMP_ANALYSIS_H__ 3 | 4 | #include <cstdint> 5 | #include <vector> 6 | 7 | #include "recompiler/context.h" 8 | 9 | namespace N64Recomp { 10 | struct AbsoluteJump { 11 | uint32_t jump_target; 12 | uint32_t instruction_vram; 13 | 14 | AbsoluteJump(uint32_t jump_target, uint32_t instruction_vram) : jump_target(jump_target), instruction_vram(instruction_vram) {} 15 | }; 16 | 17 | struct FunctionStats { 18 | std::vector<JumpTable> jump_tables; 19 | }; 20 | 21 | bool analyze_function(const Context& context, const Function& function, const std::vector<rabbitizer::InstructionCpu>& instructions, FunctionStats& stats); 22 | } 23 | 24 | #endif -------------------------------------------------------------------------------- /src/cgenerator.cpp: -------------------------------------------------------------------------------- 1 | #include <cassert> 2 | #include <fstream> 3 | 4 | #include "fmt/format.h" 5 | #include "fmt/ostream.h" 6 | 7 | #include "recompiler/generator.h" 8 | 9 | struct BinaryOpFields { std::string func_string; std::string infix_string; }; 10 | 11 | static std::vector<BinaryOpFields> c_op_fields = []() { 12 | std::vector<BinaryOpFields> ret{}; 13 | ret.resize(static_cast<size_t>(N64Recomp::BinaryOpType::COUNT)); 14 | std::vector<char> ops_setup{}; 15 | ops_setup.resize(static_cast<size_t>(N64Recomp::BinaryOpType::COUNT)); 16 | 17 | auto setup_op = [&ret, &ops_setup](N64Recomp::BinaryOpType op_type, const std::string& func_string, const std::string& infix_string) { 18 | size_t index = static_cast<size_t>(op_type); 19 | // Prevent setting up an operation twice. 20 | assert(ops_setup[index] == false && "Operation already setup!"); 21 | ops_setup[index] = true; 22 | ret[index] = { func_string, infix_string }; 23 | }; 24 | 25 | setup_op(N64Recomp::BinaryOpType::Add32, "ADD32", ""); 26 | setup_op(N64Recomp::BinaryOpType::Sub32, "SUB32", ""); 27 | setup_op(N64Recomp::BinaryOpType::Add64, "", "+"); 28 | setup_op(N64Recomp::BinaryOpType::Sub64, "", "-"); 29 | setup_op(N64Recomp::BinaryOpType::And64, "", "&"); 30 | setup_op(N64Recomp::BinaryOpType::AddFloat, "", "+"); 31 | setup_op(N64Recomp::BinaryOpType::AddDouble, "", "+"); 32 | setup_op(N64Recomp::BinaryOpType::SubFloat, "", "-"); 33 | setup_op(N64Recomp::BinaryOpType::SubDouble, "", "-"); 34 | setup_op(N64Recomp::BinaryOpType::MulFloat, "MUL_S", ""); 35 | setup_op(N64Recomp::BinaryOpType::MulDouble, "MUL_D", ""); 36 | setup_op(N64Recomp::BinaryOpType::DivFloat, "DIV_S", ""); 37 | setup_op(N64Recomp::BinaryOpType::DivDouble, "DIV_D", ""); 38 | setup_op(N64Recomp::BinaryOpType::Or64, "", "|"); 39 | setup_op(N64Recomp::BinaryOpType::Nor64, "~", "|"); 40 | setup_op(N64Recomp::BinaryOpType::Xor64, "", "^"); 41 | setup_op(N64Recomp::BinaryOpType::Sll32, "S32", "<<"); 42 | setup_op(N64Recomp::BinaryOpType::Sll64, "", "<<"); 43 | setup_op(N64Recomp::BinaryOpType::Srl32, "S32", ">>"); 44 | setup_op(N64Recomp::BinaryOpType::Srl64, "", ">>"); 45 | setup_op(N64Recomp::BinaryOpType::Sra32, "S32", ">>"); // Arithmetic aspect will be taken care of by unary op for first operand. 46 | setup_op(N64Recomp::BinaryOpType::Sra64, "", ">>"); // Arithmetic aspect will be taken care of by unary op for first operand. 47 | setup_op(N64Recomp::BinaryOpType::Equal, "", "=="); 48 | setup_op(N64Recomp::BinaryOpType::EqualFloat,"", "=="); 49 | setup_op(N64Recomp::BinaryOpType::EqualDouble,"", "=="); 50 | setup_op(N64Recomp::BinaryOpType::NotEqual, "", "!="); 51 | setup_op(N64Recomp::BinaryOpType::Less, "", "<"); 52 | setup_op(N64Recomp::BinaryOpType::LessFloat, "", "<"); 53 | setup_op(N64Recomp::BinaryOpType::LessDouble,"", "<"); 54 | setup_op(N64Recomp::BinaryOpType::LessEq, "", "<="); 55 | setup_op(N64Recomp::BinaryOpType::LessEqFloat,"", "<="); 56 | setup_op(N64Recomp::BinaryOpType::LessEqDouble,"", "<="); 57 | setup_op(N64Recomp::BinaryOpType::Greater, "", ">"); 58 | setup_op(N64Recomp::BinaryOpType::GreaterEq, "", ">="); 59 | setup_op(N64Recomp::BinaryOpType::LD, "LD", ""); 60 | setup_op(N64Recomp::BinaryOpType::LW, "MEM_W", ""); 61 | setup_op(N64Recomp::BinaryOpType::LWU, "MEM_WU", ""); 62 | setup_op(N64Recomp::BinaryOpType::LH, "MEM_H", ""); 63 | setup_op(N64Recomp::BinaryOpType::LHU, "MEM_HU", ""); 64 | setup_op(N64Recomp::BinaryOpType::LB, "MEM_B", ""); 65 | setup_op(N64Recomp::BinaryOpType::LBU, "MEM_BU", ""); 66 | setup_op(N64Recomp::BinaryOpType::LDL, "do_ldl", ""); 67 | setup_op(N64Recomp::BinaryOpType::LDR, "do_ldr", ""); 68 | setup_op(N64Recomp::BinaryOpType::LWL, "do_lwl", ""); 69 | setup_op(N64Recomp::BinaryOpType::LWR, "do_lwr", ""); 70 | setup_op(N64Recomp::BinaryOpType::True, "", ""); 71 | setup_op(N64Recomp::BinaryOpType::False, "", ""); 72 | 73 | // Ensure every operation has been setup. 74 | for (char is_set : ops_setup) { 75 | assert(is_set && "Operation has not been setup!"); 76 | } 77 | 78 | return ret; 79 | }(); 80 | 81 | static std::string gpr_to_string(int gpr_index) { 82 | if (gpr_index == 0) { 83 | return "0"; 84 | } 85 | return fmt::format("ctx->r{}", gpr_index); 86 | } 87 | 88 | static std::string fpr_to_string(int fpr_index) { 89 | return fmt::format("ctx->f{}.fl", fpr_index); 90 | } 91 | 92 | static std::string fpr_double_to_string(int fpr_index) { 93 | return fmt::format("ctx->f{}.d", fpr_index); 94 | } 95 | 96 | static std::string fpr_u32l_to_string(int fpr_index) { 97 | if (fpr_index & 1) { 98 | return fmt::format("ctx->f_odd[({} - 1) * 2]", fpr_index); 99 | } 100 | else { 101 | return fmt::format("ctx->f{}.u32l", fpr_index); 102 | } 103 | } 104 | 105 | static std::string fpr_u64_to_string(int fpr_index) { 106 | return fmt::format("ctx->f{}.u64", fpr_index); 107 | } 108 | 109 | static std::string unsigned_reloc(const N64Recomp::InstructionContext& context) { 110 | switch (context.reloc_type) { 111 | case N64Recomp::RelocType::R_MIPS_HI16: 112 | return fmt::format("{}RELOC_HI16({}, {:#X})", 113 | context.reloc_tag_as_reference ? "REF_" : "", context.reloc_section_index, context.reloc_target_section_offset); 114 | case N64Recomp::RelocType::R_MIPS_LO16: 115 | return fmt::format("{}RELOC_LO16({}, {:#X})", 116 | context.reloc_tag_as_reference ? "REF_" : "", context.reloc_section_index, context.reloc_target_section_offset); 117 | default: 118 | throw std::runtime_error(fmt::format("Unexpected reloc type {}\n", static_cast<int>(context.reloc_type))); 119 | } 120 | } 121 | 122 | static std::string signed_reloc(const N64Recomp::InstructionContext& context) { 123 | return "(int16_t)" + unsigned_reloc(context); 124 | } 125 | 126 | void N64Recomp::CGenerator::get_operand_string(Operand operand, UnaryOpType operation, const InstructionContext& context, std::string& operand_string) const { 127 | switch (operand) { 128 | case Operand::Rd: 129 | operand_string = gpr_to_string(context.rd); 130 | break; 131 | case Operand::Rs: 132 | operand_string = gpr_to_string(context.rs); 133 | break; 134 | case Operand::Rt: 135 | operand_string = gpr_to_string(context.rt); 136 | break; 137 | case Operand::Fd: 138 | operand_string = fpr_to_string(context.fd); 139 | break; 140 | case Operand::Fs: 141 | operand_string = fpr_to_string(context.fs); 142 | break; 143 | case Operand::Ft: 144 | operand_string = fpr_to_string(context.ft); 145 | break; 146 | case Operand::FdDouble: 147 | operand_string = fpr_double_to_string(context.fd); 148 | break; 149 | case Operand::FsDouble: 150 | operand_string = fpr_double_to_string(context.fs); 151 | break; 152 | case Operand::FtDouble: 153 | operand_string = fpr_double_to_string(context.ft); 154 | break; 155 | case Operand::FdU32L: 156 | operand_string = fpr_u32l_to_string(context.fd); 157 | break; 158 | case Operand::FsU32L: 159 | operand_string = fpr_u32l_to_string(context.fs); 160 | break; 161 | case Operand::FtU32L: 162 | operand_string = fpr_u32l_to_string(context.ft); 163 | break; 164 | case Operand::FdU32H: 165 | assert(false); 166 | break; 167 | case Operand::FsU32H: 168 | assert(false); 169 | break; 170 | case Operand::FtU32H: 171 | assert(false); 172 | break; 173 | case Operand::FdU64: 174 | operand_string = fpr_u64_to_string(context.fd); 175 | break; 176 | case Operand::FsU64: 177 | operand_string = fpr_u64_to_string(context.fs); 178 | break; 179 | case Operand::FtU64: 180 | operand_string = fpr_u64_to_string(context.ft); 181 | break; 182 | case Operand::ImmU16: 183 | if (context.reloc_type != N64Recomp::RelocType::R_MIPS_NONE) { 184 | operand_string = unsigned_reloc(context); 185 | } 186 | else { 187 | operand_string = fmt::format("{:#X}", context.imm16); 188 | } 189 | break; 190 | case Operand::ImmS16: 191 | if (context.reloc_type != N64Recomp::RelocType::R_MIPS_NONE) { 192 | operand_string = signed_reloc(context); 193 | } 194 | else { 195 | operand_string = fmt::format("{:#X}", (int16_t)context.imm16); 196 | } 197 | break; 198 | case Operand::Sa: 199 | operand_string = std::to_string(context.sa); 200 | break; 201 | case Operand::Sa32: 202 | operand_string = fmt::format("({} + 32)", context.sa); 203 | break; 204 | case Operand::Cop1cs: 205 | operand_string = fmt::format("c1cs"); 206 | break; 207 | case Operand::Hi: 208 | operand_string = "hi"; 209 | break; 210 | case Operand::Lo: 211 | operand_string = "lo"; 212 | break; 213 | case Operand::Zero: 214 | operand_string = "0"; 215 | break; 216 | } 217 | switch (operation) { 218 | case UnaryOpType::None: 219 | break; 220 | case UnaryOpType::ToS32: 221 | operand_string = "S32(" + operand_string + ")"; 222 | break; 223 | case UnaryOpType::ToU32: 224 | operand_string = "U32(" + operand_string + ")"; 225 | break; 226 | case UnaryOpType::ToS64: 227 | operand_string = "SIGNED(" + operand_string + ")"; 228 | break; 229 | case UnaryOpType::ToU64: 230 | // Nothing to do here, they're already U64 231 | break; 232 | case UnaryOpType::Lui: 233 | operand_string = "S32(" + operand_string + " << 16)"; 234 | break; 235 | case UnaryOpType::Mask5: 236 | operand_string = "(" + operand_string + " & 31)"; 237 | break; 238 | case UnaryOpType::Mask6: 239 | operand_string = "(" + operand_string + " & 63)"; 240 | break; 241 | case UnaryOpType::ToInt32: 242 | operand_string = "(int32_t)" + operand_string; 243 | break; 244 | case UnaryOpType::NegateFloat: 245 | operand_string = "-" + operand_string; 246 | break; 247 | case UnaryOpType::NegateDouble: 248 | operand_string = "-" + operand_string; 249 | break; 250 | case UnaryOpType::AbsFloat: 251 | operand_string = "fabsf(" + operand_string + ")"; 252 | break; 253 | case UnaryOpType::AbsDouble: 254 | operand_string = "fabs(" + operand_string + ")"; 255 | break; 256 | case UnaryOpType::SqrtFloat: 257 | operand_string = "sqrtf(" + operand_string + ")"; 258 | break; 259 | case UnaryOpType::SqrtDouble: 260 | operand_string = "sqrt(" + operand_string + ")"; 261 | break; 262 | case UnaryOpType::ConvertSFromW: 263 | operand_string = "CVT_S_W(" + operand_string + ")"; 264 | break; 265 | case UnaryOpType::ConvertWFromS: 266 | operand_string = "CVT_W_S(" + operand_string + ")"; 267 | break; 268 | case UnaryOpType::ConvertDFromW: 269 | operand_string = "CVT_D_W(" + operand_string + ")"; 270 | break; 271 | case UnaryOpType::ConvertWFromD: 272 | operand_string = "CVT_W_D(" + operand_string + ")"; 273 | break; 274 | case UnaryOpType::ConvertDFromS: 275 | operand_string = "CVT_D_S(" + operand_string + ")"; 276 | break; 277 | case UnaryOpType::ConvertSFromD: 278 | operand_string = "CVT_S_D(" + operand_string + ")"; 279 | break; 280 | case UnaryOpType::ConvertDFromL: 281 | operand_string = "CVT_D_L(" + operand_string + ")"; 282 | break; 283 | case UnaryOpType::ConvertLFromD: 284 | operand_string = "CVT_L_D(" + operand_string + ")"; 285 | break; 286 | case UnaryOpType::ConvertSFromL: 287 | operand_string = "CVT_S_L(" + operand_string + ")"; 288 | break; 289 | case UnaryOpType::ConvertLFromS: 290 | operand_string = "CVT_L_S(" + operand_string + ")"; 291 | break; 292 | case UnaryOpType::TruncateWFromS: 293 | operand_string = "TRUNC_W_S(" + operand_string + ")"; 294 | break; 295 | case UnaryOpType::TruncateWFromD: 296 | operand_string = "TRUNC_W_D(" + operand_string + ")"; 297 | break; 298 | case UnaryOpType::TruncateLFromS: 299 | operand_string = "TRUNC_L_S(" + operand_string + ")"; 300 | break; 301 | case UnaryOpType::TruncateLFromD: 302 | operand_string = "TRUNC_L_D(" + operand_string + ")"; 303 | break; 304 | // TODO these four operations should use banker's rounding, but roundeven is C23 so it's unavailable here. 305 | case UnaryOpType::RoundWFromS: 306 | operand_string = "lroundf(" + operand_string + ")"; 307 | break; 308 | case UnaryOpType::RoundWFromD: 309 | operand_string = "lround(" + operand_string + ")"; 310 | break; 311 | case UnaryOpType::RoundLFromS: 312 | operand_string = "llroundf(" + operand_string + ")"; 313 | break; 314 | case UnaryOpType::RoundLFromD: 315 | operand_string = "llround(" + operand_string + ")"; 316 | break; 317 | case UnaryOpType::CeilWFromS: 318 | operand_string = "S32(ceilf(" + operand_string + "))"; 319 | break; 320 | case UnaryOpType::CeilWFromD: 321 | operand_string = "S32(ceil(" + operand_string + "))"; 322 | break; 323 | case UnaryOpType::CeilLFromS: 324 | operand_string = "S64(ceilf(" + operand_string + "))"; 325 | break; 326 | case UnaryOpType::CeilLFromD: 327 | operand_string = "S64(ceil(" + operand_string + "))"; 328 | break; 329 | case UnaryOpType::FloorWFromS: 330 | operand_string = "S32(floorf(" + operand_string + "))"; 331 | break; 332 | case UnaryOpType::FloorWFromD: 333 | operand_string = "S32(floor(" + operand_string + "))"; 334 | break; 335 | case UnaryOpType::FloorLFromS: 336 | operand_string = "S64(floorf(" + operand_string + "))"; 337 | break; 338 | case UnaryOpType::FloorLFromD: 339 | operand_string = "S64(floor(" + operand_string + "))"; 340 | break; 341 | } 342 | } 343 | 344 | void N64Recomp::CGenerator::get_notation(BinaryOpType op_type, std::string& func_string, std::string& infix_string) const { 345 | func_string = c_op_fields[static_cast<size_t>(op_type)].func_string; 346 | infix_string = c_op_fields[static_cast<size_t>(op_type)].infix_string; 347 | } 348 | 349 | void N64Recomp::CGenerator::get_binary_expr_string(BinaryOpType type, const BinaryOperands& operands, const InstructionContext& ctx, const std::string& output, std::string& expr_string) const { 350 | thread_local std::string input_a{}; 351 | thread_local std::string input_b{}; 352 | thread_local std::string func_string{}; 353 | thread_local std::string infix_string{}; 354 | get_operand_string(operands.operands[0], operands.operand_operations[0], ctx, input_a); 355 | get_operand_string(operands.operands[1], operands.operand_operations[1], ctx, input_b); 356 | get_notation(type, func_string, infix_string); 357 | 358 | // These cases aren't strictly necessary and are just here for parity with the old recompiler output. 359 | if (type == BinaryOpType::Less && !((operands.operands[1] == Operand::Zero && operands.operand_operations[1] == UnaryOpType::None) || (operands.operands[0] == Operand::Fs || operands.operands[0] == Operand::FsDouble))) { 360 | expr_string = fmt::format("{} {} {} ? 1 : 0", input_a, infix_string, input_b); 361 | } 362 | else if (type == BinaryOpType::Equal && operands.operands[1] == Operand::Zero && operands.operand_operations[1] == UnaryOpType::None) { 363 | expr_string = "!" + input_a; 364 | } 365 | else if (type == BinaryOpType::NotEqual && operands.operands[1] == Operand::Zero && operands.operand_operations[1] == UnaryOpType::None) { 366 | expr_string = input_a; 367 | } 368 | // End unnecessary cases. 369 | 370 | // TODO encode these ops to avoid needing special handling. 371 | else if (type == BinaryOpType::LWL || type == BinaryOpType::LWR || type == BinaryOpType::LDL || type == BinaryOpType::LDR) { 372 | expr_string = fmt::format("{}(rdram, {}, {}, {})", func_string, output, input_a, input_b); 373 | } 374 | else if (!func_string.empty() && !infix_string.empty()) { 375 | expr_string = fmt::format("{}({} {} {})", func_string, input_a, infix_string, input_b); 376 | } 377 | else if (!func_string.empty()) { 378 | expr_string = fmt::format("{}({}, {})", func_string, input_a, input_b); 379 | } 380 | else if (!infix_string.empty()) { 381 | expr_string = fmt::format("{} {} {}", input_a, infix_string, input_b); 382 | } 383 | else { 384 | // Handle special cases 385 | if (type == BinaryOpType::True) { 386 | expr_string = "1"; 387 | } 388 | else if (type == BinaryOpType::False) { 389 | expr_string = "0"; 390 | } 391 | assert(false && "Binary operation must have either a function or infix!"); 392 | } 393 | } 394 | 395 | void N64Recomp::CGenerator::emit_function_start(const std::string& function_name, size_t func_index) const { 396 | (void)func_index; 397 | fmt::print(output_file, 398 | "RECOMP_FUNC void {}(uint8_t* rdram, recomp_context* ctx) {{\n" 399 | // these variables shouldn't need to be preserved across function boundaries, so make them local for more efficient output 400 | " uint64_t hi = 0, lo = 0, result = 0;\n" 401 | " int c1cs = 0;\n", // cop1 conditional signal 402 | function_name); 403 | } 404 | 405 | void N64Recomp::CGenerator::emit_function_end() const { 406 | fmt::print(output_file, ";}}\n"); 407 | } 408 | 409 | void N64Recomp::CGenerator::emit_function_call_lookup(uint32_t addr) const { 410 | fmt::print(output_file, "LOOKUP_FUNC(0x{:08X})(rdram, ctx);\n", addr); 411 | } 412 | 413 | void N64Recomp::CGenerator::emit_function_call_by_register(int reg) const { 414 | fmt::print(output_file, "LOOKUP_FUNC({})(rdram, ctx);\n", gpr_to_string(reg)); 415 | } 416 | 417 | void N64Recomp::CGenerator::emit_function_call_reference_symbol(const Context& context, uint16_t section_index, size_t symbol_index, uint32_t target_section_offset) const { 418 | (void)target_section_offset; 419 | const N64Recomp::ReferenceSymbol& sym = context.get_reference_symbol(section_index, symbol_index); 420 | fmt::print(output_file, "{}(rdram, ctx);\n", sym.name); 421 | } 422 | 423 | void N64Recomp::CGenerator::emit_function_call(const Context& context, size_t function_index) const { 424 | fmt::print(output_file, "{}(rdram, ctx);\n", context.functions[function_index].name); 425 | } 426 | 427 | void N64Recomp::CGenerator::emit_named_function_call(const std::string& function_name) const { 428 | fmt::print(output_file, "{}(rdram, ctx);\n", function_name); 429 | } 430 | 431 | void N64Recomp::CGenerator::emit_goto(const std::string& target) const { 432 | fmt::print(output_file, 433 | " goto {};\n", target); 434 | } 435 | 436 | void N64Recomp::CGenerator::emit_label(const std::string& label_name) const { 437 | fmt::print(output_file, 438 | "{}:\n", label_name); 439 | } 440 | 441 | void N64Recomp::CGenerator::emit_jtbl_addend_declaration(const JumpTable& jtbl, int reg) const { 442 | std::string jump_variable = fmt::format("jr_addend_{:08X}", jtbl.jr_vram); 443 | fmt::print(output_file, "gpr {} = {};\n", jump_variable, gpr_to_string(reg)); 444 | } 445 | 446 | void N64Recomp::CGenerator::emit_branch_condition(const ConditionalBranchOp& op, const InstructionContext& ctx) const { 447 | // Thread local variables to prevent allocations when possible. 448 | // TODO these thread locals probably don't actually help right now, so figure out a better way to prevent allocations. 449 | thread_local std::string expr_string{}; 450 | get_binary_expr_string(op.comparison, op.operands, ctx, "", expr_string); 451 | fmt::print(output_file, "if ({}) {{\n", expr_string); 452 | } 453 | 454 | void N64Recomp::CGenerator::emit_branch_close() const { 455 | fmt::print(output_file, "}}\n"); 456 | } 457 | 458 | void N64Recomp::CGenerator::emit_switch_close() const { 459 | fmt::print(output_file, "}}\n"); 460 | } 461 | 462 | void N64Recomp::CGenerator::emit_switch(const Context& recompiler_context, const JumpTable& jtbl, int reg) const { 463 | (void)recompiler_context; 464 | (void)reg; 465 | // TODO generate code to subtract the jump table address from the register's value instead. 466 | // Once that's done, the addend temp can be deleted to simplify the generator interface. 467 | std::string jump_variable = fmt::format("jr_addend_{:08X}", jtbl.jr_vram); 468 | 469 | fmt::print(output_file, "switch ({} >> 2) {{\n", jump_variable); 470 | } 471 | 472 | void N64Recomp::CGenerator::emit_case(int case_index, const std::string& target_label) const { 473 | fmt::print(output_file, "case {}: goto {}; break;\n", case_index, target_label); 474 | } 475 | 476 | void N64Recomp::CGenerator::emit_switch_error(uint32_t instr_vram, uint32_t jtbl_vram) const { 477 | fmt::print(output_file, "default: switch_error(__func__, 0x{:08X}, 0x{:08X});\n", instr_vram, jtbl_vram); 478 | } 479 | 480 | void N64Recomp::CGenerator::emit_return(const Context& context, size_t func_index) const { 481 | (void)func_index; 482 | if (context.trace_mode) { 483 | fmt::print(output_file, "TRACE_RETURN()\n "); 484 | } 485 | fmt::print(output_file, "return;\n"); 486 | } 487 | 488 | void N64Recomp::CGenerator::emit_check_fr(int fpr) const { 489 | fmt::print(output_file, "CHECK_FR(ctx, {});\n ", fpr); 490 | } 491 | 492 | void N64Recomp::CGenerator::emit_check_nan(int fpr, bool is_double) const { 493 | fmt::print(output_file, "NAN_CHECK(ctx->f{}.{}); ", fpr, is_double ? "d" : "fl"); 494 | } 495 | 496 | void N64Recomp::CGenerator::emit_cop0_status_read(int reg) const { 497 | fmt::print(output_file, "{} = cop0_status_read(ctx);\n", gpr_to_string(reg)); 498 | } 499 | 500 | void N64Recomp::CGenerator::emit_cop0_status_write(int reg) const { 501 | fmt::print(output_file, "cop0_status_write(ctx, {});", gpr_to_string(reg)); 502 | } 503 | 504 | void N64Recomp::CGenerator::emit_cop1_cs_read(int reg) const { 505 | fmt::print(output_file, "{} = get_cop1_cs();\n", gpr_to_string(reg)); 506 | } 507 | 508 | void N64Recomp::CGenerator::emit_cop1_cs_write(int reg) const { 509 | fmt::print(output_file, "set_cop1_cs({});\n", gpr_to_string(reg)); 510 | } 511 | 512 | void N64Recomp::CGenerator::emit_muldiv(InstrId instr_id, int reg1, int reg2) const { 513 | switch (instr_id) { 514 | case InstrId::cpu_mult: 515 | fmt::print(output_file, "result = S64(S32({})) * S64(S32({})); lo = S32(result >> 0); hi = S32(result >> 32);\n", gpr_to_string(reg1), gpr_to_string(reg2)); 516 | break; 517 | case InstrId::cpu_dmult: 518 | fmt::print(output_file, "DMULT(S64({}), S64({}), &lo, &hi);\n", gpr_to_string(reg1), gpr_to_string(reg2)); 519 | break; 520 | case InstrId::cpu_multu: 521 | fmt::print(output_file, "result = U64(U32({})) * U64(U32({})); lo = S32(result >> 0); hi = S32(result >> 32);\n", gpr_to_string(reg1), gpr_to_string(reg2)); 522 | break; 523 | case InstrId::cpu_dmultu: 524 | fmt::print(output_file, "DMULTU(U64({}), U64({}), &lo, &hi);\n", gpr_to_string(reg1), gpr_to_string(reg2)); 525 | break; 526 | case InstrId::cpu_div: 527 | // Cast to 64-bits before division to prevent artihmetic exception for s32(0x80000000) / -1 528 | fmt::print(output_file, "lo = S32(S64(S32({0})) / S64(S32({1}))); hi = S32(S64(S32({0})) % S64(S32({1})));\n", gpr_to_string(reg1), gpr_to_string(reg2)); 529 | break; 530 | case InstrId::cpu_ddiv: 531 | fmt::print(output_file, "DDIV(S64({}), S64({}), &lo, &hi);\n", gpr_to_string(reg1), gpr_to_string(reg2)); 532 | break; 533 | case InstrId::cpu_divu: 534 | fmt::print(output_file, "lo = S32(U32({0}) / U32({1})); hi = S32(U32({0}) % U32({1}));\n", gpr_to_string(reg1), gpr_to_string(reg2)); 535 | break; 536 | case InstrId::cpu_ddivu: 537 | fmt::print(output_file, "DDIVU(U64({}), U64({}), &lo, &hi);\n", gpr_to_string(reg1), gpr_to_string(reg2)); 538 | break; 539 | default: 540 | assert(false); 541 | break; 542 | } 543 | } 544 | 545 | void N64Recomp::CGenerator::emit_syscall(uint32_t instr_vram) const { 546 | fmt::print(output_file, "recomp_syscall_handler(rdram, ctx, 0x{:08X});\n", instr_vram); 547 | } 548 | 549 | void N64Recomp::CGenerator::emit_do_break(uint32_t instr_vram) const { 550 | fmt::print(output_file, "do_break({});\n", instr_vram); 551 | } 552 | 553 | void N64Recomp::CGenerator::emit_pause_self() const { 554 | fmt::print(output_file, "pause_self(rdram);\n"); 555 | } 556 | 557 | void N64Recomp::CGenerator::emit_trigger_event(uint32_t event_index) const { 558 | fmt::print(output_file, "recomp_trigger_event(rdram, ctx, base_event_index + {});\n", event_index); 559 | } 560 | 561 | void N64Recomp::CGenerator::emit_comment(const std::string& comment) const { 562 | fmt::print(output_file, "// {}\n", comment); 563 | } 564 | 565 | void N64Recomp::CGenerator::process_binary_op(const BinaryOp& op, const InstructionContext& ctx) const { 566 | // Thread local variables to prevent allocations when possible. 567 | // TODO these thread locals probably don't actually help right now, so figure out a better way to prevent allocations. 568 | thread_local std::string output{}; 569 | thread_local std::string expression{}; 570 | get_operand_string(op.output, UnaryOpType::None, ctx, output); 571 | get_binary_expr_string(op.type, op.operands, ctx, output, expression); 572 | fmt::print(output_file, "{} = {};\n", output, expression); 573 | } 574 | 575 | void N64Recomp::CGenerator::process_unary_op(const UnaryOp& op, const InstructionContext& ctx) const { 576 | // Thread local variables to prevent allocations when possible. 577 | // TODO these thread locals probably don't actually help right now, so figure out a better way to prevent allocations. 578 | thread_local std::string output{}; 579 | thread_local std::string input{}; 580 | get_operand_string(op.output, UnaryOpType::None, ctx, output); 581 | get_operand_string(op.input, op.operation, ctx, input); 582 | fmt::print(output_file, "{} = {};\n", output, input); 583 | } 584 | 585 | void N64Recomp::CGenerator::process_store_op(const StoreOp& op, const InstructionContext& ctx) const { 586 | // Thread local variables to prevent allocations when possible. 587 | // TODO these thread locals probably don't actually help right now, so figure out a better way to prevent allocations. 588 | thread_local std::string base_str{}; 589 | thread_local std::string imm_str{}; 590 | thread_local std::string value_input{}; 591 | get_operand_string(Operand::Base, UnaryOpType::None, ctx, base_str); 592 | get_operand_string(Operand::ImmS16, UnaryOpType::None, ctx, imm_str); 593 | get_operand_string(op.value_input, UnaryOpType::None, ctx, value_input); 594 | 595 | enum class StoreSyntax { 596 | Func, 597 | FuncWithRdram, 598 | Assignment, 599 | }; 600 | 601 | StoreSyntax syntax; 602 | std::string func_text; 603 | 604 | switch (op.type) { 605 | case StoreOpType::SD: 606 | func_text = "SD"; 607 | syntax = StoreSyntax::Func; 608 | break; 609 | case StoreOpType::SDL: 610 | func_text = "do_sdl"; 611 | syntax = StoreSyntax::FuncWithRdram; 612 | break; 613 | case StoreOpType::SDR: 614 | func_text = "do_sdr"; 615 | syntax = StoreSyntax::FuncWithRdram; 616 | break; 617 | case StoreOpType::SW: 618 | func_text = "MEM_W"; 619 | syntax = StoreSyntax::Assignment; 620 | break; 621 | case StoreOpType::SWL: 622 | func_text = "do_swl"; 623 | syntax = StoreSyntax::FuncWithRdram; 624 | break; 625 | case StoreOpType::SWR: 626 | func_text = "do_swr"; 627 | syntax = StoreSyntax::FuncWithRdram; 628 | break; 629 | case StoreOpType::SH: 630 | func_text = "MEM_H"; 631 | syntax = StoreSyntax::Assignment; 632 | break; 633 | case StoreOpType::SB: 634 | func_text = "MEM_B"; 635 | syntax = StoreSyntax::Assignment; 636 | break; 637 | case StoreOpType::SDC1: 638 | func_text = "SD"; 639 | syntax = StoreSyntax::Func; 640 | break; 641 | case StoreOpType::SWC1: 642 | func_text = "MEM_W"; 643 | syntax = StoreSyntax::Assignment; 644 | break; 645 | default: 646 | throw std::runtime_error("Unhandled store op"); 647 | } 648 | 649 | switch (syntax) { 650 | case StoreSyntax::Func: 651 | fmt::print(output_file, "{}({}, {}, {});\n", func_text, value_input, imm_str, base_str); 652 | break; 653 | case StoreSyntax::FuncWithRdram: 654 | fmt::print(output_file, "{}(rdram, {}, {}, {});\n", func_text, imm_str, base_str, value_input); 655 | break; 656 | case StoreSyntax::Assignment: 657 | fmt::print(output_file, "{}({}, {}) = {};\n", func_text, imm_str, base_str, value_input); 658 | break; 659 | } 660 | } 661 | -------------------------------------------------------------------------------- /src/config.h: -------------------------------------------------------------------------------- 1 | #ifndef __RECOMP_CONFIG_H__ 2 | #define __RECOMP_CONFIG_H__ 3 | 4 | #include <cstdint> 5 | #include <filesystem> 6 | #include <vector> 7 | 8 | namespace N64Recomp { 9 | struct InstructionPatch { 10 | std::string func_name; 11 | int32_t vram; 12 | uint32_t value; 13 | }; 14 | 15 | struct FunctionTextHook { 16 | std::string func_name; 17 | int32_t before_vram; 18 | std::string text; 19 | }; 20 | 21 | struct FunctionSize { 22 | std::string func_name; 23 | uint32_t size_bytes; 24 | 25 | FunctionSize(const std::string& func_name, uint32_t size_bytes) : func_name(std::move(func_name)), size_bytes(size_bytes) {} 26 | }; 27 | 28 | struct ManualFunction { 29 | std::string func_name; 30 | std::string section_name; 31 | uint32_t vram; 32 | uint32_t size; 33 | 34 | ManualFunction(const std::string& func_name, std::string section_name, uint32_t vram, uint32_t size) : func_name(std::move(func_name)), section_name(std::move(section_name)), vram(vram), size(size) {} 35 | }; 36 | 37 | struct Config { 38 | int32_t entrypoint; 39 | int32_t functions_per_output_file; 40 | bool has_entrypoint; 41 | bool uses_mips3_float_mode; 42 | bool single_file_output; 43 | bool use_absolute_symbols; 44 | bool unpaired_lo16_warnings; 45 | bool trace_mode; 46 | bool allow_exports; 47 | bool strict_patch_mode; 48 | std::filesystem::path elf_path; 49 | std::filesystem::path symbols_file_path; 50 | std::filesystem::path func_reference_syms_file_path; 51 | std::vector<std::filesystem::path> data_reference_syms_file_paths; 52 | std::filesystem::path rom_file_path; 53 | std::filesystem::path output_func_path; 54 | std::filesystem::path relocatable_sections_path; 55 | std::filesystem::path output_binary_path; 56 | std::vector<std::string> stubbed_funcs; 57 | std::vector<std::string> ignored_funcs; 58 | std::vector<std::string> renamed_funcs; 59 | std::vector<InstructionPatch> instruction_patches; 60 | std::vector<FunctionTextHook> function_hooks; 61 | std::vector<FunctionSize> manual_func_sizes; 62 | std::vector<ManualFunction> manual_functions; 63 | std::string bss_section_suffix; 64 | std::string recomp_include; 65 | 66 | Config(const char* path); 67 | bool good() { return !bad; } 68 | private: 69 | bool bad; 70 | }; 71 | } 72 | 73 | #endif 74 | -------------------------------------------------------------------------------- /src/operations.cpp: -------------------------------------------------------------------------------- 1 | #include "recompiler/operations.h" 2 | 3 | namespace N64Recomp { 4 | const std::unordered_map<InstrId, UnaryOp> unary_ops { 5 | { InstrId::cpu_lui, { UnaryOpType::Lui, Operand::Rt, Operand::ImmU16 } }, 6 | { InstrId::cpu_mthi, { UnaryOpType::None, Operand::Hi, Operand::Rs } }, 7 | { InstrId::cpu_mtlo, { UnaryOpType::None, Operand::Lo, Operand::Rs } }, 8 | { InstrId::cpu_mfhi, { UnaryOpType::None, Operand::Rd, Operand::Hi } }, 9 | { InstrId::cpu_mflo, { UnaryOpType::None, Operand::Rd, Operand::Lo } }, 10 | { InstrId::cpu_mtc1, { UnaryOpType::None, Operand::FsU32L, Operand::Rt } }, 11 | { InstrId::cpu_mfc1, { UnaryOpType::ToInt32, Operand::Rt, Operand::FsU32L } }, 12 | { InstrId::cpu_dmtc1, { UnaryOpType::None, Operand::FsU64, Operand::Rt } }, 13 | { InstrId::cpu_dmfc1, { UnaryOpType::None, Operand::Rt, Operand::FsU64 } }, 14 | // Float operations 15 | { InstrId::cpu_mov_s, { UnaryOpType::None, Operand::Fd, Operand::Fs, true } }, 16 | { InstrId::cpu_mov_d, { UnaryOpType::None, Operand::FdDouble, Operand::FsDouble, true } }, 17 | { InstrId::cpu_neg_s, { UnaryOpType::NegateFloat, Operand::Fd, Operand::Fs, true, true } }, 18 | { InstrId::cpu_neg_d, { UnaryOpType::NegateDouble, Operand::FdDouble, Operand::FsDouble, true, true } }, 19 | { InstrId::cpu_abs_s, { UnaryOpType::AbsFloat, Operand::Fd, Operand::Fs, true, true } }, 20 | { InstrId::cpu_abs_d, { UnaryOpType::AbsDouble, Operand::FdDouble, Operand::FsDouble, true, true } }, 21 | { InstrId::cpu_sqrt_s, { UnaryOpType::SqrtFloat, Operand::Fd, Operand::Fs, true, true } }, 22 | { InstrId::cpu_sqrt_d, { UnaryOpType::SqrtDouble, Operand::FdDouble, Operand::FsDouble, true, true } }, 23 | { InstrId::cpu_cvt_s_w, { UnaryOpType::ConvertSFromW, Operand::Fd, Operand::FsU32L, true } }, 24 | { InstrId::cpu_cvt_w_s, { UnaryOpType::ConvertWFromS, Operand::FdU32L, Operand::Fs, true } }, 25 | { InstrId::cpu_cvt_d_w, { UnaryOpType::ConvertDFromW, Operand::FdDouble, Operand::FsU32L, true } }, 26 | { InstrId::cpu_cvt_w_d, { UnaryOpType::ConvertWFromD, Operand::FdU32L, Operand::FsDouble, true } }, 27 | { InstrId::cpu_cvt_d_s, { UnaryOpType::ConvertDFromS, Operand::FdDouble, Operand::Fs, true, true } }, 28 | { InstrId::cpu_cvt_s_d, { UnaryOpType::ConvertSFromD, Operand::Fd, Operand::FsDouble, true, true } }, 29 | { InstrId::cpu_cvt_d_l, { UnaryOpType::ConvertDFromL, Operand::FdDouble, Operand::FsU64, true } }, 30 | { InstrId::cpu_cvt_l_d, { UnaryOpType::ConvertLFromD, Operand::FdU64, Operand::FsDouble, true, true } }, 31 | { InstrId::cpu_cvt_s_l, { UnaryOpType::ConvertSFromL, Operand::Fd, Operand::FsU64, true } }, 32 | { InstrId::cpu_cvt_l_s, { UnaryOpType::ConvertLFromS, Operand::FdU64, Operand::Fs, true, true } }, 33 | { InstrId::cpu_trunc_w_s, { UnaryOpType::TruncateWFromS, Operand::FdU32L, Operand::Fs, true } }, 34 | { InstrId::cpu_trunc_w_d, { UnaryOpType::TruncateWFromD, Operand::FdU32L, Operand::FsDouble, true } }, 35 | { InstrId::cpu_round_w_s, { UnaryOpType::RoundWFromS, Operand::FdU32L, Operand::Fs, true } }, 36 | { InstrId::cpu_round_w_d, { UnaryOpType::RoundWFromD, Operand::FdU32L, Operand::FsDouble, true } }, 37 | { InstrId::cpu_ceil_w_s, { UnaryOpType::CeilWFromS, Operand::FdU32L, Operand::Fs, true } }, 38 | { InstrId::cpu_ceil_w_d, { UnaryOpType::CeilWFromD, Operand::FdU32L, Operand::FsDouble, true } }, 39 | { InstrId::cpu_floor_w_s, { UnaryOpType::FloorWFromS, Operand::FdU32L, Operand::Fs, true } }, 40 | { InstrId::cpu_floor_w_d, { UnaryOpType::FloorWFromD, Operand::FdU32L, Operand::FsDouble, true } }, 41 | }; 42 | 43 | // TODO fix usage of check_nan 44 | const std::unordered_map<InstrId, BinaryOp> binary_ops { 45 | // Addition/subtraction 46 | { InstrId::cpu_addu, { BinaryOpType::Add32, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 47 | { InstrId::cpu_add, { BinaryOpType::Add32, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 48 | { InstrId::cpu_negu, { BinaryOpType::Sub32, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, // pseudo op for subu 49 | { InstrId::cpu_subu, { BinaryOpType::Sub32, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 50 | { InstrId::cpu_sub, { BinaryOpType::Sub32, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 51 | { InstrId::cpu_daddu, { BinaryOpType::Add64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 52 | { InstrId::cpu_dadd, { BinaryOpType::Add64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 53 | { InstrId::cpu_dsubu, { BinaryOpType::Sub64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 54 | { InstrId::cpu_dsub, { BinaryOpType::Sub64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 55 | // Addition/subtraction (immediate) 56 | { InstrId::cpu_addi, { BinaryOpType::Add32, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::ImmS16 }}} }, 57 | { InstrId::cpu_addiu, { BinaryOpType::Add32, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::ImmS16 }}} }, 58 | { InstrId::cpu_daddi, { BinaryOpType::Add64, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::ImmS16 }}} }, 59 | { InstrId::cpu_daddiu, { BinaryOpType::Add64, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::ImmS16 }}} }, 60 | // Bitwise 61 | { InstrId::cpu_and, { BinaryOpType::And64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 62 | { InstrId::cpu_or, { BinaryOpType::Or64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 63 | { InstrId::cpu_nor, { BinaryOpType::Nor64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 64 | { InstrId::cpu_xor, { BinaryOpType::Xor64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}} }, 65 | // Bitwise (immediate) 66 | { InstrId::cpu_andi, { BinaryOpType::And64, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::ImmU16 }}} }, 67 | { InstrId::cpu_ori, { BinaryOpType::Or64, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::ImmU16 }}} }, 68 | { InstrId::cpu_xori, { BinaryOpType::Xor64, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::ImmU16 }}} }, 69 | // Shifts 70 | { InstrId::cpu_sllv, { BinaryOpType::Sll32, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::Mask5 }, { Operand::Rt, Operand::Rs }}} }, 71 | { InstrId::cpu_dsllv, { BinaryOpType::Sll64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::Mask6 }, { Operand::Rt, Operand::Rs }}} }, 72 | { InstrId::cpu_srlv, { BinaryOpType::Srl32, Operand::Rd, {{ UnaryOpType::ToU32, UnaryOpType::Mask5 }, { Operand::Rt, Operand::Rs }}} }, 73 | { InstrId::cpu_dsrlv, { BinaryOpType::Srl64, Operand::Rd, {{ UnaryOpType::ToU64, UnaryOpType::Mask6 }, { Operand::Rt, Operand::Rs }}} }, 74 | // Hardware bug: The input is not masked to 32 bits before right shifting, so bits from the upper half of the register will bleed into the lower half. 75 | { InstrId::cpu_srav, { BinaryOpType::Sra32, Operand::Rd, {{ UnaryOpType::ToS64, UnaryOpType::Mask5 }, { Operand::Rt, Operand::Rs }}} }, 76 | { InstrId::cpu_dsrav, { BinaryOpType::Sra64, Operand::Rd, {{ UnaryOpType::ToS64, UnaryOpType::Mask6 }, { Operand::Rt, Operand::Rs }}} }, 77 | // Shifts (immediate) 78 | { InstrId::cpu_sll, { BinaryOpType::Sll32, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rt, Operand::Sa }}} }, 79 | { InstrId::cpu_dsll, { BinaryOpType::Sll64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rt, Operand::Sa }}} }, 80 | { InstrId::cpu_dsll32, { BinaryOpType::Sll64, Operand::Rd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rt, Operand::Sa32 }}} }, 81 | { InstrId::cpu_srl, { BinaryOpType::Srl32, Operand::Rd, {{ UnaryOpType::ToU32, UnaryOpType::None }, { Operand::Rt, Operand::Sa }}} }, 82 | { InstrId::cpu_dsrl, { BinaryOpType::Srl64, Operand::Rd, {{ UnaryOpType::ToU64, UnaryOpType::None }, { Operand::Rt, Operand::Sa }}} }, 83 | { InstrId::cpu_dsrl32, { BinaryOpType::Srl64, Operand::Rd, {{ UnaryOpType::ToU64, UnaryOpType::None }, { Operand::Rt, Operand::Sa32 }}} }, 84 | // Hardware bug: The input is not masked to 32 bits before right shifting, so bits from the upper half of the register will bleed into the lower half. 85 | { InstrId::cpu_sra, { BinaryOpType::Sra32, Operand::Rd, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rt, Operand::Sa }}} }, 86 | { InstrId::cpu_dsra, { BinaryOpType::Sra64, Operand::Rd, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rt, Operand::Sa }}} }, 87 | { InstrId::cpu_dsra32, { BinaryOpType::Sra64, Operand::Rd, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rt, Operand::Sa32 }}} }, 88 | // Comparisons 89 | { InstrId::cpu_slt, { BinaryOpType::Less, Operand::Rd, {{ UnaryOpType::ToS64, UnaryOpType::ToS64 }, { Operand::Rs, Operand::Rt }}} }, 90 | { InstrId::cpu_sltu, { BinaryOpType::Less, Operand::Rd, {{ UnaryOpType::ToU64, UnaryOpType::ToU64 }, { Operand::Rs, Operand::Rt }}} }, 91 | // Comparisons (immediate) 92 | { InstrId::cpu_slti, { BinaryOpType::Less, Operand::Rt, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::ImmS16 }}} }, 93 | { InstrId::cpu_sltiu, { BinaryOpType::Less, Operand::Rt, {{ UnaryOpType::ToU64, UnaryOpType::None }, { Operand::Rs, Operand::ImmS16 }}} }, 94 | // Float arithmetic 95 | { InstrId::cpu_add_s, { BinaryOpType::AddFloat, Operand::Fd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true, true } }, 96 | { InstrId::cpu_add_d, { BinaryOpType::AddDouble, Operand::FdDouble, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true, true } }, 97 | { InstrId::cpu_sub_s, { BinaryOpType::SubFloat, Operand::Fd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true, true } }, 98 | { InstrId::cpu_sub_d, { BinaryOpType::SubDouble, Operand::FdDouble, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true, true } }, 99 | { InstrId::cpu_mul_s, { BinaryOpType::MulFloat, Operand::Fd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true, true } }, 100 | { InstrId::cpu_mul_d, { BinaryOpType::MulDouble, Operand::FdDouble, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true, true } }, 101 | { InstrId::cpu_div_s, { BinaryOpType::DivFloat, Operand::Fd, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true, true } }, 102 | { InstrId::cpu_div_d, { BinaryOpType::DivDouble, Operand::FdDouble, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true, true } }, 103 | // Float comparisons TODO remaining operations and investigate ordered/unordered and default values 104 | { InstrId::cpu_c_lt_s, { BinaryOpType::LessFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 105 | { InstrId::cpu_c_nge_s, { BinaryOpType::LessFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 106 | { InstrId::cpu_c_olt_s, { BinaryOpType::LessFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 107 | { InstrId::cpu_c_ult_s, { BinaryOpType::LessFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 108 | { InstrId::cpu_c_lt_d, { BinaryOpType::LessDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 109 | { InstrId::cpu_c_nge_d, { BinaryOpType::LessDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 110 | { InstrId::cpu_c_olt_d, { BinaryOpType::LessDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 111 | { InstrId::cpu_c_ult_d, { BinaryOpType::LessDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 112 | 113 | { InstrId::cpu_c_le_s, { BinaryOpType::LessEqFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 114 | { InstrId::cpu_c_ngt_s, { BinaryOpType::LessEqFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 115 | { InstrId::cpu_c_ole_s, { BinaryOpType::LessEqFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 116 | { InstrId::cpu_c_ule_s, { BinaryOpType::LessEqFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 117 | { InstrId::cpu_c_le_d, { BinaryOpType::LessEqDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 118 | { InstrId::cpu_c_ngt_d, { BinaryOpType::LessEqDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 119 | { InstrId::cpu_c_ole_d, { BinaryOpType::LessEqDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 120 | { InstrId::cpu_c_ule_d, { BinaryOpType::LessEqDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 121 | 122 | { InstrId::cpu_c_eq_s, { BinaryOpType::EqualFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 123 | { InstrId::cpu_c_ueq_s, { BinaryOpType::EqualFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 124 | { InstrId::cpu_c_ngl_s, { BinaryOpType::EqualFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 125 | { InstrId::cpu_c_seq_s, { BinaryOpType::EqualFloat, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Fs, Operand::Ft }}, true } }, 126 | { InstrId::cpu_c_eq_d, { BinaryOpType::EqualDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 127 | { InstrId::cpu_c_ueq_d, { BinaryOpType::EqualDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 128 | { InstrId::cpu_c_ngl_d, { BinaryOpType::EqualDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 129 | /* TODO rename to c_seq_d when fixed in rabbitizer */ 130 | { InstrId::cpu_c_deq_d, { BinaryOpType::EqualDouble, Operand::Cop1cs, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::FsDouble, Operand::FtDouble }}, true } }, 131 | // Loads 132 | { InstrId::cpu_ld, { BinaryOpType::LD, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 133 | { InstrId::cpu_lw, { BinaryOpType::LW, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 134 | { InstrId::cpu_lwu, { BinaryOpType::LWU, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 135 | { InstrId::cpu_lh, { BinaryOpType::LH, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 136 | { InstrId::cpu_lhu, { BinaryOpType::LHU, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 137 | { InstrId::cpu_lb, { BinaryOpType::LB, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 138 | { InstrId::cpu_lbu, { BinaryOpType::LBU, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 139 | { InstrId::cpu_ldl, { BinaryOpType::LDL, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 140 | { InstrId::cpu_ldr, { BinaryOpType::LDR, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 141 | { InstrId::cpu_lwl, { BinaryOpType::LWL, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 142 | { InstrId::cpu_lwr, { BinaryOpType::LWR, Operand::Rt, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 143 | { InstrId::cpu_lwc1, { BinaryOpType::LW, Operand::FtU32L, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}} }, 144 | { InstrId::cpu_ldc1, { BinaryOpType::LD, Operand::FtU64, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Base, Operand::ImmS16 }}, true } }, 145 | }; 146 | 147 | const std::unordered_map<InstrId, ConditionalBranchOp> conditional_branch_ops { 148 | { InstrId::cpu_beq, { BinaryOpType::Equal, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}, false, false }}, 149 | { InstrId::cpu_beql, { BinaryOpType::Equal, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}, false, true }}, 150 | { InstrId::cpu_bne, { BinaryOpType::NotEqual, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}, false, false }}, 151 | { InstrId::cpu_bnel, { BinaryOpType::NotEqual, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Rs, Operand::Rt }}, false, true }}, 152 | { InstrId::cpu_bgez, { BinaryOpType::GreaterEq, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, false, false }}, 153 | { InstrId::cpu_bgezl, { BinaryOpType::GreaterEq, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, false, true }}, 154 | { InstrId::cpu_bgtz, { BinaryOpType::Greater, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, false, false }}, 155 | { InstrId::cpu_bgtzl, { BinaryOpType::Greater, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, false, true }}, 156 | { InstrId::cpu_blez, { BinaryOpType::LessEq, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, false, false }}, 157 | { InstrId::cpu_blezl, { BinaryOpType::LessEq, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, false, true }}, 158 | { InstrId::cpu_bltz, { BinaryOpType::Less, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, false, false }}, 159 | { InstrId::cpu_bltzl, { BinaryOpType::Less, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, false, true }}, 160 | { InstrId::cpu_bgezal, { BinaryOpType::GreaterEq, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, true, false }}, 161 | { InstrId::cpu_bgezall, { BinaryOpType::GreaterEq, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, true, true }}, 162 | { InstrId::cpu_bltzal, { BinaryOpType::Less, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, true, false }}, 163 | { InstrId::cpu_bltzall, { BinaryOpType::Less, {{ UnaryOpType::ToS64, UnaryOpType::None }, { Operand::Rs, Operand::Zero }}, true, true }}, 164 | { InstrId::cpu_bc1f, { BinaryOpType::Equal, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Cop1cs, Operand::Zero }}, false, false }}, 165 | { InstrId::cpu_bc1fl, { BinaryOpType::Equal, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Cop1cs, Operand::Zero }}, false, true }}, 166 | { InstrId::cpu_bc1t, { BinaryOpType::NotEqual, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Cop1cs, Operand::Zero }}, false, false }}, 167 | { InstrId::cpu_bc1tl, { BinaryOpType::NotEqual, {{ UnaryOpType::None, UnaryOpType::None }, { Operand::Cop1cs, Operand::Zero }}, false, true }}, 168 | }; 169 | 170 | const std::unordered_map<InstrId, StoreOp> store_ops { 171 | { InstrId::cpu_sd, { StoreOpType::SD, Operand::Rt }}, 172 | { InstrId::cpu_sdl, { StoreOpType::SDL, Operand::Rt }}, 173 | { InstrId::cpu_sdr, { StoreOpType::SDR, Operand::Rt }}, 174 | { InstrId::cpu_sw, { StoreOpType::SW, Operand::Rt }}, 175 | { InstrId::cpu_swl, { StoreOpType::SWL, Operand::Rt }}, 176 | { InstrId::cpu_swr, { StoreOpType::SWR, Operand::Rt }}, 177 | { InstrId::cpu_sh, { StoreOpType::SH, Operand::Rt }}, 178 | { InstrId::cpu_sb, { StoreOpType::SB, Operand::Rt }}, 179 | { InstrId::cpu_sdc1, { StoreOpType::SDC1, Operand::FtU64 }}, 180 | { InstrId::cpu_swc1, { StoreOpType::SWC1, Operand::FtU32L }}, 181 | }; 182 | } -------------------------------------------------------------------------------- /src/symbol_lists.cpp: -------------------------------------------------------------------------------- 1 | #include "recompiler/context.h" 2 | 3 | const std::unordered_set<std::string> N64Recomp::reimplemented_funcs { 4 | // OS initialize functions 5 | "__osInitialize_common", 6 | "osInitialize", 7 | "osGetMemSize", 8 | // Audio interface functions 9 | "osAiGetLength", 10 | "osAiGetStatus", 11 | "osAiSetFrequency", 12 | "osAiSetNextBuffer", 13 | // Video interface functions 14 | "osViSetXScale", 15 | "osViSetYScale", 16 | "osCreateViManager", 17 | "osViBlack", 18 | "osViSetSpecialFeatures", 19 | "osViGetCurrentFramebuffer", 20 | "osViGetNextFramebuffer", 21 | "osViSwapBuffer", 22 | "osViSetMode", 23 | "osViSetEvent", 24 | // RDP functions 25 | "osDpSetNextBuffer", 26 | // RSP functions 27 | "osSpTaskLoad", 28 | "osSpTaskStartGo", 29 | "osSpTaskYield", 30 | "osSpTaskYielded", 31 | "__osSpSetPc", 32 | // Controller functions 33 | "osContInit", 34 | "osContStartReadData", 35 | "osContGetReadData", 36 | "osContStartQuery", 37 | "osContGetQuery", 38 | "osContSetCh", 39 | // EEPROM functions 40 | "osEepromProbe", 41 | "osEepromWrite", 42 | "osEepromLongWrite", 43 | "osEepromRead", 44 | "osEepromLongRead", 45 | // Rumble functions 46 | "__osMotorAccess", 47 | "osMotorInit", 48 | "osMotorStart", 49 | "osMotorStop", 50 | // PFS functions 51 | "osPfsInitPak", 52 | "osPfsFreeBlocks", 53 | "osPfsAllocateFile", 54 | "osPfsDeleteFile", 55 | "osPfsFileState", 56 | "osPfsFindFile", 57 | "osPfsReadWriteFile", 58 | // Parallel interface (cartridge, DMA, etc.) functions 59 | "osCartRomInit", 60 | "osCreatePiManager", 61 | "osPiReadIo", 62 | "osPiStartDma", 63 | "osEPiStartDma", 64 | "osPiGetStatus", 65 | "osEPiRawStartDma", 66 | "osEPiReadIo", 67 | // Flash saving functions 68 | "osFlashInit", 69 | "osFlashReadStatus", 70 | "osFlashReadId", 71 | "osFlashClearStatus", 72 | "osFlashAllErase", 73 | "osFlashAllEraseThrough", 74 | "osFlashSectorErase", 75 | "osFlashSectorEraseThrough", 76 | "osFlashCheckEraseEnd", 77 | "osFlashWriteBuffer", 78 | "osFlashWriteArray", 79 | "osFlashReadArray", 80 | "osFlashChange", 81 | // Threading functions 82 | "osCreateThread", 83 | "osStartThread", 84 | "osStopThread", 85 | "osDestroyThread", 86 | "osSetThreadPri", 87 | "osGetThreadPri", 88 | "osGetThreadId", 89 | // Message Queue functions 90 | "osCreateMesgQueue", 91 | "osRecvMesg", 92 | "osSendMesg", 93 | "osJamMesg", 94 | "osSetEventMesg", 95 | // Timer functions 96 | "osGetTime", 97 | "osSetTimer", 98 | "osStopTimer", 99 | // Voice functions 100 | "osVoiceSetWord", 101 | "osVoiceCheckWord", 102 | "osVoiceStopReadData", 103 | "osVoiceInit", 104 | "osVoiceMaskDictionary", 105 | "osVoiceStartReadData", 106 | "osVoiceControlGain", 107 | "osVoiceGetReadData", 108 | "osVoiceClearDictionary", 109 | // interrupt functions 110 | "osSetIntMask", 111 | "__osDisableInt", 112 | "__osRestoreInt", 113 | // TLB functions 114 | "osVirtualToPhysical", 115 | // Coprocessor 0/1 functions 116 | "osGetCount", 117 | "__osSetFpcCsr", 118 | // Cache funcs 119 | "osInvalDCache", 120 | "osInvalICache", 121 | "osWritebackDCache", 122 | "osWritebackDCacheAll", 123 | // Debug functions 124 | "is_proutSyncPrintf", 125 | "__checkHardware_msp", 126 | "__checkHardware_kmc", 127 | "__checkHardware_isv", 128 | "__osInitialize_msp", 129 | "__osInitialize_kmc", 130 | "__osInitialize_isv", 131 | "__osRdbSend", 132 | // ido math routines 133 | "__ull_div", 134 | "__ll_div", 135 | "__ll_mul", 136 | "__ull_rem", 137 | "__ull_to_d", 138 | "__ull_to_f", 139 | }; 140 | 141 | const std::unordered_set<std::string> N64Recomp::ignored_funcs { 142 | // OS initialize functions 143 | "__createSpeedParam", 144 | "__osInitialize_common", 145 | "osInitialize", 146 | "osGetMemSize", 147 | // Audio interface functions 148 | "osAiGetLength", 149 | "osAiGetStatus", 150 | "osAiSetFrequency", 151 | "osAiSetNextBuffer", 152 | "__osAiDeviceBusy", 153 | // Video interface functions 154 | "osViBlack", 155 | "osViFade", 156 | "osViGetCurrentField", 157 | "osViGetCurrentFramebuffer", 158 | "osViGetCurrentLine", 159 | "osViGetCurrentMode", 160 | "osViGetNextFramebuffer", 161 | "osViGetStatus", 162 | "osViRepeatLine", 163 | "osViSetEvent", 164 | "osViSetMode", 165 | "osViSetSpecialFeatures", 166 | "osViSetXScale", 167 | "osViSetYScale", 168 | "osViSwapBuffer", 169 | "osCreateViManager", 170 | "viMgrMain", 171 | "__osViInit", 172 | "__osViSwapContext", 173 | "__osViGetCurrentContext", 174 | // RDP functions 175 | "osDpGetCounters", 176 | "osDpSetStatus", 177 | "osDpGetStatus", 178 | "osDpSetNextBuffer", 179 | "__osDpDeviceBusy", 180 | // RSP functions 181 | "osSpTaskLoad", 182 | "osSpTaskStartGo", 183 | "osSpTaskYield", 184 | "osSpTaskYielded", 185 | "__osSpDeviceBusy", 186 | "__osSpGetStatus", 187 | "__osSpRawStartDma", 188 | "__osSpRawReadIo", 189 | "__osSpRawWriteIo", 190 | "__osSpSetPc", 191 | "__osSpSetStatus", 192 | // Controller functions 193 | "osContGetQuery", 194 | "osContGetReadData", 195 | "osContInit", 196 | "osContReset", 197 | "osContSetCh", 198 | "osContStartQuery", 199 | "osContStartReadData", 200 | "__osContAddressCrc", 201 | "__osContDataCrc", 202 | "__osContGetInitData", 203 | "__osContRamRead", 204 | "__osContRamWrite", 205 | "__osContChannelReset", 206 | // EEPROM functions 207 | "osEepromLongRead", 208 | "osEepromLongWrite", 209 | "osEepromProbe", 210 | "osEepromRead", 211 | "osEepromWrite", 212 | "__osEepStatus", 213 | // Rumble functions 214 | "osMotorInit", 215 | "osMotorStart", 216 | "osMotorStop", 217 | "__osMotorAccess", 218 | "_MakeMotorData", 219 | // Pack functions 220 | "__osCheckId", 221 | "__osCheckPackId", 222 | "__osGetId", 223 | "__osPfsRWInode", 224 | "__osRepairPackId", 225 | "__osPfsSelectBank", 226 | "__osCheckPackId", 227 | "ramromMain", 228 | // PFS functions 229 | "osPfsAllocateFile", 230 | "osPfsChecker", 231 | "osPfsDeleteFile", 232 | "osPfsFileState", 233 | "osPfsFindFile", 234 | "osPfsFreeBlocks", 235 | "osPfsGetLabel", 236 | "osPfsInit", 237 | "osPfsInitPak", 238 | "osPfsIsPlug", 239 | "osPfsNumFiles", 240 | "osPfsRepairId", 241 | "osPfsReadWriteFile", 242 | "__osPackEepReadData", 243 | "__osPackEepWriteData", 244 | "__osPackRamReadData", 245 | "__osPackRamWriteData", 246 | "__osPackReadData", 247 | "__osPackRequestData", 248 | "__osPfsGetInitData", 249 | "__osPfsGetOneChannelData", 250 | "__osPfsGetStatus", 251 | "__osPfsRequestData", 252 | "__osPfsRequestOneChannel", 253 | "__osPfsCreateAccessQueue", 254 | "__osPfsCheckRamArea", 255 | "__osPfsGetNextPage", 256 | // Low level serial interface functions 257 | "__osSiDeviceBusy", 258 | "__osSiGetStatus", 259 | "__osSiRawStartDma", 260 | "__osSiRawReadIo", 261 | "__osSiRawWriteIo", 262 | "__osSiCreateAccessQueue", 263 | "__osSiGetAccess", 264 | "__osSiRelAccess", 265 | // Parallel interface (cartridge, DMA, etc.) functions 266 | "osCartRomInit", 267 | "osLeoDiskInit", 268 | "osCreatePiManager", 269 | "__osDevMgrMain", 270 | "osPiGetCmdQueue", 271 | "osPiGetStatus", 272 | "osPiStartDma", 273 | "osPiWriteIo", 274 | "osEPiGetDeviceType", 275 | "osEPiStartDma", 276 | "osEPiWriteIo", 277 | "osEPiReadIo", 278 | "osPiRawStartDma", 279 | "osPiRawReadIo", 280 | "osPiRawWriteIo", 281 | "osEPiRawStartDma", 282 | "osEPiRawReadIo", 283 | "osEPiRawWriteIo", 284 | "__osPiRawStartDma", 285 | "__osPiRawReadIo", 286 | "__osPiRawWriteIo", 287 | "__osEPiRawStartDma", 288 | "__osEPiRawReadIo", 289 | "__osEPiRawWriteIo", 290 | "__osPiDeviceBusy", 291 | "__osPiCreateAccessQueue", 292 | "__osPiGetAccess", 293 | "__osPiRelAccess", 294 | "__osLeoAbnormalResume", 295 | "__osLeoInterrupt", 296 | "__osLeoResume", 297 | // Flash saving functions 298 | "osFlashInit", 299 | "osFlashReadStatus", 300 | "osFlashReadId", 301 | "osFlashClearStatus", 302 | "osFlashAllErase", 303 | "osFlashAllEraseThrough", 304 | "osFlashSectorErase", 305 | "osFlashSectorEraseThrough", 306 | "osFlashCheckEraseEnd", 307 | "osFlashWriteBuffer", 308 | "osFlashWriteArray", 309 | "osFlashReadArray", 310 | "osFlashChange", 311 | // Threading functions 312 | "osCreateThread", 313 | "osStartThread", 314 | "osStopThread", 315 | "osDestroyThread", 316 | "osYieldThread", 317 | "osSetThreadPri", 318 | "osGetThreadPri", 319 | "osGetThreadId", 320 | "__osDequeueThread", 321 | // Message Queue functions 322 | "osCreateMesgQueue", 323 | "osSendMesg", 324 | "osJamMesg", 325 | "osRecvMesg", 326 | "osSetEventMesg", 327 | // Timer functions 328 | "osStartTimer", 329 | "osSetTimer", 330 | "osStopTimer", 331 | "osGetTime", 332 | "__osInsertTimer", 333 | "__osTimerInterrupt", 334 | "__osTimerServicesInit", 335 | "__osSetTimerIntr", 336 | // Voice functions 337 | "osVoiceSetWord", 338 | "osVoiceCheckWord", 339 | "osVoiceStopReadData", 340 | "osVoiceInit", 341 | "osVoiceMaskDictionary", 342 | "osVoiceStartReadData", 343 | "osVoiceControlGain", 344 | "osVoiceGetReadData", 345 | "osVoiceClearDictionary", 346 | "__osVoiceCheckResult", 347 | "__osVoiceContRead36", 348 | "__osVoiceContWrite20", 349 | "__osVoiceContWrite4", 350 | "__osVoiceContRead2", 351 | "__osVoiceSetADConverter", 352 | "__osVoiceContDataCrc", 353 | "__osVoiceGetStatus", 354 | "corrupted", 355 | "corrupted_init", 356 | // exceptasm functions 357 | "__osExceptionPreamble", 358 | "__osException", 359 | "__ptExceptionPreamble", 360 | "__ptException", 361 | "send_mesg", 362 | "handle_CpU", 363 | "__osEnqueueAndYield", 364 | "__osEnqueueThread", 365 | "__osPopThread", 366 | "__osNop", 367 | "__osDispatchThread", 368 | "__osCleanupThread", 369 | "osGetCurrFaultedThread", 370 | "osGetNextFaultedThread", 371 | // interrupt functions 372 | "osSetIntMask", 373 | "osGetIntMask", 374 | "__osDisableInt", 375 | "__osRestoreInt", 376 | "__osSetGlobalIntMask", 377 | "__osResetGlobalIntMask", 378 | // TLB functions 379 | "osMapTLB", 380 | "osUnmapTLB", 381 | "osUnmapTLBAll", 382 | "osSetTLBASID", 383 | "osMapTLBRdb", 384 | "osVirtualToPhysical", 385 | "__osGetTLBHi", 386 | "__osGetTLBLo0", 387 | "__osGetTLBLo1", 388 | "__osGetTLBPageMask", 389 | "__osGetTLBASID", 390 | "__osProbeTLB", 391 | // Coprocessor 0/1 functions 392 | "__osSetCount", 393 | "osGetCount", 394 | "__osSetSR", 395 | "__osGetSR", 396 | "__osSetCause", 397 | "__osGetCause", 398 | "__osSetCompare", 399 | "__osGetCompare", 400 | "__osSetConfig", 401 | "__osGetConfig", 402 | "__osSetWatchLo", 403 | "__osGetWatchLo", 404 | "__osSetFpcCsr", 405 | // Cache funcs 406 | "osInvalDCache", 407 | "osInvalICache", 408 | "osWritebackDCache", 409 | "osWritebackDCacheAll", 410 | // Microcodes 411 | "rspbootTextStart", 412 | "gspF3DEX2_fifoTextStart", 413 | "gspS2DEX2_fifoTextStart", 414 | "gspL3DEX2_fifoTextStart", 415 | // Debug functions 416 | "msp_proutSyncPrintf", 417 | "__osInitialize_msp", 418 | "__checkHardware_msp", 419 | "kmc_proutSyncPrintf", 420 | "__osInitialize_kmc", 421 | "__checkHardware_kmc", 422 | "isPrintfInit", 423 | "is_proutSyncPrintf", 424 | "__osInitialize_isv", 425 | "__checkHardware_isv", 426 | "__isExpJP", 427 | "__isExp", 428 | "__osRdbSend", 429 | "__rmonSendData", 430 | "__rmonWriteMem", 431 | "__rmonReadWordAt", 432 | "__rmonWriteWordTo", 433 | "__rmonWriteMem", 434 | "__rmonSetSRegs", 435 | "__rmonSetVRegs", 436 | "__rmonStopThread", 437 | "__rmonGetThreadStatus", 438 | "__rmonGetVRegs", 439 | "__rmonHitSpBreak", 440 | "__rmonRunThread", 441 | "__rmonClearBreak", 442 | "__rmonGetBranchTarget", 443 | "__rmonGetSRegs", 444 | "__rmonSetBreak", 445 | "__rmonReadMem", 446 | "__rmonRunThread", 447 | "__rmonCopyWords", 448 | "__rmonExecute", 449 | "__rmonGetExceptionStatus", 450 | "__rmonGetExeName", 451 | "__rmonGetFRegisters", 452 | "__rmonGetGRegisters", 453 | "__rmonGetRegionCount", 454 | "__rmonGetRegions", 455 | "__rmonGetRegisterContents", 456 | "__rmonGetTCB", 457 | "__rmonHitBreak", 458 | "__rmonHitCpuFault", 459 | "__rmonIdleRCP", 460 | "__rmonInit", 461 | "__rmonIOflush", 462 | "__rmonIOhandler", 463 | "__rmonIOputw", 464 | "__rmonListBreak", 465 | "__rmonListProcesses", 466 | "__rmonListThreads", 467 | "__rmonLoadProgram", 468 | "__rmonMaskIdleThreadInts", 469 | "__rmonMemcpy", 470 | "__rmonPanic", 471 | "__rmonRCPrunning", 472 | "__rmonRunRCP", 473 | "__rmonSendFault", 474 | "__rmonSendHeader", 475 | "__rmonSendReply", 476 | "__rmonSetComm", 477 | "__rmonSetFault", 478 | "__rmonSetFRegisters", 479 | "__rmonSetGRegisters", 480 | "__rmonSetSingleStep", 481 | "__rmonStepRCP", 482 | "__rmonStopUserThreads", 483 | "__rmonThreadStatus", 484 | "__rmon", 485 | "__rmonRunThread", 486 | "rmonFindFaultedThreads", 487 | "rmonMain", 488 | "rmonPrintf", 489 | "rmonGetRcpRegister", 490 | "kdebugserver", 491 | "send", 492 | 493 | // ido math routines 494 | "__ll_div", 495 | "__ll_lshift", 496 | "__ll_mod", 497 | "__ll_mul", 498 | "__ll_rem", 499 | "__ll_rshift", 500 | "__ull_div", 501 | "__ull_divremi", 502 | "__ull_rem", 503 | "__ull_rshift", 504 | "__d_to_ll", 505 | "__f_to_ll", 506 | "__d_to_ull", 507 | "__f_to_ull", 508 | "__ll_to_d", 509 | "__ll_to_f", 510 | "__ull_to_d", 511 | "__ull_to_f", 512 | // Setjmp/longjmp for mario party 513 | "setjmp", 514 | "longjmp" 515 | // 64-bit functions for banjo 516 | "func_8025C29C", 517 | "func_8025C240", 518 | "func_8025C288", 519 | 520 | // rmonregs 521 | "LoadStoreSU", 522 | "LoadStoreVU", 523 | "SetUpForRCPop", 524 | "CleanupFromRCPop", 525 | "__rmonGetGRegisters", 526 | "__rmonSetGRegisters", 527 | "__rmonGetFRegisters", 528 | "__rmonSetFRegisters", 529 | "rmonGetRcpRegister", 530 | "__rmonGetSRegs", 531 | "__rmonSetSRegs", 532 | "__rmonGetVRegs", 533 | "__rmonSetVRegs", 534 | "__rmonGetRegisterContents", 535 | 536 | // rmonbrk 537 | "SetTempBreakpoint", 538 | "ClearTempBreakpoint", 539 | "__rmonSetBreak", 540 | "__rmonListBreak", 541 | "__rmonClearBreak", 542 | "__rmonGetBranchTarget", 543 | "IsJump", 544 | "__rmonSetSingleStep", 545 | "__rmonGetExceptionStatus", 546 | "rmonSendBreakMessage", 547 | "__rmonHitBreak", 548 | "__rmonHitSpBreak", 549 | "__rmonHitCpuFault", 550 | "rmonFindFaultedThreads", 551 | 552 | // kdebugserver 553 | "string_to_u32", 554 | "send_packet", 555 | "clear_IP6", 556 | "send", 557 | "kdebugserver", 558 | }; 559 | 560 | const std::unordered_set<std::string> N64Recomp::renamed_funcs { 561 | // Math 562 | "sincosf", 563 | "sinf", 564 | "cosf", 565 | "__sinf", 566 | "__cosf", 567 | "asinf", 568 | "acosf", 569 | "atanf", 570 | "atan2f", 571 | "tanf", 572 | "sqrt", 573 | "sqrtf", 574 | 575 | // Memory 576 | "memcpy", 577 | "memset", 578 | "memmove", 579 | "memcmp", 580 | "strcmp", 581 | "strcat", 582 | "strcpy", 583 | "strchr", 584 | "strlen", 585 | "strtok", 586 | "sprintf", 587 | "bzero", 588 | "bcopy", 589 | "bcmp", 590 | 591 | // long jumps 592 | "setjmp", 593 | "longjmp", 594 | 595 | // Math 2 596 | "ldiv", 597 | "lldiv", 598 | "ceil", 599 | "ceilf", 600 | "floor", 601 | "floorf", 602 | "fmodf", 603 | "fmod", 604 | "modf", 605 | "lround", 606 | "lroundf", 607 | "nearbyint", 608 | "nearbyintf", 609 | "round", 610 | "roundf", 611 | "trunc", 612 | "truncf", 613 | 614 | // printf family 615 | "vsprintf", 616 | "gcvt", 617 | "fcvt", 618 | "ecvt", 619 | 620 | "__assert", 621 | 622 | // allocations 623 | "malloc", 624 | "free", 625 | "realloc", 626 | "calloc", 627 | 628 | // rand 629 | "rand", 630 | "srand", 631 | "random", 632 | 633 | // gzip 634 | "huft_build", 635 | "huft_free", 636 | "inflate_codes", 637 | "inflate_stored", 638 | "inflate_fixed", 639 | "inflate_dynamic", 640 | "inflate_block", 641 | "inflate", 642 | "expand_gzip", 643 | "auRomDataRead" 644 | "data_write", 645 | "unzip", 646 | "updcrc", 647 | "clear_bufs", 648 | "fill_inbuf", 649 | "flush_window", 650 | 651 | // libgcc math routines 652 | "__muldi3", 653 | "__divdi3", 654 | "__udivdi3", 655 | "__umoddi3", 656 | "div64_64", 657 | "div64_32", 658 | "__moddi3", 659 | "_matherr", 660 | }; 661 | --------------------------------------------------------------------------------