534 lines
16 KiB
Python
534 lines
16 KiB
Python
# One 9008 session: identify, back up, or flash.
|
|
import logging
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
EDL = os.path.join(HERE, "edl")
|
|
LOADER = ""
|
|
IMAGES = ""
|
|
MEMORY = "eMMC"
|
|
MAXPAYLOAD = "16384"
|
|
REQUIRED = []
|
|
BACKUPS = []
|
|
FLASHES = []
|
|
DEVINFO_LBA = 0
|
|
DEVINFO_SECTORS = 0
|
|
MODEL_ID = ""
|
|
|
|
|
|
def emit(key, value):
|
|
print(f"FLASHER\t{key}\t{value}", flush=True)
|
|
|
|
|
|
def fail(message):
|
|
emit("FAIL", message)
|
|
sys.exit(1)
|
|
|
|
|
|
def load_profile(path):
|
|
# 型号资料是唯一的分区和镜像来源。images 相对资料目录,loader 相对程序目录。
|
|
global LOADER, IMAGES, MEMORY, MAXPAYLOAD, REQUIRED, BACKUPS, FLASHES
|
|
global DEVINFO_LBA, DEVINFO_SECTORS, MODEL_ID
|
|
profile_dir = os.path.dirname(os.path.abspath(path))
|
|
app_dir = os.path.dirname(os.path.dirname(profile_dir))
|
|
values = {"partition": [], "backup": [], "flash": []}
|
|
with open(path, encoding="utf-8") as handle:
|
|
for raw in handle:
|
|
line = raw.split("#", 1)[0].strip()
|
|
if not line or "=" not in line:
|
|
continue
|
|
key, value = line.split("=", 1)
|
|
key = key.strip()
|
|
value = value.strip()
|
|
if key in values:
|
|
values[key].append(value)
|
|
else:
|
|
values[key] = value
|
|
images = values.get("images") or ""
|
|
loader = values.get("loader") or ""
|
|
if not images or not loader:
|
|
fail("型号配置缺少镜像目录或引导文件")
|
|
IMAGES = images if os.path.isabs(images) else os.path.join(profile_dir, images)
|
|
LOADER = loader if os.path.isabs(loader) else os.path.join(app_dir, loader)
|
|
MEMORY = values.get("memory") or "eMMC"
|
|
MAXPAYLOAD = str(values.get("maxpayload") or "16384")
|
|
REQUIRED = values["partition"]
|
|
BACKUPS = []
|
|
for item in values["backup"]:
|
|
name, lba, size = [part.strip() for part in item.split(",")]
|
|
BACKUPS.append((name, int(lba), int(size)))
|
|
FLASHES = []
|
|
for item in values["flash"]:
|
|
filename, lba = [part.strip() for part in item.split(",")]
|
|
FLASHES.append((filename, int(lba)))
|
|
if not REQUIRED:
|
|
fail("型号配置没有用于核对的分区")
|
|
if not os.path.isfile(LOADER):
|
|
fail("找不到引导文件")
|
|
MODEL_ID = values.get("id") or ""
|
|
devinfo = values.get("devinfo") or ""
|
|
if devinfo:
|
|
lba, count = [part.strip() for part in devinfo.split(",")]
|
|
DEVINFO_LBA = int(lba)
|
|
DEVINFO_SECTORS = int(count)
|
|
|
|
|
|
def edl_argv():
|
|
return [
|
|
"edl.py",
|
|
"printgpt",
|
|
"--memory=" + MEMORY,
|
|
"--maxpayload=" + MAXPAYLOAD,
|
|
"--loader=" + LOADER,
|
|
]
|
|
|
|
|
|
def format_size(sectors):
|
|
size = int(sectors) * 512
|
|
gib = 1024 ** 3
|
|
mib = 1024 ** 2
|
|
kib = 1024
|
|
if size >= gib:
|
|
return f"{size / gib:.1f} GiB"
|
|
if size >= mib:
|
|
return f"{size / mib:.1f} MiB"
|
|
return f"{max(size // kib, 1)} KiB"
|
|
|
|
|
|
def fill_edl_args(args):
|
|
defaults = {
|
|
"--gpt-num-part-entries": "0",
|
|
"--gpt-part-entry-size": "0",
|
|
"--gpt-part-entry-start-lba": "0",
|
|
"--lun": None,
|
|
"--skipresponse": False,
|
|
"--skipwrite": False,
|
|
"--memory": "eMMC",
|
|
}
|
|
for key, value in defaults.items():
|
|
if args.get(key) is None:
|
|
args[key] = value
|
|
|
|
|
|
def open_link():
|
|
os.chdir(EDL)
|
|
if EDL not in sys.path:
|
|
sys.path.insert(0, EDL)
|
|
sys.argv = edl_argv()
|
|
import edl
|
|
fill_edl_args(edl.args)
|
|
from edlclient.Config.usb_ids import default_ids
|
|
from edlclient.Library.Connection.usblib import usb_class
|
|
from edlclient.Library.sahara import sahara
|
|
|
|
app = edl.main(edl.args, "")
|
|
vid = int(app.args["--vid"], 16)
|
|
pid = int(app.args["--pid"], 16)
|
|
portconfig = [[vid, pid, -1]] if vid != -1 and pid != -1 else default_ids
|
|
app.serial = False
|
|
app.portname = ""
|
|
app.serial_number = None
|
|
app.cdc = usb_class(portconfig=portconfig, loglevel=logging.INFO, serial_number=None)
|
|
app.sahara = sahara(app.cdc, loglevel=logging.INFO)
|
|
app.sahara.programmer = LOADER
|
|
app.cdc.timeout = 1500
|
|
return app
|
|
|
|
|
|
def identify_only():
|
|
# 只做 Sahara 命令模式,不上传引导、不读容量。
|
|
# 读完后状态机回到等待握手,重启软件还能再读序列号和芯片型号。
|
|
app = open_link()
|
|
try:
|
|
conninfo = app.doconnect(0) or {}
|
|
mode = conninfo.get("mode")
|
|
if mode == "error":
|
|
fail("设备已拔出")
|
|
if mode != "sahara":
|
|
return "", ""
|
|
try:
|
|
version = conninfo.get("data").version
|
|
except Exception:
|
|
version = 2
|
|
if not app.sahara.cmd_info(version=version):
|
|
fail("没有读到芯片序列号")
|
|
serial = getattr(app.sahara, "serials", None) or ""
|
|
chip = chip_name(app)
|
|
return serial, chip
|
|
finally:
|
|
try:
|
|
app.cdc.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def connect():
|
|
os.chdir(EDL)
|
|
if EDL not in sys.path:
|
|
sys.path.insert(0, EDL)
|
|
sys.argv = edl_argv()
|
|
import edl
|
|
fill_edl_args(edl.args)
|
|
|
|
last = "Firehose 没有连上"
|
|
saved = {"serial": "", "chip": ""}
|
|
for skip in (False, True):
|
|
edl.args["--skipstorageinit"] = skip
|
|
app = edl.main(edl.args, "")
|
|
try:
|
|
app.run()
|
|
except Exception as exc:
|
|
last = str(exc)
|
|
app = None
|
|
if app is not None:
|
|
keep_identity(app, saved)
|
|
if app is not None and app.fh is not None and app.fh.connected:
|
|
keep_identity(app, saved)
|
|
return app
|
|
if app is not None and getattr(app, "cdc", None) is not None:
|
|
try:
|
|
app.cdc.close()
|
|
except Exception:
|
|
pass
|
|
last = "Firehose 没有连上"
|
|
fail(last)
|
|
|
|
|
|
def first_number(raw):
|
|
if raw is None:
|
|
return None
|
|
digits = []
|
|
started = False
|
|
for ch in str(raw):
|
|
if ch.isdigit():
|
|
digits.append(ch)
|
|
started = True
|
|
elif started:
|
|
break
|
|
if not digits:
|
|
return None
|
|
value = int("".join(digits))
|
|
if value <= 0:
|
|
return None
|
|
return value
|
|
|
|
|
|
def sectors_from_mapping(info):
|
|
if not isinstance(info, dict):
|
|
return None
|
|
for key in ("num_partition_sectors", "total_blocks", "total_lbas"):
|
|
value = first_number(info.get(key))
|
|
if value:
|
|
return value
|
|
return None
|
|
|
|
|
|
def storage_sectors(app):
|
|
info = None
|
|
try:
|
|
info = app.fh.get_storage_info()
|
|
except Exception:
|
|
info = None
|
|
sectors = sectors_from_mapping(info)
|
|
if sectors:
|
|
return sectors
|
|
cfg = app.fh.firehose.cfg
|
|
sectors = first_number(getattr(cfg, "total_blocks", None))
|
|
if sectors:
|
|
return sectors
|
|
xml = '<?xml version="1.0" ?><data><getstorageinfo physical_partition_number="0"/></data>'
|
|
rsp = app.fh.firehose.xmlsend(xml)
|
|
pieces = []
|
|
for item in (getattr(rsp, "data", None), getattr(rsp, "log", None), rsp):
|
|
if isinstance(item, (bytes, bytearray)):
|
|
pieces.append(item.decode("utf-8", "replace"))
|
|
elif isinstance(item, dict):
|
|
sectors = sectors_from_mapping(item)
|
|
if sectors:
|
|
return sectors
|
|
pieces.append(str(item))
|
|
elif item is not None:
|
|
pieces.append(str(item))
|
|
text = "\n".join(pieces)
|
|
for key in ("num_partition_sectors", "total_blocks"):
|
|
at = text.find(key)
|
|
if at < 0:
|
|
continue
|
|
value = first_number(text[at + len(key):])
|
|
if value:
|
|
return value
|
|
fail("没有读到 eMMC 扇区数")
|
|
|
|
|
|
def keep_identity(app, saved):
|
|
sahara = getattr(app, "sahara", None)
|
|
if sahara is None:
|
|
return
|
|
serial = getattr(sahara, "serials", None) or ""
|
|
if serial:
|
|
saved["serial"] = serial
|
|
elif saved.get("serial"):
|
|
sahara.serials = saved["serial"]
|
|
chip = chip_name(app)
|
|
if chip and not str(chip).startswith("0x"):
|
|
saved["chip"] = chip
|
|
elif chip and not saved.get("chip"):
|
|
saved["chip"] = chip
|
|
elif saved.get("chip"):
|
|
sahara._flasher_chip = saved["chip"]
|
|
|
|
|
|
def chip_name(app):
|
|
sahara = getattr(app, "sahara", None)
|
|
if sahara is None:
|
|
return ""
|
|
named = getattr(sahara, "_flasher_chip", None)
|
|
if named:
|
|
return named
|
|
msm_id = getattr(sahara, "msm_id", None)
|
|
if isinstance(msm_id, int):
|
|
try:
|
|
from edlclient.Config.qualcomm_config import msmids
|
|
name = msmids.get(msm_id)
|
|
if name:
|
|
return name
|
|
except Exception:
|
|
pass
|
|
return "0x{:06x}".format(msm_id)
|
|
hwid = getattr(sahara, "hwidstr", None) or ""
|
|
return hwid
|
|
|
|
|
|
def gpt_names(app):
|
|
try:
|
|
_data, gpt = app.fh.firehose.get_gpt(0, 0, 0, 0)
|
|
except SystemExit:
|
|
raise
|
|
except Exception as exc:
|
|
fail(f"没有读到分区表:{exc}")
|
|
entries = getattr(gpt, "partentries", None) if gpt is not None else None
|
|
if not entries:
|
|
fail("没有读到分区表")
|
|
return {str(name).lower() for name in entries}
|
|
|
|
|
|
def ensure_layout(app):
|
|
# 已在本次 Firehose 会话中。不符合就退出,不写盘,也不发复位。
|
|
names = gpt_names(app)
|
|
missing = [name for name in REQUIRED if name.lower() not in names]
|
|
if missing:
|
|
fail("分区不符,已停止:" + "、".join(missing) + "。请拔出并按住复位键后重新插入")
|
|
|
|
|
|
def read_part(app, name, path):
|
|
options = {
|
|
"<partitionname>": name,
|
|
"<filename>": path,
|
|
"--lun": None,
|
|
"--memory": MEMORY,
|
|
}
|
|
if not app.fh.handle_firehose("r", options):
|
|
fail(f"读取 {name} 失败")
|
|
|
|
|
|
def fit_partition(path, size):
|
|
with open(path, "rb") as handle:
|
|
data = handle.read()
|
|
if len(data) > size:
|
|
fail(f"{os.path.basename(path)} 大于目标分区")
|
|
if len(data) < size:
|
|
with open(path, "ab") as handle:
|
|
handle.write(b"\x00" * (size - len(data)))
|
|
|
|
|
|
def write_board_id(app, chip):
|
|
# 写在 devinfo 最后一个扇区,保留分区开头给引导程序。
|
|
if DEVINFO_LBA <= 0 or DEVINFO_SECTORS <= 0:
|
|
return
|
|
if not chip:
|
|
fail("没有芯片号,不能写入 devinfo")
|
|
text = f"FLASHER1\nchip_serial={chip}\nmodel={MODEL_ID}\n"
|
|
blob = text.encode("ascii")
|
|
if len(blob) > 512:
|
|
fail("devinfo 记录过长")
|
|
blob += b"\x00" * (512 - len(blob))
|
|
fd, path = tempfile.mkstemp(prefix="devinfo-", suffix=".bin")
|
|
try:
|
|
os.write(fd, blob)
|
|
os.close(fd)
|
|
fd = -1
|
|
emit("STATUS", "正在写入 devinfo")
|
|
write_file(app, DEVINFO_LBA + DEVINFO_SECTORS - 1, path)
|
|
finally:
|
|
if fd >= 0:
|
|
os.close(fd)
|
|
if os.path.isfile(path):
|
|
os.remove(path)
|
|
|
|
|
|
def write_file(app, start, path):
|
|
options = {
|
|
"<start_sector>": str(start),
|
|
"<filename>": path,
|
|
"--lun": None,
|
|
"--memory": MEMORY,
|
|
"--skipwrite": False,
|
|
}
|
|
if not app.fh.handle_firehose("ws", options):
|
|
fail(f"写入 {os.path.basename(path)} 失败")
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
fail("缺少命令")
|
|
command = sys.argv[1]
|
|
port = ""
|
|
dest = ""
|
|
full = False
|
|
skip_efs = False
|
|
profile = ""
|
|
chip_arg = ""
|
|
args = sys.argv[2:]
|
|
i = 0
|
|
while i < len(args):
|
|
if args[i] == "--port" and i + 1 < len(args):
|
|
port = args[i + 1]
|
|
i += 2
|
|
continue
|
|
if args[i] == "--dest" and i + 1 < len(args):
|
|
dest = args[i + 1]
|
|
i += 2
|
|
continue
|
|
if args[i] == "--profile" and i + 1 < len(args):
|
|
profile = args[i + 1]
|
|
i += 2
|
|
continue
|
|
if args[i] == "--chip" and i + 1 < len(args):
|
|
chip_arg = args[i + 1]
|
|
i += 2
|
|
continue
|
|
if args[i] == "--full":
|
|
full = True
|
|
i += 1
|
|
continue
|
|
if args[i] == "--no-efs":
|
|
skip_efs = True
|
|
i += 1
|
|
continue
|
|
i += 1
|
|
if not profile:
|
|
fail("没有型号配置")
|
|
load_profile(profile)
|
|
if port:
|
|
os.environ["EDL_USB_PORT"] = port
|
|
if command == "info":
|
|
serial, chip = identify_only()
|
|
if serial:
|
|
emit("SERIAL", serial)
|
|
if chip:
|
|
emit("CHIP", chip)
|
|
emit("DONE", "info")
|
|
return
|
|
app = connect()
|
|
serial = getattr(app.sahara, "serials", None) or ""
|
|
if serial:
|
|
emit("SERIAL", serial)
|
|
chip = chip_name(app)
|
|
if chip:
|
|
emit("CHIP", chip)
|
|
sectors = storage_sectors(app)
|
|
emit("DISK", format_size(sectors))
|
|
emit("SECTORS", str(sectors))
|
|
ensure_layout(app)
|
|
if command == "info":
|
|
emit("DONE", "info")
|
|
return
|
|
if command == "backup":
|
|
if not dest:
|
|
fail("没有备份目录")
|
|
if skip_efs and not full:
|
|
fail("没有要备份的内容")
|
|
if not skip_efs and not BACKUPS:
|
|
fail("型号配置没有备份分区")
|
|
os.makedirs(dest, exist_ok=True)
|
|
if not skip_efs:
|
|
span = 60 if full else 80
|
|
for index, (name, _lba, _size) in enumerate(BACKUPS):
|
|
emit("PROGRESS", str(int(index * span / max(len(BACKUPS), 1))))
|
|
read_part(app, name, os.path.join(dest, name + ".bin"))
|
|
if full:
|
|
emit("STATUS", "正在备份整盘")
|
|
target = os.path.join(dest, "emmc.bin")
|
|
chunk = 32768
|
|
sector_bytes = int(app.fh.firehose.cfg.SECTOR_SIZE_IN_BYTES)
|
|
total_bytes = sectors * sector_bytes
|
|
with open(target, "wb") as out:
|
|
done = 0
|
|
while done < sectors:
|
|
count = min(chunk, sectors - done)
|
|
part = os.path.join(dest, f".chunk-{done}.bin")
|
|
if not app.fh.firehose.cmd_read(
|
|
0, done, count, part, False,
|
|
progress_base=done * sector_bytes,
|
|
progress_total=total_bytes,
|
|
):
|
|
fail("整盘读取失败")
|
|
with open(part, "rb") as src:
|
|
out.write(src.read())
|
|
os.remove(part)
|
|
done += count
|
|
emit("PROGRESS", str(min(99, int(done * 100 / sectors))))
|
|
expected = sectors * 512
|
|
if os.path.getsize(target) != expected:
|
|
fail("整盘大小不完整")
|
|
emit("PROGRESS", "100")
|
|
emit("DONE", "backup")
|
|
return
|
|
if command == "flash":
|
|
restore = bool(dest)
|
|
if restore:
|
|
for name, _lba, _size in BACKUPS:
|
|
if not os.path.isfile(os.path.join(dest, name + ".bin")):
|
|
fail(f"缺少 {name} 备份")
|
|
total = len(FLASHES) + (len(BACKUPS) if restore else 0)
|
|
if total == 0:
|
|
fail("型号配置没有写入步骤")
|
|
step = 0
|
|
for filename, start in FLASHES:
|
|
path = os.path.join(IMAGES, filename)
|
|
if not os.path.isfile(path):
|
|
fail(f"镜像缺少 {filename}")
|
|
emit("STATUS", f"正在写入 {filename}")
|
|
write_file(app, start, path)
|
|
step += 1
|
|
emit("PROGRESS", str(int(step * 90 / total)))
|
|
if restore:
|
|
for name, start, size in BACKUPS:
|
|
path = os.path.join(dest, name + ".bin")
|
|
fit_partition(path, size)
|
|
emit("STATUS", f"正在写回 {name}")
|
|
write_file(app, start, path)
|
|
step += 1
|
|
emit("PROGRESS", str(int(step * 90 / total)))
|
|
write_board_id(app, chip_arg)
|
|
try:
|
|
app.cdc.timeout = 1500
|
|
app.fh.firehose.cmd_reset("reset")
|
|
except Exception:
|
|
pass
|
|
emit("PROGRESS", "100")
|
|
emit("DONE", "flash")
|
|
return
|
|
fail("未知命令")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except SystemExit:
|
|
raise
|
|
except Exception as exc:
|
|
fail(str(exc))
|