Пример #1
0
        internal ProcessWaitHandle(SafeProcessHandle processHandle)
        {
            SafeWaitHandle waitHandle;
            bool succeeded = NativeMethods.DuplicateHandle(
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                processHandle,
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                out waitHandle,
                0,
                false,
                (int)DuplicateOptions.DUPLICATE_SAME_ACCESS);

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

            this.SafeWaitHandle = waitHandle;
        }
Пример #2
0
        internal RemoteMemoryBlock(int cbSize, SafeProcessHandle processHandle) : base(true)
        {
            _processHandle = processHandle;

            SetHandle(Misc.VirtualAllocEx(_processHandle, IntPtr.Zero, new UIntPtr((uint)cbSize), UnsafeNativeMethods.MEM_COMMIT, UnsafeNativeMethods.PAGE_READWRITE));
        }
Пример #3
0
 public static extern bool WriteProcessMemory(SafeProcessHandle processHandle, IntPtr lpBaseAddress, byte[] lpBuffer, SizeT nSize,
     ref SizeT lpNumberOfBytesWritten);
Пример #4
0
        public static bool CreateProcess(ProcessStartInfo startInfo, bool createSuspended, out SafeProcessHandle process, out SafeThreadHandle thread, out uint processID, out uint threadID)
        {
            StringBuilder cmdLine = BuildCommandLine(startInfo.FileName, startInfo.Arguments);
            STARTUPINFO lpStartupInfo = new STARTUPINFO();
            PROCESS_INFORMATION lpProcessInformation = new PROCESS_INFORMATION();
            SafeProcessHandle processHandle = new SafeProcessHandle();
            SafeThreadHandle threadHandle = new SafeThreadHandle();
            GCHandle environment = new GCHandle();
            int creationFlags = 0;
            bool success;

            creationFlags = CREATE_DEFAULT_ERROR_MODE | CREATE_PRESERVE_CODE_AUTHZ_LEVEL;

            if (createSuspended)
                creationFlags |= CREATE_SUSPENDED;

            if (startInfo.CreateNoWindow)
                creationFlags |= CREATE_NO_WINDOW;

            IntPtr pinnedEnvironment = IntPtr.Zero;

            if (startInfo.EnvironmentVariables != null)
            {
                bool unicode = false;
                if (IsNt)
                {
                    creationFlags |= CREATE_UNICODE_ENVIRONMENT;
                    unicode = true;
                }
                environment = GCHandle.Alloc(EnvironmentToByteArray(startInfo.EnvironmentVariables, unicode), GCHandleType.Pinned);
                pinnedEnvironment = environment.AddrOfPinnedObject();
            }

            string workingDirectory = startInfo.WorkingDirectory;
            if (workingDirectory == "")
                workingDirectory = Environment.CurrentDirectory;

            success = CreateProcess(null, cmdLine, null, null, false, creationFlags, pinnedEnvironment, workingDirectory, lpStartupInfo, lpProcessInformation);

            if ((lpProcessInformation.hProcess != IntPtr.Zero) && (lpProcessInformation.hProcess != INVALID_HANDLE_VALUE))
                processHandle.InitialSetHandle(lpProcessInformation.hProcess);

            if ((lpProcessInformation.hThread != IntPtr.Zero) && (lpProcessInformation.hThread != INVALID_HANDLE_VALUE))
                threadHandle.InitialSetHandle(lpProcessInformation.hThread);

            if (environment.IsAllocated)
                environment.Free();

            lpStartupInfo.Dispose();

            if (success && !processHandle.IsInvalid && !threadHandle.IsInvalid)
            {
                process = processHandle;
                thread = threadHandle;
                processID = lpProcessInformation.dwProcessId;
                threadID = lpProcessInformation.dwThreadId;
                return true;
            }

            process = null;
            thread = null;
            processID = 0;
            threadID = 0;
            return false;
        }
Пример #5
0
        private unsafe int Read(SafeProcessHandle handle, uint offset, uint size, byte* pBuffer)
        {
            if (Address == IntPtr.Zero)
                throw new ObjectDisposedException("RemoteMemoryRegion");
            if ((offset + size) > Size)
                throw new ArgumentException("Size too large for region");

            int bytesRead = 0, result;
            result = Win32.ReadProcessMemory(
                handle.DangerousGetHandle(),
                (uint)(Address.ToInt64() + offset),
                new IntPtr(pBuffer), size, out bytesRead
            );

            if (result == 0 || bytesRead != size) {
                var error = Win32.GetLastError();
                throw new Exception(String.Format("Read failed: Error {0:x8}", error));
            }

            return bytesRead;
        }
Пример #6
0
 internal static extern bool SetProcessAffinityMask(SafeProcessHandle handle, IntPtr mask);
Пример #7
0
        public void Protect(SafeProcessHandle handle, uint offset, uint size, MemoryProtection newProtect)
        {
            if (Address == IntPtr.Zero)
                throw new ObjectDisposedException("RemoteMemoryRegion");
            if ((offset + size) > (Size))
                throw new ArgumentException("Size too large for region");

            MemoryProtection oldProtect;
            int result = Win32.VirtualProtectEx(
                handle.DangerousGetHandle(),
                (uint)(Address.ToInt64() + offset),
                size, newProtect, out oldProtect
            );

            if (result == 0) {
                var error = Win32.GetLastError();
                throw new Exception(String.Format("Protect failed: Error {0:x8}", error));
            }
        }
 internal static extern int GetModuleBaseName(SafeProcessHandle processHandle, IntPtr moduleHandle, [Out] char[] baseName, int size);
