Пример #1
0
        protected unsafe byte *GetSharedMemory(int iSize)
        {
            // Build our name
            String strName = GetMemorySectionName();

            IntPtr mappedFileHandle;

            // This gets shared memory for our map.  If its can't, it gives us clean memory.
            Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle);

            Contract.Assert(pMemorySection != null,
                            "[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened");

            // If that failed, we have to die.
            if (pMemorySection == null)
            {
                throw new OutOfMemoryException(
                          Environment.GetResourceString("Arg_OutOfMemoryException"));
            }

            // if we have null file handle. this means memory was allocated after
            // failing to open the mapped file.

            if (mappedFileHandle != IntPtr.Zero)
            {
                safeMemorySectionHandle = new SafeViewOfFileHandle((IntPtr)pMemorySection, true);
                safeFileMappingHandle   = new SafeFileMappingHandle(mappedFileHandle, true);
            }

            return(pMemorySection);
        }
Пример #2
0
 public void Dispose()
 {
     if (fileMapping != null)
     {
         fileMapping.Close();
         fileMapping = null;
     }
 }
 public void Dispose()
 {
     if (this.fileMapping != null)
     {
         this.fileMapping.Close();
         this.fileMapping = null;
     }
 }
Пример #4
0
        public static unsafe FileMapping OpenMapping(string name, bool inherit = false, FileMappingAccessRights accessRights = FileMappingAccessRights.All)
        {
            SafeFileMappingHandle handle = OpenFileMappingA((uint)accessRights, inherit, name);

            if (handle.IsInvalid)
            {
                throw new Win32Exception();
            }
            return(new FileMapping(handle));
        }
        internal unsafe MemoryMapFile(String fileName, String fileMappingName)
        {
            //
            // Use native API to create the file directly.
            //
            SafeFileHandle fileHandle = Win32Native.UnsafeCreateFile(fileName, FileStream.GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero);
            int            lastError  = Marshal.GetLastWin32Error();

            if (fileHandle.IsInvalid)
            {
                BCLDebug.Assert(false, "Failed to create file " + fileName + ", GetLastError = " + lastError);
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidOperation_UnexpectedWin32Error"), lastError));
            }

            int highSize;
            int lowSize = Win32Native.GetFileSize(fileHandle, out highSize);

            if (lowSize == Win32Native.INVALID_FILE_SIZE)
            {
                BCLDebug.Assert(false, "Failed to get the file size of " + fileName + ", GetLastError = " + lastError);
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidOperation_UnexpectedWin32Error"), lastError));
            }

            fileSize = (((long)highSize) << 32) | ((uint)lowSize);

            if (fileSize == 0)
            {
                // we cannot map zero size file. the caller should check for the file size.
                fileHandle.Close();
                return;
            }

            SafeFileMappingHandle fileMapHandle = Win32Native.CreateFileMapping(fileHandle, IntPtr.Zero, PAGE_READONLY, 0, 0, fileMappingName);

            fileHandle.Close();
            lastError = Marshal.GetLastWin32Error();
            if (fileMapHandle.IsInvalid)
            {
                BCLDebug.Assert(false, "Failed to create file mapping for file " + fileName + ", GetLastError = " + lastError);
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidOperation_UnexpectedWin32Error"), lastError));
            }

            viewOfFileHandle = Win32Native.MapViewOfFile(fileMapHandle, SECTION_MAP_READ, 0, 0, UIntPtr.Zero);
            lastError        = Marshal.GetLastWin32Error();
            if (viewOfFileHandle.IsInvalid)
            {
                BCLDebug.Assert(false, "Failed to map a view of file " + fileName + ", GetLastError = " + lastError);
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidOperation_UnexpectedWin32Error"), lastError));
            }

            bytes = (byte *)viewOfFileHandle.DangerousGetHandle();

            fileMapHandle.Close();
        }
