Ejemplo n.º 1
0
        /// <summary>
        /// Polls a File Descriptor for the passed in flags.
        /// </summary>
        /// <param name="fd">The descriptor to poll</param>
        /// <param name="events">The events to poll for</param>
        /// <param name="timeout">The amount of time to wait; -1 for infinite, 0 for immediate return, and a positive number is the number of milliseconds</param>
        /// <param name="triggered">The events that were returned by the poll call. May be PollEvents.POLLNONE in the case of a timeout.</param>
        /// <returns>An error or Error.SUCCESS.</returns>
        internal static unsafe Error Poll(SafeFileHandle fd, PollEvents events, int timeout, out PollEvents triggered)
        {
            bool gotRef = false;
            try
            {
                fd.DangerousAddRef(ref gotRef);

                var pollEvent = new PollEvent
                {
                    FileDescriptor = fd.DangerousGetHandle().ToInt32(),
                    Events = events,
                };

                uint unused;
                Error err = Poll(&pollEvent, 1, timeout, &unused);
                triggered = pollEvent.TriggeredEvents;
                return err;
            }
            finally
            {
                if (gotRef)
                {
                    fd.DangerousRelease();
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Polls a File Descriptor for the passed in flags.
        /// </summary>
        /// <param name="fd">The descriptor to poll</param>
        /// <param name="events">The events to poll for</param>
        /// <param name="timeout">The amount of time to wait; -1 for infinite, 0 for immediate return, and a positive number is the number of milliseconds</param>
        /// <param name="triggered">The events that were returned by the poll call. May be PollEvents.POLLNONE in the case of a timeout.</param>
        /// <returns>An error or Error.SUCCESS.</returns>
        internal static unsafe Error Poll(SafeFileHandle fd, PollEvents events, int timeout, out PollEvents triggered)
        {
            bool gotRef = false;

            try
            {
                fd.DangerousAddRef(ref gotRef);

                var pollEvent = new PollEvent
                {
                    FileDescriptor = fd.DangerousGetHandle().ToInt32(),
                    Events         = events,
                };

                uint  unused;
                Error err = Poll(&pollEvent, 1, timeout, &unused);
                triggered = pollEvent.TriggeredEvents;
                return(err);
            }
            finally
            {
                if (gotRef)
                {
                    fd.DangerousRelease();
                }
            }
        }
 public MusicFile(string path, string name, SafeFileHandle handle)
 {
     Path       = path;
     Name       = name;
     FileHandle = handle;
     FileHandle.DangerousAddRef(ref _addRefSuccess);
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Opens the device handles and registers for device removal notification.
        /// </summary>
        private void OpenDevice()
        {
            DebugWriteLine("OpenDevice()");

            if (_readHandle != null)
            {
                DebugWriteLine("Device already open");
                return;
            }

            int lastError;

            _readHandle = CreateFile(_devicePath + "\\Pipe01", CreateFileAccessTypes.GenericRead, CreateFileShares.None,
                                     IntPtr.Zero, CreateFileDisposition.OpenExisting, CreateFileAttributes.Overlapped,
                                     IntPtr.Zero);
            lastError = Marshal.GetLastWin32Error();
            if (_readHandle.IsInvalid)
            {
                _readHandle = null;
                throw new Win32Exception(lastError);
            }

            _writeHandle = CreateFile(_devicePath + "\\Pipe00", CreateFileAccessTypes.GenericWrite, CreateFileShares.None,
                                      IntPtr.Zero, CreateFileDisposition.OpenExisting, CreateFileAttributes.Overlapped,
                                      IntPtr.Zero);
            lastError = Marshal.GetLastWin32Error();
            if (_writeHandle.IsInvalid)
            {
                _writeHandle = null;
                _readHandle.Dispose();
                throw new Win32Exception(lastError);
            }

            bool success = false;

            _readHandle.DangerousAddRef(ref success);
            if (success)
            {
                _notifyWindow.RegisterDeviceRemoval(_readHandle.DangerousGetHandle());
            }
            else
            {
                DebugWriteLine("Warning: Failed to initialize device removal notification");
            }

            _deviceAvailable = true;
        }
Ejemplo n.º 5
0
        public IntPtr AddRef_GetHandle_Release()
        {
            bool success = false;

            try
            {
                _sfh.DangerousAddRef(ref success);
                return(_sfh.DangerousGetHandle());
            }
            finally
            {
                if (success)
                {
                    _sfh.DangerousRelease();
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Reads a number of bytes from an open file descriptor into a specified buffer.
        /// </summary>
        /// <param name="fd">The open file descriptor to try to read from</param>
        /// <param name="buffer">The buffer to read info into</param>
        /// <param name="count">The size of the buffer</param>
        /// <returns>
        /// Returns the number of bytes read on success; otherwise, -1 is returned
        /// Note - on fail. the position of the stream may change depending on the platform; consult man 2 read for more info
        /// </returns>
        internal static unsafe int Read(SafeFileHandle fd, byte *buffer, int count)
        {
            int  bytes_read = -1;
            bool release    = false;

            try {
                fd.DangerousAddRef(ref release);
                do
                {
                    bytes_read = Read(fd.DangerousGetHandle(), buffer, count);
                } while (bytes_read < 0 && Marshal.GetLastWin32Error() == (int)Interop.Error.EINTR);
            }
            finally {
                if (release)
                {
                    fd.DangerousRelease();
                }
            }
            return(bytes_read);
        }
Ejemplo n.º 7
0
    public static bool flushPosix(FileStream fs)
    {
        if (fsync == null)
        {
            ResolveFSync();
        }
        bool           success = false;
        SafeFileHandle handle  = fs.SafeFileHandle;

        RuntimeHelpers.PrepareConstrainedRegions();
        try
        {
            handle.DangerousAddRef(ref success);
            return(fsync(handle.DangerousGetHandle().ToInt32()) == 0);
        }
        finally
        {
            if (success)
            {
                handle.DangerousRelease();
            }
        }
    }
Ejemplo n.º 8
0
        private static SafeFileHandle CreateNewSharedMemoryObject(
            string mapName, Interop.libc.MemoryMappedProtections protections, long capacity)
        {
            // Determine the flags to use when creating the shared memory object
            Interop.libc.OpenFlags flags = (protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 ?
                                           Interop.libc.OpenFlags.O_RDWR :
                                           Interop.libc.OpenFlags.O_RDONLY;
            flags |= Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_EXCL; // CreateNew

            // Create the shared memory object
            int fd;

            Interop.CheckIo(fd = Interop.libc.shm_open(mapName, flags, (int)Interop.libc.Permissions.S_IRWXU), mapName);
            SafeFileHandle fileHandle = new SafeFileHandle((IntPtr)fd, ownsHandle: true);

            // Then enlarge it to the requested capacity
            bool gotFd = false;

            fileHandle.DangerousAddRef(ref gotFd);
            try
            {
                while (Interop.CheckIo(Interop.libc.ftruncate((int)fileHandle.DangerousGetHandle(), capacity), mapName))
                {
                    ;
                }
            }
            finally
            {
                if (gotFd)
                {
                    fileHandle.DangerousRelease();
                }
            }

            // Return the fd for the object
            return(fileHandle);
        }
Ejemplo n.º 9
0
        public static void BadHandleKind_Throws_IOException(PipeDirection direction)
        {
            using (FileStream fs = new FileStream(Path.Combine(Path.GetTempPath(), "_BadHandleKind_Throws_IOException_" + Path.GetRandomFileName()), FileMode.Create, FileAccess.Write, FileShare.None, 8, FileOptions.DeleteOnClose))
            {
                SafeFileHandle safeHandle = fs.SafeFileHandle;

                bool gotRef = false;
                try
                {
                    safeHandle.DangerousAddRef(ref gotRef);
                    IntPtr handle = safeHandle.DangerousGetHandle();

                    SafePipeHandle fakePipeHandle = new SafePipeHandle(handle, ownsHandle: false);
                    Assert.Throws <IOException>(() => new NamedPipeServerStream(direction, false, true, fakePipeHandle));
                }
                finally
                {
                    if (gotRef)
                    {
                        safeHandle.DangerousRelease();
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public static void ClientBadHandleKindThrows()
        {
            using (FileStream fs = new FileStream("tempTestFile", FileMode.Create, FileAccess.Write, FileShare.None, 8, FileOptions.DeleteOnClose))
            {
                SafeFileHandle safeHandle = fs.SafeFileHandle;

                bool gotRef = false;
                try
                {
                    safeHandle.DangerousAddRef(ref gotRef);
                    IntPtr handle = safeHandle.DangerousGetHandle();

                    SafePipeHandle fakePipeHandle = new SafePipeHandle(handle, ownsHandle: false);
                    Assert.Throws <IOException>(() => new NamedPipeClientStream(PipeDirection.InOut, false, true, fakePipeHandle));
                }
                finally
                {
                    if (gotRef)
                    {
                        safeHandle.DangerousRelease();
                    }
                }
            }
        }
Ejemplo n.º 11
0
        private static string WinInternalGetTarget(SafeFileHandle handle)
        {
            int outBufferSize = ClrFacade.SizeOf<REPARSE_DATA_BUFFER_SYMBOLICLINK>();

            IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize);
            bool success = false;

            try
            {
                int bytesReturned;

                //OACR warning 62001 about using DeviceIOControl has been disabled. 
                // According to MSDN guidance DangerousAddRef() and DangerousRelease() have been used.

                handle.DangerousAddRef(ref success);

                bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT,
                    IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);

                if (!result)
                {
                    int lastError = Marshal.GetLastWin32Error();
                    if (lastError == ERROR_NOT_A_REPARSE_POINT)
                        return null;

                    throw new Win32Exception(lastError);
                }

                //Unmarshal to symbolic link to look for tags. 
                REPARSE_DATA_BUFFER_SYMBOLICLINK reparseDataBuffer = ClrFacade.PtrToStructure<REPARSE_DATA_BUFFER_SYMBOLICLINK>(outBuffer);

                if (reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_SYMLINK && reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_MOUNT_POINT)
                    return null;

                string targetDir = null;

                if (reparseDataBuffer.ReparseTag == IO_REPARSE_TAG_SYMLINK)
                {
                    targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer, reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength);
                }

                if (reparseDataBuffer.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
                {
                    //Since this is a junction we need to unmarshal to the correct structure.
                    REPARSE_DATA_BUFFER_MOUNTPOINT reparseDataBufferMountPoint = ClrFacade.PtrToStructure<REPARSE_DATA_BUFFER_MOUNTPOINT>(outBuffer);

                    targetDir = Encoding.Unicode.GetString(reparseDataBufferMountPoint.PathBuffer, reparseDataBufferMountPoint.SubstituteNameOffset, reparseDataBufferMountPoint.SubstituteNameLength);
                }

                if (targetDir.StartsWith(NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase))
                    targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length);

                return targetDir;
            }
            finally
            {
                if (success)
                {
                    handle.DangerousRelease();
                }

                Marshal.FreeHGlobal(outBuffer);
            }
        }
Ejemplo n.º 12
0
        internal static bool WinIsHardLink(FileSystemInfo fileInfo)
        {
            bool isHardLink = false;

            // only check for hard link if the item is not directory
            if (!((fileInfo.Attributes & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory))
            {
                IntPtr nativeHandle = InternalSymbolicLinkLinkCodeMethods.CreateFile(
                    fileInfo.FullName,
                    InternalSymbolicLinkLinkCodeMethods.FileDesiredAccess.GenericRead,
                    InternalSymbolicLinkLinkCodeMethods.FileShareMode.Read,
                    IntPtr.Zero,
                    InternalSymbolicLinkLinkCodeMethods.FileCreationDisposition.OpenExisting,
                    InternalSymbolicLinkLinkCodeMethods.FileAttributes.Normal,
                    IntPtr.Zero);

                using (SafeFileHandle handle = new SafeFileHandle(nativeHandle, true))
                {
                    bool success = false;

                    try
                    {
                        handle.DangerousAddRef(ref success);
                        IntPtr dangerousHandle = handle.DangerousGetHandle();
                        isHardLink = InternalSymbolicLinkLinkCodeMethods.IsHardLink(ref dangerousHandle);
                    }
                    finally
                    {
                        if (success)
                            handle.DangerousRelease();
                    }
                }
            }

            return isHardLink;
        }