Пример #9
0
 /// <summary>Gets the ID of a process from a handle to the process.</summary>
 /// <param name="processHandle">The handle.</param>
 /// <returns>The process ID.</returns>
 public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
 {
     return(NtProcessManager.GetProcessIdFromHandle(processHandle));
 }
 private static extern ProcessPriorityClass GetPriorityClass(SafeProcessHandle handle);
 private static extern bool SetPriorityClass(SafeProcessHandle handle, ProcessPriorityClass priorityClass);
 private static extern bool GetExitCodeProcess(SafeProcessHandle hProcess, out uint lpExitCode);
 private static extern bool TerminateProcess(SafeProcessHandle hProcess, uint uExitCode);
    /// <summary>
    /// Calls <see cref="CreateProcessAsUserW"/> and safely stores the obtained handles.
    /// </summary>
    /// <param name="userToken">Token to impersonate the external process</param>
    /// <param name="createFlags">Flags used to create the external process</param>
    /// <param name="startupInfo">Startup information used to create the external process</param>
    /// <returns><c>true</c> if the call to <see cref="CreateProcessAsUserW"/> was successful; otherwise <c>false</c></returns>
    private bool SafeCreateProcessAsUserW(IntPtr userToken, CreateProcessFlags createFlags, StartupInfo startupInfo)
    {
      _processHandle = new SafeProcessHandle();
      var threadHandle = new SafeThreadHandle();
      bool success;

      // The following is necessary to make sure that processInformation.hProcess and processInformation.hThread
      // are safely stored in the respective SafeHandle classes. It is, unfortunately, not possible to define
      // processInformation.hProcess and processInformation.hThread as SafeHandles and use processInformation
      // as an out parameter, because the unmanaged code is not able to create these objects. We therefore use
      // IntPtr and ensure in the following that the IntPtrs are stored in SafeHandle objects immediately after
      // they have been obtained.
      // For details see here: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.prepareconstrainedregions(v=vs.110).aspx
      RuntimeHelpers.PrepareConstrainedRegions();
      try { }
      finally
      {
        ProcessInformation processInformation;
        success = CreateProcessAsUserW(userToken, null, GetCommandLine(), IntPtr.Zero, IntPtr.Zero, true, createFlags, IntPtr.Zero, null, startupInfo, out processInformation);
        if (success)
        {
          _processHandle.InitialSetHandle(processInformation.hProcess);
          threadHandle.InitialSetHandle(processInformation.hThread);
          _processId = processInformation.dwProcessId;
        }
      }
      
      // We don't need the threadHandle and therefore immediately dispose it.
      threadHandle.Dispose();

      if (success)
        return true;

      _processHandle.Dispose();
      var error = Marshal.GetLastWin32Error();
      _debugLogger.Error("AsyncImpersonationProcess ({0}): Cannot start process. ErrorCode: {1} ({2})", StartInfo.FileName, error, new Win32Exception(error).Message);
      return false;
    }
Пример #15
0
 internal static extern bool SymFromName(SafeProcessHandle processHandle, string name, out byte symbol);
Пример #16
0
 public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
 {
     return(Interop.Kernel32.GetProcessId(processHandle));
 }
Пример #17
0
 internal static extern int SymLoadModule(SafeProcessHandle processHandle, IntPtr fileHandle, string imageName, string?moduleName, int dllBase, int dllSize);
Пример #18
0
        /// <summary>Gets a value indicating whether the associated process has been terminated.</summary>
        /// <param name="exitCode">The exit code, if it could be determined; otherwise, null.</param>
        private bool GetHasExited(out int?exitCode)
        {
            SafeProcessHandle handle = null;

            try
            {
                handle = GetProcessHandle(Interop.PROCESS_QUERY_INFORMATION | Interop.SYNCHRONIZE, false);
                if (handle.IsInvalid)
                {
                    exitCode = null;
                    return(true);
                }
                else
                {
                    int localExitCode;

                    // Although this is the wrong way to check whether the process has exited,
                    // it was historically the way we checked for it, and a lot of code then took a dependency on
                    // the fact that this would always be set before the pipes were closed, so they would read
                    // the exit code out after calling ReadToEnd() or standard output or standard error. In order
                    // to allow 259 to function as a valid exit code and to break as few people as possible that
                    // took the ReadToEnd dependency, we check for an exit code before doing the more correct
                    // check to see if we have been signalled.
                    if (Interop.mincore.GetExitCodeProcess(handle, out localExitCode) && localExitCode != Interop.STILL_ACTIVE)
                    {
                        exitCode = localExitCode;
                        return(true);
                    }
                    else
                    {
                        // The best check for exit is that the kernel process object handle is invalid,
                        // or that it is valid and signaled.  Checking if the exit code != STILL_ACTIVE
                        // does not guarantee the process is closed,
                        // since some process could return an actual STILL_ACTIVE exit code (259).
                        if (!_signaled) // if we just came from WaitForExit, don't repeat
                        {
                            using (var wh = new ProcessWaitHandle(handle))
                            {
                                _signaled = wh.WaitOne(0);
                            }
                        }
                        if (_signaled)
                        {
                            if (!Interop.mincore.GetExitCodeProcess(handle, out localExitCode))
                            {
                                throw new Win32Exception();
                            }

                            exitCode = localExitCode;
                            return(true);
                        }
                    }
                }

                exitCode = null;
                return(false);
            }
            finally
            {
                ReleaseProcessHandle(handle);
            }
        }
Пример #19
0
 public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
 {
     return NtProcessManager.GetProcessIdFromHandle(processHandle);
 }
