If you want to construct a program which disables ASLR for itself when it runs, you can use the personality
system call on Linux. Here's a recipe:
#include <stdio.h>#include <sys/personality.h>int main(int argc, char **argv) { const int old_personality = personality(ADDR_NO_RANDOMIZE); if (!(old_personality & ADDR_NO_RANDOMIZE)) { const int new_personality = personality(ADDR_NO_RANDOMIZE); if (new_personality & ADDR_NO_RANDOMIZE) { execv(argv[0], argv); } } printf("&argc == %p\n", (void *) &argc);}
If you look at the source for setarch
, it calls personality
twice in roughly this pattern. The major difference is that setarch
calls exec
on some other program, whereas my recipe exec
s itself. It's important that you use non-zero-ness of & ADDR_NO_RANDOMIZE
and not equality tests: else you can go into an infinite exec
loop if you e.g. compile with -z execstack
.
See also the man page for personality
.