MemoryMappedFile.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. #include "il2cpp-config.h"
  2. #if !IL2CPP_USE_GENERIC_MEMORY_MAPPED_FILE && IL2CPP_TARGET_WINDOWS
  3. #include <map>
  4. #include <limits>
  5. #include "WindowsHelpers.h"
  6. #include "os/MemoryMappedFile.h"
  7. #include "utils/StringUtils.h"
  8. namespace il2cpp
  9. {
  10. namespace os
  11. {
  12. static DWORD ConvertMappedFileAccessToWindowsPageAccess(MemoryMappedFileAccess access)
  13. {
  14. switch (access)
  15. {
  16. case MMAP_FILE_ACCESS_READ:
  17. return PAGE_READONLY;
  18. case MMAP_FILE_ACCESS_READ_WRITE:
  19. return PAGE_READWRITE;
  20. case MMAP_FILE_ACCESS_COPY_ON_WRITE:
  21. return PAGE_WRITECOPY;
  22. case MMAP_FILE_ACCESS_READ_EXECUTE:
  23. return PAGE_EXECUTE_READ;
  24. case MMAP_FILE_ACCESS_READ_WRITE_EXECUTE:
  25. return PAGE_EXECUTE_READWRITE;
  26. default:
  27. IL2CPP_ASSERT("unknown MemoryMappedFileAccess");
  28. }
  29. return MMAP_FILE_ACCESS_READ;
  30. }
  31. static int ConvertMappedFileAccessToWindowsFileAccess(MemoryMappedFileAccess access)
  32. {
  33. switch (access)
  34. {
  35. case MMAP_FILE_ACCESS_READ:
  36. return FILE_MAP_READ;
  37. case MMAP_FILE_ACCESS_WRITE:
  38. return FILE_MAP_WRITE;
  39. case MMAP_FILE_ACCESS_READ_WRITE:
  40. return FILE_MAP_READ | FILE_MAP_WRITE;
  41. case MMAP_FILE_ACCESS_COPY_ON_WRITE:
  42. return FILE_MAP_COPY;
  43. case MMAP_FILE_ACCESS_READ_EXECUTE:
  44. return FILE_MAP_EXECUTE | FILE_MAP_READ;
  45. case MMAP_FILE_ACCESS_READ_WRITE_EXECUTE:
  46. return FILE_MAP_EXECUTE | FILE_MAP_READ | FILE_MAP_WRITE;
  47. default:
  48. IL2CPP_ASSERT("unknown MemoryMappedFileAccess");
  49. }
  50. return MMAP_FILE_ACCESS_READ;
  51. }
  52. static MemoryMappedFileError ConvertWindowsErrorToMemoryMappedFileError(DWORD error, MemoryMappedFileError defaultError)
  53. {
  54. switch (error)
  55. {
  56. case ERROR_FILE_NOT_FOUND:
  57. return FILE_NOT_FOUND;
  58. case ERROR_FILE_EXISTS:
  59. case ERROR_ALREADY_EXISTS:
  60. return FILE_ALREADY_EXISTS;
  61. case ERROR_ACCESS_DENIED:
  62. return ACCESS_DENIED;
  63. }
  64. return defaultError;
  65. }
  66. FileHandle* MemoryMappedFile::Create(FileHandle* file, const char* mapName, int32_t mode, int64_t *capacity, MemoryMappedFileAccess access, int32_t options, MemoryMappedFileError* error)
  67. {
  68. HANDLE result = NULL;
  69. HANDLE handle = file != NULL ? file : INVALID_HANDLE_VALUE;
  70. if (handle == INVALID_HANDLE_VALUE)
  71. {
  72. if (*capacity <= 0 && mode != os::FILE_MODE_OPEN)
  73. {
  74. *error = CAPACITY_MUST_BE_POSITIVE;
  75. return NULL;
  76. }
  77. #if IL2CPP_SIZEOF_VOID_P == 4
  78. if (*capacity > UINT32_MAX)
  79. {
  80. *error = CAPACITY_LARGER_THAN_LOGICAL_ADDRESS_SPACE;
  81. return NULL;
  82. }
  83. #endif
  84. if (!(mode == FILE_MODE_CREATE_NEW || mode == FILE_MODE_OPEN_OR_CREATE || mode == FILE_MODE_OPEN))
  85. {
  86. *error = INVALID_FILE_MODE;
  87. return NULL;
  88. }
  89. }
  90. else
  91. {
  92. FILE_STANDARD_INFO info;
  93. if (!GetFileInformationByHandleEx(handle, FileStandardInfo, &info, sizeof(FILE_STANDARD_INFO)))
  94. {
  95. *error = ConvertWindowsErrorToMemoryMappedFileError(GetLastError(), COULD_NOT_OPEN);
  96. return NULL;
  97. }
  98. if (*capacity == 0)
  99. {
  100. if (info.EndOfFile.QuadPart == 0)
  101. {
  102. *error = CAPACITY_SMALLER_THAN_FILE_SIZE;
  103. return NULL;
  104. }
  105. }
  106. else if (*capacity < info.EndOfFile.QuadPart)
  107. {
  108. *error = CAPACITY_SMALLER_THAN_FILE_SIZE;
  109. return NULL;
  110. }
  111. }
  112. UTF16String utf16MapNameString = mapName != NULL ? il2cpp::utils::StringUtils::Utf8ToUtf16(mapName) : UTF16String();
  113. LPCWSTR utf16MapName = mapName != NULL ? utf16MapNameString.c_str() : NULL;
  114. if (mode == FILE_MODE_CREATE_NEW || handle != INVALID_HANDLE_VALUE)
  115. {
  116. result = CreateFileMapping(handle, NULL, ConvertMappedFileAccessToWindowsPageAccess(access) | options, (DWORD)(((uint64_t)*capacity) >> 32), (DWORD)*capacity, utf16MapName);
  117. if (result && GetLastError() == ERROR_ALREADY_EXISTS)
  118. {
  119. CloseHandle(result);
  120. result = NULL;
  121. *error = FILE_ALREADY_EXISTS;
  122. }
  123. else if (!result && GetLastError() != NO_ERROR)
  124. {
  125. *error = ConvertWindowsErrorToMemoryMappedFileError(GetLastError(), COULD_NOT_OPEN);
  126. }
  127. }
  128. else if (mode == FILE_MODE_OPEN || mode == FILE_MODE_OPEN_OR_CREATE && access == MMAP_FILE_ACCESS_WRITE)
  129. {
  130. result = OpenFileMappingW(ConvertMappedFileAccessToWindowsFileAccess(access), FALSE, utf16MapName);
  131. if (!result)
  132. {
  133. if (mode == FILE_MODE_OPEN_OR_CREATE && GetLastError() == ERROR_FILE_NOT_FOUND)
  134. {
  135. *error = INVALID_FILE_MODE;
  136. }
  137. else
  138. {
  139. *error = ConvertWindowsErrorToMemoryMappedFileError(GetLastError(), COULD_NOT_OPEN);
  140. }
  141. }
  142. }
  143. else if (mode == FILE_MODE_OPEN_OR_CREATE)
  144. {
  145. // This replicates how CoreFX does MemoryMappedFile.CreateOrOpen ().
  146. /// Try to open the file if it exists -- this requires a bit more work. Loop until we can
  147. /// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail
  148. /// if the file exists and we have non-null security attributes, in which case we need to
  149. /// use OpenFileMapping. But, there exists a race condition because the memory mapped file
  150. /// may have closed between the two calls -- hence the loop.
  151. ///
  152. /// The retry/timeout logic increases the wait time each pass through the loop and times
  153. /// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened,
  154. /// throw an InvalidOperationException.
  155. uint32_t waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
  156. uint32_t waitSleep = 0;
  157. while (waitRetries > 0)
  158. {
  159. result = CreateFileMapping(handle, NULL, ConvertMappedFileAccessToWindowsPageAccess(access) | options, (DWORD)(((uint64_t)*capacity) >> 32), (DWORD)*capacity, utf16MapName);
  160. if (result)
  161. break;
  162. if (GetLastError() != ERROR_ACCESS_DENIED)
  163. {
  164. *error = ConvertWindowsErrorToMemoryMappedFileError(GetLastError(), COULD_NOT_OPEN);
  165. break;
  166. }
  167. result = OpenFileMapping(ConvertMappedFileAccessToWindowsFileAccess(access), FALSE, utf16MapName);
  168. if (result)
  169. break;
  170. if (GetLastError() != ERROR_FILE_NOT_FOUND)
  171. {
  172. *error = ConvertWindowsErrorToMemoryMappedFileError(GetLastError(), COULD_NOT_OPEN);
  173. break;
  174. }
  175. // increase wait time
  176. --waitRetries;
  177. if (waitSleep == 0)
  178. {
  179. waitSleep = 10;
  180. }
  181. else
  182. {
  183. Sleep(waitSleep);
  184. waitSleep *= 2;
  185. }
  186. }
  187. if (!result)
  188. *error = COULD_NOT_OPEN;
  189. }
  190. return (os::FileHandle*)result;
  191. }
  192. MemoryMappedFile::MemoryMappedFileHandle MemoryMappedFile::View(FileHandle* mappedFileHandle, int64_t* length, int64_t offset, MemoryMappedFileAccess access, int64_t* actualOffset, MemoryMappedFileError* error)
  193. {
  194. IL2CPP_ASSERT(actualOffset != NULL);
  195. IL2CPP_ASSERT(offset <= std::numeric_limits<DWORD>::max());
  196. IL2CPP_ASSERT(*length <= std::numeric_limits<DWORD>::max());
  197. static DWORD allocationGranularity = 0;
  198. if (allocationGranularity == 0)
  199. {
  200. SYSTEM_INFO info;
  201. GetSystemInfo(&info);
  202. allocationGranularity = info.dwAllocationGranularity;
  203. }
  204. int64_t extraMemNeeded = offset % allocationGranularity;
  205. uint64_t newOffset = offset - extraMemNeeded;
  206. uint64_t nativeSize = (*length != 0) ? *length + extraMemNeeded : 0;
  207. *actualOffset = newOffset;
  208. void* address = MapViewOfFile((HANDLE)mappedFileHandle, ConvertMappedFileAccessToWindowsFileAccess(access), (DWORD)(newOffset >> 32), (DWORD)newOffset, (SIZE_T)nativeSize);
  209. if (address == NULL)
  210. {
  211. if (error != NULL)
  212. *error = ConvertWindowsErrorToMemoryMappedFileError(GetLastError(), COULD_NOT_MAP_MEMORY);
  213. CloseHandle(mappedFileHandle);
  214. return NULL;
  215. }
  216. // Query the view for its size and allocation type
  217. MEMORY_BASIC_INFORMATION viewInfo;
  218. VirtualQuery(address, &viewInfo, sizeof(MEMORY_BASIC_INFORMATION));
  219. uint64_t viewSize = (uint64_t)viewInfo.RegionSize;
  220. // Allocate the pages if we were using the MemoryMappedFileOptions.DelayAllocatePages option
  221. // OR check if the allocated view size is smaller than the expected native size
  222. // If multiple overlapping views are created over the file mapping object, the pages in a given region
  223. // could have different attributes(MEM_RESERVE OR MEM_COMMIT) as MapViewOfFile preserves coherence between
  224. // views created on a mapping object backed by same file.
  225. // In which case, the viewSize will be smaller than nativeSize required and viewState could be MEM_COMMIT
  226. // but more pages may need to be committed in the region.
  227. // This is because, VirtualQuery function(that internally invokes VirtualQueryEx function) returns the attributes
  228. // and size of the region of pages with matching attributes starting from base address.
  229. // VirtualQueryEx: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366907(v=vs.85).aspx
  230. if (((viewInfo.State & MEM_RESERVE) != 0) || viewSize < (uint64_t)nativeSize)
  231. {
  232. void *tempAddress = VirtualAlloc(address, (SIZE_T)(nativeSize != 0 ? nativeSize : viewSize), MEM_COMMIT, ConvertMappedFileAccessToWindowsPageAccess(access));
  233. if (!tempAddress)
  234. {
  235. if (error != NULL)
  236. *error = ConvertWindowsErrorToMemoryMappedFileError(GetLastError(), COULD_NOT_MAP_MEMORY);
  237. return NULL;
  238. }
  239. // again query the view for its new size
  240. VirtualQuery(address, &viewInfo, sizeof(MEMORY_BASIC_INFORMATION));
  241. viewSize = (uint64_t)viewInfo.RegionSize;
  242. }
  243. if (*length == 0)
  244. *length = viewSize - extraMemNeeded;
  245. return address;
  246. }
  247. void MemoryMappedFile::Flush(MemoryMappedFileHandle memoryMappedFileData, int64_t length)
  248. {
  249. BOOL success = FlushViewOfFile(memoryMappedFileData, (SIZE_T)length);
  250. if (success)
  251. return;
  252. // This replicates how CoreFX does MemoryMappedView.Flush ().
  253. // It is a known issue within the NTFS transaction log system that
  254. // causes FlushViewOfFile to intermittently fail with ERROR_LOCK_VIOLATION
  255. // As a workaround, we catch this particular error and retry the flush operation
  256. // a few milliseconds later. If it does not work, we give it a few more tries with
  257. // increasing intervals. Eventually, however, we need to give up. In ad-hoc tests
  258. // this strategy successfully flushed the view after no more than 3 retries.
  259. if (GetLastError() != ERROR_LOCK_VIOLATION)
  260. // TODO: Propagate error to caller
  261. return;
  262. // These control the retry behaviour when lock violation errors occur during Flush:
  263. const int MAX_FLUSH_WAITS = 15; // must be <=30
  264. const int MAX_FLUSH_RETIRES_PER_WAIT = 20;
  265. for (int w = 0; w < MAX_FLUSH_WAITS; w++)
  266. {
  267. int pause = (1 << w); // MaxFlushRetries should never be over 30
  268. Sleep(pause);
  269. for (int r = 0; r < MAX_FLUSH_RETIRES_PER_WAIT; r++)
  270. {
  271. if (FlushViewOfFile(memoryMappedFileData, (SIZE_T)length))
  272. return;
  273. if (GetLastError() != ERROR_LOCK_VIOLATION)
  274. // TODO: Propagate error to caller
  275. return;
  276. SwitchToThread();
  277. }
  278. }
  279. // We got to here, so there was no success
  280. IL2CPP_ASSERT(false);
  281. }
  282. bool MemoryMappedFile::UnmapView(MemoryMappedFileHandle memoryMappedFileData, int64_t length)
  283. {
  284. if (memoryMappedFileData != NULL)
  285. {
  286. BOOL success = UnmapViewOfFile(memoryMappedFileData);
  287. IL2CPP_ASSERT(success);
  288. if (!success)
  289. return false;
  290. }
  291. return true;
  292. }
  293. bool MemoryMappedFile::Close(FileHandle* file)
  294. {
  295. BOOL success = CloseHandle(file);
  296. IL2CPP_ASSERT(success);
  297. return success;
  298. }
  299. void MemoryMappedFile::ConfigureHandleInheritability(FileHandle* file, bool inheritability)
  300. {
  301. #if IL2CPP_TARGET_WINDOWS_DESKTOP
  302. BOOL success = SetHandleInformation((HANDLE)file, HANDLE_FLAG_INHERIT, inheritability ? HANDLE_FLAG_INHERIT : 0);
  303. IL2CPP_ASSERT(success);
  304. #endif
  305. }
  306. bool MemoryMappedFile::OwnsDuplicatedFileHandle(FileHandle* file)
  307. {
  308. return true;
  309. }
  310. }
  311. }
  312. #endif