[runtime] Rename most System.Reflection.MonoX classes to RuntimeX for consistency...
[mono-project.git] / mono / metadata / file-mmap-windows.c
blob108731b0938fbfccb3e8f7e42aae81a949de0e4d
1 /**
2 * \file
3 * MemoryMappedFile internal calls for Windows
5 * Copyright 2016 Microsoft
6 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
7 */
9 /*
10 * The code in this file has been inspired by the CoreFX MemoryMappedFile Windows implementation contained in the files
12 * https://github.com/dotnet/corefx/blob/master/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs
13 * https://github.com/dotnet/corefx/blob/master/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs
16 #include <config.h>
17 #include <glib.h>
18 #include <mono/utils/mono-compiler.h>
19 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
21 #include <glib.h>
23 #include <mono/metadata/file-mmap.h>
25 // These control the retry behaviour when lock violation errors occur during Flush:
26 #define MAX_FLUSH_WAITS 15 // must be <=30
27 #define MAX_FLUSH_RETIRES_PER_WAIT 20
29 typedef struct {
30 void *address;
31 size_t length;
32 } MmapInstance;
34 enum {
35 BAD_CAPACITY_FOR_FILE_BACKED = 1,
36 CAPACITY_SMALLER_THAN_FILE_SIZE,
37 FILE_NOT_FOUND,
38 FILE_ALREADY_EXISTS,
39 PATH_TOO_LONG,
40 COULD_NOT_OPEN,
41 CAPACITY_MUST_BE_POSITIVE,
42 INVALID_FILE_MODE,
43 COULD_NOT_MAP_MEMORY,
44 ACCESS_DENIED,
45 CAPACITY_LARGER_THAN_LOGICAL_ADDRESS_SPACE
48 enum {
49 FILE_MODE_CREATE_NEW = 1,
50 FILE_MODE_CREATE = 2,
51 FILE_MODE_OPEN = 3,
52 FILE_MODE_OPEN_OR_CREATE = 4,
53 FILE_MODE_TRUNCATE = 5,
54 FILE_MODE_APPEND = 6,
57 enum {
58 MMAP_FILE_ACCESS_READ_WRITE = 0,
59 MMAP_FILE_ACCESS_READ = 1,
60 MMAP_FILE_ACCESS_WRITE = 2,
61 MMAP_FILE_ACCESS_COPY_ON_WRITE = 3,
62 MMAP_FILE_ACCESS_READ_EXECUTE = 4,
63 MMAP_FILE_ACCESS_READ_WRITE_EXECUTE = 5,
66 static DWORD get_page_access (int access)
68 switch (access) {
69 case MMAP_FILE_ACCESS_READ:
70 return PAGE_READONLY;
71 case MMAP_FILE_ACCESS_READ_WRITE:
72 return PAGE_READWRITE;
73 case MMAP_FILE_ACCESS_COPY_ON_WRITE:
74 return PAGE_WRITECOPY;
75 case MMAP_FILE_ACCESS_READ_EXECUTE:
76 return PAGE_EXECUTE_READ;
77 case MMAP_FILE_ACCESS_READ_WRITE_EXECUTE:
78 return PAGE_EXECUTE_READWRITE;
79 default:
80 g_error ("unknown MemoryMappedFileAccess %d", access);
84 static DWORD get_file_access (int access)
86 switch (access) {
87 case MMAP_FILE_ACCESS_READ:
88 case MMAP_FILE_ACCESS_READ_EXECUTE:
89 return GENERIC_READ;
90 case MMAP_FILE_ACCESS_READ_WRITE:
91 case MMAP_FILE_ACCESS_COPY_ON_WRITE:
92 case MMAP_FILE_ACCESS_READ_WRITE_EXECUTE:
93 return GENERIC_READ | GENERIC_WRITE;
94 case MMAP_FILE_ACCESS_WRITE:
95 return GENERIC_WRITE;
96 default:
97 g_error ("unknown MemoryMappedFileAccess %d", access);
101 static int get_file_map_access (int access)
103 switch (access) {
104 case MMAP_FILE_ACCESS_READ:
105 return FILE_MAP_READ;
106 case MMAP_FILE_ACCESS_WRITE:
107 return FILE_MAP_WRITE;
108 case MMAP_FILE_ACCESS_READ_WRITE:
109 return FILE_MAP_READ | FILE_MAP_WRITE;
110 case MMAP_FILE_ACCESS_COPY_ON_WRITE:
111 return FILE_MAP_COPY;
112 case MMAP_FILE_ACCESS_READ_EXECUTE:
113 return FILE_MAP_EXECUTE | FILE_MAP_READ;
114 case MMAP_FILE_ACCESS_READ_WRITE_EXECUTE:
115 return FILE_MAP_EXECUTE | FILE_MAP_READ | FILE_MAP_WRITE;
116 default:
117 g_error ("unknown MemoryMappedFileAccess %d", access);
121 static int convert_win32_error (int win32error, int default_)
123 switch (win32error) {
124 case ERROR_FILE_NOT_FOUND:
125 return FILE_NOT_FOUND;
126 case ERROR_FILE_EXISTS:
127 case ERROR_ALREADY_EXISTS:
128 return FILE_ALREADY_EXISTS;
129 case ERROR_ACCESS_DENIED:
130 return ACCESS_DENIED;
132 return default_;
135 static void*
136 open_handle (void *handle, const gunichar2 *mapName, gint mapName_length, int mode, gint64 *capacity, int access, int options, int *ioerror, MonoError *error)
138 g_assert (handle != NULL);
140 // INVALID_HANDLE_VALUE (-1) is valid, to make named shared memory,
141 // backed by physical memory / pagefile.
143 if (handle == INVALID_HANDLE_VALUE) {
144 if (*capacity <= 0 && mode != FILE_MODE_OPEN) {
145 *ioerror = CAPACITY_MUST_BE_POSITIVE;
146 return NULL;
148 #if SIZEOF_VOID_P == 4
149 if (*capacity > UINT32_MAX) {
150 *ioerror = CAPACITY_LARGER_THAN_LOGICAL_ADDRESS_SPACE;
151 return NULL;
153 #endif
154 if (!(mode == FILE_MODE_CREATE_NEW || mode == FILE_MODE_OPEN_OR_CREATE || mode == FILE_MODE_OPEN)) {
155 *ioerror = INVALID_FILE_MODE;
156 return NULL;
158 } else {
159 FILE_STANDARD_INFO info;
160 if (!GetFileInformationByHandleEx (handle, FileStandardInfo, &info, sizeof (FILE_STANDARD_INFO))) {
161 *ioerror = convert_win32_error (GetLastError (), COULD_NOT_OPEN);
162 return NULL;
164 if (*capacity == 0) {
165 if (info.EndOfFile.QuadPart == 0) {
166 *ioerror = CAPACITY_SMALLER_THAN_FILE_SIZE;
167 return NULL;
169 } else if (*capacity < info.EndOfFile.QuadPart) {
170 *ioerror = CAPACITY_SMALLER_THAN_FILE_SIZE;
171 return NULL;
175 HANDLE result = NULL;
177 if (mode == FILE_MODE_CREATE_NEW || handle != INVALID_HANDLE_VALUE) {
178 result = CreateFileMappingW (handle, NULL, get_page_access (access) | options, (DWORD)(((guint64)*capacity) >> 32), (DWORD)*capacity, mapName);
179 if (result && GetLastError () == ERROR_ALREADY_EXISTS) {
180 CloseHandle (result);
181 result = NULL;
182 *ioerror = FILE_ALREADY_EXISTS;
183 } else if (!result && GetLastError () != NO_ERROR) {
184 *ioerror = convert_win32_error (GetLastError (), COULD_NOT_OPEN);
186 } else if (mode == FILE_MODE_OPEN || mode == FILE_MODE_OPEN_OR_CREATE && access == MMAP_FILE_ACCESS_WRITE) {
187 result = OpenFileMappingW (get_file_map_access (access), FALSE, mapName);
188 if (!result) {
189 if (mode == FILE_MODE_OPEN_OR_CREATE && GetLastError () == ERROR_FILE_NOT_FOUND) {
190 *ioerror = INVALID_FILE_MODE;
191 } else {
192 *ioerror = convert_win32_error (GetLastError (), COULD_NOT_OPEN);
195 } else if (mode == FILE_MODE_OPEN_OR_CREATE) {
197 // This replicates how CoreFX does MemoryMappedFile.CreateOrOpen ().
199 /// Try to open the file if it exists -- this requires a bit more work. Loop until we can
200 /// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail
201 /// if the file exists and we have non-null security attributes, in which case we need to
202 /// use OpenFileMapping. But, there exists a race condition because the memory mapped file
203 /// may have closed between the two calls -- hence the loop.
204 ///
205 /// The retry/timeout logic increases the wait time each pass through the loop and times
206 /// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened,
207 /// throw an InvalidOperationException.
209 guint32 waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
210 guint32 waitSleep = 0;
212 while (waitRetries > 0) {
213 result = CreateFileMappingW (handle, NULL, get_page_access (access) | options, (DWORD)(((guint64)*capacity) >> 32), (DWORD)*capacity, mapName);
214 if (result)
215 break;
216 if (GetLastError() != ERROR_ACCESS_DENIED) {
217 *ioerror = convert_win32_error (GetLastError (), COULD_NOT_OPEN);
218 break;
220 result = OpenFileMappingW (get_file_map_access (access), FALSE, mapName);
221 if (result)
222 break;
223 if (GetLastError () != ERROR_FILE_NOT_FOUND) {
224 *ioerror = convert_win32_error (GetLastError (), COULD_NOT_OPEN);
225 break;
227 // increase wait time
228 --waitRetries;
229 if (waitSleep == 0) {
230 waitSleep = 10;
231 } else {
232 mono_thread_info_sleep (waitSleep, NULL);
233 waitSleep *= 2;
237 if (!result) {
238 *ioerror = COULD_NOT_OPEN;
242 return result;
245 void*
246 mono_mmap_open_file (const gunichar2 *path, gint path_length, int mode, const gunichar2 *mapName, gint mapName_length, gint64 *capacity, int access, int options, int *ioerror, MonoError *error)
248 g_assert (path != NULL || mapName != NULL);
250 HANDLE hFile = INVALID_HANDLE_VALUE;
251 HANDLE result = NULL;
252 gboolean delete_on_error = FALSE;
254 if (path) {
255 WIN32_FILE_ATTRIBUTE_DATA file_attrs;
256 gboolean existed = GetFileAttributesExW (path, GetFileExInfoStandard, &file_attrs);
257 if (!existed && mode == FILE_MODE_CREATE_NEW && *capacity == 0) {
258 *ioerror = CAPACITY_SMALLER_THAN_FILE_SIZE;
259 goto done;
261 hFile = CreateFileW (path, get_file_access (access), FILE_SHARE_READ, NULL, mode, FILE_ATTRIBUTE_NORMAL, NULL);
262 if (hFile == INVALID_HANDLE_VALUE) {
263 *ioerror = convert_win32_error (GetLastError (), COULD_NOT_OPEN);
264 goto done;
266 delete_on_error = !existed;
267 } else {
268 // INVALID_HANDLE_VALUE (-1) is valid, to make named shared memory,
269 // backed by physical memory / pagefile.
272 result = open_handle (hFile, mapName, mapName_length, mode, capacity, access, options, ioerror, error);
274 done:
275 if (hFile != INVALID_HANDLE_VALUE)
276 CloseHandle (hFile);
277 if (!result && delete_on_error)
278 DeleteFileW (path);
280 return result;
283 void*
284 mono_mmap_open_handle (void *handle, const gunichar2 *mapName, gint mapName_length, gint64 *capacity, int access, int options, int *ioerror, MonoError *error)
286 g_assert (handle != NULL);
288 return open_handle (handle, mapName, mapName_length, FILE_MODE_OPEN, capacity, access, options, ioerror, error);
291 void
292 mono_mmap_close (void *mmap_handle, MonoError *error)
294 g_assert (mmap_handle);
295 CloseHandle (mmap_handle);
298 void
299 mono_mmap_configure_inheritability (void *mmap_handle, gint32 inheritability, MonoError *error)
301 g_assert (mmap_handle);
302 if (!SetHandleInformation (mmap_handle, HANDLE_FLAG_INHERIT, inheritability ? HANDLE_FLAG_INHERIT : 0)) {
303 g_error ("mono_mmap_configure_inheritability: SetHandleInformation failed with error %d!", GetLastError ());
307 void
308 mono_mmap_flush (void *mmap_handle, MonoError *error)
310 g_assert (mmap_handle);
311 MmapInstance *h = (MmapInstance *)mmap_handle;
313 if (FlushViewOfFile (h->address, h->length))
314 return;
316 // This replicates how CoreFX does MemoryMappedView.Flush ().
318 // It is a known issue within the NTFS transaction log system that
319 // causes FlushViewOfFile to intermittently fail with ERROR_LOCK_VIOLATION
320 // As a workaround, we catch this particular error and retry the flush operation
321 // a few milliseconds later. If it does not work, we give it a few more tries with
322 // increasing intervals. Eventually, however, we need to give up. In ad-hoc tests
323 // this strategy successfully flushed the view after no more than 3 retries.
325 if (GetLastError () != ERROR_LOCK_VIOLATION)
326 // TODO: Propagate error to caller
327 return;
329 for (int w = 0; w < MAX_FLUSH_WAITS; w++) {
330 int pause = (1 << w); // MaxFlushRetries should never be over 30
331 mono_thread_info_sleep (pause, NULL);
333 for (int r = 0; r < MAX_FLUSH_RETIRES_PER_WAIT; r++) {
334 if (FlushViewOfFile (h->address, h->length))
335 return;
337 if (GetLastError () != ERROR_LOCK_VIOLATION)
338 // TODO: Propagate error to caller
339 return;
341 mono_thread_info_yield ();
345 // We got to here, so there was no success:
346 // TODO: Propagate error to caller
350 mono_mmap_map (void *handle, gint64 offset, gint64 *size, int access, void **mmap_handle, void **base_address, MonoError *error)
352 static DWORD allocationGranularity = 0;
353 if (allocationGranularity == 0) {
354 SYSTEM_INFO info;
355 GetSystemInfo (&info);
356 allocationGranularity = info.dwAllocationGranularity;
359 gint64 extraMemNeeded = offset % allocationGranularity;
360 guint64 newOffset = offset - extraMemNeeded;
361 gint64 nativeSize = (*size != 0) ? *size + extraMemNeeded : 0;
363 #if SIZEOF_VOID_P == 4
364 if (nativeSize > UINT32_MAX)
365 return CAPACITY_LARGER_THAN_LOGICAL_ADDRESS_SPACE;
366 #endif
368 void *address = MapViewOfFile (handle, get_file_map_access (access), (DWORD) (newOffset >> 32), (DWORD) newOffset, (SIZE_T) nativeSize);
369 if (!address)
370 return convert_win32_error (GetLastError (), COULD_NOT_MAP_MEMORY);
372 // Query the view for its size and allocation type
373 MEMORY_BASIC_INFORMATION viewInfo;
374 VirtualQuery (address, &viewInfo, sizeof (MEMORY_BASIC_INFORMATION));
375 guint64 viewSize = (guint64) viewInfo.RegionSize;
377 // Allocate the pages if we were using the MemoryMappedFileOptions.DelayAllocatePages option
378 // OR check if the allocated view size is smaller than the expected native size
379 // If multiple overlapping views are created over the file mapping object, the pages in a given region
380 // could have different attributes(MEM_RESERVE OR MEM_COMMIT) as MapViewOfFile preserves coherence between
381 // views created on a mapping object backed by same file.
382 // In which case, the viewSize will be smaller than nativeSize required and viewState could be MEM_COMMIT
383 // but more pages may need to be committed in the region.
384 // This is because, VirtualQuery function(that internally invokes VirtualQueryEx function) returns the attributes
385 // and size of the region of pages with matching attributes starting from base address.
386 // VirtualQueryEx: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366907(v=vs.85).aspx
387 if (((viewInfo.State & MEM_RESERVE) != 0) || viewSize < (guint64) nativeSize) {
388 void *tempAddress = VirtualAlloc (address, nativeSize != 0 ? nativeSize : viewSize, MEM_COMMIT, get_page_access (access));
389 if (!tempAddress) {
390 return convert_win32_error (GetLastError (), COULD_NOT_MAP_MEMORY);
392 // again query the view for its new size
393 VirtualQuery (address, &viewInfo, sizeof (MEMORY_BASIC_INFORMATION));
394 viewSize = (guint64) viewInfo.RegionSize;
397 if (*size == 0)
398 *size = viewSize - extraMemNeeded;
400 MmapInstance *h = g_malloc0 (sizeof (MmapInstance));
401 h->address = address;
402 h->length = *size + extraMemNeeded;
403 *mmap_handle = h;
404 *base_address = (char*) address + (offset - newOffset);
406 return 0;
409 MonoBoolean
410 mono_mmap_unmap (void *mmap_handle, MonoError *error)
412 g_assert (mmap_handle);
414 MmapInstance *h = (MmapInstance *) mmap_handle;
416 gboolean result = UnmapViewOfFile (h->address);
418 g_free (h);
419 return result;
422 #else
424 MONO_EMPTY_SOURCE_FILE (file_mmap_windows);
426 #endif