#include "unittest.h"
#define MAX_ALLOCS (100)
static int custom_allocs;
static int custom_alloc_calls;
static void *
malloc_custom(size_t size)
{
++custom_alloc_calls;
++custom_allocs;
return malloc(size);
}
static void
free_custom(void *ptr)
{
++custom_alloc_calls;
--custom_allocs;
free(ptr);
}
static void *
realloc_custom(void *ptr, size_t size)
{
++custom_alloc_calls;
return realloc(ptr, size);
}
static char *
strdup_custom(const char *s)
{
++custom_alloc_calls;
++custom_allocs;
return strdup(s);
}
int
main(int argc, char *argv[])
{
const int test_value = 123456;
char *dir = NULL;
VMEM *vmp;
size_t alignment;
unsigned i;
int *ptr;
int *ptrs[MAX_ALLOCS];
START(argc, argv, "vmem_aligned_alloc");
if (argc == 2) {
dir = argv[1];
} else if (argc > 2) {
UT_FATAL("usage: %s [directory]", argv[0]);
}
void *mem_pool = MMAP_ANON_ALIGNED(VMEM_MIN_POOL, 4 << 20);
vmem_set_funcs(malloc_custom, free_custom,
realloc_custom, strdup_custom, NULL);
for (alignment = 2; alignment <= 4 * 1024 * 1024; alignment *= 2) {
if (dir == NULL) {
vmp = vmem_create_in_region(mem_pool,
VMEM_MIN_POOL);
if (vmp == NULL)
UT_FATAL("!vmem_create_in_region");
} else {
vmp = vmem_create(dir, VMEM_MIN_POOL);
if (vmp == NULL)
UT_FATAL("!vmem_create");
}
memset(ptrs, 0, MAX_ALLOCS * sizeof(ptrs[0]));
for (i = 0; i < MAX_ALLOCS; ++i) {
ptr = vmem_aligned_alloc(vmp, alignment, sizeof(int));
ptrs[i] = ptr;
UT_ASSERT(i != 0 || ptr != NULL);
if (ptr == NULL)
break;
*ptr = test_value;
UT_ASSERTeq(*ptr, test_value);
UT_ASSERTeq((uintptr_t)(ptr) & (alignment - 1), 0);
if (dir == NULL) {
UT_ASSERTrange(ptr, mem_pool, VMEM_MIN_POOL);
}
}
for (i = 0; i < MAX_ALLOCS; ++i) {
if (ptrs[i] == NULL)
break;
vmem_free(vmp, ptrs[i]);
}
vmem_delete(vmp);
}
UT_ASSERTne(custom_alloc_calls, 0);
UT_ASSERTeq(custom_allocs, 0);
DONE(NULL);
}