MemoryMappedFile.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 ("capacity", "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. case 10:
  78. return new UnauthorizedAccessException ("Access to the path is denied.");
  79. case 11:
  80. return new ArgumentOutOfRangeException ("capacity", "The capacity cannot be greater than the size of the system's logical address space.");
  81. default:
  82. return new IOException ("Failed with unknown error code " + error);
  83. }
  84. }
  85. internal static IntPtr OpenFile (string path, FileMode mode, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options)
  86. {
  87. int error = 0;
  88. IntPtr res = OpenFileInternal (path, mode, mapName, out capacity, access, options, out error);
  89. if (error != 0)
  90. throw CreateException (error, path);
  91. return res;
  92. }
  93. internal static IntPtr OpenHandle (IntPtr handle, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options)
  94. {
  95. int error = 0;
  96. IntPtr res = OpenHandleInternal (handle, mapName, out capacity, access, options, out error);
  97. if (error != 0)
  98. throw CreateException (error, "<none>");
  99. return res;
  100. }
  101. }
  102. public class MemoryMappedFile : IDisposable {
  103. // MemoryMappedFileAccess fileAccess;
  104. // string name;
  105. // long fileCapacity;
  106. //
  107. // We allow the use of either the FileStream/keepOpen combo
  108. // or a Unix file descriptor. This way we avoid the dependency on
  109. // Mono's io-layer having the Unix file descriptors mapped to
  110. // the same io-layer handle
  111. //
  112. FileStream stream;
  113. bool keepOpen;
  114. IntPtr handle;
  115. public static MemoryMappedFile CreateFromFile (string path)
  116. {
  117. return CreateFromFile (path, FileMode.Open, null, 0, MemoryMappedFileAccess.ReadWrite);
  118. }
  119. public static MemoryMappedFile CreateFromFile (string path, FileMode mode)
  120. {
  121. long capacity = 0;
  122. if (path == null)
  123. throw new ArgumentNullException ("path");
  124. if (path.Length == 0)
  125. throw new ArgumentException ("path");
  126. if (mode == FileMode.Append)
  127. throw new ArgumentException ("mode");
  128. IntPtr handle = MemoryMapImpl.OpenFile (path, mode, null, out capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None);
  129. return new MemoryMappedFile () {
  130. handle = handle,
  131. // fileAccess = MemoryMappedFileAccess.ReadWrite,
  132. // fileCapacity = capacity
  133. };
  134. }
  135. public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName)
  136. {
  137. return CreateFromFile (path, mode, mapName, 0, MemoryMappedFileAccess.ReadWrite);
  138. }
  139. public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName, long capacity)
  140. {
  141. return CreateFromFile (path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite);
  142. }
  143. public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
  144. {
  145. if (path == null)
  146. throw new ArgumentNullException ("path");
  147. if (path.Length == 0)
  148. throw new ArgumentException ("path");
  149. if (mapName != null && mapName.Length == 0)
  150. throw new ArgumentException ("mapName");
  151. if (mode == FileMode.Append)
  152. throw new ArgumentException ("mode");
  153. if (capacity < 0)
  154. throw new ArgumentOutOfRangeException ("capacity");
  155. IntPtr handle = MemoryMapImpl.OpenFile (path, mode, mapName, out capacity, access, MemoryMappedFileOptions.None);
  156. return new MemoryMappedFile () {
  157. handle = handle,
  158. // fileAccess = access,
  159. // name = mapName,
  160. // fileCapacity = capacity
  161. };
  162. }
  163. public static MemoryMappedFile CreateFromFile (FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access,
  164. HandleInheritability inheritability,
  165. bool leaveOpen)
  166. {
  167. if (fileStream == null)
  168. throw new ArgumentNullException ("fileStream");
  169. if (mapName != null && mapName.Length == 0)
  170. throw new ArgumentException ("mapName");
  171. if ((!MonoUtil.IsUnix && capacity == 0 && fileStream.Length == 0) || (capacity > fileStream.Length))
  172. throw new ArgumentException ("capacity");
  173. IntPtr handle = MemoryMapImpl.OpenHandle (fileStream.SafeFileHandle.DangerousGetHandle (), mapName, out capacity, access, MemoryMappedFileOptions.None);
  174. MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
  175. return new MemoryMappedFile () {
  176. handle = handle,
  177. // fileAccess = access,
  178. // name = mapName,
  179. // fileCapacity = capacity,
  180. stream = fileStream,
  181. keepOpen = leaveOpen
  182. };
  183. }
  184. [MonoLimitation ("memoryMappedFileSecurity is currently ignored")]
  185. public static MemoryMappedFile CreateFromFile (FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access,
  186. MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability,
  187. bool leaveOpen)
  188. {
  189. if (fileStream == null)
  190. throw new ArgumentNullException ("fileStream");
  191. if (mapName != null && mapName.Length == 0)
  192. throw new ArgumentException ("mapName");
  193. if ((!MonoUtil.IsUnix && capacity == 0 && fileStream.Length == 0) || (capacity > fileStream.Length))
  194. throw new ArgumentException ("capacity");
  195. IntPtr handle = MemoryMapImpl.OpenHandle (fileStream.SafeFileHandle.DangerousGetHandle (), mapName, out capacity, access, MemoryMappedFileOptions.None);
  196. MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
  197. return new MemoryMappedFile () {
  198. handle = handle,
  199. // fileAccess = access,
  200. // name = mapName,
  201. // fileCapacity = capacity,
  202. stream = fileStream,
  203. keepOpen = leaveOpen
  204. };
  205. }
  206. static MemoryMappedFile CoreShmCreate (string mapName, long capacity, MemoryMappedFileAccess access,
  207. MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
  208. HandleInheritability inheritability, FileMode mode)
  209. {
  210. if (mapName != null && mapName.Length == 0)
  211. throw new ArgumentException ("mapName");
  212. if (capacity < 0)
  213. throw new ArgumentOutOfRangeException ("capacity");
  214. IntPtr handle = MemoryMapImpl.OpenFile (null, mode, mapName, out capacity, access, options);
  215. return new MemoryMappedFile () {
  216. handle = handle,
  217. // fileAccess = access,
  218. // name = mapName,
  219. // fileCapacity = capacity
  220. };
  221. }
  222. [MonoLimitation ("Named mappings scope is process local")]
  223. public static MemoryMappedFile CreateNew (string mapName, long capacity)
  224. {
  225. return CreateNew (mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, null, HandleInheritability.None);
  226. }
  227. [MonoLimitation ("Named mappings scope is process local")]
  228. public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access)
  229. {
  230. return CreateNew (mapName, capacity, access, MemoryMappedFileOptions.None, null, HandleInheritability.None);
  231. }
  232. [MonoLimitation ("Named mappings scope is process local; options is ignored")]
  233. public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability)
  234. {
  235. return CreateNew (mapName, capacity, access, options, null, inheritability);
  236. }
  237. [MonoLimitation ("Named mappings scope is process local; options and memoryMappedFileSecurity are ignored")]
  238. public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access,
  239. MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
  240. HandleInheritability inheritability)
  241. {
  242. return CoreShmCreate (mapName, capacity, access, options, memoryMappedFileSecurity, inheritability, FileMode.CreateNew);
  243. }
  244. [MonoLimitation ("Named mappings scope is process local")]
  245. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity)
  246. {
  247. return CreateOrOpen (mapName, capacity, MemoryMappedFileAccess.ReadWrite);
  248. }
  249. [MonoLimitation ("Named mappings scope is process local")]
  250. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access)
  251. {
  252. return CreateOrOpen (mapName, capacity, access, MemoryMappedFileOptions.None, null, HandleInheritability.None);
  253. }
  254. [MonoLimitation ("Named mappings scope is process local")]
  255. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability)
  256. {
  257. return CreateOrOpen (mapName, capacity, access, options, null, inheritability);
  258. }
  259. [MonoLimitation ("Named mappings scope is process local")]
  260. public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability)
  261. {
  262. return CoreShmCreate (mapName, capacity, access, options, memoryMappedFileSecurity, inheritability, FileMode.OpenOrCreate);
  263. }
  264. [MonoLimitation ("Named mappings scope is process local")]
  265. public static MemoryMappedFile OpenExisting (string mapName)
  266. {
  267. throw new NotImplementedException ();
  268. }
  269. [MonoLimitation ("Named mappings scope is process local")]
  270. public static MemoryMappedFile OpenExisting (string mapName, MemoryMappedFileRights desiredAccessRights)
  271. {
  272. throw new NotImplementedException ();
  273. }
  274. [MonoLimitation ("Named mappings scope is process local")]
  275. public static MemoryMappedFile OpenExisting (string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability)
  276. {
  277. throw new NotImplementedException ();
  278. }
  279. public MemoryMappedViewStream CreateViewStream ()
  280. {
  281. return CreateViewStream (0, 0);//FIXME this is wrong
  282. }
  283. public MemoryMappedViewStream CreateViewStream (long offset, long size)
  284. {
  285. return CreateViewStream (offset, size, MemoryMappedFileAccess.ReadWrite);
  286. }
  287. public MemoryMappedViewStream CreateViewStream (long offset, long size, MemoryMappedFileAccess access)
  288. {
  289. var view = MemoryMappedView.Create (handle, offset, size, access);
  290. return new MemoryMappedViewStream (view);
  291. }
  292. public MemoryMappedViewAccessor CreateViewAccessor ()
  293. {
  294. return CreateViewAccessor (0, 0);
  295. }
  296. public MemoryMappedViewAccessor CreateViewAccessor (long offset, long size)
  297. {
  298. return CreateViewAccessor (offset, size, MemoryMappedFileAccess.ReadWrite);
  299. }
  300. public MemoryMappedViewAccessor CreateViewAccessor (long offset, long size, MemoryMappedFileAccess access)
  301. {
  302. var view = MemoryMappedView.Create (handle, offset, size, access);
  303. return new MemoryMappedViewAccessor (view);
  304. }
  305. MemoryMappedFile ()
  306. {
  307. }
  308. public void Dispose ()
  309. {
  310. Dispose (true);
  311. }
  312. protected virtual void Dispose (bool disposing)
  313. {
  314. if (disposing){
  315. if (stream != null){
  316. if (keepOpen == false)
  317. stream.Close ();
  318. stream = null;
  319. }
  320. if (handle != IntPtr.Zero) {
  321. MemoryMapImpl.CloseMapping (handle);
  322. handle = IntPtr.Zero;
  323. }
  324. }
  325. }
  326. [MonoTODO]
  327. public MemoryMappedFileSecurity GetAccessControl ()
  328. {
  329. throw new NotImplementedException ();
  330. }
  331. [MonoTODO]
  332. public void SetAccessControl (MemoryMappedFileSecurity memoryMappedFileSecurity)
  333. {
  334. throw new NotImplementedException ();
  335. }
  336. [MonoTODO]
  337. public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle {
  338. get {
  339. throw new NotImplementedException ();
  340. }
  341. }
  342. // This converts a MemoryMappedFileAccess to a FileAccess. MemoryMappedViewStream and
  343. // MemoryMappedViewAccessor subclass UnmanagedMemoryStream and UnmanagedMemoryAccessor, which both use
  344. // FileAccess to determine whether they are writable and/or readable.
  345. internal static FileAccess GetFileAccess (MemoryMappedFileAccess access) {
  346. if (access == MemoryMappedFileAccess.Read) {
  347. return FileAccess.Read;
  348. }
  349. if (access == MemoryMappedFileAccess.Write) {
  350. return FileAccess.Write;
  351. }
  352. else if (access == MemoryMappedFileAccess.ReadWrite) {
  353. return FileAccess.ReadWrite;
  354. }
  355. else if (access == MemoryMappedFileAccess.CopyOnWrite) {
  356. return FileAccess.ReadWrite;
  357. }
  358. else if (access == MemoryMappedFileAccess.ReadExecute) {
  359. return FileAccess.Read;
  360. }
  361. else if (access == MemoryMappedFileAccess.ReadWriteExecute) {
  362. return FileAccess.ReadWrite;
  363. }
  364. // If we reached here, access was invalid.
  365. throw new ArgumentOutOfRangeException ("access");
  366. }
  367. }
  368. }