YSTest  PreAlpha_b400_20130424
The YSLib Test Project
 全部  命名空间 文件 函数 变量 类型定义 枚举 枚举值 友元 宏定义  
MemoryMapping.cpp
浏览该文件的文档.
1 /*
2  Copyright by FrankHB 2012 - 2013.
3 
4  This file is part of the YSLib project, and may only be used,
5  modified, and distributed under the terms of the YSLib project
6  license, LICENSE.TXT. By continuing to use, modify, or distribute
7  this file you indicate that you have read the license and
8  understand and accept it fully.
9 */
10 
28 #include "YCLib/MemoryMapping.h"
29 #include <fcntl.h>
30 #include <stdexcept> // for std::runtime_error;
31 #if YCL_DS
32 # include <unistd.h>
33 #elif YCL_MINGW32
34 # include <Windows.h>
35 # include <sys/stat.h>
36 
37 namespace
38 {
39 
40 #define MAP_FAILED (reinterpret_cast<void*>(-1))
41 
42 void*
43 map_file(size_t len, int fd)
44 {
45  auto map(MAP_FAILED);
46 
47  if(len != 0)
48  {
49  ::HANDLE h(::HANDLE(::_get_osfhandle(fd)));
50 
51  if(h != INVALID_HANDLE_VALUE)
52  {
53  ::HANDLE fm(::CreateFileMapping(h, nullptr, PAGE_READONLY, 0,
54  len, nullptr));
55 
56  if(fm)
57  {
58  map = ::MapViewOfFile(fm, FILE_MAP_READ, 0, 0, len);
59  ::CloseHandle(fm);
60  if(!map)
61  return MAP_FAILED;
62  }
63  }
64  }
65  return map;
66 }
67 
68 } // unnamed namespace;
69 
70 #endif
71 
72 namespace platform
73 {
74 
76  : fd(uopen(path, O_RDONLY, S_IRUSR | S_IWUSR))
77 {
78  ::fstat(fd, &st);
79 #if YCL_DS
80  addr = new ystdex::byte[st.st_size];
81 
82  ::read(fd, addr, st.st_size);
83 #elif YCL_MINGW32
84 // const auto p(::mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)));
85  const auto p(map_file(st.st_size, fd));
86 
87  if(p == MAP_FAILED)
88  throw std::runtime_error("Mapping failed.");
89  // TODO: Create specific exception type.
90  addr = static_cast<byte*>(p);
91 #else
92 # error Unsupported platform found!
93 #endif
94 }
96 {
97 #if YCL_DS
98  delete addr;
99 #elif YCL_MINGW32
100 // ::munmap(addr, st.st_size);
101  ::UnmapViewOfFile(addr);
102 #endif
103  ::close(fd);
104 }
105 
106 size_t
108 {
109  return st.st_size;
110 }
111 
112 } // namespace platform;
113