| 1 |
/* cdb_init, cdb_free and cdb_read routines
|
| 2 |
*
|
| 3 |
* This file is a part of tinycdb package by Michael Tokarev, mjt@corpit.ru.
|
| 4 |
* Public domain.
|
| 5 |
*/
|
| 6 |
|
| 7 |
#include "common/setup_before.h"
|
| 8 |
#include <stdio.h>
|
| 9 |
#ifdef HAVE_SYS_STAT_H
|
| 10 |
# include <sys/stat.h>
|
| 11 |
#endif
|
| 12 |
#include "compat/mmap.h"
|
| 13 |
#include "cdb_int.h"
|
| 14 |
#include "common/setup_after.h"
|
| 15 |
|
| 16 |
int
|
| 17 |
cdb_init(struct cdb *cdbp, FILE *fd)
|
| 18 |
{
|
| 19 |
unsigned char *mem;
|
| 20 |
unsigned fsize, dend;
|
| 21 |
|
| 22 |
/* get file size */
|
| 23 |
if (fseek(fd, 0, SEEK_END))
|
| 24 |
return -1;
|
| 25 |
fsize = (unsigned)(ftell(fd));
|
| 26 |
rewind(fd);
|
| 27 |
/* trivial sanity check: at least toc should be here */
|
| 28 |
if (fsize < 2048)
|
| 29 |
return errno = EPROTO, -1;
|
| 30 |
|
| 31 |
/* memory-map file */
|
| 32 |
if ((mem = pmmap(NULL, fsize, PROT_READ, MAP_SHARED, fileno(fd), 0)) ==
|
| 33 |
(unsigned char *)-1)
|
| 34 |
return -1;
|
| 35 |
|
| 36 |
cdbp->cdb_fd = fd;
|
| 37 |
cdbp->cdb_fsize = fsize;
|
| 38 |
cdbp->cdb_mem = mem;
|
| 39 |
|
| 40 |
#if 0
|
| 41 |
/* XXX don't know well about madvise syscall -- is it legal
|
| 42 |
to set different options for parts of one mmap() region?
|
| 43 |
There is also posix_madvise() exist, with POSIX_MADV_RANDOM etc...
|
| 44 |
*/
|
| 45 |
#ifdef MADV_RANDOM
|
| 46 |
/* set madvise() parameters. Ignore errors for now if system
|
| 47 |
doesn't support it */
|
| 48 |
madvise(mem, 2048, MADV_WILLNEED);
|
| 49 |
madvise(mem + 2048, cdbp->cdb_fsize - 2048, MADV_RANDOM);
|
| 50 |
#endif
|
| 51 |
#endif
|
| 52 |
|
| 53 |
cdbp->cdb_vpos = cdbp->cdb_vlen = 0;
|
| 54 |
cdbp->cdb_kpos = cdbp->cdb_klen = 0;
|
| 55 |
dend = cdb_unpack(mem);
|
| 56 |
if (dend < 2048) dend = 2048;
|
| 57 |
else if (dend >= fsize) dend = fsize;
|
| 58 |
cdbp->cdb_dend = dend;
|
| 59 |
|
| 60 |
return 0;
|
| 61 |
}
|
| 62 |
|
| 63 |
void
|
| 64 |
cdb_free(struct cdb *cdbp)
|
| 65 |
{
|
| 66 |
if (cdbp->cdb_mem) {
|
| 67 |
pmunmap((void*)cdbp->cdb_mem, cdbp->cdb_fsize);
|
| 68 |
cdbp->cdb_mem = NULL;
|
| 69 |
}
|
| 70 |
cdbp->cdb_fsize = 0;
|
| 71 |
}
|
| 72 |
|
| 73 |
const void *
|
| 74 |
cdb_get(const struct cdb *cdbp, unsigned len, unsigned pos)
|
| 75 |
{
|
| 76 |
if (pos > cdbp->cdb_fsize || cdbp->cdb_fsize - pos < len) {
|
| 77 |
errno = EPROTO;
|
| 78 |
return NULL;
|
| 79 |
}
|
| 80 |
return cdbp->cdb_mem + pos;
|
| 81 |
}
|
| 82 |
|
| 83 |
int
|
| 84 |
cdb_read(const struct cdb *cdbp, void *buf, unsigned len, unsigned pos)
|
| 85 |
{
|
| 86 |
const void *data = cdb_get(cdbp, len, pos);
|
| 87 |
if (!data) return -1;
|
| 88 |
memcpy(buf, data, len);
|
| 89 |
return 0;
|
| 90 |
}
|