Пример #20
0
        /// <summary>Starts the process using the supplied start info.</summary>
        /// <param name="startInfo">The start info with which to start the process.</param>
        private bool StartCore(ProcessStartInfo startInfo)
        {
            if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
            {
                throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed);
            }

            if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
            {
                throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed);
            }

            // See knowledge base article Q190351 for an explanation of the following code.  Noteworthy tricky points:
            //    * The handles are duplicated as non-inheritable before they are passed to CreateProcess so
            //      that the child process can not close them
            //    * CreateProcess allows you to redirect all or none of the standard IO handles, so we use
            //      GetStdHandle for the handles that are not being redirected

            //Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            StringBuilder commandLine = BuildCommandLine(startInfo.FileName, startInfo.Arguments);

            Interop.STARTUPINFO         startupInfo     = new Interop.STARTUPINFO();
            Interop.PROCESS_INFORMATION processInfo     = new Interop.PROCESS_INFORMATION();
            Interop.SECURITY_ATTRIBUTES unused_SecAttrs = new Interop.SECURITY_ATTRIBUTES();
            SafeProcessHandle           procSH          = new SafeProcessHandle();
            SafeThreadHandle            threadSH        = new SafeThreadHandle();
            bool retVal;
            int  errorCode = 0;
            // handles used in parent process
            SafeFileHandle standardInputWritePipeHandle = null;
            SafeFileHandle standardOutputReadPipeHandle = null;
            SafeFileHandle standardErrorReadPipeHandle  = null;
            GCHandle       environmentHandle            = new GCHandle();

            lock (s_createProcessLock)
            {
                try
                {
                    // set up the streams
                    if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
                    {
                        if (startInfo.RedirectStandardInput)
                        {
                            CreatePipe(out standardInputWritePipeHandle, out startupInfo.hStdInput, true);
                        }
                        else
                        {
                            startupInfo.hStdInput = new SafeFileHandle(Interop.mincore.GetStdHandle(Interop.STD_INPUT_HANDLE), false);
                        }

                        if (startInfo.RedirectStandardOutput)
                        {
                            CreatePipe(out standardOutputReadPipeHandle, out startupInfo.hStdOutput, false);
                        }
                        else
                        {
                            startupInfo.hStdOutput = new SafeFileHandle(Interop.mincore.GetStdHandle(Interop.STD_OUTPUT_HANDLE), false);
                        }

                        if (startInfo.RedirectStandardError)
                        {
                            CreatePipe(out standardErrorReadPipeHandle, out startupInfo.hStdError, false);
                        }
                        else
                        {
                            startupInfo.hStdError = new SafeFileHandle(Interop.mincore.GetStdHandle(Interop.STD_ERROR_HANDLE), false);
                        }

                        startupInfo.dwFlags = Interop.STARTF_USESTDHANDLES;
                    }

                    // set up the creation flags paramater
                    int creationFlags = 0;
                    if (startInfo.CreateNoWindow)
                    {
                        creationFlags |= Interop.CREATE_NO_WINDOW;
                    }

                    // set up the environment block parameter
                    IntPtr environmentPtr = (IntPtr)0;
                    if (startInfo._environmentVariables != null)
                    {
                        creationFlags |= Interop.CREATE_UNICODE_ENVIRONMENT;
                        byte[] environmentBytes = EnvironmentVariablesToByteArray(startInfo._environmentVariables);
                        environmentHandle = GCHandle.Alloc(environmentBytes, GCHandleType.Pinned);
                        environmentPtr    = environmentHandle.AddrOfPinnedObject();
                    }
                    string workingDirectory = startInfo.WorkingDirectory;
                    if (workingDirectory == string.Empty)
                    {
                        workingDirectory = Directory.GetCurrentDirectory();
                    }

                    try { }
                    finally
                    {
                        retVal = Interop.mincore.CreateProcess(
                            null,                // we don't need this since all the info is in commandLine
                            commandLine,         // pointer to the command line string
                            unused_SecAttrs,     // address to process security attributes, we don't need to inheriat the handle
                            unused_SecAttrs,     // address to thread security attributes.
                            true,                // handle inheritance flag
                            creationFlags,       // creation flags
                            environmentPtr,      // pointer to new environment block
                            workingDirectory,    // pointer to current directory name
                            startupInfo,         // pointer to STARTUPINFO
                            processInfo          // pointer to PROCESS_INFORMATION
                            );
                        if (!retVal)
                        {
                            errorCode = Marshal.GetLastWin32Error();
                        }
                        if (processInfo.hProcess != (IntPtr)0 && processInfo.hProcess != (IntPtr)Interop.INVALID_HANDLE_VALUE)
                        {
                            procSH.InitialSetHandle(processInfo.hProcess);
                        }
                        if (processInfo.hThread != (IntPtr)0 && processInfo.hThread != (IntPtr)Interop.INVALID_HANDLE_VALUE)
                        {
                            threadSH.InitialSetHandle(processInfo.hThread);
                        }
                    }
                    if (!retVal)
                    {
                        if (errorCode == Interop.ERROR_BAD_EXE_FORMAT || errorCode == Interop.ERROR_EXE_MACHINE_TYPE_MISMATCH)
                        {
                            throw new Win32Exception(errorCode, SR.InvalidApplication);
                        }
                        throw new Win32Exception(errorCode);
                    }
                }
                finally
                {
                    // free environment block
                    if (environmentHandle.IsAllocated)
                    {
                        environmentHandle.Free();
                    }

                    startupInfo.Dispose();
                }
            }

            if (startInfo.RedirectStandardInput)
            {
                Encoding enc = GetEncoding((int)Interop.mincore.GetConsoleCP());
                _standardInput           = new StreamWriter(new FileStream(standardInputWritePipeHandle, FileAccess.Write, 4096, false), enc, 4096);
                _standardInput.AutoFlush = true;
            }
            if (startInfo.RedirectStandardOutput)
            {
                Encoding enc = (startInfo.StandardOutputEncoding != null) ? startInfo.StandardOutputEncoding : GetEncoding((int)Interop.mincore.GetConsoleOutputCP());
                _standardOutput = new StreamReader(new FileStream(standardOutputReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096);
            }
            if (startInfo.RedirectStandardError)
            {
                Encoding enc = (startInfo.StandardErrorEncoding != null) ? startInfo.StandardErrorEncoding : GetEncoding((int)Interop.mincore.GetConsoleOutputCP());
                _standardError = new StreamReader(new FileStream(standardErrorReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096);
            }

            bool ret = false;

            if (!procSH.IsInvalid)
            {
                SetProcessHandle(procSH);
                SetProcessId((int)processInfo.dwProcessId);
                threadSH.Dispose();
                ret = true;
            }

            return(ret);
        }
Пример #21
0
        public byte[] ReadBytes(SafeProcessHandle handle, uint offset, uint size)
        {
            if (size == 0)
                return null;

            byte[] buffer = new byte[size];
            Read(handle, offset, (uint)size, buffer);
            return buffer;
        }
 internal static partial bool SetPriorityClass(SafeProcessHandle handle, int priorityClass);
Пример #23
0
 private bool StartWithCreateProcess(ProcessStartInfo startInfo)
 {
     if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
     {
         throw new InvalidOperationException("StandardOutputEncodingNotAllowed");
     }
     if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
     {
         throw new InvalidOperationException("StandardErrorEncodingNotAllowed");
     }
     StringBuilder stringBuilder = Process2.BuildCommandLine(startInfo.FileName, startInfo.Arguments);
     NativeMethods.STARTUPINFO sTARTUPINFO = new NativeMethods.STARTUPINFO();
     SafeNativeMethods.PROCESS_INFORMATION pROCESS_INFORMATION = new SafeNativeMethods.PROCESS_INFORMATION();
     SafeProcessHandle safeProcessHandle = new SafeProcessHandle();
     SafeThreadHandle safeThreadHandle = new SafeThreadHandle();
     int num = 0;
     SafeFileHandle handle = null;
     SafeFileHandle handle2 = null;
     SafeFileHandle handle3 = null;
     GCHandle gCHandle = default(GCHandle);
     lock (Process2.s_CreateProcessLock)
     {
         try
         {
             if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
             {
                 if (startInfo.RedirectStandardInput)
                 {
                     CreatePipe(out handle, out sTARTUPINFO.hStdInput, true);
                 }
                 else
                 {
                     sTARTUPINFO.hStdInput = new SafeFileHandle(NativeMethods.GetStdHandle(-10), false);
                 }
                 if (startInfo.RedirectStandardOutput)
                 {
                     CreatePipe(out handle2, out sTARTUPINFO.hStdOutput, false);
                 }
                 else
                 {
                     sTARTUPINFO.hStdOutput = new SafeFileHandle(NativeMethods.GetStdHandle(-11), false);
                 }
                 if (startInfo.RedirectStandardError)
                 {
                     CreatePipe(out handle3, out sTARTUPINFO.hStdError, false);
                 }
                 else
                 {
                     sTARTUPINFO.hStdError = sTARTUPINFO.hStdOutput;
                 }
                 sTARTUPINFO.dwFlags = 256;
             }
             int num2 = 0;
             if (startInfo.CreateNoWindow)
             {
                 num2 |= 134217728;
             }
             IntPtr intPtr = (IntPtr)0;
             //if (startInfo.environmentVariables != null)
             //{
             //    bool unicode = false;
             //    if (ProcessManager.IsNt)
             //    {
             //        num2 |= 1024;
             //        unicode = true;
             //    }
             //    byte[] value = EnvironmentBlock.ToByteArray(startInfo.environmentVariables, unicode);
             //    gCHandle = GCHandle.Alloc(value, GCHandleType.Pinned);
             //    intPtr = gCHandle.AddrOfPinnedObject();
             //}
             string text = startInfo.WorkingDirectory;
             if (text == string.Empty)
             {
                 text = Environment.CurrentDirectory;
             }
             bool flag2;
             //if (startInfo.UserName.Length != 0)
             //{
             //    NativeMethods.LogonFlags logonFlags = (NativeMethods.LogonFlags)0;
             //    if (startInfo.LoadUserProfile)
             //    {
             //        logonFlags = NativeMethods.LogonFlags.LOGON_WITH_PROFILE;
             //    }
             //    IntPtr intPtr2 = IntPtr.Zero;
             //    try
             //    {
             //        if (startInfo.Password == null)
             //        {
             //            intPtr2 = Marshal.StringToCoTaskMemUni(string.Empty);
             //        }
             //        else
             //        {
             //            intPtr2 = Marshal.SecureStringToCoTaskMemUnicode(startInfo.Password);
             //        }
             //        RuntimeHelpers.PrepareConstrainedRegions();
             //        try
             //        {
             //        }
             //        finally
             //        {
             //            flag2 = NativeMethods.CreateProcessWithLogonW(startInfo.UserName, startInfo.Domain, intPtr2, logonFlags, null, stringBuilder, num2, intPtr, text, sTARTUPINFO, pROCESS_INFORMATION);
             //            if (!flag2)
             //            {
             //                num = Marshal.GetLastWin32Error();
             //            }
             //            if (pROCESS_INFORMATION.hProcess != (IntPtr)0 && pROCESS_INFORMATION.hProcess != NativeMethods.INVALID_HANDLE_VALUE)
             //            {
             //                safeProcessHandle.InitialSetHandle(pROCESS_INFORMATION.hProcess);
             //            }
             //            if (pROCESS_INFORMATION.hThread != (IntPtr)0 && pROCESS_INFORMATION.hThread != NativeMethods.INVALID_HANDLE_VALUE)
             //            {
             //                safeThreadHandle.InitialSetHandle(pROCESS_INFORMATION.hThread);
             //            }
             //        }
             //        if (flag2)
             //        {
             //            goto IL_3B9;
             //        }
             //        if (num == 193 || num == 216)
             //        {
             //            throw new Win32Exception(num, SR.GetString("InvalidApplication"));
             //        }
             //        throw new Win32Exception(num);
             //    }
             //    finally
             //    {
             //        if (intPtr2 != IntPtr.Zero)
             //        {
             //            Marshal.ZeroFreeCoTaskMemUnicode(intPtr2);
             //        }
             //    }
             //}
             RuntimeHelpers.PrepareConstrainedRegions();
             try
             {
             }
             finally
             {
                 flag2 = NativeMethods.CreateProcess(null, stringBuilder, null, null, true, num2, intPtr, text, sTARTUPINFO, pROCESS_INFORMATION);
                 if (!flag2)
                 {
                     num = Marshal.GetLastWin32Error();
                 }
                 if (pROCESS_INFORMATION.hProcess != (IntPtr)0 && pROCESS_INFORMATION.hProcess != NativeMethods.INVALID_HANDLE_VALUE)
                 {
                     safeProcessHandle.InitialSetHandle(pROCESS_INFORMATION.hProcess);
                 }
                 if (pROCESS_INFORMATION.hThread != (IntPtr)0 && pROCESS_INFORMATION.hThread != NativeMethods.INVALID_HANDLE_VALUE)
                 {
                     safeThreadHandle.InitialSetHandle(pROCESS_INFORMATION.hThread);
                 }
             }
             if (!flag2)
             {
                 if (num == 193 || num == 216)
                 {
                     throw new Win32Exception(num, "InvalidApplication");
                 }
                 throw new Win32Exception(num);
             }
         }
         finally
         {
             if (gCHandle.IsAllocated)
             {
                 gCHandle.Free();
             }
             sTARTUPINFO.Dispose();
         }
     }
     if (startInfo.RedirectStandardInput)
     {
         standardInput = new StreamWriter(new FileStream(handle, FileAccess.Write, 4096, false), Console.InputEncoding, 4096);
         standardInput.AutoFlush = true;
     }
     if (startInfo.RedirectStandardOutput)
     {
         Encoding encoding = (startInfo.StandardOutputEncoding != null) ? startInfo.StandardOutputEncoding : Console.OutputEncoding;
         standardOutput = new StreamReader(new FileStream(handle2, FileAccess.Read, 4096, false), encoding, true, 4096);
     }
     if (startInfo.RedirectStandardError)
     {
         Encoding encoding2 = (startInfo.StandardErrorEncoding != null) ? startInfo.StandardErrorEncoding : Console.OutputEncoding;
         standardError = new StreamReader(new FileStream(handle3, FileAccess.Read, 4096, false), encoding2, true, 4096);
     }
     bool result = false;
     if (!safeProcessHandle.IsInvalid)
     {
         SetProcessHandle(safeProcessHandle);
         SetProcessId(pROCESS_INFORMATION.dwProcessId);
         safeThreadHandle.Close();
         result = true;
     }
     return result;
 }
Пример #24
0
 public bool EnumProcessModules(SafeProcessHandle hProcess, IntPtr[] lphModule, int cb, out int lpcbNeeded) =>
 Impl.EnumProcessModules(hProcess, lphModule, cb, out lpcbNeeded);
Пример #25
0
 internal static extern bool GetProcessTimes(
     SafeProcessHandle handle,
     out long creation,
     out long exit,
     out long kernel,
     out long user);
Пример #26
0
 public int GetModuleFileNameEx(SafeProcessHandle hProcess, IntPtr hModule, char[] lpFilename, int nSize) =>
 Impl.GetModuleFileNameEx(hProcess, hModule, lpFilename, nSize);
Пример #27
0
        private static ProcessorType GetProcessProcessorType( SafeProcessHandle processHandle )
        {
            if (processHandle == SafeProcessHandle.InvalidHandle) {
                return ProcessorType.Unknown;
            }

            if( WindowsVersionInfo.IsCurrentProcess64Bit ) {
                // on 64 bit windows, it either has to be x64 or x86
                var retVal = false;

                if (!Kernel32.IsWow64Process(processHandle, out retVal)) {
                    return ProcessorType.Unknown; // failure. Can't tell.
                }
                return retVal ? ProcessorType.X86 : ProcessorType.X64;
            }

            // if we're not on 64 bit Windows, it's gonna have to be the same 32 bit processor that the OS is.
            return WindowsVersionInfo.ProcessorType;
        }
Пример #28
0
 public static extern bool EnumProcessModules(SafeProcessHandle hProcess, [MarshalAs(UnmanagedType.LPArray)][Out] IntPtr[] lphModule, int cb, out int lpcbNeeded);
Пример #29
0
 internal static extern bool VirtualFreeEx(SafeProcessHandle processHandle, IntPtr address, SizeT size, AllocationType flAllocationType);
Пример #30
0
 public static extern int GetModuleFileNameEx(SafeProcessHandle hProcess, IntPtr hModule, [Out] char[] lpFilename, int nSize);
Пример #31
0
 internal static extern void SymCleanup(SafeProcessHandle processHandle);
Пример #32
0
 internal static extern bool WriteProcessMemory(
     SafeProcessHandle processHandle,
     IntPtr baseAddress,
     byte[] buffer,
     int size,
     out IntPtr numberOfBytesWritten);
Пример #33
0
 internal static extern bool SymInitialize(SafeProcessHandle processHandle, string?searchPath, bool invadeProcess);
Пример #34
0
 public static extern bool GetExitCodeProcess(
     [In] SafeProcessHandle hProcess,
     [Out] out int lpExitCode);
Пример #35
0
 internal static extern bool SymUnloadModule(SafeProcessHandle processHandle, int dllBase);
Пример #36
0
 //public static extern UInt32 RtlCreateUserThread(SafeProcessHandle processHandle, IntPtr lpThreadSecurity, bool createSuspended, int stackZeroBits, IntPtr stackReserved, IntPtr stackCommit, IntPtr startAddress, IntPtr parameter, out uint threadId, out IntPtr clientId);
 public static extern UInt32 RtlCreateUserThread(SafeProcessHandle processHandle, IntPtr lpThreadSecurity, bool createSuspended, int stackZeroBits, IntPtr stackReserved, IntPtr stackCommit, IntPtr startAddress, IntPtr parameter, out uint threadId,
     IntPtr clientId);
Пример #37
0
 internal static partial bool EnumProcessModules(SafeProcessHandle handle, IntPtr[]?modules, int size, out int needed);
Пример #38
0
        private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly)
        {
            // preserving Everett behavior.
            if (processId == SystemProcessID || processId == IdleProcessID)
            {
                // system process and idle process doesn't have any modules
                throw new Win32Exception(Interop.Errors.EFail, SR.EnumProcessModuleFailed);
            }

            SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle;

            try
            {
                processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true);

                IntPtr[] moduleHandles            = new IntPtr[64];
                GCHandle moduleHandlesArrayHandle = new GCHandle();
                int      moduleCount = 0;
                for (;;)
                {
                    bool enumResult = false;
                    try
                    {
                        moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned);
                        enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);

                        // The API we need to use to enumerate process modules differs on two factors:
                        //   1) If our process is running in WOW64.
                        //   2) The bitness of the process we wish to introspect.
                        //
                        // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process
                        // we can call psapi!EnumProcessModules.
                        //
                        // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then
                        // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299).  In this case we can't
                        // do the enumeration at all.  So we'll detect this case and bail out.
                        //
                        // Also, EnumProcessModules is not a reliable method to get the modules for a process.
                        // If OS loader is touching module information, this method might fail and copy part of the data.
                        // This is no easy solution to this problem. The only reliable way to fix this is to
                        // suspend all the threads in target process. Of course we don't want to do this in Process class.
                        // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times.
                        //
                        if (!enumResult)
                        {
                            bool sourceProcessIsWow64     = false;
                            bool targetProcessIsWow64     = false;
                            SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle;
                            try
                            {
                                hCurProcess = ProcessManager.OpenProcess(unchecked ((int)Interop.Kernel32.GetCurrentProcessId()), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true);
                                bool wow64Ret;

                                wow64Ret = Interop.Kernel32.IsWow64Process(hCurProcess, ref sourceProcessIsWow64);
                                if (!wow64Ret)
                                {
                                    throw new Win32Exception();
                                }

                                wow64Ret = Interop.Kernel32.IsWow64Process(processHandle, ref targetProcessIsWow64);
                                if (!wow64Ret)
                                {
                                    throw new Win32Exception();
                                }

                                if (sourceProcessIsWow64 && !targetProcessIsWow64)
                                {
                                    // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user.
                                    throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow);
                                }
                            }
                            finally
                            {
                                if (hCurProcess != SafeProcessHandle.InvalidHandle)
                                {
                                    hCurProcess.Dispose();
                                }
                            }

                            // If the failure wasn't due to Wow64, try again.
                            for (int i = 0; i < 50; i++)
                            {
                                enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);
                                if (enumResult)
                                {
                                    break;
                                }
                                Thread.Sleep(1);
                            }
                        }
                    }
                    finally
                    {
                        moduleHandlesArrayHandle.Free();
                    }

                    if (!enumResult)
                    {
                        throw new Win32Exception();
                    }

                    moduleCount /= IntPtr.Size;
                    if (moduleCount <= moduleHandles.Length)
                    {
                        break;
                    }
                    moduleHandles = new IntPtr[moduleHandles.Length * 2];
                }

                var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : moduleCount);

                char[] chars = new char[1024];

                for (int i = 0; i < moduleCount; i++)
                {
                    if (i > 0)
                    {
                        // If the user is only interested in the main module, break now.
                        // This avoid some waste of time. In addition, if the application unloads a DLL
                        // we will not get an exception.
                        if (firstModuleOnly)
                        {
                            break;
                        }
                    }

                    IntPtr moduleHandle = moduleHandles[i];
                    Interop.Kernel32.NtModuleInfo ntModuleInfo;
                    if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo))
                    {
                        HandleError();
                        continue;
                    }

                    var module = new ProcessModule()
                    {
                        ModuleMemorySize  = ntModuleInfo.SizeOfImage,
                        EntryPointAddress = ntModuleInfo.EntryPoint,
                        BaseAddress       = ntModuleInfo.BaseOfDll
                    };

                    int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length);
                    if (length == 0)
                    {
                        HandleError();
                        continue;
                    }

                    module.ModuleName = new string(chars, 0, length);

                    length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length);
                    if (length == 0)
                    {
                        HandleError();
                        continue;
                    }

                    module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ?
                                      new string(chars, 4, length - 4) :
                                      new string(chars, 0, length);

                    modules.Add(module);
                }

                return(modules);
            }
            finally
            {
                if (!processHandle.IsInvalid)
                {
                    processHandle.Dispose();
                }
            }
        }
