#include <stdlib.h>
#include <errno.h>
#include "unittest.h"
#include "vmmalloc_dummy_funcs.h"
#define USAGE "usage: %s [m|p|a]"
#define MIN_ALIGN (2)
#define MAX_ALIGN (4L * 1024L * 1024L)
#define MAX_ALLOCS (100)
static int *allocs[MAX_ALLOCS];
static void *(*Aalloc)(size_t alignment, size_t size);
static void *
posix_memalign_wrap(size_t alignment, size_t size)
{
void *ptr;
int err = posix_memalign(&ptr, alignment, size);
if (err) {
char buff[UT_MAX_ERR_MSG];
ptr = NULL;
ut_strerror(err, buff, UT_MAX_ERR_MSG);
if (err != ENOMEM)
UT_OUT("posix_memalign: %s", buff);
}
return ptr;
}
int
main(int argc, char *argv[])
{
const int test_value = 123456;
size_t alignment;
int i;
START(argc, argv, "vmmalloc_memalign");
if (argc != 2)
UT_FATAL(USAGE, argv[0]);
switch (argv[1][0]) {
case 'm':
UT_OUT("testing memalign");
Aalloc = memalign;
break;
case 'p':
UT_OUT("testing posix_memalign");
Aalloc = posix_memalign_wrap;
break;
case 'a':
UT_OUT("testing aligned_alloc");
Aalloc = aligned_alloc;
break;
default:
UT_FATAL(USAGE, argv[0]);
}
for (alignment = MAX_ALIGN; alignment >= MIN_ALIGN; alignment /= 2) {
UT_OUT("alignment %zu", alignment);
memset(allocs, 0, sizeof(allocs));
for (i = 0; i < MAX_ALLOCS; ++i) {
allocs[i] = Aalloc(alignment, sizeof(int));
if (allocs[i] == NULL)
break;
*allocs[i] = test_value;
UT_ASSERTeq(*allocs[i], test_value);
UT_ASSERTeq(
(uintptr_t)(allocs[i]) & (alignment - 1), 0);
}
UT_ASSERT(i > 0);
for (i = 0; i < MAX_ALLOCS && allocs[i] != NULL; ++i)
free(allocs[i]);
}
DONE(NULL);
}