summaryrefslogtreecommitdiffstats
path: root/mapfile.c
diff options
context:
space:
mode:
authorH. Peter Anvin <hpa@zytor.com>2008-01-06 20:37:48 -0800
committerH. Peter Anvin <hpa@zytor.com>2008-01-06 20:37:48 -0800
commit0530fa26857d1d91c5ebdcaa40e275ddf8171fab (patch)
treef621bdb57a18ddc7ff1d065b9ddfc0339980f43e /mapfile.c
parentd4c3b8e6300e9b2b1bc9c8abd6194a46f8737ceb (diff)
downloadwraplinux-0530fa26857d1d91c5ebdcaa40e275ddf8171fab.tar.gz
wraplinux-0530fa26857d1d91c5ebdcaa40e275ddf8171fab.tar.xz
wraplinux-0530fa26857d1d91c5ebdcaa40e275ddf8171fab.zip
Factor out mapping/unmapping of files
Factor out file map/unmap; this will make porting to non-Unix operating systems and/or support nonfile inputs easier.
Diffstat (limited to 'mapfile.c')
-rw-r--r--mapfile.c52
1 files changed, 52 insertions, 0 deletions
diff --git a/mapfile.c b/mapfile.c
new file mode 100644
index 0000000..0f26ca6
--- /dev/null
+++ b/mapfile.c
@@ -0,0 +1,52 @@
+/* ----------------------------------------------------------------------- *
+ *
+ * Copyright 2008 H. Peter Anvin - All Rights Reserved
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston MA 02110-1301, USA; either version 2 of the License, or
+ * (at your option) any later version; incorporated herein by reference.
+ *
+ * ----------------------------------------------------------------------- */
+
+/*
+ * mapfile.c
+ *
+ * Memory-map a file, and/or read it into a memory buffer.
+ * If the "writable" flag is set, return a writable memory
+ * buffer, *not* one which writes back to the file!
+ *
+ * Note: if this is modified to use a buffer, always round the buffer
+ * size up to at least a dword boundary.
+ */
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+
+void *mapfile(int fd, size_t *len, int writable)
+{
+ struct stat st;
+ void *ptr;
+
+ if (fstat(fd, &st))
+ return NULL;
+
+ *len = st.st_size;
+
+ if (writable)
+ ptr = mmap(NULL, st.st_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
+ else
+ ptr = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
+
+ return (ptr == MAP_FAILED) ? NULL : ptr;
+}
+
+void unmapfile(int fd, void *ptr, size_t len)
+{
+ if (ptr)
+ munmap(ptr, len);
+ if (fd >= 0)
+ close(fd);
+}