This data structure contains information about a process that is collected in bulk by querying the operating system. The reason to make this a separate structure from the process component is so that we can throw it away all at once when Refresh is called on the component.
Example #1
0
        public static ProcessInfo[] Enum()
        {
            List<ProcessInfo> Result = new List<ProcessInfo>();
            Process[] ProcList = Process.GetProcesses();

            for (int i = 0; i < ProcList.Length; i++)
            {
                Process Proc = ProcList[i];

                try
                {
                    ProcessInfo Info = new ProcessInfo();

                    Info.FileName = Proc.MainModule.FileName;
                    Info.Id = Proc.Id;
                    Info.Is64Bit = RemoteHooking.IsX64Process(Proc.Id);
                    Info.Identity = RemoteHooking.GetProcessIdentity(Proc.Id).Owner.ToString();

                    Result.Add(Info);
                }
                catch
                {
                }
            }

            return Result.ToArray();
        }
Example #2
0
        public static ProcessInfo[] EnumProcesses()
        {
            List<ProcessInfo> result = new List<ProcessInfo>();
            Process[] procList = Process.GetProcesses();

            for (int i = 0; i < procList.Length; i++)
            {
                Process proc = procList[i];

                try
                {
                    ProcessInfo info = new ProcessInfo();

                    info.FileName = proc.MainModule.FileName;
                    info.Id = proc.Id;
                    info.Is64Bit = RemoteHooking.IsX64Process(proc.Id);
                    info.User = RemoteHooking.GetProcessIdentity(proc.Id).Name;

                    result.Add(info);
                }
                catch
                {
                }
            }

            return result.ToArray();
        }
Example #3
0
        public static ProcessInfo[] EnumProcesses()
        {
            var result = new List<ProcessInfo>();
            var procList = Process.GetProcesses();

            foreach (var proc in procList)
            {
                try
                {
                    var info = new ProcessInfo
                    {
                        FileName = proc.MainModule.FileName,
                        ID = proc.Id,
                        Is64Bit = RemoteHooking.IsX64Process(proc.Id),
                        User = RemoteHooking.GetProcessIdentity(proc.Id)
                                            .Name
                    };
                    result.Add(info);
                }
                catch
                {
                }
            }
            return result.ToArray();
        }
Example #4
0
 static FileLocker()
 {
     Process currentProcess = Process.GetCurrentProcess();
     Int32 processId = currentProcess.Id;
     String processName = currentProcess.ProcessName;
     Int64 startTimeTicks = currentProcess.StartTime.Ticks;
     CurrentProcessInfo = new ProcessInfo(processId, processName, startTimeTicks);
 }
Example #5
0
        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        private static ProcessInfo CreateProcessInfo(int pid)
        {
            // Negative PIDs aren't valid
            if (pid < 0)
            {
                throw new ArgumentOutOfRangeException("pid");
            }

            ProcessInfo procInfo = new ProcessInfo()
            {
                ProcessId = pid
            };

            // Try to get the task info. This can fail if the user permissions don't permit
            // this user context to query the specified process
            Interop.libproc.proc_taskallinfo? info = Interop.libproc.GetProcessInfoById(pid);
            if (info.HasValue)
            {
                // Set the values we have; all the other values don't have meaning or don't exist on OSX
                Interop.libproc.proc_taskallinfo temp = info.Value;
                unsafe { procInfo.ProcessName = Marshal.PtrToStringAnsi(new IntPtr(temp.pbsd.pbi_comm)); }
                procInfo.BasePriority = temp.pbsd.pbi_nice;
                procInfo.HandleCount = Interop.libproc.GetFileDescriptorCountForPid(pid);
                procInfo.VirtualBytes = (long)temp.ptinfo.pti_virtual_size;
                procInfo.WorkingSet = (long)temp.ptinfo.pti_resident_size;
            }

            // Get the sessionId for the given pid, getsid returns -1 on error
            int sessionId = Interop.libc.getsid(pid);
            if (sessionId != -1)
                procInfo.SessionId = sessionId;
            
            // Create a threadinfo for each thread in the process
            List<KeyValuePair<ulong, Interop.libproc.proc_threadinfo?>> lstThreads = Interop.libproc.GetAllThreadsInProcess(pid);
            foreach (KeyValuePair<ulong, Interop.libproc.proc_threadinfo?> t in lstThreads)
            {
                var ti = new ThreadInfo()
                {
                    _processId = pid,
                    _threadId = (int)t.Key, // The OS X thread ID is 64-bits, but we're forced to truncate due to the public API signature
                    _basePriority = 0,
                    _startAddress = IntPtr.Zero
                };

                // Fill in additional info if we were able to retrieve such data about the thread
                if (t.Value.HasValue)
                {
                    ti._currentPriority = t.Value.Value.pth_curpri;
                    ti._threadState = ConvertOsxThreadRunStateToThreadState((Interop.libproc.ThreadRunState)t.Value.Value.pth_run_state);
                    ti._threadWaitReason = ConvertOsxThreadFlagsToWaitReason((Interop.libproc.ThreadFlags)t.Value.Value.pth_flags);
                }

                procInfo._threadInfoList.Add(ti);
            }

            return procInfo;
        }
Example #6
0
 //private static List<Int32> ActivePIDList = new List<Int32>();
 public static ProcessInfo AddHookedProcess(Process process)
 {
     lock (ProcessList)
     {
         ProcessInfo pInfo = new ProcessInfo(process);
         ProcessList.Add(pInfo);
         HookedProcesses.Add(process.Id);
         return pInfo;
     }
 }
Example #7
0
 public Player()
 {
     currentState = new LoginState(this);
     ProcessInfo = new ProcessInfo();
     ProcessInfo.Status = ProcessInfo.StatusCode.NotInitialized;
     Messager = new Messager();
     messageQueue = Messager.Queue;
     messagerThread = new Thread(
         new ThreadStart(Messager.Receive));
     messagerThread.Start();
 }
Example #8
0
        // CreateProcess wrapper
        public static bool CreateProcess(String ExeName, String
            CmdLine, ProcessInfo pi)
        {
            if (pi == null)
                                pi = new ProcessInfo();

                        byte[] si = new byte[128];

                        return CreateProcess(ExeName, CmdLine, IntPtr.Zero,
                            IntPtr.Zero, 0, 0, IntPtr.Zero, IntPtr.Zero, si, pi) != 0;
        }
        private void GetProcesses()
        {
            listBox1.Items.Clear();
            var processes = Process.GetProcesses();

            foreach (var process in processes)
            {
                var processInfo = new ProcessInfo(process.Id, process.ProcessName);
                listBox1.Items.Add(processInfo);
            }
        }
Example #10
0
 static extern bool CreateProcessWithLogonW(
     string principal,
     string authority,
     string password,
     LogonFlags logonFlags,
     string appName,
     string cmdLine,
     CreationFlags creationFlags,
     IntPtr environmentBlock,
     string currentDirectory,
     ref StartupInfo startupInfo,
     out ProcessInfo processInfo);
