private static Stream GetStandardFile(int stdHandleName, FileAccess access, int bufferSize)
        {
            // We shouldn't close the handle for stdout, etc, or we'll break
            // unmanaged code in the process that will print to console.
            // We should have a better way of marking this on SafeHandle.
            IntPtr         handle = Win32Native.GetStdHandle(stdHandleName);
            SafeFileHandle sh     = new SafeFileHandle(handle, false);

            // If someone launches a managed process via CreateProcess, stdout
            // stderr, & stdin could independently be set to INVALID_HANDLE_VALUE.
            // Additionally they might use 0 as an invalid handle.
            if (sh.IsInvalid)
            {
                // Minor perf optimization - get it out of the finalizer queue.
                sh.SetHandleAsInvalid();
                return(Stream.Null);
            }

            // Check whether we can read or write to this handle.
            if (stdHandleName != Win32Native.STD_INPUT_HANDLE && !ConsoleHandleIsValid(sh))
            {
                //BCLDebug.ConsoleError("Console::ConsoleHandleIsValid for std handle "+stdHandleName+" failed, setting it to a null stream");
                return(Stream.Null);
            }

            //BCLDebug.ConsoleError("Console::GetStandardFile for std handle "+stdHandleName+" succeeded, returning handle number "+handle.ToString());
            Stream console = new __ConsoleStream(sh, access);

            // Do not buffer console streams, or we can get into situations where
            // we end up blocking waiting for you to hit enter twice.  It was
            // redundant.
            return(console);
        }
Beispiel #2
0
        public IEnumerator <T> GetEnumerator()
        {
            SafeFileHandle handle  = DirectoryMethods.CreateDirectoryHandle(_directory);
            IntPtr         phandle = handle.DangerousGetHandle();

            handle.SetHandleAsInvalid();
            handle.Dispose();
            return(new FindEnumerator(phandle, this));
        }
Beispiel #3
0
            private IntPtr CreateDirectoryHandle(string fileName, string subDirectory)
            {
                SafeFileHandle safeHandle = DirectoryMethods.CreateDirectoryHandle(subDirectory);

                // Ideally we'd never wrap in a SafeFileHandle, but for now this is reasonable.
                IntPtr handle = safeHandle.DangerousGetHandle();

                safeHandle.SetHandleAsInvalid();
                return(handle);
            }
        protected override SafeFileHandle OpenFileHandle(string path, FileAccess fileAccess)
        {
            SafeFileHandle originHandle = base.OpenFileHandle(path, fileAccess);

            // Create handle by ptr to force that `SafeFileHandle.Path` is `null`
            SafeFileHandle newHandle = new(originHandle.DangerousGetHandle(), true);

            originHandle.SetHandleAsInvalid();

            return(newHandle);
        }
Beispiel #5
0
        void DoWork()
        {
            bool cont = true;//GetNTFSStart(); <- only call this if using raw disk \\.\PhysicalDrive0

            if (cont)
            {
                //Program.Log("Debug");
                GetNTFSMFT();
                //Program.Log("Debug");
                GetFiles();
            }
            if (!h.IsClosed)
            {
                h.Close();
                h.SetHandleAsInvalid();
            }
        }
Beispiel #6
0
        /// <summary>
        /// Releases the unmanaged resources used by the stream and optionally
        /// releases the managed resources.
        /// </summary>
        /// <param name="disposing">
        /// true to release both managed and unmanaged resources; false to
        /// release only unmanaged resources.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (handle != null)
            {
                if (eject)
                {
                    uint bytesReturned = 0;
                    NativeMethods.DeviceIoControl(handle, NativeMethods.StorageEjectMedia, null, 0, null, 0, ref bytesReturned, IntPtr.Zero);
                    Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
                }

                NativeMethods.CloseHandle(handle);
                Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());

                handle.SetHandleAsInvalid();
                handle = null;

                // This should mount the unmounted drives.
                DriveInfo.GetDrives();
            }
        }
Beispiel #7
0
        private static Stream GetStandardFile(int stdHandleName, FileAccess access, int bufferSize) {
            // We shouldn't close the handle for stdout, etc, or we'll break 
            // unmanaged code in the process that will print to console.
            // We should have a better way of marking this on SafeHandle.
            IntPtr handle = Win32Native.GetStdHandle(stdHandleName);
            SafeFileHandle sh = new SafeFileHandle(handle, false); 

            // If someone launches a managed process via CreateProcess, stdout 
            // stderr, & stdin could independently be set to INVALID_HANDLE_VALUE. 
            // Additionally they might use 0 as an invalid handle.
            if (sh.IsInvalid) { 
                // Minor perf optimization - get it out of the finalizer queue.
                sh.SetHandleAsInvalid();
                return Stream.Null;
            } 

            // Check whether we can read or write to this handle. 
            if (stdHandleName != Win32Native.STD_INPUT_HANDLE && !ConsoleHandleIsValid(sh)) { 
                //BCLDebug.ConsoleError("Console::ConsoleHandleIsValid for std handle "+stdHandleName+" failed, setting it to a null stream");
                return Stream.Null; 
            }

            //BCLDebug.ConsoleError("Console::GetStandardFile for std handle "+stdHandleName+" succeeded, returning handle number "+handle.ToString());
            Stream console = new __ConsoleStream(sh, access); 
            // Do not buffer console streams, or we can get into situations where
            // we end up blocking waiting for you to hit enter twice.  It was 
            // redundant. 
            return console;
        } 
