fix: address defects found in frozen native acceptance

This commit is contained in:
阿白叔 committed 2026-11-12 11:33:44 +08:00
1 parent b86e4e315a
commit 42d0cebc54
15 files changed
+808 -50

No files matched your search

+6 -5
View File
@@ -41,8 +41,8 @@ def _idle_check(library, project, pcb):
match = _native_scope_match(command, roots=scope, files=(library, project, pcb))
if match is True:
raise ValueError(f'TARGET_NATIVE_OWNER_ACTIVE: 目标工程或共享库有原生会话,PID={pid}')
if match is None:
raise ValueError(f'TARGET_NATIVE_OWNER_UNCONFIRMED: 无法确认原生会话所属工程,PID={pid}')
# Pathless clients do not identify this target. The address and
# exclusive file probes below still reject actual target occupancy.
addresses = unreleased_addresses(library, project, pcb)
if addresses:
raise ValueError(f'TARGET_DATABASE_ADDRESS_UNCONFIRMED: 地址记录需原生确认;未据此判定正在占用:{addresses}')
@@ -110,14 +110,15 @@ def _source_check(source, name, original):
if not pcb.is_relative_to(source.parent.resolve()):
raise ValueError('备份 PCB 引用越出工程目录。')
if not all(path.is_file() for path in (pcb, pcb.parent/'Layout/LayoutDB.lyt',
pcb.parent/'pcb.prj', source.parent/'database/icdb.dat')):
raise ValueError('备份不完整:需要原理图数据库、PCB、布局数据库和 PCB 工程文件。')
source.parent/'database/icdb.dat')):
raise ValueError('备份不完整:需要原理图数据库、PCB 和布局数据库。')
project_refs = re.findall(r'^KEY ProjectFile "([^"]+)"', _project_text(pcb), re.M)
for value in project_refs:
require_relative(value)
if len(project_refs) != 1 or (pcb.parent/project_refs[0]).resolve() != source.resolve():
raise ValueError('备份 PCB 必须引用所选工程,不能引用其他位置的工程。')
for project in (source, pcb.parent/'pcb.prj'):
from .maintenance_entry import maintenance_project_files
for project in maintenance_project_files(source, pcb):
data = _project_text(project)
for value in re.findall(r'^KEY iCDBDir "([^"]+)"', data, re.M):
require_relative(value)
@@ -354,7 +354,11 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
if owner['pid'] not in handles:
try: handles[owner['pid']] = win32api.OpenProcess(win32con.SYNCHRONIZE, False, owner['pid'])
except pywintypes.error as error:
if error.winerror != 87: raise
if error.winerror not in (5, 87): raise
# A dying process can deny OpenProcess. Keep it in
# owners until a fresh snapshot proves it absent.
record.setdefault('process_observation_errors', {})[str(owner['pid'])] = {
'winerror': error.winerror, 'detail': str(error)}
record['observed_pids'] = sorted(descendants | handles.keys())
identities.update({owner['pid']:
{key: owner.get(key, '') for key in ('pid', 'created', 'executable')}
+107 -37
View File
@@ -181,10 +181,81 @@ def _window_error(snapshot, pid):
return getattr(snapshot, 'incomplete', {}).get(pid)
def _desktop_names():
import ctypes
from ctypes import wintypes
user = ctypes.WinDLL('user32', use_last_error=True)
callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.LPWSTR, wintypes.LPARAM)
user.GetProcessWindowStation.restype = wintypes.HANDLE
user.EnumDesktopsW.argtypes = [wintypes.HANDLE, callback_type, wintypes.LPARAM]
names = []
@callback_type
def collect(name, _):
names.append(name)
return len(names) <= 128
ctypes.set_last_error(0)
if not user.EnumDesktopsW(user.GetProcessWindowStation(), collect, 0) or len(names) > 128:
raise OSError('无法完整枚举当前 Windows 窗口站桌面')
return names
@contextmanager
def _window_desktop(name, *, write=False):
"""Keep the desktop accessible while reading or messaging its HWNDs."""
if not name:
yield None
return
import ctypes
from ctypes import wintypes
user = ctypes.WinDLL('user32', use_last_error=True)
user.OpenDesktopW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
user.OpenDesktopW.restype = wintypes.HANDLE
user.CloseDesktop.argtypes = [wintypes.HANDLE]
desktop = user.OpenDesktopW(name, 0, False, 1 | (128 if write else 0))
if not desktop:
raise ctypes.WinError(ctypes.get_last_error())
try:
# OpenDesktop alone does not map a foreign desktop's HWNDs into this
# process. Enumerate while its handle stays open before any ownership
# checks or messages; otherwise GetWindowThreadProcessId returns 0.
_desktop_windows(desktop)
yield desktop
finally:
user.CloseDesktop(desktop)
def _desktop_windows(desktop):
import ctypes
from ctypes import wintypes
user = ctypes.WinDLL('user32', use_last_error=True)
callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
user.EnumDesktopWindows.argtypes = [wintypes.HANDLE, callback_type, wintypes.LPARAM]
windows = []
@callback_type
def collect(hwnd, _):
windows.append(int(hwnd))
return len(windows) <= 4096
ctypes.set_last_error(0)
complete = user.EnumDesktopWindows(desktop, collect, 0)
error = ctypes.get_last_error()
# Windows also returns zero with ERROR_SUCCESS for an empty desktop.
if (not complete and (error or windows)) or len(windows) > 4096:
raise OSError('无法完整读取原生桌面窗口')
return windows
def _post_window_message(window, hwnd, pid, message):
import win32gui, win32process
with _window_desktop(window.get('desktop', ''), write=True):
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid:
raise ValueError('窗口归属已变化,未发送请求')
win32gui.PostMessage(hwnd, message, 0, 0)
def _process_windows(pids):
result = _WindowSnapshot(pids)
if not pids: return result
import win32api, win32con, win32gui, win32process, win32service
import win32api, win32con, win32gui, win32process
from .native_repair_ui import _native_output
observed = set()
def capture(hwnd, _, *, pid, desktop_name):
@@ -218,7 +289,7 @@ def _process_windows(pids):
except Exception as error:
result.incomplete = {pid: str(error)[:500] for pid in pids}
return result
desktops = {}
desktops, unresolved = {}, set()
for pid in pids:
if not threads.get(pid):
result.incomplete[pid] = '进程线程已退出或暂时无法读取'
@@ -228,31 +299,36 @@ def _process_windows(pids):
if desktop:
desktops.setdefault(desktop, set()).add(pid)
except Exception as error:
result.incomplete.setdefault(pid, str(error)[:500])
if not any(pid in members for members in desktops.values()):
unresolved.add(pid)
if pid not in unresolved and not any(pid in members for members in desktops.values()):
result.incomplete.setdefault(pid, '窗口所属桌面暂时无法确认')
# EnumThreadWindows silently omits windows on other desktops. Enumerate
# only desktops actually assigned to the target processes' threads.
for name, members in desktops.items():
desktop = None
if unresolved:
# Native PCB threads can deny GetThreadDesktop even when their named
# desktop is readable. Complete a bounded station scan for those PIDs.
try:
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
win32api.SetLastError(0)
for hwnd in desktop.EnumDesktopWindows():
pid = None
try:
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid in members:
capture(hwnd, None, pid=pid, desktop_name=name)
except Exception as error:
for affected in (members if pid is None else {pid} & members):
result.incomplete.setdefault(affected, str(error)[:500])
names = _desktop_names()
if not names: raise OSError('当前窗口站未返回桌面')
for name in names:
desktops.setdefault(name, set()).update(unresolved)
except Exception as error:
for pid in unresolved:
result.incomplete.setdefault(pid, str(error)[:500])
# Filter by PID before reading window data, including on fallback desktops.
for name, members in desktops.items():
try:
with _window_desktop(name) as desktop:
for hwnd in _desktop_windows(desktop):
pid = None
try:
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid in members:
capture(hwnd, None, pid=pid, desktop_name=name)
except Exception as error:
for affected in (members if pid is None else {pid} & members):
result.incomplete.setdefault(affected, str(error)[:500])
except Exception as error:
for pid in members:
result.incomplete.setdefault(pid, str(error)[:500])
finally:
if desktop is not None:
desktop.CloseDesktop()
return result
@@ -407,7 +483,7 @@ def inspect_residual_sessions(library, *, block_names=()):
def _request_close(row, *, stop=None):
import win32con, win32event, win32gui, win32process
import win32con, win32event
with _process_handle(row['pid']) as handle:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已退出'}
@@ -422,9 +498,10 @@ def _request_close(row, *, stop=None):
from .failed_session import _startup_snapshot, _cancel_target
for window in windows:
if window['class'] != '#32770': continue
target = _cancel_target(_startup_snapshot(window['hwnd'], row['pid']))
with _window_desktop(window.get('desktop', '')):
target = _cancel_target(_startup_snapshot(window['hwnd'], row['pid']))
if target:
win32gui.PostMessage(target[1].handle, win32con.BM_CLICK, 0, 0)
_post_window_message(window, target[1].handle, row['pid'], win32con.BM_CLICK)
deadline = time.monotonic()+3
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
@@ -441,9 +518,7 @@ def _request_close(row, *, stop=None):
if target is None: return {'release_status': 'WAITING', 'detail': detail}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
if win32process.GetWindowThreadProcessId(target['hwnd'])[1] != row['pid']:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '窗口归属已变化,未关闭'}
win32gui.PostMessage(target['hwnd'], win32con.WM_CLOSE, 0, 0)
_post_window_message(target, target['hwnd'], row['pid'], win32con.WM_CLOSE)
deadline = time.monotonic()+3
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
@@ -492,7 +567,7 @@ def _finish_library_release(library, evidence):
def _request_native_cancel(row, *, stop=None):
"""Only click the exact currently visible Cancel control the user confirmed."""
import win32con, win32gui, win32process
import win32con
if row.get('scope_confirmed') is not True:
raise ValueError('取消目标归属未确认,请重新检查')
fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None)
@@ -510,11 +585,9 @@ def _request_native_cancel(row, *, stop=None):
if not prompt or prompt != row.get('cancel_prompt'):
raise ValueError('原生取消按钮已变化,请重新检查')
button = prompt['button']
if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']:
raise ValueError('原生取消按钮归属已变化')
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止,未请求原生取消'}
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
_post_window_message(prompt, button['hwnd'], row['pid'], win32con.BM_CLICK)
return {'release_status': 'WAITING', 'detail': '已请求原生取消,需重新检查实际结果;未强制结束'}
@@ -686,7 +759,7 @@ def answer_save_question(row, choice):
def _answer_save_question(row, choice):
import win32con, win32gui
import win32con
fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None)
if fresh is None or any(fresh.get(k) != row.get(k) for k in ('created', 'command', 'executable')):
raise ValueError('进程已变化,请重新检查')
@@ -698,7 +771,4 @@ def _answer_save_question(row, choice):
if not prompt or prompt != row.get('prompt'):
raise ValueError('原生提示已变化,请重新检查')
button = prompt['buttons'][choice]
import win32process
if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']:
raise ValueError('保存按钮归属已变化')
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
_post_window_message(prompt, button['hwnd'], row['pid'], win32con.BM_CLICK)
+2 -2
View File
@@ -15,14 +15,14 @@ import stat
MANIFEST_VERSION = 1
MANIFEST_RULE_VERSION = 1
MANIFEST_RULE_VERSION = 2
_ROOT_RUNTIME_PREFIX = 'work.before-restore-'
_ROOT_RUNTIME_PATH = ('projectbackup', 'backups')
_NATIVE_RUNTIME_DIRECTORIES = ('log', 'dbcheck', 'dbrestore')
_NATIVE_SERVER_DIRECTORY = 'cdbsvr'
_PROJECT_PCB_DIRECTORY = 'pcb'
_PROJECT_DATABASE_PREFIXES = (('database',), (_PROJECT_PCB_DIRECTORY, 'database'))
_NONPRIMARY_FILENAMES = ('saddress.adr',)
_NONPRIMARY_FILENAMES = ('saddress.adr', 'saddress_.adr')
_NONPRIMARY_FILENAME_PREFIXES = ('~$',)
_NONPRIMARY_DIRECTORIES = frozenset({
'log', 'logs', 'temp', 'tmp', '__pycache__', 'backup', 'backups',
+9 -2
View File
@@ -422,6 +422,12 @@ class MainWindow(QWidget):
waiting_library = self._queued_release_library()
self.queue_release_button.setVisible(waiting_library is not None)
self.queue_release_button.setEnabled(waiting_library is not None and not self._closing)
for task in self.icdb_tasks:
action = getattr(task, 'release_action', None)
if action is not None and isValid(action):
queued_target = bool(waiting_library and _library_path_keys(waiting_library, task.path_lease)
& _library_path_keys(task.requests[0].lmc_file, task.path_lease))
action.setEnabled(not self._closing and (not self.busy or queued_target))
reasons = []
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
reason = self._management_block_reason(operation)
@@ -988,8 +994,9 @@ class MainWindow(QWidget):
& _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)):
self.status_label.setText(f'请切回 {task.requests[0].lmc_file} 后释放该检查的残留。')
return
self.check_library_release()
summary.addButton('查看残留并释放…', QMessageBox.ActionRole).clicked.connect(release_task)
self.check_library_release(queued=self.busy)
task.release_action = summary.addButton('查看残留并释放…', QMessageBox.ActionRole)
task.release_action.clicked.connect(release_task)
if offers:
action = summary.addButton('选择副本恢复…', QMessageBox.ActionRole)
task.recovery_action = action