Skip to content

Instantly share code, notes, and snippets.

@RealNeGate
Last active September 12, 2023 23:39
Show Gist options
  • Save RealNeGate/20c4c10c3da037e7a2b156ed52b56fda to your computer and use it in GitHub Desktop.
Save RealNeGate/20c4c10c3da037e7a2b156ed52b56fda to your computer and use it in GitHub Desktop.
// We do a little too much trolling...
//
// Ever wanted to pretend divisions by zero just didn't happen? here you go...
// this is memes, don't try to make this work with C because the optimizer will
// fight you on it. You can apply it to your own language if you really wanted.
#include <stdint.h>
#include <stdio.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
static LONG cool_division(EXCEPTION_POINTERS* e) {
if (e->ExceptionRecord->ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO) {
uint8_t* rip = (uint8_t*) e->ExceptionRecord->ExceptionAddress;
// first byte is either 0xF6 or 0xF7 for IDIV or DIV
if (rip[0] != 0xF7 && rip[0] != 0xF6) {
return EXCEPTION_CONTINUE_SEARCH;
}
// so we need a mini x86 decoder now... it's
// just for the basic ModRM logic and we don't
// need to read sizes, just length so we can skip.
size_t len = 2;
uint8_t mod = rip[1] >> 6, rm = rip[1] & 7;
if (rm == 4) {
uint8_t sib = rip[len++];
if (mod == 0 && (sib & 7) == 5) {
// indirect disp32
mod = 2;
}
} else if (mod == 0 && rm == 5) {
len += 4; // RIP-relative
}
if (mod == 1) { // disp8
len += 1;
} else if (mod == 2) { // disp32
len += 4;
}
// skip the instruction
e->ContextRecord->Rip = (DWORD64) &rip[len];
// zero out the results
e->ContextRecord->Rdx = 0;
e->ContextRecord->Rax = 0;
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
int main() {
AddVectoredExceptionHandler(1, cool_division);
int a = 0;
int b = 16 / a;
printf("Result = %d\n", b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment