| 15 | #include <set> |
| 16 | |
| 17 | void add_manual_functions(N64Recomp::Context& context, const std::vector<N64Recomp::ManualFunction>& manual_funcs) { |
| 18 | auto exit_failure = [](const std::string& error_str) { |
| 19 | fmt::vprint(stderr, error_str, fmt::make_format_args()); |
| 20 | std::exit(EXIT_FAILURE); |
| 21 | }; |
| 22 | |
| 23 | // Build a lookup from section name to section index. |
| 24 | std::unordered_map<std::string, size_t> section_indices_by_name{}; |
| 25 | section_indices_by_name.reserve(context.sections.size()); |
| 26 | |
| 27 | for (size_t i = 0; i < context.sections.size(); i++) { |
| 28 | section_indices_by_name.emplace(context.sections[i].name, i); |
| 29 | } |
| 30 | |
| 31 | for (const N64Recomp::ManualFunction& cur_func_def : manual_funcs) { |
| 32 | const auto section_find_it = section_indices_by_name.find(cur_func_def.section_name); |
| 33 | if (section_find_it == section_indices_by_name.end()) { |
| 34 | exit_failure(fmt::format("Manual function {} specified with section {}, which doesn't exist!\n", cur_func_def.func_name, cur_func_def.section_name)); |
| 35 | } |
| 36 | size_t section_index = section_find_it->second; |
| 37 | |
| 38 | const auto func_find_it = context.functions_by_name.find(cur_func_def.func_name); |
| 39 | if (func_find_it != context.functions_by_name.end()) { |
| 40 | exit_failure(fmt::format("Manual function {} already exists!\n", cur_func_def.func_name)); |
| 41 | } |
| 42 | |
| 43 | if ((cur_func_def.size & 0b11) != 0) { |
| 44 | exit_failure(fmt::format("Manual function {} has a size that isn't divisible by 4!\n", cur_func_def.func_name)); |
| 45 | } |
| 46 | |
| 47 | auto& section = context.sections[section_index]; |
| 48 | uint32_t section_offset = cur_func_def.vram - section.ram_addr; |
| 49 | uint32_t rom_address = section_offset + section.rom_addr; |
| 50 | |
| 51 | std::vector<uint32_t> words; |
| 52 | words.resize(cur_func_def.size / 4); |
| 53 | const uint32_t* elf_words = reinterpret_cast<const uint32_t*>(context.rom.data() + context.sections[section_index].rom_addr + section_offset); |
| 54 | |
| 55 | words.assign(elf_words, elf_words + words.size()); |
| 56 | |
| 57 | size_t function_index = context.functions.size(); |
| 58 | context.functions.emplace_back( |
| 59 | cur_func_def.vram, |
| 60 | rom_address, |
| 61 | std::move(words), |
| 62 | cur_func_def.func_name, |
| 63 | uint16_t(section_index), |
| 64 | false, |
| 65 | false, |
| 66 | false |
| 67 | ); |
| 68 | |
| 69 | context.section_functions[section_index].push_back(function_index); |
| 70 | section.function_addrs.push_back(function_index); |
| 71 | context.functions_by_vram[cur_func_def.vram].push_back(function_index); |
| 72 | context.functions_by_name[cur_func_def.func_name] = function_index; |
| 73 | } |
| 74 | } |