X-Git-Url: http://nsz.repo.hu/git/?p=musl;a=blobdiff_plain;f=src%2Fmalloc%2Fmalloc.c;h=46cc21fb7b54ed95310c51e7ac0ee6a285ff5532;hp=d9a30fe44460c26c2f630c743744c894b50dc855;hb=b761bd19aa1ae0f95dd2146397b7f39b44a471b6;hpb=0b44a0315b47dd8eced9f3b7f31580cf14bbfc01 diff --git a/src/malloc/malloc.c b/src/malloc/malloc.c index d9a30fe4..46cc21fb 100644 --- a/src/malloc/malloc.c +++ b/src/malloc/malloc.c @@ -179,7 +179,7 @@ fail: return 0; } -static int init_malloc() +static int init_malloc(size_t n) { static int init, waiters; int state; @@ -196,7 +196,7 @@ static int init_malloc() mal.brk = __brk(0) + 2*SIZE_ALIGN-1 & -SIZE_ALIGN; - c = expand_heap(1); + c = expand_heap(n); if (!c) { a_store(&init, 0); @@ -210,15 +210,20 @@ static int init_malloc() a_store(&init, 2); if (waiters) __wake(&init, -1, 1); - return 0; + return 1; } static int adjust_size(size_t *n) { /* Result of pointer difference must fit in ptrdiff_t. */ - if (*n > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) { - errno = ENOMEM; - return -1; + if (*n-1 > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) { + if (*n) { + errno = ENOMEM; + return -1; + } else { + *n = SIZE_ALIGN; + return 0; + } } *n = (*n + OVERHEAD + SIZE_ALIGN - 1) & SIZE_MASK; return 0; @@ -325,10 +330,10 @@ void *malloc(size_t n) struct chunk *c; int i, j; - if (!n || adjust_size(&n) < 0) return 0; + if (adjust_size(&n) < 0) return 0; if (n > MMAP_THRESHOLD) { - size_t len = n + PAGE_SIZE - 1 & -PAGE_SIZE; + size_t len = n + OVERHEAD + PAGE_SIZE - 1 & -PAGE_SIZE; char *base = __mmap(0, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (base == (void *)-1) return 0; @@ -342,7 +347,7 @@ void *malloc(size_t n) for (;;) { uint64_t mask = mal.binmap & -(1ULL< 0) continue; c = expand_heap(n); if (!c) return 0; if (alloc_rev(c)) { @@ -377,7 +382,6 @@ void *realloc(void *p, size_t n) void *new; if (!p) return malloc(n); - else if (!n) return free(p), (void *)0; if (adjust_size(&n) < 0) return 0; @@ -389,6 +393,8 @@ void *realloc(void *p, size_t n) char *base = (char *)self - extra; size_t oldlen = n0 + extra; size_t newlen = n + extra; + /* Crash on realloc of freed chunk */ + if ((uintptr_t)base < mal.brk) *(char *)0=0; if (newlen < PAGE_SIZE && (new = malloc(n))) { memcpy(new, p, n-OVERHEAD); free(p); @@ -450,6 +456,8 @@ void free(void *p) size_t extra = self->data[-1]; char *base = (char *)self - extra; size_t len = CHUNK_SIZE(self) + extra; + /* Crash on double free */ + if ((uintptr_t)base < mal.brk) *(char *)0=0; __munmap(base, len); return; }