Example #11
0
        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        private unsafe static ProcessInfo CreateProcessInfo(int pid)
        {
            // Negative PIDs aren't valid
            if (pid < 0)
            {
                throw new ArgumentOutOfRangeException("pid");
            }

            ProcessInfo procInfo = new ProcessInfo();

            // Try to get the task info. This can fail if the user permissions don't permit
            // this user context to query the specified process
            Interop.libproc.proc_taskallinfo? info = Interop.libproc.GetProcessInfoById(pid);
            if (info.HasValue)
            {
                // We need to convert the byte pointer to an IntPtr 
                // that we can pass to the Marshal.PtrToStringAnsi call
                // but the nullable struct type makes it difficult to inline,
                // so make a temp variable to remove the nullable and get the pointer 
                Interop.libproc.proc_taskallinfo temp = info.Value;
                IntPtr ptrString = new IntPtr(temp.pbsd.pbi_comm);

                // Set the values we have; all the other values don't have meaning or don't exist on OSX
                procInfo.BasePriority = temp.ptinfo.pti_priority;
                procInfo.HandleCount = Interop.libproc.GetFileDescriptorCountForPid(pid);
                procInfo.ProcessId = pid;
                procInfo.ProcessName = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(ptrString);
                procInfo.VirtualBytes = (long)temp.ptinfo.pti_virtual_size;
                procInfo.WorkingSet = (long)temp.ptinfo.pti_resident_size;
            }

            // Create a threadinfo for each thread in the process
            List<KeyValuePair<ulong, Interop.libproc.proc_threadinfo?>> lstThreads = Interop.libproc.GetAllThreadsInProcess(pid);
            foreach (KeyValuePair<ulong, Interop.libproc.proc_threadinfo?> t in lstThreads)
            {
                if (t.Value.HasValue)
                {
                    procInfo._threadInfoList.Add(new ThreadInfo()
                    {
                        _basePriority = 0,
                        _currentPriority = t.Value.Value.pth_curpri,
                        _processId = pid,
                        _startAddress = IntPtr.Zero, // We don't have this info
                        _threadId = Convert.ToInt32(t.Key),
                        _threadState = ConvertOsxThreadRunStateToThreadState((Interop.libproc.ThreadRunState)t.Value.Value.pth_run_state),
                        _threadWaitReason = ConvertOsxThreadFlagsToWaitReason((Interop.libproc.ThreadFlags)t.Value.Value.pth_flags)
                    });
                }
            }

            return procInfo;
        }
 public override void Init(string xmlInformation)
 {
     XmlDocument xmlDoc = new XmlDocument();
     List<ProcessInfo> list = new List<ProcessInfo>();
     xmlDoc.LoadXml(xmlInformation);
     foreach (XmlNode node in xmlDoc.ChildNodes[0].ChildNodes)
     {
         ProcessInfo pInfo = new ProcessInfo();
         pInfo.PID = int.Parse(node.Attributes["ID"].Value);
         pInfo.Name = node.Attributes["Name"].Value;
         pInfo.MemoryUsed = long.Parse(node.Attributes["Memory"].Value);
         list.Add(pInfo);
     }
     Processes = list.ToArray();
 }
Example #13
0
 public static ProcessInfo GetHookedProcess(Process process)
 {
     lock (ProcessList)
     {
         ProcessInfo pInfo = new ProcessInfo(process);
         int index = ProcessList.IndexOf(pInfo);
         if (index > -1)
         {
             return ProcessList[index];
         }
         else
         {
             return null;
         }
     }
 }
Example #14
0
        public override IEnumerator<object> WaitUntilProcessReady(ProcessInfo process)
        {
            bool isReady = false;
            do {
                yield return Program.EvalPython<bool>(process, @"
            try:
              m = __import__('uix')
              g = getattr(__import__('__builtin__'), 'sm', None)
              return (m is not None) and (g is not None)
            except:
              return False").Bind(() => isReady);

                yield return new Sleep(1);
            } while (!isReady);

            Console.WriteLine("EVE started.");
        }
        protected override string GetInformationXML()
        {
            StringBuilder strBld = new StringBuilder();
            strBld.Append("<ProcessStateInfo>");
            if (activeProcesses != null)
            {
                if (activeProcesses.Length > 0)
                {

                    foreach (Process p in activeProcesses)
                    {
                        ProcessInfo pInfo = new ProcessInfo();
                        pInfo.Name = p.ProcessName;
                        pInfo.MemoryUsed = p.PagedMemorySize64;
                        pInfo.PID = p.Id;
                        strBld.Append(pInfo.ToXML());
                    }
                }
            }
            strBld.Append("</ProcessStateInfo>");
            return strBld.ToString();
        }
Example #16
0
        private static uint CreateHoneytokenProcess(string appPath, string domain, string user,
            string password, LogonFlags lf, CreationFlags cf)
        {
            StartupInfo si = new StartupInfo();
            si.cb = Marshal.SizeOf(typeof(StartupInfo));
            ProcessInfo pi = new ProcessInfo();
            pi.dwProcessId = 0;

            if (CreateProcessWithLogonW(user, domain, password,
            lf,
            appPath, null,
            cf, IntPtr.Zero, null,
            ref si, out pi))
            {
                CloseHandle(pi.hProcess);
                CloseHandle(pi.hThread);
            }
            else
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }
            return(pi.dwProcessId);
        }
Example #17
0
 public ViewResultBase Details()
 {
     if (!string.IsNullOrEmpty(Request["isTooltip"]))
     {
         Guid id;
         if (Guid.TryParse(Request["id"], out id))
         {
             var data = new ProcessInfo(base.EntityType.GetData(id));
             return new PartialViewResult { ViewName = "Partials/Details", ViewData = new ViewDataDictionary(data) };
         }
         else
         {
             throw new ValidationException("非法的Guid标识" + Request["id"]);
         }
     }
     else if (!string.IsNullOrEmpty(Request["isInner"]))
     {
         return new PartialViewResult { ViewName = "Partials/Details" };
     }
     else
     {
         return this.View();
     }
 }
Example #18
0
        public static ProcessInfo[] GetProcessInfos() {
            IntPtr handle = (IntPtr)(-1);
            GCHandle bufferHandle = new GCHandle();
            ArrayList threadInfos = new ArrayList();
            Hashtable processInfos = new Hashtable();

            try {
                handle = NativeMethods.CreateToolhelp32Snapshot(NativeMethods.TH32CS_SNAPPROCESS | NativeMethods.TH32CS_SNAPTHREAD, 0);
                if (handle == (IntPtr)(-1)) throw new Win32Exception();
                int entrySize = (int)Marshal.SizeOf(typeof(NativeMethods.WinProcessEntry));
                int bufferSize = entrySize + NativeMethods.WinProcessEntry.sizeofFileName;
                int[] buffer = new int[bufferSize / 4];
                bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                IntPtr bufferPtr = bufferHandle.AddrOfPinnedObject();
                Marshal.WriteInt32(bufferPtr, bufferSize);

                HandleRef handleRef = new HandleRef(null, handle);
                
                if (NativeMethods.Process32First(handleRef, bufferPtr)) {
                    do {
                        NativeMethods.WinProcessEntry process = new NativeMethods.WinProcessEntry();
                        Marshal.PtrToStructure(bufferPtr, process);
                        ProcessInfo processInfo = new ProcessInfo();
                        String name = Marshal.PtrToStringAnsi((IntPtr)((long)bufferPtr + entrySize));  
                        processInfo.processName = Path.ChangeExtension(Path.GetFileName(name), null);
                        processInfo.handleCount = process.cntUsage;
                        processInfo.processId = process.th32ProcessID;
                        processInfo.basePriority = process.pcPriClassBase;
                        processInfo.mainModuleId = process.th32ModuleID;
                        processInfos.Add(processInfo.processId, processInfo);
                        Marshal.WriteInt32(bufferPtr, bufferSize);
                    }
                    while (NativeMethods.Process32Next(handleRef, bufferPtr));
                }
                
                NativeMethods.WinThreadEntry thread = new NativeMethods.WinThreadEntry();
                thread.dwSize = Marshal.SizeOf(thread);
                if (NativeMethods.Thread32First(handleRef, thread)) {
                    do {
                        ThreadInfo threadInfo = new ThreadInfo();
                        threadInfo.threadId = thread.th32ThreadID;
                        threadInfo.processId = thread.th32OwnerProcessID;
                        threadInfo.basePriority = thread.tpBasePri;
                        threadInfo.currentPriority = thread.tpBasePri + thread.tpDeltaPri;
                        threadInfos.Add(threadInfo);
                    }
                    while (NativeMethods.Thread32Next(handleRef, thread));
                }

                for (int i = 0; i < threadInfos.Count; i++) {
                    ThreadInfo threadInfo = (ThreadInfo)threadInfos[i];
                    ProcessInfo processInfo = (ProcessInfo)processInfos[threadInfo.processId];
                    if (processInfo != null) 
                        processInfo.threadInfoList.Add(threadInfo);
                    //else 
                    //    throw new InvalidOperationException(SR.GetString(SR.ProcessNotFound, threadInfo.threadId.ToString(), threadInfo.processId.ToString()));                   
                }
            }
            finally {
                if (bufferHandle.IsAllocated) bufferHandle.Free();
                Debug.WriteLineIf(Process.processTracing.TraceVerbose, "Process - CloseHandle(toolhelp32 snapshot handle)");
                if (handle != (IntPtr)(-1)) SafeNativeMethods.CloseHandle(handle);
            }

            ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
            processInfos.Values.CopyTo(temp, 0);
            return temp;
        }
