2016-03-29 00:44:58 -07:00
|
|
|
|
|
|
|
#include "config.h"
|
|
|
|
|
|
|
|
#include "almalloc.h"
|
|
|
|
|
2019-06-03 22:58:56 -07:00
|
|
|
#include <cassert>
|
2019-06-06 00:37:00 -07:00
|
|
|
#include <cstddef>
|
2019-01-09 19:42:40 +01:00
|
|
|
#include <cstdlib>
|
|
|
|
#include <cstring>
|
2016-03-29 00:44:58 -07:00
|
|
|
#ifdef HAVE_MALLOC_H
|
|
|
|
#include <malloc.h>
|
|
|
|
#endif
|
|
|
|
#ifdef HAVE_WINDOWS_H
|
|
|
|
#include <windows.h>
|
2018-01-16 19:24:14 -08:00
|
|
|
#else
|
|
|
|
#include <unistd.h>
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
2019-07-26 14:02:14 -07:00
|
|
|
#define ALIGNED_ALLOC_AVAILABLE (__STDC_VERSION__ >= 201112L || __cplusplus >= 201703L)
|
|
|
|
|
2016-03-29 00:44:58 -07:00
|
|
|
void *al_malloc(size_t alignment, size_t size)
|
|
|
|
{
|
2019-06-03 22:58:56 -07:00
|
|
|
assert((alignment & (alignment-1)) == 0);
|
2019-06-06 00:37:00 -07:00
|
|
|
alignment = std::max(alignment, alignof(std::max_align_t));
|
2019-06-03 22:58:56 -07:00
|
|
|
|
2019-07-26 14:02:14 -07:00
|
|
|
#if ALIGNED_ALLOC_AVAILABLE
|
2016-03-29 00:44:58 -07:00
|
|
|
size = (size+(alignment-1))&~(alignment-1);
|
|
|
|
return aligned_alloc(alignment, size);
|
|
|
|
#elif defined(HAVE_POSIX_MEMALIGN)
|
|
|
|
void *ret;
|
|
|
|
if(posix_memalign(&ret, alignment, size) == 0)
|
|
|
|
return ret;
|
2019-01-07 12:37:13 +01:00
|
|
|
return nullptr;
|
2016-03-29 00:44:58 -07:00
|
|
|
#elif defined(HAVE__ALIGNED_MALLOC)
|
|
|
|
return _aligned_malloc(size, alignment);
|
|
|
|
#else
|
2018-11-17 19:01:10 -08:00
|
|
|
char *ret = static_cast<char*>(malloc(size+alignment));
|
2019-01-07 12:37:13 +01:00
|
|
|
if(ret != nullptr)
|
2016-03-29 00:44:58 -07:00
|
|
|
{
|
|
|
|
*(ret++) = 0x00;
|
|
|
|
while(((ptrdiff_t)ret&(alignment-1)) != 0)
|
|
|
|
*(ret++) = 0x55;
|
|
|
|
}
|
|
|
|
return ret;
|
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
void *al_calloc(size_t alignment, size_t size)
|
|
|
|
{
|
|
|
|
void *ret = al_malloc(alignment, size);
|
|
|
|
if(ret) memset(ret, 0, size);
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
2018-11-18 00:38:31 -08:00
|
|
|
void al_free(void *ptr) noexcept
|
2016-03-29 00:44:58 -07:00
|
|
|
{
|
2019-07-26 14:02:14 -07:00
|
|
|
#if ALIGNED_ALLOC_AVAILABLE || defined(HAVE_POSIX_MEMALIGN)
|
2016-03-29 00:44:58 -07:00
|
|
|
free(ptr);
|
|
|
|
#elif defined(HAVE__ALIGNED_MALLOC)
|
|
|
|
_aligned_free(ptr);
|
|
|
|
#else
|
2019-01-07 12:37:13 +01:00
|
|
|
if(ptr != nullptr)
|
2016-03-29 00:44:58 -07:00
|
|
|
{
|
2018-11-17 19:01:10 -08:00
|
|
|
char *finder = static_cast<char*>(ptr);
|
2016-03-29 00:44:58 -07:00
|
|
|
do {
|
|
|
|
--finder;
|
|
|
|
} while(*finder == 0x55);
|
|
|
|
free(finder);
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
}
|