Ejemplo n.º 1
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_viewHandle.IsClosed)
     {
         _viewHandle.Dispose();
     }
 }
Ejemplo n.º 2
0
 private void Dispose(bool disposing)
 {
     if (!_viewHandle.IsClosed)
     {
         _viewHandle.Dispose();
     }
 }
Ejemplo n.º 3
0
 protected virtual void Dispose(bool disposing)
 {
     if (m_viewHandle != null && !m_viewHandle.IsClosed)
     {
         m_viewHandle.Dispose();
     }
 }
Ejemplo n.º 4
0
        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 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);
            }
        }
        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;
            }
        }
Ejemplo n.º 7
0
        /// <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));
        }
Ejemplo n.º 8
0
        void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    mm?.Dispose();
                    va?.Dispose();
                }
                mma?.Dispose();
                mma = null;

                disposedValue = true;
            }
        }
Ejemplo n.º 9
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                // Free any other managed objects here.
                _mappedFileView.Dispose();
                _mappedFileView = null;

                _minidumpMappedFile.Dispose();
                _minidumpMappedFile = null;
            }

            // Free any unmanaged objects here.

            // All Done
            disposed = true;
        }
Ejemplo n.º 10
0
        public void Dispose()
        {
            if (_disposeFile)
            {
                if (_accessor != null)
                {
                    _accessor.Dispose();
                }

                if (_buffer != null)
                {
                    _buffer.Dispose();
                }

                if (_file != null)
                {
                    _file.Dispose();
                }
            }

            _accessor = null;
            _buffer   = null;
            _file     = null;
        }
        public void Dispose()
        {
            if (!m_disposed)
            {
                m_disposed = true;

                if (m_viewHandle != null)
                {
                    if (m_baseAddress != null)
                    {
                        m_viewHandle.ReleasePointer();
                    }
                    m_viewHandle.Dispose();
                }
                if (m_mapHandle != null)
                {
                    m_mapHandle.Dispose();
                }
                if (m_file != null)
                {
                    m_file.Dispose();
                }
            }
        }
