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
README in English; the OS fetch scripts live in sysimage/
shimoku74ef5e2356211d
diff --git a/.gitignore b/.gitignoreindex c37216e..875ea0a 100644--- a/.gitignore+++ b/.gitignore@@ -13,7 +13,7 @@!/qemu/!/tools/!/userland/-!/ios165/+!/sysimage/!/xnu/!/xnu-deps/!/uefi/@@ -45,9 +45,9 @@ __pycache__/!/userland/libmini/!/userland/var/-/ios165/*-!/ios165/fetch.sh-!/ios165/*.py+/sysimage/*+!/sysimage/fetch.sh+!/sysimage/*.py# of xnu-deps only what is ours; setup.sh fetches and builds the rest/xnu-deps/*diff --git a/README.md b/README.mdindex aea6409..1b18d18 100644--- a/README.md+++ b/README.md@@ -1,173 +1,161 @@# HakiOS-**HakiOS** — мой проект по запуску Darwin на Android-телефонах: открытое ядро XNU (xnu-8796.121.2 — то-же ядро, что в iOS 16.5), собственный загрузчик и собственные драйверы для железа Qualcomm, под-которыми работает пользовательское окружение iOS: launchd → backboardd → SpringBoard → приложения.-То же самое запускается в QEMU (`virt`, aarch64) на обычном Linux-компьютере.--Первый и пока единственный телефон, на котором всё это отлажено, — **POCO X5 Pro 5G (redwood,-Snapdragon 778G)**, но проект с самого начала делается переносимым: ядро ничего не знает о телефоне-заранее, все адреса, прерывания, рельсы питания и прошивки берутся из дерева устройств и из Android-конкретного аппарата, и каждый драйвер написан так, чтобы перенос на другой телефон на Qualcomm был-вопросом данных, а не переписывания. Если у вас другой аппарат и желание — порт делается по тем же-шагам, что описаны в `docs/notes.md` и `docs/cellular.md`.--Ничего в телефон не прошивается: загрузчик уходит в ОЗУ через `fastboot boot`, система живёт в ОЗУ до-конца сеанса, после перезагрузки телефон снова в своём Android. Это исследовательский стенд для-изучения того, как устроены XNU и железо телефона, а не прошивка и не замена Android.--## Что в репозитории, а чего нет--Я слежу за тем, чтобы в репозитории были **только мой код и мои данные** — ничего, что принадлежит-Apple или производителю телефона:--- ядро — патч к открытым исходникам XNU Apple (`xnu/redwood.patch`, лицензия APSL) и наши файлы- драйверов (`xnu/files/`), которые `xnu/apply.sh` накладывает на свежий клон xnu;-- загрузчик (`xnuloader/`), наши программы и библиотеки (`userland/src/`), инструменты (`tools/`),- сценарии сборки и запуска;-- `prebuilt/` — собранные из этого же репозитория ядро, загрузчик и наши библиотеки.--Чего **нет и не будет**:--- файлов iOS: ни одного бинарника, образа, кеша, шрифта, картинки или иного ресурса Apple, и ни одного- снимка экрана iOS. Образ системы собирается на вашей машине из IPSW iOS 16.5, который вы скачиваете- сами (`ios165/fetch.sh` берёт его с публичных серверов Apple, ничего не расшифровывая и не обходя);-- прошивок телефона (GPU, Wi-Fi, звукового процессора, модема, вибромотора, камер): они вендорские и- снимаются с того самого аппарата из его Android (`adb pull`) в каталоги `fw-*/`, которые в git- не попадают;-- ключей, сертификатов, обхода защиты, активации и чего-либо, что позволяло бы выдавать устройство за- iPhone перед службами Apple или пользоваться платными службами. Вход в учётную запись Apple здесь- невозможен и не является целью.--Пользоваться iOS на не-Apple устройстве вы можете только в рамках вашего собственного права на-копию iOS и её лицензионного соглашения; этот репозиторий — инструменты и ядро, а не iOS.--## Что работает--| Работает | Не работает / в работе |-|---|---|-| Экран блокировки, домашний экран, Пункт управления, системные жесты, запуск стандартных приложений | Сотовая связь: модем запускается, видит сеть, SIM привязывается — регистрация в сети и палочки в статус-баре в работе (`docs/cellular.md`) |-| Сенсорный экран (Goodix GT9916), мультитач, кнопки питания и громкости | Bluetooth |-| Все 8 ядер процессора (`cpus=8`), большое ядро на 2,4 ГГц | Зарядка под нашим ядром |-| Графика на Adreno телефона (`gpu=1`, OpenGL ES через Mesa) или программный рендер | Metal (есть компилятор шейдеров, самого Metal нет) |-| Звук из динамиков и запись с микрофона (`adsp=1 sound=4 mic=4`) | Вход в учётную запись Apple: нет Secure Enclave |-| Батарея и зарядка в интерфейсе (через звуковой процессор, `adsp=1`) | |-| Вибромотор (`haptic=5`) | |-| Wi-Fi телефона: радио, драйвер, подключение к сети (`wifi=1`) | |-| Камеры в Camera.app (`cam=5`) | |-| Данные `/private/var` между перезагрузками (`var_store=1 ufs_write=1`) | |-| Sileo и пакеты Procursus, SSH на телефон | |--## Быстрый старт: QEMU--Нужны Linux x86-64, ~12 ГБ места, 7-Zip 23+, `lz4`, `qemu-system-aarch64`, `edk2-aarch64`.+HakiOS runs the open-source XNU kernel (xnu-8796.121.2) with my own boot loader and my own drivers+on an Android phone with a Qualcomm SoC, and boots the stock iOS 16.5 user space on top of it:+launchd, backboardd, SpringBoard, the apps. The same thing runs in QEMU (`virt`, aarch64) on a+Linux PC.-```sh-git clone https://github.com/vcvkk/darwin-redwood.git-cd darwin-redwood-ios165/fetch.sh # IPSW iOS 16.5 с серверов Apple, распаковка нужного (7,4 ГБ)-REST=1 userland/build.sh # образы APFS: userland/root.apfs и userland/system.apfs-mkdir -p logs-qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 минут-```+Nothing is flashed. The loader goes into RAM through `fastboot boot`, the system lives in RAM for+the length of a session, and a reboot brings the phone back to its own Android. This is a research+bench, not a ROM.++The first phone is the **POCO X5 Pro 5G** (`redwood`, Snapdragon 778G). The kernel knows nothing+about it in advance: every address, interrupt, power rail and firmware comes from the phone's own+device tree and its own Android, so a port to another Qualcomm phone is a new directory under+`devices/`, not a rewrite.++## What is in the repository++Only my code and my data:++- the kernel: a patch to Apple's open-source XNU (`xnu/redwood.patch`, APSL 2.0) and my driver+ files (`xnu/files/`), laid over a fresh clone by `xnu/apply.sh`;+- the boot loader (`xnuloader/`), my programs and libraries (`userland/src/`), tools (`tools/`),+ build and run scripts;+- `prebuilt/`: the kernel, loader and libraries built from this repository;+- `devices/redwood/`: what one phone needs (its UEFI port, device tree, firmware script).-Через 2–3 минуты появится экран блокировки. Мышь с зажатой кнопкой — палец; `H` — «Домой», `L` —-питание, `↑`/`↓` — громкость.+Not in the repository, never:-## На телефоне+- any file of iOS: no binary, image, cache, font, picture or screenshot. You build the system+ image on your machine from the iOS 16.5 IPSW, which `sysimage/fetch.sh` downloads from Apple's+ public servers for you, without decrypting or circumventing anything;+- the phone's firmware (GPU, Wi-Fi, audio DSP, modem, haptics, cameras): it is the vendor's and+ is pulled from your own phone into `fw-*/`, which git ignores;+- keys, certificates, activation, or anything that would make the phone pass as an iPhone to+ Apple's services. Signing in to an Apple account is impossible here and not a goal.-Нужен телефон, для которого есть порт (сейчас — `devices/redwood/`, POCO X5 Pro 5G), с-разблокированным загрузчиком, `adb` и `fastboot`, образы из предыдущего раздела и прошивки-телефона из его Android:+## Status++| Works | Not yet |+|---|---|+| Lock screen, home screen, Control Center, gestures, the stock apps | Cellular: the modem boots, sees the network, the SIM is bound; registration and the status bar bars are in progress (`docs/cellular.md`) |+| Touch screen, multitouch, power and volume buttons | Bluetooth |+| All 8 CPU cores, the big core at 2.4 GHz | Charging under this kernel |+| GPU rendering on Adreno (`gpu=1`, OpenGL ES through Mesa) | Metal (there is a shader compiler, no Metal) |+| Speakers and microphone (`adsp=1 sound=4 mic=4`) | Apple account: no Secure Enclave |+| Battery level in the UI (through the audio DSP, `adsp=1`) | |+| Vibration (`haptic=5`) | |+| Wi-Fi: radio, driver, network connection (`wifi=1`) | |+| Cameras in Camera.app (`cam=5`) | |+| `/private/var` kept across reboots (`var_store=1 ufs_write=1`) | |+| Sileo, Procursus packages, SSH into the phone | |++## Quick start in QEMU++Linux x86-64, about 12 GB of disk, 7-Zip 23 or newer, `lz4`, `qemu-system-aarch64`, `edk2-aarch64`.```sh-devices/redwood/pull-firmware.sh # GPU, Wi-Fi, звук/батарея, вибрация, модем, камеры → fw-*/+git clone https://github.com/oosexgang/hackios-xnu-kernel.git hakios+cd hakios+sysimage/fetch.sh # the iOS 16.5 IPSW from Apple's servers, the needed parts unpacked (7.4 GB)+REST=1 userland/build.sh # the APFS images: userland/root.apfs and userland/system.apfs+mkdir -p logs+qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # a 20-minute session```-Что попало в образ, `userland/build.sh` печатает строкой `build.sh: fw/: N files from ../fw-*: …`.+The lock screen appears after two or three minutes. The mouse with the button held is a finger;+`H` is Home, `L` is the power button, `↑`/`↓` are volume.++## On the phone++A phone with a port (`devices/redwood/`, POCO X5 Pro 5G), its boot loader unlocked, `adb` and+`fastboot` on the PC, the images from the previous section, and the phone's own firmware:```sh-./xl enter # Android → fastboot → наш загрузчик в ОЗУ-./xl ramdisk userland/system.apfs # образ системы в ОЗУ телефона (~80 с), один раз на сеанс+devices/redwood/pull-firmware.sh # GPU, Wi-Fi, audio/battery, haptics, modem, cameras -> fw-*/+./xl enter # Android -> fastboot -> our loader in RAM+./xl ramdisk userland/system.apfs # the system image into the phone's RAM (~80 s), once per loader sessionXL_SB_DELAY=8 XL_SECS=600 \XL_CMDLINE="bootcpu=7 cpus=8 cpufreq=1 ufs=2 touchscreen=1 gpu=1 adsp=1 sound=4 wifi=1 haptic=5 modem=1" \-./xl run # сеанс на 10 минут, журнал в logs/-./xl reboot # обратно в Android+./xl run # a 10-minute session, the log goes to logs/+./xl reboot # back to Android```-`tools/modem-cycle.sh "ARGS" SECS` делает всё это одной командой и возвращает телефон в Android.+`tools/modem-cycle.sh "ARGS" SECS` does all of that in one command and returns the phone to Android.-Главные параметры ядра (полный список — в `docs/notes.md`):+The main kernel arguments (the full list is in `docs/notes.md`):-| Параметр | Что даёт |+| Argument | What it does ||---|---|-| `cpus=8 bootcpu=7 cpufreq=1` | все ядра процессора и их частоты |-| `touchscreen=1` | сенсорный экран |-| `gpu=1` | отрисовка на Adreno (образ, собранный с `GL=1`, прошивки в `fw-gpu/`) |-| `adsp=1 sound=4 mic=4` | звуковой процессор: динамики, микрофон; с ним же батарея и зарядка |-| `haptic=5` | вибромотор |-| `wifi=1` | Wi-Fi (сеть из `fw-wifi/network`) |-| `cam=5` | камеры |-| `modem=1` | модем рядом с системой: его прошивка, файловые системы, IPA, SIM, NAS |-| `modem_step=N` | модем по шагам, для отладки (`docs/cellular.md`) |-| `var_store=1 ufs_write=1` | сохранять `/private/var` между перезагрузками |--## Сборка из исходников--Ядро (Linux: theos с cctools и `iPhoneOS16.5.sdk`; macOS: Xcode или cctools, SDK подтягивается сам):+| `cpus=8 bootcpu=7 cpufreq=1` | all CPU cores and their clocks |+| `touchscreen=1` | the touch screen |+| `gpu=1` | rendering on Adreno (an image built with `GL=1`, firmware in `fw-gpu/`) |+| `adsp=1 sound=4 mic=4` | the audio DSP: speakers, microphone; battery and charging come with it |+| `haptic=5` | the vibration motor |+| `wifi=1` | Wi-Fi (the network from `fw-wifi/network`) |+| `cam=5` | the cameras |+| `modem=1` | the modem beside the system: its firmware, file systems, IPA, SIM, NAS |+| `modem_step=N` | the modem step by step, for debugging (`docs/cellular.md`) |+| `var_store=1 ufs_write=1` | keep `/private/var` across reboots |++## Building from source++The kernel (Linux: theos with its cctools and `iPhoneOS16.5.sdk`; macOS: Xcode or cctools, the SDK+is fetched for you):```sh-xnu/apply.sh # исходники XNU с GitHub Apple + наши правки → xnu-src/-xnu-deps/setup.sh # зависимости, инструменты и SDK-./xnu-build.sh -j8 -k # → xnu-src/…/BUILD/obj/DEVELOPMENT_ARM64_BCM2837/mach.development.bcm2837+xnu/apply.sh # XNU sources from Apple's GitHub + my changes -> xnu-src/+xnu-deps/setup.sh # dependencies, tools and the SDK+./xnu-build.sh -j8 -k # -> xnu-src/.../BUILD/obj/DEVELOPMENT_ARM64_BCM2837/mach.development.bcm2837```-Загрузчик: `xnuloader/build.sh` (clang + lld-link, EFI-приложение без EDK2). Заголовок-`xnuloader/identity.h` — свойства, по которым iOS узнаёт, «какой она iPhone», — в репозитории не-хранится: `xnuloader/mkidentity.sh` делает его при сборке из дерева устройств вашего IPSW (один файл-в 34 КБ с серверов Apple, LZFSE декодирует `lzfse`, `compression_tool` macOS или модуль Python-`lzfse`; без них собирается открытая библиотека lzfse). Userland и образы:-`REST=1 userland/build.sh` (`MODEM=1 SYSTEM=1` кладут прошивку модема в образ системы). Подробности —-`xnu/README.md` и `docs/notes.md`.+The loader: `xnuloader/build.sh` (clang + lld-link, an EFI application without EDK2). The header+`xnuloader/identity.h`, the properties by which iOS tells which iPhone it is, is not kept in the+repository: `xnuloader/mkidentity.sh` makes it at build time from the device tree in your own IPSW+(one 34 KB file; LZFSE is decoded by `lzfse`, macOS's `compression_tool` or the Python `lzfse`+module, or the open lzfse library gets built). User space and the images: `REST=1 userland/build.sh`+(`MODEM=1 SYSTEM=1` put the modem's firmware into the system image). Details: `xnu/README.md`,+`docs/notes.md`.-## Где что лежит+## Layout-| Каталог | Содержимое |+| Directory | Contents ||---|---|-| `xnu/` | патч и файлы ядра; `apply.sh`, `export.sh`; `README.md` о ядре |-| `xnu/files/bsd/dev/redwood_*.c` | наши драйверы: экран, тач, UFS, GPU, Wi-Fi, звук, модем (`redwood_mpss.c`), SIM/NAS, вибро, камеры |-| `xnuloader/` | загрузчик (UEFI-приложение) |-| `userland/` | наши программы и библиотеки (`src/`), сборка образов, задания launchd |-| `ios165/` | сценарии получения iOS 16.5 из IPSW (самих файлов нет) |-| `tools/` | APFS, прошивки, тесты QMI, сценарии прогонов |-| `qemu/` | запуск в QEMU |-| `docs/` | `notes.md` — подробные заметки, `cellular.md` — сотовая связь, `air.md`/`metal.md` — GPU |-| `prebuilt/` | собранные ядро, загрузчик, библиотеки |-| `devices/redwood/` | всё про один телефон: его UEFI (порт Mu-Silicium), дерево устройств, готовые образы UEFI, скрипт снятия прошивок, инструменты |--## Устройства--Ядро, загрузчик и userland — общие. Всё, что относится к одному телефону, живёт в `devices/<имя>/`:-его UEFI, дерево устройств, список прошивок и инструменты. Сейчас там один каталог,-`devices/redwood/` (POCO X5 Pro 5G), и его README — карта того, что нужно для порта на другой-аппарат на Qualcomm. Сами драйверы телефона — файлы `xnu/files/bsd/dev/redwood_*.c`; в начале каждого-написано, откуда взяты числа. Прошивки телефона снимаются с вашего аппарата-(`devices/redwood/pull-firmware.sh`) и в репозиторий не входят.--## Сотовая связь--Модем (Hexagon MPSS) поднимается из XNU: прошивка через TrustZone, общая память, SMP2P, GLINK, QRTR,-QMI; файловые системы модема отдаются с UFS (только чтение, записи живут в памяти ядра), TFTP и-реестр служб — наши. Пакетный ускоритель IPA запускается с прошивкой, тактом и SMMU, рукопожатие-с модемом проходит. SIM-карта привязывается к подписке, NAS читает сигнал. Текущее состояние и история —-в `docs/cellular.md`.--## Лицензии и юридическая сторона--Мой код — под той же лицензией, что и файлы, которые он изменяет: патч к XNU — Apple Public Source-License 2.0 (исходники XNU открыты Apple именно под ней, и условия я соблюдаю: изменения публикуются-в виде исходников, уведомления сохранены), остальное — см. заголовки файлов. iOS, её образы,-товарные знаки Apple и прошивки телефона принадлежат их владельцам, в репозиторий не входят и мною-не распространяются; каждый получает их сам со своего телефона и из своего IPSW. Названия «iOS»,-«iPhone», «Apple» упоминаются только для описания того, с чем работает код. Если какой-то файл-здесь, по вашему мнению, нарушает чьи-то права — напишите в issue, я уберу его.+| `xnu/` | the kernel patch and files; `apply.sh`, `export.sh`; a README about the kernel |+| `xnu/files/bsd/dev/redwood_*.c` | my drivers: display, touch, UFS, GPU, Wi-Fi, audio, modem (`redwood_mpss.c`), SIM/NAS, haptics, cameras |+| `xnuloader/` | the boot loader (a UEFI application) |+| `userland/` | my programs and libraries (`src/`), the image build, launchd jobs |+| `sysimage/` | scripts that fetch and unpack the OS files from the IPSW (none of the files themselves) |+| `devices/redwood/` | one phone: its UEFI port, device tree, prebuilt UEFI images, firmware script, tools |+| `tools/` | APFS, firmware, QMI tests, run scripts |+| `qemu/` | running in QEMU |+| `docs/` | `notes.md`: the detailed notes (Russian); `cellular.md`: cellular; `air.md`, `metal.md`: the GPU |+| `prebuilt/` | the built kernel, loader and libraries |++## Devices++The kernel, loader and user space are shared. Everything about one phone lives in+`devices/<name>/`: its UEFI, device tree, firmware list and tools. Today there is one,+`devices/redwood/`, and its README is the map of what a port to another Qualcomm phone must bring.+The phone's drivers are the files `xnu/files/bsd/dev/redwood_*.c`; the head of each says where its+numbers came from.++## Cellular++The modem (the Hexagon MPSS) is brought up from XNU: firmware through TrustZone, shared memory,+SMP2P, GLINK, QRTR, QMI; its file systems are served from the UFS (read-only, writes stay in kernel+memory), TFTP and the service registry are mine. The IPA packet engine runs with its firmware,+clock and SMMU context, and the handshake with the modem goes through. The SIM is bound to the+subscription and NAS reads the signal. The current state and the whole story are in+`docs/cellular.md`.++## Licenses and the legal side++My code is under the license of the files it changes: the XNU patch under the Apple Public Source+License 2.0 (Apple publishes XNU under it; the terms are met: changes are published as source,+notices are kept), the rest as the file headers say. iOS, its images, Apple's trademarks and the+phone's firmware belong to their owners, are not in this repository and are not distributed by me;+everyone takes them from their own phone and their own IPSW. "iOS", "iPhone" and "Apple" are+named only to describe what the code works with. If you believe a file here infringes anyone's+rights, open an issue and I will remove it.diff --git a/docs/air.md b/docs/air.mdindex d0e4f88..9fc1d2c 100644--- a/docs/air.md+++ b/docs/air.md@@ -70,7 +70,7 @@ alignment). That ABI is the runtime's, not the compiler's, and it is not implemeis this project's own calling convention, invented to make the bodies runnable.**And what the 456 itself is not: the number of shaders on the device.** It is the number of-modules in the `.metallib` *files* under `ios165/rootfs`. A library can also be a blob inside a+modules in the `.metallib` *files* under `sysimage/rootfs`. A library can also be a blob inside adylib — `GPUCompiler`'s own `GNR.videoprocessor` carries one in `__DATA`, found while looking forsomething else — so every statement here of the form "the corpus contains no X" is bounded by howthe corpus was collected, not by what the system contains. Where that distinction matters, this@@ -706,7 +706,7 @@ LLVM parameter type, and the NIR value is cut or converted to it.What each `air.*` name means was a guess until this was read, and one of the guesses was wrong.`AGXCompilerCore` — the back end of Apple's own shader compiler, in **this device's** shared-cache (`ios165/20F66__iPhone10,3_6`, never another device's) — carries its whole operation+cache (`sysimage/20F66__iPhone10,3_6`, never another device's) — carries its whole operationvocabulary as a run of C strings at file offsets `0x16cf9f`–`0x16d400`, which is virtual`0x1bbf43f9f`–`0x1bbf44400` (`__cstring` begins at file 1 482 768 for `0x1bbf41010`). 137 names,and they are suffixes: the full function is `air.` + name + `.` + a type suffix, which is why@@ -798,7 +798,7 @@ above, and the six-line listing of `clearFragment01` in `docs/metal.md` sectionsubstitutes for the thing it came from, and both carry the analysis they exist to support. Nothingcommitted anywhere is corpus bytes as an input: `docs/air-report.md` holds module names, counts anderror strings, which are facts about Apple's shaders and not Apple's shaders, and no test here has-a fixture — `tools/air/check.sh` reads `ios165/rootfs`, which is not in the repository and cannot+a fixture — `tools/air/check.sh` reads `sysimage/rootfs`, which is not in the repository and cannotbe.The part needing a decision rather than a convention: whether that line is the right one, and what@@ -1177,8 +1177,8 @@ the SPIR-V frontend does) and **I/O lowering** (variables with locations, then `The corpus report (`tools/air/corpus.py report`) is the progress meter: every number below comesout of it, and it runs from `tools/air/check.sh` (section 6). Two corpora:-- **the device image** — the five `.metallib` files the port installs (`ios165/rootfs` +- `ios165/cryptex`): 456 modules. This is the corpus the milestones are stated against.+- **the device image** — the five `.metallib` files the port installs (`sysimage/rootfs` ++ `sysimage/cryptex`): 456 modules. This is the corpus the milestones are stated against.- **the full IPSW** — all 134 MTLB libraries of the iOS 16.5 root filesystem and cryptexes,16 841 functions, extracted from `rootfs.dmg` with 7-Zip. Reported alongside, because thedevice image is a selection and the system's own shaders are this set.diff --git a/docs/metal.md b/docs/metal.mdindex 8a89e19..a3f09de 100644--- a/docs/metal.md+++ b/docs/metal.md@@ -2,7 +2,7 @@Разбор: что в iOS 16.5 просит Metal, где проходит граница, которую пришлось бы реализовать, истоит ли её переходить. Всё, что ниже, проверено по извлечённой системе-(`ios165/rootfs`, кэш `ios165/20F66__iPhone10,3_6/dyld_shared_cache_arm64`), по исходникам порта и+(`sysimage/rootfs`, кэш `sysimage/20F66__iPhone10,3_6/dyld_shared_cache_arm64`), по исходникам порта ипо журналам прогонов; адреса — невыровненные (unslid) адреса этого кэша.Коротко, в четырёх пунктах:diff --git a/docs/notes.md b/docs/notes.mdindex 23e50e5..1605994 100644--- a/docs/notes.md+++ b/docs/notes.md@@ -56,7 +56,7 @@ sudo pacman -S --needed git python 7zip lz4 gcc qemu-system-aarch64 qemu-ui-gtk```shgit clone [email protected]:vcvkk/darwin-redwood.gitcd darwin-redwood-ios165/fetch.sh # скачивает 7,4 ГБ с CDN Apple и распаковывает нужное (минут 5–15)+sysimage/fetch.sh # скачивает 7,4 ГБ с CDN Apple и распаковывает нужное (минут 5–15)REST=1 userland/build.sh # собирает образы APFS: userland/root.apfs и userland/system.apfs (2,5 ГБ)mkdir -p logsqemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 минут@@ -65,7 +65,7 @@ qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 миЧерез 2–3 минуты в окне появится экран блокировки.**Сколько это занимает.** Измерено 20 октября на этой машине (Linux x86-64, 12 потоков, NVMe), проходом-по этим самым командам из чистого клона: `ios165/fetch.sh` — 1 мин 45 с, из них скачивание криптексов+по этим самым командам из чистого клона: `sysimage/fetch.sh` — 1 мин 45 с, из них скачивание криптексов2,7 ГБ (образ корня, 4,7 ГБ, в этом прогоне уже лежал рядом; с нуля к этому времени добавится егоскачивание — на том же канале около трёх минут); `REST=1 userland/build.sh` — 1 мин 52 с; QEMU доэкрана блокировки — ещё 2–3 минуты. То есть около восьми минут от пустого каталога до iOS, если канал@@ -197,7 +197,7 @@ codec DMA TX_CDC_DMA_TX_3 и звуковой процессор в поток,CoreGraphics в них не рисовал — плитки оставались нулями. Теперь загрузчик пишет в дерево sRGB, как и есть унашего кадрового буфера, и WebKit рисует в BGRA (`xnuloader/loader.c`, `dt_identity()`; проверка —`RC_JOBS=rc.jobs.safari`). Цветные эмодзи и китайский шрифт PingFang (130 и 74 МБ) целиком в образ системы не- помещаются, и их знаки выходили квадратиками с вопросом; теперь `ios165/fetch.sh` кладёт их в образ уменьшенными+ помещаются, и их знаки выходили квадратиками с вопросом; теперь `sysimage/fetch.sh` кладёт их в образ уменьшенными(`tools/font_trim.py`): эмодзи — без самых крупных картинок (остаются 40, 64 и 96 точек; 59 МБ), PingFang — собычным и полужирным начертаниями упрощённого, традиционного и гонконгского письма (26 МБ). Проверка —`RC_JOBS=rc.jobs.fonts` (`font_test`: к какому шрифту система идёт за эмодзи, китайским, японским и корейским и@@ -234,7 +234,7 @@ codec DMA TX_CDC_DMA_TX_3 и звуковой процессор в поток,## На телефонеНужен именно **POCO X5 Pro 5G (redwood)** с разблокированным загрузчиком, `adb` и `fastboot` на компьютере-(`sudo pacman -S android-tools`), и образы из предыдущего раздела (`ios165/fetch.sh`, `REST=1 userland/build.sh`).+(`sudo pacman -S android-tools`), и образы из предыдущего раздела (`sysimage/fetch.sh`, `REST=1 userland/build.sh`).**Прошивка самого телефона.** В репозитории её нет и быть не может: она вендорская и берётся с того самогоаппарата, на котором всё будет работать, из его Android (подробности — в разделах по каждому устройству):@@ -1296,7 +1296,7 @@ APFS, и все их читает тот же драйвер APFS ядра, чту `mkapfs` из apfsprogs. `-z` — zlib, как Apple сжимает корень: маленький файл целиком в атрибуте`com.apple.decmpfs` (тип 3), остальные кусками по 64 КБ в ресурсной вилке (тип 4) — там, где это экономит блоки;`--plain fw` оставляет прошивки как есть, и драйверы ядра берут их прямо из памяти диска (`bsd/dev/redwood_image.c`;-то, что лежит не одним куском, копируется). Манифест (`ios165/system.manifest`) даёт владельцев и права. Хеш имён+то, что лежит не одним куском, копируется). Манифест (`sysimage/system.manifest`) даёт владельцев и права. Хеш имёнкаталога — CRC-32C по NFD, как у Apple. Жёстких ссылок нет: имя — отдельный файл.**Проверка.** Каждый контейнер, который делает сборка (`CHECK=1`), проверяют два читателя, которые не он:@@ -1419,7 +1419,7 @@ iOS, на блок за концом раздела, нули в супербл### Том данных между загрузками`/private/var` — файловая система в памяти (`bsd/miscfs/ramfs`): `init` монтирует её пустой при каждой загрузке и-создаёт в ней каталоги шаблона, который iOS носит в своём образе (`ios165/mkvarskel.py` → `ios165/var.skel`,+создаёт в ней каталоги шаблона, который iOS носит в своём образе (`sysimage/mkvarskel.py` → `sysimage/var.skel`,`init.c`, `mount_writable`). Поэтому ничто, что iOS туда записала, не переживало ту самую загрузку, в которуюбыло записано: ни раскладка домашнего экрана (`/var/mobile/Library/SpringBoard/IconState.plist`), ни данныеприложений (`/var/mobile/Containers/Data/Application/…`), ни снимки окон, ни запечённые обои — каждая загрузка@@ -1710,7 +1710,7 @@ xnuloader/build.sh # clang + lld-link → xnuloader/loader.efi (EFI-пр````xnuloader/identity.h` генерируется при сборке `xnuloader/mkidentity.sh` (через `mkidentity.py`) из дерева устройств-iPhone X в вашем IPSW (так система узнаёт, «какой она iPhone»); в репозитории его нет. Вручную: `python3 ios165/fetch-from-ipsw.py Firmware/all_flash/DeviceTree.d22ap.im4p dt.im4p`,+iPhone X в вашем IPSW (так система узнаёт, «какой она iPhone»); в репозитории его нет. Вручную: `python3 sysimage/fetch-from-ipsw.py Firmware/all_flash/DeviceTree.d22ap.im4p dt.im4p`,`ipsw img4 im4p extract dt.im4p -o dt.bin`, `xnuloader/mkidentity.py dt.bin > xnuloader/identity.h`. Кроме свойствкорня и `/product` оттуда же берётся узел `/product/haptics` (`closed-loop`, `supports-3rd-party-haptics`): по немуMobileGestalt отвечает `DeviceSupportsClosedLoopHaptics`, и iOS играет вибрацию и отклики волнами на устройстве@@ -1733,7 +1733,7 @@ REST=1 userland/build.sh- `userland/root.apfs` — маленький (наш init, библиотеки-вставки, задания launchd, прошивки); едет вместе сядром (`/dev/md1`, на `/redwood`), пересобирается за секунды;-- `userland/system.apfs` — корень: отобранная часть iOS 16.5 (`ios165/select-system.py`), криптексы OS (с кэшем+- `userland/system.apfs` — корень: отобранная часть iOS 16.5 (`sysimage/select-system.py`), криптексы OS (с кэшемdyld) и App на `/System/Cryptexes`. Пересобирается только при изменении входных данных или с `SYSTEM=1`;- `userland/flashboot.apfs` (`FLASHBOOT=1`) — то, что нужно в памяти, когда корень — том iOS на флеше: загрузочныйтом и оба криптекса, три контейнера подряд (см. «iOS с корнем на флеше»).@@ -2360,7 +2360,7 @@ fastboot boot ──► UEFI (Mu-Silicium, redwood) ──► xnuloader (EFI-п| `xnu-deps/` | всё для сборки XNU на Linux: `setup.sh`, обёртки инструментов, заглушки || `xnu-build.sh`, `xnu-env.sh` | сборка ядра || `userland/` | наш init, вставки (`src/inject.c` — backboardd, `src/inject_sb.c` — SpringBoard, `src/inject_media.c` — mediaserverd), звуковое устройство (`src/audio_plugin.c`), тесты, сборка образов |-| `ios165/` | добыча файлов iOS из IPSW и выбор того, что идёт в образ |+| `sysimage/` | добыча файлов iOS из IPSW и выбор того, что идёт в образ || `qemu/` | запуск в QEMU, касания, снимки экрана, разбор стеков || `uefi/`, `mkxnuimg.py` | порт UEFI на redwood и упаковка загрузочного образа для `fastboot boot` || `tools/` | `recording.py` (запись экрана → mp4), `sound.py` (запись звука → wav), `update-prebuilt.sh`, `new-workspace.sh` (вторая рабочая копия со своим ядром и QEMU), `mk-mesa.sh` (Mesa для `GL=1`), `mk-ath11k.sh` (драйвер Wi-Fi для ядра), `mk-jb.sh` (бутстрап Procursus и Sileo, см. «Sileo и пакеты»), `apfs/` (APFS на компьютере: чтение — «Чтение APFS», запись — «Запись в APFS», сборка образов `mkapfs.py` и их проверка `check-image.sh` — «Только APFS, как на iPhone»), `darwin-write.py` (запись в раздел `darwin` и только в него — «Криптексы на флеше»), `qmi-test/` и `wpa-test/` (проверки на компьютере) |@@ -2513,8 +2513,8 @@ mac80211 из Linux стоит наша станция (`wifi/lx/src/lx_80211.c`## Чтение APFS-Сначала корневая файловая система у нас была не APFS: `ios165/select-system.py` выбирал нужные файлы iOS из уже-распакованного `ios165/rootfs/`, а `mkpackfs.py` складывал их в наш образ `packfs` (только чтение, целиком в ОЗУ).+Сначала корневая файловая система у нас была не APFS: `sysimage/select-system.py` выбирал нужные файлы iOS из уже+распакованного `sysimage/rootfs/`, а `mkpackfs.py` складывал их в наш образ `packfs` (только чтение, целиком в ОЗУ).Чтобы ядро читало настоящий образ iOS как есть, нужен был свой APFS; теперь он — единственная файловая системаобразов (см. «Только APFS, как на iPhone»). Пишется он снизу вверх, и каждый слой сначала проверяется накомпьютере — в ядро идёт только то, что уже сошлось с настоящим образом.@@ -2527,9 +2527,9 @@ mac80211 из Linux стоит наша станция (`wifi/lx/src/lx_80211.c`| | ||---|---|-| `dmg.py` | `ios165/rootfs.dmg` — не файловая система, а образ диска UDIF: сначала сжатые куски, потом список блочных таблиц в XML, а в последних 512 байтах — хвост `koly`, который говорит, где этот список. Читает любое место распакованного образа и вынимает из него раздел. Виды кусков: как есть, нули, zlib, bzip2, LZMA, ADC, LZFSE (в нашем образе — LZFSE и «как есть») |+| `dmg.py` | `sysimage/rootfs.dmg` — не файловая система, а образ диска UDIF: сначала сжатые куски, потом список блочных таблиц в XML, а в последних 512 байтах — хвост `koly`, который говорит, где этот список. Читает любое место распакованного образа и вынимает из него раздел. Виды кусков: как есть, нули, zlib, bzip2, LZMA, ADC, LZFSE (в нашем образе — LZFSE и «как есть») || `apfs.py` | контейнер → контрольная точка → карта объектов → том → B-деревья → inode, каталоги, экстенты, расширенные атрибуты, дырки, сжатие `decmpfs`. Fletcher-64 проверяется у каждого прочитанного блока метаданных. Команды: `info`, `ls`, `tree`, `cat`, `stat`, `census` |-| `verify.py` | сверка с чужим читателем: тот же образ при распаковке читал 7-Zip, и от него остались `ios165/rootfs.slt` (список всего тома) и `ios165/rootfs/` (распакованные файлы) |+| `verify.py` | сверка с чужим читателем: тот же образ при распаковке читал 7-Zip, и от него остались `sysimage/rootfs.slt` (список всего тома) и `sysimage/rootfs/` (распакованные файлы) || `run-tests.sh` | всё, что проверяется на компьютере, одной командой || `write-tests.sh` | то же для записи: 81 проверка apfs_write.c против apfsck, apfs.py, 7-Zip и списка изменившихся блоков — «Запись в APFS» || `txn-probe.py` | настоящая транзакция APFS на образе `mkapfs.py`: одна запись изменена и зафиксирована новой контрольной точкой — «Запись в APFS» |@@ -2538,7 +2538,7 @@ mac80211 из Linux стоит наша станция (`wifi/lx/src/lx_80211.c`Распаковать раздел и проверить (образ нужен целиком, около 5,3 ГБ, в git он не кладётся):```sh-tools/apfs/dmg.py extract ios165/rootfs.dmg /куда/rootfs.apfs --apfs+tools/apfs/dmg.py extract sysimage/rootfs.dmg /куда/rootfs.apfs --apfstools/apfs/run-tests.sh /куда/rootfs.apfs```@@ -2596,7 +2596,7 @@ inode с `INODE_IS_SPARSE`), поэтому чтение дырок провер| `bsd/dev/redwood_apfs_check.c` | монтирует `/dev/rvblk0` и обходит том через VFS (`vnode_lookup`, `vnode_getattr`, `VNOP_READDIR`, `VNOP_READLINK`, `vn_rdwr`), печатая на запись ту же строку, что `apfs-tool census` и `verify.py clines`. Параметры ядра: `apfs_check=1` — только итоги, `=2` — каждая строка, `apfs_subtree=/путь` — часть тома. 318 098 строк — это 47 МБ через последовательный порт, поэтому по умолчанию каждая строка хешируется отдельно, а хеши складываются: сложению всё равно, в каком порядке обход видел записи. `verify.py sum` считает то же самое на хосте |```sh-tools/apfs/dmg.py extract ios165/rootfs.dmg /куда/rootfs.apfs --apfs+tools/apfs/dmg.py extract sysimage/rootfs.dmg /куда/rootfs.apfs --apfsCMDLINE="virtio_blk=1 apfs_check=1" qemu/run-ios.sh 1200 \-drive file=/куда/rootfs.apfs,format=raw,if=none,id=apfsd,readonly=on \-device virtio-blk-device,drive=apfsd@@ -3018,7 +3018,7 @@ APFS никогда не перезаписывает уже опубликовЕщё одно правило — порта, а не APFS: том с ролью системного или preboot отвергается. Это стоит сказать вслух,потому что остальные проверки его не ловят. Корневой том iOS 16.5 в том виде, в каком его берёт порт-(`ios165/rootfs.dmg`, он же записанный в `darwin`), **не запечатан**, без снимков и без метаданных целостности+(`sysimage/rootfs.dmg`, он же записанный в `darwin`), **не запечатан**, без снимков и без метаданных целостности(`incompatible 0x8` — только нечувствительность к нормализации, роль `0x0001`): он прошёл бы любую проверку APFS,какая здесь есть. На телефоне его хранит не она, а то, куда записи вообще разрешено идти: `BLOCK_WRITE_FIRST`загрузчика и ядро, у которого блочные устройства отказывают в любой записи.@@ -3235,7 +3235,7 @@ iOS, которого она ждёт, — это уже другое: созд## Про файлы Apple и лицензии-- Файлов iOS в репозитории нет: `ios165/fetch.sh` скачивает их из IPSW с CDN Apple на вашу машину.+- Файлов iOS в репозитории нет: `sysimage/fetch.sh` скачивает их из IPSW с CDN Apple на вашу машину.- `xnu/` — производная работа от XNU, распространяется на условиях APSL 2.0, как и сам XNU; `prebuilt/mach.*` —ядро, собранное из этих исходников.- `xnu/files/bsd/miscfs/apfs/libzbitmap/` — декодер LZBITMAP libzbitmap (Corellium LLC, GPL-2.0+ OR MIT; здесь —diff --git a/qemu/symstack.py b/qemu/symstack.pyindex 450c5c8..663863b 100755--- a/qemu/symstack.py+++ b/qemu/symstack.py@@ -7,7 +7,7 @@ Reads the "ustacks:" (boot-args ustacks=NAME ustacks_at=SECONDS [ustacks_ms=PERI"userabort:" lines of a console log (and, before a "userabort:", the "First throw call stack" of the exceptionthat led to it), subtracts the shared cache slide and looks every address up in the iOS dyldshared cache with "ipsw dyld a2s". Lookups take a few seconds each, so the answers are kept-in ios165/a2s.json. Addresses outside the cache (the program itself) are shown as they are.+in sysimage/a2s.json. Addresses outside the cache (the program itself) are shown as they are."""import jsonimport os@@ -15,7 +15,7 @@ import reimport subprocessimport sys-BASE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'ios165')+BASE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'sysimage')CACHE = os.path.join(BASE, '20F66__iPhone10,3_6/dyld_shared_cache_arm64')KNOWN = os.path.join(BASE, 'a2s.json')CACHE_LOW, CACHE_HIGH = 0x180000000, 0x280000000 # unslid addresses of the shared cachediff --git a/ios165/fetch-from-ipsw.py b/sysimage/fetch-from-ipsw.pysimilarity index 100%rename from ios165/fetch-from-ipsw.pyrename to sysimage/fetch-from-ipsw.pydiff --git a/ios165/fetch.sh b/sysimage/fetch.shsimilarity index 100%rename from ios165/fetch.shrename to sysimage/fetch.shdiff --git a/ios165/mkvarskel.py b/sysimage/mkvarskel.pysimilarity index 100%rename from ios165/mkvarskel.pyrename to sysimage/mkvarskel.pydiff --git a/ios165/select-system.py b/sysimage/select-system.pysimilarity index 100%rename from ios165/select-system.pyrename to sysimage/select-system.pydiff --git a/tools/air/check.sh b/tools/air/check.shindex 15946eb..70da23f 100755--- a/tools/air/check.sh+++ b/tools/air/check.sh@@ -11,7 +11,7 @@# tools/air/check.sh -q only the numbers, write nothingset -eROOT=$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)-IOS=${IOS:-$ROOT/ios165}+IOS=${IOS:-$ROOT/sysimage}QUIET=0[ "${1:-}" = "-q" ] && QUIET=1diff --git a/tools/air/intrincheck.py b/tools/air/intrincheck.pyindex a6deff1..abb494d 100755--- a/tools/air/intrincheck.py+++ b/tools/air/intrincheck.py@@ -1434,7 +1434,7 @@ def main(argv):decls = [l.strip() for l in open(decls_file) if l.strip()]else:libs = []- for dirpath, _, names in os.walk(os.path.join(ROOT, "ios165/rootfs")):+ for dirpath, _, names in os.walk(os.path.join(ROOT, "sysimage/rootfs")):for n in names:if n.endswith(".metallib"):libs.append(os.path.join(dirpath, n))diff --git a/tools/air/kernelcheck.py b/tools/air/kernelcheck.pyindex fbfde0e..4306199 100755--- a/tools/air/kernelcheck.py+++ b/tools/air/kernelcheck.py@@ -43,10 +43,10 @@ AIR_RUN = os.environ.get(os.path.join(ROOT, "build/mesa-host/build/src/gallium/drivers/freedreno/air_run"))LIBS = [- "ios165/rootfs/System/Library/VideoDecoders/AV1SW.metallib",- "ios165/rootfs/System/Library/Extensions/AppleMetalGLRenderer.bundle/default.metallib",- "ios165/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/default.metallib",- "ios165/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/portrait_filters.metallib",+ "sysimage/rootfs/System/Library/VideoDecoders/AV1SW.metallib",+ "sysimage/rootfs/System/Library/Extensions/AppleMetalGLRenderer.bundle/default.metallib",+ "sysimage/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/default.metallib",+ "sysimage/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/portrait_filters.metallib",]# One row per cause, in the order a reader wants them: what works, then what isdiff --git a/tools/air/libcheck.py b/tools/air/libcheck.pyindex 0f822f0..dfded7a 100644--- a/tools/air/libcheck.py+++ b/tools/air/libcheck.py@@ -50,7 +50,7 @@ AIR_RUN = os.environ.get(os.path.join(ROOT, "build/mesa-host/build/src/gallium/drivers/freedreno/air_run"))CPUREF = os.path.join(ROOT, "tools/air/cpuref.py")-LIBS = ["ios165/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/"+LIBS = ["sysimage/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/""portrait_filters.metallib"]# The air.* operations whose result is exactly defined, by the family name indiff --git a/tools/air/texcheck.sh b/tools/air/texcheck.shindex 73e73da..b821692 100755--- a/tools/air/texcheck.sh+++ b/tools/air/texcheck.sh@@ -29,10 +29,10 @@ AIR2NIR=${AIR2NIR:-$ROOT/build/mesa-host/build/src/compiler/air/air2nir}LIBS=("$@")if [ ${#LIBS[@]} = 0 ]; thenLIBS=(- "$ROOT/ios165/rootfs/System/Library/VideoDecoders/AV1SW.metallib"- "$ROOT/ios165/rootfs/System/Library/Extensions/AppleMetalGLRenderer.bundle/default.metallib"- "$ROOT/ios165/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/default.metallib"- "$ROOT/ios165/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/portrait_filters.metallib"+ "$ROOT/sysimage/rootfs/System/Library/VideoDecoders/AV1SW.metallib"+ "$ROOT/sysimage/rootfs/System/Library/Extensions/AppleMetalGLRenderer.bundle/default.metallib"+ "$ROOT/sysimage/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/default.metallib"+ "$ROOT/sysimage/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/portrait_filters.metallib")fidiff --git a/tools/air/texopcheck.py b/tools/air/texopcheck.pyindex dcc69c3..e521e24 100755--- a/tools/air/texopcheck.py+++ b/tools/air/texopcheck.py@@ -323,7 +323,7 @@ def collect_declarations():air2nir = os.environ.get("AIR2NIR", os.path.join(ROOT, "build/mesa-host/build/src/compiler/air/air2nir"))out = set()- for dirpath, _, names in os.walk(os.path.join(ROOT, "ios165/rootfs")):+ for dirpath, _, names in os.walk(os.path.join(ROOT, "sysimage/rootfs")):for n in sorted(names):if not n.endswith(".metallib"):continuediff --git a/tools/apfs/mkapfs.py b/tools/apfs/mkapfs.pyindex 693fe9c..bbb4e65 100755--- a/tools/apfs/mkapfs.py+++ b/tools/apfs/mkapfs.py@@ -7,7 +7,7 @@ Each NAME=DIR becomes one volume of the container (volume 0 first), case-sensitinormalization-insensitive like the iOS volumes, unencrypted, read-only content laid out once.Permission bits and symbolic links are taken from DIR; everything is owned by root:wheelunless a manifest says otherwise (lines of: mode in octal with the type bits, uid, gid, path,-[link target]; ios165/system.manifest is one; a directory or symbolic link that is only in the+[link target]; sysimage/system.manifest is one; a directory or symbolic link that is only in themanifest is made). With -z a regular file is stored compressed when that makes it smaller,as Apple stores most of the iOS root volume: a small one whole in its decmpfs attribute (type3, no block of its own at all), a bigger one in 64 KB zlib pieces in its resource fork (type 4); but not what is under a --plain DIR (relative to the volume's root), which stays asdiff --git a/tools/apfs/run-tests.sh b/tools/apfs/run-tests.shindex 7f26c3d..7605c0c 100755--- a/tools/apfs/run-tests.sh+++ b/tools/apfs/run-tests.sh@@ -3,13 +3,13 @@## 1. the on-disk structures in apfs_format.h against the offsets apfs.py reads at# 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/)+# 3. the APFS reader against 7-Zip's, over every entry in the volume (needs sysimage/)+# 4. file contents against the files 7-Zip extracted, byte for byte (needs sysimage/)# 5. the C the kernel is built from against apfs.py, over the whole volume# 6. the hash in directory records, worked out as the C lookup does (needs the image)# 7. every name looked up by name through the C, against its directory (needs the image)#-# Steps 3 to 7 need the APFS partition unpacked out of ios165/rootfs.dmg; pass it as+# Steps 3 to 7 need the APFS partition unpacked out of sysimage/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;@@ -57,34 +57,34 @@ elsefiecho-echo "== 2. the UDIF reader on ios165/rootfs.dmg"-if [ -f "$ROOT/ios165/rootfs.dmg" ]; then- python3 "$HERE/dmg.py" info "$ROOT/ios165/rootfs.dmg" | tail -n 14 || fail=1+echo "== 2. the UDIF reader on sysimage/rootfs.dmg"+if [ -f "$ROOT/sysimage/rootfs.dmg" ]; then+ python3 "$HERE/dmg.py" info "$ROOT/sysimage/rootfs.dmg" | tail -n 14 || fail=1else- echo " skipped: ios165/rootfs.dmg is not here (run ios165/fetch.sh with KEEP=1)"+ echo " skipped: sysimage/rootfs.dmg is not here (run sysimage/fetch.sh with KEEP=1)"fiechoif [ -z "$IMAGE" ] || [ ! -f "$IMAGE" ]; thenecho "== 3, 4. skipped: no APFS image given"- echo " unpack one with: tools/apfs/dmg.py extract ios165/rootfs.dmg OUT.apfs --apfs"+ echo " unpack one with: tools/apfs/dmg.py extract sysimage/rootfs.dmg OUT.apfs --apfs"exit $failfiecho "== 3. every entry in the volume against 7-Zip's listing"-if [ -f "$ROOT/ios165/rootfs.slt" ]; then- python3 "$HERE/verify.py" listing "$IMAGE" "$ROOT/ios165/rootfs.slt" || fail=1+if [ -f "$ROOT/sysimage/rootfs.slt" ]; then+ python3 "$HERE/verify.py" listing "$IMAGE" "$ROOT/sysimage/rootfs.slt" || fail=1else- echo " skipped: ios165/rootfs.slt is not here"+ echo " skipped: sysimage/rootfs.slt is not here"fiechoecho "== 4. file contents against what 7-Zip extracted"-if [ -d "$ROOT/ios165/rootfs" ]; then- python3 "$HERE/verify.py" sample "$IMAGE" "$ROOT/ios165/rootfs" || fail=1+if [ -d "$ROOT/sysimage/rootfs" ]; then+ python3 "$HERE/verify.py" sample "$IMAGE" "$ROOT/sysimage/rootfs" || fail=1echo " (that is a sample of every kind; --all compares all of them)"else- echo " skipped: ios165/rootfs is not here"+ echo " skipped: sysimage/rootfs is not here"fiechodiff --git a/tools/apfs/verify.py b/tools/apfs/verify.pyindex 9460277..175c87d 100755--- a/tools/apfs/verify.py+++ b/tools/apfs/verify.py@@ -1,13 +1,13 @@#!/usr/bin/env python3# Check tools/apfs/apfs.py against something that is not us.#-# Two independent references, both already in ios165/:+# Two independent references, both already in sysimage/:#-# listing ios165/rootfs.slt -- what 7-Zip's own APFS reader saw in the same image-# (`7z l -slt rootfs.dmg`, made by ios165/fetch.sh). Covers every entry in+# listing sysimage/rootfs.slt -- what 7-Zip's own APFS reader saw in the same image+# (`7z l -slt rootfs.dmg`, made by sysimage/fetch.sh). Covers every entry in# the volume: path, mode, owner, size, symbolic-link target, inode number.#-# content ios165/rootfs/ -- the files 7-Zip actually extracted, compared byte for+# content sysimage/rootfs/ -- the files 7-Zip actually extracted, compared byte for# byte. This is the one that proves we decompress correctly.## clines the same lines tools/apfs/apfs-tool prints, so the C code that goes into the@@ -36,7 +36,7 @@ import apfsSYSTEM_OBJ_ID_MARK = 0x0FFFFFFF00000000-# ios165/fetch.sh cuts these two fonts down after extracting them, so what is on disk in+# sysimage/fetch.sh cuts these two fonts down after extracting them, so what is on disk in# the reference tree is deliberately not what is in the imageTRIMMED = {"System/Library/Fonts/CoreAddition/AppleColorEmoji-160px.ttc",diff --git a/tools/apfs/write-tests.py b/tools/apfs/write-tests.pyindex 02bf8c3..a18ef67 100755--- a/tools/apfs/write-tests.py+++ b/tools/apfs/write-tests.py@@ -809,9 +809,9 @@ def test_real_images():rc, out = run(TOOL, 'writable', path)say(rc == 0, '%s: %s' % (rel, out.strip().splitlines()[0].split(': ', 1)[-1]))- dmg = os.path.join(ROOT, 'ios165', 'rootfs.dmg')+ dmg = os.path.join(ROOT, 'sysimage', 'rootfs.dmg')if not os.path.exists(dmg):- print('[skip] ios165/rootfs.dmg is not here')+ print('[skip] sysimage/rootfs.dmg is not here')returnc = apfs.Container(dmg)try:diff --git a/tools/apfs/write-tests.sh b/tools/apfs/write-tests.shindex 16598e2..54bec97 100755--- a/tools/apfs/write-tests.sh+++ b/tools/apfs/write-tests.sh@@ -8,7 +8,7 @@# check-image.sh pins, cloned into xnu-deps/build/apfsprogs and built there: the# reader that has nothing to do with us and checks the space manager's bitmaps# against every block anything refers to-# 7-Zip a third APFS reader, already needed by ios165/fetch.sh+# 7-Zip a third APFS reader, already needed by sysimage/fetch.sh## usage: tools/apfs/write-tests.sh [-k] [TEST ...] (-k: keep the images in apfs-work)# The tests: baseline writes refusals volume-gates extent-gates power-failure real-imagesdiff --git a/tools/font_trim.py b/tools/font_trim.pyindex 62dd171..1a57846 100755--- a/tools/font_trim.py+++ b/tools/font_trim.py@@ -14,7 +14,7 @@ the phone's memory, made from the files themselves (nothing of them is in the rematches REGEX, and only the tables they use.Both write a TrueType collection that CoreText reads as it reads the original; DST may be SRC.-ios165/fetch.sh makes both for the system image this way.+sysimage/fetch.sh makes both for the system image this way."""import osimport rediff --git a/tools/new-workspace.sh b/tools/new-workspace.shindex 72aab35..458d3e4 100755--- a/tools/new-workspace.sh+++ b/tools/new-workspace.sh@@ -10,8 +10,8 @@## The kernel tree is copied as it is now, uncommitted work included, and that state is recorded# (refs/redwood/baseline in the copy's kernel tree): tools/kernel-delta.sh, run in the workspace,-# prints what was changed in the kernel since. Files below ios165/rootfs, ios165/cryptex and-# ios165/cryptex-app are hard links to this copy's: replace them, never edit them in place.+# prints what was changed in the kernel since. Files below sysimage/rootfs, sysimage/cryptex and+# sysimage/cryptex-app are hard links to this copy's: replace them, never edit them in place.# The phone is not part of a workspace: there is one, and ./xl belongs to the main copy.set -eROOT=$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)@@ -45,13 +45,13 @@ cp -a --reflink=auto "$ROOT/xnu-deps/." xnu-deps/# out with no /System/Cryptexes/App at all, and Safari's daemons and AuthenticationServicesAgent --# eight jobs -- then look to mkjobs.py like programs nobody has (build.sh at cryptex-app, present()).for d in rootfs cryptex cryptex-app "20F66__iPhone10,3_6"; do- if [ -e "$ROOT/ios165/$d" ]; then cp -al "$ROOT/ios165/$d" ios165/; fi+ if [ -e "$ROOT/sysimage/$d" ]; then cp -al "$ROOT/sysimage/$d" sysimage/; fidonefor f in system.files system.manifest var.skel .done-rootfs .done-cryptex .done-cryptex-app a2s.json; do- if [ -e "$ROOT/ios165/$f" ]; then cp -a "$ROOT/ios165/$f" ios165/; fi+ if [ -e "$ROOT/sysimage/$f" ]; then cp -a "$ROOT/sysimage/$f" sysimage/; fidonefor f in rootfs.dmg rootfs.slt cryptex-app.dmg extracted; do- if [ -e "$ROOT/ios165/$f" ]; then ln -s "$ROOT/ios165/$f" ios165/; fi+ if [ -e "$ROOT/sysimage/$f" ]; then ln -s "$ROOT/sysimage/$f" sysimage/; fidone# The firmware the build puts into the images -- the radio's, the audio DSP's, the GPU's. A copy# without them builds an image with no /fw and says nothing about it: gpu=1 then starts no GPU.diff --git a/userland/build.sh b/userland/build.shindex 7238ffa..e278ad5 100755--- a/userland/build.sh+++ b/userland/build.sh@@ -56,7 +56,7 @@# MODEM=1 stage checked local MPSS firmware from ../fw-modem in system.apfs /fw.# This does not start the modem; the XNU MPSS driver is still required.# system.apfs the system image, the root filesystem (the resident RAM disk, /dev/md0), an-# APFS container: the part of iOS 16.5 chosen by ../ios165/select-system.py at+# APFS container: the part of iOS 16.5 chosen by ../sysimage/select-system.py at# its real paths, the dyld shared cache, and src/stage0.c as /sbin/launchd (the# real one is /sbin/launchd.ios). 2.5 GB; upload once per loader session with# `xl ramdisk userland/system.apfs`. Rebuilt when missing, when its inputs@@ -83,16 +83,16 @@ source ../xnu-env.shCC="xnu-clang -arch arm64 -Os -static -nostdlib -ffreestanding -fno-stack-protector -fno-builtin -Wall -Wextra"LD="-Wl,-e,_start -Wl,-pagezero_size,0x100000000"DYN="xnu-clang -arch arm64 -isysroot ${THEOS:-$HOME/theos}/sdks/iPhoneOS16.5.sdk -O1"-IOS=../ios165+IOS=../sysimageCACHE=$IOS/20F66__iPhone10,3_6-# ios165/rootfs and ios165/cryptex must be this copy's own directories of hard links, the way+# sysimage/rootfs and sysimage/cryptex must be this copy's own directories of hard links, the way# tools/new-workspace.sh makes them. A symlink to another copy's tree makes sysroot a symlink too, because# cp -a does not follow one, and then every rm -rf and mv below edits the shared extraction in place. That# happened on 19 October 2026: 491 LaunchDaemons, NanoLaunchDaemons, LaunchAngels, xpc/launchd.plist and# private/var went out of the main copy's tree, and only the hard links in the other copies still held them.for d in rootfs cryptex cryptex-app; do[ -L $IOS/$d ] || continue- echo "build.sh: ios165/$d is a symlink to $(readlink $IOS/$d)" >&2+ echo "build.sh: sysimage/$d is a symlink to $(readlink $IOS/$d)" >&2echo "build.sh: it has to be a directory of this copy's own: rm it and cp -al the original over," >&2echo "build.sh: as tools/new-workspace.sh does. Building against a link damages the shared tree." >&2exit 1@@ -559,11 +559,11 @@ fiif [ -f $IOS/system.manifest ] && [ -f $CACHE/dyld_shared_cache_arm64 ] &&{ [ ! -f system.apfs ] || [ obj/stage0 -nt system.apfs ] || [ $IOS/system.manifest -nt system.apfs ] ||[ $IOS/cryptex -nt system.apfs ] || [ $IOS/cryptex-app -nt system.apfs ] || [ -n "$SYSTEM" ]; }; then- # what ios165/select-system.py has chosen since ios165/rootfs was extracted is not in it, and would not be+ # what sysimage/select-system.py has chosen since sysimage/rootfs was extracted is not in it, and would not be# in the image either (so it was once with the audio plug-ins and the system's sounds: iOS found no# speaker and played nothing, though our device was there and the kernel's side worked)if [ -f $IOS/.done-rootfs ] && [ $IOS/select-system.py -nt $IOS/.done-rootfs ]; then- echo "build.sh: ios165/select-system.py has changed since ios165/rootfs was extracted: run KEEP=1 ios165/fetch.sh" >&2+ echo "build.sh: sysimage/select-system.py has changed since sysimage/rootfs was extracted: run KEEP=1 sysimage/fetch.sh" >&2exit 1firm -rf sysrootdiff --git a/userland/jobinfo.py b/userland/jobinfo.pyindex e46a068..1a82fcd 100755--- a/userland/jobinfo.py+++ b/userland/jobinfo.py@@ -3,7 +3,7 @@With -s, find the jobs that provide a Mach service whose name contains SERVICE.The jobs are those of System/Library/LaunchDaemons and LaunchAngels."""import glob, json, os, plistlib, sys-ROOTFS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'ios165/rootfs')+ROOTFS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'sysimage/rootfs')DIRS = [ROOTFS + '/System/Library/LaunchDaemons', ROOTFS + '/System/Library/LaunchAngels']def show(path):d = plistlib.load(open(path, 'rb'))diff --git a/userland/mkjobs.py b/userland/mkjobs.pyindex 3def27b..f9acbc9 100755--- a/userland/mkjobs.py+++ b/userland/mkjobs.py@@ -15,7 +15,7 @@ What "there at run time" means is the recipe, not what happens to be unpacked ontwo recipes differ. With the system image as the root, it is what select-system.py chose, and a daemon itleft out as too big really is absent. With the iOS volume on the phone's flash as the root (build.shFLASHBOOT=1), the root is Apple's whole volume: --root-volume names the technical listing of its image-(ios165/rootfs.slt) and a program counts as there if Apple ships it. Seven jobs turn on that --+(sysimage/rootfs.slt) and a program counts as there if Apple ships it. Seven jobs turn on that --fairplayd, identityservicesd, passd, assistantd, callservicesd, lskdd, searchpartyd -- and were beingrefused on a flash boot for a reason true only of the thinned copy here. (fairplayd now runs on the phoneand is never missed from a lookup again, but it does not stay: it exits 0 the moment it starts, says nothing,diff --git a/userland/src/init.c b/userland/src/init.cindex f21bca0..676e98c 100644--- a/userland/src/init.c+++ b/userland/src/init.c@@ -837,7 +837,7 @@ mount_writable(void)}check(ok, "mount a memory filesystem on /private/var");- /* the directories of the data volume, as listed in the template that ships with iOS (ios165/mkvarskel.py) */+ /* the directories of the data volume, as listed in the template that ships with iOS (sysimage/mkvarskel.py) */read_whole(in_image("/etc/var.skel"), skeleton, sizeof(skeleton));for (char *line = skeleton; ok && *line;) {char *end = strchr(line, '\n'), *f[6];diff --git a/userland/src/var_store.c b/userland/src/var_store.cindex 0a4fffd..3e496d3 100644--- a/userland/src/var_store.c+++ b/userland/src/var_store.c@@ -3,7 +3,7 @@* unpacked out of it again.** /private/var is a memory filesystem (bsd/miscfs/ramfs), mounted empty by init at every boot and- * given the directories of the template iOS ships with (ios165/mkvarskel.py), so nothing iOS keeps+ * given the directories of the template iOS ships with (sysimage/mkvarskel.py), so nothing iOS keeps* there outlives the boot that wrote it: no home screen layout, no application data, no baked* wallpaper. The kernel's APFS driver reads and does not write, and writing APFS is not the point* here -- what is needed is that the bytes come back. So the tree is packed into a plain archivediff --git a/xnu/files/bsd/dev/redwood_virtio_blk.c b/xnu/files/bsd/dev/redwood_virtio_blk.cindex e328481..97a469a 100644--- a/xnu/files/bsd/dev/redwood_virtio_blk.c+++ b/xnu/files/bsd/dev/redwood_virtio_blk.c@@ -3,7 +3,7 @@* guest (/dev/rvblk0). Only with boot-arg virtio_blk=1: the bus address is QEMU's and* means nothing on the phone.*- * This exists for the APFS driver. The volume in ios165/rootfs.dmg is 5.6 GB, which is+ * This exists for the APFS driver. The volume in sysimage/rootfs.dmg is 5.6 GB, which is* too much to hold in guest memory as a RAM disk the way this port's own images are held, and the* point of reading APFS is to read a real image rather than one cut down to fit. QEMU* serves it straight off the host's disk:diff --git a/xnuloader/mkidentity.sh b/xnuloader/mkidentity.shindex 77fe6d9..8203217 100755--- a/xnuloader/mkidentity.sh+++ b/xnuloader/mkidentity.sh@@ -3,7 +3,7 @@# from the device tree in the IPSW (Firmware/all_flash/DeviceTree.d22ap.im4p) at build time, on# the builder's machine, from their own copy of the firmware. The header is not in the repository.#-# ios165/fetch-from-ipsw.py the one file out of the IPSW on Apple's CDN (34 KB, HTTP ranges)+# sysimage/fetch-from-ipsw.py the one file out of the IPSW on Apple's CDN (34 KB, HTTP ranges)# xnuloader/im4p.py its payload: an LZFSE stream# lzfse(1) / compression_tool(1) / python3 -m lzfse / xnu-deps/host/bin/lzfse (built from the# BSD-licensed github.com/lzfse/lzfse when nothing else is there)@@ -17,7 +17,7 @@ WORK=$(mktemp -d "${TMPDIR:-/tmp}/mkidentity.XXXXXX")trap 'rm -rf "$WORK"' EXITIM4P=${1:-$WORK/dt.im4p}if [ ! -f "$IM4P" ]; then- python3 "$TOP/ios165/fetch-from-ipsw.py" Firmware/all_flash/DeviceTree.d22ap.im4p "$IM4P"+ python3 "$TOP/sysimage/fetch-from-ipsw.py" Firmware/all_flash/DeviceTree.d22ap.im4p "$IM4P"fipython3 "$HERE/im4p.py" "$IM4P" "$WORK/dt.lzfse"decode() {