aboutsummaryrefslogtreecommitdiff
path: root/src/os/linux/linux_memory.c
blob: 668604ec2dcfd48acc30c0cd571ec5d4ea84360b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <os/os.h>
#include <basic/basic.h>

#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>

b32
os_memory_allocate(OSMemory *memory, size_t size)
{
    // @Performance: Keep the fd of /dev/zero open for the whole runtime?
    int fd = open("/dev/zero", O_RDWR);
    if (fd == -1) {
        printf("open() failed: %s\n", strerror(errno));
        return false;
    }

    void *address = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
    if (address == MAP_FAILED) {
        printf("mmap failed\n");
        return false;
    }

    close(fd);

    memory->size = size;
    memory->p = address;
    return true;
}

void
os_memory_free(OSMemory *memory)
{
    munmap(memory->p, memory->size);
}