Пример #39
0
 public static RemoteMemoryRegion Allocate(Process process, SafeProcessHandle handle, UInt32 size)
 {
     var result = new RemoteMemoryRegion {
         Process = process,
         Size = size
     };
     result.Address = Win32.VirtualAllocEx(
         handle.DangerousGetHandle(), IntPtr.Zero,
         size, AllocationType.Commit | AllocationType.Reserve,
         MemoryProtection.ReadWrite
     );
     if (result.Address == IntPtr.Zero) {
         var error = Win32.GetLastError();
         throw new Exception(String.Format("Allocation failed: Error {0:x8}", error));
     }
     return result;
 }
Пример #40
0
 public MemoryScanner(Process process)
 {
     processHandle = OpenProcess(process);
 }
Пример #41
0
        public unsafe int Read(SafeProcessHandle handle, uint offset, uint size, byte[] buffer)
        {
            if ((buffer == null) || (size != buffer.Length))
                throw new ArgumentException("Invalid buffer to read into");

            fixed (byte* pBuffer = buffer)
                return Read(handle, offset, size, pBuffer);
        }
Пример #42
0
 public static extern bool ReadProcessMemory(SafeProcessHandle hProcess, uint lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);
Пример #43
0
        public unsafe int Write(SafeProcessHandle handle, uint offset, uint size, byte* data)
        {
            if (Address == IntPtr.Zero)
                throw new ObjectDisposedException("RemoteMemoryRegion");
            if ((offset + size) > Size)
                throw new ArgumentException("Size too large for region");

            int bytesWritten = 0;
            int result = Win32.WriteProcessMemory(
                handle.DangerousGetHandle(),
                (uint)(Address.ToInt64() + offset),
                new IntPtr(data), size, out bytesWritten
            );

            if (result == 0 || bytesWritten != size) {
                var error = Win32.GetLastError();
                throw new Exception(String.Format("Write failed: Error {0:x8}", error));
            }

            return bytesWritten;
        }
