add mmap_file
authorJann Horn <jann@thejh.net>
Tue, 18 Jun 2013 17:40:48 +0000 (19:40 +0200)
committerJann Horn <jann@thejh.net>
Tue, 18 Jun 2013 17:40:48 +0000 (19:40 +0200)
io.c

diff --git a/io.c b/io.c
index 1a2ddd6..a7696f9 100644 (file)
--- a/io.c
+++ b/io.c
@@ -9,6 +9,8 @@ HEADER #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <string.h>
+#include <assert.h>
+#include <sys/mman.h>
 
 // Wrapper for `read` that retries on partial reads.
 // If last_res is non-NULL, it will be filled with the
@@ -138,3 +140,19 @@ PUBLIC_FN int write_file(char *path, char *buf, ssize_t len, int open_flags) {
   if (close_res) return 1;
   return 0;
 }
+
+PUBLIC_FN void *mmap_file(void *addr, size_t length, int prot, int flags, char *path, off_t offset) {
+  assert((flags&MAP_ANONYMOUS) == 0);
+  assert(prot&(PROT_EXEC|PROT_READ|PROT_WRITE));
+  int open_flags = O_CLOEXEC;
+  if ((prot & (PROT_READ|PROT_EXEC)) && !(prot&PROT_WRITE)) open_flags |= O_RDONLY;
+  else if ((prot & (PROT_READ|PROT_EXEC))) open_flags |= O_RDWR;
+  else open_flags |= O_WRONLY;
+  int fd = open(path, open_flags);
+  if (fd == -1) return NULL;
+  void *r = mmap(addr, length, prot, flags, fd, offset);
+  int errno_ = errno;
+  close(fd);
+  errno = errno_;
+  return (r==MAP_FAILED) ? NULL : r;
+}