Ion
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
memorymappedfile.cc
Go to the documentation of this file.
1 
19 
21 #if defined(ION_PLATFORM_WINDOWS)
22 #include "ion/port/fileutils.h"
23 #include "ion/port/string.h"
24 #elif !defined(ION_PLATFORM_NACL)
25 #include <fcntl.h>
26 #include <sys/mman.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 #define POSIX_LIKE_ENOUGH
31 #endif // !WINDOWS && !NACL
32 
33 namespace ion {
34 namespace port {
35 
36 MemoryMappedFile::MemoryMappedFile(const std::string& path)
37  : data_(NULL), length_(0) {
38 #if defined(ION_PLATFORM_WINDOWS)
39  const std::wstring wide = Utf8ToWide(path);
40  HANDLE handle = ::CreateFileW(wide.c_str(), GENERIC_READ,
41  FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
42  OPEN_EXISTING, 0, NULL);
43  if (handle != INVALID_HANDLE_VALUE) {
44  mapping_ = ::CreateFileMapping(handle, NULL, PAGE_READONLY, 0, 0, NULL);
45  if (mapping_) {
46  data_ = ::MapViewOfFile(mapping_, FILE_MAP_READ, 0, 0, 0);
47  LARGE_INTEGER size;
48  if (::GetFileSizeEx(handle, &size)) {
49  length_ = static_cast<size_t>(size.QuadPart);
50  } else {
51  ::UnmapViewOfFile(data_);
52  data_ = NULL;
53  }
54  }
55  ::CloseHandle(handle);
56  }
57 #elif defined(POSIX_LIKE_ENOUGH)
58  struct stat path_stat = {0};
59  if (stat(path.c_str(), &path_stat))
60  return;
61  length_ = static_cast<size_t>(path_stat.st_size);
62  int fd = open(path.c_str(), O_RDONLY);
63  if (fd < 0)
64  return;
65  data_ = mmap(NULL, length_, PROT_READ, MAP_PRIVATE, fd, 0);
66  if (data_ == MAP_FAILED || close(fd)) {
67  data_ = NULL;
68  return;
69  }
70 #endif
71 }
72 
74 #if defined(ION_PLATFORM_WINDOWS)
75  if (data_)
76  ::UnmapViewOfFile(data_);
77  if (mapping_)
78  ::CloseHandle(mapping_);
79 #elif defined(POSIX_LIKE_ENOUGH)
80  if (data_)
81  munmap(data_, length_);
82 #endif // POSIX_LIKE_ENOUGH
83 }
84 
85 const void* MemoryMappedFile::GetData() const {
86  return data_;
87 }
88 
90  return length_;
91 }
92 
93 } // namespace port
94 } // namespace ion
unzFile handle
size_t GetLength() const
Returns the length of the mapped region.
MemoryMappedFile(const std::string &path)
Maps the file at path.
const void * GetData() const
Returns a pointer to the head of the mapped region.