Ejemplo n.º 12
0
        public static unsafe MemoryMappedView CreateView(SafeMemoryMappedFileHandle memMappedFileHandle,
                                                         MemoryMappedFileAccess access, long offset, long size)
        {
            // MapViewOfFile can only create views that start at a multiple of the system memory allocation
            // granularity. We decided to hide this restriction from the user by creating larger views than the
            // user requested and hiding the parts that the user did not request.  extraMemNeeded is the amount of
            // extra memory we allocate before the start of the requested view. MapViewOfFile will also round the
            // capacity of the view to the nearest multiple of the system page size.  Once again, we hide this
            // from the user by preventing them from writing to any memory that they did not request.
            ulong nativeSize;
            long  extraMemNeeded, newOffset;

            ValidateSizeAndOffset(
                size, offset, GetSystemPageAllocationGranularity(),
                out nativeSize, out extraMemNeeded, out newOffset);

            // if request is >= than total virtual, then MapViewOfFile will fail with meaningless error message
            // "the parameter is incorrect"; this provides better error message in advance
            Interop.CheckForAvailableVirtualMemory(nativeSize);

            // create the view
            SafeMemoryMappedViewHandle viewHandle = Interop.MapViewOfFile(memMappedFileHandle,
                                                                          (int)MemoryMappedFile.GetFileMapAccess(access), newOffset, new UIntPtr(nativeSize));

            if (viewHandle.IsInvalid)
            {
                viewHandle.Dispose();
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            // Query the view for its size and allocation type
            Interop.Kernel32.MEMORY_BASIC_INFORMATION viewInfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
            Interop.Kernel32.VirtualQuery(viewHandle, ref viewInfo, (UIntPtr)Marshal.SizeOf(viewInfo));
            ulong viewSize = (ulong)viewInfo.RegionSize;

            // Allocate the pages if we were using the MemoryMappedFileOptions.DelayAllocatePages option
            // OR check if the allocated view size is smaller than the expected native size
            // If multiple overlapping views are created over the file mapping object, the pages in a given region
            // could have different attributes(MEM_RESERVE OR MEM_COMMIT) as MapViewOfFile preserves coherence between
            // views created on a mapping object backed by same file.
            // In which case, the viewSize will be smaller than nativeSize required and viewState could be MEM_COMMIT
            // but more pages may need to be committed in the region.
            // This is because, VirtualQuery function(that internally invokes VirtualQueryEx function) returns the attributes
            // and size of the region of pages with matching attributes starting from base address.
            // VirtualQueryEx: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366907(v=vs.85).aspx
            if (((viewInfo.State & Interop.Kernel32.MemOptions.MEM_RESERVE) != 0) || ((ulong)viewSize < (ulong)nativeSize))
            {
                IntPtr tempHandle = Interop.VirtualAlloc(
                    viewHandle, (UIntPtr)(nativeSize != MemoryMappedFile.DefaultSize ? nativeSize : viewSize),
                    Interop.Kernel32.MemOptions.MEM_COMMIT, MemoryMappedFile.GetPageAccess(access));
                int lastError = Marshal.GetLastWin32Error();
                if (viewHandle.IsInvalid)
                {
                    viewHandle.Dispose();
                    throw Win32Marshal.GetExceptionForWin32Error(lastError);
                }
                // again query the view for its new size
                viewInfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
                Interop.Kernel32.VirtualQuery(viewHandle, ref viewInfo, (UIntPtr)Marshal.SizeOf(viewInfo));
                viewSize = (ulong)viewInfo.RegionSize;
            }

            // if the user specified DefaultSize as the size, we need to get the actual size
            if (size == MemoryMappedFile.DefaultSize)
            {
                size = (long)(viewSize - (ulong)extraMemNeeded);
            }
            else
            {
                Debug.Assert(viewSize >= (ulong)size, "viewSize < size");
            }

            viewHandle.Initialize((ulong)size + (ulong)extraMemNeeded);
            return(new MemoryMappedView(viewHandle, extraMemNeeded, size, access));
        }
Ejemplo n.º 13
0
 protected override void Dispose(bool disposing)
 {
     _view.Dispose();
 }
 public void Dispose()
 {
     ums?.Dispose();
     memBuffer?.Dispose();
     accessor?.Dispose();
 }
Ejemplo n.º 15
0
        internal void Grow(long minCapacity, bool sparse = false)
        {
            if (minCapacity < 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException(nameof(minCapacity));
            }

            if (_isWritable)
            {
                minCapacity = ((minCapacity - 1) / 4096 + 1) * 4096;
            }

            if (_fileStream == null)
            {
                // NB No need to recreate file
                // If capacity is larger than the size of the file on disk, the file on disk is
                // increased to match the specified capacity even if no data is written to the
                // memory-mapped file. To prevent this from occurring, specify 0 (zero) for the
                // default capacity, which will internally set capacity to the size of the file on disk.

                //var handle = Mono.Posix.Syscall.open(_filePath, (Mono.Posix.OpenFlags) (0)); // _isWritable
                //    //? Mono.Posix.OpenFlags.O_RDWR //| Mono.Posix.OpenFlags.O_CREAT
                //    //: Mono.Posix.OpenFlags.O_RDONLY); //, FileMode.S_IWUSR | FileMode.S_IRUSR | FileMode.S_IROTH | FileMode.S_IWOTH);
                //var sfh = new SafeFileHandle((IntPtr)handle, true);

                //_fileStream = new FileStream(sfh, _isWritable ? FileAccess.ReadWrite : FileAccess.Read, 1, false);

                _fileStream = new FileStream(_filePath, _isWritable ? FileMode.OpenOrCreate : FileMode.Open,
                                             _isWritable ? FileAccess.ReadWrite : FileAccess.Read,
                                             FileShare.ReadWrite, 1,
                                             _fileOptions);

                if (sparse)
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        if (!MarkAsSparseFile(_fileStream))
                        {
                            throw new Win32Exception("Cannot make a sparse file.");
                        }
                    }
                    else
                    {
                        // We allocate in chunks of 64-128 MB, not a big deal for servers
                        // Need this for MacOS, it's not nice to have pre-allocated 1 GB
                        // just in case.
                        Trace.TraceWarning("Sparse files not implemented on non-Windows");
                    }
                }

                if (!_isWritable && _fileStream.Length == 0)
                {
                    _fileStream.Dispose();
                    _fileStream = null;
                    ThrowHelper.ThrowInvalidOperationException($"File {_filePath} is empty. Cannot open DirectFile in read-only mode.");
                    return;
                }
            }
            else if (_isWritable)
            {
                // _va.Dispose does this
                // Flush(flushToDisk);
            }

            if (!_isWritable && minCapacity > _fileStream.Length)
            {
                ThrowHelper.ThrowArgumentException("minCapacity > _fileStream.Length");
            }

            // NB another thread could have increased the map size and _capacity could be stale
            var bytesCapacity = Math.Max(_fileStream.Length, minCapacity);

            _va?.Flush();
            _vaHandle?.ReleasePointer();
            _vaHandle?.Dispose();
            _va?.Dispose();
            _mmf?.Dispose();

            // var unique = ((long)Process.GetCurrentProcess().Id << 32) | _counter++;
            // NB: map name must be unique
            var mmf = MemoryMappedFile.CreateFromFile(_fileStream,
                                                      null, // $@"{Path.GetFileName(_filePath)}.{unique}"
                                                      bytesCapacity,
                                                      _isWritable ? MemoryMappedFileAccess.ReadWrite : MemoryMappedFileAccess.Read, HandleInheritability.None,
                                                      true);

            _mmf = mmf;

            byte *ptr = (byte *)0;

            _va       = _mmf.CreateViewAccessor(0, bytesCapacity, _isWritable ? MemoryMappedFileAccess.ReadWrite : MemoryMappedFileAccess.Read);
            _vaHandle = _va.SafeMemoryMappedViewHandle;
            _vaHandle.AcquirePointer(ref ptr);

            _pointer  = ptr;
            _capacity = bytesCapacity;
        }
Ejemplo n.º 16
0
 protected override void Dispose(bool disposing)
 {
     mma.Dispose();
 }