Пример #6
0
        internal static BitmapHandle CreateDIBSection(HandleRef hdc, ref InteropValues.BITMAPINFO bitmapInfo, int iUsage,
                                                      ref IntPtr ppvBits, SafeFileMappingHandle hSection, int dwOffset)
        {
            if (hSection == null)
            {
                hSection = new SafeFileMappingHandle(IntPtr.Zero);
            }

            var hBitmap = PrivateCreateDIBSection(hdc, ref bitmapInfo, iUsage, ref ppvBits, hSection, dwOffset);

            return(hBitmap);
        }
Пример #7
0
    /// <summary>Create a syncronized shared memory file</summary>
    /// <param name="name">The suffix of the shared memory file and semaphore.</param>
    public ProcessValueCoordinator(string name)
    {
        if (String.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentNullException(name);
        }

        bool created = false;

        this.semaphore          = new Semaphore(1, 1, SemaphoreName + name, out created);
        this.sharedMemoryHandle = Win32Native.CreateFileMapping(new SafeFileHandle(IntPtr.Zero, false), IntPtr.Zero, FileMapProtection.PageReadWrite, 0, BufferSize, SharedMemoryName + name);
        this.sharedMemoryMap    = Win32Native.MapViewOfFile(this.sharedMemoryHandle, FileMapAccess.FileMapAllAccess, 0, 0, BufferSize);
    }
        public void Dispose(bool disposing)
        {
            lock (this) {
                if (!m_Disposed)
                {
                    if (disposing)
                    {
                        if (m_QuotaFileStream != null)
                        {
                            m_QuotaFileStream.Dispose();
                            m_QuotaFileStream = null;
                        }

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

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

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

                    if (m_QuotaView != IntPtr.Zero)
                    {
                        Win32Native.UnmapViewOfFile(m_QuotaView);
                        m_QuotaView = IntPtr.Zero;
                    }

                    if (m_UsedSizeView != IntPtr.Zero)
                    {
                        Win32Native.UnmapViewOfFile(m_UsedSizeView);
                        m_UsedSizeView = IntPtr.Zero;
                    }

                    m_Disposed = true;
                }
            }
        }
Пример #9
0
        protected unsafe byte *GetSharedMemory(int iSize)
        {
            IntPtr mappedFileHandle;
            byte * openFileMapping = EncodingTable.nativeCreateOpenFileMapping(this.GetMemorySectionName(), iSize, out mappedFileHandle);

            if ((IntPtr)openFileMapping == IntPtr.Zero)
            {
                throw new OutOfMemoryException(Environment.GetResourceString("Arg_OutOfMemoryException"));
            }
            if (mappedFileHandle != IntPtr.Zero)
            {
                this.safeMemorySectionHandle = new SafeViewOfFileHandle((IntPtr)((void *)openFileMapping), true);
                this.safeFileMappingHandle   = new SafeFileMappingHandle(mappedFileHandle, true);
            }
            return(openFileMapping);
        }
Пример #10
0
        public static unsafe FileMapping CreateVirtualMapping(MemoryProtection memProtection, FileMappingFlags flags, UInt64 size, string name)
        {
            SafeFileMappingHandle handle = CreateFileMappingA(
                SafeFileObjectHandle.InvalidHandle,
                null,
                (uint)memProtection | (uint)flags,
                (uint)(size >> 32), (uint)(size & 0xFFFFFFFF),
                name
                );

            if (handle.IsInvalid)
            {
                throw new Win32Exception();
            }
            return(new FileMapping(handle));
        }
        protected unsafe byte *GetSharedMemory(int iSize)
        {
            IntPtr ptr;
            byte * numPtr = EncodingTable.nativeCreateOpenFileMapping(this.GetMemorySectionName(), iSize, out ptr);

            if (numPtr == null)
            {
                throw new OutOfMemoryException(Environment.GetResourceString("Arg_OutOfMemoryException"));
            }
            if (ptr != IntPtr.Zero)
            {
                this.safeMemorySectionHandle = new SafeViewOfFileHandle((IntPtr)numPtr, true);
                this.safeFileMappingHandle   = new SafeFileMappingHandle(ptr, true);
            }
            return(numPtr);
        }
        private static bool GetView(SafeFileMappingHandle fileMapping, bool writable, out SafeViewOfFileHandle handle)
        {
            handle = UnsafeNativeMethods.MapViewOfFile(fileMapping, writable ? 2 : 4, 0, 0, (IntPtr)sizeof(SharedMemoryContents));
            int error = Marshal.GetLastWin32Error();

            if (!handle.IsInvalid)
            {
                return(true);
            }
            handle.SetHandleAsInvalid();
            fileMapping.Close();
            if (writable || (error != 2))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
            }
            return(false);
        }
        private void Map()
        {
            if (m_Disposed)
            {
                // This can happen in the case where an IsolatedStorageFileStream is used after the underlying IsolatedStorageFile object is disposed.
                // which we allowed in Silverlight 3.  If this is the case, we will rebuild our state.
                Init();
                m_Disposed = false;
                GC.ReRegisterForFinalize(this);
            }

            if (m_QuotaFileMapping == null || m_QuotaFileMapping.IsInvalid)
            {
                m_QuotaFileMapping = Win32Native.CreateFileMapping(m_QuotaFileStream.SafeFileHandle, IntPtr.Zero, Win32Native.PAGE_READWRITE, 0, 0, null);

                if (m_QuotaFileMapping.IsInvalid)
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
                }
            }

            if (m_UsedSizeFileMapping == null || m_UsedSizeFileMapping.IsInvalid)
            {
                m_UsedSizeFileMapping = Win32Native.CreateFileMapping(m_UsedSizeFileStream.SafeFileHandle, IntPtr.Zero, Win32Native.PAGE_READWRITE, 0, 0, null);

                if (m_UsedSizeFileMapping.IsInvalid)
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
                }
            }

            m_QuotaView = Win32Native.MapViewOfFile(m_QuotaFileMapping, Win32Native.FILE_MAP_WRITE | Win32Native.FILE_MAP_READ, 0, 0, UIntPtr.Zero);

            if (m_QuotaView == IntPtr.Zero)
            {
                throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
            }

            m_UsedSizeView = Win32Native.MapViewOfFile(m_UsedSizeFileMapping, Win32Native.FILE_MAP_WRITE | Win32Native.FILE_MAP_READ, 0, 0, UIntPtr.Zero);

            if (m_UsedSizeView == IntPtr.Zero)
            {
                throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
            }
        }
        public static unsafe bool Read(string name, out string content)
        {
            bool flag;

            content = null;
            SafeFileMappingHandle fileMapping = UnsafeNativeMethods.OpenFileMapping(4, false, @"Global\" + name);
            int error = Marshal.GetLastWin32Error();

            if (fileMapping.IsInvalid)
            {
                fileMapping.SetHandleAsInvalid();
                fileMapping.Close();
                if (error != 2)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
                }
                return(false);
            }
            try
            {
                SafeViewOfFileHandle handle2;
                if (!GetView(fileMapping, false, out handle2))
                {
                    flag = false;
                }
                else
                {
                    try
                    {
                        SharedMemoryContents *handle = (SharedMemoryContents *)handle2.DangerousGetHandle();
                        content = handle->isInitialized ? handle->pipeGuid.ToString() : null;
                        flag    = true;
                    }
                    finally
                    {
                        handle2.Close();
                    }
                }
            }
            finally
            {
                fileMapping.Close();
            }
            return(flag);
        }