Example #19
0
 static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) {
     ProcessInfo[] processInfos = new ProcessInfo[0] ;
     byte[] dataPtr = null;
     
     int retryCount = 5;
     while (processInfos.Length == 0 && retryCount != 0) {                    
         try {
             dataPtr = library.GetPerformanceData(PerfCounterQueryString);
             processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr);
         }
         catch (Exception e) {
             throw new InvalidOperationException(SR.GetString(SR.CouldntGetProcessInfos), e);
         }
                                 
         --retryCount;                        
     }                    
 
     if (processInfos.Length == 0)
         throw new InvalidOperationException(SR.GetString(SR.ProcessDisabled));    
         
     return processInfos;                    
                 
 }
        static ProcessInfo GetProcessInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters)
        {
            ProcessInfo processInfo = new ProcessInfo();

            for (int i = 0; i < counters.Length; i++)
            {
                Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i];
                long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
                switch ((ValueId)counter.CounterNameTitlePtr)
                {
                case ValueId.ProcessId:
                    processInfo.ProcessId = (int)value;
                    break;

                case ValueId.PoolPagedBytes:
                    processInfo.PoolPagedBytes = value;
                    break;

                case ValueId.PoolNonpagedBytes:
                    processInfo.PoolNonPagedBytes = value;
                    break;

                case ValueId.VirtualBytes:
                    processInfo.VirtualBytes = value;
                    break;

                case ValueId.VirtualBytesPeak:
                    processInfo.VirtualBytesPeak = value;
                    break;

                case ValueId.WorkingSetPeak:
                    processInfo.WorkingSetPeak = value;
                    break;

                case ValueId.WorkingSet:
                    processInfo.WorkingSet = value;
                    break;

                case ValueId.PageFileBytesPeak:
                    processInfo.PageFileBytesPeak = value;
                    break;

                case ValueId.PageFileBytes:
                    processInfo.PageFileBytes = value;
                    break;

                case ValueId.PrivateBytes:
                    processInfo.PrivateBytes = value;
                    break;

                case ValueId.BasePriority:
                    processInfo.BasePriority = (int)value;
                    break;

                case ValueId.HandleCount:
                    processInfo.HandleCount = (int)value;
                    break;
                }
            }
            return(processInfo);
        }
Example #21
0
       static ProcessInfo[] GetProcessInfos(IntPtr dataPtr) {
            // 60 is a reasonable number for processes on a normal machine.
            Hashtable processInfos = new Hashtable(60);

            long totalOffset = 0;
            
            while(true) {
                IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset);
                SystemProcessInformation pi = new SystemProcessInformation();

                Marshal.PtrToStructure(currentPtr, pi);

                // get information for a process
                ProcessInfo processInfo = new ProcessInfo();
                // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD.
                processInfo.processId = pi.UniqueProcessId.ToInt32();
                processInfo.handleCount = (int)pi.HandleCount;
                processInfo.sessionId = (int)pi.SessionId;                
                processInfo.poolPagedBytes = (long)pi.QuotaPagedPoolUsage;;
                processInfo.poolNonpagedBytes = (long)pi.QuotaNonPagedPoolUsage;
                processInfo.virtualBytes = (long)pi.VirtualSize;
                processInfo.virtualBytesPeak = (long)pi.PeakVirtualSize;
                processInfo.workingSetPeak = (long)pi.PeakWorkingSetSize;
                processInfo.workingSet = (long)pi.WorkingSetSize;
                processInfo.pageFileBytesPeak = (long)pi.PeakPagefileUsage;
                processInfo.pageFileBytes = (long)pi.PagefileUsage;
                processInfo.privateBytes = (long)pi.PrivatePageCount;
                processInfo.basePriority = pi.BasePriority;


                if( pi.NamePtr == IntPtr.Zero) {                    
                    if( processInfo.processId == NtProcessManager.SystemProcessID) {
                        processInfo.processName = "System";
                    }
                    else if( processInfo.processId == NtProcessManager.IdleProcessID) {
                        processInfo.processName = "Idle";
                    }
                    else { 
                        // for normal process without name, using the process ID. 
                        processInfo.processName = processInfo.processId.ToString(CultureInfo.InvariantCulture);
                    }
                }
                else {                     
                    string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength/sizeof(char)));  
                    //
                    // On old operating system (NT4 and windows 2000), the process name might be truncated to 15 
                    // characters. For example, aspnet_admin.exe will show up in performance counter as aspnet_admin.ex.
                    // Process class try to return a nicer name. We used to get the main module name for a process and 
                    // use that as the process name. However normal user doesn't have access to module information, 
                    // so normal user will see an exception when we try to get a truncated process name.
                    //                    
                    if (ProcessManager.IsOSOlderThanXP && (processName.Length == 15)) {
                        if (processName.EndsWith(".", StringComparison.OrdinalIgnoreCase)) {
                            processName = processName.Substring(0, 14);
                        }
                        else if (processName.EndsWith(".e", StringComparison.OrdinalIgnoreCase)) {
                            processName = processName.Substring(0, 13);
                        }
                        else if (processName.EndsWith(".ex", StringComparison.OrdinalIgnoreCase)) {
                            processName = processName.Substring(0, 12);
                        }
                    }
                    processInfo.processName = processName;                                          
                }

                // get the threads for current process
                processInfos[processInfo.processId] =  processInfo;

                currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi));
                int i = 0;
                while( i < pi.NumberOfThreads) {
                    SystemThreadInformation ti = new SystemThreadInformation();
                    Marshal.PtrToStructure(currentPtr, ti);                    
                    ThreadInfo threadInfo = new ThreadInfo();                    

                    threadInfo.processId = (int)ti.UniqueProcess;
                    threadInfo.threadId = (int)ti.UniqueThread;
                    threadInfo.basePriority = ti.BasePriority;
                    threadInfo.currentPriority = ti.Priority;
                    threadInfo.startAddress = ti.StartAddress;
                    threadInfo.threadState = (ThreadState)ti.ThreadState;
                    threadInfo.threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason);

                    processInfo.threadInfoList.Add(threadInfo);
                    currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti));
                    i++;
                }

                if (pi.NextEntryOffset == 0) {
                    break;
                }
                totalOffset += pi.NextEntryOffset;
            }

            ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
            processInfos.Values.CopyTo(temp, 0);
            return temp;
        }
