Beispiel #1
0
 /// <nodoc />
 public static CreateDetouredProcessStatus CreateDetouredProcess(
     string lpcwCommandLine,
     int dwCreationFlags,
     IntPtr lpEnvironment,
     string lpcwWorkingDirectory,
     SafeHandle hStdInput,
     SafeHandle hStdOutput,
     SafeHandle hStdError,
     SafeHandle hJob,
     IProcessInjector injector,
     bool addProcessToContainer,
     out SafeProcessHandle phProcess,
     out SafeThreadHandle phThread,
     out int pdwProcessId,
     out int errorCode)
 {
     return(s_nativeMethods.CreateDetouredProcess(
                lpcwCommandLine,
                dwCreationFlags,
                lpEnvironment,
                lpcwWorkingDirectory,
                hStdInput,
                hStdOutput,
                hStdError,
                hJob,
                injector,
                addProcessToContainer,
                out phProcess,
                out phThread,
                out pdwProcessId,
                out errorCode));
 }
Beispiel #2
0
        private void VisitJobObjectProcesses(JobObject jobObject, uint[] childProcessIds, Action <SafeProcessHandle, uint> actionForProcess)
        {
            foreach (uint processId in childProcessIds)
            {
                using (SafeProcessHandle processHandle = ProcessUtilities.OpenProcess(
                           ProcessSecurityAndAccessRights.PROCESS_QUERY_INFORMATION | ProcessSecurityAndAccessRights.PROCESS_SET_QUOTA,
                           false,
                           processId))
                {
                    if (processHandle.IsInvalid)
                    {
                        // we are too late: could not open process
                        continue;
                    }

                    if (!jobObject.ContainsProcess(processHandle))
                    {
                        // we are too late: process id got reused by another process
                        continue;
                    }

                    if (!ProcessUtilities.GetExitCodeProcess(processHandle, out int exitCode))
                    {
                        // we are too late: process id got reused by another process
                        continue;
                    }

                    actionForProcess(processHandle, processId);
                }
            }
        }
        public bool IsWow64Process(SafeProcessHandle process)
        {
            IntPtr handle = process == null?GetCurrentProcess() : process.DangerousGetHandle();

            if (IO.Windows.FileSystemWin.StaticIsOSVersionGreaterOrEqual(IO.Windows.FileSystemWin.MinWindowsVersionThatSupportsWow64Processes))
            {
                return(ExternIsWow64Process(handle, out bool result) && result);
            }

            return(false);
        }
 private static extern CreateDetouredProcessStatus ExternCreateDetouredProcess(
     [MarshalAs(UnmanagedType.LPWStr)] string lpcwCommandLine,
     int dwCreationFlags,
     IntPtr lpEnvironment,
     [MarshalAs(UnmanagedType.LPWStr)] string lpcwWorkingDirectory,
     SafeHandle hStdInput,
     SafeHandle hStdOutput,
     SafeHandle hStdError,
     SafeHandle hJob,
     IntPtr injector,
     bool addProcessToSilo,
     out SafeProcessHandle phProcess,
     out SafeThreadHandle phThread,
     out int pdwProcessId);
Beispiel #5
0
        /// <summary>
        /// Checks if a particular process is part of this job.
        /// </summary>
        internal bool ContainsProcess(SafeProcessHandle processHandle)
        {
            Contract.Requires(!processHandle.IsInvalid);

            bool result;

            if (!Native.Processes.ProcessUtilities.IsProcessInJob(
                    processHandle,
                    handle,
                    out result))
            {
                throw new NativeWin32Exception(Marshal.GetLastWin32Error(), "IsProcessInJob failed");
            }

            return(result);
        }
        /// <inheritdoc />
        public CreateDetouredProcessStatus CreateDetouredProcess(
            string lpcwCommandLine,
            int dwCreationFlags,
            IntPtr lpEnvironment,
            string lpcwWorkingDirectory,
            SafeHandle hStdInput,
            SafeHandle hStdOutput,
            SafeHandle hStdError,
            SafeHandle hJob,
            IProcessInjector injector,
            bool addProcessToSilo,
            out SafeProcessHandle phProcess,
            out SafeThreadHandle phThread,
            out int pdwProcessId,
            out int errorCode)
        {
            Assert64Process();

            var status = ExternCreateDetouredProcess(
                lpcwCommandLine,
                dwCreationFlags,
                lpEnvironment,
                lpcwWorkingDirectory,
                hStdInput,
                hStdOutput,
                hStdError,
                hJob,
                injector == null ? IntPtr.Zero : injector.Injector(),
                addProcessToSilo,
                out phProcess,
                out phThread,
                out pdwProcessId);

            errorCode = status == CreateDetouredProcessStatus.Succeeded ? 0 : Marshal.GetLastWin32Error();

            // TODO: Enforce this postcondition.
            // Contract.Assume(status == CreateDetouredProcessStatus.Succeeded || errorCode != 0, "Expected a valid error code on failure.");
            return(status);
        }