Пример #44
0
 static extern int VirtualQueryEx(SafeProcessHandle hProcess, uint lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);
Пример #45
0
 private void ReleaseProcessHandle(SafeProcessHandle handle)
 {
     if (handle == null)
     {
         return;
     }
     if (haveProcessHandle && handle == m_processHandle)
     {
         return;
     }
     handle.Close();
 }
Пример #46
0
        private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly)
        {
            // preserving Everett behavior.
            if (processId == SystemProcessID || processId == IdleProcessID)
            {
                // system process and idle process doesn't have any modules
                throw new Win32Exception(HResults.E_FAIL, SR.EnumProcessModuleFailed);
            }

            SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle;

            try
            {
                processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true);

                bool succeeded = Interop.Kernel32.EnumProcessModules(processHandle, null, 0, out int needed);

                // The API we need to use to enumerate process modules differs on two factors:
                //   1) If our process is running in WOW64.
                //   2) The bitness of the process we wish to introspect.
                //
                // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process
                // we can call psapi!EnumProcessModules.
                //
                // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then
                // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299).  In this case we can't
                // do the enumeration at all.  So we'll detect this case and bail out.
                if (!succeeded)
                {
                    SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle;
                    try
                    {
                        hCurProcess = ProcessManager.OpenProcess((int)Interop.Kernel32.GetCurrentProcessId(), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true);

                        if (!Interop.Kernel32.IsWow64Process(hCurProcess, out bool sourceProcessIsWow64))
                        {
                            throw new Win32Exception();
                        }

                        if (!Interop.Kernel32.IsWow64Process(processHandle, out bool targetProcessIsWow64))
                        {
                            throw new Win32Exception();
                        }

                        if (sourceProcessIsWow64 && !targetProcessIsWow64)
                        {
                            // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user.
                            throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow);
                        }
                    }
                    finally
                    {
                        if (hCurProcess != SafeProcessHandle.InvalidHandle)
                        {
                            hCurProcess.Dispose();
                        }
                    }

                    EnumProcessModulesUntilSuccess(processHandle, null, 0, out needed);
                }

                int      modulesCount  = needed / IntPtr.Size;
                IntPtr[] moduleHandles = new IntPtr[modulesCount];
                while (true)
                {
                    int size = needed;
                    EnumProcessModulesUntilSuccess(processHandle, moduleHandles, size, out needed);
                    if (size == needed)
                    {
                        break;
                    }

                    if (needed > size && needed / IntPtr.Size > modulesCount)
                    {
                        modulesCount  = needed / IntPtr.Size;
                        moduleHandles = new IntPtr[modulesCount];
                    }
                }

                var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : modulesCount);

                char[] chars = ArrayPool <char> .Shared.Rent(1024);

                try
                {
                    for (int i = 0; i < modulesCount; i++)
                    {
                        if (i > 0)
                        {
                            // If the user is only interested in the main module, break now.
                            // This avoid some waste of time. In addition, if the application unloads a DLL
                            // we will not get an exception.
                            if (firstModuleOnly)
                            {
                                break;
                            }
                        }

                        IntPtr moduleHandle = moduleHandles[i];
                        Interop.Kernel32.NtModuleInfo ntModuleInfo;
                        if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo))
                        {
                            HandleLastWin32Error();
                            continue;
                        }

                        var module = new ProcessModule()
                        {
                            ModuleMemorySize  = ntModuleInfo.SizeOfImage,
                            EntryPointAddress = ntModuleInfo.EntryPoint,
                            BaseAddress       = ntModuleInfo.BaseOfDll
                        };

                        int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length);
                        if (length == 0)
                        {
                            HandleLastWin32Error();
                            continue;
                        }

                        module.ModuleName = new string(chars, 0, length);

                        length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length);
                        if (length == 0)
                        {
                            HandleLastWin32Error();
                            continue;
                        }

                        module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ?
                                          new string(chars, 4, length - 4) :
                                          new string(chars, 0, length);

                        modules.Add(module);
                    }
                }
                finally
                {
                    ArrayPool <char> .Shared.Return(chars);
                }

                return(modules);
            }
            finally
            {
                if (!processHandle.IsInvalid)
                {
                    processHandle.Dispose();
                }
            }
        }
