]> mj.ucw.cz Git - libucw.git/blob - lib/mmap.c
Make PROF_STR really work.
[libucw.git] / lib / mmap.c
1 /*
2  *      Sherlock Library -- Mapping of Files
3  *
4  *      (c) 1999--2002 Martin Mares <mj@ucw.cz>
5  */
6
7 #include "lib/lib.h"
8
9 #include <stdio.h>
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <sys/stat.h>
13 #include <sys/mman.h>
14
15 void *
16 mmap_file(byte *name, unsigned *len, int writeable)
17 {
18   int fd = open(name, writeable ? O_RDWR : O_RDONLY);
19   struct stat st;
20   void *x;
21
22   if (fd < 0)
23     die("open(%s): %m", name);
24   if (fstat(fd, &st) < 0)
25     die("fstat(%s): %m", name);
26   if (len)
27     *len = st.st_size;
28   if (st.st_size)
29     {
30       x = mmap(NULL, st.st_size, writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, fd, 0);
31       if (x == MAP_FAILED)
32         die("mmap(%s): %m", name);
33     }
34   else  /* For empty file, we can return any non-zero address */
35     x = "";
36   close(fd);
37   return x;
38 }
39
40 void
41 munmap_file(void *start, unsigned len)
42 {
43   munmap(start, len);
44 }