7 #include "malloc_impl.h"
9 /* This function returns true if the interval [old,new]
10 * intersects the 'len'-sized interval below &libc.auxv
11 * (interpreted as the main-thread stack) or below &b
12 * (the current stack). It is used to defend against
13 * buggy brk implementations that can cross the stack. */
15 static int traverses_stack_p(uintptr_t old, uintptr_t new)
17 const uintptr_t len = 8<<20;
20 b = (uintptr_t)libc.auxv;
21 a = b > len ? b-len : 0;
22 if (new>a && old<b) return 1;
25 a = b > len ? b-len : 0;
26 if (new>a && old<b) return 1;
31 /* Expand the heap in-place if brk can be used, or otherwise via mmap,
32 * using an exponential lower bound on growth by mmap to make
33 * fragmentation asymptotically irrelevant. The size argument is both
34 * an input and an output, since the caller needs to know the size
35 * allocated, which will be larger than requested due to page alignment
36 * and mmap minimum size rules. The caller is responsible for locking
37 * to prevent concurrent calls. */
39 void *__expand_heap(size_t *pn)
42 static unsigned mmap_step;
45 if (n > SIZE_MAX/2 - PAGE_SIZE) {
49 n += -n & PAGE_SIZE-1;
52 brk = __syscall(SYS_brk, 0);
53 brk += -brk & PAGE_SIZE-1;
56 if (n < SIZE_MAX-brk && !traverses_stack_p(brk, brk+n)
57 && __syscall(SYS_brk, brk+n)==brk+n) {
60 return (void *)(brk-n);
63 size_t min = (size_t)PAGE_SIZE << mmap_step/2;
65 void *area = __mmap(0, n, PROT_READ|PROT_WRITE,
66 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
67 if (area == MAP_FAILED) return 0;