#include "core.h" #include "platform.h" #include #include #include #include #define IsPageAligned(x) (IsAlignedTo(x, platform_page_size())) U32 platform_page_size(void) { return sysconf(_SC_PAGESIZE); } void *platform_malloc(size_t size) { return malloc(size); } void platform_free(void *mem) { free(mem); } static void *platform_allocator_func(Allocator *allocator, AllocOperation operation , void *memory, U32 size, U32 align) { switch (operation) { case Alloc_Op_Aligned: return aligned_alloc(size, align); case Alloc_Op_Free: // can't free/Free_all from an marena free(memory); return NULL; case Alloc_Op_Free_All: NotImplemented; return NULL; } Assert(false); } Allocator platform_allocator(void) { Allocator allocator = {}; allocator.op_func_ptr = platform_allocator_func; allocator.data = NULL; return allocator; } void *memory_allocate_and_commit(size_t size) { Assert(IsPageAligned(size)); void *mem = mmap(0, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); TRACEF("memory_allocate size=%7zu mem=%p\n", size, mem); if (mem == MAP_FAILED) { mem = NULL; } else { int rc = madvise(mem, size, MADV_POPULATE_WRITE); if (rc != 0) { munmap(mem, size); mem = NULL; } } return mem; } void memory_free(void *mem, size_t size) { TRACEF(" memory_free size=%7zu mem=%p\n", size, mem); Assert(IsPageAligned((uintptr_t)mem)); Assert(IsPageAligned(size)); int rc = munmap(mem, size); Assert(rc == 0); } void *memory_reserve(size_t size) { Assert(IsPageAligned(size)); void *mem = mmap(0, size, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); TRACEF("memory_reserve size=%7zu mem=%p\n", size, mem); if (mem == MAP_FAILED) { mem = NULL; } return mem; } void memory_commit(void *mem, size_t size) { Assert(IsPageAligned((uintptr_t)mem)); Assert(IsPageAligned(size)); TRACEF("memory_commit size=%7zu mem=%p\n", size, mem); int rc; rc = mprotect(mem, size, PROT_READ | PROT_WRITE); Assert(rc == 0); rc = madvise(mem, size, MADV_WILLNEED); Assert(rc == 0); } void memory_decommit(void *mem, size_t size) { TRACEF("memory_decommit size=%7zu mem=%p\n", size, mem); Assert(IsPageAligned((uintptr_t)mem)); Assert(IsPageAligned(size)); int rc; rc = mprotect(mem, size, PROT_NONE); Assert(rc == 0); rc = madvise(mem, size, MADV_DONTNEED); Assert(rc == 0); }