Files
allocators/sources/win32.c
T

135 lines
2.8 KiB
C

#include "malunal/config.h"
#if MALUNAL_PLATFORM_WIN32
#include <stdlib.h>
#include <string.h>
#include <memoryapi.h>
#include "internal.h"
static
malunal_size_t
g_platform_page_size = 0;
malunal_size_t
platform_page_size() {
if (g_platform_page_size != 0)
return g_platform_page_size;
SYSTEM_INFO si;
GetSystemInfo(&si);
g_platform_page_size = si.dwPageSize;
return g_platform_page_size;
}
static
allocation_error_t
win32_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
win32_finalize(impl_mptr_t allocator) {
MALUNAL_UNUSED(allocator);
return ALLOCATION_ERROR_SUCCESS;
}
static
allocation_result_t
win32_acquire(
impl_mptr_t allocator,
malunal_size_t size
) {
MALUNAL_UNUSED(allocator);
const malunal_int32_t memops = MEM_COMMIT | MEM_RESERVE;
const malunal_int32_t pageops = PAGE_READWRITE;
malunal_mptr_t addr = VirtualAlloc(NULL_ADDRESS, size, memops, pageops);
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
win32_release(
impl_mptr_t allocator,
malunal_mptr_t address,
malunal_size_t size
) {
MALUNAL_UNUSED(allocator);
VirtualFree(address, size, MEM_RELEASE);
allocator->allocated -= size;
allocator->reserved -= size;
allocator->releases += 1;
return ALLOCATION_ERROR_SUCCESS;
}
static
allocation_result_t
win32_reacquire(
impl_mptr_t allocator,
malunal_mptr_t address,
malunal_size_t oldsize,
malunal_size_t newsize
) {
allocation_result_t result = win32_acquire(allocator, newsize);
if (result.threw)
return result;
result.address = memcpy(result.address, address, oldsize);
win32_release(allocator, address, oldsize);
return result;
}
static const
virtual_table_t win32_vtable = {
.initialize = (allocator_initialize_pfn_t)&win32_initialize,
.finalize = (allocator_finalize_pfn_t)&win32_finalize,
.acquire = (allocator_acquire_pfn_t)&win32_acquire,
.reacquire = (allocator_reacquire_pfn_t)&win32_reacquire,
.release = (allocator_release_pfn_t)&win32_release
};
allocator_t
win32_allocator() {
implementation_t implementation = {
.vtable = &win32_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;
}
#endif /* MALUNAL_PLATFORM_WIN32 */