tools: trace private desktop thread owners using documented Win32 APIs
This commit is contained in:
1 parent
e4ef6a533e
commit
e15ee259f8
3 files changed
+298
No files matched your search
@@ -0,0 +1,67 @@
|
||||
# Windows 桌面生命周期:工单 #1 的继续排查
|
||||
|
||||
2026-10-21。此次没有修改生产替换流程、保护锁或发布包。
|
||||
|
||||
## 工单能证明什么
|
||||
|
||||
工单四次整批 BOM 导入的直接中断原因是 `inventory_cleanup`:受控 CAD、已知子进程退出,自有句柄关闭,但五秒后仍枚举到该私有桌面。它不能证明 Windows 因工程数量多而拒绝导入,也没有足够信息证明残留持有者是谁。BOM 行匹配失败是另外一类结果,详见 [首轮诊断](2026-10-21-issue-1-bom-import.md)。
|
||||
|
||||
## 对照微软官方文档
|
||||
|
||||
1. [CloseDesktop](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-closedesktop) 关闭一个打开的桌面句柄。成功不等于所有引用消失。调用进程的线程正在使用这个句柄,或它是初始桌面句柄时,关闭会失败。
|
||||
2. [GetThreadDesktop](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getthreaddesktop) 返回指定线程关联的桌面句柄;文档明确不要对该返回值调用 `CloseDesktop`。它与应用通过 `OpenDesktop` 自己打开的句柄归属不同。
|
||||
3. [Thread Connection to a Desktop](https://learn.microsoft.com/en-us/windows/win32/winstation/thread-connection-to-a-desktop) 说明线程的桌面连接、`STARTUPINFO.lpDesktop` 和继承句柄的关系。线程连接不要求存在可见窗口;不能仅凭窗口列表为空判断没有持有者。
|
||||
4. [Terminating a Process](https://learn.microsoft.com/en-us/windows/win32/procthread/terminating-a-process) 明确进程终止不会自动终止其创建的全部子进程。[TerminateProcess](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminateprocess) 是异步请求,必须等待退出。现有实现已有 Job、等待与句柄关闭逻辑;本轮未直接把它认定为错误或移除检查。
|
||||
5. [Traversing the Thread List](https://learn.microsoft.com/en-us/windows/win32/toolhelp/traversing-the-thread-list) 给出 Toolhelp 线程快照遍历方法。[CreateToolhelp32Snapshot](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot) 要求关闭快照句柄。
|
||||
6. [CreateDesktop](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createdesktopw) 说明桌面堆限制。工单已有日志没有桌面创建失败或内存不足的证据,因此本轮没有改注册表的 `SharedSection`、全局资源配额或超时常量。
|
||||
|
||||
这些接口没有提供“按桌面名称强制删除全部引用”的安全操作。不能把关闭自己的句柄解释成强行删除其他进程持有的桌面。
|
||||
|
||||
## 原生受控实验
|
||||
|
||||
实验仅使用临时 Python 进程和 `dx-doc-*` 桌面,不打开真实工程。
|
||||
|
||||
| 实验 | 结果 |
|
||||
| --- | --- |
|
||||
| 无额外引用,GUI 进程正常退出 | 进程清理后桌面立即消失 |
|
||||
| 额外持有已退出进程的内核句柄 | 桌面正常释放,不能将进程句柄残留直接当作本案根因 |
|
||||
| 额外持有已退出线程的内核句柄 | 桌面正常释放 |
|
||||
| 子进程线程仍连接私有桌面,但不创建窗口 | 复现相同保护现象;窗口清单为空,线程扫描能找到实际 PID/TID/程序路径 |
|
||||
| 该外部线程的进程退出后 | 再次核验桌面正常释放 |
|
||||
| 对当前线程正在使用的桌面调用 CloseDesktop | 真实返回 WinError 170;恢复原线程桌面后重试成功,pywin32 没有吞掉失败或丢失重试句柄 |
|
||||
|
||||
实际受控残留实验还发现该会话的 `conhost.exe` 线程。此结果只证明诊断能看到无窗口持有者,不能证明用户现场也是 `conhost.exe` 导致。
|
||||
|
||||
实验记录在 `build/desktop-doc-research-20261021`:`retained-kernel-handles.json`、`close-api-contract.txt`、`retained-thread-session.json`、`retained-thread-diagnostic.json`、`released-after-owner-exit.json`。原始机器日志未修改。
|
||||
|
||||
## 新增只读诊断工具
|
||||
|
||||
源码工具:[diagnose_private_desktop.py](../../tools/diagnose_private_desktop.py)。需要在**发生问题的机器、桌面仍残留时**运行,事后复制到另一台电脑的旧日志不能还原已消失的 Windows 资源。
|
||||
|
||||
在仓库根目录使用已安装项目依赖的 Python:
|
||||
|
||||
```powershell
|
||||
python tools/diagnose_private_desktop.py --record '实际失败会话/private-desktop.json' --output 'build/desktop-diagnostic.json'
|
||||
```
|
||||
|
||||
也可以根据日志中的真实名称传入 `--desktop dx-实际标识`。同路径或硬链接形式的输出覆盖输入记录均被拒绝。
|
||||
|
||||
工具输出桌面是否仍被枚举、残留窗口、连接该桌面的线程 PID/TID/可执行程序路径,以及无法查询的线程错误统计。目标桌面查询句柄只在短生命周期子进程中打开;扫描子进程退出后再检查桌面存在性。借用的 `GetThreadDesktop` 句柄不关闭,自有进程查询句柄和快照关闭。不调用 `SetThreadDesktop`、`SwitchDesktop`、`TerminateProcess`,不关闭外部句柄。
|
||||
|
||||
实测 Windows 对另一进程的 `GetThreadDesktop` 查询,在仅打开 `DESKTOP_READOBJECTS`、`READOBJECTS|ENUMERATE`、`READOBJECTS|WRITEOBJECTS` 时仍返回访问拒绝,而打开拥有者 `GENERIC_ALL` 句柄后可以查询。因此仅在扫描子进程中请求该权限,仍只执行查询;权限不足会报错,不能当作“没有持有者”。
|
||||
|
||||
**工具的边界:**进程若只保留一个 `OpenDesktop` 句柄,却没有线程连接或窗口,线程/窗口扫描可能找不到它。空扫描不是释放证明;`desktop_still_listed` 仍独立报告。
|
||||
|
||||
这种情况下可使用微软官方 [Sysinternals Handle](https://learn.microsoft.com/en-us/sysinternals/downloads/handle),按其文档在管理员终端查询所有类型的句柄:
|
||||
|
||||
```powershell
|
||||
handle64.exe -a 'dx-实际标识'
|
||||
```
|
||||
|
||||
这里只查询,不使用 `-c` 关闭外部句柄。该工具由现场人员按微软文档运行,本轮未下载执行、接受许可或更改系统配置。拿到真实持有 PID 后,才能区分自有程序的生命周期问题、外部进程引用和资源释放延迟,并针对已确认的所有者修复。
|
||||
|
||||
## 验证与当前结论
|
||||
|
||||
原生测试验证了无窗口线程识别、外部进程不受影响、输入桌面不切换、输入记录不修改、诊断不遗留句柄,以及无匹配线程时仍报告桌面存在。四项工具测试通过;已有 Windows 桌面测试另行通过。
|
||||
|
||||
用户现场的持有者尚未查实,不能宣称私有桌面残留已经修好。此次交付是微软文档核对、排除实验和能在现场定位到进程/线程的独立诊断工具;没有删除保护锁、强杀不明进程或放宽准确性校验。
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Desktop diagnosis must find threads without windows and leave their owner alone."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop, _Win32Api, build_startup_info
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows desktop diagnosis')
|
||||
def test_diagnostic_finds_windowless_desktop_thread_without_changing_owner(tmp_path):
|
||||
from dx_productivity.trial_task_center.cad_identity import current_desktop_name
|
||||
before = current_desktop_name()
|
||||
desktop = PrivateDesktop('dx-diagnostic-' + uuid4().hex, enabled=True)
|
||||
desktop.__enter__()
|
||||
# Explicitly connect a thread without creating any windows.
|
||||
child = _Win32Api().create_process((sys.executable, '-u', '-c',
|
||||
'import win32service,time,sys; '
|
||||
'd=win32service.OpenDesktop(sys.argv[1],0,False,0x10000000);d.SetThreadDesktop(); '
|
||||
'print("ready",flush=True);time.sleep(30)', desktop.name), build_startup_info(desktop.name).lpDesktop,
|
||||
None, None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
assert child.stdout.readline() == b'ready\r\n'
|
||||
record = tmp_path / 'private-desktop.json'
|
||||
record.write_text(json.dumps({'desktop': desktop.name}))
|
||||
original = record.read_bytes()
|
||||
output = tmp_path / 'diagnostic.json'
|
||||
script = Path(__file__).resolve().parents[2] / 'tools/diagnose_private_desktop.py'
|
||||
result = subprocess.run((sys.executable, str(script), '--record', str(record), '--output', str(output)),
|
||||
capture_output=True, timeout=20)
|
||||
assert result.returncode == 0, result.stderr.decode(errors='replace')
|
||||
report = json.loads(output.read_text(encoding='utf-8'))
|
||||
assert any(row['pid'] == child.pid for row in report['thread_scan']['threads'])
|
||||
assert report['windows'] == [] and report['desktop_still_listed']
|
||||
assert child.poll() is None and current_desktop_name() == before
|
||||
assert record.read_bytes() == original
|
||||
finally:
|
||||
child.close()
|
||||
desktop.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows desktop diagnosis')
|
||||
def test_no_thread_owner_is_not_mistaken_for_released_desktop(tmp_path):
|
||||
with PrivateDesktop('dx-diagnostic-' + uuid4().hex, enabled=True) as desktop:
|
||||
output = tmp_path / 'diagnostic.json'
|
||||
script = Path(__file__).resolve().parents[2] / 'tools/diagnose_private_desktop.py'
|
||||
result = subprocess.run((sys.executable, str(script), '--desktop', desktop.name, '--output', str(output)),
|
||||
capture_output=True, timeout=20)
|
||||
assert result.returncode == 0, result.stderr.decode(errors='replace')
|
||||
report = json.loads(output.read_text(encoding='utf-8'))
|
||||
assert report['thread_scan']['threads'] == []
|
||||
assert report['desktop_still_listed'] and report['windows'] == []
|
||||
# A leaked query handle would make this context's strict close fail.
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows desktop diagnosis')
|
||||
@pytest.mark.parametrize('hardlink', [False, True])
|
||||
def test_output_cannot_overwrite_input_record_even_through_hardlink(tmp_path, hardlink):
|
||||
record = tmp_path / 'private-desktop.json'
|
||||
original = json.dumps({'desktop': 'dx-no-such-' + uuid4().hex}).encode()
|
||||
record.write_bytes(original)
|
||||
output = record
|
||||
if hardlink:
|
||||
output = tmp_path / 'diagnostic.json'
|
||||
os.link(record, output)
|
||||
script = Path(__file__).resolve().parents[2] / 'tools/diagnose_private_desktop.py'
|
||||
result = subprocess.run((sys.executable, str(script), '--record', str(record), '--output', str(output)),
|
||||
capture_output=True, timeout=20)
|
||||
assert result.returncode != 0
|
||||
assert record.read_bytes() == original
|
||||
@@ -0,0 +1,157 @@
|
||||
"""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()
|
||||
Reference in new issue
Block a user