MemoryMappedFile.cs 17 KB

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