Files
mu300-linux/android-vendor/pull_closure.py
T
Abdurrahman Kaan DikeçandClaude Opus 5 ab19e854c9 never stream a binary through adb exec-out "su -c ..." (issue #2)
On some devices su runs the command on a pty, and the tty layer's ONLCR rewrites
every LF as CRLF. exec-out exists to avoid exactly that translation, but the pty
su allocates puts it back, so every binary read came back inflated by about one
byte in 256 - silently, with no error anywhere.

jizni reported it with a proof that leaves no room: `dd bs=1M count=64` cannot
emit more than 67108864 bytes, and 67357842 arrived. For six firmware files the
CRLF count in the corrupted copy equals the LF count in the good one exactly, and
normalising the corrupted copy back makes it byte-identical.

What it costs when it happens: the Wi-Fi firmware reaches /lib/firmware mangled,
the driver loads without complaint and no phy is ever created - the install
reports success, 5G works and there is simply no hotspot, with nothing in any log
pointing at it. The boot image is built from a corrupted dump, so it is the wrong
size and its header and AVB tail are wrong. The vendor tar fails to extract. The
GPU closure dies in struct.unpack_from. The bootloader_control block is read from
a shifted offset.

Every binary read now goes through a file on the device and `adb pull`, which
never touches a pty and is correct whether or not that device's su allocates one:
install.sh (boot_a, the misc head, the six firmware files), uninstall.sh,
backup-device.sh, collect-logs.sh, reset-password.sh, extract-subset.sh,
extract_subset.py, pull_closure.py and both .ps1 scripts.

install.sh also refuses to continue when a firmware file could not be read, which
is what turns the worst case above into a loud failure instead of a device that
boots without Wi-Fi.

Secondary problems from the same report, all confirmed in the source:

* install.ps1 piped into the `Python` helper, an advanced function with no
  pipeline-bound parameter - the binding fails, and its body would not forward
  $input to the child's stdin even if it bound. Calls the interpreter directly.
* Python detection read only Get-Command's .Source, which is empty for the
  Microsoft Store's app-execution alias, so a working interpreter was "not found".
  Falls back to .Path.
* extract_subset.py created the output directory before validating the archive, so
  a failed run left an empty directory that every later run then skipped.
  Validates first.
* regdb-load's `sleep 0.3` is rejected by busybox sleep, so the wait loop spun
  instead of waiting.

FINDINGS 9b gains the 32 GB variant: shrinking `userdata`, which is the last
partition so nothing else moves and the boot chain stays valid, recovers 10 GiB
and the installer then runs unmodified.

Worth recording that this never reproduced here - the backups taken with
backup-device.sh on the maintainer's device are all exact partition sizes - which
is why it survived this long, and why the fix is written to be correct on both
kinds of device rather than conditional on detecting one.

Reported-by: jizni
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017Z17MBkdHmZPvNPNSLxcHk
2026-09-22 20:37:31 +03:00

73 lines
3.4 KiB
Python
Executable File

"""Pull an Android binary and its shared-library closure from the device, preserving paths.
Search order approximates the vendor linker namespace: vendor, VNDK apex, system, bionic."""
import struct, subprocess, sys, os
from pathlib import Path
ROOT=Path(os.environ.get('MU300_CLOSURE_ROOT','rootfs'))
SEARCH=['/vendor/lib64','/vendor/lib64/hw','/vendor/lib64/egl','/odm/lib64','/apex/com.android.vndk.v33/lib64',
'/system/lib64','/apex/com.android.runtime/lib64/bionic','/apex/com.android.runtime/lib64',
'/apex/com.android.i18n/lib64','/system_ext/lib64']
import time
def adb(cmd):
# adb drops out when the device reboots; never treat that as "file missing"
for attempt in range(30):
r=subprocess.run(['adb','exec-out',f"su -c '{cmd}; echo __RC$?'"],capture_output=True,stdin=subprocess.DEVNULL)
out=r.stdout
i=out.rfind(b'__RC')
if r.returncode==0 and i>=0:
# text can come back CRLF-ified when su runs on a pty; callers want plain LF
return out[:i].replace(b'\r\n', b'\n') if out[i+4:].strip()==b'0' else b''
time.sleep(5)
raise SystemExit('adb unavailable')
# A binary read must not go through `adb exec-out "su -c ..."`: on some devices su gives the command a pty
# whose ONLCR rewrites every LF as CRLF, and the file arrives inflated and unparsable (issue #2).
def adb_pull_file(path):
dev = '/data/local/tmp/mu300-pull.bin'
subprocess.run(['adb', 'shell', f"su -c 'cat {path} > {dev}'"],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
r = subprocess.run(['adb', 'exec-out', f'cat {dev}'], capture_output=True, stdin=subprocess.DEVNULL)
subprocess.run(['adb', 'shell', f"su -c 'rm -f {dev}'"],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
return r.stdout if r.returncode == 0 else b''
def pull(path):
dst=ROOT/path.lstrip('/')
if dst.exists(): return dst
real=adb(f'readlink -f {path}').decode().strip()
data=adb_pull_file(real)
if not data.startswith(b'\x7fELF') and path.endswith('.so'): return None
dst.parent.mkdir(parents=True,exist_ok=True); dst.write_bytes(data); return dst
def needed(p):
b=p.read_bytes()
if b[:4]!=b'\x7fELF': return []
shoff,=struct.unpack_from('<Q',b,0x28); phoff,=struct.unpack_from('<Q',b,0x20)
phnum,=struct.unpack_from('<H',b,0x38)
dyn=None; loads=[]
for i in range(phnum):
t,f,off,va,pa,fs,ms,al=struct.unpack_from('<IIQQQQQQ',b,phoff+i*56)
if t==2: dyn=(off,fs)
if t==1: loads.append((va,off,fs))
if not dyn: return []
ents=[struct.unpack_from('<qQ',b,dyn[0]+j) for j in range(0,dyn[1],16)]
strtab=[v for t,v in ents if t==5][0]
stroff=[o+strtab-va for va,o,fs in loads if va<=strtab<va+fs][0]
out=[]
for t,v in ents:
if t==1:
e=b.index(b'\0',stroff+v); out.append(b[stroff+v:e].decode())
return out
todo=list(sys.argv[1:]); seen=set(); missing=[]
while todo:
path=todo.pop()
if path in seen: continue
seen.add(path)
p=pull(path)
if not p: missing.append(path); continue
for lib in needed(p):
for d in SEARCH:
cand=f'{d}/{lib}'
if cand in seen: break
if adb(f'[ -e {cand} ] && echo y').strip().endswith(b'y'):
todo.append(cand); break
else: missing.append(lib)
print('pulled',len(seen)-len(missing)); print('missing',sorted(set(missing)))