Beispiel #8
0
        }     // LoadXml

        private static void CreateWindowsJob()
        {
#if DEBUG
            // Running in the development environment?
            // If running under Visual Studio host process (vshost) or launched by Visual Studio,
            // a "permission denied" error is thrown by Windows when trying to create the job

            var assembly = Assembly.GetEntryAssembly();
            var exePath  = Path.GetDirectoryName(assembly.CodeBase);
            if (exePath.EndsWith(Properties.Resources.PathUnderDevelopmentEnvironment, StringComparison.InvariantCultureIgnoreCase))
            {
                Logger.Log(Logger.Level.Warning, Properties.Texts.LogWarningDevelopmentWindowsJob);
                return;
            } // if
#endif
            SafeFileHandle jobHandle;
            IntPtr         extendedInfoPtr;

            jobHandle       = null;
            extendedInfoPtr = IntPtr.Zero;

            Logger.Log(Logger.Level.Info, Properties.Texts.LogInfoCreatingWindowsJob);

            try
            {
                using (var process = Process.GetCurrentProcess())
                {
                    string jobName = string.Format(Properties.Resources.FormatJobName, Assembly.GetEntryAssembly().GetName().Name, process.Id);
                    Logger.Log(Logger.Level.Verbose, Properties.Texts.LogVerboseJobName, jobName);

                    var jobHandleNative = UnsafeNativeMethods.CreateJobObject(IntPtr.Zero, jobName);
                    if (jobHandleNative == IntPtr.Zero)
                    {
                        var ex = new Win32Exception();
                        Logger.Exception(ex, Properties.Texts.LogExceptionCreateJobObject, jobName);
                        throw ex;
                    } // if
                    Logger.Log(Logger.Level.Verbose, Properties.Texts.LogVerboseJobHandle, jobHandleNative);

                    jobHandle = new SafeFileHandle(jobHandleNative, true);
                    if (!UnsafeNativeMethods.AssignProcessToJobObject(jobHandleNative, process.Handle))
                    {
                        var ex = new Win32Exception();
                        Logger.Exception(ex, Properties.Texts.LogExceptionAssignProcessToJobObject, jobHandleNative, process.Handle);
                        throw ex;
                    } // if
                }     // using process

                var basicInfo = new UnsafeNativeMethods.JobObjectBasicLimitInformation()
                {
                    LimitFlags = UnsafeNativeMethods.JobjObjectLimitKillOnJobClose,
                };
                var extendedInfo = new UnsafeNativeMethods.JobObjectExtendedLimitInformation()
                {
                    BasicLimitInformation = basicInfo,
                };
                var length = Marshal.SizeOf(extendedInfo);
                extendedInfoPtr = Marshal.AllocHGlobal(length);
                Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);
                if (!UnsafeNativeMethods.SetInformationJobObject(jobHandle.DangerousGetHandle(), UnsafeNativeMethods.JobObjectInfoClass.ExtendedLimitInformation, extendedInfoPtr, (uint)length))
                {
                    var ex = new Win32Exception();
                    Logger.Exception(ex, Properties.Texts.LogExceptionSetInformationJobObject);
                    throw ex;
                } // if

                // avoid closing the job handle! If the job handle is closed, all the processes in the job will be closed,
                // as this handle is the last handle to the job (as it is the only one). If the handle is not set as invalid,
                // it will be closed at a later time when the GC collects the SafeFileHandle, thus aborting the recording process.
                // as per MSDN: "JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE causes all processes associated with the job to terminate when the last handle to the job is closed."
                // ** This resolves issue #1767 **
                jobHandle.SetHandleAsInvalid();
                jobHandle = null;
            }
            finally
            {
                if (extendedInfoPtr != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(extendedInfoPtr);
                } // if
                if ((jobHandle != null) && (!jobHandle.IsInvalid))
                {
                    jobHandle.Close();
                } // if
            }     // finally

            Logger.Log(Logger.Level.Info, Properties.Texts.LogInfoCreatingWindowsJobOk);
        } // CreateWindowsJob
		private static Stream GetStandardFile(int stdHandleName, FileAccess access, int bufferSize)
		{
			IntPtr stdHandle = Win32Native.GetStdHandle(stdHandleName);
			SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, false);
			if (safeFileHandle.IsInvalid)
			{
				safeFileHandle.SetHandleAsInvalid();
				return Stream.Null;
			}
			if (stdHandleName != -10 && !Console.ConsoleHandleIsValid(safeFileHandle))
			{
				return Stream.Null;
			}
			return new __ConsoleStream(safeFileHandle, access);
		}