"Jan Althaus" <he*******@gmail.comwrites:
I'm having some trouble using mprotect.
mprotect() is not a standard C function; try comp.unix.programmer.
But I'll add a few C-related comments as well.
A short code snippet to give
you an idea of where this is heading:
char *p;
p = malloc(1024+PAGESIZE-1);
if (!p)
exit(errno);
errno values and arguments to exit() are not necessarily related
(beyond the fact that 0 means "no error" for both). In standard C,
the only portable arguments to exit() are 0, EXIT_SUCCESS, and
EXIT_FAILURE. If you're not concerned with portability to all C
implementations (and since you're using mprotect(), presumably you're
not), you can use other values, but errno values aren't necessarily
sensible.
p = (char *)(((int) p + PAGESIZE-1) & ~(PAGESIZE-1));
memset( (void*)p, 0xc3, 1024 ); /* set everything to "ret" */
There's no need to cast the first argument to memset(); char*, or any
other pointer-to-object type, is implicitly converted to void*.
/* here we set p to contain some binary code */
if (mprotect(p, 1024, PROT_EXEC|PROT_WRITE|PROT_READ)) {
exit(errno);
}
__asm__ __volatile__ (
"call *%0 \n"
:
: "m"(p)
);
Obviously this is extremely non-portable; it's probably specific to
whatever compiler you're using (gcc?).
exit(0);
Now the problem is that the call always causes a segfault. I tried
setting the memory to just PROT_EXEC with no luck... so I'm wondering:
Is there something else I need to do in order for Linux to allow me
execution of a certain page? I'm really out of ideas here... :/
When I pass the last asm segment a pointer to a function that I
declared in c++ it works fine. So it has to be the memory protection
not doing what I expect it to...
Declared in C++? If your code is C++ rather than C (which may also
affect implicit conversions to void*), you should have wrongly posted
to comp.lang.c++ before being redirected to comp.unix.programmer.
8-)}
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.