aboutsummaryrefslogtreecommitdiff
path: root/src/common/compat.c
diff options
context:
space:
mode:
authorNick Mathewson <nickm@torproject.org>2006-05-28 16:54:39 +0000
committerNick Mathewson <nickm@torproject.org>2006-05-28 16:54:39 +0000
commit64d487a2d6d916fd12943db5585364e13f1aa43c (patch)
tree1c1eb35de4953cb7915b3be9d07e0c64482c2a2f /src/common/compat.c
parentf6ff3e6f0eebb18ab935e1229f7601bad941d2d0 (diff)
downloadtor-64d487a2d6d916fd12943db5585364e13f1aa43c.tar
tor-64d487a2d6d916fd12943db5585364e13f1aa43c.tar.gz
Add a basic mmap function, with a "fake-it" wrapper to do read_file_from_str instead. Based on code from Michael Mohr.
svn:r6510
Diffstat (limited to 'src/common/compat.c')
-rw-r--r--src/common/compat.c60
1 files changed, 60 insertions, 0 deletions
diff --git a/src/common/compat.c b/src/common/compat.c
index 3d70045eb..c3e42dbc2 100644
--- a/src/common/compat.c
+++ b/src/common/compat.c
@@ -87,6 +87,9 @@ const char compat_c_id[] =
#ifdef HAVE_SYS_UTIME_H
#include <sys/utime.h>
#endif
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
#include "log.h"
#include "util.h"
@@ -104,6 +107,63 @@ const char compat_c_id[] =
#define INADDR_NONE ((unsigned long) -1)
#endif
+#ifdef HAVE_SYS_MMAP
+const char *
+tor_mmap_file(const char *filename, size_t *size)
+{
+ int fd; /* router file */
+ char *string;
+ int page_size;
+
+ tor_assert(filename);
+ tor_assert(size);
+
+ fd = open(filename, O_RDONLY, 0);
+ if (fd<0) {
+ log_warn(LD_FS,"Could not open \"%s\" for mmap().",filename);
+ return NULL;
+ }
+
+ *size = lseek(fd, 0, SEEK_END);
+ lseek(fd, 0, SEEK_SET);
+ /* ensure page alignment */
+ page_size = getpagesize();
+ *size += (page_size + (page_size-(*size%page_size)));
+
+ string = mmap(0, *size, PROT_READ, MAP_PRIVATE, fd, 0);
+ if(string == MAP_FAILED) {
+ log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
+ strerror(errno));
+ return NULL;
+ }
+
+ close(fd);
+
+ return string;
+}
+
+void
+tor_munmap_file(const char *memory, size_t size)
+{
+ munmap((char*)memory, size);
+}
+#else
+const char *
+tor_mmap_file(const char *filename, size_t *size)
+{
+ char *res = read_file_to_str(filename, 1);
+ *size = strlen(res) + 1;
+ return res;
+}
+
+void
+tor_munmap_file(const char *memory, size_t size)
+{
+ char *mem = (char*) memory;
+ tor_free(mem);
+}
+#endif
+
/** Replacement for snprintf. Differs from platform snprintf in two
* ways: First, always NUL-terminates its output. Second, always
* returns -1 if the result is truncated. (Note that this return