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
Darwin, not iOS: the name in the sources, the documentation, the scripts and the files
shimoku7445df619a62a3
diff --git a/.gitignore b/.gitignoreindex 2ca5d65..103e0e1 100644--- a/.gitignore+++ b/.gitignore@@ -1,5 +1,5 @@# A whitelist: the working tree also holds gigabytes of downloads, build output, logs, third-party-# clones and files of iOS, none of which belongs in the repository. Nothing is tracked unless it+# clones and files of Darwin, none of which belongs in the repository. Nothing is tracked unless it# is named here./*!/.gitignorediff --git a/COMMUNITY.md b/COMMUNITY.mdindex ea438f3..e3c791a 100644--- a/COMMUNITY.md+++ b/COMMUNITY.md@@ -10,7 +10,7 @@ code and the money apart.request, or put a result in `docs/` ([CONTRIBUTING.md](CONTRIBUTING.md)).- **What a contribution is licensed under** is what the file it touches is under: the kernel patch and the filesthat sit in Apple's tree under APSL 2.0, everything else MIT ([LEGAL.md](LEGAL.md), [NOTICE](NOTICE)).-- **A contribution brings nothing of Apple's or a vendor's.** No iOS file, no firmware, no key, no screenshot of+- **A contribution brings nothing of Apple's or a vendor's.** No Darwin file, no firmware, no key, no screenshot ofeither. CI runs `tools/provenance-check.py` and fails a change that does. If you are not sure what counts, ask first.- **Results are reported as seen.** A test says what ran, on which phone, with which arguments, and what did not."Does not work" and "I did not try" are both useful, and are not the same.diff --git a/COMPLIANCE.md b/COMPLIANCE.mdindex 5f2ccf0..6d47843 100644--- a/COMPLIANCE.md+++ b/COMPLIANCE.md@@ -23,7 +23,7 @@ publishes under the APSL 2.0. The full text is in `LICENSE.APSL`. The obligation- **No re-licensing.** The XNU-derived code stays under the APSL; it is **not** relabeled MIT. TheMIT License in `LICENSE` applies only to our own non-XNU code.-What is NOT covered and must not be assumed covered by the APSL: iOS user space, Apple firmware,+What is NOT covered and must not be assumed covered by the APSL: Darwin user space, Apple firmware,trademarks, and any Apple binary. None of those are in this repository.## MIT (our own code)@@ -35,7 +35,7 @@ License (`LICENSE`). Contributions are accepted under the same terms (`CONTRIBUTEach third-party component is listed in `THIRD_PARTY_LICENSES.md` with its origin, license, andwhether it is redistributed in the tree or fetched at build time. Components fetched at build time-(the iOS SDK, Mesa, Procursus/Sileo, lzfse, ath11k, LinuxKPI headers) are never committed; they+(the Darwin SDK, Mesa, Procursus/Sileo, lzfse, ath11k, LinuxKPI headers) are never committed; theyare obtained from their own upstreams under their own licenses.## Items still to verifydiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 74128f5..14db99b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -3,9 +3,9 @@- One phone, one directory: anything that only one device needs goes to `devices/<name>/`; thekernel, loader and user space stay device-neutral and take their numbers from the device treeand the phone's own Android.-- Nothing of Apple's in the tree: no iOS files, images, caches, screenshots or headers derived+- Nothing of Apple's in the tree: no Darwin files, images, caches, screenshots or headers derivedfrom the firmware. The build takes what it needs from the IPSW the user got- themselves (`sysimage/unpack.sh`, `xnuloader/mkidentity.sh`); no script downloads Apple's files. CI refuses pictures and iOS files.+ themselves (`sysimage/unpack.sh`, `xnuloader/mkidentity.sh`); no script downloads Apple's files. CI refuses pictures and Darwin files.- Nothing of the vendor's either: firmware is pulled from the user's phone (`make firmware`).- Kernel changes are made in `xnu-src/` and exported with `xnu/export.sh` before committing;the patch must apply to Apple's `xnu-8796.121.2` tag (CI checks).@@ -22,7 +22,7 @@- The kernel patch and files are APSL 2.0 (derived from XNU); everything else is MIT. Do notrelabel XNU-derived code as MIT. New third-party code goes into `NOTICE` and`THIRD_PARTY_LICENSES.md` with its origin and license.-- Nothing of Apple's in the tree: no iOS files, images, caches, screenshots or headers derived+- Nothing of Apple's in the tree: no Darwin files, images, caches, screenshots or headers derivedfrom the firmware. Nothing of the vendor's firmware either. If you add a file whose origin orlicense you are not certain of, mark it "to verify" in `THIRD_PARTY_LICENSES.md` rather thanasserting it is cleared.@@ -32,7 +32,7 @@make qemu-open # kernel + placeholder loader + the hello RAM disk, under QEMU```- The full iOS user space (`make qemu`, `make phone`) additionally needs software and firmware you+ The full Darwin user space (`make qemu`, `make phone`) additionally needs software and firmware yousupply yourself.## CIdiff --git a/LEGAL.md b/LEGAL.mdindex 57ed30f..d0f56fa 100644--- a/LEGAL.md+++ b/LEGAL.md@@ -2,7 +2,7 @@HakiOS is an independent open-source research project that ports the open-source XNU kernel toARM64 Qualcomm hardware. It is **not affiliated with, endorsed by, or connected to Apple Inc.**-"iOS", "iPhone", "XNU", "Apple" and other marks belong to their owners and are used here only to+"Darwin", "iPhone", "XNU", "Apple" and other marks belong to their owners and are used here only todescribe what the code works with.This file explains, in plain terms, what is and is not distributed by this repository. It is a@@ -23,7 +23,7 @@ Linux to phones. It has three layers, and the project says plainly which one itships none, distributes none, and does not decrypt, circumvent or patch anything to obtain one: the tools only layout, on your own machine, files that you have downloaded yourself from the vendor. **Whether you may use suchsoftware on this hardware is your decision and your responsibility.** Be aware of what you are deciding: Apple's- software licence for iOS ties it to Apple-branded hardware and restricts copying and modification, courts have+ software licence for Darwin ties it to Apple-branded hardware and restricts copying and modification, courts havetreated that differently (see `docs/legal-review.md`), and the answer depends on your country and on what you do.The project does not tell you that it is permitted, and does not tell you that it is not; it tells you that it isnot the project's to decide.@@ -55,8 +55,8 @@ program that can write to flash, and CI fails if one appears that is not listed.## What this repository does NOT contain and never distributes-- **No part of iOS**: no iOS binary, image, cache, font, picture or screenshot. The user-space- half of the system image is built on your machine from the iOS 16.5 IPSW, which you+- **No part of Darwin**: no Darwin binary, image, cache, font, picture or screenshot. The user-space+ half of the system image is built on your machine from the Darwin userland 16.5 IPSW, which youget yourself, under Apple's license, and hand to `sysimage/unpack.sh` on your machine; no scripthere downloads it. Nothing of it is committed here.- **No device firmware**: the GPU, Wi-Fi, audio DSP, modem, haptics and camera firmware is the@@ -73,7 +73,7 @@ The core kernel, the boot loader and the open tools build and run with **nothingbuilds the kernel and a placeholder loader (no IPSW needed, see `xnuloader/mkidentity.sh--placeholder`) and boots a small raw-syscall user space (`userland/src/hello.c`) under QEMU.This is the configuration a contributor can build and test without downloading any closed Apple-software. The full iOS user space is an optional target that depends on software you supply.+software. The full Darwin user space is an optional target that depends on software you supply.## Reportingdiff --git a/LICENSE b/LICENSEindex 23abce4..8814a9d 100644--- a/LICENSE+++ b/LICENSE@@ -11,9 +11,10 @@ Two licenses apply, by directory:userland/src/, the tools, the scripts, the documentation, the device layer under devices/)is licensed under the MIT License below.-Third-party components and their licenses are listed in NOTICE. iOS, the iOS 16.5 IPSW, Apple's-trademarks and the phone's own firmware are not part of this repository and are not licensed by-it; every user obtains them from their own device and their own copy of the firmware.+Third-party components and their licenses are listed in NOTICE. Apple's operating system and its+firmware images (IPSW), Apple's trademarks and the phone's own firmware are not part of this+repository and are not licensed by it; every user obtains them from their own device and their own+copy of the firmware.----------------------------------------------------------------------------------------------diff --git a/Makefile b/Makefileindex a4da578..8ecdd0a 100644--- a/Makefile+++ b/Makefile@@ -2,12 +2,12 @@# below it; run the script itself for its options.## make help-# make unpack IPSW=F the OS files out of your own iOS 16.5 IPSW into sysimage/ (sysimage/unpack.sh)+# make unpack IPSW=F the OS files out of your own Darwin userland 16.5 IPSW into sysimage/ (sysimage/unpack.sh)# make images userland/root.apfs and userland/system.apfs (userland/build.sh)# make kernel the kernel from source (xnu/apply.sh, xnu-deps/setup.sh, xnu-build.sh)# make loader the boot loader, with identity.h made from your IPSW (xnuloader/build.sh)# make firmware the phone's firmware off the phone over adb (devices/$(DEVICE)/pull-firmware.sh)-# make qemu a 20-minute session in QEMU (needs the iOS images)+# make qemu a 20-minute session in QEMU (needs the Darwin images)# make qemu-open boot the open kernel in QEMU with NO Apple software# (kernel + the hello RAM disk + a placeholder loader)# make phone a session on the phone, then back to Android (tools/modem-cycle.sh)@@ -84,16 +84,16 @@ firmware:qemu:mkdir -p logs- qemu/run-ios.sh $(SECS) -display gtk | tee logs/qemu.log+ qemu/run-darwin.sh $(SECS) -display gtk | tee logs/qemu.log-# The Apple-free path: no IPSW, no iOS user space. The loader is built with a placeholder identity+# The Apple-free path: no IPSW, no Darwin user space. The loader is built with a placeholder identity# (xnuloader/mkidentity.sh --placeholder), and the kernel boots the raw-syscall `hello` RAM disk.# This is the configuration an outside contributor can build and run with nothing of Apple's.loader-open:PLACEHOLDER=1 xnuloader/mkidentity.shxnuloader/build.sh-# `hello` on its own: a static, raw-syscall program (no iOS SDK, no Apple libraries).+# `hello` on its own: a static, raw-syscall program (no Darwin SDK, no Apple libraries).hello:. ./xnu-env.sh && xnu-clang -arch arm64 -Os -static -nostdlib -ffreestanding \-fno-stack-protector -fno-builtin -Wl,-e,_start -Wl,-pagezero_size,0x100000000 \diff --git a/NOTICE b/NOTICEindex ca2335c..031ef5f 100644--- a/NOTICE+++ b/NOTICE@@ -22,7 +22,7 @@ In the repository:Fetched at build time, never committed:-- the iOS 16.5 IPSW (Apple): the user space of the system image; the user gets it and+- the Darwin userland 16.5 IPSW (Apple): the user space of the system image; the user gets it andsysimage/unpack.sh unpacks it on their machine; nothing downloads it; its license is Apple's.- the iPhoneOS 16.5 SDK from github.com/theos/sdks, and theos's cctools (Apple's open-source cctools): thekernel's and user space's build tools.diff --git a/README.md b/README.mdindex 2dc6b0e..1bdd84d 100644--- a/README.md+++ b/README.md@@ -30,7 +30,7 @@ apps describe what happens when you add layer 2 below yourself.## The three layers1. **The open core**: the kernel port, the loader, the drivers, the tools. All source, in these repositories.-2. **What you put on top**: the kernel can start a user space that you supply. It was built so that it can start the iOS 16.5+2. **What you put on top**: the kernel can start a user space that you supply. It was built so that it can start the Darwin userland 16.5user space, which you lay out yourself from files you download from Apple; nothing of it is shipped, and nothing iscircumvented to get it. Whether you may do that, and whether you want to, is your decision.3. **Apple's services** (activation, Apple ID, iCloud, the App Store): not supported and not a goal.@@ -48,7 +48,7 @@ make doctor # what this machine lacks, and what to domake qemu-open # the open kernel in QEMU: nothing of Apple's, nothing of a phone's```-iOS in QEMU (Linux, 12 GB of disk, Apple's IPSW downloaded for you), and a session on the phone:+Darwin in QEMU (Linux, 12 GB of disk, Apple's IPSW downloaded for you), and a session on the phone:[QEMU](docs/getting-started/qemu.md), [On the phone](docs/getting-started/phone.md).```sh@@ -83,23 +83,23 @@ XNU's `options` and `conf/files`), so a device's defconfig builds exactly the drIn it: only our own code and data: the patch to Apple's open-source XNU (`xnu/hakios.patch`, APSL 2.0) and our files, the bootloader, our programs and libraries, the tools, `prebuilt/` (built from this source; the loader **without** any Apple data:-`make loader` makes the one that starts iOS, on your machine, from your own IPSW), and the device and SoC directories.+`make loader` makes the one that starts Darwin, on your machine, from your own IPSW), and the device and SoC directories.-Never in it: any file of iOS (you build the system image on your machine from an IPSW you get yourself and hand to+Never in it: any file of Darwin (you build the system image on your machine from an IPSW you get yourself and hand to`sysimage/unpack.sh`; nothing is downloaded for you, decrypted or circumvented); the phone's firmware (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.## Independent, and Apple-free at the coreHakiOS is an independent research project. It is **not affiliated with or endorsed by Apple**;-"iOS", "iPhone", "XNU" and "Apple" are named only to describe what the code works with. The core+"Darwin", "iPhone", "XNU" and "Apple" are named only to describe what the code works with. The corekernel, the boot loader and the open tools build and run with nothing of Apple's:```shmake qemu-open # the open kernel + a placeholder loader + a tiny raw-syscall user space, in QEMU```-No IPSW, no iOS user space, no firmware. Booting the stock iOS user space (`make qemu`,+No IPSW, no Darwin user space, no firmware. Booting the stock Darwin user space (`make qemu`,`make phone`) is an optional path that needs the IPSW and the phone's firmware, which you supplyfrom your own device.@@ -107,9 +107,9 @@ from your own device.My code is under the license of the files it changes: the XNU patch under the Apple Public SourceLicense 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+notices are kept), the rest as the file headers say. Darwin, its images, Apple's trademarks and thephone'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+everyone takes them from their own phone and their own IPSW. "Darwin", "iPhone" and "Apple" arenamed only to describe what the code works with. If you believe a file here infringes anyone'srights, open an issue and I will remove it.@@ -118,7 +118,7 @@ these statements), `COMPLIANCE.md` (how the APSL 2.0 and other terms are met, anto verify), `THIRD_PARTY_LICENSES.md` (every third-party component with origin and license), and`NOTICE` (the short canonical list). None of this is legal advice.-hakios is an experimental project focused on bringing ios to android hardware. our goal is to make hakios free and accessible to everyone.+hakios is an experimental project focused on bringing darwin to android hardware. our goal is to make hakios free and accessible to everyone.owners:@oodze - founderdiff --git a/README.uk.md b/README.uk.mdindex 013af85..913cbab 100644--- a/README.uk.md+++ b/README.uk.md@@ -13,7 +13,7 @@ HakiOS — це адаптація ядра Darwin (відкритий XNU ві1. **Відкрите ядро**: порт ядра, завантажувач, драйвери, інструменти. Увесь код у цьому репозиторії.2. **Те, що ви кладете зверху**: ядро може запустити користувацький простір, який ви надаєте самі. Проєкт збудовано- так, що воно вміє запускати користувацький простір iOS 16.5, який ви самі збираєте з файлів, завантажених у+ так, що воно вміє запускати користувацький простір Darwin userland 16.5, який ви самі збираєте з файлів, завантажених уApple; проєкт нічого з цього не поширює і нічого не обходить, щоб це отримати. Чи можна вам це робити і чихочете ви — ваше рішення.3. **Сервіси Apple** (активація, Apple ID, iCloud, App Store): не підтримуються і не є метою.@@ -45,8 +45,8 @@ HakiOS — це адаптація ядра Darwin (відкритий XNU віЧого немає і не буде:-- жодного файлу iOS: ні бінарників, ні образів, ні кешів, ні шрифтів, ні картинок, ні знімків- екрана. Образ системи ви збираєте на своїй машині з IPSW iOS 16.5, який ви берете самі й+- жодного файлу Darwin: ні бінарників, ні образів, ні кешів, ні шрифтів, ні картинок, ні знімків+ екрана. Образ системи ви збираєте на своїй машині з IPSW Darwin userland 16.5, який ви берете самі йпередаєте `sysimage/unpack.sh`; за вас нічого не завантажується, не розшифровується й не обходиться;- прошивок телефона (GPU, Wi-Fi, аудіо-DSP, модем, вібро, камери): вони вендорські і знімаютьсяз вашого власного телефона в `fw-*/`, які git ігнорує;@@ -79,7 +79,7 @@ Linux x86-64, близько 12 ГБ на диску, 7-Zip 23 або новішgit clone -b hakios https://github.com/oosexgang/hakios-xnu-kernel.git hakioscd hakiosmake doctor # чого бракує цьому комп'ютеру (дисплей QEMU, UEFI, пам'ять) і що робити-make unpack IPSW=~/ваш.ipsw # ваш власний IPSW iOS 16.5, потрібне розпаковується (7,4 ГБ)+make unpack IPSW=~/ваш.ipsw # ваш власний IPSW Darwin userland 16.5, потрібне розпаковується (7,4 ГБ)make images # образи APFS: userland/root.apfs і userland/system.apfsmake loader # завантажувач з ідентичністю iPhone з ВАШОЇ копії IPSW (потрібні clang і lld)make qemu # сеанс на 20 хвилин@@ -89,10 +89,10 @@ make qemu # сеанс на 20 хвилинчорного екрана, потім логотип Apple, потім домашній екран приблизно за 5 хвилин на швидкому ПК (виміряно: логотип на 1-й хвилині, домашній екран на 5-й), на повільнішому довше. Миша ззатиснутою кнопкою — палець; `H` — «Додому», `L` — кнопка живлення, `↑`/`↓` — гучність.-**Якщо екран лишається чорним:** (0) чи ви виконали `make loader`? У `prebuilt/loader.efi` навмисно немає даних Apple (він запускає лише відкрите ядро), з ним iOS не стартує; `qemu/run-ios.sh` без вашого `xnuloader/loader.efi` відмовляється працювати й каже про це; (1) `tail -f logs/qemu.log` в іншому терміналі: за секунди має з'явитись+**Якщо екран лишається чорним:** (0) чи ви виконали `make loader`? У `prebuilt/loader.efi` навмисно немає даних Apple (він запускає лише відкрите ядро), з ним Darwin не стартує; `qemu/run-darwin.sh` без вашого `xnuloader/loader.efi` відмовляється працювати й каже про це; (1) `tail -f logs/qemu.log` в іншому терміналі: за секунди має з'явитись`== XNULOADER v3 ==`, далі рядки ядра і launchd; якщо порожньо — запустіть `make doctor`; (2) `qemu/screendump.sh` зберігаєте, що показує екран гостя (`logs/qemu-screen.png`), що б не робило вікно; (3) якщо вікна немає або воно чорне, а журнал-іде — у вашому QEMU може не бути GTK (WSL без WSLg): `qemu/run-ios.sh 1200 -display vnc=127.0.0.1:0` і VNC-клієнт на+іде — у вашому QEMU може не бути GTK (WSL без WSLg): `qemu/run-darwin.sh 1200 -display vnc=127.0.0.1:0` і VNC-клієнт на`127.0.0.1:5900`; (4) гість просить у QEMU 7 ГБ пам'яті (мінімум 6): на меншій пам'яті все дуже повільно.## На телефоні@@ -149,7 +149,7 @@ make images # користувацький простір і образиМій код — під ліцензією тих файлів, які він змінює: патч XNU — Apple Public Source License 2.0(повний текст у `LICENSE.APSL`; умови дотримано: зміни опубліковано у вихідниках, повідомлення-збережено), решта — MIT (`LICENSE`). iOS, її образи, торгові марки Apple і прошивки телефона+збережено), решта — MIT (`LICENSE`). Darwin, її образи, торгові марки Apple і прошивки телефонаналежать їхнім власникам, у репозиторій не входять і мною не поширюються; кожен бере їх зі своготелефона та свого IPSW. Сторонні компоненти перелічено в `NOTICE`. Якщо, на вашу думку, якийсьфайл тут порушує чиїсь права — відкрийте issue, і я його приберу.diff --git a/README.zh.md b/README.zh.mdindex f6d6130..1a380d3 100644--- a/README.zh.md+++ b/README.zh.md@@ -11,7 +11,7 @@ Linux 电脑上的 QEMU(`virt`,aarch64)里运行,不需要任何 Apple它分三层,项目说明自己对哪一层负责(`LEGAL.md`):1. **开放核心**:内核移植、引导程序、驱动、工具。全部是本仓库里的源码。-2. **你自己放在上面的东西**:内核可以启动你自己提供的用户空间。项目的构建方式使它能够启动 iOS 16.5 用户空间,但那是你自己用+2. **你自己放在上面的东西**:内核可以启动你自己提供的用户空间。项目的构建方式使它能够启动 Darwin userland 16.5 用户空间,但那是你自己用从 Apple 下载的文件在本机整理出来的;项目不提供其中任何内容,也不绕过任何限制去获取它。你是否可以这样做、是否愿意这样做,由你自己决定。3. **Apple 的服务**(激活、Apple ID、iCloud、App Store):不支持,也不是目标。@@ -38,7 +38,7 @@ Linux 电脑上的 QEMU(`virt`,aarch64)里运行,不需要任何 Apple永远不会有的东西:-- 任何 iOS 文件:没有二进制、镜像、缓存、字体、图片或截图。系统镜像由你在自己机器上用 iOS 16.5+- 任何 Darwin 文件:没有二进制、镜像、缓存、字体、图片或截图。系统镜像由你在自己机器上用 Darwin userland 16.5的 IPSW 构建,IPSW 由你自己获取并交给 `sysimage/unpack.sh`;项目不替你下载、不解密、不绕过任何东西;- 手机的固件(GPU、Wi-Fi、音频 DSP、调制解调器、振动、摄像头):属于厂商,从你自己的手机取到`fw-*/`,git 忽略这些目录;@@ -71,7 +71,7 @@ Linux x86-64,约 12 GB 磁盘,7-Zip 23 或更新,`lz4`,`qemu-system-aarcgit clone -b hakios https://github.com/oosexgang/hakios-xnu-kernel.git hakioscd hakiosmake doctor # 检查本机缺什么(QEMU 显示设备、UEFI 固件、内存)以及怎么办-make unpack IPSW=~/your.ipsw # 你自己获取的 iOS 16.5 IPSW,解包所需部分(7.4 GB)+make unpack IPSW=~/your.ipsw # 你自己获取的 Darwin userland 16.5 IPSW,解包所需部分(7.4 GB)make images # APFS 镜像:userland/root.apfs 和 userland/system.apfsmake loader # 引导程序,iPhone 的标识取自你自己的 IPSW 副本(需要 clang 和 lld)make qemu # 20 分钟的会话@@ -80,10 +80,10 @@ make qemu # 20 分钟的会话**你会看到什么。** CPU 是模拟的,所以很慢,窗口一开始是**黑的**,这是正常的:先黑一分钟左右,然后出现 Apple 标志,在较快的台式机上约 5 分钟后出现主屏幕(实测:1 分钟出现标志,5 分钟出现主屏幕),较慢的机器更久。按住鼠标键就是手指;`H` 是主屏键,`L` 是电源键,`↑`/`↓` 是音量。-**如果一直是黑屏:** (0) 你运行过 `make loader` 吗?`prebuilt/loader.efi` 里特意不含 Apple 的数据(它只能启动开放内核),用它 iOS 不会启动;没有你自己的 `xnuloader/loader.efi` 时 `qemu/run-ios.sh` 会拒绝运行并说明原因;(1) 在另一个终端运行 `tail -f logs/qemu.log`,几秒内应出现 `== XNULOADER v3 ==`,之后是内核和 launchd 的输出;+**如果一直是黑屏:** (0) 你运行过 `make loader` 吗?`prebuilt/loader.efi` 里特意不含 Apple 的数据(它只能启动开放内核),用它 Darwin 不会启动;没有你自己的 `xnuloader/loader.efi` 时 `qemu/run-darwin.sh` 会拒绝运行并说明原因;(1) 在另一个终端运行 `tail -f logs/qemu.log`,几秒内应出现 `== XNULOADER v3 ==`,之后是内核和 launchd 的输出;没有输出就运行 `make doctor`。(2) `qemu/screendump.sh` 会保存虚拟机屏幕当前的内容(`logs/qemu-screen.png`)。(3) 日志在走但没有窗口或窗口全黑:你的 QEMU 可能没有 GTK(例如没有 WSLg 的 WSL),用-`qemu/run-ios.sh 1200 -display vnc=127.0.0.1:0`,再用 VNC 客户端连接 `127.0.0.1:5900`。+`qemu/run-darwin.sh 1200 -display vnc=127.0.0.1:0`,再用 VNC 客户端连接 `127.0.0.1:5900`。(4) 虚拟机向 QEMU 要 7 GB 内存(至少 6 GB),内存不足时会非常慢。## 在手机上@@ -139,7 +139,7 @@ make images # 用户空间和镜像## 许可与法律我的代码遵循它所修改文件的许可:XNU 补丁为 Apple Public Source License 2.0(全文在-`LICENSE.APSL`;条款已满足:修改以源码形式发布,保留了声明),其余为 MIT(`LICENSE`)。iOS、+`LICENSE.APSL`;条款已满足:修改以源码形式发布,保留了声明),其余为 MIT(`LICENSE`)。Darwin、其镜像、Apple 商标和手机固件属于各自的所有者,不在本仓库中,也不由我分发;每个人从自己的手机和自己的 IPSW 取得它们。第三方组件列于 `NOTICE`。若你认为这里的某个文件侵犯了任何人的权利,请开一个 issue,我会删除它。diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.mdindex 66ab459..8a6f108 100644--- a/THIRD_PARTY_LICENSES.md+++ b/THIRD_PARTY_LICENSES.md@@ -27,7 +27,7 @@ This supersedes the summary in `NOTICE`, which stays as the short, canonical lis| Component | Fetched by | Origin | License ||---|---|---|---|-| iOS 16.5 IPSW (user space of the system image) | `sysimage/unpack.sh` | Apple | Apple's — user supplies, user's own copy |+| Darwin userland 16.5 IPSW (user space of the system image) | `sysimage/unpack.sh` | Apple | Apple's — user supplies, user's own copy || iPhoneOS 16.5 SDK | `xnu-deps/setup.sh` (github.com/theos/sdks) | Apple (headers) via theos | Apple's / theos || Apple open sources (AvailabilityVersions, libdispatch, libpthread, cctools, bootstrap_cmds) | `xnu-deps/setup.sh` | Apple | APSL 2.0 || MacOSX13.3 SDK (Kernel.framework DriverKit headers only) | `xnu-deps/setup.sh` | Apple via joseluisq/macosx-sdks | Apple's |diff --git a/ci/github-check.yml b/ci/github-check.ymlindex be13b45..a980573 100644--- a/ci/github-check.yml+++ b/ci/github-check.yml@@ -34,7 +34,7 @@ jobs:run: make help- name: Provenance - every binary and blob explained, nothing proprietary, nothing writes to the phonerun: |- # The rule of the repository: nothing of iOS, no pictures of it, no vendor firmware, and a+ # The rule of the repository: nothing of Darwin, no pictures of it, no vendor firmware, and a# promise that the project boots from RAM and does not write to the phone's storage. Every# binary must have a line in tools/provenance.allow saying where it came from.# (This replaces two lines of the form `! git ls-files | grep ...`: bash -e does not stop ondiff --git a/configs/common_defconfig b/configs/common_defconfigindex 3d8b427..43a370e 100644--- a/configs/common_defconfig+++ b/configs/common_defconfig@@ -73,7 +73,7 @@ CONFIG_HAKIOS_MODEM=y# QEMU's virtio network device as the link behind en0 (virtio_net=1). QEMU only [hakios.virtio_net.c]CONFIG_HAKIOS_VIRTIO_NET=y-# the battery: kern.hakios.battery_*, and HakiosBattery, the IOPMPowerSource iOS reads the charge from (the state ... [hakios.battery.c, hakios.battery.cpp]+# the battery: kern.hakios.battery_*, and HakiosBattery, the IOPMPowerSource Darwin reads the charge from (the state ... [hakios.battery.c, hakios.battery.cpp]CONFIG_HAKIOS_BATTERY=y# the clock of the cores the kernel runs on (cpufreq=1), and the memory bus's votes (ddr=) [hakios.cpufreq.c]@@ -1087,7 +1087,7 @@ CONFIG_MODEM_AGAIN=y# the renderer is made to answer that it has those functions after all# CONFIG_GLYES is not set-# the root is to be the iOS root volume on /dev/DEV -- the phone's flash, read only+# the root is to be the Darwin root volume on /dev/DEV -- the phone's flash, read only# CONFIG_ROOT_APFS is not set# read by inject_sb.c (user space)diff --git a/configs/symbols.tsv b/configs/symbols.tsvindex 6a3244b..e812a99 100644--- a/configs/symbols.tsv+++ b/configs/symbols.tsv@@ -190,7 +190,7 @@ REC_STEP arg rec_step GPU and display k MiniIOMobileFramebuffer.cppREGTRACE arg regtrace CPU, memory and boot k (patch)RETURN_CPU arg return_cpu CPU, memory and boot k loader_return.cRETURN_PANIC arg return_panic CPU, memory and boot k loader_return.c-ROOT_APFS arg root_apfs User space u init.c the root is to be the iOS root volume on /dev/DEV -- the phone's flash, read only+ROOT_APFS arg root_apfs User space u init.c the root is to be the Darwin root volume on /dev/DEV -- the phone's flash, read onlySERIAL arg serial Loader l loader.cSMALL_CORES arg small_cores CPU, memory and boot k (patch)SMALL_CORES_AFTER arg small_cores_after CPU, memory and boot k GenericARMPE.cppdiff --git a/docs/air.md b/docs/air.mdindex 712bb1d..95d7d06 100644--- a/docs/air.md+++ b/docs/air.md@@ -544,7 +544,7 @@ This is the biggest commitment of the project, so both sides in full.stock `llvm-dis` 22.1.8 without a failure; day one would be spent on translation, not parsing.- It comes with passes. If a shader ever needs SROA, inlining or `mem2reg` before translation, LLVMhas them, and a hand-written reader means hand-written equivalents (or NIR's, after translation).-- Future AIR versions (iOS 17, 18…) come from newer Apple LLVMs; LLVM's reader follows them for+- Future AIR versions (Darwin userland 17, 18…) come from newer Apple LLVMs; LLVM's reader follows them forfree, ours must be extended.**Against it, and for our own reader:**@@ -554,8 +554,8 @@ This is the biggest commitment of the project, so both sides in full.touches Metal. On this port that is every app: CoreAnimation, CoreImage and UIKit all linkMetal. The port's Mesa is built with `-Dllvm=disabled` (`tools/mk-mesa.sh`) for exactly thisreason today.-- **It would have to be cross-built for iOS** with the port's toolchain (the `xnu-clang` wrapper,- the iOS SDK, ld64). That is a multi-hour build and a second large dependency to keep building+- **It would have to be cross-built for Darwin** with the port's toolchain (the `xnu-clang` wrapper,+ the Darwin SDK, ld64). That is a multi-hour build and a second large dependency to keep building— the project's experience with V8 on musl says what such a build costs to keep alive.- **Apple already has an LLVM in the shared cache** (MTLCompiler, AGXCompilerCore — 3.6 MB). Ourswould be a second one in the same process, of a different version. Two-level namespaces keep the@@ -590,7 +590,7 @@ metadata, fast-math flags, alignments, calling conventions, linkage — comes baWhat would reverse this: if a later AIR (a newer `.metallib` corpus) turned out to need largeparts of LLVM's auto-upgrade machinery, or if translation turned out to need LLVM's own passes-before NIR. Neither is true of iOS 16.5.+before NIR. Neither is true of Darwin userland 16.5.## 3. What a translation unit is@@ -996,7 +996,7 @@ Three references, each independent of the translator:The other 98 of the 100 modules carried did not run, because the job list ended with`/bin/sh /redwood/share/airops/run.sh` and the answer was- **`/bin/sh: No such file or directory`, status 127. iOS 16.5's own root has no shell at all**+ **`/bin/sh: No such file or directory`, status 127. Darwin userland 16.5's own root has no shell at all**— `/bin` holds `df` and `ps`, and nothing else. The `/var/jb/bin/sh` that `rc.jobs.jb` and`rc.jobs.sileo` run belongs to the package manager's prefix, which only a `JB=1` image carries.This was asserted, not checked: a `grep` for `bin/sh` matched six `rc.jobs*` files and the@@ -1023,7 +1023,7 @@ Three references, each independent of the translator:The second is a property of the loader's log and will catch anything verbose:**the log keeps the first 256 KB and the last 1 MB and drops the middle**, saying so in one- line. With `XL_SECS=120` and `REST=1`, iOS wrote more than a megabyte of `os_log` after the+ line. With `XL_SECS=120` and `REST=1`, Darwin wrote more than a megabyte of `os_log` after thesuite had finished, so the suite's own output was in the dropped middle — 27 modules survived,at the front. `XL_FOLLOW`'s intermediate log does not help, because the drop has alreadyhappened by the time it is fetched, and a filter removes lines that are already gone. Two levers@@ -1037,12 +1037,12 @@ Three references, each independent of the translator:**How much room is left is worth knowing before the suite grows.** In the run that worked, at`XL_SECS=30`, `air_run`'s own output was 93 459 bytes for 225 modules — 415 bytes each — and the- other 1 092 137 bytes, 92% of the log, was iOS booting *with* `QUIET=1` already on. So the+ other 1 092 137 bytes, 92% of the log, was Darwin booting *with* `QUIET=1` already on. So theheadroom is about 280 KB, or roughly 650 more modules if they cost nothing in time, and fewerbecause each one adds 22 ms of further boot noise. `--cases 8` should still fit; past that it- will not, and the answer then is not a bigger cap but to stop booting iOS for a measurement at+ will not, and the answer then is not a bigger cap but to stop booting Darwin for a measurement atall: `init` runs programs itself, before `launchd`, where the log is nearly empty and nothing- can push the output out of it (`RC=<file>`, as `rc.ios` does it). The GPU is up by then, since+ can push the output out of it (`RC=<file>`, as `rc.darwin` does it). The GPU is up by then, sincethe kernel brings it up, and a question about what the hardware does to a number does not needa window server. That is the shape this suite should take if it ever outgrows `--cases 4`; ithas not yet, and the 225 modules above all arrived.@@ -1179,7 +1179,7 @@ out of it, and it runs from `tools/air/check.sh` (section 6). Two corpora:- **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,+- **the full IPSW** — all 134 MTLB libraries of the Darwin userland 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.@@ -1294,7 +1294,7 @@ the Mesa already on the phone rather than being built from nothing:`osmesa_create_gpu_screen()` in `tools/mesa/freedreno-darwin.patch` opens the kernel's `msm`driver through `tools/mesa/hakios-drm` and calls `fd_drm_screen_create_renderonly()`. It alsoalready has `osmesa_surface_resource()`, which wraps an IOSurface as a `pipe_resource`. So the- Gallium layer is reachable inside the library CoreAnimation already draws iOS through.+ Gallium layer is reachable inside the library CoreAnimation already draws Darwin through.- **freedreno takes NIR natively** (`PIPE_SHADER_CAP_SUPPORTED_IRS` includes`PIPE_SHADER_IR_NIR`; `ir3_gallium.c` handles `cso->ir_type == PIPE_SHADER_IR_NIR`), so nothinghas to go through GLSL on the way.@@ -1315,8 +1315,8 @@ got (`air_run: clearFragment01 on softpipe` here), and that line must be read bebelow it is believed. `AIR_RUN_SOFTWARE=1` forces software even on the phone, for comparing thetwo on the same device.-**It runs on iOS, and the numbers are exact there.** In QEMU (`CMDLINE="cpus=4-RC_JOBS=rc.jobs.air" qemu/run-ios.sh 420`, a clean boot: 72 `[ ok ]` lines, SpringBoard up),+**It runs on Darwin, and the numbers are exact there.** In QEMU (`CMDLINE="cpus=4+RC_JOBS=rc.jobs.air" qemu/run-darwin.sh 420`, a clean boot: 72 `[ ok ]` lines, SpringBoard up),`air_run` translated `clearFragment01`, found no `msm` device, fell back to softpipe as designed,drew the quad and read back@@ -1331,7 +1331,7 @@ ir3 on the Adreno — and that needs the phone.**On the phone, with the root on the flash, it runs and is exact — and it ran on softpipe.** Thefirst run of it (19 October, `logs/232842-run.log`) booted the flash-root recipe properly (both-`[ ok ] mount the iOS volume read only` and `[ ok ] the iOS volume is the root, the RAM part of+`[ ok ] mount the Darwin volume read only` and `[ ok ] the Darwin volume is the root, the RAM part ofthe boot on /private/preboot`), translated `clearFragment01` and read back the same four exactfloats as everywhere else. But its first line said `on softpipe`, and the kernel said why:@@ -1371,7 +1371,7 @@ dereferences it; this program handed it a zeroed struct. The port's ownday — is now what `air_run` uses. **A machine with no `msm` device never reaches that code**, sono amount of running it here would have found it; it took the first contact with real hardware.-Without the fault handler there would have been nothing at all to go on: iOS answers a crash here+Without the fault handler there would have been nothing at all to go on: Darwin answers a crash herewith "Failed to send exception EXC_CORPSE_NOTIFY" and no report. Four lines of borrowed codeturned a silent exit into an exact address.@@ -1411,7 +1411,7 @@ path produced it:### And the driver takes work that is not the window server's`logs/000739-run.log`, `rc.jobs.air2`: the same draw after SpringBoard is up — 287 mentions of it-in the log, the ringer sounding at 29 s, the window server holding the GPU and drawing iOS through+in the log, the ringer sounding at 29 s, the window server holding the GPU and drawing Darwin through`src/eagl.c`. `air_run` still got `Adreno 7c+ Gen 3` and still read back the same four floats.So the kernel's GPU driver serves a second process while CoreAnimation is drawing. That question@@ -1419,7 +1419,7 @@ was owed to the whole port rather than to this frontend, and the answer is yes.is up and holding it. A refusal is a finding the whole port needs, not just this frontend, soeither answer is worth the run.-(Counting anything out of a QEMU log here: `qemu/run-ios.sh` prints every line twice, and+(Counting anything out of a QEMU log here: `qemu/run-darwin.sh` prints every line twice, and`sort -u` does not catch it because the pairs are separated by other output.)### 5b. Dispatching a kernel@@ -1536,7 +1536,7 @@ back to software, so a run that looks fine can be a run on no GPU.Needed on this machine: meson, ninja, bison, flex, python3 with venv, and LLVM's `llvm-as` /`llvm-dis` for the reader check (22.1.8 here). The host build also patches Mesa 25.0's`src/c11/threads.h`, because glibc 2.43 and later declare C11's `once_flag` and `call_once` in-`<stdlib.h>` and Mesa defines them again; the iOS cross build has its own libc and does not.+`<stdlib.h>` and Mesa defines them again; the Darwin cross build has its own libc and does not.## 7. What this decides for the runtime (2) and the kernel ABI (3)@@ -1553,7 +1553,7 @@ reports.1. **Compilation happens at pipeline creation, not at `newLibraryWithData:`.** Function constants(`newFunctionWithName:constantValues:`), vertex/fragment varying linking and visible-functionlinking are only known then. The library step can translate eagerly and cache NIR; the ir3- step cannot run before the pipeline. (On real iOS the compile also leaves the process, for+ step cannot run before the pipeline. (On real Darwin the compile also leaves the process, for`MTLCompilerService`; whether this runtime does the same is a decision for (2), and NIRserialization — `nir_serialize` — makes either possible.)2. **Buffers are bound per stage by index, as UBOs (constant) and SSBOs (device).**diff --git a/docs/cellular.md b/docs/cellular.mdindex 11623fc..090127c 100644--- a/docs/cellular.md+++ b/docs/cellular.md@@ -40,7 +40,7 @@ for IPA 4.11; everything is in `drivers/modem/hakios.ipa.c` and `hakios.cell.c`.- The rings are polled by the interface's thread; no interrupt is taken from the GSI.- The modem's packets are an Ethernet-looking interface, `en1`, with a made-up router behind it.The kernel answers ARP for every address and DHCP with the session's address, a /24 around it,- the router and the DNS servers, so iOS's configd configures `en1` as it would a USB Ethernet+ the router and the DNS servers, so Darwin's configd configures `en1` as it would a USB Ethernetadapter and routes through it. IPv6 is not carried.- The modem is told about this side the way ModemManager does for a phone behind the IPA(`net_driver == "ipa"`): **DPM Open Port** (Data Port Mapper) names the embedded port's IPA@@ -53,7 +53,7 @@ for IPA 4.11; everything is in `drivers/modem/hakios.ipa.c` and `hakios.cell.c`.- The rings are polled by the interface's thread; no interrupt is taken from the GSI.- The modem's packets are an Ethernet-looking interface, `en1`, with a made-up router behind it.The kernel answers ARP for every address and DHCP with the session's address, a /24 around it,- the router and the DNS servers, so iOS's configd configures `en1` as it would a USB Ethernet+ the router and the DNS servers, so Darwin's configd configures `en1` as it would a USB Ethernetadapter and routes through it. IPv6 is not carried.- `modem_ipa_data_off=1` leaves all of this out; `modem_dpm_off=1` / `modem_wda_off=1` skip thosesteps; `modem_ipa_data_trace=1` logs every packet.diff --git a/docs/comparison.md b/docs/comparison.mdindex 4d64a91..0589949 100644--- a/docs/comparison.md+++ b/docs/comparison.md@@ -8,7 +8,7 @@ this repository's README claims; the things this repository has *tested* are mar| | [ios-sweet](https://github.com/dipa-studio/ios-sweet) | [UniXNU](https://github.com/UniXNU/UniXNU) | [Bergamota](https://github.com/ry-diffusion/bergamota) | HakiOS ||---|---|---|---|---|-| What it is | one phone, bring-up of iOS 16 | a general UEFI environment for iOS/macOS on ARM64, in the manner of OpenCore | one phone, bring-up of iOS 18 (a fork of ios-sweet) | a Darwin kernel port with its own loader and driver set, and a Linux-style configuration system |+| What it is | one phone, bring-up of Darwin userland 16 | a general UEFI environment for Darwin/macOS on ARM64, in the manner of OpenCore | one phone, bring-up of Darwin userland 18 (a fork of ios-sweet) | a Darwin kernel port with its own loader and driver set, and a Linux-style configuration system || Hardware | Redmi Note 10 Pro (SM7150) | Xiaomi Pad 6S Pro (SM8550), shared SoC code | Poco F1 (SDM845) | POCO X5 Pro 5G (SM7325), and a generator for a new device from its own device tree || Kernel | Apple's open xnu-8796 | not stated on its page | xnu-11215 ("Heartwood") | Apple's open xnu-8796.121.2 || Boot | `fastboot boot` of a shim; HFS+ root in `userdata` | UEFI | its own bootloader from `boot` | `fastboot boot` (RAM only), or a UEFI loader that reads its payload from the volume it was started from (tested in QEMU; not yet on a phone) |@@ -38,8 +38,8 @@ These are things that exist in this repository and that a reader can check:## What the others have that this one does not-- ios-sweet and Bergamota are small enough to read in an afternoon, and Bergamota targets a newer iOS (18) with its- own tool for the arm64e/pointer-authentication gap. HakiOS targets the iOS 16.5 generation, whose userland the+- ios-sweet and Bergamota are small enough to read in an afternoon, and Bergamota targets a newer Darwin (18) with its+ own tool for the arm64e/pointer-authentication gap. HakiOS targets the Darwin userland 16.5 generation, whose userland theopen xnu-8796 matches.- UniXNU is aiming at a shared UEFI layer that many devices use; HakiOS's loader is one device family's, so far.- Bergamota ships a macOS control app. HakiOS has `xl` and `make`, which are command lines.diff --git a/docs/concepts/architecture.md b/docs/concepts/architecture.mdindex a1ea71e..b8d433c 100644--- a/docs/concepts/architecture.md+++ b/docs/concepts/architecture.md@@ -8,7 +8,7 @@ yours (the user space you lay out).```Android's fastboot HakiOS UEFI xnuloader XNU + HakiOS launchd user space- (the phone's own) --> (Mu-Silicium with --> (loader.efi, --> (xnu/, drivers/) --> --> (yours: iOS 16.5,+ (the phone's own) --> (Mu-Silicium with --> (loader.efi, --> (xnu/, drivers/) --> --> (yours: Darwin userland 16.5,fastboot boot HakiOS's changes, xnuloader/) drivers started or userland/hello)uefi/ + the device's) reads the payload by boot-arguments```@@ -20,7 +20,7 @@ yours (the user space you lay out).| 3. the loader | `xnuloader` reads the payload (the kernel, the command line, `kernel.ver`), lays out memory and the device tree the kernel expects, keeps a service for the storage, starts the kernel; at the end of a run it takes control back | `xnuloader/` || 4. the kernel | XNU with this port: Apple's patched files (`xnu/hakios.patch`), new ones (`xnu/files/`), the drivers (`drivers/`) | [Building](../getting-started/building.md) || 5. the drivers | each one does nothing until its boot-argument asks; those the configuration left out are not in the kernel at all | [Drivers in the configuration](../drivers-config.md) |-| 6. user space | launchd starts what the system image holds: iOS 16.5's (layer 2, yours), or `userland/hello` for the open kernel | `userland/` |+| 6. user space | launchd starts what the system image holds: Darwin userland 16.5's (layer 2, yours), or `userland/hello` for the open kernel | `userland/` |## How a configuration becomes a kernel and a command linediff --git a/docs/driver-review/README.md b/docs/driver-review/README.mdindex 27f177e..8c53040 100644--- a/docs/driver-review/README.md+++ b/docs/driver-review/README.md@@ -34,9 +34,9 @@ These are in the reports; they are listed here because a fix is a choice, not asingle-user.2. **`PRIV_NET_PRIVILEGED_SOCKET_DELEGATE` granted to every credential** (P4, patch). Same kind of choice.3. **Six device nodes are mode 0666** (P3: touch, audio, microphone, camera, haptic, flashlight): any process can- read the microphone and the camera and read or forge the touch stream. They are open because every iOS daemon,+ read the microphone and the camera and read or forge the touch stream. They are open because every Darwin daemon,whatever its user, has to reach them today; tightening them means choosing which user gets which node, and- that needs the iOS user space running to check. The volume ioctl that made the audio node dangerous is fixed;+ that needs the Darwin user space running to check. The volume ioctl that made the audio node dangerous is fixed;the modes are not changed. Until this is decided, a process on this system is trusted with the sensors.4. **GPU command streams are not validated and no `CP_PROTECT` table is written** (gpu-display G1). A client canmake the GPU write anywhere its SMMU context reaches. Needs hardware knowledge of the Adreno's protection@@ -48,7 +48,7 @@ These are in the reports; they are listed here because a fix is a choice, not a7. **Wi-Fi: a forged message 1 before message 3 can still fail a join** (wifi-stack W1, rest of it): the proper fixkeeps a candidate key set and needs a change to the header the supplicant shares with the 802.11 layer.8. **The vsync notification is now sent with the framebuffer's lock held** (input/gpu fix G8). It closes a- use-after-release of the notification port; it was not run with the iOS user space. If a deadlock shows up in+ use-after-release of the notification port; it was not run with the Darwin user space. If a deadlock shows up in`IOMobileFramebufferUserClient::vsync`, that is the place to look.## What the audits did not coverdiff --git a/docs/driver-review/camera-haptic-torch.md b/docs/driver-review/camera-haptic-torch.mdindex f7f44f7..81528ff 100644--- a/docs/driver-review/camera-haptic-torch.md+++ b/docs/driver-review/camera-haptic-torch.md@@ -37,7 +37,7 @@ Method: traced every user-reachable entry (torch `write`/`read`, haptic `write`,### CAM-1 camera read vs. session end: use-after-free of the frame ring-`camdev_read` marks a place READING under `ios_lock`, drops the lock at 3869, then reads the globals `ring`, `ring_place_bytes` and `ring_frame_bytes` with no lock and copies the frame:+`camdev_read` marks a place READING under `darwin_lock`, drops the lock at 3869, then reads the globals `ring`, `ring_place_bytes` and `ring_frame_bytes` with no lock and copies the frame:```3873 vm_offset_t at = ring + (uint64_t)b * ring_place_bytes;@@ -45,45 +45,45 @@ Method: traced every user-reachable entry (torch `write`/`read`, haptic `write`,3884 error = uiomove((caddr_t)at, (int)n, uio);```-The capture thread ends a session in `ios_stop()` (3401): it sets every place FREE under the lock (3405-3407, which also overwrites READING), then, without waiting for any reader, runs `titan_down(); power_down(); ring_free();` and `ring_free()` does `kmem_free(kernel_map, ring, ring_bytes)` and `ring = 0` (3370-3374). Nothing counts readers, so a reader mid-copy keeps a pointer into freed memory.+The capture thread ends a session in `darwin_stop()` (3401): it sets every place FREE under the lock (3405-3407, which also overwrites READING), then, without waiting for any reader, runs `titan_down(); power_down(); ring_free();` and `ring_free()` does `kmem_free(kernel_map, ring, ring_bytes)` and `ring = 0` (3370-3374). Nothing counts readers, so a reader mid-copy keeps a pointer into freed memory.Ways the session ends while a reader is copying (a 12 MB frame is copied in milliseconds, and the code itself logs the time at 3891):-- another process writes `HAKIOS_CAMERA_SENSOR` (3969-3978): `ios_switch_to` is seen by the loop at 3512, `ios_stop` runs within about 1 ms;-- no read activity for `IDLE_MS` (1000 ms, 3526): `ios_last_read` is only refreshed at the start of a read (3810, 3843) and at its end (3899), not during the copy, so a reader that is descheduled or stuck in page faults on a big user buffer for 1 s is declared idle;-- any fault (`healthy()`, SMMU fault, 1.5 s without a frame, an exposure write NACK) -> `give_up` -> `ios_stop`.+- another process writes `HAKIOS_CAMERA_SENSOR` (3969-3978): `darwin_switch_to` is seen by the loop at 3512, `darwin_stop` runs within about 1 ms;+- no read activity for `IDLE_MS` (1000 ms, 3526): `darwin_last_read` is only refreshed at the start of a read (3810, 3843) and at its end (3899), not during the copy, so a reader that is descheduled or stuck in page faults on a big user buffer for 1 s is declared idle;+- any fault (`healthy()`, SMMU fault, 1.5 s without a frame, an exposure write NACK) -> `give_up` -> `darwin_stop`.Result: `dc civac` on the unmapped VA (a cache-maintenance fault from kernel code with no recovery handler) -> kernel panic; if the range was reused (the next `ring_alloc`, or any other kmem allocation) `uiomove` copies unrelated kernel memory out to user space; if `ring` was already zeroed, `at` is a near-NULL address. Reachable by any process that can open the 0666 node.Fix (sketch):```-+ static unsigned ios_readers; /* under ios_lock */- camdev_read: under ios_lock, after choosing b:++ static unsigned darwin_readers; /* under darwin_lock */+ camdev_read: under darwin_lock, after choosing b:- place[b].state = PLACE_READING;-+ place[b].state = PLACE_READING; ios_readers++;++ place[b].state = PLACE_READING; darwin_readers++;+ snapshot at/n/ring_frame_bytes into locals here, still under the lock... at the end (the existing lock at 3895):-+ ios_readers--; wakeup(&ios_readers);- ios_stop(), before ring_free():-+ lck_mtx_lock(&ios_lock);-+ while (ios_readers != 0) msleep(&ios_readers, &ios_lock, PZERO, "hakios-camera-drain", NULL);-+ lck_mtx_unlock(&ios_lock);++ darwin_readers--; wakeup(&darwin_readers);+ darwin_stop(), before ring_free():++ lck_mtx_lock(&darwin_lock);++ while (darwin_readers != 0) msleep(&darwin_readers, &darwin_lock, PZERO, "hakios-camera-drain", NULL);++ lck_mtx_unlock(&darwin_lock);```-Also refresh `ios_last_read` while `ios_readers != 0` in the idle test.+Also refresh `darwin_last_read` while `darwin_readers != 0` in the idle test.### CAM-2 unprivileged control of sensor and mode; permanent shutdown-`HAKIOS_CAMERA_SENSOR` accepts any sensor index (< 4) and any mode number `c.b` (3969-3978). `ios_select()` honours an explicit mode directly: the 4:3 / 31 fps / 13 MP filter at 4019-4032 only runs when `mode_n >= ctab->modes`; an explicit mode is accepted if it passes the checks at 4035 (lanes, data type 0x2b, `width % 4`, fps and frame length non-zero). `ios_start()` then calls `ring_alloc(RAW10_STRIDE(width) * height)` (3436) for `RING = 3` places (3254, 3383) of kernel memory. If a table has a full-resolution mode (the S5KHM2SD is a 108 MP sensor; the tables are not in the repository, so NEEDS-HARDWARE/IMAGE for the actual sizes) this is hundreds of MB per session from an unprivileged process, and each session start repeats it.+`HAKIOS_CAMERA_SENSOR` accepts any sensor index (< 4) and any mode number `c.b` (3969-3978). `darwin_select()` honours an explicit mode directly: the 4:3 / 31 fps / 13 MP filter at 4019-4032 only runs when `mode_n >= ctab->modes`; an explicit mode is accepted if it passes the checks at 4035 (lanes, data type 0x2b, `width % 4`, fps and frame length non-zero). `darwin_start()` then calls `ring_alloc(RAW10_STRIDE(width) * height)` (3436) for `RING = 3` places (3254, 3383) of kernel memory. If a table has a full-resolution mode (the S5KHM2SD is a 108 MP sensor; the tables are not in the repository, so NEEDS-HARDWARE/IMAGE for the actual sizes) this is hundreds of MB per session from an unprivileged process, and each session start repeats it.-Consequences of failure are permanent: a failed `ring_alloc` or any other step in `ios_start` returns false -> `give_up("the camera did not start")` (3500-3503); `ios_select` failing for a sensor with no `.tab` in `fw/` (the build only installs tabs for module files present in `fw-camera/`, userland/build.sh:392-400) -> `give_up("a sensor that cannot be used")` (4091-4093). `broken` is never cleared (except in quiesce), every later open/read returns EIO (3785, 3816). The same holds for one transient NACK: `exposure_write` -> `give_up` (3356-3358, 3593-3595), `sensor_table` has no retry (2703), whereas the PMIC and chip-ID reads retry (697, 1432).+Consequences of failure are permanent: a failed `ring_alloc` or any other step in `darwin_start` returns false -> `give_up("the camera did not start")` (3500-3503); `darwin_select` failing for a sensor with no `.tab` in `fw/` (the build only installs tabs for module files present in `fw-camera/`, userland/build.sh:392-400) -> `give_up("a sensor that cannot be used")` (4091-4093). `broken` is never cleared (except in quiesce), every later open/read returns EIO (3785, 3816). The same holds for one transient NACK: `exposure_write` -> `give_up` (3356-3358, 3593-3595), `sensor_table` has no retry (2703), whereas the PMIC and chip-ID reads retry (697, 1432).Fix (sketch):```camdev_write, HAKIOS_CAMERA_SENSOR:-- ios_switch_mode = c.b;-+ ios_switch_mode = c.b; /* and in ios_select(): */- ios_select(), for an explicit mode_n also require+- darwin_switch_mode = c.b;++ darwin_switch_mode = c.b; /* and in darwin_select(): */+ darwin_select(), for an explicit mode_n also require+ pixels <= 13000000 && fps_milli <= 31000- ios_select failure / ios_start failure for a switch requested from user space:+ darwin_select failure / darwin_start failure for a switch requested from user space:- give_up(...)+ fall back to the previous sensor/mode; only give_up on hardware faultsdevfs_make_node(..., 0666, ...) -> 0660 with a group the media daemon is in@@ -153,19 +153,19 @@ Fix: `sensor_delay(us > 100000 ? 100000 : us)`.### CAM-5 mode fields only partly validated-`ios_select()` checks lanes, data type, `width % 4`, fps and frame_length != 0 (4035-4036) but:-- `frame_length < EXPOSURE_MARGIN (40)` makes `ios_ask.lines = frame_length - EXPOSURE_MARGIN` (4053) wrap to ~4G (clamped later at 3311) and `*frame_lines - EXPOSURE_MARGIN` (3316) wrap so the final clamp of `lines` is skipped; `exposure_write` default branch computes `extra = frame_lines - ios_mode->frame_length` (3347), which wraps if `shortest > FRAME_LINES_MAX`.-- width/height have no upper bound: `RAW10_STRIDE(width) * ios_mode->height` is 32-bit (3436; also `frames_alloc` 2084 and 3161) and wraps; the SMMU mapping (sized from the ring) and the IFE's real write size then disagree, the SMMU refuses the overflow (so this is a fault, not corruption). In `smmu_up()` a mapping above 1 GiB gives `thirds > 512` and `second[... + t]` (2197) writes past the second-level page into the third-level pages of the same allocation (SMMU table corruption, not a heap overflow).+`darwin_select()` checks lanes, data type, `width % 4`, fps and frame_length != 0 (4035-4036) but:+- `frame_length < EXPOSURE_MARGIN (40)` makes `darwin_ask.lines = frame_length - EXPOSURE_MARGIN` (4053) wrap to ~4G (clamped later at 3311) and `*frame_lines - EXPOSURE_MARGIN` (3316) wrap so the final clamp of `lines` is skipped; `exposure_write` default branch computes `extra = frame_lines - darwin_mode->frame_length` (3347), which wraps if `shortest > FRAME_LINES_MAX`.+- width/height have no upper bound: `RAW10_STRIDE(width) * darwin_mode->height` is 32-bit (3436; also `frames_alloc` 2084 and 3161) and wraps; the SMMU mapping (sized from the ring) and the IFE's real write size then disagree, the SMMU refuses the overflow (so this is a fault, not corruption). In `smmu_up()` a mapping above 1 GiB gives `thirds > 512` and `second[... + t]` (2197) writes past the second-level page into the third-level pages of the same allocation (SMMU table corruption, not a heap overflow).-Reachable only through the table (or CAM-2's mode selection). Fix: reject modes with `frame_length <= EXPOSURE_MARGIN`, `width > 16384`, `height > 16384` in `ios_select()` and `capture_sensor()`.+Reachable only through the table (or CAM-2's mode selection). Fix: reject modes with `frame_length <= EXPOSURE_MARGIN`, `width > 16384`, `height > 16384` in `darwin_select()` and `capture_sensor()`.### CAM-6 `keep_picture` unserialised-`HAKIOS_CAMERA_KEEP` (3959-3960 -> 3906) does `bzero(keep header)`, fills the header, `uiomove`s into `keep + 4096` and updates `loader_recording[]` with no lock. Two writers (any process) interleave: header of one picture over the data of the other, `frames = 1`. Memory-safe (same bounds, `want <= keep_bytes` is checked at 3914). Fix: take `ios_lock` (or a dedicated mutex) around the body.+`HAKIOS_CAMERA_KEEP` (3959-3960 -> 3906) does `bzero(keep header)`, fills the header, `uiomove`s into `keep + 4096` and updates `loader_recording[]` with no lock. Two writers (any process) interleave: header of one picture over the data of the other, `frames = 1`. Memory-safe (same bounds, `want <= keep_bytes` is checked at 3914). Fix: take `darwin_lock` (or a dedicated mutex) around the body.### HAPTIC-2 no duty-cycle limit across taps-`HAPTIC_MAX_MS` (349) limits one LOOP state, followed by an equal rest (906-910). A TAP (waveform 1, 856-859) has no rest: iOS (or any process writing to the 0666 node) writing a burst, 30 ms of silence, another burst ... starts a new tap each time `onset_us` changes (847). Only the chip's fault flags (checked every 50 ms, 925-929) stop it. PLAUSIBLE; whether this can overheat the motor is NEEDS-HARDWARE.+`HAPTIC_MAX_MS` (349) limits one LOOP state, followed by an equal rest (906-910). A TAP (waveform 1, 856-859) has no rest: Darwin (or any process writing to the 0666 node) writing a burst, 30 ms of silence, another burst ... starts a new tap each time `onset_us` changes (847). Only the chip's fault flags (checked every 50 ms, 925-929) stop it. PLAUSIBLE; whether this can overheat the motor is NEEDS-HARDWARE.### TORCH-3 30 s cap restarts on request@@ -200,12 +200,12 @@ Camera, kernel side- `sensor_table` (2676-2714): operation/address/data widths validated per entry (2689), `out[4]` always enough, per-entry delay clamped to 100 ms. `read_chip_id`: `in` forced to 1-4 so `id[4]` is safe, `out` is 1 or 2.- All table-driven power kinds are validated (`power_step` 1233-1268): MCLK only 0/19200/24000, supply kinds only 1-3, others -> give up; the voltage written to an LDO can only be the one in `sensors[]` (`sensor_ldo`/`pm8008_put` allow-lists 645-653, 688-691; arrays indexed with `n <= 7`).- Register write allow-lists: camcc (875-879), PM8008i, PMIC GPIO 3 (555-559); read-backs on all of them; off paths for camera use `force` and always run to the end (`power_down`, `ldo_off`).-- Every polling loop is bounded: `wait_done`, `wait_bits`, `wait_reg`, SMMU TLB sync (2222), clock branches (1986), `rpmh_write` (100 ms), `ios_session` (frame timeout 1.5 s, 3521), `wait_standby`, `bus_unwedge`, `capture_tpg` (2 s), `capture_sensor` (5 s).+- Every polling loop is bounded: `wait_done`, `wait_bits`, `wait_reg`, SMMU TLB sync (2222), clock branches (1986), `rpmh_write` (100 ms), `darwin_session` (frame timeout 1.5 s, 3521), `wait_standby`, `bus_unwedge`, `capture_tpg` (2 s), `capture_sensor` (5 s).- User commands (`camdev_write` 3942-3981): fixed 24-byte struct, size checked first; `HAKIOS_CAMERA_SENSOR` index bounds-checked (3970); EXPOSURE values are unclamped when stored but clamped before use in all three consumers (3480, 3591, 3705, 3728); FOCUS clamped to 1023 in `af_move` (3039). `keep_picture` bounds: `bytes != 0`, `d` 1-3, `stride * height <= 2 * bytes` in 64-bit, `want <= keep_bytes`, copy size `min(bytes, resid)`.-- `camdev_read` header: `bzero(&f)` before filling, `MIN(sizeof(f), resid)`, so no uninitialised bytes leave; place indexes `b < RING`; state reads/writes under `ios_lock`, the lock is not held across `uiomove`/`msleep` misuse (msleep releases it).-- Locking between ioctl-side and capture thread: shared `place[]`, `ios_ask`, `ios_given` are under `ios_lock`; `ios_switch_to`/`ios_open` etc are volatile flags; lock order is always (ios_lock) or (hakios_smmu_lock) or (spmi spin), never nested with each other. The one gap is CAM-1.+- `camdev_read` header: `bzero(&f)` before filling, `MIN(sizeof(f), resid)`, so no uninitialised bytes leave; place indexes `b < RING`; state reads/writes under `darwin_lock`, the lock is not held across `uiomove`/`msleep` misuse (msleep releases it).+- Locking between ioctl-side and capture thread: shared `place[]`, `darwin_ask`, `darwin_given` are under `darwin_lock`; `darwin_switch_to`/`darwin_open` etc are volatile flags; lock order is always (darwin_lock) or (hakios_smmu_lock) or (spmi spin), never nested with each other. The one gap is CAM-1.- Single reader: a reader cannot be handed the place that is being programmed for the next frame (the next place is the lowest-sequence non-READING place, the reader takes the highest unread), so I found no tearing with one reader; with two simultaneous readers I did not prove either way.-- IFE DMA is confined by an SMMU context that maps only the ring (or `frames_bytes`); the order in `ios_stop` stops the write master (`paths_down`), tears the SMMU context down and only then frees memory. Cache maintenance (`dc civac` before reads, `dsb sy`) is present where the CPU reads DMA memory.+- IFE DMA is confined by an SMMU context that maps only the ring (or `frames_bytes`); the order in `darwin_stop` stops the write master (`paths_down`), tears the SMMU context down and only then frees memory. Cache maintenance (`dc civac` before reads, `dsb sy`) is present where the CPU reads DMA memory.- Idle timeout and frame timeout: a stalled sensor ends the session in 1.5 s (3521-3525).- Boot-args: `cam` (clamped 0-5), `cam_sensor` (string compared against the fixed names, cannot index out of range), `cam_mode` (checked against `modes` in both paths), `cam_frames` (1..300), `cam_fake_fps` (1..30), `cam_keep_mb` (<= 64), `cam_settle` (masked to a byte), `cam_vblank` (<= 0x3fff), `cam_gain`/`cam_shutter` clamped before the registers are written (3091-3103, `exposure_limits`). `cam_after` is unclamped, `secs * 1000` wraps for absurd values: trusted boot-arg.- `RPMh` command DB parse (`rpmh_resource`): `slave->count > 512` skipped, data offsets checked against the mapping, `levels[]` filled up to `max` only.@@ -222,7 +222,7 @@ Camera, user-space side- The 1568-1750 stretch of hakios.camera.c (read-only `show_*` printers) and `userland/src/camera_isp.c` outside the tuning loader (demosaic, AE, AWB) and `camera_test.c`, `camera_avtest.m`: not read for safety.- `hakios_wifi_file()`/`image_file()` (hakios.wifi.c): assumed to return a stable read-only pointer into the image; ownership and alignment not verified.- `ml_io_map_unmappable` failure mode in `rpmh_resource` (cmd_db NULL dereference if the mapping fails): not verified.-- Behaviour with two simultaneous camera readers beyond what is said above; behaviour when `psci_smp_stop_others()` leaves a stopped CPU holding `ios_lock` or `hakios_smmu_lock` (the quiesce paths skip those locks when `leaving`, torch/haptic/camera all do).+- Behaviour with two simultaneous camera readers beyond what is said above; behaviour when `psci_smp_stop_others()` leaves a stopped CPU holding `darwin_lock` or `hakios_smmu_lock` (the quiesce paths skip those locks when `leaving`, torch/haptic/camera all do).- Interplay with the audio DSP driver's use of the RPMh TCS 0 and with hakios.speaker.c / buttons for shared pins and the SPMI arbiter beyond the spin lock.- userland/src/inject_media.c (writes the torch node) and the camera ISP's float handling.@@ -230,15 +230,15 @@ Camera, user-space sideNothing was built or run; each edit was re-read for syntax and types only.-- CAM-1: FIXED (hakios.camera.c). New `ios_readers` count (under `ios_lock`); `camdev_read` counts itself in the same lock hold that marks the place READING and takes `at` and the frame size from `ring`, `ring_place_bytes` and `ring_frame_bytes` there; it leaves the count (and `wakeup`s) in its final lock section. New `ios_drain_readers()` (waits under `ios_lock` with `msleep` until the count is 0) is called before `ring_free()` in `ios_stop()` and in `fake_session()`. Lock order: the drain holds only `ios_lock` (power is already down); nothing else nests with it. The optional "refresh `ios_last_read` while a read is in progress" was not done: the drain already makes an idle stop safe.+- CAM-1: FIXED (hakios.camera.c). New `darwin_readers` count (under `darwin_lock`); `camdev_read` counts itself in the same lock hold that marks the place READING and takes `at` and the frame size from `ring`, `ring_place_bytes` and `ring_frame_bytes` there; it leaves the count (and `wakeup`s) in its final lock section. New `darwin_drain_readers()` (waits under `darwin_lock` with `msleep` until the count is 0) is called before `ring_free()` in `darwin_stop()` and in `fake_session()`. Lock order: the drain holds only `darwin_lock` (power is already down); nothing else nests with it. The optional "refresh `darwin_last_read` while a read is in progress" was not done: the drain already makes an idle stop safe.- CAM-2: SKIPPED. Capping the mode's pixels or fps for user-chosen modes changes the documented ABI (`HAKIOS_CAMERA_SENSOR` takes any mode), and the real mode sizes live in tables that are not in the tree. Replacing `give_up` with a fall back to the previous sensor and mode is a design change. Node mode is policy (see DEV-1).- TORCH-1: FIXED (hakios.torch.c). `dark()` sets a `forcing` flag while it runs and `put()` ignores the `broken` latch only then (all other checks, the allow-list, the arbiter check and the read-back stay). `dark()` also tries all four steps instead of stopping at the first failure; a clean run does the same writes in the same order. Not done: the repeated dark() retry every 100 ms in `serve()` (a design change).- TORCH-2: FIXED (hakios.torch.c). `light()` sets `lit = true` before the module-enable write; `dark()` still clears it only on success. In the torch=2 path, a failed `light(1000)` now calls `dark()` if `lit` is set. Quiesce is unchanged: it already calls `dark()` when `lit` is set, which is now true in the failing case.- HAPTIC-1: FIXED (hakios.haptic.c). `loaded = level >= 3 && configure() && load_waveforms()` is evaluated apart from `level == 4`; level 5 calls `serve()` only when `loaded`, otherwise `give_up("the waveforms are not loaded")` (chip into reset).- CAM-3: FIXED (hakios.camera.c). `vaf()` records `vaf_voted = on` before the RPMh request, as `rails()` does, so `af_down()` sends the "off" even if RPMh did not report done in time. Worst case is one extra harmless "off" request. Whether a late completion really happens is hardware behaviour.- CAM-4: FIXED (hakios.camera.c). `power_step()` passes `delay_us` capped at 100000 to `sensor_delay()`, the same cap the sensor-register path uses.-- CAM-5: FIXED (hakios.camera.c). `ios_select()` rejects modes with `frame_length <= EXPOSURE_MARGIN`, `frame_length > FRAME_LINES_MAX`, width or height over 16384; `capture_sensor()` rejects width/height over 16384 and `frame_length <= 40` (EXPOSURE_MARGIN is defined later in the file, so the literal 40 as in `exposure()`). 16384 x 16384 keeps the 32-bit sizes and the SMMU third-level count in range.-- CAM-6: FIXED (hakios.camera.c). New `keep_lock` mutex (own mutex, not `ios_lock`, so the capture thread never waits on a user copy) held across the header and data writes in `keep_picture()`; never nested with `ios_lock`.+- CAM-5: FIXED (hakios.camera.c). `darwin_select()` rejects modes with `frame_length <= EXPOSURE_MARGIN`, `frame_length > FRAME_LINES_MAX`, width or height over 16384; `capture_sensor()` rejects width/height over 16384 and `frame_length <= 40` (EXPOSURE_MARGIN is defined later in the file, so the literal 40 as in `exposure()`). 16384 x 16384 keeps the 32-bit sizes and the SMMU third-level count in range.+- CAM-6: FIXED (hakios.camera.c). New `keep_lock` mutex (own mutex, not `darwin_lock`, so the capture thread never waits on a user copy) held across the header and data writes in `keep_picture()`; never nested with `darwin_lock`.- HAPTIC-2: SKIPPED. A duty-cycle limit needs the motor's thermal limits (hardware) and is a policy change.- TORCH-3: SKIPPED. The cap is per request by design; a hard on-time limit is a policy change.- DEV-1: SKIPPED. Node mode 0666 is policy and was not to be changed.diff --git a/docs/driver-review/input.md b/docs/driver-review/input.mdindex bcf5913..aece015 100644--- a/docs/driver-review/input.md+++ b/docs/driver-review/input.md@@ -69,11 +69,11 @@ and, in the failure path, drive `PIN_AVDD` low and clear the votes.### F3. Device node is world read/write (input.c:213)-`devfs_make_node(..., UID_ROOT, GID_WHEEL, 0666, "hakios-touch")`; `touch_open` (143-147) does no check. Any process that can open the node (subject to whatever sandbox the iOS userland applies; not examined here) can:+`devfs_make_node(..., UID_ROOT, GID_WHEEL, 0666, "hakios-touch")`; `touch_open` (143-147) does no check. Any process that can open the node (subject to whatever sandbox the Darwin userland applies; not examined here) can:- `write()` records: forged DOWN/MOVE/UP samples and `HAKIOS_BUTTON_DOWN/UP` with `finger = HAKIOS_BUTTON_LOCK`, which backboardd turns into the power key (inject.c:871-879). Only the five-finger exit is protected (it counts driver fingers only, input.c:130).- `read()`: steal the real touch stream (any reader takes records away from backboardd, since there is one shared queue with no exclusive open).-Whether this matters depends on the iOS sandbox profile for third-party apps; in the kernel there is no restriction.+Whether this matters depends on the Darwin sandbox profile for third-party apps; in the kernel there is no restriction.Fix: `0600` (or `0660` with a dedicated group) and, if backboardd runs as another user, set that uid/gid in `devfs_make_node`; optionally make `touch_open` return `EBUSY` for a second opener.@@ -187,7 +187,7 @@ virtio_input.c:- Whether a Goodix finger lift is always reported as a status with the touch bit and zero count: if the chip instead reports status 0, `goodix_poll` returns at line 857 without posting UP and the finger stays down. NEEDS-HARDWARE; a hand test is noted in the buttons comment but not for this.- The content of `focaltech_fw` (706 KB array) and its provenance.- Whether the PRAM download can touch persistent flash, and whether the vendor flow's own integrity step exists in the boot ROM.-- The iOS sandbox profile for `/dev/hakios-touch` (F3 impact).+- The Darwin sandbox profile for `/dev/hakios-touch` (F3 impact).- Build correctness (flags of `kmem_alloc`, `__builtin_arm_dmb` use) and the other drivers in the tree, other than reading the lines named above for `hakios_rsc_lock`.## Fix statusdiff --git a/docs/driver-review/policy-glue.md b/docs/driver-review/policy-glue.mdindex ca0621d..9905472 100644--- a/docs/driver-review/policy-glue.md+++ b/docs/driver-review/policy-glue.md@@ -142,12 +142,12 @@ Every node the port creates, with mode and owner:| /dev/md*, /dev/rmd* | Apple bsd/dev/memdev.c:686-697 (unchanged) | 0600 root:operator | RAM disks, including the second image added at patch:1713-1723 |Can an unprivileged process read the phone's raw storage? Not directly: /dev/ufs_* and /dev/rufs_* are 0640-root:operator (owner root, group operator read-only; on iOS the group has only root in it), /dev/rvblk0 and /dev/rsp0+root:operator (owner root, group operator read-only; on Darwin the group has only root in it), /dev/rvblk0 and /dev/rsp0are 0600. With P1, any process can reach root and therefore all of them. The write path to /dev/rufs_darwin is bounded(see "Checked and found fine").The code does no check of its own in any `d_open` (`touch_open`, `audio_open`, `mic_dev_open`, `camdev_open`,-`haptic_open`, `torch_open`); file mode is the only gate. Whether the iOS sandbox adds one is out of reach here (the+`haptic_open`, `torch_open`); file mode is the only gate. Whether the Darwin sandbox adds one is out of reach here (theSandbox is a stub that allows everything, kern_minimac.c:230-242).Fix: create these nodes 0600 root:wheel, or 0660 with the group of the one daemon that uses each (backboardd for touch,@@ -364,7 +364,7 @@ Surfacehakios.battery.cpp (external methods, shared memory): outside the file list given to me.- bsd/miscfs/ramfs and apfs vnode operations: how ownership, setuid bits and `access` are enforced there (ramfs stores`va_mode & ALLPERMS`, ramfs.c:152, 1032).-- What iOS user space does with the stub answers: whether cfprefsd, lsd or containermanagerd use P7's container path+- What Darwin user space does with the stub answers: whether cfprefsd, lsd or containermanagerd use P7's container pathfor an access decision; whether dyld honours DYLD_* for setuid programs given the allow-all AMFI answer; whether thisport ships any setuid-root program; whether `task_for_pid` is otherwise gated for ad hoc signed callers.- Behaviour on hardware: P2's effect on the speakers, whether the Sandbox stub's `0` for unknown requests producesdiff --git a/docs/driver-review/sound.md b/docs/driver-review/sound.mdindex 2732e02..debdb7b 100644--- a/docs/driver-review/sound.md+++ b/docs/driver-review/sound.md@@ -39,7 +39,7 @@ Severity is about the effect if the trigger happens; confidence is as defined in| S-05 | Medium | PLAUSIBLE | speaker.c:623-646, 1068-1080 | `power_down_now()` clears `started` even when its power-down write was not acknowledged; the panic quiesce then skips the amplifier that is still on || S-06 | Medium | CONFIRMED | mic.c:1737-1778 | mic=4: a bring-up that fails without setting `broken` is retried forever (no failure count), re-toggling the codec reset and the DSP votes || S-07 | Low | CONFIRMED | sound.c:635, 693-706 | page tables for the DSP's SMMU context are allocated at every `space_on()` and never freed (12 KB per recording in mic=4) |-| S-08 | Medium | PLAUSIBLE (mode CONFIRMED; reach depends on iOS sandbox) | audio.c:343, mic.c:1732, 1524-1534 | both device nodes are 0666; any process can start the microphone, steal/split its samples, set the volume or mute; open state is a flag, not a count |+| S-08 | Medium | PLAUSIBLE (mode CONFIRMED; reach depends on Darwin sandbox) | audio.c:343, mic.c:1732, 1524-1534 | both device nodes are 0666; any process can start the microphone, steal/split its samples, set the volume or mute; open state is a flag, not a count || S-09 | Low | PLAUSIBLE | mic.c:719, 727 | SoundWire read id cycles through 0; an empty (zero) FIFO word matches id 0 and is returned as a successful read of 0 || S-10 | Low | NEEDS-HARDWARE | mic.c:704-710 | `swr_write()` waits for FIFO room at most 10 ms and then writes anyway; the result is always `true` || S-11 | Low | NEEDS-HARDWARE | sound.c:719, mic.c:1614-1617 | DSP-written mic buffer is only invalidated after the DSP has used it; dirty zero-fill lines are never cleaned first |@@ -63,7 +63,7 @@ Chain:4. `speaker.c:919` `if (a->volume == target) continue;` can never be true: `set_volume()` (707-709) raises every request to `volume_at`, so `a->volume` bottoms out at `volume_at` and `target` stays under it. The `for (;;)` at 909 sees `moved = true` forever: one I2C write plus read-back and a 1 ms wait per round, two log lines each. There is no `stopping` check and, with `step_ms = 1`, not even the status check (928 needs `step_ms >= 10`). The watcher thread is stuck, so no silence timeout, no fault polling and no `hakios_speaker_stop()` happens. Only `take_down()` at the run's end breaks it, because it calls `hakios_speaker_stop()` after 3 s and a failed/`broken` write makes the loop return.5. At the same time step 2's `guard_level(0xFFFFFFFF)` equals `HAKIOS_GUARD_SILENT` (`guard_level()` takes `min(level, guard_as)` and `guard_as` defaults to UINT32_MAX). In `hakios.guard.c:160` that means `to_speaker = 0` (no power limit) and at `:225` the peak ceiling stays at full scale: the guard only clips. Any `s` in `[2^32 - volume_at, 2^32 - 1]` is blind in the same way, because `amplitude(2 * attenuation)` wraps to a huge index and returns 0.-Failure scenario: `ioctl(fd, HAKIOS_AUDIO_SET_VOLUME, {below = 0xFFFFFF0F, muted = 0})` from any process, then any non-silent write to the same node (or iOS playing anything). The amplifiers are faded to Android's loudest level, the speaker guard is off, and the thread that should turn them off after three seconds of silence is in an endless I2C loop. Whether that level without the guard can hurt the speakers is NEEDS-HARDWARE (the guard exists "for want of the DSP's speaker protection", per `hakios.audio.h`).+Failure scenario: `ioctl(fd, HAKIOS_AUDIO_SET_VOLUME, {below = 0xFFFFFF0F, muted = 0})` from any process, then any non-silent write to the same node (or Darwin playing anything). The amplifiers are faded to Android's loudest level, the speaker guard is off, and the thread that should turn them off after three seconds of silence is in an endless I2C loop. Whether that level without the guard can hurt the speakers is NEEDS-HARDWARE (the guard exists "for want of the DSP's speaker protection", per `hakios.audio.h`).Fix (three independent layers; do all):@@ -137,7 +137,7 @@ Fix: keep `started` true when the power-down write failed (`if (ok) a->started =### S-06 Medium CONFIRMED-mic=4 retry loop, `mic.c:1737-1778`. `failed = broken;` (1761) is the only failure signal counted (`++failures >= 3`, 1770). But `path_up()` fails *without* setting `broken` in several places: `clocks_on()` false (1696-1699), `codec_wait() == 0` (1704-1706), `bolero_look()` unknown version (1118), `dsp_path_on()`/`dsp_port_on()` (APR refusal), `datapath_on()` returning false after a failed `swr_read()` (1001-1003), and `listen()` returning early on a refused RUN (1565-1569). In all of those `failed` is false, the code prints "ended", runs `undo()` and loops: `ios_wants` is still 1 while iOS keeps the device open, so it immediately starts another attempt. Each attempt is `clocks_on` (DSP votes and clock commands, up to 1 s per unanswered command), the codec reset pulse on GPIO 83, pins, SoundWire master bring-up, `codec_wait()` (200 ms) and the undo of all of it, indefinitely, with lines suppressed by `quiet` after the first. `recordings` grows without limit.+mic=4 retry loop, `mic.c:1737-1778`. `failed = broken;` (1761) is the only failure signal counted (`++failures >= 3`, 1770). But `path_up()` fails *without* setting `broken` in several places: `clocks_on()` false (1696-1699), `codec_wait() == 0` (1704-1706), `bolero_look()` unknown version (1118), `dsp_path_on()`/`dsp_port_on()` (APR refusal), `datapath_on()` returning false after a failed `swr_read()` (1001-1003), and `listen()` returning early on a refused RUN (1565-1569). In all of those `failed` is false, the code prints "ended", runs `undo()` and loops: `darwin_wants` is still 1 while Darwin keeps the device open, so it immediately starts another attempt. Each attempt is `clocks_on` (DSP votes and clock commands, up to 1 s per unanswered command), the codec reset pulse on GPIO 83, pins, SoundWire master bring-up, `codec_wait()` (200 ms) and the undo of all of it, indefinitely, with lines suppressed by `quiet` after the first. `recordings` grows without limit.Scenario: codec or DSP not answering (the case the retry cap was written for) while the audio server holds the input open: the cap never fires.@@ -151,23 +151,23 @@ Fix:+ if (up) { listen(true); }+ failed = broken || !up || (listen produced no samples, e.g. reads_done == 0);```-(then the existing `failures >= 3` and the "wait until iOS closes" logic apply).+(then the existing `failures >= 3` and the "wait until Darwin closes" logic apply).### S-07 Low CONFIRMED-`sound.c:635` `kmem_alloc(... &space.tables, 3 * 4096 ...)` in `space_on()`; `space_off()` (693-706) and the rest of the file never free it (`grep kmem_free`: no hits in the five files). `shared_get()` calls `space_on()` whenever `space_users == 0` and `!space.on` (725-730). With mic=4 and no sound=N every iOS recording takes and gives back the last user (`hakios_audio_dsp_memory()` / `_put()`), so each recording leaks 12 KB of wired kernel memory and overwrites the pointer. The same happens after the TLB-wait timeout return at 672-675 (tables allocated, `space.on` false, next call allocates again). Not freeing while the context could still be walked is safe (the pointer is simply lost); fix: keep one allocation (`if (space.tables == 0) kmem_alloc(...)`) and re-zero it, or free it in `space_off()` after the context is switched off and the TLB invalidated.+`sound.c:635` `kmem_alloc(... &space.tables, 3 * 4096 ...)` in `space_on()`; `space_off()` (693-706) and the rest of the file never free it (`grep kmem_free`: no hits in the five files). `shared_get()` calls `space_on()` whenever `space_users == 0` and `!space.on` (725-730). With mic=4 and no sound=N every Darwin recording takes and gives back the last user (`hakios_audio_dsp_memory()` / `_put()`), so each recording leaks 12 KB of wired kernel memory and overwrites the pointer. The same happens after the TLB-wait timeout return at 672-675 (tables allocated, `space.on` false, next call allocates again). Not freeing while the context could still be walked is safe (the pointer is simply lost); fix: keep one allocation (`if (space.tables == 0) kmem_alloc(...)`) and re-zero it, or free it in `space_off()` after the context is switched off and the TLB invalidated.### S-08 Medium PLAUSIBLE (mode CONFIRMED, effect depends on sandboxing, which I did not examine)`audio.c:343` and `mic.c:1732` create the nodes with mode 0666. In XNU file permissions are the only gate in the kernel for `open()` (a sandbox profile may add more).-- Microphone: opening `/dev/hakios-mic` sets `ios_wants = 1` (mic.c:1524-1526), which makes the for_ios thread power the codec path up and fill `ring`; any reader gets the audio (`mic_dev_read`, 1484-1519). Two readers split the stream. The ring is not cleared between sessions (only reset in the thread, 1752-1754, which races with a reader that starts at open).-- `ios_wants` is a single flag: `mic_dev_close` sets it to 0 (1532). If any other process opens and closes the node (or XNU calls `d_close` for a close that is not the last: I could not confirm from this tree which, the XNU `spec_close` source is not in the repository), the audio server's recording path is taken down while it still reads.+- Microphone: opening `/dev/hakios-mic` sets `darwin_wants = 1` (mic.c:1524-1526), which makes the for_darwin thread power the codec path up and fill `ring`; any reader gets the audio (`mic_dev_read`, 1484-1519). Two readers split the stream. The ring is not cleared between sessions (only reset in the thread, 1752-1754, which races with a reader that starts at open).+- `darwin_wants` is a single flag: `mic_dev_close` sets it to 0 (1532). If any other process opens and closes the node (or XNU calls `d_close` for a close that is not the last: I could not confirm from this tree which, the XNU `spec_close` source is not in the repository), the audio server's recording path is taken down while it still reads.- `/dev/hakios-audio`: any process can inject audio and call `HAKIOS_AUDIO_SET_VOLUME` (mute, unmute, S-01/S-02). Each ioctl also logs through `printf` (audio.c:272) and, in sound.c, `say()` to the loader log (1258), so a loop of ioctls floods a log that "keeps its beginning and its end".Memory safety of the concurrent readers was checked and is fine (all indices are taken modulo the ring size and every copy length is clamped; at worst a reader gets torn or repeated audio).-Fix: create both nodes `0600`/root:wheel (or a dedicated group of the audio server), refcount opens (`ios_wants` as a counter or open-exclusive with `EBUSY`), rate-limit the ioctl logging.+Fix: create both nodes `0600`/root:wheel (or a dedicated group of the audio server), refcount opens (`darwin_wants` as a counter or open-exclusive with `EBUSY`), rate-limit the ioctl logging.### S-09 Low PLAUSIBLE@@ -195,18 +195,18 @@ The DSP writes into `buffer + BUFFER_BYTES` (`sound.c:766`, memory from `kmem_al### S-15 Low CONFIRMED-Periods are re-submitted only when the DSP says it has finished the previous submission of that period. `sound.c:1194-1199` (feeder) counts a failed `period_write()` in `failed++` and moves on; `mic.c:1644` `(void)mic_read(next);`. `hakios_adsp_apr(..., ms = 0, ...)` returns false when the glink send fails or the channel is not open (`hakios.adsp.c:2536, 2555-2557`). That period never comes back (no event is ever generated for it), so after eight failures the stream is permanently empty: speakers play silence from the DSP's own underflow handling, and the mic loop spins in `sleep_ms(2)` until iOS closes the device (the "no read has come back" guard at `mic.c:1601` only counts while `reads_done == 0`). Fix: keep a "pending" bitmask of periods that failed to submit and retry them in the loop.+Periods are re-submitted only when the DSP says it has finished the previous submission of that period. `sound.c:1194-1199` (feeder) counts a failed `period_write()` in `failed++` and moves on; `mic.c:1644` `(void)mic_read(next);`. `hakios_adsp_apr(..., ms = 0, ...)` returns false when the glink send fails or the channel is not open (`hakios.adsp.c:2536, 2555-2557`). That period never comes back (no event is ever generated for it), so after eight failures the stream is permanently empty: speakers play silence from the DSP's own underflow handling, and the mic loop spins in `sleep_ms(2)` until Darwin closes the device (the "no read has come back" guard at `mic.c:1601` only counts while `reads_done == 0`). Fix: keep a "pending" bitmask of periods that failed to submit and retry them in the loop.### S-16 Low CONFIRMED (test configuration)-`mic.c:1597`: the end condition is `(for_ios ? (!ios_wants || stopping) : elapsed_ms >= mic_secs * 1000ull) || broken`. For mic=1..3 `stopping` is ignored, but `hakios_mic_dsp_down()` (1839-1847) sets `stopping` and then waits on `mic_lock`, which `mic_thread` holds through the whole `listen(false)`. So the DSP shutdown at the run's end is delayed by up to `mic_secs` (clamped to 600). Fix: test `stopping` in both branches.+`mic.c:1597`: the end condition is `(for_darwin ? (!darwin_wants || stopping) : elapsed_ms >= mic_secs * 1000ull) || broken`. For mic=1..3 `stopping` is ignored, but `hakios_mic_dsp_down()` (1839-1847) sets `stopping` and then waits on `mic_lock`, which `mic_thread` holds through the whole `listen(false)`. So the DSP shutdown at the run's end is delayed by up to `mic_secs` (clamped to 600). Fix: test `stopping` in both branches.## Checked and found finehakios.audio.c- `audio_write()`: 4 KB stack buffer, chunk length rounded to whole frames and clamped to the buffer, `uiomove` length cast safe, tail of fewer than 4 bytes dropped (not copied uninitialised), error from `uiomove` returned.- `audio_record()`: bound `rec_used + sizeof(block) + bytes > rec_size` includes the block header; `rec_frames_max` / `rec_size` computed in uint64; `rec_sound` clamped to 1200 s; memory zeroed (`KMA_ZERO`), header written before `loader_sound[]` is published; `loader_sound[1]` updated under `audio_lock`.-- Locking: `audio_lock` is a mutex; the sink is called under it and must not sleep, and neither `ios_sink` nor `sound_play` does; lock order is `audio_lock` -> `sound_lock`/nothing, never the reverse (`sound.c` takes `audio_lock` only in `hakios_audio_set_sink`/`hakios_audio_volume` without holding `sound_lock`, except `sound_thread` which takes `sound_lock` -> `audio_lock`; no path takes them the other way round). `audio_report` is re-armed under the lock and its divisions are guarded (`lasted >= 1 s`).+- Locking: `audio_lock` is a mutex; the sink is called under it and must not sleep, and neither `darwin_sink` nor `sound_play` does; lock order is `audio_lock` -> `sound_lock`/nothing, never the reverse (`sound.c` takes `audio_lock` only in `hakios_audio_set_sink`/`hakios_audio_volume` without holding `sound_lock`, except `sound_thread` which takes `sound_lock` -> `audio_lock`; no path takes them the other way round). `audio_report` is re-armed under the lock and its divisions are guarded (`lasted >= 1 s`).- `audio_play()` when the sink is replaced by NULL (take_down) is correct; sinks return `taken <= count` so `stretch_lost` cannot underflow.hakios.virtio_sound.c@@ -217,8 +217,8 @@ hakios.virtio_sound.chakios.sound.c- SMMU page-table construction: all indices (`root[0]`, `second[0]`, `third[0..23]`) are constants inside one table; `SHARED_BYTES / 4096` entries fit; tables cleaned with `dc civac` + `dsb` before the context is enabled; `used[256]` is indexed with `s2cr & 0xff`; `contexts` from `idr1 & 0xff` bounds the context search; IDR-derived geometry is validated against 1 MB before use; `space_find()` refuses to touch a context or match register that is in use.-- Speaker period cache maintenance: `period_fill()` and `period_fill_ios()` clean every line of the period (`dc cvac` loop over `PERIOD_BYTES`, then `dsb sy`) after the guard has processed it and before submission; periods are refilled only after the DSP has returned them.-- Ring between `ios_sink` (producer, serialized by `audio_lock`) and `period_fill_ios` (single consumer): free-running volatile indices, power-of-two size, data written before `ring_head` with `OSMemoryBarrier`, consumer reads `ring_head` before the data; `ring_tail` advanced after the copy; `available` can never exceed the ring.+- Speaker period cache maintenance: `period_fill()` and `period_fill_darwin()` clean every line of the period (`dc cvac` loop over `PERIOD_BYTES`, then `dsb sy`) after the guard has processed it and before submission; periods are refilled only after the DSP has returned them.+- Ring between `darwin_sink` (producer, serialized by `audio_lock`) and `period_fill_darwin` (single consumer): free-running volatile indices, power-of-two size, data written before `ring_head` with `OSMemoryBarrier`, consumer reads `ring_head` before the data; `ring_tail` advanced after the copy; `available` can never exceed the ring.- `events()`: payload length tested before `payload[3]`; bit index from the DSP's token only sets bits in a mask, extra bits are cleared by the receivers.- Every wait loop is bounded: `play()` (2 s after end, 1 s first period), TLB wait 100 ms, `take_down()` 3 s, `pin_activity` fixed 20000 reads, APR waits 1 s. Stop ordering in `take_down()`: amplifiers stop before the stream closes, the stream closes before the region is unmapped, the region is unmapped before the SMMU context is restored; the shared buffer is deliberately never freed (no use after free).- AFE parameter packets (`afe_service_param`, `afe_port_param`): payload at most 44 bytes into a 64-byte area, all sizes constant.@@ -263,7 +263,7 @@ Edits only in drivers/audio/hakios.{audio,sound,speaker,mic,virtio_sound}.c and- S-03 FIXED. speaker.c acf_monitor(): both table-end checks are done in uint64; the `less` addition for the battery rows now saturates at 0xffff instead of wrapping.- S-04 FIXED (partly). speaker.c hakios_speaker_stop(): every failed step now goes through stop_failed(), which calls power_down_now() (both amplifiers, unless already broken), so a failed read in sysctrl() no longer leaves the amplifiers up. NOT done: take_down() in sound.c still ignores the result of the stop (it is a void function; changing it is a design change), but it now finds the amplifiers powered down or retained as "started" for the quiesce.- S-05 FIXED (partly). speaker.c power_down_now(): `started` is cleared only when the power-down write and read-back were acknowledged, so hakios_speaker_quiesce() still tries again. SKIPPED: the bus recovery (clocking out SCL pulses) in bus_take(); it needs knowledge of the I2C/amplifier hardware.-- S-06 FIXED. mic.c: listen() now returns bool (false when the RUN is refused, a read cannot be sent, or no read comes back in 1.5 s); for_ios() counts `!path_up() || !listen()` as a failure, so the existing three-failure limit applies. Not done: counting "listen produced no samples" beyond those cases.+- S-06 FIXED. mic.c: listen() now returns bool (false when the RUN is refused, a read cannot be sent, or no read comes back in 1.5 s); for_darwin() counts `!path_up() || !listen()` as a failure, so the existing three-failure limit applies. Not done: counting "listen produced no samples" beyond those cases.- S-07 FIXED. sound.c space_on(): the three page-table pages are allocated once and re-zeroed on reuse, instead of a new kmem_alloc at every call.- S-08 SKIPPED. The fix is a change of the node mode (0666), which is policy and not to be changed here; the refcount of opens and the rate limit of the ioctl log are a design change.- S-09 SKIPPED. Changing the SoundWire read id range (and re-testing the FIFO) depends on how the hardware treats id 0 and an empty FIFO (NEEDS-HARDWARE).diff --git a/docs/driver-review/wifi-stack.md b/docs/driver-review/wifi-stack.mdindex 1ca2aaf..9b8b0c5 100644--- a/docs/driver-review/wifi-stack.md+++ b/docs/driver-review/wifi-stack.md@@ -93,7 +93,7 @@ The unwrap in a pairwise message also has to use `cand_kek`. Message 2 is answerTwo failures, both from a spoofed plaintext EAPOL frame:-1. Any forged signed-looking key frame with `MIC|ACK` set and a bad MIC (or no message 1 seen yet) makes `lx_wpa_message` return `LX_WPA_BAD` (lx_wpa.c:484, 493). The loop exits at once and the join fails with `EAUTH`, which iOS shows as "wrong password" (`apple80211.c:639` maps `EAUTH` to result 21, "invalid PMK").+1. Any forged signed-looking key frame with `MIC|ACK` set and a bad MIC (or no message 1 seen yet) makes `lx_wpa_message` return `LX_WPA_BAD` (lx_wpa.c:484, 493). The loop exits at once and the join fails with `EAUTH`, which Darwin shows as "wrong password" (`apple80211.c:639` maps `EAUTH` to result 21, "invalid PMK").2. A genuine message 3 sets `handshake = KEYS`; a forged message 1 right behind it sets `ANSWER` before the join thread has run. The loop then keeps waiting and times out after 8 s, although the handshake succeeded and message 4 was sent.Fix: make KEYS sticky, and do not end the wait on BAD (the standard says to silently discard bad frames):diff --git a/docs/getting-started/building.md b/docs/getting-started/building.mdindex e95c827..9655e74 100644--- a/docs/getting-started/building.md+++ b/docs/getting-started/building.md@@ -4,7 +4,7 @@## The kernel-Apple's XNU sources (the release iOS 16.5 was built from) with this port laid over them:+Apple's XNU sources (the release Darwin userland 16.5 was built from) with this port laid over them:```shmake redwood_defconfig # or any device's defconfig; without a .config every driver is built@@ -41,7 +41,7 @@ A driver you edit in `drivers/` goes into the tree by itself on the next `make kmake loader # xnuloader/build.sh: clang and 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:+The header `xnuloader/identity.h`, the properties by which Darwin 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 (`sysimage/unpack.sh` leaves it in `sysimage/`). `make loader-open` makes the placeholderloader that boots the open kernel only.diff --git a/docs/getting-started/index.md b/docs/getting-started/index.mdindex 3f6be2d..f7404ab 100644--- a/docs/getting-started/index.md+++ b/docs/getting-started/index.md@@ -6,7 +6,7 @@ should see, and what to check when you do not see it.| | What you get | What you need | Time ||---|---|---|---|| [**The open kernel in QEMU**](qemu.md#the-open-kernel) | the kernel, the loader and a tiny user space, booting | a Linux or macOS machine, QEMU | minutes |-| [**iOS in QEMU**](qemu.md#ios-in-qemu) | the lock screen and the home screen in a window | Linux, 12 GB of disk, Apple's IPSW (downloaded for you) | an hour, mostly downloads |+| [**Darwin in QEMU**](qemu.md#darwin-in-qemu) | the lock screen and the home screen in a window | Linux, 12 GB of disk, Apple's IPSW (downloaded for you) | an hour, mostly downloads || [**On the phone**](phone.md) | the system on a POCO X5 Pro 5G, in RAM | the phone, its boot loader unlocked, `adb` and `fastboot` | an hour the first time |Building from source is optional for all three: `prebuilt/` has a kernel, a loader and libraries made from these repositories.diff --git a/docs/getting-started/phone.md b/docs/getting-started/phone.mdindex 9edd01a..83ac0f2 100644--- a/docs/getting-started/phone.md+++ b/docs/getting-started/phone.md@@ -14,7 +14,7 @@ that you create yourself, and nowhere else. [What is written, exactly](../concep- the phone, its boot loader unlocked;- `adb` and `fastboot` on the PC (Google's platform-tools; on Windows, see [Windows](../windows.md));-- the images of [iOS in QEMU](qemu.md#ios-in-qemu) (`userland/system.apfs`), and `make loader` done once;+- the images of [Darwin in QEMU](qemu.md#darwin-in-qemu) (`userland/system.apfs`), and `make loader` done once;- the phone's own firmware, pulled from it (below). It is the vendor's and is never in the repositories.- the firmware that starts the loader: HakiOS's U-Boot (`make u-boot`, open source only: [U-Boot](../u-boot.md)), orSilicium's UEFI built with your phone's own vendor drivers (`uefi/README.md`). `xl` takes Silicium's when it is built, elsediff --git a/docs/getting-started/qemu.md b/docs/getting-started/qemu.mdindex e7dc4ab..5a35f7d 100644--- a/docs/getting-started/qemu.md+++ b/docs/getting-started/qemu.md@@ -16,7 +16,7 @@ What you should see in the log: `== XNULOADER v3 ==`, the kernel's banner with `(`hakios-kernel: N drivers built in (...)`), and the user space's own lines. `make qemu-open` uses `configs/defconfig`; with`make qemu_defconfig` first, the kernel is built with only QEMU's drivers in it ([devices/qemu](../devices/qemu.md)).-## iOS in QEMU+## Darwin in QEMULinux x86-64, about 12 GB of disk, 7-Zip 23 or newer, `lz4`, `qemu-system-aarch64`, `edk2-aarch64`.@@ -26,11 +26,11 @@ sysimage/unpack.sh ~/iPhone10,3,iPhone10,6_16.5_20F66_Restore.ipsw # YOUR IPSWREST=1 userland/build.sh # the APFS images: userland/root.apfs and userland/system.apfsmake loader # the boot loader, with the iPhone's identity taken from YOUR copy of the IPSWmkdir -p logs-qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # a 20-minute session+qemu/run-darwin.sh 1200 -display gtk > logs/qemu.log # a 20-minute session````make loader` is not optional here: `prebuilt/loader.efi` has no Apple data in it on purpose and boots the open kernel only.-`qemu/run-ios.sh` refuses to start without your own `xnuloader/loader.efi`, and says so.+`qemu/run-darwin.sh` refuses to start without your own `xnuloader/loader.efi`, and says so.### What you will see@@ -51,15 +51,15 @@ Check these in order.1. **The log.** `tail -f logs/qemu.log` in another terminal. It should print `== XNULOADER v3 ==` within seconds, and kernel andlaunchd lines after that. Nothing at all: QEMU did not start the loader; run `make doctor`.2. **An old loader.** A log with `ramfb: control ... after the request` near its top is a loader built before 27 October 2026 (a- compiler could skip the check of the display request): the window stays at 800x600 and iOS draws outside it. `make loader` again.+ compiler could skip the check of the display request): the window stays at 800x600 and Darwin draws outside it. `make loader` again.3. **What the guest shows.** `qemu/screendump.sh` saves the guest's screen to `logs/qemu-screen.png`, whatever your window does.4. **No window.** Your QEMU may have no GTK window (a headless package, WSL without WSLg). Use- `qemu/run-ios.sh 1200 -display vnc=127.0.0.1:0 > logs/qemu.log` and a VNC viewer on `127.0.0.1:5900`.+ `qemu/run-darwin.sh 1200 -display vnc=127.0.0.1:0 > logs/qemu.log` and a VNC viewer on `127.0.0.1:5900`.5. **Memory.** The guest asks for 7 GB (`QEMU_RAM_GB`; 6 at the very least: the system image sits 3 GB into it and is 2.5 GB).Without that the host swaps and everything is very slow.-6. **The images.** `qemu/run-ios.sh` needs `userland/system.apfs` and `userland/root.apfs`; a missing one is reported at once.+6. **The images.** `qemu/run-darwin.sh` needs `userland/system.apfs` and `userland/root.apfs`; a missing one is reported at once.## Metal in QEMU-`RC_JOBS=rc.jobs.metal` with the boot argument `metal=1` runs `metal_test`, which prints what iOS believes about Metal, what the+`RC_JOBS=rc.jobs.metal` with the boot argument `metal=1` runs `metal_test`, which prints what Darwin believes about Metal, what thedevice makes (buffers, a library) and what CoreImage does. [The Metal plan](../metal-plan.md) has what each line means.diff --git a/docs/index.md b/docs/index.mdindex a07bc7c..e6427b1 100644--- a/docs/index.md+++ b/docs/index.md@@ -6,7 +6,7 @@ of Apple's and nothing of any phone's.Where to start:-- [Getting started](getting-started/index.md): the open kernel in QEMU in a few commands, or the iOS 16.5 user space you lay+- [Getting started](getting-started/index.md): the open kernel in QEMU in a few commands, or the Darwin userland 16.5 user space you layout yourself.- [On the phone](getting-started/phone.md): the POCO X5 Pro 5G, in RAM with `fastboot boot`, back to Android with a reboot.- [Port a device](porting/index.md): a device is a repository of its own over the common one: a defconfig, a status file, its@@ -34,7 +34,7 @@ The table is made from the devices' own `device.conf`: [all devices](devices/ind## The three layers1. **The open core**: the kernel port, the loader, the drivers, the tools. All source, in these repositories.-2. **What you put on top**: the kernel can start a user space you supply; it was built so that it can start iOS 16.5's, which you+2. **What you put on top**: the kernel can start a user space you supply; it was built so that it can start Darwin userland 16.5's, which youlay out yourself from Apple's own download. None of it is in the repositories.3. **Apple's services** (activation, Apple ID, iCloud, the App Store): not supported and not a goal.diff --git a/docs/legal-review.md b/docs/legal-review.mdindex 5573cac..e976b2e 100644--- a/docs/legal-review.md+++ b/docs/legal-review.md@@ -13,8 +13,8 @@ verify something, it says so.| Layer | Verdict | Why ||---|---|---|| The open code (kernel patch under APSL 2.0, our loader/tools/userland under MIT) | **Fine, with homework done well.** | `COMPLIANCE.md` is a solid checklist: source published, Apple's notices kept, XNU-derived code not relabelled MIT. |-| **Running iOS on non-Apple hardware** | **Grey, and a breach of Apple's licence for whoever does it.** | The licence grants use "on a single Apple-branded Device" and forbids copying/decrypting/modifying/deriving ([iOS 16 licence](https://www.apple.com/legal/sla/docs/iOS16_iPadOS16.pdf), §2(a), §2(d)). Not distributing iOS is the right mitigation and you do it. Courts split on the rest (below). |-| **Four things in the repo that contradict its own legal statements** | **Fix before anything else.** | Vendor blobs tracked in git, iOS screenshots still in history, App Store/FairPlay experiments plus an iPhone identity, "iOS" emphasised in the brand. Details below. |+| **Running Darwin on non-Apple hardware** | **Grey, and a breach of Apple's licence for whoever does it.** | The licence grants use "on a single Apple-branded Device" and forbids copying/decrypting/modifying/deriving ([Darwin userland 16 licence](https://www.apple.com/legal/sla/docs/iOS16_iPadOS16.pdf), §2(a), §2(d)). Not distributing Darwin is the right mitigation and you do it. Courts split on the rest (below). |+| **Four things in the repo that contradict its own legal statements** | **Fix before anything else.** | Vendor blobs tracked in git, Darwin screenshots still in history, App Store/FairPlay experiments plus an iPhone identity, "Darwin" emphasised in the brand. Details below. || **The $HackiOS token** | **Separate, and the biggest risk of the whole thing.** | A token licenses nothing and cannot make the project "legal"; it can only fund it. But it turns a research project into one with a revenue stream, which changes how courts, Apple, platforms and regulators see it. |The single most useful sentence: **keep the token and the code completely apart, and never sell or@@ -28,13 +28,13 @@ gate anything that contains Apple's code behind it.**hardware was enforceable. Psystar was a commercial hardware seller, and the district court alsofound a DMCA violation (I could not confirm what the appeal said about the DMCA part).- **[Apple v. Corellium](https://9to5mac.com/2023/05/08/us-court-corellium-apple-ios/) (11th Cir., May- 2023, unpublished):** Corellium won on fair use for its iOS virtualisation, reasoning that it- advanced security research and that iOS is largely functional. Three limits matter to you: the+ 2023, unpublished):** Corellium won on fair use for its Darwin virtualisation, reasoning that it+ advanced security research and that Darwin is largely functional. Three limits matter to you: theopinion is unpublished and fact-specific; the court **sent back Apple's claims about icons andwallpapers** unresolved; and the parties [settled in December 2023](https://www.theregister.com/2023/12/18/apple_corellium_case_settles/)on confidential terms. Corellium was a research tool, not a consumer port.-- **What follows for HakiOS:** you sit between the two. You do not sell iOS or hardware (good, unlike- Psystar), but you are a hardware port that lets people run iOS on a phone, not a research+- **What follows for HakiOS:** you sit between the two. You do not sell Darwin or hardware (good, unlike+ Psystar), but you are a hardware port that lets people run Darwin on a phone, not a researchvirtualiser, and Corellium's facts are about research. Do not rely on Corellium as a safe harbour.- **Jurisdiction decides a lot.** Apple's licence is governed by California law (§12), but themaintainers and users live elsewhere. In the EU, rules on lawful acquirers and interoperability@@ -43,7 +43,7 @@ gate anything that contains Apple's code behind it.**### What the build does that touches Apple's code (the exposure that is yours, not the user's)- `sysimage/unpack.sh` unpacks parts of an IPSW the user supplies (nothing is downloaded) and `userland/build.sh`- assembles a modified root image: it selects parts of iOS, replaces launchd with `stage0`, injects+ assembles a modified root image: it selects parts of Darwin, replaces launchd with `stage0`, injectsour dylibs into SpringBoard and other Apple processes (`userland/src/inject*.c`), and`xnuloader/mkidentity.py` copies the iPhone's device-tree identity so the system "believes it isthe iPhone its files were built for". Licence §2(d) forbids to "modify, or create derivative works".@@ -75,7 +75,7 @@ Note: deleting `Binaries/` is not enough, because `SILICIUM_UEFI.fd` carries the`pull-firmware-root.sh` and UEFIReader flow), build `SILICIUM_UEFI.fd` locally, and drop the trackedcopies. Then fix the sentences in README/LEGAL so they are true.-### P0-b. iOS screenshots are still in the history+### P0-b. Darwin screenshots are still in the historyCommit `3849ceb` (2026-10-25) removed `docs/homescreen.jpg`, `lockscreen`, `settings`, `messages`,`maps`, `wallet`, `appstore-*`, and more, but they remain retrievable from history and from any clone@@ -92,13 +92,13 @@ consciously: the alternative is to accept the risk and say so.Apple's services". Yet: the loader presents the device as an iPhone (`identity.h`), and`userland/src/inject_store.c` (opt-in `STOREFRONT=1`) injects into `appstored`, makes it answer withthe storefront `143469-2,8`, and notes that it fetched Apple's bag from `bag.itunes.apple.com` and-`init.itunes.apple.com` "by hand". `inject_fairplay.c` studies Apple's **FairPlay** daemon. iOS itself,+`init.itunes.apple.com` "by hand". `inject_fairplay.c` studies Apple's **FairPlay** daemon. Darwin itself,believing it is an iPhone X, also contacts Apple's servers on its own.**Status (27 October 2026).** The App Store and FairPlay experiments were removed from the tree earlier. The Apple data in thedistributed loader is now gone too: `prebuilt/loader.efi` is built with the placeholder identity (`xnuloader/mkidentity.sh--placeholder`, no Apple device-tree data in it; checked by searching the binary for the iPhone model and board names), and-`tools/update-prebuilt.sh` builds it that way in a temporary copy so that it cannot come back. The loader that starts iOS is built+`tools/update-prebuilt.sh` builds it that way in a temporary copy so that it cannot come back. The loader that starts Darwin is builtby the user (`make loader`), on their own machine, with the identity taken from **their** copy of the IPSW. **Still open:** theloader's own source writes two fixed device-tree values (`serial-number` "RDW00POCOX5P", `model-number` "MQAC2", in`xnuloader/loader.c`; the second is an Apple model code), and older commits of `prebuilt/loader.efi` in the git history still@@ -110,12 +110,12 @@ store is what draws attention. **Fix:** keep these experiments out of the publicbranch), make outbound traffic to Apple's service hosts blocked by default in the image with a documentedswitch, and rewrite the sentence to say what is true.-### P1. The name and the logo emphasise "iOS"+### P1. The name and the logo emphasise "Darwin"The project is "HakiOS" in the repo, "HackiOS" in the token and site, and the brand rules write "HACK in-white, iOS in red". "iOS" is Apple's mark; descriptive use ("works with iOS") is fine, but a product name+white, Darwin in red". "Darwin" is Apple's mark; descriptive use ("works with Darwin") is fine, but a product namethat embeds and highlights it is where confusion claims start, and `hackios.org` repeats it. This is a-branding decision, not a legal emergency: at least stop highlighting "iOS" in the logo, and use one+branding decision, not a legal emergency: at least stop highlighting "Darwin" in the logo, and use onespelling everywhere. A rename is the clean fix if you expect to grow.## 3. Copyright hygiene in your own code (low effort, high value)@@ -185,7 +185,7 @@ review §2 and §4 before the team acts on this.## 6. Decisions I need from you (ranked)1. Remove the vendor blobs and the built UEFI image from the tree (P0-a)? I can prepare the change.-2. Purge the iOS screenshots from history (P0-b)? This rewrites history; it needs the whole team.+2. Purge the Darwin screenshots from history (P0-b)? This rewrites history; it needs the whole team.3. Move the App Store / FairPlay experiments off the public repository (P0-c)?4. Keep the "HackiOS" name, or rename before it grows (P1)?5. Change the community pot so it is never paid to holders pro rata (§4.1)?diff --git a/docs/metal-plan.md b/docs/metal-plan.mdindex 055d310..3562e4d 100644--- a/docs/metal-plan.md+++ b/docs/metal-plan.md@@ -98,18 +98,18 @@ What the plug-in now makes, in `userland/src/HakiosMetal.m`:How it was checked, and what that does not show:-- `tools/metallib-test.sh DIR`: the C reading and `tools/metallib.py` agree on every function of every `.metallib` of the iOS 16.5+- `tools/metallib-test.sh DIR`: the C reading and `tools/metallib.py` agree on every function of every `.metallib` of the Darwin userland 16.5system (the five MTLB files; the five runtime libraries of `AGXMetalA11.bundle` are another format, and both refuse them) and ofmacOS's; a file made by the test and then cut short at every length, and with each offset and length bent outside it, is refusedevery time, under the address and undefined-behaviour sanitizers. One correction came out of it: the header's second word at0x20 is the function list's length after its count, not its end (`tools/metallib.py` calls it `funcs_end` and does not use it).- `tools/metal-plugin-test.sh DIR`: the plug-in built for macOS, its device made the way Metal makes it, on the Mac's own`_MTLDevice`, `_MTLResource`, `_MTLLibrary`, `_MTLFunction`: buffers written, read back, copied, refused over `maxBufferLength`,- freed (and the caller's deallocator called); the five iOS libraries read (36, 135, 11, 274 and 0 functions; the last is+ freed (and the caller's deallocator called); the five Darwin libraries read (36, 135, 11, 274 and 0 functions; the last isSafariSharedUI's, a header and nothing else), every function made by its name with its type, every module LLVM bitcode. All- under the address sanitizer. **macOS's Metal is not iOS 16.5's**: this shows the plug-in's own logic, not that iOS's Metal is+ under the address sanitizer. **macOS's Metal is not Darwin userland 16.5's**: this shows the plug-in's own logic, not that Darwin's Metal iscontent with these objects.-- Built for iOS 16.5 (`-Wall -Wextra`, no warnings). Not yet run on iOS: `metal_test` asks "what the device makes" in a process of+- Built for Darwin userland 16.5 (`-Wall -Wextra`, no warnings). Not yet run on Darwin: `metal_test` asks "what the device makes" in a process ofits own (`RC_JOBS=rc.jobs.metal`, `metal=1`), and its line is the result that goes here.Still nothing is drawn or computed: a pipeline made of these functions is the empty stand-in of step one. The next step is the@@ -129,13 +129,13 @@ it is in this repository, the facts below are written here in our own words andthe question of the next step, and it is not decided here.- **Universal metallibs.** Newer systems ship framework libraries as a fat container (0xCAFEBABE) of an AIR64 slice and a binaryfor Apple's GPUs (QuartzCore's `default.metallib` on iPadOS 17). `hakios_metallib_thin()` takes the AIR64 slice, as Metal does;- `tools/metallib-test.sh` and `tools/metal-plugin-test.sh` check it. iOS 16.5's libraries are all thin.+ `tools/metallib-test.sh` and `tools/metal-plugin-test.sh` check it. Darwin userland 16.5's libraries are all thin.- **CoreImage's limits.** `CIMetalDeviceGetLimits` reads `dedicatedMemorySize` and `sharedMemorySize`, which `_MTLDevice` doesnot answer; without them every `CIContext` throws (iconservicesagent ended over symbol glyphs there). The device now answersthem, `isLowPower`, `isRemovable`, `isHeadless`, and `supportsFeatureSet:` (NO: the base reads Apple's tables).- **Clients by a file.** A file beside the bundle names the processes shown the device. `HakiosMetal.clients` does the same here,on top of `metal=N`.-- **The window server needs QuartzCore's own `default.metallib`.** Their system image has it; iOS 16.5's (this port's) does not,+- **The window server needs QuartzCore's own `default.metallib`.** Their system image has it; Darwin userland 16.5's (this port's) does not,which is the wall of step 7 above. It is not something the plug-in can supply: the library is Apple's.## Frame skipsdiff --git a/docs/net-review.md b/docs/net-review.mdindex d509fd3..535e9b1 100644--- a/docs/net-review.md+++ b/docs/net-review.md@@ -1,7 +1,7 @@# HakiOS — network stack reviewA read-level audit of the networking code: the `en0`/`en1` data paths, the links behind them,-and the Apple80211 control plane iOS talks to. The goal was to find real correctness bugs and to+and the Apple80211 control plane Darwin talks to. The goal was to find real correctness bugs and tomap what is genuinely left to do. No build or device run was part of this pass (done on a Windowshost); every finding is from reading the source, with file and line references so each can bechecked.diff --git a/docs/port-pkg110.md b/docs/port-pkg110.mdindex 97a9e97..6ee508d 100644--- a/docs/port-pkg110.md+++ b/docs/port-pkg110.md@@ -74,14 +74,14 @@ the boot test itself: `./xl enter` does a `fastboot boot`, which a truly locked`prebuilt/loader.efi` when nothing is built (`xl:50-53,120`): those are the `redwood` kernel andloader, i.e. for this SoC. The toolchain is only needed to build a *changed* kernel (which thecellular fix eventually is).-- **The iOS system image IS needed for a modem run** (a correction: the first run proved the+- **The Darwin system image IS needed for a modem run** (a correction: the first run proved theearlier assumption wrong). With no ramdisk at all (`XL_RAMDISK=none`) the kernel panics beforethe modem thread starts -- `Failed to mount root device @IOKitBSDInit.cpp:926` -- because themodem steps run "once the root is there" (`hakios.mpss.c:6256`). And the modem's firmware is readfrom `/fw` of the system image, which `MODEM=1 userland/build.sh` fills from `fw-modem/`(`hakios.mpss.c:1045-1110`). The modem's own file systems (modemst1/2, fsc, fsg) do come from thephone's UFS (`ufs=2`), but in addition to the image, not instead of it. So the project's standard- path applies: `sysimage/unpack.sh YOUR.ipsw` (iOS 16.5, which you supply; ~7.4 GB unpacked) and+ path applies: `sysimage/unpack.sh YOUR.ipsw` (Darwin userland 16.5, which you supply; ~7.4 GB unpacked) and`PREBUILT=1 REST=1 MODEM=1 SYSTEM=1 userland/build.sh`.- **Build in WSL's own ext4, not on `/mnt/d`.** `unpack.sh` relies on 7z leaving files named`NAME:com.apple.decmpfs` (finished by `unzbm`); `:` is not a legal NTFS file-name character, anddiff --git a/docs/reference/drivers.md b/docs/reference/drivers.mdindex b0771c7..6dc25ba 100644--- a/docs/reference/drivers.md+++ b/docs/reference/drivers.md@@ -9,7 +9,7 @@ Every driver the kernel can be built with. `CONFIG_HAKIOS_<NAME>=y` in a defconf| File | What ||---|---|-| `hakios.audio.c` | /dev/hakios-audio, the sound iOS plays, to whatever plays it; and where the camera, flashlight, motor and speaker drivers are started from |+| `hakios.audio.c` | /dev/hakios-audio, the sound Darwin plays, to whatever plays it; and where the camera, flashlight, motor and speaker drivers are started from || `hakios.version.c` | kern.hakios.version, and the version in the boot log || `hakios.platform.c` | what the drivers share (the locks of the PMIC arbiter, the always-on processor, RPMh and the SMMU), and kern.hakios.drivers, the list of the drivers built in || `hakios.stubs.c` | what the rest of the kernel calls in a driver that is left out: nothing, and "not there" |@@ -86,7 +86,7 @@ Every driver the kernel can be built with. `CONFIG_HAKIOS_<NAME>=y` in a defconf| Driver | Files | Requires | Boot arguments | qemu | redwood | ||---|---|---|---|---|---|-| **`HAKIOS_BATTERY`**<br>the battery: kern.hakios.battery_*, and HakiosBattery, the IOPMPowerSource iOS reads the charge from (the state comes from the audio DSP's battery manager, with adsp=1) | `hakios.battery.c`<br>`hakios.battery.cpp` | | `battery_shared_pa=` | | built | |+| **`HAKIOS_BATTERY`**<br>the battery: kern.hakios.battery_*, and HakiosBattery, the IOPMPowerSource Darwin reads the charge from (the state comes from the audio DSP's battery manager, with adsp=1) | `hakios.battery.c`<br>`hakios.battery.cpp` | | `battery_shared_pa=` | | built | || **`HAKIOS_CPUFREQ`**<br>the clock of the cores the kernel runs on (cpufreq=1), and the memory bus's votes (ddr=) | `hakios.cpufreq.c` | | `cpufreq=`, `cpuload=`, `ddr=`, `ddr_rest=`, `ddr_vote=`, `membench=` | | built | || **`HAKIOS_THERMAL`**<br>the SoC's temperature sensors (thermal=1): kern.hakios.thermal_*, and the run handed back to the loader when the phone gets too hot (thermal_stop=) | `hakios.thermal.c` | | `thermal=`, `thermal_log=`, `thermal_poll=`, `thermal_stop=`, `thermal_tm0=`, `thermal_tm1=` | | built | || **`HAKIOS_PMIC`**<br>the blocks of the power-management chips the SPMI arbiter shows, and the PMIC's clock (pmic=1); read only | `hakios.pmic.c` | | `pmic=`, `pmic_list=` | | built | |@@ -103,6 +103,6 @@ Every driver the kernel can be built with. `CONFIG_HAKIOS_<NAME>=y` in a defconf| Driver | Files | Requires | Boot arguments | qemu | redwood | ||---|---|---|---|---|---|-| **`HAKIOS_WIFI`**<br>Wi-Fi of the WCN6750 (wifi=1, wifi_step=N): the DSP that runs the radio's firmware, Linux's ath11k (its object, made by tools/mk-ath11k.sh, is linked in only with this), a station, and the Apple80211 surface iOS's wifid talks to. Needs fw-wifi/ from the phone | `hakios.wifi.c`<br>`hakios.wlfw.c`<br>`hakios.lx.c`<br>`hakios.sta.c`<br>`hakios.apple80211.c`<br>`hakios.wlan.cpp` | `HAKIOS_QMI` | `wifi=`, `wifi_again=`, `wifi_ask=`, `wifi_cal=`, `wifi_dirty=`, `wifi_file=`, `wifi_fine=`, `wifi_keep=` and 14 more | | built | |+| **`HAKIOS_WIFI`**<br>Wi-Fi of the WCN6750 (wifi=1, wifi_step=N): the DSP that runs the radio's firmware, Linux's ath11k (its object, made by tools/mk-ath11k.sh, is linked in only with this), a station, and the Apple80211 surface Darwin's wifid talks to. Needs fw-wifi/ from the phone | `hakios.wifi.c`<br>`hakios.wlfw.c`<br>`hakios.lx.c`<br>`hakios.sta.c`<br>`hakios.apple80211.c`<br>`hakios.wlan.cpp` | `HAKIOS_QMI` | `wifi=`, `wifi_again=`, `wifi_ask=`, `wifi_cal=`, `wifi_dirty=`, `wifi_file=`, `wifi_fine=`, `wifi_keep=` and 14 more | | built | |The columns on the right are the devices' defconfigs: "built" means that defconfig builds the driver in.diff --git a/docs/reference/tools.md b/docs/reference/tools.mdindex c0e8a71..0cb60da 100644--- a/docs/reference/tools.md+++ b/docs/reference/tools.md@@ -8,11 +8,11 @@ Every `make` target is a script below it; run the script itself for its options|---|---|| `make` | the list below || `make doctor` | checks this machine (and a phone on `adb`) for what HakiOS needs |-| `make unpack IPSW=F` | the OS files out of your own iOS 16.5 IPSW into `sysimage/` (nothing is downloaded) |+| `make unpack IPSW=F` | the OS files out of your own Darwin userland 16.5 IPSW into `sysimage/` (nothing is downloaded) || `make images` | `userland/root.apfs` and `userland/system.apfs` || `make kernel` | the kernel from source, with the `.config`'s drivers || `make loader` / `make loader-open` | the boot loader with your IPSW's identity / the placeholder that boots the open kernel only |-| `make qemu` / `make qemu-open` | a session in QEMU with iOS / the open kernel with nothing of Apple's |+| `make qemu` / `make qemu-open` | a session in QEMU with Darwin / the open kernel with nothing of Apple's || `make phone` | a session on the phone with the `.config`'s arguments || `make firmware` | the phone's firmware off the phone (`devices/$(DEVICE)/pull-firmware.sh`) || `make esp` | an EFI system partition tree for a UEFI-native boot ([UEFI boot](../uefi-boot.md)) |diff --git a/docs/ru/cellular.md b/docs/ru/cellular.mdindex 823f128..4c330cc 100644--- a/docs/ru/cellular.md+++ b/docs/ru/cellular.md@@ -1,16 +1,16 @@# Сотовая связь: состояние и план порта-Сейчас сотовая связь в HakiOS **не работает**, но модем уже запускается из XNU (см. «21 октября» ниже). Wi-Fi использует WPSS и свой GLINK/QRTR; модем MPSS — отдельный процессор с другим каналом. `hakios.qmi.c` кодирует сообщения QMI и теперь позволяет привязать клиент к заданному транспорту QRTR, но канал к MPSS ещё не реализован. У iOS также нет драйверов AppleBaseband и AppleIPAppender для этого аппаратного пути. Запуск `CommCenter` без них уже проверялся: он завершается аварийно (см. README, раздел «Телефония»).+Сейчас сотовая связь в HakiOS **не работает**, но модем уже запускается из XNU (см. «21 октября» ниже). Wi-Fi использует WPSS и свой GLINK/QRTR; модем MPSS — отдельный процессор с другим каналом. `hakios.qmi.c` кодирует сообщения QMI и теперь позволяет привязать клиент к заданному транспорту QRTR, но канал к MPSS ещё не реализован. У Darwin также нет драйверов AppleBaseband и AppleIPAppender для этого аппаратного пути. Запуск `CommCenter` без них уже проверялся: он завершается аварийно (см. README, раздел «Телефония»).-Проверка `python3 devices/redwood/tools/modem_firmware.py --dtb devices/redwood/prebuilt/device-tree.dtb --firmware-dir fw-modem --node /soc/qcom,mss@4080000` сопоставила 28 сегментов штатной прошивки с областью `mpss@8b800000` (PAS ID 4). `MODEM=1 SYSTEM=1 ... userland/build.sh` теперь может положить эти локальные файлы в системный APFS после проверки. Это только подготовка образа: наличие прошивки в `/fw` не запускает MPSS. Исходник `hakios.nas.c` содержит клиент QMI NAS для заданного транспорта QRTR: он ищет службу, запрашивает регистрацию и силу сигнала, разбирает ответы и сбрасывает состояние при исчезновении службы. Уровень `bars` остаётся нулевым без подтверждённой регистрации. MPSS-транспорта в XNU пока нет, поэтому этот клиент ещё не получает сообщения с телефона и не подключён к статус-бару iOS. Форматы NAS сверены с [описанием libqmi](https://github.com/linux-mobile-broadband/libqmi/blob/main/data/qmi-service-nas.json).+Проверка `python3 devices/redwood/tools/modem_firmware.py --dtb devices/redwood/prebuilt/device-tree.dtb --firmware-dir fw-modem --node /soc/qcom,mss@4080000` сопоставила 28 сегментов штатной прошивки с областью `mpss@8b800000` (PAS ID 4). `MODEM=1 SYSTEM=1 ... userland/build.sh` теперь может положить эти локальные файлы в системный APFS после проверки. Это только подготовка образа: наличие прошивки в `/fw` не запускает MPSS. Исходник `hakios.nas.c` содержит клиент QMI NAS для заданного транспорта QRTR: он ищет службу, запрашивает регистрацию и силу сигнала, разбирает ответы и сбрасывает состояние при исчезновении службы. Уровень `bars` остаётся нулевым без подтверждённой регистрации. MPSS-транспорта в XNU пока нет, поэтому этот клиент ещё не получает сообщения с телефона и не подключён к статус-бару Darwin. Форматы NAS сверены с [описанием libqmi](https://github.com/linux-mobile-broadband/libqmi/blob/main/data/qmi-service-nas.json).## Проверка на телефоне, 20 октября 2026-На redwood через `fastboot boot` временно запущены xnuloader и образ iOS 16.5. Системный APFS загружен в ОЗУ; разделы телефона не прошивались. `launchd` запустил `SpringBoard`, и на дисплее открылся интерфейс «Настройки». Это подтверждает загрузку iOS и работу экрана, но не работу модема. В журнале `mg_test` показывает `telephony = true` и `cellular-data = false`; запросы `com.apple.commcenter.xpc` и `com.apple.basebandd.xpc` остаются без службы. Значение `telephony = true` — ответ MobileGestalt о возможностях устройства, а не регистрация в сети. Тест выполнен с готовым ядром из `prebuilt`, поэтому изменения QMI в исходниках XNU в этой загрузке **не проверялись**. Дальнейший аппаратный тест требует сборки ядра с MPSS/QRTR и интеграции с iOS.+На redwood через `fastboot boot` временно запущены xnuloader и образ Darwin userland 16.5. Системный APFS загружен в ОЗУ; разделы телефона не прошивались. `launchd` запустил `SpringBoard`, и на дисплее открылся интерфейс «Настройки». Это подтверждает загрузку Darwin и работу экрана, но не работу модема. В журнале `mg_test` показывает `telephony = true` и `cellular-data = false`; запросы `com.apple.commcenter.xpc` и `com.apple.basebandd.xpc` остаются без службы. Значение `telephony = true` — ответ MobileGestalt о возможностях устройства, а не регистрация в сети. Тест выполнен с готовым ядром из `prebuilt`, поэтому изменения QMI в исходниках XNU в этой загрузке **не проверялись**. Дальнейший аппаратный тест требует сборки ядра с MPSS/QRTR и интеграции с Darwin.## Что установлено по redwood-`devices/redwood/prebuilt/device-tree.dtb` содержит зарезервированную память `mpss@8b800000`, `qcom,smp2p-modem`, `qcom,glink/modem/qcom,modem_qrtr`, `qcom,ipa@1e00000` и `qcom,rmnet-ipa`. Это разные части тракта: запуск прошивки модема, сигнализация, управляющий QMI-канал и передача IP-пакетов. Дерево Android [redwood](https://github.com/Redwood-AOSP/android_device_xiaomi_redwood) включает `full_base_telephony.mk`; его `init.qcom.rc` запускает `vendor.qcrild` и `vendor.qcrild2`. [Ветка araxys с ядром/DTB](https://github.com/Redwood-AOSP/android_device_xiaomi_redwood-kernel/tree/araxys) пригодна как аппаратный справочник. Бинарники Android RIL нельзя просто запустить в iOS: им нужны Android binder, HAL, службы и ABI.+`devices/redwood/prebuilt/device-tree.dtb` содержит зарезервированную память `mpss@8b800000`, `qcom,smp2p-modem`, `qcom,glink/modem/qcom,modem_qrtr`, `qcom,ipa@1e00000` и `qcom,rmnet-ipa`. Это разные части тракта: запуск прошивки модема, сигнализация, управляющий QMI-канал и передача IP-пакетов. Дерево Android [redwood](https://github.com/Redwood-AOSP/android_device_xiaomi_redwood) включает `full_base_telephony.mk`; его `init.qcom.rc` запускает `vendor.qcrild` и `vendor.qcrild2`. [Ветка araxys с ядром/DTB](https://github.com/Redwood-AOSP/android_device_xiaomi_redwood-kernel/tree/araxys) пригодна как аппаратный справочник. Бинарники Android RIL нельзя просто запустить в Darwin: им нужны Android binder, HAL, службы и ABI.Проверка по USB 20 октября 2026 года: fastboot определил продукт `redwood` и разблокированный загрузчик; Android сообщил `ro.boot.hardware.sku=redwood`, `ro.soc.model=SM7325`. Под Android подсистема `modem` и прошивка `yupik_ipa_fws` были `ONLINE`, `vendor.qcrild`, `vendor.qcrild2`, `vendor.qrtr-ns` — `running`; присутствовали `rmnet_ipa0` и `rmnet_data0`–`rmnet_data5`. Состояние SIM: `ABSENT,LOADED` для двух слотов. Временная загрузка `xnuloader` через `fastboot boot` и его `selftest` прошли (`selftest-ok`); это проверка загрузчика, а не сотовой связи в XNU.@@ -78,7 +78,7 @@ XL_CMDLINE="debug=0x8 rd=md0 hv_wdt_pet=1 bootcpu=7 cpus=8 cpufreq=1 sb_delay=60`modem=1` в обычной загрузке делает всё то же на своём потоке и оставляет модем включённым,опрашивая NAS каждые две секунды; результат — в `sysctl kern.hakios.cellular_up`,`cellular_registered`, `cellular_bars`, `cellular_dbm`, `cellular_radio`. Палочки в-статус‑баре iOS из этого ещё не получаются: нужна либо часть CommCenter, либо подмена+статус‑баре Darwin из этого ещё не получаются: нужна либо часть CommCenter, либо подменаэлемента статус‑бара в `libhakios.sb.dylib` по этим sysctl (следующий шаг).## 23 октября 2026: буфер RMTFS и перезапуски телефона@@ -102,7 +102,7 @@ XL_CMDLINE="debug=0x8 rd=md0 hv_wdt_pet=1 bootcpu=7 cpus=8 cpufreq=1 sb_delay=60`modem_rmtfs_rw_off=1` (отказ в чтении), `modem_rmtfs_rw_fake=1` (запись есть, ответ «нет»),`modem_rmtfs_delay=S` (пауза перед первым чтением), `modem_share_off=1`, `modem_no_nav=1`.-Паника `copyio.c:89 Assertion failed: pan != 0` в пользовательских процессах iOS встречалась в+Паника `copyio.c:89 Assertion failed: pan != 0` в пользовательских процессах Darwin встречалась вдвух прогонах с модемом; её причина не найдена.## 23 октября 2026, вечер: модем читает файлы, выходит в ONLINE@@ -238,9 +238,9 @@ readiness`. Драйвер IPA модема при ініціалізації чSwitch Slot (0x46): логічний слот 1 → фізичний слот 2, потім повторні запити.- Прогони з `modem_step=11` тримають SpringBoard 600 с (телефон стоїть на логотипі Apple);тепер `tools/modem-cycle.sh` бере `XL_SB_DELAY` з оточення, і прогін 31 — повне завантаження- iOS з модемом у фоні (`modem=1`).+ Darwin з модемом у фоні (`modem=1`).-### Прогін 31 (09:12): повне завантаження iOS, перемикання слота, ПЕРШИЙ СИГНАЛ+### Прогін 31 (09:12): повне завантаження Darwin, перемикання слота, ПЕРШИЙ СИГНАЛ`XL_SB_DELAY=8` + `modem=1`: SpringBoard стартує одразу (телефон більше не стоїть на логотипіApple під час тестів), модем піднімається у фоні. Після UIM Switch Slot (логічний 1 → фізичний 2)@@ -249,7 +249,7 @@ UMTS** — радіо працює, модем бачить мережу; реєRegister = `UIM_UNINITIALIZED`: SIM ще ініціалізується після перемикання). Тепер крок 11 раз на10 с питає стан картки та NAS Get System Info (0x4d).-Статус-бар: у SpringBoard iOS 16.5 стільникові пункти заповнює `SBStatusBarStateAggregator`+Статус-бар: у SpringBoard Darwin userland 16.5 стільникові пункти заповнює `SBStatusBarStateAggregator`через `_updateSignalStrengthItem:withData:SIMInfo:barsGetter:barsSetter:` і `_setItem:enabled:`(селектори знайдені в кеші dyld). `inject_sb.c` тепер перехоплює цей метод: коли`kern.hakios.cellular_registered`, виставляє палички через barsSetter і вмикає пункт; раз на 3 с@@ -267,7 +267,7 @@ Register = `UIM_UNINITIALIZED`: SIM ще ініціалізується післactivate, слот 1 + AID USIM, потім повторне Initiate Network Register.- Прогони з самим модемом не вмикали решту заліза: GPU (`gpu=1`), DSP/батарея (`adsp=1`),вібро (`haptic=5`), Wi-Fi (`wifi=1`) — звідси «no GPU to draw with», `SOC=-1%`, без вібрації.- Прогін 33 — з усім разом. Тач працює, коли екран увімкнений (iOS гасить його через ~25 с+ Прогін 33 — з усім разом. Тач працює, коли екран увімкнений (Darwin гасить його через ~25 сбездіяльності; кнопка живлення будить).### Прогони 33–34: усе залізо разомdiff --git a/docs/ru/metal.md b/docs/ru/metal.mdindex 67e6aa0..d0a3be5 100644--- a/docs/ru/metal.md+++ b/docs/ru/metal.md@@ -1,6 +1,6 @@# Metal-Разбор: что в iOS 16.5 просит Metal, где проходит граница, которую пришлось бы реализовать, и+Разбор: что в Darwin userland 16.5 просит Metal, где проходит граница, которую пришлось бы реализовать, истоит ли её переходить. Всё, что ниже, проверено по извлечённой системе(`sysimage/rootfs`, кэш `sysimage/20F66__iPhone10,3_6/dyld_shared_cache_arm64`), по исходникам порта ипо журналам прогонов; адреса — невыровненные (unslid) адреса этого кэша.@@ -14,13 +14,13 @@сопротивляется** (обычный битовый код LLVM, 456 модулей системы из 456 читает готовый `llvm-dis`).Измерено в разделе 9, и вывод там: «игры» — твёрдое нет, «один системный шейдер на нашем GPU» —достижимо.-- **Половина потерь — «пока», а не «нельзя».** У CoreImage в iOS 16.5 есть полный задний конец на+- **Половина потерь — «пока», а не «нельзя».** У CoreImage в Darwin userland 16.5 есть полный задний конец наOpenGL ES, у движка CoreML — 127 процессорных ядер и ни одного металлического. Разбор — раздел 7.- **Первый шаг оказался уже сделанным** (раздел 2), поэтому сделан другой: `metal_test`(`userland/src/metal_test.m`), который наконец отвечает, что система про Metal думает, — и первымже запуском исправил два моих утверждения.-## 1. Как iOS находит Metal+## 1. Как Darwin находит MetalВся процедура — пять шагов, и ни один из них не спрашивает ни про возможности устройства, ни прочто-либо ещё, кроме реестра IOKit.@@ -56,8 +56,8 @@`MTLCreateSystemDefaultDevice` (`0x181a34b3c`) выдаёт одно устройство из этого списка под`dispatch_once` (сторож `0x1e1efe9b8`, блок `0x181a3442c`, массив `0x1e1efe9a0`). **Пустой список —ответ, данный один раз и сохранённый до конца процесса, молча**: ни строки в журнал, ни кода-ошибки, ни причины. В iOS 16.5 второго способа спросить нет: `MTLCopyAllDevices` объявлен-`API_UNAVAILABLE(ios)` и в двоичном файле отсутствует.+ошибки, ни причины. В Darwin userland 16.5 второго способа спросить нет: `MTLCopyAllDevices` объявлен+`API_UNAVAILABLE(darwin)` и в двоичном файле отсутствует.## 2. Что здесь есть вместо этого@@ -77,7 +77,7 @@ metal_test: IOAcceleratorES "sgx": MetalPluginName (none), MetalPluginClassNam> the properties that name its Metal and OpenGL ES drivers is passed over by both, which leaves> CoreAnimation with its software renderer, as before.-То есть **шаг, который напрашивается как «первый» — сказать iOS правду, чтобы она пошла работающей+То есть **шаг, который напрашивается как «первый» — сказать Darwin правду, чтобы она пошла работающейдорогой, — в порте уже сделан, и сделан именно так**: служба есть, чтобы CoreAnimation не ждалполминуты, и нарочно без двух свойств, чтобы и Metal, и OpenGL ES прошли мимо. Цепочка из раздела 1обрывается не на шаге 1, а на шаге 2.@@ -140,7 +140,7 @@ CoreAnimation спросил и получил отказ только по дв| `IOGPU` — обёртка над клиентом IOKit | 461 664 | 2 266 | 711 | 36 || `MTLCompiler` — передняя часть компилятора шейдеров | 983 544 | 2 971 | — | — || `AGXCompilerCore` — его задняя часть под AGX | 2 680 736 | 7 509 | — | — |-| `AppleMetalGLRenderer` — OpenGL ES **поверх** Metal, как это делает сама iOS | 258 256 | 1 092 | 2 | 1 |+| `AppleMetalGLRenderer` — OpenGL ES **поверх** Metal, как это делает сама Darwin | 258 256 | 1 092 | 2 | 1 |Для сравнения — чем порт заменяет графическую библиотеку сейчас: `userland/src/eagl.c` — 3 685строк, `src/eagl_slots.txt` — 409 записей таблицы, из которых помечено используемыми QuartzCore@@ -194,7 +194,7 @@ AGXA11FamilyDevice -> IOGPUMetalDevice (IOGPU.framework) -> _MTLDevice (Meta**(А) Поверхность Metal над Mesa.** Дописать на уже существующую службу `IOAcceleratorES` (раздел 2)два свойства, положить в образ `/System/Library/Extensions/HakiosMetal.bundle`-(место открыто: `userland/build.sh` собирает корень из файлов iOS по их настоящим путям и уже+(место открыто: `userland/build.sh` собирает корень из файлов Darwin по их настоящим путям и ужекладёт туда свои — например `/System/Library/Audio/Plug-Ins/HAL/HakiosAudio.driver`) и реализоватьграф объектов Metal на Mesa. Цена: ~53 класса и ~1 200 методов драйвера **плюс компиляторAIR→NIR**, которого не существует. В единицах этого проекта — не файл и не два, а ещё одна Mesa, и@@ -204,7 +204,7 @@ AIR→NIR**, которого не существует. В единицах э`_MTLDevice` приходится решать целиком, AIR остаётся на входе (то есть нужен AIR→GLSL), аединственное, что экономится, — задняя часть под Adreno, то есть именно та часть, которую Mesa итак даёт бесплатно. Заодно GLES2/3 не выражает вычислительные конвейеры, argument buffers и-значительную часть того, за чем Metal и зовут. Показательно, что сама iOS переводит в обратную+значительную часть того, за чем Metal и зовут. Показательно, что сама Darwin переводит в обратнуюсторону: `AppleMetalGLRenderer.bundle` — это GLES поверх Metal, один класс и 1 092 символа.Дешёвое направление — GL→Metal, а у порта уже есть то, что делает его ненужным: настоящий GLES.@@ -265,7 +265,7 @@ CoreAnimation — рендерер OpenGL ES, который порт уже ишаге всё обрывается;4. что получает программа: `MTLCreateSystemDefaultDevice()`, а при удаче — имя, `registryID` иподдерживаемые семейства;-5. что iOS всё равно рассказывает про графику (раздел 5): `GraphicsFeatureSetClass`,+5. что Darwin всё равно рассказывает про графику (раздел 5): `GraphicsFeatureSetClass`,`GraphicsFeatureSetFallbacks` и рядом — чтобы было видно, что ответ `APPLE4` не зависит ни отчего;6. умеет ли работать фреймворк, у которого путь без Metal есть: CoreImage прогоняет `CIColorInvert` по четырём@@ -286,7 +286,7 @@ called. We cannot safely call it or ignore it in the fork() child process. Crashбыло больше одного потока, а у `metal_test` их больше (довольно слинковаться с CoreImage иOpenGLES). Прогон, сделанный так, не говорит о CoreImage ничего. Теперь `metal_test` запускает себязаново (`posix_spawn` с именем вопроса в аргументе: `ci-eagl`, `ci-default`, …), потому что `exec`-начинает среду с нуля. Урок общий: **в этом проекте нельзя проверять что-либо из iOS в потомке+начинает среду с нуля. Урок общий: **в этом проекте нельзя проверять что-либо из Darwin в потомке`fork` — только в новом процессе.**Проверка бандлов идёт **последней** нарочно: взять принципиальный класс — значит загрузить код@@ -305,7 +305,7 @@ OpenGLES). Прогон, сделанный так, не говорит о CoreI```shuserland/build.sh # obj/metal_test -> root/bin/metal_test-RC_JOBS=rc.jobs.metal qemu/run-ios.sh 240 # в QEMU+RC_JOBS=rc.jobs.metal qemu/run-darwin.sh 240 # в QEMUXL_CMDLINE="... gpu=1" RC_JOBS=rc.jobs.metal ./xl run # на телефоне```@@ -324,7 +324,7 @@ metal_test: what the registry has that is a GPUmetal_test: nonemetal_test: the device a program getsmetal_test: MTLCreateSystemDefaultDevice() = nil (and says nothing about why)-metal_test: what iOS publishes about graphics (artwork, not rendering)+metal_test: what Darwin publishes about graphics (artwork, not rendering)metal_test: GraphicsFeatureSetClass = (none)metal_test: GraphicsFeatureSetFallbacks = (none)metal_test: ArtworkDeviceSubType = (none)@@ -382,7 +382,7 @@ metal_test: AGXMetalA11.bundle: executable AGXMetalA11, principal class AGXPri### CoreImage — не Metal-only; у него **два** полных задних конца-Самая важная находка всего разбора. В iOS 16.5 CoreImage несёт две параллельных реализации:+Самая важная находка всего разбора. В Darwin userland 16.5 CoreImage несёт две параллельных реализации:| OpenGL ES | Metal || --- | --- |@@ -431,7 +431,7 @@ OpenGL ES, а не на Metal.** Он идёт прямо в `internalContextWitработу, когда никакого контекста OpenGL ES ему не дали**: по этой дороге `EAGLContext` — `nil`.И `kCIContextUseSoftwareRenderer: @YES` идёт **тем же путём, с тем же стеком и той же смертью**:-на iOS 16.5 этот ключ ничего не значит, программного растеризатора у CoreImage нет.+на Darwin userland 16.5 этот ключ ничего не значит, программного растеризатора у CoreImage нет.Значит вопрос «достижимо ли это» получает хороший ответ: дорога, которой CoreImage и так хочетидти, — ровно та, что у порта есть. Не хватает ей того единственного, чего она просит: контекстаdiff --git a/docs/ru/notes.md b/docs/ru/notes.mdindex caff9ae..4ed7248 100644--- a/docs/ru/notes.md+++ b/docs/ru/notes.md@@ -3,8 +3,8 @@> Это прежний README целиком — история работы, измерения и устройство каждой части. Краткое введение теперь в [README.md](../../README.md).-**HakiOS** — iOS 16.5 на POCO X5 Pro 5G (redwood). Открытое ядро Apple XNU (xnu-8796.121.2 — ядро iOS 16.5), свой загрузчик и свои замены закрытых драйверов,-под которыми работает **немодифицированный userland iOS 16.5** от iPhone X: launchd → backboardd → SpringBoard →+**HakiOS** — Darwin userland 16.5 на POCO X5 Pro 5G (redwood). Открытое ядро Apple XNU (xnu-8796.121.2 — ядро Darwin userland 16.5), свой загрузчик и свои замены закрытых драйверов,+под которыми работает **немодифицированный userland Darwin userland 16.5** от iPhone X: launchd → backboardd → SpringBoard →приложения. Работает в двух местах:- **POCO X5 Pro 5G (redwood, Snapdragon 778G)** — ничего не прошивается: UEFI грузится через `fastboot boot`,@@ -20,7 +20,7 @@| Работает | Не работает ||---|---|-| Экран блокировки, разблокировка свайпом, домашний экран с полным набором значков (две страницы), стандартные обои iOS 16 | Сотовая сеть, Bluetooth |+| Экран блокировки, разблокировка свайпом, домашний экран с полным набором значков (две страницы), стандартные обои Darwin userland 16 | Сотовая сеть, Bluetooth || Системные жесты: свайп снизу — «домой» и переключатель приложений, свайп от левого края — «назад», Пункт управления | Без `gpu=1` (программный рендер; в QEMU всегда) часы экрана блокировки просто белые, без «вибрации» под цвет обоев, и верх обоев под ними не затемнён || Запуск приложений: Настройки (вглубь), Часы, Календарь, Фото, Заметки и др.; расширения приложений (виджеты «Погода» и «Календарь» на домашнем экране рисуют своё содержимое — на телефоне; в QEMU им не хватает скорости) | Metal у приложений (они рисуют через него сами; WebGL, видоискатель «Камеры», эффекты снимка). Но уже не «не предполагается»: наш передний конец читает шейдеры, которые Apple скомпилировала для Metal, и исполняет их на Adreno — 54 из 456 прошли на GPU телефона: 7 отрисовкой (шесть текстурных вернули точный тексель) и все 47 вычислительных ядер корпуса диспатчем. 71 операция `air.*` сходится с LLVM на всех 45 697 случаях, 61 из них проверена на самом Adreno; слово состояния сэмплера не разобрано, то есть фильтрация и адресация самой Apple не проверены. См. `docs/air.md` || Сенсорный экран телефона (Goodix GT9916), мультитач, пробуждение касанием | Без `cpus=N` работает одно ядро процессора |@@ -29,8 +29,8 @@| Большое ядро на 2,4 ГГц, загрузка до экрана блокировки ~20 с (телефон) | || Safari: открывает страницы (на телефоне — через его Wi-Fi), его службы — из криптекса App, как на iPhone (см. «Только APFS, как на iPhone») | || Снимки экрана и запись экрана с телефона | |-| Сохранение данных: то, что iOS записала в `/private/var`, переживает перезагрузку телефона — архивом в разделе `darwin` (`var_store=1 ufs_write=1`, см. «Том данных между загрузками») | |-| Звук iOS и в QEMU (см. ниже; «Сейчас играет» — с оговоркой), и на самом телефоне: динамики играют то, что играет iOS (`adsp=1 sound=4`, по умолчанию на 30 дБ тише уровня Android), приложения записывают с его главного микрофона (`adsp=1 mic=4`: «Диктофон» пишет и рисует волну); громкость кнопок и Пункта управления — тоже | Из микрофонов поднят только нижний. Звук внутри сеанса съёмки — отдельный путь, и его нет (см. строку про камеру) |+| Сохранение данных: то, что Darwin записала в `/private/var`, переживает перезагрузку телефона — архивом в разделе `darwin` (`var_store=1 ufs_write=1`, см. «Том данных между загрузками») | |+| Звук Darwin и в QEMU (см. ниже; «Сейчас играет» — с оговоркой), и на самом телефоне: динамики играют то, что играет Darwin (`adsp=1 sound=4`, по умолчанию на 30 дБ тише уровня Android), приложения записывают с его главного микрофона (`adsp=1 mic=4`: «Диктофон» пишет и рисует волну); громкость кнопок и Пункта управления — тоже | Из микрофонов поднят только нижний. Звук внутри сеанса съёмки — отдельный путь, и его нет (см. строку про камеру) || Камера телефона в самой Camera.app (`cam=5`, см. `cam=N` в «На телефоне»): задняя и фронтальная, живой предпросмотр, цвета по тюнингу самих камер, автофокус и фокус касанием, зум, снимки в HEIC | Видео и Live Photo: звук сеанса съёмки идёт не через микрофон ядра, а через посреднический плагин аудио-HAL, которого на этом телефоне нет — узел звука отвечает `'nope'` (`inject_media.c`) || Sileo и префикс Procursus — dpkg и apt, установка пакетов из сети (`tools/mk-jb.sh`, см. «Sileo») | App Store **рисует свой интерфейс** (20 октября, ветка `services`): карточка «Welcome to the App Store», выбор про персонализированную рекламу и сам магазин с панелью вкладок Today, Games, Apps, Arcade, Search. Это `JetEngine`, рисующий тот документ, приход которого мы видели целиком, — без Apple ID, SIM и активации, по Wi-Fi телефона. **Содержимое вкладки Today не приходит**: магазин пишет в теле «Cannot Connect to App Store» с кнопкой Retry (). И это **не сеть** — за содержимым запрос не уходит вовсе: таблица задач показывает те же пять запросов (мешок трижды, `jetpack` дважды, все 200), а среди всех ошибок, созданных в приложении за сеанс, **нет ни одной из `NSURLErrorDomain`**. Ничего сетевого не падало, потому что ничего сетевого и не затевалось. Зато 24 раза создаётся `NSCocoaErrorDomain 4099` — это `NSXPCConnectionInterrupted`, а **не** `4097` (`Invalid`): собеседника не «не нашли», он умер посреди разговора, поэтому и строк `failed lookup` нет ни одной. След сошёлся: за тот же прогон умирает ровно одна служба — **`com.apple.fairplayd.H2`, двадцать шесть раз**, каждый раз `exit(0)` и «Service only ran for 0 seconds»; `appstored` при этом жив весь прогон (его собственные отчёты идут 315, 330, 345 … 510 с, часы ни разу не сбрасываются). Цепь целиком: запрос за содержимым требует подписи FairPlay → служба подписи умирает мгновенно → соединение рвётся → запрос не изготавливается → «Cannot Connect to App Store», ни одного обращения в сеть. **Это и есть то, что надо починить, чтобы «Сегодня» загрузилась**, и задача ограниченная: удержать `fairplayd.H2` живым. Разбор самого демона статикой сузил вопрос и снял первого подозреваемого: в `usr/sbin/fairplayd.H2` **не импортируются** ни `__mac_syscall`, ни `sysctl`, ни `exit`, а в его коде нет ни одной инструкции `svc` — значит и те 12 запросов к AMFI, и 33 `sysctl` из трассы принадлежат dyld и libSystem, а не его решению; отказ же MAC от ядра убивал бы процесс, а не давал чистый ноль. Уходит он **возвратом из `main`** (арифметика обфускатора даёт ровно 0), рано — до IOKit и до регистрации своей службы, а 26 смертей за прогон это `KeepAlive` в его `plist`, то есть одна и та же смерть в цикле. Точную ветку статикой не достать: бинарь защищён обфускатором FairPlay со сглаженным потоком управления и зашифрованной таблицей переходов. Зато он зовёт `MGCopyAnswer` и `SecTaskCopyValueForEntitlement` **через границу образов**, то есть подмена dyld их видит — это и есть следующий прибор. Прежняя запись здесь говорила, что магазин остаётся на индикаторе загрузки и за содержимым не ходит ни разу: и то и другое было верно по факту и неверно по смыслу — приложение стояло на первом экране приветствия и ждало нажатия, а под «LOADING» была карточка, которую никто не нажал. После «Continue» и «Turn Off» запросов становится пять вместо четырёх. Мешок настроек из подозреваемых выбыл: из 48 запрошенных ключей 31 отвечен, 17 нет, и ни один из семнадцати не про содержимое (метрики, TestFlight, пороги онбординга, таймауты)|| | Вход в учётную запись Apple и iCloud: упирается не в сеть и не в пароль, а в **отсутствие Secure Enclave**. `mobileactivationd` не может создать ключ устройства (`0xe00002c7`, `kIOReturnUnsupported` — наша заглушка `MiniAppleKeyStore` умеет keybag и не умеет UIK), поэтому нет записи активации и устройственного сертификата, поэтому `apsd` не получает push-токен (`copyTokenForDomain push.apple.com (null)`), поэтому `akd` не делает check-in. Каждое звено измерено в журналах. При этом сеть и мешок GrandSlam работают: `akd` ходит на `gsa.apple.com` уже сейчас, без учётной записи. Вторая опора, которой нет: личность устройства **выдумана загрузчиком** — серийный номер `RDW00POCOX5P`, MLB и ECID тоже наши. MobileGestalt у нас настоящая, из образа, и отвечает по дереву устройств, которое строит загрузчик: ключи семейства UDID она соберёт и выдаст — складно и устойчиво, но из выдуманного, — а `HasSEP`, `secureElementID`, `EffectiveProductionStatusSEP` и прочее вернут nil, потому что таких узлов мы не публикуем вовсе |@@ -42,7 +42,7 @@## Быстрый старт: QEMU, без сборки ядраВ `prebuilt/` лежат собранные из этого же репозитория ядро, загрузчик и наши программы, так что нужен только-образ системы. **Файлов iOS в репозитории нет** — IPSW iOS 16.5 для iPhone X вы берёте сами,+образ системы. **Файлов Darwin в репозитории нет** — IPSW Darwin userland 16.5 для iPhone X вы берёте сами,скрипт только распаковывает из него нужное.Нужно: Linux x86-64, ~12 ГБ свободного места (готовое занимает ~8 ГБ), от 4 ГБ свободной памяти. Пакеты (Arch):@@ -59,7 +59,7 @@ cd darwin-redwoodsysimage/unpack.sh ~/iPhone10,3,iPhone10,6_16.5_20F66_Restore.ipsw # ваш IPSW: распаковывает нужноеREST=1 userland/build.sh # собирает образы APFS: userland/root.apfs и userland/system.apfs (2,5 ГБ)mkdir -p logs-qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 минут+qemu/run-darwin.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 минут```Через 2–3 минуты в окне появится экран блокировки.@@ -67,7 +67,7 @@ qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 ми**Сколько это занимает.** Измерено 20 октября на этой машине (Linux x86-64, 12 потоков, NVMe), проходомпо этим самым командам из чистого клона: `sysimage/unpack.sh` — 1 мин 45 с(тогда скрипт ещё сам качал образы; теперь IPSW вы кладёте сами, и остаётся только распаковка); `REST=1 userland/build.sh` — 1 мин 52 с; QEMU до-экрана блокировки — ещё 2–3 минуты. То есть около восьми минут от пустого каталога до iOS, если канал+экрана блокировки — ещё 2–3 минуты. То есть около восьми минут от пустого каталога до Darwin, если каналотдаёт порядка 25 МБ/с; сборка ядра и загрузчика в это не входит и не нужна — они в `prebuilt/`.- **Мышь с зажатой левой кнопкой — палец.** Разблокировка и выход из приложения — свайп вверх от самого@@ -76,9 +76,9 @@ qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 ми- То же из скрипта (без окна, `-display gtk` можно не указывать):`qemu/touch.py swipe 0.5 0.985 0.5 0.3 250`, `qemu/touch.py tap 0.615 0.71`, `qemu/touch.py key home`(координаты — доли экрана), снимок экрана — `qemu/screendump.sh shot.png`.-- Первый аргумент `run-ios.sh` — длительность сеанса в секундах; по её истечении ядро возвращается в загрузчик+- Первый аргумент `run-darwin.sh` — длительность сеанса в секундах; по её истечении ядро возвращается в загрузчики QEMU завершается. Журнал ядра и демонов идёт в stdout.-- Несколько ядер процессора: `QEMU_SMP=4 CMDLINE="cpus=4" qemu/run-ios.sh 1200 …` (`QEMU_SMP` — сколько ядер у+- Несколько ядер процессора: `QEMU_SMP=4 CMDLINE="cpus=4" qemu/run-darwin.sh 1200 …` (`QEMU_SMP` — сколько ядер умашины, `cpus=` — сколько из них берёт ядро системы; без `cpus=` оно работает на одном). До экрана блокировкитогда полторы минуты вместо двух с половиной, и всё заметно отзывчивее. Программа `cpu_test` (из`userland/rc.jobs`) пишет в журнал число процессоров и, через четыре минуты, сколько из них на деле работало@@ -88,16 +88,16 @@ qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 ми### Звук-Звуком в iOS заведует `mediaserverd`; в него встаёт наше устройство вывода (`HakiosAudio.driver`), которое iOS+Звуком в Darwin заведует `mediaserverd`; в него встаёт наше устройство вывода (`HakiosAudio.driver`), которое Darwinпринимает за собственный динамик iPhone, и то, что она играет, приходит в ядро (`/dev/hakios-audio`):```shREST=1 userland/build.sh-AUDIO=pipewire qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # или AUDIO=pa, alsa, sdl; AUDIO=файл.wav — в файл+AUDIO=pipewire qemu/run-darwin.sh 1200 -display gtk > logs/qemu.log # или AUDIO=pa, alsa, sdl; AUDIO=файл.wav — в файл```Для вывода на звуковую карту компьютера QEMU нужен свой модуль (в Arch — пакет `qemu-audio-pipewire`, `qemu-audio-pa`-и т. п.); без `AUDIO` звук играется «в никуда», но внутри iOS всё происходит так же. Проверено в QEMU записью:+и т. п.); без `AUDIO` звук играется «в никуда», но внутри Darwin всё происходит так же. Проверено в QEMU записью:тон из своей программы через очередь звука и системные звуки (блокировка, сигнал) доходят до ядра; громкостьдействует (кнопки и ползунок в Пункте управления меняют уровень, индикатор громкости появляется). Под эмуляциейцепочка обработки звука iPhone не успевает за реальным временем, и запись идёт с пропусками. Модуль «Сейчас играет»@@ -107,15 +107,15 @@ AUDIO=pipewire qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # или AUD(`userland/src/sound_test.c`); когда звук смолкает, ядро пишет в журнал строку`hakios-audio: N s written at R frames a second, M s of it sound, peak P% of full scale`.-На телефоне с `adsp=1 sound=4` то, что играет iOS, звучит из обоих динамиков: через звуковой процессор (порт TDM,+На телефоне с `adsp=1 sound=4` то, что играет Darwin, звучит из обоих динамиков: через звуковой процессор (порт TDM,поток, путь к порту) и два усилителя Awinic, которые включаются, только пока есть звук (параметр `sound=N` ниже;-`RC_JOBS=rc.jobs.speakers` проигрывает тон, звук блокировки, щелчки клавиатуры и фанфары). То, что iOS играет,+`RC_JOBS=rc.jobs.speakers` проигрывает тон, звук блокировки, щелчки клавиатуры и фанфары). То, что Darwin играет,можно и забрать: параметр ядра `rec_sound=N` сохраняет первые N секунд звука в памяти, послесеанса `./xl sound out.wav` достаёт их (в QEMU — `pmemsave` по адресу из строки `hakios-audio: recording … at 0x…`,затем `tools/sound.py`); с `rec_sound_fed=1` — то, что ушло к усилителям. На телефоне звук проверен на слух.Защиты динамиков, которая у Android работает в звуковом процессоре (алгоритм Awinic с калибровкой), здесь нет;вместо неё отсчёты по пути к усилителям проходят «сторож» ядра (`drivers/audio/hakios.guard.c`): сначала усиление-`sound_gain` (по умолчанию и самое большее 12 дБ: обработка самой iOS для динамика iPhone X держит даже полный тон+`sound_gain` (по умолчанию и самое большее 12 дБ: обработка самой Darwin для динамика iPhone X держит даже полный тонна максимуме громкости на 12,6–14,3 дБ ниже полной шкалы), затем фильтр верхних частот 200 Гц, три средних мощностина динамике — за 0,2, 3 и 60 с, пределы на 3, 6 и 9 дБ ниже мощности синуса полной шкалы на уровне Android (громкостьопускается так, чтобы ни одно не вышло за свой; средние падают и при выключенных усилителях, как динамик остывает) — и@@ -123,8 +123,8 @@ AUDIO=pipewire qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # или AUDнапряжение батареи, как их видят сами усилители, и по таблице «монитора» драйвера Android из той же конфигурациигромкость снижается на холоде и при разряженной батарее. Проверка на телефоне: `sound_below=160` (−20 дБ) — сторож работает, у усилителей ни одной ошибки; −10 дБ иуровень Android — ещё впереди. По умолчанию, пока громче на слух не проверено, `sound_below=240` (−30 дБ).-`RC_JOBS=rc.jobs.loud` — самое тяжёлое: тон полной шкалы 60 с прямо в `/dev/hakios-audio` мимо обработки iOS, потом-тон через iOS на максимуме громкости; `sound_guard_as=0` вместе с `sound_below=720` показывает в журнале и записи,+`RC_JOBS=rc.jobs.loud` — самое тяжёлое: тон полной шкалы 60 с прямо в `/dev/hakios-audio` мимо обработки Darwin, потом+тон через Darwin на максимуме громкости; `sound_guard_as=0` вместе с `sound_below=720` показывает в журнале и записи,что сторож делает на уровне Android, без единого звука. `tools/guard_test.c` — сторож на этой машине.Основной микрофон телефона (`adsp=1 mic=3`, пока только в ядре): аналоговый микрофон на ADC1 кодека WCD938x,@@ -144,9 +144,9 @@ codec DMA TX_CDC_DMA_TX_3 и звуковой процессор в поток,- Память гостя — 7 ГБ (ядру достаётся то же окно 4,2 ГБ, что и на телефоне), отображённые из разрежённого файла`qemu/ram.img` (образ системы лежит в нём по нужному смещению). На btrfs/xfs это reflink и места не занимает,на ext4 образ копируется (ещё 2,5 ГБ). Один запущенный QEMU занимает 2,5–3 ГБ памяти компьютера.-- **Сеть (опытно, только в QEMU).** `QEMU_NET=1 qemu/run-ios.sh …` добавляет машине сетевую карту virtio, за+- **Сеть (опытно, только в QEMU).** `QEMU_NET=1 qemu/run-darwin.sh …` добавляет машине сетевую карту virtio, закоторой стоит «пользовательская» сеть самого QEMU (DHCP, DNS и выход в сеть компьютера, без прав root); ядро- делает из неё интерфейс `en0`. Сам по себе интерфейс iOS не настраивает: образ, собранный с+ делает из неё интерфейс `en0`. Сам по себе интерфейс Darwin не настраивает: образ, собранный с`RC_JOBS=rc.jobs.net`, при загрузке просит об этом штатный configd (`userland/src/net_test.m`), после чего усистемы есть адрес, работают DNS (через mDNSResponder) и HTTPS (CFNetwork). Штатные службы тут же начинаютходить на серверы Apple (в первые минуты около 30 МБ данных Карт), а приложения Apple — Погода, App Store,@@ -177,7 +177,7 @@ codec DMA TX_CDC_DMA_TX_3 и звуковой процессор в поток,преобразование в ядре (`iokit/Kernel/MiniAppleKeyStore.cpp`), и всё записанное лежит в `/private/var`, то есть впамяти; без `var_store=1` оно пропадает при следующем старте (см. «Том данных между загрузками»). Проверка: `/redwood/bin/keychain_test` (подписывается `ldid`с группой доступа к связке; без `ldid` связка такой программе отказывает).-- **Wi-Fi телефона (опытно): `wifi=1`.** Радио телефона подключается к одной сети WPA2 с паролем, и iOS выходит+- **Wi-Fi телефона (опытно): `wifi=1`.** Радио телефона подключается к одной сети WPA2 с паролем, и Darwin выходитчерез него в интернет: адрес по DHCP, DNS, HTTPS. Нужны прошивка радио в `fw-wifi/` (см. `wifi_step=N` втаблице параметров ядра), адрес радио одной строкой в `fw-wifi/mac` и файл `fw-wifi/network` — имя сети первойстрокой, пароль второй (оба файла в git не попадают; `userland/build.sh` кладёт второй в малый образ, на@@ -201,14 +201,14 @@ codec DMA TX_CDC_DMA_TX_3 и звуковой процессор в поток,обычным и полужирным начертаниями упрощённого, традиционного и гонконгского письма (26 МБ). Проверка —`RC_JOBS=rc.jobs.fonts` (`font_test`: к какому шрифту система идёт за эмодзи, китайским, японским и корейским исколько точек он рисует, сколько из них цветных; с `wifi=1` — китайская Википедия и страница эмодзи в Safari).- Настройки: в образе работает и wifid, служба Wi-Fi самой iOS, а ядро отвечает на её запросы+ Настройки: в образе работает и wifid, служба Wi-Fi самой Darwin, а ядро отвечает на её запросы(`drivers/wifi/hakios.apple80211.c`). Раньше его добавлял только `WIFID=1`; теперь он в образе по умолчанию, потомучто там, где радио нет вовсе, он ничего не стоит: в QEMU wifid поднимается, сам с собой разговаривает о кодахстран и сидит — 114 запущенных процессов против 119 без него, ни одной аварии, ни одного перезапуска, — а навопросы, которые система всё равно задаёт, отвечает: `com.apple.wifi.manager` (это имя wifid регистрирует сам,в задании его нет) упал с 30 ненайденных обращений за сеанс до 3, `com.apple.private.corewifi-xpc` — с одногодо нуля, а всего ненайденных обращений в сеансе стало 305 вместо 331. Оставить его за бортом — `WIFID=0`.- (Считать по журналу запуска QEMU надо, убрав повторы: `qemu/run-ios.sh` выводит журнал launchd дважды.)+ (Считать по журналу запуска QEMU надо, убрав повторы: `qemu/run-darwin.sh` выводит журнал launchd дважды.)С радио (`wifi=1`) при работающем wifid в строкесостояния есть значок Wi-Fi, в Настройках Wi-Fi включён, подключённая сеть названа, под ней список сетей,которые слышит радио. Ядро отвечает и на просьбу подключиться, которую wifid шлёт, когда в Настройках выбрали@@ -217,16 +217,16 @@ codec DMA TX_CDC_DMA_TX_3 и звуковой процессор в поток,Выключатель Wi-Fi в Настройках выключает радио и включает его снова, и сеть из файла подключается опять.У подключённой сети стоит галочка — и когда сеть подключило само ядро (при старте, после выключателя, посленеверного пароля). Подключение из Настроек пальцем проверено на телефоне: сеть выбрана, пароль набран на- экранной клавиатуре — галочка; неверный пароль — штатное сообщение iOS о неверном пароле. Чтобы радио при старте+ экранной клавиатуре — галочка; неверный пароль — штатное сообщение Darwin о неверном пароле. Чтобы радио при стартеждало выбора в Настройках, а не подключало сеть из файла, ядру дают `wifi_file=0`. С `WIFID=0`Wi-Fi в Настройках по-прежнему «Выкл.». Скорость: 20 МБ по HTTPS за 2–3 секунды (55–90 Мбит/с; канал шириной80 МГц, если точка доступа его даёт, прерывания радио и блочные подтверждения — всё это `wifi=1` включает само,а `wifi_irq=0`, `wifi_wide=0`, `wifi_ba=0` выключают по одному). Чего нет ещё: WPA3, открытых сетей, экономииэнергии.-- Несколько QEMU сразу: `QEMU_INSTANCE=1 qemu/run-ios.sh …` (у каждого номера свои порты; `touch.py`,+- Несколько QEMU сразу: `QEMU_INSTANCE=1 qemu/run-darwin.sh …` (у каждого номера свои порты; `touch.py`,`screendump.sh`, `stop.sh` понимают ту же переменную). `qemu/stop.sh` завершает QEMU досрочно.- Прошивка UEFI для aarch64 ищется там, куда её кладёт Arch. В Debian/Ubuntu (пакет `qemu-efi-aarch64`):- `QEMU_EFI=/usr/share/AAVMF/AAVMF_CODE.fd QEMU_VARS=/usr/share/AAVMF/AAVMF_VARS.fd qemu/run-ios.sh …`+ `QEMU_EFI=/usr/share/AAVMF/AAVMF_CODE.fd QEMU_VARS=/usr/share/AAVMF/AAVMF_VARS.fd qemu/run-darwin.sh …`(проверялось только на Arch).- QEMU без KVM эмулирует ARM программно: всё заметно медленнее, чем на телефоне.@@ -254,7 +254,7 @@ adb pull /vendor/firmware/aw8697_haptic.bin fw-haptic/```sh./xl enter # Android → fastboot → наш загрузчик в ОЗУ (fastboot boot), он поднимает свой USB-канал./xl ramdisk # залить образ системы в ОЗУ телефона (2,5 ГБ, ~80 с) — один раз на сеанс загрузчика-XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run # 15 минут iOS+XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run # 15 минут Darwin./xl screenshot shot.png # что осталось на экране после возврата./xl reboot # обратно в Android```@@ -262,18 +262,18 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #**Резидентный образ живёт в ОЗУ телефона между сеансами — и между сессиями.** `./xl ramdisk` заливает егоодин раз, и дальше он остаётся там, пока телефон не сброшен, сколько бы `./xl run` ни прошло и кто бы ихни запускал. Поэтому **перед своим прогоном заливайте свой образ**, даже если «ничего не меняли»: в памяти-может лежать чужой и совсем другого вида. Признак — iOS не стартует вовсе и в журнале-`/sbin/launchd.ios: No such file or directory`; это означает именно несовпадение резидентного образа с+может лежать чужой и совсем другого вида. Признак — Darwin не стартует вовсе и в журнале+`/sbin/launchd.darwin: No such file or directory`; это означает именно несовпадение резидентного образа скомандной строкой (например, 4 МБ флеш-рутового `flashboot.apfs` там, где `root_apfs=` не задан иожидался `system.apfs` на 2,4 ГБ), а не плохой образ — заливать в ответ на это другой образ наугад значитлечить симптом. Ни записка на `$XDG_RUNTIME_DIR/darwin-hakios-phone.note`, ни `flock` на `.run` этогосостояния не описывают: они отвечают «кто держит телефон» и «идёт ли прогон сейчас», а резидентный образпереживает и то и другое.-Образ системы — контейнер APFS, сжатый zlib так же, как Apple сжимает корень iOS (5,4 ГБ файлов в 2,5 ГБ); его-и прочие образы ядро читает тем же драйвером APFS, что и том iOS на флеше (см. «Только APFS, как на iPhone»).+Образ системы — контейнер APFS, сжатый zlib так же, как Apple сжимает корень Darwin (5,4 ГБ файлов в 2,5 ГБ); его+и прочие образы ядро читает тем же драйвером APFS, что и том Darwin на флеше (см. «Только APFS, как на iPhone»).Для графики телефона — образ с `GL=1` и `gpu=1` в командной строке, для звука и батареи — `adsp=1` (не-`battery=1`: с ним ядро не спрашивает батарею у звукового процессора, и iOS показывает не тот заряд).+`battery=1`: с ним ядро не спрашивает батарею у звукового процессора, и Darwin показывает не тот заряд).`./xl run` ждёт конца сеанса и кладёт журнал в `logs/`; запускать можно сколько угодно раз, образ системы в ОЗУостаётся. `./xl` без аргументов печатает все команды. Пока идёт сеанс, из другого терминала работают@@ -283,7 +283,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #**Журнал загрузчика хранит первые 256 КБ и последний мегабайт, а середину выбрасывает**, сообщая об этомодной строкой («the log between the first 256 KB and the last 1 MB was dropped»). Это важно для всякого-сеанса, который что-то печатает сам: с `REST=1` iOS насыпает больше мегабайта `os_log` за две минуты, и+сеанса, который что-то печатает сам: с `REST=1` Darwin насыпает больше мегабайта `os_log` за две минуты, иесли ваш вывод был в начале, он уедет ровно в выброшенную середину — из 225 запущенных программ в журналенашлись первые 27. `XL_FOLLOW` от этого не спасает: к моменту, когда он забирает журнал, середина ужевыброшена. И фильтр не спасает — он убирает строки, которых уже нет.@@ -315,9 +315,9 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #**Два подвоха дают один и тот же симптом «моих строк нет в журнале», и различать их надо по признаку, ане по догадке:**-- в журнале есть `/sbin/launchd.ios: No such file or directory` — iOS не стартовала вовсе, резидентный+- в журнале есть `/sbin/launchd.darwin: No such file or directory` — Darwin не стартовала вовсе, резидентныйобраз не тот (см. выше про `./xl ramdisk`). Задание не выполнялось;-- в журнале есть маркер выброса, а размер равен пределу — iOS стартовала, задание отработало, вывод не+- в журнале есть маркер выброса, а размер равен пределу — Darwin стартовала, задание отработало, вывод недоехал. Повторять с меньшим окном и `QUIET=1`, а не заливать наугад другой образ.Управление как на iPhone X: свайп вверх от нижнего края — разблокировка и «домой», погасший экран будится@@ -352,8 +352,8 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #| `cpus=N` | использовать N ядер процессора: то, на котором ядро запущено, и ещё N−1 ближайших к нему по номеру (после 7 — 6, 5, 4, потом малые 3, 2, 1); их запускает само ядро через PSCI. `cpumask=M` — выбрать по позиции в этом порядке (бит 0 — загрузочное). Без параметра — одно ядро. На телефоне ядру достаётся не больше семи: нулевое занято загрузчиком, который наблюдает за сеансом. Малые ядра (Cortex-A55, в 2,5 раза медленнее больших) загрузчик помечает в дереве устройств (`small-core`), и планировщик берёт их, только когда все большие заняты: каждое малое — пара своему большому, как второй поток ядра с гиперпотоками у XNU, но без его ограничений, а поток с малого ядра переводится на большое, как только то освободилось. `small_cores=0` — все ядра одинаковы, как было раньше (тогда `cpus=8` заметно медленнее `cpus=4`); `small_cores=1` — пары ровно как у гиперпотоков XNU. Малые ядра запускаются через 28 с после остальных, когда экран блокировки уже готов (`small_cores_after=S`, 0 — сразу). Нужен загрузчик от 15 октября (`./xl reload`): со старым малые ядра не помечены. Лучший вариант — `cpus=8` || `cpuload=MS` | каждые MS миллисекунд строка `tl: u` о том, насколько было занято каждое ядро процессора (в процентах; `tools/frames.py` показывает это по жестам) || `cpufreq=1` | поднять частоту до максимума (иначе 300 МГц) всем группам ядер, в которых есть наши |-| `rec_secs=N` | записывать экран N секунд (`rec_start=S`, `rec_mb=M`, не больше 640); потом `./xl recording out.mp4`. `rec_ring=1` — по кругу: когда память кончилась, запись идёт поверх самых старых кадров, и к концу сеанса в ней последнее (для того, что случается раз за долгий сеанс: сеанс кончают сразу после — пятью пальцами); `rec_step=N` — каждый N-й пиксель вместо третьего (4 — в 1,8 раза больше кадров). Память на запись отнимается у системы на весь сеанс: с `rec_mb=640` в долгом сеансе iOS убивала процессы ради памяти, вплоть до SpringBoard (респринги), с 256 — нет. `XL_REC_KEEP=1 ./xl recording` оставляет саму запись в `logs/recording.raw`; `tools/recording.py logs/recording.raw out.mp4 --frames DIR` раскладывает её на кадры с именами по времени ядра в миллисекундах — тому же, что в строках `glframes=1` |-| `rec_sound=N` | сохранить первые N секунд звука, который играет iOS (тишина между звуками места не занимает); потом `./xl sound out.wav`. С `rec_sound_fed=1` — то, что пропустил к усилителям сторож динамиков, с `rec_sound_mic=1` — отсчёты микрофона (`mic=3`) |+| `rec_secs=N` | записывать экран N секунд (`rec_start=S`, `rec_mb=M`, не больше 640); потом `./xl recording out.mp4`. `rec_ring=1` — по кругу: когда память кончилась, запись идёт поверх самых старых кадров, и к концу сеанса в ней последнее (для того, что случается раз за долгий сеанс: сеанс кончают сразу после — пятью пальцами); `rec_step=N` — каждый N-й пиксель вместо третьего (4 — в 1,8 раза больше кадров). Память на запись отнимается у системы на весь сеанс: с `rec_mb=640` в долгом сеансе Darwin убивала процессы ради памяти, вплоть до SpringBoard (респринги), с 256 — нет. `XL_REC_KEEP=1 ./xl recording` оставляет саму запись в `logs/recording.raw`; `tools/recording.py logs/recording.raw out.mp4 --frames DIR` раскладывает её на кадры с именами по времени ядра в миллисекундах — тому же, что в строках `glframes=1` |+| `rec_sound=N` | сохранить первые N секунд звука, который играет Darwin (тишина между звуками места не занимает); потом `./xl sound out.wav`. С `rec_sound_fed=1` — то, что пропустил к усилителям сторож динамиков, с `rec_sound_mic=1` — отсчёты микрофона (`mic=3`) || `speaker_probe=N` | только телефон, **ещё ни разу не запускалось**: посмотреть на звуковое железо, ничего не включая. `1` — только чтение (состояние выводов, имена питаний у RPMh, один регистр тактового генератора); `2` — ещё и спросить у усилителей динамиков, кто они, по I2C, для чего на время перенастраиваются два вывода (GPIO 12 и 13). Ответы — строки `speaker:` в журнале || `-v` | текст загрузки на экране (по умолчанию у `xl run`, если `XL_CMDLINE` не задана) || `applog=1` / `applog=2` | stderr приложений в журнал / плюс os_log всех процессов |@@ -371,8 +371,8 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #| `caenv=ИМЯ=ЗНАЧЕНИЕ` | (сколько угодно раз) в окружение оконного сервера: переключатели самой CoreAnimation (`CA_…`) || `fb_beat=0` | кадр уходит на панель сразу, как GPU его закончил, а не по собственному такту драйвера 60 Гц (такт держит ровный шаг, но кадр ждёт его в среднем 5–7 мс; панель всё равно обновляется 120 раз в секунду и к такту не привязана) || `ca_vbl=1` | (опыт) CoreAnimation ведёт кадры по уведомлениям драйвера экрана о такте (`CA_FORCE_TIMER=1` в backboardd), а не по своим часам; на ровность кадров не повлияло |-| `machine_name=0` | сообщать `hw.machine = arm64` вместо iPhone10,3 (как было раньше; тогда iOS не находит ни одного ресурса с суффиксом `~iphone`, и, например, Пункт управления теряет раскладку) |-| `privs=0` | привилегии ядра (`priv_check_cred`) процессам не от root — только `PRIV_WORK_INTERVAL`, как раньше. По умолчанию заглушка песочницы (`bsd/kern/kern_minimac.c`) даёт привилегию процессу, у которого в подписи есть право, что к ней относится, — так делает и песочница iOS; имена прав — те, что носят программы самой iOS: dasd — «vm-pressure-level», symptomsd и aggregated — `com.apple.private.network.statistics`, mediaserverd и mDNSResponder — `com.apple.private.network.socket-delegate` (без него NECP писал «does not hold the necessary entitlement to delegate network traffic»), и так далее, сорок привилегий. Права читаются у текущего процесса, поэтому только когда спрашивают о его собственных полномочиях: проверки, которые NECP делает за trustd и сетевой процесс WebKit в потоке ядра, по-прежнему получают отказ. Отказ, как и раньше, пишется в журнал один раз на привилегию |+| `machine_name=0` | сообщать `hw.machine = arm64` вместо iPhone10,3 (как было раньше; тогда Darwin не находит ни одного ресурса с суффиксом `~iphone`, и, например, Пункт управления теряет раскладку) |+| `privs=0` | привилегии ядра (`priv_check_cred`) процессам не от root — только `PRIV_WORK_INTERVAL`, как раньше. По умолчанию заглушка песочницы (`bsd/kern/kern_minimac.c`) даёт привилегию процессу, у которого в подписи есть право, что к ней относится, — так делает и песочница Darwin; имена прав — те, что носят программы самой Darwin: dasd — «vm-pressure-level», symptomsd и aggregated — `com.apple.private.network.statistics`, mediaserverd и mDNSResponder — `com.apple.private.network.socket-delegate` (без него NECP писал «does not hold the necessary entitlement to delegate network traffic»), и так далее, сорок привилегий. Права читаются у текущего процесса, поэтому только когда спрашивают о его собственных полномочиях: проверки, которые NECP делает за trustd и сетевой процесс WebKit в потоке ядра, по-прежнему получают отказ. Отказ, как и раньше, пишется в журнал один раз на привилегию || `xpcproxy_idversion=1` | процесс, которым становится xpcproxy (так launchd запускает службы XPC), при exec получает новую версию идентичности, как в XNU. По умолчанию он сохраняет версию xpcproxy, как если бы launchd запустил службу сам — это и значит «elide xpcproxy», о чём launchd пишет, но здесь всё равно запускает xpcproxy (`bsd/kern/kern_exec.c`). RunningBoard держит маркер аудита такого процесса из времени до exec и нового не берёт: каждая его проверка прав для такого процесса кончалась ошибкой (SecTaskLoadEntitlements error 3 — тысяча раз в минуту при открытом Safari), а веб-процессы Safari не получали утверждений («target is not running or doesn't have entitlement com.apple.runningboard.assertions.webkit»). С версией xpcproxy — ни одной такой ошибки || `wfi=0 wfe_mode=0` | простаивающее ядро процессора не засыпает, а крутится в цикле, как всегда было с одним ядром (с `cpus=N` простой — это WFI; на случай, если под гипервизором телефона он поведёт себя плохо) || `return_cpu=N`, `return_panic=1` | для проверки возврата в загрузчик с несколькими ядрами: вернуться по таймеру с процессора N (по номеру в ядре: 0 — загрузочный) и/или через панику |@@ -384,12 +384,12 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #| `wifi_irq=0`, `wifi_ba=0`, `wifi_wide=0` | с `wifi=1`: без прерываний радио (его кольца опрашиваются раз в миллисекунду, как раньше), без блочных подтверждений (точка доступа шлёт кадры по одному — скорость впятеро ниже), без широкого канала (только 20 МГц) || `wifi_step=N` | то же по шагам, как это выяснялось: первые N шагов, и ядро ждёт, пока они пройдут. 1–5 только читают (общая память процессоров, почтовый ящик процессора питания, RPMh, шины питания, выводы), 6–11 кладут прошивку процессора Wi-Fi в его память, заводят в общей памяти нашу половину его сигнальных битов (SMP2P) и запускают его через TrustZone, 12–14 поднимают связь с ним (GLINK, канал IPCRTR) и QRTR поверх неё: процессор Wi-Fi объявляет свои службы, среди них службу прошивки Wi-Fi; 15 — разговор с этой службой, какой драйвер ведёт до того, как тронет радио (нужны описания сообщений из ath11k: `tools/mk-wlfw.sh`, затем пересобрать ядро): прошивка принимает сообщения ath11k, файл платы и базу регионов телефона, с `wifi_cal=1` калибруется и через 7 секунд говорит «готова»; с `wifi_mission=1` прошивка получает настройку и переходит в рабочий режим; 16 — чтение нескольких регистров радио (`wifi_radio_read=1`): в рабочем режиме они отвечают, вне его чтение кончается ошибкой шины, и шаг его не делает (`adb pull` файлов `wpss.mdt`, `wpss.b02`…`wpss.b07` из `/vendor/firmware_mnt/image` в каталог `fw-wifi/`; в git они не попадают, `userland/build.sh` кладёт их в малый образ). Каждый шаг пишет в журнал, что собирается тронуть и что прочёл. `wifi_keep=1` оставляет процессор Wi-Fi и связь с ним работать, пока идёт сеанс. С `wifi_lx=1` шаг 15 ведёт сам драйвер ath11k из Linux (см. «Драйвер Wi-Fi» ниже; ядро собирается после `tools/mk-ath11k.sh`): его `qmi.c` проходит весь разговор с прошивкой до рабочего режима, со своей настройкой и списком теневых регистров, а регистры радио не трогает. С `wifi_lx=2 wifi_smmu=2` потоку радио в SMMU даётся контекст с нашими таблицами страниц (`wifi_smmu=2` в одиночку — только это, с возвратом как было), `ce.c` и `hal.c` драйвера заводят в регистрах радио кольца его «копировальных машин», `htc.c` подключает по ним службу WMI, и прошивка по WMI рассказывает о радио (одно, две антенные цепи, 2,4 и 5 ГГц) и через четверть секунды после запуска шины сообщает, что готова к командам («unified ready»); собственного адреса у прошивки нет (нули). Прерываний при этом нет: кольца опрашиваются раз в миллисекунду. С `wifi_scan=1` драйвер после этого регистрирует радио, заводит интерфейс в режиме станции и просит прошивку просканировать эфир — только слушая, в эфир ничего не уходит: 26 каналов 2,4 и 5 ГГц за четыре секунды, и в журнале появляются точки доступа вокруг с каналами и уровнем сигнала (имена и адреса чужих сетей — только в журнале запуска на вашей машине). Адрес радио у прошивки свой не записан: он лежит одной строкой в `fw-wifi/mac` (в git не попадает), и `xl run` передаёт его ядру параметром `wifi_mac`. С `wifi_join=1` драйвер подключается к сети из `fw-wifi/network` (WPA2 с паролем): находит её точку доступа, проходит аутентификацию, ассоциацию и четырёхстороннее рукопожатие, отдаёт ключи прошивке и становится тем, что стоит за `en0`; с `wifi_keep=1` он остаётся работать, пока идёт сеанс, без него — сворачивается, когда шаги кончились (`wifi_hold=S` — на S секунд позже). Остановленный без спроса (ядро, которое до этого не дошло) второй раз без перезагрузки телефона не запускается — такой запуск сбрасывал телефон, и драйвер от него сам отказывается; шаги и остальные параметры описаны в начале `drivers/wifi/hakios.wifi.c` || `adsp=1` | аудиопроцессор телефона (ADSP: звук, а у Xiaomi ещё и зарядка), шаг 1 звука: прошивка `adsp.mdt` и `adsp.b02`…`adsp.b36` с разделов телефона (`/vendor/firmware_mnt/image`, в каталог `fw-audio/`, в git не попадает; `userland/build.sh` кладёт её в образ системы в `/fw`, откуда ядро читает её, когда корень смонтирован, — после её появления образ системы пересобирается с `SYSTEM=1`; для `adsp_step=N`, который идёт до монтирования, — в малый образ с `ADSP=1`, и только без `GL=1`: вместе они не помещаются в 64 МБ, что берёт загрузчик) кладётся в его память, RPMh просят о его шинах питания LCX и LMX, пока он не попросит о них сам, TrustZone его запускает, через 41 мс он говорит «готов», поднимается GLINK (канал IPCRTR) и QRTR поверх него: процессор — узел 5 — объявляет 12 служб и открывает свои каналы, среди них `apr_audio_svc`; на нём — APR, протокол звуковых служб: служба ядра процессора отвечает, что звуковые службы готовы, и перечисляет их (9, среди них AFE, ASM, ADM — то, через что пойдёт звук). Рядом с загрузкой системы и рядом с `wifi=1`; в конце сеанса его просят остановиться и выключают. `adsp_step=N` — то же по шагам (первые N из 11, ядро ждёт), подробности в начале `drivers/audio/hakios.adsp.c` |-| `sound=N` | с `adsp=1`, шаг 3 звука, путь к динамикам, как его строит Android (числа — из живого дерева устройств телефона, его путей микшера и его ядра): `sound=1` — ножки TDM (GPIO 97–100) отданы интерфейсу, звуковой процессор включает его тактовую частоту (3,072 МГц), группу и порт 0x9000 (PRI_TDM_RX_0) и запускает его; по ножкам видно, что тактовый сигнал и синхронизация кадров идут. `sound=2` — ещё и поток: наша память видна процессору через SMMU (поток 0x1801), путь ADM к порту, поток ASM, и в него 3 с пишется тон 1 кГц −20 дБ полной шкалы; процессор забирает его с частотой 48 кГц. Усилители выключены. `sound=3` — ещё и усилители: настраиваются из профиля «Music» конфигурации Android (`/vendor/etc/aw882xx_acf.bin` телефона в `fw-audio/`, в git не попадает, `userland/build.sh` кладёт её в `/fw` образа системы), каждая запись читается обратно, при любом расхождении или сбое оба сразу выключаются; громкость плавно поднимается до `sound_below` восьмых долей дБ ниже уровня Android (по умолчанию 240, то есть на 30 дБ тише; выше уровня Android — никогда), тон звучит 3 с, потом всё затихает, выключается и возвращается как было. `sound=4` — то, что играет iOS (`/dev/hakios-audio`), до конца сеанса: порт и поток работают всё время (без звука в них идёт тишина), усилители настраиваются один раз и выключены, а когда в записи iOS появляется не тишина, включаются и быстро (как у драйвера Android) выводятся на `sound_below`; после трёх секунд тишины снова выключаются. Звук доходит до усилителей через 160 мс после записи, усилители готовы через 65 мс. У динамика в модуле HAL есть регулятор громкости, его значение уходит в ядро (`ioctl` `HAKIOS_AUDIO_SET_VOLUME`) и задаёт уровень усилителей ниже потолка (0 — усилители не включаются), но iOS ставит его только раз, на максимум, а громкость кнопок и Пункта управления применяет к самим отсчётам (программная громкость для динамика iPhone X в таблицах VirtualAudio); при громкости 0 iOS пишет тишину, и усилители тоже не включаются. Проверка — `RC_JOBS=rc.jobs.volume`. По пути к усилителям — сторож (см. выше): `sound_gain=N` (восьмые доли дБ, 0–96), `sound_guard_as=N` (для проверки: сторож считает усилители на N ниже уровня Android и сдерживает, как сдерживал бы там). `sound_secs=S` (не больше 3 с тоном), `sound_pause=MS`. Подробности в начале `drivers/audio/hakios.sound.c` и `drivers/audio/hakios.speaker.c` |-| `haptic=N` | моторчик вибрации: Awinic AW86927 на I2C (шина QUP SE9, GPIO 36/37, адрес 0x5a; сброс — GPIO 35), линейный мотор с резонансом 175,5 Гц; всё — из живого дерева устройств Android, его журнала и регистров (`drivers/haptic/hakios.haptic.c`). `haptic=1` — только читать: из загрузчика Android сброс держит чип выключенным, он не отвечает. `haptic=2` — сброс отпущен, как это делает драйвер Android, регистры прочитаны и сравнены с Android. `haptic=3` — ещё и настройка Android (каждая запись читается обратно; аналоговые регистры — за разблокировкой 0x5b) и волновые формы Android (`/vendor/firmware/aw8697_haptic.bin` телефона в `fw-haptic/`, в git не попадает; `userland/build.sh` кладёт его в `fw/` малого образа) в ОЗУ чипа, с проверкой чтением. `haptic=4` — ещё и одна короткая форма (`haptic_effect=1…10`) один раз, с усилением Android. `haptic=5` — моторчик для iOS до конца сеанса: всё, что iOS играет на своём устройстве «Actuator» (системные отклики и вибрация звонка, CoreHaptics приложений, отклики UIKit — например, меню иконки по долгому нажатию), звуковой модуль HAL отдаёт в `/dev/hakios-haptic`, и ядро играет по нему формы Android: каждую волну iOS — коротким толчком (форма 1), а длинную — повтором формы 11, пока iOS играет, но не дольше 1 с, после чего мотор столько же отдыхает; усиление — по громкости волны iOS: от трети полной шкалы и выше — усиление Android (0x80), ниже — до пяти восьмых его у самых тихих, и никогда не выше Android (волны iOS для Taptic Engine почти всегда гораздо тише полной шкалы, и в прямой пропорции большинство откликов выходило на десятой доле усиления Android — их было не почувствовать). Проверка обычных касаний: `RC_JOBS=rc.jobs.haptic2` (долгое нажатие на иконку, переключатель в Настройках). Без `haptic=5` iOS играет на «Actuator» как обычно, но в мотор ничего не идёт. Проверка: `RC_JOBS=rc.jobs.haptic`. Любая неисправность, о которой говорит чип, несовпадение при чтении или неотвеченный байт — чип снова в сброс до конца сеанса; не дольше 1 с на эффект; в конце сеанса и при панике — сброс |-| `torch=N` | фонарик: светодиодный модуль вспышки PM8350C (SPMI, ведомый 2, регистры 0xee00; задний светодиод — канал 0), значения Android: его фонарик горит на 125 мА через канал 0 (прочитано у включённого фонарика Android), шаг тока 12,5 мА, порядок записей — драйвера Xiaomi `leds-qti-flash.c` (`drivers/camera/hakios.torch.c`). `torch=1` — только читать: канал арбитра, тип модуля, регистры, температурная тревога PMIC. `torch=2` — ещё и зажечь один раз на 125 мА на `torch_secs` (по умолчанию 2 с). `torch=3` — фонарик для iOS: `/dev/hakios-torch` принимает уровень 0…1000 (тысячные тока Android, не выше 125 мА); загрузчик с `torch=N` добавляет в дерево `/product/camera` со свойством `flash` айфона (кнопка фонарика в Пункте управления), а `libhakios.media.dylib` отдаёт FigFlashlight в mediaserverd своё «устройство» вместо отсутствующей камеры (`userland/src/inject_media.c`). Пределы: записи — только в шесть регистров этого модуля, каждая читается обратно, канал арбитра перепроверяется; не дольше `torch_max_s` подряд (по умолчанию 30 с, не больше 120), потом темно, пока iOS не попросит снова; 10 раз в секунду — флаги неисправности и перегрева модуля, температурная тревога PMIC и температура батареи (не выше 45 °C; из battmgr при `adsp=1` или из `battery=1`) — что-то не так, и фонарик гаснет до конца сеанса; в конце сеанса и при панике — погашен. Проверка: `RC_JOBS=rc.jobs.torch` (`torch_test` — как программа, через AVFlashlight; потом кнопка в Пункте управления) |-| `cam=N` | камеры: все четыре — макро, широкая, фронтальная и сверхширокая (`cam_sensor=macro|wide|front|ultra`, по умолчанию — макро, при `cam=5` — широкая); макрокамера — OmniVision OV02B10 (2 Мп, камера 2 Android, «hakios_aac_ov02b10_macro»); всё — из живого дерева устройств (cam-sensor2), файла модуля камеры Android (`/vendor/lib64/camera/com.qti.sensormodule.hakios_aac_ov02b10_macro.bin`: адрес, где и как читается ID чипа, порядок включения) и драйверов ядра Android (`drivers/camera/hakios.camera.c`). Датчик — на CCI 1, ведущий 0 (GPIO 73/74, здесь I2C вручную, как у других драйверов), адрес 0x3c; сброс — GPIO 77; MCLK — mclk2 camcc на 19,2 МГц на GPIO 66 (у Android эти 19,2 МГц — от PLL2 camcc, здесь — от самого кварца, без PLL); питание — LDO6 (1,8 В, DOVDD) и LDO7 (2,8 В, AVDD) PM8008i, который на I2C последовательного движка 1 (GPIO 4/5, адреса 0x08 и 0x09) и выходит из сброса по GPIO 3 PM8350C, как его выводит Android. `cam=1` — только смотреть: тактовые частоты и домен питания камеры, ножки, сброс PM8008i и, если он не в сбросе, сам PM8008i. `cam=2` — ещё и включить датчик в порядке файла модуля (у макрокамеры: сброс низкий, 1 мс; DOVDD; AVDD, 2 мс; верхний домен питания камеры и MCLK, 4 мс; сброс высокий, 9 мс), прочитать ID чипа так, как читает Android (16-битный регистр по 16-битному адресу 0x0203; ждёт 0x002b), и выключить в обратном порядке. Пределы: напряжения — только Android (1,8 и 2,8 В у макрокамеры, 1,0 и 1,8 В у широкой), записи — только в перечисленные регистры (у каждого устройства — список, проверяется при каждой записи), каждая читается обратно; неотвеченный байт, регулятор не готов вовремя или сообщает о перегрузке по току, запись не читается обратно — всё выключается и больше ничего не пишется; в конце сеанса и при панике включённое выключается, найденное включённым остаётся включённым. `cam_after=S` — через сколько секунд после старта (по умолчанию 20). `cam=3` — путь кадра без датчика: генератор тестовой картинки CSID-lite 0 (RAW10 1600×1200, цветные полосы) → его путь RDI 0 → IFE-lite 0, чей мастер записи 0 пишет кадр в память через SMMU (поток 0x800, маска 0x4e0, в свободный контекст с нашими таблицами); для этого — голоса RPMh за CX на SVS и MX на SVS_L1 (через вторую TCS DRV 2, в конце отдаются), PLL0 camcc (1,2 ГГц), RCG и ветви камеры на частотах уровня «svs» из дерева устройств (cphy_rx, CSID, IFE-lite — 400 МГц, таймер PHY — 300, camnoc — 150, slow_ahb — 80), всё — по драйверам Android (`camcc-yupik.c`, `cam_ife_csid_lite17x.h`, `cam_vfe_lite16x.h`, `cam_vfe_bus_ver2.c`). `cam=4` — кадры самого датчика: питание и ID, как при `cam=2`, его таблицы Android — инициализация (108 записей), режим (1600×1200 RAW10, одна линия, 665,6 Мбит/с, 30 кадров/с), «пуск», таблица экспозиции; CSIPHY 2 (v1.2.1, D-PHY, линия данных 0 и линия такта; число отсчётов установления — из файла модуля для этого режима, 20, `cam_settle=N` — своё), приёмник CSID-lite 0 от PHY 2 и тот же путь RDI 0 → IFE-lite 0 → SMMU → память; несколько кадров подряд в два места, последний остаётся; потом «стоп» и всё выключается. Таблицы читаются при запуске из `fw/camera-ov02b10.tab` малого образа: его делает `tools/camsensor.py` из файла модуля датчика Android (`fw-camera/com.qti.sensormodule.hakios_aac_ov02b10_macro.bin` с телефона; ни он, ни таблицы в git не попадают). `cam_pattern=1` — тестовые полосы самого датчика вместо изображения, `cam_frames=N` — сколько кадров (по умолчанию 8), `cam_shutter=СТРОК`, `cam_gain=N` — своя экспозиция и усиление. Память с кадрами загрузчик отдаёт после сеанса: `./xl camera [префикс]` забирает её и через `tools/camraw.py` делает картинки (`префикс-N.png` — по пикселю на ячейку 2×2 Байера, серый мир, гамма 2,2; `префикс-N-raw.png` — сырые значения; порядок Байера изображения датчика — BGGR (см. ниже); его собственные полосы читаются как GBRG; `--bayer N` — другой порядок; `cam_vblank=СТРОК` — удлинить кадр для выдержки длиннее 1200 строк). `cam_sensor=wide` — то же для основной широкоугольной камеры, Samsung S5KHM2SD (108 Мп, камера 0 Android, «hakios_sunny_s5khm2sd_wide», cam-sensor0): CCI 0, ведущий 1 (GPIO 71/72), адрес 0x20, ID чипа 0xfad2 по адресу 0x0000; сброс — GPIO 21; MCLK — mclk1 camcc (19,2 МГц, GPIO 65); питание — LDO1 (1,0 В, VDIG) и LDO5 (1,8 В, VIO) PM8008i и VANA 2,8 В от постоянного регулятора, который включает GPIO 106 (всё — напряжения дерева устройств); порядок включения и выключения, ID, таблицы и режимы — из её файла модуля (`fw-camera/com.qti.sensormodule.hakios_sunny_s5khm2sd_wide.bin` → `fw/camera-s5khm2sd.tab`, формат RWCTAB02 — все режимы, порядок питания, назначение линий; инициализация — 1441 запись; шесть режимов, от 12000×9000 до 1920×1080 на 240 кадрах/с). Кадры — по трём трио C-PHY в CSIPHY 1 (трёхфазные таблицы v1.2.1 Android и строка таблицы скоростей, покрывающая скорость трио; число отсчётов установления — из файла модуля, 34), CSID-lite 0 — в режиме C-PHY. `cam_mode=N` — режим из таблицы датчика (по умолчанию — с наименьшим числом пикселей: у широкой — 1920×1080 RAW10 на 120 кадрах/с, 3,11 Гбит/с на трио). Порядок Байера широкой — GRBG (см. ниже), заголовок кадра говорит его сам. Экспозиция широкой — регистры SMIA внутри group hold 0x0104: `cam_vblank` — длина кадра 0x0340, `cam_shutter` — выдержка 0x0202, `cam_gain` — аналоговое усиление 0x0204 (32 — 1×). `cam_sensor=front` — фронтальная камера, OmniVision OV16A1Q (16 Мп, cam-sensor1, «hakios_aac_ov16a1q_front»): CCI 0, ведущий 0 (GPIO 69/70), адрес 0x10, ID чипа 0x1641 по адресу 0x300b; сброс — GPIO 20; MCLK — mclk0 (19,2 МГц, GPIO 64); питание — LDO3 (2,8 В, VANA), LDO2 (1,2 В, VDIG), LDO5 (1,8 В, VIO) PM8008i; четыре линии D-PHY в CSIPHY 0 (по умолчанию — режим 1920×1080 на 120 кадрах/с, 1,44 Гбит/с на линию). `cam_sensor=ultra` — сверхширокая, Samsung S5K4H7 (8 Мп, cam-sensor3, «hakios_sunny_s5k4h7_ultra»): CCI 1, ведущий 1 (GPIO 75/76), адрес 0x2d, ID чипа 0x487b по адресу 0; сброс — GPIO 78; MCLK — mclk3 на 24 МГц, как просит её файл модуля: от PLL2 camcc (Zonda, 1440 МГц, настройки `cam_cc_pll2_config` Android, запуск — как `clk_zonda_pll_enable()`), делитель 10 и M/N 1/6 (`ftbl_cam_cc_mclk0_clk_src`); питание — LDO4 (2,8 В, VANA), LDO5 (1,8 В, VIO) и VDIG 1,2 В от постоянного регулятора (`camera_ultra_dvdd_ldo`, от PM7325 S8), который включает GPIO 108; четыре линии D-PHY в CSIPHY 3. Собственных цветных полос (таблицы «tpgon» в файле модуля) нет ни у широкой, ни у фронтальной, ни у сверхширокой — только у макрокамеры; `cam_pattern=1` для остальных даёт их изображение (при `cam=4`) или полосы CSID (при `cam=5`). Выдержка по `cam_shutter`/`cam_gain`/`cam_vblank` при `cam=4` — только у макро и широкой; фронтальная и сверхширокая при `cam=4` снимают с выдержкой своих таблиц. Порядок Байера: макро и фронтальная — BGGR, широкая и сверхширокая — GRBG. Так его задаёт файл модуля каждого датчика: первое слово элемента режима `resolutionData` — `colorFilterArrangement` в нумерации CamX (0 BGGR, 1 GBRG, 2 GRBG, 3 RGGB; `TranslateColorFilterArrangement` в `camera.qcom.so` переводит его в нумерацию Android таблицей 3, 2, 1, 0), `tools/camsensor.py` печатает его у каждого режима. Раньше красный против синего угадывался по сырым уровням при тёплом свете — наоборот, и у всех четырёх камер красный и синий были переставлены (в Camera.app бежевое выходило голубым); зелёные (два отсчёта ячейки, что идут друг за другом в снимке комнаты) были на месте. Память под два кадра `cam=3`/`cam=4` (до 12 МБ каждый) берётся одним куском при загрузке (`cam_keep_mb`). `cam=5` — широкая камера для iOS: устройство `/dev/hakios-camera` (`bsd/sys/hakios.camera.h`); первое чтение после открытия включает датчик и запускает кадры (режим — `cam_mode`, по умолчанию 1: 4000×3000 RAW10, 30 кадров/с), последнее закрытие, секунда без чтения или любая неисправность всё выключают (после неисправности — до конца сеанса). Кадры идут по кругу в три места памяти ядра (отображённые через SMMU постранично): одно пишет IFE, одно может копировать чтение, одно готово; в каждом начале кадра адрес места для следующего кадра уходит мастеру записи, который берёт его в следующем начале кадра (на это есть целый кадр, а не промежуток между кадрами); кадр, для которого адреса не оказалось, считается переписанным. Строка RAW10 у мастера записи выровнена на 16 байт (4000 пикселей — 5008 байт, а не 5000). `read()` отдаёт заголовок (номер, время, выдержка, усиление, длина кадра и строки) и сам кадр; `write()` принимает другой датчик (`HAKIOS_CAMERA_SENSOR`: кадры останавливаются, всё выключается, следующее чтение включает другой; номер датчика — в заголовке кадра; режим по умолчанию — самый крупный 4:3 не быстрее 30 кадров/с и не больше 13 Мп: широкая 4000×3000, фронтальная 2304×1728, сверхширокая 3264×2448, макро 1600×1200; выдержка из `write()` пишется каждому его способом в его group hold: SMIA у широкой и сверхширокой — 0x0340/0x0202/0x0204, у фронтальной OV16A1Q — 0x380e/0x380f, 0x3500…0x3502, 0x3508/0x3509 (0x100 — 1×), у макро OV02B10 — страница 1: 0x14/0x15, 0x0e/0x0f, 0x22 (16 — 1×); предел усиления — свой у каждого: 64× у широкой, 16× у сверхширокой, 15,5× у фронтальной и макро), выдержку и усиление (пишутся между кадрами в group hold, с пределами: усиление от 1× до предела датчика, кадр не длиннее 0xfff0 строк) или картинку для хоста (память под неё — `cam_keep_mb`, по умолчанию 24, берётся при загрузке одним куском; `./xl camera` её забирает, `tools/camraw.py` понимает NV12 и BGRA). Проверка всех четырёх по очереди — `RC_JOBS=rc.jobs.cameras` (`camera_test cycle`); `camera_test noise` — уровень чёрного и шум каждого датчика в темноте (временной, фиксированный, строк) при усилении 1×…максимум. `camera_test raw` — кадры через `src/camera_isp.c` (замер, автоэкспозиция, баланс белого, цветовая матрица, гамма, NV12 BT.601 с округлением до ближайшего: полосы CSID `cam_pattern=2` с `noae noawb` выходят основными цветами с точностью до шага — точнее 8-битный YCbCr красный и синий не передаёт); `full` — каждый пиксель (билинейная демозаика в размер датчика, 8 потоков; на резких цветовых границах — кайма в 1–2 пикселя от демозаики и общей цветности 2×2), `ccm M` — своя цветовая матрица (девять чисел через запятую; по умолчанию единичная: настоящей нужна цветовая мишень). Устройство появляется сразу при старте ядра (раньше mediaserverd, который ищет камеры один раз, при старте); чтения ждут, пока датчик не включится. `cam_pattern=1` — цветные полосы: собственные полосы датчика, если в файле модуля есть их таблица, иначе — генератора CSID (у широкой камеры таблица пустая, поэтому — CSID, как при `cam=3`, датчик тогда не включается вовсе); `cam_pattern=2` — всегда CSID. Для iOS: `libhakios.media.dylib` в mediaserverd даёт его `BWFigCaptureDeviceVendor` наше устройство захвата (`src/camera_device.c`: FigCaptureDevice и FigCaptureStream, производные объекты CoreMedia, как у H10ISP.mediacapture; форматы названы, как «Photo» и «Video-60» задней камеры в `D22/AVCaptureSession.plist`); AVFoundation перечисляет «Back Camera» с 16 форматами и «Front Camera» (`camera_avtest`; у фронтальной — «Photo» 3088×2320 и «Video-30» 3840×2160 фронтальной камеры iPhone X, порт `FrontFacingCamera`), а сама Camera.app показывает живой предпросмотр с обеих камер телефона, ровный и без перерывов (`RC_JOBS=rc.jobs.camera`). Камеры переключает кнопка Camera.app: поток одной камеры, начинаясь, останавливает поток другой, и ядру уходит `HAKIOS_CAMERA_SENSOR`; картинка фронтальной OV16A1Q повёрнута на 180° — так датчик стоит в телефоне. Чтобы граф захвата встал: узлу стабилизации (VIS) отказываем на уровне соединения — ему нужна сессия обработки ISP айфона, которой нет (`video_stabilization_method/_type` → 0 в `inject_media.c`); потоку отвечаем на чтение `VideoOutputsColorInfo` (без ответа сессия не запускается) и принимаем `TimeMachineSuspendNow`/`ResumeNow`; кадры отдаём не своей памятью, а из пула (`BufferPool` в настройках выхода), который даёт сам граф — ширины и высоты в настройках нет, только пул; отдавать их начинаем лишь после того, как граф запущен (раньше mediaserverd падал по SIGSEGV). Ровным предпросмотр стал после трёх починок: аудиовходу сессии (`BWAudioSourceNode start:`) отвечаем «запустился», глотая только ошибку `'nope'` отсутствующего аудио-HAL — иначе сессия слала приложению `AVCaptureSessionRuntimeError` и оно пересобирало её каждые 2 с; PM8008i остаётся поднятым между включениями камеры (возвращённый в сброс, он потом отвечал ревизией, но его регуляторы молчали) и приводится в исходное состояние только при выходе ядра; обе программные шины I2C повторяют посылку, оставшуюся без ответа (PMIC — 4 попытки, датчик — до 40 мс). Переключение камер — а через него проходит каждый сеанс, потому что mediaserverd при старте сам смотрит устройство и оставляет ядру фронтальную, — спотыкалось дважды. Датчик, остановленный между кадрами, держит линию данных своей шины прижатой (его цифровое питание остаётся включённым: драйвер застал его включённым и не трогает), и шина больше не приходит в покой — теперь мастер выщёлкивает её свободной линией, пока датчик не договорит байт, и закрывает стопом (`bus_take`, как `i2c_generic_scl_recovery` в Linux). А сразу после того, как сняты питания фронтальной камеры, PM8008i несколько раз отвечает байтом из одних единиц, в котором бит 5 — «перегрузка по току»: камера выключалась до конца сеанса — теперь такой ответ переспрашивают, и перегрузку тоже (`ldo_on`, как давно делает `healthy()` на ходу). Предпросмотр рвался поперёк, полосами двух кадров: пул графа отдаёт буфер обратно, едва передав его дальше, а тот ещё в пути к экрану (приёмник предпросмотра, очередь картинок Camera.app, копия оконного сервера) — теперь отданный буфер держат ещё три кадра (`HELD` в `camera_device.c`), одного не хватало. За сеанс Camera.app с широкой камеры пришло 910 кадров подряд, ни одного переписанного. Цвета — по тюнингу самих камер: `tools/camtuning.py` делает из файла тюнинга Android (`fw-camera/com.qti.tuned.hakios_*.bin`, Chromatix) `fw/camera-<датчик>.isp` малого образа (`build.sh` — сам, когда файлы есть; ни те, ни другие в git не попадают): цветовые матрицы (cc13) и затенение объектива (lsc34) по освещённости сцены (lux index) и цветовой температуре и десять опорных источников света баланса белого (refPtV1). Баланс белого (`src/camera_isp.c`) — серый мир по почти нейтральным ячейкам кадра после коррекции затенения, спроецированный на ломаную опорных источников; точка на ней даёт цветовую температуру, а температура и освещённость — матрицу и затенение (смесь двух соседних таблиц). U30 (тёплый свет без инфракрасного, как у белого светодиода) берёт таблицы TL84: затенение цвета широкой камеры под тёплым светодиодом, снятое на белом листе, совпало с таблицей TL84 до 3 %, а с таблицей 2550–2900 K расходится на 12 % в красном. Фокус (у широкой камеры): мотор объектива DW9800 на шине CCI её датчика (адрес 0x0c), питание — L9C PM8350C, 2,8 В, через RPMh (`drivers/camera/hakios.camera.c`); ядро включает его вместе с датчиком, положение принимает через `write()` (`HAKIOS_CAMERA_FOCUS`) и пишет в заголовок кадра. Непрерывный автофокус — восхождение по резкости кадра; касание (`AFWindowParams` и `AutoFocusNow`) — проход объектива по окну касания с остановкой за пиком и доводка мелкими шагами. Ход — не дальше 768 из 1023 (у дальнего конца стабилизатор LDO5 PM8008i сообщал о перегрузке по току, и камера останавливалась) и шагами не больше 48 (большие шаги щёлкали). Зум — `ZoomFactor` потока, до 16×: вырез из кадра датчика с билинейной интерполяцией между ячейками; кадр несёт `ZoomFactor` в метаданных (без него предпросмотр замирал на первом же увеличении). Снимок по кнопке затвора: `StillImageCaptureNow` — один полный кадр датчика в выход StillImage, собранный из каждого пикселя (билинейная демозаика, билинейная демозаика сразу в размер снимка: 4032×3024 из кадра датчика 4000×3000 за 271 мс на восьми потоках, `isp_render_still_nv12`). Чтобы он дошёл до файла: кадры несут метаданные, как у H10ISP (без них устройство захвата откладывало снимок на каждом кадре навсегда); приоритет качества — не выше «speed» (`qualityPrioritization` в `inject_media.c`: иначе устройство просит четыре кадра для SIS, которые здесь не сложить); шумоподавление `BWGNRNode` (процессор айфона) пропускается; HEIC кодирует программный кодировщик HEVC из `VCPHEVC.videocodec`, который iOS сама не регистрирует (`register_hevc_encoder`; без него — −12908). Двенадцать мегапикселей он кодирует 5,0 с в первый раз и 2,8 с во второй; сколько потоков брать, кодировщик читает из своего домена настроек (`var/mobile/Library/Preferences/com.apple.VideoProcessing.plist`, `max-threads`) — сам по себе он кодирует в один поток. Снимок доходит до библиотеки Photos и открывается там во весь экран. Пустые (NULL) сэмплы беззвучного аудиоисточника дальше не передаются: на них падал узел Live Photo `BWIrisStagingNode`. Сам Live Photo здесь не снять: его записи нужны видео и звук вокруг затвора, а микрофоны телефона молчат — `rc.jobs.photo` его выключает. Проверять: `RC_JOBS=rc.jobs.camera` (снимать самому), `RC_JOBS=rc.jobs.photo` (два снимка без Live Photo) |-| `mic=N` | с `adsp=1`, основной микрофон (`drivers/audio/hakios.mic.c`, значения Android). `mic=1` — только посмотреть: звуковой процессор голосует за блоки LPASS и даёт тактовые частоты макроса TX (19,2 МГц), регистры макросов TX и VA, ведущего SoundWire, ножек LPASS и сброса кодека читаются; без всех четырёх ни один регистр не трогается. `mic=2` — ещё и кодек поднят настолько, чтобы ответить по SoundWire: сброс (GPIO83) отпущен, как это делает Android, ножки ведущего (LPASS GPIO 0, 1, 2, 14) — в активное состояние Android, тактовые частоты макроса TX, ведущий запущен, устройство TX кодека перечислено и его номер прочитан. `mic=3` — ещё и запись с микрофона `mic_secs` секунд (по умолчанию 10, не больше 600): настройка кодека, как в `wcd938x_init_reg()`, смещение микрофона 2750 мВ, ADC1 в режиме «low power», «ADC1 Volume» 6, дециматор 1 и порт codec DMA, шина SoundWire как на пути Android «handset-mic» (выше). Каждая запись читается обратно, любое расхождение или отказ звукового процессора — всё останавливается. Для проверки: `mic_input=0` (дециматор слушает ноль — точная тишина), `mic_adc=0`, `mic_test=1` (без смещения), `mic_test=2` (вход ADC1 удержан), `mic_main=1`, `mic_tap=1` с `haptic=5`. `mic=4` — микрофон для iOS: путь до кодека поднимается, только пока iOS записывает (пока открыт `/dev/hakios-mic`, кольцо на 341 мс, чтение никогда не ждёт и держится в 40 мс за звуковым процессором), а в плагине звука `HakiosAudio.driver` есть устройство «Codec» с одним входом и источником данных `imic` («Bottom»), из которого VirtualAudio, как на iPhone, делает «iPhone Microphone» (Built-In Microphone). Приложения записывают с него: «Диктофон» пишет и рисует волну (`RC_JOBS=rc.jobs.voicememos`), `record_test` (AVAudioRecorder) — 6,00 с из 6,00, на частоте мотора 175,5 Гц с `haptic=5` уровень растёт с −68 до −29 дБFS (`RC_JOBS=rc.jobs.mic`, с `sound=4 sound_below=720` — сначала беззвучная проверка динамиков). Программа без интерфейса, записывающая в фоне, получает оранжевую точку, но не плашку записи в строке состояния, и MediaSafetyNet в mediaserverd, как на iPhone, через девять секунд такой записи останавливает mediaserverd; записи `record_test` поэтому короче и с паузой между ними. В конце и при выключении звукового процессора всё возвращается как было: кодек снова в сбросе, ножки и регистры как были |-| `battmgr=0` | с `adsp=1` батарея не спрашивается. Без него (по умолчанию) ядро раз в 10 с спрашивает у звукового процессора, который у этого телефона и ведёт батарею с зарядкой (как Android — `qti_battery_charger`, Linux — `qcom_battmgr` поверх `pmic_glink`), по каналу `PMIC_RTR_ADSP_APPS` процент заряда, зарядку, напряжение, ток, температуру, заряд в мА·ч, ёмкость, циклы и что даёт порт USB — только читает, ни пределов, ни токов не задаёт — и показывает это iOS так же, как батарея iPhone: службой `HakiosBattery` класса `IOPMPowerSource` (`drivers/power/hakios.battery.cpp`). Её читает powerd, и дальше всё делает сама iOS: батарея с процентом и молнией в строке состояния, «58% Charged» на экране блокировки, виджет «Батареи», Настройки → Аккумулятор (переключатель «Заряд в процентах» работает; в образе он включён); перехваты батареи в SpringBoard при этой службе уступают iOS. Сверено с Android (`dumpsys battery` и `/sys/class/power_supply/battery` сразу после): 56 % и 58 %, «заряжается», напряжение, температура, заряд, ёмкость 3677 из 5000 мА·ч, 890 циклов совпадают. Номера свойств — этой прошивки: до 9-го как у Linux, дальше на один больше; `battmgr=2` пишет в журнал все. Те же числа — в `kern.hakios.battery_*`. С `battery=1` (путь загрузчика через UEFI) не включается. Историю заряда и расход по приложениям iOS 16 берёт из журнала энергии, который ведёт aggregated (`com.apple.powerlog.plxpclogger.xpc` и другие службы; база `CurrentPowerlog.PLSQL`); раньше он был в списке не запускаемых (`userland/mkjobs.py`), и страница «Аккумулятор» вечно крутила колёсико. Теперь она открывается сразу: в первые минуты — «As you use your iPhone, battery usage will be reported here» (так iOS говорит, пока данных о расходе нет), через час — график уровня заряда за 24 часа и список приложений («Connected to Charger», пока телефон на зарядке); экран всё это время iOS считала выключенным («Screen On 0m»), отчего — ещё не разобрано. Расход в процентах по приложениям iOS считает из энергии частей системы на кристалле, которую на iPhone сообщают счётчики IOReport («Energy Model»); их здесь нет. Не показывается износ в «Состоянии аккумулятора» (powerd ждёт серийный номер батареи, а его прошивка не даёт; вместо цифры колёсико). Проверка — `RC_JOBS=rc.jobs.battery` (`battery_test`), `RC_JOBS=rc.jobs.battery2` (страницы Настроек, в конце `battery_test powerlog`: что журнал энергии собрал — таблицы, строки, время), `RC_JOBS=rc.jobs.battery3` (то же после часа работы приложений) |+| `sound=N` | с `adsp=1`, шаг 3 звука, путь к динамикам, как его строит Android (числа — из живого дерева устройств телефона, его путей микшера и его ядра): `sound=1` — ножки TDM (GPIO 97–100) отданы интерфейсу, звуковой процессор включает его тактовую частоту (3,072 МГц), группу и порт 0x9000 (PRI_TDM_RX_0) и запускает его; по ножкам видно, что тактовый сигнал и синхронизация кадров идут. `sound=2` — ещё и поток: наша память видна процессору через SMMU (поток 0x1801), путь ADM к порту, поток ASM, и в него 3 с пишется тон 1 кГц −20 дБ полной шкалы; процессор забирает его с частотой 48 кГц. Усилители выключены. `sound=3` — ещё и усилители: настраиваются из профиля «Music» конфигурации Android (`/vendor/etc/aw882xx_acf.bin` телефона в `fw-audio/`, в git не попадает, `userland/build.sh` кладёт её в `/fw` образа системы), каждая запись читается обратно, при любом расхождении или сбое оба сразу выключаются; громкость плавно поднимается до `sound_below` восьмых долей дБ ниже уровня Android (по умолчанию 240, то есть на 30 дБ тише; выше уровня Android — никогда), тон звучит 3 с, потом всё затихает, выключается и возвращается как было. `sound=4` — то, что играет Darwin (`/dev/hakios-audio`), до конца сеанса: порт и поток работают всё время (без звука в них идёт тишина), усилители настраиваются один раз и выключены, а когда в записи Darwin появляется не тишина, включаются и быстро (как у драйвера Android) выводятся на `sound_below`; после трёх секунд тишины снова выключаются. Звук доходит до усилителей через 160 мс после записи, усилители готовы через 65 мс. У динамика в модуле HAL есть регулятор громкости, его значение уходит в ядро (`ioctl` `HAKIOS_AUDIO_SET_VOLUME`) и задаёт уровень усилителей ниже потолка (0 — усилители не включаются), но Darwin ставит его только раз, на максимум, а громкость кнопок и Пункта управления применяет к самим отсчётам (программная громкость для динамика iPhone X в таблицах VirtualAudio); при громкости 0 Darwin пишет тишину, и усилители тоже не включаются. Проверка — `RC_JOBS=rc.jobs.volume`. По пути к усилителям — сторож (см. выше): `sound_gain=N` (восьмые доли дБ, 0–96), `sound_guard_as=N` (для проверки: сторож считает усилители на N ниже уровня Android и сдерживает, как сдерживал бы там). `sound_secs=S` (не больше 3 с тоном), `sound_pause=MS`. Подробности в начале `drivers/audio/hakios.sound.c` и `drivers/audio/hakios.speaker.c` |+| `haptic=N` | моторчик вибрации: Awinic AW86927 на I2C (шина QUP SE9, GPIO 36/37, адрес 0x5a; сброс — GPIO 35), линейный мотор с резонансом 175,5 Гц; всё — из живого дерева устройств Android, его журнала и регистров (`drivers/haptic/hakios.haptic.c`). `haptic=1` — только читать: из загрузчика Android сброс держит чип выключенным, он не отвечает. `haptic=2` — сброс отпущен, как это делает драйвер Android, регистры прочитаны и сравнены с Android. `haptic=3` — ещё и настройка Android (каждая запись читается обратно; аналоговые регистры — за разблокировкой 0x5b) и волновые формы Android (`/vendor/firmware/aw8697_haptic.bin` телефона в `fw-haptic/`, в git не попадает; `userland/build.sh` кладёт его в `fw/` малого образа) в ОЗУ чипа, с проверкой чтением. `haptic=4` — ещё и одна короткая форма (`haptic_effect=1…10`) один раз, с усилением Android. `haptic=5` — моторчик для Darwin до конца сеанса: всё, что Darwin играет на своём устройстве «Actuator» (системные отклики и вибрация звонка, CoreHaptics приложений, отклики UIKit — например, меню иконки по долгому нажатию), звуковой модуль HAL отдаёт в `/dev/hakios-haptic`, и ядро играет по нему формы Android: каждую волну Darwin — коротким толчком (форма 1), а длинную — повтором формы 11, пока Darwin играет, но не дольше 1 с, после чего мотор столько же отдыхает; усиление — по громкости волны Darwin: от трети полной шкалы и выше — усиление Android (0x80), ниже — до пяти восьмых его у самых тихих, и никогда не выше Android (волны Darwin для Taptic Engine почти всегда гораздо тише полной шкалы, и в прямой пропорции большинство откликов выходило на десятой доле усиления Android — их было не почувствовать). Проверка обычных касаний: `RC_JOBS=rc.jobs.haptic2` (долгое нажатие на иконку, переключатель в Настройках). Без `haptic=5` Darwin играет на «Actuator» как обычно, но в мотор ничего не идёт. Проверка: `RC_JOBS=rc.jobs.haptic`. Любая неисправность, о которой говорит чип, несовпадение при чтении или неотвеченный байт — чип снова в сброс до конца сеанса; не дольше 1 с на эффект; в конце сеанса и при панике — сброс |+| `torch=N` | фонарик: светодиодный модуль вспышки PM8350C (SPMI, ведомый 2, регистры 0xee00; задний светодиод — канал 0), значения Android: его фонарик горит на 125 мА через канал 0 (прочитано у включённого фонарика Android), шаг тока 12,5 мА, порядок записей — драйвера Xiaomi `leds-qti-flash.c` (`drivers/camera/hakios.torch.c`). `torch=1` — только читать: канал арбитра, тип модуля, регистры, температурная тревога PMIC. `torch=2` — ещё и зажечь один раз на 125 мА на `torch_secs` (по умолчанию 2 с). `torch=3` — фонарик для Darwin: `/dev/hakios-torch` принимает уровень 0…1000 (тысячные тока Android, не выше 125 мА); загрузчик с `torch=N` добавляет в дерево `/product/camera` со свойством `flash` айфона (кнопка фонарика в Пункте управления), а `libhakios.media.dylib` отдаёт FigFlashlight в mediaserverd своё «устройство» вместо отсутствующей камеры (`userland/src/inject_media.c`). Пределы: записи — только в шесть регистров этого модуля, каждая читается обратно, канал арбитра перепроверяется; не дольше `torch_max_s` подряд (по умолчанию 30 с, не больше 120), потом темно, пока Darwin не попросит снова; 10 раз в секунду — флаги неисправности и перегрева модуля, температурная тревога PMIC и температура батареи (не выше 45 °C; из battmgr при `adsp=1` или из `battery=1`) — что-то не так, и фонарик гаснет до конца сеанса; в конце сеанса и при панике — погашен. Проверка: `RC_JOBS=rc.jobs.torch` (`torch_test` — как программа, через AVFlashlight; потом кнопка в Пункте управления) |+| `cam=N` | камеры: все четыре — макро, широкая, фронтальная и сверхширокая (`cam_sensor=macro|wide|front|ultra`, по умолчанию — макро, при `cam=5` — широкая); макрокамера — OmniVision OV02B10 (2 Мп, камера 2 Android, «hakios_aac_ov02b10_macro»); всё — из живого дерева устройств (cam-sensor2), файла модуля камеры Android (`/vendor/lib64/camera/com.qti.sensormodule.hakios_aac_ov02b10_macro.bin`: адрес, где и как читается ID чипа, порядок включения) и драйверов ядра Android (`drivers/camera/hakios.camera.c`). Датчик — на CCI 1, ведущий 0 (GPIO 73/74, здесь I2C вручную, как у других драйверов), адрес 0x3c; сброс — GPIO 77; MCLK — mclk2 camcc на 19,2 МГц на GPIO 66 (у Android эти 19,2 МГц — от PLL2 camcc, здесь — от самого кварца, без PLL); питание — LDO6 (1,8 В, DOVDD) и LDO7 (2,8 В, AVDD) PM8008i, который на I2C последовательного движка 1 (GPIO 4/5, адреса 0x08 и 0x09) и выходит из сброса по GPIO 3 PM8350C, как его выводит Android. `cam=1` — только смотреть: тактовые частоты и домен питания камеры, ножки, сброс PM8008i и, если он не в сбросе, сам PM8008i. `cam=2` — ещё и включить датчик в порядке файла модуля (у макрокамеры: сброс низкий, 1 мс; DOVDD; AVDD, 2 мс; верхний домен питания камеры и MCLK, 4 мс; сброс высокий, 9 мс), прочитать ID чипа так, как читает Android (16-битный регистр по 16-битному адресу 0x0203; ждёт 0x002b), и выключить в обратном порядке. Пределы: напряжения — только Android (1,8 и 2,8 В у макрокамеры, 1,0 и 1,8 В у широкой), записи — только в перечисленные регистры (у каждого устройства — список, проверяется при каждой записи), каждая читается обратно; неотвеченный байт, регулятор не готов вовремя или сообщает о перегрузке по току, запись не читается обратно — всё выключается и больше ничего не пишется; в конце сеанса и при панике включённое выключается, найденное включённым остаётся включённым. `cam_after=S` — через сколько секунд после старта (по умолчанию 20). `cam=3` — путь кадра без датчика: генератор тестовой картинки CSID-lite 0 (RAW10 1600×1200, цветные полосы) → его путь RDI 0 → IFE-lite 0, чей мастер записи 0 пишет кадр в память через SMMU (поток 0x800, маска 0x4e0, в свободный контекст с нашими таблицами); для этого — голоса RPMh за CX на SVS и MX на SVS_L1 (через вторую TCS DRV 2, в конце отдаются), PLL0 camcc (1,2 ГГц), RCG и ветви камеры на частотах уровня «svs» из дерева устройств (cphy_rx, CSID, IFE-lite — 400 МГц, таймер PHY — 300, camnoc — 150, slow_ahb — 80), всё — по драйверам Android (`camcc-yupik.c`, `cam_ife_csid_lite17x.h`, `cam_vfe_lite16x.h`, `cam_vfe_bus_ver2.c`). `cam=4` — кадры самого датчика: питание и ID, как при `cam=2`, его таблицы Android — инициализация (108 записей), режим (1600×1200 RAW10, одна линия, 665,6 Мбит/с, 30 кадров/с), «пуск», таблица экспозиции; CSIPHY 2 (v1.2.1, D-PHY, линия данных 0 и линия такта; число отсчётов установления — из файла модуля для этого режима, 20, `cam_settle=N` — своё), приёмник CSID-lite 0 от PHY 2 и тот же путь RDI 0 → IFE-lite 0 → SMMU → память; несколько кадров подряд в два места, последний остаётся; потом «стоп» и всё выключается. Таблицы читаются при запуске из `fw/camera-ov02b10.tab` малого образа: его делает `tools/camsensor.py` из файла модуля датчика Android (`fw-camera/com.qti.sensormodule.hakios_aac_ov02b10_macro.bin` с телефона; ни он, ни таблицы в git не попадают). `cam_pattern=1` — тестовые полосы самого датчика вместо изображения, `cam_frames=N` — сколько кадров (по умолчанию 8), `cam_shutter=СТРОК`, `cam_gain=N` — своя экспозиция и усиление. Память с кадрами загрузчик отдаёт после сеанса: `./xl camera [префикс]` забирает её и через `tools/camraw.py` делает картинки (`префикс-N.png` — по пикселю на ячейку 2×2 Байера, серый мир, гамма 2,2; `префикс-N-raw.png` — сырые значения; порядок Байера изображения датчика — BGGR (см. ниже); его собственные полосы читаются как GBRG; `--bayer N` — другой порядок; `cam_vblank=СТРОК` — удлинить кадр для выдержки длиннее 1200 строк). `cam_sensor=wide` — то же для основной широкоугольной камеры, Samsung S5KHM2SD (108 Мп, камера 0 Android, «hakios_sunny_s5khm2sd_wide», cam-sensor0): CCI 0, ведущий 1 (GPIO 71/72), адрес 0x20, ID чипа 0xfad2 по адресу 0x0000; сброс — GPIO 21; MCLK — mclk1 camcc (19,2 МГц, GPIO 65); питание — LDO1 (1,0 В, VDIG) и LDO5 (1,8 В, VIO) PM8008i и VANA 2,8 В от постоянного регулятора, который включает GPIO 106 (всё — напряжения дерева устройств); порядок включения и выключения, ID, таблицы и режимы — из её файла модуля (`fw-camera/com.qti.sensormodule.hakios_sunny_s5khm2sd_wide.bin` → `fw/camera-s5khm2sd.tab`, формат RWCTAB02 — все режимы, порядок питания, назначение линий; инициализация — 1441 запись; шесть режимов, от 12000×9000 до 1920×1080 на 240 кадрах/с). Кадры — по трём трио C-PHY в CSIPHY 1 (трёхфазные таблицы v1.2.1 Android и строка таблицы скоростей, покрывающая скорость трио; число отсчётов установления — из файла модуля, 34), CSID-lite 0 — в режиме C-PHY. `cam_mode=N` — режим из таблицы датчика (по умолчанию — с наименьшим числом пикселей: у широкой — 1920×1080 RAW10 на 120 кадрах/с, 3,11 Гбит/с на трио). Порядок Байера широкой — GRBG (см. ниже), заголовок кадра говорит его сам. Экспозиция широкой — регистры SMIA внутри group hold 0x0104: `cam_vblank` — длина кадра 0x0340, `cam_shutter` — выдержка 0x0202, `cam_gain` — аналоговое усиление 0x0204 (32 — 1×). `cam_sensor=front` — фронтальная камера, OmniVision OV16A1Q (16 Мп, cam-sensor1, «hakios_aac_ov16a1q_front»): CCI 0, ведущий 0 (GPIO 69/70), адрес 0x10, ID чипа 0x1641 по адресу 0x300b; сброс — GPIO 20; MCLK — mclk0 (19,2 МГц, GPIO 64); питание — LDO3 (2,8 В, VANA), LDO2 (1,2 В, VDIG), LDO5 (1,8 В, VIO) PM8008i; четыре линии D-PHY в CSIPHY 0 (по умолчанию — режим 1920×1080 на 120 кадрах/с, 1,44 Гбит/с на линию). `cam_sensor=ultra` — сверхширокая, Samsung S5K4H7 (8 Мп, cam-sensor3, «hakios_sunny_s5k4h7_ultra»): CCI 1, ведущий 1 (GPIO 75/76), адрес 0x2d, ID чипа 0x487b по адресу 0; сброс — GPIO 78; MCLK — mclk3 на 24 МГц, как просит её файл модуля: от PLL2 camcc (Zonda, 1440 МГц, настройки `cam_cc_pll2_config` Android, запуск — как `clk_zonda_pll_enable()`), делитель 10 и M/N 1/6 (`ftbl_cam_cc_mclk0_clk_src`); питание — LDO4 (2,8 В, VANA), LDO5 (1,8 В, VIO) и VDIG 1,2 В от постоянного регулятора (`camera_ultra_dvdd_ldo`, от PM7325 S8), который включает GPIO 108; четыре линии D-PHY в CSIPHY 3. Собственных цветных полос (таблицы «tpgon» в файле модуля) нет ни у широкой, ни у фронтальной, ни у сверхширокой — только у макрокамеры; `cam_pattern=1` для остальных даёт их изображение (при `cam=4`) или полосы CSID (при `cam=5`). Выдержка по `cam_shutter`/`cam_gain`/`cam_vblank` при `cam=4` — только у макро и широкой; фронтальная и сверхширокая при `cam=4` снимают с выдержкой своих таблиц. Порядок Байера: макро и фронтальная — BGGR, широкая и сверхширокая — GRBG. Так его задаёт файл модуля каждого датчика: первое слово элемента режима `resolutionData` — `colorFilterArrangement` в нумерации CamX (0 BGGR, 1 GBRG, 2 GRBG, 3 RGGB; `TranslateColorFilterArrangement` в `camera.qcom.so` переводит его в нумерацию Android таблицей 3, 2, 1, 0), `tools/camsensor.py` печатает его у каждого режима. Раньше красный против синего угадывался по сырым уровням при тёплом свете — наоборот, и у всех четырёх камер красный и синий были переставлены (в Camera.app бежевое выходило голубым); зелёные (два отсчёта ячейки, что идут друг за другом в снимке комнаты) были на месте. Память под два кадра `cam=3`/`cam=4` (до 12 МБ каждый) берётся одним куском при загрузке (`cam_keep_mb`). `cam=5` — широкая камера для Darwin: устройство `/dev/hakios-camera` (`bsd/sys/hakios.camera.h`); первое чтение после открытия включает датчик и запускает кадры (режим — `cam_mode`, по умолчанию 1: 4000×3000 RAW10, 30 кадров/с), последнее закрытие, секунда без чтения или любая неисправность всё выключают (после неисправности — до конца сеанса). Кадры идут по кругу в три места памяти ядра (отображённые через SMMU постранично): одно пишет IFE, одно может копировать чтение, одно готово; в каждом начале кадра адрес места для следующего кадра уходит мастеру записи, который берёт его в следующем начале кадра (на это есть целый кадр, а не промежуток между кадрами); кадр, для которого адреса не оказалось, считается переписанным. Строка RAW10 у мастера записи выровнена на 16 байт (4000 пикселей — 5008 байт, а не 5000). `read()` отдаёт заголовок (номер, время, выдержка, усиление, длина кадра и строки) и сам кадр; `write()` принимает другой датчик (`HAKIOS_CAMERA_SENSOR`: кадры останавливаются, всё выключается, следующее чтение включает другой; номер датчика — в заголовке кадра; режим по умолчанию — самый крупный 4:3 не быстрее 30 кадров/с и не больше 13 Мп: широкая 4000×3000, фронтальная 2304×1728, сверхширокая 3264×2448, макро 1600×1200; выдержка из `write()` пишется каждому его способом в его group hold: SMIA у широкой и сверхширокой — 0x0340/0x0202/0x0204, у фронтальной OV16A1Q — 0x380e/0x380f, 0x3500…0x3502, 0x3508/0x3509 (0x100 — 1×), у макро OV02B10 — страница 1: 0x14/0x15, 0x0e/0x0f, 0x22 (16 — 1×); предел усиления — свой у каждого: 64× у широкой, 16× у сверхширокой, 15,5× у фронтальной и макро), выдержку и усиление (пишутся между кадрами в group hold, с пределами: усиление от 1× до предела датчика, кадр не длиннее 0xfff0 строк) или картинку для хоста (память под неё — `cam_keep_mb`, по умолчанию 24, берётся при загрузке одним куском; `./xl camera` её забирает, `tools/camraw.py` понимает NV12 и BGRA). Проверка всех четырёх по очереди — `RC_JOBS=rc.jobs.cameras` (`camera_test cycle`); `camera_test noise` — уровень чёрного и шум каждого датчика в темноте (временной, фиксированный, строк) при усилении 1×…максимум. `camera_test raw` — кадры через `src/camera_isp.c` (замер, автоэкспозиция, баланс белого, цветовая матрица, гамма, NV12 BT.601 с округлением до ближайшего: полосы CSID `cam_pattern=2` с `noae noawb` выходят основными цветами с точностью до шага — точнее 8-битный YCbCr красный и синий не передаёт); `full` — каждый пиксель (билинейная демозаика в размер датчика, 8 потоков; на резких цветовых границах — кайма в 1–2 пикселя от демозаики и общей цветности 2×2), `ccm M` — своя цветовая матрица (девять чисел через запятую; по умолчанию единичная: настоящей нужна цветовая мишень). Устройство появляется сразу при старте ядра (раньше mediaserverd, который ищет камеры один раз, при старте); чтения ждут, пока датчик не включится. `cam_pattern=1` — цветные полосы: собственные полосы датчика, если в файле модуля есть их таблица, иначе — генератора CSID (у широкой камеры таблица пустая, поэтому — CSID, как при `cam=3`, датчик тогда не включается вовсе); `cam_pattern=2` — всегда CSID. Для Darwin: `libhakios.media.dylib` в mediaserverd даёт его `BWFigCaptureDeviceVendor` наше устройство захвата (`src/camera_device.c`: FigCaptureDevice и FigCaptureStream, производные объекты CoreMedia, как у H10ISP.mediacapture; форматы названы, как «Photo» и «Video-60» задней камеры в `D22/AVCaptureSession.plist`); AVFoundation перечисляет «Back Camera» с 16 форматами и «Front Camera» (`camera_avtest`; у фронтальной — «Photo» 3088×2320 и «Video-30» 3840×2160 фронтальной камеры iPhone X, порт `FrontFacingCamera`), а сама Camera.app показывает живой предпросмотр с обеих камер телефона, ровный и без перерывов (`RC_JOBS=rc.jobs.camera`). Камеры переключает кнопка Camera.app: поток одной камеры, начинаясь, останавливает поток другой, и ядру уходит `HAKIOS_CAMERA_SENSOR`; картинка фронтальной OV16A1Q повёрнута на 180° — так датчик стоит в телефоне. Чтобы граф захвата встал: узлу стабилизации (VIS) отказываем на уровне соединения — ему нужна сессия обработки ISP айфона, которой нет (`video_stabilization_method/_type` → 0 в `inject_media.c`); потоку отвечаем на чтение `VideoOutputsColorInfo` (без ответа сессия не запускается) и принимаем `TimeMachineSuspendNow`/`ResumeNow`; кадры отдаём не своей памятью, а из пула (`BufferPool` в настройках выхода), который даёт сам граф — ширины и высоты в настройках нет, только пул; отдавать их начинаем лишь после того, как граф запущен (раньше mediaserverd падал по SIGSEGV). Ровным предпросмотр стал после трёх починок: аудиовходу сессии (`BWAudioSourceNode start:`) отвечаем «запустился», глотая только ошибку `'nope'` отсутствующего аудио-HAL — иначе сессия слала приложению `AVCaptureSessionRuntimeError` и оно пересобирало её каждые 2 с; PM8008i остаётся поднятым между включениями камеры (возвращённый в сброс, он потом отвечал ревизией, но его регуляторы молчали) и приводится в исходное состояние только при выходе ядра; обе программные шины I2C повторяют посылку, оставшуюся без ответа (PMIC — 4 попытки, датчик — до 40 мс). Переключение камер — а через него проходит каждый сеанс, потому что mediaserverd при старте сам смотрит устройство и оставляет ядру фронтальную, — спотыкалось дважды. Датчик, остановленный между кадрами, держит линию данных своей шины прижатой (его цифровое питание остаётся включённым: драйвер застал его включённым и не трогает), и шина больше не приходит в покой — теперь мастер выщёлкивает её свободной линией, пока датчик не договорит байт, и закрывает стопом (`bus_take`, как `i2c_generic_scl_recovery` в Linux). А сразу после того, как сняты питания фронтальной камеры, PM8008i несколько раз отвечает байтом из одних единиц, в котором бит 5 — «перегрузка по току»: камера выключалась до конца сеанса — теперь такой ответ переспрашивают, и перегрузку тоже (`ldo_on`, как давно делает `healthy()` на ходу). Предпросмотр рвался поперёк, полосами двух кадров: пул графа отдаёт буфер обратно, едва передав его дальше, а тот ещё в пути к экрану (приёмник предпросмотра, очередь картинок Camera.app, копия оконного сервера) — теперь отданный буфер держат ещё три кадра (`HELD` в `camera_device.c`), одного не хватало. За сеанс Camera.app с широкой камеры пришло 910 кадров подряд, ни одного переписанного. Цвета — по тюнингу самих камер: `tools/camtuning.py` делает из файла тюнинга Android (`fw-camera/com.qti.tuned.hakios_*.bin`, Chromatix) `fw/camera-<датчик>.isp` малого образа (`build.sh` — сам, когда файлы есть; ни те, ни другие в git не попадают): цветовые матрицы (cc13) и затенение объектива (lsc34) по освещённости сцены (lux index) и цветовой температуре и десять опорных источников света баланса белого (refPtV1). Баланс белого (`src/camera_isp.c`) — серый мир по почти нейтральным ячейкам кадра после коррекции затенения, спроецированный на ломаную опорных источников; точка на ней даёт цветовую температуру, а температура и освещённость — матрицу и затенение (смесь двух соседних таблиц). U30 (тёплый свет без инфракрасного, как у белого светодиода) берёт таблицы TL84: затенение цвета широкой камеры под тёплым светодиодом, снятое на белом листе, совпало с таблицей TL84 до 3 %, а с таблицей 2550–2900 K расходится на 12 % в красном. Фокус (у широкой камеры): мотор объектива DW9800 на шине CCI её датчика (адрес 0x0c), питание — L9C PM8350C, 2,8 В, через RPMh (`drivers/camera/hakios.camera.c`); ядро включает его вместе с датчиком, положение принимает через `write()` (`HAKIOS_CAMERA_FOCUS`) и пишет в заголовок кадра. Непрерывный автофокус — восхождение по резкости кадра; касание (`AFWindowParams` и `AutoFocusNow`) — проход объектива по окну касания с остановкой за пиком и доводка мелкими шагами. Ход — не дальше 768 из 1023 (у дальнего конца стабилизатор LDO5 PM8008i сообщал о перегрузке по току, и камера останавливалась) и шагами не больше 48 (большие шаги щёлкали). Зум — `ZoomFactor` потока, до 16×: вырез из кадра датчика с билинейной интерполяцией между ячейками; кадр несёт `ZoomFactor` в метаданных (без него предпросмотр замирал на первом же увеличении). Снимок по кнопке затвора: `StillImageCaptureNow` — один полный кадр датчика в выход StillImage, собранный из каждого пикселя (билинейная демозаика, билинейная демозаика сразу в размер снимка: 4032×3024 из кадра датчика 4000×3000 за 271 мс на восьми потоках, `isp_render_still_nv12`). Чтобы он дошёл до файла: кадры несут метаданные, как у H10ISP (без них устройство захвата откладывало снимок на каждом кадре навсегда); приоритет качества — не выше «speed» (`qualityPrioritization` в `inject_media.c`: иначе устройство просит четыре кадра для SIS, которые здесь не сложить); шумоподавление `BWGNRNode` (процессор айфона) пропускается; HEIC кодирует программный кодировщик HEVC из `VCPHEVC.videocodec`, который Darwin сама не регистрирует (`register_hevc_encoder`; без него — −12908). Двенадцать мегапикселей он кодирует 5,0 с в первый раз и 2,8 с во второй; сколько потоков брать, кодировщик читает из своего домена настроек (`var/mobile/Library/Preferences/com.apple.VideoProcessing.plist`, `max-threads`) — сам по себе он кодирует в один поток. Снимок доходит до библиотеки Photos и открывается там во весь экран. Пустые (NULL) сэмплы беззвучного аудиоисточника дальше не передаются: на них падал узел Live Photo `BWIrisStagingNode`. Сам Live Photo здесь не снять: его записи нужны видео и звук вокруг затвора, а микрофоны телефона молчат — `rc.jobs.photo` его выключает. Проверять: `RC_JOBS=rc.jobs.camera` (снимать самому), `RC_JOBS=rc.jobs.photo` (два снимка без Live Photo) |+| `mic=N` | с `adsp=1`, основной микрофон (`drivers/audio/hakios.mic.c`, значения Android). `mic=1` — только посмотреть: звуковой процессор голосует за блоки LPASS и даёт тактовые частоты макроса TX (19,2 МГц), регистры макросов TX и VA, ведущего SoundWire, ножек LPASS и сброса кодека читаются; без всех четырёх ни один регистр не трогается. `mic=2` — ещё и кодек поднят настолько, чтобы ответить по SoundWire: сброс (GPIO83) отпущен, как это делает Android, ножки ведущего (LPASS GPIO 0, 1, 2, 14) — в активное состояние Android, тактовые частоты макроса TX, ведущий запущен, устройство TX кодека перечислено и его номер прочитан. `mic=3` — ещё и запись с микрофона `mic_secs` секунд (по умолчанию 10, не больше 600): настройка кодека, как в `wcd938x_init_reg()`, смещение микрофона 2750 мВ, ADC1 в режиме «low power», «ADC1 Volume» 6, дециматор 1 и порт codec DMA, шина SoundWire как на пути Android «handset-mic» (выше). Каждая запись читается обратно, любое расхождение или отказ звукового процессора — всё останавливается. Для проверки: `mic_input=0` (дециматор слушает ноль — точная тишина), `mic_adc=0`, `mic_test=1` (без смещения), `mic_test=2` (вход ADC1 удержан), `mic_main=1`, `mic_tap=1` с `haptic=5`. `mic=4` — микрофон для Darwin: путь до кодека поднимается, только пока Darwin записывает (пока открыт `/dev/hakios-mic`, кольцо на 341 мс, чтение никогда не ждёт и держится в 40 мс за звуковым процессором), а в плагине звука `HakiosAudio.driver` есть устройство «Codec» с одним входом и источником данных `imic` («Bottom»), из которого VirtualAudio, как на iPhone, делает «iPhone Microphone» (Built-In Microphone). Приложения записывают с него: «Диктофон» пишет и рисует волну (`RC_JOBS=rc.jobs.voicememos`), `record_test` (AVAudioRecorder) — 6,00 с из 6,00, на частоте мотора 175,5 Гц с `haptic=5` уровень растёт с −68 до −29 дБFS (`RC_JOBS=rc.jobs.mic`, с `sound=4 sound_below=720` — сначала беззвучная проверка динамиков). Программа без интерфейса, записывающая в фоне, получает оранжевую точку, но не плашку записи в строке состояния, и MediaSafetyNet в mediaserverd, как на iPhone, через девять секунд такой записи останавливает mediaserverd; записи `record_test` поэтому короче и с паузой между ними. В конце и при выключении звукового процессора всё возвращается как было: кодек снова в сбросе, ножки и регистры как были |+| `battmgr=0` | с `adsp=1` батарея не спрашивается. Без него (по умолчанию) ядро раз в 10 с спрашивает у звукового процессора, который у этого телефона и ведёт батарею с зарядкой (как Android — `qti_battery_charger`, Linux — `qcom_battmgr` поверх `pmic_glink`), по каналу `PMIC_RTR_ADSP_APPS` процент заряда, зарядку, напряжение, ток, температуру, заряд в мА·ч, ёмкость, циклы и что даёт порт USB — только читает, ни пределов, ни токов не задаёт — и показывает это Darwin так же, как батарея iPhone: службой `HakiosBattery` класса `IOPMPowerSource` (`drivers/power/hakios.battery.cpp`). Её читает powerd, и дальше всё делает сама Darwin: батарея с процентом и молнией в строке состояния, «58% Charged» на экране блокировки, виджет «Батареи», Настройки → Аккумулятор (переключатель «Заряд в процентах» работает; в образе он включён); перехваты батареи в SpringBoard при этой службе уступают Darwin. Сверено с Android (`dumpsys battery` и `/sys/class/power_supply/battery` сразу после): 56 % и 58 %, «заряжается», напряжение, температура, заряд, ёмкость 3677 из 5000 мА·ч, 890 циклов совпадают. Номера свойств — этой прошивки: до 9-го как у Linux, дальше на один больше; `battmgr=2` пишет в журнал все. Те же числа — в `kern.hakios.battery_*`. С `battery=1` (путь загрузчика через UEFI) не включается. Историю заряда и расход по приложениям Darwin userland 16 берёт из журнала энергии, который ведёт aggregated (`com.apple.powerlog.plxpclogger.xpc` и другие службы; база `CurrentPowerlog.PLSQL`); раньше он был в списке не запускаемых (`userland/mkjobs.py`), и страница «Аккумулятор» вечно крутила колёсико. Теперь она открывается сразу: в первые минуты — «As you use your iPhone, battery usage will be reported here» (так Darwin говорит, пока данных о расходе нет), через час — график уровня заряда за 24 часа и список приложений («Connected to Charger», пока телефон на зарядке); экран всё это время Darwin считала выключенным («Screen On 0m»), отчего — ещё не разобрано. Расход в процентах по приложениям Darwin считает из энергии частей системы на кристалле, которую на iPhone сообщают счётчики IOReport («Energy Model»); их здесь нет. Не показывается износ в «Состоянии аккумулятора» (powerd ждёт серийный номер батареи, а его прошивка не даёт; вместо цифры колёсико). Проверка — `RC_JOBS=rc.jobs.battery` (`battery_test`), `RC_JOBS=rc.jobs.battery2` (страницы Настроек, в конце `battery_test powerlog`: что журнал энергии собрал — таблицы, строки, время), `RC_JOBS=rc.jobs.battery3` (то же после часа работы приложений) |Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). На одном итом же сценарии `cpus=4` (четыре больших ядра: 7, 6, 5, 4) дал 929 кадров вместо 671 на одном ядре, пики 35@@ -405,7 +405,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run ### GPU-**iOS на телефоне может рисовать графический процессор** — Adreno 642L, через открытый драйвер Mesa freedreno+**Darwin на телефоне может рисовать графический процессор** — Adreno 642L, через открытый драйвер Mesa freedrenoи наш драйвер в ядре (: треугольник, экран блокировки, домашний экран).Как это устроено:@@ -413,7 +413,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #- ядро (`drivers/gpu/hakios.adreno.c`, `drivers/gpu/hakios.gpu.cpp`) поднимает Adreno — прошивка управляющегопроцессора (GMU), питание 3D-ядра, zap-шейдер через TrustZone, микрокод — и отдаёт его userland'у черезклиент IOKit с подмножеством интерфейса msm DRM (буферы, отправка команд, ожидание);-- `tools/mk-mesa.sh` собирает Mesa 25.0.7 под userland iOS (freedreno и программный softpipe, минута сборки);+- `tools/mk-mesa.sh` собирает Mesa 25.0.7 под userland Darwin (freedreno и программный softpipe, минута сборки);- `userland/src/eagl.c` встаёт за системный `EAGLContext`: в QuartzCore 16.5 есть рендер через OpenGL ES, накоторый сервер окон переходит сам, если нет Metal.@@ -462,7 +462,7 @@ CoreAnimation; если GPU не запустился, в журнале однсоздаётся вовсе (`switcher_wallpaper_overlay` в `src/inject_sb.c`): оттенок чужого цвета хуже, чем никакого.Карточки стали [18 18 18] вместо [42 26 42]. Когда появится настоящая картинка обоев для PaperBoardUI, этотперехват надо убрать; а до тех пор `switcher_wallpaper=1` среди параметров ядра возвращает наложение таким, каким-его просит iOS, — чтобы тот, кто возьмётся за обои, сразу видел, доходит ли его картинка, не пересобирая образ. Проверено по пути и отброшено: YCbCr снимков (мы сохраняем их в JPEG, карточка — две+его просит Darwin, — чтобы тот, кто возьмётся за обои, сразу видел, доходит ли его картинка, не пересобирая образ. Проверено по пути и отброшено: YCbCr снимков (мы сохраняем их в JPEG, карточка — двеплоскости), фильтрация таблиц половинной точности, разбор ASTC (обои — тоже ASTC и разбираются верно; у картинкизаглушки все просмотренные блоки «пустые», с одним цветом), работа с группами (`glgroup=0`), чтение кадровогобуфера шейдером (`glfetch=0`).@@ -532,7 +532,7 @@ P3 поверхности кадров копировались, и этогочто дала бы группа, начатая с того, что позади неё, и то же, что даёт отрисовка при полной непрозрачности. Группа, вкоторую после этого рисуют или которую читают иначе, сначала делается тем, чем была бы (матрица от ничего попокрытию). По записи экрана (`RC_JOBS=rc.jobs.cc`) диски и заголовок видны с первых кадров и проявляются вместе с-модулем, анимации iOS не тронуты. `glgroup=0` — как раньше.+модулем, анимации Darwin не тронуты. `glgroup=0` — как раньше.Штрихи значков, которые по счёту отрисовок будто бы приходили через 0,4 с, на деле на месте с первого кадра: припрозрачности 1 CoreAnimation лишь отделяет полностью покрытые отрезки заливки в свои отрисовки без смешивания (концовотрезков в кадре до и после столько же). `cc_fade=МС` (`userland/src/inject_sb.c`: анимации прозрачности в окне@@ -699,7 +699,7 @@ Sileo работает от него и держит там свою базу.Что пришлось сделать помимо этого:- **`PATH`** для запускаемых команд: программы префикса зовут друг друга по имени (`dpkg` → `dpkg-query`).- **подготовка бутстрапа один раз за загрузку** — `/var/jb/prep.sh` (его пишет `mk-jb.sh`): `usr/libexec/firmware`- заводит в базе dpkg пакет `firmware` с версией iOS, от которого зависят все остальные (у Sileo —+ заводит в базе dpkg пакет `firmware` с версией Darwin, от которого зависят все остальные (у Sileo —`firmware (>= 11.0)`), плюс `pwd_mkdb` и несколько postinst. Своя `prep_bootstrap.sh` бутстрапа не годится:она спрашивает пароль терминала в своём окне и правит `/etc`, который здесь и так новый при каждой загрузке.- **сертификаты для apt**: gnutls собран доверять `/var/jb/etc/ssl/certs/cacert.pem` из пакета `ca-certificates`,@@ -723,13 +723,13 @@ Sileo работает от него и держит там свою базу.- **свой каталог индексов**: Sileo зовёт apt с `-oDir::State::lists=sileolists/`, то есть`/var/jb/var/lib/apt/sileolists`, которого в бутстрапе нет. Создаёт его init и отдаёт mobile, иначе Sileoпоказывает «The folder … doesn't exist» и видит только установленные пакеты вместо витрины.-- **`nsurlsessiond`**: фоновые загрузки URLSession выполняет этот демон iOS, а он стоял в `DENY` в+- **`nsurlsessiond`**: фоновые загрузки URLSession выполняет этот демон Darwin, а он стоял в `DENY` в`userland/mkjobs.py` вместе со службами Apple-аккаунта. Без него загрузка пакета не начинается и необрывается — Sileo вечно показывает «Queued», без единой ошибки.И то, без чего Sileo доходил до установки, но не ставил:- **`/bin/mv`, `cp`, `rm`, `mkdir`, `chmod`**: всё, что Sileo перекладывает от root (скачанный пакет — в архивы- apt, индексы — в `lists`), он перекладывает этими программами из `/bin`, а в `/bin` iOS только `df` и `ps`.+ apt, индексы — в `lists`), он перекладывает этими программами из `/bin`, а в `/bin` Darwin только `df` и `ps`.Каждый такой запуск молча не удавался, пакет до архивов apt не доходил, и apt с `--no-download` отвечал«Unable to fetch some archives». Теперь это ссылки на программы префикса (`SILEO_BIN` в `build.sh`).- **счёт процессов root**: Sileo запускает apt, dpkg и эти пять программ от root через «персону», которой здесь@@ -747,10 +747,10 @@ Sileo работает от него и держит там свою базу.`/private/preboot/jb`. Его записываемая копия — в отдельной файловой системе в памяти, смонтированной на`/private/preboot/jb-rw`, как `procursus`, а `/var/jb` — ссылка туда: как на iPhone с rootless-взломом, где`/var/jb` ведёт в `/private/preboot/…/procursus`. Ссылки на пять программ лежат в `jb-bin` загрузочного тома, и-`init` кладёт этот каталог поверх `/bin` тома iOS объединяющим монтированием (`MNT_UNION`): чего в нём нет+`init` кладёт этот каталог поверх `/bin` тома Darwin объединяющим монтированием (`MNT_UNION`): чего в нём нет(`df`, `ps`), находится в `/bin` под ним. В памяти от префикса — 42 МБ сжатого образа.-Приложений префикса в `/Applications` тома iOS нет, поэтому их регистрирует `uicache`, как при взломе+Приложений префикса в `/Applications` тома Darwin нет, поэтому их регистрирует `uicache`, как при взломе(`prep.sh`, в фоне, с повторами: первые полминуты после SpringBoard LaunchServices занят системнымиприложениями). Чтобы это заработало:- **настоящий путь**: в приращённом префиксе файлы приложения — ссылки в загрузочный том, и такое приложение@@ -761,7 +761,7 @@ Sileo работает от него и держит там свою базу.`/var/jb/Applications`, было «Unable to register». Теперь `ramfs` находит узел по номеру (`vfs_vget`), отдаётимя каталога по записи в родителе и заявляет обе возможности.- **`/var/mobile/tmp`**: у Sileo, зарегистрированного так, нет своего контейнера данных, и временные файлы — а с- ними каждая загрузка — идут в `$HOME/tmp`, которого в шаблоне `/private/var` iOS нет. Каждая загрузка+ ними каждая загрузка — идут в `$HOME/tmp`, которого в шаблоне `/private/var` Darwin нет. Каждая загрузкакончалась «No such file or directory». `build.sh` добавляет его в шаблон.```sh@@ -858,7 +858,7 @@ mobilesubstrate` (а это почти все твики, и `preferenceloader`потом заголовок) и читаются с флеша обратно.После перезагрузки Android поднялся, `/data` — 89,6 ГБ, `resize.f2fs` ничего не тронул, загрузчик через UEFI видит-`darwin`, суммы GPT верны. В `darwin` записан корневой контейнер APFS iOS 16.5 (`rootfs.apfs`, 5 628 755 968 байт)+`darwin`, суммы GPT верны. В `darwin` записан корневой контейнер APFS Darwin userland 16.5 (`rootfs.apfs`, 5 628 755 968 байт)— из Android, `adb exec-in 'dd of=/dev/block/sda34 bs=4194304 conv=fsync'`, ~13 МБ/с; SHA-256 прочитанного с флешаобратно (после сброса кешей) совпал с файлом. Резервные копии (обе копии старой таблицы, первые 458 МБ `userdata` — все метаданныеf2fs, файлы `/sdcard`) и то, как вернуть таблицу, — в `fw-backup/userdata-shrink/` основной копии репозитория,@@ -889,10 +889,10 @@ f2fs, файлы `/sdcard`) и то, как вернуть таблицу, —говорят, куда ушло время. Остаётся сам `ReadBlocks`: около 25 мкс на запрос плюс около 1 мс на МБ, произвольноечтение 4 КБ — около 110 мкс, и в полёте всегда один запрос (драйвер Qualcomm через `BlockIo`).-### Корневой том iOS с флеша+### Корневой том Darwin с флешаВесь том за один проход, с `/dev/ufs_darwin` (`bootcpu=7 cpus=7 cpufreq=1 ufs=2 apfs_check=6 apfs_dev=ufs_darwin-apfs_mnt=/lib`; теперь — `apfs_mnt=/System/Volumes/iOS`, каталог образа системы): 318 098 записей, 8 285 771 220 байт, сумма `ceb8a53c349a011f` —+apfs_mnt=/lib`; теперь — `apfs_mnt=/System/Volumes/Darwin`, каталог образа системы): 318 098 записей, 8 285 771 220 байт, сумма `ceb8a53c349a011f` —та же, что на компьютере, ошибок 0. Время по шагам:| | обход | МБ/с содержимого |@@ -909,28 +909,28 @@ apfs_mnt=/lib`; теперь — `apfs_mnt=/System/Volumes/iOS`, каталог(`cheap_requests`; иначе один читатель ramdisk терял 8 %).**В обычном сеансе том виден пользовательскому пространству:** с `apfs_volume=ufs_darwin` ядро монтирует его-только для чтения (и `nosuid,nodev`) на `/System/Volumes/iOS` — сразу после корня и devfs, до launchd+только для чтения (и `nosuid,nodev`) на `/System/Volumes/Darwin` — сразу после корня и devfs, до launchd(`apfs_volume_at=` — другое место; каталог есть в образе системы). Корнем он не становится.```sh-SYSTEM=1 REST=1 RC_JOBS=rc.jobs.ios userland/build.sh+SYSTEM=1 REST=1 RC_JOBS=rc.jobs.darwin userland/build.sh./xl ramdisk userland/system.apfsXL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8 ufs=2 apfs_volume=ufs_darwin" XL_SECS=180 ./xl run```-iOS доходит до домашнего экрана как обычно, а `rc.jobs.ios` показывает из пространства пользователя:-`/dev/ufs_darwin on /System/Volumes/iOS (apfs, local, nodev, nosuid, read-only)` (`/sbin/mount`, `df` — 278 712-файлов), листинги `vol_ls ls` (своего `ls` в iOS нет: в `/bin` только `df` и `ps`) корня тома и+Darwin доходит до домашнего экрана как обычно, а `rc.jobs.darwin` показывает из пространства пользователя:+`/dev/ufs_darwin on /System/Volumes/Darwin (apfs, local, nodev, nosuid, read-only)` (`/sbin/mount`, `df` — 278 712+файлов), листинги `vol_ls ls` (своего `ls` в Darwin нет: в `/bin` только `df` и `ps`) корня тома и`/System/Library/CoreServices`, `SystemVersion.plist` целиком (iPhone OS 16.5, 20F66), хеши трёх файлов через`read(2)` и через отображение — совпадают между собой и с компьютером, и все 32 файла `/usr/sbin` (50 096 208байт) обоими способами — каждый размер и хеш как на компьютере, ошибок 0, 208 и 244 МБ/с. Путь отображения —`vnop_pagein`: 227 подкачек, 50 МБ, 146 мс — на телефоне он впервые и отработал.-### iOS с корнем на флеше+### Darwin с корнем на флеше-С `root_apfs=ufs_darwin` корень системы — сам том iOS на флеше, только для чтения, а в памяти телефона только то,+С `root_apfs=ufs_darwin` корень системы — сам том Darwin на флеше, только для чтения, а в памяти телефона только то,чего на нём нет: образ `flashboot.apfs` — загрузочный том (`stage0`, прошивки звукового процессора, точки-монтирования), 21 МБ. Оба криптекса — образы Apple как есть — лежат на флеше, в разделе `darwin` сразу за томом iOS+монтирования), 21 МБ. Оба криптекса — образы Apple как есть — лежат на флеше, в разделе `darwin` сразу за томом Darwin(см. «Криптексы на флеше»). Без `CRYPTEXES=flash` образ несёт их сам, тремя контейнерами подряд (994 МБ), — длятелефона, на флеше которого их нет; `init` берёт криптексы из памяти, если они там есть, иначе с флеша.@@ -940,7 +940,7 @@ CRYPTEXES=flash FLASHBOOT=1 GL=1 REST=1 RC_JOBS=rc.jobs.flashcheck userland/builXL_CMDLINE="root_apfs=ufs_darwin ufs=2 ufs_native=1 bootcpu=7 cpus=8 cpufreq=1 touchscreen=1 gpu=1 adsp=1 sound=4 wifi=1" XL_SECS=180 ./xl run```-iOS доходит до того же домашнего экрана, что и с образа в памяти (SpringBoard готов через 6,1–6,3 с против+Darwin доходит до того же домашнего экрана, что и с образа в памяти (SpringBoard готов через 6,1–6,3 с против4,5–4,6 с с образа в памяти; см. «Только APFS, как на iPhone»), и из пространства пользователя видно (`/sbin/mount`):```@@ -960,7 +960,7 @@ root_device on /private/preboot (apfs, local, read-only)ramfs on /private/var (ramfs, local)```-Как это устроено. На том ничего не пишется, поэтому то, что большой образ системы меняет в iOS, ставится вокруг+Как это устроено. На том ничего не пишется, поэтому то, что большой образ системы меняет в Darwin, ставится вокругнего при загрузке:- ядро стартует как всегда, с образа в памяти (`rd=md0` — ровно по этой строке launchd понимает, что задачи@@ -968,7 +968,7 @@ ramfs on /private/var (ramfs, local)монтирует маленький образ на `/redwood` и запускает его `init`;- `init` (`flash_root`) монтирует том на `/flash`, кладёт поверх его каталогов (bindfs) наш список заданийlaunchd, пустые `NanoLaunchDaemons` и `LaunchAngels`, `xpc` без `launchd.plist` и только наш аудиоплагин,- даёт `/Applications` 32 приложения, которые iOS ставит при первом запуске, и просит ядро сделать том корнем+ даёт `/Applications` 32 приложения, которые Darwin ставит при первом запуске, и просит ядро сделать том корнем(`sysctl kern.hakios_switch_root`, внутри — `vfs_switch_root`);- загрузочный том из памяти уезжает в `/private/preboot` тома, а `init` монтирует на его пустые `Cryptexes/OS` и`Cryptexes/App` криптексы — контейнеры 1 и 2 раздела `darwin` (`/dev/ufs_darwin,c=1`, `c=2`) или, если образ в@@ -994,7 +994,7 @@ ufs_native=1 adsp=1 sound=4`, `RC_JOBS=rc.jobs.flashsound`): «[ ok ] the firmwaтон `sound_test` — 3,00 с, 1000 Гц слева и 440 Гц справа, за ним системные звуки, усилители включаются ивыключаются вокруг каждого. В том же сеансе — чтение через отображение (подкачка страниц): `/usr/libexec`, 338файлов, 209 950 173 байта, через `read(2)` по 64 КБ — 948 мс (211 МБ/с), через отображение — 1518 мс (132 МБ/с),-сумма у обоих `978ed0d4dda1a256`, как на компьютере; за всю загрузку iOS с флеша — 144 499 поисков имён, все по+сумма у обоих `978ed0d4dda1a256`, как на компьютере; за всю загрузку Darwin с флеша — 144 499 поисков имён, все похешу (`vol_ls sysctl kern.apfs_stats`).**Несколько запросов к флешу сразу — через UEFI нельзя.** Block I/O 2 у драйвера Qualcomm есть (`ufs_probe=1`@@ -1161,7 +1161,7 @@ CACHE, WRITE BUFFER, SECURITY PROTOCOL, MODE SELECT, QUERY, задачи упрпо таймеру готовности потока и `recount`) и на каком процессоре кончилось, и по процессам — ожидания, вызовы`read(2)` и `pagein`, байты и время в них. Список заданий `userland/rc.jobs.flashlock` делит прогон на триотрезка: загрузка (до 25 с после начала списка — нашего ничего, чтобы не делить старт SpringBoard), следующие-30 с (iOS сама по себе; `vol_ls cpuload 30` смотрит загрузку процессоров) и наши проходы. Счётчики после первого+30 с (Darwin сама по себе; `vol_ls cpuload 30` смотрит загрузку процессоров) и наши проходы. Счётчики после первогоотрезка обнуляются (`vol_ls zero kern.apfs_stats`), результаты копятся в `/private/var/results` (`>>` у `init`) ипоказываются в конце (`vol_ls cat`): середину журнала ядра вытесняют строки `launchd`.@@ -1273,11 +1273,11 @@ XL_CMDLINE="root_apfs=ufs_darwin ufs=2 ufs_native=1 bootcpu=7 cpus=8 cpufreq=1 tРаньше образы порта были в своём формате packfs (`mkpackfs.py`: только чтение, сжатые куски по 64 КБ, целиком вОЗУ). Теперь packfs нет ни в ядре (`bsd/miscfs/packfs`, его строки в `vfs_conf.c` и `bsd/conf/files`, параметрконфигурации, декодер Zstandard), ни в сборке (`mkpackfs.py`, `tools/mk-zstddec.sh`): каждый образ — контейнер-APFS, и все их читает тот же драйвер APFS ядра, что и том iOS на флеше. Раскладка — как у iPhone:+APFS, и все их читает тот же драйвер APFS ядра, что и том Darwin на флеше. Раскладка — как у iPhone:-| | iPhone, iOS 16.5 | порт |+| | iPhone, Darwin userland 16.5 | порт ||---|---|---|-| системный том | System: запечатанный том на флеше | он же из раздела `darwin` (`root_apfs=ufs_darwin`, только чтение) или `system.apfs` в памяти — отобранная часть iOS 16.5 |+| системный том | System: запечатанный том на флеше | он же из раздела `darwin` (`root_apfs=ufs_darwin`, только чтение) или `system.apfs` в памяти — отобранная часть Darwin userland 16.5 || криптекс OS (общий кеш dyld) | образ `Cryptex1,SystemOS` на томе Preboot, привит (`graftdmg`) на `/private/preboot/Cryptexes/OS`, куда ведёт `/System/Cryptexes/OS` | образ Apple как есть (2,5 ГБ) — контейнер 1 раздела `darwin` на флеше, на том же месте (или второй контейнер `flashboot.apfs`: пересобранный, 1 ГБ); в `system.apfs` — каталог `/System/Cryptexes/OS` || криптекс App (службы Safari) | `Cryptex1,AppOS` на `/private/preboot/Cryptexes/App`, куда ведёт `/System/Cryptexes/App` | образ Apple байт в байт (10 МБ) — контейнер 2 раздела `darwin`, на том же месте (или третий контейнер `flashboot.apfs`); в `system.apfs` — каталог `/System/Cryptexes/App` || Preboot | том Preboot | загрузочный том `flashboot.apfs` (`stage0`, прошивки звукового процессора, точки монтирования), после смены корня — на `/private/preboot` |@@ -1316,7 +1316,7 @@ APFS, и все их читает тот же драйвер APFS ядра, чтвторое монтирование уже открытого устройства (корень с `md0` и криптексы с `md0,c=1`, `c=2`) делит с первым егоvnode;- общий кеш dyld ядро принимает (кроме корня) с тома, смонтированного в `/private/preboot/Cryptexes` — там, куда- iOS прививает криптекс OS (`bsd/vm/vm_unix.c`);+ Darwin прививает криптекс OS (`bsd/vm/vm_unix.c`);- `drivers/storage/hakios.image.c`: драйверы GPU, звукового процессора и Wi-Fi находят свои прошивки в образах APFS дисковв памяти.@@ -1324,7 +1324,7 @@ APFS, и все их читает тот же драйвер APFS ядра, чтufs_native=1`, `rc.jobs.flashcheck`):- корень на флеше (прогоны 165449 и 172245 — криптексы в памяти, 175638 и 175933 — на флеше, см. «Криптексы на- флеше»): все проверки `init`, том iOS — корень, загрузочный том на `/private/preboot`, оба криптекса на своих+ флеше»): все проверки `init`, том Darwin — корень, загрузочный том на `/private/preboot`, оба криптекса на своихместах (`mount` выше); Wi-Fi (`wifi=1`) — адрес по DHCP через 12,4–12,9 с,имя, две страницы по HTTPS (200); звук (`sound=4`) — тон, системные звуки, фанфары; батарея — 100 % от звуковогопроцессора; домашний экран рисует GPU; **Safari открывает example.com**, а его службы `SafariBookmarksSyncAgent`@@ -1332,7 +1332,7 @@ ufs_native=1`, `rc.jobs.flashcheck`):программ не было в системе);- корень в памяти (165856; 172713 — ещё и с `wifi=1 sound=4`): домашний экран, батарея, Wi-Fi, звук, Safari сослужбами из `/System/Cryptexes/App` — каталога образа системы;-- обход всего тома iOS с флеша (170142): 318 098 записей, 8 285 771 220 байт, `ceb8a53c349a011f`, ошибок 0, 17,2 с;+- обход всего тома Darwin с флеша (170142): 318 098 записей, 8 285 771 220 байт, `ceb8a53c349a011f`, ошибок 0, 17,2 с;- отпечаток флеша после каждого сеанса — тот же, что до (на флеш ничего не пишется).Цена — память. Одни и те же сеансы одним ядром (оно ещё знало packfs), образы packfs и APFS (`gpu=1 adsp=1`, без@@ -1353,7 +1353,7 @@ Wi-Fi и звука):Числа SpringBoard в разделах «Замок тома при обычной загрузке с флеша» и «read(2) через кеш страниц» сняты ещё с`battery=1` и без `gpu=1`: `battery=1` — батарея через UEFI-драйверы загрузчика, и при нём ядро не спрашивает-батарею у звукового процессора (`adsp: battmgr: not with battery=1`), так что iOS показывала не тот заряд; без+батарею у звукового процессора (`adsp: battmgr: not with battery=1`), так что Darwin показывала не тот заряд; без`gpu=1` рисует программный рендер. Все прогоны этого раздела — `gpu=1 adsp=1`.Дальше:@@ -1363,15 +1363,15 @@ Wi-Fi и звука):### Криптексы на флеше-На iPhone криптексы — файлы-образы на томе Preboot, которые iOS прививает (`graftdmg`) на+На iPhone криптексы — файлы-образы на томе Preboot, которые Darwin прививает (`graftdmg`) на`/private/preboot/Cryptexes/OS` и `App`. У порта те же образы — байт в байт, их SHA-384 те же, что в BuildManifest-IPSW, — лежат в разделе `darwin` сразу за томом iOS, контейнерами подряд, и ядро монтирует их прямо с раздела тем+IPSW, — лежат в разделе `darwin` сразу за томом Darwin, контейнерами подряд, и ядро монтирует их прямо с раздела темже способом, каким находит второй и третий контейнер образа в памяти (`/dev/ufs_darwin,c=1`, `c=2`). В памятиостаётся только загрузочный том.| блоки `darwin` (по 4 КБ) | с байта | что | sha256 ||---|---|---|---|-| 0–1 374 207 | 0 | том iOS (`rootfs.apfs`), не тронут | `9f430a58…` |+| 0–1 374 207 | 0 | том Darwin (`rootfs.apfs`), не тронут | `9f430a58…` || 1 374 208–2 039 807 | 5 628 755 968 | криптекс OS: `096-04666-078.dmg` (`Cryptex1,SystemOS`), том `SydneyF20F66.D22D221SystemCryptex` | `2279bf44…` || 2 039 808–2 042 367 | 8 355 053 568 | криптекс App: `096-03536-083.dmg` (`Cryptex1,AppOS`), том `AppCryptex` | `6b9d1f09…` || 2 042 368–5 242 874 | 8 365 539 328 | нули: контейнера 3 нет, ядро отвечает `EINVAL`; с 2 097 152 здесь лежит архив тома данных (см. «Том данных между загрузками») — единственное, куда порт пишет | |@@ -1381,14 +1381,14 @@ IPSW, — лежат в разделе `darwin` сразу за томом iOS,типа и уникальный, LBA 25374720..30617594, ничья другая запись не заходит на неё); что `sda` — логическоеустройство 0 контроллера UFS; что `/dev/block/by-name/darwin` — `sda34` с теми же номером, именем, началом иразмером в sysfs и у `blockdev`. Пишет только `dd` в `/dev/block/by-name/darwin` (имя проверяется ещё раз в той же-оболочке прямо перед `dd`), только в блоки внутри `darwin` и после тома iOS, с копии образа на телефоне, чья sha256+оболочке прямо перед `dd`), только в блоки внутри `darwin` и после тома Darwin, с копии образа на телефоне, чья sha256проверена, и читает записанное обратно. Без `DARWIN_WRITE=yes` не пишет ничего, `plan` показывает, что было бысделано, `selftest` проверяет отказы (диапазоны, номера, GPT с изменённым полем), каждая попытка — в`logs/darwin-write.log`. Порядок был такой: отпечаток флеша; `check` и `selftest`; четыре запроса за пределы (в том-iOS, на блок за концом раздела, нули в суперблок тома, криптекс OS, не помещающийся до конца) — все отказаны до+Darwin, на блок за концом раздела, нули в суперблок тома, криптекс OS, не помещающийся до конца) — все отказаны дообращения к телефону; пробная запись 1 МБ в середину свободного места, чтение обратно (и после сброса кешей),возврат нулей; оба криптекса (2,5 ГБ за 11,3 с) с чтением обратно; отпечаток флеша. Всё за пределами `darwin` —-как было, том iOS — `9f430a58…`. Ядро на флеш по-прежнему не пишет ничего.+как было, том Darwin — `9f430a58…`. Ядро на флеш по-прежнему не пишет ничего.**Что это дало.** Корень на флеше, `gpu=1 adsp=1 sound=4 wifi=1`, `rc.jobs.flashcheck`, тот же `root.apfs`:@@ -1405,11 +1405,11 @@ iOS, на блок за концом раздела, нули в суперблоткрывает example.com, а `SafariBookmarksSyncAgent` и `com.apple.Safari.History` работают из `/System/Cryptexes/App`.Обход ядром прямо с флеша (`apfs_check=6 apfs_dev=ufs_darwin[,c=N] apfs_mnt=/flash apfs_walkers=8`), против того же-на компьютере (`verify.py sum` для тома iOS, `apfs-tool census` для образов Apple), ошибок 0:+на компьютере (`verify.py sum` для тома Darwin, `apfs-tool census` для образов Apple), ошибок 0:| | записей | сумма с флеша | на компьютере | время ||---|---|---|---|---|-| том iOS (контейнер 0) | 318 098 | `ceb8a53c349a011f` | `ceb8a53c349a011f` | 17,6 с |+| том Darwin (контейнер 0) | 318 098 | `ceb8a53c349a011f` | `ceb8a53c349a011f` | 17,6 с || криптекс OS (контейнер 1) | 2093 | `25a8c994a06a8b7b` | `25a8c994a06a8b7b` | 10,8 с || криптекс App (контейнер 2) | 1047 | `df01e45a334513ee` | `df01e45a334513ee` | 0,05 с |@@ -1418,8 +1418,8 @@ iOS, на блок за концом раздела, нули в супербл### Том данных между загрузками`/private/var` — файловая система в памяти (`bsd/miscfs/ramfs`): `init` монтирует её пустой при каждой загрузке и-создаёт в ней каталоги шаблона, который iOS носит в своём образе (`sysimage/mkvarskel.py` → `sysimage/var.skel`,-`init.c`, `mount_writable`). Поэтому ничто, что iOS туда записала, не переживало ту самую загрузку, в которую+создаёт в ней каталоги шаблона, который Darwin носит в своём образе (`sysimage/mkvarskel.py` → `sysimage/var.skel`,+`init.c`, `mount_writable`). Поэтому ничто, что Darwin туда записала, не переживало ту самую загрузку, в которуюбыло записано: ни раскладка домашнего экрана (`/var/mobile/Library/SpringBoard/IconState.plist`), ни данныеприложений (`/var/mobile/Containers/Data/Application/…`), ни снимки окон, ни запечённые обои — каждая загрузкабыла «новым устройством». Том в памяти потому, что драйвер APFS ядра читает и не пишет, а оба пути ядра к@@ -1427,13 +1427,13 @@ iOS, на блок за концом раздела, нули в суперблСделан не «APFS на запись», а копия дерева. `/redwood/bin/var_store` (`userland/src/var_store.c`) упаковывает`/private/var` в простой архив и пишет его в единственное место флеша, которое принадлежит порту и которое ничто-в нём не читает, — в раздел `darwin`, за томом iOS и двумя криптексами; `init` при следующей загрузке+в нём не читает, — в раздел `darwin`, за томом Darwin и двумя криптексами; `init` при следующей загрузкераспаковывает архив поверх шаблона (`var_store=1`). Имя, которое есть и в шаблоне, и в архиве, выходит таким,каким его сохранили; что сделал шаблон, а в архиве этого нет, остаётся нетронутым.| блоки `darwin` (по 4 КБ) | с байта | что ||---|---|---|-| 0–2 042 367 | 0 | том iOS и криптексы (см. «Криптексы на флеше»); запись сюда отказана и ядром, и загрузчиком |+| 0–2 042 367 | 0 | том Darwin и криптексы (см. «Криптексы на флеше»); запись сюда отказана и ядром, и загрузчиком || 2 042 368–2 097 151 | 8 365 539 328 | свободно || 2 097 152–2 621 439 | 8 589 934 592 | слот 0 архива: заголовок (один блок), за ним архив, 2 ГиБ всего || 2 621 440–3 145 727 | 10 737 418 240 | слот 1 архива |@@ -1448,7 +1448,7 @@ iOS, на блок за концом раздела, нули в суперблможет помешать телефону загрузиться.**Что в архиве.** На каждую запись — вид (каталог, файл, символьная или жёсткая ссылка), права, владелец и-группа, флаги файла, время изменения, расширенные атрибуты (в них iOS держит метаданные контейнеров и многое+группа, флаги файла, время изменения, расширенные атрибуты (в них Darwin держит метаданные контейнеров и многоедругое) и содержимое; путь — относительно `/private/var`, и распаковка отказывается делать имя, которое ведёт заего пределы. Каталог попадает в архив дважды: перед своим содержимым и, маленькой записью, после него — иначе еговремя изменения сбивалось бы созданием того, что в нём лежит. Жёсткая ссылка — это имя и имя, под которым этот же@@ -1461,7 +1461,7 @@ inode встретился впервые. Не сохраняются соке- Блочные устройства драйвера по-прежнему не пишут вовсе: `ufs_strategy` отвечает `EROFS`, а открытие на записьотказывается, — так что ничто, что смонтировано с такого устройства, писать не может.- Записи принимает одно символьное устройство — `/dev/rufs_darwin`, — целыми блоками и только с блока 2 042 368:- том iOS, криптексы и всё за концом раздела отказываются (`EROFS`). Раздел при этом должен быть тем самым, с+ том Darwin, криптексы и всё за концом раздела отказываются (`EROFS`). Раздел при этом должен быть тем самым, скоторым порт настраивали: имя, первый LBA, число блоков, размер блока, первая логическая единица.- Загрузчик проверяет то же самое заново и вдобавок GUID типа и уникальный GUID записи GPT (те же константы, чтоу `tools/darwin-write.py`), пишет только через `BlockIo` самого раздела, который UEFI ограничивает его@@ -1497,7 +1497,7 @@ inode встретился впервые. Не сохраняются соке- **Сохранение, прерванное на середине.** Заголовок слота сначала обнуляется, архив пишется, заголовок —последним; поэтому недописанный слот просто не проходит проверку, и `load` берёт предыдущий.- **Прогон, который после сохранения продолжается.** Устройство открывается на время записи и сразу закрывается:- список запросов этого ядра возвращается в контроллер, и iOS снова читает флеш через него, а не через загрузчик.+ список запросов этого ядра возвращается в контроллер, и Darwin снова читает флеш через него, а не через загрузчик.Сохранение «каждые N секунд» тоже есть (`var_store watch N`), но по умолчанию его нет: каждое стоит 6–7 с прогонаи сотню с лишним мегабайт записи во флеш, а пока оно идёт, накопитель читается через загрузчик.@@ -1539,7 +1539,7 @@ inode встретился впервые. Не сохраняются соке- *Не писать блок, который в слоте и так лежит* — сделано: перед записью буфер сравнивается с тем, что в слоте(чтение этого накопителя в разы дешевле записи). На неизменном дереве это пропускает всё: на компьютере второе- сохранение подряд пишет 0 блоков из 1250. На живом томе — только 1024 блока из 43 000, потому что iOS+ сохранение подряд пишет 0 блоков из 1250. На живом томе — только 1024 блока из 43 000, потому что Darwinпереписывает расширенные атрибуты на месте: архив выходит той же длины и с другой контрольной суммой, хотя ниу одного файла не сдвинулось время записи.- *Складывать имена каталога по порядку*, чтобы одно и то же дерево давало одни и те же байты — сделано@@ -1559,7 +1559,7 @@ XL_CMDLINE="root_apfs=ufs_darwin ufs=2 ufs_native=1 ufs_write=1 var_store=1 boot```**Что показал телефон.** Три прогона, между каждыми двумя — настоящий холодный сброс: `./xl reboot` в Android,-снова в загрузчик, `./xl ramdisk userland/flashboot.apfs` (21 МБ за секунду) и загрузка заново. Корень iOS при+снова в загрузчик, `./xl ramdisk userland/flashboot.apfs` (21 МБ за секунду) и загрузка заново. Корень Darwin приэтом никуда не девается — он на флеше; в ОЗУ телефона между прогонами только загрузочный том.| | прогон 1 (14:51) | прогон 2 (14:56) | прогон 3 (15:06) |@@ -1575,7 +1575,7 @@ XL_CMDLINE="root_apfs=ufs_darwin ufs=2 ufs_native=1 ufs_write=1 var_store=1 boot| упаковка и запись тома | ~7 с | ~7 с | ~6 с |То есть на каждой следующей загрузке в `/private/var` лежат файлы предыдущих, с их временами: и собственный-файл-метка, который копит по строке за прогон, и то, что писала сама iOS — раскладка домашнего экрана+файл-метка, который копит по строке за прогон, и то, что писала сама Darwin — раскладка домашнего экрана(`IconState.plist`), `TodayViewArchive.plist`, `SBLastRestoreIdentifier`, контейнеры приложений.**Что показали ещё два прогона**, уже с сохранением само собой: в сценарии (`rc.jobs.persist`) не осталось ни@@ -1639,13 +1639,13 @@ XL_CMDLINE="root_apfs=ufs_darwin ufs=2 ufs_native=1 ufs_write=1 var_store=1 bootзапуска, на холодную поднимается, дальше нет. Из 199 заданий launchd, запускавшихся на холодной загрузке, 51на пятой уже не запускается, зато появился 61 другой — те, которым теперь есть с чем работать.- **Приложения не теряют своего.** 6 контейнеров на чистой системе против 156, и это те же самые 156 с теми же- идентификаторами на каждой следующей загрузке, плюс 43 группы приложений. iOS не заводит их заново.+ идентификаторами на каждой следующей загрузке, плюс 43 группы приложений. Darwin не заводит их заново.- **Связка ключей переживает перезагрузку.** Это было главным неизвестным: ключи классов защиты у порта — неSecure Enclave, а обратимое преобразование в ядре. Запись, сделанная загрузкой 1, читается загрузками 2–5дословно («written by run of 1792431023»). `keychain_test keep` пишет только если записи нет.- **Раскладка домашнего экрана держится.** На первой загрузке значок FaceTime перенесён долгим нажатием спервого места на последнее (`rwtouch drag ... GRAB`, `rc.jobs.persist1`); на пятой он там же, а остальные- подвинулись на одно место вперёд, как iOS и делает (`./xl screenshot`: `logs/home-boot1.png`,+ подвинулись на одно место вперёд, как Darwin и делает (`./xl screenshot`: `logs/home-boot1.png`,`logs/home-boot5.png`). Сам файл `IconState.plist` SpringBoard переписывает каждую загрузку — его хеш всякийраз новый, — но начинается каждая загрузка ровно с того хеша, которым кончилась предыдущая.- Цена — 8,5–9,0 с в конце каждого прогона и 168–179 МБ записи во флеш.@@ -1682,7 +1682,7 @@ device`, около 2,6 МБ), хотя место было: `vol_ls fs /privateсохранять само, `load` — распаковать, `show` — что лежит в обоих слотах, `erase` — забыть оба слота,`stamp ПУТЬ` — дописать в файл строку о том, когда (метка прогона). Сценарий `userland/rc.jobs.persist` сам несохраняет ничего: он печатает хранилище, место в томе, строки прошлых прогонов и содержимое-`/var/mobile/Library/SpringBoard` с временами, ставит свою метку и две с половиной минуты не мешает iOS.+`/var/mobile/Library/SpringBoard` с временами, ставит свою метку и две с половиной минуты не мешает Darwin.## Сборка из исходников@@ -1712,7 +1712,7 @@ xnuloader/build.sh # clang + lld-link → xnuloader/loader.efi (EFI-прiPhone X в вашем IPSW (так система узнаёт, «какой она iPhone»); в репозитории его нет. Вручную: `python3 sysimage/ipsw-member.py ВАШ.ipsw 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 играет вибрацию и отклики волнами на устройстве+MobileGestalt отвечает `DeviceSupportsClosedLoopHaptics`, и Darwin играет вибрацию и отклики волнами на устройстве«Actuator»; без него она ищет в IOKit старый вибромотор («vibrator»), которого у iPhone X нет, и не вибрирует вовсе.Из узла `/product/camera` загрузчик берёт (только с `torch=N`) одно свойство `flash` — MobileGestalt `camera-flash`,кнопка фонарика в Пункте управления; с `cam=5` сам узел есть и без него (MobileGestalt `video-camera`). С `cam=5` есть@@ -1732,16 +1732,16 @@ REST=1 userland/build.sh- `userland/root.apfs` — маленький (наш init, библиотеки-вставки, задания launchd, прошивки); едет вместе сядром (`/dev/md1`, на `/redwood`), пересобирается за секунды;-- `userland/system.apfs` — корень: отобранная часть iOS 16.5 (`sysimage/select-system.py`), криптексы OS (с кэшем+- `userland/system.apfs` — корень: отобранная часть Darwin userland 16.5 (`sysimage/select-system.py`), криптексы OS (с кэшемdyld) и App на `/System/Cryptexes`. Пересобирается только при изменении входных данных или с `SYSTEM=1`;-- `userland/flashboot.apfs` (`FLASHBOOT=1`) — то, что нужно в памяти, когда корень — том iOS на флеше: загрузочный- том и оба криптекса, три контейнера подряд (см. «iOS с корнем на флеше»).+- `userland/flashboot.apfs` (`FLASHBOOT=1`) — то, что нужно в памяти, когда корень — том Darwin на флеше: загрузочный+ том и оба криптекса, три контейнера подряд (см. «Darwin с корнем на флеше»).`CHECK=1` проверяет каждый контейнер, как только он собран (`tools/apfs/check-image.sh`): `apfsck -cw` из[apfsprogs](https://github.com/linux-apfs/apfsprogs) (скачивается и собирается при первом вызове) должен найтиего чистым, а библиотека APFS ядра (`apfs-tool census`) — прочитать каждый том ровно таким, каким был каталог.-`REST=1` добавляет ~375 штатных служб iOS «по требованию» (без них часть приложений зависает на старте;+`REST=1` добавляет ~375 штатных служб Darwin «по требованию» (без них часть приложений зависает на старте;с корнем на флеше — на семь больше, см. `FLASHBOOT=1` ниже);список исключений — `DENY` в `userland/mkjobs.py`, пропустить службу из него для опыта: `ALLOW="слово"`.Две вещи про этот список стоит знать заранее. Во-первых, демон может вести себя плохо **из-за другой строки@@ -1760,7 +1760,7 @@ REST=1 userland/build.shСписок заданий (`RC_JOBS=файл`, он же `/redwood/etc/rc.jobs`) выполняет не оболочка, а наш `init`(`run_command` в `userland/src/init.c`), и рассчитывать в нём нельзя на четыре вещи:-- **на оболочку.** В корне самой iOS 16.5 её нет вообще: `/bin` — это `df` и `ps`, и больше ничего. Строка,+- **на оболочку.** В корне самой Darwin userland 16.5 её нет вообще: `/bin` — это `df` и `ps`, и больше ничего. Строка,начинающаяся с `/bin/sh`, кончается `No such file or directory` и кодом 127. `/var/jb/bin/sh`, которыйзапускают `rc.jobs.jb` и `rc.jobs.sileo`, — оболочка префикса пакетного менеджера, и её несёт только образс `JB=1`;@@ -2198,7 +2198,7 @@ IOKit** (`IOServiceMatching`, `IOServiceGetMatchingService`, `IOServiceOpen`, `I— чего и ждёшь от обфусцированного FairPlay. **И он не спрашивает IOKit вообще**, так что заглушка`com_apple_driver_FairPlayIOKit` в ядре — а это и был напрашивающийся следующий шаг — просто не была быдостигнута. (Право `com_apple_driver_FairPlayIOKitUserClient` у него в подписи есть, оттого и казалась.)-Проверено и отброшено ещё до прогона: дело не в флаге platform binary — у iOS свои двоичные файлы+Проверено и отброшено ещё до прогона: дело не в флаге platform binary — у Darwin свои двоичные файлыподписаны ad hoc, и это ядро помечает именно такие (`bsd/kern/kern_minimac.c`), так что `fairplayd` здесьплатформенный.@@ -2248,7 +2248,7 @@ record ... MobileActivation.ErrorDomain Code=-1 "IPC Error"» из каждог`RegionInfo = LL/A`.**Телефония (`CommCenter`) — пробовали, не вышло.** Следующей по числу обращений была она: `com.apple.commcenter.xpc`-SpringBoard спрашивает десять тысяч раз за все сеансы. iOS держит два задания с одним и тем же именем и выбирает+SpringBoard спрашивает десять тысяч раз за все сеансы. Darwin держит два задания с одним и тем же именем и выбираетпо дереву устройств, и узла `baseband` у нас нет, так что launchd сам берёт `com.apple.CommCenter-noncellular` —тот вариант, который предназначен для устройства без модема. Он и берёт. CommCenter доходит далеко: отвечает на`com.apple.commcenter.xpc` и `.coretelephony.xpc` (85 и 18 ненайденных обращений за сеанс становятся нулём),@@ -2328,13 +2328,13 @@ fastboot boot ──► UEFI (Mu-Silicium, redwood) ──► xnuloader (EFI-п▼XNU (конфигурация BCM2837 как основа + своя платформа)├─ GICv3, таймер, видеоконсоль, возврат в загрузчик- ├─ APFS (образы в ОЗУ, том iOS на флеше), ramfs (/private/var, /tmp)+ ├─ APFS (образы в ОЗУ, том Darwin на флеше), ramfs (/private/var, /tmp)├─ minicrypto вместо corecrypto, заглушки AMFI и Sandbox (MAC-политики)├─ замены драйверов: IOSurface, IOMobileFramebuffer, AppleKeyStore, IONetworkStack├─ ввод: /dev/hakios-touch ◄─ Goodix GT9916 (телефон) / virtio-input (QEMU)└─ звук: /dev/hakios-audio ─► virtio-sound (QEMU) / запись в память (rec_sound)▼- launchd iOS 16.5 → logd, notifyd, cfprefsd, runningboardd, backboardd, SpringBoard, приложения+ launchd Darwin userland 16.5 → logd, notifyd, cfprefsd, runningboardd, backboardd, SpringBoard, приложения├─ в backboardd, SpringBoard и mediaserverd внедряются наши библиотеки│ (libredwood*.dylib): виртуальные HID-службы (сенсор, кнопки) и подмена│ нескольких ObjC-методов@@ -2342,12 +2342,12 @@ fastboot boot ──► UEFI (Mu-Silicium, redwood) ──► xnuloader (EFI-пмодуль CoreAudio), которое пишет смикшированный звук в /dev/hakios-audio```-Программы и библиотеки iOS (исполняемые файлы, фреймворки, общий кэш dyld) не изменены ни в одном байте: всё, чего+Программы и библиотеки Darwin (исполняемые файлы, фреймворки, общий кэш dyld) не изменены ни в одном байте: всё, чегоим не хватает, либо делает ядро (замены драйверов), либо библиотека, которую ядро подсовывает через`DYLD_INSERT_LIBRARIES` (sysctl `kern.exec_inject`) в backboardd, SpringBoard, mediaserverd и containermanagerd и-которая меняет там кое-что только в памяти. Из файлов iOS изменены два шрифта: `AppleColorEmoji-160px.ttc` и+которая меняет там кое-что только в памяти. Из файлов Darwin изменены два шрифта: `AppleColorEmoji-160px.ttc` и`PingFang.ttc` урезаны по размеру (`tools/font_trim.py`, лишние размеры и начертания выброшены), чтобы поместиться в-образ. Задания launchd собирает `userland/mkjobs.py` из заданий iOS, а настройки в `userland/var` — наши файлы.+образ. Задания launchd собирает `userland/mkjobs.py` из заданий Darwin, а настройки в `userland/var` — наши файлы.## Что где лежит@@ -2359,7 +2359,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`), тесты, сборка образов |-| `sysimage/` | добыча файлов iOS из IPSW и выбор того, что идёт в образ |+| `sysimage/` | добыча файлов Darwin из 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/` (проверки на компьютере) |@@ -2506,15 +2506,15 @@ mac80211 из Linux стоит наша станция (`wifi/lx/src/lx_80211.c`рукопожатия против точки доступа, написанной на Python). Кому нужна сеть, тот просит станцию не напрямую, ачерез ядро (`bsd/sys/hakios.sta.h`, `drivers/wifi/hakios.sta.c`: один поток, по одному вызову за раз, и списоктого, что услышало последнее сканирование): так при старте подключается сеть из файла, и так же ядро отвечает-службе Wi-Fi iOS на запросы Apple80211 (`drivers/wifi/hakios.apple80211.c`). Прерываний радио драйвер не получает: кольца+службе Wi-Fi Darwin на запросы Apple80211 (`drivers/wifi/hakios.apple80211.c`). Прерываний радио драйвер не получает: кольцаопрашивает поток, раз в миллисекунду и сразу снова, пока есть работа. Что это делает на телефоне, сказано встроке `wifi=N` таблицы параметров ядра.## Чтение APFS-Сначала корневая файловая система у нас была не APFS: `sysimage/select-system.py` выбирал нужные файлы iOS из уже+Сначала корневая файловая система у нас была не APFS: `sysimage/select-system.py` выбирал нужные файлы Darwin из ужераспакованного `sysimage/rootfs/`, а `mkpackfs.py` складывал их в наш образ `packfs` (только чтение, целиком в ОЗУ).-Чтобы ядро читало настоящий образ iOS как есть, нужен был свой APFS; теперь он — единственная файловая система+Чтобы ядро читало настоящий образ Darwin как есть, нужен был свой APFS; теперь он — единственная файловая системаобразов (см. «Только APFS, как на iPhone»). Пишется он снизу вверх, и каждый слой сначала проверяется накомпьютере — в ядро идёт только то, что уже сошлось с настоящим образом.@@ -2541,7 +2541,7 @@ tools/apfs/dmg.py extract sysimage/rootfs.dmg /куда/rootfs.apfs --apfstools/apfs/run-tests.sh /куда/rootfs.apfs```-Что в образе iOS 16.5 (`20F66`, iPhone 10,3): один том `SydneyF20F66.D22D221OS` на 5 628 755 968 байт, блок 4096 байт,+Что в образе Darwin userland 16.5 (`20F66`, iPhone 10,3): один том `SydneyF20F66.D22D221OS` на 5 628 755 968 байт, блок 4096 байт,без шифрования и без пломбы (не sealed), 142 299 файлов под 318 098 именами (остальное — жёсткие ссылки), 136 413каталогов, 2324 символьные ссылки. Сжатие только zlib и в двух видах: тип 9 — байты лежат в самом атрибуте`com.apple.decmpfs` без сжатия, тип 4 — zlib кусками по 64 КБ в `com.apple.ResourceFork`. Ни LZVN, ни LZFSE, ни@@ -2596,7 +2596,7 @@ inode с `INODE_IS_SPARSE`), поэтому чтение дырок провер```shtools/apfs/dmg.py extract sysimage/rootfs.dmg /куда/rootfs.apfs --apfs-CMDLINE="virtio_blk=1 apfs_check=1" qemu/run-ios.sh 1200 \+CMDLINE="virtio_blk=1 apfs_check=1" qemu/run-darwin.sh 1200 \-drive file=/куда/rootfs.apfs,format=raw,if=none,id=apfsd,readonly=on \-device virtio-blk-device,drive=apfsdpython3 tools/apfs/verify.py sum /куда/rootfs.apfs # с чем сравнивать@@ -2618,7 +2618,7 @@ python3 tools/apfs/verify.py sum /куда/rootfs.apfs # с чем сравсодержимого, — значит, сошлось всё это для всех 318 098 записей, и все 8,29 ГБ содержимого прочитались побайтововерно (142 299 файлов, почти все сжатые zlib, и 2324 цели ссылок). Обход занял 416 с. Ничего больше в сеансе неслучилось: ни паники, ни жалоб virtio-blk, и строка `memory:` ядра не сдвинулась от начала к концу (1451 МБ-свободно, 2803 МБ wired) — то есть чтение 8,29 ГБ не течёт ни блоками, ни vnode. iOS рядом с этим монтированием+свободно, 2803 МБ wired) — то есть чтение 8,29 ГБ не течёт ни блоками, ни vnode. Darwin рядом с этим монтированиемпродолжала загружаться до backboardd как обычно.### Отображение в память и скорость@@ -2728,7 +2728,7 @@ python3 tools/apfs/verify.py sum /куда/rootfs.apfs # с чем сравПоложить образ в раздел флеша не поможет по той же причине: читать его нечем, пока нет драйвера накопителя (этоотдельная и большая работа, зато она же дала бы порту постоянное хранение).-Зато влезает другой настоящий том APFS: **восстановительный ramdisk iOS 16.5**. Это IM4P, контейнер начинается с+Зато влезает другой настоящий том APFS: **восстановительный ramdisk Darwin userland 16.5**. Это IM4P, контейнер начинается с27-го байта — 58 880 блоков по 4096, ровно 241 172 480 байт; том называется `ramdisk`, в нём 1497 файлов, 582каталога и 307 символьных ссылок, а содержимого в них 1,24 ГБ в распакованном виде. Если отдать его ядру каккорневое устройство, его монтирует `vfs_mountroot` через `apfs_mountroot` — вторая точка входа драйвера, которой@@ -2818,7 +2818,7 @@ python3 tools/apfs/verify.py sum /куда/ramdisk.apfs # с чем сраВсе три части сняты на телефоне одним и тем же ядром, ошибок 0, недостающих блоков 0; 24,5 с, 98,5 с и 61,6 с —на одном ядре (`./xl run` без `cpus=` даёт `cpus=1`) и на частоте, какую оставил прошлый прогон. С `cpus=8cpufreq=1` и нынешним драйвером те же части проходят за 3,0, 10,4 и 7,0 с с теми же суммами (см. ниже).-То есть настоящий корневой том iOS 16.5 — тот, что нужен порту, — прочитан на живом железе целиком и совпал с хостом+То есть настоящий корневой том Darwin userland 16.5 — тот, что нужен порту, — прочитан на живом железе целиком и совпал с хостомдо байта.Чтобы до этого дойти, пришлось выяснить, почему любой обход дольше полминуты сбрасывал телефон без следа в журнале.@@ -2833,7 +2833,7 @@ cpufreq=1` и нынешним драйвером те же части прохкакой операции, и возвращается в загрузчик с журналом раньше сторожа.Отображение в память (`vnop_pagein`) этими обходами не проверяется — они читают через `vnop_read`; на телефоне-оно проверено на томе с флеша (см. «Корневой том iOS с флеша»).+оно проверено на томе с флеша (см. «Корневой том Darwin с флеша»).### Скорость чтения@@ -2889,7 +2889,7 @@ cpufreq=1` и нынешним драйвером те же части проху которого есть свободные потоки (один на томе или один из двух), получает в той же пачке распакованными ещёсемь следующих кусков — в буфер файла, откуда его следующие чтения копируют. Всё это внутри того самого запроса,в фоне ничего не идёт. Использованы все: 15 836 из 15 836.-- **Поиск имени по хешу**: `apfs_lookup` читал каталог с начала до совпадения. На iOS у записи каталога в ключе+- **Поиск имени по хешу**: `apfs_lookup` читал каталог с начала до совпадения. На Darwin у записи каталога в ключе22-битный хеш имени, и записи по нему отсортированы; для имени из ASCII это CRC-32C по имени в UTF-32LE отвсех единиц без инверсии в конце — сверено со всеми 317 749 ASCII-именами корневого тома(`tools/apfs/test_namehash.py`). Теперь и остальные: хеш любого имени — после канонической декомпозиции Unicode@@ -2923,7 +2923,7 @@ cpufreq=1` и нынешним драйвером те же части прохЧего это не говорит:- подкачка страниц (`vnop_pagein`) мерилась только с флеша, не с диска в памяти: 32 файла `/usr/sbin`, 227- подкачек, 208 МБ/с (см. «Корневой том iOS с флеша»);+ подкачек, 208 МБ/с (см. «Корневой том Darwin с флеша»);- восемь читателей упираются в малые ядра и в пробуждения ожидающих замка (ожидание 2,5–7,9 с при удержании0,2–0,6 с): само удержание уже мало, а очередь к замку остаётся;- опережающее чтение отнимает ядра у читателей, которые и сами заняты: четыре читателя с проверкой — 1756,8 МБ/с@@ -2936,7 +2936,7 @@ cpufreq=1` и нынешним драйвером те же части прохДрайвер APFS читает и не пишет, и из этого растёт остальное: `/private/var` — файловая система в памяти(`bsd/miscfs/ramfs`), которую каждая загрузка создаёт заново пустой, а чтобы хоть что-то пережило перезагрузку,дерево приходится паковать в архив и класть в раздел `darwin` мимо всякой файловой системы (ветка `persist`,-`userland/src/var_store.c`). Если APFS научится писать, не нужно ни то ни другое, а у iOS появится том данных,+`userland/src/var_store.c`). Если APFS научится писать, не нужно ни то ни другое, а у Darwin появится том данных,которого она и ждёт. Здесь — первый шаг к этому и честная мера того, сколько до остального.### Чего стоит транзакция@@ -3016,7 +3016,7 @@ APFS никогда не перезаписывает уже опубликовпотом — чтение обратно.Ещё одно правило — порта, а не APFS: том с ролью системного или preboot отвергается. Это стоит сказать вслух,-потому что остальные проверки его не ловят. Корневой том iOS 16.5 в том виде, в каком его берёт порт+потому что остальные проверки его не ловят. Корневой том Darwin userland 16.5 в том виде, в каком его берёт порт(`sysimage/rootfs.dmg`, он же записанный в `darwin`), **не запечатан**, без снимков и без метаданных целостности(`incompatible 0x8` — только нечувствительность к нормализации, роль `0x0001`): он прошёл бы любую проверку APFS,какая здесь есть. На телефоне его хранит не она, а то, куда записи вообще разрешено идти: `BLOCK_WRITE_FIRST`@@ -3035,7 +3035,7 @@ APFS никогда не перезаписывает уже опубликов| кто смотрит | что он такое ||---|---|| `apfsck -cw` | linux-apfs/apfsprogs: суммы, все деревья, битовые карты менеджера пространства против каждого блока, на который хоть что-то ссылается, счётчики ссылок, экстенты. О нас не знает ничего |-| `tools/apfs/apfs.py` | свой читатель на Python, уже сверенный с 7-Zip по всему корневому тому iOS (`verify.py`) |+| `tools/apfs/apfs.py` | свой читатель на Python, уже сверенный с 7-Zip по всему корневому тому Darwin (`verify.py`) || 7-Zip | третья реализация целиком || `apfs-tool` | ядерный `apfs_lib.c`; единственный, кто частью и есть проверяемое, поэтому никогда не свидетель в одиночку || какие блоки образа изменились | свидетель, которому читатель вообще не нужен: запись поверх себя обязана изменить блоки названного файла и ни одного блока больше |@@ -3102,7 +3102,7 @@ APFS никогда не перезаписывает уже опубликов```shpython3 tools/apfs/mkapfs.py -o apfs-work/wroot.apfs redwood=КАТАЛОГ # с обычным, несжимаемым файлом scratch-IMG=apfs-work/wroot.apfs ROOT=apfs-work/wroot.apfs QEMU_RAM_GB=4 CMDLINE="apfs_check=7 apfs_dev=md1 apfs_write_path=/scratch apfs_write_len=8192 apfs_write_byte=165" qemu/run-ios.sh 60 > logs/apfswrite.log+IMG=apfs-work/wroot.apfs ROOT=apfs-work/wroot.apfs QEMU_RAM_GB=4 CMDLINE="apfs_check=7 apfs_dev=md1 apfs_write_path=/scratch apfs_write_len=8192 apfs_write_byte=165" qemu/run-darwin.sh 60 > logs/apfswrite.log```В журнале:@@ -3131,7 +3131,7 @@ apfs-write: read back from a container opened again: 65536 bytes, hash 1b1417058### Хранилище: файлы постоянной длины вместо смещения в комментарии-Данные iOS переживают перезагрузку так: дерево `/private/var` пакуется в архив и пишется во флеш по числу,+Данные Darwin переживают перезагрузку так: дерево `/private/var` пакуется в архив и пишется во флеш по числу,записанному в комментарии, — два слота по 2 ГиБ с байта 8 589 934 592 раздела `darwin`, прямо на символьноеустройство (ветка `persist`: `userland/src/var_store.c`, `drivers/storage/hakios.ufs.c`). Запись там надёжная: еёограничивает ядро, ограничивает загрузчик, и загрузчик читает её обратно прежде чем ответить. Слабое место не@@ -3227,14 +3227,14 @@ apfs-store: read back from a container opened again: slot 0, generation 1, 40000хранилище из слотов постоянной длины на нём. Общая реализация записываемого APFS — нет, по крайней мере не какпобочная работа. Ближайшее, что осталось от хранилища до дела: ядро открывает том хранилища на `/dev/ufs_darwin`с `dev.write`, ведущим в `ufs_write()`, и `var_store` вместо смещений в разделе называет слот по имени. Том данных-iOS, которого она ждёт, — это уже другое: создание, удаление и переименование файлов, то есть транзакция на каждую+Darwin, которого она ждёт, — это уже другое: создание, удаление и переименование файлов, то есть транзакция на каждуюоперацию, менеджер пространства с очередями освобождения, деление и слияние узлов деревьев, и всё это под замкомтома, в ядре, с кешем страниц, который надо согласовать. Проба говорит, что формат для этого понят; объём — порядкатого же, что сам читатель APFS, и браться за него стоит отдельной работой, а не продолжением этой.## Про файлы Apple и лицензии-- Файлов iOS в репозитории нет: IPSW вы берёте сами, `sysimage/unpack.sh` распаковывает его на вашей машине; ничего не скачивается.+- Файлов Darwin в репозитории нет: IPSW вы берёте сами, `sysimage/unpack.sh` распаковывает его на вашей машине; ничего не скачивается.- `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/docs/u-boot.md b/docs/u-boot.mdindex 5d54fc4..c9b0d33 100644--- a/docs/u-boot.md+++ b/docs/u-boot.md@@ -156,7 +156,7 @@ Run on a POCO X5 Pro 5G (`redwood`, bootloader unlocked, Android on slot b), fro(that is what `hello` does) and the kernel returns: `result: returned 22037 0`. The loader's log is written to `logdump` and readback the same.- `./xl screenshot`: the kernel's last screen, with U-Boot's `[oosexgang]` lines under it.-- **iOS 16.5**, the images built from the IPSW (`sysimage/unpack.sh`, `PREBUILT=1 REST=1 SYSTEM=1 userland/build.sh`, `make+- **Darwin userland 16.5**, the images built from the IPSW (`sysimage/unpack.sh`, `PREBUILT=1 REST=1 SYSTEM=1 userland/build.sh`, `makeloader`), no firmware of the phone yet (no GPU: drawn in software): `./xl ramdisk userland/system.apfs` takes 2361 MB in 71 s(33 MB/s) through U-Boot, and `XL_CMDLINE="debug=0x8 rd=md0 hv_wdt_pet=1 bootcpu=7 cpus=8 cpufreq=1 ufs=2 touchscreen=1" ./xl run`brings the home screen in under a minute (the screenshot at 60 s), with touch.@@ -193,12 +193,12 @@ What was done on the POCO X5 Pro, 29 October 2026, in this order, each step chec2. **`darwin`** (`tools/userdata-carve.py --wipe DIR 20`): userdata shortened, `darwin` (sda34, 20 GiB, APFS containertype) at the end of LUN 0, two entries changed, both copies of the table checked here and with `sfdisk --sector-size4096`; written from Android (root) with `dd`, read back; then `fastboot -w` (**Android's data is erased**).-3. **The iOS volume** into `darwin`: Apple's root volume of the IPSW (`tools/apfs/dmg.py extract`), the OS and App cryptexes+3. **The Darwin volume** into `darwin`: Apple's root volume of the IPSW (`tools/apfs/dmg.py extract`), the OS and App cryptexesafter it, as the port's own layout (`docs/ru/notes.md`, "Криптексы на флеше"): 8.4 GB as 11 sparse pieces(`tools/sparse-split.py`: Google's fastboot for Windows runs out of memory on one 8 GB image), read back by U-Boot(`hakios sum darwin 0 2042368`) with the image's own sum.-4. **iOS from `darwin`, still from RAM**: `CRYPTEXES=flash FLASHBOOT=1 userland/build.sh`, `xl ramdisk userland/flashboot.apfs`,- `root_apfs=ufs_darwin ufs=2`: the iOS volume is the root, SpringBoard up.+4. **Darwin from `darwin`, still from RAM**: `CRYPTEXES=flash FLASHBOOT=1 userland/build.sh`, `xl ramdisk userland/flashboot.apfs`,+ `root_apfs=ufs_darwin ufs=2`: the Darwin volume is the root, SpringBoard up.5. **The boot image of slot a** (`tools/mkubootimg.py --install`): U-Boot, the loader, a payload with the kernel, `root.apfs`and `flashboot.apfs` as its `resident` image (the loader puts it where `xl ramdisk` would), the flash-root command line,and `devices/redwood/u-boot/install.env`; `fastboot flash boot_a`, `fastboot set_active a`.@@ -209,15 +209,15 @@ root) brings the menu back. Seen on the phone: the menu, and Android from it.### The data volume: /private/var kept, the size of the space-Without it `/private/var` is a memory filesystem: empty at every start, and iOS shows the size of that (a quarter of-the RAM, "1 GB") as the phone's storage. With it, `/private/var` is HFS Plus in `darwin` after the iOS volume and the-cryptexes (block 2042368 to the end, 12.2 GB): kept between starts, journaled, and what iOS shows is its size.+Without it `/private/var` is a memory filesystem: empty at every start, and Darwin shows the size of that (a quarter of+the RAM, "1 GB") as the phone's storage. With it, `/private/var` is HFS Plus in `darwin` after the Darwin volume and the+cryptexes (block 2042368 to the end, 12.2 GB): kept between starts, journaled, and what Darwin shows is its size.- the kernel: HFS Plus is built in (Apple's `hfs-627.100.6`, `bsd/hfs`); with `ufs_write=1` the UFS driver gives thatstretch out as `/dev/ufs_darwin_data`, which reads and writes through the loader (each write flushed and read back);- `init`: `var_hfs=ufs_darwin_data` mounts it on `/private/var`, a memory filesystem as before if it does not mount;- the empty volume, once: `tools/mkdatavol.py data.simg` and `fastboot flash darwin data.simg` (53 KB: the image says- DONT_CARE for the iOS volume and the cryptexes, and for every block the volume does not use). Flashing it again+ DONT_CARE for the Darwin volume and the cryptexes, and for every block the volume does not use). Flashing it againempties the volume;- the payload's command line gains `ufs_write=1 var_hfs=ufs_darwin_data`;- the loader serves writes to any phone's `darwin` (name, type, place, size, LUN 0; the unique GUID, which@@ -232,9 +232,9 @@ modem_buffer=0xa8000000 socinfo=1 thermal=1`. And `userland/build.sh` with `GL=1`libhakios.gl.dylib` in the image CoreAnimation draws with its software renderer whatever the GPU does -- slow, andthe wallpaper black ("Failed to initialize Metal or OpenGLES contexts!").-Tried in QEMU first (`qemu/run-hfs-test.sh`; iOS with `virtio_blk=2 var_hfs=rvblk0`): written, stopped hard, the journal+Tried in QEMU first (`qemu/run-hfs-test.sh`; Darwin with `virtio_blk=2 var_hfs=rvblk0`): written, stopped hard, the journalreplayed at the next mount, the files there. The volume's root has to be root's (`mkfs.hfsplus -U 0 -G 0 -M 755`, as-`mkdatavol.py` makes it): with another owner iOS takes it for a data volume to migrate and stays at the progress bar.+`mkdatavol.py` makes it): with another owner Darwin takes it for a data volume to migrate and stays at the progress bar.### Which slot is active is never U-Boot's to changediff --git a/docs/uefi-boot.md b/docs/uefi-boot.mdindex 6bc7cf9..5f723f9 100644--- a/docs/uefi-boot.md+++ b/docs/uefi-boot.md@@ -45,7 +45,7 @@ A file that is not a payload gives `is not a payload (no XNUP at its start)`, an## Limits- **63 MiB.** The loader's payload region is 64 MiB and its last MiB holds the panic log. The kernel is about 15 MiB;- the **big iOS system image (2.5 GB) does not come this way**. It comes over USB (`xl ramdisk`, once per loader+ the **big Darwin system image (2.5 GB) does not come this way**. It comes over USB (`xl ramdisk`, once per loadersession) or, in the flash recipe, from the partition `darwin` (`docs/install.md`).- **The region has to be free.** The loader takes all 64 MiB of it with `AllocatePages(AllocateAddress)` (not only thepages the file fills: a payload sent over USB later, and the panic log, are written into the rest). A firmware thatdiff --git a/docs/versioning.md b/docs/versioning.mdindex df6c106..26fd065 100644--- a/docs/versioning.md+++ b/docs/versioning.md@@ -62,4 +62,4 @@ A boot-argument that is removed or changes its meaning is a **VERSION** change,been seen to boot is in the README's status table and in [port-pkg110.md](port-pkg110.md).- `-dirty` means a tracked file differs from the commit. A build from a modified tree says so.- `Darwin 22.5` is a name for the open-source xnu release the kernel is built on. The kernel is not Apple's `kernel`- and is not iOS's.+ and is not Darwin's.diff --git a/drivers/README.md b/drivers/README.mdindex db92408..d6376f6 100644--- a/drivers/README.md+++ b/drivers/README.md@@ -28,7 +28,7 @@ has to be in `docs/boot-args.md` (`python3 tools/boot-args.py --check`).| `haptic/` | `hakios.haptic.c` | `haptic=` | the vibration motor || `audio/` | `hakios.adsp.c`, `hakios.audio.c`, `hakios.sound.c`, `hakios.guard.c`, `hakios.speaker.c`, `hakios.mic.c`, `hakios.virtio_sound.c` | `adsp=`, `sound=`, `mic=` | the audio DSP loader, `/dev/hakios-audio`, the speaker amplifiers and their guard (`hakios.guard.c`, until now in `storage/`), the microphone, QEMU's virtio sound || `power/` | `hakios.battery.c/.cpp`, `hakios.cpufreq.c`, `hakios.thermal.c`, `hakios.pmic.c`, `hakios.battguard.c` | `cpufreq=`, `battmgr=`, `thermal=`, `pmic=`, `battery_stop=` | battery readings (through the DSP), CPU frequency, temperature limits that hand control back to the loader, the PMIC, and an end to an unwatched run before the battery is flat (compiled only: see its head for what it was checked against) |-| `wifi/` | `hakios.wifi.c`, `hakios.wlfw.c`, `hakios.lx.c`, `hakios.sta.c`, `hakios.apple80211.c`, `hakios.wlan.cpp` | `wifi=`, `wifi_step=` | the Wi-Fi subsystem's bring-up, the WLAN firmware service, the Linux-driver layer (`wifi/lx/`) and the surface the iOS Wi-Fi service expects |+| `wifi/` | `hakios.wifi.c`, `hakios.wlfw.c`, `hakios.lx.c`, `hakios.sta.c`, `hakios.apple80211.c`, `hakios.wlan.cpp` | `wifi=`, `wifi_step=` | the Wi-Fi subsystem's bring-up, the WLAN firmware service, the Linux-driver layer (`wifi/lx/`) and the surface the Darwin Wi-Fi service expects || `bluetooth/` | `hakios.bt.c` | `bt=` | Bluetooth of the WCN6750 radio chip: step one, a look at its three pins, read only (compiled only; the rest is written down in the file's head as what it needs) || `modem/` | `hakios.mpss.c`, `hakios.cell.c`, `hakios.qmi.c`, `hakios.nas.c`, `hakios.ipa.c` | `modem=` | the cellular modem path (research; not reviewed in `docs/driver-review/`) || `net/` | `hakios.net.c`, `hakios.virtio_net.c` | | the `enN` network interface and QEMU's virtio-net |diff --git a/drivers/audio/conf b/drivers/audio/confindex a62e9eb..eeb9a3d 100644--- a/drivers/audio/conf+++ b/drivers/audio/conf@@ -3,7 +3,7 @@# tools/hakios-config.py reads this file; docs/drivers-config.md says what each word means and how it reaches XNU.standard bsd/dev/hakios.audio.c- help /dev/hakios-audio, the sound iOS plays, to whatever plays it; and where the camera, flashlight, motor+ help /dev/hakios-audio, the sound Darwin plays, to whatever plays it; and where the camera, flashlight, motorhelp and speaker drivers are started fromdriver ADSPdiff --git a/drivers/audio/hakios.adsp.c b/drivers/audio/hakios.adsp.cindex d98c3b7..c5fc819 100644--- a/drivers/audio/hakios.adsp.c+++ b/drivers/audio/hakios.adsp.c@@ -2672,7 +2672,7 @@ apr_ask(uint8_t service, uint32_t opcode, const void *payload, uint32_t length,* good). Only gets are sent from here: nothing is set, no limit, no current, no notice asked for.* With adsp=1 (battmgr=0: not) it is asked every BATTMGR_SECONDS while the DSP runs, and what it says* goes to drivers/power/hakios.battery.c (hakios_battery_report()), and from there to the power source- * that iOS reads (drivers/power/hakios.battery.cpp). battmgr=2: every property once, for the log.+ * that Darwin reads (drivers/power/hakios.battery.cpp). battmgr=2: every property once, for the log.* Units: capacity in hundredths of a percent, voltage in uV, current in uA (more than 0 while the* battery takes charge), the temperature in hundredths of a degree, charges in uAh.* The properties' numbers are this phone's firmware's, read with battmgr=2 and checked against whatdiff --git a/drivers/audio/hakios.audio.c b/drivers/audio/hakios.audio.cindex 2b5bbfc..91f784c 100644--- a/drivers/audio/hakios.audio.c+++ b/drivers/audio/hakios.audio.c@@ -1,5 +1,5 @@/*- * /dev/hakios-audio: the sound that iOS plays (see sys/hakios.audio.h).+ * /dev/hakios-audio: the sound that Darwin plays (see sys/hakios.audio.h).** What is written goes two ways:*@@ -252,7 +252,7 @@ audio_write(__unused dev_t dev, struct uio *uio, __unused int ioflag)return error;}-/* the speakers' volume, as iOS sets it (sys/hakios.audio.h): kept for the sink's driver to look at */+/* the speakers' volume, as Darwin sets it (sys/hakios.audio.h): kept for the sink's driver to look at */#define HAKIOS_AUDIO_BELOW_MAX (90 * 8) /* eighths of a dB: the amplifiers' own lowest volume (speaker.c VOLUME_LOWEST) */static uint32_t volume_below, volume_generation;static bool volume_muted;diff --git a/drivers/audio/hakios.guard.c b/drivers/audio/hakios.guard.cindex 955be01..0731597 100644--- a/drivers/audio/hakios.guard.c+++ b/drivers/audio/hakios.guard.c@@ -29,9 +29,9 @@* monitor a further reduction that the amplifiers' watch asks for (hakios.speaker.c:* Android's table for a cold amplifier, and a low battery)*- * Before all that, a gain (sound_gain, at most 12 dB): iOS's own processing for the iPhone X's+ * Before all that, a gain (sound_gain, at most 12 dB): Darwin's own processing for the iPhone X's* speaker keeps even a full-scale tone at its top volume 12.6 to 14.3 dB under full scale, so- * without it iOS at the top would stay that much under Android at the top. What it lifts over+ * without it Darwin at the top would stay that much under Android at the top. What it lifts over* full scale is held to full scale by the peak limiter (or to its lower limit), never clipped.** All the limits are in terms of the speakers: a signal at full scale with the amplifiers atdiff --git a/drivers/audio/hakios.mic.c b/drivers/audio/hakios.mic.cindex 88737f4..c574797 100644--- a/drivers/audio/hakios.mic.c+++ b/drivers/audio/hakios.mic.c@@ -109,7 +109,7 @@ say(const char *format, ...)return length;}-/* A line that says all went as it should: not said again in iOS's later recordings (mic=4), where it is the same each time. */+/* A line that says all went as it should: not said again in Darwin's later recordings (mic=4), where it is the same each time. */static bool quiet;#define note(...) do { if (!quiet) { say(__VA_ARGS__); } } while (0)@@ -1447,10 +1447,10 @@ dsp_off(void)}}-/* ---- mic=4: the microphone for iOS ------------------------------------------------------------------- */+/* ---- mic=4: the microphone for Darwin ------------------------------------------------------------------- *//*- * What the microphone hears goes into a ring, and /dev/hakios-mic gives it to iOS's audio server+ * What the microphone hears goes into a ring, and /dev/hakios-mic gives it to Darwin's audio server* (HakiosAudio.driver's device "Codec", userland/src/audio_plugin.c): 16-bit samples, one channel,* 48 kHz. The path is up only while the device is open (the audio server opens it when its input* starts and closes it when it stops), and a read never waits: it gives what has come, keeping the@@ -1465,8 +1465,8 @@ static int16_t *ring;static volatile uint64_t ring_written; /* frames put into the ring since the device was made */static uint64_t ring_read; /* frames taken from it (one reader: the audio server) */static bool ring_primed; /* the reader is RING_KEEP behind; false after it ran dry */-static uint64_t ring_skipped, ring_dry; /* frames skipped, reads that found too little: said when iOS stops */-static volatile uint32_t ios_wants; /* the device is open */+static uint64_t ring_skipped, ring_dry; /* frames skipped, reads that found too little: said when Darwin stops */+static volatile uint32_t darwin_wants; /* the device is open */static volatile bool stopping; /* the run ends (hakios_mic_dsp_down()) */static void@@ -1521,7 +1521,7 @@ mic_dev_read(__unused dev_t dev, struct uio *uio, __unused int ioflag)static intmic_dev_open(__unused dev_t dev, __unused int flags, __unused int type, __unused struct proc *p){- ios_wants = 1;+ darwin_wants = 1;return 0;}@@ -1529,7 +1529,7 @@ mic_dev_open(__unused dev_t dev, __unused int flags, __unused int type, __unusedstatic intmic_dev_close(__unused dev_t dev, __unused int flags, __unused int type, __unused struct proc *p){- ios_wants = 0;+ darwin_wants = 0;return 0;}@@ -1544,13 +1544,13 @@ static const struct cdevsw mic_cdevsw = {static uint32_t mic_secs = 10;/*- * The stream run, read for mic_secs (for_ios: while iOS has the device open): how loud it is, every- * second (for iOS: the first three, then every 30th); into the recording with rec_sound_mic=1; for- * iOS into the ring. False if it could not get going (the run refused, a read not sent, no read ever came- * back): not a failure that sets `broken', so for_ios() counts it from this.+ * The stream run, read for mic_secs (for_darwin: while Darwin has the device open): how loud it is, every+ * second (for Darwin: the first three, then every 30th); into the recording with rec_sound_mic=1; for+ * Darwin into the ring. False if it could not get going (the run refused, a read not sent, no read ever came+ * back): not a failure that sets `broken', so for_darwin() counts it from this.*/static bool-listen(bool for_ios)+listen(bool for_darwin){uint32_t run[3] = { 0, 0, 0 }, frames = 0, seconds = 0, peak = 0, periods = 0, empty = 0;int64_t sum = 0;@@ -1575,8 +1575,8 @@ listen(bool for_ios)return false;}}- if (for_ios) {- say("mic: LISTENING for iOS: %u reads of 20 ms given to the DSP\n", MIC_PERIODS);+ if (for_darwin) {+ say("mic: LISTENING for Darwin: %u reads of 20 ms given to the DSP\n", MIC_PERIODS);} else {say("mic: LISTENING: %u reads of 20 ms given to the DSP; for %u s\n", MIC_PERIODS, mic_secs);}@@ -1596,7 +1596,7 @@ listen(bool for_ios)tap = 2;}/* (`stopping' ends every kind of run: hakios_mic_dsp_down() waits for mic_lock, which is held until this returns) */- if ((for_ios ? !ios_wants : elapsed_ms >= mic_secs * 1000ull) || stopping || broken) {+ if ((for_darwin ? !darwin_wants : elapsed_ms >= mic_secs * 1000ull) || stopping || broken) {break;}if (!(read_ready & (1u << next))) {@@ -1628,7 +1628,7 @@ listen(bool for_ios)peak = a > peak ? a : peak;}frames += got;- if (for_ios) {+ if (for_darwin) {ring_put(samples, got);}if (hakios_audio_recording_mic()) {@@ -1665,7 +1665,7 @@ listen(bool for_ios)db10 = tenths - (int)((32768 - r) * 60 / 16384);}seconds++;- if (!for_ios || seconds <= 3 || seconds % 30 == 0) {+ if (!for_darwin || seconds <= 3 || seconds % 30 == 0) {say("mic: second %u: %u frames (%u periods, %u empty), level %d.%d dBFS (rms %u), peak %u, mean %lld; ""reads %u, errors %u%s%s\n", seconds, frames, periods, empty, db10 / 10, db10 < 0 ? -db10 % 10 : db10 % 10,rms, peak, sum / (int64_t)frames, reads_done, read_errors, unmuted ? "" : " (muted)",@@ -1721,11 +1721,11 @@ path_up(void)}/*- * mic=4: the path up whenever iOS opens /dev/hakios-mic, down when it closes it; after three+ * mic=4: the path up whenever Darwin opens /dev/hakios-mic, down when it closes it; after three* recordings that broke off, no more until the run ends.*/static void-for_ios(void)+for_darwin(void){int major = cdevsw_add(-1, &mic_cdevsw);unsigned recordings = 0, failures = 0;@@ -1736,12 +1736,12 @@ for_ios(void)say("mic: /dev/hakios-mic cannot be made\n");return;}- say("mic: THE MICROPHONE IS IOS'S (/dev/hakios-mic) from here on, until the run ends: it listens only while iOS records\n");+ say("mic: THE MICROPHONE IS DARWIN'S (/dev/hakios-mic) from here on, until the run ends: it listens only while Darwin records\n");while (!stopping) {uint64_t began, ns;bool failed, up;- if (!ios_wants) {+ if (!darwin_wants) {sleep_ms(20);continue;}@@ -1756,16 +1756,16 @@ for_ios(void)ring_skipped = ring_dry = 0;ring_read = __atomic_load_n(&ring_written, __ATOMIC_ACQUIRE);began = mach_absolute_time();- say("mic: iOS records (%u): the path up%s\n", recordings, quiet ? " (the lines that say all went well are not said again)" :+ say("mic: Darwin records (%u): the path up%s\n", recordings, quiet ? " (the lines that say all went well are not said again)" :"");/** (a bring-up or a start that fails without setting `broken' counts as a failure too: otherwise the three-recordings- * limit below never applies and, while iOS keeps the device open, the path is brought up and undone for ever)+ * limit below never applies and, while Darwin keeps the device open, the path is brought up and undone for ever)*/up = path_up() && listen(true);failed = broken || !up;absolutetime_to_nanoseconds(mach_absolute_time() - began, &ns);- say("mic: iOS's recording %u %s after %llu.%llu s; last: %s; %llu frames skipped as too late, %llu reads found too little\n",+ say("mic: Darwin's recording %u %s after %llu.%llu s; last: %s; %llu frames skipped as too late, %llu reads found too little\n",recordings, failed ? "BROKE OFF" : "ended", ns / NSEC_PER_SEC, ns % NSEC_PER_SEC / (NSEC_PER_SEC / 10), last_write,ring_skipped, ring_dry);undo();@@ -1776,8 +1776,8 @@ for_ios(void)say("mic: three recordings broke off: the microphone stays off until the run ends\n");break;}- /* (not again until iOS has closed the device and opened it again) */- while (ios_wants && !stopping) {+ /* (not again until Darwin has closed the device and opened it again) */+ while (darwin_wants && !stopping) {sleep_ms(20);}}@@ -1790,9 +1790,9 @@ mic_thread(__unused void *parameter, __unused wait_result_t result)say("mic: level %u: %s\n", level, level == 1 ? "a look, after the LPASS's votes and clocks; nothing written to the codec" :level == 2 ? "the codec brought up to answer on SoundWire, nothing of it set; then all undone" :level == 3 ? "the main microphone, as Android records from it, listened to; then all undone" :- "the main microphone for iOS (/dev/hakios-mic), up while iOS records");+ "the main microphone for Darwin (/dev/hakios-mic), up while Darwin records");if (level == 4) {- for_ios();+ for_darwin();} else {lck_mtx_lock(&mic_lock);if (level == 1) {diff --git a/drivers/audio/hakios.sound.c b/drivers/audio/hakios.sound.cindex add3dc8..f75fc60 100644--- a/drivers/audio/hakios.sound.c+++ b/drivers/audio/hakios.sound.c@@ -25,17 +25,17 @@* up, started once the clock runs, faded in to sound_below eighths of a dB under* Android's own level (default 160: 20 dB under, the least it may be is 0), faded* out and powered down at the end. Audible.- * sound=4 what iOS plays (/dev/hakios-audio, hakios.audio.c), until the run ends: the port- * and the stream as above, kept running (silence when iOS writes nothing); the+ * sound=4 what Darwin plays (/dev/hakios-audio, hakios.audio.c), until the run ends: the port+ * and the stream as above, kept running (silence when Darwin writes nothing); the* amplifiers set up once and powered down, started and faded in (the driver's quick* fade) whenever a write is not silence, stopped after three seconds of silence; their* level is what is set on the plug-in's volume control (ioctl HAKIOS_AUDIO_SET_VOLUME):- * so far under sound_below, which stays the loudest, and at 0 they stay off. (iOS sets+ * so far under sound_below, which stays the loudest, and at 0 they stay off. (Darwin sets* that control only once, to the top, and applies its volume to the samples itself --* see userland/src/audio_plugin.c --; at its volume 0 it writes silence, and the* amplifiers stay off for that too.) On their way the samples go through the speakers'* guard (hakios.guard.c), in place of the DSP's speaker protection that Android has:- * sound_gain eighths of a dB of gain (default and most 96, 12 dB: iOS's own processing+ * sound_gain eighths of a dB of gain (default and most 96, 12 dB: Darwin's own processing* keeps its top that far under full scale), a high-pass filter, three averages of the* power at the speakers and a peak limiter. sound_guard_as=N, for a test: the guard* reckons the amplifiers N eighths of a dB under Android's level (louder than they are)@@ -1062,7 +1062,7 @@ play(uint32_t ms, bool amplifiers)return ok;}-/* ---- sound=4: what iOS plays ------------------------------------------------------------------------------ */+/* ---- sound=4: what Darwin plays ------------------------------------------------------------------------------ *//** /dev/hakios-audio's writer (the audio server's real-time thread, hakios.audio.c) puts frames@@ -1080,12 +1080,12 @@ static int16_t ring[RING_FRAMES * 2];static volatile uint32_t ring_head, ring_tail; /* frames: written by the sink, taken by the feeder */static volatile uint64_t last_sound_us; /* when the latest write that was not silence came */static volatile bool feeder_runs, watcher_runs;-static uint64_t fed_frames, silent_frames, ios_frames;-static volatile uint32_t ios_peak; /* the largest sample since the amplifiers last started */+static uint64_t fed_frames, silent_frames, darwin_frames;+static volatile uint32_t darwin_peak; /* the largest sample since the amplifiers last started *//* From the writer's thread, under hakios.audio.c's lock: never waits. */static uint32_t-ios_sink(const int16_t *frames, uint32_t count)+darwin_sink(const int16_t *frames, uint32_t count){uint32_t head = ring_head, room = RING_FRAMES - (head - ring_tail), taken = count < room ? count : room;bool sound = false;@@ -1097,13 +1097,13 @@ ios_sink(const int16_t *frames, uint32_t count)ring[2 * ((head + i) % RING_FRAMES)] = left;ring[2 * ((head + i) % RING_FRAMES) + 1] = right;sound |= l > SILENCE || r > SILENCE;- if (l > ios_peak || r > ios_peak) {- ios_peak = l > r ? l : r;+ if (l > darwin_peak || r > darwin_peak) {+ darwin_peak = l > r ? l : r;}}OSMemoryBarrier();ring_head = head + taken;- ios_frames += taken;+ darwin_frames += taken;if (sound) {last_sound_us = now_us();}@@ -1144,7 +1144,7 @@ guard_say(const char *when, bool quiet)/* A period from the ring, the rest of it silence. */static void-period_fill_ios(unsigned period)+period_fill_darwin(unsigned period){int16_t *samples = (int16_t *)(buffer + 4096 * period);uint32_t tail = ring_tail, available = ring_head - tail, n = available < PERIOD_FRAMES ? available : PERIOD_FRAMES;@@ -1178,7 +1178,7 @@ feeder_thread(__unused void *parameter, __unused wait_result_t result)returned = 0;for (unsigned p = 0; p < PERIODS; p++) {- period_fill_ios(p);+ period_fill_darwin(p);sent += period_write(p);}while (!stopping) {@@ -1199,7 +1199,7 @@ feeder_thread(__unused void *parameter, __unused wait_result_t result)OSBitAndAtomic(~back, &returned);for (unsigned p = 0; p < PERIODS; p++) {if (back & 1u << p) {- period_fill_ios(p);+ period_fill_darwin(p);if (period_write(p)) {sent++;} else {@@ -1211,8 +1211,8 @@ feeder_thread(__unused void *parameter, __unused wait_result_t result)sleep_ms(2);}say("sound: the feeder stops: %u periods written (%u could not be sent), %u given back (%u with an error), %u underflows; "- "from iOS %llu frames came, %llu went to the DSP, %llu of silence filled in\n", sent, failed, written_done, write_errors,- underflows, ios_frames, fed_frames, silent_frames);+ "from Darwin %llu frames came, %llu went to the DSP, %llu of silence filled in\n", sent, failed, written_done, write_errors,+ underflows, darwin_frames, fed_frames, silent_frames);feeder_runs = false;thread_terminate(current_thread());}@@ -1228,7 +1228,7 @@ guard_level(uint32_t level_below)}/*- * sound_below and the volume iOS has set (`extra', eighths of a dB under it), added up: saturating, so that a+ * sound_below and the volume Darwin has set (`extra', eighths of a dB under it), added up: saturating, so that a* huge sound_below or `extra' cannot wrap the sum round to a small number, that is to a loud level.*/static uint32_t@@ -1243,7 +1243,7 @@ below_with(uint32_t extra)* The amplifiers are off. The guard goes on at their level all the same: what it lets through now reaches them* 160 ms later, behind the periods queued at the DSP, and if that is sound, they will have been started by then* (70 ms after it comes). While they are off nothing but silence comes, and the averages fall as a speaker cools.- * Only when nothing can be heard at all -- iOS's volume at 0, the amplifiers given up on -- is the guard told so.+ * Only when nothing can be heard at all -- Darwin's volume at 0, the amplifiers given up on -- is the guard told so.*/static voidguard_off(bool unheard)@@ -1255,8 +1255,8 @@ guard_off(bool unheard)}/*- * The amplifiers on while there is sound, at the volume iOS has set (hakios_audio_volume(): how- * far under the loudest, sound_below under Android's level), and off while iOS's volume is 0;+ * The amplifiers on while there is sound, at the volume Darwin has set (hakios_audio_volume(): how+ * far under the loudest, sound_below under Android's level), and off while Darwin's volume is 0;* their status looked at every 200 ms while they are on. On the sound's thread.*/static void@@ -1278,7 +1278,7 @@ watch(void)extra = extra_now;muted = muted_now;changes++;- say("sound: iOS sets the volume: %s%u.%03u dB under the loudest, which is %u.%03u dB under Android's level%s\n",+ say("sound: Darwin sets the volume: %s%u.%03u dB under the loudest, which is %u.%03u dB under Android's level%s\n",muted ? "muted (0), " : "", extra / 8, extra % 8 * 125, below / 8, below % 8 * 125,on ? (muted ? ": the amplifiers are stopped" : ": the amplifiers follow") : "");if (muted) {@@ -1296,11 +1296,11 @@ watch(void)}}if (!on && !given_up && !muted && sounded != 0 && now - sounded < 100000) {- say_when("iOS plays: the amplifiers are started");+ say_when("Darwin plays: the amplifiers are started");starts++;- ios_peak = 0;+ darwin_peak = 0;if (!hakios_speaker_start() || !hakios_speaker_volume(below_with(extra), 1)) {- say("sound: THE AMPLIFIERS DID NOT START; iOS's sound goes on to the DSP, unheard\n");+ say("sound: THE AMPLIFIERS DID NOT START; Darwin's sound goes on to the DSP, unheard\n");guard_off(true);given_up = true;} else {@@ -1316,8 +1316,8 @@ watch(void)}} else if (on && now - sounded > QUIET_BEFORE_OFF_US) {say_when("three seconds of silence: the amplifiers are stopped");- say("sound: what iOS wrote while they were on peaked at %u%% of full scale (%u)\n", ios_peak * 100 / 32768,- ios_peak);+ say("sound: what Darwin wrote while they were on peaked at %u%% of full scale (%u)\n", darwin_peak * 100 / 32768,+ darwin_peak);guard_off(false);hakios_speaker_stop();on = false;@@ -1344,7 +1344,7 @@ watch(void)sleep_ms(5);}guard_off(true);- say("sound: the watcher stops; the amplifiers were started %u times, iOS set the volume %u times%s\n", starts, changes,+ say("sound: the watcher stops; the amplifiers were started %u times, Darwin set the volume %u times%s\n", starts, changes,given_up ? ", and the amplifiers were then given up on" : "");watcher_runs = false;}@@ -1393,7 +1393,7 @@ sound_thread(__unused void *parameter, __unused wait_result_t result)thread_terminate(current_thread());}if (level == 4) {- say("sound: level 4: what iOS plays, through the port, a stream and the amplifiers, until the run ends\n");+ say("sound: level 4: what Darwin plays, through the port, a stream and the amplifiers, until the run ends\n");} else {say("sound: level %u: %s, for %u s\n", level, level == 1 ? "the speakers' TDM port" : level == 2 ?"the port and a stream with a test tone, the amplifiers off" :@@ -1438,7 +1438,7 @@ sound_thread(__unused void *parameter, __unused wait_result_t result)if (level == 4) {thread_t feeder;- announce("the amplifiers, set up from Android's Music profile, powered down until iOS plays");+ announce("the amplifiers, set up from Android's Music profile, powered down until Darwin plays");if (!hakios_speaker_prepare(acf, acf_size)) {goto out;}@@ -1452,8 +1452,8 @@ sound_thread(__unused void *parameter, __unused wait_result_t result)}thread_deallocate(feeder);watcher_runs = true;- hakios_audio_set_sink("the speakers (the audio DSP, hakios.sound.c)", ios_sink);- say("sound: WHAT IOS PLAYS GOES TO THE SPEAKERS from here on, %u.%03u dB under Android's level, until the run ends\n",+ hakios_audio_set_sink("the speakers (the audio DSP, hakios.sound.c)", darwin_sink);+ say("sound: WHAT DARWIN PLAYS GOES TO THE SPEAKERS from here on, %u.%03u dB under Android's level, until the run ends\n",below / 8, below % 8 * 125);say("sound: through the guard (hakios.guard.c): %u.%03u dB of gain first (sound_gain), then high-pass at 200 Hz; peaks ""3 dB, the 0.2 s/3 s/60 s power 6/9/12 dB under full scale at Android's level\n", gain / 8, gain % 8 * 125);diff --git a/drivers/audio/hakios.virtio_sound.c b/drivers/audio/hakios.virtio_sound.cindex d80e48b..55a095f 100644--- a/drivers/audio/hakios.virtio_sound.c+++ b/drivers/audio/hakios.virtio_sound.c@@ -1,7 +1,7 @@/** A virtio sound device as the sink of /dev/hakios-audio (see sys/hakios.audio.h).*- * Under QEMU's "virt" machine a "virtio-sound-device" plays what iOS plays: through the host's+ * Under QEMU's "virt" machine a "virtio-sound-device" plays what Darwin plays: through the host's* sound system, or into a file ("-audiodev wav"), whichever back end QEMU is given. Like the* input devices (hakios.virtio_input.c) it sits on the machine's virtio-mmio bus, which must* be the current one, not "legacy". Only with boot-arg virtio_sound=1: the bus address isdiff --git a/drivers/camera/hakios.camera.c b/drivers/camera/hakios.camera.cindex fb632f7..eca227b 100644--- a/drivers/camera/hakios.camera.c+++ b/drivers/camera/hakios.camera.c@@ -3234,10 +3234,10 @@ capture_sensor(void)}}-/* ---- cam=5: the wide camera for iOS (/dev/hakios-camera) ------------------------------------------- */+/* ---- cam=5: the wide camera for Darwin (/dev/hakios-camera) ------------------------------------------- *//*- * The sensor's frames for a program (iOS's camera stack in mediaserverd, libhakios.media.dylib), for+ * The sensor's frames for a program (Darwin's camera stack in mediaserverd, libhakios.media.dylib), for* as long as it holds /dev/hakios-camera open (sys/hakios.camera.h): the sensor powered up and* streaming at the first read after the open, everything down again at the last close, after* IDLE_MS without a read, and on any fault (and then for the rest of the run). The sequence is@@ -3268,8 +3268,8 @@ capture_sensor(void)enum { PLACE_FREE, PLACE_WRITING, PLACE_READY, PLACE_READING };-static LCK_GRP_DECLARE(ios_lck_grp, "hakios-camera");-static LCK_MTX_DECLARE(ios_lock, &ios_lck_grp);+static LCK_GRP_DECLARE(darwin_lck_grp, "hakios-camera");+static LCK_MTX_DECLARE(darwin_lock, &darwin_lck_grp);static struct {uint8_t state;uint64_t sequence, time;@@ -3277,15 +3277,15 @@ static struct {} place[RING];static vm_offset_t ring;static uint64_t ring_bytes, ring_tables_bytes, ring_place_bytes;-static uint32_t ring_frame_bytes, ios_odd_frames;-static const struct ctab_mode *ios_mode;-static uint32_t ios_mode_n, ios_line_ns;-static volatile bool ios_open, ios_streaming, ios_wanted; /* open; frames coming; a read wants them */-static uint64_t ios_last_read, ios_given, ios_frames_done, ios_writes_late;-/* reads copying from the ring now (under ios_lock): a session's end waits for them before it frees the ring */-static unsigned ios_readers;-static struct { uint32_t lines, gain, frame_lines; bool pending; uint32_t focus; bool focus_pending; } ios_ask;-static struct { uint32_t lines, gain, frame_lines; uint64_t from; } ios_now, ios_next;+static uint32_t ring_frame_bytes, darwin_odd_frames;+static const struct ctab_mode *darwin_mode;+static uint32_t darwin_mode_n, darwin_line_ns;+static volatile bool darwin_open, darwin_streaming, darwin_wanted; /* open; frames coming; a read wants them */+static uint64_t darwin_last_read, darwin_given, darwin_frames_done, darwin_writes_late;+/* reads copying from the ring now (under darwin_lock): a session's end waits for them before it frees the ring */+static unsigned darwin_readers;+static struct { uint32_t lines, gain, frame_lines; bool pending; uint32_t focus; bool focus_pending; } darwin_ask;+static struct { uint32_t lines, gain, frame_lines; uint64_t from; } darwin_now, darwin_next;/** What the frames are (boot-arg cam_pattern): 0 the sensor's picture; 1 colour bars -- the sensor's own,* where its module file has a table for them (Android's "testPatternData"), else the CSID's; 2 the@@ -3293,13 +3293,13 @@ static struct { uint32_t lines, gain, frame_lines; uint64_t from; } ios_now, ios* sensor's (its one test pattern table is empty), so cam_pattern=1 gives it the CSID's.*/enum { SOURCE_SENSOR, SOURCE_SENSOR_PATTERN, SOURCE_CSID_TPG };-static int ios_source = SOURCE_SENSOR;+static int darwin_source = SOURCE_SENSOR;/* HAKIOS_CAMERA_SENSOR: the sensor (and mode) to change to, taken between sessions */-static volatile unsigned ios_switch_to; /* 1 + the sensor's index; 0: none asked for */-static uint32_t ios_switch_mode;+static volatile unsigned darwin_switch_to; /* 1 + the sensor's index; 0: none asked for */+static uint32_t darwin_switch_mode;static uint64_t-ios_ms(void)+darwin_ms(void){uint64_t ns;@@ -3311,7 +3311,7 @@ ios_ms(void)static voidexposure_limits(uint32_t *lines, uint32_t *gain, uint32_t *frame_lines){- uint32_t shortest = ios_mode->frame_length;+ uint32_t shortest = darwin_mode->frame_length;*gain = *gain < GAIN_UNITY ? GAIN_UNITY : *gain > GAIN_MAX ? GAIN_MAX : *gain;*lines = *lines < 4 ? 4 : *lines > FRAME_LINES_MAX - EXPOSURE_MARGIN ? FRAME_LINES_MAX - EXPOSURE_MARGIN : *lines;@@ -3350,7 +3350,7 @@ exposure_write(uint32_t lines, uint32_t gain, uint32_t frame_lines)sensor_table("holdoff");break;default: {- uint32_t extra = frame_lines - ios_mode->frame_length;+ uint32_t extra = frame_lines - darwin_mode->frame_length;ok = sensor_write(0xfd, 0x01, false) && sensor_write(0x14, (uint16_t)(extra >> 8), false) &&sensor_write(0x15, (uint16_t)(extra & 0xff), false) && sensor_write(0x0e, (uint16_t)(lines >> 8), false) &&@@ -3407,27 +3407,27 @@ ring_alloc(uint32_t frame_bytes)* one; this stops ring_free() from freeing the memory under a read that is mid-copy.*/static void-ios_drain_readers(void)+darwin_drain_readers(void){- lck_mtx_lock(&ios_lock);- while (ios_readers != 0) {- (void)msleep(&ios_readers, &ios_lock, PZERO, "hakios-camera-drain", NULL);+ lck_mtx_lock(&darwin_lock);+ while (darwin_readers != 0) {+ (void)msleep(&darwin_readers, &darwin_lock, PZERO, "hakios-camera-drain", NULL);}- lck_mtx_unlock(&ios_lock);+ lck_mtx_unlock(&darwin_lock);}/* The session's end, whatever ended it: the sensor's "off", the blocks, the supplies, the memory. */static void-ios_stop(const char *why)+darwin_stop(const char *why){- lck_mtx_lock(&ios_lock);- ios_streaming = false;+ lck_mtx_lock(&darwin_lock);+ darwin_streaming = false;for (int i = 0; i < RING; i++) {place[i].state = PLACE_FREE;}- lck_mtx_unlock(&ios_lock);- wakeup(&ios_frames_done);- if (!broken && ios_source != SOURCE_CSID_TPG) {+ lck_mtx_unlock(&darwin_lock);+ wakeup(&darwin_frames_done);+ if (!broken && darwin_source != SOURCE_CSID_TPG) {(void)sensor_table("off");}af_down();@@ -3439,103 +3439,103 @@ ios_stop(const char *why)csiphy_down();titan_down();power_down();- ios_drain_readers();+ darwin_drain_readers();ring_free();- say("camera: the frames for iOS stopped (%s): %llu done, %llu given, %llu written over\n", why, ios_frames_done, ios_given,- ios_writes_late);+ say("camera: the frames for Darwin stopped (%s): %llu done, %llu given, %llu written over\n", why, darwin_frames_done, darwin_given,+ darwin_writes_late);}-static const char *ios_res(void);+static const char *darwin_res(void);static bool-ios_start(void)+darwin_start(void){uint32_t lines, gain, frame_lines;- ios_frames_done = ios_given = ios_writes_late = 0;- ios_odd_frames = 0;- if (!ring_alloc(RAW10_STRIDE(ios_mode->width) * ios_mode->height)) {+ darwin_frames_done = darwin_given = darwin_writes_late = 0;+ darwin_odd_frames = 0;+ if (!ring_alloc(RAW10_STRIDE(darwin_mode->width) * darwin_mode->height)) {return false;}- if (ios_source == SOURCE_CSID_TPG) {+ if (darwin_source == SOURCE_CSID_TPG) {/* the CSID's colour bars in the mode's size, as cam=3 makes them: no sensor, no CSIPHY */if (!titan_up() || !smmu_up() || !csid_reset() ||- !csid_config(-1, 4, 0x3210, TPG_VC, ios_mode->width, ios_mode->height, false) ||+ !csid_config(-1, 4, 0x3210, TPG_VC, darwin_mode->width, darwin_mode->height, false) ||!ife_config(FRAME_ADDRESSES, ring_frame_bytes, 0) || !tpg_start()) {return false;}- lck_mtx_lock(&ios_lock);+ lck_mtx_lock(&darwin_lock);for (int i = 0; i < RING; i++) {place[i].state = PLACE_FREE;}place[0].state = PLACE_WRITING;- lck_mtx_unlock(&ios_lock);- ios_now.lines = ios_next.lines = ios_mode->frame_length - EXPOSURE_MARGIN;- ios_now.gain = ios_next.gain = GAIN_UNITY;- ios_now.frame_lines = ios_next.frame_lines = ios_mode->frame_length;- ios_next.from = 0;- say("camera: the frames for iOS: the CSID's colour bars, %ux%u (no sensor)\n", ios_mode->width, ios_mode->height);+ lck_mtx_unlock(&darwin_lock);+ darwin_now.lines = darwin_next.lines = darwin_mode->frame_length - EXPOSURE_MARGIN;+ darwin_now.gain = darwin_next.gain = GAIN_UNITY;+ darwin_now.frame_lines = darwin_next.frame_lines = darwin_mode->frame_length;+ darwin_next.from = 0;+ say("camera: the frames for Darwin: the CSID's colour bars, %ux%u (no sensor)\n", darwin_mode->width, darwin_mode->height);return true;}- if (!power_up() || !healthy() || !read_chip_id() || !sensor_table("init") || !sensor_table(ios_res()) || !healthy() ||+ if (!power_up() || !healthy() || !read_chip_id() || !sensor_table("init") || !sensor_table(darwin_res()) || !healthy() ||!titan_up() || !smmu_up() || !csid_reset() ||- !csid_config((int)hw->csiphy, ios_mode->lanes, ctab->lane_assign & ((1u << (4 * ios_mode->lanes)) - 1), 0, ios_mode->width,- ios_mode->height, ios_mode->cphy != 0) || !ife_config(FRAME_ADDRESSES, ring_frame_bytes, 0) ||- !csiphy_up(ios_mode->lanes, ios_mode->cphy != 0, ctab->lane_assign, ios_mode->settle,- (uint64_t)ios_mode->pixel_clock * 10 / ios_mode->lanes)) {+ !csid_config((int)hw->csiphy, darwin_mode->lanes, ctab->lane_assign & ((1u << (4 * darwin_mode->lanes)) - 1), 0, darwin_mode->width,+ darwin_mode->height, darwin_mode->cphy != 0) || !ife_config(FRAME_ADDRESSES, ring_frame_bytes, 0) ||+ !csiphy_up(darwin_mode->lanes, darwin_mode->cphy != 0, ctab->lane_assign, darwin_mode->settle,+ (uint64_t)darwin_mode->pixel_clock * 10 / darwin_mode->lanes)) {return false;}- if (ios_source == SOURCE_SENSOR_PATTERN && !sensor_table("tpgon")) {+ if (darwin_source == SOURCE_SENSOR_PATTERN && !sensor_table("tpgon")) {return false;}- lck_mtx_lock(&ios_lock);+ lck_mtx_lock(&darwin_lock);for (int i = 0; i < RING; i++) {place[i].state = PLACE_FREE;}place[0].state = PLACE_WRITING;- lines = ios_ask.lines;- gain = ios_ask.gain;- frame_lines = ios_ask.frame_lines;- ios_ask.pending = false;- lck_mtx_unlock(&ios_lock);+ lines = darwin_ask.lines;+ gain = darwin_ask.gain;+ frame_lines = darwin_ask.frame_lines;+ darwin_ask.pending = false;+ lck_mtx_unlock(&darwin_lock);exposure_limits(&lines, &gain, &frame_lines);if (!sensor_table("on") || !exposure_write(lines, gain, frame_lines)) {return false;}- af_up(ios_source == SOURCE_SENSOR);- ios_now.lines = ios_next.lines = lines;- ios_now.gain = ios_next.gain = gain;- ios_now.frame_lines = ios_next.frame_lines = frame_lines;- ios_next.from = 0;- say("camera: the frames for iOS: mode %u, %ux%u, %u lines of %u ns a frame at the shortest; exposure %u lines, gain %#x, "- "frame %u lines\n", ios_mode_n, ios_mode->width, ios_mode->height, ios_mode->frame_length, ios_line_ns, lines, gain, frame_lines);+ af_up(darwin_source == SOURCE_SENSOR);+ darwin_now.lines = darwin_next.lines = lines;+ darwin_now.gain = darwin_next.gain = gain;+ darwin_now.frame_lines = darwin_next.frame_lines = frame_lines;+ darwin_next.from = 0;+ say("camera: the frames for Darwin: mode %u, %ux%u, %u lines of %u ns a frame at the shortest; exposure %u lines, gain %#x, "+ "frame %u lines\n", darwin_mode_n, darwin_mode->width, darwin_mode->height, darwin_mode->frame_length, darwin_line_ns, lines, gain, frame_lines);return true;}static void-ios_session(void)+darwin_session(void){int writing = 0, next = 0; /* (place 0's address is the write master's from ife_config(): taken at the first SOF) */uint64_t last_frame;- if (!ios_start()) {+ if (!darwin_start()) {give_up("the camera did not start");- ios_stop("it did not start");+ darwin_stop("it did not start");return;}- last_frame = ios_ms();+ last_frame = darwin_ms();blk_put(ife, "IFE", IFE_IRQ_CLEAR0, 0xffffffff, false);blk_put(ife, "IFE", IFE_IRQ_GLOBAL_CLEAR, 1, false);- lck_mtx_lock(&ios_lock);- ios_streaming = true;- ios_last_read = ios_ms();- lck_mtx_unlock(&ios_lock);- while (!broken && ios_open && ios_switch_to == 0) {+ lck_mtx_lock(&darwin_lock);+ darwin_streaming = true;+ darwin_last_read = darwin_ms();+ lck_mtx_unlock(&darwin_lock);+ while (!broken && darwin_open && darwin_switch_to == 0) {uint32_t top, bus;uint64_t now;wait_ms(1);- now = ios_ms();+ now = darwin_ms();top = rd(ife + IFE_IRQ_STATUS0);bus = rd(ife + BUS_IRQ_STATUS1);if (!(top & RDI0_SOF) && !(bus & WM0_DONE)) {@@ -3544,7 +3544,7 @@ ios_session(void)give_up("no frame for 1.5 s");break;}- if (now - ios_last_read > IDLE_MS) {+ if (now - darwin_last_read > IDLE_MS) {break;}continue;@@ -3553,34 +3553,34 @@ ios_session(void)blk_put(ife, "IFE", IFE_IRQ_GLOBAL_CLEAR, 1, false);blk_put(ife, "IFE", BUS_IRQ_CLEAR1, bus & WM0_DONE, false);blk_put(ife, "IFE", BUS_IRQ_GLOBAL_CLEAR, 1, false);- lck_mtx_lock(&ios_lock);+ lck_mtx_lock(&darwin_lock);if (bus & WM0_DONE) {uint32_t ping = rd(csid + CSID_RDI0_BYTES_PING), pong = rd(csid + CSID_RDI0_BYTES_PONG);- uint32_t data = ios_mode->width * 10 / 8 * ios_mode->height;+ uint32_t data = darwin_mode->width * 10 / 8 * darwin_mode->height;last_frame = now;- ios_frames_done++;- if ((ping != data || (pong != data && ios_frames_done > 1)) && ios_odd_frames++ < 8) {- say("camera: frame %llu: the CSID counted %u and %u bytes (the mode's frame is %u)\n", ios_frames_done, ping, pong,+ darwin_frames_done++;+ if ((ping != data || (pong != data && darwin_frames_done > 1)) && darwin_odd_frames++ < 8) {+ say("camera: frame %llu: the CSID counted %u and %u bytes (the mode's frame is %u)\n", darwin_frames_done, ping, pong,data);}- if (ios_frames_done >= ios_next.from && ios_next.from != 0) {- ios_now = ios_next;- ios_next.from = 0;+ if (darwin_frames_done >= darwin_next.from && darwin_next.from != 0) {+ darwin_now = darwin_next;+ darwin_next.from = 0;}place[writing].state = PLACE_READY;- place[writing].sequence = ios_frames_done;+ place[writing].sequence = darwin_frames_done;place[writing].time = mach_absolute_time();- place[writing].exposure_lines = ios_now.lines;- place[writing].gain = ios_now.gain;- place[writing].frame_lines = ios_now.frame_lines;+ place[writing].exposure_lines = darwin_now.lines;+ place[writing].gain = darwin_now.gain;+ place[writing].frame_lines = darwin_now.frame_lines;}if (top & RDI0_SOF) {if (next >= 0) {writing = next; /* (the address given at the last SOF, taken at this one) */next = -1;} else {- ios_writes_late++; /* no address waiting: this frame goes where the last one went */+ darwin_writes_late++; /* no address waiting: this frame goes where the last one went */}place[writing].state = PLACE_WRITING;/* the address for the frame after this one, taken at the next SOF: a whole frame's time to give it in */@@ -3596,31 +3596,31 @@ ios_session(void)blk_put(ife, "IFE", IFE_REG_UPDATE, 0x2, false);}}- bool ask = (bus & WM0_DONE) && ios_ask.pending, focus = (bus & WM0_DONE) && ios_ask.focus_pending;- uint32_t lines = ios_ask.lines, gain = ios_ask.gain, frame_lines = ios_ask.frame_lines, position = ios_ask.focus;+ bool ask = (bus & WM0_DONE) && darwin_ask.pending, focus = (bus & WM0_DONE) && darwin_ask.focus_pending;+ uint32_t lines = darwin_ask.lines, gain = darwin_ask.gain, frame_lines = darwin_ask.frame_lines, position = darwin_ask.focus;- ios_ask.pending = ios_ask.pending && !ask;- ios_ask.focus_pending = ios_ask.focus_pending && !focus;- lck_mtx_unlock(&ios_lock);+ darwin_ask.pending = darwin_ask.pending && !ask;+ darwin_ask.focus_pending = darwin_ask.focus_pending && !focus;+ lck_mtx_unlock(&darwin_lock);if (focus) {af_move(position);}if (bus & WM0_DONE) {- wakeup(&ios_frames_done);+ wakeup(&darwin_frames_done);}- if (ask && ios_source != SOURCE_CSID_TPG) {+ if (ask && darwin_source != SOURCE_CSID_TPG) {exposure_limits(&lines, &gain, &frame_lines);- if (lines != ios_now.lines || gain != ios_now.gain || frame_lines != ios_now.frame_lines) {+ if (lines != darwin_now.lines || gain != darwin_now.gain || frame_lines != darwin_now.frame_lines) {if (!exposure_write(lines, gain, frame_lines)) {break;}- ios_next.lines = lines;- ios_next.gain = gain;- ios_next.frame_lines = frame_lines;- ios_next.from = ios_frames_done + 2;+ darwin_next.lines = lines;+ darwin_next.gain = gain;+ darwin_next.frame_lines = frame_lines;+ darwin_next.from = darwin_frames_done + 2;}}- if ((bus & WM0_DONE) && ios_frames_done % 30 == 0) {+ if ((bus & WM0_DONE) && darwin_frames_done % 30 == 0) {uint32_t fsr = rd(smmu_context + SMMU_CB_FSR);if (!healthy()) {@@ -3631,12 +3631,12 @@ ios_session(void)give_up("the SMMU refused the IFE");break;}- if (ios_frames_done == 30 || ios_frames_done % 900 == 0) {+ if (darwin_frames_done == 30 || darwin_frames_done % 900 == 0) {show_paths("streaming");}}}- ios_stop(broken ? "a fault" : !ios_open ? "closed" : ios_switch_to != 0 ? "another sensor asked for" : "nobody reads");+ darwin_stop(broken ? "a fault" : !darwin_open ? "closed" : darwin_switch_to != 0 ? "another sensor asked for" : "nobody reads");}/*@@ -3688,7 +3688,7 @@ static voidfake_fill(int p, uint32_t lines, uint32_t gain){uint8_t *at = (uint8_t *)(ring + (uint64_t)p * ring_place_bytes);- uint32_t width = ios_mode->width, height = ios_mode->height, stride = RAW10_STRIDE(width), ramp_from = height * 3 / 4 & ~1u;+ uint32_t width = darwin_mode->width, height = darwin_mode->height, stride = RAW10_STRIDE(width), ramp_from = height * 3 / 4 & ~1u;uint64_t light = (uint64_t)lines * gain / GAIN_UNITY;fake_line(at, width, false, false, light);@@ -3702,7 +3702,7 @@ fake_fill(int p, uint32_t lines, uint32_t gain)}}-/* a session of cam_fake: ios_session()'s, with the chart for the sensor and a timer for its frames */+/* a session of cam_fake: darwin_session()'s, with the chart for the sensor and a timer for its frames */static voidfake_session(void){@@ -3710,46 +3710,46 @@ fake_session(void)(void)PE_parse_boot_argn("cam_fake_fps", &fps, sizeof(fps));fps = fps < 1 ? 1 : fps > 30 ? 30 : fps;- ios_frames_done = ios_given = ios_writes_late = 0;- if (!ring_alloc(RAW10_STRIDE(ios_mode->width) * ios_mode->height)) {+ darwin_frames_done = darwin_given = darwin_writes_late = 0;+ if (!ring_alloc(RAW10_STRIDE(darwin_mode->width) * darwin_mode->height)) {return;}- lck_mtx_lock(&ios_lock);+ lck_mtx_lock(&darwin_lock);for (int i = 0; i < RING; i++) {place[i].state = PLACE_FREE;place[i].sequence = 0;}- lines = ios_ask.lines;- gain = ios_ask.gain;- frame_lines = ios_ask.frame_lines;- ios_ask.pending = false;+ lines = darwin_ask.lines;+ gain = darwin_ask.gain;+ frame_lines = darwin_ask.frame_lines;+ darwin_ask.pending = false;exposure_limits(&lines, &gain, &frame_lines);- ios_now.lines = lines;- ios_now.gain = gain;- ios_now.frame_lines = frame_lines;- ios_streaming = true;- ios_last_read = ios_ms();- lck_mtx_unlock(&ios_lock);- say("camera: the frames for iOS: cam_fake's colour chart, %ux%u in %s's order, %u a second\n", ios_mode->width, ios_mode->height,+ darwin_now.lines = lines;+ darwin_now.gain = gain;+ darwin_now.frame_lines = frame_lines;+ darwin_streaming = true;+ darwin_last_read = darwin_ms();+ lck_mtx_unlock(&darwin_lock);+ say("camera: the frames for Darwin: cam_fake's colour chart, %ux%u in %s's order, %u a second\n", darwin_mode->width, darwin_mode->height,hw->chip, fps);- while (ios_open && ios_switch_to == 0) {+ while (darwin_open && darwin_switch_to == 0) {int p = -1;wait_ms(1000 / fps);- lck_mtx_lock(&ios_lock);- if (ios_ms() - ios_last_read > IDLE_MS) {- lck_mtx_unlock(&ios_lock);+ lck_mtx_lock(&darwin_lock);+ if (darwin_ms() - darwin_last_read > IDLE_MS) {+ lck_mtx_unlock(&darwin_lock);break;}- if (ios_ask.pending) {- lines = ios_ask.lines;- gain = ios_ask.gain;- frame_lines = ios_ask.frame_lines;- ios_ask.pending = false;+ if (darwin_ask.pending) {+ lines = darwin_ask.lines;+ gain = darwin_ask.gain;+ frame_lines = darwin_ask.frame_lines;+ darwin_ask.pending = false;exposure_limits(&lines, &gain, &frame_lines);- ios_now.lines = lines;- ios_now.gain = gain;- ios_now.frame_lines = frame_lines;+ darwin_now.lines = lines;+ darwin_now.gain = gain;+ darwin_now.frame_lines = frame_lines;}for (int i = 0; i < RING; i++) {if (place[i].state != PLACE_READING && (p < 0 || place[i].sequence < place[p].sequence)) {@@ -3759,45 +3759,45 @@ fake_session(void)if (p >= 0) {place[p].state = PLACE_WRITING;}- lck_mtx_unlock(&ios_lock);+ lck_mtx_unlock(&darwin_lock);if (p < 0) {- ios_writes_late++;+ darwin_writes_late++;continue;}- if (filled_lines[p] != ios_now.lines || filled_gain[p] != ios_now.gain) {- fake_fill(p, ios_now.lines, ios_now.gain);- filled_lines[p] = ios_now.lines;- filled_gain[p] = ios_now.gain;+ if (filled_lines[p] != darwin_now.lines || filled_gain[p] != darwin_now.gain) {+ fake_fill(p, darwin_now.lines, darwin_now.gain);+ filled_lines[p] = darwin_now.lines;+ filled_gain[p] = darwin_now.gain;}- lck_mtx_lock(&ios_lock);+ lck_mtx_lock(&darwin_lock);place[p].state = PLACE_READY;- place[p].sequence = ++ios_frames_done;+ place[p].sequence = ++darwin_frames_done;place[p].time = mach_absolute_time();- place[p].exposure_lines = ios_now.lines;- place[p].gain = ios_now.gain;- place[p].frame_lines = ios_now.frame_lines;- lck_mtx_unlock(&ios_lock);- wakeup(&ios_frames_done);- }- lck_mtx_lock(&ios_lock);- ios_streaming = false;+ place[p].exposure_lines = darwin_now.lines;+ place[p].gain = darwin_now.gain;+ place[p].frame_lines = darwin_now.frame_lines;+ lck_mtx_unlock(&darwin_lock);+ wakeup(&darwin_frames_done);+ }+ lck_mtx_lock(&darwin_lock);+ darwin_streaming = false;for (int i = 0; i < RING; i++) {place[i].state = PLACE_FREE;}- lck_mtx_unlock(&ios_lock);- wakeup(&ios_frames_done);- ios_drain_readers();+ lck_mtx_unlock(&darwin_lock);+ wakeup(&darwin_frames_done);+ darwin_drain_readers();ring_free();- say("camera: the frames for iOS stopped (%s): %llu done, %llu given\n", !ios_open ? "closed" : ios_switch_to != 0 ?- "another sensor asked for" : "nobody reads", ios_frames_done, ios_given);+ say("camera: the frames for Darwin stopped (%s): %llu done, %llu given\n", !darwin_open ? "closed" : darwin_switch_to != 0 ?+ "another sensor asked for" : "nobody reads", darwin_frames_done, darwin_given);}static const char *-ios_res(void)+darwin_res(void){static char res[8];- snprintf(res, sizeof(res), "res%u", ios_mode_n);+ snprintf(res, sizeof(res), "res%u", darwin_mode_n);return res;}@@ -3807,7 +3807,7 @@ camdev_open(__unused dev_t dev, __unused int flags, __unused int type, __unusedif (broken) {return EIO;}- ios_open = true;+ darwin_open = true;return 0;}@@ -3815,9 +3815,9 @@ camdev_open(__unused dev_t dev, __unused int flags, __unused int type, __unusedstatic intcamdev_close(__unused dev_t dev, __unused int flags, __unused int type, __unused struct proc *p){- ios_open = false;- ios_wanted = false;- wakeup(&ios_open);+ darwin_open = false;+ darwin_wanted = false;+ wakeup(&darwin_open);return 0;}@@ -3825,79 +3825,79 @@ static intcamdev_read(__unused dev_t dev, struct uio *uio, __unused int ioflag){struct hakios_camera_frame f;- uint64_t since = ios_ms();+ uint64_t since = darwin_ms();int b = -1, error = 0;vm_offset_t at = 0; /* the place's address and the frame's size, taken under the lock with the place */uint32_t frame_bytes = 0;- lck_mtx_lock(&ios_lock);- ios_last_read = ios_ms();- if (!ios_streaming && !ios_wanted) {- ios_wanted = true;- wakeup(&ios_open);+ lck_mtx_lock(&darwin_lock);+ darwin_last_read = darwin_ms();+ if (!darwin_streaming && !darwin_wanted) {+ darwin_wanted = true;+ wakeup(&darwin_open);}for (;;) {if (broken) {- lck_mtx_unlock(&ios_lock);+ lck_mtx_unlock(&darwin_lock);return EIO;}b = -1;for (int i = 0; i < RING; i++) {- if (place[i].state == PLACE_READY && place[i].sequence > ios_given && (b < 0 || place[i].sequence > place[b].sequence)) {+ if (place[i].state == PLACE_READY && place[i].sequence > darwin_given && (b < 0 || place[i].sequence > place[b].sequence)) {b = i;}}if (b >= 0) {break;}- if (ios_ms() - since > (ios_streaming ? 3000u : 15000u)) { /* (the sensor's tables take seconds) */- lck_mtx_unlock(&ios_lock);+ if (darwin_ms() - since > (darwin_streaming ? 3000u : 15000u)) { /* (the sensor's tables take seconds) */+ lck_mtx_unlock(&darwin_lock);return EAGAIN;}- if (!ios_streaming && !ios_wanted) {- ios_wanted = true; /* (the frames stopped meanwhile: another sensor) */- wakeup(&ios_open);+ if (!darwin_streaming && !darwin_wanted) {+ darwin_wanted = true; /* (the frames stopped meanwhile: another sensor) */+ wakeup(&darwin_open);}struct timespec ts = { 0, 100 * NSEC_PER_MSEC };- error = msleep(&ios_frames_done, &ios_lock, PZERO | PCATCH, "hakios-camera", &ts);+ error = msleep(&darwin_frames_done, &darwin_lock, PZERO | PCATCH, "hakios-camera", &ts);if (error != 0 && error != EWOULDBLOCK) {- lck_mtx_unlock(&ios_lock);+ lck_mtx_unlock(&darwin_lock);return error;}- ios_last_read = ios_ms();+ darwin_last_read = darwin_ms();}place[b].state = PLACE_READING;/** Counted as a reader in the same lock hold that chose the place (the ring is live while a place is READY):* a session's end waits for this read, so the ring is not freed under the copy below (a use-after-free).*/- ios_readers++;+ darwin_readers++;at = ring + (uint64_t)b * ring_place_bytes;frame_bytes = ring_frame_bytes;- ios_given = place[b].sequence;+ darwin_given = place[b].sequence;bzero(&f, sizeof(f));memcpy(f.magic, HAKIOS_CAMERA_MAGIC, 8);f.header_bytes = sizeof(f);- f.width = ios_mode->width;- f.height = ios_mode->height;- f.stride = RAW10_STRIDE(ios_mode->width);+ f.width = darwin_mode->width;+ f.height = darwin_mode->height;+ f.stride = RAW10_STRIDE(darwin_mode->width);f.format = 1;- f.bayer = ios_source == SOURCE_CSID_TPG ? 0 : ios_source == SOURCE_SENSOR_PATTERN ? hw->pattern_bayer : hw->bayer;+ f.bayer = darwin_source == SOURCE_CSID_TPG ? 0 : darwin_source == SOURCE_SENSOR_PATTERN ? hw->pattern_bayer : hw->bayer;f.black = 64;f.sequence = place[b].sequence;f.time = place[b].time;f.exposure_lines = place[b].exposure_lines;- f.line_ns = ios_line_ns;+ f.line_ns = darwin_line_ns;f.gain = place[b].gain;f.gain_unity = GAIN_UNITY;f.gain_max = GAIN_MAX;f.frame_lines = place[b].frame_lines;- f.frame_lines_min = ios_mode->frame_length;+ f.frame_lines_min = darwin_mode->frame_length;f.frame_lines_max = FRAME_LINES_MAX;f.margin = EXPOSURE_MARGIN;f.sensor = hw_index;f.focus = af_position;- lck_mtx_unlock(&ios_lock);+ lck_mtx_unlock(&darwin_lock);error = uiomove((caddr_t)&f, (int)MIN(sizeof(f), (size_t)uio_resid(uio)), uio);if (error == 0 && uio_resid(uio) > 0) {@@ -3922,19 +3922,19 @@ camdev_read(__unused dev_t dev, struct uio *uio, __unused int ioflag)a / 1000, b / 1000);}}- lck_mtx_lock(&ios_lock);+ lck_mtx_lock(&darwin_lock);if (place[b].state == PLACE_READING) {place[b].state = PLACE_READY;}- ios_last_read = ios_ms();- ios_readers--; /* (the copy is over: a session's end waiting to free the ring may go on) */- lck_mtx_unlock(&ios_lock);- wakeup(&ios_readers);+ darwin_last_read = darwin_ms();+ darwin_readers--; /* (the copy is over: a session's end waiting to free the ring may go on) */+ lck_mtx_unlock(&darwin_lock);+ wakeup(&darwin_readers);return error;}-/* serialises the writers of `keep' (never held together with ios_lock) */-static LCK_MTX_DECLARE(keep_lock, &ios_lck_grp);+/* serialises the writers of `keep' (never held together with darwin_lock) */+static LCK_MTX_DECLARE(keep_lock, &darwin_lck_grp);/* HAKIOS_CAMERA_KEEP: a picture for the host, in one piece of memory the loader hands over. */static int@@ -3950,7 +3950,7 @@ keep_picture(const struct hakios_camera_command *c, struct uio *uio)return ENOSPC; /* (the piece is made when the device is, while there is memory in one piece) */}/*- * One writer at a time (its own mutex: ios_lock is the capture thread's and must not wait on a user copy):+ * One writer at a time (its own mutex: darwin_lock is the capture thread's and must not wait on a user copy):* two writers would interleave one picture's header with the other's data in `keep'.*/lck_mtx_lock(&keep_lock);@@ -3964,7 +3964,7 @@ keep_picture(const struct hakios_camera_command *c, struct uio *uio)h->bayer = c->d == 1 ? hw->bayer : 0;h->frame_bytes = c->bytes;h->source = 2;- strlcpy(h->sensor, "iOS", sizeof(h->sensor));+ strlcpy(h->sensor, "Darwin", sizeof(h->sensor));int error = uiomove((caddr_t)(keep + CAM_HEADER_BYTES), (int)MIN((uint64_t)c->bytes, (uint64_t)uio_resid(uio)), uio);h->frames = error == 0 ? 1 : 0;for (vm_offset_t line = keep; line < keep + want; line += 64) {@@ -3975,7 +3975,7 @@ keep_picture(const struct hakios_camera_command *c, struct uio *uio)loader_recording[1] = want;loader_recording[2] = (uint64_t)keep;lck_mtx_unlock(&keep_lock);- say("camera: a picture from iOS for the host: %ux%u, format %u, %u bytes\n", c->a, c->b, c->d, c->bytes);+ say("camera: a picture from Darwin for the host: %ux%u, format %u, %u bytes\n", c->a, c->b, c->d, c->bytes);return error;}@@ -3989,33 +3989,33 @@ camdev_write(__unused dev_t dev, struct uio *uio, __unused int ioflag)return EINVAL;}if (c.command == HAKIOS_CAMERA_EXPOSURE) {- lck_mtx_lock(&ios_lock);- ios_ask.lines = c.a;- ios_ask.gain = c.b;- ios_ask.frame_lines = c.c;- ios_ask.pending = true;- lck_mtx_unlock(&ios_lock);+ lck_mtx_lock(&darwin_lock);+ darwin_ask.lines = c.a;+ darwin_ask.gain = c.b;+ darwin_ask.frame_lines = c.c;+ darwin_ask.pending = true;+ lck_mtx_unlock(&darwin_lock);return 0;}if (c.command == HAKIOS_CAMERA_KEEP) {return keep_picture(&c, uio);}if (c.command == HAKIOS_CAMERA_FOCUS) {- lck_mtx_lock(&ios_lock);- ios_ask.focus = c.a;- ios_ask.focus_pending = true;- lck_mtx_unlock(&ios_lock);+ lck_mtx_lock(&darwin_lock);+ darwin_ask.focus = c.a;+ darwin_ask.focus_pending = true;+ lck_mtx_unlock(&darwin_lock);return 0;}if (c.command == HAKIOS_CAMERA_SENSOR) {if (c.a >= sizeof(sensors) / sizeof(sensors[0])) {return EINVAL;}- lck_mtx_lock(&ios_lock);- ios_switch_mode = c.b;- ios_switch_to = c.a + 1;- lck_mtx_unlock(&ios_lock);- wakeup(&ios_open);+ lck_mtx_lock(&darwin_lock);+ darwin_switch_mode = c.b;+ darwin_switch_to = c.a + 1;+ lck_mtx_unlock(&darwin_lock);+ wakeup(&darwin_open);return 0;}return EINVAL;@@ -4029,7 +4029,7 @@ static const struct cdevsw camdev_cdevsw = {/** The device node, made as the thread starts (before mediaserverd does: its capture stack looks for- * cameras once, when it starts); reads wait until serve_ios() is there to answer them.+ * cameras once, when it starts); reads wait until serve_darwin() is there to answer them.*/static bool camdev_made;@@ -4048,7 +4048,7 @@ camdev_make(void)* colour bars' source (cam_pattern), the first exposure. False if the sensor cannot be used.*/static bool-ios_select(unsigned index, uint32_t mode_n)+darwin_select(unsigned index, uint32_t mode_n){select_sensor(index);if (!fake) {@@ -4071,43 +4071,43 @@ ios_select(unsigned index, uint32_t mode_n)}}}- ios_mode_n = mode_n;- ios_mode = &ctab_modes[mode_n];- if (ios_mode->lanes < 1 || ios_mode->lanes > (ios_mode->cphy ? 3u : 4u) || ios_mode->data_type != RAW10_DT ||- ios_mode->width % 4 != 0 || ios_mode->fps_milli == 0 || ios_mode->frame_length == 0 ||+ darwin_mode_n = mode_n;+ darwin_mode = &ctab_modes[mode_n];+ if (darwin_mode->lanes < 1 || darwin_mode->lanes > (darwin_mode->cphy ? 3u : 4u) || darwin_mode->data_type != RAW10_DT ||+ darwin_mode->width % 4 != 0 || darwin_mode->fps_milli == 0 || darwin_mode->frame_length == 0 ||/* (a frame_length not above the margin makes `frame_length - EXPOSURE_MARGIN' wrap; sides over 16384 make the* 32-bit frame size wrap, so the ring and the IFE's writes would disagree) */- ios_mode->frame_length <= EXPOSURE_MARGIN || ios_mode->frame_length > FRAME_LINES_MAX || ios_mode->width > 16384 ||- ios_mode->height > 16384) {+ darwin_mode->frame_length <= EXPOSURE_MARGIN || darwin_mode->frame_length > FRAME_LINES_MAX || darwin_mode->width > 16384 ||+ darwin_mode->height > 16384) {say("camera: mode %u is not what this is written for\n", mode_n);return false;}- ios_line_ns = (uint32_t)(1000000000000ull / ((uint64_t)ios_mode->fps_milli * ios_mode->frame_length));+ darwin_line_ns = (uint32_t)(1000000000000ull / ((uint64_t)darwin_mode->fps_milli * darwin_mode->frame_length));uint32_t pattern = 0, count = 0;const struct ctab_entry *tpgon;(void)PE_parse_boot_argn("cam_pattern", &pattern, sizeof(pattern));tpgon = ctab_find("tpgon", &count);- ios_source = pattern == 0 ? SOURCE_SENSOR : pattern == 1 && tpgon != NULL && count > 0 && tpgon[0].address != 0 ?+ darwin_source = pattern == 0 ? SOURCE_SENSOR : pattern == 1 && tpgon != NULL && count > 0 && tpgon[0].address != 0 ?SOURCE_SENSOR_PATTERN : SOURCE_CSID_TPG;if (pattern != 0) {- say("camera: cam_pattern=%u: %s\n", pattern, ios_source == SOURCE_SENSOR_PATTERN ? "the sensor's colour bars (its tpgon table)" :+ say("camera: cam_pattern=%u: %s\n", pattern, darwin_source == SOURCE_SENSOR_PATTERN ? "the sensor's colour bars (its tpgon table)" :"the CSID's colour bars");}/* the first exposure, until the program asks for its own: boot-args as cam=4's, else a room's */- ios_ask.lines = ios_mode->frame_length - EXPOSURE_MARGIN;- ios_ask.gain = 8 * GAIN_UNITY;- ios_ask.frame_lines = 0;- (void)PE_parse_boot_argn("cam_shutter", &ios_ask.lines, sizeof(ios_ask.lines));- (void)PE_parse_boot_argn("cam_gain", &ios_ask.gain, sizeof(ios_ask.gain));+ darwin_ask.lines = darwin_mode->frame_length - EXPOSURE_MARGIN;+ darwin_ask.gain = 8 * GAIN_UNITY;+ darwin_ask.frame_lines = 0;+ (void)PE_parse_boot_argn("cam_shutter", &darwin_ask.lines, sizeof(darwin_ask.lines));+ (void)PE_parse_boot_argn("cam_gain", &darwin_ask.gain, sizeof(darwin_ask.gain));say("camera: /dev/hakios-camera: the %s camera's frames (mode %u: %ux%u, %u.%03u frames/s at the most), whenever it is "- "read\n", hw->name, mode_n, ios_mode->width, ios_mode->height, ios_mode->fps_milli / 1000, ios_mode->fps_milli % 1000);+ "read\n", hw->name, mode_n, darwin_mode->width, darwin_mode->height, darwin_mode->fps_milli / 1000, darwin_mode->fps_milli % 1000);return true;}/* cam=5: a session whenever a read wants frames, another sensor whenever one is asked for, until a fault. */static void-serve_ios(void)+serve_darwin(void){uint32_t mode_n = ~0u;@@ -4116,36 +4116,36 @@ serve_ios(void)return;}(void)PE_parse_boot_argn("cam_mode", &mode_n, sizeof(mode_n));- if (!ios_select(hw_index, mode_n)) {+ if (!darwin_select(hw_index, mode_n)) {return;}while (!broken) {- lck_mtx_lock(&ios_lock);- while (!broken && !(ios_open && ios_wanted) && ios_switch_to == 0) {- (void)msleep(&ios_open, &ios_lock, PZERO, "hakios-camera-idle", NULL);+ lck_mtx_lock(&darwin_lock);+ while (!broken && !(darwin_open && darwin_wanted) && darwin_switch_to == 0) {+ (void)msleep(&darwin_open, &darwin_lock, PZERO, "hakios-camera-idle", NULL);}- unsigned to = ios_switch_to;+ unsigned to = darwin_switch_to;- ios_switch_to = 0;- lck_mtx_unlock(&ios_lock);+ darwin_switch_to = 0;+ lck_mtx_unlock(&darwin_lock);if (broken) {break;}if (to != 0) {/* (the last session is over: everything is down) */- if (!ios_select(to - 1, ios_switch_mode)) {+ if (!darwin_select(to - 1, darwin_switch_mode)) {give_up("a sensor that cannot be used");break;}continue;}- lck_mtx_lock(&ios_lock);- ios_wanted = false;- lck_mtx_unlock(&ios_lock);+ lck_mtx_lock(&darwin_lock);+ darwin_wanted = false;+ lck_mtx_unlock(&darwin_lock);if (fake) {fake_session();} else {- ios_session();+ darwin_session();}}say("camera: /dev/hakios-camera: no more frames in this run\n");@@ -4217,9 +4217,9 @@ camera_thread(__unused void *parameter, __unused wait_result_t result)}}if (fake) {- say("camera: cam=5 cam_fake=1: the %s camera's frames for iOS are a chart made here; nothing of the phone is touched\n",+ say("camera: cam=5 cam_fake=1: the %s camera's frames for Darwin are a chart made here; nothing of the phone is touched\n",hw->name);- serve_ios();+ serve_darwin();say("camera: done\n");thread_terminate(current_thread());}@@ -4230,7 +4230,7 @@ camera_thread(__unused void *parameter, __unused wait_result_t result)arb_core = ml_io_map(ARB_CORE_PHYS, ARB_CORE_SIZE);arb_cnfg = ml_io_map(ARB_CNFG_PHYS, ARB_CNFG_SIZE);arb_observer = ml_io_map(ARB_OBSERVER_PHYS, ARB_OBSERVER_SIZE);- say("camera: cam=%u: the %s camera%s\n", level, hw->name, level == 5 ? ": its frames for iOS" :+ say("camera: cam=%u: the %s camera%s\n", level, hw->name, level == 5 ? ": its frames for Darwin" :level == 4 ? ": its frames through its CSIPHY and RDI 0 into memory" :level == 3 ? ": the CSID's test pattern through RDI 0 into memory" :level == 2 ? ": powered up, its chip ID read, powered down" : ": a look, reading only");@@ -4242,7 +4242,7 @@ camera_thread(__unused void *parameter, __unused wait_result_t result)capture_tpg();power_down();} else if (level == 5) {- serve_ios();+ serve_darwin();power_down();} else if (level == 4) {capture_sensor();diff --git a/drivers/camera/hakios.torch.c b/drivers/camera/hakios.torch.cindex b19f57a..df83134 100644--- a/drivers/camera/hakios.torch.c+++ b/drivers/camera/hakios.torch.c@@ -20,7 +20,7 @@* read back, and any surprise ends all writing for the run. Transfers through the arbiter are made* one at a time with the buttons' driver (hakios_spmi_lock()): two at once, and it drops one.*- * What iOS's flashlight is on this machine: the loader says the camera has a flash (with torch=N,+ * What Darwin's flashlight is on this machine: the loader says the camera has a flash (with torch=N,* /product/camera "flash": MobileGestalt's camera-flash, Control Center's flashlight button), and* libhakios.media.dylib in mediaserverd hands FigFlashlight, which finds no camera here, a device* of ours whose torch level is written to /dev/hakios-torch (userland/src/inject_media.c).@@ -31,7 +31,7 @@* through it, the module's type, its registers, the PMIC's temperature alarm* torch=2 ... and the light on once at Android's torch current for torch_secs (default 2),* then off, every write read back- * torch=3 ... no light at the start; the light for iOS until the run ends: /dev/hakios-torch+ * torch=3 ... no light at the start; the light for Darwin until the run ends: /dev/hakios-torch* takes a level of 0 to 1000 (a 32-bit number; thousandths of Android's current, 0* off) and the module is set to it -- never above Android's 125 mA; a read gives* what is lit now@@ -522,7 +522,7 @@ dark(void)return ok;}-/* ---- torch=3: the light for iOS --------------------------------------------------------------------- */+/* ---- torch=3: the light for Darwin --------------------------------------------------------------------- */static volatile uint32_t wanted; /* the level asked for last, 0 to 1000 */static volatile uint32_t asked; /* how many times one was */@@ -581,14 +581,14 @@ serve(void){uint32_t applied = 0, times = 0, cut = 0;uint64_t since = 0, last_look = 0;- bool waiting_for_off = false; /* cut at the limit: dark until iOS asks for 0 */+ bool waiting_for_off = false; /* cut at the limit: dark until Darwin asks for 0 */int major = cdevsw_add(-1, &torch_cdevsw);if (major < 0 || devfs_make_node(makedev(major, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666, "hakios-torch") == NULL) {say("torch: /dev/hakios-torch cannot be made\n");return;}- say("torch: THE LIGHT IS IOS'S (/dev/hakios-torch) from here on, until the run ends: at most Android's %u mA, at most %u s "+ say("torch: THE LIGHT IS DARWIN'S (/dev/hakios-torch) from here on, until the run ends: at most Android's %u mA, at most %u s ""at a time\n", ANDROID_TORCH_MA, max_secs);while (!broken) {uint32_t want = wanted;@@ -607,9 +607,9 @@ serve(void)times++;}if (want == 0) {- note("off (iOS asked for 0)");+ note("off (Darwin asked for 0)");} else {- note("ON (iOS asked for %u of 1000; the battery %d C)", wanted, hakios_battery_temperature());+ note("ON (Darwin asked for %u of 1000; the battery %d C)", wanted, hakios_battery_temperature());}applied = want;shown = want;@@ -619,7 +619,7 @@ serve(void)}if (applied != 0 && now - since >= max_secs * 1000ull) {cut++;- note("on for %u s, the limit: off until iOS asks again", max_secs);+ note("on for %u s, the limit: off until Darwin asks again", max_secs);waiting_for_off = true;if (!dark()) {break;@@ -657,7 +657,7 @@ torch_thread(__unused void *parameter, __unused wait_result_t result)uint8_t id[2] = { 0, 0 }, revision = 0, alarm_status = 0;say("torch: level %u: %s\n", level, level == 1 ? "a look, reading only" : level == 2 ? "the light on once" :- "the light for iOS");+ "the light for Darwin");arb_core = ml_io_map(ARB_CORE_PHYS, ARB_CORE_SIZE);arb_cnfg = ml_io_map(ARB_CNFG_PHYS, ARB_CNFG_SIZE);arb_observer = ml_io_map(ARB_OBSERVER_PHYS, ARB_OBSERVER_SIZE);diff --git a/drivers/haptic/hakios.haptic.c b/drivers/haptic/hakios.haptic.cindex f5e6205..dea76bd 100644--- a/drivers/haptic/hakios.haptic.c+++ b/drivers/haptic/hakios.haptic.c@@ -27,15 +27,15 @@* haptic=3 ... and Android's configuration written (every write read back), Android's* waveforms loaded into its RAM and read back; then standby. Nothing moves.* haptic=4 ... and one short effect played (haptic_effect=N, default 1: Android's effect 0)- * haptic=5 ... configured and loaded as for 3, and instead of the effect the motor for iOS until- * the run ends: what iOS plays on its "Actuator" device (the HAL plug-in's,+ * haptic=5 ... configured and loaded as for 3, and instead of the effect the motor for Darwin until+ * the run ends: what Darwin plays on its "Actuator" device (the HAL plug-in's,* userland/src/audio_plugin.c: the system's feedbacks and vibrations, CoreHaptics'* patterns, UIKit's feedbacks) is written to /dev/hakios-haptic as samples of one- * channel, and the motor plays Android's waveforms by it: each waveform of iOS's (a+ * channel, and the motor plays Android's waveforms by it: each waveform of Darwin's (a* stretch of samples after a pause) a short tap (waveform 1), and one that goes on for* longer than a tap the waveform Android loops for vibrations (11), until it ends -- or* for HAPTIC_MAX_MS at most, after which the motor rests for as long before it plays- * again. The gain follows how loud iOS's waveform is: Android's own (0x80) from a third+ * again. The gain follows how loud Darwin's waveform is: Android's own (0x80) from a third* of full scale up, five eighths of it for the softest, never above it (gain_for()).** Limits, whatever asks: Android's own values only (its gain 0x80, its boost and drive levels, its@@ -658,19 +658,19 @@ play_effect(unsigned effect)return healthy("after playing");}-/* ---- haptic=5: the motor for iOS ------------------------------------------------------------------- */+/* ---- haptic=5: the motor for Darwin ------------------------------------------------------------------- */#define ACTIVE_US 30000 /* a write that was not silence counts for this long */#define SILENT_BELOW 256 /* of 32768: samples no larger are silence */#define TAP_US 60000 /* longer than this, and it is a vibration, not a tap */-#define SETTLE_US 8000 /* how long iOS's waveform is listened to before a tap: its loudness */-#define FOLLOW_US 20000 /* how often a vibration's strength follows iOS's */+#define SETTLE_US 8000 /* how long Darwin's waveform is listened to before a tap: its loudness */+#define FOLLOW_US 20000 /* how often a vibration's strength follows Darwin's */#define TOLD_EVENTS 24 /* the first so many taps and vibrations are each said */static volatile uint64_t heard_us; /* when the last write that was not silence came */static volatile uint64_t quiet_us; /* when the last write that was silence came */-static volatile uint64_t onset_us; /* when iOS's last waveform began: the first write not silence after a pause */+static volatile uint64_t onset_us; /* when Darwin's last waveform began: the first write not silence after a pause */static volatile uint32_t heard_peak; /* the largest sample of that waveform, or since the service last looked */static uint64_t written_frames;static unsigned taps, loops, capped; /* what has been played, for the run's end */@@ -727,9 +727,9 @@ haptic_write(__unused dev_t dev, struct uio *uio, __unused int ioflag)}/*- * A test's stand-in for iOS's waveform (hakios.mic.c, mic_tap=1: the microphone hears the motor): as if+ * A test's stand-in for Darwin's waveform (hakios.mic.c, mic_tap=1: the microphone hears the motor): as if* a write of this loudness (of 32767) had just come, or silence for 0. The service plays it with all its- * own limits, as it plays iOS's.+ * own limits, as it plays Darwin's.*/voidhakios_haptic_pretend(uint32_t peak)@@ -801,7 +801,7 @@ chip_state(void)}/*- * How strong to play what iOS plays. iOS drives its Taptic Engine with waveforms far under full+ * How strong to play what Darwin plays. Darwin drives its Taptic Engine with waveforms far under full* scale for most feedbacks (a tap's peak anywhere from 1000 to 33000 of 32768, a vibration's* about 17000), and followed in proportion (gain = Android's * peak / full scale) most of them came* out at a tenth of Android's gain or less: not felt at all. Android plays its own clicks and@@ -829,7 +829,7 @@ serve(void)say("haptic: /dev/hakios-haptic cannot be made\n");return;}- say("haptic: THE MOTOR PLAYS WHAT IOS PLAYS ON ITS ACTUATOR (/dev/hakios-haptic) from here on, until the run ends\n");+ say("haptic: THE MOTOR PLAYS WHAT DARWIN PLAYS ON ITS ACTUATOR (/dev/hakios-haptic) from here on, until the run ends\n");while (!broken) {uint64_t now = now_us();bool active = heard_us != 0 && now - heard_us < ACTIVE_US;@@ -840,7 +840,7 @@ serve(void)case IDLE:case TAP:/*- * A waveform of iOS's that has begun (after a pause: a tap of a series is a tap of its own) is+ * A waveform of Darwin's that has begun (after a pause: a tap of a series is a tap of its own) is* a tap -- once its first milliseconds are heard: a waveform begins softly, and they say how* loud it is; one that goes on without a pause, a vibration.*/@@ -859,7 +859,7 @@ serve(void)taps++;if (taps + loops <= TOLD_EVENTS) {wait_ms(4);- say("haptic: tap %u: iOS's waveform peaks at %u of 32768: Android's waveform 1 at gain %#04x; the "+ say("haptic: tap %u: Darwin's waveform peaks at %u of 32768: Android's waveform 1 at gain %#04x; the ""chip's state %u\n", taps, peak, gain ? gain : 1, chip_state());}break;@@ -877,7 +877,7 @@ serve(void)heard_peak = 0;if (taps + loops <= TOLD_EVENTS) {wait_ms(4);- say("haptic: vibration %u: iOS goes on playing (peak %u): Android's waveform 11 over and over at "+ say("haptic: vibration %u: Darwin goes on playing (peak %u): Android's waveform 11 over and over at ""gain %#04x, %u ms at most; the chip's state %u\n", loops, peak, gain ? gain : 1,HAPTIC_MAX_MS, chip_state());}@@ -887,7 +887,7 @@ serve(void)}break;case LOOP:- /* as strong as iOS's waveform is now (Android's gain at full scale, never more) */+ /* as strong as Darwin's waveform is now (Android's gain at full scale, never more) */if (active && now - followed >= FOLLOW_US) {followed = now;heard_peak = 0;@@ -910,7 +910,7 @@ serve(void)state = rest_until > now ? REST : IDLE;if (taps + loops <= TOLD_EVENTS + 1) {say("haptic: vibration %u: %s after %llu ms (its strength changed %u times, last to gain %#04x); "- "the chip is in standby\n", loops, cut ? "CUT at the limit" : "iOS stopped, and so does the motor",+ "the chip is in standby\n", loops, cut ? "CUT at the limit" : "Darwin stopped, and so does the motor",(now - since) / 1000, follows, playing_gain);}}@@ -942,7 +942,7 @@ haptic_thread(__unused void *parameter, __unused wait_result_t result)tlmm = ml_io_map(TLMM_PHYS, TLMM_SIZE);say("haptic: level %u: %s\n", level, level == 1 ? "a look, reading only" : level == 2 ? "the reset released, registers read" :level == 3 ? "the chip configured and its waveforms loaded, nothing played" : level == 4 ? "one effect played" :- "the motor for iOS");+ "the motor for Darwin");show_pins();if (level >= 2 && !((rd(GPIO_CFG(PIN_RESET)) & CFG_OUTPUT) && (rd(GPIO_IO(PIN_RESET)) & 2))) {/* (Android's driver: the pin low, 5 ms, high, and the chip ready for I2C 8 ms later) */@@ -1005,7 +1005,7 @@ hakios_haptic_quiesce(void)leaving = true;reset_pin(false);if (level == 5) {- say("haptic: at the run's end: %u taps and %u vibrations played (%u cut at %u ms), from %llu frames iOS "+ say("haptic: at the run's end: %u taps and %u vibrations played (%u cut at %u ms), from %llu frames Darwin ""wrote; the chip is held in reset\n", taps, loops, capped, HAPTIC_MAX_MS, written_frames);}}diff --git a/drivers/modem/hakios.cell.c b/drivers/modem/hakios.cell.cindex 21dfcaa..1a45081 100644--- a/drivers/modem/hakios.cell.c+++ b/drivers/modem/hakios.cell.c@@ -1,7 +1,7 @@/*- * en1: the modem's packets as a network interface iOS will use.+ * en1: the modem's packets as a network interface Darwin will use.*- * iOS's own cellular interface (pdp_ip0) is made by its baseband stack, which is not here. What+ * Darwin's own cellular interface (pdp_ip0) is made by its baseband stack, which is not here. What* is here is the kernel's Ethernet-looking interface (hakios.net.c) and configd, which treats an* Ethernet interface whose link comes up the way it treats a USB Ethernet adapter: it runs DHCP* on it, takes the address, the router and the DNS servers it is given, and routes through it.diff --git a/drivers/net/hakios.net.c b/drivers/net/hakios.net.cindex 955e542..5c42b95 100644--- a/drivers/net/hakios.net.c+++ b/drivers/net/hakios.net.c@@ -1,11 +1,11 @@/*- * en0: a network interface that is Ethernet as far as the rest of the kernel and iOS can tell.+ * en0: a network interface that is Ethernet as far as the rest of the kernel and Darwin can tell.*- * iOS expects its interfaces from IONetworkingFamily, which this kernel does not have; the BSD+ * Darwin expects its interfaces from IONetworkingFamily, which this kernel does not have; the BSD* half of the kernel does not need it. The interface is made with the kernel's own interface* KPI, the way bsd/net/if_fake.c makes its "feth": family Ethernet, the stock Ethernet framing* and demultiplexing, one function that is given a frame to send and one call to hand a frame- * that has arrived to the stack. What iOS's user space makes of an interface that has no+ * that has arrived to the stack. What Darwin's user space makes of an interface that has no* IOKit object behind it is another matter: see userland/src/net_test.m.** What carries the frames is a link driver's business; sys/hakios.net.h is all that the two@@ -222,7 +222,7 @@ net_ioctl(ifnet_t ifp, u_long command, void *data)if (n->link->wireless && net_ioctls_said < 80) {char who[32] = "?";- /* (while iOS's Wi-Fi side is being got to talk to this: who asks the interface what) */+ /* (while Darwin's Wi-Fi side is being got to talk to this: who asks the interface what) */proc_selfname(who, sizeof(who));if (strcmp(who, "configd") != 0) {net_ioctls_said++;@@ -262,7 +262,7 @@ net_ioctl(ifnet_t ifp, u_long command, void *data)case SIOCDELMULTI:break; /* the link hands us everything anyway */default:- /* what iOS's Wi-Fi side asks of a radio's interface: drivers/wifi/hakios.apple80211.c */+ /* what Darwin's Wi-Fi side asks of a radio's interface: drivers/wifi/hakios.apple80211.c */error = n->link->wireless ? hakios_apple80211_ioctl(command, data) : EOPNOTSUPP;break;}@@ -406,7 +406,7 @@ hakios_net_attach(const struct hakios_net_link *link)net_link_event(ifp, KEV_DL_LINK_ON);}if (link->wireless) {- /* (a radio's address is the phone's own: not for the log; and iOS's Wi-Fi side finds the interface by a service) */+ /* (a radio's address is the phone's own: not for the log; and Darwin's Wi-Fi side finds the interface by a service) */printf("net: en%u attached on %s (a radio), link %s\n", unit, link->name, n->up ? "up" : "down");HakiosWLANStart(uniqueid + 7, address);} else {diff --git a/drivers/net/hakios.virtio_net.c b/drivers/net/hakios.virtio_net.cindex 2706ba0..9b5411d 100644--- a/drivers/net/hakios.virtio_net.c+++ b/drivers/net/hakios.virtio_net.c@@ -3,7 +3,7 @@** "-device virtio-net-device" on the virt machine's virtio-mmio bus, which must be the current* one, not "legacy" (-global virtio-mmio.force-legacy=false), with any "-netdev" behind it;- * qemu/run-ios.sh does that with QEMU_NET=1. Only with boot-arg virtio_net=1: the bus address is+ * qemu/run-darwin.sh does that with QEMU_NET=1. Only with boot-arg virtio_net=1: the bus address is* QEMU's and means nothing on the phone.** Nothing of what the device offers is taken (no checksums or segmentation left to it, nodiff --git a/drivers/power/conf b/drivers/power/confindex 0820423..4993f85 100644--- a/drivers/power/conf+++ b/drivers/power/conf@@ -5,7 +5,7 @@driver BATTERYfile bsd/dev/hakios.battery.cfile iokit/Kernel/hakios.battery.cpp iokitcpp- help the battery: kern.hakios.battery_*, and HakiosBattery, the IOPMPowerSource iOS reads the charge from+ help the battery: kern.hakios.battery_*, and HakiosBattery, the IOPMPowerSource Darwin reads the charge fromhelp (the state comes from the audio DSP's battery manager, with adsp=1)driver CPUFREQdiff --git a/drivers/power/hakios.battery.c b/drivers/power/hakios.battery.cindex 19c8344..54acd33 100644--- a/drivers/power/hakios.battery.c+++ b/drivers/power/hakios.battery.c@@ -113,7 +113,7 @@ battery_poll(void)/** What the audio DSP's battery manager says (drivers/audio/hakios.adsp.c, with adsp=1 unless battmgr=0):* the values that Android shows, from where Android takes them. They are kept here for the sysctls- * and passed on to the power source that iOS reads (drivers/power/hakios.battery.cpp).+ * and passed on to the power source that Darwin reads (drivers/power/hakios.battery.cpp).*/static int battery_full_uah, battery_design_uah, battery_cycles, battery_source_dsp;diff --git a/drivers/power/hakios.battery.cpp b/drivers/power/hakios.battery.cppindex 88abe5d..cbc26e4 100644--- a/drivers/power/hakios.battery.cpp+++ b/drivers/power/hakios.battery.cpp@@ -1,5 +1,5 @@/*- * HakiosBattery: the phone's battery as iOS looks for it, an IOPMPowerSource.+ * HakiosBattery: the phone's battery as Darwin looks for it, an IOPMPowerSource.** powerd finds every service of the class IOPMPowerSource (it calls the first "InternalBattery-0"),* listens for its kIOPMMessageBatteryStatusHasChanged and then reads its properties: whether a@@ -96,7 +96,7 @@ HakiosBattery::object(const char * key, OSObject * value)}/*- * What iOS calls the charger by (IOPSKeysPrivate.h's kIOPSFamilyCode*, iokit_family_err(sub_iokit_usb, n)),+ * What Darwin calls the charger by (IOPSKeysPrivate.h's kIOPSFamilyCode*, iokit_family_err(sub_iokit_usb, n)),* from Linux's POWER_SUPPLY_USB_TYPE_*, as the DSP gives it.*/static unsigneddiff --git a/drivers/storage/hakios.apfs_check.c b/drivers/storage/hakios.apfs_check.cindex 716aa8c..3cfa631 100644--- a/drivers/storage/hakios.apfs_check.c+++ b/drivers/storage/hakios.apfs_check.c@@ -1732,9 +1732,9 @@ apfs_check_runner(void *arg, wait_result_t wr)/** sysctl kern.hakios_switch_root="INCOMING OUTGOING": the volume mounted on INCOMING* becomes the root, and what was the root until now is mounted on OUTGOING inside it (a- * path without a leading slash, which must be a directory there -- on the iOS volume, a+ * path without a leading slash, which must be a directory there -- on the Darwin volume, a* synthetic one). devfs stays on /dev (vfs_switch_root() keeps it there). This is how- * the iOS root volume on the phone's flash becomes the root: the kernel starts from the+ * the Darwin root volume on the phone's flash becomes the root: the kernel starts from the* small image, whose init mounts the volume, puts in place what the system needs on it* and then asks for this (userland/src/init.c, boot-arg root_apfs=). Process 1 only, once.*/@@ -1783,15 +1783,15 @@ SYSCTL_PROC(_kern, OID_AUTO, hakios_switch_root, CTLTYPE_STRING | CTLFLAG_RW | C/** apfs_volume=DEV: a volume for user space in an ordinary boot. Mounted read only (and- * nosuid, nodev) on apfs_volume_at -- by default /System/Volumes/iOS, which the system image+ * nosuid, nodev) on apfs_volume_at -- by default /System/Volumes/Darwin, which the system image* has for it (userland/build.sh) -- right here, after the root and devfs and before launchd,- * so that all of user space sees it from the start. apfs_volume=ufs_darwin is the iOS root+ * so that all of user space sees it from the start. apfs_volume=ufs_darwin is the Darwin root* container on the phone's flash (ufs=2 for the loader, bootcpu=7).*/static voidapfs_volume_mount(void){- char dev[48], at[256] = "/System/Volumes/iOS", path[64];+ char dev[48], at[256] = "/System/Volumes/Darwin", path[64];vfs_context_t ctx = vfs_context_kernel();uint64_t t0, ns = 0;vnode_t vp = NULLVP;diff --git a/drivers/storage/hakios.sparse.c b/drivers/storage/hakios.sparse.cindex d68fc2e..0aab36e 100644--- a/drivers/storage/hakios.sparse.c+++ b/drivers/storage/hakios.sparse.c@@ -2,7 +2,7 @@* A block device over an image that holds only some of its blocks (/dev/rsp0). Only with* boot-arg apfs_sparse=<offset>.*- * This exists so that the real iOS root volume can be read on the phone. The phone has+ * This exists so that the real Darwin root volume can be read on the phone. The phone has* no driver for its own storage, so a volume there has to live in a RAM disk, and that* volume is 5368 MB against the 4288 MB its firmware leaves usable. But a given walk* reads only some of those blocks, so tools/apfs/mksparse.py writes out the ones it readsdiff --git a/drivers/storage/hakios.ufs.c b/drivers/storage/hakios.ufs.cindex abbd0a4..c4b6686 100644--- a/drivers/storage/hakios.ufs.c+++ b/drivers/storage/hakios.ufs.c@@ -1,7 +1,7 @@/** The phone's storage: one block device and one character device for every GPT partition of its* UFS (/dev/ufs_NAME and /dev/rufs_NAME, NAME as the partition table has it). Read only, but for- * the one place the data of iOS lives (ufs_write=1, below).+ * the one place the data of Darwin lives (ufs_write=1, below).** There is no UFS driver here, and none is needed. UEFI never exits on this port: Qualcomm's own* UFS driver (UFSDxe) has brought up the controller, its PHY, its clocks and power, and stays@@ -15,9 +15,9 @@* Read only wherever a write could do harm, by construction. The block devices never write: the* strategy routine refuses, so no filesystem mounted from one can write, and opening one for* writing is refused. With ufs_write=1 one character device alone takes writes -- /dev/rufs_darwin,- * the port's own partition -- and in it only whole blocks from UFS_WRITE_FIRST on, past the iOS+ * the port's own partition -- and in it only whole blocks from UFS_WRITE_FIRST on, past the Darwin* volume and both cryptexes that the build writes from the computer (tools/darwin-write.py); that- * is where the data volume of iOS is kept between runs (userland/src/var_store.c). The partition+ * is where the data volume of Darwin is kept between runs (userland/src/var_store.c). The partition* has to be the one the port was set up with (its name, size, place and logical unit here; its* GUIDs as well on the loader's side), and the loader refuses the same things over again and reads* every write back before it answers. Without ufs_write=1 nothing writes at all.@@ -28,7 +28,7 @@* ever overwrites the other's. The data buffer, which only core 0's reads fill, is mapped cacheable* and the part of it an answer covers is invalidated here before it is copied out.*- * The data volume of iOS (HFS Plus, built into this kernel: bsd/hfs) is /dev/ufs_darwin_data: darwin from+ * The data volume of Darwin (HFS Plus, built into this kernel: bsd/hfs) is /dev/ufs_darwin_data: darwin from* UFS_WRITE_FIRST to its end, a block device of its own that reads and writes, there with ufs_write=1 only. Its* writes go the same way as /dev/rufs_darwin's -- through the loader, which flushes and reads every one back before it* answers -- so a write that has come back is on the flash, which is what the file system's journal counts on. The@@ -81,7 +81,7 @@ extern void FlushPoC_DcacheRegion(vm_offset_t va, size_t length); /* osfmk/arm/** Where a write may go, and nowhere else: darwin, the port's own 20 GiB at the end of logical- * unit 0, and in it only past what the build puts there from the computer -- the iOS volume+ * unit 0, and in it only past what the build puts there from the computer -- the Darwin volume* (blocks 0..1374207) and the two cryptexes behind it (..2042367). The loader keeps the same* bounds and checks the partition's type besides (xnuloader/loader.c, BLOCK_WRITE_FIRST). Where darwin* begins and its exact size are the phone's (tools/userdata-carve.py puts it after userdata, whatever@@ -595,7 +595,7 @@ ufs_read(uint32_t part, uint64_t offset, uint8_t *dst, uint64_t len)* the loader. This kernel's own driver never writes -- its whitelist of commands has no write in* it -- so for the length of a write its transfer list goes out and UEFI's driver, which the* loader calls, has the controller again; reads meanwhile go through the loader too (ufs_read),- * which is slower and right. Nothing of iOS waits on this but the writer itself: the data volume+ * which is slower and right. Nothing of Darwin waits on this but the writer itself: the data volume* is in memory (ramfs) and only its copy for the next boot is written here.*/static int@@ -614,7 +614,7 @@ ufs_write(uint32_t op, uint32_t part, uint64_t offset, const uint8_t *src, uint6}if (offset / nbs < UFS_WRITE_FIRST || offset > ufs_part_bytes(part) ||len > ufs_part_bytes(part) - offset) {- /* the iOS volume, the cryptexes, and anything past the partition's end: never */+ /* the Darwin volume, the cryptexes, and anything past the partition's end: never */ufs_write_refused++;return EROFS;}@@ -1760,7 +1760,7 @@ hakios_ufs_init(void)"through the loader's page at %llx and its %u KB buffer\n", made, pa, ufs_buffer_size >> 10);/*- * ufs_write=1: /dev/rufs_darwin takes writes, past the iOS volume and the cryptexes. darwin+ * ufs_write=1: /dev/rufs_darwin takes writes, past the Darwin volume and the cryptexes. darwin* has to be the partition the port was set up with, in everything the loader's table says of* it; the loader looks at its GUIDs besides, and refuses the same bounds of its own accord.*/diff --git a/drivers/storage/hakios.ufshc.c b/drivers/storage/hakios.ufshc.cindex 465c2f5..3f45b99 100644--- a/drivers/storage/hakios.ufshc.c+++ b/drivers/storage/hakios.ufshc.c@@ -27,7 +27,7 @@* direction in the request descriptor (from the device or none, never to it), and the command* UPIU's flags (never W); and the logical unit: never a well-known one (REPORT LUNS, BOOT, RPMB,* the device), and only those reads are allowed to go to now (ufshc_set_luns: LUN 0, where the- * iOS volume is, unless a comparison with the loader's reads asks for more). A read's length in+ * Darwin volume is, unless a comparison with the loader's reads asks for more). A read's length in* the CDB must be what the UPIU expects. It is tried at the probe on made-up commands that must* pass or be refused. This file builds READ(10) and TEST UNIT READY only.*diff --git a/drivers/storage/hakios.virtio_blk.c b/drivers/storage/hakios.virtio_blk.cindex 85b5b24..01a7c6f 100644--- a/drivers/storage/hakios.virtio_blk.c+++ b/drivers/storage/hakios.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 darwin165/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/drivers/wifi/conf b/drivers/wifi/confindex 78c46e9..1ef4fd3 100644--- a/drivers/wifi/conf+++ b/drivers/wifi/conf@@ -12,4 +12,4 @@ driver WIFIrequires QMIhelp Wi-Fi of the WCN6750 (wifi=1, wifi_step=N): the DSP that runs the radio's firmware, Linux's ath11khelp (its object, made by tools/mk-ath11k.sh, is linked in only with this), a station, and the Apple80211- help surface iOS's wifid talks to. Needs fw-wifi/ from the phone+ help surface Darwin's wifid talks to. Needs fw-wifi/ from the phonediff --git a/drivers/wifi/hakios.apple80211.c b/drivers/wifi/hakios.apple80211.cindex 90cf524..62662f7 100644--- a/drivers/wifi/hakios.apple80211.c+++ b/drivers/wifi/hakios.apple80211.c@@ -1,7 +1,7 @@/** Darwin-on-hakios: Apple80211, answered in the kernel.*- * iOS's Wi-Fi side -- wifid, and through it Settings and the status bar -- talks to a Wi-Fi+ * Darwin's Wi-Fi side -- wifid, and through it Settings and the status bar -- talks to a Wi-Fi* driver in requests that were once ioctls and are, where the driver offers no user client,* ioctls still: SIOCGA80211 and SIOCSA80211 on any socket, with a struct apple80211req that* names the interface, a request type, a value, and a buffer in the caller's memory@@ -11,7 +11,7 @@** What is asked is answered from the station boundary (sys/hakios.sta.h): the radio's power,* its channels, a scan and what it heard, the network joined. What happens there by itself is- * told to iOS the way a driver tells it: kernel events of class 6 (IEEE 802.11), subclass 1,+ * told to Darwin the way a driver tells it: kernel events of class 6 (IEEE 802.11), subclass 1,* whose code is Apple80211's own event number and whose data begins with the interface's name* in 16 bytes (IO80211.framework reads them from a PF_SYSTEM socket and compares the name).*@@ -20,7 +20,7 @@* a network's name or its key may be in there.** The request types and the layouts are Apple's. The old ones are as the headers of its open- * IO80211 sources once described them (apple80211_ioctl.h, apple80211_var.h); where iOS 16.5+ * IO80211 sources once described them (apple80211_ioctl.h, apple80211_var.h); where Darwin userland 16.5* differs the layout was read out of IO80211.framework of 16.5, which fills and reads the same* structures on the other side (Apple80211GetWithIOCTL, _getScanData, _addScanResultToList,* _performAssociation, _dispatchAsyncAssocEvent, _dispatchLinkChangedEvent).@@ -178,18 +178,18 @@ struct apple80211_link_changed {};_Static_assert(sizeof(struct apple80211_assoc) == 592 && offsetof(struct apple80211_assoc, key) == 0x48,- "the association request as iOS 16.5 has it");+ "the association request as Darwin userland 16.5 has it");_Static_assert(sizeof(struct apple80211_link_changed) == 32 && offsetof(struct apple80211_link_changed, reason) == 0x14,- "the link event as iOS 16.5 reads it");-_Static_assert(sizeof(struct apple80211_channels) == 4824, "the channel list as iOS 16.5 has it");+ "the link event as Darwin userland 16.5 reads it");+_Static_assert(sizeof(struct apple80211_channels) == 4824, "the channel list as Darwin userland 16.5 has it");_Static_assert(sizeof(struct apple80211_channels_info) == 10016 && offsetof(struct apple80211_channels_info, number) == 0x32e &&- offsetof(struct apple80211_channels_info, flags) == 0x12d0, "the channels' description as iOS 16.5 has it");+ offsetof(struct apple80211_channels_info, flags) == 0x12d0, "the channels' description as Darwin userland 16.5 has it");_Static_assert(sizeof(struct apple80211_scan_request) == 5456 && offsetof(struct apple80211_scan_request, channels) == 0x48 &&offsetof(struct apple80211_scan_request, flags) == 0x1308 && offsetof(struct apple80211_scan_request, names) == 0x1318,- "the scan request as iOS 16.5 has it");+ "the scan request as Darwin userland 16.5 has it");_Static_assert(sizeof(struct apple80211_scan_result) == 1164 && offsetof(struct apple80211_scan_result, ssid_length) == 0x60 &&offsetof(struct apple80211_scan_result, age_ms) == 0x84 && offsetof(struct apple80211_scan_result, elements) == 0x8c,- "a scan's result as iOS 16.5 has it");+ "a scan's result as Darwin userland 16.5 has it");/* Apple80211's events (APPLE80211_M_...) */enum { EVENT_POWER_CHANGED = 1, EVENT_SSID_CHANGED = 2, EVENT_BSSID_CHANGED = 3, EVENT_LINK_CHANGED = 4, EVENT_ASSOC_DONE = 9,@@ -315,7 +315,7 @@ get(struct apple80211req *request)return give(request, bits, sizeof(bits));}case 19: { /* the radio's power: one radio. Until the driver is up it counts as on: it */- struct { /* is being brought up, and iOS asks this once, early */+ struct { /* is being brought up, and Darwin asks this once, early */uint32_t version, radios, state[4];} answer = { .version = 1, .radios = 1, .state = { !hakios_sta_present() || hakios_sta_powered() } };diff --git a/drivers/wifi/hakios.lx.c b/drivers/wifi/hakios.lx.cindex 8203bef..6e01bef 100644--- a/drivers/wifi/hakios.lx.c+++ b/drivers/wifi/hakios.lx.c@@ -333,7 +333,7 @@ lx_os_net_attach(const unsigned char *address)}/*- * With wifi=1 the interface is made when the kernel starts, before the radio is up: iOS's Wi-Fi+ * With wifi=1 the interface is made when the kernel starts, before the radio is up: Darwin's Wi-Fi* side looks for it and for its registry entry as soon as it runs, once, and a radio that* turns up twelve seconds later is one it has already failed to open.*/diff --git a/drivers/wifi/hakios.sta.c b/drivers/wifi/hakios.sta.cindex b3f7c29..6e56de5 100644--- a/drivers/wifi/hakios.sta.c+++ b/drivers/wifi/hakios.sta.c@@ -14,7 +14,7 @@** The network the kernel was given in a file is a standing request: joined at the start, and* again whenever the radio is turned back on (Settings' switch), until somebody asks for- * another network -- as iOS itself rejoins the networks it knows. If that other network cannot+ * another network -- as Darwin itself rejoins the networks it knows. If that other network cannot* be joined (a wrong passphrase), the standing one is joined again.*/#include <kern/kalloc.h>diff --git a/drivers/wifi/hakios.wifi.c b/drivers/wifi/hakios.wifi.cindex 57239db..04c350d 100644--- a/drivers/wifi/hakios.wifi.c+++ b/drivers/wifi/hakios.wifi.c@@ -80,7 +80,7 @@** wifi=1 is all of it for whoever uses the phone: the steps that are needed (not the ones that* only look), ath11k as step 15 for real, its station given to the rest of the kernel to ask- * (sys/hakios.sta.h: iOS's Wi-Fi side does, through drivers/wifi/hakios.apple80211.c), the network+ * (sys/hakios.sta.h: Darwin's Wi-Fi side does, through drivers/wifi/hakios.apple80211.c), the network* of fw/network joined if the small image has that file, and everything left running while the* system does -- on a thread of its own, so that the system's start does not wait for it, and* without a word in the log but the outcome (what the steps say is kept, and shown if the radio@@ -3352,7 +3352,7 @@ static void radio_space_faults(void);* CCMP), authenticates, associates (20 MHz, HT and VHT, two streams) and answers the access* point's handshake; 130 ms after the association both keys are with the firmware and frames* pass. With wifi_keep=1 and the system started on top, configd's DHCP has an address in 4 to- * 6 s, names resolve, and pages are fetched over HTTPS: iOS on the network through the+ * 6 s, names resolve, and pages are fetched over HTTPS: Darwin on the network through the* phone's own radio. 20 MB come down in 10.5 s (15 Mbit/s) with one processor, the rings* looked at by a thread and the radio's buffers not behind the processor's cache; what of* that holds the rate down was not taken apart. With four processors the network works as@@ -4213,7 +4213,7 @@ steps_over(uint32_t done)}/*- * The network of the file, joined the way anybody joins one: by asking the station. iOS's Wi-Fi+ * The network of the file, joined the way anybody joins one: by asking the station. Darwin's Wi-Fi* side may ask for another later, or for none.*/static voiddiff --git a/drivers/wifi/hakios.wlan.cpp b/drivers/wifi/hakios.wlan.cppindex 8a18a73..5df3e5d 100644--- a/drivers/wifi/hakios.wlan.cpp+++ b/drivers/wifi/hakios.wlan.cpp@@ -1,8 +1,8 @@/*- * HakiosWLAN: the registry entries by which iOS finds the Wi-Fi interface.+ * HakiosWLAN: the registry entries by which Darwin finds the Wi-Fi interface.** en0 is made with the BSD interface KPI (drivers/net/hakios.net.c) and has no IOKit object behind- * it of its own; iOS looks for two, as IO80211Family would have made them:+ * it of its own; Darwin looks for two, as IO80211Family would have made them:** - wifid's device is whatever service has the property IO80211InterfaceRole =* "Infrastructure", and IO80211.framework binds to an interface through a service whosediff --git a/qemu/run-ios.sh b/qemu/run-darwin.shsimilarity index 86%rename from qemu/run-ios.shrename to qemu/run-darwin.shindex d7f041a..0ff94b2 100755--- a/qemu/run-ios.sh+++ b/qemu/run-darwin.sh@@ -2,7 +2,7 @@# Boot the whole system under QEMU: the big system image preloaded at the loader's resident# address (it becomes /dev/md0, the root) and the small image in the payload (/dev/md1), the# same arrangement `xl ramdisk` + `xl run` make on the phone.-# usage: run-ios.sh [seconds] [extra qemu args...]+# usage: run-darwin.sh [seconds] [extra qemu args...]## Counting anything in the log this writes: every console line comes out TWICE, the second copy in a# block replayed some thousands of lines later (take any launchd line and grep -n it). So `grep -c` gives@@ -18,7 +18,7 @@# (it hands out an address by DHCP, answers DNS and passes connections on to# this machine's network; no privileges needed). The kernel makes en0 of it# (boot-arg virtio_net=1, added here); see userland/src/net_test.m for the rest.-# AUDIO=<where> what plays the sound of iOS: a QEMU audio back end (pipewire, pa, alsa, sdl: each+# AUDIO=<where> what plays the sound of Darwin: a QEMU audio back end (pipewire, pa, alsa, sdl: each# needs its QEMU module, e.g. the package qemu-audio-pipewire) or FILE.wav to# write it into a file instead. Default: nowhere (the guest plays all the same).# QEMU_INSTANCE=<n> to run several at once: each number has its own monitor and QMP ports@@ -35,17 +35,17 @@# host RAM).cd "$(dirname "$(readlink -f "$0")")/.." || exit 1K=hakios-kernel-[ -f $K ] || { K=prebuilt/hakios-kernel; echo "run-ios.sh: no kernel built here, using $K" >&2; }-# iOS has to be told which iPhone it runs on, and that comes from the user's own IPSW, into the loader at build time-# (xnuloader/mkidentity.sh). The loader in prebuilt/ has no Apple data, so with it iOS does not start, and the window stays black.+[ -f $K ] || { K=prebuilt/hakios-kernel; echo "run-darwin.sh: no kernel built here, using $K" >&2; }+# Darwin has to be told which iPhone it runs on, and that comes from the user's own IPSW, into the loader at build time+# (xnuloader/mkidentity.sh). The loader in prebuilt/ has no Apple data, so with it Darwin does not start, and the window stays black.if [ ! -f xnuloader/loader.efi ] && [ -z "$QEMU_PREBUILT_LOADER" ]; then- echo "run-ios.sh: no xnuloader/loader.efi: iOS needs the loader built with the identity of the iPhone from your own IPSW:"+ echo "run-darwin.sh: no xnuloader/loader.efi: Darwin needs the loader built with the identity of the iPhone from your own IPSW:"echo " make loader (needs clang and lld; QEMU_PREBUILT_LOADER=1 to run with the one without Apple data anyway)"exit 1fiIMG=${IMG:-userland/system.apfs}ROOT=${ROOT:-userland/root.apfs}-[ -f "$IMG" ] && [ -f "$ROOT" ] || { echo "run-ios.sh: $IMG or $ROOT is missing (userland/build.sh makes them)"; exit 1; }+[ -f "$IMG" ] && [ -f "$ROOT" ] || { echo "run-darwin.sh: $IMG or $ROOT is missing (userland/build.sh makes them)"; exit 1; }SECS=${1:-60}; shiftRAM_BASE=0x40000000 RD_ADDR=0xFC000000RAM_GB=${QEMU_RAM_GB:-7}@@ -54,7 +54,7 @@ INSTANCE=${QEMU_INSTANCE:-$(cat qemu/instance 2>/dev/null || echo 0)}# an instance takes 2.5-3 GB of host memory; starting one that does not fit gets something killedAVAILABLE=$(awk '/^MemAvailable:/ { print int($2 / 1024) }' /proc/meminfo)if [ "${AVAILABLE:-9999}" -lt 3000 ] && [ -z "$QEMU_FORCE" ]; then- echo "run-ios.sh: only $AVAILABLE MB of memory available on this machine: stop another QEMU first (QEMU_FORCE=1 to start anyway)"+ echo "run-darwin.sh: only $AVAILABLE MB of memory available on this machine: stop another QEMU first (QEMU_FORCE=1 to start anyway)"exit 1fidiff --git a/qemu/run.sh b/qemu/run.shindex 9b5fbb7..c05e8a0 100755--- a/qemu/run.sh+++ b/qemu/run.sh@@ -4,7 +4,7 @@# env: QEMU_TB_MB megabytes for QEMU's cache of translated code (default 384; QEMU's own# default of 1 GB mostly costs host memory)# QEMU_SMP processor cores of the machine (default 1); the kernel uses as many of them as-# its boot-arg cpus=N says (CMDLINE="cpus=4" for run-ios.sh), one without it+# its boot-arg cpus=N says (CMDLINE="cpus=4" for run-darwin.sh), one without it# QEMU_ESP=1 no loader device: the payload is the file \EFI\hakios\payload.bin on the ESP, which the loader# reads itself (UEFI-native boot; what a boot menu or a USB stick does)# QEMU_EFI, QEMU_VARS the UEFI firmware for aarch64 guests (found by itself where Arch's edk2-aarch64diff --git a/qemu/stop.sh b/qemu/stop.shindex 9830f05..b1ae2b4 100755--- a/qemu/stop.sh+++ b/qemu/stop.sh@@ -1,6 +1,6 @@#!/bin/bash# Stop the QEMU of this working copy (and only it): "quit" on its monitor.-# The instance is QEMU_INSTANCE, or the number in qemu/instance, or 0 (see run-ios.sh).+# The instance is QEMU_INSTANCE, or the number in qemu/instance, or 0 (see run-darwin.sh).here=$(dirname "$(readlink -f "$0")")port=$((4444 + 10 * ${QEMU_INSTANCE:-$(cat "$here/instance" 2>/dev/null || echo 0)}))python3 - $port <<'PY'diff --git a/qemu/symstack.py b/qemu/symstack.pyindex 663863b..624cf2c 100755--- a/qemu/symstack.py+++ b/qemu/symstack.py@@ -5,7 +5,7 @@ usage: symstack.py LOG [PROCESS]Reads the "ustacks:" (boot-args ustacks=NAME ustacks_at=SECONDS [ustacks_ms=PERIOD]), "usertrap:" and"userabort:" lines of a console log (and, before a "userabort:", the "First throw call stack" of the exception-that led to it), subtracts the shared cache slide and looks every address up in the iOS dyld+that led to it), subtracts the shared cache slide and looks every address up in the Darwin dyldshared cache with "ipsw dyld a2s". Lookups take a few seconds each, so the answers are keptin sysimage/a2s.json. Addresses outside the cache (the program itself) are shown as they are."""diff --git a/qemu/touch.py b/qemu/touch.pyindex 6c90d36..6ffecdb 100755--- a/qemu/touch.py+++ b/qemu/touch.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Touch the screen of the system running under QEMU (qemu/run-ios.sh), through QMP.+"""Touch the screen of the system running under QEMU (qemu/run-darwin.sh), through QMP.usage: touch.py STEP...tap X Y a short touchdiff --git a/sysimage/ipsw-member.py b/sysimage/ipsw-member.pyindex 069bbc7..1903211 100755--- a/sysimage/ipsw-member.py+++ b/sysimage/ipsw-member.py@@ -25,7 +25,7 @@ def main():try:info = archive.getinfo(member)except KeyError:- sys.exit(f'ipsw-member.py: {member} is not in {ipsw} (is it the iOS 16.5 20F66 IPSW for iPhone10,3/iPhone10,6?)')+ sys.exit(f'ipsw-member.py: {member} is not in {ipsw} (is it the Darwin userland 16.5 20F66 IPSW for iPhone10,3/iPhone10,6?)')with archive.open(info) as stream, open(output, 'wb') as out:shutil.copyfileobj(stream, out, 1 << 20)print(f'{member}: {info.file_size} bytes')diff --git a/sysimage/mkvarskel.py b/sysimage/mkvarskel.pyindex 8faa3ec..70226e3 100755--- a/sysimage/mkvarskel.py+++ b/sysimage/mkvarskel.py@@ -1,13 +1,13 @@#!/usr/bin/env python3"""Write the skeleton of the data volume: mkvarskel.py rootfs.slt > var.skel-The iOS image carries a template of /private/var (the restore process copies it to the data+The Darwin image carries a template of /private/var (the restore process copies it to the datavolume). Our /private/var is an empty memory filesystem at every boot, so init re-creates thedirectories of that template, with their owners and modes, from this list. Lines, tab separated:d mode(octal) uid gid pathl target path (symbolic link)The staged applications and assets of the template are left out; a few directories that daemons-expect but only a running iOS creates are added at the end.+expect but only a running Darwin creates are added at the end."""import importlib.utilimport osdiff --git a/sysimage/select-system.py b/sysimage/select-system.pyindex e5cda12..68dfd85 100755--- a/sysimage/select-system.py+++ b/sysimage/select-system.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Choose the part of the iOS root filesystem that goes into the in-memory system image.+"""Choose the part of the Darwin root filesystem that goes into the in-memory system image.usage: select-system.py rootfs.slt system.files system.manifest@@ -16,7 +16,7 @@ The whole root is 7.9 GB and the kernel on the phone has about 4 GB of RAM for e- from the framework directories (the code itself is in the dyld shared cache) what aprogram may open at run time and is not huge: property lists, string tables, resources,plug-ins, and the XPC services and helper executables bundled with frameworks;- - the applications (the home screen is made of their icons), without their media; those that iOS+ - the applications (the home screen is made of their icons), without their media; those that Darwinkeeps in /private/var/staged_system_apps until its first boot installs them (Maps, Notes,Weather, ...) are put straight into /Applications, where they are system applications likethe rest: system.files names them where they are in the image, system.manifest where they godiff --git a/sysimage/unpack.sh b/sysimage/unpack.shindex f19de4c..1c57172 100755--- a/sysimage/unpack.sh+++ b/sysimage/unpack.sh@@ -1,5 +1,5 @@#!/bin/bash-# Unpack the files of iOS 16.5 (20F66, iPhone X) that the system image is made of, out of an IPSW+# Unpack the files of Darwin userland 16.5 (20F66, iPhone X) that the system image is made of, out of an IPSW# you have on your own disk, and lay them out the way ../userland/build.sh expects them:## rootfs/ the chosen part of the root filesystem (see select-system.py)@@ -28,7 +28,7 @@ set -eIPSW=${1:-${IPSW:-}}if [ -z "$IPSW" ]; thensed -n '16,20p' "$0" | sed 's/^# \{0,1\}//' >&2- echo "unpack.sh: give the path of your iOS 16.5 IPSW" >&2+ echo "unpack.sh: give the path of your Darwin userland 16.5 IPSW" >&2exit 1fi[ -f "$IPSW" ] || { echo "unpack.sh: $IPSW: no such file" >&2; exit 1; }@@ -36,7 +36,7 @@ IPSW=$(cd "$(dirname "$IPSW")" && pwd)/$(basename "$IPSW")size=$(wc -c < "$IPSW" | tr -d ' ')# select-system.py and the checks below are made for this one build; another IPSW would unpack, then fail somewhere laterif [ "$size" != 6165698198 ] && [ -z "${ANY_IPSW:-}" ]; then- echo "unpack.sh: $IPSW is $size bytes, not the 6165698198 of iOS 16.5 20F66 for iPhone10,3/10,6 (ANY_IPSW=1 tries it anyway)" >&2+ echo "unpack.sh: $IPSW is $size bytes, not the 6165698198 of Darwin userland 16.5 20F66 for iPhone10,3/10,6 (ANY_IPSW=1 tries it anyway)" >&2exit 1ficd "$(dirname "$0")"diff --git a/tools/air/check.sh b/tools/air/check.shindex 70da23f..be605b8 100755--- a/tools/air/check.sh+++ b/tools/air/check.sh@@ -11,17 +11,17 @@# tools/air/check.sh -q only the numbers, write nothingset -eROOT=$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)-IOS=${IOS:-$ROOT/sysimage}+DARWIN=${DARWIN:-$ROOT/sysimage}QUIET=0[ "${1:-}" = "-q" ] && QUIET=1# The corpus: the MTLB libraries of the device image. The five are named rather# than searched for, so a missing one is an error and not a smaller corpus.LIBS=(- "$IOS/rootfs/System/Library/VideoDecoders/AV1SW.metallib"- "$IOS/rootfs/System/Library/Extensions/AppleMetalGLRenderer.bundle/default.metallib"- "$IOS/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/default.metallib"- "$IOS/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/portrait_filters.metallib"+ "$DARWIN/rootfs/System/Library/VideoDecoders/AV1SW.metallib"+ "$DARWIN/rootfs/System/Library/Extensions/AppleMetalGLRenderer.bundle/default.metallib"+ "$DARWIN/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/default.metallib"+ "$DARWIN/rootfs/System/Library/CoreImage/PortraitFilters.cifilter/portrait_filters.metallib")# SafariSharedUI's default.metallib is in the corpus list of docs/air.md and is# deliberately not here: it is 118 bytes and holds no functions at all.diff --git a/tools/air/intrincheck.py b/tools/air/intrincheck.pyindex 099141b..405c949 100755--- a/tools/air/intrincheck.py+++ b/tools/air/intrincheck.py@@ -1042,7 +1042,7 @@ def emit_suite(arith, outdir, want, verbose, few=False, cases=0):f.write(RUNNER)os.chmod(run, 0o755)# rc.jobs: the same suite as a job list, for a device with no shell. run.sh- # above is for this machine; the phone cannot use it, because iOS 16.5's own+ # above is for this machine; the phone cannot use it, because Darwin userland 16.5's own# root carries no sh at all (/bin holds df and ps, nothing else) and the# /var/jb/bin/sh that userland/rc.jobs.jb runs belongs to the jailbreak# prefix, which a flash-root image does not carry. So every module gets a@@ -1104,7 +1104,7 @@ def parse_runner_log(path):ident = Noneblock = []lines = [l.rstrip("\n") for l in open(path, errors="replace")]- # A log QEMU produced has every line twice: qemu/run-ios.sh writes the+ # A log QEMU produced has every line twice: qemu/run-darwin.sh writes the# console to two places that both end up here, and the two copies are# adjacent. Undoing it needs care, because a suite legitimately prints the# same four numbers for two different cases, so no per-line rule is safe.@@ -1120,7 +1120,7 @@ def parse_runner_log(path):if ident is None:return# An id already answered is not replaced. The console log of a phone or- # QEMU run repeats lines -- qemu/run-ios.sh prints every one twice --+ # QEMU run repeats lines -- qemu/run-darwin.sh prints every one twice --# and the second copy of a marker opens a block with nothing after it,# which would turn an answer into a refusal. A refusal therefore never# overwrites an answer, and the first answer stands.diff --git a/tools/air/mk-host.sh b/tools/air/mk-host.shindex f78b7d8..04c1927 100755--- a/tools/air/mk-host.sh+++ b/tools/air/mk-host.sh@@ -4,7 +4,7 @@# without the phone) and softpipe (so it can be run without a GPU at all).## This is the frontend's development and test build. The one that goes on the-# phone is tools/mk-mesa.sh, which cross-compiles for iOS; both take the+# phone is tools/mk-mesa.sh, which cross-compiles for Darwin; both take the# frontend from tools/mesa/air, so what is tested here is what runs there.## Nothing of Mesa is in the repository: the pinned release is fetched, patched@@ -49,7 +49,7 @@ if [ ! -d "$SRC" ] || [ "$(cat "$SRC/.air-patches" 2>/dev/null)" != "$PATCHES" ]# glibc 2.43 and later declare C11's once_flag and call_once in <stdlib.h>,# which clashes with Mesa 25.0's own definitions in src/c11/threads.h. Only- # this host build hits it; the iOS cross build has its own libc.+ # this host build hits it; the Darwin cross build has its own libc.python3 - "$SRC" <<-'PY'import sysroot = sys.argv[1]diff --git a/tools/apfs/apfs.py b/tools/apfs/apfs.pyindex c3f34a9..8feb090 100755--- a/tools/apfs/apfs.py+++ b/tools/apfs/apfs.py@@ -628,7 +628,7 @@ class Volume:"""(name, file_id, d_type) for each entry of a directory."""out = []for k, v in self.records(obj_id, TYPE_DIR_REC):- # iOS volumes use the hashed key: a 32-bit field holding the name length and+ # Darwin volumes use the hashed key: a 32-bit field holding the name length and# a hash of the name, then the name itselfnlh = struct.unpack_from("<I", k, 8)[0]name_len = nlh & J_DREC_LEN_MASK@@ -857,7 +857,7 @@ def decmpfs_attr(ctype, attr, usize):The contents sit in the com.apple.decmpfs attribute itself, right after the header.Type 9 means they were stored as they are, with one marker byte in front. All 23947- type-9 files in the iOS 16.5 root file system have 0xcc there and exactly usize bytes+ type-9 files in the Darwin userland 16.5 root file system have 0xcc there and exactly usize bytesafter it, which is how the marker's length was settled -- the attribute is taken asbare only if it is already exactly usize bytes long."""diff --git a/tools/apfs/bench-qemu.sh b/tools/apfs/bench-qemu.shindex 6fa2923..0812315 100755--- a/tools/apfs/bench-qemu.sh+++ b/tools/apfs/bench-qemu.sh@@ -20,7 +20,7 @@ LOGS=${BENCH_LOGS:-$ROOT/apfs-work}INSTANCE=$(cat "$ROOT/qemu/instance" 2>/dev/null || echo 0)PORT=$((4444 + 10 * INSTANCE))cd "$ROOT" || exit 1-touch "$IMAGE" # run-ios.sh rebuilds its RAM image only from a newer file+touch "$IMAGE" # run-darwin.sh rebuilds its RAM image only from a newer fileprintf "%-7s %9s %11s %12s %12s %8s %s\n" readers wall_ms MB/s lock_wait_ms lock_held_ms "bad" sumsfor n in $COUNTS; do@@ -32,7 +32,7 @@ for n in $COUNTS; dolog="$LOGS/bench-$(date +%H%M%S)-$n.log"QEMU_SMP=$SMP IMG="$IMAGE" ROOT=userland/root.apfs \CMDLINE="cpus=$SMP apfs_check=5 apfs_threads=$n $EXTRA" \- timeout 900 qemu/run-ios.sh 600 > "$log" 2>&1+ timeout 900 qemu/run-darwin.sh 600 > "$log" 2>&1wall=$(grep -ao "$n readers done in [0-9]*" "$log" | head -1 | awk '{print $5}')kbs=$(grep -ao "bytes [0-9]* KB/s" "$log" | head -1 | awk '{print $2}')lock=$(grep -a "apfs: lock" "$log" | head -1 | sed 's/^\[[^]]*\]: //')diff --git a/tools/apfs/mkapfs.py b/tools/apfs/mkapfs.pyindex bbb4e65..2628f4a 100755--- a/tools/apfs/mkapfs.py+++ b/tools/apfs/mkapfs.py@@ -4,14 +4,14 @@usage: mkapfs.py -o IMAGE [-z [--plain DIR]...] [--time SECONDS] [--slack BLOCKS] NAME=DIR[,manifest=FILE] [NAME=DIR ...]Each NAME=DIR becomes one volume of the container (volume 0 first), case-sensitive and-normalization-insensitive like the iOS volumes, unencrypted, read-only content laid out once.+normalization-insensitive like the Darwin 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]; 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 (type+as Apple stores most of the Darwin 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 as-it is and in one piece -- the firmware a driver uses where it lies in memory. Times are all --time (default: 2023-05-12, the iOS 16.5 images'), so the same+it is and in one piece -- the firmware a driver uses where it lies in memory. Times are all --time (default: 2023-05-12, the Darwin userland 16.5 images'), so the sameinput gives the same image byte for byte.The image is what Apple's newfs_apfs and a single transaction would leave (one checkpoint,diff --git a/tools/apfs/mksparse.py b/tools/apfs/mksparse.pyindex 792f094..993bdfa 100755--- a/tools/apfs/mksparse.py+++ b/tools/apfs/mksparse.py@@ -3,7 +3,7 @@# plus a table saying where each of them went.## Why: the phone has no driver for its own storage, so a volume there has to live in a RAM-# disk, and the whole iOS root volume is 5368 MB against the 4288 MB the phone's firmware+# disk, and the whole Darwin root volume is 5368 MB against the 4288 MB the phone's firmware# leaves usable. Most of those blocks are never read by a given walk, though, so this# writes out the ones that are and the driver cannot tell the difference -- every block it# asks for is there.diff --git a/tools/apfs/test_fetch.c b/tools/apfs/test_fetch.cindex c18bb29..6507930 100644--- a/tools/apfs/test_fetch.c+++ b/tools/apfs/test_fetch.c@@ -1,6 +1,6 @@/** stream_fetch() -- the part of reading a file's contents that runs without the volume's- * lock -- against made-up runs, since the iOS 16.5 root volume has no sparse file and so+ * lock -- against made-up runs, since the Darwin userland 16.5 root volume has no sparse file and so* never gives it a hole: holes at the front, between runs and at the end, runs that start* and end inside a block, a run inside one block, no runs at all. apfs_lib.c is included* whole, so that its static functions can be called. The device is 64 blocks of memory,diff --git a/tools/apfs/test_namenorm.py b/tools/apfs/test_namenorm.pyindex 50482cb..44e86f7 100755--- a/tools/apfs/test_namenorm.py+++ b/tools/apfs/test_namenorm.py@@ -13,7 +13,7 @@# 3. apfs-tool lookupnames IMAGE LIST looks them up through apfs_lookup## What a lookup must give is worked out from the directory's own names: on a case-sensitive,-# normalization-insensitive volume (iOS) a name matches the entry whose NFD is the same; another+# normalization-insensitive volume (Darwin) a name matches the entry whose NFD is the same; another# composition of a stored name (NFC of an NFD name, say) finds that entry; a case variant finds# only an entry with exactly that name; the name with "#" after it, nothing.diff --git a/tools/apfs/test_sparse.py b/tools/apfs/test_sparse.pyindex f8d509e..b04b45e 100755--- a/tools/apfs/test_sparse.py+++ b/tools/apfs/test_sparse.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-# The iOS 16.5 root file system has no sparse file in it -- a walk over all 318098 entries+# The Darwin userland 16.5 root file system has no sparse file in it -- a walk over all 318098 entries# finds no inode with INODE_IS_SPARSE or a sparse-bytes extended field -- so the hole# handling in read_stream cannot be checked against that image. This checks it against# made-up extent lists instead: a gap between two extents, an extent whose physical blockdiff --git a/tools/apfs/write-tests.py b/tools/apfs/write-tests.pyindex 1226786..c094239 100755--- a/tools/apfs/write-tests.py+++ b/tools/apfs/write-tests.py@@ -8,7 +8,7 @@ by at least one reader that is not apfs_write.c's and preferably by all of themapfsck linux-apfs/apfsprogs: checksums, every tree, the space manager's bitmaps againstevery block anything refers to, reference counts, extents. Knows nothing of us.apfs.py this repository's own Python reader, which verify.py has already checked against- 7-Zip over the whole iOS root volume.+ 7-Zip over the whole Darwin root volume.7-Zip a third implementation entirely.apfs-tool the kernel's own apfs_lib.c -- the one reader that is partly the code under test(it shares struct definitions), so it is never the only witness.@@ -638,7 +638,7 @@ def test_volume_gates():for what, off, value in (('a sealed volume', 56, 0x08 | 0x20),('a volume with snapshots', 216, 1),('a volume with integrity metadata', 1024, 999),- ("iOS's own system volume, by its role", 964, 1),+ ("Darwin's own system volume, by its role", 964, 1),('the preboot volume, by its role', 964, 0x10)):base, img = fresh('g-%d-%d' % (off, value))sb = find_object(img, 0x0d) # APFS_OBJECT_TYPE_FS: the volume superblock@@ -798,7 +798,7 @@ def test_power_failure():def test_real_images():- """What the gates say about the images this port really has. The iOS root volume is the one+ """What the gates say about the images this port really has. The Darwin root volume is the onethat matters: it is read through apfs.py because apfs-tool does not open a .dmg, and what itsays about it is the reason apfs_write_volume_ok() refuses a volume by its role as well."""for rel in ('userland/root.apfs', 'userland/system.apfs', 'userland/flashboot.apfs'):@@ -822,10 +822,10 @@ def test_real_images():finally:c.close()sealed = bool(incompat & 0x20)- print(' the iOS root volume: incompatible 0x%x (sealed: %s), snapshots %d, '+ print(' the Darwin root volume: incompatible 0x%x (sealed: %s), snapshots %d, ''integrity metadata %d, role 0x%04x' % (incompat, sealed, snaps, integrity, role))say(not sealed and snaps == 0 and integrity == 0,- 'the iOS root volume would pass every APFS gate there is -- so the role gate is the '+ 'the Darwin root volume would pass every APFS gate there is -- so the role gate is the ''one that refuses it, and where a write may go is what really keeps it safe')say(role == 0x0001, ' and it is refused: its role is the system volume')diff --git a/tools/buttons-session.sh b/tools/buttons-session.shindex c167b75..70fcdbb 100755--- a/tools/buttons-session.sh+++ b/tools/buttons-session.sh@@ -1,6 +1,6 @@#!/bin/bash-# A session for somebody with a hand on the phone's keys: one run of iOS with the buttons' driver-# on (boot-arg buttons=1), in which everything the driver sees and everything iOS makes of it is+# A session for somebody with a hand on the phone's keys: one run of Darwin with the buttons' driver+# on (boot-arg buttons=1), in which everything the driver sees and everything Darwin makes of it is# collected, and a summary at the end.## tools/buttons-session.sh [SECONDS] (default 120)@@ -57,7 +57,7 @@ echoecho "=== what the driver saw (the kernel's log, $out/run.log) ==="grep -a -E '^buttons: (power-on block|volume up.s pin|step 5|.*(PRESSED|released at)|so far|reading|a key reads|more than half)' "$out/run.log" | cut -c1-230echo-echo "=== what iOS's event system made of it (backboardd) ==="+echo "=== what Darwin's event system made of it (backboardd) ==="grep -a -E '\[Button\] [A-Za-z]+ page|Set Blanked' "$out/run.log" | sed -E 's/^[0-9-]+ //; s/\+0[0-9]+ backboardd\[[0-9:]+\]//' | cut -c1-120echofor key in power "volume up" "volume down"; dodiff --git a/tools/buttons-watch.sh b/tools/buttons-watch.shindex 1318534..e4600c8 100755--- a/tools/buttons-watch.sh+++ b/tools/buttons-watch.sh@@ -3,7 +3,7 @@# (the driver's "buttons:" lines, backboardd's "[Button]" lines, button presses a script makes# with rwtouch), print each new line, and take pictures of the screen after every press -- one at# once and one two seconds later -- so that a session in which somebody presses the phone's keys-# also shows what iOS made of them (a volume key: the volume indicator; the side button: the+# also shows what Darwin made of them (a volume key: the volume indicator; the side button: the# screen off, or back on).## usage: XL_SECS=N tools/buttons-watch.sh [DIR] (N as for the run; pictures go to DIR, defaultdiff --git a/tools/camraw.py b/tools/camraw.pyindex 7045df2..f617bd9 100755--- a/tools/camraw.py+++ b/tools/camraw.py@@ -11,7 +11,7 @@ four, their low two bits together in the fifth. Each frame becomes PREFIX-N.png,taking each 2x2 cell (bayer 0 RGGB, 1 GRBG, 2 GBRG, 3 BGGR) as one pixel -- half the resolution, nointerpolation -- with a plain grey-world white balance and a gamma of 2.2: a first look, not afinished photograph; PREFIX-N-raw.png is the frame's raw values as they are (grey, 8 bits).-Formats 2 and 3 are a picture iOS made of a frame (cam=5): NV12 (full-range YCbCr 4:2:0, the chroma plane+Formats 2 and 3 are a picture Darwin made of a frame (cam=5): NV12 (full-range YCbCr 4:2:0, the chroma planeafter the luma one, both of the stride) or BGRA, which becomes PREFIX.png as it is.--bayer N takes the frames for that order instead of the header's. The header's is the one eachsensor's module file gives (tools/camsensor.py lists it): the OV02B10's and the OV16A1Q's picture is@@ -62,7 +62,7 @@ def main():print(f'camraw.py: {sensor}: {width}x{height}, stride {stride}, format {fmt}, bayer {bayer}, {frames} frame(s) written whole, 'f'the last in place {last}')if fmt in (2, 3):- # a picture iOS made of a frame (cam=5, camera_test or mediaserverd): NV12 (full range) or BGRA+ # a picture Darwin made of a frame (cam=5, camera_test or mediaserverd): NV12 (full range) or BGRAbase = 4096rows = []for y in range(height):diff --git a/tools/darwin-write.py b/tools/darwin-write.pyindex c43b6b9..ddf6bdf 100755--- a/tools/darwin-write.py+++ b/tools/darwin-write.py@@ -16,7 +16,7 @@ Blocks are darwin's own, 4096 bytes, counted from the partition's start. What itdarwin, its type and unique GUIDs, LBA 25374720..30617594; no other entry over any of it), sda beinglogical unit 0 of the UFS controller, /dev/block/by-name/darwin being /dev/block/sda34, whose number,name, start and size in sysfs and whose size by blockdev say the same. Anything else: no write.- - the blocks lie inside darwin and after the iOS volume at its start (rootfs.apfs, blocks 0..1374207,+ - the blocks lie inside darwin and after the Darwin volume at its start (rootfs.apfs, blocks 0..1374207,which is never written): BLOCK >= 1374208 and BLOCK + COUNT <= 5242875. Anything else: no write.- the write goes to /dev/block/by-name/darwin only, by dd with seek and count in blocks of 4096, from acopy of the image on the phone whose sha256 has been checked; in the same shell, right before dd,@@ -163,7 +163,7 @@ def blocks_ok(block, count):if count <= 0:raise Refused('nothing to write (%d blocks)' % count)if block < PROTECTED:- raise Refused('block %d is inside the iOS volume (blocks 0..%d), which is never written' % (block, PROTECTED - 1))+ raise Refused('block %d is inside the Darwin volume (blocks 0..%d), which is never written' % (block, PROTECTED - 1))if block + count > BLOCKS:raise Refused('blocks %d..%d go past darwin\'s end (%d blocks)' % (block, block + count - 1, BLOCKS))@@ -269,7 +269,7 @@ def cmd_zero(block, count):def cmd_selftest():"""The refusals: each must refuse, and none of them reaches the phone's dd."""ok = True- for block, count, why in ((PROTECTED - 1, 256, 'one block into the iOS volume'), (0, 1, 'the iOS volume\'s superblock'),+ for block, count, why in ((PROTECTED - 1, 256, 'one block into the Darwin volume'), (0, 1, 'the Darwin volume\'s superblock'),(BLOCKS - 100, 256, 'past darwin\'s end'), (BLOCKS, 1, 'right after darwin'),(-1, 1, 'before darwin'), (PROTECTED, 0, 'nothing'), (10 ** 12, 1, 'far away')):try:diff --git a/tools/doctor.sh b/tools/doctor.shindex 2f470f9..3ba8c02 100755--- a/tools/doctor.sh+++ b/tools/doctor.sh@@ -48,7 +48,7 @@ fiif have cc || have clang; then ok "C compiler ($(have cc && echo cc || echo clang)): builds unzbm for sysimage/unpack.sh"; else need "no C compiler" "install clang or gcc"; fihave git && ok "git" || bad "git not found" "install git"-if have lld-link; then ok "lld-link: the boot loader can be built (xnuloader/build.sh)"; else warn "lld-link not found" "needed to build the boot loader with the iPhone identity from your own IPSW (make loader), which the iOS run needs (apt: lld; brew: lld); the open kernel (make qemu-open) runs with prebuilt/loader.efi, which has no Apple data"; fi+if have lld-link; then ok "lld-link: the boot loader can be built (xnuloader/build.sh)"; else warn "lld-link not found" "needed to build the boot loader with the iPhone identity from your own IPSW (make loader), which the Darwin run needs (apt: lld; brew: lld); the open kernel (make qemu-open) runs with prebuilt/loader.efi, which has no Apple data"; fihave lz4 && ok "lz4" || warn "lz4 not found" "needed by some image steps (apt: lz4)"if have flock; then@@ -80,9 +80,9 @@ elsefiif have qemu-system-aarch64; thenok "qemu-system-aarch64: make qemu-open works"- # what the iOS run (qemu/run-ios.sh) needs on top: a display device, the UEFI firmware, memory. Without the display+ # what the Darwin run (qemu/run-darwin.sh) needs on top: a display device, the UEFI firmware, memory. Without the display# SpringBoard does not start, and the window stays black, which is what people reported first.- if qemu-system-aarch64 -device help 2>/dev/null | grep -q '"ramfb"'; then ok "qemu has the ramfb display device (the screen of qemu/run-ios.sh)"+ if qemu-system-aarch64 -device help 2>/dev/null | grep -q '"ramfb"'; then ok "qemu has the ramfb display device (the screen of qemu/run-darwin.sh)"else bad "this qemu-system-aarch64 has no ramfb display device" "the screen stays black without it: install a QEMU of 7.0 or newer (the full package, e.g. qemu-system-arm on Debian/Ubuntu)"; fifw=""; for f in "${QEMU_EFI:-}" /usr/share/edk2/aarch64/QEMU_EFI.fd /usr/share/AAVMF/AAVMF_CODE.fd; do [ -n "$f" ] && [ -f "$f" ] && { fw=$f; break; }; doneif [ -n "$fw" ]; then ok "UEFI firmware for the guest: $fw"@@ -90,8 +90,8 @@ if have qemu-system-aarch64; then# the guest has 7 GB of RAM by default (QEMU_RAM_GB, never below 6: the system image sits in it, 3 GB up)mem_mb=$(awk '/^MemAvailable:/ { print int($2 / 1024) }' /proc/meminfo 2>/dev/null)if [ -n "$mem_mb" ]; then- if [ "$mem_mb" -ge 7200 ]; then ok "memory: ${mem_mb} MB available (the iOS run wants about 7 GB)"- else warn "memory: only ${mem_mb} MB available; the iOS run asks QEMU for 7 GB" "close other programs, or on a small machine give WSL/the VM more memory; below that the host swaps and the window stays black for a long time"; fi+ if [ "$mem_mb" -ge 7200 ]; then ok "memory: ${mem_mb} MB available (the Darwin run wants about 7 GB)"+ else warn "memory: only ${mem_mb} MB available; the Darwin run asks QEMU for 7 GB" "close other programs, or on a small machine give WSL/the VM more memory; below that the host swaps and the window stays black for a long time"; fifinote "this is an emulated CPU, so the run is slow: the window is black for the first minute or two, then the Apple logo,"note "then the lock screen after about 3 to 10 minutes. 'tail -f logs/qemu.log' shows it is alive; qemu/screendump.sh saves the screen."@@ -101,7 +101,7 @@ fihead1 "What is already built here"if [ -f fw-modem/modem.mdt ]; then ok "phone firmware pulled (fw-*/)"; else warn "no fw-modem/ yet" "with the phone on adb: devices/redwood/pull-firmware.sh, or pull-firmware-root.sh if that gets nothing"; fi-if [ -f userland/system.apfs ] && [ -f userland/root.apfs ]; then ok "userland/system.apfs and root.apfs"; else warn "no iOS images yet" "make unpack IPSW=your.ipsw (iOS 16.5 20F66 for iPhone X, which you get yourself), then PREBUILT=1 REST=1 MODEM=1 SYSTEM=1 userland/build.sh (~8 GB)"; fi+if [ -f userland/system.apfs ] && [ -f userland/root.apfs ]; then ok "userland/system.apfs and root.apfs"; else warn "no Darwin images yet" "make unpack IPSW=your.ipsw (Darwin userland 16.5 20F66 for iPhone X, which you get yourself), then PREBUILT=1 REST=1 MODEM=1 SYSTEM=1 userland/build.sh (~8 GB)"; fihead1 "Phone"adb=""@@ -164,7 +164,7 @@ elsefiif [ "$root" = 1 ]; thenif A 'su -c "ls /dev/block/by-name"' | grep -qx darwin; then- ok "the partition darwin exists (the port's own: persistence and the iOS system image)"+ ok "the partition darwin exists (the port's own: persistence and the Darwin system image)"elsenote "no partition darwin yet: only persistence and a flash install need it (tools/userdata-carve.py plans it, and says what it does to Android's data)"fidiff --git a/tools/flash-fingerprint.sh b/tools/flash-fingerprint.shindex cc0e783..3e0c0cd 100755--- a/tools/flash-fingerprint.sh+++ b/tools/flash-fingerprint.sh@@ -4,7 +4,7 @@# flash-fingerprint.sh android DIR from Android (adb, root): for each logical unit sda..sdf its# size, sha256 of its first and last 8 blocks of 4 KB and# `sgdisk --android-dump`; sha256 of userdata's first MB, of-# darwin's first 5628755968 bytes (the iOS volume image), the+# darwin's first 5628755968 bytes (the Darwin volume image), the# number of files under /sdcard, and whether Android is up# (sys.boot_completed, /data mounted) -> DIR/android.txt# flash-fingerprint.sh survey LOG DIR the loader's own survey (ufs=1 or 2) out of a run's log:diff --git a/tools/font_trim.py b/tools/font_trim.pyindex 5272e44..39f738c 100755--- a/tools/font_trim.py+++ b/tools/font_trim.py@@ -1,6 +1,6 @@#!/usr/bin/env python3"""-font_trim.py: smaller copies of the two fonts iOS has that are too big for a system image kept in+font_trim.py: smaller copies of the two fonts Darwin has that are too big for a system image kept inthe phone's memory, made from the files themselves (nothing of them is in the repository).font_trim.py emoji SRC DST [PPEM,...]diff --git a/tools/guard_test.c b/tools/guard_test.cindex 7f0a566..34ec9f4 100644--- a/tools/guard_test.c+++ b/tools/guard_test.c@@ -137,11 +137,11 @@ main(void)run("pink noise at -15 dB RMS (loud music)", 0, 2, pow(10, -15 / 20.0), 0, 60, 10);run("pink noise at -9 dB RMS (music mastered as loud as it goes)", 0, 2, pow(10, -9 / 20.0), 0, 120, 20);run("silence", HAKIOS_GUARD_SILENT, 0, 0, 0, 300, 300);- /* iOS at its top: a tone 12.6 dB under full scale, then 12 dB of gain before the guard */+ /* Darwin at its top: a tone 12.6 dB under full scale, then 12 dB of gain before the guard */hakios_guard_configure(true, 96);- run("iOS's top (a 440 Hz sine at -12.6 dB) with 12 dB of gain", 0, 1, pow(10, -12.6 / 20), 440, 90, 10);+ run("Darwin's top (a 440 Hz sine at -12.6 dB) with 12 dB of gain", 0, 1, pow(10, -12.6 / 20), 440, 90, 10);run("silence", HAKIOS_GUARD_SILENT, 0, 0, 0, 600, 600);- run("pink noise at -24 dB RMS (loud music as iOS leaves it) with 12 dB of gain", 0, 2, pow(10, -24 / 20.0), 0, 60, 20);+ run("pink noise at -24 dB RMS (loud music as Darwin leaves it) with 12 dB of gain", 0, 2, pow(10, -24 / 20.0), 0, 60, 20);run("silence", HAKIOS_GUARD_SILENT, 0, 0, 0, 600, 600);run("the same with the amplifiers 90 dB under (sound_below=720)", 720, 2, pow(10, -24 / 20.0), 0, 10, 5);return 0;diff --git a/tools/mesa/air/air_layout.c b/tools/mesa/air/air_layout.cindex 60e194c..313d498 100644--- a/tools/mesa/air/air_layout.c+++ b/tools/mesa/air/air_layout.c@@ -5,7 +5,7 @@/** Sizes and alignments from the module's datalayout string, by LLVM's rules- * (LangRef, "Data Layout"). Every AIR module of iOS 16.5 has the same layout,+ * (LangRef, "Data Layout"). Every AIR module of Darwin userland 16.5 has the same layout,* but it is read rather than assumed: GEP offsets are computed from it, and* a wrong offset is a wrong read.*/diff --git a/tools/mesa/air/air_metallib.c b/tools/mesa/air/air_metallib.cindex f94492e..05020b6 100644--- a/tools/mesa/air/air_metallib.c+++ b/tools/mesa/air/air_metallib.c@@ -6,7 +6,7 @@/** The MTLB container of a .metallib: a header, a function list of tagged* fields, and one LLVM module per function. Worked out against the files of- * iOS 16.5 (docs/metal.md, section 9.1; tools/metallib.py is the same in+ * Darwin userland 16.5 (docs/metal.md, section 9.1; tools/metallib.py is the same in* Python).*/diff --git a/tools/mesa/air/air_module.h b/tools/mesa/air/air_module.hindex 7ea7c95..1b89a99 100644--- a/tools/mesa/air/air_module.h+++ b/tools/mesa/air/air_module.h@@ -6,7 +6,7 @@/** The part of LLVM IR that AIR uses, read from bitcode into plain C* structures. It is a reader, not an IR library: nothing here is modified- * after reading, and only what the 456 modules of iOS 16.5's system+ * after reading, and only what the 456 modules of Darwin userland 16.5's system* libraries contain (plus a little margin) is understood. Anything else is an* error that names the record, never a silent skip, because a skipped* instruction is a wrong shader.diff --git a/tools/mesa/air/air_run.c b/tools/mesa/air/air_run.cindex 2697b14..afcd243 100644--- a/tools/mesa/air/air_run.c+++ b/tools/mesa/air/air_run.c@@ -55,7 +55,7 @@#include <mach-o/dyld.h>#include <signal.h>/* <sys/ucontext.h>, not <ucontext.h>: the latter refuses to be included- * without _XOPEN_SOURCE on the iOS SDK, and userland/src/inject.c takes the+ * without _XOPEN_SOURCE on the Darwin SDK, and userland/src/inject.c takes the* same route for the same reason.*/#include <sys/ucontext.h>@@ -104,7 +104,7 @@ texel_value(unsigned slot, unsigned x, unsigned y, unsigned z, float out[4])* print the fault before dying. These two functions are userland/src/inject.c's* say_the_fault()/watch_for_faults() (branch sileo2, 6683521), with the slide* taken from this program's own image rather than from the shared cache, since- * the pc of interest is in air_run or in libOSMesa and not in iOS.+ * the pc of interest is in air_run or in libOSMesa and not in Darwin.*/static voidsay_the_fault(int signal_number, siginfo_t *info, void *context_in)@@ -762,7 +762,7 @@ main(int argc, char **argv)*/bool want_library = false;/* --buffer FILE is AIR_RUN_BUFFER as an argument, and it exists because the- * device has no shell to set one with. iOS 16.5's own root carries no sh at+ * device has no shell to set one with. Darwin userland 16.5's own root carries no sh at* all -- /bin holds df and ps -- and the job list that runs this is read by* our init, which splits a line on blanks and has no notion of a variable* (userland/src/init.c, run_command). So a generated suite whose everydiff --git a/tools/metal-plugin-test.sh b/tools/metal-plugin-test.shindex 0f53e5c..b379e02 100755--- a/tools/metal-plugin-test.sh+++ b/tools/metal-plugin-test.sh@@ -4,7 +4,7 @@# usage: tools/metal-plugin-test.sh [DIR]set -ecd "$(dirname "$0")/.."-[ "$(uname)" = Darwin ] || { echo "metal-plugin-test: needs macOS (its Metal stands in for iOS's)"; exit 0; }+[ "$(uname)" = Darwin ] || { echo "metal-plugin-test: needs macOS (its Metal stands in for Darwin's)"; exit 0; }tmp=$(mktemp -d)trap 'rm -rf "$tmp"' EXITclang -O1 -g -fsanitize=address -Wall -Wno-unused-parameter -Iuserland/src -framework Foundation -framework Metal -lobjc \diff --git a/tools/metal_plugin_test.m b/tools/metal_plugin_test.mindex c45b608..2dd4adf 100644--- a/tools/metal_plugin_test.m+++ b/tools/metal_plugin_test.m@@ -3,10 +3,10 @@* macOS, its device made by hand the way Metal makes it (-initWithAcceleratorPort:), and what a program does with buffers and* libraries checked. tools/metal-plugin-test.sh builds and runs it, under the address sanitizer.*- * What this shows and what it does not. Metal's private classes on macOS are not iOS 16.5's (the plug-in takes _MTLResource,+ * What this shows and what it does not. Metal's private classes on macOS are not Darwin userland 16.5's (the plug-in takes _MTLResource,* _MTLLibrary and _MTLFunction where they exist, and both systems have them), so this checks the plug-in's own logic -- the* classes it makes at run time, their state, the buffers' memory, the reading of a .metallib, every object freed -- not that- * iOS's Metal is content with them. That is metal_test's to say, in QEMU (userland/rc.jobs.metal).+ * Darwin's Metal is content with them. That is metal_test's to say, in QEMU (userland/rc.jobs.metal).** The binary must be called metal_test: the plug-in shows its device to that program only (metal=1, the level a Mac's* kern.bootargs gives, having no metal= in it).diff --git a/tools/metallib.py b/tools/metallib.pyindex b96706e..6dec881 100755--- a/tools/metallib.py+++ b/tools/metallib.py@@ -1,7 +1,7 @@#!/usr/bin/env python3"""Take a .metallib apart: the MTLB container, its function list, and each function's LLVM bitcode.-The container was worked out by hand against the files of iOS 16.5; what is in it, and what the+The container was worked out by hand against the files of Darwin userland 16.5; what is in it, and what thenumbers below mean, is written down in docs/metal.md (section 9). Every module of every .metallibin the extracted system is ordinary LLVM bitcode in the standard 0x0B17C0DE wrapper, so after"metallib.py dump" an ordinary llvm-dis reads them.diff --git a/tools/mk-jb.sh b/tools/mk-jb.shindex 5896b08..8737b70 100755--- a/tools/mk-jb.sh+++ b/tools/mk-jb.sh@@ -1,12 +1,12 @@#!/bin/bash# Fetch what Sileo needs into jb/ (never in the repository, like fw-*): the Procursus bootstrap for-# iOS and the Sileo package, both for arm64 and both "rootless" -- everything under /var/jb.+# Darwin and the Sileo package, both for arm64 and both "rootless" -- everything under /var/jb.## Rootless is what fits this port: / is an APFS image that cannot be written to, and /private/var# is the only writable filesystem there is (a memory filesystem, made afresh at every boot), so the# whole prefix has to live under /var. The binaries of the rootless distribution are built for-# iOS 15 and up (dpkg 1.22.6, apt 2.9.4) and Sileo for iOS 11 and up; the "1800" in the path is the-# name of the distribution, not a demand for iOS 18.+# Darwin userland 15 and up (dpkg 1.22.6, apt 2.9.4) and Sileo for Darwin userland 11 and up; the "1800" in the path is the+# name of the distribution, not a demand for Darwin userland 18.## What is left behind in jb/:# root/var/jb/... the bootstrap with Sileo unpacked into it, as the phone will have it@@ -158,14 +158,14 @@ for package in shshd libkrw0 libdimentio0; dodone# The dependency on "firmware" is taken out of the records of the packages that carry it. That-# package is not a package: usr/libexec/firmware writes it straight into dpkg's database (the iOS+# package is not a package: usr/libexec/firmware writes it straight into dpkg's database (the Darwin# version, "firmware 16.5"), no repository has it and nothing provides it. apt on the command line# is content with that -- but Sileo asks apt with an index of its own making (it writes a reduced# Packages file into var/lib/apt/sileolists and runs "apt-get -sqf ... -oDir::State::lists=# sileolists/"), and against that index apt calls the same firmware "not installable" and reports# org.coolstar.sileo and snaputil as broken. Sileo then shows those as errors and refuses to install-# anything at all. What the dependency says -- "this iOS is new enough" -- is true here by-# construction: the system is iOS 16.5 and cannot be anything else.+# anything at all. What the dependency says -- "this Darwin is new enough" -- is true here by+# construction: the system is Darwin userland 16.5 and cannot be anything else.python3 - "$OUT/root/var/jb/Library/dpkg/status" <<'EOF'import re, sys@@ -191,14 +191,14 @@ EOF# What the bootstrap's own prep_bootstrap.sh does, less what this port has no use for: it asks for a# terminal password through a window of its own, and sets login shells in an /etc that is made anew# at every boot anyway. What is left matters: usr/libexec/firmware puts a package named "firmware"-# in dpkg's database with the iOS version in it, which is what every other package depends on+# in dpkg's database with the Darwin version in it, which is what every other package depends on# (Sileo: "firmware (>= 11.0)"), and the few postinst scripts settle the shells and apt's own state.cat > "$OUT/root/var/jb/prep.sh" <<'PREP'#!/var/jb/bin/sh# Run once per boot, after the prefix has been grafted onto /var/jb (rc.jobs.sileo does it)./var/jb/usr/libexec/firmware# The prefix's applications: in the system image they are in /Applications already (userland/build.sh),-# where LaunchServices finds them by itself; with the iOS volume on the flash as the root they are not,+# where LaunchServices finds them by itself; with the Darwin volume on the flash as the root they are not,# and are registered from the prefix as a rootless jailbreak does it (uikittools' uicache) -- by where the# bundle really is, as there: in /var/jb, grafted, its files are links into the boot volume# (/private/preboot/jb), and LaunchServices refuses a bundle made of links ("Unable to register").diff --git a/tools/mk-mesa.sh b/tools/mk-mesa.shindex 7d67b11..045e37b 100755--- a/tools/mk-mesa.sh+++ b/tools/mk-mesa.sh@@ -1,8 +1,8 @@#!/bin/bash-# Build Mesa for the iOS userland: the OpenGL ES library behind userland/src/eagl.c (see there and+# Build Mesa for the Darwin userland: the OpenGL ES library behind userland/src/eagl.c (see there and# userland/src/gl_osmesa.c). Mesa is fetched (a pinned release), patched with tools/mesa/*.patch and# built with the cross compiler of the kernel (xnu-deps/host/bin/xnu-clang, see xnu-deps/setup.sh)-# against the iOS SDK that userland/build.sh uses; nothing of it is in the repository.+# against the Darwin SDK that userland/build.sh uses; nothing of it is in the repository.## DRIVERS="softpipe,freedreno"# the gallium drivers to build. softpipe: a rasterizer in plain C; it needs nodiff --git a/tools/mkdatavol.py b/tools/mkdatavol.pyindex a34f293..cf59e58 100755--- a/tools/mkdatavol.py+++ b/tools/mkdatavol.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""The data volume of iOS for the phone: an empty HFS Plus volume in darwin past the iOS volume and the cryptexes,+"""The data volume of Darwin for the phone: an empty HFS Plus volume in darwin past the Darwin volume and the cryptexes,as an Android sparse image of the whole of darwin that writes that volume and nothing else.usage: mkdatavol.py OUT.simg [MKFS] (MKFS: mkfs.hfsplus, default the one in $PATH)@@ -9,13 +9,13 @@ usage: mkdatavol.py OUT.simg [MKFS] (MKFS: mkfs.hfsplus, default the one inThe kernel gives that stretch of darwin out as /dev/ufs_darwin_data (drivers/storage/hakios.ufs.c, ufs_write=1) andinit mounts it on /private/var (userland/src/init.c, var_hfs=ufs_darwin_data). Flashing this again empties it.-The image says DONT_CARE for darwin's blocks before the volume -- the iOS volume and both cryptexes, which the+The image says DONT_CARE for darwin's blocks before the volume -- the Darwin volume and both cryptexes, which thebootloader therefore leaves as they are -- and, inside the volume, for every block the new volume does not use: whatis in free space does not matter to HFS Plus, and twelve gigabytes of zeros need not go over USB. The blocks it uses(the volume headers, the allocation bitmap, the catalog and extents trees, the journal) are written whole, zerosincluded: which those are is read from the volume's own allocation bitmap.-Case-sensitive (HFSX), as iOS's own data volume is, and journaled.+Case-sensitive (HFSX), as Darwin's own data volume is, and journaled."""import osimport structdiff --git a/tools/mkesp.py b/tools/mkesp.pyindex 0cd1c79..4ddf7c8 100755--- a/tools/mkesp.py+++ b/tools/mkesp.py@@ -18,7 +18,7 @@ card starts the kernel, with no fastboot. docs/uefi-boot.md says what this doesIt refuses what the loader would refuse, and says so here instead of on a phone's screen: a file that is not apayload (no XNUP), a payload with no kernel in it, one that does not fit in the loader's payload region (63 MiB: the-big iOS system image does not come this way).+big Darwin system image does not come this way)."""import argparseimport os@@ -72,7 +72,7 @@ def main():sys.exit("mkesp: the payload has no kernel in it (entries: %s)" % (", ".join(sorted(parts)) or "none"))if len(data) > PAYLOAD_LIMIT:sys.exit("mkesp: the payload is %d bytes and the loader's payload region holds %d: the root image is too big for "- "this way of booting (the big iOS image goes in over USB, `xl ramdisk`)" % (len(data), PAYLOAD_LIMIT))+ "this way of booting (the big Darwin image goes in over USB, `xl ramdisk`)" % (len(data), PAYLOAD_LIMIT))version = parts.get("kernel.ver", b"").rstrip(b"\0").decode(errors="replace")head = open(loader, "rb").read(2)if head != b"MZ":diff --git a/tools/new-workspace.sh b/tools/new-workspace.shindex 2567025..ab1b40f 100755--- a/tools/new-workspace.sh+++ b/tools/new-workspace.sh@@ -6,7 +6,7 @@## usage: tools/new-workspace.sh NAME INSTANCE [DIR]# NAME the branch, and the directory ../hakios-NAME unless DIR is given-# INSTANCE the QEMU instance number of the copy (1, 2, ...; see qemu/run-ios.sh)+# INSTANCE the QEMU instance number of the copy (1, 2, ...; see qemu/run-darwin.sh)## 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,@@ -37,7 +37,7 @@ rm -rf $K/BUILD)# what the kernel build needs besides the treecp -a --reflink=auto "$ROOT/xnu-deps/." xnu-deps/-# The files of iOS and the system image made of them. Every one of these is taken only if it is+# The files of Darwin and the system image made of them. Every one of these is taken only if it is# there: a main copy that has not built its images yet has no system.apfs nor root.apfs, and# cryptex-app is unpacked only where somebody has needed it -- under "set -e" a copy of a file that# is not there used to end the script halfway, leaving a workspace without its QEMU instance numberdiff --git a/tools/provenance-check.py b/tools/provenance-check.pyindex 807def3..04fe4af 100755--- a/tools/provenance-check.py+++ b/tools/provenance-check.py@@ -4,7 +4,7 @@usage: tools/provenance-check.py [--report] [--root DIR]The rule of this repository is that it holds only what its authors may redistribute: the source of-the project, and files built from that source. Nothing of Apple's closed software (iOS, its images,+the project, and files built from that source. Nothing of Apple's closed software (Darwin, its images,fonts, pictures), nothing of a phone vendor's firmware. A rule like that holds only if a machinechecks it on every push, so this does. It reads the files git tracks and fails when it findsdiff --git a/tools/sound.py b/tools/sound.pyindex a75cb81..eb54ed0 100755--- a/tools/sound.py+++ b/tools/sound.py@@ -7,7 +7,7 @@ RECORDING is the piece of memory as the loader hands it over ("xl sound"; undermonitor's pmemsave at the address in the kernel's line "hakios-audio: recording ... at 0x..."):a header { "RWSND001", rate, channels, blocks }, then for every write to /dev/hakios-audio thetime it was made (nanoseconds since the kernel started), the number of frames and the frames-themselves, 16-bit samples. iOS writes only while something plays, so the recording holds no+themselves, 16-bit samples. Darwin writes only while something plays, so the recording holds nosilence: here the blocks are put back where they were in time, with silence in between(a pause of more than a quarter of a second is a pause; anything shorter is the writer beingearly or late, and the blocks are joined).diff --git a/tools/update-prebuilt.sh b/tools/update-prebuilt.shindex d90ebe6..1726108 100755--- a/tools/update-prebuilt.sh+++ b/tools/update-prebuilt.sh@@ -11,7 +11,7 @@ mkdir -p prebuilt/userland devices/redwood/prebuiltcp $K prebuilt/hakios-kernel# The loader in prebuilt/ is built with the PLACEHOLDER identity (xnuloader/mkidentity.sh --placeholder: no Apple data), in a# temporary copy so that the real xnuloader/identity.h of this tree, made from your own IPSW, is left alone and never copied-# here. It boots the open kernel (make qemu-open); to start iOS, build the loader yourself (make loader).+# here. It boots the open kernel (make qemu-open); to start Darwin, build the loader yourself (make loader).if command -v lld-link >/dev/null && command -v clang >/dev/null; thenT=$(mktemp -d)mkdir "$T/xnuloader"diff --git a/userland/build.sh b/userland/build.shindex c256422..6afef97 100755--- a/userland/build.sh+++ b/userland/build.sh@@ -6,11 +6,11 @@# (LaunchDaemons/), an APFS container (../tools/apfs/mkapfs.py). It travels in# the payload next to the kernel (the second RAM disk, /dev/md1) and is mounted# on /redwood. Rebuilt every time.-# RC=<file> etc/rc: rc.launchd (default) hands process 1 to the iOS launchd-# after init's checks; rc.ios runs a few iOS programs and halts-# JOBS="..." labels of the stock iOS launchd jobs to load (default: IOS_JOBS)+# RC=<file> etc/rc: rc.launchd (default) hands process 1 to the Darwin launchd+# after init's checks; rc.darwin runs a few Darwin programs and halts+# JOBS="..." labels of the stock Darwin launchd jobs to load (default: DARWIN_JOBS)# REST=1 ... and the rest of them, started only when asked for (see mkjobs.py)-# WIFID=0 without wifid, iOS's Wi-Fi daemon, which is in by default (see below)+# WIFID=0 without wifid, Darwin's Wi-Fi daemon, which is in by default (see below)# OSLOG="..." labels of the jobs whose os_log output goes to the console ("all": every# one of JOBS; default: only the window server, which says little)# INJECT="..." the programs started with a library of ours, "LIBRARY NAME..." per line@@ -28,7 +28,7 @@# RC_JOBS=<file> what the job com.hakios.demo runs: rc.jobs (default), or# rc.jobs.unlock, which also swipes the lock screen away (for the phone,# where nothing else can touch the screen yet).-# A job list cannot assume a shell. iOS 16.5's own root has none at all+# A job list cannot assume a shell. Darwin userland 16.5's own root has none at all# -- /bin is df and ps, and nothing else -- so a line beginning /bin/sh# fails with "No such file or directory" and status 127 on a flash-root# boot. The /var/jb/bin/sh that rc.jobs.jb and rc.jobs.sileo run is the@@ -54,23 +54,23 @@# 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 ../sysimage/select-system.py at+# APFS container: the part of Darwin userland 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+# real one is /sbin/launchd.darwin). 2.5 GB; upload once per loader session with# `xl ramdisk userland/system.apfs`. Rebuilt when missing, when its inputs# (stage0, the manifest, the cryptex files) are newer, or with SYSTEM=1 (after# changing the recipe below).-# flashboot.apfs FLASHBOOT=1: the RAM part of a boot whose root is the iOS volume on the phone's+# flashboot.apfs FLASHBOOT=1: the RAM part of a boot whose root is the Darwin volume on the phone's# flash (see below); with CRYPTEXES=flash the boot volume alone, the cryptexes being# on the flash. FLASHBOOT=1 also decides what goes into root.apfs: the job list is-# then made for the whole iOS volume (mkjobs.py --root-volume), so it holds daemons+# then made for the whole Darwin volume (mkjobs.py --root-volume), so it holds daemons# -- fairplayd, identityservicesd, passd ... -- that the system image has not got.# That root.apfs is for a flash boot; a RAM boot wants one built without FLASHBOOT=1,# or launchd will fail to start those few when something asks for them.## PREBUILT=1 do not compile anything: take our programs from ../prebuilt/userland (this is also# what happens when the cross toolchain is not set up, see ../xnu-deps/setup.sh);-# the images are then made of them and of the iOS files alone (python3)+# the images are then made of them and of the Darwin files alone (python3)# CHECK=1 check every image (every container) as it is made: apfsck has to find it clean and# the kernel's apfs_lib has to read every volume back as the directory it was made of# (../tools/apfs/check-image.sh; the system image takes a few minutes more)@@ -83,22 +83,22 @@ 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=../sysimage-CACHE=$IOS/20F66__iPhone10,3_6+DARWIN=../sysimage+CACHE=$DARWIN/20F66__iPhone10,3_6# 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: sysimage/$d is a symlink to $(readlink $IOS/$d)" >&2+ [ -L $DARWIN/$d ] || continue+ echo "build.sh: sysimage/$d is a symlink to $(readlink $DARWIN/$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 1done-# The stock iOS jobs given to launchd, roughly in the order they were brought up.-IOS_JOBS=${JOBS-"+# The stock Darwin jobs given to launchd, roughly in the order they were brought up.+DARWIN_JOBS=${JOBS-"com.apple.notifyd com.apple.cfprefsd.xpc.daemon com.apple.cfprefsd.xpc.daemon.system com.apple.logdcom.apple.syslogd com.apple.distnoted.xpc.daemon com.apple.diagnosticd com.apple.fseventsdcom.apple.containermanagerd com.apple.containermanagerd.system com.apple.runningboardd@@ -107,7 +107,7 @@ IOS_JOBS=${JOBS-"com.apple.iconservices.iconservicesagent com.apple.pluginkit.pkdcom.apple.SpringBoard"}-# iOS's own Wi-Fi daemon, for Settings to have a Wi-Fi to show: the kernel answers it in+# Darwin's own Wi-Fi daemon, for Settings to have a Wi-Fi to show: the kernel answers it in# drivers/wifi/hakios.apple80211.c. With the radio (wifi=1) Settings then shows Wi-Fi on, the network joined and the# networks the radio hears. NOT FINISHED: a network cannot be joined from Settings yet.# It is in by default now, because it costs nothing where there is no radio at all: in QEMU it comes up, talks@@ -115,14 +115,14 @@ IOS_JOBS=${JOBS-"# restarted -- and it answers what the rest of the system keeps asking for anyway. com.apple.wifi.manager, which# wifid registers itself rather than declaring in its plist, fell from 30 failed lookups a session to 3,# com.apple.private.corewifi-xpc from 1 to none, and the session's whole failed-lookup count from 331 to 305.-# (Count a QEMU run log with its duplicate lines removed: run-ios.sh prints launchd's log twice.)+# (Count a QEMU run log with its duplicate lines removed: run-darwin.sh prints launchd's log twice.)# WIFID=0 leaves it out.-[ "${WIFID-1}" != 0 ] && IOS_JOBS="$IOS_JOBS com.apple.wifid"+[ "${WIFID-1}" != 0 ] && DARWIN_JOBS="$DARWIN_JOBS com.apple.wifid"# The programs (file names) started with a library of ours inside them: "LIBRARY NAME..." per line# (src/inject.c is libhakios.dylib, src/inject_sb.c is libhakios.sb.dylib, src/inject_media.c is# libhakios.media.dylib).# What Sileo runs from /bin (see the package manager's prefix below): the system image's /bin, or the-# boot volume's bin, bound over the iOS volume's /bin when that is the root (src/init.c, flash_root).+# boot volume's bin, bound over the Darwin volume's /bin when that is the root (src/init.c, flash_root).SILEO_BIN="chmod cp mkdir mv rm"# (libhakios.tweaks is the tweak loader of the package manager's prefix, src/inject_tweaks.c: in# SpringBoard the library above opens it, here it is named for the programs that have no library of@@ -159,7 +159,7 @@ mkdir -p root/sbin root/bin root/etc root/share root/LaunchDaemonscp obj/init root/sbin/initcp obj/child root/bin/child# The data volume into the flash and back (src/var_store.c), and the job that saves it when a run-# ends: the program and its job together, away from the iOS job list below, which several working+# ends: the program and its job together, away from the Darwin job list below, which several working# copies are editing at once.[ -f obj/var_store ] && cp obj/var_store root/bin/cp com.hakios.varstore.plist root/LaunchDaemons/@@ -175,9 +175,9 @@ for d in $EXTRA_SHARE; do[ -d "$d" ] || { echo "build.sh: EXTRA_SHARE: $d is not a directory"; exit 1; }cp -rL "$d" root/share/done-if [ -d $IOS/rootfs/usr/lib ]; then+if [ -d $DARWIN/rootfs/usr/lib ]; thenif [ -z "$PREBUILT" ]; then- # ordinary dynamically linked programs of our own, built against the iOS SDK+ # ordinary dynamically linked programs of our own, built against the Darwin SDK$DYN -o obj/hello_dyn src/hello_dyn.c$DYN -framework CoreFoundation -o obj/svc_test src/svc_test.c$DYN -Wno-four-char-constants -framework CoreFoundation -framework IOSurface -o obj/surf_test src/surf_test.c@@ -194,7 +194,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then$DYN -o obj/cpu_test src/cpu_test.c$DYN -framework CoreFoundation -framework IOSurface -o obj/cow_test src/cow_test.c$DYN -framework CoreFoundation -framework CoreGraphics -framework IOSurface -o obj/cg_test src/cg_test.c- # what iOS here believes about Metal, and what CoreImage does without it (src/metal_test.m);+ # what Darwin here believes about Metal, and what CoreImage does without it (src/metal_test.m);# OpenGLES for the CIContext made over an EAGLContext, which is deprecated and the point$DYN -fobjc-arc -Wno-deprecated-declarations -framework Foundation -framework CoreGraphics \-framework CoreImage -framework IOKit -framework Metal -framework OpenGLES \@@ -217,7 +217,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then$DYN -framework CoreFoundation -framework Security -o obj/wifipw_test src/wifipw_test.c &&{ ${LDID:-ldid} -Ssrc/wifipw_test.entitlements obj/wifipw_test 2>/dev/null ||echo "build.sh: no ldid: wifipw_test is unsigned, and the keychain will refuse it (-34018)"; }- # our library for inside stock iOS programs (the jobs in INJECT are started with it)+ # our library for inside stock Darwin programs (the jobs in INJECT are started with it)$DYN -dynamiclib -install_name /redwood/lib/libhakios.dylib -framework CoreFoundation -framework IOKit -lobjc \-o obj/libhakios.dylib src/inject.c$DYN -dynamiclib -install_name /redwood/lib/libhakios.sb.dylib -framework CoreFoundation -framework IOKit -lobjc \@@ -236,12 +236,12 @@ if [ -d $IOS/rootfs/usr/lib ]; then$DYN -bundle -framework CoreFoundation -o obj/HakiosAudio src/audio_plugin.c# the plug-in Metal loads when the kernel names it (boot-arg metal=1): a device, its buffers and the libraries it reads# (src/HakiosMetal.m, src/hakios_metallib.c; tools/metal-plugin-test.sh tries the same objects on a Mac)- # With hakios-metal (github.com/oosexgang/hakios-metal, `make ios` in it, beside this tree or at HAKIOS_METAL=): buffers in+ # With hakios-metal (github.com/oosexgang/hakios-metal, `make darwin` in it, beside this tree or at HAKIOS_METAL=): buffers in# the GPU's memory, command buffers, and blits done by the GPU when the kernel has one (gpu=1). Without it, the plug-in as before.HM=${HAKIOS_METAL:-../../hakios-metal}METAL_GPU=- if [ -f $HM/out/ios/libhakios-metal.a ]; then- METAL_GPU="-DHAKIOS_METAL_GPU -I$HM/include $HM/out/ios/libhakios-metal.a -lc++ -framework IOKit"+ if [ -f $HM/out/darwin/libhakios-metal.a ]; then+ METAL_GPU="-DHAKIOS_METAL_GPU -I$HM/include $HM/out/darwin/libhakios-metal.a -lc++ -framework IOKit"echo "build.sh: HakiosMetal with hakios-metal ($HM)"fi$DYN -bundle -framework Foundation -framework Metal -lobjc -o obj/HakiosMetal src/HakiosMetal.m src/hakios_metallib.c $METAL_GPU@@ -325,7 +325,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then*) echo "$library $names" ;;esacdone > root/etc/inject.conf- cp $IOS/var.skel root/etc/var.skel # the directories init creates in /private/var+ cp $DARWIN/var.skel root/etc/var.skel # the directories init creates in /private/var# time zones: the template's links go in a circle until the time zone daemon has run (/usr/share/zoneinfo# points back into /var); point them at the data that ships with the system, and use this machine's zonezone=$(timedatectl show -p Timezone --value 2>/dev/null || true); zone=${zone:-UTC}@@ -338,14 +338,14 @@ if [ -d $IOS/rootfs/usr/lib ]; thencase $f in mobile/*) owner=501 ;; *) owner=0 ;; esacprintf 'f\t644\t%s\t%s\t/private/var/%s\t/var/%s\n' $owner $owner "$f" "$f"done >> root/etc/var.skel- # mobile's own temporary directory, $HOME/tmp, which iOS's template does not have: an application of+ # mobile's own temporary directory, $HOME/tmp, which Darwin's template does not have: an application of# mobile's without a data container of its own keeps its temporary files there -- Sileo, registered from# the prefix with the root on the flash, downloads every package and index there, and without it each# download ended in "No such file or directory"printf 'd\t700\t501\t501\t/private/var/mobile/tmp\n' >> root/etc/var.skel# A key of ours for root, when there is one: ssh/authorized_keys, never in the repository (like# fw-*). dropbear from the package manager's prefix reads it and lets us in over the phone's- # Wi-Fi, which saves rebuilding an image for every question one wants to ask a running iOS. It+ # Wi-Fi, which saves rebuilding an image for every question one wants to ask a running Darwin. It# refuses a key whose directory anyone but its owner may write, hence the 700.# SHARE=1: no keys in an image that is going to somebody else. ssh_host_ed25519_key is a# private key, and it would be leaving this machine inside a 2.5 GB container@@ -370,15 +370,15 @@ if [ -d $IOS/rootfs/usr/lib ]; then# kernel's log; the daemons keep their own standard error on the console all the same.rm -f root/etc/quiet[ -n "$QUIET" ] && : > root/etc/quiet- # the jobs the iOS launchd will see (/System/Library/LaunchDaemons is a symlink to this directory).+ # the jobs the Darwin launchd will see (/System/Library/LaunchDaemons is a symlink to this directory).# With FLASHBOOT=1 the root will be Apple's whole volume on the flash, not the part of it that fits in# the system image, so mkjobs.py judges "is this daemon's program there" by the listing of the volume# and not by what select-system.py extracted here (--root-volume; seven jobs turn on the difference,# fairplayd among them).cp com.hakios.demo.plist com.hakios.wifi.plist root/LaunchDaemons/VOLUME=""- [ -n "$FLASHBOOT" ] && [ -f $IOS/rootfs.slt ] && VOLUME="--root-volume $IOS/rootfs.slt"- [ -n "$IOS_JOBS" ] && OSLOG=${OSLOG-com.apple.backboardd} ./mkjobs.py ${REST:+--rest} $VOLUME $IOS/rootfs root/LaunchDaemons $IOS_JOBS+ [ -n "$FLASHBOOT" ] && [ -f $DARWIN/rootfs.slt ] && VOLUME="--root-volume $DARWIN/rootfs.slt"+ [ -n "$DARWIN_JOBS" ] && OSLOG=${OSLOG-com.apple.backboardd} ./mkjobs.py ${REST:+--rest} $VOLUME $DARWIN/rootfs root/LaunchDaemons $DARWIN_JOBSfi# firmware of the phone's own hardware, where somebody has pulled it from the phone's Android into ../fw-gpu# (it is the vendor's and never in the repository): the kernel's GPU bring-up, drivers/gpu/hakios.adreno.c, finds it in fw/@@ -453,14 +453,14 @@ if [ -n "$secrets" ]; thenecho "build.sh: this image carries:$secrets"echo "build.sh: do not pass it on as it is; SHARE=1 builds the same image without them."fi-# When the iOS volume on the phone's flash is to become the root (boot-arg root_apfs=ufs_darwin,-# with flashboot.apfs resident; src/init.c, flash_root): an empty directory to hide iOS's+# When the Darwin volume on the phone's flash is to become the root (boot-arg root_apfs=ufs_darwin,+# with flashboot.apfs resident; src/init.c, flash_root): an empty directory to hide Darwin's# NanoLaunchDaemons and LaunchAngels with,-# xpc without launchd.plist (launchd would read that list of all of iOS's jobs instead of+# xpc without launchd.plist (launchd would read that list of all of Darwin's jobs instead of# LaunchDaemons) and the audio server's plug-in directory with only our device in it.mkdir -p root/empty root/xpc root/halfor f in extensions.plist extensions.plist.sig; do- [ -f $IOS/rootfs/System/Library/xpc/$f ] && cp $IOS/rootfs/System/Library/xpc/$f root/xpc/+ [ -f $DARWIN/rootfs/System/Library/xpc/$f ] && cp $DARWIN/rootfs/System/Library/xpc/$f root/xpc/done[ -d root/lib/HakiosAudio.driver ] && ln -s /redwood/lib/HakiosAudio.driver root/hal/HakiosAudio.driver# the image: zlib where it saves room (a small file whole in its attribute, as Apple keeps them); fw/@@ -469,7 +469,7 @@ python3 ../tools/apfs/mkapfs.py -z --plain fw -o root.apfs redwood=root | tail -[ -z "$CHECK" ] || ../tools/apfs/check-image.sh root.apfs redwood=root# --- the RAM part of a boot off the flash: FLASHBOOT=1 -> flashboot.apfs ---------------------------------# With the iOS volume on the phone's flash as the root, all that has to come from RAM is what is not+# With the Darwin volume on the phone's flash as the root, all that has to come from RAM is what is not# on it -- the two cryptexes, OS with the dyld shared cache and App -- and what starts the boot: three# APFS containers back to back in the one resident image. The first, the boot volume, is the root the# kernel starts from (rd=md0): stage0 as /sbin/launchd mounts the small image on /redwood and runs its@@ -477,12 +477,12 @@ python3 ../tools/apfs/mkapfs.py -z --plain fw -o root.apfs redwood=root | tail -# boot volume to the volume's /private/preboot, then mounts the second container -- the OS cryptex -- on# the boot volume's empty Cryptexes/OS and the third -- Apple's App cryptex as it is -- on Cryptexes/App:# /private/preboot/Cryptexes/OS and App, where the volume's own /System/Cryptexes/OS and App point and-# where iOS grafts the cryptexes (src/init.c, flash_root; the kernel's apfs takes "/dev/md0,c=1" and+# where Darwin grafts the cryptexes (src/init.c, flash_root; the kernel's apfs takes "/dev/md0,c=1" and# "c=2", and bsd/vm/vm_unix.c takes a shared cache from Cryptexes/OS). CRYPTEX_IMAGE=FILE:# Apple's own image of the cryptex as it is instead of this one remade (2.6 GB against 1 GB: too much-# for the phone's memory beside iOS, not for QEMU's). Upload it with `xl ramdisk userland/flashboot.apfs`.+# for the phone's memory beside Darwin, not for QEMU's). Upload it with `xl ramdisk userland/flashboot.apfs`.# CRYPTEXES=flash: the boot volume alone (20 MB) -- the cryptexes are Apple's images as they are on the-# flash, in darwin right after the iOS volume (../tools/darwin-write.py put them there), and init mounts+# flash, in darwin right after the Darwin volume (../tools/darwin-write.py put them there), and init mounts# them from there, the same containers 1 and 2 of the root's own device.if [ -n "$FLASHBOOT" ] && [ -f $CACHE/dyld_shared_cache_arm64 ]; thenrm -rf flashboot flashboot.os@@ -493,7 +493,7 @@ if [ -n "$FLASHBOOT" ] && [ -f $CACHE/dyld_shared_cache_arm64 ]; then# built and thrown away unused. The guard ends with the cache: everything after it goes# into the boot volume, which every recipe carries, flash cryptexes includedif [ "$CRYPTEXES" != flash ]; then- if [ -d $IOS/cryptex ]; then linkcopy $IOS/cryptex flashboot.os; else mkdir -p flashboot.os; fi+ if [ -d $DARWIN/cryptex ]; then linkcopy $DARWIN/cryptex flashboot.os; else mkdir -p flashboot.os; fiD=flashboot.os/System/Library/Caches/com.apple.dyldmkdir -p $Dfor f in $CACHE/dyld_shared_cache_arm64*; do@@ -504,7 +504,7 @@ if [ -n "$FLASHBOOT" ] && [ -f $CACHE/dyld_shared_cache_arm64 ]; thenfi# the audio DSP's firmware and the speaker amplifiers' configuration, as in the system image's /fw: the kernel# reads the firmware as soon as there is a root (this image, adsp=1), the configuration maybe later -- by then- # from the iOS volume's /fw, which src/init.c (flash_root) binds to this+ # from the Darwin volume's /fw, which src/init.c (flash_root) binds to thisif [ -f ../fw-audio/adsp.mdt ]; thenmkdir -p flashboot/fwcp ../fw-audio/adsp.mdt ../fw-audio/adsp.b0[2-9] ../fw-audio/adsp.b[1-9][0-9] flashboot/fw/@@ -514,12 +514,12 @@ if [ -n "$FLASHBOOT" ] && [ -f $CACHE/dyld_shared_cache_arm64 ]; thencp ../fw-audio/aw882xx_acf.bin flashboot/fw/fi# the package manager's prefix, when tools/mk-jb.sh has fetched one: /jb of the boot volume, which is- # /private/preboot/jb once the iOS volume is the root -- the volume where a rootless jailbreak keeps its+ # /private/preboot/jb once the Darwin volume is the root -- the volume where a rootless jailbreak keeps its# Procursus on an iPhone as well; init grafts it onto /var/jb (src/init.c, mount_writable)if [ -d ../jb/root/var/jb ]; thencp -a ../jb/root/var/jb flashboot/jbmkdir -p flashboot/jb-rw # where init mounts the prefix's writable copy (src/init.c)- # and what Sileo runs from /bin, for init to put over the iOS volume's /bin (see the system image below)+ # and what Sileo runs from /bin, for init to put over the Darwin volume's /bin (see the system image below)mkdir -p flashboot/jb-binfor c in $SILEO_BIN; doln -s /var/jb/usr/bin/$c flashboot/jb-bin/$c@@ -530,7 +530,7 @@ if [ -n "$FLASHBOOT" ] && [ -f $CACHE/dyld_shared_cache_arm64 ]; then[ -z "$CHECK" ] || ../tools/apfs/check-image.sh flashboot.boot.apfs Boot=flashboot# the third container: Apple's App cryptex as it is (10 MB; unpack.sh), for the boot volume's Cryptexes/AppAPP=""- [ -f $IOS/cryptex-app.dmg ] && APP=$IOS/cryptex-app.dmg+ [ -f $DARWIN/cryptex-app.dmg ] && APP=$DARWIN/cryptex-app.dmgif [ "$CRYPTEXES" = flash ]; thenmv flashboot.boot.apfs flashboot.apfselif [ -n "$CRYPTEX_IMAGE" ]; then@@ -546,32 +546,32 @@ if [ -n "$FLASHBOOT" ] && [ -f $CACHE/dyld_shared_cache_arm64 ]; thenfi# --- the system image ------------------------------------------------------------------------------if [ -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+if [ -f $DARWIN/system.manifest ] && [ -f $CACHE/dyld_shared_cache_arm64 ] &&+ { [ ! -f system.apfs ] || [ obj/stage0 -nt system.apfs ] || [ $DARWIN/system.manifest -nt system.apfs ] ||+ [ $DARWIN/cryptex -nt system.apfs ] || [ $DARWIN/cryptex-app -nt system.apfs ] || [ -n "$SYSTEM" ]; }; then# 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+ # in the image either (so it was once with the audio plug-ins and the system's sounds: Darwin 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+ if [ -f $DARWIN/.done-rootfs ] && [ $DARWIN/select-system.py -nt $DARWIN/.done-rootfs ]; thenecho "build.sh: sysimage/select-system.py has changed since sysimage/rootfs was extracted: run KEEP=1 sysimage/unpack.sh" >&2exit 1firm -rf sysroot- linkcopy $IOS/rootfs sysroot # hard links or clones: no copies of the 0.5 GB- # launchd must load our choice of jobs, not all 500 that iOS has+ linkcopy $DARWIN/rootfs sysroot # hard links or clones: no copies of the 0.5 GB+ # launchd must load our choice of jobs, not all 500 that Darwin hasrm -rf sysroot/System/Library/LaunchDaemons sysroot/System/Library/NanoLaunchDaemons \sysroot/System/Library/LaunchAngels sysroot/System/Library/xpc/launchd.plistln -s /redwood/LaunchDaemons sysroot/System/Library/LaunchDaemonsmkdir -p sysroot/redwood sysroot/sbin- # where the kernel mounts the iOS root container off the phone's flash (boot-arg apfs_volume=):- # iOS has no /System/Volumes, and nothing can make a directory in this image once it is built- mkdir -p sysroot/System/Volumes/iOS- # the applications iOS installs on its first boot are system applications here (see select-system.py)+ # where the kernel mounts the Darwin root container off the phone's flash (boot-arg apfs_volume=):+ # Darwin has no /System/Volumes, and nothing can make a directory in this image once it is built+ mkdir -p sysroot/System/Volumes/Darwin+ # the applications Darwin installs on its first boot are system applications here (see select-system.py)if [ -d sysroot/private/var/staged_system_apps ]; thenmv sysroot/private/var/staged_system_apps/* sysroot/Applications/rm -rf sysroot/private/varfi- mv sysroot/sbin/launchd sysroot/sbin/launchd.ios+ mv sysroot/sbin/launchd sysroot/sbin/launchd.darwincp obj/stage0 sysroot/sbin/launchd# the audio DSP's firmware, the phone's own from ../fw-audio (never in the repository), where the kernel reads# it once the root is mounted (drivers/audio/hakios.adsp.c, adsp=1): 20 MB that do not fit beside GL=1 in the small image@@ -612,7 +612,7 @@ if [ -f $IOS/system.manifest ] && [ -f $CACHE/dyld_shared_cache_arm64 ] &&[ -d "$app" ] && cp -a "$app" sysroot/Applications/done# Sileo moves, copies and removes files as root with /bin/mv, /bin/cp, /bin/rm, /bin/mkdir and- # /bin/chmod -- where a jailbreak with a writable root keeps them -- and iOS's /bin has df and ps+ # /bin/chmod -- where a jailbreak with a writable root keeps them -- and Darwin's /bin has df and ps# alone: every one of those spawns failed with nothing said, and the package it had downloaded never# reached apt's archives ("Unable to fetch some archives"). The prefix's own programs, by those names.for c in $SILEO_BIN; do@@ -629,10 +629,10 @@ if [ -f $IOS/system.manifest ] && [ -f $CACHE/dyld_shared_cache_arm64 ] &&# the OS cryptex: on a device a separate volume grafted at /System/Cryptexes/OS. It holds the dyld# shared cache (dyld looks there first) and a few libraries and resources outside the cache.mkdir -p sysroot/System/Cryptexes- if [ -d $IOS/cryptex ]; then linkcopy $IOS/cryptex sysroot/System/Cryptexes/OS; fi+ if [ -d $DARWIN/cryptex ]; then linkcopy $DARWIN/cryptex sysroot/System/Cryptexes/OS; fi# the App cryptex, the same way: Safari's daemons (eight launchd jobs run them from there), its settings and# the bundles around it, which the root's links reach (System/Library/PreferenceBundles/MobileSafariSettings.bundle...)- if [ -d $IOS/cryptex-app ]; then linkcopy $IOS/cryptex-app sysroot/System/Cryptexes/App; fi+ if [ -d $DARWIN/cryptex-app ]; then linkcopy $DARWIN/cryptex-app sysroot/System/Cryptexes/App; fiD=sysroot/System/Cryptexes/OS/System/Library/Caches/com.apple.dyldmkdir -p $Dfor f in $CACHE/dyld_shared_cache_arm64*; do@@ -641,8 +641,8 @@ if [ -f $IOS/system.manifest ] && [ -f $CACHE/dyld_shared_cache_arm64 ] &&ln -f "$f" $D/done# zlib where it saves room, as Apple keeps the root (a small file whole in its attribute): 5.4 GB of- # files in 2.5 GB, what fits into the phone's RAM beside iOS- python3 ../tools/apfs/mkapfs.py -z -o system.apfs System=sysroot,manifest=$IOS/system.manifest | tail -1- [ -z "$CHECK" ] || ../tools/apfs/check-image.sh system.apfs System=sysroot,manifest=$IOS/system.manifest+ # files in 2.5 GB, what fits into the phone's RAM beside Darwin+ python3 ../tools/apfs/mkapfs.py -z -o system.apfs System=sysroot,manifest=$DARWIN/system.manifest | tail -1+ [ -z "$CHECK" ] || ../tools/apfs/check-image.sh system.apfs System=sysroot,manifest=$DARWIN/system.manifestrm -rf sysrootfidiff --git a/userland/jobinfo.py b/userland/jobinfo.pyindex 1a82fcd..5bcea2a 100755--- a/userland/jobinfo.py+++ b/userland/jobinfo.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Show stock iOS launchd jobs: jobinfo.py [-s SERVICE | LABEL...]+"""Show stock Darwin launchd jobs: jobinfo.py [-s SERVICE | LABEL...]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, sysdiff --git a/userland/mkeagl.py b/userland/mkeagl.pyindex 29b6bce..25d36c1 100755--- a/userland/mkeagl.py+++ b/userland/mkeagl.py@@ -1,6 +1,6 @@#!/usr/bin/env python3"""Make the function table of src/eagl.c: one function of ours for every entry of the table that-iOS's OpenGLES hands out through -[EAGLContext getMacroContextPrivate] (src/eagl_slots.txt).+Darwin's OpenGLES hands out through -[EAGLContext getMacroContextPrivate] (src/eagl_slots.txt).mkeagl.py SLOTS GL.XML EXPORTED EAGL.C > obj/eagl_gen.hdiff --git a/userland/mkjobs.py b/userland/mkjobs.pyindex 7e1f42f..c3710e5 100755--- a/userland/mkjobs.py+++ b/userland/mkjobs.py@@ -1,9 +1,9 @@#!/usr/bin/env python3-"""Copy stock iOS launchd job definitions into the small image, adjusted for the bring-up.+"""Copy stock Darwin launchd job definitions into the small image, adjusted for the bring-up.-usage: mkjobs.py [--rest] [--root-volume LISTING] IOS_ROOTFS DEST_DIR label...+usage: mkjobs.py [--rest] [--root-volume LISTING] DARWIN_ROOTFS DEST_DIR label...-For every label, IOS_ROOTFS/System/Library/LaunchDaemons/<label>.plist is copied to DEST_DIR with+For every label, DARWIN_ROOTFS/System/Library/LaunchDaemons/<label>.plist is copied to DEST_DIR withits standard error sent to the console, which is where a daemon's last words are read (thereis no log viewer or crash reporter yet). For the jobs named in the environment variable OSLOG("all" for every one) OS_ACTIVITY_DT_MODE is set too, which makes os_log print there as well:@@ -13,7 +13,7 @@ The program itself must be there at run time; a warning is printed if it will noWhat "there at run time" means is the recipe, not what happens to be unpacked on this machine, and thetwo recipes differ. With the system image as the root, it is what select-system.py chose, and a daemon it-left out as too big really is absent. With the iOS volume on the phone's flash as the root (build.sh+left out as too big really is absent. With the Darwin 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(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 being@@ -25,7 +25,7 @@ Weather were never its doing: see the network section of README.md.) Eight more,AuthenticationServicesAgent, hang on the App cryptex being unpacked beside it at all (see CRYPTEXESbelow); a workspace used to lose those silently, which tools/new-workspace.sh no longer does.-With --rest, the other jobs of iOS follow (their standard error on the console as well, their os_log+With --rest, the other jobs of Darwin follow (their standard error on the console as well, their os_logonly when named in OSLOG), and with them the "launch angels" (System/Library/LaunchAngels: theapplications without an icon that draw parts of the system's own interface in a process of theirown -- the wallpaper, the keyboard, the now playing controls -- and are reached through a Mach@@ -68,7 +68,7 @@ import sys# got (apsd -> mobileactivationd, "Device is probably unactivated"), so the push itself stays out of reach.)# CommCenter stays, and this is what it cost to find out. Shipping both of its plists is the stock# arrangement -- they carry the same label and launchd picks by the device tree, so with no "baseband" node-# it takes com.apple.CommCenter-noncellular, the variant iOS has for a device with no modem -- and it does+# it takes com.apple.CommCenter-noncellular, the variant Darwin has for a device with no modem -- and it does# pick it. It then gets a long way: it answers com.apple.commcenter.xpc and .coretelephony.xpc (85 and 18# failed lookups in a session become none), serves geod its policy, loads the network-extension# configurations. And then it dies, every time, on one of two IOKit drivers of the cellular path that this@@ -220,7 +220,7 @@ DENY = ('watchdog', 'CommCenter', 'wifi', 'WiFi', 'bluetooth', 'BTServer', 'loca'purplebuddy', 'restore', 'usb', 'accessoryd','mobileassetd', 'bird',# these start, crash and are asked for again, over and over. (aggregated, which was among them, is where- # iOS 16 keeps its power log -- com.apple.powerlog.plxpclogger.xpc and the rest -- that Settings > Battery+ # Darwin userland 16 keeps its power log -- com.apple.powerlog.plxpclogger.xpc and the rest -- that Settings > Battery# waits for; it now runs through a session.)'homed', 'routined', 'duetexpertd', 'com.apple.dmd', 'syncdefaultsd', 'photoanalysisd', 'avconferenced')@@ -229,7 +229,7 @@ DENY = tuple(word for word in DENY if word not in os.environ.get('ALLOW', '').spargs = sys.argv[1:]rest = '--rest' in args-root_volume = None # the listing of the whole iOS volume, when that volume is the root+root_volume = None # the listing of the whole Darwin volume, when that volume is the rootif '--root-volume' in args:i = args.index('--root-volume')root_volume = args[i + 1]@@ -245,7 +245,7 @@ CRYPTEXES = {'/System/Cryptexes/OS/': 'cryptex', '/System/Cryptexes/App/': 'crypdef volume_paths(listing, _cache={}):- """Every path in a 7z technical listing of the iOS root filesystem image, without a leading slash."""+ """Every path in a 7z technical listing of the Darwin root filesystem image, without a leading slash."""if listing not in _cache:_cache[listing] = {line[len('Path = '):].strip()for line in open(listing, errors='replace') if line.startswith('Path = ')}@@ -276,7 +276,7 @@ for label in labels:with open(f'{dest}/{label}.plist', 'wb') as f:plistlib.dump(job, f, fmt=plistlib.FMT_BINARY)program = job.get('Program') or job['ProgramArguments'][0]- missing = '' if present(program) else (' (NOT on the iOS volume!)' if root_volume+ missing = '' if present(program) else (' (NOT on the Darwin volume!)' if root_volumeelse ' (NOT in the system image!)')print(f' job {label}: {program}{missing}')diff --git a/userland/rc.ios b/userland/rc.darwinsimilarity index 68%rename from userland/rc.iosrename to userland/rc.darwinindex 694a8a9..ce35551 100644--- a/userland/rc.ios+++ b/userland/rc.darwin@@ -1,5 +1,5 @@# Commands init runs after its own checks: one per line, words separated by blanks.-# Our own program first, then programs taken unmodified from iOS 16.5.+# Our own program first, then programs taken unmodified from Darwin userland 16.5./redwood/bin/hello_dyn one two/bin/df/sbin/mountdiff --git a/userland/rc.jobs.bake b/userland/rc.jobs.bakeindex 3029d86..5048533 100644--- a/userland/rc.jobs.bake+++ b/userland/rc.jobs.bake@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# Does iOS ever bake the wallpaper here (RC_JOBS=rc.jobs.bake, gpu=1)? The bottom layer of every+# Does Darwin ever bake the wallpaper here (RC_JOBS=rc.jobs.bake, gpu=1)? The bottom layer of every# frosted material is a blurred copy of the wallpaper, which PaperBoardUI takes from a snapshot# source; on a phone that copy is made once, when a wallpaper is set, and kept on the data volume.# Here no such file exists even after the switcher has been open, and the materials fall back to adiff --git a/userland/rc.jobs.camera b/userland/rc.jobs.cameraindex bfed1ed..3c908d9 100644--- a/userland/rc.jobs.camera+++ b/userland/rc.jobs.camera@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The cameras for iOS (RC_JOBS=rc.jobs.camera, with cam=5; with cam_pattern=1 its frames are colour bars):+# The cameras for Darwin (RC_JOBS=rc.jobs.camera, with cam=5; with cam_pattern=1 its frames are colour bars):# first what AVFoundation lists (camera_avtest: the device is libhakios.media.dylib's in mediaserverd,# camera_device.c, whose frames come from the kernel's /dev/hakios-camera), then Camera.app opened from the home# screen as a finger opens it (with cam=5 the loader's /arm-io/isp node puts its icon on the first page, top right),diff --git a/userland/rc.jobs.darwin b/userland/rc.jobs.darwinnew file mode 100644index 0000000..be0c900--- /dev/null+++ b/userland/rc.jobs.darwin@@ -0,0 +1,16 @@+# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).+# The Darwin root container on the phone's flash, which the kernel mounts read only on+# /System/Volumes/Darwin at boot (ufs=2 apfs_volume=ufs_darwin, with bootcpu=7): what user space+# sees of it, in an ordinary session. Darwin's own mount and df first, then ours (vol_ls: ls, cat,+# hashes through read(2) and through a mapping), then every file of /usr/sbin both ways.+# The host's hashes: SystemVersion.plist 47687daabd864929, usr/lib/dyld 602fba9751ad6aa7,+# usr/sbin/mediaserverd 895037cd97f96801 (tools/apfs/apfs-tool census, apfs.py).+/sbin/mount+/bin/df+/redwood/bin/vol_ls fs /System/Volumes/Darwin+/redwood/bin/vol_ls ls /System/Volumes/Darwin+/redwood/bin/vol_ls ls /System/Volumes/Darwin/System/Library/CoreServices+/redwood/bin/vol_ls cat /System/Volumes/Darwin/System/Library/CoreServices/SystemVersion.plist+/redwood/bin/vol_ls hash /System/Volumes/Darwin/System/Library/CoreServices/SystemVersion.plist /System/Volumes/Darwin/usr/lib/dyld /System/Volumes/Darwin/usr/sbin/mediaserverd+/redwood/bin/apfs_mmap_test mmap /System/Volumes/Darwin/usr/sbin+/redwood/bin/apfs_mmap_test read /System/Volumes/Darwin/usr/sbin 65536diff --git a/userland/rc.jobs.fairplay b/userland/rc.jobs.fairplayindex e6d4b88..c1e2b72 100644--- a/userland/rc.jobs.fairplay+++ b/userland/rc.jobs.fairplay@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# What fairplayd changes (RC_JOBS=rc.jobs.fairplay, the iOS volume on the flash as the root, where the+# What fairplayd changes (RC_JOBS=rc.jobs.fairplay, the Darwin volume on the flash as the root, where the# program exists: FLASHBOOT=1, mkjobs.py --root-volume). Two questions, in this order.## First, and it needs no finger: does fairplayd stay up? It wants the IOKit user client@@ -17,7 +17,7 @@# That said, one boot here did need it and the reason is not settled: with a loader left resident by# another copy, the kernel got no ufs_shared_pa= on its command line, so its UFS driver never came up,# /dev/ufs_darwin never appeared ("mount /dev/ufs_darwin: No such file or directory") and the boot fell-# back to /sbin/launchd.ios, which exists only in the RAM image. `./xl reload` with this copy's prebuilt+# back to /sbin/launchd.darwin, which exists only in the RAM image. `./xl reload` with this copy's prebuilt# loader fixed it immediately. So either that particular resident loader was not the persist one, or the# "any kernel" claim does not hold for a prebuilt kernel. Check the command line in the log for# ufs_shared_pa= before reaching for reload. Thendiff --git a/userland/rc.jobs.flashcache b/userland/rc.jobs.flashcacheindex 515c513..7c01942 100644--- a/userland/rc.jobs.flashcache+++ b/userland/rc.jobs.flashcache@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The iOS root volume on the phone's flash as the root (flashboot.apfs resident, root_apfs=ufs_darwin+# The Darwin root volume on the phone's flash as the root (flashboot.apfs resident, root_apfs=ufs_darwin# ufs=2 ufs_native=1), read(2) through the page cache. The driver's numbers and the kernel's line about# memory for the boot (until 25 s after this list began: nothing of ours meanwhile) and the next 30 s;# then /usr/sbin and /usr/libexec, each: out of the page cache (drop), read(2) cold and warm, a mappingdiff --git a/userland/rc.jobs.flashcheck b/userland/rc.jobs.flashcheckindex 760f085..004c8af 100644--- a/userland/rc.jobs.flashcheck+++ b/userland/rc.jobs.flashcheck@@ -1,8 +1,8 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The iOS root volume on the phone's flash as the root, everything in RAM as APFS (flashboot.apfs resident,+# The Darwin root volume on the phone's flash as the root, everything in RAM as APFS (flashboot.apfs resident,# root.apfs with the kernel, built with GL=1; root_apfs=ufs_darwin ufs=2 ufs_native=1 gpu=1 adsp=1 sound=4# rec_sound=12 wifi=1, and no battery=1, which keeps the battery from the audio DSP off): what is mounted-# from where, the firmware on /fw, the battery as iOS has it, something to hear (a tone of three seconds,+# from where, the firmware on /fw, the battery as Darwin has it, something to hear (a tone of three seconds,# the lock sound, a click, a fanfare: ./xl sound), the network over the phone's Wi-Fi (an address by# DHCP, a name, a page over HTTPS), and Safari opening a page with its daemons from the App cryptex# (Apple's image as it is, the third container of flashboot.apfs, through the volume's owndiff --git a/userland/rc.jobs.flashlock b/userland/rc.jobs.flashlockindex 5db33b7..3c9bd7c 100644--- a/userland/rc.jobs.flashlock+++ b/userland/rc.jobs.flashlock@@ -1,8 +1,8 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The iOS root volume on the phone's flash as the root (flashboot.apfs resident, root_apfs=ufs_darwin+# The Darwin root volume on the phone's flash as the root (flashboot.apfs resident, root_apfs=ufs_darwin# ufs=2 ufs_native=1). The APFS driver's numbers (kern.apfs_stats: the volume's lock by who takes it) for# three stretches: the boot, until 25 s after this list began (nothing of ours meanwhile, so that-# SpringBoard's start is not shared); the next 30 s, iOS left to itself (only how busy each processor+# SpringBoard's start is not shared); the next 30 s, Darwin left to itself (only how busy each processor# was, sampled: vol_ls cpuload); then our reads -- /usr/sbin# through read(2) and a mapping (sum 3095b9e298a4df17) and /usr/libexec twice each way, only the totals# printed, each with the driver's numbers for itself. The results go to a file and are shown at the end,diff --git a/userland/rc.jobs.flashroot b/userland/rc.jobs.flashrootindex c81a18e..437d06b 100644--- a/userland/rc.jobs.flashroot+++ b/userland/rc.jobs.flashroot@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The iOS root volume on the phone's flash as the root (flashboot.apfs resident,+# The Darwin root volume on the phone's flash as the root (flashboot.apfs resident,# root_apfs=ufs_darwin ufs=2 bootcpu=7; src/init.c, flash_root), seen from user space: what# is mounted where, the root's own files read through read(2) and through a mapping.# The host's hashes: SystemVersion.plist 47687daabd864929, usr/lib/dyld 602fba9751ad6aa7,diff --git a/userland/rc.jobs.flashsound b/userland/rc.jobs.flashsoundindex 13c1962..0c595f4 100644--- a/userland/rc.jobs.flashsound+++ b/userland/rc.jobs.flashsound@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The iOS root volume on the phone's flash as the root (flashboot.apfs resident, root_apfs=ufs_darwin+# The Darwin root volume on the phone's flash as the root (flashboot.apfs resident, root_apfs=ufs_darwin# ufs=2 [ufs_native=1] adsp=1 sound=4): what is mounted, the firmware on /fw, reading files through# read(2) and through a mapping (page-in) with the APFS driver's numbers before and after, then# something to hear -- a tone of three seconds, the lock sound, a keyboard click, a fanfare -- whichdiff --git a/userland/rc.jobs.haptic b/userland/rc.jobs.hapticindex d6fbebb..aa23720 100644--- a/userland/rc.jobs.haptic+++ b/userland/rc.jobs.haptic@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The vibration motor for iOS (RC_JOBS=rc.jobs.haptic, with haptic=5): the system's haptic feedbacks -- peek (1519),+# The vibration motor for Darwin (RC_JOBS=rc.jobs.haptic, with haptic=5): the system's haptic feedbacks -- peek (1519),# pop (1520), "nope" (1521: three short ones) -- and the vibration of the ringer (4095), each played the way a program# plays a system sound; then haptics the way an application plays them (CoreHaptics: a tap, a vibration, three taps),# once with a vibration longer than the kernel's limit of 1 s, which the kernel cuts; then the feedback of the homediff --git a/userland/rc.jobs.ios b/userland/rc.jobs.iosdeleted file mode 100644index 739c959..0000000--- a/userland/rc.jobs.ios+++ /dev/null@@ -1,16 +0,0 @@-# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The iOS root container on the phone's flash, which the kernel mounts read only on-# /System/Volumes/iOS at boot (ufs=2 apfs_volume=ufs_darwin, with bootcpu=7): what user space-# sees of it, in an ordinary session. iOS's own mount and df first, then ours (vol_ls: ls, cat,-# hashes through read(2) and through a mapping), then every file of /usr/sbin both ways.-# The host's hashes: SystemVersion.plist 47687daabd864929, usr/lib/dyld 602fba9751ad6aa7,-# usr/sbin/mediaserverd 895037cd97f96801 (tools/apfs/apfs-tool census, apfs.py).-/sbin/mount-/bin/df-/redwood/bin/vol_ls fs /System/Volumes/iOS-/redwood/bin/vol_ls ls /System/Volumes/iOS-/redwood/bin/vol_ls ls /System/Volumes/iOS/System/Library/CoreServices-/redwood/bin/vol_ls cat /System/Volumes/iOS/System/Library/CoreServices/SystemVersion.plist-/redwood/bin/vol_ls hash /System/Volumes/iOS/System/Library/CoreServices/SystemVersion.plist /System/Volumes/iOS/usr/lib/dyld /System/Volumes/iOS/usr/sbin/mediaserverd-/redwood/bin/apfs_mmap_test mmap /System/Volumes/iOS/usr/sbin-/redwood/bin/apfs_mmap_test read /System/Volumes/iOS/usr/sbin 65536diff --git a/userland/rc.jobs.loud b/userland/rc.jobs.loudindex 718dfc0..c95ec58 100644--- a/userland/rc.jobs.loud+++ b/userland/rc.jobs.loud@@ -1,9 +1,9 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).# The speakers at their loudest (RC_JOBS=rc.jobs.loud, with adsp=1 sound=4 and the sound_below being tried). First a-# tone at full scale (1 kHz left, 440 Hz right) for 60 seconds written straight to /dev/hakios-audio, past iOS's+# tone at full scale (1 kHz left, 440 Hz right) for 60 seconds written straight to /dev/hakios-audio, past Darwin's# own processing, which never lets a tone come near full scale: the hardest thing the speakers can be given, for# the guard to hold back (the kernel's "sound: the guard" lines; its "speaker:" lines are the amplifiers' status,-# temperature and battery voltage). Then the same tone through iOS for 30 seconds, with its volume pressed up to the+# temperature and battery voltage). Then the same tone through Darwin for 30 seconds, with its volume pressed up to the# top, the lock sound and a fanfare./redwood/bin/sound_test springboard route/redwood/bin/sound_test level 1 raw 60 wait 6diff --git a/userland/rc.jobs.metal b/userland/rc.jobs.metalindex b5fe1d4..0064a6b 100644--- a/userland/rc.jobs.metal+++ b/userland/rc.jobs.metal@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# What iOS here believes about Metal (RC_JOBS=rc.jobs.metal, a run of half a minute): the services Metal+# What Darwin here believes about Metal (RC_JOBS=rc.jobs.metal, a run of half a minute): the services Metal# looks for and does not find, the GPU the registry does have under another name, whether a plug-in bundle# of this image would load at all, the nil a program gets, what MobileGestalt still says about graphics,# and whether CoreImage can run a filter kernel without Metal. See src/metal_test.m and docs/metal.md.diff --git a/userland/rc.jobs.mic b/userland/rc.jobs.micindex 19df673..bb85f39 100644--- a/userland/rc.jobs.mic+++ b/userland/rc.jobs.mic@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The microphone for iOS (RC_JOBS=rc.jobs.mic, with adsp=1 mic=4, haptic=5 and sound=4): first the speakers' path+# The microphone for Darwin (RC_JOBS=rc.jobs.mic, with adsp=1 mic=4, haptic=5 and sound=4): first the speakers' path# as a check (a tone of two seconds and a keyboard click; with sound_below=720 the amplifiers play it 90 dB under# Android's level, which is silence), then two recordings the way an application makes them (record_test:# AVAudioRecorder through the built-in microphone, which the virtual audio device makes of HakiosAudio.driver'sdiff --git a/userland/rc.jobs.persist b/userland/rc.jobs.persistindex 3311ba9..29e310c 100644--- a/userland/rc.jobs.persist+++ b/userland/rc.jobs.persist@@ -1,8 +1,8 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The data volume of iOS kept between boots (var_store=1 ufs_write=1; src/var_store.c): what the+# The data volume of Darwin kept between boots (var_store=1 ufs_write=1; src/var_store.c): what the# store held when this boot began, how much room the volume has, the line every run before this one# left in /private/var and the names SpringBoard had made by then with the seconds they were-# written; then this run's own line, and after two and a half minutes of iOS left to itself the+# written; then this run's own line, and after two and a half minutes of Darwin left to itself the# same names again.# Nothing here saves. The job com.hakios.varstore stays for the run and writes the volume into the# flash when the kernel says the run is ending -- which is the point: a run that was never told todiff --git a/userland/rc.jobs.persist5 b/userland/rc.jobs.persist5index c336243..64e874a 100644--- a/userland/rc.jobs.persist5+++ b/userland/rc.jobs.persist5@@ -6,9 +6,9 @@# the store at the start, and how much room the volume has;# the line every run before this one left, and the keychain item an earlier boot wrote ("keep"# writes one only if there is none, so every later boot reads the first boot's);-# the containers iOS gives its applications -- the same identifiers boot after boot, or new ones;+# the containers Darwin gives its applications -- the same identifiers boot after boot, or new ones;# the home screen's layout by hash and by the second it was written;-# and, after two minutes of iOS left to itself, the same again, with the process list.+# and, after two minutes of Darwin left to itself, the same again, with the process list./redwood/bin/var_store show/redwood/bin/vol_ls fs /private/var/redwood/bin/vol_ls cat /private/var/hakios-stamp 4096diff --git a/userland/rc.jobs.safari b/userland/rc.jobs.safariindex 9d1563f..1a26125 100644--- a/userland/rc.jobs.safari+++ b/userland/rc.jobs.safari@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# Safari (RC_JOBS=rc.jobs.safari, with wifi=1): whether iOS takes the screen for one of extended colour (it must+# Safari (RC_JOBS=rc.jobs.safari, with wifi=1): whether Darwin takes the screen for one of extended colour (it must# not: WebKit then draws into surfaces of ten bits a colour that come out black), then yandex.ru and example.com# opened the way a link opens them (battery_test open URL: SpringBoard is asked to open it), for screenshots of what# Safari shows; Safari's layers, application state and web views are said in between (com.hakios.layers, whendiff --git a/userland/rc.jobs.speakers b/userland/rc.jobs.speakersindex de54858..37f9495 100644--- a/userland/rc.jobs.speakers+++ b/userland/rc.jobs.speakers@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The phone's speakers (boot-arg sound=4 with adsp=1, drivers/audio/hakios.sound.c): once SpringBoard is up, what iOS+# The phone's speakers (boot-arg sound=4 with adsp=1, drivers/audio/hakios.sound.c): once SpringBoard is up, what Darwin# plays in the ways that matter to the amplifiers, which are on only while there is sound -- a tone of three# seconds (1000 Hz left, 440 Hz right), the lock sound, keyboard clicks four seconds apart (each one starts the# amplifiers anew: after three seconds of silence they are stopped), three clicks half a second apart (theydiff --git a/userland/rc.jobs.ssh b/userland/rc.jobs.sshindex dbf6bd6..4997311 100644--- a/userland/rc.jobs.ssh+++ b/userland/rc.jobs.ssh@@ -3,7 +3,7 @@# the phone's radio joins the network named in fw-wifi/network, configd gives en0 an address, and# OpenSSH from the package manager's prefix lets us log in as root with the key in# ssh/authorized_keys, which build.sh puts on the data volume. That spares a rebuilt image and a-# six-minute boot for every question one wants to ask a running iOS.+# six-minute boot for every question one wants to ask a running Darwin.# (dropbear would be smaller, but its package in Procursus depends on libtomcrypt1 and libtommath1,# which are in no suite of that repository: it cannot be installed at all.)# The host key is made on the computer and shipped with the image (build.sh), because ssh-keygen ondiff --git a/userland/rc.jobs.switcher b/userland/rc.jobs.switcherindex 05e3430..aca7669 100644--- a/userland/rc.jobs.switcher+++ b/userland/rc.jobs.switcher@@ -2,7 +2,7 @@# The switcher of running applications (RC_JOBS=rc.jobs.switcher, gpu=1): three applications are# started one after another (ones that ask nothing: an application that puts up a question of its# own -- Photos asks about notifications -- leaves a modal alert on the screen, and with one of-# those up iOS opens no switcher at all), the first two left running by the home button and the+# those up Darwin opens no switcher at all), the first two left running by the home button and the# third kept on the screen; then a drag up from the bottom edge that stops a third of the way and# waits opens the switcher, where the cards behind the front one are dimmed. Those of the two on# the left came out purple instead. (If the drag brings nothing, the notification asks SpringBoarddiff --git a/userland/rc.jobs.torch b/userland/rc.jobs.torchindex d78bb7c..cb58a9c 100644--- a/userland/rc.jobs.torch+++ b/userland/rc.jobs.torch@@ -1,5 +1,5 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The flashlight for iOS (RC_JOBS=rc.jobs.torch, with torch=3): as a program works it (torch_test: AVFlashlight, i.e.+# The flashlight for Darwin (RC_JOBS=rc.jobs.torch, with torch=3): as a program works it (torch_test: AVFlashlight, i.e.# mediaserverd's FigFlashlight, i.e. the kernel's /dev/hakios-torch) at full and at a quarter, then off; then from# Control Center, as a finger works it: opened from the top right corner, its flashlight button pressed, pressed again# 5 s later, Control Center closed (a tap below its buttons); then on for 8 s, which the kernel cuts with torch_max_s=5diff --git a/userland/rc.jobs.users b/userland/rc.jobs.usersindex f001a54..d6691d3 100644--- a/userland/rc.jobs.users+++ b/userland/rc.jobs.users@@ -1,14 +1,14 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).-# The user database (RC_JOBS=rc.jobs.users). iOS has no flat-file user lookup left: getpwuid and+# The user database (RC_JOBS=rc.jobs.users). Darwin has no flat-file user lookup left: getpwuid and# getpwnam go over Mach to com.apple.system.libinfo.muser, which usermanagerd serves, and a program# that cannot reach it sees every user as missing ("No user exists for uid 0" is what OpenSSH says).# ps is the probe already in the image: it calls getpwuid for every process and prints the bare uid# when there is no answer, and `ps -U NAME` is a getpwnam that fails loudly.#-# How it came out, so nobody re-runs the argument. iOS's own database answers: all three questions+# How it came out, so nobody re-runs the argument. Darwin's own database answers: all three questions# below succeed, usermanagerd is up serving muser, and in 112 run logs not one lookup of that name# has ever failed. What did not answer was OpenSSH from the package manager's prefix, and the reason-# is that it never asks iOS: ssh-keygen and sshd import _ie_getpwnam, _ie_getpwuid and _ie_getpwent+# is that it never asks Darwin: ssh-keygen and sshd import _ie_getpwnam, _ie_getpwuid and _ie_getpwent# from @rpath/libiosexec.1.dylib, Procursus's own shim, which reads /var/jb/etc/pwd.db and spwd.db --# the plain /var/jb/etc/passwd is not even in its string table -- and those two files are built by# pwd_mkdb at install time, which no hand-unpacked overlay has done. The sileo2 copy now runsdiff --git a/userland/rc.jobs.volume b/userland/rc.jobs.volumeindex 549618d..c69581c 100644--- a/userland/rc.jobs.volume+++ b/userland/rc.jobs.volume@@ -1,6 +1,6 @@# Commands run by the launchd job com.hakios.demo (see com.hakios.demo.plist).# The speakers' volume (boot-arg sound=4 with adsp=1): once SpringBoard is up, a tone of two seconds at-# iOS's volume as it is, then after every few presses of the volume buttons another one -- four steps down,+# Darwin's volume as it is, then after every few presses of the volume buttons another one -- four steps down,# eight up (to the top), sixteen down (to 0: the amplifiers stay off), four up. Every setting of the# plug-in's volume control is in the log ("hakios: audio: the volume is ..."), and the kernel's "sound:" and# "speaker:" lines say what the amplifiers did with it (register 0x05).diff --git a/userland/rc.launchd b/userland/rc.launchdindex 1a04d07..a4a59e8 100644--- a/userland/rc.launchd+++ b/userland/rc.launchd@@ -1,2 +1,2 @@-# Experiment: hand process 1 over to the real iOS launchd.-exec /sbin/launchd.ios+# Experiment: hand process 1 over to the real Darwin launchd.+exec /sbin/launchd.darwindiff --git a/userland/rc.u2f b/userland/rc.u2findex bc0ec25..ef7f711 100644--- a/userland/rc.u2f+++ b/userland/rc.u2f@@ -1,5 +1,5 @@# Commands init runs after its own checks: one per line, words separated by blanks.# The GPU's answer and nothing else (src/u2f_test.c, with gpu=1 adreno_keep=1): this runs-# before launchd, so no daemon of iOS can push the answer out of the loader's log -- which is+# before launchd, so no daemon of Darwin can push the answer out of the loader's log -- which is# what happened three runs in a row with the question asked from rc.jobs./redwood/bin/u2f_testdiff --git a/userland/src/HakiosMetal.m b/userland/src/HakiosMetal.mindex 1789950..2fcb0f9 100644--- a/userland/src/HakiosMetal.m+++ b/userland/src/HakiosMetal.m@@ -11,7 +11,7 @@* makes buffers that hold memory and libraries read from a .metallib, and stand-ins for the rest (a queue that queues nothing,* pipeline and state objects that hold nothing). It cannot run anything on the GPU yet, and says so: a message it does not know* is logged ("HakiosMetal: asked and not implemented: -...") and answers nil/0/NO instead of crashing, so that the question- * "what does iOS ask a device first, and in what order?" can be read off the log rather than guessed. The compiler for the shaders is a separate piece and is largely done+ * "what does Darwin ask a device first, and in what order?" can be read off the log rather than guessed. The compiler for the shaders is a separate piece and is largely done* (docs/air.md: Apple's shader bitcode into Mesa's NIR); the command queue and the kernel side are not started (docs/metal-plan.md).** _MTLDevice is not in the SDK's Metal.tbd (it lives in the system's own copy of the framework), so the class is made at run@@ -19,9 +19,9 @@* If there is none, nothing is registered, and Metal drops this plug-in as it does any that is not a _MTLDevice.** Status. Step one ran in QEMU (docs/metal-plan.md: what it found). Step two -- buffers, libraries, functions -- was built for- * iOS 16.5 and run on a Mac only, against the Mac's own Metal (tools/metal-plugin-test.sh, under the address sanitizer: every+ * Darwin userland 16.5 and run on a Mac only, against the Mac's own Metal (tools/metal-plugin-test.sh, under the address sanitizer: every* buffer written and read back and freed, the system's five MTLB libraries read, all of their functions by name with their- * bitcode); it has not run on iOS yet: metal_test's "what the device makes" is the check for that (QEMU, metal=1).+ * bitcode); it has not run on Darwin yet: metal_test's "what the device makes" is the check for that (QEMU, metal=1).*/#import <Foundation/Foundation.h>#import <Metal/Metal.h>diff --git a/userland/src/audio_plugin.c b/userland/src/audio_plugin.cindex 3fe67c7..9bac107 100644--- a/userland/src/audio_plugin.c+++ b/userland/src/audio_plugin.c@@ -1,5 +1,5 @@/*- * HakiosAudio.driver: the output device of iOS on this machine.+ * HakiosAudio.driver: the output device of Darwin on this machine.** Audio devices reach the audio server's hardware layer (the "HAL" of CoreAudio, inside* mediaserverd) in two ways: kernel drivers through IOAudio2 -- that is how an iPhone's own@@ -7,11 +7,11 @@* /System/Library/Audio/Plug-Ins/HAL, which is how Bluetooth, AirPlay, CarPlay and USB audio* arrive. This is such a plug-in. Its interface is the one macOS documents for user-space* audio drivers (AudioServerPlugIn: a CFPlugIn with one COM-style table of functions; the HAL- * asks for objects and their properties, then runs the I/O); the iOS SDK has no header for it,+ * asks for objects and their properties, then runs the I/O); the Darwin SDK has no header for it,* so what is needed of it is declared below.** Above the HAL sits the virtual audio device (/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin),- * through which everything in iOS is routed. It knows an iPhone's own devices by their names+ * through which everything in Darwin is routed. It knows an iPhone's own devices by their names* (their UIDs) and makes a port of each: "Speaker" becomes the speaker port, the route an iPhone* with nothing plugged in plays through, with a volume, the volume display and the place in* Control Center that go with it. So this presents four devices under those names:@@ -23,7 +23,7 @@* speaker route without a second virtual device of its own (its type 'vhaw', a* mandatory companion of the default one in the iPhone X's routing tables) whose* only port is this input; without it everything stays on the null port.- * "Actuator" one output of one channel: the iPhone's Taptic Engine, on which iOS plays its+ * "Actuator" one output of one channel: the iPhone's Taptic Engine, on which Darwin plays its* haptics as waveforms (through the chain 'd22_actuator_general'); its samples go to* the kernel's motor driver, /dev/hakios-haptic (see actuator_write())* "Codec" one input of one channel: on an iPhone, the audio codec that the built-in@@ -37,7 +37,7 @@** What is played through the speaker port passes the iPhone X's chain of effects for its own* speakers first ('d22_speaker_general', from /Library/Audio/Tunings/D22: equalisers,- * compressors, speaker protection), at the volume iOS has set.+ * compressors, speaker protection), at the volume Darwin has set.** The device has no clock but the system's: it claims to play exactly HAKIOS_AUDIO_RATE frames* a second of mach_absolute_time(), and the HAL's I/O thread paces itself by that.@@ -45,7 +45,7 @@* The speaker's output has a volume control, as the iPhone's own speaker has: what is set on it* goes to the kernel (ioctl HAKIOS_AUDIO_SET_VOLUME), which sets the amplifiers' level by it -- on* the phone, so far under the loudest it allows. Its scale is 48 dB in a straight line of- * decibels, 3 dB for each of iOS's sixteen steps; 0 is silence. What iOS does with it (the phone,+ * decibels, 3 dB for each of Darwin's sixteen steps; 0 is silence. What Darwin does with it (the phone,* 15 October): the virtual audio device sets it once, to its top (0 dB), when it takes the* device, and leaves it there -- its routing tables keep the iPhone X's speaker in software volume* mode, so the volume buttons and Control Center scale the samples themselves, and at 0 what is@@ -241,7 +241,7 @@ static int sink = -1; /* /dev/hakios-audio */static Float64 ticks_per_frame;static UInt64 written, refused; /* frames since the speaker's I/O started */static Boolean inactive[OBJECT_LAST + 1]; /* streams the HAL has switched off */-static Float32 volume = 1.0f; /* the speaker's volume control, 0 to 1 (iOS sets it once it routes there) */+static Float32 volume = 1.0f; /* the speaker's volume control, 0 to 1 (Darwin sets it once it routes there) */static voidsay(const char *format, ...)@@ -964,10 +964,10 @@ begin_end_io_operation(__unused AudioServerPlugInDriverRef driver, __unused Audi}/*- * What iOS plays on the actuator -- the haptics: the system's feedbacks and the ringer's vibration,+ * What Darwin plays on the actuator -- the haptics: the system's feedbacks and the ringer's vibration,* CoreHaptics' patterns, UIKit's feedbacks, as waveforms of one channel -- goes to the kernel's motor* driver (/dev/hakios-haptic, drivers/haptic/hakios.haptic.c, haptic=5), which plays Android's own- * waveforms on the phone's motor by it. (iOS plays on this device at all only because the device+ * waveforms on the phone's motor by it. (Darwin plays on this device at all only because the device* tree says the phone's haptics are "closed-loop": see mkidentity.py.) Said the first times, with* how loud.*/diff --git a/userland/src/battery_test.c b/userland/src/battery_test.cindex 71d25d5..d65cc75 100644--- a/userland/src/battery_test.c+++ b/userland/src/battery_test.c@@ -1,5 +1,5 @@/*- * The battery as iOS sees it: the kernel's power source (the IOPMPowerSource that powerd reads,+ * The battery as Darwin sees it: the kernel's power source (the IOPMPowerSource that powerd reads,* drivers/power/hakios.battery.cpp) and what powerd has made of it (the power sources list that* the status bar, the lock screen and Settings get through IOPS), side by side with the kernel's* own numbers (kern.hakios.battery_*).@@ -9,7 +9,7 @@* battery_test open URL have SpringBoard open a URL, such as prefs:root=BATTERY_USAGE (Settings >* Battery): for screenshots of a page that is hard to reach by touches alone* (needs the entitlement in battery_test.entitlements, which build.sh signs in)- * battery_test powerlog what iOS's power log (aggregated, CurrentPowerlog.PLSQL) has collected: every+ * battery_test powerlog what Darwin's power log (aggregated, CurrentPowerlog.PLSQL) has collected: every* table with rows, how many and over what time; one row of each of the accounting* tables Settings > Battery reads (the energy per application comes from them)*/diff --git a/userland/src/camera_avtest.m b/userland/src/camera_avtest.mindex 118c5bd..90bce9e 100644--- a/userland/src/camera_avtest.m+++ b/userland/src/camera_avtest.m@@ -1,11 +1,11 @@/*- * camera_avtest: what cameras iOS lists for applications, as AVFoundation gives them: the video+ * camera_avtest: what cameras Darwin lists for applications, as AVFoundation gives them: the video* devices, and every format of the default one (on this machine the device is libhakios.media.dylib's* in mediaserverd: camera_device.c, the kernel's /dev/hakios-camera, cam=5).** usage: camera_avtest*- * Frames are for applications in the foreground, as iOS has it: a program like this one is not+ * Frames are for applications in the foreground, as Darwin has it: a program like this one is not* given any (its session is interrupted at once). Camera.app is the test for those (rc.jobs.camera).*/#import <AVFoundation/AVFoundation.h>diff --git a/userland/src/camera_device.c b/userland/src/camera_device.cindex 24b1d6b..6181c1b 100644--- a/userland/src/camera_device.c+++ b/userland/src/camera_device.c@@ -1,12 +1,12 @@/*- * The phone's cameras as iOS's capture stack wants them: a FigCaptureDevice with two FigCaptureStreams,+ * The phone's cameras as Darwin's capture stack wants them: a FigCaptureDevice with two FigCaptureStreams,* the wide camera as the back camera and the front one as the front camera, made for mediaserverd's* BWFigCaptureDeviceVendor in place of the device Apple's H10ISP.mediacapture makes of the iPhone's ISP* (part of libhakios.media.dylib; inject_media.c gives the vendor our device's create function when* the kernel has a camera: cam=5).** Both are CoreMedia "derived objects" (CMDerivedObjectCreate): a table of functions for the base- * class (properties) and one for the device or stream class, as H10ISP's are laid out in iOS 16.5:+ * class (properties) and one for the device or stream class, as H10ISP's are laid out in Darwin userland 16.5:* device RequestStreams, RelinquishStreams (and a processing session and Pearl calibration, not here)* stream Start, Stop, AddAttachmentsToSampleBuffer* A stream's frames go to the capture graph through the blocks it is given in its property@@ -68,7 +68,7 @@ hakios_camera_say(const char *format, ...)}#define say hakios_camera_say-/* ---- CoreMedia's derived objects, as iOS 16.5 lays them out ---------------------------------------- */+/* ---- CoreMedia's derived objects, as Darwin userland 16.5 lays them out ---------------------------------------- */typedef struct OpaqueCMBaseObject *CMBaseObjectRef;typedef const void *CMBaseClassID;diff --git a/userland/src/eagl.c b/userland/src/eagl.cindex 0a525ec..2d25d84 100644--- a/userland/src/eagl.c+++ b/userland/src/eagl.c@@ -1,5 +1,5 @@/*- * libhakios.gl.dylib: an OpenGL ES implementation behind iOS's EAGLContext, inside the window+ * libhakios.gl.dylib: an OpenGL ES implementation behind Darwin's EAGLContext, inside the window* server (backboardd; libhakios.dylib loads this when the image has it: build.sh GL=1).** CoreAnimation's render server draws with Metal, or else with OpenGL ES, or else with its own@@ -10,7 +10,7 @@* -API 3* -setParameter:to: noted* -getMacroContextPrivate a table of functions, called as entry(table[0], arguments...) at- * the offsets of iOS's own OpenGLES (src/eagl_slots.txt); ours is+ * the offsets of Darwin's own OpenGLES (src/eagl_slots.txt); ours is* made by mkeagl.py: each entry counts the call and passes it on,* except the ones written by hand below (my_gl...)* -texImageIOSurface:target:internalFormat:width:height:format:type:plane:invert:@@ -28,7 +28,7 @@* (glFlush, glFinish), with nothing but OpenGL ES calls. Either way this file does not know* what draws: the library is reached through its gl* functions and the functions of hakios.gl.h.*- * Where CoreAnimation relies on iOS's library being what it is, this stands in between:+ * Where CoreAnimation relies on Darwin's library being what it is, this stands in between:* blue-first pixels into a texture called GL_RGBA (internal_format()), shaders that read* textures at coordinates in pixels (my_glShaderSource()), and draws made with no program* (plain_draw_begin()).@@ -209,7 +209,7 @@ now_us(void)/* ---- a context -------------------------------------------------------------------------------- */-#define SLOTS 0x440 /* entries of the table: more than iOS's has (checked below) */+#define SLOTS 0x440 /* entries of the table: more than Darwin's has (checked below) *//* (a vibrant layer inside a group: see group_draw_begin()) */#define GROUP_TEXTURES 8192@@ -1603,7 +1603,7 @@ triangles_of(GLenum mode, GLsizei count)/** CoreAnimation's OpenGL ES renderer draws the last of its ninety "functions" (0x59, "cst" in the* table its Metal renderer names its shaders by; no textures of its own by that table) with no- * program at all: glUseProgram(0), and then the draw. On iOS's library that may have meant+ * program at all: glUseProgram(0), and then the draw. On Darwin's library that may have meant* something; in OpenGL ES it draws nothing, and what goes that way is missing from the picture:* the lock screen's wallpaper, and the clock that is that wallpaper seen through its digits.* Here such a draw is made with a program of ours, the plainest there could be: CoreAnimation's@@ -3248,7 +3248,7 @@ my_glGetString(void *context, GLenum name)const GLubyte *string;EAGL_ENTER(e, 0x3b0);- /* 0x8a1e is no name of OpenGL ES's; iOS's library answers it (the constructor of CA::OGL::GLESContext asks) */+ /* 0x8a1e is no name of OpenGL ES's; Darwin's library answers it (the constructor of CA::OGL::GLESContext asks) */string = name == 0x8a1e ? (const GLubyte *)"" : glGetString(name);if (name == GL_EXTENSIONS && string != NULL && !fetch_offered) {static char without[8192]; /* (the list less that extension: see fetch_offered) */@@ -3269,7 +3269,7 @@ my_glGetString(void *context, GLenum name)}/* The list of extensions is longer than a line of the log, and it was being cut at 900characters -- which is where one looks to see whether the driver takes a compressed- texture of iOS's kind (ASTC). In pieces, then, so that none of it is lost. */+ texture of Darwin's kind (ASTC). In pieces, then, so that none of it is lost. */if (name == GL_EXTENSIONS && string != NULL) {size_t length = strlen((const char *)string);@@ -3574,7 +3574,7 @@ my_glDeleteFramebuffers(void *context, GLsizei n, const GLuint *framebuffers)EAGL_LEAVE(e, 0x1510);}-/* A private entry of iOS's library (CA::OGL::GLESContext::set_surface calls it); nobody else has it. */+/* A private entry of Darwin's library (CA::OGL::GLESContext::set_surface calls it); nobody else has it. */static voidmy_glFramebufferParameteriAPPLE(void *context, GLenum target, GLenum name, GLint value){@@ -3788,7 +3788,7 @@ my_glLinkProgram(void *context, GLuint program)EAGL_LEAVE(e, 0x12c0);}-/* iOS's library has one entry for deleting a program and deleting a shader. */+/* Darwin's library has one entry for deleting a program and deleting a shader. */static voidmy_glDeleteProgram(void *context, GLuint name){@@ -3854,7 +3854,7 @@ my_API(id self, SEL selector)/** -[EAGLContext sharegroup]. CoreAnimation never asks for it, but CoreImage does: a CIContext made* over an EAGLContext goes +[CIContext contextWithEAGLContext:] -> internalContextWithEAGLContext:- * -> CI::GLContext::GLContext -> wrapEAGLContextCreate -> -[EAGLContext sharegroup], and iOS's own+ * -> CI::GLContext::GLContext -> wrapEAGLContextCreate -> -[EAGLContext sharegroup], and Darwin's own* accessor reads ivars of an EAGLContext that my_initWithAPI never filled in (it keeps its state in* `struct eagl` beside the object and does not call through to Apple's init). On the phone that* crashed in -[EAGLContext sharegroup]+4 touching address 0x8. Nothing here shares a context with@@ -3982,7 +3982,7 @@ my_attachImage(id self, SEL selector, unsigned long target, IOSurfaceRef surface* there is in the black ones, and the one sign with colours in it, blue in the software* renderer's picture, comes out orange if red is taken to follow the opacity). Read* blue-first, like the surfaces that are drawn into, the black ones have no opacity at all- * and are not seen. iOS's library has the order from the surface; here it is taken from+ * and are not seen. Darwin's library has the order from the surface; here it is taken from* there being no pixel format.*/image->wrapped = image->alpha_first = pixels == 0;diff --git a/userland/src/eagl_slots.txt b/userland/src/eagl_slots.txtindex 3a28c2d..89259c5 100644--- a/userland/src/eagl_slots.txt+++ b/userland/src/eagl_slots.txt@@ -1,4 +1,4 @@-# The function table behind -[EAGLContext getMacroContextPrivate] of iOS 16.5 (20F66) OpenGLES: the offset of+# The function table behind -[EAGLContext getMacroContextPrivate] of Darwin userland 16.5 (20F66) OpenGLES: the offset of# each entry and the functions of OpenGLES.framework that call through it (read off their code: each loads# the table from thread-local storage and jumps through one offset). An entry is called as# entry(table[0], arguments...). '*' marks the entries QuartzCore's OpenGL ES renderer is seen to call.diff --git a/userland/src/hakios.audio.h b/userland/src/hakios.audio.hindex 91ec377..8c87890 100644--- a/userland/src/hakios.audio.h+++ b/userland/src/hakios.audio.h@@ -1,7 +1,7 @@/*- * /dev/hakios-audio: the sound iOS plays, on its way to whatever can make it heard.+ * /dev/hakios-audio: the sound Darwin plays, on its way to whatever can make it heard.*- * iOS expects its output devices from Apple's audio drivers through IOAudio2; neither exists+ * Darwin expects its output devices from Apple's audio drivers through IOAudio2; neither exists* here. Instead the audio server (mediaserverd) is given a plug-in of ours that presents one* stereo output device, and the plug-in writes what the server has mixed for that device* here. In the kernel the samples go to a sink -- a driver for something that plays them --@@ -24,9 +24,9 @@#define HAKIOS_AUDIO_FRAME 4 /* bytes *//*- * ioctl(HAKIOS_AUDIO_SET_VOLUME): the speakers' volume, as iOS sets it on the plug-in's volume+ * ioctl(HAKIOS_AUDIO_SET_VOLUME): the speakers' volume, as Darwin sets it on the plug-in's volume* control -- how many eighths of a dB under the loudest they may play, and whether they are- * muted (iOS's volume at 0). The loudest is the kernel's to say (on the phone: Android's own+ * muted (Darwin's volume at 0). The loudest is the kernel's to say (on the phone: Android's own* level less sound_below, hakios.sound.c); the plug-in only says how far under it.*/#include <sys/ioccom.h>@@ -47,7 +47,7 @@ struct hakios_audio_volume {typedef uint32_t (*hakios_audio_sink_t)(const int16_t *frames, uint32_t count);void hakios_audio_set_sink(const char *name, hakios_audio_sink_t sink);-/* The volume iOS has set last (HAKIOS_AUDIO_SET_VOLUME): false if it has set none; *generation counts the settings. */+/* The volume Darwin has set last (HAKIOS_AUDIO_SET_VOLUME): false if it has set none; *generation counts the settings. */bool hakios_audio_volume(uint32_t *below, bool *muted, uint32_t *generation);void hakios_audio_init(void);void hakios_virtio_sound_init(void); /* boot-arg virtio_sound=1: QEMU's virtio sound device */diff --git a/userland/src/hakios.camera.h b/userland/src/hakios.camera.hindex 978151e..5e12cc2 100644--- a/userland/src/hakios.camera.h+++ b/userland/src/hakios.camera.h@@ -1,5 +1,5 @@/*- * /dev/hakios-camera: the phone's wide camera for iOS (boot-arg cam=5; the kernel's drivers/camera/hakios.camera.c,+ * /dev/hakios-camera: the phone's wide camera for Darwin (boot-arg cam=5; the kernel's drivers/camera/hakios.camera.c,* whose bsd/sys/hakios.camera.h this is a copy of).** open() the first one powers the sensor up and starts its frames (the sensor's mode: boot-argdiff --git a/userland/src/hakios.input.h b/userland/src/hakios.input.hindex e93aca2..eb919ae 100644--- a/userland/src/hakios.input.h+++ b/userland/src/hakios.input.h@@ -2,7 +2,7 @@* /dev/hakios-touch: touch samples on their way from whoever produces them to the* program that turns them into HID events for the window server.*- * iOS expects touches from Apple's multitouch driver through IOHIDFamily; neither exists+ * Darwin expects touches from Apple's multitouch driver through IOHIDFamily; neither exists* here. Instead a producer -- a kernel driver for a real touch controller or for an emulated* pointer, or a user program replaying a script -- posts samples, and code of ours running* inside backboardd reads them and synthesizes the events. Both sides use the same record.diff --git a/userland/src/hakios_metallib.h b/userland/src/hakios_metallib.hindex ad8a2fd..80d4c14 100644--- a/userland/src/hakios_metallib.h+++ b/userland/src/hakios_metallib.h@@ -35,7 +35,7 @@ struct hakios_metallib_function {};struct hakios_metallib {- uint16_t version[2]; /* the container's (32769.2 on iOS 16.5) */+ uint16_t version[2]; /* the container's (32769.2 on Darwin userland 16.5) */uint64_t file_size; /* what the header says the file is */uint32_t count; /* the functions in the file (more than were kept, if the caller's array was short) */};diff --git a/userland/src/hello_dyn.c b/userland/src/hello_dyn.cindex 0e589ad..1bf1662 100644--- a/userland/src/hello_dyn.c+++ b/userland/src/hello_dyn.c@@ -1,5 +1,5 @@/*- * The first ordinary program: dynamically linked against the real iOS+ * The first ordinary program: dynamically linked against the real Darwin* libSystem, loaded by the real dyld out of the dyld shared cache.*/#include <stdio.h>diff --git a/userland/src/init.c b/userland/src/init.cindex 755cace..6801ce2 100644--- a/userland/src/init.c+++ b/userland/src/init.c@@ -7,7 +7,7 @@* a system expects there;* - checks what the kernel can do for user space, one line per check;* - runs the commands listed in etc/rc of its image: usually just- * "exec /sbin/launchd.ios", which turns process 1 into the iOS launchd;+ * "exec /sbin/launchd.darwin", which turns process 1 into the Darwin launchd;* - halts the machine if it is still process 1 after that.** Started with a file name by anything else, it is a command runner: that is@@ -35,9 +35,9 @@ in_image(const char *path)return buf;}-/* ---- the iOS root volume on the phone's flash as the root (boot-arg root_apfs=DEV) ---- */+/* ---- the Darwin root volume on the phone's flash as the root (boot-arg root_apfs=DEV) ---- */-/* the root is the iOS volume: its /sbin/launchd is Apple's, there is no launchd.ios */+/* the root is the Darwin volume: its /sbin/launchd is Apple's, there is no launchd.darwin */static int flash_root_mode;static void check(int ok, const char *what);@@ -115,22 +115,22 @@ synthetic_dir(const char *path)}/*- * root_apfs=DEV: the root is to be the iOS root volume on /dev/DEV -- the phone's flash, read+ * root_apfs=DEV: the root is to be the Darwin root volume on /dev/DEV -- the phone's flash, read* only. The kernel has started off the boot volume of flashboot.apfs (the resident image, md0,* its first container: stage0, firmware, mount points; the OS cryptex with the dyld shared cache- * is its second container) and stage0 has mounted this image on /redwood. What the big system image changes in iOS (userland/build.sh) is put in place on+ * is its second container) and stage0 has mounted this image on /redwood. What the big system image changes in Darwin (userland/build.sh) is put in place on* the volume instead, without writing to it:- * - our choice of launchd jobs instead of iOS's 500 (this image's LaunchDaemons, and+ * - our choice of launchd jobs instead of Darwin's 500 (this image's LaunchDaemons, and* nothing for NanoLaunchDaemons, LaunchAngels, nor xpc's launchd.plist, which launchd* would read instead of the directory);* - only our audio device among the audio server's plug-ins;- * - the applications iOS installs on its first boot (private/var/staged_system_apps)+ * - the applications Darwin installs on its first boot (private/var/staged_system_apps)* among the system's own in /Applications: another name for each there (a synthetic* entry of the volume -- not a mount, which whatever registers the system's* applications passed over), made before /private/var is covered by a memory* filesystem.* Then the volume becomes the root (sysctl kern.hakios_switch_root) and the boot volume- * goes to its /private/preboot, the cryptexes onto that volume's Cryptexes/OS and App: the iOS+ * goes to its /private/preboot, the cryptexes onto that volume's Cryptexes/OS and App: the Darwin* volume's /System/Cryptexes/OS and App point to /private/preboot/Cryptexes/OS and App, and the* kernel takes a shared cache from the first. This* image goes along with it, to /private/preboot/redwood, and is bound back on /redwood, a@@ -143,7 +143,7 @@ synthetic_dir(const char *path)/** Mount a cryptex on /private/preboot/Cryptexes/NAME: container C (",c=N") of md0, or, when md0 has* no such container (EINVAL: the RAM part of the boot is the boot volume alone), the same container- * of the device the iOS volume came from. Neither: said, and a check fails.+ * of the device the Darwin volume came from. Neither: said, and a check fails.*/static voidmount_cryptex(const char *name, const char *container, const char *flashdev)@@ -182,13 +182,13 @@ flash_root(const char *dev)ssize_t n;int fd, ok, apps = 0, bound = 0;- printf("\n-- the iOS root volume on /dev/%s as the root --\n", dev);+ printf("\n-- the Darwin root volume on /dev/%s as the root --\n", dev);strcpy(devpath, join("/dev/", dev, ""));ok = mount("apfs", "/flash", MNT_RDONLY, devpath) == 0;if (!ok) {printf(" mount %s: %s\n", devpath, strerror(errno));}- check(ok, "mount the iOS volume read only");+ check(ok, "mount the Darwin volume read only");if (!ok) {return;}@@ -196,7 +196,7 @@ flash_root(const char *dev)check(bind_dir(in_image("/LaunchDaemons"), "/flash/System/Library/LaunchDaemons") &&bind_dir(in_image("/empty"), "/flash/System/Library/NanoLaunchDaemons") &&bind_dir(in_image("/empty"), "/flash/System/Library/LaunchAngels") &&- bind_dir(in_image("/xpc"), "/flash/System/Library/xpc"), "our launchd jobs, not iOS's");+ bind_dir(in_image("/xpc"), "/flash/System/Library/xpc"), "our launchd jobs, not Darwin's");check(bind_dir(in_image("/hal"), "/flash/System/Library/Audio/Plug-Ins/HAL"),"our audio device, not Apple's plug-ins");if (stat("/fw", &fw_st) == 0) {@@ -206,7 +206,7 @@ flash_root(const char *dev)if (stat("/jb-bin", &fw_st) == 0) {/** The package manager's prefix is in the boot volume (/jb), and Sileo runs mv, cp, rm, mkdir- * and chmod from /bin, where iOS has df and ps alone (userland/build.sh, SILEO_BIN): the boot+ * and chmod from /bin, where Darwin has df and ps alone (userland/build.sh, SILEO_BIN): the boot* volume's jb-bin -- those five, links into the prefix -- over the volume's /bin as a union* mount, through which what it does not have is found in the /bin below.*/@@ -251,17 +251,17 @@ flash_root(const char *dev)if (!ok) {printf(" switching the root: %s\n", strerror(errno));}- check(ok, "the iOS volume is the root, the RAM part of the boot on /private/preboot");+ check(ok, "the Darwin volume is the root, the RAM part of the boot on /private/preboot");if (!ok) {return;}chdir("/");/*- * The cryptexes, where iOS grafts them: the boot volume's empty Cryptexes/OS and Cryptexes/App,- * now /private/preboot/Cryptexes/OS and App, where the iOS volume's /System/Cryptexes/OS and App+ * The cryptexes, where Darwin grafts them: the boot volume's empty Cryptexes/OS and Cryptexes/App,+ * now /private/preboot/Cryptexes/OS and App, where the Darwin volume's /System/Cryptexes/OS and App* point (and the kernel takes a shared cache from the first, bsd/vm/vm_unix.c). Each from md0 when* the RAM part of the boot has it (flashboot.apfs: the second and third containers), else from- * the flash -- darwin, where Apple's images lie as they are after the iOS volume (containers 1 and 2+ * the flash -- darwin, where Apple's images lie as they are after the Darwin volume (containers 1 and 2* of the root's own device).*/mount_cryptex("OS", ",c=1", devpath);@@ -503,7 +503,7 @@ test_processes(void)}/*- * Present only in the image that carries the iOS dyld and shared cache:+ * Present only in the image that carries the Darwin dyld and shared cache:* an ordinary dynamically linked program.*/static void@@ -568,7 +568,7 @@ parse_number(const char *text, int radix)/** /private/var is an empty directory of the read-only root: give it a* memory-backed filesystem and the directories a system expects there.- * (/tmp is a symlink to /private/var/tmp, as on iOS.)+ * (/tmp is a symlink to /private/var/tmp, as on Darwin.)*/static intcopy_file(const char *from, const char *to, int mode, int uid, int gid)@@ -823,7 +823,7 @@ read_whole(const char *path, char *buf, size_t size)/** The data volume on the phone's flash (boot-arg var_hfs=DEV, DEV a node of /dev: ufs_darwin_data, darwin past the- * iOS volume and the cryptexes): HFS Plus, which this kernel has built in, so that what iOS keeps in /private/var is+ * Darwin volume and the cryptexes): HFS Plus, which this kernel has built in, so that what Darwin keeps in /private/var is* there at the next boot and its size is the size of the space -- not a memory filesystem's quarter of the RAM.* Journaled: a phone reset in the middle of a write finds the volume whole at the next mount. If it does not mount* (no volume made there yet, or this kernel cannot write it), the memory filesystem as before.@@ -929,7 +929,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 (sysimage/mkvarskel.py) */+ /* the directories of the data volume, as listed in the template that ships with Darwin (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];@@ -953,7 +953,7 @@ mount_writable(void)symlink(f[1], f[2]);} else if (count == 6 && f[0][0] == 'f') {/* a file of ours to start with (build.sh: the var/ directory): mode, owner, group, path, source in the image;- * on the kept volume only if it is not there yet -- what iOS made of it since is what counts */+ * on the kept volume only if it is not there yet -- what Darwin made of it since is what counts */if (var_kept && lstat(f[4], &st) == 0) {files++;} else if (!copy_file(in_image(f[5]), f[4], (int)parse_number(f[1], 8), (int)parse_number(f[2], 10),@@ -981,7 +981,7 @@ mount_writable(void)/** and the package manager's prefix, when the image was built with one (tools/mk-jb.sh): /jb of- * the system image in RAM, or, with the iOS volume on the flash as the root, /private/preboot/jb+ * the system image in RAM, or, with the Darwin volume on the flash as the root, /private/preboot/jb* -- the boot volume, where a rootless jailbreak on an iPhone keeps its Procursus too* (/var/jb leads into /private/preboot there)*/@@ -1039,14 +1039,14 @@ mount_writable(void)}grafted = own_tree("/private/var/jb/var/mobile", 501) && grafted;/*- * The prefix's own user database. Its programs do not ask iOS who a user is: they are+ * The prefix's own user database. Its programs do not ask Darwin who a user is: they are* built against libiosexec, which carries an ie_getpwnam of its own and reads* /var/jb/etc/pwd.db -- a Berkeley database that pwd_mkdb makes from master.passwd and* that the bootstrap does not ship, only the text it is made from. Without it every* program of the prefix answers "no such user": an sshd from here refused every login- * with "Invalid user root" while iOS's own /bin/ps resolved users perfectly -- and the- * asymmetry is exactly this, not anything about iOS's own database or the launchd domain- * its server sits in, because a program of the prefix never asks iOS at all. The+ * with "Invalid user root" while Darwin's own /bin/ps resolved users perfectly -- and the+ * asymmetry is exactly this, not anything about Darwin's own database or the launchd domain+ * its server sits in, because a program of the prefix never asks Darwin at all. The* writable copy of the prefix is new at every boot, so the database is made at every* boot; it takes milliseconds.*/@@ -1072,9 +1072,9 @@ mount_writable(void)/** What the last boot left in /private/var, back out of the phone's flash (var_store=1): the- * memory filesystem is empty at every boot, so everything iOS writes -- the home screen's layout,+ * memory filesystem is empty at every boot, so everything Darwin writes -- the home screen's layout,* the applications' own data, the snapshots and the baked wallpaper -- would otherwise be new- * again every time. userland/src/var_store.c keeps a copy in the partition darwin, past the iOS+ * again every time. userland/src/var_store.c keeps a copy in the partition darwin, past the Darwin* volume and the cryptexes, and puts it back here, over the skeleton: a name the skeleton has and* the store has too comes out as the store has it. A store that is not there or does not check* out leaves what the skeleton made, and the boot goes on either way -- so a bad store cannot@@ -1327,8 +1327,8 @@ run_command(char *line)close(null);}}- if (flash_root_mode && strcmp(argv[1], "/sbin/launchd.ios") == 0) {- argv[1] = "/sbin/launchd"; /* the root is iOS's own volume: its launchd is that */+ if (flash_root_mode && strcmp(argv[1], "/sbin/launchd.darwin") == 0) {+ argv[1] = "/sbin/launchd"; /* the root is Darwin's own volume: its launchd is that */}execve(argv[1], argv + 1, envp);printf("%s: %s\n", argv[1], strerror(errno));@@ -1487,7 +1487,7 @@ configure_inject(void)/** The kernel is configured for a very small machine (the size class "xsmall" of- * config/MASTER.arm64.bcm2837) and so stops at 1024 vnodes, whatever the memory. An iOS system+ * config/MASTER.arm64.bcm2837) and so stops at 1024 vnodes, whatever the memory. An Darwin system* with an application open needs more: the table fills ("vnode: table is full"), opens wait and* idle daemons are killed to free vnodes. Give it what the kernel's own rule gives a bigger* configuration -- one for every 64 KB of memory, and 1024 -- up to MAX_VNODES.diff --git a/userland/src/inject.c b/userland/src/inject.cindex fb9f6b2..1a125f2 100644--- a/userland/src/inject.c+++ b/userland/src/inject.c@@ -1,5 +1,5 @@/*- * libhakios.dylib: code of ours inside stock iOS programs.+ * libhakios.dylib: code of ours inside stock Darwin programs.** launchd starts the jobs named in INJECT (see build.sh / mkjobs.py) with* DYLD_INSERT_LIBRARIES pointing here; dyld honours that because the kernel's AMFI stand-in@@ -22,7 +22,7 @@* everything that needs a container (the window server, for one) waits with* them. Told that personas are not supported, they do not ask.*- * Addresses of things inside the dyld shared cache are those of iOS 16.5 (20F66) for iPhone10,3;+ * Addresses of things inside the dyld shared cache are those of Darwin userland 16.5 (20F66) for iPhone10,3;* every one is checked against what is expected to be there before it is touched.*/#include <CoreFoundation/CoreFoundation.h>@@ -581,7 +581,7 @@ brightness_fixes(void)/* ---- backboardd: the touch screen and the buttons ---------------------------------------------- */-/* IOKit's HID event system, the part that has no public header on iOS (prototypes checked against 20F66) */+/* IOKit's HID event system, the part that has no public header on Darwin (prototypes checked against 20F66) */typedef struct __IOHIDEvent *IOHIDEventRef;typedef struct __IOHIDEventSystemClient *IOHIDEventSystemClientRef;typedef struct __IOHIDServiceClient *IOHIDServiceClientRef;diff --git a/userland/src/inject_media.c b/userland/src/inject_media.cindex 43092f0..f9dcc59 100644--- a/userland/src/inject_media.c+++ b/userland/src/inject_media.c@@ -10,7 +10,7 @@* What the daemon is wanted for meanwhile is neither sound nor the camera: it is where* VideoToolbox decodes for everybody else (the service com.apple.coremedia.decompressionsession),* and a HEIC picture is HEVC inside. Without the daemon ImageIO has "no way to decode a HEIC",- * and the stock wallpaper of iOS 16, whose layers are four such pictures, is its gradient alone.+ * and the stock wallpaper of Darwin userland 16, whose layers are four such pictures, is its gradient alone.* There is no hardware decoder here; VideoToolbox takes its software one (VCPHEVC.videocodec).** The flashlight (only where the kernel has one: torch=3, /dev/hakios-torch): Control Center's@@ -408,7 +408,7 @@ emit_sample_buffer(id self, SEL selector, CMSampleBufferRef sample_buffer)* (com.apple.videotoolbox.videoencoder.hevc and .hevc.gva, behind its AVE): the photo encoder node* failed with kVTCouldNotFindVideoEncoderErr (-12908). Apple's software HEVC codec is in the system* all the same, VCPHEVC.videocodec, whose decoder VideoToolbox takes here for every HEIC picture (see- * the top), and there is an encoder in it, HEVCVideoEncoder_CreateInstance, that iOS never registers:+ * the top), and there is an encoder in it, HEVCVideoEncoder_CreateInstance, that Darwin never registers:* the codec's VCPHEVCRegisterEncoder is an empty function. It is registered here, as the codec* registers its decoder (VTRegisterVideoDecoderWithInfo, not hardware accelerated).*/@@ -479,7 +479,7 @@ flashlight_classes(void)/** The class methods replaced, each as soon as its class exists. `expected` is the unslid address- * of the code in iOS 16.5 (20F66): a method that is not what it was is left alone. `original`, where+ * of the code in Darwin userland 16.5 (20F66): a method that is not what it was is left alone. `original`, where* there is one, keeps what was there (the vendor's: given as it is wherever there is one, and where* there is none, ours only with the kernel's camera or flashlight).*/diff --git a/userland/src/inject_sb.c b/userland/src/inject_sb.cindex e902ca4..f93446d 100644--- a/userland/src/inject_sb.c+++ b/userland/src/inject_sb.c@@ -134,7 +134,7 @@ static uintptr_t slide;/** Replace -[CLASS SELECTOR] (or +[CLASS SELECTOR]: `kind` is that first character), whose code must now- * be at the unslid address `expected` (iOS 16.5, 20F66: what a replacement does depends on what the+ * be at the unslid address `expected` (Darwin userland 16.5, 20F66: what a replacement does depends on what the* original did). Returns the original.* (dyld interposing of the C functions underneath does not reach calls made from inside the* shared cache: there one library branches straight into the other.)@@ -190,12 +190,12 @@ set_setup_required_reason(id self, SEL selector, long reason)/** +[XBApplicationSnapshotManifestImpl _outputFormatForSnapshot:] chooses the file format of the picture* SpringBoard takes of an application that leaves the screen: 0 = PNG, 1 and 2 = ATX (an ASTC texture),- * 3 = JPEG. A device with a wide colour display that can decode ASTC gets ATX, and iOS compresses it on+ * 3 = JPEG. A device with a wide colour display that can decode ASTC gets ATX, and Darwin compresses it on* the processor: fast with the vector code of Apple's cores, but here it takes one core more than ten* seconds per picture (under QEMU; seconds on the phone) -- and all that time the application waits for* the answer, until the watchdog for scene updates (10 s, there is no setting to scale it) kills it:* no application survived going to the background. JPEG takes a fraction of a second; it has no- * transparency, so a picture that needs it becomes a PNG (which is what iOS itself does on a device+ * transparency, so a picture that needs it becomes a PNG (which is what Darwin itself does on a device* without ASTC).*/#define SNAPSHOT_FORMAT_PNG 0@@ -216,17 +216,17 @@ snapshot_output_format(__unused id self, __unused SEL selector, id snapshot)/* ---- battery state from redwood's Qualcomm charger stack ----------------------------------------- *//*- * iOS reads battery level through UIDevice.batteryLevel and UIDevice.batteryState; SpringBoard's+ * Darwin reads battery level through UIDevice.batteryLevel and UIDevice.batteryState; SpringBoard's* status bar reads it the same way via SBBatteryController. Where the battery has no power source* of its own in the kernel (battery=1, the loader's way through Qualcomm's UEFI charger protocols),* we hook the UIDevice accessors to return what XNU publishes as kern.hakios.battery_soc (0..100)* and kern.hakios.battery_charging.* When the sysctl is missing (battery=1 not in boot-args, or the driver never started) we hand- * back the value the real implementation computed; the status bar then shows whatever iOS last+ * back the value the real implementation computed; the status bar then shows whatever Darwin last* knew, which is better than crashing.* With adsp=1 the battery is a power source (the service HakiosBattery, an IOPMPowerSource:- * drivers/power/hakios.battery.cpp), which powerd reads like an iPhone's own, and from it iOS knows- * everything by itself; once that service is there, the hooks hand everything to iOS's own code.+ * drivers/power/hakios.battery.cpp), which powerd reads like an iPhone's own, and from it Darwin knows+ * everything by itself; once that service is there, the hooks hand everything to Darwin's own code.*/static float (*original_battery_level)(id self, SEL sel);static long (*original_battery_state)(id self, SEL sel);@@ -247,7 +247,7 @@ sysctl_int(const char *name)return value;}-/* Is the battery a power source that iOS reads by itself (see above)? Once it is, it stays one. */+/* Is the battery a power source that Darwin reads by itself (see above)? Once it is, it stays one. */static boolbattery_power_source(void){@@ -266,7 +266,7 @@ battery_power_source(void)/** SpringBoard's SBStatusBarStateAggregator fills the raw status bar data from CoreTelephony, which* has no baseband here. Its item updaters take the data and a getter and setter for the field- * (iOS 16.5: -[SBStatusBarStateAggregator _updateSignalStrengthItem:withData:SIMInfo:barsGetter:+ * (Darwin userland 16.5: -[SBStatusBarStateAggregator _updateSignalStrengthItem:withData:SIMInfo:barsGetter:* barsSetter:], and the like for the service string): the signal one is replaced so that, when the* kernel's modem is registered (sysctl kern.hakios.cellular_registered, _bars: hakios.mpss.c),* the bars are set and the item switched on (-[... _setItem:enabled:]). The aggregator's whole@@ -301,7 +301,7 @@ update_signal_item(id self, SEL sel, long item, void *data, id sim, void *getteritem, data, (void *)sim, getter, setter, up, registered, bars, dbm);}/*- * Force the signal item on. iOS hides it unless its own cellular stack (CommCenter, which is+ * Force the signal item on. Darwin hides it unless its own cellular stack (CommCenter, which is* not here) says there is service, so the bars never appear on their own. The kernel knows* the modem's state, so once it is up the item is shown here with the kernel's bars; when the* kernel has a reading but zero bars (a brief "no signal" sample, or a reading just after@@ -388,7 +388,7 @@ update_service_item(id self, SEL sel, long item, void *data, id sim, id other, v/** The bars are drawn by UIKit's signal view, whose "signal mode" says how: inactive (all bars grey),- * searching, or active (the bars that count dark). iOS's cellular stack (CommCenter, not here)+ * searching, or active (the bars that count dark). Darwin's cellular stack (CommCenter, not here)* puts it in active mode once there is service; without it the bars stay grey whatever their* number. So for the cellular signal view (not the Wi-Fi one), while the kernel says the modem is* registered, the mode is made active. The modes seen are said in the log once each.@@ -545,7 +545,7 @@ battery_state(id self, SEL sel)/** UIKitCore's status-bar view has its own presentation policy, separate from UIDevice. With the power- * source it is iOS's own again: the switch Battery Percentage in Settings > Battery, which the image+ * source it is Darwin's own again: the switch Battery Percentage in Settings > Battery, which the image* turns on (SBShowBatteryPercentage in userland/var/mobile/Library/Preferences/com.apple.springboard.plist).*/static BOOL@@ -578,7 +578,7 @@ battery_view_should_show_bolt(id self, SEL sel)/** The actual number the status bar draws. _UIBatteryView keeps the fill fraction (0.0..1.0) in- * chargePercent; it is set through setChargePercent: and read back for layout. iOS feeds it from+ * chargePercent; it is set through setChargePercent: and read back for layout. Darwin feeds it from* BatteryCenter / IOPowerSources, which is empty on this phone, so without us it sits near zero* (the "1%" the user saw). We override both sides: setChargePercent: so the stored value is ours* no matter who writes it, and the getter so any layout path that reads it agrees.@@ -771,7 +771,7 @@ unlock(void)}/*- * The poster switcher: on iOS 16 a long press on the lock screen's wallpaper shrinks it into a+ * The poster switcher: on Darwin userland 16 a long press on the lock screen's wallpaper shrinks it into a* row of posters to choose from or customize. The row is PosterBoard's, an application scene of* that process which the lock screen hosts (CSPosterSwitcherViewController, a CALayerHost of the* context of PosterBoard's window over an opaque black layer). PosterBoard does lay it out -- its@@ -833,7 +833,7 @@ text_of(id object)* shadow one expects to see. Only the wash is left out, because a wash of a colour that is not the* wallpaper's is worse than no wash at all. When something here can give PaperBoardUI a real* picture of the wallpaper, this hook is what should go -- and until then switcher_wallpaper=1- * among the boot-args puts it back as iOS asks for it, so that whoever works on the wallpaper can+ * among the boot-args puts it back as Darwin asks for it, so that whoever works on the wallpaper can* see at once whether their picture arrives, without rebuilding an image to find out.*/static void (*original_switcher_wallpaper_overlay)(id self, SEL selector);@@ -854,7 +854,7 @@ switcher_wallpaper_overlay(id self, SEL selector)}if (told++ == 0) {say("hakios: the switcher's wash of wallpaper is %s\n", wanted ?- "drawn as iOS asks (switcher_wallpaper=1)" : "left out: there is no picture of the wallpaper for it");+ "drawn as Darwin asks (switcher_wallpaper=1)" : "left out: there is no picture of the wallpaper for it");}if (wanted) {original_switcher_wallpaper_overlay(self, selector);@@ -1099,7 +1099,7 @@ layers(void)/** The switcher of running applications, on the notification com.hakios.switcher (rwtouch notify).* A drag up from the bottom edge is the way to it on a phone, but the touches a script puts in do- * not reach iOS's system gestures -- nothing comes of such a drag, not even going home -- and two+ * not reach Darwin's system gestures -- nothing comes of such a drag, not even going home -- and two* presses of the home button only go home (there is no home button on a phone of this shape, and* what is sent as one goes home and no more). SpringBoard opens it itself for anything that is* not a gesture (a hardware keyboard, accessibility): SBMainSwitcherControllerCoordinator, which@@ -1155,7 +1155,7 @@ switcher(void)* and Focus came in only when the springs had settled, at the end of the presentation. (On an iPhone* they are whole all along.) So in Control Center's window an opacity animation is replaced with an* eased-out fade of cc_fade=MS between the same values: the modules still fade in and out, and are at- * full opacity, glyphs whole, after a few frames. Off by default (iOS's own animations stay as they+ * full opacity, glyphs whole, after a few frames. Off by default (Darwin's own animations stay as they* are; the real fix belongs in the drawing, not in the animations): a workaround, for checks only.*/#define CC_FADE_MS 0@@ -1296,7 +1296,7 @@ hakios_springboard_init(void)/** Battery hooks on UIDevice: these are the methods every app and SpringBoard itself calls, so* hooking them here in the SpringBoard process covers both the status bar and any app that- * reads [UIDevice currentDevice].batteryLevel. The addresses are for iOS 16.5 (20F66).+ * reads [UIDevice currentDevice].batteryLevel. The addresses are for Darwin userland 16.5 (20F66).*/original_battery_level = (float (*)(id, SEL))replace_method("UIDevice", "batteryLevel", 0x1897021b0UL, (IMP)battery_level);original_battery_state = (long (*)(id, SEL))replace_method("UIDevice", "batteryState", 0x189209794UL, (IMP)battery_state);@@ -1413,7 +1413,7 @@ hakios_springboard_init(void)* failed, or the panel is a FocalTech and the firmware upload is still chewing through* ~114 KB of SPI (that takes a hot second during bring-up), the user ends up staring at a* dark lock screen with nothing to swipe. So we just forcibly dismiss it after 10 seconds- * so iOS always lands on the home screen even in the worst case. Harmless if touch is+ * so Darwin always lands on the home screen even in the worst case. Harmless if touch is* already working: the user just doesn't need to swipe themselves.* With autounlock=0 among the kernel's arguments the lock screen stays until it is swiped away* (to show the phone starting the way an iPhone does).diff --git a/userland/src/metal_test.m b/userland/src/metal_test.mindex f059b4f..5eb8157 100644--- a/userland/src/metal_test.m+++ b/userland/src/metal_test.m@@ -1,7 +1,7 @@/*- * metal_test: what iOS here believes about Metal, and what it does with the answer.+ * metal_test: what Darwin here believes about Metal, and what it does with the answer.*- * Nothing in iOS says a word when Metal is missing. A program asks for the system's device with+ * Nothing in Darwin says a word when Metal is missing. A program asks for the system's device with* MTLCreateSystemDefaultDevice(); if there is none it gets nil, with no log line, no error and no* reason, and whatever the caller does next -- fall back, draw nothing, or stop at an assertion --* is all that is ever seen. This prints the whole chain instead, so that a failure somewhere above@@ -21,7 +21,7 @@* an empty list is an answer given once and kept, silently, for the life of the process.** So the question "is there Metal" has exactly one answer, and no capability bit anywhere stands- * in for it. What iOS publishes about graphics besides -- MobileGestalt's GraphicsFeatureSetClass+ * in for it. What Darwin publishes about graphics besides -- MobileGestalt's GraphicsFeatureSetClass* and GraphicsFeatureSetFallbacks, from the device tree's "graphics-featureset-class" and* "graphics-featureset-fallbacks" -- is read by CoreUI and CoreThemeDefinition to choose which* compiled artwork to take out of an asset catalog, not by anything that decides how to draw; it@@ -365,7 +365,7 @@ device_objects(void)[names count] ? "; the first is " : "", [names count] ? [names[0] UTF8String] : "");}-/* What iOS publishes about graphics besides: artwork, not rendering (see the note above). */+/* What Darwin publishes about graphics besides: artwork, not rendering (see the note above). */static voidgestalt(void){@@ -402,7 +402,7 @@ static NSDictionary *coreimage_options;static int coreimage_over_eagl;/*- * The way back for CoreImage, if there is one. iOS 16.5's CoreImage carries a whole second back+ * The way back for CoreImage, if there is one. Darwin userland 16.5's CoreImage carries a whole second back* end on OpenGL ES -- CI::GLContext, CI::GLMainProgram, CI::GLTextureManager beside the* CI::MetalContext family -- it is linked against OpenGLES, it compiles its shaders as GLSL (not* AIR), and CIGLIsUsable() is compiled to "return 1". The public way in is@@ -424,7 +424,7 @@ make_eagl(void)* the way it does it -- replacing methods of EAGLContext through the ObjC runtime -- is local* to a process. The library installs itself from a constructor, so loading it is enough; what* it replaced it says itself in lines "hakios-gl:". Without this, EAGLContext here would be- * iOS's own, which is AppleMetalGLRenderer over Metal -- the thing that is missing.+ * Darwin's own, which is AppleMetalGLRenderer over Metal -- the thing that is missing.*/if (access(HAKIOS_GL, R_OK) != 0) {printf("metal_test: %s is not in this image: build it with GL=1\n", HAKIOS_GL);@@ -493,7 +493,7 @@ coreimage(void)return;}/*- * Which of CoreImage's two backends the default context took. iOS 16.5 has both:+ * Which of CoreImage's two backends the default context took. Darwin userland 16.5 has both:* CI::GLContext (with CI::GLMainProgram, CI::GLTextureManager) and CI::MetalContext* (with CI::MetalDAG, CI::MetalKernel); -[CIContext initWithOptions:] chooses between* them by CIGLIsUsable(). -isOpenGLBased and -device are private, so they are asked for@@ -659,7 +659,7 @@ main(int argc, char **argv)the_device();in_a_new_process("what the device makes: buffers, a library", "objects", 60);in_a_new_process("blits through Metal: copy and fill, done by the GPU", "blits", 60);- printf("metal_test: what iOS publishes about graphics (artwork, not rendering)\n");+ printf("metal_test: what Darwin publishes about graphics (artwork, not rendering)\n");gestalt();printf("metal_test: CoreImage, which has a path without Metal\n");/*diff --git a/userland/src/mg_test.c b/userland/src/mg_test.cindex cb52f04..595f052 100644--- a/userland/src/mg_test.c+++ b/userland/src/mg_test.c@@ -1,5 +1,5 @@/*- * mg_test: what MobileGestalt says about this device (the answers iOS builds its idea of the+ * mg_test: what MobileGestalt says about this device (the answers Darwin builds its idea of the* hardware from). usage: mg_test [KEY...]* A key may also be one of the obfuscated names programs ask by; "MGGetProductType" gives the number* MGGetProductType() returns (what programs tell the models apart by).diff --git a/userland/src/net_test.m b/userland/src/net_test.mindex 8207fa3..8853ded 100644--- a/userland/src/net_test.m+++ b/userland/src/net_test.m@@ -1,5 +1,5 @@/*- * net_test: bring the network interface up the way iOS itself would, and see whether iOS can+ * net_test: bring the network interface up the way Darwin itself would, and see whether Darwin can* use it. Each step is one layer of what a stock application needs:** usage: net_test STEP...@@ -37,7 +37,7 @@* plugin that does the configuring keeps its own list* of interfaces, straight from the kernel, and has a Mach interface of its own, the one the* "ipconfig" command of macOS uses ("ipconfig set en0 DHCP"; the command itself is not part of- * iOS). "dhcp" is one of its calls: the plugin makes a service for the interface that exists in+ * Darwin). "dhcp" is one of its calls: the plugin makes a service for the interface that exists in* no preferences file, runs DHCP, and publishes what it learns; the rest of configd then treats* it like any other service.* (Not "ipconfig set", the first call one thinks of: the service that one makes is gone at@@ -63,7 +63,7 @@#include <sys/socket.h>#include <unistd.h>-/* not in the iOS SDK's headers, in the libraries all the same */+/* not in the Darwin SDK's headers, in the libraries all the same */extern mach_port_t bootstrap_port;extern kern_return_t bootstrap_look_up(mach_port_t bootstrap, const char *name, mach_port_t *service);typedef const struct __SCDynamicStore *SCDynamicStoreRef;@@ -501,7 +501,7 @@ wrongjoin(void)return;}length = request.length;- /* the layout of iOS 16.5 (drivers/wifi/hakios.apple80211.c of the kernel): version, mode, authentication lower and+ /* the layout of Darwin userland 16.5 (drivers/wifi/hakios.apple80211.c of the kernel): version, mode, authentication lower and* upper, the name's length and the name, the access point (none: any), the key's version, length and kind (10:* a passphrase as typed), the key */memset(assoc, 0, sizeof(assoc));diff --git a/userland/src/shm_test.c b/userland/src/shm_test.cindex 9e1b5be..4c22941 100644--- a/userland/src/shm_test.c+++ b/userland/src/shm_test.c@@ -19,7 +19,7 @@#include <unistd.h>extern char **environ;-/* (the SDK's mach/mach_vm.h refuses to be included on iOS; the calls are there all the same) */+/* (the SDK's mach/mach_vm.h refuses to be included on Darwin; the calls are there all the same) */extern kern_return_t mach_vm_allocate(vm_map_t, mach_vm_address_t *, mach_vm_size_t, int);extern kern_return_t mach_vm_map(vm_map_t, mach_vm_address_t *, mach_vm_size_t, mach_vm_offset_t, int, mem_entry_name_port_t,memory_object_offset_t, boolean_t, vm_prot_t, vm_prot_t, vm_inherit_t);diff --git a/userland/src/sound_test.c b/userland/src/sound_test.cindex 7b153e7..00011ae 100644--- a/userland/src/sound_test.c+++ b/userland/src/sound_test.c@@ -1,5 +1,5 @@/*- * sound_test: make iOS play something, the way a program would.+ * sound_test: make Darwin play something, the way a program would.** usage: sound_test STEP...* wait SECONDS@@ -9,14 +9,14 @@* tone SECONDS [LEFT_HZ RIGHT_HZ] a sine wave in each channel (default 1000 and 440 Hz) at half of* full scale, through an audio queue: what a music player does* level PEAK the tones after this one at PEAK of full scale (0 to 1) instead- * (before iOS's volume, which scales the samples itself)- * raw SECONDS the same tone written straight to /dev/hakios-audio, past iOS's own+ * (before Darwin's volume, which scales the samples itself)+ * raw SECONDS the same tone written straight to /dev/hakios-audio, past Darwin's own* processing and volume (which keep a tone more than 12 dB under full* scale even at the top): to try what the kernel does with full scale* system ID a system sound by its number (1100 is the lock sound,* 1104 a keyboard click), as SpringBoard plays them* file PATH a sound file, played as a system sound- * route where iOS says its sound goes: the audio session's outputs and volume,+ * route where Darwin says its sound goes: the audio session's outputs and volume,* and the devices of the system's output context* haptic [SECONDS] haptics the way an application (and UIKit's feedback generators) plays* them, through CoreHaptics: a tap, then a vibration of SECONDS (defaultdiff --git a/userland/src/stage0.c b/userland/src/stage0.cindex 516346f..3f04cc9 100644--- a/userland/src/stage0.c+++ b/userland/src/stage0.c@@ -1,7 +1,7 @@/** /sbin/launchd of the big system image: the first program the kernel runs.*- * The system image (the iOS files and the dyld shared cache) takes a minute+ * The system image (the Darwin files and the dyld shared cache) takes a minute* and a half to upload to the phone, so nothing that changes often lives in* it. All of that - the real init, its tests, the list of launchd jobs - is* in the small image that travels with the kernel (the second RAM disk,diff --git a/userland/src/svc_test.c b/userland/src/svc_test.cindex a31db9c..f6cc0fc 100644--- a/userland/src/svc_test.c+++ b/userland/src/svc_test.c@@ -1,5 +1,5 @@/*- * A client of the first real iOS services: each call below is answered by a+ * A client of the first real Darwin services: each call below is answered by a* daemon that launchd starts on demand.* notifyd - Darwin notifications (libnotify)* cfprefsd - preferences (CoreFoundation)diff --git a/userland/src/torch_test.c b/userland/src/torch_test.cindex 66fe60e..f4eed93 100644--- a/userland/src/torch_test.c+++ b/userland/src/torch_test.c@@ -9,7 +9,7 @@* off the flashlight off (level 0, then AVFlashlight's turnPowerOff)* state what the kernel says is lit now (thousandths of Android's current)*- * Says first whether iOS believes there is a flashlight (AVFlashlight's hasFlashlight: MobileGestalt's+ * Says first whether Darwin believes there is a flashlight (AVFlashlight's hasFlashlight: MobileGestalt's* camera-flash) and whether it is available.*/#include <CoreFoundation/CoreFoundation.h>diff --git a/userland/src/var_store.c b/userland/src/var_store.cindex 9339669..84f246b 100644--- a/userland/src/var_store.c+++ b/userland/src/var_store.c@@ -1,14 +1,14 @@/*- * The data volume of iOS between two boots: /private/var packed into the phone's flash and+ * The data volume of Darwin between two boots: /private/var packed into the phone's flash and* 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 (sysimage/mkvarskel.py), so nothing iOS keeps+ * given the directories of the template Darwin ships with (sysimage/mkvarskel.py), so nothing Darwin 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 archive* and the archive is written into the one place on the phone's flash this port owns and nothing of- * it uses: the partition darwin, past the iOS volume and both cryptexes. The kernel takes those+ * it uses: the partition darwin, past the Darwin volume and both cryptexes. The kernel takes those* writes on /dev/rufs_darwin alone and refuses anything else (drivers/storage/hakios.ufs.c, ufs_write=1).** var_store save pack /private/var into the store@@ -55,7 +55,7 @@#define ROOT "/private/var"#define MAX_PATH 1024#define MAX_DEPTH 32-#define MAX_XATTR (256u << 10) /* one attribute's value; iOS keeps small ones */+#define MAX_XATTR (256u << 10) /* one attribute's value; Darwin keeps small ones */#define XPACK (512u << 10) /* all the attributes of one file, packed */#define LINKS 8192 /* names remembered for hard links */#define LINK_PATH 256@@ -301,7 +301,7 @@ out_flush(int last)}/** What is already there is read first, and if it is what we were about to write, it is not- * written. A volume that iOS has stopped touching packs to the very same bytes -- measured:+ * written. A volume that Darwin has stopped touching packs to the very same bytes -- measured:* two saves a minute apart came out with the same checksum -- and the slots hold alternate* copies of it, so a save that changes nothing then costs reads and no writes at all. Reads* of this storage are several times cheaper than writes, and flash wears by writing.@@ -481,7 +481,7 @@ newest(struct head *out_head)* How much of this save is new since the last one: an entry whose time of writing is later than* the second the previous generation was saved at. It costs nothing to count -- the walk has every* entry's time in hand anyway -- and it is what says whether saving only the difference would be- * worth building, or whether iOS rewrites the volume faster than any such thing could help.+ * worth building, or whether Darwin rewrites the volume faster than any such thing could help.*/static uint64_t last_saved_at, changed_entries, changed_bytes;@@ -522,7 +522,7 @@ link_name(uint64_t ino, const char *relative)}/*- * The extended attributes of path -- iOS keeps container metadata and much else in them -- packed+ * The extended attributes of path -- Darwin keeps container metadata and much else in them -- packed* into a buffer of their own, because the entry's head says how many there are and has to go out* before them. One that does not fit is left out and counted.*/@@ -1247,7 +1247,7 @@ save_once(void)* The device is opened for the save and closed again, not held: while a write is in flight* this kernel's own transfer list is out of the controller, and it goes back in when the* device is closed (drivers/storage/hakios.ufs.c, ufs_cclose). A watcher that kept the device open- * would leave iOS reading the flash through the loader for the rest of the run.+ * would leave Darwin reading the flash through the loader for the rest of the run.*/fd = open(DEVICE, O_RDWR, 0);if (fd < 0) {diff --git a/userland/src/vol_ls.c b/userland/src/vol_ls.cindex 71ff153..0cc56c5 100644--- a/userland/src/vol_ls.c+++ b/userland/src/vol_ls.c@@ -1,6 +1,6 @@/** A look at a mounted volume from user space, on a system that has no ls of its own (the- * iOS root has df and ps in /bin and nothing else): what ls -l and cat would show, how+ * Darwin root has df and ps in /bin and nothing else): what ls -l and cat would show, how* the volume is mounted, and a hash of a file read both ways.** usage: vol_ls fs PATH the file system PATH is on: type, device, mount point, flagsdiff --git a/userland/var/mobile/Library/Preferences/com.apple.keyboard.preferences.plist b/userland/var/mobile/Library/Preferences/com.apple.keyboard.preferences.plistindex 2a7a675..37cf961 100644--- a/userland/var/mobile/Library/Preferences/com.apple.keyboard.preferences.plist+++ b/userland/var/mobile/Library/Preferences/com.apple.keyboard.preferences.plist@@ -2,7 +2,7 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>- <!-- the first time a keyboard comes up iOS shows how to type by sliding a finger over it, with a+ <!-- the first time a keyboard comes up Darwin shows how to type by sliding a finger over it, with afilm (UIKeyboardContinuousPathIntroduction*.mov, not in the image, and nothing here could playit): without the film UIKit puts nil into an array, and the application that wanted a keyboarddies. This says the introduction has been shown. -->diff --git a/wifi/lx/src/lx_80211.c b/wifi/lx/src/lx_80211.cindex a9c94da..0941945 100644--- a/wifi/lx/src/lx_80211.c+++ b/wifi/lx/src/lx_80211.c@@ -19,7 +19,7 @@** On the phone, 13 October, this scans -- 26 channels in 4.1 s, the access points around heard* with their channels and strengths -- and joins: the handshake is through 130 ms after the- * association, and iOS has the network (drivers/wifi/hakios.wifi.c, step_driver(), has the+ * association, and Darwin has the network (drivers/wifi/hakios.wifi.c, step_driver(), has the* account). What is said of other people's networks names them: it is for the log of the run.* The name of the network to join and its passphrase are never said, only their lengths.*/diff --git a/xl b/xlindex eebf9e1..f544465 100755--- a/xl+++ b/xl@@ -11,7 +11,7 @@# xl recording [F] fetch the screen recording the last run made (rec_secs=N among XL_CMDLINE) and# make a video of it (default logs/recording.mp4)# xl sound [F] fetch the sound the last run recorded (rec_sound=N among XL_CMDLINE: the first N-# seconds of what iOS played) and make a WAV file of it (default logs/sound.wav)+# seconds of what Darwin played) and make a WAV file of it (default logs/sound.wav)# xl camera [P] fetch the frames the last run's camera left (cam=3 and up among XL_CMDLINE) and make# pictures of them (P-0.png, ...; default prefix logs/camera)# xl selftest exercise only the kernel->loader return path@@ -61,7 +61,7 @@ K=hakios-kernel # make kernel makes itL=xnuloader/loader.efiif [ ! -f $L ]; thenL=prebuilt/loader.efi- echo "xl: no xnuloader/loader.efi: using prebuilt/loader.efi, which has no iPhone identity in it (iOS will not start; make loader builds one from your own IPSW)" >&2+ echo "xl: no xnuloader/loader.efi: using prebuilt/loader.efi, which has no iPhone identity in it (Darwin will not start; make loader builds one from your own IPSW)" >&2fimkdir -p logs# There is one phone, whichever working copy (tools/new-workspace.sh) talks to it: the locks are@@ -191,7 +191,7 @@ run() { # run <oem command> <label># The resident image: whose it is and how big, when the last upload was not from here.# Both values and not just "not from here", because a foreign image of the same kind# changes nothing, while a foreign one of another kind makes the boot fail in a way that- # names neither it nor its owner -- /sbin/launchd.ios: No such file or directory, with a+ # names neither it nor its owner -- /sbin/launchd.darwin: No such file or directory, with a# perfectly good image on this side. The warning is not a refusal: relying on another# copy's upload is legitimate when you know what it is, and this says what it is.if [ -s $PHONE.ramdisk ]; thendiff --git a/xnu-deps/setup.sh b/xnu-deps/setup.shindex ebf44f7..f506b30 100755--- a/xnu-deps/setup.sh+++ b/xnu-deps/setup.sh@@ -14,7 +14,7 @@# (toolchain/linux/iphone: the cctools linker) and sdks/iPhoneOS16.5.sdk.## What ends up where (all under xnu-deps/, none of it committed):-# AvailabilityVersions libdispatch libpthread Apple open source, at the releases of iOS 16.5+# AvailabilityVersions libdispatch libpthread Apple open source, at the releases of Darwin userland 16.5# mm_bootstrap_cmds tcsh unifdef sources of mig, csh and unifdef# MacOSX13.3.sdk only Kernel.framework: the DriverKit headers# that Apple's closed "iig" would generate@@ -28,7 +28,7 @@ source "$HERE/../xnu-env.sh"cd "$XNUDEPS"JOBS=${JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu)}CCTOOLS=$THEOS/toolchain/linux/iphone/bin-IOS_SDK=$THEOS/sdks/iPhoneOS16.5.sdk+DARWIN_SDK=$THEOS/sdks/iPhoneOS16.5.sdkMACOS_SDK_URL=https://github.com/joseluisq/macosx-sdks/releases/download/13.3/MacOSX13.3.sdk.tar.xzlog() { echo "setup: $*"; }@@ -102,7 +102,7 @@ stage1() {done[ -z "$missing" ] || die "not installed:$missing"[ -x "$CCTOOLS/ld" ] || die "no cctools in $CCTOOLS: install theos with its Linux toolchain (or set THEOS)"- [ -d "$IOS_SDK/usr/include" ] || die "no $IOS_SDK (the SDKs of github.com/theos/sdks go to \$THEOS/sdks)"+ [ -d "$DARWIN_SDK/usr/include" ] || die "no $DARWIN_SDK (the SDKs of github.com/theos/sdks go to \$THEOS/sdks)"# --- sources -------------------------------------------------------------------------------fetch AvailabilityVersions https://github.com/apple-oss-distributions/AvailabilityVersions.git \@@ -157,7 +157,7 @@ stage1() {cp tcsh/tcsh host/bin/tcshfilink tcsh host/bin/csh- # what 7z leaves undone when it extracts files of the iOS images (see build/lzbitmap/unzbm.c)+ # what 7z leaves undone when it extracts files of the Darwin images (see build/lzbitmap/unzbm.c)if [ ! -x host/bin/unzbm ]; thencc -O2 -w -o host/bin/unzbm build/lzbitmap/unzbm.c build/lzbitmap/libzbitmap.cfi@@ -177,9 +177,9 @@ stage1() {# The makefiles ask xcrun (ours: host/bin/xcrun) for an SDK and a platform directory.mkdir -p sdk/Platforms/iPhoneOS.platformif [ ! -d "$XNU_SDK_PATH/usr/include" ]; then- log "making the SDK: links to $IOS_SDK"+ log "making the SDK: links to $DARWIN_SDK"rm -rf "$XNU_SDK_PATH"- linktree "$(cd "$IOS_SDK" && pwd -P)" "$XNU_SDK_PATH"+ linktree "$(cd "$DARWIN_SDK" && pwd -P)" "$XNU_SDK_PATH"filocal sdk_local=$XNU_SDK_PATH/usr/localmkdir -p $sdk_local/include/kernel/os $sdk_local/include/os $sdk_local/lib/kernel $sdk_local/libexecdiff --git a/xnu-env.sh b/xnu-env.shindex 4a2179d..8e90285 100644--- a/xnu-env.sh+++ b/xnu-env.sh@@ -1,6 +1,6 @@# source this (from bash) before building XNU on Linux# Everything is found relative to this file. THEOS (default ~/theos) provides the cctools and the-# iOS SDK; XNU_SRC is the kernel tree (xnu/apply.sh creates it).+# Darwin SDK; XNU_SRC is the kernel tree (xnu/apply.sh creates it).DARWIN_REDWOOD=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)export DARWIN_REDWOODexport XNU_HOST_OS=$(uname)diff --git a/xnu/README.md b/xnu/README.mdindex 09e2998..b00548b 100644--- a/xnu/README.md+++ b/xnu/README.md@@ -1,6 +1,6 @@# The kernel-Our changes to XNU `xnu-8796.121.2` (the kernel of iOS 16.5, Darwin 22.5.0):+Our changes to XNU `xnu-8796.121.2` (the kernel of Darwin userland 16.5, Darwin 22.5.0):- `hakios.patch`: changes to Apple's files;- `files/`: new files at their paths in the XNU tree;@@ -24,7 +24,7 @@ xnu-deps/setup.sh # dependencies, mig/unifdef/tcsh, the SDK overlay, two```The kernel: `hakios-kernel` at the top of the repository (`make kernel` copies it there from XNU's `xnu-src/xnu-8796.121.2/BUILD/obj/DEVELOPMENT_ARM64_BCM2837/mach.development.bcm2837`).-`./xl run` and `qemu/run-ios.sh` take it from there (`prebuilt/` only when it is missing).+`./xl run` and `qemu/run-darwin.sh` take it from there (`prebuilt/` only when it is missing).Things to know:diff --git a/xnu/apply.sh b/xnu/apply.shindex 9aa07b0..7f7b206 100755--- a/xnu/apply.sh+++ b/xnu/apply.sh@@ -1,5 +1,5 @@#!/bin/bash-# Get Apple's XNU sources (the release that iOS 16.5 was built from) and put the HakiOS+# Get Apple's XNU sources (the release that Darwin userland 16.5 was built from) and put the HakiOS# work on top of them: hakios.patch changes Apple's files, files/ holds the new ones.# usage: xnu/apply.sh [DIR] (default: $XNU_SRC, else xnu-src/xnu-8796.121.2 next to this directory)# env: XNU_URL where to fetch from (default: Apple's repository on GitHub; an existing clonediff --git a/xnu/files/bsd/kern/kern_minimac.c b/xnu/files/bsd/kern/kern_minimac.cindex f65c979..dd6e082 100644--- a/xnu/files/bsd/kern/kern_minimac.c+++ b/xnu/files/bsd/kern/kern_minimac.c@@ -5,7 +5,7 @@* __mac_syscall() and relies on what they decide.** Neither stand-in is a security mechanism. This kernel runs whatever it is- * given (see libkern/amfi/miniamfi.c); these only give the answers the iOS+ * given (see libkern/amfi/miniamfi.c); these only give the answers the Darwin* user space needs in order to run at all:** AMFI The binaries of the operating system carry ad hoc signatures@@ -244,7 +244,7 @@ minisandbox_policy_syscall(struct proc *p, int call, user_addr_t arg)/** Privileges for processes that are not root. On a device the sandbox hands them out by* entitlement: a privilege is granted to a process whose code signature has the entitlement- * that goes with it. The table is the same pairing: the names are the entitlements iOS's own+ * that goes with it. The table is the same pairing: the names are the entitlements Darwin's own* programs carry for them (dasd "vm-pressure-level", symptomsd and aggregated* com.apple.private.network.statistics, mediaserverd and mDNSResponder* com.apple.private.network.socket-delegate -- without which NECP said "does not hold thediff --git a/xnu/files/bsd/miscfs/apfs/apfs.h b/xnu/files/bsd/miscfs/apfs/apfs.hindex af662d1..e1cefb3 100644--- a/xnu/files/bsd/miscfs/apfs/apfs.h+++ b/xnu/files/bsd/miscfs/apfs/apfs.h@@ -47,7 +47,7 @@ struct apfs_node;#define APFS_SYNTH_NAMELEN 96/** Object ids from here up are synthetic: the last few of the 60 bits an id has. (Not- * 0x0FFFFFFF00000000: the iOS root volume numbers its own objects from there.)+ * 0x0FFFFFFF00000000: the Darwin root volume numbers its own objects from there.)*/#define APFS_SYNTH_BASE 0x0FFFFFFFFFFFF000ULLdiff --git a/xnu/files/bsd/miscfs/apfs/apfs_format.h b/xnu/files/bsd/miscfs/apfs/apfs_format.hindex 973046d..cfcc7a3 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_format.h+++ b/xnu/files/bsd/miscfs/apfs/apfs_format.h@@ -14,7 +14,7 @@** Decompression of file contents (the com.apple.decmpfs attribute) is not part of APFS* and is not in the reference; it is at the end of this file, from bsd/sys/decmpfs.h and- * from what the iOS 16.5 root file system actually contains.+ * from what the Darwin userland 16.5 root file system actually contains.*/#ifndef _MISCFS_APFS_APFS_FORMAT_H_@@ -531,7 +531,7 @@ struct apfs_j_inode_val {#define APFS_INODE_IS_SYNC_ROOT 0x00200000#define APFS_INODE_SNAPSHOT_COW_EXEMPTION 0x00400000-/* directory entry. iOS uses the hashed key; the hash is of the name, case-folded. */+/* directory entry. Darwin uses the hashed key; the hash is of the name, case-folded. */struct apfs_j_drec_key {struct apfs_j_key hdr;uint16_t name_len; /* including the trailing zero byte */@@ -722,7 +722,7 @@ struct apfs_x_field {* themselves are depends on the type. The header is little-endian.** XNU (bsd/sys/decmpfs.h) names only type 1; the rest live in Apple's closed- * AppleFSCompression. The types below are the ones the iOS 16.5 root file system+ * AppleFSCompression. The types below are the ones the Darwin userland 16.5 root file system* actually uses -- see tools/apfs/apfs.py, which counts them over the whole volume.** In the attribute (types 3 and 4 the common pair): the bytes after the header are adiff --git a/xnu/files/bsd/miscfs/apfs/apfs_lib.c b/xnu/files/bsd/miscfs/apfs/apfs_lib.cindex db383dc..c7c268c 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_lib.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_lib.c@@ -647,7 +647,7 @@ tree_node_addr(struct apfs_btree *tree, uint64_t oid, uint64_t *addr);* of the object quietly go missing instead of the read failing.*//*- * A sealed volume (the iOS cryptexes) keeps its file-system tree in nodes without an object+ * A sealed volume (the Darwin cryptexes) keeps its file-system tree in nodes without an object* header -- no Fletcher checksum -- and each parent keeps the SHA-256 of each child's whole* block instead. Checked once per block the cache brings in (b->checked, which for such a* block means "its hash was right"); `len` is 32 on the way down, 8 when a cursor comes back@@ -1646,7 +1646,7 @@ apfs_readdir(struct apfs_vol *vol, uint64_t dir_id, apfs_dir_cb cb, void *ctx)return 0;}/*- * iOS uses the hashed key: a word holding the name's length and a hash of it,+ * Darwin uses the hashed key: a word holding the name's length and a hash of it,* then the name. The plain key has a 16-bit length instead; both are handled* so that a volume made elsewhere still reads.*/@@ -1727,7 +1727,7 @@ lookup_cb(void *ctx, const char *name, size_t name_len, uint64_t file_id, uint8_* caseless form (case-folded NFD), Unicode 9.0 as APFS has it. For the decomposition and folding* the kernel's own (bsd/vfs/vfs_unicode.c, utf8_normalizeOptCaseFoldAndHash, which is APFS's);* a name of plain ASCII needs neither and is hashed directly. Checked against the hash stored- * with every name of the iOS 16.5 root volume, ASCII and not (tools/apfs/test_namehash.py,+ * with every name of the Darwin userland 16.5 root volume, ASCII and not (tools/apfs/test_namehash.py,* apfs-tool namehash).*/static const uint32_t crc32c_nibble[16] = {@@ -3030,7 +3030,7 @@ apfs_zfree(voidpf opaque, voidpf address)* zlib's 344, and on the phone 1248 ms against 3834 for one reader (856 once its Adler-32* is the NEON one). It checks the stream's Adler-32 just as zlib does. A stream it will* not take is handed to zlib instead and counted, so that such a thing cannot go by- * unnoticed -- none of the pieces in either iOS volume is one. `d` is the caller's+ * unnoticed -- none of the pieces in either Darwin volume is one. `d` is the caller's* decompressor, NULL for one made here for this call alone.*/static int apfs_inflate_counted(struct apfs_nx *nx, const uint8_t *src, size_t src_len,@@ -3126,13 +3126,13 @@ apfs_inflate_counted(struct apfs_nx *nx, const uint8_t *src, size_t src_len, uin* bytes after the header.** Type 9 means they were stored as they are, with one marker byte in front. All 23947- * type-9 files in the iOS 16.5 root file system have 0xcc there and exactly `want` bytes+ * type-9 files in the Darwin userland 16.5 root file system have 0xcc there and exactly `want` bytes* after it, which is how the marker's length was settled; a payload that is already* exactly the right length is taken whole.*//** One piece of a compressed file by the file's method: zlib (types 3 and 4) as above;- * LZBITMAP (13 and 14) -- what the iOS 16 cryptexes use -- by libzbitmap (apfs_zbitmap.c):+ * LZBITMAP (13 and 14) -- what the Darwin userland 16 cryptexes use -- by libzbitmap (apfs_zbitmap.c):* a piece that starts with 'Z' is a stream of it, one whose first byte has its low four bits* set is stored after that byte.*/diff --git a/xnu/files/bsd/miscfs/apfs/apfs_lib.h b/xnu/files/bsd/miscfs/apfs/apfs_lib.hindex 74a6964..d0a64a2 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_lib.h+++ b/xnu/files/bsd/miscfs/apfs/apfs_lib.h@@ -296,14 +296,14 @@ struct apfs_vol {* Whether directory-entry keys carry a hash of the name. Apple's reference* describes both shapes of the key but never says which a volume uses; the hash it* defines (CRC-32C of the name decomposed and widened) is only of use for looking- * a name up without regard to case or normalization, and the iOS 16.5 volume, which+ * a name up without regard to case or normalization, and the Darwin userland 16.5 volume, which* is normalization-insensitive, does carry it. So: hashed when either of those two* features is on. A wrong guess does not go unnoticed -- the name length would not* fit the key and the record is refused.*/bool hashed_names;/*- * A sealed volume (the iOS 16 cryptexes) keeps its files' extents in a tree of their own,+ * A sealed volume (the Darwin userland 16 cryptexes) keeps its files' extents in a tree of their own,* keyed by stream and offset, rather than among the file-system tree's records.*/struct apfs_btree fext;diff --git a/xnu/files/bsd/miscfs/apfs/apfs_store.c b/xnu/files/bsd/miscfs/apfs/apfs_store.cindex 7abe968..9b78983 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_store.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_store.c@@ -3,7 +3,7 @@** What this is instead of* ------------------------ * The data of iOS survives a boot today by being packed into an archive and written into the+ * The data of Darwin survives a boot today by being packed into an archive and written into the* phone's flash at a number in a comment: two slots of two gigabytes each at byte 8589934592 of* the partition darwin, straight onto a character device (userland/src/var_store.c,* drivers/storage/hakios.ufs.c). It works, and its weakness is not the writing but the addressing --diff --git a/xnu/files/bsd/miscfs/apfs/apfs_vfsops.c b/xnu/files/bsd/miscfs/apfs/apfs_vfsops.cindex ae7dfac..d944094 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_vfsops.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_vfsops.c@@ -164,7 +164,7 @@ apfs_device_held(dev_t rdev)}/*- * Which volume kern.apfs_stats is about: the root's, when the root is APFS (the iOS volume on+ * Which volume kern.apfs_stats is about: the root's, when the root is APFS (the Darwin volume on* the flash, once init has switched to it); else the one mounted last.*/extern vnode_t rootvnode;diff --git a/xnu/files/bsd/miscfs/apfs/apfs_vnops.c b/xnu/files/bsd/miscfs/apfs/apfs_vnops.cindex e879d02..8b662f1 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_vnops.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_vnops.c@@ -337,7 +337,7 @@ apfs_vnop_lookup(struct vnop_lookup_args *ap)/** A name that is not there stays not there (the volume cannot change; a synthetic* directory added later purges its parent's entries): the name cache says so from now on,- * instead of asking again -- iOS asks for missing files thousands of times after a boot.+ * instead of asking again -- Darwin asks for missing files thousands of times after a boot.*/if (error == ENOENT && cnp->cn_nameiop == LOOKUP && (cnp->cn_flags & MAKEENTRY)) {cache_enter(dvp, NULLVP, cnp);@@ -1188,7 +1188,7 @@ apfs_vnop_reclaim(struct vnop_reclaim_args *ap)/** No ioctl or fsctl means anything here. ENOTTY is what callers take for "this filesystem- * does not have that"; the default, ENOTSUP, is not -- the iOS dyld, probing the root+ * does not have that"; the default, ENOTSUP, is not -- the Darwin dyld, probing the root* volume for APFS features, gives up on it.*/static intdiff --git a/xnu/files/bsd/miscfs/apfs/apfs_write.c b/xnu/files/bsd/miscfs/apfs/apfs_write.cindex 4ec37fa..217fdad 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_write.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_write.c@@ -143,7 +143,7 @@ apfs_write_volume_ok(struct apfs_vol *vol, const char **why)reason = "the volume has snapshots, which share its blocks";} else if (vol->role == APFS_VOL_ROLE_SYSTEM || vol->role == APFS_VOL_ROLE_PREBOOT) {/*- * Not an APFS rule but this port's: the system volume of iOS is not ours to+ * Not an APFS rule but this port's: the system volume of Darwin is not ours to* change. It is worth saying out loud because the gates above do not catch it --* on an iPhone that volume is sealed, but the copy this port boots from was* unpacked out of an IPSW and is not, so it would otherwise pass every check@@ -151,7 +151,7 @@ apfs_write_volume_ok(struct apfs_vol *vol, const char **why)* loader's BLOCK_WRITE_FIRST and a kernel whose block devices refuse every* write); this is one more fence in front of that, not instead of it.*/- reason = "the volume is iOS's own system or preboot volume";+ reason = "the volume is Darwin's own system or preboot volume";} else if (vol->extentref_oid == 0) {reason = "no extent-reference tree: nothing can say a block is not shared";}diff --git a/xnu/files/bsd/miscfs/apfs/apfs_zbitmap.c b/xnu/files/bsd/miscfs/apfs/apfs_zbitmap.cindex 1a8619f..6fbf7f2 100644--- a/xnu/files/bsd/miscfs/apfs/apfs_zbitmap.c+++ b/xnu/files/bsd/miscfs/apfs/apfs_zbitmap.c@@ -1,5 +1,5 @@/*- * LZBITMAP, Apple's method for the files of the iOS 16 cryptexes (decmpfs types 13 and 14:+ * LZBITMAP, Apple's method for the files of the Darwin userland 16 cryptexes (decmpfs types 13 and 14:* the OS cryptex of the IPSW keeps its dyld shared cache this way), so that a cryptex image* can be mounted as Apple ships it. The same file is built into the kernel and into* tools/apfs/apfs-tool.diff --git a/xnu/files/bsd/miscfs/ramfs/ramfs.c b/xnu/files/bsd/miscfs/ramfs/ramfs.cindex e3a4949..bba5dd1 100644--- a/xnu/files/bsd/miscfs/ramfs/ramfs.c+++ b/xnu/files/bsd/miscfs/ramfs/ramfs.c@@ -61,7 +61,7 @@ struct ramfs_dirent {uint32_t rd_namelen;};-/* An extended attribute: iOS keeps container metadata, ACLs and much else in them. */+/* An extended attribute: Darwin keeps container metadata, ACLs and much else in them. */struct ramfs_xattr {TAILQ_ENTRY(ramfs_xattr) rx_link;char *rx_name; /* rx_namelen bytes and a terminator */diff --git a/xnu/files/bsd/sys/hakios.audio.h b/xnu/files/bsd/sys/hakios.audio.hindex 59ad01d..9bcf18e 100644--- a/xnu/files/bsd/sys/hakios.audio.h+++ b/xnu/files/bsd/sys/hakios.audio.h@@ -1,7 +1,7 @@/*- * /dev/hakios-audio: the sound iOS plays, on its way to whatever can make it heard.+ * /dev/hakios-audio: the sound Darwin plays, on its way to whatever can make it heard.*- * iOS expects its output devices from Apple's audio drivers through IOAudio2; neither exists+ * Darwin expects its output devices from Apple's audio drivers through IOAudio2; neither exists* here. Instead the audio server (mediaserverd) is given a plug-in of ours that presents one* stereo output device, and the plug-in writes what the server has mixed for that device* here. In the kernel the samples go to a sink -- a driver for something that plays them --@@ -24,9 +24,9 @@#define HAKIOS_AUDIO_FRAME 4 /* bytes *//*- * ioctl(HAKIOS_AUDIO_SET_VOLUME): the speakers' volume, as iOS sets it on the plug-in's volume+ * ioctl(HAKIOS_AUDIO_SET_VOLUME): the speakers' volume, as Darwin sets it on the plug-in's volume* control -- how many eighths of a dB under the loudest they may play, and whether they are- * muted (iOS's volume at 0). The loudest is the kernel's to say (on the phone: Android's own+ * muted (Darwin's volume at 0). The loudest is the kernel's to say (on the phone: Android's own* level less sound_below, hakios.sound.c); the plug-in only says how far under it.*/#include <sys/ioccom.h>@@ -47,14 +47,14 @@ struct hakios_audio_volume {typedef uint32_t (*hakios_audio_sink_t)(const int16_t *frames, uint32_t count);void hakios_audio_set_sink(const char *name, hakios_audio_sink_t sink);-/* The volume iOS has set last (HAKIOS_AUDIO_SET_VOLUME): false if it has set none; *generation counts the settings. */+/* The volume Darwin has set last (HAKIOS_AUDIO_SET_VOLUME): false if it has set none; *generation counts the settings. */bool hakios_audio_volume(uint32_t *below, bool *muted, uint32_t *generation);void hakios_audio_init(void);void hakios_virtio_sound_init(void); /* boot-arg virtio_sound=1: QEMU's virtio sound device */void hakios_speaker_init(void); /* boot-arg speaker_probe=N: a look at the phone's speaker amplifiers */void hakios_haptic_init(void); /* boot-arg haptic=N: the phone's vibration motor (drivers/haptic/hakios.haptic.c) */void hakios_haptic_quiesce(void); /* its chip back into reset: at the run's end and on a panic's way out */-void hakios_haptic_pretend(uint32_t peak); /* a test's stand-in for iOS's waveform: as if a write of this loudness came */+void hakios_haptic_pretend(uint32_t peak); /* a test's stand-in for Darwin's waveform: as if a write of this loudness came */void hakios_torch_init(void); /* boot-arg torch=N: the phone's flashlight (drivers/camera/hakios.torch.c) */void hakios_torch_quiesce(void); /* the light off: at the run's end and on a panic's way out */void hakios_camera_init(void); /* boot-arg cam=N: the phone's cameras (drivers/camera/hakios.camera.c) */@@ -94,7 +94,7 @@ void hakios_guard_monitor(uint32_t below); /* a reduction asvoid hakios_guard_process(int16_t *frames, uint32_t count); /* stereo frames, in place */void hakios_guard_take_report(struct hakios_guard_report *report); /* what happened since the last call */int hakios_guard_decibels(uint64_t ratio); /* 10 log10 of a Q30 ratio, in tenths of a dB */-/* boot-arg rec_sound_fed=1: the recording (rec_sound=N) has what the guard let through instead of what iOS wrote */+/* boot-arg rec_sound_fed=1: the recording (rec_sound=N) has what the guard let through instead of what Darwin wrote */bool hakios_audio_recording_fed(void);void hakios_audio_record_fed(const int16_t *frames, uint32_t count);diff --git a/xnu/files/bsd/sys/hakios.camera.h b/xnu/files/bsd/sys/hakios.camera.hindex e5e7ea4..47be533 100644--- a/xnu/files/bsd/sys/hakios.camera.h+++ b/xnu/files/bsd/sys/hakios.camera.h@@ -1,5 +1,5 @@/*- * /dev/hakios-camera: the phone's wide camera for iOS (boot-arg cam=5; drivers/camera/hakios.camera.c).+ * /dev/hakios-camera: the phone's wide camera for Darwin (boot-arg cam=5; drivers/camera/hakios.camera.c).** open() the first one powers the sensor up and starts its frames (the sensor's mode: boot-arg* cam_mode, else the module file's 4000x3000 one); the last close puts everything downdiff --git a/xnu/files/bsd/sys/hakios.input.h b/xnu/files/bsd/sys/hakios.input.hindex 07125e1..bfb7d63 100644--- a/xnu/files/bsd/sys/hakios.input.h+++ b/xnu/files/bsd/sys/hakios.input.h@@ -2,7 +2,7 @@* /dev/hakios-touch: touch samples on their way from whoever produces them to the* program that turns them into HID events for the window server.*- * iOS expects touches from Apple's multitouch driver through IOHIDFamily; neither exists+ * Darwin expects touches from Apple's multitouch driver through IOHIDFamily; neither exists* here. Instead a producer -- a kernel driver for a real touch controller or for an emulated* pointer, or a user program replaying a script -- posts samples, and code of ours running* inside backboardd reads them and synthesizes the events. Both sides use the same record.@@ -56,7 +56,7 @@ void hakios_spmi_unlock(void);/** How the battery is, as the audio DSP's battery manager says (drivers/audio/hakios.adsp.c, with adsp=1):* handed to drivers/power/hakios.battery.c, which keeps it for the sysctls kern.hakios.battery_* and- * passes it on to drivers/power/hakios.battery.cpp, the power source that iOS reads. The structure+ * passes it on to drivers/power/hakios.battery.cpp, the power source that Darwin reads. The structure* is repeated there (this header is not seen from iokit/), and `size` tells whether the two agree.*/struct hakios_battery_state {diff --git a/xnu/files/bsd/sys/hakios.ipa.h b/xnu/files/bsd/sys/hakios.ipa.hindex 9c53ef7..51af148 100644--- a/xnu/files/bsd/sys/hakios.ipa.h+++ b/xnu/files/bsd/sys/hakios.ipa.h@@ -7,7 +7,7 @@* driver of the modem (hakios.mpss.c) brings the IPA up; hakios.ipa.c sets up this processor's* side of it -- GSI rings, the IPA's endpoints, its tables -- before the modem is started, and* then moves packets. hakios.cell.c makes an Ethernet-looking interface (en1) out of that, with- * an ARP and DHCP responder of its own, so that iOS configures it as it would a USB Ethernet+ * an ARP and DHCP responder of its own, so that Darwin configures it as it would a USB Ethernet* adapter: address, router and DNS come from the modem's data session (QMI WDS), which* hakios.mpss.c reports with hakios_cell_session().*/diff --git a/xnu/files/bsd/sys/hakios.net.h b/xnu/files/bsd/sys/hakios.net.hindex 2cc8a1f..5b68142 100644--- a/xnu/files/bsd/sys/hakios.net.h+++ b/xnu/files/bsd/sys/hakios.net.h@@ -1,7 +1,7 @@/** en0, and what stands behind it.*- * The network interface iOS uses here is made in drivers/net/hakios.net.c with the kernel's own+ * The network interface Darwin uses here is made in drivers/net/hakios.net.c with the kernel's own* interface KPI: Ethernet as far as the rest of the kernel and user space can tell. What carries* the frames is a "link", a driver of its own that knows nothing about interfaces: QEMU's virtio* network device today (drivers/net/hakios.virtio_net.c), the phone's radio or frames carried overdiff --git a/xnu/files/bsd/sys/hakios.sparse.h b/xnu/files/bsd/sys/hakios.sparse.hindex cd77738..7257dd0 100644--- a/xnu/files/bsd/sys/hakios.sparse.h+++ b/xnu/files/bsd/sys/hakios.sparse.h@@ -1,5 +1,5 @@/*- * A block device over an image holding only some of its blocks: how the real iOS root+ * A block device over an image holding only some of its blocks: how the real Darwin root* volume is read on the phone, which cannot hold all of it. Only with boot-arg* apfs_sparse=<offset in md0>. See drivers/storage/hakios.sparse.c.*/diff --git a/xnu/files/bsd/sys/hakios.sta.h b/xnu/files/bsd/sys/hakios.sta.hindex 6945173..8e2c9db 100644--- a/xnu/files/bsd/sys/hakios.sta.h+++ b/xnu/files/bsd/sys/hakios.sta.h@@ -3,7 +3,7 @@** On one side whatever does the scanning and the joining with a radio: the station logic over* ath11k on the phone (wifi/lx in the repository). On the other whoever wants a network: the- * Apple80211 requests of iOS's Wi-Fi side, answered in drivers/wifi/hakios.apple80211.c, and the+ * Apple80211 requests of Darwin's Wi-Fi side, answered in drivers/wifi/hakios.apple80211.c, and the* kernel's own join of the network it was given in a file (drivers/wifi/hakios.wifi.c). Frames do* not pass here, and neither does "the link is up": those go through bsd/sys/hakios.net.h,* which the station side calls itself.diff --git a/xnu/files/iokit/Kernel/GenericARMPE.cpp b/xnu/files/iokit/Kernel/GenericARMPE.cppindex cfaa292..8af42ca 100644--- a/xnu/files/iokit/Kernel/GenericARMPE.cpp+++ b/xnu/files/iokit/Kernel/GenericARMPE.cpp@@ -298,7 +298,7 @@ GenericARMPE::start(IOService * provider)/* BSD looks the platform expert up by class (IOSecureBSDRoot). */registerService();- /* Stand-ins for the closed graphics drivers that the iOS window server talks to. */+ /* Stand-ins for the closed graphics drivers that the Darwin window server talks to. */MiniIOSurfaceStart(this);MiniIOMobileFramebufferStart(this);MiniAppleKeyStoreStart();@@ -384,7 +384,7 @@ GenericARMPE::excludeList(void)/** hw.machine. On Apple's devices it is the product type ("iPhone10,3"), from the device tree's- * "model", and iOS decides from it what kind of device it is on: with anything it does not know+ * "model", and Darwin decides from it what kind of device it is on: with anything it does not know* MobileGestalt settles for an iPod touch.*/booldiff --git a/xnu/files/iokit/Kernel/MiniAppleKeyStore.cpp b/xnu/files/iokit/Kernel/MiniAppleKeyStore.cppindex f0e367a..343426c 100644--- a/xnu/files/iokit/Kernel/MiniAppleKeyStore.cpp+++ b/xnu/files/iokit/Kernel/MiniAppleKeyStore.cpp@@ -12,7 +12,7 @@* Requests that would need real keys or bags otherwise (creating or loading bags, keys kept in the* key store) are refused, logged once.*- * The protocol was worked out from the user-space side of iOS 16.5: selectors, and the+ * The protocol was worked out from the user-space side of Darwin userland 16.5: selectors, and the* DER-encoded answers ("SET of SEQUENCE { UTF8String key, INTEGER value }").*/diff --git a/xnu/files/iokit/Kernel/MiniDrivers.h b/xnu/files/iokit/Kernel/MiniDrivers.hindex 1a35381..bd64f73 100644--- a/xnu/files/iokit/Kernel/MiniDrivers.h+++ b/xnu/files/iokit/Kernel/MiniDrivers.h@@ -1,5 +1,5 @@/*- * Stand-ins for Apple's closed kernel extensions: just enough of each for the stock iOS+ * Stand-ins for Apple's closed kernel extensions: just enough of each for the stock Darwin* user space to work on a machine without Apple hardware. The platform expert* (GenericARMPE) starts them once the registry is up.*diff --git a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cppindex 68e3619..4754e4c 100644--- a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp+++ b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp@@ -7,7 +7,7 @@* surfaces of its layers into that memory, and "vsync" is a timer.** The protocol (selectors and the layout of the swap request) was worked out from the- * user-space side of iOS 16.5. Everything not implemented is logged once.+ * user-space side of Darwin userland 16.5. Everything not implemented is logged once.*/#include <IOKit/IOLib.h>@@ -39,7 +39,7 @@ extern struct vc_info vinfo; /* the boot framebuffer, as the text conextern "C" void hakios_tl(const char * format, ...) __printflike(1, 2);-/* IOConnectCallMethod selectors of the framebuffer user client (iOS 16.5) */+/* IOConnectCallMethod selectors of the framebuffer user client (Darwin userland 16.5) */enum {kFBMethodGetLayerDefaultSurface = 3,kFBMethodSwapBegin = 4,@@ -90,7 +90,7 @@ static uint8_t gFBCalls[128]; /* how many calls of each selector were/** The display user space is told about. The system carries the identity of the iPhone X- * (see the loader), and iOS knows what screen that phone has: with any other size+ * (see the loader), and Darwin knows what screen that phone has: with any other size* MobileGestalt reports an unknown screen class and the user interface has no layout for it.* So the display is always the iPhone's, and a swap scales the picture to the panel that is* really there (in QEMU the loader makes the panel exactly this size and nothing is scaled).@@ -133,7 +133,7 @@ static TUNABLE(uint32_t, gFBTrace, "fbtrace", 3);* frames to be matched with what the window server's per-frame lines (glframes=1,* userland/src/eagl.c) say. rec_step=N (2 to 8, default 3) keeps one pixel of every N instead of 3:* N = 4 holds 1.8 times as many frames, 6 four times. The memory is taken from the system's for the- * whole run: 640 MB of it under a long session of applications had iOS killing processes for+ * whole run: 640 MB of it under a long session of applications had Darwin killing processes for* memory, SpringBoard and the window server among them (two respring in one run); 256 did not.*/static TUNABLE(uint32_t, gRecSeconds, "rec_secs", 0);diff --git a/xnu/files/iokit/Kernel/MiniIOSurface.cpp b/xnu/files/iokit/Kernel/MiniIOSurface.cppindex 63967e1..a520658 100644--- a/xnu/files/iokit/Kernel/MiniIOSurface.cpp+++ b/xnu/files/iokit/Kernel/MiniIOSurface.cpp@@ -35,7 +35,7 @@ static_assert(sizeof(struct minisurf_result) == 0x68, "result layout");static_assert(offsetof(struct minisurf_shared, attachments) == 0x30, "shared layout");static_assert(sizeof(struct minisurf_result) + 20 * sizeof(struct minisurf_plane) == MINISURF_RESULT_MAX, "result size");-/* IOConnectCallMethod selectors of IOSurfaceRootUserClient (iOS 16.5) */+/* IOConnectCallMethod selectors of IOSurfaceRootUserClient (Darwin userland 16.5) */enum {kSurfaceMethodCreate = 0,kSurfaceMethodLookup = 4,diff --git a/xnu/files/iokit/Kernel/MiniIOSurface.h b/xnu/files/iokit/Kernel/MiniIOSurface.hindex feccca0..30539e5 100644--- a/xnu/files/iokit/Kernel/MiniIOSurface.h+++ b/xnu/files/iokit/Kernel/MiniIOSurface.h@@ -1,9 +1,9 @@/*- * MiniIOSurface: a stand-in for Apple's closed IOSurface.kext, enough of it for the iOS+ * MiniIOSurface: a stand-in for Apple's closed IOSurface.kext, enough of it for the Darwin* window server and its clients to share pixel buffers on a machine without Apple hardware.** The protocol (user client selectors, traps and the layout of the structures the kernel- * hands to IOSurface.framework) was worked out from the user-space side of iOS 16.5.+ * hands to IOSurface.framework) was worked out from the user-space side of Darwin userland 16.5.*/#ifndef _IOKIT_MINIIOSURFACE_H#define _IOKIT_MINIIOSURFACE_Hdiff --git a/xnu/hakios.patch b/xnu/hakios.patchindex d6ddd19..3bade39 100644--- a/xnu/hakios.patch+++ b/xnu/hakios.patch@@ -519,7 +519,7 @@ index 95192dd62449..b00da803b5b4 100644/*diff --git a/bsd/kern/kern_exec.c b/bsd/kern/kern_exec.c-index 1d71c66629fb..1d5025f32b88 100644+index 1d71c66629fb..a22095ccf5f0 100644--- a/bsd/kern/kern_exec.c+++ b/bsd/kern/kern_exec.c@@ -1157,6 +1157,9 @@ SYSCTL_PROC(_vm, OID_AUTO, shared_region_control,@@ -670,7 +670,7 @@ index 1d71c66629fb..1d5025f32b88 100644+ if (persona == NULL) {+ /*+ * hakios: there are no personas in this port -- nothing makes them, and-+ * kpersona_find_by_type() answers "no such process" to everyone who asks. iOS's own++ * kpersona_find_by_type() answers "no such process" to everyone who asks. Darwin's own+ * programs get along without them, but a package manager becomes root by way of one:+ * Sileo asks posix_spawn for persona 99 with OVERRIDE and uid 0 (its APTWrapper), and+ * that is how it runs apt and dpkg. With the persona missing the lookup failed, the@@ -922,7 +922,7 @@ index 1750d3a52d3c..0373d0dd160f 100644}diff --git a/bsd/kern/kern_priv.c b/bsd/kern/kern_priv.c-index 88adf2dda936..e29e09fc0f0b 100644+index 88adf2dda936..168384889bc1 100644--- a/bsd/kern/kern_priv.c+++ b/bsd/kern/kern_priv.c@@ -82,6 +82,19 @@ priv_check_cred(kauth_cred_t cred, int priv, int flags)@@ -931,7 +931,7 @@ index 88adf2dda936..e29e09fc0f0b 100644+ /*+ * hakios: nothing is signed here and no process carries an entitlement (AMFI is a stub), so-+ * every privilege that an entitlement would answer for is refused -- and iOS leans on one of++ * every privilege that an entitlement would answer for is refused -- and Darwin leans on one of+ * them for ordinary work. A daemon that goes to the network on behalf of an application+ * (trustd checking the certificate for whoever opened the connection, nsurlsessiond carrying+ * out its downloads) describes the connection to NECP as delegated, and without this@@ -1018,7 +1018,7 @@ index 4ca22ee4371a..e95e618b4cb6 100644int spacetype = IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;diff --git a/bsd/kern/sys_work_interval.c b/bsd/kern/sys_work_interval.c-index b544bf307dfe..85e34caf9f62 100644+index b544bf307dfe..a06cbc68ffdb 100644--- a/bsd/kern/sys_work_interval.c+++ b/bsd/kern/sys_work_interval.c@@ -265,6 +265,22 @@ work_interval_ctl(__unused proc_t p, struct work_interval_ctl_args *uap,@@ -1030,7 +1030,7 @@ index b544bf307dfe..85e34caf9f62 100644+ case 8:+ /*+ * (redwood) Not in the open source: what os_workgroup_interval_start(), _update() and-+ * _finish() of iOS send, for the performance controller, which is not here either.++ * _finish() of Darwin send, for the performance controller, which is not here either.+ * CoreAudio does it in every I/O cycle and logs an error each time it is refused: fifty+ * lines a second from the audio server's real-time thread. For its threads, and only+ * for them, there is nothing to do and nothing wrong. (The window server asks for its@@ -1058,7 +1058,7 @@ index dce802fc36f1..e2e6b3a3f3db 100644user_ssize_t rlen;off_t pgoff;diff --git a/bsd/miscfs/bindfs/bind_vfsops.c b/bsd/miscfs/bindfs/bind_vfsops.c-index 412f9ecfc22c..1788b8698ebd 100644+index 412f9ecfc22c..c88c240d4262 100644--- a/bsd/miscfs/bindfs/bind_vfsops.c+++ b/bsd/miscfs/bindfs/bind_vfsops.c@@ -139,8 +139,12 @@ bindfs_mount(struct mount * mp, __unused vnode_t devvp, user_addr_t user_data, v@@ -1069,7 +1069,7 @@ index 412f9ecfc22c..1788b8698ebd 100644- if (!IOCurrentTaskHasEntitlement(BINDFS_ENTITLEMENT)) {+ /*+ * check entitlement -- hakios: or process 1, the port's own init, unsigned, which binds-+ * its choice of launchd jobs and the like onto the read-only iOS root volume before it++ * its choice of launchd jobs and the like onto the read-only Darwin root volume before it+ * hands over to launchd (userland/src/init.c, root_apfs=)+ */+ if (!IOCurrentTaskHasEntitlement(BINDFS_ENTITLEMENT) && proc_getpid(current_proc()) != 1) {@@ -1581,7 +1581,7 @@ index 5b51e9c46a8d..6872b94631c9 100644context.vc_thread = current_thread();context.vc_ucred = cred;diff --git a/bsd/vm/vm_unix.c b/bsd/vm/vm_unix.c-index 60c8b9eedd50..b0029de5ef21 100644+index 60c8b9eedd50..4384b6fec634 100644--- a/bsd/vm/vm_unix.c+++ b/bsd/vm/vm_unix.c@@ -2538,7 +2538,19 @@ after_root_check:@@ -1590,7 +1590,7 @@ index 60c8b9eedd50..b0029de5ef21 100644error = vnode_lookup(PREBOOT_CRYPTEX_PATH, 0, &preboot_vp, vfs_context_current());- if (error || srfmp->vp->v_mount != preboot_vp->v_mount) {+ /*-+ * (redwood) Or a volume of its own mounted on a directory right inside it: iOS++ * (redwood) Or a volume of its own mounted on a directory right inside it: Darwin+ * grafts each cryptex image into the Preboot volume (graftdmg), so its files are+ * that volume's; this port mounts the image there as it is (bsd/miscfs/apfs), a+ * mount of its own whose covered directory is Preboot's Cryptexes/<name>.diff --git a/xnuloader/loader.c b/xnuloader/loader.cindex 23e82cf..422f9d3 100644--- a/xnuloader/loader.c+++ b/xnuloader/loader.c@@ -10,7 +10,7 @@* - exits boot services, turns the MMU off and jumps to the kernel entry*/#include "efi.h"-#include "identity.h" /* who iOS shall think we are: from the iPhone's own device tree (mkidentity.py) */+#include "identity.h" /* who Darwin shall think we are: from the iPhone's own device tree (mkidentity.py) *//* ------------------------------------------------------------------------ *//* Fixed conventions shared with the boot shim, the packer and the kernel */@@ -170,7 +170,7 @@ str_eq(const char *a, const char *b)static int screen_quiet;/** And while the kernel runs, whatever started the loader: under HakiOS's U-Boot (the menu of an installed HakiOS) there- * is no USB command loop, the text console is U-Boot's, drawn into the framebuffer the kernel shows iOS in, and every+ * is no USB command loop, the text console is U-Boot's, drawn into the framebuffer the kernel shows Darwin in, and every* line core 0 printed during a run (the storage's, the battery's, the watchdog's) ran over the system's screen.* What it was before the run, to go back to.*/@@ -492,7 +492,7 @@ dt_prop_padded(struct dt_writer *w, const char *name, const char *value, uint32_/** Properties copied from the iPhone's device tree (identity.h), but one: the iPhone X's display is a- * wide-gamut one ("artwork-display-gamut" P3), and with it iOS takes the screen for one that shows+ * wide-gamut one ("artwork-display-gamut" P3), and with it Darwin takes the screen for one that shows* extended colour (MobileGestalt's HasExtendedColorDisplay): WebKit then draws a page's tiles into* surfaces of ten bits a colour ('w30r', 'b3a8'), which neither the kernel's surfaces nor the window* server's renderer here do (eight bits, BGRA), and every page comes out black. Here the screen is@@ -1495,7 +1495,7 @@ ufs_survey(void)* Reads, and -- with ufs_write=1 on the command line -- writes into one partition and nowhere* else: the port's own darwin, proved by its GPT entry (name, both GUIDs, first and last LBA, its* logical unit), and in it only past everything the build writes from the computer, so that no- * answer to the kernel can reach Android's partitions, the iOS volume or the cryptexes. The+ * answer to the kernel can reach Android's partitions, the Darwin volume or the cryptexes. The* refusals are here, in the kernel (drivers/storage/hakios.ufs.c) and in UEFI's own driver, which gives* out a partition's BlockIo and bounds it: a request has to pass all three.*@@ -1516,7 +1516,7 @@ ufs_survey(void)/** The data volume's writes (HFS Plus on /dev/ufs_darwin_data): written and nothing more -- no flush, no read back --* because its journal asks for the flush itself (BLOCK_OP_FLUSH) where the order matters, and a flush and a read- * back after every 4 KB of metadata made iOS crawl. Offered with BLOCK_CAN_FAST in write_caps; the same bounds as+ * back after every 4 KB of metadata made Darwin crawl. Offered with BLOCK_CAN_FAST in write_caps; the same bounds as* BLOCK_OP_WRITE. /dev/rufs_darwin's writes stay BLOCK_OP_WRITE, flushed and read back.*/#define BLOCK_OP_WRITE_FAST 2u@@ -1526,8 +1526,8 @@ ufs_survey(void)/** The one partition a write may reach, and from which of its blocks. darwin is the port's own* 20 GiB at the end of logical unit 0 (README, "The port's partition"); what the build puts there- * from the computer (tools/darwin-write.py) is the iOS volume at its start and the two cryptexes- * behind it, and nothing of this port reads or writes the rest -- so the data of iOS lives there+ * from the computer (tools/darwin-write.py) is the Darwin volume at its start and the two cryptexes+ * behind it, and nothing of this port reads or writes the rest -- so the data of Darwin lives there* and a write is refused before that block. The identity: the partition named darwin, of the APFS* container type, on logical unit 0, in blocks of 4096 and at least the 20 GiB the port lays out. Not* its place, its exact size or its unique GUID: tools/userdata-carve.py makes darwin at the end of@@ -2997,7 +2997,7 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)int more_cores = 0, battery_requested = 0, ufs_requested = 0;/* "torch=N" (not 0) there too: the phone's flashlight is the kernel's (drivers/camera/hakios.torch.c) */int torch_requested = 0;- /* "cam=5" there too: the phone's wide camera is iOS's (drivers/camera/hakios.camera.c) */+ /* "cam=5" there too: the phone's wide camera is Darwin's (drivers/camera/hakios.camera.c) */int camera_requested = 0;/* (the loader stays for run after run: what the last run's arguments said must not hold for this one) */gamut_p3 = 0;@@ -3219,7 +3219,7 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)dt_begin(&w, "device-tree");/*- * The identity is the iPhone's (model, compatible, target-type ...): iOS user space looks+ * The identity is the iPhone's (model, compatible, target-type ...): Darwin user space looks* its device up by these, and its files -- the dyld shared cache to begin with -- are* those of that phone. XNU itself does not care; the hardware is described further down.*/@@ -3318,9 +3318,9 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)dt_begin(&w, "product");dt_identity(&w, identity_product, sizeof(identity_product) / sizeof(identity_product[0]), identity_product_data);/*- * and its haptics: "closed-loop" (MobileGestalt's DeviceSupportsClosedLoopHaptics) makes iOS play+ * and its haptics: "closed-loop" (MobileGestalt's DeviceSupportsClosedLoopHaptics) makes Darwin play* its vibrations and feedbacks as waveforms on the "Actuator" audio device (the audio plug-in- * hands them to the kernel's motor driver); without it iOS looks for an IOKit vibration motor+ * hands them to the kernel's motor driver); without it Darwin looks for an IOKit vibration motor* that the iPhone X does not have, and nothing vibrates.*/dt_begin(&w, "haptics");@@ -4074,7 +4074,7 @@ usb_command_loop(void)* QEMU's "ramfb" display shows whatever guest memory it is told to, in any size; the firmware* only offers a few small landscape modes of it. So we point it at memory of our own with the* shape of the iPhone's screen, through the fw_cfg file "etc/ramfb" (the firmware's own mode- * is simply replaced). In QEMU the display is then exactly what iOS expects; on the real phone+ * is simply replaced). In QEMU the display is then exactly what Darwin expects; on the real phone* the kernel's display driver scales that picture to the panel.*/#define PHONE_WIDTH 1125 /* the screen of the iPhone X, whose identity we carry */@@ -4108,7 +4108,7 @@ ramfb_phone_screen(void)/** volatile: QEMU writes `control' back (to 0) when it has done the request, behind the compiler's back. Without the* qualifier a build is free to keep the value written a few lines below and never look again, and the loader then- * says the request failed, leaves ramfb at the firmware's 800x600 and iOS draws its 1125x2436 into a corner: a black window+ * says the request failed, leaves ramfb at the firmware's 800x600 and Darwin draws its 1125x2436 into a corner: a black window* (it did, with a newer build of this very file; the older one happened to reload).*/static volatile struct {@@ -4175,7 +4175,7 @@ ramfb_phone_screen(void)* happened, and efi_main says it under the banner. The file has to fit in the payload region (less the last MiB,* which holds the panic log), and the region has to be free: where a firmware keeps it reserved, the allocation is* refused and the loader goes on without a payload, as it always did.- * Only the kernel and a root image that fits in the payload come this way; the big iOS system image does not+ * Only the kernel and a root image that fits in the payload come this way; the big Darwin system image does not* (docs/uefi-boot.md says what does).*/static uint64_t volume_payload_bytes; /* 0: nothing was read; else the payload's size */diff --git a/xnuloader/mkidentity.py b/xnuloader/mkidentity.pyindex cf84cf8..fc8f549 100755--- a/xnuloader/mkidentity.py+++ b/xnuloader/mkidentity.py@@ -6,14 +6,14 @@ usage: mkidentity.py DeviceTree.<board>.bin > identity.hThe input is the device tree itself, i.e. the payload of Firmware/all_flash/DeviceTree.<board>.im4pof the IPSW, decompressed: "ipsw img4 im4p extract DeviceTree.d22ap.im4p -o DeviceTree.d22ap.bin".-iOS user space (MobileGestalt above all) decides what device it runs on from the device+Darwin user space (MobileGestalt above all) decides what device it runs on from the devicetree: the root node's model and compatible, and the /product node (screen class, artworkscale, product name ...), and the /product/haptics node: what the phone's haptics are (MobileGestalt's-DeviceSupportsClosedLoopHaptics is its "closed-loop"; with it iOS plays the system's vibrations and+DeviceSupportsClosedLoopHaptics is its "closed-loop"; with it Darwin plays the system's vibrations andfeedbacks as waveforms on the actuator, and without it looks for an old vibration motor in IOKit,which the iPhone X does not have), and of the /product/camera node what the phone here has as well (its"flash": MobileGestalt's camera-flash, without which there is no flashlight in Control Center). The loader builds its own device tree for the hardware we really-have, but copies these properties from the device tree in the iOS firmware so that the+have, but copies these properties from the device tree in the Darwin firmware so that thesystem believes it is the iPhone its files were built for.Properties that iBoot fills in on a real phone ("syscfg/..." placeholders: serial number,@@ -72,9 +72,9 @@ def emit_empty(label):def placeholder():"""An identity.h with no Apple-derived data, for building the loader without an IPSW.- The device-tree properties iOS reads to tell which iPhone it is are left empty. This is+ The device-tree properties Darwin reads to tell which iPhone it is are left empty. This isenough to build and boot the open kernel under QEMU with an Apple-free user space (the- `hello` RAM disk); it is NOT enough to run the iOS 16.5 user space, which wants the real+ `hello` RAM disk); it is NOT enough to run the Darwin userland 16.5 user space, which wants the realproperties. Generate the real header from your own IPSW (mkidentity.sh) for that."""print('/* Generated by mkidentity.py --placeholder: no Apple device-tree data. */')@@ -90,7 +90,7 @@ def main():raw = open(sys.argv[1], 'rb').read()root, _ = parse(raw)children = {name_of(c): c for c in root[1]}- print('/* Generated by mkidentity.py from the device tree of the iOS firmware. Do not edit. */')+ print('/* Generated by mkidentity.py from the device tree of the Darwin firmware. Do not edit. */')print('struct identity_prop { const char *name; unsigned offset, length; };\n')# of the root: who we are. Addresses, the phandle and what iBoot fills in stay ours.emit('identity_root', root[0], ('name', '#address-cells', '#size-cells', 'AAPL,phandle', 'clock-frequency',diff --git a/xnuloader/mkidentity.sh b/xnuloader/mkidentity.shindex 5f06014..30a109b 100755--- a/xnuloader/mkidentity.sh+++ b/xnuloader/mkidentity.sh@@ -1,5 +1,5 @@#!/bin/bash-# Make xnuloader/identity.h: the identity of the iPhone whose files iOS 16.5 was built for, taken+# Make xnuloader/identity.h: the identity of the iPhone whose files Darwin userland 16.5 was built for, taken# 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.#@@ -14,14 +14,14 @@# (with no argument: sysimage/DeviceTree.d22ap.im4p, or $IPSW)# xnuloader/mkidentity.sh --placeholder (no IPSW: an identity.h with no Apple data,# enough to build and boot the open kernel under-# QEMU with an Apple-free user space, not iOS)+# QEMU with an Apple-free user space, not Darwin)set -eHERE=$(cd "$(dirname "$0")" && pwd)TOP=$(cd "$HERE/.." && pwd)if [ "$1" = --placeholder ] || [ "${PLACEHOLDER:-}" = 1 ]; thenpython3 "$HERE/mkidentity.py" --placeholder > "$HERE/identity.h.new"mv "$HERE/identity.h.new" "$HERE/identity.h"- echo "mkidentity.sh: xnuloader/identity.h made WITHOUT an IPSW (placeholder; no Apple data, not for iOS)"+ echo "mkidentity.sh: xnuloader/identity.h made WITHOUT an IPSW (placeholder; no Apple data, not for Darwin)"exit 0fiWORK=$(mktemp -d "${TMPDIR:-/tmp}/mkidentity.XXXXXX")@@ -31,7 +31,7 @@ SRC=${1:-}[ -n "$SRC" ] || { [ -f "$TOP/sysimage/DeviceTree.d22ap.im4p" ] && SRC=$TOP/sysimage/DeviceTree.d22ap.im4p; } || SRC=${IPSW:-}if [ -z "$SRC" ] || [ ! -f "$SRC" ]; thenecho "mkidentity.sh: no device tree. Run sysimage/unpack.sh YOUR.ipsw first, or give the IPSW or" >&2- echo " DeviceTree.d22ap.im4p as the argument (or --placeholder for the open kernel without iOS)" >&2+ echo " DeviceTree.d22ap.im4p as the argument (or --placeholder for the open kernel without Darwin)" >&2exit 1ficase $SRC in