Пример #15
0
        public static bool Read(string name, out string content)
        {
            content = null;

            SafeFileMappingHandle fileMapping = UnsafeNativeMethods.OpenFileMapping(UnsafeNativeMethods.FILE_MAP_READ, false, ListenerConstants.GlobalPrefix + name);
            int errorCode = Marshal.GetLastWin32Error();

            if (fileMapping.IsInvalid)
            {
                fileMapping.SetHandleAsInvalid();
                fileMapping.Close();
                if (errorCode == UnsafeNativeMethods.ERROR_FILE_NOT_FOUND)
                {
                    return(false);
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(errorCode));
            }

            try
            {
                SafeViewOfFileHandle view;
                if (!GetView(fileMapping, false, out view))
                {
                    return(false);
                }

                try
                {
                    SharedMemoryContents *contents = (SharedMemoryContents *)view.DangerousGetHandle();
                    content = contents->isInitialized ? contents->pipeGuid.ToString() : null;
                    return(true);
                }
                finally
                {
                    view.Close();
                }
            }
            finally
            {
                fileMapping.Close();
            }
        }
Пример #16
0
        public static unsafe SharedMemory Create(string name, Guid content, List <SecurityIdentifier> allowedSids)
        {
            int errorCode = UnsafeNativeMethods.ERROR_SUCCESS;

            byte[] binarySecurityDescriptor = SecurityDescriptorHelper.FromSecurityIdentifiers(allowedSids, UnsafeNativeMethods.GENERIC_READ);
            SafeFileMappingHandle fileMapping;

            UnsafeNativeMethods.SECURITY_ATTRIBUTES securityAttributes = new UnsafeNativeMethods.SECURITY_ATTRIBUTES();
            fixed(byte *pinnedSecurityDescriptor = binarySecurityDescriptor)
            {
                securityAttributes.lpSecurityDescriptor = (IntPtr)pinnedSecurityDescriptor;
                fileMapping = UnsafeNativeMethods.CreateFileMapping((IntPtr)(-1), securityAttributes, UnsafeNativeMethods.PAGE_READWRITE, 0, sizeof(SharedMemoryContents), name);
                errorCode   = Marshal.GetLastWin32Error();
            }

            if (fileMapping.IsInvalid)
            {
                fileMapping.SetHandleAsInvalid();
                fileMapping.Close();
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(errorCode));
            }

            SharedMemory         sharedMemory = new SharedMemory(fileMapping);
            SafeViewOfFileHandle view;

            // Ignore return value.
            GetView(fileMapping, true, out view);

            try
            {
                SharedMemoryContents *contents = (SharedMemoryContents *)view.DangerousGetHandle();
                contents->pipeGuid = content;
                Thread.MemoryBarrier();
                contents->isInitialized = true;
                return(sharedMemory);
            }
            finally
            {
                view.Close();
            }
        }
