1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python3
# Minimal sdat2img: rebuild a raw ext4 image from an Android OTA
# block-based transfer list + new.dat (already brotli-decompressed).
# usage: sdat2img.py system.transfer.list system.new.dat system.img
import sys

BLOCK = 4096

def ranges(s):
    xs = [int(x) for x in s.split(",")]
    assert xs[0] == len(xs) - 1
    return [(xs[i], xs[i + 1]) for i in range(1, len(xs), 2)]

tl, dat, out = sys.argv[1:4]
lines = open(tl).read().splitlines()
version = int(lines[0])
cmds = lines[4:] if version >= 2 else lines[2:]

with open(dat, "rb") as src, open(out, "wb") as dst:
    maxblk = 0
    for line in cmds:
        op, *rest = line.split(" ")
        if op == "new":
            for a, b in ranges(rest[0]):
                dst.seek(a * BLOCK)
                left = (b - a) * BLOCK
                while left:
                    chunk = src.read(min(left, 1 << 20))
                    assert chunk, "new.dat too short"
                    dst.write(chunk)
                    left -= len(chunk)
                maxblk = max(maxblk, b)
        elif op in ("erase", "zero"):
            for a, b in ranges(rest[0]):
                maxblk = max(maxblk, b)
        else:
            sys.exit("unsupported op: " + op)
    dst.truncate(maxblk * BLOCK)