Beispiel #7
0
 /// <inheritdoc />
 public bool GetExitCodeProcess(SafeProcessHandle hProcess, out int exitCode)
 => throw new NotImplementedException();
Beispiel #8
0
 /// <inheritdoc />
 public bool TerminateProcess(SafeProcessHandle hProcess, int exitCode)
 => throw new NotImplementedException();
Beispiel #9
0
        => new byte[0];     // TODO: this is only used for communication between BuildXL and external sandboxed process, which we don't do yet on Unix systems.

        /// <inheritdoc />
        public CreateDetouredProcessStatus CreateDetouredProcess(string lpcwCommandLine, int dwCreationFlags, IntPtr lpEnvironment, string lpcwWorkingDirectory, SafeHandle hStdInput, SafeHandle hStdOutput, SafeHandle hStdError, SafeHandle hJob, IProcessInjector injector, bool addProcessToSilo, out SafeProcessHandle phProcess, out SafeThreadHandle phThread, out int pdwProcessId, out int errorCode)
        => throw new NotImplementedException();
Beispiel #10
0
 /// <inheritdoc />
 public uint GetModuleFileNameEx(SafeProcessHandle hProcess, IntPtr hModule, StringBuilder lpBaseName, uint nSize)
 => throw new NotImplementedException();
Beispiel #11
0
 private static extern bool ExternTerminateProcess(SafeProcessHandle hProcess, int exitCode);
Beispiel #12
0
 /// <summary>
 /// Retrieves the fully qualified path for the file containing the specified module.
 /// </summary>
 public static uint GetModuleFileNameEx(SafeProcessHandle hProcess, IntPtr hModule, StringBuilder lpBaseName, uint nSize)
 => s_nativeMethods.GetModuleFileNameEx(hProcess, hModule, lpBaseName, nSize);
Beispiel #13
0
 /// <nodoc />
 public static bool IsWow64Process(SafeProcessHandle process = null)
 => s_nativeMethods.IsWow64Process(process);
Beispiel #14
0
 /// <inheritdoc />
 public bool GetExitCodeProcess(SafeProcessHandle hProcess, out int exitCode)
 => ExternGetExitCodeProcess(hProcess, out exitCode);
Beispiel #15
0
 /// <inheritdoc />
 public bool TerminateProcess(SafeProcessHandle hProcess, int exitCode)
 => ExternTerminateProcess(hProcess, exitCode);
Beispiel #16
0
 /// <inheritdoc />
 public uint GetModuleFileNameEx(SafeProcessHandle hProcess, IntPtr hModule, StringBuilder lpBaseName, uint nSize)
 => ExternGetModuleFileNameEx(hProcess, hModule, lpBaseName, nSize);
Beispiel #17
0
 private static extern uint ExternGetModuleFileNameEx(
     SafeProcessHandle hProcess,
     IntPtr hModule,
     [Out] StringBuilder lpBaseName,
     uint nSize);
Beispiel #18
0
 private static extern bool ExternIsProcessInJob(SafeProcessHandle hProcess, IntPtr hJob, [MarshalAs(UnmanagedType.Bool)] out bool result);
