Inheritance: SafeHandleZeroOrMinusOneIsInvalid
Ejemplo n.º 1
0
        public void Dispose()
        {
            if (!m_disposed)
            {
                using (var semaphoreReleaser = m_syncSemaphore.AcquireSemaphore())
                {
                    StopWaiting(semaphoreReleaser);
                    WaitUntilErrorAndOutputEof(true, semaphoreReleaser).GetAwaiter().GetResult();

                    if (m_processInjector != null)
                    {
                        // We may have already called Stop() in CompletionCallback, but that's okay.
                        m_processInjector.Stop().GetAwaiter().GetResult();
                        m_processInjector.Dispose();
                        m_processInjector = null;
                    }

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

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

                m_syncSemaphore.Dispose();

                m_disposed = true;
            }
        }
Ejemplo n.º 2
0
 public void AddProcess(SafeProcessHandle processHandle)
 {
     ValidateDisposed();
     if (!AssignProcessToJobObject(_handle, processHandle))
     {
         throw new InvalidOperationException("Unable to add the process");
     }
 }
Ejemplo n.º 3
0
 public void Dispose()
 {
     if (processHandle != null)
     {
         processHandle.Close();
         processHandle = null;
     }
 }
 public static int GetProcessIdFromHandle(Microsoft.Win32.SafeHandles.SafeProcessHandle processHandle)
 {
     if (!IsNt)
     {
         throw new PlatformNotSupportedException(SR.GetString("WinNTRequired"));
     }
     return(NtProcessManager.GetProcessIdFromHandle(processHandle));
 }
 internal static extern bool DuplicateHandle(
     SafeProcessHandle hSourceProcessHandle,
     SafeHandle hSourceHandle,
     SafeProcessHandle hTargetProcess,
     out SafeWaitHandle targetHandle,
     int dwDesiredAccess,
     bool bInheritHandle,
     int dwOptions
 );
Ejemplo n.º 6
0
		void OpenProcess()
		{
			if (openCount++ != 0)
				return;

			handle = Win32.OpenProcess(Win32.ProcessAccessFlags.QueryInformation | Win32.ProcessAccessFlags.VirtualMemoryRead | Win32.ProcessAccessFlags.VirtualMemoryWrite | Win32.ProcessAccessFlags.VirtualMemoryOperation, false, pid);
			if (handle.IsInvalid)
				throw new Win32Exception();
		}
Ejemplo n.º 7
0
		SafeProcessHandle DuplicateHandle(SafeProcessHandle process, IntPtr handle, bool throwOnFail = true)
		{
			SafeProcessHandle dupHandle;
			if (!Win32.DuplicateHandle(process, handle, Win32.GetCurrentProcess(), out dupHandle, 0, false, Win32.DUPLICATE_SAME_ACCESS))
				if (throwOnFail)
					throw new Win32Exception();
				else
					return null;
			return dupHandle;
		}
Ejemplo n.º 8
0
        internal ProcessWaitHandle(Microsoft.Win32.SafeHandles.SafeProcessHandle processHandle)
        {
            SafeWaitHandle targetHandle = null;

            if (!Microsoft.Win32.NativeMethods.DuplicateHandle(new HandleRef(this, Microsoft.Win32.NativeMethods.GetCurrentProcess()), processHandle, new HandleRef(this, Microsoft.Win32.NativeMethods.GetCurrentProcess()), out targetHandle, 0, false, 2))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            base.SafeWaitHandle = targetHandle;
        }
Ejemplo n.º 9
0
		public static bool GetExitCodeProcess (SafeProcessHandle processHandle, out int exitCode)
		{
			bool release = false;
			try {
				processHandle.DangerousAddRef (ref release);
				return GetExitCodeProcess (processHandle.DangerousGetHandle (), out exitCode);
			} finally {
				if (release)
					processHandle.DangerousRelease ();
			}
		}
Ejemplo n.º 10
0
        public static int GetProcessIdFromHandle(Microsoft.Win32.SafeHandles.SafeProcessHandle processHandle)
        {
            Microsoft.Win32.NativeMethods.NtProcessBasicInfo info = new Microsoft.Win32.NativeMethods.NtProcessBasicInfo();
            int error = Microsoft.Win32.NativeMethods.NtQueryInformationProcess(processHandle, 0, info, Marshal.SizeOf(info), null);

            if (error != 0)
            {
                throw new InvalidOperationException(SR.GetString("CantGetProcessId"), new Win32Exception(error));
            }
            return(info.UniqueProcessId.ToInt32());
        }
Ejemplo n.º 11
0
		public Protect(SafeProcessHandle handle, VirtualQueryInfo info, int protect)
		{
			this.handle = handle;
			this.info = info;
			this.protect = protect;

			if (protect == info.Protect)
				return;

			int oldProtect;
			if (!Win32.VirtualProtectEx(handle.DangerousGetHandle(), (IntPtr)info.StartAddress, (IntPtr)info.RegionSize, protect, out oldProtect))
				throw new Win32Exception();
		}
Ejemplo n.º 12
0
 public static string GetItem(int row, int subitem, SafeProcessHandle hProcess)
 {
     IntPtr ptr;
     LV_ITEM lpBuffer = new LV_ITEM();
     lpBuffer.cchTextMax = 260;
     lpBuffer.mask = 1;
     lpBuffer.iItem = row;
     lpBuffer.iSubItem = subitem;
     StringBuilder builder = new StringBuilder(260);
     try
     {
         IntPtr ptr2;
         ptr = VirtualAllocEx(hProcess, IntPtr.Zero, 260, 0x1000, 4);
         lpBuffer.pszText = ptr;
         try
         {
             ptr2 = VirtualAllocEx(hProcess, IntPtr.Zero, lpBuffer.Size(), 0x1000, 4);
             int lpNumberOfBytesWritten = 0;
             if (!WriteProcessMemory(hProcess, ptr2, ref lpBuffer, lpBuffer.Size(), ref lpNumberOfBytesWritten))
             {
                 throw new Win32Exception();
             }
             SendMessage(listViewHandle, 0x102d, row, ptr2);
             lpNumberOfBytesWritten = 0;
             if (!ReadProcessMemory(hProcess, ptr, builder, 260, ref lpNumberOfBytesWritten))
             {
                 throw new Win32Exception();
             }
             lpNumberOfBytesWritten = 0;
             if (!ReadProcessMemory(hProcess, ptr2, ref lpBuffer, Marshal.SizeOf(lpBuffer), ref lpNumberOfBytesWritten))
             {
                 throw new Win32Exception();
             }
         }
         finally
         {
             if (!ptr2.Equals(IntPtr.Zero) && !VirtualFreeEx(hProcess, ptr2, 0, 0x8000))
             {
                 throw new Win32Exception();
             }
         }
     }
     finally
     {
         if (!ptr.Equals(IntPtr.Zero) && !VirtualFreeEx(hProcess, ptr, 0, 0x8000))
         {
             throw new Win32Exception();
         }
     }
     return builder.ToString();
 }
Ejemplo n.º 13
0
		public static bool DuplicateHandle(HandleRef hSourceProcessHandle, HandleRef hSourceHandle, HandleRef hTargetProcess,
			out SafeProcessHandle targetHandle, int dwDesiredAccess, bool bInheritHandle, int dwOptions)
		{
				MonoIOError error;
				IntPtr nakedTargetHandle;
				bool ret = MonoIO.DuplicateHandle (hSourceProcessHandle.Handle, hSourceHandle.Handle, hTargetProcess.Handle,
					out nakedTargetHandle, dwDesiredAccess, bInheritHandle ? 1 : 0, dwOptions, out error);

				if (error != MonoIOError.ERROR_SUCCESS)
					throw MonoIO.GetException (error);

				targetHandle = new SafeProcessHandle (nakedTargetHandle, true);
				return ret;
		}
Ejemplo n.º 14
0
        internal ProcessWaitHandle(SafeProcessHandle processHandle)
        {
            // Get the process ID from the process handle.  The handle is just a facade that wraps
            // the process ID, and closing the handle won't affect the process or its ID at all.
            // So we can grab it, and it's not "dangerous".
            int processId = (int)processHandle.DangerousGetHandle();

            // Create a wait state holder for this process ID.  This gives us access to the shared
            // wait state associated with this process.
            _waitStateHolder = new ProcessWaitState.Holder(processId);

            // Get the wait state's event, and use that event's safe wait handle
            // in place of ours.  This will let code register for completion notifications
            // on this ProcessWaitHandle and be notified when the wait state's handle completes.
            ManualResetEvent mre = _waitStateHolder._state.EnsureExitedEvent();
            this.SetSafeWaitHandle(mre.GetSafeWaitHandle());
        }
        internal ProcessWaitHandle( SafeProcessHandle processHandle): base() {
            SafeWaitHandle waitHandle = null;
            bool succeeded = NativeMethods.DuplicateHandle(
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                processHandle,
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                out waitHandle,
                0,
                false,
                NativeMethods.DUPLICATE_SAME_ACCESS);
                    
            if (!succeeded) {                    
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            this.SafeWaitHandle = waitHandle;         
        }
        internal ProcessWaitHandle(SafeProcessHandle processHandle)
        {
            SafeWaitHandle waitHandle = null;
            SafeProcessHandle currentProcHandle = Interop.mincore.GetCurrentProcess();
            bool succeeded = Interop.mincore.DuplicateHandle(
                currentProcHandle,
                processHandle,
                currentProcHandle,
                out waitHandle,
                0,
                false,
                Interop.DUPLICATE_SAME_ACCESS);

            if (!succeeded)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            this.SetSafeWaitHandle(waitHandle);
        }
        public static Microsoft.Win32.SafeHandles.SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited)
        {
            Microsoft.Win32.SafeHandles.SafeProcessHandle handle = Microsoft.Win32.NativeMethods.OpenProcess(access, false, processId);
            int error = Marshal.GetLastWin32Error();

            if (!handle.IsInvalid)
            {
                return(handle);
            }
            if (processId == 0)
            {
                throw new Win32Exception(5);
            }
            if (IsProcessRunning(processId))
            {
                throw new Win32Exception(error);
            }
            if (throwIfExited)
            {
                throw new InvalidOperationException(SR.GetString("ProcessHasExited", new object[] { processId.ToString(CultureInfo.CurrentCulture) }));
            }
            return(Microsoft.Win32.SafeHandles.SafeProcessHandle.InvalidHandle);
        }
Ejemplo n.º 18
0
        internal ProcessWaitHandle( SafeProcessHandle processHandle): base() {
            SafeWaitHandle waitHandle = null;
            bool succeeded = NativeMethods.DuplicateHandle(
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                processHandle,
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                out waitHandle,
                0,
                false,
                NativeMethods.DUPLICATE_SAME_ACCESS);
                    
            if (!succeeded) {                    
#if MONO
                // In Mono, Marshal.GetHRForLastWin32Error is not implemented;
                // and also DuplicateHandle throws its own exception rather
                // than returning false on error, so this code is unreachable.
                throw new SystemException("Unknown error in DuplicateHandle");
#else
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
#endif
            }

            this.SafeWaitHandle = waitHandle;         
        }
Ejemplo n.º 19
0
 //[ResourceExposure(ResourceScope.None)]
 public static extern bool GetExitCodeProcess(Microsoft.Win32.SafeHandles.SafeProcessHandle processHandle, out int exitCode);
Ejemplo n.º 20
0
 /// <summary>
 /// Assigns a process to an existing job object.
 /// </summary>
 /// <param name="hJob">A handle to the job object to which the process will be associated. </param>
 /// <param name="hProcess">A handle to the process to associate with the job object</param>
 /// <returns>If the function succeeds, the return value is nonzero.</returns>
 public static bool AssignProcessToJobObject(IntPtr hJob, ProcessPtr hProcess)
 => s_nativeMethods.AssignProcessToJobObject(hJob, hProcess);
Ejemplo n.º 21
0
 internal static extern bool TerminateProcess(SafeProcessHandle processHandle, int exitCode);
 internal static extern bool SetProcessWorkingSetSizeEx(SafeProcessHandle handle, IntPtr min, IntPtr max, int flags);
Ejemplo n.º 23
0
        private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly)
        {
            ModuleInfo[] infoArray2;
            if ((processId == SystemProcessID) || (processId == 0))
            {
                throw new Win32Exception(-2147467259, SR.GetString("EnumProcessModuleFailed"));
            }
            Microsoft.Win32.SafeHandles.SafeProcessHandle invalidHandle = Microsoft.Win32.SafeHandles.SafeProcessHandle.InvalidHandle;
            try
            {
                bool flag;
                invalidHandle = ProcessManager.OpenProcess(processId, 0x410, true);
                IntPtr[] ptrArray = new IntPtr[0x40];
                GCHandle handle2  = new GCHandle();
                int      needed   = 0;
Label_0045:
                flag = false;
                try
                {
                    handle2 = GCHandle.Alloc(ptrArray, GCHandleType.Pinned);
                    flag    = Microsoft.Win32.NativeMethods.EnumProcessModules(invalidHandle, handle2.AddrOfPinnedObject(), ptrArray.Length * IntPtr.Size, ref needed);
                    if (!flag)
                    {
                        bool flag2 = false;
                        bool flag3 = false;
                        if (!ProcessManager.IsOSOlderThanXP)
                        {
                            Microsoft.Win32.SafeHandles.SafeProcessHandle hProcess = Microsoft.Win32.SafeHandles.SafeProcessHandle.InvalidHandle;
                            try
                            {
                                hProcess = ProcessManager.OpenProcess(Microsoft.Win32.NativeMethods.GetCurrentProcessId(), 0x400, true);
                                if (!Microsoft.Win32.SafeNativeMethods.IsWow64Process(hProcess, ref flag2))
                                {
                                    throw new Win32Exception();
                                }
                                if (!Microsoft.Win32.SafeNativeMethods.IsWow64Process(invalidHandle, ref flag3))
                                {
                                    throw new Win32Exception();
                                }
                                if (flag2 && !flag3)
                                {
                                    throw new Win32Exception(0x12b, SR.GetString("EnumProcessModuleFailedDueToWow"));
                                }
                            }
                            finally
                            {
                                if (hProcess != Microsoft.Win32.SafeHandles.SafeProcessHandle.InvalidHandle)
                                {
                                    hProcess.Close();
                                }
                            }
                        }
                        for (int j = 0; j < 50; j++)
                        {
                            flag = Microsoft.Win32.NativeMethods.EnumProcessModules(invalidHandle, handle2.AddrOfPinnedObject(), ptrArray.Length * IntPtr.Size, ref needed);
                            if (flag)
                            {
                                goto Label_012F;
                            }
                            Thread.Sleep(1);
                        }
                    }
                }
                finally
                {
                    handle2.Free();
                }
Label_012F:
                if (!flag)
                {
                    throw new Win32Exception();
                }
                needed /= IntPtr.Size;
                if (needed > ptrArray.Length)
                {
                    ptrArray = new IntPtr[ptrArray.Length * 2];
                    goto Label_0045;
                }
                ArrayList list = new ArrayList();
                for (int i = 0; i < needed; i++)
                {
                    ModuleInfo info   = new ModuleInfo();
                    IntPtr     handle = ptrArray[i];
                    Microsoft.Win32.NativeMethods.NtModuleInfo ntModuleInfo = new Microsoft.Win32.NativeMethods.NtModuleInfo();
                    if (!Microsoft.Win32.NativeMethods.GetModuleInformation(invalidHandle, new HandleRef(null, handle), ntModuleInfo, Marshal.SizeOf(ntModuleInfo)))
                    {
                        throw new Win32Exception();
                    }
                    info.sizeOfImage = ntModuleInfo.SizeOfImage;
                    info.entryPoint  = ntModuleInfo.EntryPoint;
                    info.baseOfDll   = ntModuleInfo.BaseOfDll;
                    StringBuilder baseName = new StringBuilder(0x400);
                    if (Microsoft.Win32.NativeMethods.GetModuleBaseName(invalidHandle, new HandleRef(null, handle), baseName, baseName.Capacity * 2) == 0)
                    {
                        throw new Win32Exception();
                    }
                    info.baseName = baseName.ToString();
                    StringBuilder builder2 = new StringBuilder(0x400);
                    if (Microsoft.Win32.NativeMethods.GetModuleFileNameEx(invalidHandle, new HandleRef(null, handle), builder2, builder2.Capacity * 2) == 0)
                    {
                        throw new Win32Exception();
                    }
                    info.fileName = builder2.ToString();
                    if (string.Compare(info.fileName, @"\SystemRoot\System32\smss.exe", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        info.fileName = Path.Combine(Environment.SystemDirectory, "smss.exe");
                    }
                    if (((info.fileName != null) && (info.fileName.Length >= 4)) && info.fileName.StartsWith(@"\\?\", StringComparison.Ordinal))
                    {
                        info.fileName = info.fileName.Substring(4);
                    }
                    list.Add(info);
                    if (firstModuleOnly)
                    {
                        break;
                    }
                }
                ModuleInfo[] array = new ModuleInfo[list.Count];
                list.CopyTo(array, 0);
                infoArray2 = array;
            }
            finally
            {
                if (!invalidHandle.IsInvalid)
                {
                    invalidHandle.Close();
                }
            }
            return(infoArray2);
        }
Ejemplo n.º 24
0
 public static extern bool ReadProcessMemory(SafeProcessHandle hProcess, int lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);
Ejemplo n.º 25
0
		public static bool SetPriorityClass(SafeProcessHandle handle, int priorityClass)
		{
			bool release = false;
			try {
				handle.DangerousAddRef (ref release);
				return SetPriorityClass (handle.DangerousGetHandle (), priorityClass);
			} finally {
				if (release)
					handle.DangerousRelease ();
			}
		}
Ejemplo n.º 26
0
        private Boolean StartWithCreateProcess(ProcessStartInfo startInfo, Int32 flags)
        {
            if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
            {
                throw new InvalidOperationException("StandardOutputEncodingNotAllowed");
            }
            if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
            {
                throw new InvalidOperationException("StandardErrorEncodingNotAllowed");
            }
            if (this._disposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }
            StringBuilder stringBuilder = (StringBuilder)Private.s_BuildCommandLine.Invoke(null, new[] { startInfo.FileName, startInfo.Arguments });
            STARTUPINFO   lpStartupInfo = new STARTUPINFO();

            MyProcess.PROCESS_INFORMATION lpProcessInformation          = new MyProcess.PROCESS_INFORMATION();
            Microsoft.Win32.SafeHandles.SafeProcessHandle processHandle = null;
            SafeThreadHandle safeThreadHandle = new SafeThreadHandle();
            int            error         = 0;
            SafeFileHandle parentHandle1 = (SafeFileHandle)null;
            SafeFileHandle parentHandle2 = (SafeFileHandle)null;
            SafeFileHandle parentHandle3 = (SafeFileHandle)null;
            GCHandle       gcHandle      = new GCHandle();

            lock (typeof(Process).GetField("s_CreateProcessLock", BindingFlags.Static | BindingFlags.NonPublic))
            {
                try
                {
                    if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
                    {
                        if (startInfo.RedirectStandardInput)
                        {
                            this.CreatePipe(out parentHandle1, out lpStartupInfo.hStdInput, true);
                        }
                        else
                        {
                            lpStartupInfo.hStdInput = new SafeFileHandle(SafeNativeMethods.GetStdHandle(-10), false);
                        }
                        if (startInfo.RedirectStandardOutput)
                        {
                            this.CreatePipe(out parentHandle2, out lpStartupInfo.hStdOutput, false);
                        }
                        else
                        {
                            lpStartupInfo.hStdOutput = new SafeFileHandle(SafeNativeMethods.GetStdHandle(-11), false);
                        }
                        if (startInfo.RedirectStandardError)
                        {
                            this.CreatePipe(out parentHandle3, out lpStartupInfo.hStdError, false);
                        }
                        else
                        {
                            lpStartupInfo.hStdError = new SafeFileHandle(SafeNativeMethods.GetStdHandle(-12), false);
                        }
                        lpStartupInfo.dwFlags = 256;
                    }

                    int num1 = flags;
                    if (startInfo.CreateNoWindow)
                    {
                        num1 |= 134217728;
                    }
                    IntPtr num2 = (IntPtr)0;
                    // Not supported
                    //if (startInfo.environmentVariables != null)
                    //{
                    //    bool unicode = false;
                    //    if (ProcessManager.IsNt)
                    //    {
                    //        num1 |= 1024;
                    //        unicode = true;
                    //    }

                    //    gcHandle = GCHandle.Alloc((object)EnvironmentBlock.ToByteArray(startInfo.environmentVariables, unicode), GCHandleType.Pinned);
                    //    num2 = gcHandle.AddrOfPinnedObject();
                    //}

                    string lpCurrentDirectory = startInfo.WorkingDirectory;
                    if (lpCurrentDirectory == String.Empty)
                    {
                        lpCurrentDirectory = Environment.CurrentDirectory;
                    }
                    if (startInfo.UserName.Length != 0)
                    {
                        throw new NotSupportedException("startInfo.UserName.Length != 0");
                    }
                    else
                    {
                        RuntimeHelpers.PrepareConstrainedRegions();
                        bool process;
                        try
                        {
                        }
                        finally
                        {
                            process = SafeNativeMethods.CreateProcess((string)null, stringBuilder, IntPtr.Zero, IntPtr.Zero, true, num1, num2, lpCurrentDirectory, lpStartupInfo, out lpProcessInformation);
                            if (!process)
                            {
                                error = Marshal.GetLastWin32Error();
                            }
                            if (lpProcessInformation.hProcess != (IntPtr)0 && lpProcessInformation.hProcess != new IntPtr(-1))
                            {
                                processHandle = new Microsoft.Win32.SafeHandles.SafeProcessHandle(lpProcessInformation.hProcess, true);
                            }
                            if (lpProcessInformation.hThread != (IntPtr)0 && lpProcessInformation.hThread != new IntPtr(-1))
                            {
                                safeThreadHandle.InitialSetHandle(lpProcessInformation.hThread);
                            }
                        }

                        if (!process)
                        {
                            if (error == 193 || error == 216)
                            {
                                throw new Win32Exception(error, "InvalidApplication");
                            }
                            throw new Win32Exception(error);
                        }
                    }
                }
                finally
                {
                    if (gcHandle.IsAllocated)
                    {
                        gcHandle.Free();
                    }
                    lpStartupInfo.Dispose();
                }
            }

            if (startInfo.RedirectStandardInput)
            {
                var sw = new StreamWriter((Stream) new FileStream(parentHandle1, FileAccess.Write, 4096, false), Console.InputEncoding, 4096);
                sw.AutoFlush = true;

                Private.standardInput.SetValue(this, sw);
            }

            if (startInfo.RedirectStandardOutput)
            {
                Encoding encoding = startInfo.StandardOutputEncoding != null ? startInfo.StandardOutputEncoding : Console.OutputEncoding;
                var      sr       = new StreamReader((Stream) new FileStream(parentHandle2, FileAccess.Read, 4096, false), encoding, true, 4096);

                Private.standardOutput.SetValue(this, sr);
            }

            if (startInfo.RedirectStandardError)
            {
                Encoding encoding = startInfo.StandardErrorEncoding != null ? startInfo.StandardErrorEncoding : Console.OutputEncoding;
                var      sr       = new StreamReader((Stream) new FileStream(parentHandle3, FileAccess.Read, 4096, false), encoding, true, 4096);

                Private.standardError.SetValue(this, sr);
            }

            bool flag = false;

            if (processHandle != null && !processHandle.IsInvalid)
            {
                Private.SetProcessHandle.Invoke(this, new[] { processHandle });
                Private.SetProcessId.Invoke(this, new Object[] { lpProcessInformation.dwProcessId });
                ProcessInformation = lpProcessInformation;
                _mainThread        = safeThreadHandle;
                flag = true;
            }

            return(flag);
        }
Ejemplo n.º 27
0
		public static bool SetProcessWorkingSetSize (SafeProcessHandle handle, IntPtr min, IntPtr max)
		{
			bool release = false;
			try {
				handle.DangerousAddRef (ref release);
				return SetProcessWorkingSetSize (handle.DangerousGetHandle (), min, max);
			} finally {
				if (release)
					handle.DangerousRelease ();
			}
		}
Ejemplo n.º 28
0
		static string ProcessName_internal(SafeProcessHandle handle)
		{
			bool release = false;
			try {
				handle.DangerousAddRef (ref release);
				return ProcessName_internal (handle.DangerousGetHandle ());
			} finally {
				if (release)
					handle.DangerousRelease ();
			}
		}
Ejemplo n.º 29
0
 public static extern int WaitForInputIdle(SafeProcessHandle handle, int milliseconds); 
Ejemplo n.º 30
0
 public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) {
     if (IsNt)
         return NtProcessManager.GetProcessIdFromHandle(processHandle);
     else
         throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
 }
 public static extern bool IsWow64Process(Microsoft.Win32.SafeHandles.SafeProcessHandle hProcess, ref bool Wow64Process);
Ejemplo n.º 32
0
 /// <inheritdoc />
 public bool AssignProcessToJobObject(IntPtr hJob, ProcessPtr hProcess)
 => ExternAssignProcessToJobObject(hJob, hProcess);
Ejemplo n.º 33
0
		public static int WaitForInputIdle (SafeProcessHandle handle, int milliseconds)
		{
			bool release = false;
			try {
				handle.DangerousAddRef (ref release);
				return WaitForInputIdle (handle.DangerousGetHandle (), milliseconds);
			} finally {
				if (release)
					handle.DangerousRelease ();
			}
		}
Ejemplo n.º 34
0
 private static extern bool ExternAssignProcessToJobObject(IntPtr hJob, ProcessPtr hProcess);
Ejemplo n.º 35
0
		public static bool GetProcessTimes (SafeProcessHandle handle, out long creation, out long exit, out long kernel, out long user)
		{
			bool release = false;
			try {
				handle.DangerousAddRef (ref release);
				return GetProcessTimes (handle.DangerousGetHandle (), out creation, out exit, out kernel, out user);
			} finally {
				if (release)
					handle.DangerousRelease ();
			}
		}
Ejemplo n.º 36
0
 static extern int VirtualQueryEx(SafeProcessHandle hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);
Ejemplo n.º 37
0
        private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine)
        {
            IntSecurity.UnmanagedCode.Demand();
            if ((outputName == null) || (outputName.Length == 0))
            {
                outputName = tempFiles.AddExtension("out");
            }
            if ((errorName == null) || (errorName.Length == 0))
            {
                errorName = tempFiles.AddExtension("err");
            }
            FileStream stream  = CreateInheritedFile(outputName);
            FileStream stream2 = CreateInheritedFile(errorName);
            bool       flag    = false;

            Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION();
            Microsoft.Win32.SafeHandles.SafeProcessHandle         processHandle        = new Microsoft.Win32.SafeHandles.SafeProcessHandle();
            Microsoft.Win32.SafeHandles.SafeThreadHandle          handle2 = new Microsoft.Win32.SafeHandles.SafeThreadHandle();
            SafeUserTokenHandle hNewToken = null;

            try
            {
                Microsoft.Win32.NativeMethods.STARTUPINFO startupinfo;
                StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
                writer.Write(currentDir);
                writer.Write("> ");
                writer.WriteLine((trueCmdLine != null) ? trueCmdLine : cmd);
                writer.WriteLine();
                writer.WriteLine();
                writer.Flush();
                startupinfo = new Microsoft.Win32.NativeMethods.STARTUPINFO {
                    cb          = Marshal.SizeOf(startupinfo),
                    dwFlags     = 0x101,
                    wShowWindow = 0,
                    hStdOutput  = stream.SafeFileHandle,
                    hStdError   = stream2.SafeFileHandle,
                    hStdInput   = new SafeFileHandle(Microsoft.Win32.UnsafeNativeMethods.GetStdHandle(-10), false)
                };
                StringDictionary sd = new StringDictionary();
                foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
                {
                    sd[(string)entry.Key] = (string)entry.Value;
                }
                sd["_ClrRestrictSecAttributes"] = "1";
                byte[] buffer = EnvironmentBlock.ToByteArray(sd, false);
                try
                {
                    fixed(byte *numRef = buffer)
                    {
                        IntPtr lpEnvironment = new IntPtr((void *)numRef);

                        if ((userToken == null) || userToken.IsInvalid)
                        {
                            RuntimeHelpers.PrepareConstrainedRegions();
                            try
                            {
                                goto Label_0325;
                            }
                            finally
                            {
                                flag = Microsoft.Win32.NativeMethods.CreateProcess(null, new StringBuilder(cmd), null, null, true, 0, lpEnvironment, currentDir, startupinfo, lpProcessInformation);
                                if ((lpProcessInformation.hProcess != IntPtr.Zero) && (lpProcessInformation.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE))
                                {
                                    processHandle.InitialSetHandle(lpProcessInformation.hProcess);
                                }
                                if ((lpProcessInformation.hThread != IntPtr.Zero) && (lpProcessInformation.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE))
                                {
                                    handle2.InitialSetHandle(lpProcessInformation.hThread);
                                }
                            }
                        }
                        flag = SafeUserTokenHandle.DuplicateTokenEx(userToken, 0xf01ff, null, 2, 1, out hNewToken);
                        if (flag)
                        {
                            RuntimeHelpers.PrepareConstrainedRegions();
                            try
                            {
                            }
                            finally
                            {
                                flag = Microsoft.Win32.NativeMethods.CreateProcessAsUser(hNewToken, null, cmd, null, null, true, 0, new HandleRef(null, lpEnvironment), currentDir, startupinfo, lpProcessInformation);
                                if ((lpProcessInformation.hProcess != IntPtr.Zero) && (lpProcessInformation.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE))
                                {
                                    processHandle.InitialSetHandle(lpProcessInformation.hProcess);
                                }
                                if ((lpProcessInformation.hThread != IntPtr.Zero) && (lpProcessInformation.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE))
                                {
                                    handle2.InitialSetHandle(lpProcessInformation.hThread);
                                }
                            }
                        }
                    }
                }
                finally
                {
                    numRef = null;
                }
            }
            finally
            {
                if ((!flag && (hNewToken != null)) && !hNewToken.IsInvalid)
                {
                    hNewToken.Close();
                    hNewToken = null;
                }
                stream.Close();
                stream2.Close();
            }
Label_0325:
            if (flag)
            {
                try
                {
                    bool flag2;
                    ProcessWaitHandle handle4 = null;
                    try
                    {
                        handle4 = new ProcessWaitHandle(processHandle);
                        flag2   = handle4.WaitOne(0x927c0, false);
                    }
                    finally
                    {
                        if (handle4 != null)
                        {
                            handle4.Close();
                        }
                    }
                    if (!flag2)
                    {
                        throw new ExternalException(SR.GetString("ExecTimeout", new object[] { cmd }), 0x102);
                    }
                    int exitCode = 0x103;
                    if (!Microsoft.Win32.NativeMethods.GetExitCodeProcess(processHandle, out exitCode))
                    {
                        throw new ExternalException(SR.GetString("ExecCantGetRetCode", new object[] { cmd }), Marshal.GetLastWin32Error());
                    }
                    return(exitCode);
                }
                finally
                {
                    processHandle.Close();
                    handle2.Close();
                    if ((hNewToken != null) && !hNewToken.IsInvalid)
                    {
                        hNewToken.Close();
                    }
                }
            }
            int error = Marshal.GetLastWin32Error();

            if (error == 8)
            {
                throw new OutOfMemoryException();
            }
            Win32Exception    inner      = new Win32Exception(error);
            ExternalException exception2 = new ExternalException(SR.GetString("ExecCantExec", new object[] { cmd }), inner);

            throw exception2;
        }
Ejemplo n.º 38
0
 public MemoryScanner(Process process)
 {
     processHandle = OpenProcess(process);
 }
Ejemplo n.º 39
0
 public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) {
     NativeMethods.NtProcessBasicInfo info = new NativeMethods.NtProcessBasicInfo();
     int status = NativeMethods.NtQueryInformationProcess(processHandle, NativeMethods.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null);
     if (status != 0) {
         throw new InvalidOperationException(SR.GetString(SR.CantGetProcessId), new Win32Exception(status));
     }
     // We should change the signature of this function and ID property in process class.
     return info.UniqueProcessId.ToInt32();
 }
Ejemplo n.º 40
0
 /// <inheritdoc />
 public bool AssignProcessToJobObject(IntPtr hJob, ProcessPtr hProcess)
 => throw new NotImplementedException();
Ejemplo n.º 41
0
		ProcessModule[] GetModules_internal (SafeProcessHandle handle)
		{
			bool release = false;
			try {
				handle.DangerousAddRef (ref release);
				return GetModules_internal (handle.DangerousGetHandle ());
			} finally {
				if (release)
					handle.DangerousRelease ();
			}
		}
 internal static extern bool GetProcessPriorityBoost(SafeProcessHandle handle, out bool disabled);
Ejemplo n.º 43
0
		/* Private constructor called from other methods */
		private Process (SafeProcessHandle handle, int id) {
			SetProcessHandle (handle);
			SetProcessId (id);
		}
Ejemplo n.º 44
0
 private static extern int NtQueryInformationProcess(SafeProcessHandle hProcess, PROCESSINFOCLASS pic, ref PROCESS_BASIC_INFORMATION pbi, int cb, ref int pSize);