// vim:fileencoding=utf-8:foldmethod=marker

#include "../../../common/aliases/aliases.h"
#include "../../../common/platform/platform.h"

#ifdef WP_PLATFORM_POSIX

#include "mem_os_posix.h"
#include "../mem_os_ops.h"
#include <sys/mman.h>

wp_intern const i32 access_types[] = {
	[WP_MEM_ACCESS_NONE]            = PROT_NONE,
	[WP_MEM_ACCESS_READ_ONLY]       = PROT_READ,
	[WP_MEM_ACCESS_EXEC_ONLY]       = PROT_EXEC,
	[WP_MEM_ACCESS_READ_WRITE]      = PROT_READ | PROT_WRITE,
	[WP_MEM_ACCESS_READ_EXEC]       = PROT_READ | PROT_EXEC,
	[WP_MEM_ACCESS_READ_WRITE_EXEC] = PROT_READ | PROT_WRITE | PROT_EXEC,
};

void *_osMemAllocate(void *addr, u64 size, WpMemAccess access, WpMemAllocFlags flags, WpMemInitType type) {
	(void)type;
	i32 alloc_flags = flags | MAP_ANON | MAP_PRIVATE;

#if defined(WP_PLATFORM_LINUX) || defined(WP_PLATFORM_GNU) || defined(WP_PLATFORM_NET_BSD)
	alloc_flags |= MAP_NORESERVE;
#endif

	return mmap(addr, size, access_types[access], alloc_flags, -1, 0);
}

void _osMemFree(void *ptr, u64 size) {
	munmap(ptr, size);
}

#endif // !WP_PLATFORM_POSIX
