MemoryMappedFile.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. //
  2. // MemoryMappedFile.cs
  3. //
  4. // Authors:
  5. // Zoltan Varga ([email protected])
  6. //
  7. // Copyright (C) 2009, Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. #if NET_4_0
  29. using System;
  30. using System.IO;
  31. using System.Collections.Generic;
  32. using Microsoft.Win32.SafeHandles;
  33. using System.Runtime.InteropServices;
  34. using System.Runtime.CompilerServices;
  35. namespace System.IO.MemoryMappedFiles
  36. {
  37. internal static class MemoryMapImpl {
  38. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  39. static extern IntPtr OpenFileInternal (string path, FileMode mode, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, out int error);
  40. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  41. static extern IntPtr OpenHandleInternal (IntPtr handle, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, out int error);
  42. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  43. internal extern static void CloseMapping (IntPtr handle);
  44. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  45. internal extern static void Flush (IntPtr file_handle);
  46. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  47. internal extern static void ConfigureHandleInheritability (IntPtr handle, HandleInheritability inheritability);
  48. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  49. internal extern static bool Unmap (IntPtr mmap_handle);
  50. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  51. extern static int MapInternal (IntPtr handle, long offset, ref long size, MemoryMappedFileAccess access, out IntPtr mmap_handle, out IntPtr base_address);
  52. internal static void Map (IntPtr handle, long offset, ref long size, MemoryMappedFileAccess access, out IntPtr mmap_handle, out IntPtr base_address)
  53. {
  54. int error = MapInternal (handle, offset, ref size, access, out mmap_handle, out base_address);
  55. if (error != 0)
  56. throw CreateException (error, "<none>");
  57. }
  58. static Exception CreateException (int error, string path) {
  59. switch (error){
  60. case 1:
  61. return new ArgumentException ("A positive capacity must be specified for a Memory Mapped File backed by an empty file.");
  62. case 2:
  63. return new ArgumentOutOfRangeException ("The capacity may not be smaller than the file size.");
  64. case 3:
  65. return new FileNotFoundException (path);
  66. case 4:
  67. return new IOException ("The file already exists");
  68. case 5:
  69. return new PathTooLongException ();
  70. case 6:
  71. return new IOException ("Could not open file");
  72. case 7:
  73. return new ArgumentException ("Capacity must be bigger than zero for non-file mappings");
  74. case 8:
  75. return new ArgumentException ("Invalid FileMode value.");
  76. case 9:
  77. return new IOException ("Could not map file");
  78. default:
  79. return new IOException ("Failed with unknown error code " + error);
  80. }
  81. }
  82. internal static IntPtr OpenFile (string path, FileMode mode, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options)
  83. {
  84. int error = 0;
  85. IntPtr res = OpenFileInternal (path, mode, mapName, out capacity, access, options, out error);
  86. if (error != 0)
  87. throw CreateException (error, path);
  88. return res;
  89. }
  90. internal static IntPtr OpenHandle (IntPtr handle, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options)
  91. {
  92. int error = 0;
  93. IntPtr res = OpenHandleInternal (handle, mapName, out capacity, access, options, out error);
  94. if (error != 0)
  95. throw CreateException (error, "<none>");
  96. return res;
  97. }
  98. }
  99. public class MemoryMappedFile : IDisposable {
  100. MemoryMappedFileAccess fileAccess;
  101. string name;
  102. long fileCapacity;
  103. //
  104. // We allow the use of either the FileStream/keepOpen combo
  105. // or a Unix file descriptor. This way we avoid the dependency on
  106. // Mono's io-layer having the Unix file descriptors mapped to
  107. // the same io-layer handle
  108. //
  109. FileStream stream;
  110. bool keepOpen;
  111. IntPtr handle;
  112. public static MemoryMappedFile CreateFromFile (string path)
  113. {
  114. return CreateFromFile (path, FileMode.Open, null, 0, MemoryMappedFileAccess.ReadWrite);
  115. }
  116. public static MemoryMappedFile CreateFromFile (string path, FileMode mode)
  117. {
  118. long capacity = 0;
  119. if (path == null)
  120. throw new ArgumentNullException ("path");
  121. if (path.Length == 0)
  122. throw new ArgumentException ("path");
  123. if (mode == FileMode.Append)
  124. throw new ArgumentException ("mode");
  125. IntPtr handle = MemoryMapImpl.OpenFile (path, mode, null, out capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages);
  126. return new MemoryMappedFile () {
  127. handle = handle,
  128. fileAccess = MemoryMappedFileAccess.ReadWrite,
  129. fileCapacity = capacity
  130. };
  131. }
  132. public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName)
  133. {
  134. return CreateFromFile (path, mode, mapName, 0, MemoryMappedFileAccess.ReadWrite);
  135. }
  136. public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName, long capacity)
  137. {
  138. return CreateFromFile (path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite);
  139. }
  140. public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
  141. {
  142. if (path == null)
  143. throw new ArgumentNullException ("path");
  144. if (path.Length == 0)
  145. throw new ArgumentException ("path");
  146. if (mapName != null && mapName.Length == 0)
  147. throw new ArgumentException ("mapName");
  148. if (mode == FileMode.Append)
  149. throw new ArgumentException ("mode");
  150. if (capacity < 0)
  151. throw new ArgumentOutOfRangeException ("capacity");
  152. IntPtr handle = MemoryMapImpl.OpenFile (path, mode, mapName, out capacity, access, MemoryMappedFileOptions.DelayAllocatePages);
  153. return new MemoryMappedFile () {
  154. handle = handle,
  155. fileAccess = access,
  156. name = mapName,
  157. fileCapacity = capacity
  158. };
  159. }
  160. [MonoLimitation ("memoryMappedFileSecurity is currently ignored")]
  161. public static MemoryMappedFile CreateFromFile (FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access,
  162. MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability,
  163. bool leaveOpen)
  164. {
  165. if (fileStream == null)
  166. throw new ArgumentNullException ("fileStream");
  167. if (mapName != null && mapName.Length == 0)
  168. throw new ArgumentException ("mapName");
  169. if ((!MonoUtil.IsUnix && capacity == 0 && fileStream.Length == 0) || (capacity > fileStream.Length))
  170. throw new ArgumentException ("capacity");
  171. IntPtr handle = MemoryMapImpl.OpenHandle (fileStream.Handle, mapName, out capacity, access, MemoryMappedFileOptions.DelayAllocatePages);
  172. MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
  173. return new MemoryMappedFile () {
  174. handle = handle,
  175. fileAccess = access,
  176. name = mapName,
  177. fileCapacity = capacity,
  178. stream = fileStream,
  179. keepOpen = leaveOpen
  180. };
  181. }
  182. static MemoryMappedFile CoreShmCreate (string mapName, long capacity, MemoryMappedFileAccess access,
  183. MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
  184. HandleInheritability inheritability, FileMode mode)
  185. {
  186. if (mapName != null && mapName.Length == 0)
  187. throw new ArgumentException ("mapName");
  188. if (capacity < 0)
  189. throw new ArgumentOutOfRangeException ("capacity");
  190. IntPtr handle = MemoryMapImpl.OpenFile (null, mode, mapName, out capacity, access, options);
  191. return new MemoryMappedFile () {
  192. handle = handle,
  193. fileAccess = access,
  194. name = mapName,
  195. fileCapacity = capacity
  196. };
  197. }
  198. [MonoLimitation ("Named mappings scope is process local")]
  199. public static MemoryMappedFile CreateNew (string mapName, long capacity)
  200. {
  201. return CreateNew (mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, null, HandleInheritability.None);
  202. }
  203. [MonoLimitation ("Named mappings scope is process local")]
  204. public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access)
  205. {
  206. return CreateNew (mapName, capacity, access, MemoryMappedFileOptions.DelayAllocatePages, null, HandleInheritability.None);
  207. }
  208. [MonoLimitation ("Named mappings scope is process local; options and memoryMappedFileSecurity are ignored")]
  209. public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access,
  210. MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
  211. HandleInheritability inheritability)
  212. {
  213. return CoreShmCreate (mapName, capacity, access, options, memoryMappedFileSecurity, inheritability, FileMode.CreateNew);
  214. }
  215. [MonoLimitation ("Named mappings scope is process local")]
  216. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity)
  217. {
  218. return CreateOrOpen (mapName, capacity, MemoryMappedFileAccess.ReadWrite);
  219. }
  220. [MonoLimitation ("Named mappings scope is process local")]
  221. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access)
  222. {
  223. return CreateOrOpen (mapName, capacity, access, MemoryMappedFileOptions.DelayAllocatePages, null, HandleInheritability.None);
  224. }
  225. [MonoLimitation ("Named mappings scope is process local")]
  226. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability)
  227. {
  228. return CoreShmCreate (mapName, capacity, access, options, memoryMappedFileSecurity, inheritability, FileMode.OpenOrCreate);
  229. }
  230. [MonoLimitation ("Named mappings scope is process local")]
  231. public static MemoryMappedFile OpenExisting (string mapName)
  232. {
  233. throw new NotImplementedException ();
  234. }
  235. [MonoLimitation ("Named mappings scope is process local")]
  236. public static MemoryMappedFile OpenExisting (string mapName, MemoryMappedFileRights desiredAccessRights)
  237. {
  238. throw new NotImplementedException ();
  239. }
  240. [MonoLimitation ("Named mappings scope is process local")]
  241. public static MemoryMappedFile OpenExisting (string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability)
  242. {
  243. throw new NotImplementedException ();
  244. }
  245. public MemoryMappedViewStream CreateViewStream ()
  246. {
  247. return CreateViewStream (0, 0);//FIXME this is wrong
  248. }
  249. public MemoryMappedViewStream CreateViewStream (long offset, long size)
  250. {
  251. return CreateViewStream (offset, size, MemoryMappedFileAccess.ReadWrite);
  252. }
  253. public MemoryMappedViewStream CreateViewStream (long offset, long size, MemoryMappedFileAccess access)
  254. {
  255. return new MemoryMappedViewStream (handle, offset, size, access);
  256. }
  257. public MemoryMappedViewAccessor CreateViewAccessor ()
  258. {
  259. return CreateViewAccessor (0, 0);
  260. }
  261. public MemoryMappedViewAccessor CreateViewAccessor (long offset, long size)
  262. {
  263. return CreateViewAccessor (offset, size, MemoryMappedFileAccess.ReadWrite);
  264. }
  265. public MemoryMappedViewAccessor CreateViewAccessor (long offset, long size, MemoryMappedFileAccess access)
  266. {
  267. return new MemoryMappedViewAccessor (handle, offset, size, access);
  268. }
  269. MemoryMappedFile ()
  270. {
  271. }
  272. public void Dispose ()
  273. {
  274. Dispose (true);
  275. }
  276. protected virtual void Dispose (bool disposing)
  277. {
  278. if (disposing){
  279. if (stream != null){
  280. if (keepOpen == false)
  281. stream.Close ();
  282. stream = null;
  283. }
  284. if (handle != IntPtr.Zero) {
  285. MemoryMapImpl.CloseMapping (handle);
  286. handle = IntPtr.Zero;
  287. }
  288. }
  289. }
  290. [MonoTODO]
  291. public MemoryMappedFileSecurity GetAccessControl ()
  292. {
  293. throw new NotImplementedException ();
  294. }
  295. [MonoTODO]
  296. public void SetAccessControl (MemoryMappedFileSecurity memoryMappedFileSecurity)
  297. {
  298. throw new NotImplementedException ();
  299. }
  300. [MonoTODO]
  301. public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle {
  302. get {
  303. throw new NotImplementedException ();
  304. }
  305. }
  306. }
  307. }
  308. #endif