Skip to content

Instantly share code, notes, and snippets.

@katlogic
Last active August 29, 2015 14:05
Show Gist options
  • Save katlogic/4721e91ff5a845d2b939 to your computer and use it in GitHub Desktop.
Save katlogic/4721e91ff5a845d2b939 to your computer and use it in GitHub Desktop.
#include <stdint.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
static struct chunk {
struct chunk *next;
uint32_t base;
uint32_t len;
} *clist;
static int n_mmap, n_munmap;
#define LIMIT (1024 * 1024)
static void reserve(uint32_t base, uint64_t len)
{
void *p;
struct chunk *c;
if (len < LIMIT) return;
p = mmap((void*)(uintptr_t)base, len, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
n_mmap++;
if (p == MAP_FAILED || p != (void*)(uintptr_t)base) {
struct chunk *c1, *c2;
if (p != MAP_FAILED) {
n_munmap++;
munmap(p, len);
}
reserve(base, len / 2);
reserve(base + len / 2, len / 2);
return;
}
c = malloc(sizeof(*c));
c->base = base;
c->len = len;
c->next = clist;
clist = c;
}
int main()
{
uint64_t total = 0;
struct chunk *c;
reserve(0,0x100000000);
for (c = clist; c; c = c->next) {
printf("Chunk 0x%08llx - 0x%08llx, len %u MB\n", c->base, (uint64_t)c->base + c->len, c->len >> 20);
total += c->len;
}
printf("Seized total of %lu MB using %dx mmap, %dx munmap\n", total >> 20, n_mmap, n_munmap);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment