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
APFS: a cursor must hold block addresses, not object identifiers
vcvkk3c084565d253
diff --git a/README.md b/README.mdindex 0a1f936..b28f5d8 100644--- a/README.md+++ b/README.md@@ -638,8 +638,33 @@ LZBITMAP внутри файлов не встречается.inode с `INODE_IS_SPARSE`), поэтому чтение дырок проверено на придуманных списках экстентов — `test_sparse.py`,девять случаев. Шифрование, снимки и Fusion не читаются совсем.-Драйвера в ядре пока нет: следующий шаг — `bsd/miscfs/apfs/` по образцу `packfs` (монтирование и чтение, запись не-нужна).+Чтение формата есть и в ядре — отдельно от всего, что знает про vnode, чтобы его можно было собрать программой для+компьютера и прогнать по настоящему образу прежде, чем оно попадёт в ядро:++| | |+|---|---|+| `bsd/miscfs/apfs/apfs_lib.{h,c}` | контейнер, контрольная точка, карты объектов, B-деревья, записи, inode, каталоги, символьные ссылки, расширенные атрибуты, экстенты и дырки, `decmpfs`. Про vnode не знает ничего. Проверяет всё по дороге: Fletcher-64 у каждого блока метаданных, каждое смещение и длину внутри узла, длину каждой записи против полей, вынутых из неё, — на порче чтение кончается `EIO`, а не диким указателем |+| `bsd/miscfs/apfs/apfs.h`, `apfs_vfsops.c`, `apfs_vnops.c` | прослойка до VFS: монтирование, vnode на объект (ищется по хешу номеров), `lookup`, `getattr`, `read`, `readdir`, `readlink`, `getxattr`, `listxattr`, `pagein`. Только чтение. `apfs_lib` выдаёт указатели в свой кеш блоков, а его курсоры сами не блокируются, поэтому каждый вызов в него — под замком тома |+| `tools/apfs/apfs-tool.c`, `build-tool.sh` | тот же `apfs_lib.c`, без правок, собранный программой для компьютера. Её `census` печатает по строке на запись каталога — путь, вид, права, владелец, группа, размер и хеш содержимого — в том же виде, что `verify.py clines`, так что два читателя сравниваются построчно |++В таблице файловых систем ядра он стоит под именем `apfs` перед `packfs`: устройство с настоящим контейнером+узнаётся как APFS, а на любом другом `apfs_mountroot` отвечает `EINVAL`, и `vfs_mountroot()` спокойно пробует+следующую.++Две вещи, которых в спецификации Apple нет, а образ их показал:++- таблица кусков в ресурсной вилке лежит не по постоянному смещению, а на четыре байта дальше того смещения+ данных, что записано в её заголовке HFS+ (с обратным порядком байтов): здесь это 260, а не 256;+- спецификация даёт две формы ключа записи каталога и не говорит, какая используется. Хеш, который она описывает,+ нужен только для поиска имени без учёта регистра и нормализации, и этот том (normalization-insensitive) его+ несёт — значит, хешированный ключ там, где включено одно из этих двух свойств. Неверная догадка не пройдёт+ молча: длина имени не сойдётся с длиной ключа и запись будет отвергнута.++Про драйвер проверено только то, что ядро с ним собирается и линкуется (`_apfs_vfsops`, `_apfs_mountroot`,+`_apfs_nx_open` есть в `mach.development.bcm2837`), и что код формата под ним читает образ правильно: `census`+из `apfs-tool` и `verify.py clines` дают для всех 318 098 записей тома побайтово одинаковые строки — путь, вид,+права, владелец, группа, размер и хеш содержимого (а значит, прочитано и всё содержимое: 142 299 файлов и 2324+ссылки). Смонтирован он не был ни на телефоне, ни в QEMU, так что больше про него ничего не известно.## Про файлы Apple и лицензииdiff --git a/tools/apfs/run-tests.sh b/tools/apfs/run-tests.shindex 3c8140c..035aecc 100755--- a/tools/apfs/run-tests.sh+++ b/tools/apfs/run-tests.sh@@ -5,16 +5,21 @@# 2. the UDIF reader against the image's own trailer and partition table# 3. the APFS reader against 7-Zip's, over every entry in the volume (needs ios165/)# 4. file contents against the files 7-Zip extracted, byte for byte (needs ios165/)+# 5. the C the kernel is built from against apfs.py, over the whole volume#-# Steps 3 and 4 need the APFS partition unpacked out of ios165/rootfs.dmg; pass it as+# Steps 3, 4 and 5 need the APFS partition unpacked out of ios165/rootfs.dmg; pass it as# $1, or set APFS_IMAGE. Without it only the first two steps run.#+# APFS_SUBTREE=/some/path keeps step 5 to one subtree, which is the quick way to run it;+# unset, it walks the whole volume and reads every file through both readers.+## usage: tools/apfs/run-tests.sh [APFS-PARTITION-OR-DMG]set -uHERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)ROOT=$(cd "$HERE/../.." && pwd)IMAGE=${1:-${APFS_IMAGE:-}}+APFS_SUBTREE=${APFS_SUBTREE:-}TMP=$(mktemp -d)trap 'rm -rf "$TMP"' EXITfail=0@@ -68,5 +73,28 @@ if [ -d "$ROOT/ios165/rootfs" ]; thenelseecho " skipped: ios165/rootfs is not here"fi+echo++# The C in bsd/miscfs/apfs is what goes into the kernel, so it is run against the reader+# that has already been checked against 7-Zip. SUBTREE keeps it to part of the volume;+# with no SUBTREE it walks all 318098 entries and reads every file, which takes a while+# on the Python side.+echo "== 5. the kernel's C against apfs.py${APFS_SUBTREE:+ over $APFS_SUBTREE}"+if "$HERE/build-tool.sh" "$TMP/apfs-tool" > /dev/null; then+ "$TMP/apfs-tool" census "$IMAGE" ${APFS_SUBTREE:+"$APFS_SUBTREE"} 2>/dev/null |+ sort > "$TMP/c.txt"+ python3 "$HERE/verify.py" clines "$IMAGE" ${APFS_SUBTREE:+"$APFS_SUBTREE"} |+ sort > "$TMP/py.txt"+ if diff "$TMP/c.txt" "$TMP/py.txt" > "$TMP/d.txt"; then+ echo " $(wc -l < "$TMP/c.txt") entries, identical in both readers"+ else+ echo " $(grep -c '^[<>]' "$TMP/d.txt") differing lines of $(wc -l < "$TMP/py.txt"):"+ head -10 "$TMP/d.txt"+ fail=1+ fi+else+ echo " skipped: the tool would not build"+ fail=1+fiexit $faildiff --git a/xnu/files/bsd/miscfs/apfs/apfs_lib.c b/xnu/files/bsd/miscfs/apfs/apfs_lib.cindex 51b8f66..c4775bb 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_lib.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_lib.c@@ -310,16 +310,20 @@ node_child(struct apfs_btree *tree, const struct node *n, uint32_t i, uint64_t *static inttree_node_addr(struct apfs_btree *tree, uint64_t oid, uint64_t *addr);+/*+ * Read a node that is already known by block address.+ *+ * Everything that walks a tree keeps block addresses, never object identifiers: the root+ * is only ever an address, so a cursor that mixed the two would resolve the root's+ * address through the object map as though it were an identifier. That lookup fails with+ * ENOENT, which a caller scanning for records reads as "there are no more" -- the records+ * of the object quietly go missing instead of the read failing.+ */static int-tree_node(struct apfs_btree *tree, uint64_t oid, const uint8_t **blk, struct node *n)+node_at(struct apfs_btree *tree, uint64_t addr, const uint8_t **blk, struct node *n){- uint64_t addr;- int error = tree_node_addr(tree, oid, &addr);+ int error = nx_block(tree->nx, addr, blk, true);- if (error) {- return error;- }- error = nx_block(tree->nx, addr, blk, true);if (error) {return error;}@@ -330,6 +334,19 @@ tree_node(struct apfs_btree *tree, uint64_t oid, const uint8_t **blk, struct nodreturn node_parse(tree, *blk, n);}+/* The block address of child i of a non-leaf node. */+static int+node_child_addr(struct apfs_btree *tree, const struct node *n, uint32_t i, uint64_t *addr)+{+ uint64_t oid;+ int error = node_child(tree, n, i, &oid);++ if (error) {+ return error;+ }+ return tree_node_addr(tree, oid, addr);+}+/* ------------------------------------------------------------------ object maps */static int omap_find(struct apfs_omap *omap, uint64_t oid, apfs_xid_t want_xid,@@ -725,16 +742,12 @@ apfs_seek(struct apfs_btree *tree, uint64_t obj_id, uint8_t type,{const uint8_t *blk;struct node n;- uint64_t node_oid = tree->root;+ uint64_t addr = tree->root;int error;memset(cur, 0, sizeof(*cur));cur->tree = tree;- error = nx_block(tree->nx, node_oid, &blk, true);- if (error) {- return error;- }- error = node_parse(tree, blk, &n);+ error = node_at(tree, addr, &blk, &n);if (error) {return error;}@@ -745,7 +758,7 @@ apfs_seek(struct apfs_btree *tree, uint64_t obj_id, uint8_t type,if (cur->depth >= APFS_MAX_LEVELS) {return EIO;}- cur->node[cur->depth] = node_oid;+ cur->node[cur->depth] = addr;if (n.nkeys == 0) {cur->done = true;return 0;@@ -795,12 +808,12 @@ apfs_seek(struct apfs_btree *tree, uint64_t obj_id, uint8_t type,}}cur->index[cur->depth] = pick;- error = node_child(tree, &n, pick, &node_oid);+ error = node_child_addr(tree, &n, pick, &addr);if (error) {return error;}cur->depth++;- error = tree_node(tree, node_oid, &blk, &n);+ error = node_at(tree, addr, &blk, &n);if (error) {return error;}@@ -823,7 +836,7 @@ apfs_cursor_next(struct apfs_cursor *cur, struct apfs_rec *rec)return ENOENT;}for (;;) {- error = tree_node(tree, cur->node[cur->depth], &blk, &n);+ error = node_at(tree, cur->node[cur->depth], &blk, &n);if (error) {return error;}@@ -857,7 +870,7 @@ apfs_cursor_next(struct apfs_cursor *cur, struct apfs_rec *rec)return ENOENT;}cur->depth--;- error = tree_node(tree, cur->node[cur->depth], &blk, &n);+ error = node_at(tree, cur->node[cur->depth], &blk, &n);if (error) {return error;}@@ -873,7 +886,7 @@ apfs_cursor_next(struct apfs_cursor *cur, struct apfs_rec *rec)for (;;) {uint64_t child;- error = node_child(tree, &n, cur->index[cur->depth], &child);+ error = node_child_addr(tree, &n, cur->index[cur->depth], &child);if (error) {return error;}@@ -883,7 +896,7 @@ apfs_cursor_next(struct apfs_cursor *cur, struct apfs_rec *rec)cur->depth++;cur->node[cur->depth] = child;cur->index[cur->depth] = 0;- error = tree_node(tree, child, &blk, &n);+ error = node_at(tree, child, &blk, &n);if (error) {return error;}diff --git a/xnu/files/bsd/miscfs/apfs/apfs_lib.h b/xnu/files/bsd/miscfs/apfs/apfs_lib.hindex 9da14c6..c8b9038 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_lib.h+++ b/xnu/files/bsd/miscfs/apfs/apfs_lib.h@@ -153,7 +153,8 @@ struct apfs_rec {struct apfs_cursor {struct apfs_btree *tree;int depth;- uint64_t node[APFS_MAX_LEVELS]; /* block address at each level */+ uint64_t node[APFS_MAX_LEVELS]; /* the block address at each level,+ * never an object identifier */uint32_t index[APFS_MAX_LEVELS];bool done;};