#include #include #include #include #include static inline size_t align(size_t granularity, size_t value) { return value - value % granularity; } void *map_file(const char *file, size_t granularity, size_t *size) { int fd = open(file, O_RDONLY, S_IRUSR); if (-1 == fd) goto open; struct stat stat; if (-1 == fstat(fd, &stat)) goto stat; if (stat.st_size > (size_t)-1) goto size; size_t aligned_size = align(granularity, stat.st_size); void *ptr = mmap(0, aligned_size, PROT_READ, MAP_SHARED, fd, 0); if ((void*)(-1) == ptr) goto mmap; if (-1 == close(fd)) goto fclose; *size = aligned_size; return ptr; fclose: munmap(ptr, aligned_size); mmap: size: stat: close(fd); open: return 0; } void unmap_file(void *addr, size_t bytes) { if (addr) munmap(addr, bytes); }