diff --git a/musl_src.gni b/musl_src.gni index b4a644e6cdd8ca0544de19526802446eb5bd1605..61cdab7c5d0ea06cf05b8aa42dc43f41569b6557 100644 --- a/musl_src.gni +++ b/musl_src.gni @@ -2069,6 +2069,7 @@ musl_src_porting_file = [ "src/linux/tgkill.c", "src/malloc/malloc.c", "src/malloc/memalign.c", + "src/malloc/expand_heap.c", "src/malloc/stats.c", "src/malloc/malloc_random.c", "src/multibyte/wcsnrtombs.c", diff --git a/porting/linux/user/src/malloc/expand_heap.c b/porting/linux/user/src/malloc/expand_heap.c new file mode 100644 index 0000000000000000000000000000000000000000..0883f44ac0b63e3fdb4d39fe6a19a72e71977c02 --- /dev/null +++ b/porting/linux/user/src/malloc/expand_heap.c @@ -0,0 +1,75 @@ +#include +#include +#include +#include +#include "libc.h" +#include "syscall.h" +#include "malloc_impl.h" + +#include + +/* This function returns true if the interval [old,new] + * intersects the 'len'-sized interval below &libc.auxv + * (interpreted as the main-thread stack) or below &b + * (the current stack). It is used to defend against + * buggy brk implementations that can cross the stack. */ + +static int traverses_stack_p(uintptr_t old, uintptr_t new) +{ + const uintptr_t len = 8<<20; + uintptr_t a, b; + + b = (uintptr_t)libc.auxv; + a = b > len ? b-len : 0; + if (new>a && old len ? b-len : 0; + if (new>a && old SIZE_MAX/2 - PAGE_SIZE) { + errno = ENOMEM; + return 0; + } + n += -n & PAGE_SIZE-1; + + if (!brk) { + brk = __syscall(SYS_brk, 0); + brk += -brk & PAGE_SIZE-1; + } + + if (n < SIZE_MAX-brk && !traverses_stack_p(brk, brk+n) + && __syscall(SYS_brk, brk+n)==brk+n) { + *pn = n; + brk += n; + return (void *)(brk-n); + } + + size_t min = (size_t)PAGE_SIZE << mmap_step/3; + if (n < min) n = min; + void *area = __mmap(0, n, PROT_READ|PROT_WRITE, + MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); + if (area == MAP_FAILED) return 0; + prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, area, n, "native_heap:musl"); + + *pn = n; + mmap_step++; + return area; +}