Example #22
0
        /// <devdoc>
        ///     Helper method for checking preconditions when accessing properties.
        /// </devdoc>
        /// <internalonly/>
        private void EnsureState(State state)
        {
            if ((state & State.Associated) != (State)0)
            {
                if (!Associated)
                {
                    throw new InvalidOperationException(SR.NoAssociatedProcess);
                }
            }

            if ((state & State.HaveId) != (State)0)
            {
                if (!_haveProcessId)
                {
                    if (_haveProcessHandle)
                    {
                        SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle));
                    }
                    else
                    {
                        EnsureState(State.Associated);
                        throw new InvalidOperationException(SR.ProcessIdRequired);
                    }
                }
                if ((state & State.HaveNonExitedId) == State.HaveNonExitedId)
                {
                    ThrowIfExited(refresh: false);
                }
            }

            if ((state & State.IsLocal) != (State)0 && _isRemoteMachine)
            {
                throw new NotSupportedException(SR.NotSupportedRemote);
            }

            if ((state & State.HaveProcessInfo) != (State)0)
            {
                if (_processInfo == null)
                {
                    if ((state & State.HaveNonExitedId) != State.HaveNonExitedId)
                    {
                        EnsureState(State.HaveNonExitedId);
                    }
                    _processInfo = ProcessManager.GetProcessInfo(_processId, _machineName);
                    if (_processInfo == null)
                    {
                        throw new InvalidOperationException(SR.NoProcessInfo);
                    }
                }
            }

            if ((state & State.Exited) != (State)0)
            {
                if (!HasExited)
                {
                    throw new InvalidOperationException(SR.WaitTillExit);
                }

                if (!_haveProcessHandle)
                {
                    throw new InvalidOperationException(SR.NoProcessHandle);
                }
            }
        }
        /// <summary>
        /// Creates a ProcessInfo from the data parsed from a /proc/pid/stat file and the associated tasks directory.
        /// </summary>
        internal static ProcessInfo CreateProcessInfo(ref Interop.procfs.ParsedStat procFsStat, ref Interop.procfs.ParsedStatus procFsStatus, ReusableTextReader reusableReader, string?processName = null)
        {
            int pid = procFsStat.pid;

            var pi = new ProcessInfo()
            {
                ProcessId        = pid,
                ProcessName      = processName ?? Process.GetUntruncatedProcessName(ref procFsStat) ?? string.Empty,
                BasePriority     = (int)procFsStat.nice,
                SessionId        = procFsStat.session,
                PoolPagedBytes   = (long)procFsStatus.VmSwap,
                VirtualBytes     = (long)procFsStatus.VmSize,
                VirtualBytesPeak = (long)procFsStatus.VmPeak,
                WorkingSetPeak   = (long)procFsStatus.VmHWM,
                WorkingSet       = (long)procFsStatus.VmRSS,
                PageFileBytes    = (long)procFsStatus.VmSwap,
                PrivateBytes     = (long)procFsStatus.VmData,
                // We don't currently fill in the other values.
                // A few of these could probably be filled in from getrusage,
                // but only for the current process or its children, not for
                // arbitrary other processes.
            };

            // Then read through /proc/pid/task/ to find each thread in the process...
            string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid);

            try
            {
                foreach (string taskDir in Directory.EnumerateDirectories(tasksDir))
                {
                    // ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo
                    string dirName = Path.GetFileName(taskDir);
                    int    tid;
                    Interop.procfs.ParsedStat stat;
                    if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid) &&
                        Interop.procfs.TryReadStatFile(pid, tid, out stat, reusableReader))
                    {
                        unsafe
                        {
                            pi._threadInfoList.Add(new ThreadInfo()
                            {
                                _processId        = pid,
                                _threadId         = (ulong)tid,
                                _basePriority     = pi.BasePriority,
                                _currentPriority  = (int)stat.nice,
                                _startAddress     = IntPtr.Zero,
                                _threadState      = ProcFsStateToThreadState(stat.state),
                                _threadWaitReason = ThreadWaitReason.Unknown
                            });
                        }
                    }
                }
            }
            catch (IOException)
            {
                // Between the time that we get an ID and the time that we try to read the associated
                // directories and files in procfs, the process could be gone.
            }

            // Finally return what we've built up
            return(pi);
        }
        public static ProcessInfo[] GetProcessInfos()
        {
            IntPtr    ptr       = (IntPtr)(-1);
            GCHandle  handle    = new GCHandle();
            ArrayList list      = new ArrayList();
            Hashtable hashtable = new Hashtable();

            try
            {
                Microsoft.Win32.NativeMethods.WinThreadEntry entry2;
                ptr = Microsoft.Win32.NativeMethods.CreateToolhelp32Snapshot(6, 0);
                if (ptr == ((IntPtr)(-1)))
                {
                    throw new Win32Exception();
                }
                int   num      = Marshal.SizeOf(typeof(Microsoft.Win32.NativeMethods.WinProcessEntry));
                int   val      = num + 260;
                int[] numArray = new int[val / 4];
                handle = GCHandle.Alloc(numArray, GCHandleType.Pinned);
                IntPtr ptr2 = handle.AddrOfPinnedObject();
                Marshal.WriteInt32(ptr2, val);
                HandleRef ref2 = new HandleRef(null, ptr);
                if (Microsoft.Win32.NativeMethods.Process32First(ref2, ptr2))
                {
                    do
                    {
                        Microsoft.Win32.NativeMethods.WinProcessEntry structure = new Microsoft.Win32.NativeMethods.WinProcessEntry();
                        Marshal.PtrToStructure(ptr2, structure);
                        ProcessInfo info = new ProcessInfo();
                        string      path = Marshal.PtrToStringAnsi((IntPtr)(((long)ptr2) + num));
                        info.processName  = Path.ChangeExtension(Path.GetFileName(path), null);
                        info.handleCount  = structure.cntUsage;
                        info.processId    = structure.th32ProcessID;
                        info.basePriority = structure.pcPriClassBase;
                        info.mainModuleId = structure.th32ModuleID;
                        hashtable.Add(info.processId, info);
                        Marshal.WriteInt32(ptr2, val);
                    }while (Microsoft.Win32.NativeMethods.Process32Next(ref2, ptr2));
                }
                entry2 = new Microsoft.Win32.NativeMethods.WinThreadEntry {
                    dwSize = Marshal.SizeOf(entry2)
                };
                if (Microsoft.Win32.NativeMethods.Thread32First(ref2, entry2))
                {
                    do
                    {
                        ThreadInfo info2 = new ThreadInfo {
                            threadId        = entry2.th32ThreadID,
                            processId       = entry2.th32OwnerProcessID,
                            basePriority    = entry2.tpBasePri,
                            currentPriority = entry2.tpBasePri + entry2.tpDeltaPri
                        };
                        list.Add(info2);
                    }while (Microsoft.Win32.NativeMethods.Thread32Next(ref2, entry2));
                }
                for (int i = 0; i < list.Count; i++)
                {
                    ThreadInfo  info3 = (ThreadInfo)list[i];
                    ProcessInfo info4 = (ProcessInfo)hashtable[info3.processId];
                    if (info4 != null)
                    {
                        info4.threadInfoList.Add(info3);
                    }
                }
            }
            finally
            {
                if (handle.IsAllocated)
                {
                    handle.Free();
                }
                if (ptr != ((IntPtr)(-1)))
                {
                    Microsoft.Win32.SafeNativeMethods.CloseHandle(new HandleRef(null, ptr));
                }
            }
            ProcessInfo[] array = new ProcessInfo[hashtable.Values.Count];
            hashtable.Values.CopyTo(array, 0);
            return(array);
        }
Example #25
0
		/// <summary>
		/// Currently Mono returns incomplete process names in Process.GetProcesses() so we need to parse 'ps' output.
		/// </summary>
		/// <returns></returns>
		public override ProcessInfo[] GetProcesses()
		{
			var Result = new List<ProcessInfo>();

			var StartInfo = new ProcessStartInfo ();
			StartInfo.FileName = "ps";
			StartInfo.Arguments = "-eaw -o pid,comm";
			StartInfo.CreateNoWindow = true;
			StartInfo.UseShellExecute = false;
			StartInfo.RedirectStandardOutput = true;

			var Proc = new Process ();
			Proc.StartInfo = StartInfo;
			try
			{
				Proc.Start();
				Proc.WaitForExit();
				for (string Line = Proc.StandardOutput.ReadLine(); Line != null; Line = Proc.StandardOutput.ReadLine())
				{
					Line = Line.Trim();
					int PIDEnd = Line.IndexOf(' ');
					var PIDString = Line.Substring(0, PIDEnd);
					if (PIDString != "PID")
					{
						var Filename = Line.Substring(PIDEnd + 1);
						var Pid = Int32.Parse(PIDString);
						try
						{
							var ExistingProc = Process.GetProcessById(Pid);
							if (ExistingProc != null && Pid != Process.GetCurrentProcess().Id && ExistingProc.HasExited == false)
							{
								var ProcInfo = new ProcessInfo(ExistingProc);
								ProcInfo.Name = Path.GetFileName(Filename);
								ProcInfo.Filename = Filename;
								Result.Add(ProcInfo);
							}
						} catch {}
					}
				}

			}
			catch {}
			return Result.ToArray();
		}
Example #26
0
 public virtual IEnumerator<object> WaitUntilProcessReady(ProcessInfo process)
 {
     yield break;
 }
Example #27
0
            public bool Equals(ProcessInfo p)
            {
                // If parameter is null return false:
                if ((object)p == null)
                {
                    return false;
                }

                // Return true if the fields match:
                return p.Process.Id==this.Process.Id;
            }
