/// <summary>Initializes the memory-mapped file handle.</summary> /// <param name="fileStream">The underlying file stream; may be null.</param> /// <param name="ownsFileStream">Whether this SafeHandle is responsible for Disposing the fileStream.</param> /// <param name="inheritability">The inheritability of the memory-mapped file.</param> /// <param name="access">The access for the memory-mapped file.</param> /// <param name="options">The options for the memory-mapped file.</param> /// <param name="capacity">The capacity of the memory-mapped file.</param> internal SafeMemoryMappedFileHandle( FileStream?fileStream, bool ownsFileStream, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) : base(ownsHandle: true) { Debug.Assert(!ownsFileStream || fileStream != null, "We can only own a FileStream we're actually given."); // Store the arguments. We'll actually open the map when the view is created. _fileStream = fileStream; _ownsFileStream = ownsFileStream; _inheritability = inheritability; _access = access; _options = options; _capacity = capacity; IntPtr handlePtr; if (fileStream != null) { bool ignored = false; SafeFileHandle handle = fileStream.SafeFileHandle; handle.DangerousAddRef(ref ignored); _fileStreamHandle = handle; handlePtr = handle.DangerousGetHandle(); } else { handlePtr = IntPtr.MaxValue; } SetHandle(handlePtr); }
public void ValidArgumentCombinations_Execute( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { // Map doesn't exist using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } // Map does exist (CreateNew) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf2, capacity, access, inheritability); } // (Avoid testing with CreateFromFile when using execute permissions.) }
private static SafeMemoryMappedFileHandle CreateCore( SafeFileHandle fileHandle, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); // split the long into two ints int capacityLow = unchecked ((int)(capacity & 0x00000000FFFFFFFFL)); int capacityHigh = unchecked ((int)(capacity >> 32)); SafeMemoryMappedFileHandle handle = fileHandle != null? Interop.mincore.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName) : Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); int errorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { if (errorCode == Interop.mincore.Errors.ERROR_ALREADY_EXISTS) { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } else if (handle.IsInvalid) { throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return(handle); }
/// <summary> /// Used by the 2 Create factory method groups. A null fileHandle specifies that the /// memory mapped file should not be associated with an existing file on disk (i.e. start /// out empty). /// </summary> private static SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null; Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); SafeMemoryMappedFileHandle handle = fileHandle != null? Interop.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName) : Interop.CreateFileMapping(new IntPtr(-1), ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName); int errorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { if (errorCode == Interop.Errors.ERROR_ALREADY_EXISTS) { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } else // handle.IsInvalid { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return(handle); }
private static SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null; Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); SafeMemoryMappedFileHandle handle = fileHandle != null ? Interop.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName) : Interop.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName); int errorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { if (errorCode == Interop.Errors.ERROR_ALREADY_EXISTS) { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } else // handle.IsInvalid { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return handle; }
/// <summary> /// Used by the 2 Create factory method groups. A null fileHandle specifies that the /// memory mapped file should not be associated with an existing file on disk (i.e. start /// out empty). /// </summary> private static SafeMemoryMappedFileHandle CreateCore( SafeFileHandle?fileHandle, string?mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity, long fileSize) { Debug.Assert(fileHandle is null || fileSize >= 0); Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); if (fileHandle != null) { VerifyMemoryMappedFileAccess(access, capacity, fileSize); } SafeMemoryMappedFileHandle handle = fileHandle != null? Interop.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName) : Interop.CreateFileMapping(new IntPtr(-1), ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName); int errorCode = Marshal.GetLastPInvokeError(); if (!handle.IsInvalid) { if (errorCode == Interop.Errors.ERROR_ALREADY_EXISTS) { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } else // handle.IsInvalid { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return(handle); }
private static unsafe SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { if (mapName != null) { // Named maps are not supported in our Unix implementation. We could support named maps on Linux using // shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due // to very low default limits on OSX for the size of such objects; it also doesn't support behaviors // like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up // relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've // been marked for deletion (IPC_RMID). We could also support named maps using the current implementation // by not unlinking after creating the backing store, but then the backing stores would remain around // and accessible even after process exit, with no good way to appropriately clean them up. // (File-backed maps may still be used for cross-process communication.) throw CreateNamedMapsNotSupportedException(); } bool ownsFileStream = false; if (fileStream != null) { // This map is backed by a file. Make sure the file's size is increased to be // at least as big as the requested capacity of the map. if (fileStream.Length < capacity) { try { fileStream.SetLength(capacity); } catch (ArgumentException exc) { // If the capacity is too large, we'll get an ArgumentException from SetLength, // but on Windows this same condition is represented by an IOException. throw new IOException(exc.Message, exc); } } } else { // This map is backed by memory-only. With files, multiple views over the same map // will end up being able to share data through the same file-based backing store; // for anonymous maps, we need a similar backing store, or else multiple views would logically // each be their own map and wouldn't share any data. To achieve this, we create a backing object // (either memory or on disk, depending on the system) and use its file descriptor as the file handle. // However, we only do this when the permission is more than read-only. We can't change the size // of an object that has read-only permissions, but we also don't need to worry about sharing // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views // will always see zero and can't change that. In that case, we just use the built-in anonymous support of // the map by leaving fileStream as null. Interop.libc.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false); if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0) { ownsFileStream = true; fileStream = CreateSharedBackingObject(protections, capacity); } } return new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity); }
private static SafeMemoryMappedFileHandle CreateCore( SafeFileHandle fileHandle, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { Interop.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); // split the long into two ints int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL)); int capacityHigh = unchecked((int)(capacity >> 32)); SafeMemoryMappedFileHandle handle = fileHandle != null ? Interop.mincore.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName) : Interop.mincore.CreateFileMapping(Interop.INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); int errorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { if (errorCode == Interop.ERROR_ALREADY_EXISTS) { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } else if (handle.IsInvalid) { throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return handle; }
private static unsafe SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { if (mapName != null) { // TODO: We currently do not support named maps. We could possibly support // named maps in the future by using shm_open / shm_unlink. throw CreateNamedMapsNotSupportedException(); } SafeFileHandle fileHandle = null; if (fileStream != null) { fileHandle = fileStream.SafeFileHandle; if (fileStream.Length < capacity) { fileStream.SetLength(capacity); } } return(new SafeMemoryMappedFileHandle(fileHandle, inheritability, access, options, capacity)); }
public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) #endif { return(CreateFromFile(mapName, FileMode.CreateNew, mapName, capacity, access)); }
private static SafeMemoryMappedFileHandle CreateOrOpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { // Since we don't support mapName != null, CreateOrOpenCore can't // be used to Open an existing map, and thus is identical to CreateCore. return CreateCore(null, mapName, inheritability, access, options, capacity); }
private static SafeMemoryMappedFileHandle CreateOrOpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { // Since we don't support mapName != null, CreateOrOpenCore can't // be used to Open an existing map, and thus is identical to CreateCore. return(CreateCore(null, mapName, inheritability, access, options, capacity)); }
public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.GetString(SR.ArgumentNull_MapName)); } if (mapName.Length == 0) { throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString)); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_NeedPositiveNumber)); } if (IntPtr.Size == 4 && capacity > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed)); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle; // special case for write access; create will never succeed if (access == MemoryMappedFileAccess.Write) { handle = OpenCore(mapName, inheritability, GetFileMapAccess(access), true); } else { handle = CreateOrOpenCore(new SafeFileHandle(new IntPtr(-1), true), mapName, inheritability, memoryMappedFileSecurity, access, options, capacity); } return(new MemoryMappedFile(handle)); }
public IMemoryMappedFile CreateOrOpen( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) { return new MemoryMappedFileWrapper(MemoryMappedFile.CreateOrOpen( mapName, capacity, access, options, memoryMappedFileSecurity, inheritability)); }
public IMemoryMappedFile CreateOrOpen( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) { return(new MemoryMappedFileWrapper(MemoryMappedFile.CreateOrOpen( mapName, capacity, access, options, memoryMappedFileSecurity, inheritability))); }
public void CreateOrOpen(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { instance = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability); this.mapName = mapName; this.capacity = capacity; this.access = access; this.options = options; this.inheritability = inheritability; ci = CreateInstance.CreateOrOpen; ni = 2; }
private static unsafe SafeMemoryMappedFileHandle CreateCore( SafeFileHandle fileHandle, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { if (mapName != null) { throw CreateNamedMapsNotSupportedException(); } return new SafeMemoryMappedFileHandle(fileHandle, inheritability, access, options, capacity); }
public static MemoryMappedFile CreateOrOpen(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException(nameof(mapName), SR.ArgumentNull_MapName); } if (mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > uint.MaxValue) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException(nameof(access)); } //if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) //{ // throw new ArgumentOutOfRangeException(nameof(options)); //} if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException(nameof(inheritability)); } SafeMemoryMappedFileHandle handle; // special case for write access; create will never succeed if (access == MemoryMappedFileAccess.Write) { handle = OpenCore(mapName, inheritability, access, true); } else { handle = CreateOrOpenCore(mapName, inheritability, access, options, capacity); } return(new MemoryMappedFile(handle)); }
private static unsafe SafeMemoryMappedFileHandle CreateCore( SafeFileHandle fileHandle, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { if (mapName != null) { throw CreateNamedMapsNotSupportedException(); } return(new SafeMemoryMappedFileHandle(fileHandle, inheritability, access, options, capacity)); }
private static unsafe SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { if (mapName != null) { // Named maps are not supported in our Unix implementation. We could support named maps on Linux using // shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due // to very low default limits on OSX for the size of such objects; it also doesn't support behaviors // like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up // relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've // been marked for deletion (IPC_RMID). We could also support named maps using the current implementation // by not unlinking after creating the backing store, but then the backing stores would remain around // and accessible even after process exit, with no good way to appropriately clean them up. // (File-backed maps may still be used for cross-process communication.) throw CreateNamedMapsNotSupportedException(); } bool ownsFileStream = false; if (fileStream != null) { // This map is backed by a file. Make sure the file's size is increased to be // at least as big as the requested capacity of the map. if (fileStream.Length < capacity) { fileStream.SetLength(capacity); } } else { // This map is backed by memory-only. With files, multiple views over the same map // will end up being able to share data through the same file-based backing store; // for anonymous maps, we need a similar backing store, or else multiple views would logically // each be their own map and wouldn't share any data. To achieve this, we create a backing object // (either memory or on disk, depending on the system) and use its file descriptor as the file handle. // However, we only do this when the permission is more than read-only. We can't change the size // of an object that has read-only permissions, but we also don't need to worry about sharing // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views // will always see zero and can't change that. In that case, we just use the built-in anonymous support of // the map by leaving fileStream as null. Interop.libc.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false); if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0) { ownsFileStream = true; fileStream = CreateSharedBackingObject(protections, capacity); } } return(new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity)); }
private static unsafe SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { if (mapName != null) { // TODO: We currently do not support named maps. We could possibly support // named maps in the future by using shm_open / shm_unlink, as we do for // giving internal names to anonymous maps. Issues to work through will include // dealing with permissions, passing information from the creator of the // map to another opener of it, etc. throw CreateNamedMapsNotSupportedException(); } SafeFileHandle fileHandle = null; if (fileStream != null) { // This map is backed by a file. Make sure the file's size is increased to be // at least as big as the requested capacity of the map. fileHandle = fileStream.SafeFileHandle; if (fileStream.Length < capacity) { fileStream.SetLength(capacity); } } else { // This map is backed by memory-only. With files, multiple views over the same map // will end up being able to share data through the same file-based backing store; // for anonymous maps, we need a similar backing store, or else multiple views would logically // each be their own map and wouldn't share any data. To achieve this, we create a POSIX shared // memory object and use its file descriptor as the file handle. However, we only do this when the // permission is more than read-only. We can't ftruncate to increase the size of a shared memory // object that has read-only permissions, but we also don't need to worry about sharing // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views // will always see zero and can't change that. In that case, we just use the built-in anonymous support of // the map by leaving fileHandle as null. Interop.libc.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false); if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0) { mapName = "/AnonCoreFxMemMap_" + Guid.NewGuid().ToString("N"); // unique name must start with "/" and be < NAME_MAX length fileHandle = CreateNewSharedMemoryObject(mapName, protections, capacity); } } return(new SafeMemoryMappedFileHandle(mapName, fileHandle, inheritability, access, options, capacity)); }
public void ValidArgumentCombinations_NonExecute( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { // Map doesn't exist using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } // Map does exist (CreateNew) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { ValidateMemoryMappedFile(mmf2, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf2, capacity, access, inheritability); } // Map does exist (CreateFromFile) using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { ValidateMemoryMappedFile(mmf2, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } }
public void ValidArgumentCombinations( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } }
/// <summary>Initializes the memory-mapped file handle.</summary> /// <param name="fileHandle">The underlying file handle; this may be null in the case of a page-file backed memory-mapped file.</param> /// <param name="inheritability">The inheritability of the memory-mapped file.</param> /// <param name="access">The access for the memory-mapped file.</param> /// <param name="options">The options for the memory-mapped file.</param> /// <param name="capacity">The capacity of the memory-mapped file.</param> internal SafeMemoryMappedFileHandle( SafeFileHandle fileHandle, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) : base(new IntPtr(-1), ownsHandle: true) { // Store the arguments. We'll actually open the map when the view is created. _fileHandle = fileHandle; _inheritability = inheritability; _access = access; _options = options; _capacity = capacity; // Fake a unique int handle value > 0. int nextHandleValue = (int)((Interlocked.Increment(ref s_counter) % (int.MaxValue - 1)) + 1); SetHandle(new IntPtr(nextHandleValue)); }
private static unsafe SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { if (mapName != null) { // TODO: We currently do not support named maps. We could possibly support // named maps in the future by using shm_open / shm_unlink, as we do for // giving internal names to anonymous maps. Issues to work through will include // dealing with permissions, passing information from the creator of the // map to another opener of it, etc. throw CreateNamedMapsNotSupportedException(); } var fileStreamSource = SafeMemoryMappedFileHandle.FileStreamSource.Provided; if (fileStream != null) { // This map is backed by a file. Make sure the file's size is increased to be // at least as big as the requested capacity of the map. if (fileStream.Length < capacity) { fileStream.SetLength(capacity); } } else { // This map is backed by memory-only. With files, multiple views over the same map // will end up being able to share data through the same file-based backing store; // for anonymous maps, we need a similar backing store, or else multiple views would logically // each be their own map and wouldn't share any data. To achieve this, we create a backing object // (either memory or on disk, depending on the system) and use its file descriptor as the file handle. // However, we only do this when the permission is more than read-only. We can't change the size // of an object that has read-only permissions, but we also don't need to worry about sharing // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views // will always see zero and can't change that. In that case, we just use the built-in anonymous support of // the map by leaving fileHandle as null. Interop.libc.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false); if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0) { fileStream = CreateSharedBackingObject(protections, capacity, out mapName, out fileStreamSource); } } return new SafeMemoryMappedFileHandle(mapName, fileStream, fileStreamSource, inheritability, access, options, capacity); }
public static MemoryMappedFile CreateNew(String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) { if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString)); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_NeedPositiveNumber)); } if (IntPtr.Size == 4 && capacity > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed)); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle = CreateCore(new SafeFileHandle(new IntPtr(-1), true), mapName, inheritability, memoryMappedFileSecurity, access, options, capacity); return(new MemoryMappedFile(handle)); }
public static MemoryMappedFile CreateNew(string?mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > uint.MaxValue) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException(nameof(access)); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, nameof(access)); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException(nameof(options)); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException(nameof(inheritability)); } SafeMemoryMappedFileHandle handle = CreateCore(null, mapName, inheritability, access, options, capacity); return(new MemoryMappedFile(handle)); }
/// <summary>Initializes the memory-mapped file handle.</summary> /// <param name="fileStream">The underlying file stream; may be null.</param> /// <param name="ownsFileStream">Whether this SafeHandle is responsible for Disposing the fileStream.</param> /// <param name="inheritability">The inheritability of the memory-mapped file.</param> /// <param name="access">The access for the memory-mapped file.</param> /// <param name="options">The options for the memory-mapped file.</param> /// <param name="capacity">The capacity of the memory-mapped file.</param> internal SafeMemoryMappedFileHandle( FileStream fileStream, bool ownsFileStream, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) : base(new IntPtr(-1), ownsHandle: true) { Debug.Assert(!ownsFileStream || fileStream != null, "We can only own a FileStream we're actually given."); // Store the arguments. We'll actually open the map when the view is created. _fileStream = fileStream; _ownsFileStream = ownsFileStream; _inheritability = inheritability; _access = access; _options = options; _capacity = capacity; // Fake a unique int handle value > 0. int nextHandleValue = (int)((Interlocked.Increment(ref s_counter) % (int.MaxValue - 1)) + 1); SetHandle(new IntPtr(nextHandleValue)); }
public void ValidArgumentCombinations_Execute( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { AssertExtensions.ThrowsIf <UnauthorizedAccessException>(PlatformDetection.IsWinRT && (access == MemoryMappedFileAccess.ReadExecute || access == MemoryMappedFileAccess.ReadWriteExecute), () => { // Map doesn't exist using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } }); AssertExtensions.ThrowsIf <UnauthorizedAccessException>(PlatformDetection.IsWinRT && (access == MemoryMappedFileAccess.ReadExecute || access == MemoryMappedFileAccess.ReadWriteExecute), () => { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } }); AssertExtensions.ThrowsIf <UnauthorizedAccessException>(PlatformDetection.IsWinRT && (access == MemoryMappedFileAccess.ReadExecute || access == MemoryMappedFileAccess.ReadWriteExecute), () => { // Map does exist (CreateNew) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } }); AssertExtensions.ThrowsIf <UnauthorizedAccessException>(PlatformDetection.IsWinRT && (access == MemoryMappedFileAccess.ReadExecute || access == MemoryMappedFileAccess.ReadWriteExecute), () => { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf2, capacity, access, inheritability); } }); // (Avoid testing with CreateFromFile when using execute permissions.) }
static MemoryMappedFile CoreShmCreate(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability, FileMode mode) { if (mapName != null && mapName.Length == 0) { throw new ArgumentException("mapName"); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity"); } IntPtr handle = MemoryMapImpl.OpenFile(null, mode, mapName, out capacity, access, options); return(new MemoryMappedFile() { handle = handle, // fileAccess = access, // name = mapName, // fileCapacity = capacity }); }
private static SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null; Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); // split the long into two ints int capacityLow = unchecked ((int)(capacity & 0x00000000FFFFFFFFL)); int capacityHigh = unchecked ((int)(capacity >> 32)); SafeMemoryMappedFileHandle handle = fileHandle != null? Interop.mincore.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName) : Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); int errorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { // If the object exists before the function call, the function // returns a handle to the existing object (with its current size, // not the specified size), and GetLastError returns ERROR_ALREADY_EXISTS. if (errorCode == Interop.mincore.Errors.ERROR_ALREADY_EXISTS) { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } else // handle.IsInvalid { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return(handle); }
public void ValidArgumentCombinations( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } AssertExtensions.ThrowsIf <UnauthorizedAccessException>(PlatformDetection.IsWinRT && (access == MemoryMappedFileAccess.ReadExecute || access == MemoryMappedFileAccess.ReadWriteExecute), () => { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } }); AssertExtensions.ThrowsIf <UnauthorizedAccessException>(PlatformDetection.IsWinRT && (access == MemoryMappedFileAccess.ReadExecute || access == MemoryMappedFileAccess.ReadWriteExecute), () => { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } }); }
public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) #endif { throw new NotImplementedException (); }
public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability)
public void InvalidArgument_Options(MemoryMappedFileOptions options) { Assert.Throws<ArgumentOutOfRangeException>("options", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, options, HandleInheritability.None)); }
private static SafeMemoryMappedFileHandle CreateOrOpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { /// Try to open the file if it exists -- this requires a bit more work. Loop until we can /// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail /// if the file exists and we have non-null security attributes, in which case we need to /// use OpenFileMapping. But, there exists a race condition because the memory mapped file /// may have closed between the two calls -- hence the loop. /// /// The retry/timeout logic increases the wait time each pass through the loop and times /// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened, /// throw an InvalidOperationException. Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf"); SafeMemoryMappedFileHandle handle = null; Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // keep looping until we've exhausted retries or break as soon we get valid handle while (waitRetries > 0) { // try to create handle = Interop.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName); if (!handle.IsInvalid) { break; } else { handle.Dispose(); int createErrorCode = Marshal.GetLastWin32Error(); if (createErrorCode != Interop.Errors.ERROR_ACCESS_DENIED) { throw Win32Marshal.GetExceptionForWin32Error(createErrorCode); } } // try to open handle = Interop.OpenFileMapping(GetFileMapAccess(access), (inheritability & HandleInheritability.Inheritable) != 0, mapName); // valid handle if (!handle.IsInvalid) { break; } // didn't get valid handle; have to retry else { handle.Dispose(); int openErrorCode = Marshal.GetLastWin32Error(); if (openErrorCode != Interop.Errors.ERROR_FILE_NOT_FOUND) { throw Win32Marshal.GetExceptionForWin32Error(openErrorCode); } // increase wait time --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { ThreadSleep(waitSleep); waitSleep *= 2; } } } // finished retrying but couldn't create or open if (handle == null || handle.IsInvalid) { throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping); } return handle; }
public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) { Contract.Ensures(Contract.Result<System.IO.MemoryMappedFiles.MemoryMappedFile>() != null); return default(MemoryMappedFile); }
public static MemoryMappedFile CreateOrOpen(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability handleInheritability) { throw new NotImplementedException(); }
static MemoryMappedFile CoreShmCreate (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability, FileMode mode) { if (mapName != null && mapName.Length == 0) throw new ArgumentException ("mapName"); if (capacity < 0) throw new ArgumentOutOfRangeException ("capacity"); IntPtr handle = MemoryMapImpl.OpenFile (null, mode, mapName, out capacity, access, options); return new MemoryMappedFile () { handle = handle, fileAccess = access, name = mapName, fileCapacity = capacity }; }
public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) { return CoreShmCreate (mapName, capacity, access, options, memoryMappedFileSecurity, inheritability, FileMode.OpenOrCreate); }
static extern IntPtr OpenFileInternal (string path, FileMode mode, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, out int error);
public void InvalidArgument_Options(MemoryMappedFileOptions options) { AssertExtensions.Throws <ArgumentOutOfRangeException>("options", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, options, HandleInheritability.None)); }
/// <summary> /// Provides input data to the ValidArgumentCombinations tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses">The accesses to yield</param> /// <param name="options">The options to yield.</param> /// <param name="inheritabilities">The inheritabilities to yield.</param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinations( string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, MemoryMappedFileOptions[] options, HandleInheritability[] inheritabilities) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { foreach (MemoryMappedFileOptions option in options) { foreach (HandleInheritability inheritability in inheritabilities) { string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mapName, capacity, access, option, inheritability }; } } } } } }
internal static IntPtr OpenHandle (IntPtr handle, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options) { int error = 0; IntPtr res = OpenHandleInternal (handle, mapName, out capacity, access, options, out error); if (error != 0) throw CreateException (error, "<none>"); return res; }
private static SafeMemoryMappedFileHandle CreateOrOpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { /// Try to open the file if it exists -- this requires a bit more work. Loop until we can /// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail /// if the file exists and we have non-null security attributes, in which case we need to /// use OpenFileMapping. But, there exists a race condition because the memory mapped file /// may have closed between the two calls -- hence the loop. /// /// The retry/timeout logic increases the wait time each pass through the loop and times /// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened, /// throw an InvalidOperationException. Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf"); SafeMemoryMappedFileHandle handle = null; Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); // split the long into two ints int capacityLow = unchecked ((int)(capacity & 0x00000000FFFFFFFFL)); int capacityHigh = unchecked ((int)(capacity >> 32)); int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // keep looping until we've exhausted retries or break as soon we get valid handle while (waitRetries > 0) { // try to create handle = Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); if (!handle.IsInvalid) { break; } else { handle.Dispose(); int createErrorCode = Marshal.GetLastWin32Error(); if (createErrorCode != Interop.mincore.Errors.ERROR_ACCESS_DENIED) { throw Win32Marshal.GetExceptionForWin32Error(createErrorCode); } } // try to open handle = Interop.mincore.OpenFileMapping(GetFileMapAccess(access), (inheritability & HandleInheritability.Inheritable) != 0, mapName); // valid handle if (!handle.IsInvalid) { break; } // didn't get valid handle; have to retry else { handle.Dispose(); int openErrorCode = Marshal.GetLastWin32Error(); if (openErrorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) { throw Win32Marshal.GetExceptionForWin32Error(openErrorCode); } // increase wait time --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { ThreadSleep(waitSleep); waitSleep *= 2; } } } // finished retrying but couldn't create or open if (handle == null || handle.IsInvalid) { throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping); } return(handle); }
public static MemoryMappedFile CreateOrOpen(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.ArgumentNull_MapName); } if (mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > uint.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle; // special case for write access; create will never succeed if (access == MemoryMappedFileAccess.Write) { handle = OpenCore(mapName, inheritability, access, true); } else { handle = CreateOrOpenCore(mapName, inheritability, access, options, capacity); } return new MemoryMappedFile(handle); }
public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > uint.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle = CreateCore(null, mapName, inheritability, access, options, capacity); return new MemoryMappedFile(handle); }
public void VerifyException <EXCTYPE>(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) where EXCTYPE : Exception { iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } }
public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { return CreateNew (mapName, capacity, access, options, null, inheritability); }
public void InvalidArguments_Options(MemoryMappedFileOptions options) { AssertExtensions.Throws <ArgumentOutOfRangeException>("options", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Read, options, HandleInheritability.None)); }
private static SafeMemoryMappedFileHandle CreateOrOpenCore(SafeFileHandle fileHandle, String mapName, HandleInheritability inheritability, MemoryMappedFileSecurity memoryMappedFileSecurity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, Int64 capacity) { Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf"); SafeMemoryMappedFileHandle handle = null; Object pinningHandle; UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, memoryMappedFileSecurity, out pinningHandle); // split the long into two ints Int32 capacityLow = (Int32)(capacity & 0x00000000FFFFFFFFL); Int32 capacityHigh = (Int32)(capacity >> 32); try { int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // keep looping until we've exhausted retries or break as soon we we get valid handle while (waitRetries > 0) { // try to create handle = UnsafeNativeMethods.CreateFileMapping(fileHandle, secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); Int32 createErrorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { break; } else { if (createErrorCode != UnsafeNativeMethods.ERROR_ACCESS_DENIED) { __Error.WinIOError(createErrorCode, String.Empty); } // the mapname exists but our ACL is preventing us from opening it with CreateFileMapping. // Let's try to open it with OpenFileMapping. handle.SetHandleAsInvalid(); } // try to open handle = UnsafeNativeMethods.OpenFileMapping(GetFileMapAccess(access), (inheritability & HandleInheritability.Inheritable) != 0, mapName); Int32 openErrorCode = Marshal.GetLastWin32Error(); // valid handle if (!handle.IsInvalid) { break; } // didn't get valid handle; have to retry else { if (openErrorCode != UnsafeNativeMethods.ERROR_FILE_NOT_FOUND) { __Error.WinIOError(openErrorCode, String.Empty); } // increase wait time --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } } } // finished retrying but couldn't create or open if (handle == null || handle.IsInvalid) { throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_CantCreateFileMapping)); } } finally { if (pinningHandle != null) { GCHandle pinHandle = (GCHandle)pinningHandle; pinHandle.Free(); } } return handle; }
public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability) #endif { return CreateFromFile (mapName, FileMode.CreateNew, mapName, capacity, access); }
static extern IntPtr OpenHandleInternal (IntPtr handle, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, out int error);
internal static IntPtr OpenFile (string path, FileMode mode, string mapName, out long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options) { int error = 0; IntPtr res = OpenFileInternal (path, mode, mapName, out capacity, access, options, out error); if (error != 0) throw CreateException (error, path); return res; }
public void InvalidArguments_Options(MemoryMappedFileOptions options) { Assert.Throws<ArgumentOutOfRangeException>("options", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Read, options, HandleInheritability.None)); }