Пример #47
0
 private void SetProcessHandle(SafeProcessHandle processHandle)
 {
     m_processHandle = processHandle;
     haveProcessHandle = true;
     if (watchForExit)
     {
         EnsureWatchingForExit();
     }
 }
Пример #48
0
        /// <devdoc>
        ///    <para>
        ///       Frees any resources associated with this component.
        ///    </para>
        /// </devdoc>
        public void Close()
        {
            if (Associated)
            {
                // We need to lock to ensure we don't run concurrently with CompletionCallback.
                // Without this lock we could reset _raisedOnExited which causes CompletionCallback to
                // raise the Exited event a second time for the same process.
                lock (this)
                {
                    // This sets _waitHandle to null which causes CompletionCallback to not emit events.
                    StopWatchingForExit();
                }

                if (_haveProcessHandle)
                {
                    _processHandle.Dispose();
                    _processHandle     = null;
                    _haveProcessHandle = false;
                }
                _haveProcessId   = false;
                _isRemoteMachine = false;
                _machineName     = ".";
                _raisedOnExited  = false;

                // Only call close on the streams if the user cannot have a reference on them.
                // If they are referenced it is the user's responsibility to dispose of them.
                try
                {
                    if (_standardOutput != null && (_outputStreamReadMode == StreamReadMode.AsyncMode || _outputStreamReadMode == StreamReadMode.Undefined))
                    {
                        if (_outputStreamReadMode == StreamReadMode.AsyncMode)
                        {
                            _output?.CancelOperation();
                            _output?.Dispose();
                        }
                        _standardOutput.Close();
                    }

                    if (_standardError != null && (_errorStreamReadMode == StreamReadMode.AsyncMode || _errorStreamReadMode == StreamReadMode.Undefined))
                    {
                        if (_errorStreamReadMode == StreamReadMode.AsyncMode)
                        {
                            _error?.CancelOperation();
                            _error?.Dispose();
                        }
                        _standardError.Close();
                    }

                    if (_standardInput != null && !_standardInputAccessed)
                    {
                        _standardInput.Close();
                    }
                }
                finally
                {
                    _standardOutput = null;
                    _standardInput  = null;
                    _standardError  = null;

                    _output = null;
                    _error  = null;

                    CloseCore();
                    Refresh();
                }
            }
        }
