00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 #include <fcntl.h>
00018 #include <sys/errno.h>
00019
00020 #include "MmapFile.h"
00021 #include "FileIOClient.h"
00022 #include "FileUtils.h"
00023
00024 namespace oasys {
00025
00026
00027 MmapFile::MmapFile(const char* logpath)
00028 : Logger("MmapFile", logpath),
00029 ptr_(NULL),
00030 len_(0)
00031 {
00032 }
00033
00034
00035 MmapFile::~MmapFile()
00036 {
00037 if (ptr_ != NULL)
00038 unmap();
00039 }
00040
00041
00042 void*
00043 MmapFile::map(const char* filename, int prot, int flags,
00044 size_t len, off_t offset)
00045 {
00046 if (len == 0) {
00047 int ret = FileUtils::size(filename, logpath_);
00048 if (ret < 0) {
00049 log_err("error getting size of file '%s': %s",
00050 filename, strerror(errno));
00051 return NULL;
00052 }
00053 len = (size_t)ret;
00054 }
00055
00056 ASSERT(ptr_ == NULL);
00057 ASSERT(offset < (int)len);
00058
00059 FileIOClient f;
00060 f.logpathf("%s/file", logpath_);
00061
00062 int open_flags = 0;
00063 if (flags & PROT_READ) open_flags |= O_RDONLY;
00064 if (flags & PROT_WRITE) open_flags |= O_WRONLY;
00065
00066 int err;
00067 int fd = f.open(filename, open_flags, &err);
00068 if (fd < 0) {
00069 log_err("error opening file '%s': %s",
00070 filename, strerror(err));
00071 return NULL;
00072 }
00073
00074 len_ = len;
00075 ptr_ = mmap(0, len, prot, flags, fd, offset);
00076 if (ptr_ == (void*)-1) {
00077 log_err("error in mmap of file '%s': %s",
00078 filename, strerror(errno));
00079 ptr_ = NULL;
00080 len_ = 0;
00081 return NULL;
00082 }
00083
00084 return ptr_;
00085 }
00086
00087
00088 bool
00089 MmapFile::unmap()
00090 {
00091 ASSERT(ptr_ != NULL);
00092 int ret = munmap(ptr_, len_);
00093 if (ret != 0) {
00094 log_err("error in munmap: %s", strerror(errno));
00095 return false;
00096 }
00097 ptr_ = NULL;
00098 len_ = 0;
00099 return true;
00100 }
00101
00102 }