fix: 修复7个Critical并发安全和异常处理问题
1. OCR 单例无锁保护 - 添加 _ocr_lock 和 _ocr_coords_lock 2. ADB 文本广播命令注入 - 使用 shlex.quote() 转义 3. 截图文件 Race Condition - 添加 PNG 完整性验证 4. JSON 持久化无锁 - 添加文件级锁字典 5. 双检查锁不完整 - 修复 _ensure_debug_save_worker_started 6. Daemon 线程无 Graceful Shutdown - 添加 shutdown event 和 atexit 7. 关键路径异常处理 - 添加 logging.debug 替代 pass Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1fdec7a548
commit
ff8de2c9b8
6 files changed
+283
-199
No files matched your search
+106
-72
@@ -1,4 +1,5 @@
|
||||
import subprocess
|
||||
import threading
|
||||
from datetime import datetime, timedelta
|
||||
import os
|
||||
import sys
|
||||
@@ -48,11 +49,26 @@ _EXTERNAL_AXF_SCREENSHOT = (
|
||||
)
|
||||
|
||||
|
||||
def _verify_png_integrity(path: str) -> bool:
|
||||
"""验证 PNG 文件头尾完整性,防止读取半写文件"""
|
||||
try:
|
||||
with open(path, 'rb') as f:
|
||||
header = f.read(8)
|
||||
if len(header) < 8 or header[:4] != b'\x89PNG':
|
||||
return False
|
||||
f.seek(-12, 2) # IEND chunk 至少 12 字节
|
||||
tail = f.read(12)
|
||||
return b'IEND' in tail
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bool:
|
||||
"""安全地替换文件,处理Windows文件锁定问题。
|
||||
|
||||
根本优化:优先使用直接复制而不是替换,避免文件锁定问题。
|
||||
如果文件被占用,直接复制内容而不是等待释放。
|
||||
对于 PNG 文件,会先验证完整性再替换。
|
||||
|
||||
Args:
|
||||
tmp_file: 临时文件路径
|
||||
@@ -67,6 +83,12 @@ def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bo
|
||||
if not os.path.exists(tmp_file):
|
||||
return False
|
||||
|
||||
# 对于 PNG 文件,先验证完整性
|
||||
if tmp_file.lower().endswith('.png'):
|
||||
if not _verify_png_integrity(tmp_file):
|
||||
logging.debug("PNG 文件不完整,跳过替换: %s", tmp_file)
|
||||
return False
|
||||
|
||||
# 根本优化:优先尝试原子替换(最快),如果失败则直接复制(避免等待)
|
||||
try:
|
||||
# 方法1: 直接使用 os.replace (原子操作,最快)
|
||||
@@ -205,6 +227,9 @@ class underlying_operations:
|
||||
self.ocr_type = None # 'easyocr' 或 'paddleocr'
|
||||
# 用于存储OCR区域的坐标信息(key为picname,value为(left, top, right, bottom))
|
||||
self._ocr_coords_cache: dict[str, tuple[int, int, int, int]] = {}
|
||||
# 线程安全锁
|
||||
self._ocr_lock = threading.RLock() # 保护 OCR 初始化
|
||||
self._ocr_coords_lock = threading.Lock() # 保护坐标缓存
|
||||
|
||||
# 默认使用CPU模式(删除GPU检测)
|
||||
self._gpu_available = False
|
||||
@@ -338,69 +363,73 @@ class underlying_operations:
|
||||
if self.ocr is not None:
|
||||
return
|
||||
|
||||
# 默认使用CPU模式(延迟初始化时)
|
||||
with self._ocr_lock:
|
||||
if self.ocr is not None:
|
||||
return
|
||||
|
||||
# 优先尝试EasyOCR
|
||||
try:
|
||||
# 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题
|
||||
import importlib
|
||||
# 默认使用CPU模式(延迟初始化时)
|
||||
|
||||
# 优先尝试EasyOCR
|
||||
try:
|
||||
easyocr = importlib.import_module("easyocr")
|
||||
except Exception:
|
||||
easyocr = None
|
||||
# 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题
|
||||
import importlib
|
||||
|
||||
# 临时重定向输出以减少初始化时的噪音
|
||||
import io
|
||||
from contextlib import redirect_stdout, redirect_stderr
|
||||
|
||||
fake_stdout = io.StringIO()
|
||||
fake_stderr = io.StringIO()
|
||||
|
||||
if easyocr is not None:
|
||||
with redirect_stdout(fake_stdout), redirect_stderr(fake_stderr):
|
||||
self.ocr = easyocr.Reader(
|
||||
["ch_sim", "en"], gpu=False, verbose=False
|
||||
)
|
||||
|
||||
self.ocr_type = "easyocr"
|
||||
gpu_status = "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})")
|
||||
else:
|
||||
raise ImportError("easyocr not available")
|
||||
except Exception as e:
|
||||
# EasyOCR失败,回退到PaddleOCR
|
||||
print(f"[OCR] 延迟初始化EasyOCR失败: {e},回退到PaddleOCR")
|
||||
devnull = None
|
||||
try:
|
||||
devnull = open(os.devnull, "w", encoding="utf-8")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# 使用 PaddleOCR(强制 CPU 模式)
|
||||
use_gpu = False
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_angle_cls=False,
|
||||
use_gpu=use_gpu,
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
print("[OCR] 延迟初始化:使用 PaddleOCR(CPU模式)")
|
||||
except Exception:
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
finally:
|
||||
try:
|
||||
if devnull is not None:
|
||||
devnull.close()
|
||||
easyocr = importlib.import_module("easyocr")
|
||||
except Exception:
|
||||
pass
|
||||
easyocr = None
|
||||
|
||||
# 临时重定向输出以减少初始化时的噪音
|
||||
import io
|
||||
from contextlib import redirect_stdout, redirect_stderr
|
||||
|
||||
fake_stdout = io.StringIO()
|
||||
fake_stderr = io.StringIO()
|
||||
|
||||
if easyocr is not None:
|
||||
with redirect_stdout(fake_stdout), redirect_stderr(fake_stderr):
|
||||
self.ocr = easyocr.Reader(
|
||||
["ch_sim", "en"], gpu=False, verbose=False
|
||||
)
|
||||
|
||||
self.ocr_type = "easyocr"
|
||||
gpu_status = "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})")
|
||||
else:
|
||||
raise ImportError("easyocr not available")
|
||||
except Exception as e:
|
||||
# EasyOCR失败,回退到PaddleOCR
|
||||
print(f"[OCR] 延迟初始化EasyOCR失败: {e},回退到PaddleOCR")
|
||||
devnull = None
|
||||
try:
|
||||
devnull = open(os.devnull, "w", encoding="utf-8")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# 使用 PaddleOCR(强制 CPU 模式)
|
||||
use_gpu = False
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_angle_cls=False,
|
||||
use_gpu=use_gpu,
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
print("[OCR] 延迟初始化:使用 PaddleOCR(CPU模式)")
|
||||
except Exception:
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
finally:
|
||||
try:
|
||||
if devnull is not None:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def select_device(self):
|
||||
"""选择需要连接的设备"""
|
||||
@@ -1396,7 +1425,8 @@ class underlying_operations:
|
||||
# 存储坐标信息供analyse_pic_word使用
|
||||
if name:
|
||||
try:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
with self._ocr_coords_lock:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1517,7 +1547,8 @@ class underlying_operations:
|
||||
# 存储坐标信息供analyse_pic_word使用
|
||||
if name:
|
||||
try:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
with self._ocr_coords_lock:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1652,7 +1683,8 @@ class underlying_operations:
|
||||
# 尝试获取OCR区域坐标
|
||||
ocr_coords = None
|
||||
try:
|
||||
ocr_coords = self._ocr_coords_cache.get(picname)
|
||||
with self._ocr_coords_lock:
|
||||
ocr_coords = self._ocr_coords_cache.get(picname)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -2895,11 +2927,14 @@ class underlying_operations:
|
||||
if not t:
|
||||
return False
|
||||
|
||||
# 使用 shlex.quote 转义文本,防止 shell 注入
|
||||
safe_t = shlex.quote(t)
|
||||
|
||||
# 1) cmd clipboard set
|
||||
try:
|
||||
if (
|
||||
subprocess.run(
|
||||
self._adb_args(device_id, "shell", "cmd", "clipboard", "set", t),
|
||||
self._adb_args(device_id, "shell", "cmd", "clipboard", "set", safe_t),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=3.0,
|
||||
@@ -2924,7 +2959,7 @@ class underlying_operations:
|
||||
"clipper.set",
|
||||
"-e",
|
||||
"text",
|
||||
t,
|
||||
safe_t,
|
||||
),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
@@ -2951,13 +2986,9 @@ class underlying_operations:
|
||||
return False
|
||||
# 空格用 %s,避免被 shell 分词
|
||||
t = t.replace(" ", "%s")
|
||||
# 仅做最小转义,避免破坏中文
|
||||
t = (
|
||||
t.replace("&", "\\&")
|
||||
.replace("<", "\\<")
|
||||
.replace(">", "\\>")
|
||||
.replace("|", "\\|")
|
||||
)
|
||||
# 完整转义所有 shell 特殊字符
|
||||
for ch in ['&', '<', '>', '|', ';', '$', '`', "'", '"', '\\', '(', ')', '{', '}', '[', ']', '!', '#', '*', '?']:
|
||||
t = t.replace(ch, '\\' + ch)
|
||||
try:
|
||||
return (
|
||||
subprocess.run(
|
||||
@@ -3085,12 +3116,13 @@ class underlying_operations:
|
||||
act = str(action or "").strip()
|
||||
if not act:
|
||||
return False
|
||||
# 这里不依赖 broadcast 的返回文本,只要命令成功执行就认为 ok
|
||||
# 使用 shlex.quote 转义消息,防止 shell 注入
|
||||
safe_msg = shlex.quote(str(msg or ""))
|
||||
try:
|
||||
return (
|
||||
subprocess.run(
|
||||
self._adb_args(
|
||||
device_id, "shell", "am", "broadcast", "-a", act, "--es", "msg", str(msg or "")
|
||||
device_id, "shell", "am", "broadcast", "-a", act, "--es", "msg", safe_msg
|
||||
),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
@@ -3113,11 +3145,13 @@ class underlying_operations:
|
||||
v = int(value)
|
||||
except Exception:
|
||||
return False
|
||||
# 使用 shlex.quote 转义 key,防止 shell 注入
|
||||
safe_k = shlex.quote(k)
|
||||
try:
|
||||
return (
|
||||
subprocess.run(
|
||||
self._adb_args(
|
||||
device_id, "shell", "am", "broadcast", "-a", act, "--ei", k, v
|
||||
device_id, "shell", "am", "broadcast", "-a", act, "--ei", safe_k, v
|
||||
),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
|
||||
Reference in new issue
Block a user