2 * UCW Library -- Mapping of File Parts
4 * (c) 2003 Martin Mares <mj@ucw.cz>
5 * (c) 2003 Robert Spalek <robert@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
25 sh_off_t start_off, end_off;
31 #define PARTMAP_WINDOW 4096
33 #define PARTMAP_WINDOW 16777216
37 partmap_open(byte *name, int writeable)
39 struct partmap *p = xmalloc_zero(sizeof(struct partmap));
41 p->fd = sh_open(name, writeable ? O_RDWR : O_RDONLY);
43 die("open(%s): %m", name);
44 if ((p->file_size = sh_seek(p->fd, 0, SEEK_END)) < 0)
45 die("lseek(%s): %m", name);
46 p->writeable = writeable;
51 partmap_size(struct partmap *p)
57 partmap_close(struct partmap *p)
60 munmap(p->start_map, p->end_off - p->start_off);
66 partmap_map(struct partmap *p, sh_off_t start, uns size)
68 if (!p->start_map || start < p->start_off || (sh_off_t) (start+size) > p->end_off)
71 munmap(p->start_map, p->end_off - p->start_off);
72 sh_off_t end = start + size;
73 sh_off_t win_start = start/PAGE_SIZE * PAGE_SIZE;
74 uns win_len = PARTMAP_WINDOW;
75 if ((sh_off_t) (win_start+win_len) > p->file_size)
76 win_len = ALIGN(p->file_size - win_start, PAGE_SIZE);
77 if ((sh_off_t) (win_start+win_len) < end)
78 die("partmap_map: Window is too small for mapping %d bytes", size);
79 p->start_map = sh_mmap(NULL, win_len, p->writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, p->fd, win_start);
80 if (p->start_map == MAP_FAILED)
81 die("mmap failed at position %Ld: %m", (long long)win_start);
82 p->start_off = win_start;
83 p->end_off = win_start+win_len;
85 return p->start_map + (start - p->start_off);
89 int main(int argc, char **argv)
91 struct partmap *p = partmap_open(argv[1], 0);
92 uns l = partmap_size(p);
95 putchar(*(char *)partmap_map(p, i, 1));