Пример #49
0
 internal static extern bool GetExitCodeProcess(SafeProcessHandle processHandle, out int exitCode);
Пример #50
0
        [Fact, PlatformSpecific(TestPlatforms.Windows), OuterLoop] // Uses P/Invokes, Requires admin privileges
        public void TestUserCredentialsPropertiesOnWindows()
        {
            string username = "******", password = "******";

            try
            {
                Interop.NetUserAdd(username, password);
            }
            catch (Exception exc)
            {
                Console.Error.WriteLine("TestUserCredentialsPropertiesOnWindows: NetUserAdd failed: {0}", exc.Message);
                return; // test is irrelevant if we can't add a user
            }

            bool hasStarted          = false;
            SafeProcessHandle handle = null;
            Process           p      = null;

            try
            {
                p = CreateProcessLong();

                p.StartInfo.LoadUserProfile     = true;
                p.StartInfo.UserName            = username;
                p.StartInfo.PasswordInClearText = password;

                hasStarted = p.Start();

                if (Interop.OpenProcessToken(p.SafeHandle, 0x8u, out handle))
                {
                    SecurityIdentifier sid;
                    if (Interop.ProcessTokenToSid(handle, out sid))
                    {
                        string actualUserName = sid.Translate(typeof(NTAccount)).ToString();
                        int    indexOfDomain  = actualUserName.IndexOf('\\');
                        if (indexOfDomain != -1)
                        {
                            actualUserName = actualUserName.Substring(indexOfDomain + 1);
                        }

                        bool isProfileLoaded = GetNamesOfUserProfiles().Any(profile => profile.Equals(username));

                        Assert.Equal(username, actualUserName);
                        Assert.True(isProfileLoaded);
                    }
                }
            }
            finally
            {
                IEnumerable <uint> collection = new uint[] { 0 /* NERR_Success */, 2221 /* NERR_UserNotFound */ };
                Assert.Contains <uint>(Interop.NetUserDel(null, username), collection);

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

                if (hasStarted)
                {
                    if (!p.HasExited)
                    {
                        p.Kill();
                    }

                    Assert.True(p.WaitForExit(WaitInMS));
                }
            }
        }
Пример #51
0
 internal static extern bool TerminateProcess(SafeProcessHandle processHandle, int exitCode);
