Guest User

Untitled

a guest
Dec 3rd, 2022
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.08 KB | None | 0 0
  1. <#
  2. Copyright (c) 2022 Steffen Illhardt
  3. https://github.com/german-one/termproc
  4.  
  5. Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. this software and associated documentation files (the "Software"), to deal in
  7. the Software without restriction, including without limitation the rights to
  8. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  9. the Software, and to permit persons to whom the Software is furnished to do so,
  10. subject to the following conditions:
  11.  
  12. The above copyright notice and this permission notice shall be included in all
  13. copies or substantial portions of the Software.
  14.  
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  17. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  18. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  19. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #>
  22.  
  23. # min. req.: PowerShell v.2
  24.  
  25. Add-Type @'
  26. using System;
  27. using System.Diagnostics;
  28. using System.Runtime.ConstrainedExecution;
  29. using System.Runtime.InteropServices;
  30.  
  31. //# provides the TermProc property referencing the process of the terminal connected to the current console application
  32. public static class WinTerm {
  33. //# imports the used Windows API functions
  34. private static class NativeMethods {
  35. [DllImport("kernel32.dll")]
  36. internal static extern int CloseHandle(IntPtr Hndl);
  37. [DllImport("kernelbase.dll")]
  38. internal static extern int CompareObjectHandles(IntPtr hFirst, IntPtr hSecond);
  39. [DllImport("kernel32.dll")]
  40. internal static extern int DuplicateHandle(IntPtr SrcProcHndl, IntPtr SrcHndl, IntPtr TrgtProcHndl, out IntPtr TrgtHndl, int Acc, int Inherit, int Opts);
  41. [DllImport("kernel32.dll")]
  42. internal static extern IntPtr GetConsoleWindow();
  43. [DllImport("kernel32.dll")]
  44. internal static extern IntPtr GetCurrentProcess();
  45. [DllImport("user32.dll")]
  46. internal static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint procId);
  47. [DllImport("ntdll.dll")]
  48. internal static extern int NtQuerySystemInformation(int SysInfClass, IntPtr SysInf, int SysInfLen, out int RetLen);
  49. [DllImport("kernel32.dll")]
  50. internal static extern IntPtr OpenProcess(int Acc, int Inherit, uint ProcId);
  51. [DllImport("user32.dll")]
  52. internal static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
  53. }
  54.  
  55. private class SafeRes : CriticalFinalizerObject, IDisposable {
  56. //# resource type of a SafeRes object
  57. internal enum ResType { MemoryPointer, Handle }
  58.  
  59. private IntPtr raw = IntPtr.Zero;
  60. private readonly ResType resourceType = ResType.MemoryPointer;
  61.  
  62. internal IntPtr Raw { get { return raw; } }
  63. internal bool IsInvalid { get { return raw == IntPtr.Zero || raw == new IntPtr(-1); } }
  64.  
  65. internal SafeRes(IntPtr raw, ResType resourceType) {
  66. this.raw = raw;
  67. this.resourceType = resourceType;
  68. }
  69.  
  70. ~SafeRes() { Dispose(false); }
  71.  
  72. public void Dispose() {
  73. Dispose(true);
  74. GC.SuppressFinalize(this);
  75. }
  76.  
  77. protected virtual void Dispose(bool disposing) {
  78. if (IsInvalid) { return; }
  79. if (resourceType == ResType.MemoryPointer) {
  80. Marshal.FreeHGlobal(raw);
  81. raw = IntPtr.Zero;
  82. return;
  83. }
  84.  
  85. if (NativeMethods.CloseHandle(raw) != 0) { raw = new IntPtr(-1); }
  86. }
  87. }
  88.  
  89. //# undocumented SYSTEM_HANDLE structure, SYSTEM_HANDLE_TABLE_ENTRY_INFO might be the actual name
  90. [StructLayout(LayoutKind.Sequential)]
  91. private struct SystemHandle {
  92. internal readonly uint ProcId; //# PID of the process the SYSTEM_HANDLE belongs to
  93. internal readonly byte ObjTypeNum;
  94. internal readonly byte Flgs;
  95. internal readonly ushort Handle; //# value representing an opened handle in the process
  96. internal readonly IntPtr pObj;
  97. internal readonly uint Acc;
  98. }
  99.  
  100. private static uint FindWTCallback(uint shellPid, uint termPid) {
  101. const int PROCESS_DUP_HANDLE = 0x0040, //# access right to duplicate handles
  102. PROCESS_QUERY_LIMITED_INFORMATION = 0x1000, //# access right to retrieve certain process information
  103. STATUS_INFO_LENGTH_MISMATCH = -1073741820, //# NTSTATUS returned if we still didn't allocate enough memory
  104. SystemHandleInformation = 16; //# one of the SYSTEM_INFORMATION_CLASS values
  105. int status, //# retrieves the NTSTATUS return value
  106. infSize = 0x10000; //# initially allocated memory size for the SYSTEM_HANDLE_INFORMATION object
  107. //# open a handle to the WindowsTerminal process, granting permissions to duplicate handles
  108. using (SafeRes sHTerm = new SafeRes(NativeMethods.OpenProcess(PROCESS_DUP_HANDLE, 0, termPid), SafeRes.ResType.Handle)) {
  109. if (sHTerm.IsInvalid) { return 0; }
  110. //# open a handle to the Shell process
  111. using (SafeRes sHShell = new SafeRes(NativeMethods.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, shellPid), SafeRes.ResType.Handle)) {
  112. if (sHShell.IsInvalid) { return 0; }
  113. //# allocate some memory representing an undocumented SYSTEM_HANDLE_INFORMATION object, which can't be meaningfully declared in C# code
  114. IntPtr pSysHndlInf = Marshal.AllocHGlobal(infSize);
  115. //# try to get an array of all available SYSTEM_HANDLE objects, allocate more memory if necessary
  116. int len;
  117. while ((status = NativeMethods.NtQuerySystemInformation(SystemHandleInformation, pSysHndlInf, infSize, out len)) == STATUS_INFO_LENGTH_MISMATCH) {
  118. Marshal.FreeHGlobal(pSysHndlInf);
  119. pSysHndlInf = Marshal.AllocHGlobal(infSize = len);
  120. }
  121.  
  122. using (SafeRes sPSysHndlInf = new SafeRes(pSysHndlInf, SafeRes.ResType.MemoryPointer)) {
  123. if (status < 0) { return 0; }
  124. uint pid = 0;
  125. IntPtr hCur = NativeMethods.GetCurrentProcess();
  126. int sysHndlSize = Marshal.SizeOf(typeof(SystemHandle));
  127. //# iterate over the array of SYSTEM_HANDLE objects, which begins at an offset of pointer size in the SYSTEM_HANDLE_INFORMATION object
  128. //# the number of SYSTEM_HANDLE objects is specified in the first 32 bits of the SYSTEM_HANDLE_INFORMATION object
  129. for (IntPtr pSysHndl = (IntPtr)((long)sPSysHndlInf.Raw + IntPtr.Size), pEnd = (IntPtr)((long)pSysHndl + Marshal.ReadInt32(sPSysHndlInf.Raw) * sysHndlSize);
  130. pSysHndl != pEnd;
  131. pSysHndl = (IntPtr)((long)pSysHndl + sysHndlSize)) {
  132. //# get one SYSTEM_HANDLE at a time
  133. SystemHandle sysHndl = (SystemHandle)Marshal.PtrToStructure(pSysHndl, typeof(SystemHandle));
  134. IntPtr hDup;
  135. if (sysHndl.ProcId != termPid ||
  136. NativeMethods.DuplicateHandle(sHTerm.Raw, (IntPtr)sysHndl.Handle, hCur, out hDup, PROCESS_QUERY_LIMITED_INFORMATION, 0, 0) == 0) {
  137. continue;
  138. }
  139.  
  140. //# at this point duplicating succeeded and thus, sHDup is valid
  141. using (SafeRes sHDup = new SafeRes(hDup, SafeRes.ResType.Handle)) {
  142. //# compare the duplicated handle with the handle of our shell process
  143. //# if they point to the same kernel object, we are going to step out of the loop and return the PID of the WindowsTerminal process
  144. if (NativeMethods.CompareObjectHandles(sHDup.Raw, sHShell.Raw) != 0) {
  145. pid = termPid;
  146. break;
  147. }
  148. }
  149. }
  150.  
  151. return pid;
  152. }
  153. }
  154. }
  155. }
  156.  
  157. private static readonly IntPtr conWnd = NativeMethods.GetConsoleWindow();
  158. private static Process GetTermProc() {
  159. const int WM_GETICON = 0x007F;
  160.  
  161. //# Get the ID of the Shell process that spawned the Conhost process.
  162. uint shellPid;
  163. if (NativeMethods.GetWindowThreadProcessId(conWnd, out shellPid) == 0) { return null; }
  164. if (NativeMethods.SendMessageW(conWnd, WM_GETICON, IntPtr.Zero, IntPtr.Zero) != IntPtr.Zero) {
  165. //# Conhost assumed: The Shell process' main window is the console window.
  166. //# (weird because the Shell has no own window, but it has always been like this)
  167. return Process.GetProcessById((int)shellPid);
  168. }
  169.  
  170. foreach (Process termProc in Process.GetProcessesByName("WindowsTerminal")) {
  171. uint termPid = FindWTCallback(shellPid, (uint)termProc.Id);
  172. if (termPid != 0) { return termProc; }
  173. }
  174.  
  175. return null;
  176. }
  177.  
  178. private static readonly Process termProc = GetTermProc();
  179. public static Process TermProc { get { return termProc; } }
  180. }
  181. '@
  182.  
  183. $Proc = [WinTerm]::TermProc
  184. if ($Proc -and ($Proc.ProcessName -eq 'WindowsTerminal')) {
  185. "Id:$($Proc.Id)"
  186. "ProcessName:$($Proc.ProcessName)"
  187. "MainWindowHandle:$($Proc.MainWindowHandle)"
  188. }
Add Comment
Please, Sign In to add comment