Example #28
0
        internal static ProcessInfo?CreateProcessInfo(int pid, string?processNameFilter = null)
        {
            // Negative PIDs aren't valid
            if (pid < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pid));
            }

            ProcessInfo procInfo;

            // Try to get the task info. This can fail if the user permissions don't permit
            // this user context to query the specified process
            Interop.libproc.proc_taskallinfo?info = Interop.libproc.GetProcessInfoById(pid);
            if (info.HasValue)
            {
                // Set the values we have; all the other values don't have meaning or don't exist on OSX
                Interop.libproc.proc_taskallinfo temp = info.Value;
                string processName;
                unsafe { processName = Marshal.PtrToStringUTF8(new IntPtr(temp.pbsd.pbi_comm)) !; }
                if (!string.IsNullOrEmpty(processNameFilter) && !string.Equals(processName, processNameFilter, StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                procInfo = new ProcessInfo()
                {
                    ProcessId    = pid,
                    ProcessName  = processName,
                    BasePriority = temp.pbsd.pbi_nice,
                    VirtualBytes = (long)temp.ptinfo.pti_virtual_size,
                    WorkingSet   = (long)temp.ptinfo.pti_resident_size,
                };
            }
            else if (string.IsNullOrEmpty(processNameFilter))
            {
                procInfo = new ProcessInfo()
                {
                    ProcessId = pid,
                };
            }
            else
            {
                // We couldn't get process information but we only want to return a process that
                // matches the specified name, so consider this process not a match.
                return(null);
            }

            // Get the sessionId for the given pid, getsid returns -1 on error
            int sessionId = Interop.Sys.GetSid(pid);

            if (sessionId != -1)
            {
                procInfo.SessionId = sessionId;
            }

            // Create a threadinfo for each thread in the process
            List <KeyValuePair <ulong, Interop.libproc.proc_threadinfo?> > lstThreads = Interop.libproc.GetAllThreadsInProcess(pid);

            foreach (KeyValuePair <ulong, Interop.libproc.proc_threadinfo?> t in lstThreads)
            {
                var ti = new ThreadInfo()
                {
                    _processId    = pid,
                    _threadId     = t.Key,
                    _basePriority = procInfo.BasePriority,
                    _startAddress = IntPtr.Zero
                };

                // Fill in additional info if we were able to retrieve such data about the thread
                if (t.Value.HasValue)
                {
                    ti._currentPriority  = t.Value.Value.pth_curpri;
                    ti._threadState      = ConvertOsxThreadRunStateToThreadState((Interop.libproc.ThreadRunState)t.Value.Value.pth_run_state);
                    ti._threadWaitReason = ConvertOsxThreadFlagsToWaitReason((Interop.libproc.ThreadFlags)t.Value.Value.pth_flags);
                }

                procInfo._threadInfoList.Add(ti);
            }

            return(procInfo);
        }
Example #29
0
        /// <summary>
        /// Creates a ProcessInfo from the data parsed from a /proc/pid/stat file and the associated tasks directory.
        /// </summary>
        internal static ProcessInfo CreateProcessInfo(Interop.procfs.ParsedStat procFsStat, ReusableTextReader reusableReader)
        {
            int pid = procFsStat.pid;

            // Get long process name if possible, otherwise use a fall back method.
            string procName = Path.GetFileName(Process.GetExePath(pid));

            if (string.IsNullOrEmpty(procName))
            {
                procName = procFsStat.comm;
            }

            var pi = new ProcessInfo()
            {
                ProcessId    = pid,
                ProcessName  = procName,
                BasePriority = (int)procFsStat.nice,
                VirtualBytes = (long)procFsStat.vsize,
                WorkingSet   = procFsStat.rss * Environment.SystemPageSize,
                SessionId    = procFsStat.session,

                // We don't currently fill in the other values.
                // A few of these could probably be filled in from getrusage,
                // but only for the current process or its children, not for
                // arbitrary other processes.
            };

            // Then read through /proc/pid/task/ to find each thread in the process...
            string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid);

            try
            {
                foreach (string taskDir in Directory.EnumerateDirectories(tasksDir))
                {
                    // ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo
                    string dirName = Path.GetFileName(taskDir);
                    int    tid;
                    Interop.procfs.ParsedStat stat;
                    if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid) &&
                        Interop.procfs.TryReadStatFile(pid, tid, out stat, reusableReader))
                    {
                        unsafe
                        {
                            pi._threadInfoList.Add(new ThreadInfo()
                            {
                                _processId        = pid,
                                _threadId         = (ulong)tid,
                                _basePriority     = pi.BasePriority,
                                _currentPriority  = (int)stat.nice,
                                _startAddress     = IntPtr.Zero,
                                _threadState      = ProcFsStateToThreadState(stat.state),
                                _threadWaitReason = ThreadWaitReason.Unknown
                            });
                        }
                    }
                }
            }
            catch (IOException)
            {
                // Between the time that we get an ID and the time that we try to read the associated
                // directories and files in procfs, the process could be gone.
            }

            // Finally return what we've built up
            return(pi);
        }
        static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data)
        {
#if FEATURE_TRACESWITCH
            Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()");
#endif
            Dictionary <int, ProcessInfo> processInfos = new Dictionary <int, ProcessInfo>();
            List <ThreadInfo>             threadInfos  = new List <ThreadInfo>();

            GCHandle dataHandle = new GCHandle();
            try
            {
                dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
                IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject();
                Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK();
                Marshal.PtrToStructure(dataBlockPtr, dataBlock);
                IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength);
                Interop.Advapi32.PERF_INSTANCE_DEFINITION instance     = new Interop.Advapi32.PERF_INSTANCE_DEFINITION();
                Interop.Advapi32.PERF_COUNTER_BLOCK       counterBlock = new Interop.Advapi32.PERF_COUNTER_BLOCK();
                for (int i = 0; i < dataBlock.NumObjectTypes; i++)
                {
                    Interop.Advapi32.PERF_OBJECT_TYPE type = new Interop.Advapi32.PERF_OBJECT_TYPE();
                    Marshal.PtrToStructure(typePtr, type);
                    IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength);
                    IntPtr counterPtr  = (IntPtr)((long)typePtr + type.HeaderLength);
                    List <Interop.Advapi32.PERF_COUNTER_DEFINITION> counterList = new List <Interop.Advapi32.PERF_COUNTER_DEFINITION>();

                    for (int j = 0; j < type.NumCounters; j++)
                    {
                        Interop.Advapi32.PERF_COUNTER_DEFINITION counter = new Interop.Advapi32.PERF_COUNTER_DEFINITION();
                        Marshal.PtrToStructure(counterPtr, counter);
                        string counterName = library.GetCounterName(counter.CounterNameTitleIndex);

                        if (type.ObjectNameTitleIndex == processIndex)
                        {
                            counter.CounterNameTitlePtr = (int)GetValueId(counterName);
                        }
                        else if (type.ObjectNameTitleIndex == threadIndex)
                        {
                            counter.CounterNameTitlePtr = (int)GetValueId(counterName);
                        }
                        counterList.Add(counter);
                        counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength);
                    }

                    Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters = counterList.ToArray();

                    for (int j = 0; j < type.NumInstances; j++)
                    {
                        Marshal.PtrToStructure(instancePtr, instance);
                        IntPtr namePtr      = (IntPtr)((long)instancePtr + instance.NameOffset);
                        string instanceName = Marshal.PtrToStringUni(namePtr);
                        if (instanceName.Equals("_Total"))
                        {
                            continue;
                        }
                        IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength);
                        Marshal.PtrToStructure(counterBlockPtr, counterBlock);
                        if (type.ObjectNameTitleIndex == processIndex)
                        {
                            ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
                            if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0)
                            {
                                // Sometimes we'll get a process structure that is not completely filled in.
                                // We can catch some of these by looking for non-"idle" processes that have id 0
                                // and ignoring those.
#if FEATURE_TRACESWITCH
                                Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring.");
#endif
                            }
                            else
                            {
                                if (processInfos.ContainsKey(processInfo.ProcessId))
                                {
                                    // We've found two entries in the perfcounters that claim to be the
                                    // same process.  We throw an exception.  Is this really going to be
                                    // helpful to the user?  Should we just ignore?
#if FEATURE_TRACESWITCH
                                    Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id");
#endif
                                }
                                else
                                {
                                    // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe",
                                    // if it's in the first 15.  The problem is that sometimes that will leave us with part of ".exe"
                                    // at the end.  If instanceName ends in ".", ".e", or ".ex" we remove it.
                                    string processName = instanceName;
                                    if (processName.Length == 15)
                                    {
                                        if (instanceName.EndsWith(".", StringComparison.Ordinal))
                                        {
                                            processName = instanceName.Substring(0, 14);
                                        }
                                        else if (instanceName.EndsWith(".e", StringComparison.Ordinal))
                                        {
                                            processName = instanceName.Substring(0, 13);
                                        }
                                        else if (instanceName.EndsWith(".ex", StringComparison.Ordinal))
                                        {
                                            processName = instanceName.Substring(0, 12);
                                        }
                                    }
                                    processInfo.ProcessName = processName;
                                    processInfos.Add(processInfo.ProcessId, processInfo);
                                }
                            }
                        }
                        else if (type.ObjectNameTitleIndex == threadIndex)
                        {
                            ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
                            if (threadInfo._threadId != 0)
                            {
                                threadInfos.Add(threadInfo);
                            }
                        }
                        instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength);
                    }

                    typePtr = (IntPtr)((long)typePtr + type.TotalByteLength);
                }
            }
            finally
            {
                if (dataHandle.IsAllocated)
                {
                    dataHandle.Free();
                }
            }

            for (int i = 0; i < threadInfos.Count; i++)
            {
                ThreadInfo  threadInfo = (ThreadInfo)threadInfos[i];
                ProcessInfo processInfo;
                if (processInfos.TryGetValue(threadInfo._processId, out processInfo))
                {
                    processInfo._threadInfoList.Add(threadInfo);
                }
            }

            ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
            processInfos.Values.CopyTo(temp, 0);
            return(temp);
        }
