]> mj.ucw.cz Git - libucw.git/blob - ucw/io-mmap.c
Merge branch 'master' into dev-sizet
[libucw.git] / ucw / io-mmap.c
1 /*
2  *      UCW Library -- Mapping of Files
3  *
4  *      (c) 1999--2012 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/io.h>
12
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <sys/stat.h>
17 #include <sys/mman.h>
18
19 void *
20 mmap_file(const char *name, size_t *len, int writeable)
21 {
22   int fd = ucw_open(name, writeable ? O_RDWR : O_RDONLY);
23   ucw_stat_t st;
24   void *x;
25
26   if (fd < 0)
27     die("open(%s): %m", name);
28   if (ucw_fstat(fd, &st) < 0)
29     die("fstat(%s): %m", name);
30   if ((uintmax_t)st.st_size > SIZE_MAX)
31     die("mmap(%s): File too large", name);
32   if (len)
33     *len = st.st_size;
34   if (st.st_size)
35     {
36       x = mmap(NULL, st.st_size, writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, fd, 0);
37       if (x == MAP_FAILED)
38         die("mmap(%s): %m", name);
39     }
40   else  /* For empty file, we can return any non-zero address */
41     x = "";
42   close(fd);
43   return x;
44 }
45
46 void
47 munmap_file(void *start, size_t len)
48 {
49   munmap(start, len);
50 }