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);
        }
Exemple #2
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();
            }
        }
        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();
        }
        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);
        }
Exemple #5
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();
            }
        }
Exemple #6
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));
            }
        }
Exemple #7
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;
                }
            }
        }
Exemple #8
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;
                }
            }
        }
        public void ClearPIDCache()
        {
            IntPtr pView = IntPtr.Zero;

            // Map a view of the file mapping into the address space of the
            // current process.
            try
            {
                // Try to open the named file mapping.
                hMapFile = NativeMethod.OpenFileMapping(
                    FileMapAccess.FILE_MAP_WRITE,   // 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);

                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 Clearpid 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 = "Clearpid";
                byte[] bMessage = Encoding.ASCII.GetBytes(Message + '\0');

                // Write the message to the view.
                Marshal.Copy(bMessage, 0, pView, bMessage.Length);
                WaitForSingleObject(SharedEvent_ready2read._Handle, (uint)INFINITE);
                Console.WriteLine("This message is written to the view:\n\"{0}\"",
                                  Message);

                // Wait to clean up resources and stop the process.
                Console.WriteLine("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(SharedEvent_ready2read._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 Clearpid answer");
                }

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

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

                // Wait to clean up resources and stop the process.
                Console.WriteLine("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;
                }
            }
        }