Natural alignment for USE_MALLOC (#248)

* Add concept of natural alignment to tests.

snmalloc naturally aligns blocks very heavily, so that
the largest power-of-two in the rounded size is the alignment.
This checks that in the test, and provides a method for
finding the natural alignment of a block.

* Improve USE_MALLOC to provide alignment

snmalloc provides a lot of alginment guarantees. This ensures that when
we pass through to the system allocator we still get those alignment
guarantees.

The commit also fixes the tests to work with USE_MALLOC, and builds a
set of unit tests for ctest to check behaviour.
This commit is contained in:
Matthew Parkinson
2020-09-28 10:08:19 +01:00
committed by GitHub
parent f89f78ad46
commit 923705e514
16 changed files with 203 additions and 54 deletions

64
src/mem/external_alloc.h Normal file
View File

@@ -0,0 +1,64 @@
#pragma once
#ifdef SNMALLOC_PASS_THROUGH
# include <stdlib.h>
# if defined(_WIN32) //|| defined(__APPLE__)
# error "Pass through not supported on this platform"
// The Windows aligned allocation API is not capable of supporting the
// snmalloc API Apple was not providing aligned memory in some tests.
# else
// Defines malloc_size for the platform.
# if defined(_WIN32)
namespace snmalloc::external_alloc
{
inline size_t malloc_usable_size(void* ptr)
{
return _msize(ptr);
}
}
# elif defined(__APPLE__)
# include <malloc/malloc.h>
namespace snmalloc::external_alloc
{
inline size_t malloc_usable_size(void* ptr)
{
return malloc_size(ptr);
}
}
# elif defined(__linux__)
# include <malloc.h>
namespace snmalloc::external_alloc
{
using ::malloc_usable_size;
}
# elif defined(__sun) || defined(__HAIKU__) || defined(__NetBSD__) || \
defined(__OpenBSD__)
namespace snmalloc::external_alloc
{
using ::malloc_usable_size;
}
# elif defined(__FreeBSD__)
# include <malloc_np.h>
namespace snmalloc::external_alloc
{
using ::malloc_usable_size;
}
# else
# error Define malloc size macro for this platform.
# endif
namespace snmalloc::external_alloc
{
inline void* aligned_alloc(size_t alignment, size_t size)
{
void* result;
if (posix_memalign(&result, alignment, size) != 0)
{
result = nullptr;
}
return result;
}
using ::free;
}
# endif
#endif