utils: Add malloc/free wrappers returning aligned data

While we could use posix_memalign(3), that is not fully portable. Further, it
might be difficult on some platforms to properly catch it in leak-detective,
which results in invalid free()s when releasing such memory.

We instead use a simple wrapper, which allocates larger data, and saves the
padding size in the allocated header. This requires that memory is released
using a dedicated function.

To reduce the risk of invalid free() when working on corrupted data, we fill up
all the padding with the padding length, and verify it during free_align().
This commit is contained in:
Martin Willi
2015-04-15 13:44:40 +02:00
parent edab6c658c
commit f206bb7444
3 changed files with 101 additions and 0 deletions
@@ -228,6 +228,41 @@ START_TEST(test_strpfx)
}
END_TEST
/*******************************************************************************
* mallac_align/free_align
*/
START_TEST(test_malloc_align)
{
void *ptr[128][256];
int size, align;
for (size = 0; size < countof(ptr); size++)
{
for (align = 0; align < countof(ptr[0]); align++)
{
ptr[size][align] = malloc_align(size, align);
if (align)
{
ck_assert((uintptr_t)ptr[size][align] % align == 0);
}
if (size)
{
ck_assert(ptr[size][align]);
memset(ptr[size][align], 0xEF, size);
}
}
}
for (size = 0; size < countof(ptr); size++)
{
for (align = 0; align < countof(ptr[0]); align++)
{
free_align(ptr[size][align]);
}
}
}
END_TEST
/*******************************************************************************
* memxor
*/
@@ -816,6 +851,10 @@ Suite *utils_suite_create()
tcase_add_loop_test(tc, test_strpfx, 0, countof(strpfx_data));
suite_add_tcase(s, tc);
tc = tcase_create("malloc_align");
tcase_add_test(tc, test_malloc_align);
suite_add_tcase(s, tc);
tc = tcase_create("memxor");
tcase_add_test(tc, test_memxor);
tcase_add_test(tc, test_memxor_aligned);