diff --git a/patcher/patcher.cpp b/patcher/patcher.cpp index b0691f46..d533fa2b 100644 --- a/patcher/patcher.cpp +++ b/patcher/patcher.cpp @@ -139,5 +139,58 @@ int main(int argc, char *argv[]) { spdlog::info(".text section RVA: 0x{:x}, size: 0x{:x}", textSectionRVA, textSectionSize); spdlog::info(".text section VA: 0x{:x} - 0x{:x}", textSectionVA, textSectionEndVA); + // Find available space at the end of .text section (look for null bytes) + auto textSectionData = textSection->get_data(); + uint32_t originalTextSize = textSection->get_data_size(); + + // Search backwards from the end to find contiguous null bytes + uint32_t availableSpace = 0; + for (int32_t i = originalTextSize - 1; i >= 0; i--) { + if (reinterpret_cast(textSectionData)[i] == 0x00) { + availableSpace++; + } else { + break; // Found non-null byte, stop counting + } + } + + spdlog::info("Found {} bytes of available space (null bytes) at end of .text section", availableSpace); + + if (availableSpace < mainSize) { + spdlog::error("Not enough space in .text section! Need {} bytes, found {} bytes", + mainSize, availableSpace); + return 1; + } + + // Calculate injection offset (place code at start of null space) + uint32_t injectionOffset = originalTextSize - availableSpace; + uint64_t injectionVA = textSectionVA + injectionOffset; + + spdlog::info("Injecting {} bytes at .text section offset 0x{:x} (VA: 0x{:x})", + mainSize, injectionOffset, injectionVA); + + // Copy the main function code into the available space + const uint8_t* mainCode = reinterpret_cast(mainCodeData) + mainOffset; + + // Create a copy of the section data to modify + std::vector newTextData(reinterpret_cast(textSectionData), + reinterpret_cast(textSectionData) + originalTextSize); + + // Copy our code into the null space + std::memcpy(newTextData.data() + injectionOffset, mainCode, mainSize); + + // Update the .text section with modified data (same size) + textSection->set_data(reinterpret_cast(newTextData.data()), newTextData.size()); + + spdlog::info("Injected code into existing .text section space (size unchanged: 0x{:x})", originalTextSize); + + // Save the modified PE file to output path + spdlog::info("Saving patched PE file to: {}", outputFile); + if (!peReader.save(outputFile)) { + spdlog::error("Failed to save patched PE file to: {}", outputFile); + return 1; + } + + spdlog::info("Successfully patched PE file! Main function injected at VA: 0x{:x}", injectionVA); + return 0; } \ No newline at end of file