Пример #52
0
 public static extern int GetProcessId(SafeProcessHandle hProcess);
        public RestrictedProcess(string fileName, string workingDirectory, IEnumerable<string> arguments = null, int bufferSize = 4096)
        {
            // Initialize fields
            this.fileName = fileName;
            this.IsDisposed = false;

            // Prepare startup info and redirect standard IO handles
            var startupInfo = new StartupInfo();
            this.RedirectStandardIoHandles(ref startupInfo, bufferSize);

            // Create restricted token
            var restrictedToken = this.CreateRestrictedToken();

            // Set mandatory label
            this.SetTokenMandatoryLabel(restrictedToken, SecurityMandatoryLabel.Low);

            var processSecurityAttributes = new SecurityAttributes();
            var threadSecurityAttributes = new SecurityAttributes();
            this.processInformation = new ProcessInformation();

            const uint CreationFlags = (uint)(
                CreateProcessFlags.CREATE_SUSPENDED |
                CreateProcessFlags.CREATE_BREAKAWAY_FROM_JOB |
                CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT |
                CreateProcessFlags.CREATE_NEW_PROCESS_GROUP |
                CreateProcessFlags.DETACHED_PROCESS | // http://stackoverflow.com/questions/6371149/what-is-the-difference-between-detach-process-and-create-no-window-process-creat
                CreateProcessFlags.CREATE_NO_WINDOW) |
                (uint)ProcessPriorityClass.High;

            string commandLine;
            if (arguments != null)
            {
                var commandLineBuilder = new StringBuilder();
                commandLineBuilder.AppendFormat("\"{0}\"", fileName);
                foreach (var argument in arguments)
                {
                    commandLineBuilder.Append(' ');
                    commandLineBuilder.Append(argument);
                }

                commandLine = commandLineBuilder.ToString();
            }
            else
            {
                commandLine = fileName;
            }

            if (!NativeMethods.CreateProcessAsUser(
                    restrictedToken,
                    null,
                    commandLine,
                    processSecurityAttributes,
                    threadSecurityAttributes,
                    true, // In order to standard input, output and error redirection work, the handles must be inheritable and the CreateProcess() API must specify that inheritable handles are to be inherited by the child process by specifying TRUE in the bInheritHandles parameter.
                    CreationFlags,
                    IntPtr.Zero,
                    workingDirectory,
                    startupInfo,
                    out this.processInformation))
            {
                throw new Win32Exception();
            }

            this.safeProcessHandle = new SafeProcessHandle(this.processInformation.Process);

            // This is a very important line! Without disposing the startupInfo handles, reading the standard output (or error) will hang forever.
            // Same problem described here: http://social.msdn.microsoft.com/Forums/vstudio/en-US/3c25a2e8-b1ea-4fc4-927b-cb865d435147/how-does-processstart-work-in-getting-output
            startupInfo.Dispose();

            NativeMethods.CloseHandle(restrictedToken);
        }
 internal static extern bool GetProcessWorkingSetSizeEx(SafeProcessHandle handle, out IntPtr min, out IntPtr max, out int flags);
Пример #55
0
 public static extern bool FlushInstructionCache(SafeProcessHandle processHandle, IntPtr lpBaseAddress, SizeT dwSize);
Пример #56
0
        private void RestrainProcess(List <KeyValuePair <int, ulong> > IOBytes)
        {
            int           RestrainPerSample = 3;
            ulong?        prevRw            = null;
            StringBuilder log = new StringBuilder();

            foreach (var i in IOBytes)
            {
                int   pid = i.Key;
                ulong rw  = i.Value;

                if (rw < 512 || Restrained.ContainsKey(pid))
                {
                    continue;
                }
                if (prevRw != null)
                {
                    if ((double)rw / prevRw < 0.8)
                    {
                        continue;
                    }
                }
                else
                {
                    prevRw = rw;
                }

                Process proc  = null;
                string  pname = "<unknown>";
                // Restrain process
                HddRestrainedProcess rproc = new HddRestrainedProcess()
                {
                    Revert = false, Process = null
                };
                try
                {
                    proc  = Process.GetProcessById(i.Key);
                    pname = proc.ProcessName;
                    SafeProcessHandle hProc = proc.SafeHandle;
                    rproc.OriginalIoPriority = GetIOPriority(hProc);
                    if (rproc.OriginalIoPriority > 0)
                    {
                        SetIOPriority(hProc, 0);
                        rproc.Process       = proc;
                        rproc.Revert        = true;
                        rproc.NewIoPriority = 0;
                    }
                }
                catch (ArgumentException) { }
                catch (Exception ex)
                {
                    WriteLogEntry(2002, $"限制进程失败,进程{pid} \"{pname}\"{Environment.NewLine}{ex.GetType().Name}:{ex.Message}", true);
                }
                finally { if (!rproc.Revert)
                          {
                              proc?.Dispose();
                          }
                }
                Restrained.Add(pid, rproc);
                if (rproc.Revert)
                {
                    log.AppendLine($"已限制进程。 进程{pid} \"{pname}\" 在过去{CheckInterval}ms内造成读写压力{rw}");
                    RestrainPerSample--;
                    if (RestrainPerSample <= 0)
                    {
                        break;
                    }
                }
            }
            if (Lagfree.Verbose && log.Length > 0)
            {
                WriteLogEntry(1001, log.ToString());
            }
            RestrainedCount.RawValue = Restrained.Count;
        }
Пример #57
0
 internal static extern IntPtr VirtualAllocEx(SafeProcessHandle processHandle, IntPtr address, SizeT size, AllocationType flAllocationType,
     MemoryProtection flProtect);
Пример #58
0
 public ProcessInfo(DbgProcess process, HexCachedBufferStream stream, SafeProcessHandle processHandle)
 {
     Process       = process ?? throw new ArgumentNullException(nameof(process));
     Stream        = stream ?? throw new ArgumentNullException(nameof(stream));
     ProcessHandle = processHandle;
 }
Пример #59
0
 public static extern SafeThreadHandle CreateRemoteThread(SafeProcessHandle processHandle, IntPtr lpThreadAttributes, SizeT dwStackSize,
     IntPtr lpStartAddress, IntPtr lpParameter, CreateRemoteThreadFlags creationFlags, out uint lpThreadId);
 public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
 {
     NativeMethods.NtProcessBasicInfo ntProcessBasicInfo = new NativeMethods.NtProcessBasicInfo();
     int num = NativeMethods.NtQueryInformationProcess(processHandle, 0, ntProcessBasicInfo, Marshal.SizeOf(ntProcessBasicInfo), null);
     if (num != 0)
     {
         throw new InvalidOperationException("CantGetProcessId", new Win32Exception(num));
     }
     return ntProcessBasicInfo.UniqueProcessId.ToInt32();
 }