Complete memory allocation and deallocation function definitions

This commit is contained in:
Abdelrahman Said 2024-06-02 20:09:36 +01:00
parent 18448dd7c1
commit 9807334ac9

View File

@ -1,8 +1,43 @@
#include "mem_utils.h" #include "mem_utils.h"
#include "aliases.h" #include "aliases.h"
#include "platform.h"
#include <assert.h> #include <assert.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#if defined(WAPP_PLATFORM_WINDOWS)
#include <Windows.h>
#include <memoryapi.h>
internal const i32 access_types[] = {
[WAPP_MEM_ACCESS_NONE] = PAGE_NOACCESS,
[WAPP_MEM_ACCESS_READ_ONLY] = PAGE_READONLY,
[WAPP_MEM_ACCESS_EXEC_ONLY] = PAGE_EXECUTE,
[WAPP_MEM_ACCESS_READ_WRITE] = PAGE_READWRITE,
[WAPP_MEM_ACCESS_READ_EXEC] = PAGE_EXECUTE_READ,
[WAPP_MEM_ACCESS_READ_WRITE_EXEC] = PAGE_EXECUTE_READWRITE,
};
internal inline void *alloc_windows(u64 size, MemAccess access,
MemAllocFlags flags);
#elif defined(WAPP_PLATFORM_POSIX)
#include <sys/mman.h>
internal const i32 access_types[] = {
[WAPP_MEM_ACCESS_NONE] = PROT_NONE,
[WAPP_MEM_ACCESS_READ_ONLY] = PROT_READ,
[WAPP_MEM_ACCESS_EXEC_ONLY] = PROT_EXEC,
[WAPP_MEM_ACCESS_READ_WRITE] = PROT_READ | PROT_WRITE,
[WAPP_MEM_ACCESS_READ_EXEC] = PROT_READ | PROT_EXEC,
[WAPP_MEM_ACCESS_READ_WRITE_EXEC] = PROT_READ | PROT_WRITE | PROT_EXEC,
};
internal inline void *alloc_posix(u64 size, MemAccess access,
MemAllocFlags flags);
#else
#error "Unrecognised platform"
#endif
internal bool is_power_of_two(u64 num) { return (num & (num - 1)) == 0; } internal bool is_power_of_two(u64 num) { return (num & (num - 1)) == 0; }
@ -26,3 +61,48 @@ void *wapp_mem_util_align_forward(void *ptr, u64 alignment) {
return (void *)p; return (void *)p;
} }
void *wapp_mem_util_alloc(u64 size, MemAccess access, MemAllocFlags flags,
MemInitType type) {
#if defined(WAPP_PLATFORM_WINDOWS)
void *output = alloc_windows(size, access, flags);
#elif defined(WAPP_PLATFORM_POSIX)
void *output = alloc_posix(size, access, flags);
#else
return NULL;
#endif
if (type == WAPP_MEM_INIT_INITIALISED) {
memset(output, 0, size);
}
return output;
}
void wapp_mem_util_free(void *ptr, u64 size) {
#if defined(WAPP_PLATFORM_WINDOWS)
VirtualFree(ptr, size, MEM_RELEASE);
#elif defined(WAPP_PLATFORM_POSIX)
munmap(ptr, size);
#endif
}
#ifdef WAPP_PLATFORM_WINDOWS
internal inline void *alloc_windows(u64 size, MemAccess access,
MemAllocFlags flags) {
return VirtualAlloc2(NULL, NULL, (SIZE_T)size, flags, access_types[access]);
}
#endif
#if defined(WAPP_PLATFORM_POSIX)
internal inline void *alloc_posix(u64 size, MemAccess access,
MemAllocFlags flags) {
i32 alloc_flags = flags | MAP_ANON | MAP_PRIVATE;
#ifdef WAPP_PLATFORM_LINUX
alloc_flags |= MAP_NORESERVE;
#endif
return mmap(NULL, size, access_types[access], alloc_flags, -1, 0);
}
#endif