// ----------------------------- // ---- 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; }
// ----------------------------- // ---- 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.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.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; }
static ThreadInfo GetThreadInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); 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: threadInfo._processId = (int)value; break; case ValueId.ThreadId: threadInfo._threadId = (ulong)value; break; case ValueId.BasePriority: threadInfo._basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo._currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo._startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo._threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo._threadWaitReason = GetThreadWaitReason((int)value); break; } } return(threadInfo); }
public static bool processCheck(IntPtr hwnd, ref ThreadInfo threadInfo) { //Get Process ID from the windowHandler int pid = 0; GetWindowThreadProcessId(hwnd.ToInt32(), out pid); //Check if the process is a sub-process of the process: spotify if (pid == (int)threadInfo.spID) { //Check if the process' title contains the word Spotify (Caps Sensitive) if (getWindowTitle(hwnd).Contains("Spotify")) { //Throw the info into the threadInfo object threadInfo.hWnd = hwnd; threadInfo.title = getWindowTitle(hwnd); //Break out of our loop searching all processes return false; } } return true; }
private static ThreadInfo GetThreadInfo(Microsoft.Win32.NativeMethods.PERF_OBJECT_TYPE type, IntPtr instancePtr, Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo info = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION perf_counter_definition = counters[i]; long num2 = ReadCounterValue(perf_counter_definition.CounterType, (IntPtr)(((long)instancePtr) + perf_counter_definition.CounterOffset)); switch (perf_counter_definition.CounterNameTitlePtr) { case 11: info.threadId = (int)num2; break; case 12: info.processId = (int)num2; break; case 13: info.basePriority = (int)num2; break; case 14: info.currentPriority = (int)num2; break; case 0x11: info.startAddress = (IntPtr)num2; break; case 0x12: info.threadState = (System.Diagnostics.ThreadState)((int)num2); break; case 0x13: info.threadWaitReason = GetThreadWaitReason((int)num2); break; } } return(info); }
public static ThreadInfo Impersonate(ThreadInfo ti) { if (ti == null) throw new ArgumentNullException("ti"); ThreadInfo prevInfo = Capture(true, true, true, true); Restore(ti); return (prevInfo); }
void Initialize( bool propogateThreadPrincipal, bool propogateCallContext, bool propogateHttpContext, bool propogateCASMarkers ) { workingTime = timeStampStarted = DateTime.Now; threadInfo = ThreadInfo.Capture( propogateThreadPrincipal, propogateCallContext, propogateHttpContext, propogateCASMarkers ); }
public bool NextItem(ref ThreadInfo Info) { Debug.Assert(m_EnumHandle != null); Info.Size = (uint)Marshal.SizeOf(typeof(ThreadInfo)); int hr = JpfsvGetNextThread(m_EnumHandle, ref Info); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); throw new InvalidOperationException("Cannot get here"); } else if (hr == 1) { return false; } else { return true; } }
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; }
private void LoadThreadList() { try { string path = Path.Combine(Settings.GetSettingsDirectory(), Settings.ThreadsFileName); if (!File.Exists(path)) return; string[] lines = File.ReadAllLines(path); if (lines.Length < 1) return; int fileVersion = Int32.Parse(lines[0]); int linesPerThread; switch (fileVersion) { case 1: linesPerThread = 6; break; case 2: linesPerThread = 7; break; case 3: linesPerThread = 10; break; case 4: linesPerThread = 13; break; default: return; } if (lines.Length < (1 + linesPerThread)) return; _isLoadingThreadsFromFile = true; Invoke(() => { UpdateCategories(String.Empty); }); int i = 1; while (i <= lines.Length - linesPerThread) { ThreadInfo thread = new ThreadInfo { ExtraData = new WatcherExtraData() }; thread.URL = lines[i++]; thread.PageAuth = lines[i++]; thread.ImageAuth = lines[i++]; thread.CheckIntervalSeconds = Int32.Parse(lines[i++]); thread.OneTimeDownload = lines[i++] == "1"; thread.SaveDir = lines[i++]; thread.SaveDir = thread.SaveDir.Length != 0 ? General.GetAbsoluteDirectoryPath(thread.SaveDir, Settings.AbsoluteDownloadDirectory) : null; if (fileVersion >= 2) { string stopReasonLine = lines[i++]; if (stopReasonLine.Length != 0) { thread.StopReason = (StopReason)Int32.Parse(stopReasonLine); } } if (fileVersion >= 3) { thread.Description = lines[i++]; thread.ExtraData.AddedOn = new DateTime(Int64.Parse(lines[i++]), DateTimeKind.Utc).ToLocalTime(); string lastImageOn = lines[i++]; if (lastImageOn.Length != 0) { thread.ExtraData.LastImageOn = new DateTime(Int64.Parse(lastImageOn), DateTimeKind.Utc).ToLocalTime(); } } else { thread.Description = String.Empty; thread.ExtraData.AddedOn = DateTime.Now; } if (fileVersion >= 4) { thread.ExtraData.AddedFrom = lines[i++]; thread.Category = lines[i++]; thread.AutoFollow = lines[i++] == "1"; } else { thread.ExtraData.AddedFrom = String.Empty; thread.Category = String.Empty; } Invoke(() => { AddThread(thread); }); } foreach (ThreadWatcher threadWatcher in ThreadWatchers) { ThreadWatcher parentThread; _watchers.TryGetValue(((WatcherExtraData)threadWatcher.Tag).AddedFrom, out parentThread); threadWatcher.ParentThread = parentThread; if (parentThread != null && !parentThread.ChildThreads.ContainsKey(threadWatcher.PageID) && !parentThread.ChildThreads.ContainsKey(parentThread.PageID)) { parentThread.ChildThreads.Add(threadWatcher.PageID, threadWatcher); } ThreadWatcher watcher = threadWatcher; Invoke(() => { DisplayAddedFrom(watcher); }); if (Settings.ChildThreadsAreNewFormat == true && threadWatcher.StopReason != StopReason.PageNotFound && threadWatcher.StopReason != StopReason.UserRequest) { threadWatcher.Start(); } } if (Settings.ChildThreadsAreNewFormat != true) { foreach (ThreadWatcher threadWatcher in ThreadWatchers) { if (threadWatcher.ChildThreads.Count == 0 || threadWatcher.ParentThread != null) continue; foreach (ThreadWatcher descendantThread in threadWatcher.DescendantThreads.Values) { descendantThread.DoNotRename = true; string sourceDir = descendantThread.ThreadDownloadDirectory; string destDir; if (General.RemoveLastDirectory(sourceDir) == descendantThread.MainDownloadDirectory) { destDir = Path.Combine(descendantThread.MainDownloadDirectory, General.RemoveLastDirectory(sourceDir)); } else { destDir = Path.Combine(General.RemoveLastDirectory(threadWatcher.ThreadDownloadDirectory), General.GetRelativeDirectoryPath(descendantThread.ThreadDownloadDirectory, threadWatcher.ThreadDownloadDirectory)); } if (String.Equals(destDir, sourceDir, StringComparison.Ordinal) || !Directory.Exists(sourceDir)) continue; try { if (String.Equals(destDir, sourceDir, StringComparison.OrdinalIgnoreCase)) { Directory.Move(sourceDir, destDir + " Temp"); sourceDir = destDir + " Temp"; } if (!Directory.Exists(General.RemoveLastDirectory(destDir))) Directory.CreateDirectory(General.RemoveLastDirectory(destDir)); Directory.Move(sourceDir, destDir); descendantThread.ThreadDownloadDirectory = destDir; } catch (Exception ex) { Logger.Log(ex.ToString()); } descendantThread.DoNotRename = false; } } Settings.ChildThreadsAreNewFormat = true; Settings.Save(); foreach (ThreadWatcher threadWatcher in ThreadWatchers) { if (threadWatcher.StopReason != StopReason.PageNotFound && threadWatcher.StopReason != StopReason.UserRequest) threadWatcher.Start(); } } _isLoadingThreadsFromFile = false; } catch (Exception ex) { _isLoadingThreadsFromFile = false; Logger.Log(ex.ToString()); } }
private bool AddThread(string pageURL) { ThreadInfo thread = new ThreadInfo { URL = pageURL, PageAuth = (chkPageAuth.Checked && (txtPageAuth.Text.IndexOf(':') != -1)) ? txtPageAuth.Text : String.Empty, ImageAuth = (chkImageAuth.Checked && (txtImageAuth.Text.IndexOf(':') != -1)) ? txtImageAuth.Text : String.Empty, CheckIntervalSeconds = pnlCheckEvery.Enabled ? (cboCheckEvery.Enabled ? (int)cboCheckEvery.SelectedValue * 60 : Int32.Parse(txtCheckEvery.Text) * 60) : 0, OneTimeDownload = chkOneTime.Checked, SaveDir = null, Description = String.Empty, StopReason = null, ExtraData = null, Category = cboCategory.Text, AutoFollow = chkAutoFollow.Checked }; return AddThread(thread); }
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._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))); 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); }
private static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) { Hashtable hashtable = new Hashtable(); ArrayList list = new ArrayList(); GCHandle handle = new GCHandle(); try { handle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr ptr = handle.AddrOfPinnedObject(); Microsoft.Win32.NativeMethods.PERF_DATA_BLOCK structure = new Microsoft.Win32.NativeMethods.PERF_DATA_BLOCK(); Marshal.PtrToStructure(ptr, structure); IntPtr ptr2 = (IntPtr)(((long)ptr) + structure.HeaderLength); Microsoft.Win32.NativeMethods.PERF_INSTANCE_DEFINITION perf_instance_definition = new Microsoft.Win32.NativeMethods.PERF_INSTANCE_DEFINITION(); Microsoft.Win32.NativeMethods.PERF_COUNTER_BLOCK perf_counter_block = new Microsoft.Win32.NativeMethods.PERF_COUNTER_BLOCK(); for (int j = 0; j < structure.NumObjectTypes; j++) { Microsoft.Win32.NativeMethods.PERF_OBJECT_TYPE perf_object_type = new Microsoft.Win32.NativeMethods.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(ptr2, perf_object_type); IntPtr ptr3 = (IntPtr)(((long)ptr2) + perf_object_type.DefinitionLength); IntPtr ptr4 = (IntPtr)(((long)ptr2) + perf_object_type.HeaderLength); ArrayList list2 = new ArrayList(); for (int k = 0; k < perf_object_type.NumCounters; k++) { Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION perf_counter_definition = new Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(ptr4, perf_counter_definition); string counterName = library.GetCounterName(perf_counter_definition.CounterNameTitleIndex); if (perf_object_type.ObjectNameTitleIndex == processIndex) { perf_counter_definition.CounterNameTitlePtr = (int)GetValueId(counterName); } else if (perf_object_type.ObjectNameTitleIndex == threadIndex) { perf_counter_definition.CounterNameTitlePtr = (int)GetValueId(counterName); } list2.Add(perf_counter_definition); ptr4 = (IntPtr)(((long)ptr4) + perf_counter_definition.ByteLength); } Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION[] perf_counter_definitionArray = new Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION[list2.Count]; list2.CopyTo(perf_counter_definitionArray, 0); for (int m = 0; m < perf_object_type.NumInstances; m++) { Marshal.PtrToStructure(ptr3, perf_instance_definition); IntPtr ptr5 = (IntPtr)(((long)ptr3) + perf_instance_definition.NameOffset); string strA = Marshal.PtrToStringUni(ptr5); if (!strA.Equals("_Total")) { IntPtr ptr6 = (IntPtr)(((long)ptr3) + perf_instance_definition.ByteLength); Marshal.PtrToStructure(ptr6, perf_counter_block); if (perf_object_type.ObjectNameTitleIndex == processIndex) { ProcessInfo info = GetProcessInfo(perf_object_type, (IntPtr)(((long)ptr3) + perf_instance_definition.ByteLength), perf_counter_definitionArray); if (((info.processId != 0) || (string.Compare(strA, "Idle", StringComparison.OrdinalIgnoreCase) == 0)) && (hashtable[info.processId] == null)) { string str3 = strA; if (str3.Length == 15) { if (strA.EndsWith(".", StringComparison.Ordinal)) { str3 = strA.Substring(0, 14); } else if (strA.EndsWith(".e", StringComparison.Ordinal)) { str3 = strA.Substring(0, 13); } else if (strA.EndsWith(".ex", StringComparison.Ordinal)) { str3 = strA.Substring(0, 12); } } info.processName = str3; hashtable.Add(info.processId, info); } } else if (perf_object_type.ObjectNameTitleIndex == threadIndex) { ThreadInfo info2 = GetThreadInfo(perf_object_type, (IntPtr)(((long)ptr3) + perf_instance_definition.ByteLength), perf_counter_definitionArray); if (info2.threadId != 0) { list.Add(info2); } } ptr3 = (IntPtr)((((long)ptr3) + perf_instance_definition.ByteLength) + perf_counter_block.ByteLength); } } ptr2 = (IntPtr)(((long)ptr2) + perf_object_type.TotalByteLength); } } finally { if (handle.IsAllocated) { handle.Free(); } } 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); } } ProcessInfo[] array = new ProcessInfo[hashtable.Values.Count]; hashtable.Values.CopyTo(array, 0); return(array); }
/// <summary> /// /// </summary> ThreadInfo CreateThread() { if ((GeneralHelper.ApplicationStopwatchMilliseconds - _lastThreadCreatedMillisecond) < _minimumThreadCreationIntervalMilliseconds) {// Minimum inter thread creation time not met. return null; } if (IsRunning == false || _threadsHotSwap.Count >= MaximumThreadsCount) { return null; } _lastThreadCreatedMillisecond = GeneralHelper.ApplicationStopwatchMilliseconds; Thread newThread = new Thread(new ParameterizedThreadStart(ThreadExecute)); newThread.SetApartmentState(_threadsApartmentState); newThread.Name = this._name + ".WorkerThread"; ThreadInfo threadInfo; lock (this) { Dictionary<int, ThreadInfo> newThreads = new Dictionary<int, ThreadInfo>(_threadsHotSwap); threadInfo = new ThreadInfo() { Thread = newThread, ThreadId = newThread.ManagedThreadId }; newThreads.Add(newThread.ManagedThreadId, threadInfo); // Hot Swap. _threadsHotSwap = newThreads; } Interlocked.Increment(ref _totalThreadsStarted); //newThread.Name = DefaultThreadName; newThread.Start(threadInfo); return threadInfo; }
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); }
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); }
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); }
private static extern int JpfsvGetNextThread( IntPtr EnumHandle, ref ThreadInfo Info );
public static extern int EnumWindows(CallBackPtr callPtr, ref ThreadInfo threadInfo);
/// <devdoc> /// Internal constructor. /// </devdoc> /// <internalonly/> internal ProcessThread(bool isRemoteMachine, ThreadInfo threadInfo) { _isRemoteMachine = isRemoteMachine; _threadInfo = threadInfo; }
private void SendRelationshipsInfo(IEnumerable<EmailThreadingEntity> rawDocumentRelationships) { // For eDocs we ALWAYS send relationships info //if (!m_Parameters.IsImportFamilyRelations) //{ // return; //} FamiliesInfo familiesInfo = new FamiliesInfo(); ThreadsInfo threadsInfo = new ThreadsInfo(); foreach (EmailThreadingEntity emailThreadingEntity in rawDocumentRelationships) { string docReferenceId = emailThreadingEntity.ChildDocumentID; if (String.IsNullOrEmpty(docReferenceId)) { continue; } if (emailThreadingEntity.RelationshipType == ThreadRelationshipEntity.RelationshipType.OutlookEmailThread) { // Sanitize the value emailThreadingEntity.ConversationIndex = String.IsNullOrEmpty(emailThreadingEntity.ConversationIndex) ? null : emailThreadingEntity.ConversationIndex; // On Append we only calculate relationships between new documents, // therefore we don't even send standalone documents to threads linker if (emailThreadingEntity.ConversationIndex == null) { continue; } var threadInfo = new ThreadInfo(docReferenceId, emailThreadingEntity.ConversationIndex); threadsInfo.ThreadInfoList.Add(threadInfo); } else { // We don't skip standalone documents for Families, because they always can appear to be topmost parents FamilyInfo familyInfoRecord = new FamilyInfo(docReferenceId); familyInfoRecord.OriginalDocumentId = docReferenceId; familyInfoRecord.OriginalParentId = String.IsNullOrEmpty(emailThreadingEntity.ParentDocumentID) ? null : emailThreadingEntity.ParentDocumentID; //Tracer.Warning("SendRelationshipsInfo: OriginalDocumentId = {0}, OriginalParentId = {1}", // familyInfoRecord.OriginalDocumentId, familyInfoRecord.OriginalParentId); if (String.Equals(familyInfoRecord.OriginalDocumentId, familyInfoRecord.OriginalParentId, StringComparison.InvariantCulture)) { //Tracer.Warning("SendRelationshipsInfo: OriginalDocumentId = {0}, OriginalParentId reset to null", familyInfoRecord.OriginalDocumentId); familyInfoRecord.OriginalParentId = null; // Document must not be its own parent } familiesInfo.FamilyInfoList.Add(familyInfoRecord); } const int BatchSize = 500; if (threadsInfo.ThreadInfoList.Count >= BatchSize) { SendThreads(threadsInfo); threadsInfo.ThreadInfoList.Clear(); } if (familiesInfo.FamilyInfoList.Count >= BatchSize) { SendFamilies(familiesInfo); familiesInfo.FamilyInfoList.Clear(); } } if (threadsInfo.ThreadInfoList.Any()) { SendThreads(threadsInfo); } if (familiesInfo.FamilyInfoList.Any()) { SendFamilies(familiesInfo); } }
private void ThreadWatcher_AddThread(ThreadWatcher watcher, AddThreadEventArgs args) { BeginInvoke(() => { ThreadInfo thread = new ThreadInfo { URL = args.PageURL, PageAuth = watcher.PageAuth, ImageAuth = watcher.ImageAuth, CheckIntervalSeconds = watcher.CheckIntervalSeconds, OneTimeDownload = watcher.OneTimeDownload, SaveDir = null, Description = String.Empty, StopReason = null, ExtraData = new WatcherExtraData { AddedOn = DateTime.Now, AddedFrom = watcher.PageID }, Category = watcher.Category, AutoFollow = Settings.RecursiveAutoFollow != false }; SiteHelper siteHelper = SiteHelper.GetInstance((new Uri(thread.URL)).Host); siteHelper.SetURL(thread.URL); if (_watchers.ContainsKey(siteHelper.GetPageID())) return; if (AddThread(thread)) { _saveThreadList = true; } }); }
static ThreadInfo GetThreadInfo(NativeMethods.PERF_OBJECT_TYPE type, IntPtr instancePtr, NativeMethods.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); 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: threadInfo.processId = (int)value; break; case ValueId.ThreadId: threadInfo.threadId = (int)value; break; case ValueId.BasePriority: threadInfo.basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo.currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo.startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo.threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo.threadWaitReason = GetThreadWaitReason((int)value); break; } } return threadInfo; }
private bool AddThread(ThreadInfo thread) { ThreadWatcher watcher = null; ThreadWatcher parentThread = null; ListViewItem newListViewItem = null; SiteHelper siteHelper = SiteHelper.GetInstance((new Uri(thread.URL)).Host); siteHelper.SetURL(thread.URL); string pageID = siteHelper.GetPageID(); if (IsBlacklisted(pageID)) return false; if (_watchers.ContainsKey(pageID)) { watcher = _watchers[pageID]; if (watcher.IsRunning) return false; } if (watcher == null) { watcher = new ThreadWatcher(thread.URL); watcher.ThreadDownloadDirectory = thread.SaveDir; watcher.Description = thread.Description; if (_isLoadingThreadsFromFile) watcher.DoNotRename = true; watcher.Category = thread.Category; watcher.DoNotRename = false; if (thread.ExtraData != null && !String.IsNullOrEmpty(thread.ExtraData.AddedFrom)) { _watchers.TryGetValue(thread.ExtraData.AddedFrom, out parentThread); watcher.ParentThread = parentThread; } watcher.DownloadStatus += ThreadWatcher_DownloadStatus; watcher.WaitStatus += ThreadWatcher_WaitStatus; watcher.StopStatus += ThreadWatcher_StopStatus; watcher.ReparseStatus += ThreadWatcher_ReparseStatus; watcher.ThreadDownloadDirectoryRename += ThreadWatcher_ThreadDownloadDirectoryRename; watcher.DownloadStart += ThreadWatcher_DownloadStart; watcher.DownloadProgress += ThreadWatcher_DownloadProgress; watcher.DownloadEnd += ThreadWatcher_DownloadEnd; watcher.AddThread += ThreadWatcher_AddThread; newListViewItem = new ListViewItem(String.Empty); for (int i = 1; i < lvThreads.Columns.Count; i++) { newListViewItem.SubItems.Add(String.Empty); } newListViewItem.Tag = watcher; lvThreads.Items.Add(newListViewItem); lvThreads.Sort(); UpdateCategories(watcher.Category); } watcher.PageAuth = thread.PageAuth; watcher.ImageAuth = thread.ImageAuth; watcher.CheckIntervalSeconds = thread.CheckIntervalSeconds; watcher.OneTimeDownload = thread.OneTimeDownload; watcher.AutoFollow = thread.AutoFollow; if (thread.ExtraData == null) { thread.ExtraData = watcher.Tag as WatcherExtraData ?? new WatcherExtraData { AddedOn = DateTime.Now }; } if (newListViewItem != null) { thread.ExtraData.ListViewItem = newListViewItem; } watcher.Tag = thread.ExtraData; if (parentThread != null) parentThread.ChildThreads.Add(watcher.PageID, watcher); if (!_watchers.ContainsKey(watcher.PageID)) { _watchers.Add(watcher.PageID, watcher); } else { _watchers[watcher.PageID] = watcher; } DisplayData(watcher); if (thread.StopReason == null && !_isLoadingThreadsFromFile) { watcher.Start(); } else if (thread.StopReason != null) { watcher.Stop(thread.StopReason.Value); } return true; }
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); }
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 unsafe ProcessInfo[] GetProcessInfos(IntPtr dataPtr) { // 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); // 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; 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++; }
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; }
/// <devdoc> /// Internal constructor. /// </devdoc> /// <internalonly/> internal ProcessThread(bool isRemoteMachine, int processId, ThreadInfo threadInfo) { _isRemoteMachine = isRemoteMachine; _processId = processId; _threadInfo = threadInfo; }
// // CONSTRUCTORS // /// <include file='doc\ProcessThread.uex' path='docs/doc[@for="ProcessThread.ProcessThread"]/*' /> /// <devdoc> /// Internal constructor. /// </devdoc> /// <internalonly/> internal ProcessThread(bool isRemoteMachine, ThreadInfo threadInfo) { this.isRemoteMachine = isRemoteMachine; this.threadInfo = threadInfo; }
private static ThreadInfo GetThreadInfo(Microsoft.Win32.NativeMethods.PERF_OBJECT_TYPE type, IntPtr instancePtr, Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo info = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION perf_counter_definition = counters[i]; long num2 = ReadCounterValue(perf_counter_definition.CounterType, (IntPtr) (((long) instancePtr) + perf_counter_definition.CounterOffset)); switch (perf_counter_definition.CounterNameTitlePtr) { case 11: info.threadId = (int) num2; break; case 12: info.processId = (int) num2; break; case 13: info.basePriority = (int) num2; break; case 14: info.currentPriority = (int) num2; break; case 0x11: info.startAddress = (IntPtr) num2; break; case 0x12: info.threadState = (System.Diagnostics.ThreadState) ((int) num2); break; case 0x13: info.threadWaitReason = GetThreadWaitReason((int) num2); break; } } return info; }
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; }
static void Register(ThreadInfo ti) { using (_lock.EnterWriteLock ()) { _threads[ti.ID] = ti; } }
internal ProcessThread(bool isRemoteMachine, ThreadInfo threadInfo) { this.isRemoteMachine = isRemoteMachine; this.threadInfo = threadInfo; GC.SuppressFinalize(this); }
static void Unregister(ThreadInfo ti) { using (_lock.EnterWriteLock ()) { _threads.Remove (ti.ID); } }
public static void Restore(ThreadInfo ti) { if (ti == null) throw new ArgumentNullException("ti"); // Restore call context. // if (miSetLogicalCallContext != null) { miSetLogicalCallContext.Invoke(Thread.CurrentThread, new object[] { ti.callContext }); } // Restore HttpContext with the moral equivalent of // HttpContext.Current = ti.httpContext; // CallContext.SetData(HttpContextSlotName, ti.httpContext); // Restore thread identity. It's important that this be done after // restoring call context above, since restoring call context also // overwrites the current thread principal setting. If propogateCallContext // and propogateThreadPrincipal are both true, then the following is redundant. // However, since propogating call context requires the use of reflection // to capture/restore call context, I want that behavior to be independantly // switchable so that it can be disabled; while still allowing thread principal // to be propogated. This also covers us in the event that call context // propogation changes so that it no longer propogates thread principal. // Thread.CurrentPrincipal = ti.principal; if (ti.compressedStack != null) { // TODO: Uncomment the following when Thread.SetCompressedStack is no longer guarded // by a StrongNameIdentityPermission. // // Thread.CurrentThread.SetCompressedStack(ti.compressedStack); } }
//TODO: Needs to be renamed public ThreadInfo threadInfo(int pid) { ThreadInfo threadInfo = new ThreadInfo(); //Put the spotify process ID into the threadInfo so Report method can use it. threadInfo.spID = SpotifyHandle; EnumWindows(new CallBackPtr(processCheck), ref threadInfo); //Process have been checked. if (threadInfo.hWnd == IntPtr.Zero) { //Couldn't find a thread with the correct title return null; } //We found it, pass through our dataobject return threadInfo; }