diff --git a/flasher/runtime/edl/edlclient/Library/firehose.py b/flasher/runtime/edl/edlclient/Library/firehose.py new file mode 100644 index 0000000..acdbe38 --- /dev/null +++ b/flasher/runtime/edl/edlclient/Library/firehose.py @@ -0,0 +1,1805 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# (c) B.Kerler 2018-2024 under GPLv3 license +# If you use my code, make sure you refer to my name +# +# !!!!! If you use this code in commercial products, your product is automatically +# GPLv3 and has to be open sourced under GPLv3 as well. !!!!! + +import binascii +import json +import os.path +import platform +from binascii import hexlify +from queue import Queue +from threading import Thread + +from edlclient.Library.Modules.nothing import nothing +from edlclient.Library.gpt import gpt, AB_FLAG_OFFSET, AB_PARTITION_ATTR_SLOT_ACTIVE +from edlclient.Library.sparse import QCSparse +from edlclient.Library.utils import * +from edlclient.Library.utils import progress + + +def writedata(filename, rq): + pos = 0 + with open(filename, "wb") as wf: + while True: + data = rq.get() + if data is None: + break + pos += len(data) + wf.write(data) + rq.task_done() + + +class response: + resp = False + data = b"" + error = "" + log = None + + def __init__(self, resp=False, data=b"", error: str = "", log: dict = ""): + self.resp = resp + self.data = data + self.error = error + self.log = log + + +try: + from edlclient.Library.Modules.init import modules +except ImportError as e: + pass + + +class nand_partition: + partentries = {} + + def __init__(self, parent, printer=None): + if printer is None: + self.printer = print + else: + self.printer = printer + self.partentries = {} + self.partitiontblsector = None + self.parent = parent + self.storage_info = {} + self.totalsectors = None + self.largesector = False + + def parse(self, partdata): + self.partentries = {} + + class partf: + sector = 0 + sectors = 0 + name = "" + attr1 = 0 + attr2 = 0 + attr3 = 0 + which_flash = 0 + + magic1, magic2, version, numparts = unpack("= sectors: + sectors += self.partentries[part].sectors + self.totalsectors = sectors + return True + return False + + def print(self): + self.printer("Name Offset\t\tLength\t\tAttr\t\t\tFlash") + self.printer("-------------------------------------------------------------") + for selpart in self.partentries: + partition = self.partentries[selpart] + name = partition.name + for i in range(0x10 - len(partition.name)): + name += " " + offset = partition.sector * self.parent.cfg.SECTOR_SIZE_IN_BYTES + length = partition.sectors * self.parent.cfg.SECTOR_SIZE_IN_BYTES + attr1 = partition.attr1 + attr2 = partition.attr2 + attr3 = partition.attr3 + which_flash = partition.which_flash + self.printer( + f"{name}\t%08X\t%08X\t{hex(attr1)}/{hex(attr2)}/{hex(attr3)}\t{which_flash}" % (offset, length)) + + +def writefile(wf, q, stop): + while True: + data = q.get() + if len(data) > 0: + wf.write(data) + q.task_done() + if stop() and q.empty(): + break + + +class asyncwriter: + def __init__(self, wf): + self.writequeue = Queue() + self.worker = Thread(target=writefile, args=(wf, self.writequeue, lambda: self.stopthreads,), daemon=True) + self.stopthreads = False + self.worker.start() + + def write(self, data): + self.writequeue.put_nowait(data) + + def stop(self): + self.stopthreads = True + self.writequeue.join() + + +class firehose(metaclass=LogBase): + class cfg: + TargetName = "" + Version = "" + ZLPAwareHost = 1 + SkipStorageInit = 0 + SkipWrite = 0 + MaxPayloadSizeToTargetInBytes = 1048576 + MaxPayloadSizeFromTargetInBytes = 8192 + MaxXMLSizeInBytes = 4096 + bit64 = True + + total_blocks = 0 + num_physical = 0 + block_size = 0 + SECTOR_SIZE_IN_BYTES = 0 + PAGES_PER_BLOCK = 0 + MemoryName = "eMMC" + prod_name = "Unknown" + maxlun = 99 + programmer = "" + + def __init__(self, cdc, xml, cfg, loglevel, devicemodel, serial, skipresponse, luns, args): + self.cdc = cdc + self.lasterror = b"" + self.loglevel = loglevel + self.args = args + self.xml = xml + self.cfg = cfg + # Remember the loader we were started with, edl_config.json may override cfg.programmer later on + self.loader_programmer = cfg.programmer + self.prog = 0 + self.progtime = 0 + self.progpos = 0 + self.pk = None + self.modules = None + self.serial = serial + self.devicemodel = devicemodel + self.skipresponse = skipresponse + self.luns = luns + self.supported_functions = [] + self.lunsizes = {} + self.rq = Queue() + self.info = self.__logger.info + self.error = self.__logger.error + self.debug = self.__logger.debug + self.warning = self.__logger.warning + + self.__logger.setLevel(loglevel) + if loglevel == logging.DEBUG: + logfilename = "log.txt" + fh = logging.FileHandler(logfilename) + self.__logger.addHandler(fh) + self.nandparttbl = None + self.nandpart = nand_partition(parent=self, printer=print) + + def detect_partition(self, arguments, partitionname, send_full=False): + if arguments is None: + arguments = {} + gpt_num = int(arguments.get("--gpt-num-part-entries") or 0) + gpt_size = int(arguments.get("--gpt-part-entry-size") or 0) + gpt_start = int(arguments.get("--gpt-part-entry-start-lba") or 0) + fpartitions = {} + for lun in self.luns: + lunname = "Lun" + str(lun) + fpartitions[lunname] = [] + data, guid_gpt = self.get_gpt(lun, gpt_num, gpt_size, gpt_start) + if guid_gpt is None: + break + else: + if partitionname in guid_gpt.partentries: + return [True, lun, data, guid_gpt] if send_full else [True, lun, + guid_gpt.partentries[partitionname]] + for part in guid_gpt.partentries: + fpartitions[lunname].append(part) + return [False, fpartitions] + + def getstatus(self, resp): + if "value" in resp: + value = resp["value"] + if value == "ACK" or value == "true": + return True + else: + return False + return True + + def decoder(self, data): + if isinstance(data, bytes) or isinstance(data, bytearray): + if data[:5] == b" response: + self.cdc.flush() + self.cdc.xmlread = True + if isinstance(data, bytes) or isinstance(data, bytearray): + self.cdc.write(data[:self.cfg.MaxXMLSizeInBytes]) + else: + self.cdc.write(bytes(data, 'utf-8')[:self.cfg.MaxXMLSizeInBytes]) + rdata = bytearray() + counter = 0 + timeout = 3 + if not skipresponse: + while b" timeout: + break + rdata += tmp + except Exception as err: + self.error(err) + return response(resp=False, error=str(err)) + if not rdata: + # Target didn't answer at all, so give the caller a chance to react + self.debug("No response received from target") + return response(resp=False) + try: + if b"raw hex token" in rdata: + rdata = rdata + try: + resp = self.xml.getresponse(rdata) + status = self.getstatus(resp) + if "rawmode" in resp: + if resp["rawmode"] == "false": + if status: + log = self.xml.getlog(rdata) + return response(resp=status, data=rdata, log=log) + else: + error = self.xml.getlog(rdata) + return response(resp=status, error=error, data=resp, log=error) + else: + if status: + if b"log value=" in rdata: + log = self.xml.getlog(rdata) + return response(resp=resp, data=rdata, log=log) + return response(resp=status, data=rdata) + except Exception as e: # pylint: disable=broad-except + rdata = bytes(self.decoder(rdata), 'utf-8') + resp = self.xml.getresponse(rdata) + status = self.getstatus(resp) + if status: + return response(resp=True, data=resp) + else: + error = "" + if b"' + val = self.xmlsend(data) + try: + v = None + while v != b'': + v = self.cdc.read(timeout=None) + if v != b'': + resp = self.xml.getlog(v)[0] + else: + break + print(resp) + except Exception as err: + self.error(str(err)) + pass + if val.resp: + self.info("Reset succeeded.") + return True + else: + self.error("Reset failed: " + val.error) + return False + + def cmd_xml(self, filename): + with open(filename, 'rb') as rf: + data = rf.read() + val = self.xmlsend(data) + if val.resp: + self.info("Command succeeded." + str(val.data)) + return val.data + else: + self.error("Command failed:" + str(val.error)) + return val.error + + def cmd_nop(self): + data = '' + resp = self.xmlsend(data, True) + self.debug(resp.data.hex()) + info = b"" + tmp = None + while tmp != b"": + tmp = self.cdc.read(timeout=None) + if tmp == b"": + break + info += tmp + if info != b"": + self.info("Nop succeeded.") + return self.xml.getlog(info) + else: + self.error("Nop failed.") + return False + + def cmd_getsha256digest(self, physical_partition_number, start_sector, num_partition_sectors): + data = f"\n" + val = self.xmlsend(data) + if val.resp: + res = self.xml.getlog(val.data) + for line in res: + self.info(line) + if "Digest " in res: + return res.split("Digest ")[1] + else: + return res + else: + self.error("GetSha256Digest failed: " + val.error) + return False + + def cmd_setbootablestoragedrive(self, partition_number): + data = f"\n" + val = self.xmlsend(data) + if val.resp: + self.info("Setbootablestoragedrive succeeded.") + return True + else: + self.error("Setbootablestoragedrive failed: " + val.error) + return False + + def cmd_send(self, content, responsexml=True): + data = f"\n<{content} />" + if responsexml: + val = self.xmlsend(data) + if val.resp: + return val.data + else: + self.error(f"{content} failed.") + self.error(f"{val.error}") + return val.error + else: + self.xmlsend(data, True) + return True + + def cmd_patch(self, physical_partition_number, start_sector, byte_offset, value, size_in_bytes, display=True): + """ + + """ + + data = f"\n" + \ + f"\n" + + rsp = self.xmlsend(data) + if rsp.resp: + if display: + self.info(f"Patch:\n--------------------\n") + self.info(rsp.data) + return True + else: + self.error(f"Error:{rsp.error}") + return False + + def wait_for_data(self): + tmp = bytearray() + timeout = 0 + while b'response value' not in tmp: + res = self.cdc.read(timeout=None) + if res == b'': + timeout += 1 + if timeout == 4: + break + time.sleep(0.1) + tmp += res + return tmp + + def nand_pages_attr(self): + if self.cfg.MemoryName.lower() == "nand" and self.cfg.PAGES_PER_BLOCK: + return f" PAGES_PER_BLOCK=\"{self.cfg.PAGES_PER_BLOCK}\"" + return "" + + def cmd_program(self, physical_partition_number, start_sector, filename, display=True): + total = os.stat(filename).st_size + sparse = QCSparse(filename, self.loglevel) + sparseformat = False + if sparse.readheader(): + sparseformat = True + total = sparse.getsize() + bytestowrite = total + progbar = progress(self.cfg.SECTOR_SIZE_IN_BYTES) + with open(filename, "rb") as rf: + # Make sure we fill data up to the sector size + num_partition_sectors = total // self.cfg.SECTOR_SIZE_IN_BYTES + if (total % self.cfg.SECTOR_SIZE_IN_BYTES) != 0: + num_partition_sectors += 1 + if display: + self.info(f"\nWriting to physical partition {str(physical_partition_number)}, " + + f"sector {str(start_sector)}, sectors {str(num_partition_sectors)}") + + data = f"\n" + \ + f"\n" + rsp = self.xmlsend(data, self.skipresponse) + progbar.show_progress(prefix="Write", pos=0, total=total, display=display) + if rsp.resp: + while bytestowrite > 0: + wlen = min(bytestowrite, self.cfg.MaxPayloadSizeToTargetInBytes) + + if sparseformat: + wdata = sparse.read(wlen) + else: + wdata = rf.read(wlen) + bytestowrite -= wlen + + if wlen % self.cfg.SECTOR_SIZE_IN_BYTES != 0: + filllen = (wlen // self.cfg.SECTOR_SIZE_IN_BYTES * self.cfg.SECTOR_SIZE_IN_BYTES) + \ + self.cfg.SECTOR_SIZE_IN_BYTES + wdata += b"\x00" * (filllen - wlen) + + self.cdc.write(wdata) + progbar.show_progress(prefix="Write", pos=total - bytestowrite, total=total, display=display) + self.cdc.write(b'') + # time.sleep(0.2) + + wd = self.wait_for_data() + log = self.xml.getlog(wd) + rsp = self.xml.getresponse(wd) + if "value" in rsp: + if rsp["value"] != "ACK": + self.error(f"Error:") + for line in log: + self.error(line) + return False + else: + self.error(f"Error:{rsp}") + return False + return True + + def cmd_program_buffer(self, physical_partition_number, start_sector, wfdata, display=True): + bytestowrite = len(wfdata) + total = bytestowrite + # Make sure we fill data up to the sector size + num_partition_sectors = bytestowrite // self.cfg.SECTOR_SIZE_IN_BYTES + if (bytestowrite % self.cfg.SECTOR_SIZE_IN_BYTES) != 0: + num_partition_sectors += 1 + if display: + self.info(f"\nWriting to physical partition {str(physical_partition_number)}, " + + f"sector {str(start_sector)}, sectors {str(num_partition_sectors)}") + + data = f"\n" + \ + f"\n" + rsp = self.xmlsend(data, self.skipresponse) + progbar = progress(self.cfg.SECTOR_SIZE_IN_BYTES) + progbar.show_progress(prefix="Write", pos=0, total=total, display=display) + if rsp.resp: + pos = 0 + while bytestowrite > 0: + wlen = min(bytestowrite, self.cfg.MaxPayloadSizeToTargetInBytes) + + wrdata = wfdata[pos:pos + wlen] + pos += wlen + bytestowrite -= wlen + + if wlen % self.cfg.SECTOR_SIZE_IN_BYTES != 0: + filllen = (wlen // self.cfg.SECTOR_SIZE_IN_BYTES * self.cfg.SECTOR_SIZE_IN_BYTES) + \ + self.cfg.SECTOR_SIZE_IN_BYTES + wrdata += b"\x00" * (filllen - wlen) + + self.cdc.write(wrdata) + + progbar.show_progress(prefix="Write", pos=total - bytestowrite, total=total, display=display) + self.cdc.write(b'') + # time.sleep(0.2) + + wd = self.wait_for_data() + log = self.xml.getlog(wd) + rsp = self.xml.getresponse(wd) + if "value" in rsp: + if rsp["value"] != "ACK": + self.error(f"Error:") + for line in log: + self.error(line) + return False + else: + self.error(f"Error:{rsp}") + return False + else: + self.error(f"Error:{rsp.error}") + return True + + def cmd_erase(self, physical_partition_number, start_sector, num_partition_sectors, display=True): + if display: + self.info(f"\nErasing from physical partition {str(physical_partition_number)}, " + + f"sector {str(start_sector)}, sectors {str(num_partition_sectors)}") + + if "erase" in self.supported_functions: + data = f"\n" + \ + f"\n" + rsp = self.xmlsend(data, self.skipresponse) + if rsp.resp: + return True + self.error(f"Error:{rsp.error}") + return False + + data = f"\n" + \ + f"\n" + + rsp = self.xmlsend(data, self.skipresponse) + empty = b"\x00" * self.cfg.MaxPayloadSizeToTargetInBytes + pos = 0 + bytestowrite = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors + total = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors + progbar = progress(self.cfg.MaxPayloadSizeToTargetInBytes) + progbar.show_progress(prefix="Erase", pos=0, total=total, display=display) + if rsp.resp: + while bytestowrite > 0: + wlen = min(bytestowrite, self.cfg.MaxPayloadSizeToTargetInBytes) + self.cdc.write(empty[:wlen]) + progbar.show_progress(prefix="Erase", pos=total - bytestowrite, total=total, display=display) + bytestowrite -= wlen + pos += wlen + self.cdc.write(b'') + + res = self.wait_for_data() + info = self.xml.getlog(res) + rsp = self.xml.getresponse(res) + if "value" in rsp: + if rsp["value"] != "ACK": + self.error(f"Error:") + for line in info: + self.error(line) + return False + else: + self.error(f"Error:{rsp}") + return False + else: + self.error(f"Error:{rsp.error}") + return False + return True + + def cmd_read(self, physical_partition_number, start_sector, num_partition_sectors, filename, display=True, progress_base=0, progress_total=None): + self.lasterror = b"" + progbar = progress(self.cfg.SECTOR_SIZE_IN_BYTES) + progbar.byte_base = progress_base + if progress_total: + progbar.byte_span = progress_total + if display: + self.info( + f"\nReading from physical partition {str(physical_partition_number)}, " + + f"sector {str(start_sector)}, sectors {str(num_partition_sectors)}") + + data = f"\n" + + rsp = self.xmlsend(data, self.skipresponse) + self.cdc.xmlread = False + time.sleep(0.01) + if not rsp.resp: + if display: + self.error(rsp.error) + return b"" + else: + bytestoread = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors + total = bytestoread + show_progress = progbar.show_progress + usb_read = self.cdc.read + progbar.show_progress(prefix="Read", pos=0, total=total, display=display) + worker = Thread(target=writedata, args=(filename, self.rq), daemon=True) + worker.start() + while bytestoread > 0: + if self.cdc.is_serial: + maxsize = self.cfg.MaxPayloadSizeFromTargetInBytes + else: + maxsize = 5 * 1024 * 1024 + size = min(maxsize, bytestoread) + data = usb_read(size) + if len(data) > 0: + self.rq.put(data) + bytestoread -= len(data) + show_progress(prefix="Read", pos=total - bytestoread, total=total, display=display) + self.rq.put(None) + worker.join(60) + self.cdc.xmlread = True + wd = self.wait_for_data() + info = self.xml.getlog(wd) + rsp = self.xml.getresponse(wd) + if "value" in rsp: + if rsp["value"] != "ACK": + if bytestoread != 0: + self.error(f"Error:") + for line in info: + self.error(line) + self.lasterror += bytes(line + "\n", "utf-8") + return False + else: + if display: + self.error(f"Error:{rsp[2]}") + return False + return True + + def cmd_read_buffer(self, physical_partition_number, start_sector, num_partition_sectors, display=True): + self.lasterror = b"" + prog = 0 + if display: + self.info( + f"\nReading from physical partition {str(physical_partition_number)}, " + + f"sector {str(start_sector)}, sectors {str(num_partition_sectors)}") + print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) + + data = f"\n" + + progbar = progress(self.cfg.SECTOR_SIZE_IN_BYTES) + rsp = self.xmlsend(data, self.skipresponse) + if "value" in rsp.data and rsp.data["value"] == "NAK": + return rsp + self.cdc.xmlread = False + resData = bytearray() + if not rsp.resp: + if display: + self.error(rsp.error) + return rsp + else: + bytestoread = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors + total = bytestoread + if display: + progbar.show_progress(prefix="Read", pos=total - bytestoread, total=total, display=display) + while bytestoread > 0: + tmp = self.cdc.read(min(self.cdc.maxsize, bytestoread)) + size = len(tmp) + bytestoread -= size + resData.extend(tmp) + progbar.show_progress(prefix="Read", pos=total - bytestoread, total=total, display=display) + self.cdc.xmlread = True + wd = self.wait_for_data() + info = self.xml.getlog(wd) + rsp = self.xml.getresponse(wd) + if "value" in rsp: + if rsp["value"] != "ACK": + self.error(f"Error:") + for line in info: + self.error(line) + return response(resp=False, data=resData, error=info) + elif "rawmode" in rsp: + if rsp["rawmode"] == "false": + return response(resp=True, data=resData) + else: + if len(rsp) > 1: + if b"Failed to open the UFS Device" in rsp[2]: + self.error(f"Error:{rsp[2]}") + self.lasterror = rsp[2] + return response(resp=False, data=resData, error=rsp[2]) + if rsp["value"] != "ACK": + self.lasterror = rsp[2] + if display and prog != 100: + progbar.show_progress(prefix="Read", pos=total, total=total, display=display) + resp = rsp["value"] == "ACK" + return response(resp=resp, data=resData, error=rsp[2]) # Do not remove, needed for oneplus + + def get_gpt(self, lun, gpt_num_part_entries, gpt_part_entry_size, gpt_part_entry_start_lba, start_sector=1): + try: + resp = self.cmd_read_buffer(lun, 0, 1, False) + except Exception as err: + self.debug(str(err)) + self.skipresponse = True + resp = self.cmd_read_buffer(lun, 0, 1, False) + + if not resp.resp: + for line in resp.error: + self.error(line) + return None, None + data = resp.data + magic = unpack(" 64: + sectors = 64 + data += self.cmd_read_buffer(lun, header.part_entry_start_lba, sectors, False).data + if data == b"": + return None, None + guid_gpt.parse(data, self.cfg.SECTOR_SIZE_IN_BYTES) + return data, guid_gpt + else: + return None, None + except Exception as err: + self.debug(str(err)) + return None, None + + def get_backup_gpt(self, lun, gpt_num_part_entries, gpt_part_entry_size, gpt_part_entry_start_lba): + resp = self.cmd_read_buffer(lun, 0, 2, False) + if not resp.resp: + self.error("Error on reading backup gpt") + return None + guid_gpt = gpt( + num_part_entries=gpt_num_part_entries, + part_entry_size=gpt_part_entry_size, + part_entry_start_lba=gpt_part_entry_start_lba, + loglevel=self.__logger.level + ) + header = guid_gpt.parseheader(resp.data, self.cfg.SECTOR_SIZE_IN_BYTES) + if "backup_lba" in header: + sectors = header.first_usable_lba - 1 + data = self.cmd_read_buffer(lun, header.backup_lba, sectors, False) + if data == b"": + return None + return data + else: + return None + + def calc_offset(self, sector, offset): + sector = sector + (offset // self.cfg.SECTOR_SIZE_IN_BYTES) + offset = offset % self.cfg.SECTOR_SIZE_IN_BYTES + return sector, offset + + def getluns(self, argument): + if argument["--lun"] is not None: + return [int(argument["--lun"])] + + luns = [] + if self.cfg.MemoryName.lower() == "ufs": + for i in range(0, self.cfg.maxlun): + luns.append(i) + else: + luns = [0] + return luns + + def configure(self, lvl): + if self.cfg.SECTOR_SIZE_IN_BYTES == 0: + if self.cfg.MemoryName.lower() == "emmc": + self.cfg.SECTOR_SIZE_IN_BYTES = 512 + else: + self.cfg.SECTOR_SIZE_IN_BYTES = 4096 + + connectcmd = f"" + \ + f"" + ''' + "" \ + "" + ''' + rsp = self.xmlsend(connectcmd) + if not rsp.resp: + if not rsp.data and not rsp.error: + # Target is completely silent. Most loaders hang in storage_device_open() in this case, + # which they tell you themselves: "If this hangs use SkipStorageInit='1' for configure" + if not self.cfg.SkipStorageInit: + self.warning("Loader didn't respond to configure, retrying with SkipStorageInit=1 " + + "(loader seems to hang in storage_device_open)") + self.cfg.SkipStorageInit = 1 + return self.configure(lvl + 1) + self.error("Loader didn't respond to configure even with SkipStorageInit=1, it seems to be " + + "incompatible with this device.\n" + + f"Loader used: {self.loader_programmer}\n" + + "Try another loader with --loader, or another memory type with --memory.") + return False + if rsp.error == "": + try: + if "MemoryName" in rsp.data: + self.cfg.MemoryName = rsp.data["MemoryName"] + except TypeError: + self.warning("!DEBUG! rsp.data: '%s'" % (rsp.data,)) + return self.configure(lvl + 1) + if "MaxPayloadSizeFromTargetInBytes" in rsp.data: + self.cfg.MaxPayloadSizeFromTargetInBytes = int(rsp.data["MaxPayloadSizeFromTargetInBytes"]) + if "MaxPayloadSizeToTargetInBytes" in rsp.data: + self.cfg.MaxPayloadSizeToTargetInBytes = int(rsp.data["MaxPayloadSizeToTargetInBytes"]) + if "MaxPayloadSizeToTargetInBytesSupported" in rsp.data: + self.cfg.MaxPayloadSizeToTargetInBytesSupported = int( + rsp.data["MaxPayloadSizeToTargetInBytesSupported"]) + if "TargetName" in rsp.data: + self.cfg.TargetName = rsp.data["TargetName"] + if lvl >= 4: + self.error(f"Loader didn't accept configure ({rsp.data})") + return False + return self.configure(lvl + 1) + for line in rsp.error: + if "Not support configure MemoryName eMMC" in line: + self.info("eMMC is not supported by the firehose loader. Trying UFS instead.") + self.cfg.MemoryName = "UFS" + return self.configure(lvl + 1) + elif "Only nop and sig tag can be" in line: + self.info("Xiaomi EDL Auth detected.") + try: + self.modules = modules(fh=self, serial=self.serial, + supported_functions=self.supported_functions, + loglevel=self.__logger.level, + devicemodel=self.devicemodel, args=self.args) + except Exception as err: # pylint: disable=broad-except + self.modules = None + if self.modules.edlauth(): + self.info("EDL Authenticated successfully.") + rsp = self.xmlsend(connectcmd) + return rsp.resp + else: + self.error("Error on EDL Authentification") + return False + elif "MaxPayloadSizeToTargetInBytes" in rsp.data: + try: + self.cfg.MemoryName = rsp.data["MemoryName"] + self.cfg.MaxPayloadSizeToTargetInBytes = int(rsp.data["MaxPayloadSizeToTargetInBytes"]) + self.cfg.MaxPayloadSizeToTargetInBytesSupported = int( + rsp.data["MaxPayloadSizeToTargetInBytesSupported"]) + if "MaxXMLSizeInBytes" in rsp.data: + self.cfg.MaxXMLSizeInBytes = int(rsp.data["MaxXMLSizeInBytes"]) + else: + self.cfg.MaxXMLSizeInBytes = 4096 + if "MaxPayloadSizeFromTargetInBytes" in rsp.data: + self.cfg.MaxPayloadSizeFromTargetInBytes = int(rsp.data["MaxPayloadSizeFromTargetInBytes"]) + else: + self.cfg.MaxPayloadSizeFromTargetInBytes = 4096 + if "TargetName" in rsp.data: + self.cfg.TargetName = rsp.data["TargetName"] + else: + self.cfg.TargetName = "Unknown" + if "MSM" not in self.cfg.TargetName: + self.cfg.TargetName = "MSM" + self.cfg.TargetName + if "Version" in rsp.data: + self.cfg.Version = rsp.data["Version"] + else: + self.cfg.Version = "Unknown" + if lvl == 0: + return self.configure(lvl + 1) + else: + self.error(f"Error:{rsp}") + sys.exit() + except Exception as e: + pass + elif "ERROR" in line or "WARN" in line: + if "ERROR" in line: + self.error(line) + sys.exit() + elif "WARN" in line: + self.warning(line) + else: + info = self.cdc.read(timeout=1) + if isinstance(rsp.resp, dict): + field = rsp.resp + if "MemoryName" not in field: + # print(rsp[1]) + field["MemoryName"] = "eMMC" + if "MaxXMLSizeInBytes" not in field: + field["MaxXMLSizeInBytes"] = "4096" + self.warning("Couldn't detect MaxPayloadSizeFromTargetinBytes") + if "MaxPayloadSizeToTargetInBytes" not in field: + field["MaxPayloadSizeToTargetInBytes"] = "1038576" + if "MaxPayloadSizeToTargetInBytesSupported" not in field: + field["MaxPayloadSizeToTargetInBytesSupported"] = "1038576" + if field["MemoryName"].lower() != self.cfg.MemoryName.lower(): + self.warning("Memory type was set as " + self.cfg.MemoryName + " but device reported it is " + + field["MemoryName"] + " instead.") + self.cfg.MemoryName = field["MemoryName"] + if "MaxPayloadSizeToTargetInBytes" in field: + self.cfg.MaxPayloadSizeToTargetInBytes = int(field["MaxPayloadSizeToTargetInBytes"]) + else: + self.cfg.MaxPayloadSizeToTargetInBytes = 1048576 + if "MaxPayloadSizeToTargetInBytesSupported" in field: + self.cfg.MaxPayloadSizeToTargetInBytesSupported = int( + field["MaxPayloadSizeToTargetInBytesSupported"]) + else: + self.cfg.MaxPayloadSizeToTargetInBytesSupported = 1048576 + if "MaxXMLSizeInBytes" in field: + self.cfg.MaxXMLSizeInBytes = int(field["MaxXMLSizeInBytes"]) + else: + self.cfg.MaxXMLSizeInBytes = 4096 + if "MaxPayloadSizeFromTargetInBytes" in field: + self.cfg.MaxPayloadSizeFromTargetInBytes = int(field["MaxPayloadSizeFromTargetInBytes"]) + else: + self.cfg.MaxPayloadSizeFromTargetInBytes = self.cfg.MaxXMLSizeInBytes + self.warning("Couldn't detect MaxPayloadSizeFromTargetinBytes") + if "TargetName" in field: + self.cfg.TargetName = field["TargetName"] + if "MSM" not in self.cfg.TargetName: + self.cfg.TargetName = "MSM" + self.cfg.TargetName + else: + self.cfg.TargetName = "Unknown" + self.warning("Couldn't detect TargetName") + if "Version" in field: + self.cfg.Version = field["Version"] + else: + self.cfg.Version = 0 + self.warning("Couldn't detect Version") + self.info(f"TargetName={self.cfg.TargetName}") + self.info(f"MemoryName={self.cfg.MemoryName}") + self.info(f"Version={self.cfg.Version}") + self.info("Trying to read first storage sector...") + rsp = self.cmd_read_buffer(0, 1, 1, False) + self.info("Running configure...") + if not rsp.resp and self.args["--memory"] is None: + for line in rsp.error: + if "Failed to set the IO options" in line: + self.warning( + "Memory type eMMC doesn't seem to match (Failed to init). Trying to use NAND instead.") + self.cfg.MemoryName = "nand" + return self.configure(0) + elif "Failed to open the SDCC Device" in line: + self.warning( + "Memory type eMMC doesn't seem to match (Failed to init). Trying to use UFS instead.") + self.cfg.MemoryName = "UFS" + return self.configure(0) + elif "Failed to initialize (open whole lun) UFS Device slot" in line: + self.warning( + "Memory type UFS doesn't seem to match (Failed to init). Trying to use eMMC instead.") + self.cfg.MemoryName = "eMMC" + return self.configure(0) + if not rsp.resp: + for line in rsp.error: + if "Attribute \'SECTOR_SIZE_IN_BYTES\'=4096 must be equal to disk sector size 512" in line \ + or "different from device sector size (512)" in line: + self.cfg.SECTOR_SIZE_IN_BYTES = 512 + return self.configure(0) + elif "Attribute \'SECTOR_SIZE_IN_BYTES\'=4096 must be equal to disk sector size 2048" in line \ + or "different from device sector size (2048)" in line: + self.cfg.SECTOR_SIZE_IN_BYTES = 2048 + return self.configure(0) + elif "Attribute \'SECTOR_SIZE_IN_BYTES\'=512 must be equal to disk sector size 4096" in line \ + or "different from device sector size (4096)" in line: + self.cfg.SECTOR_SIZE_IN_BYTES = 4096 + return self.configure(0) + self.parse_storage() + for function in self.supported_functions: + if function == "checkntfeature": + if type(self.devicemodel) == list: + self.devicemodel = self.devicemodel[0] + self.nothing = nothing(fh=self, projid=self.devicemodel, serial=self.serial, + supported_functions=self.supported_functions, + loglevel=self.loglevel) + if self.nothing is not None: + self.nothing.ntprojectverify() + self.luns = self.getluns(self.args) + return True + + def getlunsize(self, lun): + if lun not in self.lunsizes: + try: + data, guid_gpt = self.get_gpt( + lun, + int(self.args.get("--gpt-num-part-entries") or 0), + int(self.args.get("--gpt-part-entry-size") or 0), + int(self.args.get("--gpt-part-entry-start-lba") or 0), + ) + self.lunsizes[lun] = guid_gpt.totalsectors + except Exception as err: + self.error(err) + return -1 + else: + return self.lunsizes[lun] + return guid_gpt.totalsectors + + def get_supported_functions(self): + supfunc = False + info = self.cmd_nop() + if not info: + self.info("No supported functions detected, configuring qc generic commands") + self.supported_functions = ['configure', 'program', 'firmwarewrite', 'patch', 'setbootablestoragedrive', + 'ufs', 'emmc', 'power', 'benchmark', 'read', 'getstorageinfo', + 'getcrc16digest', 'getsha256digest', 'erase', 'peek', 'poke', 'nop', 'xml'] + else: + self.supported_functions = [] + for line in info: + if "chip serial num" in line.lower(): + self.info(line) + try: + serial = line.split("0x")[1][:-1] + self.serial = int(serial, 16) + except Exception as err: # pylint: disable=broad-except + self.debug(str(err)) + serial = line.split(": ")[2] + self.serial = int(serial.split(" ")[0]) + if supfunc and "end of supported functions" not in line.lower(): + rs = line.replace("\n", "") + if rs != "": + rs = rs.replace("INFO: ", "") + self.supported_functions.append(rs) + if "supported functions" in line.lower(): + supfunc = True + + if len(self.supported_functions) > 1: + info = "Supported Functions: " + for line in self.supported_functions: + info += line + "," + self.info(info[:-1]) + data = self.cdc.read(timeout=None) + try: + self.info(data.decode('utf-8')) + except Exception as err: # pylint: disable=broad-except + self.debug(str(err)) + pass + + if not self.supported_functions: + self.supported_functions = ['configure', 'program', 'firmwarewrite', 'patch', 'setbootablestoragedrive', + 'ufs', 'emmc', 'power', 'benchmark', 'read', 'getstorageinfo', + 'getcrc16digest', 'getsha256digest', 'erase', 'peek', 'poke', 'nop', 'xml'] + + def connect(self): + v = b'-1' + if platform.system() == 'Windows': + self.cdc.timeout = 50 + elif platform.system() == 'Darwin': + # must ensure the timeout is enough to fill the buffer we alloc + # which is 1MB, othwise some data are dropped in the underlying usb libraries + self.cdc.timeout = 50 + else: + self.cdc.timeout = 50 + info = [] + while v != b'': + try: + v = self.cdc.read(timeout=None) + if (b"response" in v and b"" in v) or v == b'': + break + data = self.xml.getlog(v) + if len(data) > 0: + info.append(data[0]) + if not info: + break + except Exception as err: # pylint: disable=broad-except + pass + + if info == [] or (len(info) > 0 and 'ERROR' in info[0]): + if len(info) > 0: + self.debug(info[0]) + if len(info) > 0: + supfunc = False + for line in info: + self.info(line) + if "chip serial num" in line.lower(): + try: + serial = line.split("0x")[1][:-1] + if ")" in serial: + serial = serial[:serial.rfind(")")] + self.serial = int(serial, 16) + except Exception as err: # pylint: disable=broad-except + self.debug(str(err)) + serial = line.split(": ")[2] + self.serial = int(serial.split(" ")[0]) + if supfunc and "end of supported functions" not in line.lower(): + rs = line.replace("\n", "") + if rs != "": + rs = rs.replace("INFO: ", "") + self.supported_functions.append(rs) + if "supported functions" in line.lower(): + supfunc = True + if "program" in line.lower(): + idx = line.find("Functions: ") + if idx != -1: + v = line[idx + 11:].split(" ") + for val in v: + if val != "": + self.supported_functions.append(val) + supfunc = False + try: + if os.path.exists(self.cfg.programmer): + data = open(self.cfg.programmer, "rb").read() + for cmd in [b"demacia", b"setprojmodel", b"setswprojmodel", b"setprocstart", b"SetNetType", + b"checkntfeature"]: + if cmd in data: + self.supported_functions.append(cmd.decode('utf-8')) + state = { + "supported_functions": self.supported_functions, + "programmer": self.cfg.programmer, + "serial": self.serial + } + if os.path.exists("edl_config.json"): + data = json.loads(open("edl_config.json", "rb").read().decode('utf-8')) + if "serial" in data and data["serial"] != state["serial"]: + open("edl_config.json", "w").write(json.dumps(state)) + else: + self.supported_functions = data["supported_functions"] + self.cfg.programmer = data["programmer"] + else: + open("edl_config.json", "w").write(json.dumps(state)) + if "001920e101cf0000_fa2836525c2aad8a_fhprg.bin" in self.cfg.programmer: + self.devicemodel = '20111' + elif "000b80e100020000_467f3020c4cc788d_fhprg.bin" in self.cfg.programmer: + self.devicemodel = '22111' + except: + pass + + elif self.serial is None or self.supported_functions is []: + try: + if os.path.exists("edl_config.json"): + pinfo = json.loads(open("edl_config.json", "rb").read()) + if not self.supported_functions: + if "supported_functions" in pinfo: + self.supported_functions = pinfo["supported_functions"] + if self.serial is None: + if "serial" in pinfo: + self.serial = pinfo["serial"] + else: + self.get_supported_functions() + except: + self.get_supported_functions() + pass + + # rsp = self.xmlsend(data, self.skipresponse) + + return self.supported_functions + + def parse_storage(self): + storageinfo, res = self.cmd_getstorageinfo() + if res is None or res.resp and len(res.data) == 0: + return False + info = res.data + if "UFS Inquiry Command Output" in info: + self.cfg.prod_name = info["UFS Inquiry Command Output"] + self.info(info) + if "UFS Erase Block Size" in info: + self.cfg.block_size = int(info["UFS Erase Block Size"], 16) + self.info(info) + self.cfg.MemoryName = "UFS" + self.cfg.SECTOR_SIZE_IN_BYTES = 4096 + if "UFS Boot Partition Enabled" in info: + self.info(info["UFS Boot Partition Enabled"]) + if "UFS Total Active LU" in info: + self.cfg.maxlun = int(info["UFS Total Active LU"], 16) + if "SECTOR_SIZE_IN_BYTES" in info: + self.cfg.SECTOR_SIZE_IN_BYTES = int(info["SECTOR_SIZE_IN_BYTES"]) + if "num_physical_partitions" in info: + self.cfg.num_physical = int(info["num_physical_partitions"]) + return True + + # OEM Stuff here below -------------------------------------------------- + + def cmd_writeimei(self, imei): + if len(imei) != 16: + self.info("IMEI must be 16 digits") + return False + data = '' + val = self.xmlsend(data) + if val.resp: + self.info("writeIMEI succeeded.") + return True + else: + self.error("writeIMEI failed.") + return False + + def cmd_getstorageinfo(self): + data = '' + val = self.xmlsend(data) + if val.data == '' and val.log == '' and val.resp: + return None + if isinstance(val.data, dict): + if "bNumberLu" in val.data: + self.cfg.maxlun = int(val.data["bNumberLu"]) + if val.resp: + if val.log is not None: + res = {} + for value in val.log: + v = value.split("=") + if len(v) > 1: + res[v[0]] = v[1] + else: + if '"storage_info"' in value: + try: + info = value.replace("INFO:", "") + si = json.loads(info)["storage_info"] + except Exception as err: # pylint: disable=broad-except + self.debug(str(err)) + continue + self.info("Storage report:") + for sii in si: + self.info(f"{sii}:{si[sii]}") + if "total_blocks" in si: + self.cfg.total_blocks = si["total_blocks"] + if "num_physical" in si: + self.cfg.num_physical = si["num_physical"] + self.cfg.maxlun = self.cfg.num_physical + if "block_size" in si: + self.cfg.block_size = si["block_size"] + if "page_size" in si: + self.cfg.SECTOR_SIZE_IN_BYTES = si["page_size"] + if "mem_type" in si: + self.cfg.MemoryName = si["mem_type"] + if "prod_name" in si: + self.cfg.prod_name = si["prod_name"] + return value, response(resp=val.resp, data=res) + else: + v = value.split(":") + if len(v) > 1: + res[v[0]] = v[1].lstrip(" ") + return None, response(resp=val.resp, data=res) + return None, response(resp=val.resp, data=val.data) + else: + if val.error: + for v in val.error: + if "Failed to open the SDCC Device" in v: + self.cfg.MemoryName = "ufs" + self.configure(0) + return self.cmd_getstorageinfo() + self.warning("GetStorageInfo command isn't supported.") + return None, None + + def cmd_setactiveslot(self, slot: str): + # flags: 0x3a for inactive and 0x6f for active boot partition + def set_flags(flags, active, is_boot): + new_flags = flags + if active: + if is_boot: + #new_flags |= (PART_ATT_PRIORITY_VAL | PART_ATT_ACTIVE_VAL | PART_ATT_MAX_RETRY_COUNT_VAL) + #new_flags &= (~PART_ATT_SUCCESSFUL_VAL & ~PART_ATT_UNBOOTABLE_VAL) + new_flags = 0x6f << (AB_FLAG_OFFSET * 8) + else: + new_flags |= AB_PARTITION_ATTR_SLOT_ACTIVE << (AB_FLAG_OFFSET * 8) + else: + if is_boot: + #new_flags &= (~PART_ATT_PRIORITY_VAL & ~PART_ATT_ACTIVE_VAL) + #new_flags |= ((MAX_PRIORITY-1) << PART_ATT_PRIORITY_BIT) + new_flags = 0x3a << (AB_FLAG_OFFSET * 8) + else: + new_flags &= ~(AB_PARTITION_ATTR_SLOT_ACTIVE << (AB_FLAG_OFFSET * 8)) + return new_flags + + def patch_helper(gpt_data_a, gpt_data_b, guid_gpt_a, guid_gpt_b, partition_a, partition_b, slot_a_status, + slot_b_status, is_boot): + part_entry_size = guid_gpt_a.header.part_entry_size + + rf_a = BytesIO(gpt_data_a) + rf_b = BytesIO(gpt_data_b) + + entryoffset_a = partition_a.entryoffset - ( + (guid_gpt_a.header.part_entry_start_lba - 2) * guid_gpt_a.sectorsize) + entryoffset_b = partition_b.entryoffset - ( + (guid_gpt_b.header.part_entry_start_lba - 2) * guid_gpt_b.sectorsize) + rf_a.seek(entryoffset_a) + rf_b.seek(entryoffset_b) + + sdata_a = rf_a.read(part_entry_size) + sdata_b = rf_b.read(part_entry_size) + + partentry_a = gpt.gpt_partition(sdata_a) + partentry_b = gpt.gpt_partition(sdata_b) + + partentry_a.flags = set_flags(partentry_a.flags, slot_a_status, is_boot) + partentry_b.flags = set_flags(partentry_b.flags, slot_b_status, is_boot) + partentry_a.type, partentry_b.type = partentry_b.type, partentry_a.type + + pdata_a, pdata_b = partentry_a.create(), partentry_b.create() + return pdata_a, partition_a.entryoffset, pdata_b, partition_b.entryoffset + + def cmd_patch_multiple(lun, start_sector, byte_offset, patch_data): + offset = 0 + size_each_patch = 8 if len(patch_data) % 8 == 0 else 4 + unpack_fmt = "> ( + AB_FLAG_OFFSET * 8)) & 0xFF) & AB_PARTITION_ATTR_SLOT_ACTIVE == AB_PARTITION_ATTR_SLOT_ACTIVE + if (active_a and slot_a_status) or (not active_a and slot_b_status): + return True + + partitionname_b = partitionname_a[:-1] + "b" + if partitionname_b in guid_gpt_a.partentries: + lun_b = lun_a + gpt_data_b = gpt_data_a + guid_gpt_b = guid_gpt_a + backup_gpt_data_b = backup_gpt_data_a + backup_guid_gpt_b = backup_guid_gpt_a + else: + resp = self.detect_partition(arguments=None, + partitionname=partitionname_b, + send_full=True) + if not resp[0]: + self.error(f"Cannot find partition {partitionname_b}") + return False + _, lun_b, gpt_data_b, guid_gpt_b = resp + backup_gpt_data_b, backup_guid_gpt_b = self.get_gpt(lun_b, 0, 0, 0, + guid_gpt_b.header.backup_lba) + + if not check_gpt_hdr and partitionname_a[ + :3] != "xbl": # xbl partition don't need check consistency + sts, gpt_data_a, backup_gpt_data_a = ensure_gpt_hdr_consistency(guid_gpt_a, + backup_guid_gpt_a, + gpt_data_a, + backup_gpt_data_a) + if not sts: + return False + if lun_a != lun_b: + sts, gpt_data_b, backup_gpt_data_b = ensure_gpt_hdr_consistency(guid_gpt_b, + backup_guid_gpt_b, + gpt_data_b, + backup_gpt_data_b) + if not sts: + return False + check_gpt_hdr = True + + update_gpt_info(guid_gpt_a, guid_gpt_b, + partitionname_a, partitionname_b, + gpt_data_a, gpt_data_b, + slot_a_status, slot_b_status, + lun_a, lun_b) + + # update the backup gpt header as well, depending on the xbl implementation in case of + # discording GPTs the backup may be used, thus negating the switch + update_gpt_info(backup_guid_gpt_a, backup_guid_gpt_b, + partitionname_a, partitionname_b, + backup_gpt_data_a, backup_gpt_data_b, + slot_a_status, slot_b_status, + lun_a, lun_b) + + except Exception as err: + self.error(str(err)) + return False + return True + + def cmd_test(self, cmd): + token = "1234" + pk = "1234" + data = f'\n\n<{cmd} token="{token}" pk="{pk}" />\n' + val = self.xmlsend(data) + if val.resp: + if b"raw hex token" in val[2]: + return True + if b"opcmd is not enabled" in val[2]: + return True + return False + + def cmd_getstorageinfo_string(self): + data = '' + val = self.xmlsend(data) + if val.resp: + self.info(f"GetStorageInfo:\n--------------------\n") + data = self.xml.getlog(val.data) + for line in data: + self.info(line) + return True + else: + self.warning("GetStorageInfo command isn't supported.") + return False + + def cmd_poke(self, address, data, filename="", info=False): + rf = None + if filename != "": + rf = open(filename, "rb") + SizeInBytes = os.stat(filename).st_size + else: + SizeInBytes = len(data) + if info: + self.info(f"Poke: Address({hex(address)}),Size({hex(SizeInBytes)})") + ''' + + ''' + maxsize = 8 + lengthtowrite = SizeInBytes + if lengthtowrite < maxsize: + maxsize = lengthtowrite + pos = 0 + old = 0 + datawritten = 0 + mode = 0 + if info: + print_progress(0, 100, prefix='Progress:', suffix='Complete', bar_length=50) + while lengthtowrite > 0: + if rf is not None: + content = hex(int(hexlify(rf.read(maxsize)).decode('utf-8'), 16)) + else: + content = 0 + if lengthtowrite < maxsize: + maxsize = lengthtowrite + for i in range(0, maxsize): + content = (content << 8) + int( + hexlify(data[pos + maxsize - i - 1:pos + maxsize - i]).decode('utf-8'), 16) + # content=hex(int(hexlify(data[pos:pos+maxsize]).decode('utf-8'),16)) + content = hex(content) + if mode == 0: + xdata = f"\n" + else: + xdata = f"\n" + try: + self.cdc.write(xdata[:self.cfg.MaxXMLSizeInBytes]) + except Exception as err: # pylint: disable=broad-except + self.debug(str(err)) + pass + addrinfo = self.cdc.read(timeout=None) + if b"SizeInBytes" in addrinfo or b"Invalid parameters" in addrinfo: + tmp = b"" + while b"NAK" not in tmp and b"ACK" not in tmp: + tmp += self.cdc.read(timeout=None) + xdata = f"\n" + self.cdc.write(xdata[:self.cfg.MaxXMLSizeInBytes]) + addrinfo = self.cdc.read(timeout=None) + if (b' old: + print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) + old = prog + if info: + self.info("Done writing.") + return True + + def cmd_peek(self, address, SizeInBytes, filename="", info=False): + if info: + self.info(f"Peek: Address({hex(address)}),Size({hex(SizeInBytes)})") + wf = None + if filename != "": + wf = open(filename, "wb") + ''' + + ''' + data = f"\n" + ''' + + + ''' + try: + self.cdc.write(data[:self.cfg.MaxXMLSizeInBytes]) + except Exception as err: # pylint: disable=broad-except + self.debug(str(err)) + pass + addrinfo = self.cdc.read(timeout=None) + if b"SizeInBytes" in addrinfo or b"Invalid parameters" in addrinfo: + tmp = b"" + while b"NAK" not in tmp and b"ACK" not in tmp: + tmp += self.cdc.read(timeout=None) + data = f"" + self.cdc.write(data[:self.cfg.MaxXMLSizeInBytes]) + addrinfo = self.cdc.read(timeout=None) + if (b'" and len(received_data) > 0: + received_data = self.cdc.read(timeout=None) + tmp += received_data + if b' old: + print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) + old = prog + + if wf is not None: + wf.close() + if (b' 0: + for offset in offsets: + error = 0 + rt = offset + len(t[0]) + for i in range(1, len(t)): + if t[i] == b'': + rt += 1 + continue + rt += 1 + prep = data[rt:].find(t[i]) + if prep != 0: + error = 1 + break + rt += len(t[i]) + if error == 0: + return offset + pos + else: + return None + else: + offsets.append(pre) + pre += 1 + return None + + +class progress: + def __init__(self, pagesize): + self.progtime = 0 + self.prog = 0 + self.progpos = 0 + self.start = time.time() + self.pagesize = pagesize + + def calcProcessTime(self, starttime, cur_iter, max_iter): + telapsed = time.time() - starttime + if telapsed > 0 and cur_iter > 0: + testimated = (telapsed / cur_iter) * max_iter + finishtime = starttime + testimated + finishtime = dt.datetime.fromtimestamp(finishtime).strftime("%H:%M:%S") # in time + lefttime = testimated - telapsed # in seconds + return int(telapsed), int(lefttime), finishtime + else: + return 0, 0, "" + + def show_progress(self, prefix, pos, total, display=True): + if pos > total: + pos = total + if pos != 0: + prog = round(float(pos) / float(total) * float(100), 1) + else: + prog = 0 + if prog == 0: + self.prog = 0 + self.start = time.time() + self.progtime = time.time() + self.progpos = pos + self._emit_bytes(pos, total) + if display: + print_progress(prog, 100, prefix='Done', + suffix=prefix + ' (Sector 0x%X of 0x%X) %0.2f MB/s' % + (pos // self.pagesize, + total // self.pagesize, + 0), bar_length=10) + + if prog > self.prog or prog == 100.0: + t0 = time.time() + if display: + tdiff = t0 - self.progtime + datasize = (pos - self.progpos) / 1024 / 1024 + if datasize != 0 and tdiff != 0: + try: + throughput = datasize / tdiff + except: + throughput = 0 + else: + throughput = 0 + telapsed, lefttime, finishtime = self.calcProcessTime(self.start, prog, 100) + hinfo = "" + if lefttime > 0: + sec = lefttime + if sec > 60: + min = sec // 60 + sec = sec % 60 + if min > 60: + h = min // 24 + min = min % 24 + hinfo = "%02dh:%02dm:%02ds left" % (h, min, sec) + else: + hinfo = "%02dm:%02ds left" % (min, sec) + else: + hinfo = "%02ds left" % sec + print_progress(prog, 100, prefix='Progress:', + suffix=prefix + f' (Sector 0x%X of 0x%X, {hinfo}) %0.2f MB/s' % + (pos // self.pagesize, + total // self.pagesize, + throughput), bar_length=10) + self._emit_rate(prefix, pos, t0) + self._emit_bytes(pos, total) + self.prog = prog + self.progpos = pos + self.progtime = t0 + + def _emit_rate(self, prefix, pos, now): + kind = "" + lowered = prefix.lower() + if lowered.startswith("write"): + kind = "W" + elif lowered.startswith("read"): + kind = "R" + if not kind or pos <= 0: + return + if now - getattr(self, "rate_time", 0) < 0.4: + return + elapsed = now - self.start + if elapsed <= 0: + return + shown = int(round((pos / 1024 / 1024) / elapsed)) + if shown < 1: + shown = 1 + self.rate_time = now + sys.stdout.write(f"\nFLASHER\tRATE\t{kind}:{shown}mb/s\n") + sys.stdout.flush() + + def _emit_bytes(self, pos, total): + done = int(getattr(self, "byte_base", 0) + pos) + whole = getattr(self, "byte_span", None) + whole = int(whole if whole else total) + now = time.time() + if pos < total and now - getattr(self, "byte_time", 0) < 0.4: + return + self.byte_time = now + sys.stdout.write(f"\nFLASHER\tBYTES\t{done}\t{whole}\n") + sys.stdout.flush() + + +class structhelper: + pos = 0 + + def __init__(self, data, pos=0): + self.pos = 0 + self.data = data + + def qword(self, big=False): + e = ">" if big else "<" + dat = unpack(e + "Q", self.data[self.pos:self.pos + 8])[0] + self.pos += 8 + return dat + + def dword(self, big=False): + e = ">" if big else "<" + dat = unpack(e + "I", self.data[self.pos:self.pos + 4])[0] + self.pos += 4 + return dat + + def dwords(self, dwords=1, big=False): + e = ">" if big else "<" + dat = unpack(e + str(dwords) + "I", self.data[self.pos:self.pos + 4 * dwords]) + self.pos += 4 * dwords + return dat + + def qwords(self, qwords=1, big=False): + e = ">" if big else "<" + dat = unpack(e + str(qwords) + "Q", self.data[self.pos:self.pos + 8 * qwords]) + self.pos += 8 * qwords + return dat + + def short(self, big=False): + e = ">" if big else "<" + dat = unpack(e + "H", self.data[self.pos:self.pos + 2])[0] + self.pos += 2 + return dat + + def shorts(self, shorts, big=False): + e = ">" if big else "<" + dat = unpack(e + str(shorts) + "H", self.data[self.pos:self.pos + 2 * shorts]) + self.pos += 2 * shorts + return dat + + def bytes(self, rlen=1): + dat = self.data[self.pos:self.pos + rlen] + self.pos += rlen + if rlen == 1: return dat[0] + return dat + + def string(self, rlen=1): + dat = self.data[self.pos:self.pos + rlen] + self.pos += rlen + return dat + + def getpos(self): + return self.pos + + def seek(self, pos): + self.pos = pos + + +def do_tcp_server(client, arguments, handler): + def tcpprint(arg): + if isinstance(arg, bytes) or isinstance(arg, bytearray): + return connection.sendall(arg) + else: + return connection.sendall(bytes(str(arg), 'utf-8')) + + client.printer = tcpprint + import socket + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + port = int(arguments["--tcpport"]) + server_address = ('localhost', port) + print('starting up on %s port %s' % server_address) + sock.bind(server_address) + sock.listen(1) + response = None + while True: + print('waiting for a connection') + connection, client_address = sock.accept() + try: + print('connection from', client_address) + while True: + data = connection.recv(4096).decode('utf-8') + if data == '': + break + print('received %s' % data) + if data: + print('handling request') + lines = data.split("\n") + for line in lines: + if ":" in line: + cmd = line.split(":")[0] + marguments = line.split(":")[1] + try: + opts = parse_args(cmd, marguments, arguments) + except: + response = "Wrong arguments\n\n" + opts = None + if opts is not None: + if handler(cmd, opts): + response = "\n" + else: + response = "\n" + connection.sendall(bytes(response, 'utf-8')) + finally: + connection.close() + + +def parse_args(cmd, args, mainargs): + options = {} + opts = None + if "," in args: + opts = args.split(",") + else: + opts = [args] + for arg in mainargs: + if "--" in arg: + options[arg] = mainargs[arg] + if cmd == "gpt": + options[""] = opts[0] + elif cmd == "r": + options[""] = opts[0] + options[""] = opts[1] + elif cmd == "rl": + options[""] = opts[0] + elif cmd == "rf": + options[""] = opts[0] + elif cmd == "rs": + options[""] = opts[0] + options[""] = opts[1] + options[""] = opts[2] + elif cmd == "w": + options[""] = opts[0] + options[""] = opts[0] + elif cmd == "wl": + options[""] = opts[0] + elif cmd == "wf": + options[""] = opts[0] + elif cmd == "ws": + options[""] = opts[0] + options[""] = opts[1] + elif cmd == "e": + options[""] = opts[0] + elif cmd == "es": + options[""] = opts[0] + options[""] = opts[1] + elif cmd == "footer": + options[""] = opts[0] + elif cmd == "peek": + options[""] = opts[0] + options[""] = opts[1] + options[""] = opts[2] + elif cmd == "peekhex": + options[""] = opts[0] + options[""] = opts[1] + elif cmd == "peekdword": + options[""] = opts[0] + elif cmd == "peekqword": + options[""] = opts[0] + elif cmd == "memtbl": + options[""] = opts[0] + elif cmd == "poke": + options[""] = opts[0] + options[""] = opts[1] + elif cmd == "pokehex": + options[""] = opts[0] + options[""] = opts[1] + elif cmd == "pokedword": + options[""] = opts[0] + options[""] = opts[1] + elif cmd == "pokeqword": + options[""] = opts[0] + options[""] = opts[1] + elif cmd == "memcpy": + options[""] = opts[0] + options[""] = opts[1] + elif cmd == "pbl": + options[""] = opts[0] + elif cmd == "qfp": + options[""] = opts[0] + elif cmd == "setbootablestoragedrive": + options[""] = opts[0] + elif cmd == "send": + options[""] = opts[0] + elif cmd == "xml": + options[""] = opts[0] + elif cmd == "rawxml": + options[""] = opts[0] + return options + + +def getint(valuestr): + try: + return int(valuestr) + except: + try: + return int(valuestr, 16) + except: + return 0 + + +class ColorFormatter(logging.Formatter): + LOG_COLORS = { + logging.ERROR: colorama.Fore.RED, + logging.DEBUG: colorama.Fore.LIGHTMAGENTA_EX, + logging.WARNING: colorama.Fore.YELLOW, + } + + def format(self, record, *args, **kwargs): + # if the corresponding logger has children, they may receive modified + # record, so we want to keep it intact + new_record = copy.copy(record) + if new_record.levelno in self.LOG_COLORS: + pad = "" + if new_record.name != "root": + print(new_record.name) + pad = "[LIB]: " + # we want levelname to be in different color, so let's modify it + new_record.msg = "{pad}{color_begin}{msg}{color_end}".format( + pad=pad, + msg=new_record.msg, + color_begin=self.LOG_COLORS[new_record.levelno], + color_end=colorama.Style.RESET_ALL, + ) + # now we can let standart formatting take care of the rest + return super(ColorFormatter, self).format(new_record, *args, **kwargs) + + +class LogBase(type): + debuglevel = logging.root.level + + def __init__(cls, *args): + super().__init__(*args) + logger_attribute_name = '_' + cls.__name__ + '__logger' + logger_debuglevel_name = '_' + cls.__name__ + '__debuglevel' + logger_name = '.'.join([c.__name__ for c in cls.mro()[-2::-1]]) + LOG_CONFIG = { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "root": { + "()": ColorFormatter, + "format": "%(name)s - %(message)s", + } + }, + "handlers": { + "root": { + # "level": cls.__logger.level, + "formatter": "root", + "class": "logging.StreamHandler", + "stream": "ext://sys.stdout", + } + }, + "loggers": { + "": { + "handlers": ["root"], + # "level": cls.debuglevel, + "propagate": False + } + }, + } + logging.config.dictConfig(LOG_CONFIG) + logger = logging.getLogger(logger_name) + + setattr(cls, logger_attribute_name, logger) + setattr(cls, logger_debuglevel_name, cls.debuglevel) + + +def del_rw(action, name, exc): + os.chmod(name, stat.S_IWRITE) + os.remove(name) + + +def rmrf(path): + if os.path.exists(path): + if os.path.isfile(path): + del_rw("", path, "") + else: + shutil.rmtree(path, onerror=del_rw) + + +class elf: + class memorysegment: + phy_addr = 0 + virt_start_addr = 0 + virt_end_addr = 0 + file_start_addr = 0 + file_end_addr = 0 + + def __init__(self, indata, filename): + self.data = indata + self.filename = filename + self.header, self.pentry = self.parse() + self.memorylayout = [] + for entry in self.pentry: + ms = self.memorysegment() + ms.phy_addr = entry.phy_addr + ms.virt_start_addr = entry.virt_addr + ms.virt_end_addr = entry.virt_addr + entry.seg_mem_len + ms.file_start_addr = entry.from_file + ms.file_end_addr = entry.from_file + entry.seg_file_len + self.memorylayout.append(ms) + + def getfileoffset(self, offset): + for memsegment in self.memorylayout: + if memsegment.virt_end_addr >= offset >= memsegment.virt_start_addr: + return offset - memsegment.virt_start_addr + memsegment.file_start_addr + return None + + def getvirtaddr(self, fileoffset): + for memsegment in self.memorylayout: + if memsegment.file_end_addr >= fileoffset >= memsegment.file_start_addr: + return memsegment.virt_start_addr + fileoffset - memsegment.file_start_addr + return None + + def getbaseaddr(self, offset): + for memsegment in self.memorylayout: + if memsegment.virt_end_addr >= offset >= memsegment.virt_start_addr: + return memsegment.virt_start_addr + return None + + class programentry: + p_type = 0 + from_file = 0 + virt_addr = 0 + phy_addr = 0 + seg_file_len = 0 + seg_mem_len = 0 + p_flags = 0 + p_align = 0 + + def parse_programentry(self, dat): + pe = self.programentry() + if self.elfclass == 1: + (pe.p_type, pe.from_file, pe.virt_addr, pe.phy_addr, pe.seg_file_len, pe.seg_mem_len, pe.p_flags, + pe.p_align) = struct.unpack("> 16 + a = ((offset + div) & 0xFFFF) + strasm = "" + if div > 0: + strasm += "# " + hex(offset) + "\n" + strasm += "mov " + reg + ", #" + hex(a) + ";\n" + strasm += "movk " + reg + ", #" + hex(abase) + ", LSL#16;\n" + strasm += "sub " + reg + ", " + reg + ", #" + hex(div) + ";\n" + else: + strasm += "# " + hex(offset) + "\n" + strasm += "mov " + reg + ", #" + hex(a) + ";\n" + strasm += "movk " + reg + ", #" + hex(abase) + ", LSL#16;\n" + strasm += "add " + reg + ", " + reg + ", #" + hex(-div) + ";\n" + return strasm + + def uart_valid_sc(self, sc): + badchars = [b'\x00', b'\n', b'\r', b'\x08', b'\x7f', b'\x20', b'\x09'] + for idx, c in enumerate(sc): + c = bytes([c]) + if c in badchars: + print("bad char 0x%s in SC at offset %d, opcode # %d!\n" % (codecs.encode(c, 'hex'), idx, idx / 4)) + print(codecs.encode(sc, 'hex')) + return False + return True + + def disasm(self, code, size): + cs = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN) + instr = [] + for i in cs.disasm(code, size): + # print("0x%x:\t%s\t%s" % (i.address, i.mnemonic, i.op_str)) + instr.append("%s\t%s" % (i.mnemonic, i.op_str)) + return instr + + def assembler(self, code): + ks = Ks(KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN) + if self.bDebug: + try: + encoding, count = ks.asm(code) + except KsError as e: + print(e) + print(e.stat_count) + print(code[e.stat_count:e.stat_count + 10]) + exit(0) + if self.bDebug: + # walk every line to find the (first) error + for idx, line in enumerate(code.splitlines()): + print("%02d: %s" % (idx, line)) + if len(line) and line[0] != '.': + try: + encoding, count = ks.asm(line) + except Exception as e: + print("bummer: " + str(e)) + else: + exit(0) + else: + encoding, count = ks.asm(code) + + sc = "" + count = 0 + out = "" + for i in encoding: + if self.cstyle: + out += ("\\x%02x" % i) + else: + out += ("%02x" % i) + sc += "%02x" % i + + count += 1 + # if bDebug and count % 4 == 0: + # out += ("\n") + + return out + + def find_binary(self, data, strf, pos=0): + t = strf.split(b".") + pre = 0 + offsets = [] + while pre != -1: + pre = data[pos:].find(t[0], pre) + if pre == -1: + if len(offsets) > 0: + for offset in offsets: + error = 0 + rt = offset + len(t[0]) + for i in range(1, len(t)): + if t[i] == b'': + rt += 1 + continue + rt += 1 + prep = data[rt:].find(t[i]) + if prep != 0: + error = 1 + break + rt += len(t[i]) + if error == 0: + return offset + else: + return None + else: + offsets.append(pre) + pre += 1 + return None + + +def read_object(data: object, definition: object) -> dict: + """ + Unpacks a structure using the given data and definition. + """ + obj = {} + object_size = 0 + pos = 0 + for (name, stype) in definition: + object_size += struct.calcsize(stype) + obj[name] = struct.unpack(stype, data[pos:pos + struct.calcsize(stype)])[0] + pos += struct.calcsize(stype) + obj['object_size'] = object_size + obj['raw_data'] = data + return obj + + +def write_object(definition, *args): + """ + Unpacks a structure using the given data and definition. + """ + obj = {} + object_size = 0 + data = b"" + i = 0 + for (name, stype) in definition: + object_size += struct.calcsize(stype) + arg = args[i] + try: + data += struct.pack(stype, arg) + except Exception as e: + print("Error:" + str(e)) + break + i += 1 + obj['object_size'] = len(data) + obj['raw_data'] = data + return obj + + +def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100): + """ + Call in a loop to create terminal progress bar + @params: + iteration - Required : current iteration (Int) + total - Required : total iterations (Int) + prefix - Optional : prefix string (Str) + suffix - Optional : suffix string (Str) + decimals - Optional : positive number of decimals in percent complete (Int) + bar_length - Optional : character length of bar (Int) + """ + str_format = "{:>5." + str(decimals) + "f}" + percents = str_format.format(100 * (iteration / float(total))) + filled_length = int(round(bar_length * iteration / float(total))) + bar = '█' * filled_length + '-' * (bar_length - filled_length) + + progstring = '\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix) + cols, _ = shutil.get_terminal_size() + progstring += " " * (cols - len(progstring) - 1) + sys.stdout.write(progstring) + + if iteration == total: + sys.stdout.write('\n') + sys.stdout.flush() diff --git a/flasher/runtime/worker.py b/flasher/runtime/worker.py new file mode 100644 index 0000000..29c5e80 --- /dev/null +++ b/flasher/runtime/worker.py @@ -0,0 +1,440 @@ +# 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)) diff --git a/flasher/src/main.rs b/flasher/src/main.rs index bb0d197..7ce8d7a 100644 --- a/flasher/src/main.rs +++ b/flasher/src/main.rs @@ -49,6 +49,8 @@ struct Device { status: String, rate: String, progress: i32, + bytes_done: u64, + bytes_total: u64, pending: Option, queued: bool, present: bool, @@ -62,6 +64,7 @@ enum EventMsg { Chip(String, String), Disk(String, String), Progress(String, i32), + Bytes(String, u64, u64), Status(String, String), Rate(String, String), Finished(String, &'static str), @@ -342,6 +345,14 @@ fn apply_line(line: &str, out: &mut WorkerOut, tx: &mpsc::Sender, loca let _ = tx.send(EventMsg::Progress(location.to_string(), n)); } } + "BYTES" => { + let mut nums = value.split('\t'); + if let (Some(done), Some(total)) = (nums.next(), nums.next()) { + if let (Ok(done), Ok(total)) = (done.parse::(), total.parse::()) { + let _ = tx.send(EventMsg::Bytes(location.to_string(), done, total)); + } + } + } "STATUS" => { let _ = tx.send(EventMsg::Status(location.to_string(), value)); } @@ -587,7 +598,7 @@ fn main() { table.set_col_resize(true); table.set_col_resize_min(48); table.set_type(TableRowSelectMode::Single); - for (index, width) in [46, 110, 110, 210, 100, 250, 70].into_iter().enumerate() { + for (index, width) in [46, 110, 110, 190, 90, 230, 160].into_iter().enumerate() { table.set_col_width(index as i32, width); } table.end(); @@ -868,6 +879,9 @@ fn enqueue(queue: &Arc>>, devices: &Arc>>, dev.queued = true; dev.pending = Some(kind); dev.progress = 0; + dev.bytes_done = 0; + dev.bytes_total = 0; + dev.rate.clear(); dev.status = job_status(kind).into(); queue.lock().unwrap().push_back(Job { location: location.to_string(), kind, resume: false }); } @@ -929,6 +943,8 @@ fn apply_found(found: &[(String, String, String, String)], devices: &Arc>, row: i32, col: i32) -> String { 4 => dev.disk.clone(), 5 if dev.rate.is_empty() => dev.status.clone(), 5 => format!("{} {}", dev.status, dev.rate), + 6 if dev.bytes_total > 0 && dev.status.contains('备') => { + format!("{}/{}", format_amount(dev.bytes_done), format_amount(dev.bytes_total)) + } 6 => format!("{}%", dev.progress), _ => String::new(), } @@ -987,6 +1006,27 @@ fn draw_mark(checked: bool, x: i32, y: i32, w: i32, h: i32) { } } +fn format_amount(bytes: u64) -> String { + const KB: f64 = 1024.0; + const MB: f64 = 1024.0 * 1024.0; + const GB: f64 = 1024.0 * 1024.0 * 1024.0; + let value = bytes as f64; + let (scaled, unit) = if value >= GB { + (value / GB, "GB") + } else if value >= MB { + (value / MB, "MB") + } else if value >= KB { + (value / KB, "KB") + } else { + return format!("{bytes}B"); + }; + if scaled >= 100.0 || (scaled - scaled.round()).abs() < 0.05 { + format!("{:.0}{unit}", scaled) + } else { + format!("{:.1}{unit}", scaled) + } +} + fn refresh_table(table: &mut TableRow, devices: &Arc>>) { let count = devices.lock().unwrap().len() as i32; if table.rows() != count { @@ -1018,10 +1058,21 @@ fn apply(devices: &Arc>>, msg: EventMsg) { dev.progress = value; } } + EventMsg::Bytes(location, done, total) => { + if let Some(dev) = list.iter_mut().find(|d| d.location == location) { + dev.bytes_done = done; + dev.bytes_total = total; + if total > 0 { + dev.progress = ((done.saturating_mul(100)) / total).min(100) as i32; + } + } + } EventMsg::Status(location, status) => { if let Some(dev) = list.iter_mut().find(|d| d.location == location) { dev.status = status; dev.rate.clear(); + dev.bytes_done = 0; + dev.bytes_total = 0; } } EventMsg::Rate(location, rate) => { @@ -1034,6 +1085,8 @@ fn apply(devices: &Arc>>, msg: EventMsg) { dev.queued = false; dev.pending = None; dev.rate.clear(); + dev.bytes_done = 0; + dev.bytes_total = 0; if kind == "info" { dev.info_done = true; dev.progress = 0; @@ -1053,6 +1106,8 @@ fn apply(devices: &Arc>>, msg: EventMsg) { dev.queued = false; dev.pending = None; dev.rate.clear(); + dev.bytes_done = 0; + dev.bytes_total = 0; dev.info_done = true; if err == "设备已拔出" { dev.present = false;