Skip to content

getlunsize() crashes on a TypeError, permanently wedges skipresponse, and makes qfil write the BackupGPT to a negative sector #808

Open

Description

@suddenBook

Environment

edlclient 3.62 (Arch AUR edl-git 3.52.1.r428.g51e1102-1, commit 51e1102)
Python 3.14
Host OS Linux 7.1.5 (CachyOS)
Connection USB (usblib.py), VID:PID 05c6:9008
Device Lenovo TB390FU, UFS, 8 LUNs, 4096-byte sectors, prod_name=HN8T174EJKX075
Command edl --loader=xbl_s_devprg_ns.melf --memory=ufs qfil <rawprogram list> <patch list> <imagedir>

Line numbers below are from the installed 3.62 copy of edlclient/Library/.

Summary

Three defects chain together. The first is a plain TypeError, but it is caught and logged as a
one-line message, so the symptom that reaches the user is a red line plus a ~1000× slowdown plus a
partition table written to a negative sector — with no indication that anything failed.

  1. cmd_read_buffer() does "value" in rsp.data where rsp.data can be a bytearray, which raises
    TypeError: a bytes-like object is required, not 'str'.
  2. get_gpt() catches that, sets self.skipresponse = True as a fallback, and never restores it.
    Nothing else in the codebase resets the flag, so every subsequent transfer runs unsynchronised.
  3. getlunsize() catches the resulting exception and returns -1. qfil substitutes that into
    start_sector="NUM_DISK_SECTORS-5.", producing -1-5 → eval → -6, and programs the
    BackupGPT there.

Bug 1 — TypeError in cmd_read_buffer()

Library/firehose.py:736

rsp = self.xmlsend(data, self.skipresponse)
if "value" in rsp.data and rsp.data["value"] == "NAK":
    return rsp

rsp.data is only a dict on some paths out of xmlsend(). It is a bytearray on others:

  • firehose.py:302 — return response(resp=resp, data=rdata, log=log)
  • firehose.py:303 — return response(resp=status, data=rdata)
  • firehose.py:329 — return response(resp=True, data=rdata) (the skipresponse path; rdata is an
    empty bytearray())

In Python 3, str in bytearray raises:

>>> "value" in bytearray(b"")
TypeError: a bytes-like object is required, not 'str'

The dict-returning path is taken when the device answers a <read> with rawmode present
(firehose.py:290). When the reply has no rawmode attribute the bytearray path is taken instead,
and this line raises.

Suggested fix

--- a/edlclient/Library/firehose.py
+++ b/edlclient/Library/firehose.py
@@ -733,7 +733,7 @@ class firehose(metaclass=LogBase):
 
         progbar = progress(self.cfg.SECTOR_SIZE_IN_BYTES)
         rsp = self.xmlsend(data, self.skipresponse)
-        if "value" in rsp.data and rsp.data["value"] == "NAK":
+        if isinstance(rsp.data, dict) and rsp.data.get("value") == "NAK":
             return rsp
         self.cdc.xmlread = False
         resData = bytearray()

Bug 2 — skipresponse is set as a fallback and never restored

Library/firehose.py:782-787

try:
    resp = self.cmd_read_buffer(lun, 0, 1, False)
except Exception as err:
    self.debug(str(err))
    self.skipresponse = True          # <-- never set back
    resp = self.cmd_read_buffer(lun, 0, 1, False)

grep -n "skipresponse" Library/firehose.py shows the only other assignment is in __init__. Once
this fallback fires, self.skipresponse stays True for the rest of the session and is passed to
every later xmlsend() (lines 500, 556, 610, 626, 673, 735).

With skipresponse=True, xmlsend() returns without ever reading the device's
<response value="ACK" rawmode="true"/>. Two things follow:

  • The host starts pushing bulk data before the loader has entered raw mode.
  • The unread response stays in the USB IN pipe, so the next wait_for_data() immediately picks up a
    stale response. The stream is permanently one reply behind. (usblib.flush() is a no-op —
    Library/Connection/usblib.py:210 is just return — so nothing ever drains it.)

Measured impact

Same device, same images, same cable; the only difference is this patch. MAX_USB_BULK_BUFFER_SIZE
is 16384, so a 1 MB payload is 64 bulk writes.

image size before after
xbl_s.melf 1.18 MB 0.03 MB/s 183.50 MB/s
xbl_config.elf 0.35 MB 0.09 MB/s 171.62 MB/s
NON-HLOS.bin 69.9 MB 0.16 MB/s 213.37 MB/s
dspso.bin 67.1 MB 0.25 MB/s 225.65 MB/s

Before the patch, 67.1 MB took 268 s — about 65 ms per 16 KB bulk write. A full ~2.5 GB flash was
projected at over 100 minutes; after the patch it completed in 12 min 45 s.

The slowdown starts at the exact log line where the first getlunsize() failure is printed, and
affects every LUN after it.

Suggested fix

--- a/edlclient/Library/firehose.py
+++ b/edlclient/Library/firehose.py
@@ -783,8 +783,12 @@
             resp = self.cmd_read_buffer(lun, 0, 1, False)
         except Exception as err:
             self.debug(str(err))
