private MemoryMappedView(SafeMemoryMappedViewHandle viewHandle, long pointerOffset, long size, MemoryMappedFileAccess access) { this.m_viewHandle = viewHandle; this.m_pointerOffset = pointerOffset; this.m_size = size; this.m_access = access; }
public MemoryMappedFileMemoryManager(SafeMemoryMappedViewHandle view, int offset, int size) { _view = view; _offset = offset; _size = size; _view.AcquirePointer(ref _pointer); }
protected override void Dispose(bool disposing) { try { if (disposing && _disposeFile) { if (_accessor != null) { _accessor.Dispose(); } if (_buffer != null) { _buffer.Dispose(); } if (_file != null) { _file.Dispose(); } } _accessor = null; _buffer = null; _file = null; } finally { base.Dispose(disposing); } }
public void Close() { //if (PE.IsAttached) //{ // PE.Dettach(); // OnEventNotify(Closed); //} if (smmv != null) { smmv.ReleasePointer(); smmv = null; } if (mmva != null) { // mmva.Dispose(); 会自己析构不用管,下同 mmva = null; } if (mmf != null) { mmf = null; } if (fs != null) { fs.Close(); fs = null; } }
public MemoryMappedFileAccessor(string filePath, long offset, long length, bool writable) { var access = writable ? MemoryMappedFileAccess.ReadWrite : MemoryMappedFileAccess.Read; using (var stream = new FileStream(filePath, FileMode.Open, writable ? FileAccess.ReadWrite : FileAccess.Read, FileShare.ReadWrite)) { _length = stream.Length; if (length > 0) { _length = length; } _file = MemoryMappedFile.CreateFromFile( stream, null, _length, access, null, HandleInheritability.None, false); } _accessor = _file.CreateViewAccessor(offset, _length, access); _buffer = _accessor.SafeMemoryMappedViewHandle; }
internal static MemoryMappedView CreateView(SafeMemoryMappedFileHandle safeMemoryMappedFileHandle, MemoryMappedFileAccess access, long offset, long size) { // http://msdn.microsoft.com/en-us/library/windows/desktop/aa366548(v=vs.85).aspx UnsafeNativeMethods.SYSTEM_INFO info = new UnsafeNativeMethods.SYSTEM_INFO(); UnsafeNativeMethods.GetSystemInfo(ref info); // To calculate where to start the file mapping, round down the // offset of the data into the memory-mapped file to the nearest multiple of the // system allocation granularity. long fileMapStart = (offset / info.dwAllocationGranularity) * info.dwAllocationGranularity; // How large will the file mapping object be? long mapViewSize = (offset % info.dwAllocationGranularity) + size; // The data of interest is not necessarily at the beginning of the // view, so determine how far into the view to set the pointer. long viewDelta = offset - fileMapStart; SafeMemoryMappedViewHandle safeHandle = UnsafeNativeMethods.MapViewOfFile(safeMemoryMappedFileHandle, access.ToMapViewFileAccess(), (ulong)fileMapStart, new UIntPtr((ulong)mapViewSize)); var lastWin32Error = Marshal.GetLastWin32Error(); if (safeHandle.IsInvalid) { if (lastWin32Error == UnsafeNativeMethods.ERROR_FILE_NOT_FOUND) { throw new FileNotFoundException(); } throw new System.IO.IOException(UnsafeNativeMethods.GetMessage(lastWin32Error)); } return(new MemoryMappedView(safeHandle, viewDelta, size)); }
public FixedSizeDirectFile(string filePath, int size = 4096) { _filePath = filePath; if (size < 0) { throw new ArgumentOutOfRangeException(nameof(size)); } size = ((size - 1) / 4096 + 1) * 4096; _fileStream = new FileStream(_filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, 1, FileOptions.None); var bytesCapacity = checked ((int)Math.Max(_fileStream.Length, size)); _mmf = MemoryMappedFile.CreateFromFile(_fileStream, null, bytesCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true); _va = _mmf.CreateViewAccessor(0, bytesCapacity, MemoryMappedFileAccess.ReadWrite); _vaHandle = _va.SafeMemoryMappedViewHandle; _vaHandle.AcquirePointer(ref _pointer); _size = bytesCapacity; }
public static MemoryMapping Create(string path) { MemoryMappedFile file = null; MemoryMappedViewAccessor accessor = null; SafeMemoryMappedViewHandle handle = null; MemoryMapping mapping = null; FileStream stream = null; byte * ptr = null; try { stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite); file = MemoryMappedFile.CreateFromFile(stream, null, 0, MemoryMappedFileAccess.Read, null, HandleInheritability.None, true); accessor = file.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); mapping = new MemoryMapping(); // we need to make sure that the handle and the acquired pointer get stored to MemoryMapping: RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { handle = accessor.SafeMemoryMappedViewHandle; handle.AcquirePointer(ref ptr); if (ptr == null) { throw new IOException("Cannot create a file mapping"); } mapping._handle = handle; mapping._pointer = ptr; mapping._capacity = accessor.Capacity; } } finally { stream?.Dispose(); accessor?.Dispose(); file?.Dispose(); } return(mapping); }
private unsafe MemoryMappedView(SafeMemoryMappedViewHandle viewHandle, Int64 pointerOffset, Int64 size, MemoryMappedFileAccess access) { m_viewHandle = viewHandle; m_pointerOffset = pointerOffset; m_size = size; m_access = access; }
private unsafe MemoryMappedView(SafeMemoryMappedViewHandle viewHandle, long pointerOffset, long size, MemoryMappedFileAccess access) { _viewHandle = viewHandle; _pointerOffset = pointerOffset; _size = size; _access = access; }
void Dispose(bool disposeManagedResources) { if (this._handle != null && !this._handle.IsClosed) { this._handle.Dispose(); } this._handle = null; }
unsafe void Create(long offset, long size, MemoryMappedFileAccess access) { int offset_diff; MemoryMapImpl.Map(file_handle, offset, ref size, access, out mmap_addr, out offset_diff); handle = new SafeMemoryMappedViewHandle((IntPtr)((long)mmap_addr + offset_diff), size); Initialize(handle, 0, size, ToFileAccess(access)); }
private MemoryMappedView(SafeMemoryMappedViewHandle viewHandle, long pointerOffset, long size, MemoryMappedFileAccess access) { Debug.Assert(viewHandle != null); _viewHandle = viewHandle; _pointerOffset = pointerOffset; _size = size; _access = access; }
unsafe void Create(IntPtr handle, long offset, long size, MemoryMappedFileAccess access) { IntPtr base_address; MemoryMapImpl.Map(handle, offset, ref size, access, out mmap_handle, out base_address); safe_handle = new SafeMemoryMappedViewHandle(mmap_handle, base_address, size); Initialize(safe_handle, 0, size, ToFileAccess(access)); }
private Win32MemoryMappedFile(FileStream fs, SafeMemoryMappedFileHandle handle, ulong size) { Contract.Requires(fs != null && handle != null && !handle.IsInvalid && !handle.IsClosed); m_mapHandle = handle; m_file = fs; m_size = size; // verify that it fits on 32 bit OS... if (IntPtr.Size == 4 && size > uint.MaxValue) { // won't work with 32-bit pointers throw new InvalidOperationException("Memory mapped file size is too big to be opened on a 32-bit system."); } // verifiy that it will fit in the virtual address space of the process var totalVirtual = UnsafeNativeMethods.GetTotalVirtualAddressSpaceSize(); if (size > totalVirtual) { throw new InvalidOperationException("Memory mapped file size is too big to fit in the current process virtual address space"); } SafeMemoryMappedViewHandle view = null; byte *baseAddress = null; try { view = UnsafeNativeMethods.MapViewOfFile(m_mapHandle, UnsafeNativeMethods.FileMapAccess.FileMapRead, 0, 0, new UIntPtr(size)); if (view.IsInvalid) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } view.Initialize(size); m_viewHandle = view; view.AcquirePointer(ref baseAddress); m_baseAddress = baseAddress; } catch { if (baseAddress != null) { view.ReleasePointer(); } if (view != null) { view.Dispose(); } m_file = null; m_viewHandle = null; m_mapHandle = null; m_baseAddress = null; throw; } }
public GlobalMemoryMappedFile(string name, int size) { this.size = size; var secAttribs = CreateSecAttribs(); try { memBuffer = NativeMethods.CreateFileMapping( new IntPtr(-1), ref secAttribs, (int)NativeMethods.PageOptions.PAGE_READWRITE, 0, size, name); if (memBuffer.IsInvalid) { //Console.WriteLine(memBuffer.DangerousGetHandle()); int lasterror = Marshal.GetLastWin32Error(); memBuffer.Dispose(); if (lasterror == 5) { throw new IOException("Access denied!"); } memBuffer = NativeMethods.OpenFileMapping((int)NativeMethods.FileMapOptions.Full, false, name); } if (memBuffer.IsInvalid) { int lasterror = Marshal.GetLastWin32Error(); memBuffer.Dispose(); throw new Win32Exception(lasterror, string.Format(CultureInfo.InvariantCulture, "Error creating shared memory. Errorcode is {0}", lasterror)); } accessor = NativeMethods.MapViewOfFile(memBuffer, (uint)NativeMethods.ViewAccess.FILE_MAP_ALL_ACCESS, 0, 0, (uint)size); accessor.Initialize((uint)size); if (accessor.IsInvalid) { accessor.Dispose(); memBuffer.Dispose(); int lasterror = Marshal.GetLastWin32Error(); throw new Win32Exception((int)lasterror, string.Format(CultureInfo.InvariantCulture, "Error creating shared memory view. Errorcode is {0}", lasterror)); } } finally { NativeMethods.SecHelper.Destroy(secAttribs); } }
internal static MemoryMappedView CreateView(SafeMemoryMappedFileHandle memMappedFileHandle, MemoryMappedFileAccess access, long offset, long size) { ulong num3; ulong num = (ulong)(offset % ((long)MemoryMappedFile.GetSystemPageAllocationGranularity())); ulong num2 = ((ulong)offset) - num; if (size != 0L) { num3 = ((ulong)size) + num; } else { num3 = 0L; } if ((IntPtr.Size == 4) && (num3 > 0xffffffffL)) { throw new ArgumentOutOfRangeException("size", System.SR.GetString("ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed")); } Microsoft.Win32.UnsafeNativeMethods.MEMORYSTATUSEX lpBuffer = new Microsoft.Win32.UnsafeNativeMethods.MEMORYSTATUSEX(); Microsoft.Win32.UnsafeNativeMethods.GlobalMemoryStatusEx(lpBuffer); ulong ullTotalVirtual = lpBuffer.ullTotalVirtual; if (num3 >= ullTotalVirtual) { throw new IOException(System.SR.GetString("IO_NotEnoughMemory")); } uint dwFileOffsetLow = (uint)(num2 & 0xffffffffL); uint dwFileOffsetHigh = (uint)(num2 >> 0x20); SafeMemoryMappedViewHandle address = Microsoft.Win32.UnsafeNativeMethods.MapViewOfFile(memMappedFileHandle, MemoryMappedFile.GetFileMapAccess(access), dwFileOffsetHigh, dwFileOffsetLow, new UIntPtr(num3)); if (address.IsInvalid) { System.IO.__Error.WinIOError(Marshal.GetLastWin32Error(), string.Empty); } Microsoft.Win32.UnsafeNativeMethods.MEMORY_BASIC_INFORMATION buffer = new Microsoft.Win32.UnsafeNativeMethods.MEMORY_BASIC_INFORMATION(); Microsoft.Win32.UnsafeNativeMethods.VirtualQuery(address, ref buffer, (IntPtr)Marshal.SizeOf(buffer)); ulong regionSize = (ulong)buffer.RegionSize; if ((buffer.State & 0x2000) != 0) { Microsoft.Win32.UnsafeNativeMethods.VirtualAlloc(address, (UIntPtr)regionSize, 0x1000, MemoryMappedFile.GetPageAccess(access)); int errorCode = Marshal.GetLastWin32Error(); if (address.IsInvalid) { System.IO.__Error.WinIOError(errorCode, string.Empty); } } if (size == 0L) { size = (long)(regionSize - num); } address.Initialize(((ulong)size) + num); return(new MemoryMappedView(address, (long)num, size, access)); }
internal unsafe static MemoryMappedView Create(IntPtr handle, long offset, long size, MemoryMappedFileAccess access) { IntPtr base_address; IntPtr mmap_handle; MemoryMapImpl.Map(handle, offset, ref size, access, out mmap_handle, out base_address); var safe_handle = new SafeMemoryMappedViewHandle(mmap_handle, base_address, size); // MemoryMapImpl.Map returns a base_address to the offset so MemoryMappedView is initiated // no offset. return(new MemoryMappedView(safe_handle, 0, size, access)); }
public MemoryMappedFileAccessor(MemoryMappedViewAccessor accessor, long offset, long length) { if (accessor == null) { throw new ArgumentNullException("accessor"); } _accessor = accessor; _buffer = _accessor.SafeMemoryMappedViewHandle; _origin = offset; _length = length; _disposeFile = false; }
public MemoryMappedFileAccessor(MemoryMappedFileAccessor accessor, long offset, long length) { if (accessor == null) { throw new ArgumentNullException("accessor"); } _origin = accessor._origin + offset; _length = _origin + length; _file = accessor._file; _accessor = accessor._accessor; _buffer = accessor._buffer; _disposeFile = false; }
/// <summary> /// Opens an existing minidump file on the specified path. /// </summary> /// <param name="path">The file to open.</param> /// <returns></returns> public static MiniDumpFile OpenExisting(string path) { MemoryMappedFile minidumpMappedFile = null; SafeMemoryMappedViewHandle mappedFileView = null; // MemoryMappedFile will close the FileStream when it gets Disposed. FileStream fileStream = File.Open(path, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read); try { minidumpMappedFile = MemoryMappedFile.CreateFromFile(fileStream, Path.GetFileName(path), 0, MemoryMappedFileAccess.Read, null, HandleInheritability.None, false); mappedFileView = NativeMethods.MapViewOfFile(minidumpMappedFile.SafeMemoryMappedFileHandle, NativeMethods.FILE_MAP_READ, 0, 0, IntPtr.Zero); if (mappedFileView.IsInvalid) { throw new Win32Exception(Marshal.GetLastWin32Error()); } MEMORY_BASIC_INFORMATION memoryInformation = default(MEMORY_BASIC_INFORMATION); if (NativeMethods.VirtualQuery(mappedFileView, ref memoryInformation, (IntPtr)Marshal.SizeOf(memoryInformation)) == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); } mappedFileView.Initialize((ulong)memoryInformation.RegionSize); } catch { // Cleanup whatever didn't work and rethrow if ((minidumpMappedFile != null) && (!mappedFileView.IsInvalid)) { minidumpMappedFile.Dispose(); } if ((mappedFileView != null) && (!mappedFileView.IsInvalid)) { mappedFileView.Dispose(); } if (minidumpMappedFile == null) { fileStream?.Close(); } throw; } return(new MiniDumpFile(minidumpMappedFile, mappedFileView)); }
void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { mm?.Dispose(); va?.Dispose(); } mma?.Dispose(); mma = null; disposedValue = true; } }
unsafe void CreatePosix(FileStream file, long offset, long size, MemoryMappedFileAccess access) { long fsize = file.Length; if (size == 0 || size > fsize) { size = fsize; } int offset_diff; MemoryMappedFile.MapPosix(file, offset, size, access, out mmap_addr, out offset_diff, out mmap_size); handle = new SafeMemoryMappedViewHandle((IntPtr)((long)mmap_addr + offset_diff), size); }
public MemoryMappedFileMemory(long size) { _memoryMappedFile = MemoryMappedFile.CreateNew(null, size, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); _memoryMappedViewAccessor = _memoryMappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.ReadWrite); _dataOffset = _memoryMappedViewAccessor.PointerOffset; _dataLength = size; var handle = _memoryMappedViewAccessor.SafeMemoryMappedViewHandle; bool success = false; handle.DangerousAddRef(ref success); _buffer = handle; }
/* Note that the SafeMemoryMappedViewHandle property of SafeMemoryMappedViewAccess and SafeMemoryMappedViewStream * is actually the address where the file is mapped */ private static string GetPathWithGetMappedFileName(SafeMemoryMappedViewHandle memoryMappedViewHandle) { // The maximum path length in the NT kernel is 32,767 - memory is cheap nowadays so its not a problem // to just allocate the maximum size of 32KB right away. StringBuilder filename = new StringBuilder(short.MaxValue); int len; len = GetMappedFileName(Process.GetCurrentProcess().SafeHandle, memoryMappedViewHandle, filename, short.MaxValue); if (len == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } filename.Length = len; return(filename.ToString()); }
public void HandleClosedOnDisposal() { foreach (MemoryMappedFile mmf in CreateSampleMaps()) { using (mmf) { MemoryMappedViewStream s = mmf.CreateViewStream(); SafeMemoryMappedViewHandle handle = s.SafeMemoryMappedViewHandle; Assert.False(handle.IsClosed); s.Dispose(); Assert.True(handle.IsClosed); } } }
public DirectFile(string filePath, long minCapacity = 0, bool isWritable = false, FileOptions fileOptions = FileOptions.None, bool sparse = false) { if (!isWritable && !File.Exists(filePath)) { ThrowHelper.ThrowArgumentException($"File {filePath} does not exists."); } _filePath = filePath; _isWritable = isWritable; _fileOptions = fileOptions; _mmf = null; _va = null; _fileStream = null; _vaHandle = default; // ReSharper disable once ExpressionIsAlwaysNull Grow(minCapacity, sparse); }
public ReadOnlySpan <byte> ReadSpan() { va = mm.CreateViewStream(); mma = va.SafeMemoryMappedViewHandle; ReadOnlySpan <byte> bytes; unsafe { byte *ptrMemMap = (byte *)0; mma.AcquirePointer(ref ptrMemMap); bytes = new ReadOnlySpan <byte>(ptrMemMap, (int)mma.ByteLength); mma.ReleasePointer(); } return(bytes); }
public override unsafe int Read(TiffStreamOffset offset, Memory <byte> buffer) { MemoryMappedFile?file = Volatile.Read(ref _file); if (file is null) { throw new ObjectDisposedException(nameof(ContentReader)); } if (offset.Offset + buffer.Length > _capacity) { buffer = buffer.Slice(0, Math.Max(0, (int)(_capacity - offset.Offset))); } if (buffer.IsEmpty) { return(0); } using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor(offset, 0, MemoryMappedFileAccess.Read)) { byte *pointer = null; SafeMemoryMappedViewHandle handle = accessor.SafeMemoryMappedViewHandle; #if !NETSTANDARD1_3 System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { handle.AcquirePointer(ref pointer); if (pointer != null) { new Span <byte>(pointer + accessor.PointerOffset, buffer.Length).CopyTo(buffer.Span); } return(buffer.Length); } finally { if (pointer != null) { handle.ReleasePointer(); } } } }
public bool runTest() { try { // pagefile backed using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 100)) { using (MemoryMappedViewAccessor viewAccessor = mmf.CreateViewAccessor()) { _iCountTestcases++; SafeMemoryMappedViewHandle handle = viewAccessor.SafeMemoryMappedViewHandle; } } // file backed String fileText = "Non-empty file for MMF testing."; File.WriteAllText("test2.txt", fileText); using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("test2.txt", FileMode.Open)) { using (MemoryMappedViewAccessor viewAccessor = mmf.CreateViewAccessor()) { _iCountTestcases++; SafeMemoryMappedViewHandle handle = viewAccessor.SafeMemoryMappedViewHandle; } } /// END TEST CASES if (_iCountErrors == 0) { return(true); } else { Console.WriteLine("Fail! iCountErrors==" + _iCountErrors); return(false); } } catch (Exception ex) { Console.WriteLine("ERR999: Unexpected exception in runTest, {0}", ex); return(false); } }