Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

UFS: what lies in super, read from its own metadata

vcvkk1decad0a02d2
diff --git a/README.md b/README.md
index 89f9a5f..4eeba6a 100644
--- a/README.md
+++ b/README.md
@@ -423,6 +423,13 @@ P3 поверхности кадров копировались, и этого
загрузчик прочитал сам до старта ядра. С образами из `fw/fw.zip` они **не** совпадают: на телефоне стоит
другая версия прошивки (начала разделов при этом верные — ELF у загрузчиков, FAT у `modem` и `bluetooth`).
+Что лежит внутри `super` (8,5 ГБ, где у Android `system`, `vendor`, `product` и прочие логические разделы):
+с `ufs=1` загрузчик выводит метаданные liblp как есть, `tools/ufs-super.py` проверяет их суммы SHA-256 (все
+верны) и раскладывает. Телефон живёт на слоте `_b` (Virtual A/B: разделов `_a` в `super` нет вовсе), семь
+логических разделов занимают 8,42 ГБ, и не покрыто ни одним экстентом **85 МБ** — 12 + 2,6 МБ дырами после
+прошлого обновления и 70 МБ в хвосте. Своему тому порта места в `super` нет. Вне `super` на флеше свободного
+места нет тоже: `userdata` доходит до конца единицы 0, а следующий по величине раздел — `cust`, 2 ГБ.
+
Загрузчик пишет на флеш с первого коммита проекта ровно одно — свой журнал, в служебный раздел `logdump`
(`write_logs`); к этому драйверу это не относится.
diff --git a/tools/ufs-super.py b/tools/ufs-super.py
new file mode 100755
index 0000000..6aec08f
--- /dev/null
+++ b/tools/ufs-super.py
@@ -0,0 +1,137 @@
+#!/usr/bin/env python3
+"""What is in the phone's "super" partition, and where in it nothing is.
+
+usage: ufs-super.py [LOG]
+ LOG the loader's log of a run with ufs=1 among XL_CMDLINE (default logs/last.log)
+
+Android's system, vendor, product and the rest are logical partitions inside the GPT partition
+"super", laid out by liblp's metadata at its start. With ufs=1 the loader (xnuloader/loader.c,
+ufs_dump_super) prints that metadata raw: the geometry, the header of the first slot and its tables.
+This checks their SHA-256 sums -- right sums mean the bytes are the metadata as Android wrote it --
+lists the logical partitions with their extents and groups, and says which ranges of super no
+extent covers. Nothing is read from the phone here; it only reads the log.
+"""
+import hashlib
+import re
+import struct
+import sys
+
+SECTOR = 512
+
+
+def blob(text, what):
+ rows = re.findall(rf'^ufs: super {what} \+([0-9a-f]+): ([0-9a-f]*)$', text, re.M)
+ data = bytearray()
+ for at, hexa in rows:
+ if int(at, 16) != len(data):
+ sys.exit(f'ufs-super.py: the {what} lines are not contiguous at +{at}')
+ data += bytes.fromhex(hexa)
+ return bytes(data)
+
+
+def checked(data, at, name):
+ """the sum at data[at:at+32] over data with that field zeroed"""
+ zeroed = data[:at] + bytes(32) + data[at + 32:]
+ right = hashlib.sha256(zeroed).digest() == data[at:at + 32]
+ print(f'{name} sha256 {"right" if right else "WRONG"}')
+ return right
+
+
+def cstr(b):
+ return b.split(b'\0', 1)[0].decode('ascii', 'replace')
+
+
+def size(n):
+ return f'{n / 2**30:.2f} GB' if n >= 2**30 else f'{n / 2**20:.1f} MB'
+
+
+def slot(number, header, tables):
+ print(f'\n=== metadata slot {number} (as slot _{"ab"[number]} sees super) ===')
+ _, major, minor, header_size = struct.unpack_from('<IHHI', header)
+ tables_size = struct.unpack_from('<I', header, 44)[0]
+ ok = checked(header[:header_size], 12, f'header v{major}.{minor}')
+ right = hashlib.sha256(tables).digest() == header[48:80]
+ print(f'tables sha256 {"right" if right else "WRONG"} ({tables_size} bytes)')
+ ok &= right
+ desc = [struct.unpack_from('<III', header, 80 + 12 * i) for i in range(4)]
+ flags = struct.unpack_from('<I', header, 128)[0] if header_size >= 132 else 0
+
+ def table(i, fmt):
+ offset, count, entry = desc[i]
+ return [struct.unpack_from(fmt, tables, offset + k * entry) for k in range(count)]
+
+ partitions = table(0, '<36sIIII')
+ extents = table(1, '<QIQI')
+ groups = table(2, '<36sIQ')
+ devices = table(3, '<QIIQ36sI')
+
+ print(f'block devices (header flags {flags:#x}):')
+ for first, align, align_off, dev_size, name, dflags in devices:
+ print(f' {cstr(name)}: {size(dev_size)} ({dev_size} bytes), data from sector {first}, '
+ f'alignment {align}, flags {dflags:#x}')
+ print('groups:')
+ used_in = {}
+ for _, attrs, first, count, group in partitions:
+ used_in[group] = used_in.get(group, 0) + sum(extents[first + k][0] for k in range(count)) * SECTOR
+ for i, (name, gflags, maximum) in enumerate(groups):
+ room = f', {size(maximum - used_in.get(i, 0))} of it unused' if maximum else ''
+ print(f' {cstr(name) or "(default)"}: at most {size(maximum) if maximum else "unlimited"}, '
+ f'holds {size(used_in.get(i, 0))}{room}')
+
+ print('logical partitions:')
+ taken = []
+ for name, attrs, first, count, group in partitions:
+ parts = []
+ for k in range(count):
+ sectors, kind, target, source = extents[first + k]
+ if kind == 0:
+ taken.append((target, target + sectors, cstr(name), source))
+ parts.append(f'{sectors * SECTOR / 2**20:.0f} MB at sector {target}')
+ else:
+ parts.append(f'{sectors * SECTOR / 2**20:.0f} MB of zeros')
+ total = sum(extents[first + k][0] for k in range(count)) * SECTOR
+ print(f' {cstr(name):<20} {size(total):>9} group {cstr(groups[group][0]) or group}, '
+ f'attributes {attrs:#x}' + (f': {"; ".join(parts)}' if parts else ', empty'))
+
+ print('what lies where in super (sectors of 512):')
+ first_data, dev_end = devices[0][0], devices[0][3] // SECTOR
+ print(f' 0 .. {first_data}: liblp metadata ({size(first_data * SECTOR)})')
+ at, free = first_data, 0
+ for start, end, name, source in sorted(t for t in taken if t[3] == 0):
+ if start > at:
+ print(f' {at} .. {start}: FREE, {size((start - at) * SECTOR)}')
+ free += start - at
+ print(f' {start} .. {end}: {name}')
+ at = max(at, end)
+ if at < dev_end:
+ print(f' {at} .. {dev_end}: FREE, {size((dev_end - at) * SECTOR)}')
+ free += dev_end - at
+ print(f'{size(free * SECTOR)} of {size(devices[0][3])} in super is covered by no extent of slot {number}')
+ return ok
+
+
+def main():
+ log_path = sys.argv[1] if len(sys.argv) > 1 else 'logs/last.log'
+ text = open(log_path, encoding='utf-8', errors='replace').read()
+ for line in re.findall(r'^ufs: super: .*$', text, re.M):
+ print(line)
+ geometry = blob(text, 'geometry')
+ if not geometry:
+ sys.exit(f'ufs-super.py: no "ufs: super" dump in {log_path} (was the run made with ufs=1?)')
+ gpt = re.search(r'^ufs: part super: lba (\d+)\.\.(\d+), (\d+) KB$', text, re.M)
+ if gpt:
+ print(f'GPT: super is lba {gpt[1]}..{gpt[2]}, {size(int(gpt[3]) * 1024)}')
+
+ magic, struct_size = struct.unpack_from('<II', geometry)
+ max_size, slots, block_size = struct.unpack_from('<III', geometry, 40)
+ ok = checked(geometry[:struct_size], 8, 'geometry')
+ print(f' metadata up to {max_size} bytes, {slots} slots, logical block {block_size}')
+ for number in range(2):
+ header, tables = blob(text, f'header{number}'), blob(text, f'tables{number}')
+ if header:
+ ok &= slot(number, header, tables)
+ return 0 if ok else 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/xnuloader/loader.c b/xnuloader/loader.c
index 29f6bf3..87c8987 100644
--- a/xnuloader/loader.c
+++ b/xnuloader/loader.c
@@ -1239,6 +1239,73 @@ ufs_check_gpt(efi_block_io *bio, uint64_t unit)
got_entries == entries_crc ? "right" : "WRONG", (uint64_t)got_entries);
}
+/* one line per 32 bytes: "ufs: super WHAT +OFFSET: hex" */
+static void
+ufs_dump(const char *what, const uint8_t *p, uint64_t n)
+{
+ for (uint64_t at = 0; at < n; at += 32) {
+ char line[72];
+ unsigned k = 0;
+
+ for (uint64_t i = at; i < n && i < at + 32; i++) {
+ line[k++] = "0123456789abcdef"[p[i] >> 4];
+ line[k++] = "0123456789abcdef"[p[i] & 15];
+ }
+ line[k] = 0;
+ print("ufs: super %s +%x: %s\n", what, at, line);
+ }
+}
+
+/*
+ * Android's own system (system, vendor, product, ...) is not in GPT partitions but in logical ones
+ * inside "super", which liblp's metadata at its start describes: a geometry at 4096 (and its copy
+ * at 8192), then its metadata slots from 12288 on -- each a header and its tables of partitions,
+ * extents, groups and block devices. Printed raw for tools/ufs-super.py, which checks their SHA-256 sums and
+ * says where in super nothing lies: a place a volume of this port's own could have without
+ * anything of Android's being moved.
+ */
+static void
+ufs_dump_super(efi_block_io *bio)
+{
+ uint64_t bs = bio->media->block_size, want = 256 * 1024;
+ const uint8_t *geometry = ufs_buffer + 4096;
+ uint32_t max_size, slots;
+
+ if (bs == 0 || want % bs || (bio->media->last_block + 1) * bs < want ||
+ EFI_ERROR(bio->read_blocks(bio, bio->media->media_id, 0, want, ufs_buffer))) {
+ print("ufs: super: its start could not be read\n");
+ return;
+ }
+ if (*(const uint32_t *)geometry != 0x616c4467) {
+ print("ufs: super: no liblp geometry (magic %x)\n", (uint64_t)*(const uint32_t *)geometry);
+ return;
+ }
+ ufs_dump("geometry", geometry, 52);
+ max_size = *(const uint32_t *)(geometry + 40);
+ slots = *(const uint32_t *)(geometry + 44);
+ /* a slot per A/B slot: the first describes super as slot _a sees it, the second as _b does */
+ for (uint32_t slot = 0; slot < slots && slot < 2; slot++) {
+ const uint8_t *header = ufs_buffer + 3 * 4096 + (uint64_t)slot * max_size;
+ uint32_t header_size, tables_size;
+ char what[8] = "header0", tables[8] = "tables0";
+
+ if (3 * 4096 + (uint64_t)(slot + 1) * max_size > want || *(const uint32_t *)header != 0x414c5030) {
+ print("ufs: super: slot %d: no metadata header within the first %d KB\n", (uint64_t)slot, want >> 10);
+ continue;
+ }
+ header_size = *(const uint32_t *)(header + 8);
+ tables_size = *(const uint32_t *)(header + 44);
+ if (header_size < 128 || header_size > 256 || tables_size > max_size - header_size || tables_size > 16384) {
+ print("ufs: super: slot %d: header of %d bytes, tables of %d: not dumped\n", (uint64_t)slot,
+ (uint64_t)header_size, (uint64_t)tables_size);
+ continue;
+ }
+ what[6] = tables[6] = (char)('0' + slot);
+ ufs_dump(what, header, header_size);
+ ufs_dump(tables, header + header_size, tables_size);
+ }
+}
+
static void
ufs_survey(void)
{
@@ -1284,6 +1351,9 @@ ufs_survey(void)
if ((r = ufs_reference_of(name)) >= 0) {
ufs_hash_partition(bio, name, ufs_references[r].bytes);
}
+ if (name[0] == 's' && name[1] == 'u' && name[2] == 'p' && name[3] == 'e' && name[4] == 'r' && name[5] == 0) {
+ ufs_dump_super(bio);
+ }
}
print("ufs: %d raw units, %d partitions\n", units, partitions);
}