Пример #17
0
        static bool GetView(SafeFileMappingHandle fileMapping, bool writable, out SafeViewOfFileHandle handle)
        {
            handle = UnsafeNativeMethods.MapViewOfFile(fileMapping, writable ? UnsafeNativeMethods.FILE_MAP_WRITE : UnsafeNativeMethods.FILE_MAP_READ, 0, 0, (IntPtr)sizeof(SharedMemoryContents));
            int errorCode = Marshal.GetLastWin32Error();

            if (!handle.IsInvalid)
            {
                return(true);
            }
            else
            {
                handle.SetHandleAsInvalid();
                fileMapping.Close();

                // Only return false when it's reading time.
                if (!writable && errorCode == UnsafeNativeMethods.ERROR_FILE_NOT_FOUND)
                {
                    return(false);
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(errorCode));
            }
        }
Пример #18
0
        static void Main(string[] args)
        {
            SafeFileMappingHandle hMapFile = null;
            IntPtr pView = IntPtr.Zero;

            try
            {
                // Try to open the named file mapping.
                hMapFile = NativeMethod.OpenFileMapping(
                    FileMapAccess.FILE_MAP_READ,    // Read access
                    false,                          // Do not inherit the name
                    FullMapName                     // File mapping name
                    );

                if (hMapFile.IsInvalid)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The file mapping ({0}) is opened", FullMapName);

                // Map a view of the file mapping into the address space of the
                // current process.
                pView = NativeMethod.MapViewOfFile(
                    hMapFile,                       // Handle of the map object
                    FileMapAccess.FILE_MAP_READ,    // Read access
                    0,                              // High-order DWORD of file offset
                    ViewOffset,                     // Low-order DWORD of file offset
                    ViewSize                        // Byte# to map to view
                    );

                if (pView == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The file view is mapped");

                // Read and display the content in the view.
                string message = Marshal.PtrToStringUni(pView);
                Console.WriteLine("Read from the file mapping:\n\"{0}\"", message);

                // Wait to clean up resources and stop the process.
                Console.Write("Press ENTER to clean up resources and quit");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The process throws the error: {0}", ex.Message);
            }
            finally
            {
                if (hMapFile != null)
                {
                    if (pView != IntPtr.Zero)
                    {
                        // Unmap the file view.
                        NativeMethod.UnmapViewOfFile(pView);
                        pView = IntPtr.Zero;
                    }
                    // Close the file mapping object.
                    hMapFile.Close();
                    hMapFile = null;
                }
            }
        }
Пример #19
0
 public static extern IntPtr MapViewOfFile(
     SafeFileMappingHandle hFileMappingObject,
     FileMapAccess dwDesiredAccess,
     uint dwFileOffsetHigh,
     uint dwFileOffsetLow,
     uint dwNumberOfBytesToMap);
Пример #20
0
 internal FileMapping(SafeFileMappingHandle handle)
 {
     this.handle = handle;
 }
Пример #21
0
        /// <summary>Initializes a new instance of the <see cref="FileMapping" /> class.</summary>
        /// <param name="fileName">The file that should be memory-mapped</param>
        public FileMapping(string fileName, FileMapMode mode)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            var               fileMode = FileMode.Open;
            FileAccess        fileAccess;
            FileShare         fileShare;
            FileMapProtection mapProtection;
            FileMapAccess     mapAccess;

            switch (mode)
            {
            case FileMapMode.Read:
                fileAccess    = FileAccess.Read | GenericRead;
                fileShare     = FileShare.Read;
                mapProtection = FileMapProtection.PageReadOnly;
                mapAccess     = FileMapAccess.FileMapRead;
                break;

            case FileMapMode.Write:
                fileAccess    = FileAccess.Write | GenericWrite;
                fileShare     = FileShare.None;
                mapProtection = FileMapProtection.PageWriteCopy;
                mapAccess     = FileMapAccess.FileMapWrite;
                break;

            case FileMapMode.ReadWrite:
            default:
                fileAccess    = FileAccess.ReadWrite | GenericRead | GenericWrite;
                fileShare     = FileShare.None;
                mapProtection = FileMapProtection.PageReadWrite;
                mapAccess     = FileMapAccess.FileMapAllAccess;
                break;
            }


            // Get the size.
            // This throws a proper FileNotFoundException if the file doesn't exist so we don't need to check that anymore.
            _size = new FileInfo(fileName).Length;

            try
            {
                _file = NativeMethods.CreateFile(
                    fileName,
                    fileAccess,
                    fileShare,
                    IntPtr.Zero,
                    fileMode,
                    FileAttributes.Normal,
                    IntPtr.Zero
                    );
                if (_file.IsInvalid)
                {
                    throw new Win32Exception();
                }

                _mapping = NativeMethods.CreateFileMapping(_file, IntPtr.Zero, mapProtection, 0, 0, null);
                if (_mapping.IsInvalid)
                {
                    throw new Win32Exception();
                }

                _view = NativeMethods.MapViewOfFile(_mapping, mapAccess, 0, 0, IntPtr.Zero);
                if (_view == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }
            }
            catch
            {
                if (_view != IntPtr.Zero)
                {
                    NativeMethods.UnmapViewOfFile(_view);
                }
                _mapping?.Dispose();
                _file?.Dispose();
                throw;
            }
        }
