"""Read-only desktop thread diagnosis, with borrowed handles confined to a child. Windows contracts: GetThreadDesktop handles must NOT be closed; Toolhelp snapshots must be closed. A missing thread/window owner does not prove that no other process holds an OpenDesktop handle. See the accompanying research. """ import argparse from collections import Counter import ctypes from ctypes import wintypes import json import os from pathlib import Path import re import subprocess import sys sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src')) def scan_threads(desktop_name): """Run only in the short-lived scan child, never in the application UI.""" import win32service class ThreadEntry(ctypes.Structure): _fields_ = [('dwSize', wintypes.DWORD), ('cntUsage', wintypes.DWORD), ('th32ThreadID', wintypes.DWORD), ('th32OwnerProcessID', wintypes.DWORD), ('tpBasePri', wintypes.LONG), ('tpDeltaPri', wintypes.LONG), ('dwFlags', wintypes.DWORD)] kernel = ctypes.WinDLL('kernel32', use_last_error=True) user = ctypes.WinDLL('user32', use_last_error=True) snapshot = kernel.CreateToolhelp32Snapshot snapshot.argtypes, snapshot.restype = [wintypes.DWORD, wintypes.DWORD], wintypes.HANDLE first, next_thread = kernel.Thread32First, kernel.Thread32Next for function in (first, next_thread): function.argtypes, function.restype = [wintypes.HANDLE, ctypes.POINTER(ThreadEntry)], wintypes.BOOL kernel.CloseHandle.argtypes, kernel.CloseHandle.restype = [wintypes.HANDLE], wintypes.BOOL user.GetThreadDesktop.argtypes, user.GetThreadDesktop.restype = [wintypes.DWORD], wintypes.HANDLE user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)] user.GetUserObjectInformationW.restype = wintypes.BOOL kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] kernel.OpenProcess.restype = wintypes.HANDLE kernel.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)] kernel.QueryFullProcessImageNameW.restype = wintypes.BOOL images = {} def image(pid): if pid not in images: process = kernel.OpenProcess(0x1000, False, pid) # QUERY_LIMITED_INFORMATION if not process: images[pid] = {'image_error': ctypes.get_last_error()} else: try: value, length = ctypes.create_unicode_buffer(32768), wintypes.DWORD(32768) images[pid] = ({'image': value.value} if kernel.QueryFullProcessImageNameW( process, 0, value, ctypes.byref(length)) else {'image_error': ctypes.get_last_error()}) finally: kernel.CloseHandle(process) return images[pid] handle = snapshot(0x4, 0) # TH32CS_SNAPTHREAD, read-only system snapshot if handle == ctypes.c_void_p(-1).value: raise ctypes.WinError(ctypes.get_last_error()) threads, unreadable, total = [], Counter(), 0 target = None try: # On Windows a READOBJECTS-only handle still made GetThreadDesktop # return ACCESS_DENIED for another process on this desktop. Open with # the owner's full access, but perform queries only. Never switch to it. try: target = win32service.OpenDesktop(desktop_name, 0, False, 0x10000000) except Exception as error: code = getattr(error, 'winerror', error.args[0] if error.args else None) if code == 2: return {'threads': [], 'snapshot_threads': 0, 'unreadable_by_winerror': {}, 'target_gone': True} raise entry = ThreadEntry() entry.dwSize = ctypes.sizeof(entry) valid = first(handle, ctypes.byref(entry)) while valid: total += 1 desktop = user.GetThreadDesktop(entry.th32ThreadID) if not desktop: unreadable[str(ctypes.get_last_error())] += 1 else: name, required = ctypes.create_unicode_buffer(256), wintypes.DWORD() if not user.GetUserObjectInformationW(desktop, 2, name, ctypes.sizeof(name), ctypes.byref(required)): unreadable[str(ctypes.get_last_error())] += 1 elif name.value.casefold() == desktop_name.casefold(): pid = entry.th32OwnerProcessID threads.append({'pid': pid, 'thread_id': entry.th32ThreadID, **image(pid)}) # GetThreadDesktop is borrowed. CloseDesktop is forbidden here. valid = next_thread(handle, ctypes.byref(entry)) if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES raise ctypes.WinError(ctypes.get_last_error()) finally: if target is not None: target.CloseDesktop() if not kernel.CloseHandle(handle): raise ctypes.WinError(ctypes.get_last_error()) return {'threads': threads, 'snapshot_threads': total, 'unreadable_by_winerror': dict(unreadable)} def diagnose(desktop_name): from dx_productivity.trial_task_center.isolated_desktop import _Win32Api # The child exits before we recheck desktop lifetime. GetThreadDesktop can # never make the long-lived supervisor responsible for borrowed handles. completed = subprocess.run((sys.executable, str(Path(__file__).resolve()), '--scan-worker', desktop_name), capture_output=True, text=True, encoding='utf-8', timeout=15, creationflags=subprocess.CREATE_NO_WINDOW) completed.check_returncode() report = {'desktop': desktop_name, 'thread_scan': json.loads(completed.stdout)} api = _Win32Api() listed = {name.casefold() for name in api.service.GetProcessWindowStation().EnumDesktops()} report['desktop_still_listed'] = desktop_name.casefold() in listed if report['desktop_still_listed']: try: report['windows'] = api._desktop_windows(desktop_name) except Exception as error: report['window_query_error'] = str(error) else: report['windows'] = [] report['scope'] = 'Thread/window scan only; external handle-only owners may require Microsoft Sysinternals Handle.' return report def main(): parser = argparse.ArgumentParser(description=__doc__) source = parser.add_mutually_exclusive_group(required=True) source.add_argument('--record', type=Path, help='Existing private-desktop.json (read only)') source.add_argument('--desktop', help='Owned dx- desktop name') source.add_argument('--scan-worker', help=argparse.SUPPRESS) parser.add_argument('--output', type=Path) args = parser.parse_args() if os.name != 'nt': parser.error('Windows is required') desktop = args.scan_worker or args.desktop if args.record: desktop = json.loads(args.record.read_text(encoding='utf-8-sig'))['desktop'] if args.output and (args.output.resolve() == args.record.resolve() or args.output.exists() and args.output.samefile(args.record)): parser.error('Diagnostic output must not overwrite its input record') if not isinstance(desktop, str) or not re.fullmatch(r'dx-[A-Za-z0-9-]{1,100}', desktop): parser.error('Only a valid owned dx- desktop name is accepted') report = scan_threads(desktop) if args.scan_worker else diagnose(desktop) text = json.dumps(report, ensure_ascii=True, indent=2) if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(text, encoding='utf-8') print(text) if __name__ == '__main__': main()