5 // Zoltan Varga (vargaz@gmail.com)
7 // Copyright (C) 2009, Novell, Inc (http://www.novell.com)
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
33 using System.Collections.Generic;
34 using Microsoft.Win32.SafeHandles;
35 using Mono.Unix.Native;
37 using System.Runtime.InteropServices;
39 namespace System.IO.MemoryMappedFiles
41 public class MemoryMappedFile : IDisposable {
42 MemoryMappedFileAccess fileAccess;
47 // We allow the use of either the FileStream/keepOpen combo
48 // or a Unix file descriptor. This way we avoid the dependency on
49 // Mono's io-layer having the Unix file descriptors mapped to
50 // the same io-layer handle
56 public static MemoryMappedFile CreateFromFile (FileStream fileStream)
58 if (fileStream == null)
59 throw new ArgumentNullException ("fileStream");
61 return new MemoryMappedFile () {
63 fileAccess = MemoryMappedFileAccess.ReadWrite
67 public static MemoryMappedFile CreateFromFile (string path)
69 return CreateFromFile (path, FileMode.Open, null, 0, MemoryMappedFileAccess.ReadWrite);
73 public static MemoryMappedFile CreateFromFile (string path, FileMode mode)
75 return CreateFromFile (path, mode, null, 0, MemoryMappedFileAccess.ReadWrite);
78 public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName)
80 return CreateFromFile (path, mode, mapName, 0, MemoryMappedFileAccess.ReadWrite);
83 public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName, long capacity)
85 return CreateFromFile (path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite);
89 // Turns the FileMode into the first half of open(2) flags
91 static OpenFlags ToUnixMode (FileMode mode)
94 case FileMode.CreateNew:
95 return OpenFlags.O_CREAT | OpenFlags.O_EXCL;
98 return OpenFlags.O_CREAT | OpenFlags.O_TRUNC;
100 case FileMode.OpenOrCreate:
101 return OpenFlags.O_CREAT;
103 case FileMode.Truncate:
104 return OpenFlags.O_TRUNC;
106 case FileMode.Append:
107 return OpenFlags.O_APPEND;
115 // Turns the MemoryMappedFileAccess into the second half of open(2) flags
117 static OpenFlags ToUnixMode (MemoryMappedFileAccess access)
120 case MemoryMappedFileAccess.CopyOnWrite:
121 case MemoryMappedFileAccess.ReadWriteExecute:
122 case MemoryMappedFileAccess.ReadWrite:
123 return OpenFlags.O_RDWR;
125 case MemoryMappedFileAccess.Write:
126 return OpenFlags.O_WRONLY;
128 case MemoryMappedFileAccess.ReadExecute:
129 case MemoryMappedFileAccess.Read:
131 return OpenFlags.O_RDONLY;
135 public static MemoryMappedFile CreateFromFile (string path, FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
138 throw new ArgumentNullException ("path");
139 if (path.Length == 0)
140 throw new ArgumentException ("path");
141 if (mapName != null && mapName.Length == 0)
142 throw new ArgumentException ("mapName");
145 if (MonoUtil.IsUnix){
147 if (Syscall.stat (path, out buf) == -1)
148 UnixMarshal.ThrowExceptionForLastError ();
150 if ((capacity == 0 && buf.st_size == 0) || (capacity > buf.st_size))
151 throw new ArgumentException ("capacity");
153 fd = Syscall.open (path, ToUnixMode (mode) | ToUnixMode (access), FilePermissions.DEFFILEMODE);
156 UnixMarshal.ThrowExceptionForLastError ();
158 throw new NotImplementedException ();
160 return new MemoryMappedFile () {
164 fileCapacity = capacity
168 public static void ConfigureUnixFD (IntPtr handle, HandleInheritability h)
170 // TODO: Mono.Posix is lacking O_CLOEXEC definitions for fcntl.
174 [DllImport("kernel32.dll", SetLastError = true)]
175 static extern bool SetHandleInformation (IntPtr hObject, int dwMask, int dwFlags);
176 public static void ConfigureWindowsFD (IntPtr handle, HandleInheritability h)
178 SetHandleInformation (handle, 1 /* FLAG_INHERIT */, h == HandleInheritability.None ? 0 : 1);
181 [MonoLimitation ("memoryMappedFileSecurity is currently ignored")]
182 public static MemoryMappedFile CreateFromFile (FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access,
183 MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability,
186 if (fileStream == null)
187 throw new ArgumentNullException ("fileStream");
188 if (mapName != null && mapName.Length == 0)
189 throw new ArgumentException ("mapName");
190 if ((capacity == 0 && fileStream.Length == 0) || (capacity > fileStream.Length))
191 throw new ArgumentException ("capacity");
194 ConfigureUnixFD (fileStream.Handle, inheritability);
196 ConfigureWindowsFD (fileStream.Handle, inheritability);
198 return new MemoryMappedFile () {
202 fileCapacity = capacity,
207 [MonoLimitation ("CreateNew requires that mapName be a file name on Unix")]
208 public static MemoryMappedFile CreateNew (string mapName, long capacity)
210 return CreateNew (mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, null, 0);
213 [MonoLimitation ("CreateNew requires that mapName be a file name on Unix")]
214 public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access)
216 return CreateNew (mapName, capacity, access, MemoryMappedFileOptions.DelayAllocatePages, null, 0);
219 [MonoLimitation ("CreateNew requires that mapName be a file name on Unix; options and memoryMappedFileSecurity are ignored")]
220 public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access,
221 MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
222 HandleInheritability handleInheritability)
224 return CreateFromFile (mapName, FileMode.CreateNew, mapName, capacity, access);
228 public static MemoryMappedFile CreateOrOpen (string mapName, long capacity) {
229 throw new NotImplementedException ();
233 public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access) {
234 throw new NotImplementedException ();
239 public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability handleInheritability) {
240 throw new NotImplementedException ();
244 public MemoryMappedViewStream CreateViewStream ()
246 return CreateViewStream (0, 0);
249 public MemoryMappedViewStream CreateViewStream (long offset, long size)
251 return CreateViewStream (offset, size, MemoryMappedFileAccess.ReadWrite);
254 public MemoryMappedViewStream CreateViewStream (long offset, long size, MemoryMappedFileAccess access)
256 return new MemoryMappedViewStream (stream != null ? (int)stream.Handle : unix_fd, offset, size, access);
259 public MemoryMappedViewAccessor CreateViewAccessor ()
261 return CreateViewAccessor (0, 0);
264 public MemoryMappedViewAccessor CreateViewAccessor (long offset, long size)
266 return CreateViewAccessor (offset, size, MemoryMappedFileAccess.ReadWrite);
269 public MemoryMappedViewAccessor CreateViewAccessor (long offset, long size, MemoryMappedFileAccess access)
271 int file_handle = stream != null ? (int) stream.Handle : unix_fd;
273 return new MemoryMappedViewAccessor (file_handle, offset, size, access);
280 public void Dispose ()
285 protected virtual void Dispose (bool disposing)
289 if (keepOpen == false)
294 Syscall.close (unix_fd);
301 public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle {
303 throw new NotImplementedException ();
309 static MmapProts ToUnixProts (MemoryMappedFileAccess access)
314 case MemoryMappedFileAccess.ReadWrite:
315 return MmapProts.PROT_WRITE | MmapProts.PROT_READ;
318 case MemoryMappedFileAccess.Write:
319 return MmapProts.PROT_WRITE;
321 case MemoryMappedFileAccess.CopyOnWrite:
322 return MmapProts.PROT_WRITE | MmapProts.PROT_READ;
324 case MemoryMappedFileAccess.ReadExecute:
325 return MmapProts.PROT_EXEC;
327 case MemoryMappedFileAccess.ReadWriteExecute:
328 return MmapProts.PROT_WRITE | MmapProts.PROT_READ | MmapProts.PROT_EXEC;
330 case MemoryMappedFileAccess.Read:
332 return MmapProts.PROT_READ;
336 internal static unsafe void MapPosix (int file_handle, long offset, long size, MemoryMappedFileAccess access, out IntPtr map_addr, out int offset_diff)
339 pagesize = Syscall.getpagesize ();
342 Syscall.fstat (file_handle, out buf);
343 long fsize = buf.st_size;
345 if (size == 0 || size > fsize)
349 long real_offset = offset & ~(pagesize - 1);
351 offset_diff = (int)(offset - real_offset);
353 // FIXME: Need to determine the unix fd for the file, Handle is only
354 // equal to it by accident
356 // The new API no longer uses FileStream everywhere, but exposes instead
357 // the filename (with one exception), we could move this API to use
358 // file descriptors instead of the FileStream plus its Handle.
360 map_addr = Syscall.mmap (IntPtr.Zero, (ulong) size,
361 ToUnixProts (access),
362 access == MemoryMappedFileAccess.CopyOnWrite ? MmapFlags.MAP_PRIVATE : MmapFlags.MAP_SHARED,
363 file_handle, real_offset);
365 if (map_addr == (IntPtr)(-1))
366 throw new IOException ("mmap failed for fd#" + file_handle + "(" + offset + ", " + size + ")");
369 internal static bool UnmapPosix (IntPtr map_addr, ulong map_size)
371 return Syscall.munmap (map_addr, map_size) == 0;