1 #include <limits.h>
2 #include <stdint.h>
3 #include <errno.h>
4 #include <sys/mman.h>
5 #include "libc.h"
6 #include "syscall.h"
7 #include "malloc_impl.h"
8 
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. */
14 
traverses_stack_p(uintptr_t old,uintptr_t new)15 static int traverses_stack_p(uintptr_t old, uintptr_t new)
16 {
17 	const uintptr_t len = 8<<20;
18 	uintptr_t a, b;
19 
20 	b = (uintptr_t)libc.auxv;
21 	a = b > len ? b-len : 0;
22 	if (new>a && old<b) return 1;
23 
24 	b = (uintptr_t)&b;
25 	a = b > len ? b-len : 0;
26 	if (new>a && old<b) return 1;
27 
28 	return 0;
29 }
30 
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. */
38 
__expand_heap(size_t * pn)39 void *__expand_heap(size_t *pn)
40 {
41 	static uintptr_t brk;
42 	static unsigned mmap_step;
43 	size_t n = *pn;
44 
45 	if (n > SIZE_MAX/2 - PAGE_SIZE) {
46 		errno = ENOMEM;
47 		return 0;
48 	}
49 	n += -n & PAGE_SIZE-1;
50 
51 	if (!brk) {
52 		brk = __syscall(SYS_brk, 0);
53 		brk += -brk & PAGE_SIZE-1;
54 	}
55 
56 	if (n < SIZE_MAX-brk && !traverses_stack_p(brk, brk+n)
57 	    && __syscall(SYS_brk, brk+n)==brk+n) {
58 		*pn = n;
59 		brk += n;
60 		return (void *)(brk-n);
61 	}
62 
63 	size_t min = (size_t)PAGE_SIZE << mmap_step/2;
64 	if (n < min) n = min;
65 	void *area = __mmap(0, n, PROT_READ|PROT_WRITE,
66 		MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
67 	if (area == MAP_FAILED) return 0;
68 	*pn = n;
69 	mmap_step++;
70 	return area;
71 }
72