Created
February 10, 2014 16:58
-
-
Save zhuowei/8919846 to your computer and use it in GitHub Desktop.
Self modifying code demo
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 <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