Last active
September 5, 2019 18:39
-
-
Save vmchale/555ee6169d5d9cb851f43e3c6b5df5a9 to your computer and use it in GitHub Desktop.
Monkey patching C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <stdbool.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/mman.h> | |
#include <unistd.h> | |
int getpagesize(void); | |
void n_primes(int); | |
void change_page_permissions_of_address(void *addr) { | |
int page_size = getpagesize(); | |
addr = (void *)((long)addr - (unsigned long)addr % page_size); | |
mprotect(addr, page_size, PROT_READ | PROT_WRITE | PROT_EXEC); | |
} | |
bool is_prime(int x) { | |
if (x == 1) | |
return false; | |
int count; | |
for (count = 2; count < x; count++) { | |
if (x % count == 0) | |
return false; | |
} | |
return true; | |
} | |
void n_primes(int n) { | |
int i; | |
for (i = 1; i <= n; i += 12) { | |
if (is_prime(i)) { | |
printf("%d\n", i); | |
} | |
} | |
} | |
#if defined(__clang__) | |
#define OFFSET 84 | |
#elif defined(__GNUC__) | |
#if __GNUC__ >= 9 | |
#define OFFSET 57 | |
#else | |
#define OFFSET 59 | |
#endif | |
#endif | |
int main(int argc, char *argv[]) { | |
void *n_primes_addr = (void *)n_primes; | |
change_page_permissions_of_address(n_primes_addr); | |
unsigned char *instruction = (unsigned char *)n_primes_addr + OFFSET; | |
*instruction = 0x01; | |
n_primes(100); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment