From 5c999f4c62b0562e783fcb8959ffba6a28106c13 Mon Sep 17 00:00:00 2001 From: leitner Date: Thu, 14 Jul 2016 16:19:47 +0000 Subject: [PATCH] add mmap_readat --- mmap.h | 3 +++ mmap/mmap_readat.3 | 23 +++++++++++++++++++++++ mmap/mmap_readat.c | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 mmap/mmap_readat.3 create mode 100644 mmap/mmap_readat.c diff --git a/mmap.h b/mmap.h index aaab28c..47d4516 100644 --- a/mmap.h +++ b/mmap.h @@ -12,6 +12,9 @@ extern "C" { * map in filesize and return pointer to map. */ const char* mmap_read(const char *filename,size_t* filesize); +/* like mmap_read but use openat instead of open */ +const char* mmap_readat(const char *filename,size_t* filesize,int dirfd); + /* open file for writing, mmap whole file privately (copy on write), * close file, write length of map in filesize and return pointer to * map. */ diff --git a/mmap/mmap_readat.3 b/mmap/mmap_readat.3 new file mode 100644 index 0000000..de48a9f --- /dev/null +++ b/mmap/mmap_readat.3 @@ -0,0 +1,23 @@ +.TH mmap_readat 3 +.SH NAME +mmap_readat \- memory map a file for reading +.SH SYNTAX +.B #include + +char* \fBmmap_readat\fP(const char* \fIfilename\fR,size_t* \fIfilesize\fR,int \fIdirfd\fR); +.SH DESCRIPTION +mmap_readat opens \fIfilename\fR for reading, maps the whole file into +memory, closes the file, writes the length of the file to \fIfilesize\fR +and returns a pointer to the mapped file. + +If \fIfilename\fR is a relative path and \fIdirfd\fR is not -1, +\fIfilename\fR is interpreted relative to \fIdirfd\fR, which must be an +open directory. + +The file is unmapped by the operating system if the process terminates. +It can also be manually unmapped by calling \fBmunmap\fR from +. + +If the file could not be opened or mapped, (void*)0 is returned. +.SH "SEE ALSO" +mmap_unmap(3) diff --git a/mmap/mmap_readat.c b/mmap/mmap_readat.c new file mode 100644 index 0000000..e7de33d --- /dev/null +++ b/mmap/mmap_readat.c @@ -0,0 +1,36 @@ +#define _POSIX_C_SOURCE 200809 +#define _ATFILE_SOURCE + +#include +#include +#ifndef __MINGW32__ +#include +#include +#include +#include +#endif +#include "open.h" +#include "mmap.h" + +extern const char* mmap_readat(const char* filename,size_t * filesize,int dirfd) { +#ifdef __MINGW32__ + return 0; +#else + int fd=openat(dirfd,filename,O_RDONLY); + char *map; + if (fd>=0) { + register off_t o=lseek(fd,0,SEEK_END); + if (sizeof(off_t)!=sizeof(size_t) && o > (off_t)(size_t)-1) { close(fd); return 0; } + *filesize=(size_t)o; + if (o>0) { + map=mmap(0,*filesize,PROT_READ,MAP_SHARED,fd,0); + if (map==(char*)-1) + map=0; + } else + map=""; + close(fd); + return map; + } + return 0; +#endif +}