cammy/src/sram.c
XANTRONIX Development a5122fd773 A bit less segfault-y
2016-05-07 19:52:55 -05:00

63 lines
1.3 KiB
C

#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <cammy/sram.h>
static inline size_t _mapped_size(size_t size, size_t page_size) {
return size + (page_size - (size % page_size));
}
cammy_sram *cammy_sram_open(const char *file) {
cammy_sram *sram;
struct stat st;
if ((sram = malloc(sizeof(*sram))) == NULL) {
goto error_malloc_sram;
}
if ((sram->fd = open(file, O_RDWR)) < 0) {
goto error_open;
}
if (fstat(sram->fd, &st) < 0) {
goto error_stat;
}
if (st.st_size < sizeof(cammy_sram_data)) {
errno = EINVAL;
goto error_invalid_file;
}
sram->size = st.st_size;
sram->page_size = (size_t)sysconf(_SC_PAGESIZE);
sram->mapped_size = _mapped_size(st.st_size, sram->page_size);
if ((sram->data = mmap(NULL, sram->mapped_size,
PROT_READ | PROT_WRITE, MAP_SHARED, sram->fd, 0)) == NULL) {
goto error_mmap;
}
return sram;
error_mmap:
error_invalid_file:
error_stat:
close(sram->fd);
error_open:
free(sram);
error_malloc_sram:
return NULL;
}
void cammy_sram_close(cammy_sram *sram) {
munmap(sram->data, sram->mapped_size);
close(sram->fd);
free(sram);
}