import xml.etree.ElementTree as ET import binascii import time import os from Library.utils import * class xmlparser(): def _iter_roots(self, raw): raw_bytes = bytes(raw) first_xml = raw_bytes.find(b"") if end != -1: part = part[:end + len(b"")] part = part.strip(b"\x00 \t\r\n") if not part: continue try: parser = ET.XMLParser(encoding="utf-8") roots.append(ET.fromstring(part, parser=parser)) except ET.ParseError: continue return roots def getresponse(self, input): content = {} for root in self._iter_roots(input): for atype in root.findall('response'): for field in atype.attrib: content[field] = atype.attrib[field] return content def getlog(self, input): data = '' for root in self._iter_roots(input): for atype in root.findall('log'): if 'value' in atype.attrib: data += atype.attrib['value'] return data class qualcomm_firehose: class cfg: MemoryName = "eMMC" TargetName = "" Version = "" ZLPAwareHost = 1 SkipStorageInit = 0 SkipWrite = 0 MaxPayloadSizeToTargetInBytes = 0x100000 SECTOR_SIZE_IN_BYTES=512 MaxXMLSizeInBytes=4096 bit64=True def __init__(self,cdc,xml,cfg): self.cdc=cdc self.xml=xml self.cfg=cfg if self.cfg.MemoryName=="UFS": self.cfg.SECTOR_SIZE_IN_BYTES=4096 def getstatus(self,resp): if "value" in resp: value = resp["value"] if value == "ACK": return True return False def xmlsend(self,data, skipResponse=False): self.cdc.write(data,self.cfg.MaxXMLSizeInBytes) if skipResponse: return True, {} data=bytearray() while b"" val=self.xmlsend(data) if val[0]==True: print("Reset succeeded.") return True else: print("Reset failed.") return False def cmd_xml(self,data): val=self.xmlsend(data) if val[0]==True: print("Command succeeded.") print(val[2]) return val[2] else: print("Command failed:") print(val[2]) return val[2] def cmd_nop(self): data="" val=self.xmlsend(data) if val[0]==True: print("Nop succeeded.") return True else: print("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[0]==True: res = self.xml.getlog(val[2]) print(res) if "Digest " in res: return res.split("Digest ")[1] else: return res else: print("GetSha256Digest failed.") return False def cmd_setbootablestoragedrive(self,partition_number): data=f"\n" val=self.xmlsend(data) if val[0]==True: print("Setbootablestoragedrive succeeded.") return True else: print("Setbootablestoragedrive failed.") return False def wait_response(self): data = bytearray() while b"\n"+\ f"\n" rsp = self.xmlsend(data) pos=0 prog=0 if Display: print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) if (rsp[0]) == True: bytesToWrite = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors total=self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors old=0 while (bytesToWrite>0): wdata=rf.read(self.cfg.MaxPayloadSizeToTargetInBytes) wlen=len(wdata) 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) wlen=len(wdata) self.cdc.write(wdata,self.cfg.MaxPayloadSizeToTargetInBytes) prog = int(float(pos) / float(total) * float(100)) if (prog > old): if Display: print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) old = prog bytesToWrite -= wlen pos+=wlen #time.sleep(0.05) if Display and prog!=100: print_progress(100, 100, prefix='Progress:', suffix='Complete', bar_length=50) self.cdc.write(b'',self.cfg.MaxPayloadSizeToTargetInBytes) time.sleep(0.2) info, rsp = self.wait_response() if rsp.get("value") == "ACK": return True else: print(f"Error:{info}") return False else: print(f"Error:{rsp}") return False return False def cmd_erase(self,physical_partition_number,start_sector,num_partition_sectors,Display=True): if Display: print(f"\nErasing from physical partition {str(physical_partition_number)}, sector {str(start_sector)}, sectors {str(num_partition_sectors)}") data=f"\n"+\ f"\n" rsp = self.xmlsend(data) empty = b"\x00" * self.cfg.MaxPayloadSizeToTargetInBytes pos=0 prog=0 if Display: print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) if (rsp[0]) == True: bytesToWrite = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors total=self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors old=0 while (bytesToWrite>0): wlen=self.cfg.MaxPayloadSizeToTargetInBytes if bytesToWrite old): if Display: print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) old = prog bytesToWrite -= wlen pos+=wlen #time.sleep(0.05) if Display and prog!=100: print_progress(100, 100, prefix='Progress:', suffix='Complete', bar_length=50) self.cdc.write(b'',self.cfg.MaxPayloadSizeToTargetInBytes) time.sleep(0.2) info, rsp = self.wait_response() if rsp.get("value")=="ACK": return True else: print(f"Error:{info}") else: print(f"Error:{rsp}") return False return False def _begin_raw_read(self, xml_cmd, bytes_to_read): """Send a command and handle optional initial ACK XML packets. Standard Qualcomm Firehose loaders (8k.mbn, 2720v.mbn) answer with before streaming raw sectors, whereas FIH programmers (8110.mbn, 2720.mbn, 800t.mbn) stream raw sector data immediately. """ self.cdc.write(xml_cmd, self.cfg.MaxXMLSizeInBytes) sector_size = self.cfg.SECTOR_SIZE_IN_BYTES max_chunk = max(sector_size, self.cfg.MaxPayloadSizeToTargetInBytes) read_size = min(bytes_to_read, max_chunk) if bytes_to_read > 0 else max_chunk pending = bytearray() while True: if pending: pkt = bytes(pending) pending = bytearray() else: pkt = bytes(self.cdc.read(read_size)) if not pkt: return False, bytearray(), "empty response from device" raw = pkt.lstrip(b"\x00 \t\r\n") end_idx = pkt.find(b"") is_xml = ( raw.startswith(b"") xml_part = pkt[:split_at] tail = pkt[split_at:] if tail and (len(tail) >= sector_size or tail.strip(b"\x00 \t\r\n")): leftover = bytearray(tail) else: leftover = bytearray() log_msg = self.xml.getlog(xml_part) resp = self.xml.getresponse(xml_part) if not resp: if leftover and leftover.lstrip(b"\x00 \t\r\n").startswith(b"\n" ) bytes_to_read = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors ok, initial_raw, err_info = self._begin_raw_read(data, bytes_to_read) if not ok: print(f"Error:{err_info}") return False max_chunk = max(self.cfg.SECTOR_SIZE_IN_BYTES, self.cfg.MaxPayloadSizeToTargetInBytes) total = bytes_to_read dataread = 0 old = 0 prog = 0 if Display: print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) if initial_raw and bytes_to_read > 0: chunk = initial_raw[:bytes_to_read] on_chunk(chunk) bytes_to_read -= len(chunk) dataread += len(chunk) if total > 0: prog = int(float(dataread) / float(total) * float(100)) if prog > old: if Display: print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) old = prog while bytes_to_read > 0: tmp = self.cdc.read(min(bytes_to_read, max_chunk)) if not tmp: print("Error:Short read from device") return False chunk = tmp[:bytes_to_read] on_chunk(chunk) bytes_to_read -= len(chunk) dataread += len(chunk) prog = int(float(dataread) / float(total) * float(100)) if prog > old: if Display: print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) old = prog if Display and prog != 100: print_progress(100, 100, prefix='Progress:', suffix='Complete', bar_length=50) time.sleep(0.2) info, rsp = self.wait_response() if rsp.get("value") == "ACK": return True print(f"Error:{info}") return False def cmd_read_buffer(self, physical_partition_number, start_sector, num_partition_sectors, Display=True): resData = bytearray() if not self._read_raw_sectors( physical_partition_number, start_sector, num_partition_sectors, resData.extend, Display=Display, ): return "" return resData def cmd_read(self, physical_partition_number, start_sector, num_partition_sectors, filename, Display=True): with open(filename, "wb") as wf: if not self._read_raw_sectors( physical_partition_number, start_sector, num_partition_sectors, wf.write, Display=Display, ): return "" return True def connect(self,lvl): v = b'-1' try: while v != b'': v = self.cdc.read() info=self.xml.getlog(v) print(info) except: lvl=lvl data=f""+\ f""+\ "" ''' "" \ "" ''' rsp=self.xmlsend(data) try: self.cdc.read() except: lvl=lvl if rsp[0]==True: self.cfg.MemoryName=rsp[1]["MemoryName"] self.cfg.MaxPayloadSizeToTargetInBytes=int(rsp[1]["MaxPayloadSizeToTargetInBytes"]) self.cfg.MaxPayloadSizeToTargetInBytesSupported=int(rsp[1]["MaxPayloadSizeToTargetInBytesSupported"]) self.cfg.MaxXMLSizeInBytes=int(rsp[1]["MaxXMLSizeInBytes"]) if "MaxPayloadSizeFromTargetInBytes" in rsp[1]: self.cfg.MaxPayloadSizeFromTargetInBytes=int(rsp[1]["MaxPayloadSizeFromTargetInBytes"]) else: #print("Unknown cmd structure, please issue this to github: "+str(rsp[1])) self.cfg.MaxPayloadSizeFromTargetInBytes=self.cfg.MaxXMLSizeInBytes if "TargetName" in rsp[1]: self.cfg.TargetName=rsp[1]["TargetName"] if "MSM" not in self.cfg.TargetName: self.cfg.TargetName="MSM"+self.cfg.TargetName else: self.cfg.TargetName="Unknown" if "Version" in rsp[1]: self.cfg.Version=rsp[1]["Version"] else: self.cfg.Version="0" else: if "MaxPayloadSizeToTargetInBytes" in rsp[1]: self.cfg.MemoryName = rsp[1]["MemoryName"] self.cfg.MaxPayloadSizeToTargetInBytes = int(rsp[1]["MaxPayloadSizeToTargetInBytes"]) self.cfg.MaxPayloadSizeToTargetInBytesSupported = int(rsp[1]["MaxPayloadSizeToTargetInBytesSupported"]) self.cfg.MaxXMLSizeInBytes = int(rsp[1]["MaxXMLSizeInBytes"]) self.cfg.MaxPayloadSizeFromTargetInBytes = int(rsp[1]["MaxPayloadSizeFromTargetInBytes"]) self.cfg.TargetName = rsp[1]["TargetName"] if "MSM" not in self.cfg.TargetName: self.cfg.TargetName = "MSM" + self.cfg.TargetName self.cfg.Version = rsp[1]["Version"] if lvl==0: return self.connect(lvl+1) else: print(f"Error:{rsp}") exit(0) print(f"TargetName={self.cfg.TargetName}") print(f"MemoryName={self.cfg.MemoryName}") print(f"Version={self.cfg.Version}") if self.cfg.MemoryName.lower()=="emmc": self.cfg.SECTOR_SIZE_IN_BYTES=512 elif self.cfg.MemoryName.lower()=="ufs": self.cfg.SECTOR_SIZE_IN_BYTES = 4096 return True # OEM Stuff here below -------------------------------------------------- def cmd_writeimei(self,imei): if len(imei)!=16: print("IMEI must be 16 digits") return False data="" val=self.xmlsend(data) if val[0]==True: print("writeIMEI succeeded.") return True else: print("writeIMEI failed.") return False def cmd_getstorageinfo(self): data="" val=self.xmlsend(data) if val[0]==True: print(f"GetStorageInfo:\n--------------------\n") print(val[1]) return True else: print("GetStorageInfo command isn't supported.") return False def cmd_peek(self,address,SizeInBytes,filename): print(f"Peek: Address({hex(address)}),Size({hex(SizeInBytes)})") with open(filename,"wb") as wf: ''' ''' data=f"\n" ''' ''' try: self.cdc.write(data, self.cfg.MaxXMLSizeInBytes) except: data=data addrinfo=self.cdc.read(self.cfg.MaxXMLSizeInBytes) if (b"size_in_bytes" in addrinfo): tmp=b"" while b"NAK" not in tmp and b"ACK" not in tmp: tmp+=self.cdc.read(self.cfg.MaxXMLSizeInBytes) data = f"" self.cdc.write(data, self.cfg.MaxXMLSizeInBytes) addrinfo = self.cdc.read(self.cfg.MaxXMLSizeInBytes) if b' old): print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50) old=prog if b'