Skip to content

Instantly share code, notes, and snippets.

@crowell
Forked from Jinmo/i-hate-heap-leak.c
Created September 4, 2017 23:48
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 crowell/e7387ef76f99a84a0ac8997ec094e498 to your computer and use it in GitHub Desktop.
Save crowell/e7387ef76f99a84a0ac8997ec094e498 to your computer and use it in GitHub Desktop.
/*
first malloc(16) : 0x1a61450
eh.. and malloc(-1) : (nil)
second malloc(16) : 0x7fe57c0008c0
FYI, libc.so address is : 0x7fe5837dc000
let's calculate! : 0x7fe580000000
*/
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <link.h> // for link_map
// from glibc-2.23/malloc/arena.c
#define HEAP_MIN_SIZE (32 * 1024)
#ifndef HEAP_MAX_SIZE
# ifdef DEFAULT_MMAP_THRESHOLD_MAX
# define HEAP_MAX_SIZE (2 * DEFAULT_MMAP_THRESHOLD_MAX)
# else
# define HEAP_MAX_SIZE (1024 * 1024) /* must be a power of two */
# endif
#endif
// wtf? It differs!
#define HEAP_MAX_SIZE 0x4000000
int main() {
struct link_map *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD);
// Allocation doesn't matter.
printf("first malloc(16) : %p\n", malloc(16));
// It must return 0 because of large size,
// which will move thread_arena into libc-related address.
printf("eh.. and malloc(-1) : %p\n", malloc(-100));
// Let's see newly allocated address.
printf("second malloc(16) : %p\n", malloc(16));
printf("FYI, libc.so address is : 0x%llx\n", libc->l_addr);
// It's calculatable from libc address.
printf("let's calculate! : 0x%llx\n", (libc->l_addr & ~((HEAP_MAX_SIZE << 1) - 1)));
// With some error.. anyway, it's HEAP_MAX_SIZE aligned mmap pointer.
// printf("It may differ, gonna fix it but I don't know how it works..\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment