Skip to content

Instantly share code, notes, and snippets.

@vmchale
Last active September 5, 2019 18:39
Show Gist options
  • Save vmchale/555ee6169d5d9cb851f43e3c6b5df5a9 to your computer and use it in GitHub Desktop.
Save vmchale/555ee6169d5d9cb851f43e3c6b5df5a9 to your computer and use it in GitHub Desktop.
Monkey patching C
#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