Skip to content

Instantly share code, notes, and snippets.

@zhuowei
Created February 10, 2014 16:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhuowei/8919846 to your computer and use it in GitHub Desktop.
Save zhuowei/8919846 to your computer and use it in GitHub Desktop.
Self modifying code demo
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
int AddTwo(int input) {
return input + 2;
}
void patchThisShizzle() {
int pageSize = sysconf(_SC_PAGE_SIZE); //size of a page. Smallest unit that
//I can un-protect so I can write to it
mprotect((void*) ((((long) &AddTwo) / pageSize) * pageSize), pageSize * 2,
PROT_READ | PROT_WRITE | PROT_EXEC);
//unprotect the two pages of memory that contains the code for AddTwo by
//rounding down the pointer to the nearest page
//set the property to read, write, and execute
unsigned char* addInstrPtr = ((unsigned char*) &AddTwo);
for(;;addInstrPtr++) { //for every byte in the function code
if (*addInstrPtr == 2) { //if the byte is 2
*addInstrPtr = 3; //change it to 3
break;
}
}
}
int main() {
patchThisShizzle();
int out = AddTwo(2);
printf("%d\n", out);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment