| 1 |
|
| 2 |
|
| 3 |
#include "utils.h" |
| 4 |
|
| 5 |
#include <sys/mman.h> |
| 6 |
#include <sys/stat.h> |
| 7 |
#include <fcntl.h> |
| 8 |
#include <unistd.h> |
| 9 |
|
| 10 |
#include <errno.h> |
| 11 |
#include <limits.h> |
| 12 |
#include <stdbool.h> |
| 13 |
#include <stddef.h> |
| 14 |
#include <stdio.h> |
| 15 |
#include <stdlib.h> |
| 16 |
#include <string.h> |
| 17 |
|
| 18 |
struct mem_range map_file(const char path[], bool rw) |
| 19 |
{ |
| 20 |
struct mem_range range = {0}; |
| 21 |
|
| 22 |
int open_flags = rw ? O_RDWR : O_RDONLY; |
| 23 |
int mmap_flags = rw ? PROT_READ | PROT_WRITE : PROT_READ; |
| 24 |
|
| 25 |
int fd = open(path, open_flags); |
| 26 |
if (fd == -1) { |
| 27 |
fprintf(stderr, "Failed to open(): %s\n", strerror(errno)); |
| 28 |
return range; |
| 29 |
} |
| 30 |
|
| 31 |
struct stat stat_buf; |
| 32 |
if (fstat(fd, &stat_buf) != 0) { |
| 33 |
(void)close(fd); |
| 34 |
fprintf(stderr, "Failed to fstat(): %s\n", strerror(errno)); |
| 35 |
return range; |
| 36 |
} |
| 37 |
|
| 38 |
if (stat_buf.st_size == 0) { |
| 39 |
(void)close(fd); |
| 40 |
fprintf(stderr, "Can't map an empty \"%s\" file\n", path); |
| 41 |
return range; |
| 42 |
} |
| 43 |
|
| 44 |
uint8_t *mem = mmap(NULL, stat_buf.st_size, mmap_flags, |
| 45 |
MAP_SHARED | MAP_POPULATE, fd, 0); |
| 46 |
(void)close(fd); |
| 47 |
if (mem == MAP_FAILED) { |
| 48 |
fprintf(stderr, "Failed to mmap(): %s\n", strerror(errno)); |
| 49 |
return range; |
| 50 |
} |
| 51 |
|
| 52 |
range.start = mem; |
| 53 |
range.length = stat_buf.st_size; |
| 54 |
return range; |
| 55 |
} |
| 56 |
|
| 57 |
void unmap_file(struct mem_range store) |
| 58 |
{ |
| 59 |
if (munmap(store.start, store.length) != 0) |
| 60 |
fprintf(stderr, "Failed to munmap(): %s\n", strerror(errno)); |
| 61 |
} |