Files

73 lines
1.5 KiB
C

#include "malunal/config.h"
#if MALUNAL_PLATFORM_LINUX
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include "malunal/allocator.h"
static
malunal_size_t
g_platform_page_size = 0;
malunal_size_t
platform_page_size() {
return g_platform_page_size == 0
? g_platform_page_size = sysconf(_SC_PAGE_SIZE)
: g_platform_page_size;
}
static
error_t
linux_allocator_acquire(
allocator_mptr_t allocator,
malunal_size_t size,
malunal_mptr_t* out
) {
MALUNAL_UNUSED(allocator);
const malunal_int32_t memops = PROT_READ | PROT_WRITE;
const malunal_int32_t memprms = MAP_PRIVATE | MAP_ANONYMOUS;
malunal_mptr_t ptr = mmap(0, size, memops, memprms, -1, 0);
if (ptr == MAP_FAILED || ptr == null)
return (error_t) {
.domain = &ERROR_DOMAIN_ALLOCATOR_T,
.code = ALLOCATOR_ERROR_OUT_OF_MEMORY
};
*out = ptr;
return NO_ERROR;
}
static
error_t
linux_allocator_dispose(
allocator_mptr_t allocator,
malunal_mptr_t address,
malunal_size_t size
) {
MALUNAL_UNUSED(allocator);
munmap(address, size);
return NO_ERROR;
}
static const
allocator_vtable_t linux_allocator_vtable = {
.acquire = (allocator_acquire_pfn_t)&linux_allocator_acquire,
.dispose = (allocator_dispose_pfn_t)&linux_allocator_dispose
};
static const
allocator_t linux_allocator_instance = {
.vtable = &linux_allocator_vtable
};
allocator_mptr_t
linux_allocator() {
return &linux_allocator_instance;
}
#endif /* MALUNAL_PLATFORM_LINUX */