Example #31
0
        static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) {
            Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos()");
            Hashtable processInfos = new Hashtable();
            ArrayList threadInfos = new ArrayList();

            GCHandle dataHandle = new GCHandle();             
            try {
                dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
                IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject();
                NativeMethods.PERF_DATA_BLOCK dataBlock = new NativeMethods.PERF_DATA_BLOCK();
                Marshal.PtrToStructure(dataBlockPtr, dataBlock);
                IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength);
                NativeMethods.PERF_INSTANCE_DEFINITION instance = new NativeMethods.PERF_INSTANCE_DEFINITION();
                NativeMethods.PERF_COUNTER_BLOCK counterBlock = new NativeMethods.PERF_COUNTER_BLOCK();                        
                for (int i = 0; i < dataBlock.NumObjectTypes; i++) {
                    NativeMethods.PERF_OBJECT_TYPE type = new NativeMethods.PERF_OBJECT_TYPE();
                    Marshal.PtrToStructure(typePtr, type);
                    IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength);
                    IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength);
                    ArrayList counterList = new ArrayList();
                    
                    for (int j = 0; j < type.NumCounters; j++) {                    
                        NativeMethods.PERF_COUNTER_DEFINITION counter = new NativeMethods.PERF_COUNTER_DEFINITION();
                        Marshal.PtrToStructure(counterPtr, counter);
                        string counterName = library.GetCounterName(counter.CounterNameTitleIndex);

                        if (type.ObjectNameTitleIndex == processIndex)
                            counter.CounterNameTitlePtr = (int)GetValueId(counterName);
                        else if (type.ObjectNameTitleIndex == threadIndex)
                            counter.CounterNameTitlePtr = (int)GetValueId(counterName);
                        counterList.Add(counter);
                        counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength);
                    }
                    NativeMethods.PERF_COUNTER_DEFINITION[] counters = new NativeMethods.PERF_COUNTER_DEFINITION[counterList.Count];
                    counterList.CopyTo(counters, 0);
                    for (int j = 0; j < type.NumInstances; j++) {
                        Marshal.PtrToStructure(instancePtr, instance);
                        IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset);
                        string instanceName = Marshal.PtrToStringUni(namePtr);            
                        if (instanceName.Equals("_Total")) continue;
                        IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength);
                        Marshal.PtrToStructure(counterBlockPtr, counterBlock);
                        if (type.ObjectNameTitleIndex == processIndex) {
                            ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
                            if (processInfo.processId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0) {
                                // Sometimes we'll get a process structure that is not completely filled in.
                                // We can catch some of these by looking for non-"idle" processes that have id 0
                                // and ignoring those.
                                Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring.");
                            }
                            else {
                                if (processInfos[processInfo.processId] != null) {
                                    // We've found two entries in the perfcounters that claim to be the
                                    // same process.  We throw an exception.  Is this really going to be
                                    // helpfull to the user?  Should we just ignore?
                                    Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id");
                                }
                                else {
                                    // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe",
                                    // if it's in the first 15.  The problem is that sometimes that will leave us with part of ".exe"
                                    // at the end.  If instanceName ends in ".", ".e", or ".ex" we remove it.
                                    string processName = instanceName;
                                    if (processName.Length == 15) {
                                        if      (instanceName.EndsWith(".", StringComparison.Ordinal  )) processName = instanceName.Substring(0, 14);
                                        else if (instanceName.EndsWith(".e", StringComparison.Ordinal )) processName = instanceName.Substring(0, 13);
                                        else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12);
                                    }
                                    processInfo.processName = processName;
                                    processInfos.Add(processInfo.processId, processInfo);
                                }
                            }
                        }
                        else if (type.ObjectNameTitleIndex == threadIndex) {
                            ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
                            if (threadInfo.threadId != 0) threadInfos.Add(threadInfo);
                        }
                        instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength);
                    }                                
                    
                    typePtr = (IntPtr)((long)typePtr + type.TotalByteLength);
                }
            }
            finally {
                if (dataHandle.IsAllocated) dataHandle.Free();
            }

            for (int i = 0; i < threadInfos.Count; i++) {
                ThreadInfo threadInfo = (ThreadInfo)threadInfos[i];
                ProcessInfo processInfo = (ProcessInfo)processInfos[threadInfo.processId];
                if (processInfo != null) {
                    processInfo.threadInfoList.Add(threadInfo);
                }
            }
                        
            ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
            processInfos.Values.CopyTo(temp, 0);
            return temp;
        }
Example #32
0
        private static ProcessInfo[] GetProcessInfos(IntPtr dataPtr)
        {
            IntPtr    ptr;
            Hashtable hashtable = new Hashtable(60);
            long      num       = 0L;

Label_000B:
            ptr = (IntPtr)(((long)dataPtr) + num);
            SystemProcessInformation structure = new SystemProcessInformation();

            Marshal.PtrToStructure(ptr, structure);
            ProcessInfo info = new ProcessInfo {
                processId         = structure.UniqueProcessId.ToInt32(),
                handleCount       = (int)structure.HandleCount,
                sessionId         = (int)structure.SessionId,
                poolPagedBytes    = (long)((ulong)structure.QuotaPagedPoolUsage),
                poolNonpagedBytes = (long)((ulong)structure.QuotaNonPagedPoolUsage),
                virtualBytes      = (long)((ulong)structure.VirtualSize),
                virtualBytesPeak  = (long)((ulong)structure.PeakVirtualSize),
                workingSetPeak    = (long)((ulong)structure.PeakWorkingSetSize),
                workingSet        = (long)((ulong)structure.WorkingSetSize),
                pageFileBytesPeak = (long)((ulong)structure.PeakPagefileUsage),
                pageFileBytes     = (long)((ulong)structure.PagefileUsage),
                privateBytes      = (long)((ulong)structure.PrivatePageCount),
                basePriority      = structure.BasePriority
            };

            if (structure.NamePtr == IntPtr.Zero)
            {
                if (info.processId == NtProcessManager.SystemProcessID)
                {
                    info.processName = "System";
                }
                else if (info.processId == 0)
                {
                    info.processName = "Idle";
                }
                else
                {
                    info.processName = info.processId.ToString(CultureInfo.InvariantCulture);
                }
            }
            else
            {
                string processShortName = GetProcessShortName(Marshal.PtrToStringUni(structure.NamePtr, structure.NameLength / 2));
                if (ProcessManager.IsOSOlderThanXP && (processShortName.Length == 15))
                {
                    if (processShortName.EndsWith(".", StringComparison.OrdinalIgnoreCase))
                    {
                        processShortName = processShortName.Substring(0, 14);
                    }
                    else if (processShortName.EndsWith(".e", StringComparison.OrdinalIgnoreCase))
                    {
                        processShortName = processShortName.Substring(0, 13);
                    }
                    else if (processShortName.EndsWith(".ex", StringComparison.OrdinalIgnoreCase))
                    {
                        processShortName = processShortName.Substring(0, 12);
                    }
                }
                info.processName = processShortName;
            }
            hashtable[info.processId] = info;
            ptr = (IntPtr)(((long)ptr) + Marshal.SizeOf(structure));
            for (int i = 0; i < structure.NumberOfThreads; i++)
            {
                SystemThreadInformation information2 = new SystemThreadInformation();
                Marshal.PtrToStructure(ptr, information2);
                ThreadInfo info2 = new ThreadInfo {
                    processId        = (int)information2.UniqueProcess,
                    threadId         = (int)information2.UniqueThread,
                    basePriority     = information2.BasePriority,
                    currentPriority  = information2.Priority,
                    startAddress     = information2.StartAddress,
                    threadState      = (ThreadState)information2.ThreadState,
                    threadWaitReason = NtProcessManager.GetThreadWaitReason((int)information2.WaitReason)
                };
                info.threadInfoList.Add(info2);
                ptr = (IntPtr)(((long)ptr) + Marshal.SizeOf(information2));
            }
            if (structure.NextEntryOffset != 0)
            {
                num += structure.NextEntryOffset;
                goto Label_000B;
            }
            ProcessInfo[] array = new ProcessInfo[hashtable.Values.Count];
            hashtable.Values.CopyTo(array, 0);
            return(array);
        }