Beispiel #19
0
 private static extern bool ExternGetExitCodeProcess(SafeProcessHandle processHandle, out int exitCode);
Beispiel #20
0
 /// <inheritdoc />
 public bool IsWow64Process([CanBeNull] SafeProcessHandle process)
 => throw new NotImplementedException();
Beispiel #21
0
 /// <summary>
 /// Returns the exit code of a process identified by a handle.
 /// </summary>
 public static bool GetExitCodeProcess(SafeProcessHandle hProcess, out int exitCode)
 => s_nativeMethods.GetExitCodeProcess(hProcess, out exitCode);
Beispiel #22
0
 /// <summary>
 /// Terminates the specified process and all of its threads.
 /// </summary>
 public static bool TerminateProcess(SafeProcessHandle hProcess, int exitCode)
 => s_nativeMethods.TerminateProcess(hProcess, exitCode);
Beispiel #23
0
 /// <summary>
 /// Determines whether the process is running in the specified job.
 /// </summary>
 public static bool IsProcessInJob(SafeProcessHandle hProcess, IntPtr hJob, out bool result)
 => s_nativeMethods.IsProcessInJob(hProcess, hJob, out result);
Beispiel #24
0
 /// <inheritdoc />
 public bool IsProcessInJob(SafeProcessHandle hProcess, IntPtr hJob, out bool result)
 => ExternIsProcessInJob(hProcess, hJob, out result);
Beispiel #25
0
        /// <inheritdoc />
        public ulong?GetActivePeakWorkingSet()
        {
            using (m_queryJobDataLock.AcquireReadLock())
            {
                var detouredProcess = m_detouredProcess;
                if (detouredProcess == null ||
                    !detouredProcess.HasStarted ||
                    detouredProcess.HasExited ||
                    m_disposeStarted)
                {
                    return(null);
                }

                ulong?currentPeakWorkingSet    = null;
                ulong?currentPeakPagefileUsage = null;

                var jobObject = detouredProcess.GetJobObject();
                if (jobObject == null || !jobObject.TryGetProcessIds(out uint[] childProcessIds) || childProcessIds.Length == 0)
                {
                    return(null);
                }

                foreach (uint processId in childProcessIds)
                {
                    using (SafeProcessHandle processHandle = ProcessUtilities.OpenProcess(
                               ProcessSecurityAndAccessRights.PROCESS_QUERY_INFORMATION,
                               false,
                               processId))
                    {
                        if (processHandle.IsInvalid)
                        {
                            // we are too late: could not open process
                            continue;
                        }

                        if (!jobObject.ContainsProcess(processHandle))
                        {
                            // we are too late: process id got reused by another process
                            continue;
                        }

                        int exitCode;
                        if (!ProcessUtilities.GetExitCodeProcess(processHandle, out exitCode))
                        {
                            // we are too late: process id got reused by another process
                            continue;
                        }

                        var memoryUsage = Interop.Dispatch.GetMemoryUsageCounters(processHandle.DangerousGetHandle());
                        if (memoryUsage != null)
                        {
                            currentPeakWorkingSet    = (currentPeakWorkingSet ?? 0) + memoryUsage.PeakWorkingSetSize;
                            currentPeakPagefileUsage = (currentPeakPagefileUsage ?? 0) + memoryUsage.PeakPagefileUsage;
                        }
                    }
                }

                m_peakWorkingSet.RegisterSample(currentPeakWorkingSet ?? 0);
                m_peakPagefileUsage.RegisterSample(currentPeakPagefileUsage ?? 0);

                return(currentPeakWorkingSet);
            }
        }
Beispiel #26
0
 /// <inheritdoc />
 public bool IsProcessInJob(SafeProcessHandle hProcess, IntPtr hJob, out bool result)
 => throw new NotImplementedException();
Beispiel #27
0
        private static Dictionary <uint, ReportedProcess> GetSurvivingChildProcesses(JobObject jobObject)
        {
            if (!jobObject.TryGetProcessIds(out uint[] survivingChildProcessIds) || survivingChildProcessIds.Length == 0)
            {
                return(null);
            }

            var survivingChildProcesses = new Dictionary <uint, ReportedProcess>();

            foreach (uint processId in survivingChildProcessIds)
            {
                using (SafeProcessHandle processHandle = ProcessUtilities.OpenProcess(
                           ProcessSecurityAndAccessRights.PROCESS_QUERY_INFORMATION |
                           ProcessSecurityAndAccessRights.PROCESS_VM_READ,
                           false,
                           processId))
                {
                    if (processHandle.IsInvalid)
                    {
                        // we are too late: could not open process
                        continue;
                    }

                    if (!jobObject.ContainsProcess(processHandle))
                    {
                        // we are too late: process id got reused by another process
                        continue;
                    }

                    int exitCode;
                    if (!ProcessUtilities.GetExitCodeProcess(processHandle, out exitCode))
                    {
                        // we are too late: process id got reused by another process
                        continue;
                    }

                    using (PooledObjectWrapper <StringBuilder> wrap = Pools.GetStringBuilder())
                    {
                        StringBuilder sb = wrap.Instance;
                        if (sb.Capacity < MaxProcessPathLength)
                        {
                            sb.Capacity = MaxProcessPathLength;
                        }

                        if (ProcessUtilities.GetModuleFileNameEx(processHandle, IntPtr.Zero, sb, (uint)sb.Capacity) <= 0)
                        {
                            // we are probably too late
                            continue;
                        }

                        // Attempt to read the process arguments (command line) from the process
                        // memory. This is not fatal if it does not succeed.
                        string processArgs = string.Empty;

                        var  basicInfoSize = (uint)Marshal.SizeOf <Native.Processes.Windows.ProcessUtilitiesWin.PROCESS_BASIC_INFORMATION>();
                        var  basicInfoPtr  = Marshal.AllocHGlobal((int)basicInfoSize);
                        uint basicInfoReadLen;
                        try
                        {
                            if (Native.Processes.Windows.ProcessUtilitiesWin.NtQueryInformationProcess(
                                    processHandle,
                                    Native.Processes.Windows.ProcessUtilitiesWin.ProcessInformationClass.ProcessBasicInformation,
                                    basicInfoPtr, basicInfoSize, out basicInfoReadLen) == 0)
                            {
                                Native.Processes.Windows.ProcessUtilitiesWin.PROCESS_BASIC_INFORMATION basicInformation = Marshal.PtrToStructure <Native.Processes.Windows.ProcessUtilitiesWin.PROCESS_BASIC_INFORMATION>(basicInfoPtr);
                                Contract.Assert(basicInformation.UniqueProcessId == processId);

                                // NativeMethods.ReadProcessStructure and NativeMethods.ReadUnicodeString handle null\zero addresses
                                // passed into them. Since these are all value types, then there is no need to do any type
                                // of checking as passing zero through will just result in an empty process args string.
                                var peb = Native.Processes.Windows.ProcessUtilitiesWin.ReadProcessStructure <Native.Processes.Windows.ProcessUtilitiesWin.PEB>(processHandle, basicInformation.PebBaseAddress);
                                var processParameters = Native.Processes.Windows.ProcessUtilitiesWin.ReadProcessStructure <Native.Processes.Windows.ProcessUtilitiesWin.RTL_USER_PROCESS_PARAMETERS>(processHandle, peb.ProcessParameters);
                                processArgs = Native.Processes.Windows.ProcessUtilitiesWin.ReadProcessUnicodeString(processHandle, processParameters.CommandLine);
                            }
                        }
                        finally
                        {
                            Marshal.FreeHGlobal(basicInfoPtr);
                        }

                        string path = sb.ToString();
                        survivingChildProcesses.Add(processId, new ReportedProcess(processId, path, processArgs));
                    }
                }
            }


            return(survivingChildProcesses);
        }
Beispiel #28
0
        /// <summary>
        /// Adds a running process to this job. Any children it later spawns will be part of this job, too.
        /// </summary>
#if FEATURE_SAFE_PROCESS_HANDLE
        private bool AddProcess(SafeProcessHandle processHandle)