Пример #22
0
        static void Main(string[] args)
        {
            SafeFileMappingHandle hMapFile = null;
            IntPtr pView = IntPtr.Zero;

            try
            {
                // Create the file mapping object.
                hMapFile = NativeMethod.CreateFileMapping(
                    INVALID_HANDLE_VALUE,          // Use paging file - shared memory
                    IntPtr.Zero,                   // Default security attributes
                    FileProtection.PAGE_READWRITE, // Allow read and write access
                    0,                             // High-order DWORD of file mapping max size
                    MapSize,                       // Low-order DWORD of file mapping max size
                    FullMapName                    // Name of the file mapping object
                    );

                if (hMapFile.IsInvalid)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The file mapping ({0}) is created", FullMapName);

                // Map a view of the file mapping into the address space of the
                // current process.
                pView = NativeMethod.MapViewOfFile(
                    hMapFile,                          // Handle of the map object
                    FileMapAccess.FILE_MAP_ALL_ACCESS, // Read and write access
                    0,                                 // High-order DWORD of file offset
                    ViewOffset,                        // Low-order DWORD of file offset
                    ViewSize                           // Byte# to map to the view
                    );

                if (pView == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The file view is mapped");

                // Prepare a message to be written to the view. Append '\0' to
                // mark the end of the string when it is marshaled to the native
                // memory.
                byte[] bMessage = Encoding.Unicode.GetBytes(Message + '\0');

                // Write the message to the view.
                Marshal.Copy(bMessage, 0, pView, bMessage.Length);

                Console.WriteLine("This message is written to the view:\n\"{0}\"",
                                  Message);

                // Wait to clean up resources and stop the process.
                Console.Write("Press ENTER to clean up resources and quit");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The process throws the error: {0}", ex.Message);
            }
            finally
            {
                if (hMapFile != null)
                {
                    if (pView != IntPtr.Zero)
                    {
                        // Unmap the file view.
                        NativeMethod.UnmapViewOfFile(pView);
                        pView = IntPtr.Zero;
                    }
                    // Close the file mapping object.
                    hMapFile.Close();
                    hMapFile = null;
                }
            }
        }
Пример #23
0
 SharedMemory(SafeFileMappingHandle fileMapping)
 {
     this.fileMapping = fileMapping;
 }
Пример #24
0
 private static extern BitmapHandle PrivateCreateDIBSection(HandleRef hdc, ref InteropValues.BITMAPINFO bitmapInfo, int iUsage,
                                                            ref IntPtr ppvBits, SafeFileMappingHandle hSection, int dwOffset);
Пример #25
0
 public static extern IntPtr MapViewOfFile(
     SafeFileMappingHandle hFileMappingObject,
     FileMapAccess dwDesiredAccess,
     uint dwFileOffsetHigh,
     uint dwFileOffsetLow,
     uint dwNumberOfBytesToMap);
 internal static extern SafeViewOfFileHandle MapViewOfFile(
     SafeFileMappingHandle handle, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, UIntPtr dwNumerOfBytesToMap);
Пример #27
0
 private static extern NativeMethods.BitmapHandle PrivateCreateDIBSection(HandleRef hdc, ref NativeMethods.BITMAPINFO bitmapInfo, int iUsage, ref IntPtr ppvBits, SafeFileMappingHandle hSection, int dwOffset);
        public void ClearMmunloadedDrivers()
        {
            IntPtr pView = IntPtr.Zero;

            // Map a view of the file mapping into the address space of the
            // current process.
            try
            {
                pView = NativeMethod.MapViewOfFile(
                    hMapFile,                     // Handle of the map object
                    FileMapAccess.FILE_MAP_WRITE, // Read and write access
                    0,                            // High-order DWORD of file offset
                    ViewOffset,                   // Low-order DWORD of file offset
                    ViewSize                      // Byte# to map to the view
                    );

                if (pView == IntPtr.Zero)
                {
                    throw new Win32Exception("Failed to write Clearmm request");
                }

                Console.WriteLine("The file view is mapped");

                // Prepare a message to be written to the view. Append '\0' to
                // mark the end of the string when it is marshaled to the native
                // memory.
                Message = "Clearmm";
                byte[] bMessage = Encoding.Unicode.GetBytes(Message + '\0');

                // Write the message to the view.
                Marshal.Copy(bMessage, 0, pView, bMessage.Length);

                Console.WriteLine("This message is written to the view:\n\"{0}\"",
                                  Message);

                // Wait to clean up resources and stop the process.
                Console.Write("Press ENTER to clean up resources and quit");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The process throws the error: {0}", ex.Message);
            }
            finally
            {
                if (hMapFile != null)
                {
                    if (pView != IntPtr.Zero)
                    {
                        // Unmap the file view.
                        NativeMethod.UnmapViewOfFile(pView);
                        pView = IntPtr.Zero;
                    }
                    // Close the file mapping object.
                    //hMapFile.Close();
                    //hMapFile = null;
                }
            }

            //SharedEvent_ready2read = CreateEventA(&sa, TRUE, FALSE, "Global\\ReadyRead");
            IntPtr handle = IntPtr.Zero;//SharedEvent_ready2read

            WaitForSingleObject(handle, (uint)INFINITE);
            //read
            try
            {
                // Try to open the named file mapping.
                hMapFile = NativeMethod.OpenFileMapping(
                    FileMapAccess.FILE_MAP_READ,    // Read access
                    false,                          // Do not inherit the name
                    FullMapName                     // File mapping name
                    );
                if (hMapFile.IsInvalid)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The file mapping ({0}) is opened", FullMapName);

                // Map a view of the file mapping into the address space of the
                // current process.
                pView = NativeMethod.MapViewOfFile(
                    hMapFile,                       // Handle of the map object
                    FileMapAccess.FILE_MAP_READ,    // Read access
                    0,                              // High-order DWORD of file offset
                    ViewOffset,                     // Low-order DWORD of file offset
                    ViewSize                        // Byte# to map to view
                    );

                if (pView == IntPtr.Zero)
                {
                    throw new Win32Exception("Failed to read Clearmm answer");
                }

                Console.WriteLine("The file view is mapped");

                // Read and display the content in the view.
                string message = Marshal.PtrToStringUni(pView);
                Console.WriteLine("Read from the file mapping:\n\"{0}\"", message);

                // Wait to clean up resources and stop the process.
                Console.Write("Press ENTER to clean up resources and quit");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The process throws the error: {0}", ex.Message);
            }
            finally
            {
                if (hMapFile != null)
                {
                    if (pView != IntPtr.Zero)
                    {
                        // Unmap the file view.
                        NativeMethod.UnmapViewOfFile(pView);
                        pView = IntPtr.Zero;
                    }
                    // Close the file mapping object.
                    //hMapFile.Close();
                    //hMapFile = null;
                }
            }
        }
Пример #29
0
        internal static NativeMethods.BitmapHandle CreateDIBSection(HandleRef hdc, ref NativeMethods.BITMAPINFO bitmapInfo, int iUsage, ref IntPtr ppvBits, SafeFileMappingHandle hSection, int dwOffset)
        {
            if (hSection == null)
            {
                // PInvoke marshalling does not handle null SafeHandle, we must pass an IntPtr.Zero backed SafeHandle
                hSection = new SafeFileMappingHandle(IntPtr.Zero);
            }

            NativeMethods.BitmapHandle hBitmap = PrivateCreateDIBSection(hdc, ref bitmapInfo, iUsage, ref ppvBits, hSection, dwOffset);
            int error = Marshal.GetLastWin32Error();

            if ( hBitmap.IsInvalid )
            {
                Debug.WriteLine("CreateDIBSection failed. Error = " + error);
            }

            return hBitmap;
        }
Пример #30
0
 static extern IntPtr MapViewOfFile2(SafeFileMappingHandle fileMapping, SafeProcessHandle processHandle, UInt64 Offset, IntPtr baseAddress, uint size, UInt32 allocationType, UInt32 pageProtection);
 internal static extern SafeViewOfFileHandle MapViewOfFile
 (
     SafeFileMappingHandle handle,
     int dwDesiredAccess,
     int dwFileOffsetHigh,
     int dwFileOffsetLow,
     IntPtr dwNumberOfBytesToMap
 );
Пример #32
0
 internal static extern SafeMapViewOfFileHandle MapViewOfFile(SafeFileMappingHandle handle, FileMapAccess desiredAccess, uint fileOffsetHigh, uint fileOffsetLow, uint numberOfBytesToMap);