Skip to content

Instantly share code, notes, and snippets.

@tixxdz
Created October 7, 2016 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tixxdz/301158c64cdcdd0b976891579ce52609 to your computer and use it in GitHub Desktop.
Save tixxdz/301158c64cdcdd0b976891579ce52609 to your computer and use it in GitHub Desktop.
dumb bad MAP_FXIED
#include <errno.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
/* MAP_FIXED is bad... map a big ANONYMOUS in the right direction of your addresses and let MAP_FIXED reclame it... */
/* This is wrong and was written quickly it ignores linux mmap_min_addr
* addresses and plenty of bugs ... */
static void *mmap_hint(void *base_addr) {
unsigned offset = 0;
static void *addr = NULL;
static void *up = NULL;
static unsigned long psize = 0;
if (!psize)
psize = getpagesize();
if ((void *)base_addr != NULL) {
if (!addr) {
addr = base_addr;
offset = 0;
up = base_addr;
} else if (up) {
if ((unsigned long)base_addr > (unsigned long)up) {
errno = -EINVAL;
return MAP_FAILED;
}
offset += psize;
} else {
errno = -EINVAL;
return MAP_FAILED;
}
addr -= offset;
addr = (void *)((unsigned long)addr & ~(psize - 1));
goto mmap_call;
}
addr = NULL;
/* MAP_FIXED is bad... */
mmap_call:
return mmap(addr, psize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
}
int main(void)
{
void *ptr1, *ptr2, *ptr3, *ptr4, *ptr5, *ptr6, *ptr7;
ptr1 = mmap(NULL, 1024*1024, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
ptr2 = mmap_hint((void *)0x0000070000000000ULL);
ptr3 = mmap_hint((void *)0x0000070000000000ULL);
ptr4 = mmap_hint((void *)0x0000070000000000ULL);
ptr5 = mmap_hint((void *)0x0000070000000000ULL);
ptr6 = mmap_hint((void *)0x0000070000000000ULL);
ptr7 = mmap(NULL, 1024*1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
printf("%p %p %p %p %p %p %p\n", ptr1, ptr2, ptr3, ptr4, ptr5, ptr6, ptr7);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment