cbase 1.46.11
C/C++ Static Template
Loading...
Searching...
No Matches
mem_os.c
Go to the documentation of this file.
1
7
8#include "memory/mem_os.h"
9#include "base/base_macros.h"
10
11#if OS_WINDOWS
12# include <windows.h>
13#elif OS_LINUX || OS_MAC
14# include <sys/mman.h>
15#endif
16
17void *
19{
20#if OS_WINDOWS
21 return VirtualAlloc(0, size, MEM_RESERVE, PAGE_NOACCESS);
22#elif OS_LINUX || OS_MAC
23 void *ptr = mmap(0, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
24 return (ptr == MAP_FAILED) ? 0 : ptr;
25#endif
26}
27
28b32
29os_mem_commit(void *ptr, usize size)
30{
31#if OS_WINDOWS
32 return VirtualAlloc(ptr, size, MEM_COMMIT, PAGE_READWRITE) != 0;
33#elif OS_LINUX || OS_MAC
34 return mprotect(ptr, size, PROT_READ | PROT_WRITE) == 0;
35#endif
36}
37
38void
39os_mem_decommit(void *ptr, usize size)
40{
41#if OS_WINDOWS
42 VirtualFree(ptr, size, MEM_DECOMMIT);
43#elif OS_LINUX || OS_MAC
44 mprotect(ptr, size, PROT_NONE);
45 madvise(ptr, size, MADV_DONTNEED);
46#endif
47}
48
49void
50os_mem_release(void *ptr, usize size)
51{
52#if OS_WINDOWS
53 // Note: Windows requires size to be 0 when using MEM_RELEASE
54 (void)size;
55 VirtualFree(ptr, 0, MEM_RELEASE);
56#elif OS_LINUX || OS_MAC
57 munmap(ptr, size);
58#endif
59}
Context detection, utilities, compiler abstractions, and data structures.
void * os_mem_reserve(usize size)
Reserves a block of virtual address space.
Definition mem_os.c:18
b32 os_mem_commit(void *ptr, usize size)
Commits physical RAM to a previously reserved address range.
Definition mem_os.c:29
void os_mem_decommit(void *ptr, usize size)
Decommits physical RAM, returning it to the OS while keeping the address space.
Definition mem_os.c:39
void os_mem_release(void *ptr, usize size)
Releases a reserved virtual address range entirely back to the OS.
Definition mem_os.c:50
size_t usize
Definition base_types.h:43
int32_t b32
Definition base_types.h:75
Operating System virtual memory wrappers.