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>
|
2020-06-07 15:38:16 -07:00
|
|
|
#include <memory>
|
2016-03-29 00:44:58 -07:00
|
|
|
#ifdef HAVE_MALLOC_H
|
|
|
|
#include <malloc.h>
|
|
|
|
#endif
|
2018-01-16 19:24:14 -08:00
|
|
|
|
|
|
|
|
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
|
|
|
|
2020-05-19 08:13:13 -07:00
|
|
|
#if defined(HAVE_STD_ALIGNED_ALLOC)
|
2016-03-29 00:44:58 -07:00
|
|
|
size = (size+(alignment-1))&~(alignment-1);
|
2020-05-16 01:21:09 -07:00
|
|
|
return std::aligned_alloc(alignment, size);
|
2016-03-29 00:44:58 -07:00
|
|
|
#elif defined(HAVE_POSIX_MEMALIGN)
|
2020-06-07 15:38:16 -07:00
|
|
|
void *ret{};
|
2016-03-29 00:44:58 -07:00
|
|
|
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
|
2020-06-07 15:38:16 -07:00
|
|
|
size_t total_size{size + alignment-1 + sizeof(void*)};
|
|
|
|
void *base{std::malloc(total_size)};
|
|
|
|
if(base != nullptr)
|
2016-03-29 00:44:58 -07:00
|
|
|
{
|
2020-06-07 15:38:16 -07:00
|
|
|
void *aligned_ptr{static_cast<char*>(base) + sizeof(void*)};
|
|
|
|
total_size -= sizeof(void*);
|
|
|
|
|
|
|
|
std::align(alignment, size, aligned_ptr, total_size);
|
|
|
|
*(static_cast<void**>(aligned_ptr)-1) = base;
|
|
|
|
base = aligned_ptr;
|
2016-03-29 00:44:58 -07:00
|
|
|
}
|
2020-06-07 15:38:16 -07:00
|
|
|
return base;
|
2016-03-29 00:44:58 -07:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
void *al_calloc(size_t alignment, size_t size)
|
|
|
|
{
|
2020-06-07 15:38:16 -07:00
|
|
|
void *ret{al_malloc(alignment, size)};
|
2020-05-16 01:21:09 -07:00
|
|
|
if(ret) std::memset(ret, 0, size);
|
2016-03-29 00:44:58 -07:00
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
2018-11-18 00:38:31 -08:00
|
|
|
void al_free(void *ptr) noexcept
|
2016-03-29 00:44:58 -07:00
|
|
|
{
|
2020-05-19 08:13:13 -07:00
|
|
|
#if defined(HAVE_STD_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
|
2020-05-16 01:21:09 -07:00
|
|
|
std::free(ptr);
|
2016-03-29 00:44:58 -07:00
|
|
|
#elif defined(HAVE__ALIGNED_MALLOC)
|
|
|
|
_aligned_free(ptr);
|
|
|
|
#else
|
2019-01-07 12:37:13 +01:00
|
|
|
if(ptr != nullptr)
|
2020-06-07 15:38:16 -07:00
|
|
|
std::free(*(static_cast<void**>(ptr) - 1));
|
2016-03-29 00:44:58 -07:00
|
|
|
#endif
|
|
|
|
}
|