# One 9008 session: identify, back up, or flash.
import logging
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
EDL = os.path.join(HERE, "edl")
LOADER = os.path.join(
EDL, "Loaders", "cyanogen", "007050e100000000_4614048173062ae4_fhprg_peek.bin"
)
IMAGES = os.path.join(os.path.dirname(HERE), "images")
WRITES = [
("gpt_primary.bin", 0),
("gpt_backup.bin", 7471038),
("cdt.bin", 131072),
("sbl1.mbn", 262144),
("rpm.mbn", 263168),
("tz.mbn", 264192),
("hyp.mbn", 266240),
("aboot.mbn", 524288),
("boot.img", 526336),
("rootfs.img", 659456),
]
EFS = [
("modemst1.bin", "modemst1", 267296),
("modemst2.bin", "modemst2", 271392),
("fsc.bin", "fsc", 275488),
("fsg.bin", "fsg", 393216),
]
EFS_BYTES = {
"modemst1": 2 * 1024 * 1024,
"modemst2": 2 * 1024 * 1024,
"fsc": 1024,
"fsg": 2 * 1024 * 1024,
}
def emit(key, value):
print(f"FLASHER\t{key}\t{value}", flush=True)
def fail(message):
emit("FAIL", message)
sys.exit(1)
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.py",
"printgpt",
"--memory=eMMC",
"--maxpayload=16384",
"--loader=" + LOADER,
]
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.py",
"printgpt",
"--memory=eMMC",
"--maxpayload=16384",
"--loader=" + LOADER,
]
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 = ''
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 read_part(app, name, path):
options = {
"": name,
"": path,
"--lun": None,
"--memory": "eMMC",
}
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_file(app, start, path):
options = {
"": str(start),
"": path,
"--lun": None,
"--memory": "eMMC",
"--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
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] == "--full":
full = True
i += 1
continue
if args[i] == "--no-efs":
skip_efs = True
i += 1
continue
i += 1
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))
if command == "info":
emit("DONE", "info")
return
if command == "backup":
if not dest:
fail("没有备份目录")
if skip_efs and not full:
fail("没有要备份的内容")
os.makedirs(dest, exist_ok=True)
if not skip_efs:
span = 60 if full else 80
for index, (_file, name, _lba) in enumerate(EFS):
emit("PROGRESS", str(int(index * span / len(EFS))))
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 in ("modemst1", "modemst2", "fsc", "fsg"):
if not os.path.isfile(os.path.join(dest, name + ".bin")):
fail(f"缺少 {name} 备份")
total = len(WRITES) + (len(EFS) if restore else 0)
step = 0
for filename, start in WRITES:
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 filename, name, start in EFS:
path = os.path.join(dest, name + ".bin")
fit_partition(path, EFS_BYTES[name])
emit("STATUS", f"正在写回 {name}")
write_file(app, start, path)
step += 1
emit("PROGRESS", str(int(step * 90 / total)))
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))