Example #33
0
 static ProcessInfo GetProcessInfo(NativeMethods.PERF_OBJECT_TYPE type, IntPtr instancePtr, NativeMethods.PERF_COUNTER_DEFINITION[] counters) {
     ProcessInfo processInfo = new ProcessInfo();
     for (int i = 0; i < counters.Length; i++) {
         NativeMethods.PERF_COUNTER_DEFINITION counter = counters[i];
         long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
         switch ((ValueId)counter.CounterNameTitlePtr) {
             case ValueId.ProcessId:
                 processInfo.processId = (int)value;
                 break;
             case ValueId.HandleCount:
                 processInfo.handleCount = (int)value;
                 break;
             case ValueId.PoolPagedBytes:
                 processInfo.poolPagedBytes = value;
                 break;
             case ValueId.PoolNonpagedBytes:
                 processInfo.poolNonpagedBytes = value;
                 break;
             case ValueId.VirtualBytes:
                 processInfo.virtualBytes = value;
                 break;
             case ValueId.VirtualBytesPeak:
                 processInfo.virtualBytesPeak = value;
                 break;
             case ValueId.WorkingSetPeak:
                 processInfo.workingSetPeak = value;
                 break;
             case ValueId.WorkingSet:
                 processInfo.workingSet = value;
                 break;
             case ValueId.PageFileBytesPeak:
                 processInfo.pageFileBytesPeak = value;
                 break;
             case ValueId.PageFileBytes:
                 processInfo.pageFileBytes = value;
                 break;
             case ValueId.PrivateBytes:
                 processInfo.privateBytes = value;
                 break;
             case ValueId.BasePriority:
                 processInfo.basePriority = (int)value;
                 break;
         }
     }
     return processInfo;
 }
        static ProcessInfo[] GetProcessInfos(IntPtr dataPtr)
        {
            // 60 is a reasonable number for processes on a normal machine.
            Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60);

            long totalOffset = 0;

            while (true)
            {
                IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset);
                SystemProcessInformation pi = new SystemProcessInformation();

                Marshal.PtrToStructure(currentPtr, pi);

                // get information for a process
                ProcessInfo processInfo = new ProcessInfo();
                // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD.
                processInfo.ProcessId = pi.UniqueProcessId.ToInt32();
                processInfo.SessionId = (int)pi.SessionId;
                processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; ;
                processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage;
                processInfo.VirtualBytes = (long)pi.VirtualSize;
                processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize;
                processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize;
                processInfo.WorkingSet = (long)pi.WorkingSetSize;
                processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage;
                processInfo.PageFileBytes = (long)pi.PagefileUsage;
                processInfo.PrivateBytes = (long)pi.PrivatePageCount;
                processInfo.BasePriority = pi.BasePriority;


                if (pi.NamePtr == IntPtr.Zero)
                {
                    if (processInfo.ProcessId == NtProcessManager.SystemProcessID)
                    {
                        processInfo.ProcessName = "System";
                    }
                    else if (processInfo.ProcessId == NtProcessManager.IdleProcessID)
                    {
                        processInfo.ProcessName = "Idle";
                    }
                    else
                    {
                        // for normal process without name, using the process ID. 
                        processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture);
                    }
                }
                else
                {
                    string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength / sizeof(char)));
                    processInfo.ProcessName = processName;
                }

                // get the threads for current process
                processInfos[processInfo.ProcessId] = processInfo;

                currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi));
                int i = 0;
                while (i < pi.NumberOfThreads)
                {
                    SystemThreadInformation ti = new SystemThreadInformation();
                    Marshal.PtrToStructure(currentPtr, ti);
                    ThreadInfo threadInfo = new ThreadInfo();

                    threadInfo._processId = (int)ti.UniqueProcess;
                    threadInfo._threadId = (ulong)ti.UniqueThread;
                    threadInfo._basePriority = ti.BasePriority;
                    threadInfo._currentPriority = ti.Priority;
                    threadInfo._startAddress = ti.StartAddress;
                    threadInfo._threadState = (ThreadState)ti.ThreadState;
                    threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason);

                    processInfo._threadInfoList.Add(threadInfo);
                    currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti));
                    i++;
                }

                if (pi.NextEntryOffset == 0)
                {
                    break;
                }
                totalOffset += pi.NextEntryOffset;
            }

            ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
            processInfos.Values.CopyTo(temp, 0);
            return temp;
        }
        private static ProcessInfo CreateProcessInfo(int pid)
        {
            // Read /proc/pid/stat to get information about the process, and churn that into a ProcessInfo
            ProcessInfo pi;

            try
            {
                Interop.procfs.ParsedStat procFsStat = Interop.procfs.ReadStatFile(pid);
                pi = new ProcessInfo
                {
                    _processId    = pid,
                    _processName  = procFsStat.comm,
                    _basePriority = (int)procFsStat.nice,
                    _virtualBytes = (long)procFsStat.vsize,
                    _workingSet   = procFsStat.rss,
                    _sessionId    = procFsStat.session,
                    _handleCount  = 0, // not a Unix concept

                    // We don't currently fill in the following values.
                    // A few of these could probably be filled in from getrusage,
                    // but only for the current process or its children, not for
                    // arbitrary other processes.
                    _poolPagedBytes    = 0,
                    _poolNonpagedBytes = 0,
                    _virtualBytesPeak  = 0,
                    _workingSetPeak    = 0,
                    _pageFileBytes     = 0,
                    _pageFileBytesPeak = 0,
                    _privateBytes      = 0,
                };
            }
            catch (FileNotFoundException)
            {
                // Between the time that we get an ID and the time that we try to read the associated stat
                // file(s), the process could be gone.
                return(null);
            }

            // Then read through /proc/pid/task/ to find each thread in the process...
            try
            {
                string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid);
                foreach (string taskDir in Directory.EnumerateDirectories(tasksDir))
                {
                    string dirName = Path.GetFileName(taskDir);
                    int    tid;
                    if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid))
                    {
                        // ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo
                        Interop.procfs.ParsedStat stat = Interop.procfs.ReadStatFile(pid, tid);
                        pi._threadInfoList.Add(new ThreadInfo
                        {
                            _processId        = pid,
                            _threadId         = tid,
                            _basePriority     = pi._basePriority,
                            _currentPriority  = (int)stat.nice,
                            _startAddress     = (IntPtr)stat.startstack,
                            _threadState      = ProcFsStateToThreadState(stat.state),
                            _threadWaitReason = ThreadWaitReason.Unknown
                        });
                    }
                }
            }
            catch (FileNotFoundException) { } // process and/or threads may go away by the time we try to read from them
            catch (DirectoryNotFoundException) { }

            // Finally return what we've built up
            return(pi);
        }
