LONG WINAPI VectoredHandler(PEXCEPTION_POINTERS pExceptionInfo) {
// Check if the exception is an INT3 (Breakpoint) exception
if (pExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) {
// PrintRegistersAndStack(pExceptionInfo->ContextRecord);
LogStackRegisters(pExceptionInfo->ContextRecord);//Логика моегоо хука
printf("Exception trigerred:0x%llx\n", pExceptionInfo->ContextRecord->Rip);
std::vector<uint8_t> trampolineBytes;
void* trampoline = VirtualAlloc(NULL,1000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!trampoline) {
std::cerr << "Failed to allocate memory for trampoline." << std::endl;
return EXCEPTION_CONTINUE_SEARCH;
}
void* ripAddress = reinterpret_cast<void*>(pExceptionInfo->ContextRecord->Rip);
auto it = originalInstructions.find(ripAddress);//Берем оригинальные байты которую мы запатчили
const std::vector<BYTE>& originalBytes = it->second;
size_t length = originalBytes.size();
trampolineBytes.insert(trampolineBytes.end(), originalBytes.begin(), originalBytes.end());
//Записываем их в трамполин
// Add JMP [RIP+0x0] (6 bytes) for an absolute jump
trampolineBytes.push_back(0xFF); // JMP opcode
trampolineBytes.push_back(0x25); // RIP-relative addressing mode
// Reserve space for the 4-byte RIP-relative offset and copy 0x00000000
uint32_t offset = 0x00000000;
trampolineBytes.resize(trampolineBytes.size() + sizeof(uint32_t));
memcpy(&trampolineBytes[trampolineBytes.size() - sizeof(uint32_t)], &offset, sizeof(uint32_t));
// Reserve space for the 8-byte address and copy the return address
uintptr_t returnAddress = pExceptionInfo->ContextRecord->Rip + length;
trampolineBytes.resize(trampolineBytes.size() + sizeof(uintptr_t));
memcpy(&trampolineBytes[trampolineBytes.size() - sizeof(uintptr_t)], &returnAddress, sizeof(uintptr_t));
//Делаем прыжок на следующую инструкцию после патча
// Copy the "stolen bytes" (overwritten instruction) to the trampoline
memcpy(trampoline, trampolineBytes.data(), trampolineBytes.size());
pExceptionInfo->ContextRecord->Rip = reinterpret_cast<uintptr_t>(trampoline);
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}