comparison src/lib/mmap-util.c @ 0:3b1985cbc908 HEAD

Initial revision
author Timo Sirainen <tss@iki.fi>
date Fri, 09 Aug 2002 12:15:38 +0300
parents
children 1b34ec11fff8
comparison
equal deleted inserted replaced
-1:000000000000 0:3b1985cbc908
1 /*
2 mmap-util.c - Memory mapping utilities
3
4 Copyright (c) 2002 Timo Sirainen
5
6 Permission is hereby granted, free of charge, to any person obtaining
7 a copy of this software and associated documentation files (the
8 "Software"), to deal in the Software without restriction, including
9 without limitation the rights to use, copy, modify, merge, publish,
10 distribute, sublicense, and/or sell copies of the Software, and to
11 permit persons to whom the Software is furnished to do so, subject to
12 the following conditions:
13
14 The above copyright notice and this permission notice shall be
15 included in all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26 #include "lib.h"
27 #include "mmap-util.h"
28
29 static void *mmap_file(int fd, size_t *length, int access)
30 {
31 *length = lseek(fd, 0, SEEK_END);
32 if ((off_t)*length == (off_t)-1)
33 return MAP_FAILED;
34
35 if (*length == 0)
36 return NULL;
37
38 i_assert(*length > 0 && *length < INT_MAX);
39
40 return mmap(NULL, *length, access, MAP_SHARED, fd, 0);
41 }
42
43 void *mmap_ro_file(int fd, size_t *length)
44 {
45 return mmap_file(fd, length, PROT_READ);
46 }
47
48 void *mmap_rw_file(int fd, size_t *length)
49 {
50 return mmap_file(fd, length, PROT_READ | PROT_WRITE);
51 }
52
53 void *mmap_aligned(int fd, int access, off_t offset, size_t length,
54 void **data_start, size_t *mmap_length)
55 {
56 void *mmap_base;
57
58 #ifdef HAVE_GETPAGESIZE
59 static int pagemask = 0;
60
61 if (pagemask == 0) {
62 pagemask = getpagesize();
63 i_assert(pagemask > 0);
64 pagemask--;
65 }
66
67 *mmap_length = length + (offset & pagemask);
68
69 mmap_base = mmap(NULL, *mmap_length, access, MAP_SHARED,
70 fd, offset & ~pagemask);
71 *data_start = mmap_base == MAP_FAILED || mmap_base == NULL ? NULL :
72 (char *) mmap_base + (offset & pagemask);
73 #else
74 *mmap_length = length + offset;
75
76 mmap_base = mmap(NULL, *mmap_length, access, MAP_SHARED, fd, 0);
77 *data_start = mmap_base == MAP_FAILED || mmap_base == NULL ? NULL :
78 (char *) mmap_base + offset;
79 #endif
80
81 return mmap_base;
82 }
83
84 #ifndef HAVE_MADVISE
85 int madvise(void *start, size_t length, int advice)
86 {
87 }
88 #endif