I'm trying to modify a value in the .text segment using protect to give me writing access:
int pageSize = sysconf(_SC_PAGE_SIZE);
int *toModify = (int *)(foo+5);
if (mprotect(toModify, pageSize, PROT_WRITE) < 0 ) {
perror("mprotect failed with error:");
return -1;
}
*toModify = 5;
printf("Modify :%i",foo());
mprotect does never work. It always returns an mprotect failed with error:: Invalid argument
error.
foo is a method that returns an int that is stored 5bytes after the function(thats the reason for foo+5)
I have executed the following code on OS X 10.9, and it appears to have the desired behavior. The output is “foo returns 23.”
For
foo
, I used this assembly code. Both sources were built withcc -arch i386
.You should modify code this way only as a learning exercise and not use it in any deployed application.