Compare commits

...

10 Commits

Author SHA1 Message Date
Nils O. Selåsdal 66dfd956da Fix 64 bit variants. Note undefined behavior 2026-05-20 20:33:10 +02:00
Nils O. Selåsdal c7d175d90f Remove scons support 2026-05-20 20:07:43 +02:00
Nils O. Selåsdal fb0efd9cbb Fix nextpow2 , provide optimized and 64 bit variants 2026-05-20 20:05:49 +02:00
Nils O. Selåsdal 735c5cb77e Moved allocators to lilalloc repo 2026-05-11 22:41:49 +02:00
Nils O. Selåsdal d58e24f6a9 Minor cleanup 2026-04-21 23:01:22 +02:00
Nils O. Selåsdal d1a45cf8e0 Comments 2026-04-21 22:53:48 +02:00
Nils O. Selåsdal 36457f775f Improve sarena.h 2026-04-21 13:20:07 +02:00
Nils O. Selåsdal afc3148de3 Update slot_allocator 2026-04-21 13:10:03 +02:00
Nils O. Selåsdal a695653e27 Better name 2026-04-21 01:19:07 +02:00
Nils O. Selåsdal a4cae42114 small_allocator improvements
Remove unnneded align_up. last_alloc could point to the middle
of a merged block. Fix by resetting the last_alloc on free
2026-04-21 01:00:49 +02:00
10 changed files with 52 additions and 938 deletions
-177
View File
@@ -1,177 +0,0 @@
import os
import platform
#version info of the library, we use 5 chars from the git hash
revision = os.popen('git describe --abbrev=5 --dirty --always').read()[:-1]
version_info = {
'version_major': 1 ,
'version_minor': 0 ,
'version_patch': 0 ,
'version_revision': revision,
#version_abi is the abi version of the shared library. Only bump it when
#backwards compatibility breaks. Strive to not break the ABI.
'version_abi': '1.0.0'
}
version_info['version_str'] = "%d.%d.%d.%s" % (
version_info['version_major'],
version_info['version_minor'],
version_info['version_patch'],
version_info['version_revision'])
AddOption('--build_type',
dest = 'build_type',
type = 'choice',
nargs = 1,
action='store',
default='debug',
metavar='TYPE',
choices = ['debug', 'release'],
help = 'debug|release - Build a Debug (default) or Release variant'
)
AddOption('--prefix',
dest='prefix',
type='string',
nargs=1,
action='store',
metavar='DIR',
default='/usr',
help='installation prefix'
)
AddOption('--test_xml',
dest='test_xml',
action='store_true',
help='Create a result.xml when running the testsuite'
)
AddOption('--coverage',
dest='coverage',
action='store_true',
help='Build with coverage (gcov) support'
)
AddOption('--without-assertions',
dest='assertions',
action='store_false',
default=True,
help='Build without assertions enabled'
)
AddOption('--stack-protection',
dest = 'stack_protection',
action='store_true',
default=False,
help = 'Build with stack protection support'
)
AddOption('--sanitizer',
dest = 'sanitizer',
action='store_true',
default=False,
help = 'Build with gcc sanitizer'
)
AddOption('--32',
dest='force32bit',
action='store_true',
default=False,
help='Force building for 32 bit architecture'
)
build_type = GetOption('build_type')
assertions = GetOption('assertions')
stack_protection = GetOption('stack_protection')
test_xml = GetOption('test_xml')
prefix = GetOption('prefix')
lib_suffix = ''
if not (build_type in ['debug', 'release']):
print("Error: expected 'debug' or 'release', found: " + build_type)
Exit(1)
def InstallPerm(env, dest, files, perm):
obj = env.Install(dest, files)
for i in obj:
env.AddPostAction(i, Chmod(str(i), perm))
return obj
env = Environment(tools = ['default', 'textfile', 'packaging'])
#allow shell environment to override compiler
if os.environ.get('CC'):
env['CC'] = os.environ['CC']
env.AddMethod(InstallPerm)
env.Append(CFLAGS = ['-std=gnu99','-Wall', '-Wextra', '-Wundef', '-Wcast-qual','-Wshadow' ,'-Wcast-align','-pipe', '-ggdb', '-pthread'])
env.Append(CFLAGS = ['-Wno-unused-parameter', '-Werror=implicit-function-declaration', '-Winit-self'])
env.Append(LINKFLAGS = ['-O2', '-pthread'])
env.Append(CPPDEFINES = ['_FILE_OFFSET_BITS=64'])
env.Append(CPPPATH = ['#include'])
env.Append(SHLIBVERSION = version_info['version_abi'])
if GetOption('force32bit'):
env.Append(CFLAGS = ['-m32'])
env.Append(LINKFLAGS = ['-m32'])
if build_type == 'release':
env.Append(CFLAGS = ['-O2'])
elif build_type == 'debug':
lib_suffix = 'D'
env.Append(CPPDEFINES = ['DEBUG'])
if stack_protection:
env.Append(CFLAGS = ['-fstack-protector', '--param=ssp-buffer-size=4'])
env.Append(CPPDEFINES = ['_FORTIFY_SOURCE=2'])
if not assertions:
#this will turn off assert()
env.Append(CPPDEFINES = ['NDEBUG'])
if GetOption('coverage'):
env.Append(CFLAGS = ['--coverage'])
env.Append(LINKFLAGS = ['--coverage'])
if GetOption('sanitizer'):
env.Append(CFLAGS = ['-fsanitize=undefined', '-fsanitize=address'])
env.Append(LINKFLAGS = ['-fsanitize=undefined', '-fsanitize=address'])
# Generate substitute dictionary
subst_info = dict(('@' + key + '@', version_info[key]) for key in version_info)
subst_info['@prefix@'] = prefix
subst_info['@build_type@'] = build_type
if assertions:
subst_info['@build_type@'] += '_A'
if stack_protection:
subst_info['@build_type@'] += '_SP'
subst_info['@build_host@'] = platform.node()
Export('env', 'build_type', 'prefix', 'lib_suffix', 'version_info', 'test_xml', 'subst_info')
#put all .sconsign files in one place
env.SConsignFile()
subdirs = [
'src',
'include',
'test',
]
for subdir in subdirs:
env.SConscript(subdir + '/SConscript', variant_dir='#build/' + subdir, src_dir='#'+subdir, duplicate=0)
env.Package(target = 'libucore-' + version_info['version_str'] + '.tar.gz',
source = env.FindInstalledFiles(),
NAME = 'libucore',
VERSION = version_info['version_str'],
PACKAGEVERSION = 0,
PACKAGETYPE = 'targz',
LICENSE = 'BSD',
SUMMARY = 'libucore is a C library of misc useful stuff including an eventloop, timer support and various data-structures.',
DESCRIPTION = 'libucore is a C library of misc useful stuff including an eventloop, timer support and various data-structures.',
X_RPM_GROUP = 'Development/Libraries'
)
-13
View File
@@ -1,13 +0,0 @@
import os
Import('env', 'build_type', 'prefix', 'version_info')
ucore_env = env.Clone()
headers = ucore_env.Glob('ucore/*.h')
#install targets
ucore_env.Alias('install',
ucore_env.InstallPerm(os.path.join(prefix, 'include', 'ucore'), headers, 0o0644))
+52 -1
View File
@@ -19,9 +19,40 @@ uc_phi_32(uint32_t N);
uint64_t uint64_t
uc_phi_64(uint64_t N); uc_phi_64(uint64_t N);
#if defined(__has_builtin)
# if __has_builtin(__builtin_clzll)
# define HAVE_BUILTIN_CLZ 1
# endif
#endif
// Note: the nextpow2 functions have undefined behavior if
// x > 2^(n-1) for n of the 32 or 64 bit variants
#if HAVE_BUILTIN_CLZ
static inline uint32_t static inline uint32_t
uc_nextpow2(uint32_t x) uc_nextpow2(uint32_t x)
{ {
if (x <= 1) return 1;
return 1u << (32 - __builtin_clz(x - 1));
return x;
}
static inline uint64_t
uc_nextpow2_64(uint64_t x)
{
if (x <= 1) return 1;
return (uint64_t)1 << (64 - __builtin_clzll(x - 1));
return x;
}
#else
static inline uint32_t
uc_nextpow2(uint32_t x)
{
if (x == 0) {
return 1;
}
x--; x--;
x |= x >> 1; x |= x >> 1;
x |= x >> 2; x |= x >> 2;
@@ -29,10 +60,30 @@ uc_nextpow2(uint32_t x)
x |= x >> 8; x |= x >> 8;
x |= x >> 16; x |= x >> 16;
x++; x++;
return x; return x;
} }
static inline uint64_t
uc_nextpow2_64(uint64_t x)
{
if (x == 0) {
return 1;
}
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
x++;
return x;
}
#endif
#undef HAVE_BUILTIN_CLZ
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
-177
View File
@@ -1,177 +0,0 @@
#ifndef UC_SARENA_H_
#define UC_SARENA_H_
#include <stddef.h>
#include <stdint.h>
#include <assert.h>
/** @file
* Static arena allocator.
*
* An UCSArena allocates memory from a provided buffer.
*
* The backing buffer should be suitable aligned to the types
* that will be allocated from it. Use .e.g
* @code
* _Alignas(16) char mem[1024];
* @endcode
* as the backing buffer.
*
* Once allocated, a piece of memory obtained from the
* allocator cannot be free'd individually, only the entire SArena can
* be free'd/reset
*/
typedef struct UCSArena UCSArena;
struct UCSArena {
unsigned char *start; // start of user buffer
unsigned char *curr; // next alloc point
unsigned char *end; // one past end of user buffer
int tmp_allocs; // no of uc_sar_tmp_begin calls
};
typedef struct UCSTmpAlloc UCSTmpAlloc;
struct UCSTmpAlloc {
unsigned char *alloc_point;
UCSArena *arena;
};
/** Initialize a UCSArena with predefined backing array.
*
* @data must be an array type
* Use as
* @code
* _Alignas(16) char v[128];
* UCSArena a = UC_BV_STATIC_INITIALIZER(v);
* @endcode
*/
#define UC_SAR_STATIC_INITIALIZER(data) UC_SAR_INITIALIZER((data), sizeof(data))
/** Initializer for UCSArena with predefined memory
* Use as
* @code
* char v[128];
* UCSArena a = UC_BV_STATIC_INITIALIZER(v, sizeof v);
* @endcode
* or
* @code
* char *m = malloc(128);
* UCSArena a = UC_BV_INIT(m, 128);
* @endcode
*/
#define UC_SAR_INITIALIZER(data, sz) {(data), (data), (data) + sz}
/** Initialize a UCSArena with an array as the backing memory to allocate from.
* The macro can be used at local scope to allocate memory automatic on the stack,
* or at global scope where the backing array will have static storage duration
*
* Use as:
* @code
* UC_SAR_ALLOC_DEF(my_allocator, 1024)
* struct foo *foo = uc_sar_alloc(&my_allocator);
* if (foo == NULL) {
* // out of memory
* }
* @endcode
*
* @note, the backing buffer has alignment of 16. Use manual init if a different alignment
* is needed.
* @param var_name Variable name for the allocator
* @param size_ byte size of the backing array
*/
#define UC_SAR_ALLOC_DEF(var_name, size_) \
struct { \
_Alignas(16) char memory[size_]; \
} var_name##_arena_memory; \
UCSArena var_name = UC_SAR_STATIC_INITIALIZER(var_name##_arena_memory.memory)
/** Allocate space for @type_ , returned memory is aligned to requirements
* of @type.
*
* Use as:
* @code
* UC_SAR_ALLOC_DEF(my_allocator, 1024)
* struct foo *foo = UC_SAR_ALLOC_ALIGNED(&my_allocator, struct foo);
* // Array types can be used too:
* struct Foo *str = UC_SAR_ALLOC_ALIGNED(&my_allocator, struct Foo[32]);
* @endcode
*/
#define UC_SAR_ALLOC_ALIGNED(allocator, type_) uc_sar_alloc_aligned((allocator), sizeof(type_), _Alignof(type_))
// Initialize an UCSArena to allocate from @mem which is @sz bytes
static inline void uc_sar_init(UCSArena *arena, void *memory, size_t sz)
{
arena->start = arena->curr = (unsigned char *)memory;
arena->end = arena->start + sz;
}
// begin temporary allocation. All allocations afterwards will be released in uc_sar_tmp_end
static inline UCSTmpAlloc uc_sar_tmp_begin(UCSArena *arena)
{
UCSTmpAlloc state = {.alloc_point = arena->curr, .arena = arena};
arena->tmp_allocs++;
return state;
}
// end temporary allocations, releaseing all allocations since the most recent uc_sar_tmp_begin
static inline void uc_sar_tmp_end(const UCSTmpAlloc *state)
{
UCSArena *arena = state->arena;
assert(arena->tmp_allocs > 0);
arena->curr = state->alloc_point;
arena->tmp_allocs--;
}
// Allocate @sz bytes from the UCSArena. Returns NULL if not enough space
void *uc_sar_alloc(UCSArena *arena, size_t sz)
{
if (arena->curr + sz > arena->end) {
return NULL;
}
void *start = arena->curr;
arena->curr += sz;
return start;
}
// Allocate @sz bytes from the UCSArena, returned pointer is aligned to @align
// Returns NULL if not enough space
void *uc_sar_alloc_aligned(UCSArena *arena, size_t sz, unsigned int align) [[gnu::alloc_align(3)]]
{
assert(align != 0);
assert((align & (align - 1)) == 0); // power of 2
uintptr_t curr = (uintptr_t)arena->curr;
uintptr_t aligned = (curr + (align - (uintptr_t)1)) & ~(align - (uintptr_t)1);
unsigned char *start = (unsigned char *)aligned;
if (start + sz > arena->end) {
return NULL;
}
arena->curr = start + sz;
return start;
}
static inline void uc_sar_reset(UCSArena *arena)
{
arena->curr = arena->start;
}
// Arena size in bytes
static inline size_t uc_sar_size(const UCSArena *arena)
{
return (size_t)(arena->end - arena->start);
}
// Used bytes of the arena
static inline size_t uc_sar_used(const UCSArena *arena)
{
return (size_t)(arena->curr - arena->start);
}
// Available unused bytes in the arena
static inline size_t uc_sar_available(const UCSArena *arena)
{
return uc_sar_size(arena) - uc_sar_used(arena);
}
#endif
-79
View File
@@ -1,79 +0,0 @@
#ifndef UC_SLOT_ALLOCATOR_H_
#define UC_SLOT_ALLOCATOR_H_
#include <stddef.h>
#include <stdint.h>
#include <assert.h>
// Repurpose free memory to eep a linked list of free slots
typedef struct UCSlot UCSlot;
struct UCSlot {
UCSlot *next;
};
typedef struct UCSlotArena UCSlotArena;
struct UCSlotArena {
UCSlot *free_list;
uint8_t *memory_start;
size_t memory_len;
size_t n_slots;
size_t slot_size;
};
/**
* Initialize a memory arena for dynamically allocating slots of memory.
* Each allocation returns memory slots of the same size
* Note: For max speed, align @memory and @slot_size to the size of a pointer
*
* @param arena arena to initialize
* @param memory start of the backing memory
* @param memory_len length of @memory
* @param slot_size size of each slot allocation
*/
static inline void uc_slot_arena_init(UCSlotArena *arena, void *memory, size_t memory_len, size_t slot_size)
{
// Optionally - align to a pointer
//slot_size = (slot_size + _Alignof(UCSlot) - 1) & (~(_Alignof(UCSlot) - 1));
assert(slot_size >= sizeof(UCSlot));
size_t n_slots = memory_len / slot_size;
arena->free_list = NULL;
uint8_t *start = (uint8_t *)memory;
// build free_list in ascending order, anticipating sequential allocation
// and sequential access as the common case
for (size_t slot = n_slots; slot > 0; slot--) {
size_t index = slot - 1;
UCSlot *free_slot = (UCSlot *)(start + index * slot_size);
free_slot->next = arena->free_list;
arena->free_list = free_slot;
}
arena->n_slots = n_slots;
arena->memory_start = (uint8_t*)memory;
arena->memory_len = memory_len;
arena->slot_size = slot_size;
}
static inline void *uc_slot_alloc(UCSlotArena *arena)
{
UCSlot *slot = arena->free_list;
if (slot != NULL) {
arena->free_list = slot->next;
}
return slot;
}
static inline void uc_slot_free(UCSlotArena *arena, void *mem)
{
if (mem != NULL) {
assert((uint8_t *)mem >= arena->memory_start);
assert((uint8_t *)mem < arena->memory_start + arena->memory_len);
UCSlot *slot = (UCSlot *)mem;
slot->next = arena->free_list;
arena->free_list = slot;
}
}
#endif
-62
View File
@@ -1,62 +0,0 @@
#ifndef UC_SPOOL_H_
#define UC_SPOOL_H_
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef union UCPoolBlock UCPoolBlock;
union UCPoolBlock {
UCPoolBlock *next; // next free block (when not allocated)
unsigned char data[0]; // data when allocated
};
/** @file
* Static pool allocator.
*
* An UCPool allocates fixed size memory chunks from a provided buffer,
* and memory allocations can be free'd in any order.
*
* The backing array should be suitable aligned to the types
* that will be allocated from it. Use .e.g
* @code
* _Alignas(16) char mem[1024];
* @endcode
* as the backing buffer.
*
*/
typedef struct UCPool UCPool;
struct UCPool {
UCPoolBlock *free_list; // free list
size_t block_size; // aligned size of each block
size_t capacity; // number of blocks
size_t align; // alignment
UCPoolBlock *start; // start of user buffer
UCPoolBlock *end; // one past end of user buffer
};
/** Initialize the pool.
*
* Block size will be rounded up by alignment, or to size of a pointer
*
* @param buffer backing buffer for the pool
* @param buffer_size size of @buffer
* @param block_size size of each allocation.
* @param alignment alignment of each block (must be power of 2)
*/
void uc_pool_init(UCPool *pool, void *buffer, size_t buffer_size, size_t block_size, size_t alignment);
// Allocate a block from the pool. Returns NULL if no more space
[[gnu::assume_aligned(_Alignof(UCPoolBlock))]]
void *uc_pool_alloc(UCPool *pool);
// Free @p . Returns memory to the pool
void uc_pool_free(UCPool *pool, void *p);
void uc_pool_reset(UCPool *pool);
#ifdef __cplusplus
}
#endif
#endif
-25
View File
@@ -1,25 +0,0 @@
import os
Import('env', 'build_type', 'prefix', 'lib_suffix', 'subst_info')
ucore_env = env.Clone()
ucore_env.Substfile('version.c.in', SUBST_DICT = subst_info)
sources = ucore_env.Glob('*.c')
#print 'ucore_env', dir(ucore_env)
#print ucore_env.Dump()
#print 'sources:', sources[len(sources)-2]
#Build library
ucore_staticlib = ucore_env.StaticLibrary(target='ucore' + lib_suffix , source=sources)
ucore_sharedlib = ucore_env.SharedLibrary(target='ucore' + lib_suffix , source=sources)
#install targets
ucore_env.Alias('install',
ucore_env.Install(os.path.join(prefix, 'lib'), [ucore_staticlib]))
ucore_env.Alias('install',
ucore_env.InstallVersionedLib(os.path.join(prefix, 'lib'), [ucore_sharedlib]))
ucore_env.Default([ucore_staticlib, ucore_sharedlib])
-244
View File
@@ -1,244 +0,0 @@
#include <stdint.h>
#include <stddef.h>
#include <stdint.h>
#include <stddef.h>
#include <assert.h>
/**
* General purpose allocator.
* - Allocated pointers are aligned to 16 bytes.
* - Backing buffer must be aligned to 16 bytes start
* - 4Gb - 16 is max for the allocator backing buffer.
* - Allocation of > 0 bytes returns a size aligned up to 16 bytes
* - Allocation of 0 bytes returns a valid pointer with 0 usable space
* The allocator maintains a doubly linked list of blocks,
* when blocks are free'd, adjacent blocks are merged to keep
* fragmentation to a minimum
*/
typedef struct BlockHeader {
uint32_t next; // offset from base
uint32_t prev; // offset from base
uint32_t size_and_flags; // size | free_bit
// Padding to ensure we always return 16 byte aligned pointers.
uint8_t pad[4];
} BlockHeader;
#define ALIGNMENT sizeof(BlockHeader)
#define ALIGN_UP(n) (((n) + (ALIGNMENT - 1)) & ~(ALIGNMENT - 1))
#define ALIGN_DOWN(n) ((n) & ~(ALIGNMENT - 1))
#define NULL_BLOCK (0xffffffff)
#define BLOCK_FREE ((uint32_t)1)
_Static_assert(ALIGNMENT == 16, "sizeof(BlockHeader) is not 16");
typedef struct {
uint8_t* base; // backing store
uint32_t size; // total size
BlockHeader* heap_start; // first block
BlockHeader* last_alloc; // next-fit pointer
} SmallAllocator;
/* --- Header helpers --- */
static inline uint32_t block_size(const BlockHeader* b)
{
return b->size_and_flags & ~BLOCK_FREE;
}
static inline int block_is_free(const BlockHeader* b)
{
return (b->size_and_flags & BLOCK_FREE) != 0;
}
static inline void block_set_free(BlockHeader* b)
{
b->size_and_flags |= BLOCK_FREE;
}
static inline void block_set_used(BlockHeader* b)
{
b->size_and_flags &= ~BLOCK_FREE;
}
static inline void block_set_size(BlockHeader* b, uint32_t size)
{
uint32_t flags = b->size_and_flags & BLOCK_FREE;
b->size_and_flags = size | flags;
}
static inline BlockHeader* block_from_offset(const SmallAllocator* a, uint32_t off)
{
if (off == NULL_BLOCK) {
return NULL;
}
return (BlockHeader*)((uintptr_t)a->base + off);
}
static inline uint32_t bh_offset(SmallAllocator* a, BlockHeader* bh)
{
if (bh == NULL) {
return NULL_BLOCK;
}
return (uint32_t)((uintptr_t)bh - (uintptr_t)a->base);
}
void small_allocator_init(SmallAllocator* a, void* backing_store, uint32_t size)
{
// backing store must be aligned, otherwise all alignment guarantees are lies
assert(((uintptr_t)backing_store & (ALIGNMENT - 1)) == 0);
assert(size >= sizeof(BlockHeader));
assert(size < 0xfffffff0);
a->base = backing_store;
a->size = size;
BlockHeader* first = backing_store;
uint32_t usable = ALIGN_DOWN(size - sizeof(BlockHeader));
block_set_free(first);
block_set_size(first, usable);
first->next = NULL_BLOCK;
first->prev = NULL_BLOCK;
a->heap_start = first;
a->last_alloc = first;
}
static void maybe_split_block(SmallAllocator* a, BlockHeader* block, uint32_t size)
{
// assumes size is already aligned
uint32_t bsize = block_size(block);
if (bsize < size + sizeof(BlockHeader) + ALIGNMENT) return;
uint8_t* base = (uint8_t*)block;
BlockHeader* new_block = (BlockHeader*)(base + sizeof(BlockHeader) + size);
uint32_t new_size = ALIGN_UP(bsize - size - sizeof(BlockHeader));
block_set_size(block, size);
block_set_used(block);
new_block->size_and_flags = new_size | BLOCK_FREE;
new_block->next = block->next;
new_block->prev = bh_offset(a, block);
BlockHeader* next = block_from_offset(a, new_block->next);
if (next) {
next->prev = bh_offset(a, new_block);
}
block->next = bh_offset(a, new_block);
}
static void merge_with_next(SmallAllocator* a, BlockHeader* block)
{
BlockHeader* next = block_from_offset(a, block->next);
if (next == NULL || !block_is_free(next)) return;
uint32_t new_size = ALIGN_UP(block_size(block) + sizeof(BlockHeader) + block_size(next));
block_set_size(block, new_size);
block->next = next->next;
BlockHeader* nextnext = block_from_offset(a, next->next);
if (nextnext) nextnext->prev = bh_offset(a, block);
}
void* small_alloc(SmallAllocator* a, uint32_t size)
{
size = ALIGN_UP(size);
BlockHeader* start = a->last_alloc ? a->last_alloc : a->heap_start;
BlockHeader* curr = start;
do {
if (block_is_free(curr) && block_size(curr) >= size) {
maybe_split_block(a, curr, size);
block_set_used(curr);
a->last_alloc = curr;
return (uint8_t*)curr + sizeof(BlockHeader);
}
curr = block_from_offset(a, curr->next) ? block_from_offset(a, curr->next) : a->heap_start;
} while (curr != start);
return NULL;
}
/* Free */
void small_free(SmallAllocator* a, void* ptr)
{
if (!ptr) {
return;
}
BlockHeader* block = (BlockHeader*)((uint8_t*)ptr - sizeof(BlockHeader));
assert((uint8_t*)ptr >= a->base && (uint8_t*)ptr < a->base + a->size);
// double free detection
assert(!block_is_free(block));
block_set_free(block);
merge_with_next(a, block);
BlockHeader* prev = block_from_offset(a, block->prev);
if (prev != NULL && block_is_free(prev)) {
merge_with_next(a, prev);
if (a->last_alloc == block) {
a->last_alloc = prev;
}
}
}
#if 0
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void debug_alloc(const SmallAllocator* a)
{
puts("--debug start--");
for (BlockHeader* b = a->heap_start; b; b = block_from_offset(a, b->next)) {
printf("Block size %u free %d prev %u next %u \n", block_size(b), block_is_free(b), b->prev, b->next);
}
puts("--debug end--");
}
[[gnu::aligned(16)]] char buff[1023 * 1023];
int main(void)
{
printf("bh size %zu\n", sizeof(BlockHeader));
#define SZ 64
SmallAllocator a;
char* ptrs[SZ];
small_allocator_init(&a, buff, sizeof buff);
debug_alloc(&a);
ptrs[0] = small_alloc(&a, 32);
ptrs[1] = small_alloc(&a, 80);
ptrs[2] = small_alloc(&a, 32);
small_free(&a, ptrs[1]);
ptrs[3] = small_alloc(&a, 12);
ptrs[4] = small_alloc(&a, 12);
debug_alloc(&a);
small_free(&a, ptrs[0]);
small_free(&a, ptrs[2]);
small_free(&a, ptrs[3]);
small_free(&a, ptrs[4]);
for (int i = 0; i < SZ; i++) {
ptrs[i] = small_alloc(&a, rand() % 256 + 1);
}
for (int i = 0; i < SZ; i++) {
// if (rand() % 2 == 0) {
small_free(&a, ptrs[i]);
// }
}
debug_alloc(&a);
}
#endif
-118
View File
@@ -1,118 +0,0 @@
#include <assert.h>
#include "ucore/spool.h"
#include "ucore/utils.h"
#include <string.h>
void uc_pool_init(UCPool *pool, void *buffer, size_t buffer_size, size_t block_size, size_t align)
{
assert(align > 0);
assert((align & (align - 1)) == 0); // power of 2
// enforce minimum for storing free list pointers
if (align < _Alignof(UCPoolBlock)) {
align = _Alignof(UCPoolBlock);
}
if (block_size < sizeof(UCPoolBlock)) {
block_size = sizeof(UCPoolBlock);
}
// ensure initial alignment
size_t stride = UC_ALIGN(block_size, align);
// align first usable block
uintptr_t start_addr = (uintptr_t)buffer;
uintptr_t first_addr = UC_ALIGN(start_addr, align);
size_t padding = first_addr - start_addr;
if (padding + stride > buffer_size) {
pool->capacity = 0;
pool->free_list = NULL;
} else {
size_t usable = buffer_size - padding;
pool->capacity = usable / stride;
// build intrusive free list
UCPoolBlock *p = (UCPoolBlock*)first_addr;
for (size_t i = 0; i < pool->capacity - 1; ++i) {
void *punt = __builtin_assume_aligned(&p->data[0] + pool->block_size, _Alignof(UCPoolBlock));
UCPoolBlock *next = punt;
p->next = next;
p = next;
}
((UCPoolBlock *)p)->next = NULL; // last element
pool->free_list = (UCPoolBlock *)first_addr;
}
pool->block_size = stride;
pool->align = align;
pool->start = buffer;
pool->end = buffer + buffer_size;
}
void *uc_pool_alloc(UCPool *pool)
{
if (!pool->free_list) {
return NULL;
}
UCPoolBlock *block = pool->free_list;
pool->free_list = block->next;
#ifdef DEBUG
memset(block, 0xCB, pool->block_size);
#endif
return block->data;
}
#include <stdio.h>
void uc_pool_free(UCPool *pool, void *p)
{
if (p == NULL) {
return;
}
UCPoolBlock *block = p;
#ifdef DEBUG
assert(block >= pool->start && block < pool->end);
assert(((uintptr_t)p - (uintptr_t)pool->start) % pool->block_size == 0);
// double-free detection
for (UCPoolBlock *f = pool->free_list; f; f = f->next) {
if (f == p) {
assert(0 && "Double free detected in pool!");
return;
}
}
memset(p, 0xDD, pool->block_size);
#endif
// When not in use, store pointer to next free element inline in the block
block->next = pool->free_list;
pool->free_list = p;
}
void uc_pool_reset(UCPool *pool)
{
if (pool->capacity == 0)
return;
uintptr_t start_addr = (uintptr_t)pool->start;
uintptr_t first_addr = UC_ALIGN(start_addr, pool->align);
// build intrusive free list
UCPoolBlock *p = (UCPoolBlock*)first_addr;
for (size_t i = 0; i < pool->capacity - 1; ++i) {
void *punt = __builtin_assume_aligned(&p->data[0] + pool->block_size, _Alignof(UCPoolBlock));
UCPoolBlock *next = punt;
p->next = next;
p = next;
}
p->next = NULL; // last element
pool->free_list = (UCPoolBlock *)first_addr;
}
-42
View File
@@ -1,42 +0,0 @@
import platform
Import('env', 'build_type', 'prefix', 'lib_suffix', 'version_info', 'test_xml')
test_env = env.Clone()
test_env.Append(LIBPATH = ['#build/src']);
test_env.Append(LIBS = ['ucore' + lib_suffix, 'check','m'])
system = platform.system()
#NetBSD needs /usr/pkg/...
if 'netbsd' in system.lower():
test_env.Append(LIBPATH = ['/usr/pkg/lib'])
test_env.Append(LINKFLAGS = ['-Wl,-rpath,/usr/pkg/lib'])
test_env.Append(CPPPATH = ['/usr/pkg/include'])
if 'darwin' in system.lower():
test_env.Append(LIBPATH = ['/opt/homebrew/lib'])
test_env.Append(LINKFLAGS = ['-Wl,-rpath,/opt/homebrew/lib'])
test_env.Append(CPPPATH = ['/opt/homebrew/include'])
if 'darwin' not in system.lower():
test_env.Append(LIBS = ['rt'])
tests = test_env.Glob('test_*.c')
test_executable = 'test_runner'
#run test_runner --xml to produce an xml result file
if test_xml:
test_executable += ' -x'
#rpath to shared lib, so test_runner can actually be executed
test_env.Append(LINKFLAGS = ['-Wl,-rpath,\\$$ORIGIN/../src'])
prog = test_env.Program('test_runner', tests)
cmd = test_env.Command(target='test_phony' ,
source = None,
action= test_env.Dir('.').abspath + '/' + test_executable)
test_env.Depends(cmd, prog)
test_env.AlwaysBuild(cmd)
test_env.Default(test_executable)