+            oldskip = self.skipresponse
             self.skipresponse = True
-            resp = self.cmd_read_buffer(lun, 0, 1, False)
+            try:
+                resp = self.cmd_read_buffer(lun, 0, 1, False)
+            finally:
+                self.skipresponse = oldskip
 
         if not resp.resp:
             for line in resp.error:

Bug 3 — qfil turns getlunsize() == -1 into a negative start_sector

Library/firehose.py:1092-1104

def getlunsize(self, lun):
    if lun not in self.lunsizes:
        try:
            data, guid_gpt = self.get_gpt(...)
            self.lunsizes[lun] = guid_gpt.totalsectors
        except Exception as err:
            self.error(err)
            return -1                      # <-- not cached, so it retries and re-logs every time

Library/firehose_client.py:951-958

num_disk_sectors = self.firehose.getlunsize(partition_number)
start_sector = elem.get("start_sector")
if "NUM_DISK_SECTORS" in start_sector:
    start_sector = start_sector.replace("NUM_DISK_SECTORS", str(num_disk_sectors))
if "-" in start_sector or "*" in start_sector or "/" in start_sector or "+" in start_sector:
    start_sector = start_sector.replace(".", "")
    start_sector = eval(start_sector)

With a stock Qualcomm-generated rawprogram1.xml:

<program filename="gpt_backup1.bin" label="BackupGPT" num_partition_sectors="5"
         physical_partition_number="1" start_sector="NUM_DISK_SECTORS-5." ... />

"NUM_DISK_SECTORS-5." → "-1-5." → "-1-5" → eval → -6, and edl programs there:

firehose_client - [qfil] programming .../gpt_backup1.bin to partition(1)@sector(-6)...
firehose -
Writing to physical partition 1, sector -6, sectors 5
Progress: |██████████| 100.0% Write (Sector 0x5 of 0x5, ) 0.01 MB/s

No error is raised — the device ACKs. On the loader I tested, the negative sector was silently
discarded (I read back the tail of LUN1 afterwards: the five sectors below the BackupGPT were all
zero and the factory BackupGPT was untouched), so the net effect was a missing BackupGPT rather
than a misplaced one. On a loader that accepts negative offsets as "count back from the end of the
LUN", -6 would land one sector before the correct NUM_DISK_SECTORS-5, putting the backup header
on the second-to-last LBA instead of the last one.

Either way, silently computing a negative offset from a failed size query is worth guarding.

Suggested fix

--- a/edlclient/Library/firehose_client.py
+++ b/edlclient/Library/firehose_client.py
@@ -951,6 +951,13 @@
                                 num_disk_sectors = self.firehose.getlunsize(partition_number)
                                 start_sector = elem.get("start_sector")
                                 if "NUM_DISK_SECTORS" in start_sector:
+                                    if num_disk_sectors <= 0:
+                                        self.error(f"Could not determine size of LUN "
+                                                   f"{partition_number} (getlunsize returned "
+                                                   f"{num_disk_sectors}). Refusing to write "
+                                                   f"{filename} at a bogus offset.")
+                                        success = False
+                                        continue
                                     start_sector = start_sector.replace("NUM_DISK_SECTORS", str(num_disk_sectors))
                                 if "-" in start_sector or "*" in start_sector or "/" in start_sector or \
                                         "+" in start_sector:

Reproduction

Not reliably reproducible on demand — whether get_gpt() fails depends on how the device answers a
<read> of LUN sector 0, which varied by LUN and by session in my testing. What is deterministic is
the chain once the first failure happens: TypeError → skipresponse stuck → every remaining LUN
fails identically → every NUM_DISK_SECTORS-N expression evaluates negative.

In one 127-entry qfil run I got 73 occurrences of the caught exception, all from LUN 1 and LUN 4.
LUN 0, 2, 3 and 5 succeeded in the same run.

Observed log, with all three defects active:

firehose_client - [qfil] programming .../rawprogram1.xml
firehose
firehose - [LIB]: a bytes-like object is required, not 'str'
firehose_client - [qfil] programming .../xbl_s.melf to partition(1)@sector(6)...
firehose -
Writing to physical partition 1, sector 6, sectors 287
Progress: |██████████| 100.0% Write (Sector 0x11E of 0x11E, ) 0.03 MB/s
...
firehose_client - [qfil] programming .../gpt_backup1.bin to partition(1)@sector(-6)...

After applying all three patches, the same command on the same device produces no exceptions on the
LUNs that previously worked, refuses (loudly) on the ones where get_gpt() genuinely cannot read the
table, and runs at full USB speed.

Unrelated cosmetic issue in the same area

Library/utils.py:413 has a leftover debug print() inside ColorFormatter.format(), so every
coloured (ERROR/WARNING/DEBUG) record is preceded by a bare line containing the logger name:

if new_record.name != "root":
    print(new_record.name)          # <-- debug leftover
    pad = "[LIB]: "

which is why the log above shows a lone firehose line before each red message. The same code is
duplicated in Library/gpt.py:37, Tools/enableadb.py:74, Tools/sierrakeygen.py:36,
Tools/Library/gpt.py:37 and Tools/Library/utils.py:414.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions