From 9f43b2f8b54f9c8a31efad0cf487d49fd2cfbbeb Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Sun, 26 Sep 2010 00:42:46 +0930 Subject: [PATCH] alloc: fix case where poolsize is not a power of 2. --- ccan/alloc/alloc.c | 3 ++- ccan/alloc/test/run-corrupt.c | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 ccan/alloc/test/run-corrupt.c diff --git a/ccan/alloc/alloc.c b/ccan/alloc/alloc.c index 6cd96d8d..40b5b6ec 100644 --- a/ccan/alloc/alloc.c +++ b/ccan/alloc/alloc.c @@ -133,7 +133,7 @@ static unsigned int size_to_bucket(unsigned long size) static unsigned int small_page_bits(unsigned long poolsize) { - return fls(poolsize / MAX_SMALL_PAGES / 2); + return fls(poolsize / MAX_SMALL_PAGES - 1); } static struct page_header *from_pgnum(struct header *head, @@ -404,6 +404,7 @@ void alloc_init(void *pool, unsigned long poolsize) /* Add the rest of the pages as large pages. */ i = SMALL_PAGES_PER_LARGE_PAGE; while ((i << sp_bits) + (1 << lp_bits) <= poolsize) { + assert(i < MAX_SMALL_PAGES); ph = from_pgnum(head, i, sp_bits); ph->elements_used = 0; add_large_page_to_freelist(head, ph, sp_bits); diff --git a/ccan/alloc/test/run-corrupt.c b/ccan/alloc/test/run-corrupt.c new file mode 100644 index 00000000..3e7be173 --- /dev/null +++ b/ccan/alloc/test/run-corrupt.c @@ -0,0 +1,26 @@ +/* Example allocation which caused corruption. */ +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + void *mem; + + plan_tests(7); + + mem = malloc(1179648); + alloc_init(mem, 1179648); + ok1(alloc_check(mem, 1179648)); + ok1(alloc_get(mem, 1179648, 48, 16)); + ok1(alloc_check(mem, 1179648)); + ok1(alloc_get(mem, 1179648, 53, 16)); + ok1(alloc_check(mem, 1179648)); + ok1(alloc_get(mem, 1179648, 53, 16)); + ok1(alloc_check(mem, 1179648)); + free(mem); + + return exit_status(); +} -- 2.39.2