110 lines
2.2 KiB
C
110 lines
2.2 KiB
C
#include <stdlib.h>
|
|
#include <memory.h>
|
|
#include "internal.h"
|
|
|
|
|
|
static
|
|
allocation_error_t
|
|
libc_initialize(
|
|
impl_mptr_t allocator,
|
|
allocator_mptr_t upstream,
|
|
malunal_size_t capacity
|
|
) {
|
|
MALUNAL_UNUSED(allocator);
|
|
MALUNAL_UNUSED(upstream);
|
|
MALUNAL_UNUSED(capacity);
|
|
return ALLOCATION_ERROR_SUCCESS;
|
|
}
|
|
|
|
static
|
|
allocation_error_t
|
|
libc_finalize(impl_mptr_t allocator) {
|
|
MALUNAL_UNUSED(allocator);
|
|
return ALLOCATION_ERROR_SUCCESS;
|
|
}
|
|
|
|
static
|
|
allocation_result_t
|
|
libc_acquire(
|
|
impl_mptr_t allocator,
|
|
malunal_size_t size
|
|
) {
|
|
malunal_mptr_t addr = malloc(size);
|
|
if (addr == NULL_ADDRESS) {
|
|
return (allocation_result_t) {
|
|
.threw = 1,
|
|
.error = ALLOCATION_ERROR_OUT_OF_MEMORY
|
|
};
|
|
}
|
|
|
|
allocator->allocated += size;
|
|
allocator->reserved += size;
|
|
allocator->acquires += 1;
|
|
return (allocation_result_t) {
|
|
.threw = 0,
|
|
.address = addr
|
|
};
|
|
}
|
|
|
|
static
|
|
allocation_error_t
|
|
libc_release(
|
|
impl_mptr_t allocator,
|
|
malunal_mptr_t address,
|
|
malunal_size_t size
|
|
) {
|
|
free(address);
|
|
|
|
allocator->allocated -= size;
|
|
allocator->reserved -= size;
|
|
allocator->releases += 1;
|
|
return ALLOCATION_ERROR_SUCCESS;
|
|
}
|
|
|
|
static
|
|
allocation_result_t
|
|
libc_reacquire(
|
|
impl_mptr_t allocator,
|
|
malunal_mptr_t address,
|
|
malunal_size_t oldsize,
|
|
malunal_size_t newsize
|
|
) {
|
|
allocation_result_t result = libc_acquire(allocator, newsize);
|
|
if (result.threw)
|
|
return result;
|
|
|
|
result.address = memcpy( result.address, address, oldsize);
|
|
libc_release(allocator, address, oldsize);
|
|
return result;
|
|
}
|
|
|
|
static const
|
|
virtual_table_t libc_vtable = {
|
|
.initialize = (allocator_initialize_pfn_t)&libc_initialize,
|
|
.finalize = (allocator_finalize_pfn_t)&libc_finalize,
|
|
.acquire = (allocator_acquire_pfn_t)&libc_acquire,
|
|
.reacquire = (allocator_reacquire_pfn_t)&libc_reacquire,
|
|
.release = (allocator_release_pfn_t)&libc_release
|
|
};
|
|
|
|
allocator_t
|
|
libc_allocator() {
|
|
implementation_t implementation = {
|
|
.vtable = &libc_vtable,
|
|
.upstream = NULL_ADDRESS,
|
|
.context = NULL_ADDRESS,
|
|
.allocated = 0,
|
|
.reserved = 0,
|
|
.acquires = 0,
|
|
.releases = 0
|
|
};
|
|
|
|
allocator_t result;
|
|
memcpy(
|
|
&result,
|
|
&implementation,
|
|
sizeof(implementation_t)
|
|
);
|
|
return result;
|
|
}
|