Example #36
0
        private void RefreshByModule()
        {
            Dictionary<string, ProcessInfo> dict = new Dictionary<string, ProcessInfo>(StringComparer.CurrentCultureIgnoreCase);
            foreach(Process p in Process.GetProcesses())
            {
                string procname = GetSafeProcessName(p);

                ProcessModuleCollection pmc = null;
                try
                {
                     pmc = p.Modules;
                }
                catch
                {
                    continue;
                }
                if (pmc != null)
                {
                    string FormattedProcessName = string.Format("{0} [{1}]", procname, p.Id);
                    foreach (ProcessModule m in pmc)
                    {
                        string key = GetSafeModuleName(m);
                        ProcessInfo pi = null;
                        try
                        {
                            if (dict.ContainsKey(key))
                            {
                                pi = dict[key];
                            }
                        }
                        catch
                        {

                        }
                        if (pi == null)
                        {
                            pi = new ProcessInfo(key, CurrentDisplayMode);
                            dict[key] = pi;
                        }
                        pi.Dependencies.Add(FormattedProcessName);
                    }
                }
            }

            Items.Clear();
            foreach (ProcessInfo pi in dict.Values)
                Items.Add(pi);
        }
Example #37
0
        /// <summary>
        /// Creates a ProcessInfo from the data parsed from a /proc/pid/stat file and the associated tasks directory.
        /// </summary>
        internal static ProcessInfo CreateProcessInfo(Interop.procfs.ParsedStat procFsStat, ReusableTextReader reusableReader)
        {
            int pid = procFsStat.pid;

            var pi = new ProcessInfo()
            {
                ProcessId = pid,
                ProcessName = procFsStat.comm,
                BasePriority = (int)procFsStat.nice,
                VirtualBytes = (long)procFsStat.vsize,
                WorkingSet = procFsStat.rss,
                SessionId = procFsStat.session,

                // We don't currently fill in the other values.
                // A few of these could probably be filled in from getrusage,
                // but only for the current process or its children, not for
                // arbitrary other processes.
            };

            // Then read through /proc/pid/task/ to find each thread in the process...
            string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid);
            foreach (string taskDir in Directory.EnumerateDirectories(tasksDir))
            {
                // ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo
                string dirName = Path.GetFileName(taskDir);
                int tid;
                Interop.procfs.ParsedStat stat;
                if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid) &&
                    Interop.procfs.TryReadStatFile(pid, tid, out stat, reusableReader))
                {
                    pi._threadInfoList.Add(new ThreadInfo()
                    {
                        _processId = pid,
                        _threadId = (ulong)tid,
                        _basePriority = pi.BasePriority,
                        _currentPriority = (int)stat.nice,
                        _startAddress = (IntPtr)stat.startstack,
                        _threadState = ProcFsStateToThreadState(stat.state),
                        _threadWaitReason = ThreadWaitReason.Unknown
                    });
                }
            }

            // Finally return what we've built up
            return pi;
        }
Example #38
0
        private void RefreshByProcess()
        {
            Items.Clear();

            foreach(Process p in Process.GetProcesses())
            {
                ProcessInfo pi = new ProcessInfo(GetSafeProcessName(p), p.Id, CurrentDisplayMode);
                Items.Add(pi);
                ProcessModuleCollection pmc = null;
                try
                {
                     pmc = p.Modules;
                }
                catch
                {
                    continue;
                }
                foreach (ProcessModule m in pmc)
                {
                    pi.Dependencies.Add(GetSafeModuleName(m));
                }
            }
        }
Example #39
0
 public double[] GetCpuUsage(string processName, bool monitor = false)
 {
     ArrayList cpuUsage = new ArrayList();
     ArrayList threadPool = new ArrayList();
     try
     {
         processName = GetProcessName(processName);
         common.LogMessage(processName);
         Process[] processes = Process.GetProcessesByName(processName);
         foreach (Process p in processes)
         {
             try
             {
                 // Need to call this once, before calling GetCurrentCpuUsage
                 ProcessPerformanceCounter perf = new ProcessPerformanceCounter(
                     common, processName, p.Id);
                 if (perf != null)
                     perf = null;
                 ProcessInfo processInfo = new ProcessInfo();
                 processInfo.process = p;
                 processInfo.monitor = monitor;
                 processInfo.cpuUsage = cpuUsage;
                 if (processes.Length > 1)
                 {
                     // Increased the performance of output
                     // else for running 10+ instance of an app
                     // takes lot of time
                     Thread thread = new Thread(new ParameterizedThreadStart(
                         GetCurrentCpuUsage));
                     thread.Start(processInfo);
                     threadPool.Add(thread);
                 }
                 else
                     GetCurrentCpuUsage(processInfo);
             }
             catch (Exception ex)
             {
                 common.LogMessage(ex);
             }
         }
         foreach (Thread thread in threadPool)
         {
             // Wait for each thread to complete its job
             thread.Join();
         }
         if (common.Debug)
         {
             foreach (double value in cpuUsage)
                 common.LogMessage(value);
         }
         return cpuUsage.ToArray(typeof(double)) as double[];
     }
     catch (Exception ex)
     {
         common.LogMessage(ex);
         return cpuUsage.ToArray(typeof(double)) as double[];
     }
     finally
     {
         cpuUsage = null;
         threadPool = null;
     }
 }
        private static unsafe ProcessInfo[] GetProcessInfos(IntPtr dataPtr, Predicate <int> processIdFilter)
        {
            // Use a dictionary to avoid duplicate entries if any
            // 60 is a reasonable number for processes on a normal machine.
            Dictionary <int, ProcessInfo> processInfos = new Dictionary <int, ProcessInfo>(60);

            long totalOffset = 0;

            while (true)
            {
                IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset);
                ref SystemProcessInformation pi = ref *(SystemProcessInformation *)(currentPtr);

                // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD.
                var processInfoProcessId = pi.UniqueProcessId.ToInt32();
                if (processIdFilter == null || processIdFilter(processInfoProcessId))
                {
                    // get information for a process
                    ProcessInfo processInfo = new ProcessInfo();
                    processInfo.ProcessId         = processInfoProcessId;
                    processInfo.SessionId         = (int)pi.SessionId;
                    processInfo.PoolPagedBytes    = (long)pi.QuotaPagedPoolUsage;
                    processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage;
                    processInfo.VirtualBytes      = (long)pi.VirtualSize;
                    processInfo.VirtualBytesPeak  = (long)pi.PeakVirtualSize;
                    processInfo.WorkingSetPeak    = (long)pi.PeakWorkingSetSize;
                    processInfo.WorkingSet        = (long)pi.WorkingSetSize;
                    processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage;
                    processInfo.PageFileBytes     = (long)pi.PagefileUsage;
                    processInfo.PrivateBytes      = (long)pi.PrivatePageCount;
                    processInfo.BasePriority      = pi.BasePriority;
                    processInfo.HandleCount       = (int)pi.HandleCount;

                    if (pi.ImageName.Buffer == IntPtr.Zero)
                    {
                        if (processInfo.ProcessId == NtProcessManager.SystemProcessID)
                        {
                            processInfo.ProcessName = "System";
                        }
                        else if (processInfo.ProcessId == NtProcessManager.IdleProcessID)
                        {
                            processInfo.ProcessName = "Idle";
                        }
                        else
                        {
                            // for normal process without name, using the process ID.
                            processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture);
                        }
                    }
                    else
                    {
                        string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.ImageName.Buffer, pi.ImageName.Length / sizeof(char)));
                        processInfo.ProcessName = processName;
                    }

                    // get the threads for current process
                    processInfos[processInfo.ProcessId] = processInfo;

                    currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi));
                    int i = 0;
                    while (i < pi.NumberOfThreads)
                    {
                        ref SystemThreadInformation ti = ref *(SystemThreadInformation *)(currentPtr);
                        ThreadInfo threadInfo          = new ThreadInfo();

                        threadInfo._processId        = (int)ti.ClientId.UniqueProcess;
                        threadInfo._threadId         = (ulong)ti.ClientId.UniqueThread;
                        threadInfo._basePriority     = ti.BasePriority;
                        threadInfo._currentPriority  = ti.Priority;
                        threadInfo._startAddress     = ti.StartAddress;
                        threadInfo._threadState      = (ThreadState)ti.ThreadState;
                        threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason);

                        processInfo._threadInfoList.Add(threadInfo);
                        currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti));
                        i++;
                    }
                }