3#include "../platform.h"
4#include "../../error.h"
22 if (opts->
mode == CLOD_REGION_MODE_RDWR) o_flags |= O_RDWR;
23 if (opts->
mode == CLOD_REGION_MODE_RDONLY) o_flags |= O_RDONLY;
24 if (create) o_flags |= O_CREAT;
29 const int fd = openat((
int)(intptr_t)d, name, o_flags, o_mode);
31 if (!create && errno == ENOENT) {
41 if (statx(fd,
"", AT_EMPTY_PATH, STATX_SIZE, &st)) {
46 const size_t size = st.stx_size;
54 const size_t size = (size_t)st.st_size;
58 if (opts->
mode == CLOD_REGION_MODE_RDWR) prot |= PROT_WRITE;
61 map = mmap(
nullptr, size, prot, MAP_SHARED, fd, 0);
62 if (map == MAP_FAILED) {
69 struct file *file_struct = malloc(
sizeof(
struct file));
72 if (size > 0) munmap(map, size);
77 file_struct->map = map;
78 file_struct->size = size;
80 file_struct->writeable = opts->
mode == CLOD_REGION_MODE_RDWR;
81 *f = (uintptr_t)file_struct;
85 *data = ((
struct file *)f)->map;
86 *size = ((
struct file *)f)->size;
90 auto const file_struct = (
struct file *)f;
93 if (ftruncate(file_struct->fd, (off_t)new_size)) {
97 const size_t old_size = file_struct->size;
98 file_struct->size = new_size;
101 if (file_struct->map !=
nullptr && new_size > 0) {
102 assert(old_size > 0);
103 file_struct->map = mremap(file_struct->map, old_size, new_size, MREMAP_MAYMOVE);
104 if (file_struct->map == MAP_FAILED) {
105 file_struct->map =
nullptr;
112 if (file_struct->map !=
nullptr) {
113 assert(old_size > 0);
114 munmap(file_struct->map, old_size);
115 file_struct->map =
nullptr;
118 int mmap_flag = PROT_READ;
119 if (file_struct->writeable) mmap_flag |= PROT_WRITE;
121 file_struct->map = mmap(
nullptr, new_size, mmap_flag, MAP_SHARED, file_struct->fd, 0);
122 if (file_struct->map == MAP_FAILED) {
123 file_struct->map =
nullptr;
130 auto const file_struct = (
struct file *)f;
132 if (file_struct->map && munmap(file_struct->map, file_struct->size)) {
135 if (close(file_struct->fd)) {
@ CLOD_REGION_INVALID_USAGE