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
The fourth bound: a device that lies about a write, and the block an extent has to begin on
vcvkkc8f1d7b0081c
diff --git a/README.md b/README.mdindex 61c416e..3956781 100644--- a/README.md+++ b/README.md@@ -1220,7 +1220,7 @@ mac80211 из Linux стоит наша станция (`wifi/lx/src/lx_80211.c`| `apfs.py` | контейнер → контрольная точка → карта объектов → том → B-деревья → inode, каталоги, экстенты, расширенные атрибуты, дырки, сжатие `decmpfs`. Fletcher-64 проверяется у каждого прочитанного блока метаданных. Команды: `info`, `ls`, `tree`, `cat`, `stat`, `census` || `verify.py` | сверка с чужим читателем: тот же образ при распаковке читал 7-Zip, и от него остались `ios165/rootfs.slt` (список всего тома) и `ios165/rootfs/` (распакованные файлы) || `run-tests.sh` | всё, что проверяется на компьютере, одной командой |-| `write-tests.sh` | то же для записи: 62 проверки apfs_write.c против apfsck, apfs.py, 7-Zip и списка изменившихся блоков — «Запись в APFS» |+| `write-tests.sh` | то же для записи: 64 проверки apfs_write.c против apfsck, apfs.py, 7-Zip и списка изменившихся блоков — «Запись в APFS» || `txn-probe.py` | настоящая транзакция APFS на образе `mkapfs.py`: одна запись изменена и зафиксирована новой контрольной точкой — «Запись в APFS» |Распаковать раздел и проверить (образ нужен целиком, около 5,3 ГБ, в git он не кладётся):@@ -1717,7 +1717,7 @@ APFS никогда не перезаписывает уже опубликов### Чем это проверяется-`tools/apfs/write-tests.sh` — 62 проверки на этой машине, где испорченный образ ничего не стоит, и ни одна не на+`tools/apfs/write-tests.sh` — 64 проверки на этой машине, где испорченный образ ничего не стоит, и ни одна не наслово той программы, которую проверяют: образ собирается `mkapfs.py`, пишется ядерным же `apfs_write.c`(`apfs-tool write`, собранный для этой машины), а дальше спрашиваются все остальные.@@ -1729,13 +1729,17 @@ APFS никогда не перезаписывает уже опубликов| `apfs-tool` | ядерный `apfs_lib.c`; единственный, кто частью и есть проверяемое, поэтому никогда не свидетель в одиночку || какие блоки образа изменились | свидетель, которому читатель вообще не нужен: запись поверх себя обязана изменить блоки названного файла и ни одного блока больше |-Семь групп. Записи: целый блок, пролёт через границу блока, середина мегабайта, один байт, последний байт файла+Восемь групп. Записи: целый блок, пролёт через границу блока, середина мегабайта, один байт, последний байт файланецелой длины. Отказы: за конец, в каталог, в сжатый файл, в файл нулевой длины. Запреты по тому — каждыйставится правкой суперблока тома: запечатан, снимки, метаданные целостности, роли системного и preboot. Запретыпо блокам — каждый ставится правкой записи дерева так, чтобы она говорила то, чего здоровый том не говорит: дыратам, где лягут байты; экстент, переставленный в кольцо описателей; экстент, который дерево ссылок называетразделённым; экстент, который оно отдаёт другому потоку. Настоящие образы — что о них говорят запреты.+И ещё одно — устройство, которое соврало: `--corrupt-after N` после N блоков пишет не то, что ему дали. Этого не+поймать ничем, что прочитано до записи, — поэтому каждый блок читается обратно и сравнивается прежде, чем пойдёт+следующий, и запись останавливается на том же блоке.+И пропадание питания, ради которого всё и делалось: `--fail-after N` останавливает устройство после N блоков, изапись в двенадцать блоков прогоняется остановленной после каждого из них. После каждой `apfsck` по-прежнемунаходит контейнер чистым, любой другой файл побайтово тот же, а новые байты лежат ровно в тех блоках, которые ужеdiff --git a/tools/apfs/apfs-tool.c b/tools/apfs/apfs-tool.cindex 788fc57..8c259f1 100644--- a/tools/apfs/apfs-tool.c+++ b/tools/apfs/apfs-tool.c@@ -16,8 +16,9 @@* apfs-tool census IMAGE [PATH] [--meta] (--meta: do not read contents)* apfs-tool lookups IMAGE (every name looked up by name; see cmd_lookups)* apfs-tool writable IMAGE (may the volume be written in place, and why not)- * apfs-tool write IMAGE PATH OFFSET FILE|- [--fail-after N]- * (the kernel's apfs_write.c; --fail-after is a power failure)+ * apfs-tool write IMAGE PATH OFFSET FILE|- [--fail-after N | --corrupt-after N]+ * (the kernel's apfs_write.c; --fail-after is a power failure,+ * --corrupt-after a device that lies about the write)*//* pread(2) and clock_gettime(2) come with -D_DEFAULT_SOURCE, set by build-tool.sh */@@ -156,6 +157,7 @@ static void op_end(void);*/static bool want_write;static bool write_fails; /* --fail-after was given; 0 of them is a failure too */+static bool write_corrupts; /* --corrupt-after: a device that lies about a write */static uint64_t write_fail_after;static uint64_t writes_done;@@ -165,20 +167,38 @@ file_write(void *ctx, uint64_t off, const void *buf, size_t len)int fd = (int)(intptr_t)ctx;const uint8_t *p = buf;+ uint8_t *copy = NULL;+if (write_fails && writes_done >= write_fail_after) {return EIO;}+ if (write_corrupts && writes_done >= write_fail_after) {+ /*+ * A device that says the write went through and puts something else on the+ * platter: the one failure no checking before the write can catch, and what the+ * read-back comparison in apfs_write.c is there for.+ */+ copy = malloc(len);+ if (copy == NULL) {+ return EIO;+ }+ memcpy(copy, p, len);+ copy[0] ^= 0xff;+ p = copy;+ }writes_done++;while (len > 0) {ssize_t n = pwrite(fd, p, len, (off_t)off);if (n <= 0) {+ free(copy);return EIO;}p += n;off += (uint64_t)n;len -= (size_t)n;}+ free(copy);return 0;}@@ -1511,9 +1531,14 @@ main(int argc, char **argv)int i;for (i = 1; i < argc; i++) {- if (strcmp(argv[i], "--fail-after") == 0 && i + 1 < argc) {+ if ((strcmp(argv[i], "--fail-after") == 0 ||+ strcmp(argv[i], "--corrupt-after") == 0) && i + 1 < argc) {write_fail_after = strtoull(argv[i + 1], NULL, 0);- write_fails = true;+ if (argv[i][2] == 'f') {+ write_fails = true;+ } else {+ write_corrupts = true;+ }memmove(&argv[i], &argv[i + 2], (size_t)(argc - i - 2) * sizeof(*argv));argc -= 2;i--;@@ -1526,7 +1551,7 @@ main(int argc, char **argv)" apfs-tool stat IMAGE PATH\n"" apfs-tool cat IMAGE PATH\n"" apfs-tool census IMAGE [PATH] [--meta]\n"- " apfs-tool write IMAGE PATH OFFSET FILE|- [--fail-after N]\n"+ " apfs-tool write IMAGE PATH OFFSET FILE|- [--fail-after N | --corrupt-after N]\n"" apfs-tool writable IMAGE\n"" apfs-tool lookups IMAGE\n"" apfs-tool cfrace IMAGE [THREADS [ROUNDS]]\n"diff --git a/tools/apfs/write-tests.py b/tools/apfs/write-tests.pyindex cacf641..5e3ee71 100755--- a/tools/apfs/write-tests.py+++ b/tools/apfs/write-tests.py@@ -262,11 +262,13 @@ def find_record(image, bno, key):# ---------------------------------------------------------------- the tests-def write(image, path, at, data, fail_after=None):+def write(image, path, at, data, fail_after=None, corrupt_after=None):"""apfs-tool write: the kernel's apfs_write.c on this image."""argv = [TOOL, 'write', image, path, str(at), '-']if fail_after is not None:argv += ['--fail-after', str(fail_after)]+ if corrupt_after is not None:+ argv += ['--corrupt-after', str(corrupt_after)]p = subprocess.run(argv, input=data, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)return p.returncode, p.stdout.decode('utf-8', 'replace')@@ -459,6 +461,23 @@ def test_extent_gates():say(False, 'could not find the extent-reference record to give away')+def test_lying_device():+ """The last of the four bounds: a device that says the write went through and puts something+ else there. Nothing read before the write can catch that, which is why every block is read+ back and compared before the next one goes out."""+ base, img = fresh('lying')+ data = b'\x33' * (4 * BS)+ rc, out = write(img, '/big', 0, data, corrupt_after=2)+ say(rc != 0 and 'read back' in out.lower(),+ 'refused: a device that wrote something other than what it was given' ++ ('' if rc != 0 else ':\n' + out.strip()))+ diff = set(changed_blocks(base, img))+ target = blocks_of(base, '/big')+ say(diff <= target and len(diff) == 3,+ ' and it stopped at that block: %d of the file\'s own blocks changed, none other'+ % len(diff))++def test_power_failure():"""The power out in the middle of a write, at every block in turn. What must hold aftereach: the container is clean, the volume mounts, every other file is byte for byte what it@@ -612,6 +631,7 @@ TESTS = {'refusals': test_refusals,'volume-gates': test_volume_gates,'extent-gates': test_extent_gates,+ 'lying-device': test_lying_device,'power-failure': test_power_failure,'real-images': test_real_images,}diff --git a/xnu/files/bsd/miscfs/apfs/apfs_lib.c b/xnu/files/bsd/miscfs/apfs/apfs_lib.cindex 50e4c1c..db383dc 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_lib.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_lib.c@@ -2345,8 +2345,9 @@ apfs_extent_at(struct apfs_vol *vol, uint64_t stream_id, uint64_t off,if (error) {return error;}- if (length == 0 || (length % vol->nx->block_size) != 0) {- return EIO;+ if (length == 0 || (length % vol->nx->block_size) != 0 ||+ (logical % vol->nx->block_size) != 0) {+ return EIO; /* an extent of APFS begins and ends on a block */}if (off < logical) {return ENOENT; /* a gap in the records: not a hole, damage */diff --git a/xnu/files/bsd/miscfs/apfs/apfs_write.c b/xnu/files/bsd/miscfs/apfs/apfs_write.cindex 48ab904..1abfcf6 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_write.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_write.c@@ -347,6 +347,11 @@ apfs_write_in_place(struct apfs_vol *vol, uint64_t obj_id, uint64_t off, const vgoto refuse;}+ /*+ * An extent at a time. Looking one up walks the stream's extents from the front, so a+ * write across a badly fragmented file costs more than it looks -- which is fine for what+ * this is for (a file of a few extents written whole) and would not be for a filesystem.+ */while (left > 0) {struct apfs_extent ext;uint64_t ext_blocks, piece;