#ifndef PROTOTYPE1_SRC_L1_SYSTEM_SHARED_MEMORY_H
#define PROTOTYPE1_SRC_L1_SYSTEM_SHARED_MEMORY_H

#include <fcntl.h>
#include <sys/mman.h>
#include "../core/util.h"
#include <unistd.h>
#include <errno.h>

static int create_shm_file(){
    char name[] = "/prototype1-XXXXXXXXXXXX";
    U64 v = ((U64)rand() << 32) + (U64)rand();
    for (int i = 0; i < 12; i++) {
        name[sizeof(name) - 1 - 12 + i] = 'A' + (v&15) + (v&16)*2;
        v >>= 5;
    }
    int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
    if (fd < 0)
        abortf("shm_open(\"%s\")", name);
    if (shm_unlink(name) < 0)
        abortf("shm_unlink(\"%s\")", name);
    return fd;
}

static int allocate_shm_file(size_t size) {
    int fd = create_shm_file();
    int ret;
    do {
        ret = ftruncate(fd, size);
    } while (ret < 0 && errno == EINTR);
    if (ret < 0) {
        abortf("ftruncate(%ld)", size);
    }
    return fd;
}

#endif