4

I've been trying to use mprotect() to change protections on a certain region of memory on Android. However whatever I do I cannot cause the region to be writeable (whatever I do it still seems to remain PROT_READ|PROT_EXEC. Maybe there's something I'm not understanding about Android's memory protections? Will it absolutely always refuse me the right to write into executable memory regions? If so there a system option to disable this?

The code looks like something like this:

int sub() { return 0; }

void main()
{
    int pagesize = sysconf(_SC_PAGESIZE); /* 0x1000 */
    mprotect( (void *)((int)sub - ((int)sub % pagesize), pagesize, PROT_WRITE);
    *((unsigned char *)sub) = 0; /* fails here */
}

I'v tried using mmap and calling the mprotect syscall directly but to no avail. I've also tried PROT_READ|PROT_WRITE.

I've done a similar thing on iOS which works absolutely fine...

David Kaplan
  • 81
  • 1
  • 6
  • 1
    I'd have expected that it's only possible to make a page writeable if that page is backed by writeable storage --- i.e., swap or a writeable file. You're trying to change the access mode of a demand-paged executable, which has been mmapped to be read only, so I'd expect that to fail. However... the `mprotect()` man page does specifically say that what you're trying to do is possible. *shrug* What does mprotect return? Does it set errno? – David Given Mar 05 '12 at 12:57
  • That's exactly the point of the `mprotect()` call. Should allow these things. However on certain platforms this functionality has been removed in the kernel but I wasn't aware that this was the case with Android. The `mprotect()` call returns `0` (i.e. succeeds). – David Kaplan Mar 06 '12 at 07:30
  • If the addr of sub happens to be aligned at the page boundary, your mprotect() call will set a page ahead of the "sub" function. May this be the reason? – Infinite Feb 16 '17 at 05:51

0 Answers0