MemoryMappedFile.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. using System;
  29. using System.IO;
  30. using System.Collections.Generic;
  31. using Microsoft.Win32.SafeHandles;
  32. using System.Runtime.InteropServices;
  33. using System.Runtime.CompilerServices;
  34. namespace System.IO.MemoryMappedFiles
  35. {
  36. internal static class MemoryMapImpl {
  37. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  38. static extern IntPtr OpenFileInternal (string path, FileMode mode, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, out int error);
  39. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  40. static extern IntPtr OpenHandleInternal (IntPtr handle, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, out int error);
  41. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  42. internal extern static void CloseMapping (IntPtr handle);
  43. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  44. internal extern static void Flush (IntPtr file_handle);
  45. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  46. internal extern static void ConfigureHandleInheritability (IntPtr handle, HandleInheritability inheritability);
  47. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  48. internal extern static bool Unmap (IntPtr mmap_handle);
  49. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  50. extern static int MapInternal (IntPtr handle, long offset, ref long size, MemoryMappedFileAccess access, out IntPtr mmap_handle, out IntPtr base_address);
  51. internal static void Map (IntPtr handle, long offset, ref long size, MemoryMappedFileAccess access, out IntPtr mmap_handle, out IntPtr base_address)
  52. {
  53. int error = MapInternal (handle, offset, ref size, access, out mmap_handle, out base_address);
  54. if (error != 0)
  55. throw CreateException (error, "<none>");
  56. }
  57. static Exception CreateException (int error, string path) {
  58. switch (error){
  59. case 1:
  60. return new ArgumentException ("A positive capacity must be specified for a Memory Mapped File backed by an empty file.");
  61. case 2:
  62. return new ArgumentOutOfRangeException ("The capacity may not be smaller than the file size.");
  63. case 3:
  64. return new FileNotFoundException (path);
  65. case 4:
  66. return new IOException ("The file already exists");
  67. case 5:
  68. return new PathTooLongException ();
  69. case 6:
  70. return new IOException ("Could not open file");
  71. case 7:
  72. return new ArgumentException ("Capacity must be bigger than zero for non-file mappings");
  73. case 8:
  74. return new ArgumentException ("Invalid FileMode value.");
  75. case 9:
  76. return new IOException ("Could not map file");
  77. default:
  78. return new IOException ("Failed with unknown error code " + error);
  79. }
  80. }
  81. internal static IntPtr OpenFile (string path, FileMode mode, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options)
  82. {
  83. int error = 0;
  84. IntPtr res = OpenFileInternal (path, mode, mapName, out capacity, access, options, out error);
  85. if (error != 0)
  86. throw CreateException (error, path);
  87. return res;
  88. }
  89. internal static IntPtr OpenHandle (IntPtr handle, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options)
  90. {
  91. int error = 0;
  92. IntPtr res = OpenHandleInternal (handle, mapName, out capacity, access, options, out error);
  93. if (error != 0)
  94. throw CreateException (error, "<none>");
  95. return res;
  96. }
  97. }
  98. public class MemoryMappedFile : IDisposable {
  99. MemoryMappedFileAccess fileAccess;
  100. string name;
  101. long fileCapacity;
  102. //
  103. // We allow the use of either the FileStream/keepOpen combo
  104. // or a Unix file descriptor. This way we avoid the dependency on
  105. // Mono's io-layer having the Unix file descriptors mapped to
  106. // the same io-layer handle
  107. //
  108. FileStream stream;
  109. bool keepOpen;
  110. IntPtr handle;
  111. public static MemoryMappedFile CreateFromFile (string path)
  112. {
  113. return CreateFromFile (path, FileMode.Open, null, 0, MemoryMappedFileAccess.ReadWrite);
  114. }
  115. public static MemoryMappedFile CreateFromFile (string path, FileMode mode)
  116. {
  117. long capacity = 0;
  118. if (path == null)
  119. throw new ArgumentNullException ("path");
  120. if (path.Length == 0)
  121. throw new ArgumentException ("path");
  122. if (mode == FileMode.Append)
  123. throw new ArgumentException ("mode");
  124. IntPtr handle = MemoryMapImpl.OpenFile (path, mode, null, out capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages);
  125. return new MemoryMappedFile () {
  126. handle = handle,
  127. fileAccess = MemoryMappedFileAccess.ReadWrite,
  128. fileCapacity = capacity
  129. };
  130. }
  131. public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName)
  132. {
  133. return CreateFromFile (path, mode, mapName, 0, MemoryMappedFileAccess.ReadWrite);
  134. }
  135. public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName, long capacity)
  136. {
  137. return CreateFromFile (path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite);
  138. }
  139. public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
  140. {
  141. if (path == null)
  142. throw new ArgumentNullException ("path");
  143. if (path.Length == 0)
  144. throw new ArgumentException ("path");
  145. if (mapName != null && mapName.Length == 0)
  146. throw new ArgumentException ("mapName");
  147. if (mode == FileMode.Append)
  148. throw new ArgumentException ("mode");
  149. if (capacity < 0)
  150. throw new ArgumentOutOfRangeException ("capacity");
  151. IntPtr handle = MemoryMapImpl.OpenFile (path, mode, mapName, out capacity, access, MemoryMappedFileOptions.DelayAllocatePages);
  152. return new MemoryMappedFile () {
  153. handle = handle,
  154. fileAccess = access,
  155. name = mapName,
  156. fileCapacity = capacity
  157. };
  158. }
  159. [MonoLimitation ("memoryMappedFileSecurity is currently ignored")]
  160. public static MemoryMappedFile CreateFromFile (FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access,
  161. MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability,
  162. bool leaveOpen)
  163. {
  164. if (fileStream == null)
  165. throw new ArgumentNullException ("fileStream");
  166. if (mapName != null && mapName.Length == 0)
  167. throw new ArgumentException ("mapName");
  168. if ((!MonoUtil.IsUnix && capacity == 0 && fileStream.Length == 0) || (capacity > fileStream.Length))
  169. throw new ArgumentException ("capacity");
  170. IntPtr handle = MemoryMapImpl.OpenHandle (fileStream.Handle, mapName, out capacity, access, MemoryMappedFileOptions.DelayAllocatePages);
  171. MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
  172. return new MemoryMappedFile () {
  173. handle = handle,
  174. fileAccess = access,
  175. name = mapName,
  176. fileCapacity = capacity,
  177. stream = fileStream,
  178. keepOpen = leaveOpen
  179. };
  180. }
  181. static MemoryMappedFile CoreShmCreate (string mapName, long capacity, MemoryMappedFileAccess access,
  182. MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
  183. HandleInheritability inheritability, FileMode mode)
  184. {
  185. if (mapName != null && mapName.Length == 0)
  186. throw new ArgumentException ("mapName");
  187. if (capacity < 0)
  188. throw new ArgumentOutOfRangeException ("capacity");
  189. IntPtr handle = MemoryMapImpl.OpenFile (null, mode, mapName, out capacity, access, options);
  190. return new MemoryMappedFile () {
  191. handle = handle,
  192. fileAccess = access,
  193. name = mapName,
  194. fileCapacity = capacity
  195. };
  196. }
  197. [MonoLimitation ("Named mappings scope is process local")]
  198. public static MemoryMappedFile CreateNew (string mapName, long capacity)
  199. {
  200. return CreateNew (mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, null, HandleInheritability.None);
  201. }
  202. [MonoLimitation ("Named mappings scope is process local")]
  203. public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access)
  204. {
  205. return CreateNew (mapName, capacity, access, MemoryMappedFileOptions.DelayAllocatePages, null, HandleInheritability.None);
  206. }
  207. [MonoLimitation ("Named mappings scope is process local; options and memoryMappedFileSecurity are ignored")]
  208. public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access,
  209. MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
  210. HandleInheritability inheritability)
  211. {
  212. return CoreShmCreate (mapName, capacity, access, options, memoryMappedFileSecurity, inheritability, FileMode.CreateNew);
  213. }
  214. [MonoLimitation ("Named mappings scope is process local")]
  215. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity)
  216. {
  217. return CreateOrOpen (mapName, capacity, MemoryMappedFileAccess.ReadWrite);
  218. }
  219. [MonoLimitation ("Named mappings scope is process local")]
  220. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access)
  221. {
  222. return CreateOrOpen (mapName, capacity, access, MemoryMappedFileOptions.DelayAllocatePages, null, HandleInheritability.None);
  223. }
  224. [MonoLimitation ("Named mappings scope is process local")]
  225. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability)
  226. {
  227. return CoreShmCreate (mapName, capacity, access, options, memoryMappedFileSecurity, inheritability, FileMode.OpenOrCreate);
  228. }
  229. [MonoLimitation ("Named mappings scope is process local")]
  230. public static MemoryMappedFile OpenExisting (string mapName)
  231. {
  232. throw new NotImplementedException ();
  233. }
  234. [MonoLimitation ("Named mappings scope is process local")]
  235. public static MemoryMappedFile OpenExisting (string mapName, MemoryMappedFileRights desiredAccessRights)
  236. {
  237. throw new NotImplementedException ();
  238. }
  239. [MonoLimitation ("Named mappings scope is process local")]
  240. public static MemoryMappedFile OpenExisting (string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability)
  241. {
  242. throw new NotImplementedException ();
  243. }
  244. public MemoryMappedViewStream CreateViewStream ()
  245. {
  246. return CreateViewStream (0, 0);//FIXME this is wrong
  247. }
  248. public MemoryMappedViewStream CreateViewStream (long offset, long size)
  249. {
  250. return CreateViewStream (offset, size, MemoryMappedFileAccess.ReadWrite);
  251. }
  252. public MemoryMappedViewStream CreateViewStream (long offset, long size, MemoryMappedFileAccess access)
  253. {
  254. var view = MemoryMappedView.Create (handle, offset, size, access);
  255. return new MemoryMappedViewStream (view);
  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. var view = MemoryMappedView.Create (handle, offset, size, access);
  268. return new MemoryMappedViewAccessor (view);
  269. }
  270. MemoryMappedFile ()
  271. {
  272. }
  273. public void Dispose ()
  274. {
  275. Dispose (true);
  276. }
  277. protected virtual void Dispose (bool disposing)
  278. {
  279. if (disposing){
  280. if (stream != null){
  281. if (keepOpen == false)
  282. stream.Close ();
  283. stream = null;
  284. }
  285. if (handle != IntPtr.Zero) {
  286. MemoryMapImpl.CloseMapping (handle);
  287. handle = IntPtr.Zero;
  288. }
  289. }
  290. }
  291. [MonoTODO]
  292. public MemoryMappedFileSecurity GetAccessControl ()
  293. {
  294. throw new NotImplementedException ();
  295. }
  296. [MonoTODO]
  297. public void SetAccessControl (MemoryMappedFileSecurity memoryMappedFileSecurity)
  298. {
  299. throw new NotImplementedException ();
  300. }
  301. [MonoTODO]
  302. public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle {
  303. get {
  304. throw new NotImplementedException ();
  305. }
  306. }
  307. // This converts a MemoryMappedFileAccess to a FileAccess. MemoryMappedViewStream and
  308. // MemoryMappedViewAccessor subclass UnmanagedMemoryStream and UnmanagedMemoryAccessor, which both use
  309. // FileAccess to determine whether they are writable and/or readable.
  310. internal static FileAccess GetFileAccess (MemoryMappedFileAccess access) {
  311. if (access == MemoryMappedFileAccess.Read) {
  312. return FileAccess.Read;
  313. }
  314. if (access == MemoryMappedFileAccess.Write) {
  315. return FileAccess.Write;
  316. }
  317. else if (access == MemoryMappedFileAccess.ReadWrite) {
  318. return FileAccess.ReadWrite;
  319. }
  320. else if (access == MemoryMappedFileAccess.CopyOnWrite) {
  321. return FileAccess.ReadWrite;
  322. }
  323. else if (access == MemoryMappedFileAccess.ReadExecute) {
  324. return FileAccess.Read;
  325. }
  326. else if (access == MemoryMappedFileAccess.ReadWriteExecute) {
  327. return FileAccess.ReadWrite;
  328. }
  329. // If we reached here, access was invalid.
  330. throw new ArgumentOutOfRangeException ("access");
  331. }
  332. }
  333. }