]> mj.ucw.cz Git - libucw.git/blobdiff - lib/mmap.c
Merge with git+ssh://cvs.ucw.cz/projects/sherlock/GIT/sherlock.git
[libucw.git] / lib / mmap.c
index 47147310ecf018fec0589168fe47a877d3253d50..aa63622259d50034fce4b774dc600c92dcf1828b 100644 (file)
@@ -1,36 +1,47 @@
 /*
 /*
- *     Sherlock Library -- Mapping of Files
+ *     UCW Library -- Mapping of Files
  *
  *
- *     (c) 1999 Martin Mares, <mj@atrey.karlin.mff.cuni.cz>
+ *     (c) 1999--2002 Martin Mares <mj@ucw.cz>
+ *
+ *     This software may be freely distributed and used according to the terms
+ *     of the GNU Lesser General Public License.
  */
 
  */
 
+#include "lib/lib.h"
+
 #include <stdio.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <sys/stat.h>
 #include <sys/mman.h>
 
 #include <stdio.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <sys/stat.h>
 #include <sys/mman.h>
 
-#include "lib.h"
-
 void *
 void *
-mmap_file(byte *name, unsigned *len)
+mmap_file(byte *name, unsigned *len, int writeable)
 {
 {
-  int fd = open(name, O_RDONLY);
+  int fd = open(name, writeable ? O_RDWR : O_RDONLY);
   struct stat st;
   void *x;
 
   if (fd < 0)
   struct stat st;
   void *x;
 
   if (fd < 0)
-    return NULL;
+    die("open(%s): %m", name);
   if (fstat(fd, &st) < 0)
   if (fstat(fd, &st) < 0)
-    x = NULL;
-  else
+    die("fstat(%s): %m", name);
+  if (len)
+    *len = st.st_size;
+  if (st.st_size)
     {
     {
-      if (len)
-       *len = st.st_size;
-      x = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
+      x = mmap(NULL, st.st_size, writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, fd, 0);
       if (x == MAP_FAILED)
       if (x == MAP_FAILED)
-       x = NULL;
+       die("mmap(%s): %m", name);
     }
     }
+  else /* For empty file, we can return any non-zero address */
+    x = "";
   close(fd);
   return x;
 }
   close(fd);
   return x;
 }
+
+void
+munmap_file(void *start, unsigned len)
+{
+  munmap(start, len);
+}