From: Eric Biggers Date: Thu, 12 Jun 2014 04:15:40 +0000 (-0500) Subject: Add aligned malloc and free X-Git-Tag: v1.7.0~41 X-Git-Url: https://wimlib.net/git/?p=wimlib;a=commitdiff_plain;h=e3a7c6c725964662f4ad1fcfe21d2da742499b8a Add aligned malloc and free Don't make dependent on OS support, since that would break the custom memory allocation functions and also would need to be different between UNIX and Windows anyway. --- diff --git a/include/wimlib/util.h b/include/wimlib/util.h index 869388fe..91bed5a4 100644 --- a/include/wimlib/util.h +++ b/include/wimlib/util.h @@ -72,12 +72,20 @@ wimlib_wcsdup(const wchar_t *str) _malloc_attribute; extern char * wimlib_strdup(const char *str) _malloc_attribute; +extern void * +wimlib_aligned_malloc(size_t size, size_t alignment) _malloc_attribute; + +extern void +wimlib_aligned_free(void *ptr); + #define MALLOC wimlib_malloc #define FREE wimlib_free_memory #define REALLOC wimlib_realloc #define CALLOC wimlib_calloc #define STRDUP wimlib_strdup #define WCSDUP wimlib_wcsdup +#define ALIGNED_MALLOC wimlib_aligned_malloc +#define ALIGNED_FREE wimlib_aligned_free extern void * memdup(const void *mem, size_t size) _malloc_attribute; diff --git a/src/util.c b/src/util.c index fceae14b..54e29444 100644 --- a/src/util.c +++ b/src/util.c @@ -37,6 +37,7 @@ #endif #include "wimlib.h" +#include "wimlib/assert.h" #include "wimlib/compiler.h" #include "wimlib/encoding.h" #include "wimlib/error.h" @@ -432,6 +433,36 @@ wimlib_wcsdup(const wchar_t *str) } #endif +void * +wimlib_aligned_malloc(size_t size, size_t alignment) +{ + u8 *raw_ptr; + u8 *ptr; + uintptr_t mask; + + wimlib_assert(alignment != 0 && is_power_of_2(alignment) && + alignment <= 4096); + mask = alignment - 1; + + raw_ptr = MALLOC(size + alignment - 1 + sizeof(size_t)); + if (!raw_ptr) + return NULL; + + ptr = (u8 *)raw_ptr + sizeof(size_t); + while ((uintptr_t)ptr & mask) + ptr++; + *((size_t *)ptr - 1) = (ptr - raw_ptr); + + return ptr; +} + +void +wimlib_aligned_free(void *ptr) +{ + if (ptr) + FREE((u8 *)ptr - *((size_t *)ptr - 1)); +} + void * memdup(const void *mem, size_t size) {