Skip to content

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

C

Darwin on redwood: XNU + iOS 16.5 userland on POCO X5 Pro 5G and QEMU

vcvkkbfb886a1de22
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a05ac37
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,74 @@
+# 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
+# is named here.
+/*
+!/.gitignore
+!/README.md
+!/xl
+!/mkpackfs.py
+!/mkxnuimg.py
+!/xnu-build.sh
+!/xnu-env.sh
+!/xnuloader/
+!/qemu/
+!/tools/
+!/userland/
+!/ios165/
+!/xnu/
+!/xnu-deps/
+!/uefi/
+!/prebuilt/
+
+__pycache__/
+*~
+*.orig
+*.rej
+
+/xnuloader/*
+!/xnuloader/build.sh
+!/xnuloader/efi.h
+!/xnuloader/identity.h
+!/xnuloader/loader.c
+!/xnuloader/mkidentity.py
+!/xnuloader/mkpayload.py
+
+/qemu/*
+!/qemu/*.sh
+!/qemu/*.py
+
+/userland/*
+!/userland/build.sh
+!/userland/*.py
+!/userland/rc.*
+!/userland/com.redwood.demo.plist
+!/userland/src/
+!/userland/libmini/
+!/userland/var/
+
+/ios165/*
+!/ios165/fetch.sh
+!/ios165/*.py
+
+# of xnu-deps only what is ours; setup.sh fetches and builds the rest
+/xnu-deps/*
+!/xnu-deps/setup.sh
+!/xnu-deps/gen-iig-stubs.py
+!/xnu-deps/hostinc/
+!/xnu-deps/iig-impl/
+!/xnu-deps/host/
+/xnu-deps/host/*
+!/xnu-deps/host/bin/
+/xnu-deps/host/bin/*
+!/xnu-deps/host/bin/codesign
+!/xnu-deps/host/bin/iig
+!/xnu-deps/host/bin/install
+!/xnu-deps/host/bin/plutil
+!/xnu-deps/host/bin/sw_vers
+!/xnu-deps/host/bin/xcrun
+!/xnu-deps/host/bin/xnu-clang
+!/xnu-deps/build/
+/xnu-deps/build/*
+!/xnu-deps/build/pthread/
+/xnu-deps/build/pthread/*
+!/xnu-deps/build/pthread/build.sh
+!/xnu-deps/build/lzbitmap/
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a2513d7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,218 @@
+# Darwin на redwood
+
+Открытое ядро Apple XNU (xnu-8796.121.2 — ядро iOS 16.5), свой загрузчик и свои замены закрытых драйверов,
+под которыми работает **немодифицированный userland iOS 16.5** от iPhone X: launchd → backboardd → SpringBoard →
+приложения. Работает в двух местах:
+
+- **POCO X5 Pro 5G (redwood, Snapdragon 778G)** — ничего не прошивается: UEFI грузится через `fastboot boot`,
+ вся система живёт в ОЗУ, после перезагрузки телефон снова в Android;
+- **QEMU** (`virt`, aarch64) — то же самое на любом Linux-компьютере, без телефона.
+
+Графика — программный рендер CoreAnimation (GPU не используется), поэтому всё небыстро: на телефоне 10–25 кадров/с.
+
+## Что работает и чего нет
+
+| Работает | Не работает |
+|---|---|
+| Экран блокировки, разблокировка свайпом, домашний экран с полным набором значков (две страницы) | Звук, сеть (Wi-Fi/сотовая), Bluetooth, камера |
+| Запуск приложений: Настройки (вглубь), Часы, Календарь, Фото, Заметки и др. | GPU/Metal — только программный рендер |
+| Сенсорный экран телефона (Goodix GT9916), мультитач | SMP — работает одно ядро процессора |
+| Кнопки «Домой»/«Блокировка»/громкость (в QEMU — клавишами) | Зарядка под нашим ядром (телефон только разряжается) |
+| Большое ядро на 2,4 ГГц, загрузка до экрана блокировки ~20 с (телефон) | Safari (лежит в отдельном «App cryptex», которого у нас нет) |
+| Снимки экрана и запись экрана с телефона | Сохранение данных: /private/var в памяти, каждая загрузка — «новое устройство» |
+
+Это стенд для исследования, а не прошивка: сеанс длится заданное число секунд, потом ядро возвращается в загрузчик
+и отдаёт журнал.
+
+## Быстрый старт: QEMU, без сборки ядра
+
+В `prebuilt/` лежат собранные из этого же репозитория ядро, загрузчик и наши программы, так что нужен только
+образ системы. **Файлов iOS в репозитории нет** — скрипт сам скачивает их с серверов Apple (из IPSW iOS 16.5
+для iPhone X) и раскладывает.
+
+Нужно: Linux x86-64, ~20 ГБ свободного места (после сборки остаётся ~11 ГБ), 16 ГБ ОЗУ. Пакеты (Arch):
+
+```sh
+sudo pacman -S --needed git python 7zip lz4 gcc qemu-system-aarch64 qemu-ui-gtk edk2-aarch64
+```
+
+(7-Zip нужен версии 23 или новее — он читает APFS; `lz4` — библиотека `liblz4`.)
+
+```sh
+git clone [email protected]:vcvkk/darwin-redwood.git
+cd darwin-redwood
+ios165/fetch.sh # скачивает 7,4 ГБ с CDN Apple и распаковывает нужное (минут 5–15)
+REST=1 userland/build.sh # собирает образы: userland/root.packfs и userland/system.packfs (2,5 ГБ)
+mkdir -p logs
+qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 минут
+```
+
+Через 2–3 минуты в окне появится экран блокировки.
+
+- **Мышь с зажатой левой кнопкой — палец.** Разблокировка — свайп вверх от самого нижнего края.
+- Клавиши: `H` — «Домой», `L` — блокировка/питание, `↑`/`↓` — громкость.
+- То же из скрипта (без окна, `-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` — длительность сеанса в секундах; по её истечении ядро возвращается в загрузчик
+ и QEMU завершается. Журнал ядра и демонов идёт в stdout.
+- Сразу после появления SpringBoard система ещё занята (регистрирует приложения): подождите секунд 30–40,
+ иначе жесты «растягиваются» и не распознаются.
+
+Замечания:
+
+- Память гостя — 12 ГБ, отображённые из разрежённого файла `qemu/ram.img` (образ системы лежит в нём по нужному
+ смещению). На btrfs/xfs это reflink и места не занимает, на ext4 образ копируется (ещё 2,5 ГБ). Если QEMU не
+ может выделить память — `sudo sysctl vm.overcommit_memory=1`.
+- Прошивка 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 …`
+ (проверялось только на Arch).
+- QEMU без KVM эмулирует ARM программно: всё заметно медленнее, чем на телефоне.
+
+## На телефоне
+
+Нужен именно **POCO X5 Pro 5G (redwood)** с разблокированным загрузчиком, `adb` и `fastboot` на компьютере
+(`sudo pacman -S android-tools`), и образы из предыдущего раздела (`ios165/fetch.sh`, `REST=1 userland/build.sh`).
+
+```sh
+./xl enter # Android → fastboot → наш загрузчик в ОЗУ (fastboot boot), он поднимает свой USB-канал
+./xl ramdisk # залить образ системы в ОЗУ телефона (2,5 ГБ, ~80 с) — один раз на сеанс загрузчика
+XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7" ./xl run # 15 минут iOS
+./xl screenshot shot.png # что осталось на экране после возврата
+./xl reboot # обратно в Android
+```
+
+`./xl run` ждёт конца сеанса и кладёт журнал в `logs/`; запускать можно сколько угодно раз, образ системы в ОЗУ
+остаётся. `./xl` без аргументов печатает все команды.
+
+**Прочитайте до запуска:**
+
+- В постоянную память ничего не прошивается, с одним исключением: загрузчик пишет свой текстовый журнал в начало
+ сырого раздела **`logdump`** (отладочный раздел Xiaomi; Android им в обычной жизни не пользуется). Если есть root —
+ сохраните его заранее: `adb shell su -c 'dd if=/dev/block/by-name/logdump of=/sdcard/logdump.img'`.
+- UEFI собран из драйверов прошивки `OS1.0.3.0.UMSMIXM`. С другой версией xbl он может не завестись — тогда
+ телефон просто не выйдет на связь; выход — зажать питание на 10–15 секунд.
+- Ядро напрямую трогает железо (регуляторы через RPMh, GPIO, частоту процессора). Проверено ровно на одном
+ экземпляре. **На свой риск.**
+- Под нашим ядром телефон **не заряжается** и греется (одно ядро на 2,4 ГГц постоянно рисует). Между длинными
+ сеансами возвращайте его в Android (`./xl reboot`).
+- Сенсоры в redwood бывают двух видов: Goodix GT9916 и FocalTech FT3680. Драйвер есть только для Goodix.
+- Если ядро зависло, сторожевой таймер гипервизора сам перезагрузит телефон в Android (до минуты). Если нет —
+ питание на 10–15 секунд.
+
+Параметры ядра (`XL_CMDLINE`, в QEMU — переменная `CMDLINE`):
+
+| Параметр | Что делает |
+|---|---|
+| `touchscreen=1` | включить сенсорный экран телефона (`touch_flip=1\|2\|3` — отразить оси) |
+| `bootcpu=7` | запустить ядро на самом большом ядре процессора (загрузчик остаётся на нулевом и наблюдает) |
+| `cpufreq=1` | поднять этому ядру частоту до максимума (иначе 300 МГц) |
+| `rec_secs=N` | записывать экран N секунд (`rec_start=S`, `rec_mb=M`, не больше 640); потом `./xl recording out.mp4` |
+| `-v` | текст загрузки на экране (по умолчанию у `xl run`, если `XL_CMDLINE` не задана) |
+| `applog=1` / `applog=2` | stderr приложений в журнал / плюс os_log всех процессов |
+| `systrace=1` | печатать неудачные системные вызовы и аварии процессов |
+| `machine_name=1` | представляться iPhone10,3 (иначе устройство называется «iPod touch»); мало проверено |
+
+## Сборка из исходников
+
+Готовые бинарники в `prebuilt/` собраны из этого репозитория; пересобрать всё можно самому.
+
+### Ядро
+
+См. `xnu/README.md`: исходники XNU берутся у Apple (`apple-oss-distributions/xnu`, тег `xnu-8796.121.2`), поверх
+накладываются наши правки (`xnu/redwood.patch` + новые файлы в `xnu/files/`), окружение для сборки на Linux
+стоковым clang готовит `xnu-deps/setup.sh`.
+
+### Загрузчик
+
+```sh
+xnuloader/build.sh # clang + lld-link → xnuloader/loader.efi (EFI-приложение без EDK2)
+```
+
+`xnuloader/identity.h` сгенерирован `mkidentity.py` из дерева устройств iPhone X (так система узнаёт, «какой она
+iPhone»); перегенерировать: `python3 ios165/fetch-from-ipsw.py Firmware/all_flash/DeviceTree.d22ap.im4p dt.im4p`,
+`ipsw img4 im4p extract dt.im4p -o dt.bin`, `xnuloader/mkidentity.py dt.bin > xnuloader/identity.h`.
+
+### Userland и образы
+
+```sh
+REST=1 userland/build.sh
+```
+
+Без кросс-компилятора (см. раздел про ядро — он тот же) скрипт берёт наши программы из `prebuilt/userland`,
+с ним — компилирует `userland/src`. Получаются два образа в своём формате packfs (`mkpackfs.py`):
+
+- `userland/root.packfs` — маленький (наш init, библиотеки-вставки, задания launchd); едет вместе с ядром,
+ пересобирается за секунды;
+- `userland/system.packfs` — корень: отобранная часть iOS 16.5 (`ios165/select-system.py`), кэш dyld, сжатие LZ4.
+ Пересобирается только при изменении входных данных или с `SYSTEM=1`.
+
+`REST=1` добавляет ~350 штатных служб iOS «по требованию» (без них часть приложений зависает на старте).
+Остальные переменные (`JOBS`, `OSLOG`, `INJECT`, `RC_JOBS`) описаны в начале `userland/build.sh`.
+
+После пересборки ядра/загрузчика/программ `tools/update-prebuilt.sh` обновляет `prebuilt/`.
+
+### UEFI для телефона
+
+См. `uefi/README.md` (порт Project Silicium на redwood). Для запуска пересобирать не нужно: `mkxnuimg.py` берёт
+готовое из `prebuilt/uefi`.
+
+## Как это устроено
+
+```
+fastboot boot ──► UEFI (Mu-Silicium, redwood) ──► xnuloader (EFI-приложение)
+ │ остаётся резидентным: USB-канал (протокол fastboot),
+ │ сторожевой таймер, приём журнала от ядра
+ ▼
+ XNU (конфигурация BCM2837 как основа + своя платформа)
+ ├─ GICv3, таймер, видеоконсоль, возврат в загрузчик
+ ├─ packfs (корень, сжатый образ в ОЗУ), ramfs (/private/var, /tmp)
+ ├─ minicrypto вместо corecrypto, заглушки AMFI и Sandbox (MAC-политики)
+ ├─ замены драйверов: IOSurface, IOMobileFramebuffer, AppleKeyStore
+ └─ ввод: /dev/redwood-touch ◄─ Goodix GT9916 (телефон) / virtio-input (QEMU)
+ ▼
+ launchd iOS 16.5 → logd, notifyd, cfprefsd, runningboardd, backboardd, SpringBoard, приложения
+ └─ в backboardd и SpringBoard внедряются наши библиотеки (libredwood*.dylib):
+ виртуальные HID-службы (сенсор, кнопки) и подмена нескольких ObjC-методов
+```
+
+Userland не изменён ни в одном байте: всё, чего ему не хватает, либо делает ядро (замены драйверов), либо
+библиотека, которую ядро подсовывает через `DYLD_INSERT_LIBRARIES` (sysctl `kern.exec_inject`).
+
+## Что где лежит
+
+| Путь | Что |
+|---|---|
+| `xl` | управление телефоном по USB: загрузчик, запуск ядра, журнал, снимки экрана |
+| `xnuloader/` | загрузчик: `loader.c` (UEFI-приложение), `mkpayload.py` (контейнер «ядро + образ + аргументы») |
+| `xnu/` | наши правки XNU: патч, новые файлы, `apply.sh`/`export.sh` |
+| `xnu-deps/` | всё для сборки XNU на Linux: `setup.sh`, обёртки инструментов, заглушки |
+| `xnu-build.sh`, `xnu-env.sh` | сборка ядра |
+| `userland/` | наш init, вставки (`src/inject.c` — backboardd, `src/inject_sb.c` — SpringBoard), тесты, сборка образов |
+| `ios165/` | добыча файлов iOS из IPSW и выбор того, что идёт в образ |
+| `mkpackfs.py` | сборщик образов packfs (формат описан в `bsd/miscfs/packfs/packfs.h` ядра) |
+| `qemu/` | запуск в QEMU, касания, снимки экрана, разбор стеков |
+| `uefi/`, `mkxnuimg.py` | порт UEFI на redwood и упаковка загрузочного образа для `fastboot boot` |
+| `tools/` | `recording.py` (запись экрана → mp4), `update-prebuilt.sh` |
+| `prebuilt/` | собранные ядро, загрузчик, наши программы и куски UEFI |
+
+Скрипты не зависят от того, куда склонирован репозиторий.
+
+## Отладка
+
+- Журнал сеанса: stdout QEMU или `logs/ЧЧММСС-run.log` с телефона. Драйвер экрана раз в 5 с пишет частоту кадров,
+ драйвер сенсора раз в минуту — сводку касаний.
+- `userabort:` в журнале — стек процесса, вызвавшего `abort()`; `usertrap:` (с `systrace=1`) — аварии.
+- Стеки зависшего процесса на лету (QEMU): `qemu/touch.py stacks ИМЯ`, затем `qemu/symstack.py ЖУРНАЛ ИМЯ`
+ (нужен [`ipsw`](https://github.com/blacktop/ipsw)).
+- `userland/jobinfo.py [-s СЛУЖБА | МЕТКА…]` — штатные задания launchd и кто даёт Mach-службу.
+- `OSLOG=all userland/build.sh` — os_log всех заданий на консоль (очень многословно).
+
+## Про файлы Apple и лицензии
+
+- Файлов iOS в репозитории нет: `ios165/fetch.sh` скачивает их из IPSW с CDN Apple на вашу машину.
+- `xnu/` — производная работа от XNU, распространяется на условиях APSL 2.0, как и сам XNU; `prebuilt/mach.*` —
+ ядро, собранное из этих исходников.
+- `xnu-deps/build/lzbitmap/libzbitmap.*` — libzbitmap (Corellium, GPL-2.0+ OR MIT).
+- `uefi/files/Binaries/redwood` и `prebuilt/uefi/SILICIUM_UEFI.fd` содержат драйверы UEFI из прошивки Xiaomi
+ (так же, как их распространяет Project Silicium для других устройств); `prebuilt/uefi/mkbootimg.py` — AOSP, Apache-2.0.
diff --git a/ios165/fetch-from-ipsw.py b/ios165/fetch-from-ipsw.py
new file mode 100755
index 0000000..a1f4273
--- /dev/null
+++ b/ios165/fetch-from-ipsw.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""Fetch one member of the iOS 16.5 iPhone X firmware archive without downloading the rest.
+
+usage: fetch-from-ipsw.py MEMBER OUTPUT
+
+The IPSW is a ZIP64 archive on Apple's CDN; its directory is read with HTTP range requests and
+the member is streamed (and inflated, if it is compressed) straight to OUTPUT.
+"""
+import struct
+import sys
+import urllib.request
+import zlib
+
+URL = ('https://updates.cdn-apple.com/2023SpringFCS/fullrestores/032-85130/6AB0D10A-8AF9-4F6C-8CF5-A1B315CABE88/'
+ 'iPhone10,3,iPhone10,6_16.5_20F66_Restore.ipsw')
+SIZE = 6165698198
+
+
+def fetch(start, end):
+ request = urllib.request.Request(URL, headers={'Range': f'bytes={start}-{end}'})
+ return urllib.request.urlopen(request, timeout=120)
+
+
+def directory():
+ tail = fetch(SIZE - 65536, SIZE - 1).read()
+ at = tail.rfind(b'PK\x06\x06')
+ cd_size, cd_offset = struct.unpack('<QQ', tail[at + 40:at + 56])
+ cd = fetch(cd_offset, cd_offset + cd_size - 1).read()
+ p = 0
+ while cd[p:p + 4] == b'PK\x01\x02':
+ method, = struct.unpack('<H', cd[p + 10:p + 12])
+ csize, usize, nl, el, cl = struct.unpack('<IIHHH', cd[p + 20:p + 34])
+ offset, = struct.unpack('<I', cd[p + 42:p + 46])
+ name = cd[p + 46:p + 46 + nl].decode()
+ extra = cd[p + 46 + nl:p + 46 + nl + el]
+ q = 0
+ while q + 4 <= len(extra):
+ tag, length = struct.unpack('<HH', extra[q:q + 4])
+ if tag == 1:
+ values = list(struct.unpack('<' + 'Q' * (length // 8), extra[q + 4:q + 4 + length // 8 * 8]))
+ if usize == 0xFFFFFFFF:
+ usize = values.pop(0)
+ if csize == 0xFFFFFFFF:
+ csize = values.pop(0)
+ if offset == 0xFFFFFFFF:
+ offset = values.pop(0)
+ q += 4 + length
+ yield name, method, csize, usize, offset
+ p += 46 + nl + el + cl
+
+
+def main():
+ member, output = sys.argv[1], sys.argv[2]
+ for name, method, csize, usize, offset in directory():
+ if name != member:
+ continue
+ header = fetch(offset, offset + 29).read()
+ nl, el = struct.unpack('<HH', header[26:30])
+ data = offset + 30 + nl + el
+ inflater = zlib.decompressobj(-15) if method == 8 else None
+ written = 0
+ with fetch(data, data + csize - 1) as stream, open(output, 'wb') as out:
+ while chunk := stream.read(1 << 20):
+ chunk = inflater.decompress(chunk) if inflater else chunk
+ out.write(chunk)
+ written += len(chunk)
+ if inflater:
+ tail = inflater.flush()
+ out.write(tail)
+ written += len(tail)
+ print(f'{member}: {written} bytes (expected {usize})')
+ sys.exit(0 if written == usize else 1)
+ sys.exit(f'{member}: not in the archive')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/ios165/fetch.sh b/ios165/fetch.sh
new file mode 100755
index 0000000..c58c185
--- /dev/null
+++ b/ios165/fetch.sh
@@ -0,0 +1,79 @@
+#!/bin/bash
+# Get the files of iOS 16.5 (20F66, iPhone X) that the system image is made of, straight from
+# Apple's servers, and lay them out the way ../userland/build.sh expects them:
+#
+# rootfs/ the chosen part of the root filesystem (see select-system.py)
+# system.files/.manifest what was chosen, with owners, modes and symbolic links
+# var.skel the skeleton of /private/var (see mkvarskel.py)
+# cryptex/ the OS cryptex without the dyld shared cache
+# 20F66__iPhone10,3_6/ the dyld shared cache (arm64)
+#
+# Nothing of this is in the repository: the two disk images are fetched out of the IPSW on
+# Apple's CDN (fetch-from-ipsw.py reads single members of the archive, 4.7 GB + 2.7 GB instead of
+# all 6.2 GB) and unpacked with 7z. Needs: python3, 7z (7-Zip 23 or newer: it reads APFS), cc.
+# About 11 GB of disk while it runs, 5.5 GB afterwards.
+#
+# KEEP=1 keep the downloaded disk images (rootfs.dmg is needed again only after changing
+# select-system.py; with it in place a second run downloads nothing)
+set -e
+cd "$(dirname "$0")"
+ROOTFS_DMG=096-04088-077.dmg # the root filesystem, APFS
+CRYPTEX_DMG=096-04666-078.dmg # the OS cryptex: dyld shared cache and a few libraries
+CACHE=20F66__iPhone10,3_6
+UNZBM=../xnu-deps/host/bin/unzbm
+
+for tool in python3 7z cc; do
+ command -v $tool >/dev/null || { echo "fetch.sh: $tool is not installed"; exit 1; }
+done
+# 7z leaves files compressed with LZBITMAP as an empty file and two attribute files; unzbm finishes them
+if [ ! -x $UNZBM ]; then
+ mkdir -p "$(dirname $UNZBM)"
+ cc -O2 -w -o $UNZBM ../xnu-deps/build/lzbitmap/unzbm.c ../xnu-deps/build/lzbitmap/libzbitmap.c
+fi
+unzbm_all() { # unzbm_all DIR: expand every LZBITMAP file below DIR
+ find "$1" -type f -name '*:com.apple.decmpfs' | sed 's/:com\.apple\.decmpfs$//' | tr '\n' '\0' | xargs -0 -r -n 200 $UNZBM
+ local left
+ left=$(find "$1" -name '*:com.apple.*' | wc -l)
+ [ "$left" = 0 ] || { echo "fetch.sh: $left files in $1 are still compressed"; exit 1; }
+}
+
+# --- the root filesystem --------------------------------------------------------------------------
+if [ ! -f .done-rootfs ] || [ select-system.py -nt .done-rootfs ]; then
+ if [ ! -f rootfs.dmg ]; then
+ echo "fetch.sh: downloading the root filesystem image (4.7 GB)"
+ python3 fetch-from-ipsw.py $ROOTFS_DMG rootfs.dmg.part
+ mv rootfs.dmg.part rootfs.dmg
+ fi
+ echo "fetch.sh: listing the image"
+ 7z l -slt rootfs.dmg > rootfs.slt
+ python3 select-system.py rootfs.slt system.files system.manifest
+ python3 mkvarskel.py rootfs.slt > var.skel
+ echo "fetch.sh: extracting $(wc -l < system.files) files"
+ rm -rf rootfs
+ 7z x -y -orootfs rootfs.dmg @system.files > extract-system.log
+ touch .done-rootfs
+ [ -n "$KEEP" ] || rm -f rootfs.dmg
+fi
+
+# --- the OS cryptex -------------------------------------------------------------------------------
+if [ ! -f .done-cryptex ]; then
+ if [ ! -f cryptex-os.dmg ]; then
+ echo "fetch.sh: downloading the OS cryptex image (2.7 GB)"
+ python3 fetch-from-ipsw.py $CRYPTEX_DMG cryptex-os.dmg.part
+ mv cryptex-os.dmg.part cryptex-os.dmg
+ fi
+ echo "fetch.sh: extracting the cryptex"
+ rm -rf cryptex cryptex.cache $CACHE
+ # 7z reports every LZBITMAP file as an error ("Unsupported Method"): expected, unzbm_all checks the result
+ 7z x -y -ocryptex cryptex-os.dmg '-xr!com.apple.dyld' '-x!System/DriverKit' > extract-cryptex.log 2>&1 || true
+ unzbm_all cryptex
+ # the dyld shared cache; its .symbols file (0.6 GB) is never mapped and is left out
+ 7z x -y -ocryptex.cache cryptex-os.dmg System/Library/Caches/com.apple.dyld '-xr!*.symbols*' > extract-dyld.log 2>&1 || true
+ unzbm_all cryptex.cache
+ mv cryptex.cache/System/Library/Caches/com.apple.dyld $CACHE
+ rm -rf cryptex.cache
+ [ "$(ls $CACHE | wc -l)" = 43 ] || { echo "fetch.sh: the dyld shared cache is incomplete"; exit 1; }
+ touch .done-cryptex
+ [ -n "$KEEP" ] || rm -f cryptex-os.dmg
+fi
+echo "fetch.sh: done: $(du -sh rootfs | cut -f1) rootfs, $(du -sh cryptex | cut -f1) cryptex, $(du -sh $CACHE | cut -f1) dyld shared cache"
diff --git a/ios165/mkvarskel.py b/ios165/mkvarskel.py
new file mode 100755
index 0000000..8faa3ec
--- /dev/null
+++ b/ios165/mkvarskel.py
@@ -0,0 +1,62 @@
+#!/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
+volume). Our /private/var is an empty memory filesystem at every boot, so init re-creates the
+directories of that template, with their owners and modes, from this list. Lines, tab separated:
+ d mode(octal) uid gid path
+ l 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.
+"""
+import importlib.util
+import os
+import stat
+import sys
+
+here = os.path.dirname(os.path.abspath(__file__))
+spec = importlib.util.spec_from_file_location('select_system', os.path.join(here, 'select-system.py'))
+select_system = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(select_system)
+
+SKIP = ('private/var/staged_system_apps', 'private/var/MobileAsset/')
+EXTRA = [ # path, mode, uid, gid
+ ('/private/var/db/uuidtext', 0o755, 272, 272), # logd
+ ('/private/var/db/diagnostics/timesync', 0o755, 272, 272),
+ ('/private/var/containers', 0o755, 0, 0), # containermanagerd
+ ('/private/var/containers/Data', 0o755, 0, 0),
+ ('/private/var/containers/Shared', 0o755, 0, 0),
+ ('/private/var/containers/Bundle', 0o755, 0, 0),
+ ('/private/var/mobile/Containers', 0o755, 501, 501),
+ ('/private/var/mobile/Containers/Data', 0o755, 501, 501),
+ ('/private/var/mobile/Containers/Shared', 0o755, 501, 501),
+ ('/private/var/mobile/Library/Caches', 0o755, 501, 501),
+ ('/private/var/mobile/Library/Preferences', 0o755, 501, 501),
+ ('/private/var/mobile/Library/Logs', 0o755, 501, 501),
+ ('/private/var/root/Library/Caches', 0o700, 0, 0),
+ ('/private/var/root/Library/Preferences', 0o700, 0, 0),
+ ('/private/var/root/Library/Logs', 0o700, 0, 0),
+]
+
+dirs, links = {}, []
+for e in select_system.entries(sys.argv[1]):
+ path = e['Path']
+ if not path.startswith('private/var') or path.startswith(SKIP):
+ continue
+ mode = select_system.mode_bits(e['Mode'])
+ if mode is None:
+ continue
+ if stat.S_ISDIR(mode):
+ dirs['/' + path] = (mode & 0o7777, int(e.get('User ID') or 0), int(e.get('Group ID') or 0))
+ elif stat.S_ISLNK(mode):
+ links.append((e.get('Symbolic Link', ''), '/' + path))
+for path, mode, uid, gid in EXTRA:
+ dirs.setdefault(path, (mode, uid, gid))
+dirs.pop('/private/var', None) # the mount point itself: init sets it up
+for path in sorted(dirs):
+ mode, uid, gid = dirs[path]
+ print(f'd\t{mode:o}\t{uid}\t{gid}\t{path}')
+for target, path in links:
+ print(f'l\t{target}\t{path}')
+# the time zone database is on the system volume
+print('l\t/usr/share/zoneinfo\t/private/var/db/timezone/zoneinfo')
diff --git a/ios165/select-system.py b/ios165/select-system.py
new file mode 100755
index 0000000..e6f6400
--- /dev/null
+++ b/ios165/select-system.py
@@ -0,0 +1,188 @@
+#!/usr/bin/env python3
+"""Choose the part of the iOS root filesystem that goes into the in-memory system image.
+
+usage: select-system.py rootfs.slt system.files system.manifest
+
+rootfs.slt is the technical listing of the root filesystem image ("7z l -slt rootfs.dmg").
+Two files are written:
+ system.files the regular files to extract ("7z x -orootfs rootfs.dmg @system.files")
+ system.manifest every chosen file, directory and symbolic link with its owner, group and mode,
+ tab separated: mode(octal, with the type bits) uid gid path [link target].
+ mkpackfs.py builds the image from the extracted files and this manifest,
+ because extraction on Linux keeps neither owners nor all of the symlinks.
+
+The whole root is 7.9 GB and the kernel on the phone has about 4 GB of RAM for everything, so:
+ - programs, libraries and their data outside the framework directories are taken whole;
+ - from the framework directories (the code itself is in the dyld shared cache) what a
+ program 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
+ keeps 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 like
+ the rest: system.files names them where they are in the image, system.manifest where they go
+ (userland/build.sh moves the extracted files);
+ - machine-learning models, other languages' localizations, media and GPU shader libraries
+ are left out, and so are a few very big daemons that have nothing to do with the display;
+ - of pictures, what the user interface itself is drawn with: small images, asset catalogs of
+ moderate size; the fonts except the two biggest (colour emoji and Chinese);
+ - the empty LANGUAGE.lproj directories of the bundles whose strings are in one .loctable file
+ for all languages: they are how CoreFoundation knows which languages a bundle has, and
+ without them every string comes out as its key.
+"""
+import re
+import stat
+import sys
+
+WHOLE = ('usr/libexec/', 'usr/sbin/', 'usr/bin/', 'usr/lib/', 'usr/share/', 'sbin/', 'bin/', 'private/etc/',
+ 'System/Library/', 'Applications/')
+# ... except these parts of /System/Library: big, and not needed to get a picture on the screen
+SKIP_SYSTEM_LIBRARY = ('LinguisticData', 'PreinstalledAssetsV2', 'NanoTimeKit', 'Health', 'Audio',
+ 'OnBoardingBundles', 'Assistant', 'AccessibilityBundles',
+ 'VideoProcessors', 'ScreenReader', 'Photos', 'Carrier Bundles', 'NanoPreferenceBundles',
+ 'ImagingNetworks', 'ProductDocuments', 'AppPlaceholders', 'UserNotifications',
+ 'Caches')
+FRAMEWORKS = ('System/Library/Frameworks/', 'System/Library/PrivateFrameworks/')
+SMALL = 4 << 20
+# never from frameworks: machine-learning models, shader libraries, sound and video, big tables.
+# (Not the data models, .mom: an application that keeps its data with Core Data dies without its
+# model -- Notes did; nor the animations and vector pictures the interface is drawn with.)
+SKIP_EXT = ('.weights', '.weights_nonane', '.metallib', '.mov', '.pcm', '.scnz', '.espresso.net',
+ '.espresso.shape', '.caf', '.m4a', '.aiff', '.mp4', '.heic', '.wav', '.art', '.scube',
+ '.ds', '.dat', '.bin')
+# never from applications: their sound, video and 3D content
+SKIP_APP_EXT = ('.mov', '.mp4', '.m4a', '.caf', '.wav', '.heic', '.aiff', '.metallib', '.scnz', '.usdz')
+# pictures the user interface is drawn with: small images, and asset catalogs up to this size
+# (the one with all the SF Symbols alone is 170 MB and is left out)
+MAX_ASSET_CATALOG = 4 << 20
+# fonts: all but the very big ones (the colour emoji, 130 MB, and PingFang, 74 MB)
+MAX_FONT = 25 << 20
+# string tables hold every language; the biggest (Shortcuts' actions, Home) are 5-12 MB
+MAX_STRING_TABLE = 16 << 20
+# applications waiting here to be installed by the first boot go to /Applications instead
+STAGED_APPS = 'private/var/staged_system_apps/'
+# frameworks whose pictures are wanted whatever their size
+ALL_PICTURES = ('System/Library/PrivateFrameworks/ProgressUI.framework/',)
+# ... and asset catalogs: the SF Symbols (UIKit crashes on the first system image without them)
+BIG_CATALOGS = ('System/Library/PrivateFrameworks/SFSymbols.framework/',)
+# taken whole in principle, but not these: big and of no use until much later
+SKIP_PREFIX = ('usr/share/tokenizer/', 'usr/share/firmware/', 'usr/share/mecabra/',
+ 'usr/standalone/') + tuple(f'System/Library/{name}/' for name in SKIP_SYSTEM_LIBRARY)
+BIG_PROGRAM = 10 << 20 # daemons bigger than this (locationd, lskdd, ...) are not on the way to the screen
+KEEP_LANG = ('en', 'Base', 'English', 'en_US', 'en_GB')
+
+
+def entries(listing):
+ """Yield one dict per entry of a 7z technical listing."""
+ entry = {}
+ for line in open(listing, errors='replace'):
+ line = line.rstrip('\n')
+ if not line:
+ if 'Path' in entry and 'Mode' in entry:
+ yield entry
+ entry = {}
+ elif ' = ' in line or line.endswith(' ='):
+ key, _, value = line.partition(' =')
+ entry[key] = value[1:] if value.startswith(' ') else value
+ if 'Path' in entry and 'Mode' in entry:
+ yield entry
+
+
+def mode_bits(text):
+ """'-rwsr-xr-x' -> st_mode"""
+ kinds = {'-': stat.S_IFREG, 'd': stat.S_IFDIR, 'l': stat.S_IFLNK}
+ if text[0] not in kinds:
+ return None
+ mode = kinds[text[0]]
+ for i, ch in enumerate(text[1:10]):
+ if ch in 'rwxst':
+ mode |= 0o400 >> i
+ if ch in 'sS' and i == 2:
+ mode |= stat.S_ISUID
+ if ch in 'sS' and i == 5:
+ mode |= stat.S_ISGID
+ if ch in 'tT' and i == 8:
+ mode |= stat.S_ISVTX
+ if ch in 'ST':
+ mode &= ~(0o400 >> i)
+ return mode
+
+
+def wanted_file(path, size):
+ lproj = re.search(r'/([^/]+)\.lproj/', path)
+ if lproj and lproj.group(1) not in KEEP_LANG:
+ return False
+ if path.startswith(SKIP_PREFIX):
+ return False
+ if path.startswith('System/Library/Fonts/'):
+ return size <= MAX_FONT
+ if path.startswith(ALL_PICTURES) and path.lower().endswith('.png'):
+ return True
+ if path.startswith(('usr/libexec/', 'usr/sbin/')):
+ return size <= BIG_PROGRAM
+ if path.startswith('Applications/'):
+ return not path.lower().endswith(SKIP_APP_EXT) and '.mlmodelc/' not in path
+ if path.startswith(FRAMEWORKS):
+ if re.search(r'/(XPCServices|Support|Helpers)/', path):
+ return size <= 32 << 20 and not path.lower().endswith(('.png', '.car', '.loctable', '.caml'))
+ if path.endswith('.car'):
+ return size <= MAX_ASSET_CATALOG or path.startswith(BIG_CATALOGS)
+ if path.endswith('.loctable'):
+ return size <= MAX_STRING_TABLE
+ return size <= SMALL and not path.lower().endswith(SKIP_EXT) and '.mlmodelc/' not in path
+ return path.startswith(WHOLE)
+
+
+def main():
+ listing, files_out, manifest_out = sys.argv[1:4]
+ meta = {} # path in our image -> (mode, uid, gid, target, size)
+ source = {} # ... -> path in Apple's image, where that is another
+ for e in entries(listing):
+ mode = mode_bits(e['Mode'])
+ path = e['Path']
+ if mode is None:
+ continue
+ if path.startswith(STAGED_APPS):
+ source['Applications/' + path[len(STAGED_APPS):]] = path
+ path = 'Applications/' + path[len(STAGED_APPS):]
+ elif path.startswith('private/var/'):
+ continue
+ meta[path] = (mode, int(e.get('User ID') or 0), int(e.get('Group ID') or 0),
+ e.get('Symbolic Link', ''), int(e.get('Size') or 0))
+
+ chosen = set()
+ for path, (mode, uid, gid, target, size) in meta.items():
+ if stat.S_ISREG(mode):
+ keep = wanted_file(path, size)
+ elif stat.S_ISLNK(mode):
+ # a symlink costs nothing: keep every one that lives where we take anything at all
+ keep = '/' not in path or path.startswith(WHOLE) and not path.startswith(SKIP_PREFIX)
+ else:
+ lproj = re.search(r'/([^/]+)\.lproj$', path)
+ keep = '/' not in path or path in ('private/var', 'private/tmp', 'private/etc', 'private/preboot',
+ 'private/xarts', 'private') or \
+ bool(lproj) and lproj.group(1) in KEEP_LANG and path.startswith(WHOLE) and \
+ not path.startswith(SKIP_PREFIX)
+ if keep:
+ chosen.add(path)
+ # every directory on the way to something chosen
+ for path in list(chosen):
+ while '/' in path:
+ path = path.rsplit('/', 1)[0]
+ chosen.add(path)
+
+ total = count = 0
+ with open(files_out, 'w') as files, open(manifest_out, 'w') as manifest:
+ for path in sorted(chosen):
+ if path not in meta:
+ continue
+ mode, uid, gid, target, size = meta[path]
+ manifest.write(f'{mode:o}\t{uid}\t{gid}\t{path}\t{target if stat.S_ISLNK(mode) else ""}\n')
+ if stat.S_ISREG(mode):
+ files.write(source.get(path, path) + '\n')
+ total += size
+ count += 1
+ print(f'select-system: {count} files, {total / 1048576:.0f} MB; {len(chosen)} entries in the manifest')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/mkpackfs.py b/mkpackfs.py
new file mode 100755
index 0000000..1a9b4c8
--- /dev/null
+++ b/mkpackfs.py
@@ -0,0 +1,338 @@
+#!/usr/bin/env python3
+"""Build a packfs image (the read-only filesystems of the Darwin bring-up) from a directory.
+
+usage: mkpackfs.py [-b BLOCK] [-a PAGE] [-z [LEVEL]] [-m MANIFEST] [-o IMAGE] ROOTDIR
+
+The format is described in xnu bsd/miscfs/packfs/packfs.h. Permission bits, symlinks and
+modification times are taken from ROOTDIR, and everything is owned by root:wheel, unless a
+manifest says otherwise. Device nodes, FIFOs and sockets are skipped (/dev is devfs).
+
+With -z every file is stored "chunked": cut into 64 KB chunks, each LZ4-compressed when that
+makes it smaller. Such an image is about half the size and is read in place by the kernel, so
+it mounts only from a RAM disk (see packfs.h). LEVEL is the LZ4 HC level (default 9; 0 = the
+fast compressor).
+
+A manifest (-m) carries what a directory on this machine cannot: lines of
+ mode(octal, with the type bits) <TAB> uid <TAB> gid <TAB> path <TAB> [link target]
+For a path that exists in ROOTDIR it sets owner, group and permissions. A directory or
+symbolic link that is only in the manifest is created in the image; a regular file that is
+only in the manifest is left out (there is nothing to put in it).
+"""
+import argparse
+import concurrent.futures
+import ctypes
+import ctypes.util
+import os
+import stat
+import struct
+import sys
+
+MAGIC = b'PACKFS1\0'
+SUPER_SIZE = 4096
+META_ALIGN = 4096
+SUPER = struct.Struct('<8sIIQQQQQQ')
+DNODE = struct.Struct('<IIIIQQIIIIQQ')
+MAX_NAME = 255
+F_CHUNKED = 0x1
+CHUNK = 65536
+
+_lz4 = None
+
+
+def lz4_block(data, level):
+ """One raw LZ4 block (no frame, no size prefix)."""
+ global _lz4
+ if _lz4 is None:
+ _lz4 = ctypes.CDLL(ctypes.util.find_library('lz4') or 'liblz4.so.1')
+ bound = _lz4.LZ4_compressBound(len(data))
+ out = ctypes.create_string_buffer(bound)
+ if level > 0:
+ n = _lz4.LZ4_compress_HC(data, out, len(data), bound, level)
+ else:
+ n = _lz4.LZ4_compress_default(data, out, len(data), bound)
+ if n <= 0:
+ raise RuntimeError('LZ4 failed')
+ return out.raw[:n]
+
+
+def chunked_extent(job):
+ """The extent of a chunked file: the table of chunk offsets, then the chunks."""
+ path, level = job
+ with open(path, 'rb') as f:
+ data = f.read()
+ chunks = []
+ for at in range(0, len(data), CHUNK):
+ raw = data[at:at + CHUNK]
+ packed = lz4_block(raw, level)
+ chunks.append(packed if len(packed) < len(raw) else raw)
+ table = [(len(chunks) + 1) * 4]
+ for chunk in chunks:
+ table.append(table[-1] + len(chunk))
+ if table[-1] >= 1 << 32:
+ raise RuntimeError(f'{path}: too big for a chunked file')
+ return len(data), struct.pack(f'<{len(table)}I', *table) + b''.join(chunks)
+
+
+def align(value, to):
+ return (value + to - 1) // to * to
+
+
+class Node:
+ def __init__(self, name, mode, mtime, source=None, target=None):
+ self.name = name # bytes
+ self.mode = mode # st_mode: type and permissions
+ self.uid = self.gid = 0
+ self.mtime = int(mtime)
+ self.source = source # regular file: where the contents are
+ self.target = target # symlink: bytes
+ self.children = {} # directory: name -> Node
+ self.parent = None
+ self.index = None
+ self.data = self.size = 0
+ self.name_off = 0
+
+
+def scan(root):
+ """Read the directory into a tree of nodes; returns the root node and the special files skipped."""
+ skipped = []
+
+ def walk(path, name):
+ st = os.lstat(path)
+ if stat.S_ISDIR(st.st_mode):
+ node = Node(name, st.st_mode, st.st_mtime)
+ for entry in os.listdir(path):
+ child = walk(os.path.join(path, entry), os.fsencode(entry))
+ if child is not None:
+ node.children[child.name] = child
+ return node
+ if stat.S_ISREG(st.st_mode):
+ return Node(name, st.st_mode, st.st_mtime, source=path)
+ if stat.S_ISLNK(st.st_mode):
+ return Node(name, st.st_mode, st.st_mtime, target=os.fsencode(os.readlink(path)))
+ skipped.append(path)
+ return None
+
+ return walk(root, b''), skipped
+
+
+def apply_manifest(root, manifest):
+ """Owners, groups and modes from the manifest; directories and symlinks that exist only there."""
+ added = 0
+ for line in open(manifest, 'rb'):
+ fields = line.rstrip(b'\n').split(b'\t')
+ if len(fields) < 4:
+ continue
+ mode, uid, gid, path = int(fields[0], 8), int(fields[1]), int(fields[2]), fields[3]
+ target = fields[4] if len(fields) > 4 else b''
+ node = root
+ parts = [p for p in path.split(b'/') if p]
+ for depth, part in enumerate(parts):
+ child = node.children.get(part)
+ last = depth == len(parts) - 1
+ if child is None:
+ if not last or stat.S_ISREG(mode) or not stat.S_ISDIR(node.mode):
+ node = None # a missing parent, or a file that was not extracted
+ break
+ if stat.S_ISLNK(mode):
+ child = Node(part, mode, root.mtime, target=target)
+ elif stat.S_ISDIR(mode):
+ child = Node(part, mode, root.mtime)
+ else:
+ node = None
+ break
+ node.children[part] = child
+ added += 1
+ node = child
+ if node is not None and stat.S_IFMT(node.mode) == stat.S_IFMT(mode):
+ node.mode, node.uid, node.gid = mode, uid, gid
+ return added
+
+
+def layout(root):
+ """Number the nodes breadth-first, so that the children of a directory are consecutive, sorted by name."""
+ nodes = [root]
+ root.index = 0
+ root.parent = root
+ queue = [root]
+ while queue:
+ directory = queue.pop(0)
+ for name in sorted(directory.children):
+ child = directory.children[name]
+ if len(name) > MAX_NAME:
+ sys.exit(f'mkpackfs: name too long: {name!r}')
+ child.parent = directory
+ child.index = len(nodes)
+ nodes.append(child)
+ if stat.S_ISDIR(child.mode):
+ queue.append(child)
+ return nodes
+
+
+def build_chunked(root, block, output, level):
+ """Write an image in which every file is chunked and compressed."""
+ nodes = layout(root)
+ strings = bytearray(b'\0')
+ for node in nodes:
+ if node.index:
+ node.name_off = len(strings)
+ strings += node.name + b'\0'
+ nodes_off = SUPER_SIZE
+ strings_off = align(nodes_off + len(nodes) * DNODE.size, META_ALIGN)
+ for node in nodes:
+ if stat.S_ISLNK(node.mode):
+ node.data, node.size = len(strings), len(node.target)
+ strings += node.target + b'\0'
+ elif stat.S_ISDIR(node.mode):
+ ordered = sorted(node.children)
+ node.data = node.children[ordered[0]].index if ordered else 0
+ node.size = len(ordered)
+ data_off = align(strings_off + len(strings), META_ALIGN)
+ files = [n for n in nodes if stat.S_ISREG(n.mode)]
+ raw_total = 0
+
+ with open(output, 'wb') as out, concurrent.futures.ProcessPoolExecutor() as pool:
+ out.seek(data_off)
+ # in order, a bounded number of files ahead of the writer (the big ones are 100 MB each)
+ pending = []
+ todo = iter(files)
+
+ def submit():
+ node = next(todo, None)
+ if node is not None:
+ pending.append((node, pool.submit(chunked_extent, (node.source, level))))
+
+ for _ in range(2 * (os.cpu_count() or 2)):
+ submit()
+ while pending:
+ node, future = pending.pop(0)
+ size, extent = future.result()
+ submit()
+ node.size = size
+ raw_total += size
+ if size:
+ out.write(b'\0' * (-out.tell() % 8))
+ node.data = out.tell()
+ out.write(extent)
+ image_size = align(out.tell(), block)
+ out.write(b'\0' * (image_size - out.tell()))
+
+ meta = bytearray(data_off)
+ SUPER.pack_into(meta, 0, MAGIC, block, len(nodes), nodes_off, strings_off, len(strings), data_off, image_size,
+ max(n.mtime for n in nodes))
+ for node in nodes:
+ if stat.S_ISDIR(node.mode):
+ nlink = 2 + sum(stat.S_ISDIR(c.mode) for c in node.children.values())
+ else:
+ nlink = 1
+ flags = F_CHUNKED if stat.S_ISREG(node.mode) and node.size else 0
+ DNODE.pack_into(meta, nodes_off + node.index * DNODE.size, node.mode, node.uid, node.gid, nlink, node.size,
+ node.data, node.parent.index, node.name_off, len(node.name), 0, node.mtime, flags)
+ meta[strings_off:strings_off + len(strings)] = strings
+ out.seek(0)
+ out.write(meta)
+ print(f'{output}: {raw_total // 1048576} MB of files in {(image_size - data_off) // 1048576} MB', file=sys.stderr)
+ return image_size, len(nodes)
+
+
+def build(root, block, output, page=None):
+ """Write the image to output; file data is streamed, never held in memory.
+
+ Files of at least `page` bytes start on a multiple of it (the kernel's page size: such a
+ file can be mapped straight from a memory disk); smaller ones only on a block boundary.
+ """
+ page = page or block
+ nodes = layout(root)
+
+ strings = bytearray(b'\0') # offset 0: the empty name of the root
+ for node in nodes:
+ if node.index:
+ node.name_off = len(strings)
+ strings += node.name + b'\0'
+
+ nodes_off = SUPER_SIZE
+ strings_off = align(nodes_off + len(nodes) * DNODE.size, META_ALIGN)
+
+ for node in nodes:
+ if stat.S_ISLNK(node.mode):
+ node.data, node.size = len(strings), len(node.target)
+ strings += node.target + b'\0'
+ elif stat.S_ISDIR(node.mode):
+ ordered = sorted(node.children)
+ node.data = node.children[ordered[0]].index if ordered else 0
+ node.size = len(ordered)
+
+ data_off = align(strings_off + len(strings), page)
+ cursor = data_off
+ files = [n for n in nodes if stat.S_ISREG(n.mode)]
+ for node in files:
+ node.size = os.path.getsize(node.source)
+ # the page-aligned files first, so that the small ones do not open gaps between them
+ for node in sorted(files, key=lambda n: (n.size < page, n.index)):
+ if node.size:
+ cursor = align(cursor, page if node.size >= page else block)
+ node.data = cursor
+ cursor += align(node.size, block)
+ image_size = align(cursor, page)
+
+ meta = bytearray(data_off)
+ SUPER.pack_into(meta, 0, MAGIC, block, len(nodes), nodes_off, strings_off, len(strings), data_off, image_size,
+ max(n.mtime for n in nodes))
+ for node in nodes:
+ if stat.S_ISDIR(node.mode):
+ nlink = 2 + sum(stat.S_ISDIR(c.mode) for c in node.children.values())
+ else:
+ nlink = 1
+ DNODE.pack_into(meta, nodes_off + node.index * DNODE.size, node.mode, node.uid, node.gid, nlink, node.size,
+ node.data, node.parent.index, node.name_off, len(node.name), 0, node.mtime, 0)
+ meta[strings_off:strings_off + len(strings)] = strings
+
+ with open(output, 'wb') as out:
+ out.write(meta)
+ for node in sorted((n for n in files if n.size), key=lambda n: n.data):
+ out.write(b'\0' * (node.data - out.tell()))
+ copied = 0
+ with open(node.source, 'rb') as f:
+ while chunk := f.read(8 << 20):
+ out.write(chunk)
+ copied += len(chunk)
+ if copied != node.size:
+ sys.exit(f'mkpackfs: {node.source} changed while being packed')
+ out.write(b'\0' * (align(copied, block) - copied))
+ out.write(b'\0' * (image_size - out.tell()))
+ return image_size, len(nodes)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__.split('\n')[0])
+ parser.add_argument('root')
+ parser.add_argument('-o', '--output', default='root.packfs')
+ parser.add_argument('-m', '--manifest', help='owners, modes and extra symlinks/directories (see above)')
+ parser.add_argument('-b', '--block', type=lambda v: int(v, 0), default=16384,
+ help='file data alignment, a power of two >= 4096 (default 16384)')
+ parser.add_argument('-z', '--compress', type=int, nargs='?', const=9, default=None, metavar='LEVEL',
+ help='store every file in LZ4-compressed chunks (an image for a RAM disk only)')
+ parser.add_argument('-a', '--page-align', type=lambda v: int(v, 0), default=0, metavar='SIZE',
+ help='align files of at least SIZE bytes to SIZE (a multiple of the block size); '
+ 'use -b 4096 -a 16384 for images with many small files')
+ args = parser.parse_args()
+ if args.block < 4096 or args.block & (args.block - 1):
+ sys.exit('mkpackfs: block size must be a power of two, at least 4096')
+ if not os.path.isdir(args.root):
+ sys.exit(f'mkpackfs: {args.root} is not a directory')
+
+ root, skipped = scan(args.root)
+ added = apply_manifest(root, args.manifest) if args.manifest else 0
+ if args.page_align and args.page_align % args.block:
+ sys.exit('mkpackfs: the page alignment must be a multiple of the block size')
+ if args.compress is not None:
+ size, count = build_chunked(root, args.block, args.output, args.compress)
+ else:
+ size, count = build(root, args.block, args.output, args.page_align or None)
+ for path in skipped:
+ print(f'mkpackfs: skipped special file {path}', file=sys.stderr)
+ extra = f' ({added} from the manifest alone)' if added else ''
+ print(f'{args.output}: {count} nodes{extra}, {size // 1024} KB')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/mkxnuimg.py b/mkxnuimg.py
new file mode 100755
index 0000000..75206c5
--- /dev/null
+++ b/mkxnuimg.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+"""
+Pack the redwood UEFI (with the hook that starts the XNU loader) and an optional payload
+into an Android boot image for `fastboot boot`.
+
+ kernel = gzip(BootShim + UEFI FD + ["XNUP" container]) + DTB
+
+The boot shim copies the FD to its base and the payload to PAYLOAD_BASE.
+
+The UEFI pieces are taken from a Mu-Silicium tree built here (Mu-Silicium/, see uefi/README.md)
+or, when there is none, from prebuilt/uefi/.
+
+usage: mkxnuimg.py [-p payload.bin] [-o out.img]
+"""
+import argparse, gzip, os, subprocess, sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+MU = os.path.join(HERE, 'Mu-Silicium')
+PREBUILT = os.path.join(HERE, 'prebuilt', 'uefi')
+FD_BASE, FD_SIZE = 0x9FD00000, 0x200000
+PAYLOAD_BASE, PAYLOAD_MAX = 0xF0000000, 0x04000000
+
+ap = argparse.ArgumentParser()
+ap.add_argument('-p', '--payload')
+ap.add_argument('-o', '--output', default=os.path.join(HERE, 'xnu-redwood.img'))
+ap.add_argument('--mode', default='RELEASE')
+args = ap.parse_args()
+
+fd_path = os.path.join(MU, f'Build/redwoodPkg/{args.mode}_CLANGPDB/FV/SILICIUM_UEFI.fd')
+if os.path.isfile(fd_path):
+ shim_dir = os.path.join(MU, 'BootShim')
+ for f in ('BootShim.elf', 'BootShim.bin'):
+ try: os.unlink(os.path.join(shim_dir, f))
+ except FileNotFoundError: pass
+ subprocess.check_call(['make', 'REQUIRES_KERNEL_HEADER=1', f'FD_BASE={FD_BASE:#x}', f'FD_SIZE={FD_SIZE:#x}',
+ f'CFLAGS=--target=aarch64-linux-gnu -DPAYLOAD_BASE={PAYLOAD_BASE:#x}'],
+ cwd=shim_dir, stdout=subprocess.DEVNULL)
+ parts = {'shim': os.path.join(shim_dir, 'BootShim.bin'), 'fd': fd_path,
+ 'dtb': os.path.join(MU, 'Resources/DTBs/redwood.dtb'), 'ramdisk': os.path.join(MU, 'Resources/ramdisk'),
+ 'mkbootimg': os.path.join(MU, 'Resources/Scripts/mkbootimg.py')}
+else:
+ parts = {'shim': os.path.join(PREBUILT, 'BootShim.bin'), 'fd': os.path.join(PREBUILT, 'SILICIUM_UEFI.fd'),
+ 'dtb': os.path.join(PREBUILT, 'redwood.dtb'), 'ramdisk': os.path.join(PREBUILT, 'ramdisk'),
+ 'mkbootimg': os.path.join(PREBUILT, 'mkbootimg.py')}
+shim = open(parts['shim'], 'rb').read()
+fd = open(parts['fd'], 'rb').read()
+assert len(fd) == FD_SIZE, hex(len(fd))
+
+blob = shim + fd
+if args.payload:
+ data = open(args.payload, 'rb').read()
+ # the payload file is a complete "XNUP" container (see xnuloader/mkpayload.py)
+ assert data[:4] == b'XNUP' and len(data) <= PAYLOAD_MAX - 0x1000, 'bad or oversized payload'
+ blob += data
+ blob += b'\0' * (-len(blob) % 16)
+ print(f'payload: {len(data)} bytes, bytesum={sum(data) & 0xffffffff:08x}')
+
+dtb = open(parts['dtb'], 'rb').read()
+kernel = args.output + '.kernel~'
+open(kernel, 'wb').write(gzip.compress(blob, 6) + dtb)
+try:
+ subprocess.check_call([sys.executable, parts['mkbootimg'], '--kernel', kernel, '--ramdisk', parts['ramdisk'],
+ '--header_version', '1', '-o', args.output])
+finally:
+ os.unlink(kernel)
+print(f'{args.output}: {os.path.getsize(args.output)} bytes (shim {len(shim)}, uncompressed {len(blob)})')
diff --git a/prebuilt/SHA256SUMS b/prebuilt/SHA256SUMS
new file mode 100644
index 0000000..bcda47f
--- /dev/null
+++ b/prebuilt/SHA256SUMS
@@ -0,0 +1,20 @@
+Built 2026-10-12 14:04 from this tree.
+
+eb8ceadbfdfd53cc905884e1450a2f40d56f0087ca1296ef18315f024dc1c30f prebuilt/mach.development.bcm2837
+4b703f1bce73fef0cdb803ef4773668d28a4fb956f5e16dcbfb895455ab2e091 prebuilt/loader.efi
+d2a35a4a1d6658ffb3696914f727661b52c9333de8a3af8a31642b8023ce03ac prebuilt/userland/child
+db564073effc31e7ab1679a7ffe0631ec22c3030ad347c927028f3e53c8583c3 prebuilt/userland/hello
+a8baa9ab38333280369b0824aafaf92c7aa6a85851ff0b2551a4c711dbe59cfd prebuilt/userland/hello_dyn
+8ea257e130b1d8757ef2a6311418215b953eff00cfcd8e9956161bbb8f5304b7 prebuilt/userland/init
+14401099c916e09320ae6ee71b13d3522a021f52ff3d5ee4cf31826147d8d61e prebuilt/userland/libredwood.dylib
+8a3eb47519e80f6edb97580e8f7a9d9aafc25e88374dd00bf07cfde66acadce2 prebuilt/userland/libredwood-sb.dylib
+b540c061fc5909e9c640cccf4f6f84fd15b58337caa4f95a3610aa694d198346 prebuilt/userland/mg_test
+e9dd4a78e3f61d5001fd4745cbc3dd6d498850a4140b3e90eeb8592e9dccf349 prebuilt/userland/rwtouch
+298ac69d2e70ec14b86493e31a6592826fd9bff6cddc8b5821da2d01c84954fc prebuilt/userland/stage0
+143a06695cf54273b39a74a979c690715b7ba171dd408400084eac3ca78db3da prebuilt/userland/surf_test
+879d6d554758905cdd17795e7049267bc516452cb6264c20ef11f680d25de5dd prebuilt/userland/svc_test
+c25b95de00e4b2dffa5e1ede1810ff80e29b61f6cc39dc1ae2286620902acd20 prebuilt/uefi/BootShim.bin
+55037fd1a6d6cd861add76c2083d5d4321373bf714acae3f6a40deb004c27d47 prebuilt/uefi/mkbootimg.py
+b5a2c96250612366ea272ffac6d9744aaf4b45aacd96aa7cfcb931ee3b558259 prebuilt/uefi/ramdisk
+ee93220116d7f59664edf41f43dfae69d036f26faa21e55f9e5ba3c1187f6cef prebuilt/uefi/redwood.dtb
+d1c0c4a33fb10cda3e034b09e082fdd8fd68465405c883143f21286972ac21ec prebuilt/uefi/SILICIUM_UEFI.fd
diff --git a/prebuilt/loader.efi b/prebuilt/loader.efi
new file mode 100755
index 0000000..ddb5ee1
Binary files /dev/null and b/prebuilt/loader.efi differ
diff --git a/prebuilt/mach.development.bcm2837 b/prebuilt/mach.development.bcm2837
new file mode 100755
index 0000000..148ebf8
Binary files /dev/null and b/prebuilt/mach.development.bcm2837 differ
diff --git a/prebuilt/uefi/BootShim.bin b/prebuilt/uefi/BootShim.bin
new file mode 100644
index 0000000..8628583
Binary files /dev/null and b/prebuilt/uefi/BootShim.bin differ
diff --git a/prebuilt/uefi/SILICIUM_UEFI.fd b/prebuilt/uefi/SILICIUM_UEFI.fd
new file mode 100644
index 0000000..4632b9b
Binary files /dev/null and b/prebuilt/uefi/SILICIUM_UEFI.fd differ
diff --git a/prebuilt/uefi/mkbootimg.py b/prebuilt/uefi/mkbootimg.py
new file mode 100644
index 0000000..b8c73c6
--- /dev/null
+++ b/prebuilt/uefi/mkbootimg.py
@@ -0,0 +1,674 @@
+#!/usr/bin/env python3
+#
+# Copyright 2015, The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates the boot image."""
+
+from argparse import (ArgumentParser, ArgumentTypeError,
+ FileType, RawDescriptionHelpFormatter)
+from hashlib import sha1
+from os import fstat
+from struct import pack
+
+import array
+import collections
+import os
+import re
+import subprocess
+import tempfile
+
+# Constant and structure definition is in
+# system/tools/mkbootimg/include/bootimg/bootimg.h
+BOOT_MAGIC = 'ANDROID!'
+BOOT_MAGIC_SIZE = 8
+BOOT_NAME_SIZE = 16
+BOOT_ARGS_SIZE = 512
+BOOT_EXTRA_ARGS_SIZE = 1024
+BOOT_IMAGE_HEADER_V1_SIZE = 1648
+BOOT_IMAGE_HEADER_V2_SIZE = 1660
+BOOT_IMAGE_HEADER_V3_SIZE = 1580
+BOOT_IMAGE_HEADER_V3_PAGESIZE = 4096
+BOOT_IMAGE_HEADER_V4_SIZE = 1584
+BOOT_IMAGE_V4_SIGNATURE_SIZE = 4096
+
+VENDOR_BOOT_MAGIC = 'VNDRBOOT'
+VENDOR_BOOT_MAGIC_SIZE = 8
+VENDOR_BOOT_NAME_SIZE = BOOT_NAME_SIZE
+VENDOR_BOOT_ARGS_SIZE = 2048
+VENDOR_BOOT_IMAGE_HEADER_V3_SIZE = 2112
+VENDOR_BOOT_IMAGE_HEADER_V4_SIZE = 2128
+
+VENDOR_RAMDISK_TYPE_NONE = 0
+VENDOR_RAMDISK_TYPE_PLATFORM = 1
+VENDOR_RAMDISK_TYPE_RECOVERY = 2
+VENDOR_RAMDISK_TYPE_DLKM = 3
+VENDOR_RAMDISK_NAME_SIZE = 32
+VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE = 16
+VENDOR_RAMDISK_TABLE_ENTRY_V4_SIZE = 108
+
+# Names with special meaning, mustn't be specified in --ramdisk_name.
+VENDOR_RAMDISK_NAME_BLOCKLIST = {b'default'}
+
+PARSER_ARGUMENT_VENDOR_RAMDISK_FRAGMENT = '--vendor_ramdisk_fragment'
+
+
+def filesize(f):
+ if f is None:
+ return 0
+ try:
+ return fstat(f.fileno()).st_size
+ except OSError:
+ return 0
+
+
+def update_sha(sha, f):
+ if f:
+ sha.update(f.read())
+ f.seek(0)
+ sha.update(pack('I', filesize(f)))
+ else:
+ sha.update(pack('I', 0))
+
+
+def pad_file(f, padding):
+ pad = (padding - (f.tell() & (padding - 1))) & (padding - 1)
+ f.write(pack(str(pad) + 'x'))
+
+
+def get_number_of_pages(image_size, page_size):
+ """calculates the number of pages required for the image"""
+ return (image_size + page_size - 1) // page_size
+
+
+def get_recovery_dtbo_offset(args):
+ """calculates the offset of recovery_dtbo image in the boot image"""
+ num_header_pages = 1 # header occupies a page
+ num_kernel_pages = get_number_of_pages(filesize(args.kernel), args.pagesize)
+ num_ramdisk_pages = get_number_of_pages(filesize(args.ramdisk),
+ args.pagesize)
+ num_second_pages = get_number_of_pages(filesize(args.second), args.pagesize)
+ dtbo_offset = args.pagesize * (num_header_pages + num_kernel_pages +
+ num_ramdisk_pages + num_second_pages)
+ return dtbo_offset
+
+
+def write_header_v3_and_above(args):
+ if args.header_version > 3:
+ boot_header_size = BOOT_IMAGE_HEADER_V4_SIZE
+ else:
+ boot_header_size = BOOT_IMAGE_HEADER_V3_SIZE
+
+ args.output.write(pack(f'{BOOT_MAGIC_SIZE}s', BOOT_MAGIC.encode()))
+ # kernel size in bytes
+ args.output.write(pack('I', filesize(args.kernel)))
+ # ramdisk size in bytes
+ args.output.write(pack('I', filesize(args.ramdisk)))
+ # os version and patch level
+ args.output.write(pack('I', (args.os_version << 11) | args.os_patch_level))
+ args.output.write(pack('I', boot_header_size))
+ # reserved
+ args.output.write(pack('4I', 0, 0, 0, 0))
+ # version of boot image header
+ args.output.write(pack('I', args.header_version))
+ args.output.write(pack(f'{BOOT_ARGS_SIZE + BOOT_EXTRA_ARGS_SIZE}s',
+ args.cmdline))
+ if args.header_version >= 4:
+ # The signature used to verify boot image v4.
+ args.output.write(pack('I', BOOT_IMAGE_V4_SIGNATURE_SIZE))
+ pad_file(args.output, BOOT_IMAGE_HEADER_V3_PAGESIZE)
+
+
+def write_vendor_boot_header(args):
+ if filesize(args.dtb) == 0:
+ raise ValueError('DTB image must not be empty.')
+
+ if args.header_version > 3:
+ vendor_ramdisk_size = args.vendor_ramdisk_total_size
+ vendor_boot_header_size = VENDOR_BOOT_IMAGE_HEADER_V4_SIZE
+ else:
+ vendor_ramdisk_size = filesize(args.vendor_ramdisk)
+ vendor_boot_header_size = VENDOR_BOOT_IMAGE_HEADER_V3_SIZE
+
+ args.vendor_boot.write(pack(f'{VENDOR_BOOT_MAGIC_SIZE}s',
+ VENDOR_BOOT_MAGIC.encode()))
+ # version of boot image header
+ args.vendor_boot.write(pack('I', args.header_version))
+ # flash page size
+ args.vendor_boot.write(pack('I', args.pagesize))
+ # kernel physical load address
+ args.vendor_boot.write(pack('I', args.base + args.kernel_offset))
+ # ramdisk physical load address
+ args.vendor_boot.write(pack('I', args.base + args.ramdisk_offset))
+ # ramdisk size in bytes
+ args.vendor_boot.write(pack('I', vendor_ramdisk_size))
+ args.vendor_boot.write(pack(f'{VENDOR_BOOT_ARGS_SIZE}s',
+ args.vendor_cmdline))
+ # kernel tags physical load address
+ args.vendor_boot.write(pack('I', args.base + args.tags_offset))
+ # asciiz product name
+ args.vendor_boot.write(pack(f'{VENDOR_BOOT_NAME_SIZE}s', args.board))
+
+ # header size in bytes
+ args.vendor_boot.write(pack('I', vendor_boot_header_size))
+
+ # dtb size in bytes
+ args.vendor_boot.write(pack('I', filesize(args.dtb)))
+ # dtb physical load address
+ args.vendor_boot.write(pack('Q', args.base + args.dtb_offset))
+
+ if args.header_version > 3:
+ vendor_ramdisk_table_size = (args.vendor_ramdisk_table_entry_num *
+ VENDOR_RAMDISK_TABLE_ENTRY_V4_SIZE)
+ # vendor ramdisk table size in bytes
+ args.vendor_boot.write(pack('I', vendor_ramdisk_table_size))
+ # number of vendor ramdisk table entries
+ args.vendor_boot.write(pack('I', args.vendor_ramdisk_table_entry_num))
+ # vendor ramdisk table entry size in bytes
+ args.vendor_boot.write(pack('I', VENDOR_RAMDISK_TABLE_ENTRY_V4_SIZE))
+ # bootconfig section size in bytes
+ args.vendor_boot.write(pack('I', filesize(args.vendor_bootconfig)))
+ pad_file(args.vendor_boot, args.pagesize)
+
+
+def write_header(args):
+ if args.header_version > 4:
+ raise ValueError(
+ f'Boot header version {args.header_version} not supported')
+ if args.header_version in {3, 4}:
+ return write_header_v3_and_above(args)
+
+ ramdisk_load_address = ((args.base + args.ramdisk_offset)
+ if filesize(args.ramdisk) > 0 else 0)
+ second_load_address = ((args.base + args.second_offset)
+ if filesize(args.second) > 0 else 0)
+
+ args.output.write(pack(f'{BOOT_MAGIC_SIZE}s', BOOT_MAGIC.encode()))
+ # kernel size in bytes
+ args.output.write(pack('I', filesize(args.kernel)))
+ # kernel physical load address
+ args.output.write(pack('I', args.base + args.kernel_offset))
+ # ramdisk size in bytes
+ args.output.write(pack('I', filesize(args.ramdisk)))
+ # ramdisk physical load address
+ args.output.write(pack('I', ramdisk_load_address))
+ # second bootloader size in bytes
+ args.output.write(pack('I', filesize(args.second)))
+ # second bootloader physical load address
+ args.output.write(pack('I', second_load_address))
+ # kernel tags physical load address
+ args.output.write(pack('I', args.base + args.tags_offset))
+ # flash page size
+ args.output.write(pack('I', args.pagesize))
+ # version of boot image header
+ args.output.write(pack('I', args.header_version))
+ # os version and patch level
+ args.output.write(pack('I', (args.os_version << 11) | args.os_patch_level))
+ # asciiz product name
+ args.output.write(pack(f'{BOOT_NAME_SIZE}s', args.board))
+ args.output.write(pack(f'{BOOT_ARGS_SIZE}s', args.cmdline))
+
+ sha = sha1()
+ update_sha(sha, args.kernel)
+ update_sha(sha, args.ramdisk)
+ update_sha(sha, args.second)
+
+ if args.header_version > 0:
+ update_sha(sha, args.recovery_dtbo)
+ if args.header_version > 1:
+ update_sha(sha, args.dtb)
+
+ img_id = pack('32s', sha.digest())
+
+ args.output.write(img_id)
+ args.output.write(pack(f'{BOOT_EXTRA_ARGS_SIZE}s', args.extra_cmdline))
+
+ if args.header_version > 0:
+ if args.recovery_dtbo:
+ # recovery dtbo size in bytes
+ args.output.write(pack('I', filesize(args.recovery_dtbo)))
+ # recovert dtbo offset in the boot image
+ args.output.write(pack('Q', get_recovery_dtbo_offset(args)))
+ else:
+ # Set to zero if no recovery dtbo
+ args.output.write(pack('I', 0))
+ args.output.write(pack('Q', 0))
+
+ # Populate boot image header size for header versions 1 and 2.
+ if args.header_version == 1:
+ args.output.write(pack('I', BOOT_IMAGE_HEADER_V1_SIZE))
+ elif args.header_version == 2:
+ args.output.write(pack('I', BOOT_IMAGE_HEADER_V2_SIZE))
+
+ if args.header_version > 1:
+ if filesize(args.dtb) == 0:
+ raise ValueError('DTB image must not be empty.')
+
+ # dtb size in bytes
+ args.output.write(pack('I', filesize(args.dtb)))
+ # dtb physical load address
+ args.output.write(pack('Q', args.base + args.dtb_offset))
+
+ pad_file(args.output, args.pagesize)
+ return img_id
+
+
+class AsciizBytes:
+ """Parses a string and encodes it as an asciiz bytes object.
+
+ >>> AsciizBytes(bufsize=4)('foo')
+ b'foo\\x00'
+ >>> AsciizBytes(bufsize=4)('foob')
+ Traceback (most recent call last):
+ ...
+ argparse.ArgumentTypeError: Encoded asciiz length exceeded: max 4, got 5
+ """
+
+ def __init__(self, bufsize):
+ self.bufsize = bufsize
+
+ def __call__(self, arg):
+ arg_bytes = arg.encode() + b'\x00'
+ if len(arg_bytes) > self.bufsize:
+ raise ArgumentTypeError(
+ 'Encoded asciiz length exceeded: '
+ f'max {self.bufsize}, got {len(arg_bytes)}')
+ return arg_bytes
+
+
+class VendorRamdiskTableBuilder:
+ """Vendor ramdisk table builder.
+
+ Attributes:
+ entries: A list of VendorRamdiskTableEntry namedtuple.
+ ramdisk_total_size: Total size in bytes of all ramdisks in the table.
+ """
+
+ VendorRamdiskTableEntry = collections.namedtuple( # pylint: disable=invalid-name
+ 'VendorRamdiskTableEntry',
+ ['ramdisk_path', 'ramdisk_size', 'ramdisk_offset', 'ramdisk_type',
+ 'ramdisk_name', 'board_id'])
+
+ def __init__(self):
+ self.entries = []
+ self.ramdisk_total_size = 0
+ self.ramdisk_names = set()
+
+ def add_entry(self, ramdisk_path, ramdisk_type, ramdisk_name, board_id):
+ # Strip any trailing null for simple comparison.
+ stripped_ramdisk_name = ramdisk_name.rstrip(b'\x00')
+ if stripped_ramdisk_name in VENDOR_RAMDISK_NAME_BLOCKLIST:
+ raise ValueError(
+ f'Banned vendor ramdisk name: {stripped_ramdisk_name}')
+ if stripped_ramdisk_name in self.ramdisk_names:
+ raise ValueError(
+ f'Duplicated vendor ramdisk name: {stripped_ramdisk_name}')
+ self.ramdisk_names.add(stripped_ramdisk_name)
+
+ if board_id is None:
+ board_id = array.array(
+ 'I', [0] * VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE)
+ else:
+ board_id = array.array('I', board_id)
+ if len(board_id) != VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE:
+ raise ValueError('board_id size must be '
+ f'{VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE}')
+
+ with open(ramdisk_path, 'rb') as f:
+ ramdisk_size = filesize(f)
+ self.entries.append(self.VendorRamdiskTableEntry(
+ ramdisk_path, ramdisk_size, self.ramdisk_total_size, ramdisk_type,
+ ramdisk_name, board_id))
+ self.ramdisk_total_size += ramdisk_size
+
+ def write_ramdisks_padded(self, fout, alignment):
+ for entry in self.entries:
+ with open(entry.ramdisk_path, 'rb') as f:
+ fout.write(f.read())
+ pad_file(fout, alignment)
+
+ def write_entries_padded(self, fout, alignment):
+ for entry in self.entries:
+ fout.write(pack('I', entry.ramdisk_size))
+ fout.write(pack('I', entry.ramdisk_offset))
+ fout.write(pack('I', entry.ramdisk_type))
+ fout.write(pack(f'{VENDOR_RAMDISK_NAME_SIZE}s',
+ entry.ramdisk_name))
+ fout.write(entry.board_id)
+ pad_file(fout, alignment)
+
+
+def write_padded_file(f_out, f_in, padding):
+ if f_in is None:
+ return
+ f_out.write(f_in.read())
+ pad_file(f_out, padding)
+
+
+def parse_int(x):
+ return int(x, 0)
+
+
+def parse_os_version(x):
+ match = re.search(r'^(\d{1,3})(?:\.(\d{1,3})(?:\.(\d{1,3}))?)?', x)
+ if match:
+ a = int(match.group(1))
+ b = c = 0
+ if match.lastindex >= 2:
+ b = int(match.group(2))
+ if match.lastindex == 3:
+ c = int(match.group(3))
+ # 7 bits allocated for each field
+ assert a < 128
+ assert b < 128
+ assert c < 128
+ return (a << 14) | (b << 7) | c
+ return 0
+
+
+def parse_os_patch_level(x):
+ match = re.search(r'^(\d{4})-(\d{2})(?:-(\d{2}))?', x)
+ if match:
+ y = int(match.group(1)) - 2000
+ m = int(match.group(2))
+ # 7 bits allocated for the year, 4 bits for the month
+ assert 0 <= y < 128
+ assert 0 < m <= 12
+ return (y << 4) | m
+ return 0
+
+
+def parse_vendor_ramdisk_type(x):
+ type_dict = {
+ 'none': VENDOR_RAMDISK_TYPE_NONE,
+ 'platform': VENDOR_RAMDISK_TYPE_PLATFORM,
+ 'recovery': VENDOR_RAMDISK_TYPE_RECOVERY,
+ 'dlkm': VENDOR_RAMDISK_TYPE_DLKM,
+ }
+ if x.lower() in type_dict:
+ return type_dict[x.lower()]
+ return parse_int(x)
+
+
+def get_vendor_boot_v4_usage():
+ return """vendor boot version 4 arguments:
+ --ramdisk_type {none,platform,recovery,dlkm}
+ specify the type of the ramdisk
+ --ramdisk_name NAME
+ specify the name of the ramdisk
+ --board_id{0..15} NUMBER
+ specify the value of the board_id vector, defaults to 0
+ --vendor_ramdisk_fragment VENDOR_RAMDISK_FILE
+ path to the vendor ramdisk file
+
+ These options can be specified multiple times, where each vendor ramdisk
+ option group ends with a --vendor_ramdisk_fragment option.
+ Each option group appends an additional ramdisk to the vendor boot image.
+"""
+
+
+def parse_vendor_ramdisk_args(args, args_list):
+ """Parses vendor ramdisk specific arguments.
+
+ Args:
+ args: An argparse.Namespace object. Parsed results are stored into this
+ object.
+ args_list: A list of argument strings to be parsed.
+
+ Returns:
+ A list argument strings that are not parsed by this method.
+ """
+ parser = ArgumentParser(add_help=False)
+ parser.add_argument('--ramdisk_type', type=parse_vendor_ramdisk_type,
+ default=VENDOR_RAMDISK_TYPE_NONE)
+ parser.add_argument('--ramdisk_name',
+ type=AsciizBytes(bufsize=VENDOR_RAMDISK_NAME_SIZE),
+ required=True)
+ for i in range(VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE):
+ parser.add_argument(f'--board_id{i}', type=parse_int, default=0)
+ parser.add_argument(PARSER_ARGUMENT_VENDOR_RAMDISK_FRAGMENT, required=True)
+
+ unknown_args = []
+
+ vendor_ramdisk_table_builder = VendorRamdiskTableBuilder()
+ if args.vendor_ramdisk is not None:
+ vendor_ramdisk_table_builder.add_entry(
+ args.vendor_ramdisk.name, VENDOR_RAMDISK_TYPE_PLATFORM, b'', None)
+
+ while PARSER_ARGUMENT_VENDOR_RAMDISK_FRAGMENT in args_list:
+ idx = args_list.index(PARSER_ARGUMENT_VENDOR_RAMDISK_FRAGMENT) + 2
+ vendor_ramdisk_args = args_list[:idx]
+ args_list = args_list[idx:]
+
+ ramdisk_args, extra_args = parser.parse_known_args(vendor_ramdisk_args)
+ ramdisk_args_dict = vars(ramdisk_args)
+ unknown_args.extend(extra_args)
+
+ ramdisk_path = ramdisk_args.vendor_ramdisk_fragment
+ ramdisk_type = ramdisk_args.ramdisk_type
+ ramdisk_name = ramdisk_args.ramdisk_name
+ board_id = [ramdisk_args_dict[f'board_id{i}']
+ for i in range(VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE)]
+ vendor_ramdisk_table_builder.add_entry(ramdisk_path, ramdisk_type,
+ ramdisk_name, board_id)
+
+ if len(args_list) > 0:
+ unknown_args.extend(args_list)
+
+ args.vendor_ramdisk_total_size = (vendor_ramdisk_table_builder
+ .ramdisk_total_size)
+ args.vendor_ramdisk_table_entry_num = len(vendor_ramdisk_table_builder
+ .entries)
+ args.vendor_ramdisk_table_builder = vendor_ramdisk_table_builder
+ return unknown_args
+
+
+def parse_cmdline():
+ version_parser = ArgumentParser(add_help=False)
+ version_parser.add_argument('--header_version', type=parse_int, default=0)
+ if version_parser.parse_known_args()[0].header_version < 3:
+ # For boot header v0 to v2, the kernel commandline field is split into
+ # two fields, cmdline and extra_cmdline. Both fields are asciiz strings,
+ # so we minus one here to ensure the encoded string plus the
+ # null-terminator can fit in the buffer size.
+ cmdline_size = BOOT_ARGS_SIZE + BOOT_EXTRA_ARGS_SIZE - 1
+ else:
+ cmdline_size = BOOT_ARGS_SIZE + BOOT_EXTRA_ARGS_SIZE
+
+ parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter,
+ epilog=get_vendor_boot_v4_usage())
+ parser.add_argument('--kernel', type=FileType('rb'),
+ help='path to the kernel')
+ parser.add_argument('--ramdisk', type=FileType('rb'),
+ help='path to the ramdisk')
+ parser.add_argument('--second', type=FileType('rb'),
+ help='path to the second bootloader')
+ parser.add_argument('--dtb', type=FileType('rb'), help='path to the dtb')
+ dtbo_group = parser.add_mutually_exclusive_group()
+ dtbo_group.add_argument('--recovery_dtbo', type=FileType('rb'),
+ help='path to the recovery DTBO')
+ dtbo_group.add_argument('--recovery_acpio', type=FileType('rb'),
+ metavar='RECOVERY_ACPIO', dest='recovery_dtbo',
+ help='path to the recovery ACPIO')
+ parser.add_argument('--cmdline', type=AsciizBytes(bufsize=cmdline_size),
+ default='', help='kernel command line arguments')
+ parser.add_argument('--vendor_cmdline',
+ type=AsciizBytes(bufsize=VENDOR_BOOT_ARGS_SIZE),
+ default='',
+ help='vendor boot kernel command line arguments')
+ parser.add_argument('--base', type=parse_int, default=0x10000000,
+ help='base address')
+ parser.add_argument('--kernel_offset', type=parse_int, default=0x00008000,
+ help='kernel offset')
+ parser.add_argument('--ramdisk_offset', type=parse_int, default=0x01000000,
+ help='ramdisk offset')
+ parser.add_argument('--second_offset', type=parse_int, default=0x00f00000,
+ help='second bootloader offset')
+ parser.add_argument('--dtb_offset', type=parse_int, default=0x01f00000,
+ help='dtb offset')
+
+ parser.add_argument('--os_version', type=parse_os_version, default=0,
+ help='operating system version')
+ parser.add_argument('--os_patch_level', type=parse_os_patch_level,
+ default=0, help='operating system patch level')
+ parser.add_argument('--tags_offset', type=parse_int, default=0x00000100,
+ help='tags offset')
+ parser.add_argument('--board', type=AsciizBytes(bufsize=BOOT_NAME_SIZE),
+ default='', help='board name')
+ parser.add_argument('--pagesize', type=parse_int,
+ choices=[2**i for i in range(11, 15)], default=2048,
+ help='page size')
+ parser.add_argument('--id', action='store_true',
+ help='print the image ID on standard output')
+ parser.add_argument('--header_version', type=parse_int, default=0,
+ help='boot image header version')
+ parser.add_argument('-o', '--output', type=FileType('wb'),
+ help='output file name')
+ parser.add_argument('--gki_signing_algorithm',
+ help='GKI signing algorithm to use')
+ parser.add_argument('--gki_signing_key',
+ help='path to RSA private key file')
+ parser.add_argument('--gki_signing_signature_args',
+ help='other hash arguments passed to avbtool')
+ parser.add_argument('--gki_signing_avbtool_path',
+ help='path to avbtool for boot signature generation')
+ parser.add_argument('--vendor_boot', type=FileType('wb'),
+ help='vendor boot output file name')
+ parser.add_argument('--vendor_ramdisk', type=FileType('rb'),
+ help='path to the vendor ramdisk')
+ parser.add_argument('--vendor_bootconfig', type=FileType('rb'),
+ help='path to the vendor bootconfig file')
+
+ args, extra_args = parser.parse_known_args()
+ if args.vendor_boot is not None and args.header_version > 3:
+ extra_args = parse_vendor_ramdisk_args(args, extra_args)
+ if len(extra_args) > 0:
+ raise ValueError(f'Unrecognized arguments: {extra_args}')
+
+ if args.header_version < 3:
+ args.extra_cmdline = args.cmdline[BOOT_ARGS_SIZE-1:]
+ args.cmdline = args.cmdline[:BOOT_ARGS_SIZE-1] + b'\x00'
+ assert len(args.cmdline) <= BOOT_ARGS_SIZE
+ assert len(args.extra_cmdline) <= BOOT_EXTRA_ARGS_SIZE
+
+ return args
+
+
+def add_boot_image_signature(args, pagesize):
+ """Adds the boot image signature.
+
+ Note that the signature will only be verified in VTS to ensure a
+ generic boot.img is used. It will not be used by the device
+ bootloader at boot time. The bootloader should only verify
+ the boot vbmeta at the end of the boot partition (or in the top-level
+ vbmeta partition) via the Android Verified Boot process, when the
+ device boots.
+ """
+ args.output.flush() # Flush the buffer for signature calculation.
+
+ # Appends zeros if the signing key is not specified.
+ if not args.gki_signing_key or not args.gki_signing_algorithm:
+ zeros = b'\x00' * BOOT_IMAGE_V4_SIGNATURE_SIZE
+ args.output.write(zeros)
+ pad_file(args.output, pagesize)
+ return
+
+ avbtool = 'avbtool' # Used from otatools.zip or Android build env.
+
+ # We need to specify the path of avbtool in build/core/Makefile.
+ # Because avbtool is not guaranteed to be in $PATH there.
+ if args.gki_signing_avbtool_path:
+ avbtool = args.gki_signing_avbtool_path
+
+ # Need to specify a value of --partition_size for avbtool to work.
+ # We use 64 MB below, but avbtool will not resize the boot image to
+ # this size because --do_not_append_vbmeta_image is also specified.
+ avbtool_cmd = [
+ avbtool, 'add_hash_footer',
+ '--partition_name', 'boot',
+ '--partition_size', str(64 * 1024 * 1024),
+ '--image', args.output.name,
+ '--algorithm', args.gki_signing_algorithm,
+ '--key', args.gki_signing_key,
+ '--salt', 'd00df00d'] # TODO: use a hash of kernel/ramdisk as the salt.
+
+ # Additional arguments passed to avbtool.
+ if args.gki_signing_signature_args:
+ avbtool_cmd += args.gki_signing_signature_args.split()
+
+ # Outputs the signed vbmeta to a separate file, then append to boot.img
+ # as the boot signature.
+ with tempfile.TemporaryDirectory() as temp_out_dir:
+ boot_signature_output = os.path.join(temp_out_dir, 'boot_signature')
+ avbtool_cmd += ['--do_not_append_vbmeta_image',
+ '--output_vbmeta_image', boot_signature_output]
+ subprocess.check_call(avbtool_cmd)
+ with open(boot_signature_output, 'rb') as boot_signature:
+ if filesize(boot_signature) > BOOT_IMAGE_V4_SIGNATURE_SIZE:
+ raise ValueError(
+ f'boot sigature size is > {BOOT_IMAGE_V4_SIGNATURE_SIZE}')
+ write_padded_file(args.output, boot_signature, pagesize)
+
+
+def write_data(args, pagesize):
+ write_padded_file(args.output, args.kernel, pagesize)
+ write_padded_file(args.output, args.ramdisk, pagesize)
+ write_padded_file(args.output, args.second, pagesize)
+
+ if args.header_version > 0 and args.header_version < 3:
+ write_padded_file(args.output, args.recovery_dtbo, pagesize)
+ if args.header_version == 2:
+ write_padded_file(args.output, args.dtb, pagesize)
+ if args.header_version >= 4:
+ add_boot_image_signature(args, pagesize)
+
+
+def write_vendor_boot_data(args):
+ if args.header_version > 3:
+ builder = args.vendor_ramdisk_table_builder
+ builder.write_ramdisks_padded(args.vendor_boot, args.pagesize)
+ write_padded_file(args.vendor_boot, args.dtb, args.pagesize)
+ builder.write_entries_padded(args.vendor_boot, args.pagesize)
+ write_padded_file(args.vendor_boot, args.vendor_bootconfig,
+ args.pagesize)
+ else:
+ write_padded_file(args.vendor_boot, args.vendor_ramdisk, args.pagesize)
+ write_padded_file(args.vendor_boot, args.dtb, args.pagesize)
+
+
+def main():
+ args = parse_cmdline()
+ if args.vendor_boot is not None:
+ if args.header_version not in {3, 4}:
+ raise ValueError(
+ '--vendor_boot not compatible with given header version')
+ if args.header_version == 3 and args.vendor_ramdisk is None:
+ raise ValueError('--vendor_ramdisk missing or invalid')
+ write_vendor_boot_header(args)
+ write_vendor_boot_data(args)
+ if args.output is not None:
+ if args.second is not None and args.header_version > 2:
+ raise ValueError(
+ '--second not compatible with given header version')
+ img_id = write_header(args)
+ if args.header_version > 2:
+ write_data(args, BOOT_IMAGE_HEADER_V3_PAGESIZE)
+ else:
+ write_data(args, args.pagesize)
+ if args.id and img_id is not None:
+ print('0x' + ''.join(f'{octet:02x}' for octet in img_id))
+
+
+if __name__ == '__main__':
+ main()
\ No newline at end of file
diff --git a/prebuilt/uefi/ramdisk b/prebuilt/uefi/ramdisk
new file mode 100644
index 0000000..2995a4d
--- /dev/null
+++ b/prebuilt/uefi/ramdisk
@@ -0,0 +1 @@
+dummy
\ No newline at end of file
diff --git a/prebuilt/uefi/redwood.dtb b/prebuilt/uefi/redwood.dtb
new file mode 100644
index 0000000..123163c
Binary files /dev/null and b/prebuilt/uefi/redwood.dtb differ
diff --git a/prebuilt/userland/child b/prebuilt/userland/child
new file mode 100755
index 0000000..dde667d
Binary files /dev/null and b/prebuilt/userland/child differ
diff --git a/prebuilt/userland/hello b/prebuilt/userland/hello
new file mode 100755
index 0000000..ff1d5c2
Binary files /dev/null and b/prebuilt/userland/hello differ
diff --git a/prebuilt/userland/hello_dyn b/prebuilt/userland/hello_dyn
new file mode 100755
index 0000000..59a27fd
Binary files /dev/null and b/prebuilt/userland/hello_dyn differ
diff --git a/prebuilt/userland/init b/prebuilt/userland/init
new file mode 100755
index 0000000..05f2c08
Binary files /dev/null and b/prebuilt/userland/init differ
diff --git a/prebuilt/userland/libredwood-sb.dylib b/prebuilt/userland/libredwood-sb.dylib
new file mode 100755
index 0000000..3aa9311
Binary files /dev/null and b/prebuilt/userland/libredwood-sb.dylib differ
diff --git a/prebuilt/userland/libredwood.dylib b/prebuilt/userland/libredwood.dylib
new file mode 100755
index 0000000..d3ddb70
Binary files /dev/null and b/prebuilt/userland/libredwood.dylib differ
diff --git a/prebuilt/userland/mg_test b/prebuilt/userland/mg_test
new file mode 100755
index 0000000..2137875
Binary files /dev/null and b/prebuilt/userland/mg_test differ
diff --git a/prebuilt/userland/rwtouch b/prebuilt/userland/rwtouch
new file mode 100755
index 0000000..f29c87c
Binary files /dev/null and b/prebuilt/userland/rwtouch differ
diff --git a/prebuilt/userland/stage0 b/prebuilt/userland/stage0
new file mode 100755
index 0000000..111bd38
Binary files /dev/null and b/prebuilt/userland/stage0 differ
diff --git a/prebuilt/userland/surf_test b/prebuilt/userland/surf_test
new file mode 100755
index 0000000..574f4a0
Binary files /dev/null and b/prebuilt/userland/surf_test differ
diff --git a/prebuilt/userland/svc_test b/prebuilt/userland/svc_test
new file mode 100755
index 0000000..b0b29d0
Binary files /dev/null and b/prebuilt/userland/svc_test differ
diff --git a/qemu/daemonlog.sh b/qemu/daemonlog.sh
new file mode 100755
index 0000000..3d8c2ef
--- /dev/null
+++ b/qemu/daemonlog.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+# Pick one daemon's story out of a run log: its own messages (stderr/os_log on the console), what
+# launchd said about it, its failing system calls and crashes.
+# usage: daemonlog.sh LOG NAME [max lines]
+log=$1 name=$2 max=${3:-60}
+sed -n '/== KERNEL LOG ==/,/--- kernel message buffer ---/p' "$log" |
+ grep -a -E "(^|\] |[ 0-9:.+-]{20,40} )$name\[|\((system|user/[0-9]+|pid)/[^ ]*$name[^)]*\)|requestor = $name\[" |
+ grep -a -v 'internal event\|service state: \(spawn\|xpcproxy\|running\)\|persona\|uncorking\|> created$\|shutting down\|cleaning up\|removing child\|launching: ' |
+ cut -c1-${COLS:-250} | awk '!seen[$0]++' | head -"$max"
+echo "--- crashes"
+grep -a "usertrap: $name\[" -A5 "$log" | sed 's/^\[[^]]*\]: //' | awk '!seen[$0]++' | head -14
+echo "--- failing system calls"
+grep -a "systrace: $name\[" "$log" | sed 's/^\[[^]]*\]: //; s/\[[0-9]*\]/[]/; s/0x[0-9a-f]*/X/g' | sort | uniq -c | sort -rn |
+ grep -a -v 'FeatureFlags\|fsgetpath\|getattrlist\|Info.plist\|libdispatch\|gettid\|#535\|__mac_syscall(X, X, X, X) = 103\|timezone\|shm_open' | cut -c1-200 | head -${SYS:-14}
diff --git a/qemu/run-ios.sh b/qemu/run-ios.sh
new file mode 100755
index 0000000..849d51c
--- /dev/null
+++ b/qemu/run-ios.sh
@@ -0,0 +1,43 @@
+#!/bin/bash
+# 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...]
+# env: ROOT=<small image>, IMG=<system image>, CMDLINE=<extra boot-args>
+# The machine has a display (ramfb; without one SpringBoard does not start): the loader sets a mode of the
+# size of the phone's screen. qemu/screendump.sh saves a picture of it (through the monitor on port 4444).
+# Add "-display gtk" to see it in a window and use it with the mouse: the pointer with the left button
+# held is a finger (the keys L, H, Up and Down are the lock, home and volume buttons).
+# Touches can also be sent from a script: qemu/touch.py (through the QMP socket on port 4445).
+#
+# The system image is not read into QEMU: guest RAM is a private mapping of qemu/ram.img, a sparse
+# file that holds the image at the right offset (reflinked, so it costs neither disk space nor
+# host RAM).
+cd "$(dirname "$(readlink -f "$0")")/.." || exit 1
+K=xnu-src/xnu-8796.121.2/BUILD/obj/DEVELOPMENT_ARM64_BCM2837/mach.development.bcm2837
+[ -f $K ] || { K=prebuilt/mach.development.bcm2837; echo "run-ios.sh: no kernel built here, using $K" >&2; }
+IMG=${IMG:-userland/system.packfs}
+ROOT=${ROOT:-userland/root.packfs}
+[ -f "$IMG" ] && [ -f "$ROOT" ] || { echo "run-ios.sh: $IMG or $ROOT is missing (userland/build.sh makes them)"; exit 1; }
+SECS=${1:-60}; shift
+RAM_BASE=0x40000000 RD_ADDR=0xFC000000 RAM_SIZE=$((12 << 30))
+
+if [ ! -f qemu/ram.img ] || [ "$IMG" -nt qemu/ram.img ]; then
+ python3 - "$IMG" qemu/ram.img $((RD_ADDR - RAM_BASE)) $RAM_SIZE <<'PY' || exit 1
+import os, sys
+src = os.open(sys.argv[1], os.O_RDONLY)
+dst = os.open(sys.argv[2], os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o644)
+offset, size = int(sys.argv[3]), int(sys.argv[4])
+os.ftruncate(dst, size)
+total, done = os.fstat(src).st_size, 0
+while done < total:
+ done += os.copy_file_range(src, dst, total - done, done, offset + done)
+PY
+fi
+xnuloader/mkpayload.py -o qemu/payload.bin kernel=$K ramdisk=$ROOT --rdres "$(printf '%x' "$(stat -c %s "$IMG")")" \
+ --cmdline "loader_return_after=$SECS epoch=$(date +%s) virtio_input=1 $CMDLINE" >/dev/null || exit 1
+QEMU_MEM=12G exec qemu/run.sh $((SECS + 40)) \
+ -object memory-backend-file,id=ram,size=$RAM_SIZE,mem-path="$PWD/qemu/ram.img",share=off \
+ -machine memory-backend=ram \
+ -global virtio-mmio.force-legacy=false -device virtio-tablet-device -device virtio-keyboard-device \
+ -device ramfb -monitor tcp:127.0.0.1:4444,server,nowait -qmp tcp:127.0.0.1:4445,server,nowait "$@"
diff --git a/qemu/run.sh b/qemu/run.sh
new file mode 100755
index 0000000..969fd65
--- /dev/null
+++ b/qemu/run.sh
@@ -0,0 +1,20 @@
+#!/bin/bash
+# Boot the XNU loader + kernel payload under QEMU (virt, GICv3, UEFI at EL1).
+# usage: run.sh [seconds] [extra qemu args...]
+# env: QEMU_EFI, QEMU_VARS the UEFI firmware for aarch64 guests (default: where Arch's edk2-aarch64
+# puts it; Debian/Ubuntu: /usr/share/AAVMF/AAVMF_CODE.fd and AAVMF_VARS.fd)
+cd "$(dirname "$0")"
+T=${1:-20}; shift
+EFI=${QEMU_EFI:-/usr/share/edk2/aarch64/QEMU_EFI.fd}
+[ -f "$EFI" ] || { echo "run.sh: no UEFI firmware at $EFI (set QEMU_EFI and QEMU_VARS)"; exit 1; }
+cp "${QEMU_VARS:-/usr/share/edk2/aarch64/QEMU_VARS.fd}" vars.fd 2>/dev/null
+# the loader is the boot application of the little FAT volume QEMU makes of esp/:
+# the one built here, or else the one that comes with the repository
+L=../xnuloader/loader.efi; [ -f $L ] || L=../prebuilt/loader.efi
+mkdir -p esp/EFI/BOOT && cp -u $L esp/EFI/BOOT/BOOTAA64.EFI
+timeout "$T" qemu-system-aarch64 -M virt,gic-version=3 -cpu cortex-a76 -smp 1 -m ${QEMU_MEM:-6G} \
+ -drive if=pflash,format=raw,readonly=on,file="$EFI" \
+ -drive if=pflash,format=raw,file=vars.fd \
+ -drive file=fat:rw:esp,format=raw,if=virtio \
+ -device loader,file=payload.bin,addr=0xF0000000,force-raw=on \
+ -display none -serial stdio -monitor none -no-reboot "$@" 2>&1
diff --git a/qemu/screendump.sh b/qemu/screendump.sh
new file mode 100755
index 0000000..f2cc36d
--- /dev/null
+++ b/qemu/screendump.sh
@@ -0,0 +1,25 @@
+#!/bin/bash
+# Save the screen of a running QEMU (started with -device ramfb -monitor tcp:127.0.0.1:4444,server,nowait) as a PNG.
+# usage: screendump.sh [out.png] (FULL=1: the whole mode, not only the phone-sized corner)
+out=$(realpath -m "${1:-$(dirname "$(readlink -f "$0")")/../logs/qemu-screen.png}") # QEMU writes it: absolute
+mkdir -p "$(dirname "$out")"
+python3 - "$out" <<'PY'
+import socket, struct, sys, time, zlib, os
+out = sys.argv[1]; ppm = out + '.ppm'
+s = socket.create_connection(('127.0.0.1', 4444)); s.settimeout(2)
+s.sendall(b'\n'); time.sleep(0.3)
+s.sendall(f'screendump {ppm}\n'.encode()); time.sleep(1.5)
+d = open(ppm, 'rb').read(); os.unlink(ppm)
+magic, size, maxval, pix = d.split(b'\n', 3)
+w, h = map(int, size.split())
+# the kernel uses the top left 1125x2436 of a bigger mode as the phone's screen (boot-args fbwidth/fbheight)
+cw, ch = (min(w, 1125), min(h, 2436)) if os.environ.get('FULL') != '1' else (w, h)
+# QEMU pads every row of the PPM to a multiple of 4 bytes (wrong for the format, but that is what it writes)
+stride = len(pix) // h
+rows = b''.join(b'\0' + pix[y * stride:y * stride + cw * 3] for y in range(ch))
+w, h = cw, ch
+chunk = lambda k, b: struct.pack('>I', len(b)) + k + b + struct.pack('>I', zlib.crc32(k + b))
+open(out, 'wb').write(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)) +
+ chunk(b'IDAT', zlib.compress(rows, 6)) + chunk(b'IEND', b''))
+print(out, w, h)
+PY
diff --git a/qemu/sym.py b/qemu/sym.py
new file mode 100755
index 0000000..d9e1888
--- /dev/null
+++ b/qemu/sym.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python3
+"""Symbolicate kernel addresses: sym.py 0xaddr [0xaddr ...] (uses kernel.syms from nm -n)."""
+import sys, bisect, os, subprocess
+syms = []
+for l in open(os.path.join(os.path.dirname(__file__), 'kernel.syms')):
+ p = l.split()
+ if len(p) == 3 and p[1] in 'tTsSdDbB':
+ syms.append((int(p[0], 16), p[2]))
+addrs = [s[0] for s in syms]
+for a in sys.argv[1:]:
+ v = int(a, 16); i = bisect.bisect_right(addrs, v) - 1
+ name = syms[i][1]
+ if name.startswith('__Z'):
+ name = subprocess.run(['c++filt', name[1:]], capture_output=True, text=True).stdout.strip() or name
+ print(f'{a}: {name} + {v - syms[i][0]:#x}')
diff --git a/qemu/symstack.py b/qemu/symstack.py
new file mode 100755
index 0000000..4d88481
--- /dev/null
+++ b/qemu/symstack.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python3
+"""Put names on the user-space addresses the kernel's bring-up aids print.
+
+usage: symstack.py LOG [PROCESS]
+
+Reads the "ustacks:" (boot-args ustacks=NAME ustacks_at=SECONDS [ustacks_ms=PERIOD]) and "usertrap:" lines of a
+console log, subtracts the shared cache slide and looks every address up in the iOS dyld
+shared cache with "ipsw dyld a2s". Lookups take a few seconds each, so the answers are kept
+in ios165/a2s.json. Addresses outside the cache (the program itself) are shown as they are.
+"""
+import json
+import os
+import re
+import subprocess
+import sys
+
+BASE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'ios165')
+CACHE = os.path.join(BASE, '20F66__iPhone10,3_6/dyld_shared_cache_arm64')
+KNOWN = os.path.join(BASE, 'a2s.json')
+CACHE_LOW, CACHE_HIGH = 0x180000000, 0x280000000 # unslid addresses of the shared cache
+
+known = json.load(open(KNOWN)) if os.path.exists(KNOWN) else {}
+
+
+def name(address, slide):
+ unslid = address - slide
+ if not CACHE_LOW <= unslid < CACHE_HIGH:
+ return f'{address:#x} (not in the shared cache)'
+ key = f'{unslid:#x}'
+ if key not in known:
+ out = subprocess.run(['ipsw', 'dyld', 'a2s', CACHE, key], capture_output=True, text=True).stdout
+ lines = [line for line in out.splitlines() if key in line]
+ known[key] = re.sub(r'^\S+:\s*', '', lines[-1]).strip() if lines else '?'
+ json.dump(known, open(KNOWN, 'w'), indent=0)
+ return known[key]
+
+
+def main():
+ log = sys.argv[1]
+ only = sys.argv[2] if len(sys.argv) > 2 else None
+ slide, show = 0, True
+ for line in open(log, errors='replace'):
+ line = line.rstrip('\n')
+ m = re.search(r'(ustacks|usertrap): (\S+)\[(\d+)\].*shared cache slide (0x[0-9a-f]+)', line)
+ if m:
+ slide = int(m.group(4), 16)
+ show = only is None or m.group(2) == only
+ if show:
+ print(line[line.index(m.group(1)):])
+ continue
+ if not show:
+ continue
+ m = re.search(r'ustacks: thread (0x[0-9a-f]+): (.*)', line)
+ if m:
+ print(f' thread {m.group(1)}')
+ for depth, text in enumerate(m.group(2).split()):
+ if depth == 1:
+ continue # the link register: usually stale, the frame chain has the caller
+ print(f' {name(int(text, 16), slide)}')
+ continue
+ m = re.search(r'usertrap: called from (0x[0-9a-f]+)', line)
+ if m:
+ print(f' {name(int(m.group(1), 16), slide)}')
+ elif 'usertrap: x' in line:
+ print(' ' + line[line.index('usertrap:') + 10:])
+
+
+if __name__ == '__main__':
+ main()
diff --git a/qemu/touch.py b/qemu/touch.py
new file mode 100755
index 0000000..2927b0e
--- /dev/null
+++ b/qemu/touch.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python3
+"""Touch the screen of the system running under QEMU (qemu/run-ios.sh), through QMP.
+
+usage: touch.py STEP...
+ tap X Y a short touch
+ hold X Y MS touch and stay
+ swipe X0 Y0 X1 Y1 [MS] drag in MS milliseconds (default 300)
+ key NAME [MS] press a button: lock, home, volup, voldown; fivefingers = five fingers on the
+ screen for MS (held 1500 ms they end the run)
+ stacks PROCESS have the kernel print where the threads of that process are (the
+ addresses come out in the log; qemu/symstack.py names them)
+ wait SECONDS
+Positions are fractions of the screen: 0 0 is the top left corner, 1 1 the bottom right.
+Example, the "swipe up to open" gesture: touch.py swipe 0.5 0.98 0.5 0.4 250
+"""
+import json
+import socket
+import sys
+import time
+
+KEYS = {'lock': 'l', 'home': 'h', 'volup': 'up', 'voldown': 'down', 'fivefingers': 'f11'}
+
+
+class Qmp:
+ def __init__(self, port=4445):
+ self.sock = socket.create_connection(('127.0.0.1', port))
+ self.file = self.sock.makefile('rw')
+ self.file.readline() # the greeting
+ self.command('qmp_capabilities')
+
+ def command(self, name, **arguments):
+ self.file.write(json.dumps({'execute': name, 'arguments': arguments}) + '\n')
+ self.file.flush()
+ while True:
+ reply = json.loads(self.file.readline())
+ if 'return' in reply or 'error' in reply:
+ if 'error' in reply:
+ sys.exit(f'touch.py: {name}: {reply["error"]["desc"]}')
+ return reply['return']
+
+ def events(self, *events):
+ self.command('input-send-event', events=list(events))
+
+ def pointer(self, x, y, down=None):
+ events = [{'type': 'abs', 'data': {'axis': 'x', 'value': round(x * 0x7fff)}},
+ {'type': 'abs', 'data': {'axis': 'y', 'value': round(y * 0x7fff)}}]
+ if down is not None:
+ events.append({'type': 'btn', 'data': {'button': 'left', 'down': down}})
+ self.events(*events)
+
+ def key(self, name, down):
+ self.events({'type': 'key', 'data': {'key': {'type': 'qcode', 'data': name}, 'down': down}})
+
+
+def main():
+ args = sys.argv[1:]
+ if not args:
+ sys.exit(__doc__)
+ qmp = Qmp()
+ while args:
+ step = args.pop(0)
+ if step == 'wait':
+ time.sleep(float(args.pop(0)))
+ elif step in ('tap', 'hold'):
+ x, y = float(args.pop(0)), float(args.pop(0))
+ ms = float(args.pop(0)) if step == 'hold' else 60
+ qmp.pointer(x, y)
+ qmp.pointer(x, y, True)
+ time.sleep(ms / 1000)
+ qmp.pointer(x, y, False)
+ elif step == 'swipe':
+ x0, y0, x1, y1 = (float(args.pop(0)) for _ in range(4))
+ ms = float(args.pop(0)) if args and args[0][0].isdigit() else 300
+ steps = max(2, int(ms / 16))
+ qmp.pointer(x0, y0)
+ qmp.pointer(x0, y0, True)
+ for i in range(1, steps + 1):
+ time.sleep(ms / 1000 / steps)
+ qmp.pointer(x0 + (x1 - x0) * i / steps, y0 + (y1 - y0) * i / steps)
+ time.sleep(0.016)
+ qmp.pointer(x1, y1, False)
+ elif step == 'stacks':
+ # F12, the name, Enter: the kernel's virtio keyboard driver takes it as a command
+ special = {'.': 'dot', '-': 'minus', '_': 'minus', ' ': 'spc'}
+ qmp.key('f12', True)
+ qmp.key('f12', False)
+ for ch in args.pop(0):
+ shifted = ch.isupper() or ch == '_'
+ code = special.get(ch, ch.lower())
+ if shifted:
+ qmp.key('shift', True)
+ qmp.key(code, True)
+ qmp.key(code, False)
+ if shifted:
+ qmp.key('shift', False)
+ time.sleep(0.02)
+ qmp.key('ret', True)
+ qmp.key('ret', False)
+ elif step == 'key':
+ name = KEYS.get(args.pop(0))
+ if name is None:
+ sys.exit('touch.py: buttons are: ' + ' '.join(KEYS))
+ ms = float(args.pop(0)) if args and args[0][0].isdigit() else 80
+ qmp.key(name, True)
+ time.sleep(ms / 1000)
+ qmp.key(name, False)
+ else:
+ sys.exit(f'touch.py: bad step "{step}"')
+ time.sleep(0.05)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/qemu/where.py b/qemu/where.py
new file mode 100755
index 0000000..e537608
--- /dev/null
+++ b/qemu/where.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+"""Ask a running QEMU (monitor on tcp:127.0.0.1:4444) where the guest CPU is, a few times."""
+import socket, time, re, subprocess, sys, os
+n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
+s = socket.create_connection(('127.0.0.1', 4444)); s.settimeout(2)
+def cmd(c):
+ s.sendall(c.encode() + b'\n'); time.sleep(0.4)
+ out = b''
+ try:
+ while True:
+ d = s.recv(65536)
+ if not d: break
+ out += d
+ except socket.timeout:
+ pass
+ return out.decode(errors='replace')
+cmd('')
+pcs = []
+for i in range(n):
+ r = cmd('info registers')
+ m = re.search(r'PC=([0-9a-f]+)', r); l = re.search(r'X30=([0-9a-f]+)', r)
+ if m: pcs.append(('0x' + m.group(1), '0x' + l.group(1) if l else '0x0'))
+ time.sleep(1.0)
+for pc, lr in pcs:
+ out = subprocess.run([os.path.join(os.path.dirname(__file__), 'sym.py'), pc, lr], capture_output=True, text=True).stdout.strip().replace('\n', ' <- lr ')
+ print(out)
diff --git a/tools/recording.py b/tools/recording.py
new file mode 100755
index 0000000..cfb8a6a
--- /dev/null
+++ b/tools/recording.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+"""Make a video of a screen recording left by the kernel's display driver (boot-arg rec_secs=N).
+
+usage: recording.py RECORDING OUT.mp4 [--max-hold SECONDS]
+
+With --max-hold, no picture stays longer than that: the stretches in which nothing changes on the
+screen (an emulated machine thinking about starting an application) are cut short, while whatever
+moves keeps its real speed.
+
+RECORDING is the piece of memory as the loader hands it over ("xl recording"; under QEMU, the
+monitor's pmemsave): a header { "RWREC001", width, height, frames }, then for every frame the
+time it was shown (nanoseconds from the first) and width x height pixels of three bytes (R, G, B).
+The frames are not evenly spaced -- one is recorded whenever the screen changes -- so each is
+repeated for as long as it stayed on the screen, at 30 pictures a second, and ffmpeg encodes
+that. The picture is enlarged twice (it was recorded at a third of the panel's resolution).
+"""
+import struct
+import subprocess
+import sys
+
+FPS = 30
+
+
+def main():
+ if len(sys.argv) < 3:
+ sys.exit(__doc__)
+ data = open(sys.argv[1], 'rb').read()
+ magic, width, height, frames, _ = struct.unpack_from('<8sIIII', data, 0)
+ if magic != b'RWREC002' or not width or not height:
+ sys.exit('recording.py: not a recording')
+ size = width * height * 3
+ times, offsets, at = [], [], 24
+ for _ in range(frames):
+ if at + 8 + size > len(data):
+ break
+ times.append(struct.unpack_from('<Q', data, at)[0] / 1e9)
+ offsets.append(at + 8)
+ at += 8 + size
+ if not times:
+ sys.exit('recording.py: no frames in the recording')
+ real = times[-1]
+ if '--max-hold' in sys.argv:
+ hold = float(sys.argv[sys.argv.index('--max-hold') + 1])
+ squeezed = [0.0]
+ for a, b in zip(times, times[1:]):
+ squeezed.append(squeezed[-1] + min(b - a, hold))
+ times = squeezed
+ length = times[-1] + 1.0
+ scale = f'scale={width * 2}:{height * 2}:flags=lanczos,pad=ceil(iw/2)*2:ceil(ih/2)*2'
+ out = sys.argv[2]
+ codec = ['-c:v', 'libx264', '-preset', 'slow', '-crf', '20', '-pix_fmt', 'yuv420p', '-movflags', '+faststart']
+ ffmpeg = subprocess.Popen(['ffmpeg', '-loglevel', 'error', '-y', '-f', 'rawvideo', '-pix_fmt', 'rgb24',
+ '-s', f'{width}x{height}', '-r', str(FPS), '-i', '-', '-vf', scale] + codec + [out],
+ stdin=subprocess.PIPE)
+ current = 0
+ for n in range(int(length * FPS)):
+ while current + 1 < len(times) and times[current + 1] <= n / FPS:
+ current += 1
+ ffmpeg.stdin.write(data[offsets[current]:offsets[current] + size])
+ ffmpeg.stdin.close()
+ if ffmpeg.wait() != 0:
+ sys.exit('recording.py: ffmpeg failed')
+ gaps = sorted(b - a for a, b in zip(times, times[1:]))
+ typical = gaps[len(gaps) // 2] if gaps else 0
+ print(f'{out}: {len(times)} frames over {real:.1f} s ({len(times) / max(real, 0.001):.1f} a second on average'
+ + (f', typically {1 / typical:.0f} a second while something moves' if typical else '') + f'), {width}x{height}'
+ + (f'; the video is {times[-1]:.0f} s long' if times[-1] != real else ''))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/update-prebuilt.sh b/tools/update-prebuilt.sh
new file mode 100755
index 0000000..8d7fe99
--- /dev/null
+++ b/tools/update-prebuilt.sh
@@ -0,0 +1,25 @@
+#!/bin/bash
+# Refresh prebuilt/ from what is built in this tree: the kernel, the loader, our user-space programs
+# and the pieces of the phone's UEFI. With them somebody without the cross toolchain can still make the
+# images and run the system (QEMU or the phone); see README.md.
+set -e
+cd "$(dirname "$(readlink -f "$0")")/.."
+K=xnu-src/xnu-8796.121.2/BUILD/obj/DEVELOPMENT_ARM64_BCM2837/mach.development.bcm2837
+MU=Mu-Silicium
+mkdir -p prebuilt/userland prebuilt/uefi
+cp $K prebuilt/mach.development.bcm2837
+cp xnuloader/loader.efi prebuilt/loader.efi
+cp userland/hello prebuilt/userland/
+for f in init child stage0 hello_dyn svc_test surf_test rwtouch mg_test libredwood.dylib libredwood-sb.dylib; do
+ cp userland/obj/$f prebuilt/userland/
+done
+if [ -f $MU/Build/redwoodPkg/RELEASE_CLANGPDB/FV/SILICIUM_UEFI.fd ]; then
+ cp $MU/Build/redwoodPkg/RELEASE_CLANGPDB/FV/SILICIUM_UEFI.fd $MU/BootShim/BootShim.bin $MU/Resources/DTBs/redwood.dtb \
+ $MU/Resources/ramdisk $MU/Resources/Scripts/mkbootimg.py prebuilt/uefi/
+fi
+{
+ echo "Built $(date '+%Y-%m-%d %H:%M') from this tree."
+ echo
+ sha256sum prebuilt/mach.development.bcm2837 prebuilt/loader.efi prebuilt/userland/* prebuilt/uefi/* 2>/dev/null
+} > prebuilt/SHA256SUMS
+ls -la prebuilt prebuilt/userland prebuilt/uefi
diff --git a/uefi/BASE b/uefi/BASE
new file mode 100644
index 0000000..eacc726
--- /dev/null
+++ b/uefi/BASE
@@ -0,0 +1 @@
+e51cd877e31c8fbb322032dc4cb6715e83d25ad3
diff --git a/uefi/README.md b/uefi/README.md
new file mode 100644
index 0000000..118efe6
--- /dev/null
+++ b/uefi/README.md
@@ -0,0 +1,47 @@
+# UEFI для redwood
+
+Порт [Project Silicium / Mu-Silicium](https://github.com/Project-Silicium/Mu-Silicium) на POCO X5 Pro 5G (redwood).
+В апстриме этого устройства нет; порт сделан по образцу `lisa` (тот же SoC-пакет `KodiakPkg`).
+
+Для запуска пересобирать UEFI не нужно — готовый образ лежит в `prebuilt/uefi`, `mkxnuimg.py` берёт его сам.
+
+Что здесь:
+
+- `BASE` — коммит Mu-Silicium, на котором сделан порт;
+- `mu-silicium.patch` — правки существующих файлов:
+ `BootShim/BootShim.S` (копирует за образом UEFI наш контейнер «XNUP» по адресу 0xF0000000),
+ `BootManagerLib` (вместо меню запускает загрузчик XNU из контейнера);
+- `files/` — новые файлы: `Platforms/Xiaomi/redwoodPkg` (карта памяти, список драйверов),
+ `Silicon/…/BootManagerLib/XnuLoader.[ch]`, `Resources/Configs/redwood.toml`, `Resources/DTBs/redwood.dtb`
+ (дерево устройств из vendor_boot телефона), `Binaries/redwood` (драйверы UEFI из прошивки
+ `OS1.0.3.0.UMSMIXM`, извлечены [UEFIReader](https://github.com/WOA-Project/UEFIReader) из `xbl.img`,
+ с пятью штатными заплатками Silicium — см. `files/Binaries/redwood/README.md`).
+
+## Сборка
+
+Пакеты — как в `setup_env.sh` из Mu-Silicium (на Arch: `git base-devel lld nasm clang llvm aarch64-linux-gnu-gcc
+python python-pip python-virtualenv`).
+
+```sh
+uefi/apply.sh # клонирует Mu-Silicium (с подмодулями, ~3 ГБ) и накладывает порт
+python3 -m venv venv && venv/bin/pip install -r Mu-Silicium/pip-requirements.txt
+cd Mu-Silicium
+source ../venv/bin/activate
+python3 build_uefi.py -d redwood -r RELEASE # → Build/redwoodPkg/RELEASE_CLANGPDB/FV/SILICIUM_UEFI.fd
+```
+
+Грабля: зависимость `mu_nasm` ставится через NuGet и требует Mono. Обход без Mono — подложить системный nasm:
+
+```sh
+D=Mu_Basecore/BaseTools/Bin/mu_nasm_extdep
+mkdir -p $D/Linux-x86-64
+echo 'version: 20016.1.1' > $D/extdep_state.yaml
+ln -s /usr/bin/nasm /usr/bin/ndisasm $D/Linux-x86-64/
+```
+
+После сборки `mkxnuimg.py` (его вызывает `./xl enter`) берёт UEFI уже из `Mu-Silicium/`, а
+`tools/update-prebuilt.sh` обновляет `prebuilt/uefi`.
+
+`uefi/export.sh` — обратное действие: сохранить правки из `Mu-Silicium/` сюда.
+
+Сборка «с нуля» по этой инструкции заново не проверялась (дерево собиралось по ходу работы над портом).
diff --git a/uefi/apply.sh b/uefi/apply.sh
new file mode 100755
index 0000000..600d260
--- /dev/null
+++ b/uefi/apply.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+# Make ../Mu-Silicium: a clone of Project-Silicium/Mu-Silicium at the commit our port was made on,
+# with the redwood port (this directory) put into it. See README.md here for how to build it.
+set -e
+cd "$(dirname "$(readlink -f "$0")")"
+MU=../Mu-Silicium
+[ -e $MU ] && { echo "uefi/apply.sh: $MU already exists"; exit 1; }
+git clone https://github.com/Project-Silicium/Mu-Silicium.git $MU
+git -C $MU checkout -q "$(cat BASE)"
+git -C $MU submodule update --init --recursive
+git -C $MU apply --whitespace=nowarn "$PWD/mu-silicium.patch"
+cp -r files/. $MU/
+echo "uefi/apply.sh: done; next: uefi/README.md"
diff --git a/uefi/export.sh b/uefi/export.sh
new file mode 100755
index 0000000..14a769a
--- /dev/null
+++ b/uefi/export.sh
@@ -0,0 +1,19 @@
+#!/bin/bash
+# Save our changes to the Mu-Silicium tree (../Mu-Silicium, a clone of Project-Silicium/Mu-Silicium
+# with the redwood port in it) into this directory: mu-silicium.patch for the files that upstream
+# has, files/ for the ones it does not. apply.sh puts them into a fresh clone.
+set -e
+cd "$(dirname "$(readlink -f "$0")")"
+MU=../Mu-Silicium
+git -C $MU rev-parse HEAD > BASE
+git -C $MU diff -- BootShim Silicon > mu-silicium.patch
+rm -rf files
+mkdir -p files/Resources/Configs files/Resources/DTBs files/Platforms/Xiaomi files/Binaries \
+ files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib
+cp -r $MU/Platforms/Xiaomi/redwoodPkg files/Platforms/Xiaomi/
+cp $MU/Resources/Configs/redwood.toml files/Resources/Configs/
+cp $MU/Resources/DTBs/redwood.dtb files/Resources/DTBs/
+cp $MU/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.[ch] files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/
+cp -r $MU/Binaries/redwood files/Binaries/
+find files -name __pycache__ -prune -exec rm -rf {} +
+echo "uefi/export.sh: base $(cut -c1-12 BASE), patch $(wc -l < mu-silicium.patch) lines, $(find files -type f | wc -l) files"
diff --git a/uefi/files/Binaries/redwood/ArmPkg/Drivers/ArmGic/ArmGicDxe.depex b/uefi/files/Binaries/redwood/ArmPkg/Drivers/ArmGic/ArmGicDxe.depex
new file mode 100644
index 0000000..f506d29
Binary files /dev/null and b/uefi/files/Binaries/redwood/ArmPkg/Drivers/ArmGic/ArmGicDxe.depex differ
diff --git a/uefi/files/Binaries/redwood/ArmPkg/Drivers/ArmGic/ArmGicDxe.efi b/uefi/files/Binaries/redwood/ArmPkg/Drivers/ArmGic/ArmGicDxe.efi
new file mode 100644
index 0000000..c692d40
Binary files /dev/null and b/uefi/files/Binaries/redwood/ArmPkg/Drivers/ArmGic/ArmGicDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/ArmPkg/Drivers/ArmGic/ArmGicDxe.inf b/uefi/files/Binaries/redwood/ArmPkg/Drivers/ArmGic/ArmGicDxe.inf
new file mode 100644
index 0000000..bce275d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/ArmPkg/Drivers/ArmGic/ArmGicDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ArmGicDxe
+ FILE_GUID = DE371F7C-DEC4-4D21-ADF1-593ABCC15882
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ArmGicDxe.depex|*
+ PE32|ArmGicDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/ArmPkg/Drivers/CpuDxe/CpuDxe.depex b/uefi/files/Binaries/redwood/ArmPkg/Drivers/CpuDxe/CpuDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/ArmPkg/Drivers/CpuDxe/CpuDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/ArmPkg/Drivers/CpuDxe/CpuDxe.efi b/uefi/files/Binaries/redwood/ArmPkg/Drivers/CpuDxe/CpuDxe.efi
new file mode 100644
index 0000000..e9e4aea
Binary files /dev/null and b/uefi/files/Binaries/redwood/ArmPkg/Drivers/CpuDxe/CpuDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/ArmPkg/Drivers/CpuDxe/CpuDxe.inf b/uefi/files/Binaries/redwood/ArmPkg/Drivers/CpuDxe/CpuDxe.inf
new file mode 100644
index 0000000..fdafca7
--- /dev/null
+++ b/uefi/files/Binaries/redwood/ArmPkg/Drivers/CpuDxe/CpuDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ArmCpuDxe
+ FILE_GUID = B8D9777E-D72A-451F-9BDB-BAFB52A68415
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|CpuDxe.depex|*
+ PE32|CpuDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/ArmPkg/Drivers/TimerDxe/TimerDxe.depex b/uefi/files/Binaries/redwood/ArmPkg/Drivers/TimerDxe/TimerDxe.depex
new file mode 100644
index 0000000..ac7d737
--- /dev/null
+++ b/uefi/files/Binaries/redwood/ArmPkg/Drivers/TimerDxe/TimerDxe.depex
@@ -0,0 +1 @@
+곐(=C� �H�?�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/ArmPkg/Drivers/TimerDxe/TimerDxe.efi b/uefi/files/Binaries/redwood/ArmPkg/Drivers/TimerDxe/TimerDxe.efi
new file mode 100644
index 0000000..fd9aef1
Binary files /dev/null and b/uefi/files/Binaries/redwood/ArmPkg/Drivers/TimerDxe/TimerDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/ArmPkg/Drivers/TimerDxe/TimerDxe.inf b/uefi/files/Binaries/redwood/ArmPkg/Drivers/TimerDxe/TimerDxe.inf
new file mode 100644
index 0000000..c468a10
--- /dev/null
+++ b/uefi/files/Binaries/redwood/ArmPkg/Drivers/TimerDxe/TimerDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ArmTimerDxe
+ FILE_GUID = 49EA041E-6752-42CA-B0B1-7344FE2546B7
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|TimerDxe.depex|*
+ PE32|TimerDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/EmbeddedPkg/Ebl/Ebl.efi b/uefi/files/Binaries/redwood/EmbeddedPkg/Ebl/Ebl.efi
new file mode 100644
index 0000000..0c4dd0c
Binary files /dev/null and b/uefi/files/Binaries/redwood/EmbeddedPkg/Ebl/Ebl.efi differ
diff --git a/uefi/files/Binaries/redwood/EmbeddedPkg/Ebl/Ebl.inf b/uefi/files/Binaries/redwood/EmbeddedPkg/Ebl/Ebl.inf
new file mode 100644
index 0000000..f76ac5c
--- /dev/null
+++ b/uefi/files/Binaries/redwood/EmbeddedPkg/Ebl/Ebl.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = Ebl
+ FILE_GUID = 3CEF354A-3B7A-4519-AD70-72A134698311
+ MODULE_TYPE = UEFI_APPLICATION
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|Ebl.efi|*
diff --git a/uefi/files/Binaries/redwood/EmbeddedPkg/MetronomeDxe/MetronomeDxe.depex b/uefi/files/Binaries/redwood/EmbeddedPkg/MetronomeDxe/MetronomeDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/EmbeddedPkg/MetronomeDxe/MetronomeDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/EmbeddedPkg/MetronomeDxe/MetronomeDxe.efi b/uefi/files/Binaries/redwood/EmbeddedPkg/MetronomeDxe/MetronomeDxe.efi
new file mode 100644
index 0000000..4c8d5bf
Binary files /dev/null and b/uefi/files/Binaries/redwood/EmbeddedPkg/MetronomeDxe/MetronomeDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf b/uefi/files/Binaries/redwood/EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
new file mode 100644
index 0000000..52470b7
--- /dev/null
+++ b/uefi/files/Binaries/redwood/EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = MetronomeDxe
+ FILE_GUID = 4C6E0267-C77D-410D-8100-1495911A989D
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|MetronomeDxe.depex|*
+ PE32|MetronomeDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.depex b/uefi/files/Binaries/redwood/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.efi b/uefi/files/Binaries/redwood/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.efi
new file mode 100644
index 0000000..a68ddfa
Binary files /dev/null and b/uefi/files/Binaries/redwood/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf b/uefi/files/Binaries/redwood/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
new file mode 100644
index 0000000..f7565d9
--- /dev/null
+++ b/uefi/files/Binaries/redwood/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = RealTimeClock
+ FILE_GUID = B336F62D-4135-4A55-AE4E-4971BBF0885D
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|RealTimeClockRuntimeDxe.depex|*
+ PE32|RealTimeClockRuntimeDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/FatPkg/EnhancedFatDxe/Fat.efi b/uefi/files/Binaries/redwood/FatPkg/EnhancedFatDxe/Fat.efi
new file mode 100644
index 0000000..501b37b
Binary files /dev/null and b/uefi/files/Binaries/redwood/FatPkg/EnhancedFatDxe/Fat.efi differ
diff --git a/uefi/files/Binaries/redwood/FatPkg/EnhancedFatDxe/Fat.inf b/uefi/files/Binaries/redwood/FatPkg/EnhancedFatDxe/Fat.inf
new file mode 100644
index 0000000..3b227d7
--- /dev/null
+++ b/uefi/files/Binaries/redwood/FatPkg/EnhancedFatDxe/Fat.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = Fat
+ FILE_GUID = 961578FE-B6B7-44C3-AF35-6BC705CD2B1F
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|Fat.efi|*
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Core/Dxe/DxeMain.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Core/Dxe/DxeMain.efi
new file mode 100644
index 0000000..bff2e14
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Core/Dxe/DxeMain.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Core/Dxe/DxeMain.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Core/Dxe/DxeMain.inf
new file mode 100644
index 0000000..b409238
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Core/Dxe/DxeMain.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = DxeCore
+ FILE_GUID = D6A2CB7F-6A18-4E2F-B43B-9920A733700A
+ MODULE_TYPE = DXE_CORE
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|DxeMain.efi|*
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.depex b/uefi/files/Binaries/redwood/MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.efi
new file mode 100644
index 0000000..2e5a7b1
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
new file mode 100644
index 0000000..0b3f05f
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = RuntimeDxe
+ FILE_GUID = B601F8C4-43B7-4784-95B1-F4226CB40CEE
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|RuntimeDxe.depex|*
+ PE32|RuntimeDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.depex b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.depex
new file mode 100644
index 0000000..f1f3873
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.depex
@@ -0,0 +1 @@
+�AdbcDN�p}�1�$S
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.efi
new file mode 100644
index 0000000..db35ecd
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
new file mode 100644
index 0000000..2814017
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = CapsuleRuntimeDxe
+ FILE_GUID = 42857F0A-13F2-4B21-8A23-53D3F714B840
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|CapsuleRuntimeDxe.depex|*
+ PE32|CapsuleRuntimeDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.efi
new file mode 100644
index 0000000..5cbd31f
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
new file mode 100644
index 0000000..af348c9
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ConPlatformDxe
+ FILE_GUID = 51CCF399-4FDF-4E55-A45B-E123F84D456A
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|ConPlatformDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.efi
new file mode 100644
index 0000000..1b5b79f
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
new file mode 100644
index 0000000..3ca8862
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ConSplitterDxe
+ FILE_GUID = 408EDCEC-CF6D-477C-A5A8-B4844E3DE281
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|ConSplitterDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.efi
new file mode 100644
index 0000000..a484a0f
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
new file mode 100644
index 0000000..b38ab73
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = GraphicsConsoleDxe
+ FILE_GUID = CCCB0C28-4B24-11D5-9A5A-0090273FC14D
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|GraphicsConsoleDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.depex b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.efi
new file mode 100644
index 0000000..c98c460
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
new file mode 100644
index 0000000..cbd1bad
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = DevicePathDxe
+ FILE_GUID = 9B680FCE-AD6B-4F3A-B60B-F59899003443
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|DevicePathDxe.depex|*
+ PE32|DevicePathDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.efi
new file mode 100644
index 0000000..410023f
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
new file mode 100644
index 0000000..684fe6a
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = DiskIoDxe
+ FILE_GUID = 6B38F7B4-AD98-40E9-9093-ACA2B5A253C4
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|DiskIoDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.efi
new file mode 100644
index 0000000..9a027c6
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
new file mode 100644
index 0000000..7fe2c6e
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = PartitionDxe
+ FILE_GUID = 1FA1F39E-FEFF-4AAE-BD7B-38A070A3B609
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|PartitionDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.efi
new file mode 100644
index 0000000..5f17ef7
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
new file mode 100644
index 0000000..996e012
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = EnglishDxe
+ FILE_GUID = CD3BAFB6-50FB-4FE8-8E4E-AB74D2C1A600
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|EnglishDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/FvSimpleFileSystemDxe/FvSimpleFileSystemDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/FvSimpleFileSystemDxe/FvSimpleFileSystemDxe.efi
new file mode 100644
index 0000000..ebd1982
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/FvSimpleFileSystemDxe/FvSimpleFileSystemDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/FvSimpleFileSystemDxe/FvSimpleFileSystemDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/FvSimpleFileSystemDxe/FvSimpleFileSystemDxe.inf
new file mode 100644
index 0000000..7cc6c2d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/FvSimpleFileSystemDxe/FvSimpleFileSystemDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = FvSimpleFileSystem
+ FILE_GUID = 907125C0-A5F1-11E3-A3FE-A3198B49350C
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|FvSimpleFileSystemDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.depex b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.efi
new file mode 100644
index 0000000..f176a63
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
new file mode 100644
index 0000000..6cd02af
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = HiiDatabase
+ FILE_GUID = 348C4D62-BFBD-4882-9ECE-C80BB1C4783B
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|HiiDatabaseDxe.depex|*
+ PE32|HiiDatabaseDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/PrintDxe/PrintDxe.depex b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/PrintDxe/PrintDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/PrintDxe/PrintDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/PrintDxe/PrintDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/PrintDxe/PrintDxe.efi
new file mode 100644
index 0000000..4a37ed1
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/PrintDxe/PrintDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/PrintDxe/PrintDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/PrintDxe/PrintDxe.inf
new file mode 100644
index 0000000..2a5bf0d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/PrintDxe/PrintDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = PrintDxe
+ FILE_GUID = 79E4A61C-ED73-4312-94FE-E3E7563362A9
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|PrintDxe.depex|*
+ PE32|PrintDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/RscRtDxe.depex b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/RscRtDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/RscRtDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/RscRtDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/RscRtDxe.efi
new file mode 100644
index 0000000..fae74c5
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/RscRtDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/RscRtDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/RscRtDxe.inf
new file mode 100644
index 0000000..e593844
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/RscRtDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = RscRtDxe
+ FILE_GUID = D93CE3D8-A7EB-4730-8C8E-CC466A9ECC3C
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|RscRtDxe.depex|*
+ PE32|RscRtDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.depex b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.efi
new file mode 100644
index 0000000..eded0dd
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
new file mode 100644
index 0000000..b0bd12a
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = SecurityStubDxe
+ FILE_GUID = F80697E9-7FD6-4665-8646-88E33EF71DFC
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|SecurityStubDxe.depex|*
+ PE32|SecurityStubDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/SCHandlerRtDxe.depex b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/SCHandlerRtDxe.depex
new file mode 100644
index 0000000..0ae5438
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/SCHandlerRtDxe.depex
@@ -0,0 +1 @@
+6)!�v�A�:*��9�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/SCHandlerRtDxe.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/SCHandlerRtDxe.efi
new file mode 100644
index 0000000..11065c6
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/SCHandlerRtDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/SCHandlerRtDxe.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/SCHandlerRtDxe.inf
new file mode 100644
index 0000000..679892c
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/SCHandlerRtDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = SCHandlerRtDxe
+ FILE_GUID = 6C2004EF-4E0E-4BE4-B14C-340EB4AA5891
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|SCHandlerRtDxe.depex|*
+ PE32|SCHandlerRtDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.depex b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.depex
new file mode 100644
index 0000000..03d5718
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.depex differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.efi b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.efi
new file mode 100644
index 0000000..30d8593
Binary files /dev/null and b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.efi differ
diff --git a/uefi/files/Binaries/redwood/MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
new file mode 100644
index 0000000..59747c6
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = WatchdogTimer
+ FILE_GUID = F099D67F-71AE-4C36-B2A3-DCEB0EB2B7D8
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|WatchdogTimer.depex|*
+ PE32|WatchdogTimer.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/MiPkg/Protocol/MiToken/MiToken.depex b/uefi/files/Binaries/redwood/MiPkg/Protocol/MiToken/MiToken.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MiPkg/Protocol/MiToken/MiToken.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/MiPkg/Protocol/MiToken/MiToken.efi b/uefi/files/Binaries/redwood/MiPkg/Protocol/MiToken/MiToken.efi
new file mode 100644
index 0000000..a0e9d02
Binary files /dev/null and b/uefi/files/Binaries/redwood/MiPkg/Protocol/MiToken/MiToken.efi differ
diff --git a/uefi/files/Binaries/redwood/MiPkg/Protocol/MiToken/MiToken.inf b/uefi/files/Binaries/redwood/MiPkg/Protocol/MiToken/MiToken.inf
new file mode 100644
index 0000000..54d4fdd
--- /dev/null
+++ b/uefi/files/Binaries/redwood/MiPkg/Protocol/MiToken/MiToken.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = MiTokenDxe
+ FILE_GUID = 068AAE46-BDC6-4073-85D5-31C5EEF19A15
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|MiToken.depex|*
+ PE32|MiToken.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Application/QcomChargerApp/QcomChargerApp.efi b/uefi/files/Binaries/redwood/QcomPkg/Application/QcomChargerApp/QcomChargerApp.efi
new file mode 100644
index 0000000..1aa2363
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Application/QcomChargerApp/QcomChargerApp.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Application/QcomChargerApp/QcomChargerApp.inf b/uefi/files/Binaries/redwood/QcomPkg/Application/QcomChargerApp/QcomChargerApp.inf
new file mode 100644
index 0000000..5b315be
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Application/QcomChargerApp/QcomChargerApp.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = QcomChargerApp
+ FILE_GUID = EEE9C2B1-16CA-4F34-87EA-2E6D1E160CC4
+ MODULE_TYPE = UEFI_APPLICATION
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|QcomChargerApp.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ASN1X509Dxe/ASN1X509Dxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ASN1X509Dxe/ASN1X509Dxe.efi
new file mode 100644
index 0000000..3749166
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ASN1X509Dxe/ASN1X509Dxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ASN1X509Dxe/ASN1X509Dxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ASN1X509Dxe/ASN1X509Dxe.inf
new file mode 100644
index 0000000..32b34c4
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ASN1X509Dxe/ASN1X509Dxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ASN1X509Dxe
+ FILE_GUID = C2F9A4F5-F7B4-43E7-BA99-5EA804CC103A
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|ASN1X509Dxe.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.depex
new file mode 100644
index 0000000..0704fb6
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.depex differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.efi
new file mode 100644
index 0000000..7e942df
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.inf
new file mode 100644
index 0000000..eefb737
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ButtonsDxe
+ FILE_GUID = 5BD181DB-0487-4F1A-AE73-820E165611B3
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ButtonsDxe.depex|*
+ PE32|ButtonsDxe.patched.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.patched.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.patched.efi
new file mode 100644
index 0000000..85c3b02
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.patched.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.depex
new file mode 100644
index 0000000..d24065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.efi
new file mode 100644
index 0000000..c816eb9
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.inf
new file mode 100644
index 0000000..44ca0f2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = CPRDxe
+ FILE_GUID = 1B52138D-3FA3-4E50-B958-20887353F809
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|CPRDxe.depex|*
+ PE32|CPRDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.efi
new file mode 100644
index 0000000..f5e2467
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.inf
new file mode 100644
index 0000000..fe80775
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ChargerExDxe
+ FILE_GUID = 2E3042F3-2BB9-463F-8866-56D75B7C4AB0
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ChargerExDxe.depex|*
+ PE32|ChargerExDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.depex
new file mode 100644
index 0000000..26bd57d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�|�a�'�(O�=2�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.efi
new file mode 100644
index 0000000..0b11d97
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.inf
new file mode 100644
index 0000000..81c6ec2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ChipInfo
+ FILE_GUID = 10E193DF-9966-44E7-B17C-59DD831E20FC
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ChipInfoDxe.depex|*
+ PE32|ChipInfoDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.depex
new file mode 100644
index 0000000..14cd96a
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�iv� �zH��(�{E��
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.efi
new file mode 100644
index 0000000..4b08807
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.inf
new file mode 100644
index 0000000..28494fd
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ClockDxe
+ FILE_GUID = 4DB5DEA6-5302-4D1A-8A82-677A683B0D29
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ClockDxe.depex|*
+ PE32|ClockDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.efi
new file mode 100644
index 0000000..57de829
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.inf
new file mode 100644
index 0000000..f5b03e7
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = CmdDbDxe
+ FILE_GUID = ABA01FF8-2CCB-4E12-8B2E-CD3F4A742993
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|CmdDbDxe.depex|*
+ PE32|CmdDbDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.depex
new file mode 100644
index 0000000..098cfdc
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.depex
@@ -0,0 +1 @@
+����9��G��f�v28
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.efi
new file mode 100644
index 0000000..7bd1f22
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.inf
new file mode 100644
index 0000000..ef30e94
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = DALSys
+ FILE_GUID = 8E9BD160-B184-11DF-94E2-0800200C9A66
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|DALSYSDxe.depex|*
+ PE32|DALSYSDxe.patched.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.patched.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.patched.efi
new file mode 100644
index 0000000..06e1e38
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.patched.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.efi
new file mode 100644
index 0000000..8a4b625
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.inf
new file mode 100644
index 0000000..f5f8e4e
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = DDRInfoDxe
+ FILE_GUID = 7DB0793A-4402-4BE1-906E-D0FABAD2707E
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|DDRInfoDxe.depex|*
+ PE32|DDRInfoDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.depex
new file mode 100644
index 0000000..b0b41b3
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.depex
@@ -0,0 +1 @@
+E\z�!�C�|�/�_�iv� �zH��(�{E��A|�[`�[C�[<>�+�Q=��"��O�&����h-����l�H�U��B��O�f�l�MB�b�ӵ���Q��8��F���iR�V��GoUiB�(.�� 욭�{ H��00�=���z�>M�\�m�����$_�lO��Ž�y��
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.efi
new file mode 100644
index 0000000..5ea2546
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.inf
new file mode 100644
index 0000000..705cbba
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = DisplayDxe
+ FILE_GUID = 4138022F-06C7-4F79-9C94-7E33B511A4E7
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|DisplayDxe.depex|*
+ PE32|DisplayDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.efi
new file mode 100644
index 0000000..4a8ccf8
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
new file mode 100644
index 0000000..7dab538
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = EmbeddedMonotonicCounter
+ FILE_GUID = 37795BA0-E1CF-4ED5-BD8B-16DF6BCB1E1A
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|EmbeddedMonotonicCounter.depex|*
+ PE32|EmbeddedMonotonicCounter.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.efi
new file mode 100644
index 0000000..e6924de
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.inf
new file mode 100644
index 0000000..4d0b04b
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = EnvDxe
+ FILE_GUID = 90A49AFD-422F-08AE-9611-E788D3804845
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|EnvDxe.depex|*
+ PE32|EnvDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/FeatureEnablerDxe/FeatureEnablerDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FeatureEnablerDxe/FeatureEnablerDxe.efi
new file mode 100644
index 0000000..9b01d1a
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FeatureEnablerDxe/FeatureEnablerDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/FeatureEnablerDxe/FeatureEnablerDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FeatureEnablerDxe/FeatureEnablerDxe.inf
new file mode 100644
index 0000000..05c0608
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FeatureEnablerDxe/FeatureEnablerDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = FeatureEnablerDxe
+ FILE_GUID = 1C04F529-0612-4319-9315-B2E75C16810A
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|FeatureEnablerDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/FontDxe/FontDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FontDxe/FontDxe.depex
new file mode 100644
index 0000000..2520e65
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FontDxe/FontDxe.depex
@@ -0,0 +1 @@
+ti��#�L�˘�wP2*r��ﲡ�F�'m2�A`B�r~XP�yO� �)��
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/FontDxe/FontDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FontDxe/FontDxe.efi
new file mode 100644
index 0000000..2f0393d
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FontDxe/FontDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/FontDxe/FontDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FontDxe/FontDxe.inf
new file mode 100644
index 0000000..92577da
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FontDxe/FontDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = FontDxe
+ FILE_GUID = ED15FFD5-BC96-4107-9118-95366600188E
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|FontDxe.depex|*
+ PE32|FontDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/FvUtilsDxe/FvUtilsDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FvUtilsDxe/FvUtilsDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FvUtilsDxe/FvUtilsDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/FvUtilsDxe/FvUtilsDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FvUtilsDxe/FvUtilsDxe.efi
new file mode 100644
index 0000000..a5b87f7
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FvUtilsDxe/FvUtilsDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/FvUtilsDxe/FvUtilsDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FvUtilsDxe/FvUtilsDxe.inf
new file mode 100644
index 0000000..0288d11
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/FvUtilsDxe/FvUtilsDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = FvDxe
+ FILE_GUID = E2534A24-1D9A-4A54-AAEC-BE8836D0F45D
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|FvUtilsDxe.depex|*
+ PE32|FvUtilsDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.depex
new file mode 100644
index 0000000..fd2256c
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.depex
@@ -0,0 +1 @@
+׊�R�7A�d��M�.�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.efi
new file mode 100644
index 0000000..1ff2920
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.inf
new file mode 100644
index 0000000..d1236f2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = GlinkDxe
+ FILE_GUID = 7942A7EB-B7D5-4E2E-B908-831E4DE55B58
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|GLinkDxe.depex|*
+ PE32|GLinkDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.depex
new file mode 100644
index 0000000..1a5bc1e
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.depex differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.efi
new file mode 100644
index 0000000..8819d6b
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.inf
new file mode 100644
index 0000000..01f2753
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = GpiDxe
+ FILE_GUID = 569EA0DE-B557-4043-84CF-01103FE516E5
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|GpiDxe.depex|*
+ PE32|GpiDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.depex
new file mode 100644
index 0000000..1a5bc1e
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.depex differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.efi
new file mode 100644
index 0000000..ab44caf
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.inf
new file mode 100644
index 0000000..9bfa428
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = HALIOMMU
+ FILE_GUID = 9A00771F-36D4-4DD5-8916-C48ED9B16B86
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|HALIOMMUDxe.depex|*
+ PE32|HALIOMMUDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.depex
new file mode 100644
index 0000000..d24065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.efi
new file mode 100644
index 0000000..0ec24fb
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.inf
new file mode 100644
index 0000000..cbff823
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = HWIODxeDriver
+ FILE_GUID = AF9763A2-033B-4109-8E17-56A98D380C92
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|HWIODxe.depex|*
+ PE32|HWIODxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.depex
new file mode 100644
index 0000000..11fe8cc
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.depex differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.efi
new file mode 100644
index 0000000..8162707
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.inf
new file mode 100644
index 0000000..314c74f
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = I2C
+ FILE_GUID = 04DE8591-D2B3-4077-BBBE-B12070094EB6
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|I2CDxe.depex|*
+ PE32|I2CDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.depex
new file mode 100644
index 0000000..14cd96a
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�iv� �zH��(�{E��
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.efi
new file mode 100644
index 0000000..d1522cc
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.inf
new file mode 100644
index 0000000..f505857
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ICBDxe
+ FILE_GUID = 5824F9DE-17D2-4B1F-A5FE-5EB77FA53093
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ICBDxe.depex|*
+ PE32|ICBDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.depex
new file mode 100644
index 0000000..d24065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.efi
new file mode 100644
index 0000000..943ae5e
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.inf
new file mode 100644
index 0000000..a27ee3a
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = IPCCDxe
+ FILE_GUID = 42031F68-1F0B-429B-93F1-0EB0CF89DDBF
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|IPCCDxe.depex|*
+ PE32|IPCCDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.efi
new file mode 100644
index 0000000..d92caae
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.inf
new file mode 100644
index 0000000..fa4279b
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = LimitsDxe
+ FILE_GUID = F09AD92E-4E91-490F-AB89-E66939B840B2
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|LimitsDxe.depex|*
+ PE32|LimitsDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/MinidumpTADxe/MinidumpTADxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/MinidumpTADxe/MinidumpTADxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/MinidumpTADxe/MinidumpTADxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/MinidumpTADxe/MinidumpTADxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/MinidumpTADxe/MinidumpTADxe.efi
new file mode 100644
index 0000000..a260f7b
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/MinidumpTADxe/MinidumpTADxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/MinidumpTADxe/MinidumpTADxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/MinidumpTADxe/MinidumpTADxe.inf
new file mode 100644
index 0000000..dfab633
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/MinidumpTADxe/MinidumpTADxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = MinidumpTADxe
+ FILE_GUID = 2A0ECDCE-01AE-446E-9FFD-C4217DE0340F
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|MinidumpTADxe.depex|*
+ PE32|MinidumpTADxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.efi
new file mode 100644
index 0000000..ab84660
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.inf
new file mode 100644
index 0000000..6adb5f1
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = NpaDxe
+ FILE_GUID = CB29F4D1-7F37-4692-A416-93E82E219711
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|NpaDxe.depex|*
+ PE32|NpaDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.depex
new file mode 100644
index 0000000..d24065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.efi
new file mode 100644
index 0000000..559185d
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.inf
new file mode 100644
index 0000000..210065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = PILDxe
+ FILE_GUID = 1D317734-4083-47C6-83EA-E3A42F2A6BFF
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|PILDxe.depex|*
+ PE32|PILDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.depex
new file mode 100644
index 0000000..e34b761
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.depex
@@ -0,0 +1 @@
+3���mN�>+g��$��w$��K�.4�z��
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.efi
new file mode 100644
index 0000000..0255bfe
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.inf
new file mode 100644
index 0000000..7120d29
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = PILProxyDxe
+ FILE_GUID = 8CF9C920-D5E6-4DAC-BEF9-6E6A4EEC7ADD
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|PILProxyDxe.depex|*
+ PE32|PILProxyDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ParserDxe/ParserDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ParserDxe/ParserDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ParserDxe/ParserDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ParserDxe/ParserDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ParserDxe/ParserDxe.efi
new file mode 100644
index 0000000..f4948fc
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ParserDxe/ParserDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ParserDxe/ParserDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ParserDxe/ParserDxe.inf
new file mode 100644
index 0000000..ddc6727
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ParserDxe/ParserDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ParserDxe
+ FILE_GUID = 4A568B8A-4D9D-4984-9C75-CEE33698E451
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ParserDxe.depex|*
+ PE32|ParserDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.depex
new file mode 100644
index 0000000..d24065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.efi
new file mode 100644
index 0000000..7d2b94f
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.inf
new file mode 100644
index 0000000..f39e53a
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = PlatformInfoDxeDriver
+ FILE_GUID = B105211B-BBBD-4ADD-A3B0-D1CF4A52154C
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|PlatformInfoDxe.depex|*
+ PE32|PlatformInfoDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.depex
new file mode 100644
index 0000000..743af29
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�k0_�}��J�}�/��0
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.efi
new file mode 100644
index 0000000..1919984
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.inf
new file mode 100644
index 0000000..4ce6a10
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = PmicDxe
+ FILE_GUID = 5776232E-082D-4B75-9A0E-FE1D13F7A5D9
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|PmicDxeLa.depex|*
+ PE32|PmicDxeLa.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.efi
new file mode 100644
index 0000000..7bcbf71
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.inf
new file mode 100644
index 0000000..bd263ed
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = PmicGlinkDxe
+ FILE_GUID = 6D4A9CF7-CC0C-42B0-AA89-F6A6A8D99273
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|PmicGlinkDxe.depex|*
+ PE32|PmicGlinkDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.depex
new file mode 100644
index 0000000..d24065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.efi
new file mode 100644
index 0000000..89ebaee
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.inf
new file mode 100644
index 0000000..3f3a5c8
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ProjectInfoDxeDriver
+ FILE_GUID = 0A8D6360-7EF3-11EA-B20F-B3A524584400
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ProjectInfoDxe.depex|*
+ PE32|ProjectInfoDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.efi
new file mode 100644
index 0000000..c2b3a15
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.inf
new file mode 100644
index 0000000..502fec6
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = PwrUtilsDxe
+ FILE_GUID = 0401B830-BFF9-44A2-A5F6-95734A33C017
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|PwrUtilsDxe.depex|*
+ PE32|PwrUtilsDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomBds/QcomBds.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomBds/QcomBds.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomBds/QcomBds.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomBds/QcomBds.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomBds/QcomBds.efi
new file mode 100644
index 0000000..1881617
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomBds/QcomBds.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomBds/QcomBds.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomBds/QcomBds.inf
new file mode 100644
index 0000000..67d96f0
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomBds/QcomBds.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = QcomBds
+ FILE_GUID = 5A50AA81-C3AE-4608-A0E3-41A2E69BAF94
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|QcomBds.depex|*
+ PE32|QcomBds.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.efi
new file mode 100644
index 0000000..0030892
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.inf
new file mode 100644
index 0000000..a14b9c5
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = QcomChargerDxeLA
+ FILE_GUID = 4BCE7F36-428E-4393-99E3-7E0844404DBA
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|QcomChargerDxeLA.depex|*
+ PE32|QcomChargerDxeLA.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomWDogDxe/QcomWDogDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomWDogDxe/QcomWDogDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomWDogDxe/QcomWDogDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomWDogDxe/QcomWDogDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomWDogDxe/QcomWDogDxe.efi
new file mode 100644
index 0000000..1d35fea
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomWDogDxe/QcomWDogDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomWDogDxe/QcomWDogDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomWDogDxe/QcomWDogDxe.inf
new file mode 100644
index 0000000..043ae0a
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/QcomWDogDxe/QcomWDogDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = QcomWDogDxe
+ FILE_GUID = 040E1E61-0AFB-411B-9EC9-00F3FC59CC13
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|QcomWDogDxe.depex|*
+ PE32|QcomWDogDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/RNGDxe/RngDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RNGDxe/RngDxe.efi
new file mode 100644
index 0000000..01e984a
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RNGDxe/RngDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/RNGDxe/RngDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RNGDxe/RngDxe.inf
new file mode 100644
index 0000000..902e0ad
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RNGDxe/RngDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = RngDxe
+ FILE_GUID = B0D3689E-11F8-43C6-8ECE-023A29CEC35B
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|RngDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ResetRuntimeDxe/ResetRuntimeDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ResetRuntimeDxe/ResetRuntimeDxe.depex
new file mode 100644
index 0000000..1d4d28f
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ResetRuntimeDxe/ResetRuntimeDxe.depex
@@ -0,0 +1 @@
+k0_�}��J�}�/��0
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ResetRuntimeDxe/ResetRuntimeDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ResetRuntimeDxe/ResetRuntimeDxe.efi
new file mode 100644
index 0000000..0d7f308
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ResetRuntimeDxe/ResetRuntimeDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ResetRuntimeDxe/ResetRuntimeDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ResetRuntimeDxe/ResetRuntimeDxe.inf
new file mode 100644
index 0000000..6fc299e
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ResetRuntimeDxe/ResetRuntimeDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ResetRuntimeDxe
+ FILE_GUID = 3AE17DB7-3CC5-4B89-9304-9549211057EF
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ResetRuntimeDxe.depex|*
+ PE32|ResetRuntimeDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.depex
new file mode 100644
index 0000000..d24065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.efi
new file mode 100644
index 0000000..2f7c43c
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.inf
new file mode 100644
index 0000000..b823144
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = RpmhDxe
+ FILE_GUID = CB29F4D1-7F37-4692-A416-93E82E219766
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|RpmhDxe.depex|*
+ PE32|RpmhDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.depex
new file mode 100644
index 0000000..11fe8cc
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.depex differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.efi
new file mode 100644
index 0000000..3c6d09e
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.inf
new file mode 100644
index 0000000..5bacc3c
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = SPI
+ FILE_GUID = 7A32BD23-F735-4F57-AA1A-447D2FE3BE0D
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|SPIDxe.depex|*
+ PE32|SPIDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.efi
new file mode 100644
index 0000000..861845a
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.inf
new file mode 100644
index 0000000..c6a1513
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = SPMI
+ FILE_GUID = 2A7B4BEF-80CD-49E1-B473-374BA4D673FC
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|SPMIDxe.depex|*
+ PE32|SPMIDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.depex
new file mode 100644
index 0000000..265ee7c
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.depex differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.efi
new file mode 100644
index 0000000..8a593ab
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.inf
new file mode 100644
index 0000000..51934f0
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = SdccDxe
+ FILE_GUID = F10F76DB-42C1-533F-34A8-69BE24653110
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|SdccDxe.depex|*
+ PE32|SdccDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SecRSADxe/SecRSADxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SecRSADxe/SecRSADxe.efi
new file mode 100644
index 0000000..9d840c2
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SecRSADxe/SecRSADxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SecRSADxe/SecRSADxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SecRSADxe/SecRSADxe.inf
new file mode 100644
index 0000000..e5452aa
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SecRSADxe/SecRSADxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = SecRSADxe
+ FILE_GUID = 32C71E68-83A8-46ED-AED1-094E71B12057
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|SecRSADxe.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SerialPortDxe/SerialPortDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SerialPortDxe/SerialPortDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SerialPortDxe/SerialPortDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SerialPortDxe/SerialPortDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SerialPortDxe/SerialPortDxe.efi
new file mode 100644
index 0000000..b2f4e1e
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SerialPortDxe/SerialPortDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SerialPortDxe/SerialPortDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SerialPortDxe/SerialPortDxe.inf
new file mode 100644
index 0000000..426a36b
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SerialPortDxe/SerialPortDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = SerialPortDxe
+ FILE_GUID = 84CC57F6-38BE-4ACF-9752-73D1E23F793F
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|SerialPortDxe.depex|*
+ PE32|SerialPortDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.efi
new file mode 100644
index 0000000..c534cc1
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.inf
new file mode 100644
index 0000000..b7f4634
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ShmBridgeDxeLA
+ FILE_GUID = 8430C46D-AB1C-4F82-896B-33E156931FB3
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ShmBridgeDxeLA.depex|*
+ PE32|ShmBridgeDxeLA.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SimpleTextInOutSerialDxe/SimpleTextInOutSerial.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SimpleTextInOutSerialDxe/SimpleTextInOutSerial.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SimpleTextInOutSerialDxe/SimpleTextInOutSerial.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SimpleTextInOutSerialDxe/SimpleTextInOutSerial.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SimpleTextInOutSerialDxe/SimpleTextInOutSerial.efi
new file mode 100644
index 0000000..49003f0
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SimpleTextInOutSerialDxe/SimpleTextInOutSerial.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SimpleTextInOutSerialDxe/SimpleTextInOutSerial.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SimpleTextInOutSerialDxe/SimpleTextInOutSerial.inf
new file mode 100644
index 0000000..dff052b
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SimpleTextInOutSerialDxe/SimpleTextInOutSerial.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = SimpleTextInOutSerial
+ FILE_GUID = 857A8741-0EEC-43BD-9482-27D14ED47D72
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|SimpleTextInOutSerial.depex|*
+ PE32|SimpleTextInOutSerial.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.efi
new file mode 100644
index 0000000..fb1a9a0
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.inf
new file mode 100644
index 0000000..56d294d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = SmemDxe
+ FILE_GUID = F541D663-4A48-40AA-AABF-FF158CCAE34C
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|SmemDxe.depex|*
+ PE32|SmemDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.depex
new file mode 100644
index 0000000..d24065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.efi
new file mode 100644
index 0000000..c3968b9
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.inf
new file mode 100644
index 0000000..0eace14
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = DALTLMM
+ FILE_GUID = 8681CC5A-0DF6-441E-B4B8-E915C538F067
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|TLMMDxe.depex|*
+ PE32|TLMMDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.depex
new file mode 100644
index 0000000..d24065d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.efi
new file mode 100644
index 0000000..371a895
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.inf
new file mode 100644
index 0000000..3de2958
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = TsensDxe
+ FILE_GUID = F09AD92E-485C-9CDB-3E05-3385C38F94CC
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|TsensDxe.depex|*
+ PE32|TsensDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/ScmDxeLA.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/ScmDxeLA.efi
new file mode 100644
index 0000000..4a1a407
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/ScmDxeLA.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/ScmDxeLA.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/ScmDxeLA.inf
new file mode 100644
index 0000000..65399b7
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/ScmDxeLA.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ScmDxeLA
+ FILE_GUID = 4B4973EE-401B-4F36-A6A9-533DFCCDFC33
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|ScmDxeLA.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.efi
new file mode 100644
index 0000000..d910c9a
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.inf
new file mode 100644
index 0000000..e7bcea6
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = TzDxeLA
+ FILE_GUID = CF6DFC66-14AB-4E13-84DB-9C02912D1404
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|TzDxeLA.patched.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.patched.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.patched.efi
new file mode 100644
index 0000000..cdf62b7
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.patched.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UCDxe/UCDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UCDxe/UCDxe.efi
new file mode 100644
index 0000000..1cff566
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UCDxe/UCDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UCDxe/UCDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UCDxe/UCDxe.inf
new file mode 100644
index 0000000..0a070be
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UCDxe/UCDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UCDxe
+ FILE_GUID = 5F0937CD-73F9-445E-B320-BB6FD5D3CBDE
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|UCDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.depex
new file mode 100644
index 0000000..098cfdc
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.depex
@@ -0,0 +1 @@
+����9��G��f�v28
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.efi
new file mode 100644
index 0000000..95af578
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.inf
new file mode 100644
index 0000000..65d28c8
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UFSDxe
+ FILE_GUID = 0D35CD8E-97EA-4F9A-96AF-0F0D89F76567
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|UFSDxe.depex|*
+ PE32|UFSDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.efi
new file mode 100644
index 0000000..ca96a49
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.inf
new file mode 100644
index 0000000..065368b
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = ULogDxe
+ FILE_GUID = E43128A8-8692-42B6-8AFA-676158578D18
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|ULogDxe.depex|*
+ PE32|ULogDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbBusDxe/UsbBusDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbBusDxe/UsbBusDxe.efi
new file mode 100644
index 0000000..9718abb
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbBusDxe/UsbBusDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbBusDxe/UsbBusDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbBusDxe/UsbBusDxe.inf
new file mode 100644
index 0000000..6053ba5
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbBusDxe/UsbBusDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UsbBusDxe
+ FILE_GUID = 240612B7-A063-11D4-9A3A-0090273FC14D
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|UsbBusDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.depex
new file mode 100644
index 0000000..8f72e31
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.depex
@@ -0,0 +1 @@
+iv� �zH��(�{E������9��G��f�v28E\z�!�C�|�/�_�������I�K����
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.efi
new file mode 100644
index 0000000..6cbbdfb
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.inf
new file mode 100644
index 0000000..f623ee0
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UsbConfigDxe
+ FILE_GUID = CD823A4D-7DEC-4531-AE5D-4134FA4127B8
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|UsbConfigDxe.depex|*
+ PE32|UsbConfigDxe.patched.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.patched.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.patched.efi
new file mode 100644
index 0000000..a1c5108
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.patched.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.depex
new file mode 100644
index 0000000..098cfdc
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.depex
@@ -0,0 +1 @@
+����9��G��f�v28
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.efi
new file mode 100644
index 0000000..9b362db
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.inf
new file mode 100644
index 0000000..9bdbe13
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UsbDeviceDxe
+ FILE_GUID = 3299A266-15F0-4346-8318-716336736D3E
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|UsbDeviceDxe.depex|*
+ PE32|UsbDeviceDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.depex
new file mode 100644
index 0000000..2faa00f
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.depex
@@ -0,0 +1 @@
+?�"�P��B��[��7
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.efi
new file mode 100644
index 0000000..0f3a5e9
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.inf
new file mode 100644
index 0000000..9e6ddde
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UsbInitDxe
+ FILE_GUID = 0A134F0E-075E-40B3-9C63-3B3906804663
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|UsbInitDxe.depex|*
+ PE32|UsbInitDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbKbDxe/UsbKbDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbKbDxe/UsbKbDxe.efi
new file mode 100644
index 0000000..87b4a40
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbKbDxe/UsbKbDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbKbDxe/UsbKbDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbKbDxe/UsbKbDxe.inf
new file mode 100644
index 0000000..0253559
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbKbDxe/UsbKbDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UsbKbDxe
+ FILE_GUID = 2D2E62CF-9ECF-43B7-8219-94E7FC713DFE
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|UsbKbDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMassStorageDxe/UsbMassStorageDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMassStorageDxe/UsbMassStorageDxe.efi
new file mode 100644
index 0000000..ad5ea67
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMassStorageDxe/UsbMassStorageDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMassStorageDxe/UsbMassStorageDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMassStorageDxe/UsbMassStorageDxe.inf
new file mode 100644
index 0000000..ab3b4b6
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMassStorageDxe/UsbMassStorageDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UsbMassStorageDxe
+ FILE_GUID = 9FB4B4A7-42C0-4BCD-8540-9BCC6711F83E
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|UsbMassStorageDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.efi
new file mode 100644
index 0000000..388c637
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.inf
new file mode 100644
index 0000000..29b2eba
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UsbMsdDxe
+ FILE_GUID = 5AF77F10-90DF-4E7E-8325-A17EC09D5443
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|UsbMsdDxe.depex|*
+ PE32|UsbMsdDxe.patched.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.patched.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.patched.efi
new file mode 100644
index 0000000..33c5535
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.patched.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.efi
new file mode 100644
index 0000000..198f0b4
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.inf
new file mode 100644
index 0000000..8e4f06e
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UsbPwrCtrlDxe
+ FILE_GUID = 11FAED4C-B21F-4D88-8E48-C4C28A1E50DF
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|UsbPwrCtrlDxe.depex|*
+ PE32|UsbPwrCtrlDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.depex
new file mode 100644
index 0000000..a743e84
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.depex differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.efi
new file mode 100644
index 0000000..555c014
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.inf
new file mode 100644
index 0000000..1687ffc
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = UsbfnDwc3Dxe
+ FILE_GUID = 94F8A6A7-DC34-4101-88C1-99179CCEAE83
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|UsbfnDwc3Dxe.depex|*
+ PE32|UsbfnDwc3Dxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/VariableDxe/VariableDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VariableDxe/VariableDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VariableDxe/VariableDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/VariableDxe/VariableDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VariableDxe/VariableDxe.efi
new file mode 100644
index 0000000..8eaa627
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VariableDxe/VariableDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/VariableDxe/VariableDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VariableDxe/VariableDxe.inf
new file mode 100644
index 0000000..001e9ff
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VariableDxe/VariableDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = VariableDxe
+ FILE_GUID = 2B0ECDCE-01AE-446E-9FFD-C4217DE0340F
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|VariableDxe.depex|*
+ PE32|VariableDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.depex
new file mode 100644
index 0000000..14cd96a
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.depex
@@ -0,0 +1 @@
+B�7�E�L���f��G�iv� �zH��(�{E��
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.efi
new file mode 100644
index 0000000..1d6b66c
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.inf
new file mode 100644
index 0000000..f9dcc23
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = VcsDxe
+ FILE_GUID = 8BD3B475-401A-4B0B-9315-EDEE61A1EAE5
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|VcsDxe.depex|*
+ PE32|VcsDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/VerifiedBootDxe/VerifiedBootDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VerifiedBootDxe/VerifiedBootDxe.depex
new file mode 100644
index 0000000..2a47cc2
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VerifiedBootDxe/VerifiedBootDxe.depex
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/VerifiedBootDxe/VerifiedBootDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VerifiedBootDxe/VerifiedBootDxe.efi
new file mode 100644
index 0000000..93bc827
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VerifiedBootDxe/VerifiedBootDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/VerifiedBootDxe/VerifiedBootDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VerifiedBootDxe/VerifiedBootDxe.inf
new file mode 100644
index 0000000..4ebb5ef
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/VerifiedBootDxe/VerifiedBootDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = VerifiedBootDxe
+ FILE_GUID = A25F5839-4D55-428F-8F0B-5CE1D565F53E
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|VerifiedBootDxe.depex|*
+ PE32|VerifiedBootDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciDxe/XhciDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciDxe/XhciDxe.efi
new file mode 100644
index 0000000..4f32846
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciDxe/XhciDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciDxe/XhciDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciDxe/XhciDxe.inf
new file mode 100644
index 0000000..98c5123
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciDxe/XhciDxe.inf
@@ -0,0 +1,9 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = XhciDxe
+ FILE_GUID = B7F50E91-A759-412C-ADE4-DCD03E7F7C28
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ PE32|XhciDxe.efi|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.depex b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.depex
new file mode 100644
index 0000000..4b367c2
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.depex differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.efi b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.efi
new file mode 100644
index 0000000..e45895b
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.efi differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.inf b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.inf
new file mode 100644
index 0000000..c8b4e7f
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = XhciPciEmulation
+ FILE_GUID = BEB12BEE-F6E1-11E1-9FB8-6C626DE4AEB1
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = EfiEntry
+
+[Binaries.AARCH64]
+ DXE_DEPEX|XhciPciEmulationDxe.depex|*
+ PE32|XhciPciEmulationDxe.efi|*
+
+[Depex]
+ TRUE
diff --git a/uefi/files/Binaries/redwood/QcomPkg/XBLCore/XBLCore.inf b/uefi/files/Binaries/redwood/QcomPkg/XBLCore/XBLCore.inf
new file mode 100644
index 0000000..4b5f8f4
--- /dev/null
+++ b/uefi/files/Binaries/redwood/QcomPkg/XBLCore/XBLCore.inf
@@ -0,0 +1,10 @@
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = XBLCore
+ FILE_GUID = 8AF09F13-44C5-96EC-1437-DD899CB5EE5D
+ MODULE_TYPE = SEC
+ VERSION_STRING = 1.0
+
+[Binaries.AARCH64]
+ RAW|XBLCore.raw|*
+ TE|XBLCore.te|*
diff --git a/uefi/files/Binaries/redwood/QcomPkg/XBLCore/XBLCore.raw b/uefi/files/Binaries/redwood/QcomPkg/XBLCore/XBLCore.raw
new file mode 100644
index 0000000..a44bcb1
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/XBLCore/XBLCore.raw differ
diff --git a/uefi/files/Binaries/redwood/QcomPkg/XBLCore/XBLCore.te b/uefi/files/Binaries/redwood/QcomPkg/XBLCore/XBLCore.te
new file mode 100644
index 0000000..cbd49db
Binary files /dev/null and b/uefi/files/Binaries/redwood/QcomPkg/XBLCore/XBLCore.te differ
diff --git a/uefi/files/Binaries/redwood/README.md b/uefi/files/Binaries/redwood/README.md
new file mode 100644
index 0000000..15a8cbe
--- /dev/null
+++ b/uefi/files/Binaries/redwood/README.md
@@ -0,0 +1,37 @@
+## Firmware Infos
+
+- **Device:** POCO X5 Pro 5G (redwood)
+- **Region:** Global
+- **Version:** `OS1.0.3.0.UMSMIXM` / `BOOT.MXF.1.0-00852-LAHAINA-2.12801.8`
+
+## Patches/Fixes
+
+### ButtonsDxe:
+
+- **Reason:** To make the Power Button usable in UEFI.
+- **Patch:** The Special Qcom Key Code (`0x102`) has been Changed to the Key Code Enter (`0xD`).
+- **Patch Creator:** [Gustave Monce](https://github.com/gus33000)
+
+### DALSYSDxe:
+
+- **Reason:** To avoid Mismatched Cached Copies.
+- **Patch:** Enabled Cache Coherence for UFS.
+- **Patch Creator:** [Gustave Monce](https://github.com/gus33000)
+
+### TzDxeLA:
+
+- **Reason:** To make UEFI not Crash during UEFI Boot.
+- **Patch:** The Global TZ Applet Variable has been Changed to `TRUE` from `FALSE`.
+- **Patch Creator:** [N1kroks](https://github.com/N1kroks/)
+
+### UsbConfigDxe:
+
+- **Reason:** To make USB work in the OS.
+- **Patch:** The USB Deinit Code has been Removed from Exit Boot Services Event to allow the OS to continue using the USB Port.
+- **Patch Creator:** [Gustave Monce](https://github.com/gus33000)
+
+### UsbMsdDxe:
+
+- **Reason:** To make the Internal Storage be recognised as Hard Drives instead of USB Drives in Mass Storage.
+- **Patch:** Changed Removable State to Non-Removable.
+- **Patch Creator:** [N1kroks](https://github.com/N1kroks)
diff --git a/uefi/files/Binaries/redwood/RawFiles/BATTERY.PROVISION b/uefi/files/Binaries/redwood/RawFiles/BATTERY.PROVISION
new file mode 100644
index 0000000..0fa28ea
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/BATTERY.PROVISION
@@ -0,0 +1,1751 @@
+[BATTERY_PROFILE]
+GUI Version: PM855GUI - 1.0.0.10
+Checksum,1538
+#9/28/2018 11:09:21 AM
+
+#Alium_860_89032_0000_3600mAh_averaged_MasterSlave_Sept24th2018
+Float_Voltage,4350
+Profile_Revision,24
+Nom_Batt_capacity,3600
+Batt_id,107000
+Therm_B,4250
+Thermistor_Value,100000
+Battery_name,Alium_860_89032_0000_3600mAh_averaged_MasterSlave_Sept24th2018
+Therm_c0_Coefficients,0x2318
+Therm_c1_Coefficients,0xD0C
+Therm_c2_Coefficients,0xDAF7
+Therm_c3_Coefficients,0xC556
+Therm_c4_Coefficients,0x848D
+Therm_Center_Offset,0x70
+Therm_Pullup,100
+Rslow_Normal_Coefficients, 0x1A7702DF
+Rslow_Low_Coefficients, 0x13D00451
+Address, Address2, Offset, Data
+041, 041, 0, 09
+041, 041, 1, 00
+042, 042, 0, C7
+042, 042, 1, EA
+043, 043, 0, C4
+043, 043, 1, DC
+044, 044, 0, 8E
+044, 044, 1, E2
+045, 045, 0, 3A
+045, 045, 1, DD
+046, 046, 0, 00
+046, 046, 1, 00
+047, 047, 0, 15
+047, 047, 1, BC
+048, 048, 0, A5
+048, 048, 1, 8A
+049, 049, 0, 02
+049, 049, 1, 80
+04A, 04A, 0, D1
+04A, 04A, 1, 92
+04B, 04B, 0, AB
+04B, 04B, 1, 9D
+04C, 04C, 0, 47
+04C, 04C, 1, 80
+04D, 04D, 0, 10
+04D, 04D, 1, 00
+04E, 04E, 0, DF
+04E, 04E, 1, 02
+04F, 04F, 0, 77
+04F, 04F, 1, 1A
+050, 050, 0, 85
+050, 050, 1, EC
+051, 051, 0, E1
+051, 051, 1, FD
+052, 052, 0, CE
+052, 052, 1, 07
+053, 053, 0, 32
+053, 053, 1, 00
+054, 054, 0, 75
+054, 054, 1, EB
+055, 055, 0, AA
+055, 055, 1, ED
+056, 056, 0, F3
+056, 056, 1, CD
+057, 057, 0, 0C
+057, 057, 1, 0A
+058, 058, 0, 7A
+058, 058, 1, E4
+059, 059, 0, ED
+059, 059, 1, C5
+05A, 05A, 0, 40
+05A, 05A, 1, 1B
+05B, 05B, 0, D0
+05B, 05B, 1, 02
+05C, 05C, 0, 1F
+05C, 05C, 1, CA
+05D, 05D, 0, FF
+05D, 05D, 1, 00
+05E, 05E, 0, 52
+05E, 05E, 1, 00
+05F, 05F, 0, 4D
+05F, 05F, 1, 00
+060, 060, 0, 4A
+060, 060, 1, 00
+061, 061, 0, 3C
+061, 061, 1, 00
+062, 062, 0, 35
+062, 062, 1, 00
+063, 063, 0, 38
+063, 063, 1, 00
+064, 064, 0, 39
+064, 064, 1, 00
+065, 065, 0, 48
+065, 065, 1, 00
+066, 066, 0, 43
+066, 066, 1, 00
+067, 067, 0, 3F
+067, 067, 1, 00
+068, 068, 0, FF
+068, 068, 1, 00
+069, 069, 0, 38
+069, 069, 1, 00
+06A, 06A, 0, 40
+06A, 06A, 1, 00
+06B, 06B, 0, 46
+06B, 06B, 1, 00
+06C, 06C, 0, 50
+06C, 06C, 1, 00
+06D, 06D, 0, 45
+06D, 06D, 1, 00
+06E, 06E, 0, 5C
+06E, 06E, 1, 00
+06F, 06F, 0, 7E
+06F, 06F, 1, 64
+070, 070, 0, 60
+070, 070, 1, 00
+071, 071, 0, 50
+071, 071, 1, 08
+072, 072, 0, 50
+072, 072, 1, 10
+073, 073, 0, FF
+073, 073, 1, 00
+074, 074, 0, 6A
+074, 074, 1, 00
+075, 075, 0, 5F
+075, 075, 1, 00
+076, 076, 0, 63
+076, 076, 1, 00
+077, 077, 0, 6E
+077, 077, 1, 00
+078, 078, 0, 60
+078, 078, 1, 00
+079, 079, 0, 7D
+079, 079, 1, 20
+07A, 07A, 0, 96
+07A, 07A, 1, 40
+07B, 07B, 0, 75
+07B, 07B, 1, 50
+07C, 07C, 0, 6B
+07C, 07C, 1, 13
+07D, 07D, 0, 63
+07D, 07D, 1, 00
+07E, 07E, 0, D8
+07E, 07E, 1, 00
+07F, 07F, 0, 14
+07F, 07F, 1, 22
+080, 080, 0, 7E
+080, 080, 1, 0D
+081, 081, 0, 21
+081, 081, 1, 02
+082, 082, 0, AA
+082, 082, 1, 04
+083, 083, 0, ED
+083, 083, 1, 1C
+084, 084, 0, D4
+084, 084, 1, 09
+085, 085, 0, 64
+085, 085, 1, 0C
+086, 086, 0, D3
+086, 086, 1, 23
+087, 087, 0, A4
+087, 087, 1, 18
+088, 088, 0, D3
+088, 088, 1, 42
+089, 089, 0, B5
+089, 089, 1, 55
+08A, 08A, 0, 91
+08A, 08A, 1, 02
+08B, 08B, 0, 90
+08B, 08B, 1, 12
+08C, 08C, 0, 2A
+08C, 08C, 1, 1F
+08D, 08D, 0, 02
+08D, 08D, 1, 06
+08E, 08E, 0, 1F
+08E, 08E, 1, 0A
+08F, 08F, 0, A3
+08F, 08F, 1, 06
+090, 090, 0, AE
+090, 090, 1, 1C
+091, 091, 0, 8D
+091, 091, 1, 02
+092, 092, 0, 96
+092, 092, 1, 04
+093, 093, 0, D2
+093, 093, 1, 03
+094, 094, 0, D1
+094, 094, 1, 17
+095, 095, 0, 51
+095, 095, 1, 23
+096, 096, 0, 3F
+096, 096, 1, 45
+097, 097, 0, 28
+097, 097, 1, 53
+098, 098, 0, 69
+098, 098, 1, 14
+099, 099, 0, 93
+099, 099, 1, 20
+09A, 09A, 0, 8E
+09A, 09A, 1, EC
+09B, 09B, 0, 18
+09B, 09B, 1, CB
+09C, 09C, 0, C8
+09C, 09C, 1, C5
+09D, 09D, 0, DB
+09D, 09D, 1, 1C
+09E, 09E, 0, 7B
+09E, 09E, 1, C9
+09F, 09F, 0, 7C
+09F, 09F, 1, 05
+0A0, 0A0, 0, E6
+0A0, 0A0, 1, C2
+0A1, 0A1, 0, B9
+0A1, 0A1, 1, 17
+0A2, 0A2, 0, 2C
+0A2, 0A2, 1, 93
+0A3, 0A3, 0, 87
+0A3, 0A3, 1, 85
+0A4, 0A4, 0, A2
+0A4, 0A4, 1, 92
+0A5, 0A5, 0, 91
+0A5, 0A5, 1, A8
+0A6, 0A6, 0, 09
+0A6, 0A6, 1, 80
+0A7, 0A7, 0, 92
+0A7, 0A7, 1, F2
+0A8, 0A8, 0, 1A
+0A8, 0A8, 1, 0D
+0A9, 0A9, 0, F4
+0A9, 0A9, 1, FC
+0AA, 0AA, 0, 5E
+0AA, 0AA, 1, EB
+0AB, 0AB, 0, 00
+0AB, 0AB, 1, F8
+0AC, 0AC, 0, FB
+0AC, 0AC, 1, ED
+0AD, 0AD, 0, 15
+0AD, 0AD, 1, E2
+0AE, 0AE, 0, F6
+0AE, 0AE, 1, 0F
+0AF, 0AF, 0, 75
+0AF, 0AF, 1, 02
+0B0, 0B0, 0, 72
+0B0, 0B0, 1, 05
+0B1, 0B1, 0, 49
+0B1, 0B1, 1, 01
+0B2, 0B2, 0, 10
+0B2, 0B2, 1, 00
+0B3, 0B3, 0, FA
+0B3, 0B3, 1, E5
+0B4, 0B4, 0, E2
+0B4, 0B4, 1, 03
+0B5, 0B5, 0, 8D
+0B5, 0B5, 1, 05
+0B6, 0B6, 0, 85
+0B6, 0B6, 1, 02
+0B7, 0B7, 0, CE
+0B7, 0B7, 1, 07
+0B8, 0B8, 0, 32
+0B8, 0B8, 1, 00
+0B9, 0B9, 0, 23
+0B9, 0B9, 1, 03
+0BA, 0BA, 0, 46
+0BA, 0BA, 1, 02
+0BB, 0BB, 0, 9C
+0BB, 0BB, 1, 04
+0BC, 0BC, 0, 03
+0BC, 0BC, 1, 02
+0BD, 0BD, 0, 48
+0BD, 0BD, 1, 07
+0BE, 0BE, 0, 0A
+0BE, 0BE, 1, 00
+0BF, 0BF, 0, BA
+0BF, 0BF, 1, 03
+0C0, 0C0, 0, 97
+0C0, 0C0, 1, 02
+0C1, 0C1, 0, 65
+0C1, 0C1, 1, 05
+0C2, 0C2, 0, 50
+0C2, 0C2, 1, 00
+0C3, 0C3, 0, 3A
+0C3, 0C3, 1, 00
+0C4, 0C4, 0, 41
+0C4, 0C4, 1, 00
+0C5, 0C5, 0, 43
+0C5, 0C5, 1, 64
+0C6, 0C6, 0, 45
+0C6, 0C6, 1, 00
+0C7, 0C7, 0, 45
+0C7, 0C7, 1, 10
+0C8, 0C8, 0, 45
+0C8, 0C8, 1, 18
+0C9, 0C9, 0, 46
+0C9, 0C9, 1, 08
+0CA, 0CA, 0, 44
+0CA, 0CA, 1, 00
+0CB, 0CB, 0, 47
+0CB, 0CB, 1, 00
+0CC, 0CC, 0, 3A
+0CC, 0CC, 1, 08
+0CD, 0CD, 0, 4B
+0CD, 0CD, 1, 08
+0CE, 0CE, 0, 37
+0CE, 0CE, 1, 00
+0CF, 0CF, 0, 47
+0CF, 0CF, 1, 20
+0D0, 0D0, 0, 4E
+0D0, 0D0, 1, 40
+0D1, 0D1, 0, 54
+0D1, 0D1, 1, 58
+0D2, 0D2, 0, 60
+0D2, 0D2, 1, 10
+0D3, 0D3, 0, 57
+0D3, 0D3, 1, 00
+0D4, 0D4, 0, 5F
+0D4, 0D4, 1, 00
+0D5, 0D5, 0, 57
+0D5, 0D5, 1, 08
+0D6, 0D6, 0, 55
+0D6, 0D6, 1, 00
+0D7, 0D7, 0, 4B
+0D7, 0D7, 1, 00
+0D8, 0D8, 0, 50
+0D8, 0D8, 1, 00
+0D9, 0D9, 0, 3E
+0D9, 0D9, 1, 08
+0DA, 0DA, 0, 52
+0DA, 0DA, 1, 08
+0DB, 0DB, 0, 52
+0DB, 0DB, 1, 00
+0DC, 0DC, 0, 5C
+0DC, 0DC, 1, 20
+0DD, 0DD, 0, 6F
+0DD, 0DD, 1, 40
+0DE, 0DE, 0, 7D
+0DE, 0DE, 1, 58
+0DF, 0DF, 0, 67
+0DF, 0DF, 1, 10
+0E0, 0E0, 0, 63
+0E0, 0E0, 1, 00
+0E1, 0E1, 0, 69
+0E1, 0E1, 1, 08
+0E2, 0E2, 0, 4F
+0E2, 0E2, 1, 10
+0E3, 0E3, 0, D8
+0E3, 0E3, 1, 00
+0E4, 0E4, 0, 8C
+0E4, 0E4, 1, 2A
+0E5, 0E5, 0, DB
+0E5, 0E5, 1, 04
+0E6, 0E6, 0, 28
+0E6, 0E6, 1, 02
+0E7, 0E7, 0, AD
+0E7, 0E7, 1, 04
+0E8, 0E8, 0, 0B
+0E8, 0E8, 1, 1D
+0E9, 0E9, 0, 50
+0E9, 0E9, 1, 22
+0EA, 0EA, 0, A7
+0EA, 0EA, 1, 45
+0EB, 0EB, 0, 0D
+0EB, 0EB, 1, 52
+0EC, 0EC, 0, A2
+0EC, 0EC, 1, 18
+0ED, 0ED, 0, 74
+0ED, 0ED, 1, 03
+0EE, 0EE, 0, AD
+0EE, 0EE, 1, 04
+0EF, 0EF, 0, 35
+0EF, 0EF, 1, 02
+0F0, 0F0, 0, AE
+0F0, 0F0, 1, 13
+0F1, 0F1, 0, 3F
+0F1, 0F1, 1, 0A
+0F2, 0F2, 0, 5A
+0F2, 0F2, 1, 20
+0F3, 0F3, 0, DD
+0F3, 0F3, 1, 04
+0F4, 0F4, 0, F1
+0F4, 0F4, 1, 02
+0F5, 0F5, 0, D8
+0F5, 0F5, 1, 05
+0F6, 0F6, 0, C7
+0F6, 0F6, 1, 1C
+0F7, 0F7, 0, DD
+0F7, 0F7, 1, 02
+0F8, 0F8, 0, 3D
+0F8, 0F8, 1, 04
+0F9, 0F9, 0, EB
+0F9, 0F9, 1, 03
+0FA, 0FA, 0, 97
+0FA, 0FA, 1, 18
+0FB, 0FB, 0, 52
+0FB, 0FB, 1, 03
+0FC, 0FC, 0, D5
+0FC, 0FC, 1, 04
+0FD, 0FD, 0, 19
+0FD, 0FD, 1, 02
+0FE, 0FE, 0, 72
+0FE, 0FE, 1, 00
+0FF, 0FF, 0, 14
+0FF, 0FF, 1, 22
+100, 100, 0, 7E
+100, 100, 1, 05
+101, 101, 0, 21
+101, 101, 1, 02
+102, 102, 0, AA
+102, 102, 1, 04
+103, 103, 0, ED
+103, 103, 1, 1C
+104, 104, 0, D4
+104, 104, 1, 01
+105, 105, 0, 64
+105, 105, 1, 04
+106, 106, 0, D3
+106, 106, 1, 03
+107, 107, 0, A4
+107, 107, 1, 18
+108, 108, 0, D3
+108, 108, 1, 02
+109, 109, 0, B5
+109, 109, 1, 05
+10A, 10A, 0, 91
+10A, 10A, 1, 02
+10B, 10B, 0, 90
+10B, 10B, 1, 00
+10C, 10C, 0, 7C
+10C, 10C, 1, 01
+10D, 10D, 0, C0
+10D, 10D, 1, 00
+10E, 10E, 0, FA
+10E, 10E, 1, 00
+10F, 10F, 0, 04
+10F, 10F, 1, 0E
+
+[BATTERY_PROFILE]
+GUI Version: PM855GUI - 1.0.0.13
+Checksum,393C
+#1/22/2019 11:50:57 AM
+
+#QRD8250mcnair_3650mAh_averaged_MasterSlave_Jan21st2019
+Float_Voltage,4400
+Profile_Revision,24
+Nom_Batt_capacity,3650
+Batt_id,44200
+Therm_B,4250
+Thermistor_Value,100000
+Battery_name,QRD8250mcnair_3650mAh_averaged_MasterSlave_Jan21st2019
+Therm_c0_Coefficients,0x2318
+Therm_c1_Coefficients,0xD0C
+Therm_c2_Coefficients,0xDAF7
+Therm_c3_Coefficients,0xC556
+Therm_c4_Coefficients,0x848D
+Therm_Center_Offset,0x70
+Therm_Pullup,100
+Rslow_Normal_Coefficients, 0x0D8715A9
+Rslow_Low_Coefficients, 0xFC650CAE
+Address, Address2, Offset, Data
+041, 041, 0, 09
+041, 041, 1, 00
+042, 042, 0, 15
+042, 042, 1, EA
+043, 043, 0, CA
+043, 043, 1, DC
+044, 044, 0, 05
+044, 044, 1, E3
+045, 045, 0, 99
+045, 045, 1, DC
+046, 046, 0, 00
+046, 046, 1, 00
+047, 047, 0, A6
+047, 047, 1, BD
+048, 048, 0, 4F
+048, 048, 1, 8A
+049, 049, 0, F9
+049, 049, 1, 87
+04A, 04A, 0, 88
+04A, 04A, 1, 9D
+04B, 04B, 0, 79
+04B, 04B, 1, 9A
+04C, 04C, 0, E7
+04C, 04C, 1, 87
+04D, 04D, 0, 48
+04D, 04D, 1, 00
+04E, 04E, 0, A9
+04E, 04E, 1, 15
+04F, 04F, 0, 87
+04F, 04F, 1, 0D
+050, 050, 0, 7C
+050, 050, 1, 04
+051, 051, 0, 30
+051, 051, 1, 02
+052, 052, 0, CE
+052, 052, 1, 07
+053, 053, 0, 32
+053, 053, 1, 00
+054, 054, 0, BF
+054, 054, 1, EB
+055, 055, 0, 95
+055, 055, 1, ED
+056, 056, 0, 67
+056, 056, 1, D5
+057, 057, 0, 16
+057, 057, 1, 0A
+058, 058, 0, 1A
+058, 058, 1, EB
+059, 059, 0, 5C
+059, 059, 1, B2
+05A, 05A, 0, FE
+05A, 05A, 1, 0D
+05B, 05B, 0, A9
+05B, 05B, 1, 06
+05C, 05C, 0, 23
+05C, 05C, 1, BB
+05D, 05D, 0, 60
+05D, 05D, 1, 00
+05E, 05E, 0, 3E
+05E, 05E, 1, 00
+05F, 05F, 0, 3D
+05F, 05F, 1, 00
+060, 060, 0, 3E
+060, 060, 1, 00
+061, 061, 0, 38
+061, 061, 1, 00
+062, 062, 0, 32
+062, 062, 1, 00
+063, 063, 0, 33
+063, 063, 1, 00
+064, 064, 0, 38
+064, 064, 1, 00
+065, 065, 0, 40
+065, 065, 1, 00
+066, 066, 0, 4A
+066, 066, 1, 00
+067, 067, 0, 5A
+067, 067, 1, 00
+068, 068, 0, 60
+068, 068, 1, 00
+069, 069, 0, 51
+069, 069, 1, 00
+06A, 06A, 0, 41
+06A, 06A, 1, 00
+06B, 06B, 0, 36
+06B, 06B, 1, 00
+06C, 06C, 0, 31
+06C, 06C, 1, 00
+06D, 06D, 0, 2E
+06D, 06D, 1, 00
+06E, 06E, 0, 3C
+06E, 06E, 1, 00
+06F, 06F, 0, 45
+06F, 06F, 1, 64
+070, 070, 0, 43
+070, 070, 1, 00
+071, 071, 0, 47
+071, 071, 1, 00
+072, 072, 0, 40
+072, 072, 1, 00
+073, 073, 0, 60
+073, 073, 1, 00
+074, 074, 0, 54
+074, 074, 1, 00
+075, 075, 0, 45
+075, 075, 1, 00
+076, 076, 0, 50
+076, 076, 1, 08
+077, 077, 0, 53
+077, 077, 1, 08
+078, 078, 0, 3F
+078, 078, 1, 00
+079, 079, 0, 66
+079, 079, 1, 28
+07A, 07A, 0, 61
+07A, 07A, 1, 48
+07B, 07B, 0, 51
+07B, 07B, 1, 58
+07C, 07C, 0, 4A
+07C, 07C, 1, 0E
+07D, 07D, 0, 47
+07D, 07D, 1, 00
+07E, 07E, 0, D8
+07E, 07E, 1, 00
+07F, 07F, 0, F6
+07F, 07F, 1, 1F
+080, 080, 0, 7F
+080, 080, 1, 0D
+081, 081, 0, FA
+081, 081, 1, 03
+082, 082, 0, 53
+082, 082, 1, 07
+083, 083, 0, 73
+083, 083, 1, 1C
+084, 084, 0, DE
+084, 084, 1, 0A
+085, 085, 0, 82
+085, 085, 1, 0C
+086, 086, 0, 64
+086, 086, 1, 23
+087, 087, 0, 1A
+087, 087, 1, 17
+088, 088, 0, 4E
+088, 088, 1, 42
+089, 089, 0, 8C
+089, 089, 1, 55
+08A, 08A, 0, 99
+08A, 08A, 1, 03
+08B, 08B, 0, 7D
+08B, 08B, 1, 13
+08C, 08C, 0, 79
+08C, 08C, 1, 1F
+08D, 08D, 0, 98
+08D, 08D, 1, 05
+08E, 08E, 0, 91
+08E, 08E, 1, 0A
+08F, 08F, 0, 2B
+08F, 08F, 1, 06
+090, 090, 0, BE
+090, 090, 1, 1C
+091, 091, 0, 32
+091, 091, 1, 02
+092, 092, 0, 67
+092, 092, 1, 05
+093, 093, 0, F4
+093, 093, 1, 02
+094, 094, 0, F9
+094, 094, 1, 17
+095, 095, 0, 27
+095, 095, 1, 23
+096, 096, 0, 72
+096, 096, 1, 45
+097, 097, 0, DB
+097, 097, 1, 52
+098, 098, 0, 72
+098, 098, 1, 13
+099, 099, 0, FE
+099, 099, 1, 1F
+09A, 09A, 0, 14
+09A, 09A, 1, ED
+09B, 09B, 0, F1
+09B, 09B, 1, CA
+09C, 09C, 0, CA
+09C, 09C, 1, 85
+09D, 09D, 0, D3
+09D, 09D, 1, 1C
+09E, 09E, 0, 8C
+09E, 09E, 1, C1
+09F, 09F, 0, 78
+09F, 09F, 1, 05
+0A0, 0A0, 0, 11
+0A0, 0A0, 1, BB
+0A1, 0A1, 0, 4C
+0A1, 0A1, 1, 17
+0A2, 0A2, 0, 80
+0A2, 0A2, 1, 8B
+0A3, 0A3, 0, 33
+0A3, 0A3, 1, 85
+0A4, 0A4, 0, 0F
+0A4, 0A4, 1, 9B
+0A5, 0A5, 0, 88
+0A5, 0A5, 1, 80
+0A6, 0A6, 0, 09
+0A6, 0A6, 1, 80
+0A7, 0A7, 0, 01
+0A7, 0A7, 1, F2
+0A8, 0A8, 0, F2
+0A8, 0A8, 1, 05
+0A9, 0A9, 0, FE
+0A9, 0A9, 1, 03
+0AA, 0AA, 0, AC
+0AA, 0AA, 1, FB
+0AB, 0AB, 0, 00
+0AB, 0AB, 1, F8
+0AC, 0AC, 0, 51
+0AC, 0AC, 1, DD
+0AD, 0AD, 0, 44
+0AD, 0AD, 1, EB
+0AE, 0AE, 0, F4
+0AE, 0AE, 1, 07
+0AF, 0AF, 0, 89
+0AF, 0AF, 1, F5
+0B0, 0B0, 0, 8C
+0B0, 0B0, 1, CA
+0B1, 0B1, 0, 33
+0B1, 0B1, 1, 18
+0B2, 0B2, 0, 2A
+0B2, 0B2, 1, 00
+0B3, 0B3, 0, 11
+0B3, 0B3, 1, DD
+0B4, 0B4, 0, AB
+0B4, 0B4, 1, 01
+0B5, 0B5, 0, 86
+0B5, 0B5, 1, 05
+0B6, 0B6, 0, 2F
+0B6, 0B6, 1, 03
+0B7, 0B7, 0, CE
+0B7, 0B7, 1, 07
+0B8, 0B8, 0, 32
+0B8, 0B8, 1, 00
+0B9, 0B9, 0, 3D
+0B9, 0B9, 1, 03
+0BA, 0BA, 0, D9
+0BA, 0BA, 1, 03
+0BB, 0BB, 0, 45
+0BB, 0BB, 1, 05
+0BC, 0BC, 0, 01
+0BC, 0BC, 1, 07
+0BD, 0BD, 0, 23
+0BD, 0BD, 1, 02
+0BE, 0BE, 0, 17
+0BE, 0BE, 1, 05
+0BF, 0BF, 0, C8
+0BF, 0BF, 1, 03
+0C0, 0C0, 0, 9F
+0C0, 0C0, 1, 07
+0C1, 0C1, 0, 33
+0C1, 0C1, 1, 03
+0C2, 0C2, 0, 50
+0C2, 0C2, 1, 00
+0C3, 0C3, 0, 3F
+0C3, 0C3, 1, 00
+0C4, 0C4, 0, 3F
+0C4, 0C4, 1, 00
+0C5, 0C5, 0, 41
+0C5, 0C5, 1, 64
+0C6, 0C6, 0, 43
+0C6, 0C6, 1, 00
+0C7, 0C7, 0, 42
+0C7, 0C7, 1, F8
+0C8, 0C8, 0, 3F
+0C8, 0C8, 1, 00
+0C9, 0C9, 0, 45
+0C9, 0C9, 1, 00
+0CA, 0CA, 0, 44
+0CA, 0CA, 1, 00
+0CB, 0CB, 0, 42
+0CB, 0CB, 1, 00
+0CC, 0CC, 0, 3B
+0CC, 0CC, 1, 10
+0CD, 0CD, 0, 45
+0CD, 0CD, 1, 10
+0CE, 0CE, 0, 3D
+0CE, 0CE, 1, 00
+0CF, 0CF, 0, 44
+0CF, 0CF, 1, 20
+0D0, 0D0, 0, 43
+0D0, 0D0, 1, 40
+0D1, 0D1, 0, 45
+0D1, 0D1, 1, 58
+0D2, 0D2, 0, 4B
+0D2, 0D2, 1, 0F
+0D3, 0D3, 0, 39
+0D3, 0D3, 1, 00
+0D4, 0D4, 0, 3A
+0D4, 0D4, 1, 00
+0D5, 0D5, 0, 44
+0D5, 0D5, 1, 08
+0D6, 0D6, 0, 56
+0D6, 0D6, 1, 00
+0D7, 0D7, 0, 4B
+0D7, 0D7, 1, 00
+0D8, 0D8, 0, 3E
+0D8, 0D8, 1, 00
+0D9, 0D9, 0, 3A
+0D9, 0D9, 1, 10
+0DA, 0DA, 0, 48
+0DA, 0DA, 1, 10
+0DB, 0DB, 0, 45
+0DB, 0DB, 1, 00
+0DC, 0DC, 0, 4D
+0DC, 0DC, 1, 20
+0DD, 0DD, 0, 5F
+0DD, 0DD, 1, 40
+0DE, 0DE, 0, 40
+0DE, 0DE, 1, 58
+0DF, 0DF, 0, 42
+0DF, 0DF, 1, 10
+0E0, 0E0, 0, 4E
+0E0, 0E0, 1, 00
+0E1, 0E1, 0, 4B
+0E1, 0E1, 1, 08
+0E2, 0E2, 0, 2C
+0E2, 0E2, 1, 10
+0E3, 0E3, 0, D8
+0E3, 0E3, 1, 08
+0E4, 0E4, 0, B3
+0E4, 0E4, 1, 1F
+0E5, 0E5, 0, 41
+0E5, 0E5, 1, FC
+0E6, 0E6, 0, B9
+0E6, 0E6, 1, 03
+0E7, 0E7, 0, EF
+0E7, 0E7, 1, 06
+0E8, 0E8, 0, C5
+0E8, 0E8, 1, 1C
+0E9, 0E9, 0, 57
+0E9, 0E9, 1, 23
+0EA, 0EA, 0, D8
+0EA, 0EA, 1, 45
+0EB, 0EB, 0, 2D
+0EB, 0EB, 1, 52
+0EC, 0EC, 0, 7D
+0EC, 0EC, 1, 18
+0ED, 0ED, 0, 86
+0ED, 0ED, 1, 03
+0EE, 0EE, 0, 8C
+0EE, 0EE, 1, 04
+0EF, 0EF, 0, 5C
+0EF, 0EF, 1, 02
+0F0, 0F0, 0, 6C
+0F0, 0F0, 1, 12
+0F1, 0F1, 0, 3F
+0F1, 0F1, 1, 0A
+0F2, 0F2, 0, 68
+0F2, 0F2, 1, 20
+0F3, 0F3, 0, D1
+0F3, 0F3, 1, 04
+0F4, 0F4, 0, 1D
+0F4, 0F4, 1, 03
+0F5, 0F5, 0, A0
+0F5, 0F5, 1, 05
+0F6, 0F6, 0, B9
+0F6, 0F6, 1, 1C
+0F7, 0F7, 0, 1B
+0F7, 0F7, 1, 03
+0F8, 0F8, 0, FB
+0F8, 0F8, 1, 05
+0F9, 0F9, 0, 1F
+0F9, 0F9, 1, 02
+0FA, 0FA, 0, 94
+0FA, 0FA, 1, 18
+0FB, 0FB, 0, 4E
+0FB, 0FB, 1, 03
+0FC, 0FC, 0, DD
+0FC, 0FC, 1, 04
+0FD, 0FD, 0, 14
+0FD, 0FD, 1, 02
+0FE, 0FE, 0, 70
+0FE, 0FE, 1, 00
+0FF, 0FF, 0, 9D
+0FF, 0FF, 1, 23
+100, 100, 0, A2
+100, 100, 1, 04
+101, 101, 0, D6
+101, 101, 1, 02
+102, 102, 0, A4
+102, 102, 1, 05
+103, 103, 0, E6
+103, 103, 1, 1C
+104, 104, 0, D7
+104, 104, 1, 03
+105, 105, 0, 78
+105, 105, 1, 04
+106, 106, 0, CB
+106, 106, 1, 03
+107, 107, 0, 84
+107, 107, 1, 18
+108, 108, 0, F7
+108, 108, 1, 02
+109, 109, 0, 88
+109, 109, 1, 05
+10A, 10A, 0, D7
+10A, 10A, 1, 02
+10B, 10B, 0, 95
+10B, 10B, 1, 00
+10C, 10C, 0, 58
+10C, 10C, 1, 01
+10D, 10D, 0, C0
+10D, 10D, 1, 00
+10E, 10E, 0, FA
+10E, 10E, 1, 00
+10F, 10F, 0, 29
+10F, 10F, 1, 0E
+
+[BATTERY_PROFILE]
+GUI Version: PM855GUI - 1.0.0.13
+Checksum,C0ED
+#3/1/2019 11:53:15 AM
+
+#Ascent_wConn_3450mAh_Fresh_averaged_MasterSlave_Feb28th2019
+Float_Voltage,4350
+Profile_Revision,24
+Nom_Batt_capacity,3450
+Batt_id,60000
+Therm_B,3435
+Thermistor_Value,68000
+Battery_name,Ascent_wConn_3450mAh_Fresh_averaged_MasterSlave_Feb28th2019
+Therm_c0_Coefficients,0x2313
+Therm_c1_Coefficients,0xC42
+Therm_c2_Coefficients,0xEA62
+Therm_c3_Coefficients,0xCC3D
+Therm_c4_Coefficients,0x8313
+Therm_Center_Offset,0x5B
+Therm_Pullup,100
+Rslow_Normal_Coefficients, 0x1A7B0A43
+Rslow_Low_Coefficients, 0x221813D0
+Address, Address2, Offset, Data
+041, 041, 0, 09
+041, 041, 1, 00
+042, 042, 0, 63
+042, 042, 1, EA
+043, 043, 0, 65
+043, 043, 1, DD
+044, 044, 0, F5
+044, 044, 1, DB
+045, 045, 0, 02
+045, 045, 1, D4
+046, 046, 0, 00
+046, 046, 1, 00
+047, 047, 0, A5
+047, 047, 1, BD
+048, 048, 0, 62
+048, 048, 1, 8A
+049, 049, 0, FA
+049, 049, 1, 87
+04A, 04A, 0, 3A
+04A, 04A, 1, A4
+04B, 04B, 0, 16
+04B, 04B, 1, 9A
+04C, 04C, 0, D5
+04C, 04C, 1, 80
+04D, 04D, 0, 0E
+04D, 04D, 1, 00
+04E, 04E, 0, 43
+04E, 04E, 1, 0A
+04F, 04F, 0, 7B
+04F, 04F, 1, 1A
+050, 050, 0, 3B
+050, 050, 1, F4
+051, 051, 0, 4D
+051, 051, 1, F2
+052, 052, 0, CE
+052, 052, 1, 07
+053, 053, 0, 32
+053, 053, 1, 00
+054, 054, 0, 1F
+054, 054, 1, F3
+055, 055, 0, 18
+055, 055, 1, D4
+056, 056, 0, 81
+056, 056, 1, DA
+057, 057, 0, D4
+057, 057, 1, 02
+058, 058, 0, 0B
+058, 058, 1, E4
+059, 059, 0, F3
+059, 059, 1, C4
+05A, 05A, 0, F6
+05A, 05A, 1, 1B
+05B, 05B, 0, AB
+05B, 05B, 1, F3
+05C, 05C, 0, AF
+05C, 05C, 1, C4
+05D, 05D, 0, 60
+05D, 05D, 1, 00
+05E, 05E, 0, 4A
+05E, 05E, 1, 00
+05F, 05F, 0, 42
+05F, 05F, 1, 00
+060, 060, 0, 43
+060, 060, 1, 00
+061, 061, 0, 42
+061, 061, 1, 00
+062, 062, 0, 3A
+062, 062, 1, 00
+063, 063, 0, 3C
+063, 063, 1, 00
+064, 064, 0, 49
+064, 064, 1, 00
+065, 065, 0, 3D
+065, 065, 1, 00
+066, 066, 0, 39
+066, 066, 1, 00
+067, 067, 0, 3A
+067, 067, 1, 00
+068, 068, 0, 60
+068, 068, 1, 00
+069, 069, 0, 26
+069, 069, 1, 00
+06A, 06A, 0, 24
+06A, 06A, 1, 00
+06B, 06B, 0, 33
+06B, 06B, 1, 00
+06C, 06C, 0, 3D
+06C, 06C, 1, 00
+06D, 06D, 0, 36
+06D, 06D, 1, 00
+06E, 06E, 0, 94
+06E, 06E, 1, 00
+06F, 06F, 0, 58
+06F, 06F, 1, 64
+070, 070, 0, 41
+070, 070, 1, 00
+071, 071, 0, 3A
+071, 071, 1, 00
+072, 072, 0, 35
+072, 072, 1, 08
+073, 073, 0, 60
+073, 073, 1, F8
+074, 074, 0, 18
+074, 074, 1, 00
+075, 075, 0, 25
+075, 075, 1, 00
+076, 076, 0, 3B
+076, 076, 1, 08
+077, 077, 0, 3C
+077, 077, 1, 08
+078, 078, 0, 3D
+078, 078, 1, 00
+079, 079, 0, 83
+079, 079, 1, 20
+07A, 07A, 0, 4E
+07A, 07A, 1, 40
+07B, 07B, 0, 44
+07B, 07B, 1, 50
+07C, 07C, 0, 42
+07C, 07C, 1, 12
+07D, 07D, 0, 3E
+07D, 07D, 1, 00
+07E, 07E, 0, D8
+07E, 07E, 1, 00
+07F, 07F, 0, 6D
+07F, 07F, 1, 20
+080, 080, 0, B5
+080, 080, 1, 0C
+081, 081, 0, E5
+081, 081, 1, FA
+082, 082, 0, 2B
+082, 082, 1, 04
+083, 083, 0, 7C
+083, 083, 1, 1C
+084, 084, 0, F0
+084, 084, 1, 0A
+085, 085, 0, 55
+085, 085, 1, 0C
+086, 086, 0, A7
+086, 086, 1, 23
+087, 087, 0, 95
+087, 087, 1, 17
+088, 088, 0, 74
+088, 088, 1, 43
+089, 089, 0, 11
+089, 089, 1, 55
+08A, 08A, 0, 74
+08A, 08A, 1, 03
+08B, 08B, 0, 79
+08B, 08B, 1, 14
+08C, 08C, 0, A1
+08C, 08C, 1, 1F
+08D, 08D, 0, 9B
+08D, 08D, 1, 05
+08E, 08E, 0, 5A
+08E, 08E, 1, 02
+08F, 08F, 0, EF
+08F, 08F, 1, F4
+090, 090, 0, AE
+090, 090, 1, 1C
+091, 091, 0, 34
+091, 091, 1, 02
+092, 092, 0, 90
+092, 092, 1, 05
+093, 093, 0, 8E
+093, 093, 1, 0A
+094, 094, 0, 1D
+094, 094, 1, 17
+095, 095, 0, 66
+095, 095, 1, 23
+096, 096, 0, 70
+096, 096, 1, 45
+097, 097, 0, A8
+097, 097, 1, 52
+098, 098, 0, 7B
+098, 098, 1, 14
+099, 099, 0, DE
+099, 099, 1, 1E
+09A, 09A, 0, 75
+09A, 09A, 1, EE
+09B, 09B, 0, 7D
+09B, 09B, 1, D3
+09C, 09C, 0, 02
+09C, 09C, 1, C4
+09D, 09D, 0, AA
+09D, 09D, 1, 1C
+09E, 09E, 0, F8
+09E, 09E, 1, C1
+09F, 09F, 0, 06
+09F, 09F, 1, 04
+0A0, 0A0, 0, 25
+0A0, 0A0, 1, BA
+0A1, 0A1, 0, 33
+0A1, 0A1, 1, 18
+0A2, 0A2, 0, BD
+0A2, 0A2, 1, 8A
+0A3, 0A3, 0, F2
+0A3, 0A3, 1, 85
+0A4, 0A4, 0, 21
+0A4, 0A4, 1, A2
+0A5, 0A5, 0, 78
+0A5, 0A5, 1, 98
+0A6, 0A6, 0, 09
+0A6, 0A6, 1, 80
+0A7, 0A7, 0, 3D
+0A7, 0A7, 1, FA
+0A8, 0A8, 0, AD
+0A8, 0A8, 1, 0D
+0A9, 0A9, 0, 2F
+0A9, 0A9, 1, 02
+0AA, 0AA, 0, 61
+0AA, 0AA, 1, 03
+0AB, 0AB, 0, 00
+0AB, 0AB, 1, F8
+0AC, 0AC, 0, DF
+0AC, 0AC, 1, D5
+0AD, 0AD, 0, 6D
+0AD, 0AD, 1, EA
+0AE, 0AE, 0, F9
+0AE, 0AE, 1, 0F
+0AF, 0AF, 0, E8
+0AF, 0AF, 1, F5
+0B0, 0B0, 0, 6A
+0B0, 0B0, 1, D5
+0B1, 0B1, 0, 0F
+0B1, 0B1, 1, 11
+0B2, 0B2, 0, 0C
+0B2, 0B2, 1, 18
+0B3, 0B3, 0, 03
+0B3, 0B3, 1, F5
+0B4, 0B4, 0, 6A
+0B4, 0B4, 1, 03
+0B5, 0B5, 0, B0
+0B5, 0B5, 1, 05
+0B6, 0B6, 0, D8
+0B6, 0B6, 1, 01
+0B7, 0B7, 0, CE
+0B7, 0B7, 1, 07
+0B8, 0B8, 0, 32
+0B8, 0B8, 1, 00
+0B9, 0B9, 0, 9F
+0B9, 0B9, 1, 03
+0BA, 0BA, 0, 19
+0BA, 0BA, 1, 04
+0BB, 0BB, 0, 0B
+0BB, 0BB, 1, 05
+0BC, 0BC, 0, 5D
+0BC, 0BC, 1, 02
+0BD, 0BD, 0, 79
+0BD, 0BD, 1, 03
+0BE, 0BE, 0, E4
+0BE, 0BE, 1, 05
+0BF, 0BF, 0, 4A
+0BF, 0BF, 1, 03
+0C0, 0C0, 0, FB
+0C0, 0C0, 1, 05
+0C1, 0C1, 0, AB
+0C1, 0C1, 1, 02
+0C2, 0C2, 0, 55
+0C2, 0C2, 1, 00
+0C3, 0C3, 0, 3F
+0C3, 0C3, 1, 00
+0C4, 0C4, 0, 41
+0C4, 0C4, 1, 00
+0C5, 0C5, 0, 40
+0C5, 0C5, 1, 64
+0C6, 0C6, 0, 40
+0C6, 0C6, 1, 00
+0C7, 0C7, 0, 44
+0C7, 0C7, 1, F8
+0C8, 0C8, 0, 37
+0C8, 0C8, 1, 00
+0C9, 0C9, 0, 3B
+0C9, 0C9, 1, F0
+0CA, 0CA, 0, 41
+0CA, 0CA, 1, 00
+0CB, 0CB, 0, 43
+0CB, 0CB, 1, 00
+0CC, 0CC, 0, 36
+0CC, 0CC, 1, 10
+0CD, 0CD, 0, 60
+0CD, 0CD, 1, 10
+0CE, 0CE, 0, 3E
+0CE, 0CE, 1, 00
+0CF, 0CF, 0, 4A
+0CF, 0CF, 1, 20
+0D0, 0D0, 0, 4E
+0D0, 0D0, 1, 40
+0D1, 0D1, 0, 52
+0D1, 0D1, 1, 58
+0D2, 0D2, 0, 5D
+0D2, 0D2, 1, 0F
+0D3, 0D3, 0, 45
+0D3, 0D3, 1, 00
+0D4, 0D4, 0, 46
+0D4, 0D4, 1, 00
+0D5, 0D5, 0, 4B
+0D5, 0D5, 1, 08
+0D6, 0D6, 0, 5E
+0D6, 0D6, 1, F8
+0D7, 0D7, 0, 43
+0D7, 0D7, 1, 00
+0D8, 0D8, 0, 5E
+0D8, 0D8, 1, 00
+0D9, 0D9, 0, 42
+0D9, 0D9, 1, 08
+0DA, 0DA, 0, 52
+0DA, 0DA, 1, 10
+0DB, 0DB, 0, 50
+0DB, 0DB, 1, 00
+0DC, 0DC, 0, 65
+0DC, 0DC, 1, 20
+0DD, 0DD, 0, 78
+0DD, 0DD, 1, 40
+0DE, 0DE, 0, 59
+0DE, 0DE, 1, 50
+0DF, 0DF, 0, 65
+0DF, 0DF, 1, 12
+0E0, 0E0, 0, 66
+0E0, 0E0, 1, 00
+0E1, 0E1, 0, 5E
+0E1, 0E1, 1, 00
+0E2, 0E2, 0, 47
+0E2, 0E2, 1, 08
+0E3, 0E3, 0, D8
+0E3, 0E3, 1, 00
+0E4, 0E4, 0, A8
+0E4, 0E4, 1, 1F
+0E5, 0E5, 0, 53
+0E5, 0E5, 1, 04
+0E6, 0E6, 0, 7D
+0E6, 0E6, 1, 0B
+0E7, 0E7, 0, 52
+0E7, 0E7, 1, 0C
+0E8, 0E8, 0, A9
+0E8, 0E8, 1, 1C
+0E9, 0E9, 0, 7D
+0E9, 0E9, 1, 23
+0EA, 0EA, 0, B8
+0EA, 0EA, 1, 45
+0EB, 0EB, 0, 44
+0EB, 0EB, 1, 52
+0EC, 0EC, 0, 5E
+0EC, 0EC, 1, 18
+0ED, 0ED, 0, A8
+0ED, 0ED, 1, 03
+0EE, 0EE, 0, 4D
+0EE, 0EE, 1, 04
+0EF, 0EF, 0, 9D
+0EF, 0EF, 1, 02
+0F0, 0F0, 0, 6C
+0F0, 0F0, 1, 13
+0F1, 0F1, 0, 3F
+0F1, 0F1, 1, 0A
+0F2, 0F2, 0, 85
+0F2, 0F2, 1, 1F
+0F3, 0F3, 0, F5
+0F3, 0F3, 1, 05
+0F4, 0F4, 0, 11
+0F4, 0F4, 1, 02
+0F5, 0F5, 0, 6D
+0F5, 0F5, 1, 05
+0F6, 0F6, 0, A7
+0F6, 0F6, 1, 1C
+0F7, 0F7, 0, 0E
+0F7, 0F7, 1, 03
+0F8, 0F8, 0, 06
+0F8, 0F8, 1, 04
+0F9, 0F9, 0, 11
+0F9, 0F9, 1, 02
+0FA, 0FA, 0, 47
+0FA, 0FA, 1, 18
+0FB, 0FB, 0, 1C
+0FB, 0FB, 1, 03
+0FC, 0FC, 0, 61
+0FC, 0FC, 1, 05
+0FD, 0FD, 0, 15
+0FD, 0FD, 1, 03
+0FE, 0FE, 0, 6C
+0FE, 0FE, 1, 00
+0FF, 0FF, 0, 6C
+0FF, 0FF, 1, 20
+100, 100, 0, DD
+100, 100, 1, 04
+101, 101, 0, E4
+101, 101, 1, 02
+102, 102, 0, EF
+102, 102, 1, 05
+103, 103, 0, C4
+103, 103, 1, 1C
+104, 104, 0, 1F
+104, 104, 1, 02
+105, 105, 0, D9
+105, 105, 1, 05
+106, 106, 0, 31
+106, 106, 1, 02
+107, 107, 0, 7B
+107, 107, 1, 18
+108, 108, 0, C5
+108, 108, 1, 02
+109, 109, 0, D2
+109, 109, 1, 05
+10A, 10A, 0, 60
+10A, 10A, 1, 02
+10B, 10B, 0, 85
+10B, 10B, 1, 00
+10C, 10C, 0, A4
+10C, 10C, 1, 01
+10D, 10D, 0, C0
+10D, 10D, 1, 00
+10E, 10E, 0, FA
+10E, 10E, 1, 00
+10F, 10F, 0, A4
+10F, 10F, 1, 0D
+
+[BATTERY_PROFILE]
+GUI Version: PM855GUI - 1.0.0.13
+Checksum,CC95
+#5/14/2019 3:40:30 PM
+
+#QRD8250ATL_3650mAh_averaged_MasterSlave_May14th2019
+Float_Voltage,4400
+Profile_Revision,24
+Nom_Batt_capacity,3650
+Batt_id,30900
+Therm_B,4250
+Thermistor_Value,100000
+Battery_name,QRD8250ATL_3650mAh_averaged_MasterSlave_May14th2019
+Therm_c0_Coefficients,0x2318
+Therm_c1_Coefficients,0xD0C
+Therm_c2_Coefficients,0xDAF7
+Therm_c3_Coefficients,0xC556
+Therm_c4_Coefficients,0x848D
+Therm_Center_Offset,0x70
+Therm_Pullup,100
+Rslow_Normal_Coefficients, 0x1399FAB1
+Rslow_Low_Coefficients, 0xFA211579
+Address, Address2, Offset, Data
+041, 041, 0, 09
+041, 041, 1, 00
+042, 042, 0, CB
+042, 042, 1, E3
+043, 043, 0, B1
+043, 043, 1, DD
+044, 044, 0, D0
+044, 044, 1, DB
+045, 045, 0, 31
+045, 045, 1, D4
+046, 046, 0, 00
+046, 046, 1, 00
+047, 047, 0, 9F
+047, 047, 1, BD
+048, 048, 0, BE
+048, 048, 1, 83
+049, 049, 0, FE
+049, 049, 1, 87
+04A, 04A, 0, 38
+04A, 04A, 1, 9C
+04B, 04B, 0, 6C
+04B, 04B, 1, 87
+04C, 04C, 0, 9B
+04C, 04C, 1, 80
+04D, 04D, 0, 1A
+04D, 04D, 1, 00
+04E, 04E, 0, B1
+04E, 04E, 1, FA
+04F, 04F, 0, 99
+04F, 04F, 1, 13
+050, 050, 0, B9
+050, 050, 1, 06
+051, 051, 0, 13
+051, 051, 1, FA
+052, 052, 0, CE
+052, 052, 1, 07
+053, 053, 0, 32
+053, 053, 1, 00
+054, 054, 0, 3D
+054, 054, 1, EB
+055, 055, 0, F9
+055, 055, 1, ED
+056, 056, 0, BF
+056, 056, 1, D5
+057, 057, 0, 38
+057, 057, 1, 0A
+058, 058, 0, 45
+058, 058, 1, DB
+059, 059, 0, BD
+059, 059, 1, 9C
+05A, 05A, 0, 6F
+05A, 05A, 1, 12
+05B, 05B, 0, 8B
+05B, 05B, 1, E3
+05C, 05C, 0, 55
+05C, 05C, 1, C4
+05D, 05D, 0, 60
+05D, 05D, 1, 00
+05E, 05E, 0, 4A
+05E, 05E, 1, 00
+05F, 05F, 0, 47
+05F, 05F, 1, 00
+060, 060, 0, 43
+060, 060, 1, 00
+061, 061, 0, 34
+061, 061, 1, 00
+062, 062, 0, 31
+062, 062, 1, 00
+063, 063, 0, 34
+063, 063, 1, 00
+064, 064, 0, 43
+064, 064, 1, 00
+065, 065, 0, 40
+065, 065, 1, 00
+066, 066, 0, 42
+066, 066, 1, 00
+067, 067, 0, 44
+067, 067, 1, 00
+068, 068, 0, 60
+068, 068, 1, 00
+069, 069, 0, 33
+069, 069, 1, 00
+06A, 06A, 0, 3D
+06A, 06A, 1, 00
+06B, 06B, 0, 47
+06B, 06B, 1, 00
+06C, 06C, 0, 3F
+06C, 06C, 1, 00
+06D, 06D, 0, 37
+06D, 06D, 1, 00
+06E, 06E, 0, 75
+06E, 06E, 1, 00
+06F, 06F, 0, 5D
+06F, 06F, 1, 64
+070, 070, 0, 49
+070, 070, 1, 00
+071, 071, 0, 40
+071, 071, 1, 00
+072, 072, 0, 40
+072, 072, 1, 08
+073, 073, 0, 60
+073, 073, 1, 00
+074, 074, 0, 50
+074, 074, 1, 00
+075, 075, 0, 4C
+075, 075, 1, 00
+076, 076, 0, 58
+076, 076, 1, 08
+077, 077, 0, 4C
+077, 077, 1, 10
+078, 078, 0, 45
+078, 078, 1, 00
+079, 079, 0, 84
+079, 079, 1, 28
+07A, 07A, 0, 5D
+07A, 07A, 1, 48
+07B, 07B, 0, 4F
+07B, 07B, 1, 58
+07C, 07C, 0, 48
+07C, 07C, 1, 0E
+07D, 07D, 0, 45
+07D, 07D, 1, 00
+07E, 07E, 0, D8
+07E, 07E, 1, 08
+07F, 07F, 0, 6F
+07F, 07F, 1, 20
+080, 080, 0, 6F
+080, 080, 1, 14
+081, 081, 0, 61
+081, 081, 1, 03
+082, 082, 0, 7F
+082, 082, 1, FD
+083, 083, 0, A0
+083, 083, 1, 1C
+084, 084, 0, E7
+084, 084, 1, 02
+085, 085, 0, 0D
+085, 085, 1, 04
+086, 086, 0, 24
+086, 086, 1, 22
+087, 087, 0, 9B
+087, 087, 1, 17
+088, 088, 0, 2C
+088, 088, 1, 42
+089, 089, 0, B2
+089, 089, 1, 55
+08A, 08A, 0, 61
+08A, 08A, 1, 03
+08B, 08B, 0, 71
+08B, 08B, 1, 13
+08C, 08C, 0, 44
+08C, 08C, 1, 22
+08D, 08D, 0, 57
+08D, 08D, 1, 05
+08E, 08E, 0, 4B
+08E, 08E, 1, 0A
+08F, 08F, 0, 5F
+08F, 08F, 1, 04
+090, 090, 0, 06
+090, 090, 1, 1D
+091, 091, 0, D3
+091, 091, 1, 02
+092, 092, 0, A2
+092, 092, 1, 05
+093, 093, 0, F5
+093, 093, 1, 02
+094, 094, 0, 30
+094, 094, 1, 18
+095, 095, 0, 25
+095, 095, 1, 23
+096, 096, 0, 6C
+096, 096, 1, 45
+097, 097, 0, E4
+097, 097, 1, 52
+098, 098, 0, 95
+098, 098, 1, 12
+099, 099, 0, D5
+099, 099, 1, 1F
+09A, 09A, 0, 3F
+09A, 09A, 1, E5
+09B, 09B, 0, D9
+09B, 09B, 1, CA
+09C, 09C, 0, DF
+09C, 09C, 1, BD
+09D, 09D, 0, E0
+09D, 09D, 1, 1C
+09E, 09E, 0, 8B
+09E, 09E, 1, C9
+09F, 09F, 0, 5B
+09F, 09F, 1, 05
+0A0, 0A0, 0, 43
+0A0, 0A0, 1, BB
+0A1, 0A1, 0, 55
+0A1, 0A1, 1, 17
+0A2, 0A2, 0, B2
+0A2, 0A2, 1, 8B
+0A3, 0A3, 0, E2
+0A3, 0A3, 1, 84
+0A4, 0A4, 0, 97
+0A4, 0A4, 1, 93
+0A5, 0A5, 0, 84
+0A5, 0A5, 1, 98
+0A6, 0A6, 0, 09
+0A6, 0A6, 1, 80
+0A7, 0A7, 0, A3
+0A7, 0A7, 1, 03
+0A8, 0A8, 0, CD
+0A8, 0A8, 1, 05
+0A9, 0A9, 0, 66
+0A9, 0A9, 1, 05
+0AA, 0AA, 0, 3D
+0AA, 0AA, 1, F2
+0AB, 0AB, 0, 00
+0AB, 0AB, 1, F8
+0AC, 0AC, 0, 58
+0AC, 0AC, 1, D5
+0AD, 0AD, 0, E3
+0AD, 0AD, 1, E2
+0AE, 0AE, 0, F7
+0AE, 0AE, 1, 07
+0AF, 0AF, 0, D5
+0AF, 0AF, 1, EB
+0B0, 0B0, 0, 0A
+0B0, 0B0, 1, C5
+0B1, 0B1, 0, 37
+0B1, 0B1, 1, 18
+0B2, 0B2, 0, 17
+0B2, 0B2, 1, 00
+0B3, 0B3, 0, 33
+0B3, 0B3, 1, E7
+0B4, 0B4, 0, CB
+0B4, 0B4, 1, 02
+0B5, 0B5, 0, 36
+0B5, 0B5, 1, 07
+0B6, 0B6, 0, 5E
+0B6, 0B6, 1, 03
+0B7, 0B7, 0, CE
+0B7, 0B7, 1, 07
+0B8, 0B8, 0, 32
+0B8, 0B8, 1, 00
+0B9, 0B9, 0, 2B
+0B9, 0B9, 1, 03
+0BA, 0BA, 0, 07
+0BA, 0BA, 1, 04
+0BB, 0BB, 0, 3D
+0BB, 0BB, 1, 05
+0BC, 0BC, 0, D6
+0BC, 0BC, 1, 02
+0BD, 0BD, 0, EB
+0BD, 0BD, 1, 05
+0BE, 0BE, 0, 73
+0BE, 0BE, 1, 03
+0BF, 0BF, 0, 9F
+0BF, 0BF, 1, 03
+0C0, 0C0, 0, 33
+0C0, 0C0, 1, 03
+0C1, 0C1, 0, 02
+0C1, 0C1, 1, 05
+0C2, 0C2, 0, 4C
+0C2, 0C2, 1, 00
+0C3, 0C3, 0, 3D
+0C3, 0C3, 1, 00
+0C4, 0C4, 0, 42
+0C4, 0C4, 1, 00
+0C5, 0C5, 0, 42
+0C5, 0C5, 1, 64
+0C6, 0C6, 0, 46
+0C6, 0C6, 1, 00
+0C7, 0C7, 0, 4A
+0C7, 0C7, 1, 00
+0C8, 0C8, 0, 3E
+0C8, 0C8, 1, 08
+0C9, 0C9, 0, 44
+0C9, 0C9, 1, F8
+0CA, 0CA, 0, 46
+0CA, 0CA, 1, 00
+0CB, 0CB, 0, 46
+0CB, 0CB, 1, 00
+0CC, 0CC, 0, 3B
+0CC, 0CC, 1, 10
+0CD, 0CD, 0, 3E
+0CD, 0CD, 1, 10
+0CE, 0CE, 0, 3B
+0CE, 0CE, 1, 00
+0CF, 0CF, 0, 49
+0CF, 0CF, 1, 28
+0D0, 0D0, 0, 4A
+0D0, 0D0, 1, 48
+0D1, 0D1, 0, 52
+0D1, 0D1, 1, 60
+0D2, 0D2, 0, 64
+0D2, 0D2, 1, 0D
+0D3, 0D3, 0, 40
+0D3, 0D3, 1, 00
+0D4, 0D4, 0, 48
+0D4, 0D4, 1, 00
+0D5, 0D5, 0, 50
+0D5, 0D5, 1, 08
+0D6, 0D6, 0, 4C
+0D6, 0D6, 1, 00
+0D7, 0D7, 0, 39
+0D7, 0D7, 1, 00
+0D8, 0D8, 0, 3E
+0D8, 0D8, 1, 00
+0D9, 0D9, 0, 3D
+0D9, 0D9, 1, 10
+0DA, 0DA, 0, 48
+0DA, 0DA, 1, 10
+0DB, 0DB, 0, 42
+0DB, 0DB, 1, 00
+0DC, 0DC, 0, 51
+0DC, 0DC, 1, 20
+0DD, 0DD, 0, 65
+0DD, 0DD, 1, 40
+0DE, 0DE, 0, 43
+0DE, 0DE, 1, 58
+0DF, 0DF, 0, 4D
+0DF, 0DF, 1, 0E
+0E0, 0E0, 0, 48
+0E0, 0E0, 1, 00
+0E1, 0E1, 0, 38
+0E1, 0E1, 1, 00
+0E2, 0E2, 0, 20
+0E2, 0E2, 1, 08
+0E3, 0E3, 0, D8
+0E3, 0E3, 1, 00
+0E4, 0E4, 0, 2D
+0E4, 0E4, 1, 20
+0E5, 0E5, 0, 39
+0E5, 0E5, 1, 05
+0E6, 0E6, 0, B1
+0E6, 0E6, 1, 0A
+0E7, 0E7, 0, 33
+0E7, 0E7, 1, 0C
+0E8, 0E8, 0, BD
+0E8, 0E8, 1, 1C
+0E9, 0E9, 0, 71
+0E9, 0E9, 1, 23
+0EA, 0EA, 0, 97
+0EA, 0EA, 1, 45
+0EB, 0EB, 0, 8D
+0EB, 0EB, 1, 52
+0EC, 0EC, 0, 5C
+0EC, 0EC, 1, 18
+0ED, 0ED, 0, 22
+0ED, 0ED, 1, 02
+0EE, 0EE, 0, 7F
+0EE, 0EE, 1, 05
+0EF, 0EF, 0, 0C
+0EF, 0EF, 1, 02
+0F0, 0F0, 0, 6A
+0F0, 0F0, 1, 11
+0F1, 0F1, 0, 3F
+0F1, 0F1, 1, 0A
+0F2, 0F2, 0, 36
+0F2, 0F2, 1, 20
+0F3, 0F3, 0, E5
+0F3, 0F3, 1, 04
+0F4, 0F4, 0, 25
+0F4, 0F4, 1, 03
+0F5, 0F5, 0, 8D
+0F5, 0F5, 1, 05
+0F6, 0F6, 0, C5
+0F6, 0F6, 1, 1C
+0F7, 0F7, 0, FD
+0F7, 0F7, 1, 02
+0F8, 0F8, 0, FA
+0F8, 0F8, 1, 05
+0F9, 0F9, 0, 37
+0F9, 0F9, 1, 02
+0FA, 0FA, 0, 88
+0FA, 0FA, 1, 18
+0FB, 0FB, 0, B2
+0FB, 0FB, 1, 03
+0FC, 0FC, 0, 1A
+0FC, 0FC, 1, 04
+0FD, 0FD, 0, DA
+0FD, 0FD, 1, 02
+0FE, 0FE, 0, 6C
+0FE, 0FE, 1, 00
+0FF, 0FF, 0, 78
+0FF, 0FF, 1, 20
+100, 100, 0, 8C
+100, 100, 1, 04
+101, 101, 0, 75
+101, 101, 1, 03
+102, 102, 0, 37
+102, 102, 1, 05
+103, 103, 0, D7
+103, 103, 1, 1C
+104, 104, 0, 3B
+104, 104, 1, 02
+105, 105, 0, 84
+105, 105, 1, 05
+106, 106, 0, BF
+106, 106, 1, 02
+107, 107, 0, 93
+107, 107, 1, 18
+108, 108, 0, 11
+108, 108, 1, 03
+109, 109, 0, 4E
+109, 109, 1, 05
+10A, 10A, 0, 45
+10A, 10A, 1, 03
+10B, 10B, 0, 7A
+10B, 10B, 1, 00
+10C, 10C, 0, 1D
+10C, 10C, 1, 01
+10D, 10D, 0, C0
+10D, 10D, 1, 00
+10E, 10E, 0, FA
+10E, 10E, 1, 00
+10F, 10F, 0, 47
+10F, 10F, 1, 0E
diff --git a/uefi/files/Binaries/redwood/RawFiles/BDS_Menu.cfg b/uefi/files/Binaries/redwood/RawFiles/BDS_Menu.cfg
new file mode 100644
index 0000000..c8495cc
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/BDS_Menu.cfg
@@ -0,0 +1,148 @@
+#
+# Configure the BDS Menu entries
+#
+[BDS Menu]
+
+Indent = 1
+FirstRow = 1
+# DefaultSelect = 2
+
+#
+# First Label and App should be for Exit option
+# Menu code will just exit on selection of 0 option
+# So do NOT change this option
+#
+Label = "Exit BDS Menu"
+App = Exit
+
+#
+# Enable Secure Boot
+# This option writes the PK UEFI Secure variable with the
+# available configured PK key value. This enables UEFI Security
+#
+Label = "Enable Secure Boot"
+App = SecurityToggleApp
+Arg = "/SecureBootEnable"
+
+#
+# Disable Secure Boot
+# This option writes the Clear PK UEFI Secure variable that
+# can clear the previously written PK to disable UEFI Security
+#
+Label = "Disable Secure Boot"
+App = SecurityToggleApp
+Arg = /SecureBootDisable
+
+#
+# Enable Debug Policy
+# This option writes the Debug policy variable to enable HLOS debug
+#
+Label = "Enable Debug Policy"
+App = DebugPolicyToggleApp
+Arg = "/DebugPolicyEnable"
+
+#
+# Disable Debug Policy
+# This option clears the Debug policy variable to disble HLOS debug
+#
+Label = "Disable Debug Policy"
+App = DebugPolicyToggleApp
+Arg = "/DebugPolicyDisable"
+
+#
+# Configure PPI Display
+# This option writes the DisplayPpiFlag variable to configure PPI display
+#
+Label = "Config PPI display"
+App = DebugPolicyToggleApp
+Arg = "/ConfigPpiDisplay"
+
+
+#
+# Provision RPMB
+# This option provisions RPMB with the Key provided by TZ. If the
+# device is intended to be used with Fuses blown, this operation
+# should be avoided until the fuses are blown. Since the Key Generated
+# by TZ would change once the fuses are blown. Once key provisioned
+# will NOT be able to change. Making any exception will brick the device
+#
+Label = "Provision RPMB"
+App = RPMBProvision
+Arg = "-Prompt"
+
+
+#
+# Enter Shell
+# Launch the Shell, no startup script is run
+#
+Label = "Enter Shell"
+App = Shell
+Arg = "-nomap -nostartup"
+
+
+#
+# Toggle BootFromUSB First
+# Toggle the variable value AttemptUSBFirst variable
+#
+Label = "Boot USB First"
+App = Cmd
+Arg = "BootUSBFirst"
+
+#
+# MassStorage
+# Put the device into Mass Storage mode to access from PC. Only USER partition
+# of eMMC is available
+#
+Label = "MassStorage"
+App = UsbfnMsdApp
+Arg = "MassStorage"
+
+#
+# Reboot the device
+#
+Label = "Reboot"
+App = Cmd
+Arg = "Reboot"
+
+#
+# Shutdown and power off the device
+#
+Label = "Shutdown"
+App = Cmd
+Arg = "Shutdown"
+
+
+# Clock Menu
+Label = "CLOCK Menu"
+App = Menu
+Arg = "Clock_Menu.cfg"
+
+# USB Menu
+Label = "USB Menu"
+App = Menu
+Arg = "Usb_Menu.cfg"
+
+# Pmic Menu
+Label = "PMIC Menu"
+App = Menu
+Arg = "Pmic_Menu.cfg"
+
+# EUD Menu
+Label = "EUD Menu"
+App = Menu
+Arg = "EUD_Menu.cfg"
+
+Label = "EDL Mode"
+App = Cmd
+Arg = "edl"
+
+# UEFI Menu -- This should be last item in list
+Label = "UEFI Menu"
+App = Menu
+Arg = "Uefi_Menu.cfg"
+
+#
+# If BDS Menu should show some platform specific help string at the bottom of the
+# menu, add it here as value for MenuHelp
+# MenuHelp = "Platform has specific help need?"
+
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_K9B_42_02_0a_amoled_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_K9B_42_02_0a_amoled_dsc_cmd.xml
new file mode 100644
index 0000000..34334ad
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_K9B_42_02_0a_amoled_dsc_cmd.xml
@@ -0,0 +1,138 @@
+<?xml version=\"1.0\" encoding=\"utf-8\"?>
+<PanelDescription>k9b 42 02 0a Single DSI Cmd Mode AMOLED Panel with DSC (1080x2400 24bpp)</PanelDescription>
+<Group id=\"Active Timing\">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>16</HorizontalFrontPorch>
+ <HorizontalBackPorch>8</HorizontalBackPorch>
+ <HorizontalSyncPulse>8</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2400</VerticalActive>
+ <VerticalFrontPorch>4</VerticalFrontPorch>
+ <VerticalBackPorch>8</VerticalBackPorch>
+ <VerticalSyncPulse>4</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIFlags>0x8</DSIFlags>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>8</DSIDSCProfileID>
+ <DSIDSCSliceWidth>1080</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>12</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>1</DSIDSCSlicePerPacket>
+ <DSIBitClockFrequency>831000000</DSIBitClockFrequency>
+ <DSILP11AtInit>True</DSILP11AtInit>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2400</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2400</DSITEvSyncInitVal>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 15 90 01
+ 39 91 AB 28 00 0C C2 00 03 1C 01 7E 00 0F 08 BB 04 3D 10 F0
+ 15 03 01
+ 05 2C
+ 15 35 00
+ 39 2A 00 00 04 37
+ 39 2B 00 00 09 5F
+ 15 53 20
+ 39 F0 55 AA 52 08 00
+ 39 6F 02
+ 39 B2 08 08
+ 39 51 07 FF
+ 15 2F 01
+ 39 F0 55 AA 52 08 01
+ 39 C3 94 01 8C D0 22 02 00
+ 15 6F 01
+ 39 D2 00 00 11
+ 15 6F 06
+ 15 D2 05
+ 15 6F 09
+ 39 D2 00 00
+ 15 6F 0F
+ 15 D2 00
+ 15 CE 00
+ 39 FF AA 55 A5 80
+ 15 6F 61
+ 15 F3 80
+ 39 F0 55 AA 52 08 00
+ 15 C0 46
+ 39 BE 0E 0B
+ 15 6F 05
+ 15 BE 88
+ 15 6F 08
+ 15 B5 32
+ 15 6F 0B
+ 39 B5 33 23 2B
+ 15 6F 29
+ 15 D9 00
+ 15 6F 01
+ 15 D9 80
+ 15 6F 07
+ 39 B2 07 FF
+ 15 6F 17
+ 39 B2 07 FF
+ 15 6F 1F
+ 39 B2 00 50
+ 39 F0 55 AA 52 08 07
+ 15 C0 05
+ 39 C1 30 0F 03 C1 0B D1 F2 AE 3F FC DC AA 3F F9 27 4A 80 00 A7 E2 79 00 1A 00 00 85 1F 33 B0 0C F5 0F E1 95 00 00 00 14 18 00 19 1F 00
+ 39 C2 38 0F 0D 99 02 71 F4 7A 3F F9 F8 D6 FF FD E2 02 00 00 75 80 91 00 00 20 00 19 8F 33 F0 0A D7 0F 91 E7 00 00 04 1E 18 04 23 1F 00
+ 39 C3 36 00 03 C1 0B D1 0D 52 00 00 00 00 3F F3 96 04 80 00 00 00 00 03 B2 00 04 1D 1F 33 B0 00 00 03 1F 95 00 00 90 14 40 90 19 47 00
+ 39 C4 3E 00 0D 99 02 71 0B 86 00 03 5F 48 FF FC C1 EC 00 00 00 00 00 04 1E 20 04 37 8F 33 F0 00 00 03 6F E7 00 00 94 1E 40 94 23 47 00
+ 39 C5 2C 00 0D 99 02 71 0B 86 3F F4 F9 BC C0 00 00 00 00 00 00 00 00 80 00 D0 90 19 3F 33 F0 00 00 0C 91 19 00 00 00 00 00 00 00 00 00
+ 39 C6 2C 00 03 C1 0B D1 0D 52 3F FB 3F BC 00 03 FC 18 00 00 00 00 00 90 1A 40 90 85 5F 33 30 00 00 0C E1 6B 00 00 00 00 00 00 00 00 00
+ 39 C7 2A 0F 03 C1 0B D1 F2 AE 00 01 9C EE 00 09 8D 5E 7F FE AB 86 0D 93 B2 40 94 1D 5F 33 3F F3 0B 00 1F 6B 00 00 00 00 00 00 00 00 00
+ 39 C8 2A 0F 0D 99 02 71 F4 7A 00 08 5E 62 C0 01 20 16 7F FF 0D 95 E5 84 1E D0 94 37 3F 33 FF F5 29 00 6F 19 00 00 00 00 00 00 00 00 00
+ 39 C9 21 00 2A 40 2B E4 00 00 3F DD 03 00 3F DC 56 C0 80 07 3E 61 00 71 B3 FA 82 1D 62 33 F0 2B 10 0F 98 96 00 00 00 00 00 00 00 00 00
+ 39 CA 27 00 2B 11 28 A4 00 00 00 00 00 00 3F DE A9 78 80 00 00 00 00 72 1E FA 82 84 63 33 D0 00 00 03 69 9A 00 00 00 00 00 00 00 00 00
+ 39 CB 2D 00 2A 40 2B 11 00 00 3F DD 57 80 80 00 00 00 00 00 00 00 00 81 B3 63 82 1C CB 33 90 00 00 0C 98 69 00 00 00 00 00 00 00 00 00
+ 39 CC 2B 00 29 71 29 71 00 00 00 00 00 00 80 00 00 00 7F F9 4A 9C 1F 82 1D 64 82 84 CB 33 8F D6 8F 00 67 67 00 00 00 00 00 00 00 00 00
+ 39 CD 2D 00 03 C1 03 C1 00 00 3F FF 17 42 00 00 00 00 80 00 00 00 00 01 FC 3F 02 1B 5E 33 50 00 00 0C E1 1F 00 00 00 00 00 00 00 00 00
+ 39 CE 2B 00 03 C1 03 C1 00 00 00 00 00 00 00 00 00 00 FF FF F1 E8 7F 02 1C 3F 02 3B 5E 33 5F FC 3F 00 1F 1F 00 00 00 00 00 00 00 00 00
+ 39 CF 21 00 03 C1 03 84 00 00 3F FF 1E C4 3F FF 26 08 00 00 0D 32 84 01 FC 1F 02 1A 3E 33 80 03 A2 0F E1 E2 00 00 00 00 00 00 00 00 00
+ 39 D0 27 00 03 C1 04 00 00 00 00 00 00 00 3F FF 08 00 00 00 00 00 00 02 1B 1F 02 3B 3E 33 90 00 00 03 1F E0 00 00 00 00 00 00 00 00 00
+ 05 11
+ FF 50
+ 05 29
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 0A
+ 05 10
+ FF 78
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>15</BacklightDefault>
+ <DisplayResetInfo>0 2000 2000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_K9D_36_02_0a_amoled_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_K9D_36_02_0a_amoled_dsc_cmd.xml
new file mode 100644
index 0000000..fba8bfa
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_K9D_36_02_0a_amoled_dsc_cmd.xml
@@ -0,0 +1,170 @@
+<?xml version=\"1.0\" encoding=\"utf-8\"?>
+<PanelDescription>k9d 36 02 0a Single DSI Cmd Mode AMOLED Panel with DSC (1080x2400 24bpp)</PanelDescription>
+<Group id=\"Active Timing\">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>16</HorizontalFrontPorch>
+ <HorizontalBackPorch>8</HorizontalBackPorch>
+ <HorizontalSyncPulse>8</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2400</VerticalActive>
+ <VerticalFrontPorch>1212</VerticalFrontPorch>
+ <VerticalBackPorch>8</VerticalBackPorch>
+ <VerticalSyncPulse>4</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIFlags>0x8</DSIFlags>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>8</DSIDSCProfileID>
+ <DSIDSCSliceWidth>1080</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>12</DSIDSCSliceHeight>
+ <DSIBitClockFrequency>682000000</DSIBitClockFrequency>
+ <DSILP11AtInit>True</DSILP11AtInit>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2400</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2400</DSITEvSyncInitVal>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 F0 55 AA 52 08 00
+ 39 BA 01 E6 00 10 00 30 00 01
+ 15 B2 58
+ 15 6F 02
+ 39 B2 0C 0C
+ 39 BE 0E 0B 14 13
+ 15 6F 05
+ 15 BE 8A
+ 15 C0 66
+ 15 6F 08
+ 15 B5 32
+ 39 F0 55 AA 52 08 07
+ 39 C0 01
+ 39 C1 30 0F 04 C9 0F 81 EE C6 3F FB B3 6A 3F F6 D1 42 80 00 F7 33 B1 00 18 00 00 8B 23 33 C0 0F B9 0F DD 8D 00 00 00 0D 08 00 17 23 00
+ 39 C2 38 0F 0B 64 02 11 F6 4C 3F FA E2 14 FF FE 41 A8 00 00 5E 26 90 00 00 24 00 17 90 33 C0 09 B4 0F 94 E9 00 00 90 0D 3C 90 17 57 00
+ 39 C3 3C 00 04 C9 0F 81 11 3A 3F F9 58 7C 00 04 F1 78 00 00 00 00 00 90 18 3C 90 8B 5F 33 60 00 00 0C DD 73 00 00 04 20 08 04 2A 23 00
+ 39 C4 3C 00 0B 64 02 11 09 B4 3F F6 CA 24 C0 00 00 00 00 00 00 00 00 80 00 CF 90 17 3B 33 C0 00 00 0C 94 17 00 00 94 20 3C 94 2A 57 00
+ 39 C5 26 00 04 C9 0F 81 11 3A 00 00 00 00 3F EF 14 34 80 00 00 00 00 03 AC 00 04 1F 23 33 C0 00 00 03 23 8D 00 00 00 00 00 00 00 00 00
+ 39 C6 2E 00 0B 64 02 11 09 B4 00 03 11 F4 FF FD 62 7C 00 00 00 00 00 04 20 24 04 37 90 33 C0 00 00 03 6C E9 00 00 00 00 00 00 00 00 00
+ 39 C7 2A 0F 04 C9 0F 81 EE C6 00 02 5A EE 00 0C AE 86 7F FD F9 F3 65 93 AC 3C 94 1F 5F 33 6F F0 47 00 23 73 00 00 00 00 00 00 00 00 00
+ 39 C8 2A 0F 0B 64 02 11 F6 4C 00 07 29 E4 C0 00 DF 2C 7F FF 43 B2 E0 84 20 CF 94 37 3B 33 CF F6 4C 00 6C 17 00 00 00 00 00 00 00 00 00
+ 39 C9 27 00 03 C1 04 41 00 00 00 00 00 00 3F FE F8 42 00 00 00 00 00 00 63 24 00 84 43 33 90 00 00 03 1F DF 00 00 00 00 00 00 00 00 00
+ 39 CA 21 00 03 C1 04 00 00 00 3F FF 0F C0 3F FF 08 00 00 00 0F 04 00 00 42 24 00 62 43 33 90 03 E0 0F E1 E0 00 00 00 00 00 00 00 00 00
+ 39 CB 2D 00 04 00 04 00 00 00 3F FF 00 00 00 00 00 00 80 00 00 00 00 00 42 44 00 62 64 33 60 00 00 0C E0 20 00 00 00 00 00 00 00 00 00
+ 39 CC 2B 00 04 00 04 41 00 00 00 00 00 00 00 00 00 00 FF FF EE FC 00 00 63 44 00 84 64 33 6F FB E0 00 20 21 00 00 00 00 00 00 00 00 00
+ 15 B4 C0
+ 15 6F 01
+ 39 B4 00 80 80
+ 39 F0 55 AA 52 08 01
+ 39 6F 01
+ 39 D2 00 00 11
+ 39 6F 06
+ 39 D2 05
+ 39 6F 0F
+ 39 D2 00
+ 39 6F 09
+ 39 D2 00 00
+ 39 CE 00
+ 39 FF AA 55 A5 80
+ 39 6F 61
+ 39 F3 80
+ 39 F0 55 AA 52 08 00
+ 39 C0 46
+ 39 BE 0E 0B
+ 39 6F 05
+ 39 BE 88
+ 39 6F 08
+ 39 B5 32
+ 39 6F 0B
+ 39 B5 33 23 2B
+ 39 F0 55 AA 52 08 01
+ 39 D1 07 00 04
+ 39 3B 00 10 00 30
+ 39 D9 C8
+ 15 90 01
+ 39 91 AB 28 00 0C C2 00 03 1C 01 7E 00 0F 08 BB 04 3D 10 F0
+ 15 03 01
+ 39 51 00 00 00 00
+ 15 53 20
+ 15 35 00
+ 39 2A 00 00 04 37
+ 39 2B 00 00 09 5F
+ 15 2F 02
+ 39 FF AA 55 A5 81
+ 15 6F 0F
+ 39 FD 01 5A
+ 15 6F 04
+ 15 FD 5F
+ 15 6F 1A
+ 15 FD 5F
+ 05 2C
+ 39 F0 55 AA 52 08 00
+ 39 CA 12 00 92 02
+ 15 6F 02
+ 39 EC 80 10
+ 39 F0 55 AA 52 08 01
+ 39 CD 05 31
+ 15 6F 10
+ 15 D8 0C
+ 39 F0 55 AA 52 08 05
+ 39 B3 86 80
+ 39 B5 85 81
+ 39 B7 85 00 00 81
+ 39 B8 05 00 00 81
+ 39 EC 0D 11
+ 15 6F 02
+ 39 EC 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+ 39 F0 55 AA 52 08 00
+ 39 6F 08
+ 39 B5 32
+ 39 6F 0B
+ 39 B5 33 23 2B
+ 39 F0 55 AA 52 08 01
+ 39 CE 00
+ 39 F0 55 AA 52 08 01
+ 39 C3 94 01 97 D0 22 02 00
+ 05 11
+ FF 32
+ 05 29
+ FF 10
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 14
+ 05 10
+ FF 50
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>15</BacklightDefault>
+ <DisplayResetInfo>0 2000 2000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_K9D_42_0d_0b_amoled_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_K9D_42_0d_0b_amoled_dsc_cmd.xml
new file mode 100644
index 0000000..30fd561
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_K9D_42_0d_0b_amoled_dsc_cmd.xml
@@ -0,0 +1,132 @@
+<?xml version=\"1.0\" encoding=\"utf-8\"?>
+<PanelDescription>k9d 42 0d 0b Single DSI Cmd Mode AMOLED Panel with DSC (1080x2400 24bpp)</PanelDescription>
+<Group id=\"Active Timing\">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>16</HorizontalFrontPorch>
+ <HorizontalBackPorch>8</HorizontalBackPorch>
+ <HorizontalSyncPulse>8</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2400</VerticalActive>
+ <VerticalFrontPorch>1212</VerticalFrontPorch>
+ <VerticalBackPorch>8</VerticalBackPorch>
+ <VerticalSyncPulse>4</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIFlags>0x8</DSIFlags>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>8</DSIDSCProfileID>
+ <DSIDSCSliceWidth>1080</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>12</DSIDSCSliceHeight>
+ <DSIBitClockFrequency>682000000</DSIBitClockFrequency>
+ <DSILP11AtInit>True</DSILP11AtInit>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2400</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2400</DSITEvSyncInitVal>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 15 03 01
+ 39 F0 AA 10
+ 39 E7 00 40 00
+ 39 CF 09 07 8B 89 13
+ 39 B1 01 EC 00 18 04 E0 00
+ 39 44 00 03
+ 39 F0 AA 12
+ 39 C1 00 0F
+ 39 C3 C1 20 01 37 01 37 01 37 03 A5 03 A5 03 A5 20 00 63
+ 39 C4 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+ 05 35 00
+ 15 53 20
+ 15 59 09
+ 39 51 07 FF
+ 15 6C 00
+ 15 6F 02
+ 39 70 11 00 00 89 30 80 09 60 04 38 00 28 04 38 04 38 02 00 03 A3 00 20 04 72 00 0F 00 0F 03 14 01 46 18 00 10 F0 03 0C 20 00 06 0B 0B 33 0E 1C 2A 38 46 54
+ 15 65 32
+ 39 70 62 69 70 77 79 7B 7D 7E 01 02 01 00 09 40 09 BE 19 FC 19 FA 19 F8 1A 38 1A 78 1A B6 2A B6 2A F4 2A F4 4B 34 7B F4 00 00 00 00 00 00
+ 39 F0 AA 14
+ 39 B2 03 33
+ 39 B4 0A 56 00 00 0A 56 00 00 0A 56 00 00
+ 39 B5 00 17 17 17 17 17 17 06 01
+ 39 B9 00 00 0A 17 17 17
+ 39 BC 10 00 00 0A 11 17 69 17 69 17 69
+ 39 BE 10 10 00 0A 22 17 41 17 41 17 41
+ 39 FF 5A 81
+ 15 65 05
+ 15 F3 0F
+ 39 F0 AA 12
+ 39 C7 2F 43 32 44
+ 39 F0 AA 18
+ 15 B0 13
+ 15 B2 13
+ 39 F0 AA 17
+ 39 B1 00 00 12 00
+ 39 B2 00 00 00 02 e0 00 0e 00 00 e0 00 00 00 00 20 20 00 40 00 00 20 20
+ 39 B3 00 40 1A 00 3c 00 80 A8 98 80 A8 80 00 C0 00 00 1F A0
+ 39 F0 AA 10
+ 39 B3 C7
+ 39 F0 AA 00
+ 39 FF 5A 00
+ 39 F0 AA 15
+ 15 C3 01
+ 39 D2 00 01 04 38 05 C9 0A 00
+ 15 B1 65
+ 39 B2 36 02 00 03 30 00
+ 39 B3 26 41
+ 39 B4 25 41 00 45 00 00
+ 39 B5 25 41 00 45 00 00
+ 39 B6 25 41 00 45 00 00
+ 39 B7 25 41 00 45 00 00
+ 39 B8 A4 00 00 25 00 00
+ 39 BC 07 02
+ 39 BE 22 44 22 22 44 44 44 44 44 44 00
+ 39 F0 AA 12
+ 39 65 08
+ 39 D2 10 00 01 01
+ 39 F0 AA 00
+ 39 FF 5A 00
+ 05 11
+ FF 78
+ 05 29
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 78
+ 05 10
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>15</BacklightDefault>
+ <DisplayResetInfo>0 2000 2000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_K9E_35_02_0b_amoled_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_K9E_35_02_0b_amoled_dsc_cmd.xml
new file mode 100644
index 0000000..e230b9d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_K9E_35_02_0b_amoled_dsc_cmd.xml
@@ -0,0 +1,143 @@
+<?xml version=\"1.0\" encoding=\"utf-8\"?>
+<PanelDescription>k9e 35 02 0b Single DSI Cmd Mode AMOLED Panel with DSC (1080x2400 24bpp)</PanelDescription>
+<Group id=\"Active Timing\">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>16</HorizontalFrontPorch>
+ <HorizontalBackPorch>8</HorizontalBackPorch>
+ <HorizontalSyncPulse>8</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2400</VerticalActive>
+ <VerticalFrontPorch>4</VerticalFrontPorch>
+ <VerticalBackPorch>8</VerticalBackPorch>
+ <VerticalSyncPulse>4</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIFlags>0x8</DSIFlags>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>8</DSIDSCProfileID>
+ <DSIDSCSliceWidth>1080</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>12</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>1</DSIDSCSlicePerPacket>
+ <DSIBitClockFrequency>831000000</DSIBitClockFrequency>
+ <DSILP11AtInit>True</DSILP11AtInit>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2400</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2400</DSITEvSyncInitVal>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 90 01
+ 39 91 89 28 00 0C C2 00 03 1C 01 7E 00 0F 08 BB 04 3D 10 F0
+ 39 03 01
+ 39 2C
+ 39 35 00
+ 39 2A 00 00 04 37
+ 39 2B 00 00 09 5F
+ 39 53 20
+ 39 F0 55 AA 52 08 00
+ 39 B2 19
+ 39 6F 02
+ 39 B2 08 08
+ 39 51 07 FF 0F FE
+ 39 2F 01
+ 39 B5 94
+ 39 82 AE
+ 39 5F 01
+ 39 BE 0E 0B
+ 39 6F 05
+ 39 BE 88
+ 39 6F 1F
+ 39 B2 00 30
+ 39 6F 17
+ 39 B2 07 FF
+ 39 F0 55 AA 52 08 07
+ 39 C0 05 02
+ 39 6F 04
+ 39 C0 55 00
+ 39 C1 30 0F 03 C1 0B D1 F2 AE 3F FC DC AA 3F F9 27 4A 80 00 A7 E2 79 00 1A 00 00 85 1F 33 B0 0C F5 0F E1 95 00 00 00 14 18 00 19 1F 00
+ 39 C2 38 0F 0D 99 02 71 F4 7A 3F F9 F8 D6 FF FD E2 02 00 00 75 80 91 00 00 20 00 19 8F 33 F0 0A D7 0F 91 E7 00 00 04 1E 18 04 23 1F 00
+ 39 C3 36 00 03 C1 0B D1 0D 52 00 00 00 00 3F F3 96 04 80 00 00 00 00 03 B2 00 04 1D 1F 33 B0 00 00 03 1F 95 00 00 90 14 40 90 19 47 00
+ 39 C4 3E 00 0D 99 02 71 0B 86 00 03 5F 48 FF FC C1 EC 00 00 00 00 00 04 1E 20 04 37 8F 33 F0 00 00 03 6F E7 00 00 94 1E 40 94 23 47 00
+ 39 C5 2C 00 0D 99 02 71 0B 86 3F F4 F9 BC C0 00 00 00 00 00 00 00 00 80 00 D0 90 19 3F 33 F0 00 00 0C 91 19 00 00 00 00 00 00 00 00 00
+ 39 C6 2C 00 03 C1 0B D1 0D 52 3F FB 3F BC 00 03 FC 18 00 00 00 00 00 90 1A 40 90 85 5F 33 30 00 00 0C E1 6B 00 00 00 00 00 00 00 00 00
+ 39 C7 2A 0F 03 C1 0B D1 F2 AE 00 01 9C EE 00 09 8D 5E 7F FE AB 86 0D 93 B2 40 94 1D 5F 33 3F F3 0B 00 1F 6B 00 00 00 00 00 00 00 00 00
+ 39 C8 2A 0F 0D 99 02 71 F4 7A 00 08 5E 62 C0 01 20 16 7F FF 0D 95 E5 84 1E D0 94 37 3F 33 FF F5 29 00 6F 19 00 00 00 00 00 00 00 00 00
+ 39 C9 21 00 28 A4 28 A4 00 00 3F DF 9D 50 3F DF 9D 50 80 06 73 A9 10 00 00 00 00 66 66 33 D0 28 A4 0F 9A 9A 00 00 00 00 00 00 00 00 00
+ 39 CA 27 00 28 A4 27 D9 00 00 00 00 00 00 3F E0 3F 14 80 00 00 00 00 00 67 00 00 CC 66 33 D0 00 00 03 66 9B 00 00 00 00 00 00 00 00 00
+ 39 CB 2D 00 27 D9 28 A4 00 00 3F E0 3F 14 80 00 00 00 00 00 00 00 00 00 00 67 00 66 CC 33 70 00 00 0C 9B 66 00 00 00 00 00 00 00 00 00
+ 39 CC 2B 00 27 D9 27 D9 00 00 00 00 00 00 80 00 00 00 7F F9 CC 2A 0F 00 67 67 00 CC CC 33 7F D8 27 00 65 65 00 00 00 00 00 00 00 00 00
+ 39 CD 2D 00 03 C1 03 C1 00 00 3F FF 17 42 00 00 00 00 80 00 00 00 00 01 FC 3F 02 1B 5E 33 50 00 00 0C E1 1F 00 00 00 00 00 00 00 00 00
+ 39 CE 2B 00 03 C1 03 C1 00 00 00 00 00 00 00 00 00 00 FF FF F1 E8 7F 02 1C 3F 02 3B 5E 33 5F FC 3F 00 1F 1F 00 00 00 00 00 00 00 00 00
+ 39 CF 21 00 03 C1 03 84 00 00 3F FF 1E C4 3F FF 26 08 00 00 0D 32 84 01 FC 1F 02 1A 3E 33 80 03 A2 0F E1 E2 00 00 00 00 00 00 00 00 00
+ 39 D0 27 00 03 C1 04 00 00 00 00 00 00 00 3F FF 08 00 00 00 00 00 00 02 1B 1F 02 3B 3E 33 90 00 00 03 1F E0 00 00 00 00 00 00 00 00 00
+ 39 F0 55 AA 52 08 01
+ 39 6F 01
+ 39 D2 00 00 11
+ 39 6F 06
+ 39 D2 05
+ 39 6F 09
+ 39 D2 00 00
+ 39 6F 0F
+ 39 D2 00
+ 39 CE 00
+ 39 FF AA 55 A5 80
+ 39 6F 61
+ 39 F3 80
+ 39 F0 55 AA 52 08 00
+ 39 C0 46
+ 39 6F 06
+ 39 B5 2D 19 32
+ 39 6F 0B
+ 39 B5 33 23 2D
+ 39 6F 02
+ 39 EC 80 10
+ 39 F0 55 AA 52 08 01
+ 39 CE 08
+ 39 11
+ FF 78
+ 39 29
+ 39 F0 55 AA 52 08 01
+ 39 CE 00
+</DSIInitSequence>
+<DSITermSequence>
+ 39 28
+ FF 0A
+ 39 10
+ FF 64
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>15</BacklightDefault>
+ <DisplayResetInfo>0 2000 2000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_K9E_42_02_0a_amoled_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_K9E_42_02_0a_amoled_dsc_cmd.xml
new file mode 100644
index 0000000..e2c246f
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_K9E_42_02_0a_amoled_dsc_cmd.xml
@@ -0,0 +1,142 @@
+<?xml version=\"1.0\" encoding=\"utf-8\"?>
+<PanelDescription>k9e 42 02 0a Single DSI Cmd Mode AMOLED Panel with DSC (1080x2400 24bpp)</PanelDescription>
+<Group id=\"Active Timing\">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>16</HorizontalFrontPorch>
+ <HorizontalBackPorch>8</HorizontalBackPorch>
+ <HorizontalSyncPulse>8</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2400</VerticalActive>
+ <VerticalFrontPorch>4</VerticalFrontPorch>
+ <VerticalBackPorch>8</VerticalBackPorch>
+ <VerticalSyncPulse>4</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIFlags>0x8</DSIFlags>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>8</DSIDSCProfileID>
+ <DSIDSCSliceWidth>1080</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>12</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>1</DSIDSCSlicePerPacket>
+ <DSIBitClockFrequency>831000000</DSIBitClockFrequency>
+ <DSILP11AtInit>True</DSILP11AtInit>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2400</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2400</DSITEvSyncInitVal>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 15 90 01
+ 39 91 A9 28 00 0C C2 00 03 1C 01 7E 00 0F 08 BB 04 3D 10 F0
+ 15 03 01
+ 05 2C
+ 15 35 00
+ 39 2A 00 00 04 37
+ 39 2B 00 00 09 5F
+ 15 53 20
+ 39 F0 55 AA 52 08 00
+ 39 6F 02
+ 39 B2 08 08
+ 39 51 00 00
+ 15 2F 01
+ 39 F0 55 AA 52 08 01
+ 39 C3 94 01 8C D0 22 02 00
+ 15 6F 01
+ 39 D2 00 00 11
+ 15 6F 06
+ 15 D2 05
+ 15 6F 09
+ 39 D2 00 00
+ 15 6F 0F
+ 15 D2 00
+ 15 CE 00
+ 39 FF AA 55 A5 80
+ 15 6F 61
+ 15 F3 80
+ 39 F0 55 AA 52 08 00
+ 15 C0 46
+ 39 BE 0E 0B
+ 15 6F 05
+ 15 BE 88
+ 15 6F 08
+ 15 B5 32
+ 15 6F 0B
+ 39 B5 33 23 2B
+ 15 6F 29
+ 15 D9 00
+ 15 6F 01
+ 15 D9 80
+ 15 6F 07
+ 39 B2 07 FF
+ 15 6F 17
+ 39 B2 07 FF
+ 15 6F 1F
+ 39 B2 00 50
+ 39 F0 55 AA 52 08 07
+ 15 C0 05
+ 39 C1 30 0F 03 C1 0B D1 F2 AE 3F FC DC AA 3F F9 27 4A 80 00 A7 E2 79 00 1A 00 00 85 1F 33 B0 0C F5 0F E1 95 00 00 00 14 18 00 19 1F 00
+ 39 C2 38 0F 0D 99 02 71 F4 7A 3F F9 F8 D6 FF FD E2 02 00 00 75 80 91 00 00 20 00 19 8F 33 F0 0A D7 0F 91 E7 00 00 04 1E 18 04 23 1F 00
+ 39 C3 36 00 03 C1 0B D1 0D 52 00 00 00 00 3F F3 96 04 80 00 00 00 00 03 B2 00 04 1D 1F 33 B0 00 00 03 1F 95 00 00 90 14 40 90 19 47 00
+ 39 C4 3E 00 0D 99 02 71 0B 86 00 03 5F 48 FF FC C1 EC 00 00 00 00 00 04 1E 20 04 37 8F 33 F0 00 00 03 6F E7 00 00 94 1E 40 94 23 47 00
+ 39 C5 2C 00 0D 99 02 71 0B 86 3F F4 F9 BC C0 00 00 00 00 00 00 00 00 80 00 D0 90 19 3F 33 F0 00 00 0C 91 19 00 00 00 00 00 00 00 00 00
+ 39 C6 2C 00 03 C1 0B D1 0D 52 3F FB 3F BC 00 03 FC 18 00 00 00 00 00 90 1A 40 90 85 5F 33 30 00 00 0C E1 6B 00 00 00 00 00 00 00 00 00
+ 39 C7 2A 0F 03 C1 0B D1 F2 AE 00 01 9C EE 00 09 8D 5E 7F FE AB 86 0D 93 B2 40 94 1D 5F 33 3F F3 0B 00 1F 6B 00 00 00 00 00 00 00 00 00
+ 39 C8 2A 0F 0D 99 02 71 F4 7A 00 08 5E 62 C0 01 20 16 7F FF 0D 95 E5 84 1E D0 94 37 3F 33 FF F5 29 00 6F 19 00 00 00 00 00 00 00 00 00
+ 39 C9 21 00 2A 40 2B E4 00 00 3F DD 03 00 3F DC 56 C0 80 07 3E 61 00 71 B3 FA 82 1D 62 33 F0 2B 10 0F 98 96 00 00 00 00 00 00 00 00 00
+ 39 CA 27 00 2B 11 28 A4 00 00 00 00 00 00 3F DE A9 78 80 00 00 00 00 72 1E FA 82 84 63 33 D0 00 00 03 69 9A 00 00 00 00 00 00 00 00 00
+ 39 CB 2D 00 2A 40 2B 11 00 00 3F DD 57 80 80 00 00 00 00 00 00 00 00 81 B3 63 82 1C CB 33 90 00 00 0C 98 69 00 00 00 00 00 00 00 00 00
+ 39 CC 2B 00 29 71 29 71 00 00 00 00 00 00 80 00 00 00 7F F9 4A 9C 1F 82 1D 64 82 84 CB 33 8F D6 8F 00 67 67 00 00 00 00 00 00 00 00 00
+ 39 CD 2D 00 03 C1 03 C1 00 00 3F FF 17 42 00 00 00 00 80 00 00 00 00 01 FC 3F 02 1B 5E 33 50 00 00 0C E1 1F 00 00 00 00 00 00 00 00 00
+ 39 CE 2B 00 03 C1 03 C1 00 00 00 00 00 00 00 00 00 00 FF FF F1 E8 7F 02 1C 3F 02 3B 5E 33 5F FC 3F 00 1F 1F 00 00 00 00 00 00 00 00 00
+ 39 CF 21 00 03 C1 03 84 00 00 3F FF 1E C4 3F FF 26 08 00 00 0D 32 84 01 FC 1F 02 1A 3E 33 80 03 A2 0F E1 E2 00 00 00 00 00 00 00 00 00
+ 39 D0 27 00 03 C1 04 00 00 00 00 00 00 00 3F FF 08 00 00 00 00 00 00 02 1B 1F 02 3B 3E 33 90 00 00 03 1F E0 00 00 00 00 00 00 00 00 00
+ 39 F0 55 AA 52 08 01
+ 39 CE 08 00 01 00 04
+ 05 11
+ FF 50
+ 05 29
+ 39 F0 55 AA 52 08 01
+ 39 CE 00 00 01 00 04
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 0A
+ 05 10
+ FF 78
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>15</BacklightDefault>
+ <DisplayResetInfo>0 2000 2000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_L9_36_02_0b_amoled_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_L9_36_02_0b_amoled_dsc_cmd.xml
new file mode 100644
index 0000000..1f39ca7
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_L9_36_02_0b_amoled_dsc_cmd.xml
@@ -0,0 +1,139 @@
+<?xml version=\"1.0\" encoding=\"utf-8\"?>
+<PanelDescription>l9 36 02 0b Single DSI Cmd Mode AMOLED Panel with DSC (1080x2400 24bpp)</PanelDescription>
+<Group id=\"Active Timing\">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>32</HorizontalFrontPorch>
+ <HorizontalBackPorch>32</HorizontalBackPorch>
+ <HorizontalSyncPulse>32</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2400</VerticalActive>
+ <VerticalFrontPorch>1300</VerticalFrontPorch>
+ <VerticalBackPorch>1335</VerticalBackPorch>
+ <VerticalSyncPulse>32</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIFlags>0x8</DSIFlags>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>8</DSIDSCProfileID>
+ <DSIDSCSliceWidth>1080</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>12</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>1</DSIDSCSlicePerPacket>
+ <DSIBitClockFrequency>831000000</DSIBitClockFrequency>
+ <DSILP11AtInit>True</DSILP11AtInit>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2400</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2400</DSITEvSyncInitVal>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 F0 55 AA 52 08 04
+ 39 6F 1C
+ 39 C0 15 27 38 00 00
+ 39 3B 00 10 00 04
+ 39 90 01
+ 39 91 89 28 00 0C C2 00 03 1C 01 7E 00 0F 08 BB 04 3D 10 F0
+ 39 03 01
+ 39 FF AA 55 A5 80
+ 39 6F 1D
+ 39 F2 05
+ 39 F0 55 AA 52 08 07
+ 39 C0 01
+ 39 C1 00
+ 39 C2 00
+ 39 C3 00
+ 39 C4 00
+ 39 C5 00
+ 39 C6 00
+ 39 C7 00
+ 39 C8 00
+ 39 C9 00
+ 39 CA 00
+ 39 CB 00
+ 39 CC 00
+ 39 51 07 FF 03 FF
+ 39 53 20
+ 39 F0 55 AA 52 08 00
+ 39 C0 7E B3 21
+ 39 6F 01
+ 39 C0 B3
+ 39 6F 11
+ 39 C0 30
+ 39 6F 06
+ 39 B5 2C 11 32
+ 39 B2 19
+ 39 6F 02
+ 39 B2 08 08
+ 39 35 00
+ 39 2A 00 00 04 37
+ 39 2B 00 00 09 5F
+ 39 2F 01
+ 39 5F 01
+ 39 2C 00
+ 39 F0 55 AA 52 08 01
+ 39 C3 94 01 8F D0 22 02 00
+ 39 F0 55 AA 52 08 08
+ 39 E2 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+ 39 E3 E8 46 62 88 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FC
+ 39 E4 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+ 39 E5 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+ 39 E6 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+ 39 E7 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+ 39 6F 04
+ 39 C1 00
+ 39 6F 03
+ 39 C1 02
+ 39 CE 12 00 0B 01 0B 6F 00 6F 38 00 38 3A 00 3A 26 00 26 26 00 26 20 00 20 20 00 20 20
+ 39 6F 09
+ 39 D5 00 00 00 00 00 00 00 00
+ 39 F0 55 AA 52 08 01
+ 39 CE 08
+ 05 11
+ FF 78
+ 39 F0 55 AA 52 08 08
+ 39 E1 63 00 73 00 00
+ 05 29
+ 39 F0 55 AA 52 08 01
+ 39 CE 00
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 0A
+ 05 10
+ FF 64
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>15</BacklightDefault>
+ <DisplayResetInfo>0 2000 2000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_L9_42_02_0a_amoled_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_L9_42_02_0a_amoled_dsc_cmd.xml
new file mode 100644
index 0000000..a051b0c
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_L9_42_02_0a_amoled_dsc_cmd.xml
@@ -0,0 +1,116 @@
+<?xml version=\"1.0\" encoding=\"utf-8\"?>
+<PanelDescription>l9 42 02 0a Single DSI Cmd Mode AMOLED Panel with DSC (1080x2400 24bpp)</PanelDescription>
+<Group id=\"Active Timing\">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>32</HorizontalFrontPorch>
+ <HorizontalBackPorch>32</HorizontalBackPorch>
+ <HorizontalSyncPulse>32</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2400</VerticalActive>
+ <VerticalFrontPorch>1300</VerticalFrontPorch>
+ <VerticalBackPorch>1335</VerticalBackPorch>
+ <VerticalSyncPulse>32</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIFlags>0x8</DSIFlags>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>8</DSIDSCProfileID>
+ <DSIDSCSliceWidth>1080</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>12</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>1</DSIDSCSlicePerPacket>
+ <DSIBitClockFrequency>831000000</DSIBitClockFrequency>
+ <DSILP11AtInit>True</DSILP11AtInit>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2400</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2400</DSITEvSyncInitVal>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 FF AA 55 A5 80
+ 39 6F 1D
+ 39 F2 05
+ 39 F0 55 AA 52 08 00
+ 39 6F 01
+ 39 CA AA
+ 39 6F 01
+ 39 C0 B3
+ 39 6F 11
+ 39 C0 30
+ 39 6F 1C
+ 39 C0 03 12
+ 39 3B 00 14 00 12
+ 39 90 01
+ 39 91 AB 28 00 0C C2 00 03 1C 01 7E 00 0F 08 BB 04 3D 10 F0
+ 39 03 01
+ 05 2C
+ 39 F0 55 AA 52 08 07
+ 39 C0 01
+ 39 53 20
+ 39 F0 55 AA 52 08 00
+ 39 6F 02
+ 39 B2 08 08
+ 39 35 00
+ 39 2A 00 00 04 37
+ 39 2B 00 00 09 5F
+ 39 F0 55 AA 52 08 01
+ 39 C3 94 01 8C D0 22 02 00
+ 39 2F 02
+ 39 5F 01
+ 39 F0 55 AA 52 08 00
+ 39 6F 09
+ 39 C0 00
+ 39 F0 55 AA 52 08 02
+ 39 CC 30
+ 39 CE 01
+ FF 14
+ 39 CC 00
+ 39 F0 55 AA 52 08 01
+ 39 CE 08
+ 05 11
+ FF 78
+ 05 29
+ 39 F0 55 AA 52 08 01
+ 39 CE 00
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 0A
+ 05 10
+ FF 78
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>15</BacklightDefault>
+ <DisplayResetInfo>0 2000 2000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_M20_36_02_0a_amoled_dsc_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_M20_36_02_0a_amoled_dsc_vid.xml
new file mode 100644
index 0000000..b819148
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_M20_36_02_0a_amoled_dsc_vid.xml
@@ -0,0 +1,161 @@
+<?xml version=\"1.0\" encoding=\"utf-8\"?>
+<PanelDescription>m20 36 02 0a Single DSI Vid Mode AMOLED Panel with DSC (1080x2400 24bpp)</PanelDescription>
+<Group id=\"Active Timing\">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>48</HorizontalFrontPorch>
+ <HorizontalBackPorch>64</HorizontalBackPorch>
+ <HorizontalSyncPulse>4</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2400</VerticalActive>
+ <VerticalFrontPorch>20</VerticalFrontPorch>
+ <VerticalBackPorch>10</VerticalBackPorch>
+ <VerticalSyncPulse>2</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>8</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>1</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x780000</DSIRefreshRate>
+ <DSIBitClockFrequency>833000000</DSIBitClockFrequency>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>2</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>8</DSIDSCProfileID>
+ <DSIDSCSliceWidth>540</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>20</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>2</DSIDSCSlicePerPacket>
+ <DSILP11AtInit>True</DSILP11AtInit>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+ <DSITimingCLKZeroOverride>True</DSITimingCLKZeroOverride>
+ <DSITimingCLKZeroValue>0x1d</DSITimingCLKZeroValue>
+ <DSITimingCLKPrepareOverride>True</DSITimingCLKPrepareOverride>
+ <DSITimingCLKPrepareValue>0x07</DSITimingCLKPrepareValue>
+ <DSITimingCLKTrailOverride>True</DSITimingCLKTrailOverride>
+ <DSITimingCLKTrailValue>0x07</DSITimingCLKTrailValue>
+ <DSITimingHSExitOverride>True</DSITimingHSExitOverride>
+ <DSITimingHSExitValue>0x17</DSITimingHSExitValue>
+ <DSITimingHSZeroOverride>True</DSITimingHSZeroOverride>
+ <DSITimingHSZeroValue>0x16</DSITimingHSZeroValue>
+ <DSITimingHSPrepareOverride>True</DSITimingHSPrepareOverride>
+ <DSITimingHSPrepareValue>0x07</DSITimingHSPrepareValue>
+ <DSITimingHSTrailOverride>True</DSITimingHSTrailOverride>
+ <DSITimingHSTrailValue>0x07</DSITimingHSTrailValue>
+ <DSITimingHSRequestOverride>True</DSITimingHSRequestOverride>
+ <DSITimingHSRequestValue>0x08</DSITimingHSRequestValue>
+ <DSITimingTAGoOverride>True</DSITimingTAGoOverride>
+ <DSITimingTAGoValue>0x02</DSITimingTAGoValue>
+ <DSITimingTAGetOverride>True</DSITimingTAGetOverride>
+ <DSITimingTAGetValue>0x04</DSITimingTAGetValue>
+ <DSITimingCLKPreOverride>True</DSITimingCLKPreOverride>
+ <DSITimingCLKPreValue>0x19</DSITimingCLKPreValue>
+ <DSITimingCLKPostOverride>True</DSITimingCLKPostOverride>
+ <DSITimingCLKPostValue>0x0C</DSITimingCLKPostValue>
+</Group>
+<DSIInitSequence>
+ 39 FF AA 55 A5 80
+ 39 6F 17
+ 39 F4 02
+ 39 FF AA 55 A5 81
+ 39 6F 13
+ 39 F9 01
+ 39 17 03
+ 39 71 00
+ 39 8D 00 00 04 37 00 00 09 5F
+ 39 FF AA 55 A5 81
+ 39 6F 3C
+ 39 F5 81
+ 39 F0 55 AA 52 08 01
+ 39 6F 03
+ 39 C7 07
+ 39 F0 55 AA 52 08 00
+ 39 B9 00 04 38
+ 39 BD 09 60
+ 39 2A 00 00 04 37
+ 39 2B 00 00 09 5F
+ 39 90 03 03
+ 39 91 AB A8 00 14 D2 00 02 25 01 D5 00 07 05 7A 05 16 10 F0
+ 39 93 AB A8 00 14 D2 00 02 25 01 D5 00 07 05 7A 05 16 10 F0
+ 39 95 AB A8 00 14 D2 00 02 25 01 D5 00 07 05 7A 05 16 10 F0
+ 39 97 AB A8 00 14 D2 00 02 25 01 D5 00 07 05 7A 05 16 10 F0
+ 39 53 20
+ 39 3B 00 0C 00 14
+ 39 35 00
+ 39 51 00 00 00 00 00 00
+ 39 F0 55 AA 52 08 00
+ 39 B2 08
+ 39 6F 05
+ 39 B2 04 04
+ 39 2F 00
+ 39 5F 01
+ 39 26 00
+ 39 F0 55 AA 52 08 00
+ 39 6F 03
+ 39 C0 20
+ 39 F0 55 AA 52 08 00
+ 39 BE 47 00
+ 39 6F 05
+ 39 BE 18
+ 39 6F 0F
+ 39 BE FB FB
+ 39 FF AA 55 A5 80
+ 39 6F 31
+ 39 FC 30
+ 39 F0 55 AA 52 08 01
+ 39 6F 0A
+ 39 E4 90
+ 39 F0 55 AA 52 08 01
+ 39 E8 30
+ 39 FF AA 55 A5 84
+ 39 6F 21
+ 39 F4 FF FF F9 FF FF FF
+ 39 6F 9C
+ 39 F4 FF C0
+ 39 53 20
+ 05 11
+ FF 78
+ 05 29
+ 39 F0 55 AA 52 08 01
+ 39 6F 03
+ 39 C7 47
+ 39 F0 55 AA 52 08 00
+ 39 BE 47 C5
+ 39 F0 55 AA 52 00 00
+ 39 FF AA 55 A5 00
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 14
+ 05 10
+ FF 64
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>15</BacklightDefault>
+ <DisplayResetInfo>0 2000 2000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_M20_42_0d_0b_amoled_dsc_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_M20_42_0d_0b_amoled_dsc_vid.xml
new file mode 100644
index 0000000..0c7f32e
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_M20_42_0d_0b_amoled_dsc_vid.xml
@@ -0,0 +1,137 @@
+<?xml version=\"1.0\" encoding=\"utf-8\"?>
+<PanelDescription>m20 42 0d 0b Single DSI Vid Mode AMOLED Panel with DSC (1080x2400 24bpp)</PanelDescription>
+<Group id=\"Active Timing\">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>48</HorizontalFrontPorch>
+ <HorizontalBackPorch>64</HorizontalBackPorch>
+ <HorizontalSyncPulse>4</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2400</VerticalActive>
+ <VerticalFrontPorch>20</VerticalFrontPorch>
+ <VerticalBackPorch>8</VerticalBackPorch>
+ <VerticalSyncPulse>4</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>8</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>1</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x780000</DSIRefreshRate>
+ <DSIBitClockFrequency>833000000</DSIBitClockFrequency>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>2</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>8</DSIDSCProfileID>
+ <DSIDSCSliceWidth>540</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>12</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>2</DSIDSCSlicePerPacket>
+ <DSILP11AtInit>True</DSILP11AtInit>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+ <DSITimingCLKZeroOverride>True</DSITimingCLKZeroOverride>
+ <DSITimingCLKZeroValue>0x1d</DSITimingCLKZeroValue>
+ <DSITimingCLKPrepareOverride>True</DSITimingCLKPrepareOverride>
+ <DSITimingCLKPrepareValue>0x07</DSITimingCLKPrepareValue>
+ <DSITimingCLKTrailOverride>True</DSITimingCLKTrailOverride>
+ <DSITimingCLKTrailValue>0x07</DSITimingCLKTrailValue>
+ <DSITimingHSExitOverride>True</DSITimingHSExitOverride>
+ <DSITimingHSExitValue>0x17</DSITimingHSExitValue>
+ <DSITimingHSZeroOverride>True</DSITimingHSZeroOverride>
+ <DSITimingHSZeroValue>0x16</DSITimingHSZeroValue>
+ <DSITimingHSPrepareOverride>True</DSITimingHSPrepareOverride>
+ <DSITimingHSPrepareValue>0x07</DSITimingHSPrepareValue>
+ <DSITimingHSTrailOverride>True</DSITimingHSTrailOverride>
+ <DSITimingHSTrailValue>0x07</DSITimingHSTrailValue>
+ <DSITimingHSRequestOverride>True</DSITimingHSRequestOverride>
+ <DSITimingHSRequestValue>0x08</DSITimingHSRequestValue>
+ <DSITimingTAGoOverride>True</DSITimingTAGoOverride>
+ <DSITimingTAGoValue>0x02</DSITimingTAGoValue>
+ <DSITimingTAGetOverride>True</DSITimingTAGetOverride>
+ <DSITimingTAGetValue>0x04</DSITimingTAGetValue>
+ <DSITimingCLKPreOverride>True</DSITimingCLKPreOverride>
+ <DSITimingCLKPreValue>0x19</DSITimingCLKPreValue>
+ <DSITimingCLKPostOverride>True</DSITimingCLKPostOverride>
+ <DSITimingCLKPostValue>0x0C</DSITimingCLKPostValue>
+</Group>
+<DSIInitSequence>
+ 15 53 20
+ 39 51 00 00
+ 15 6F 01
+ 15 03 01
+ 15 35 00
+ 15 6C 02
+ 39 70 12 00 00 AB 30 80 09 60 04 38 00 0C 02 1C 02 1C 02 00 02 0E 00 20 01 1F 00 07 00 0C 08 BB 08 7A 18 00 10 F0 07 10 20 00 06 0F 0F 33 0E 1C 2A 38 46 54 62 69 70 77 79 7B 7D 7E 02 02 22 00 2A 40 2A BE 3A FC 3A FA 3A F8 3B 38 3B 78 43 B6 4B B6 4B F6 4B F4 64 34 84 74 00 00 00 00 00 00
+ 15 59 09
+ 39 F0 AA 10
+ 15 65 04
+ 15 CF 7F
+ 39 F0 AA 18
+ 15 B0 13
+ 15 B2 13
+ 39 FF 5A 81
+ 15 65 03
+ 15 F4 03
+ 15 65 08
+ 39 F6 51 44
+ 39 F0 AA 13
+ 15 C8 04
+ 15 D0 04
+ 15 E0 04
+ 39 FF 5A 80
+ 15 65 0E
+ 15 F9 B9
+ 15 55 00
+ 39 F0 AA 11
+ 39 BA 82 10
+ 15 65 01
+ 15 B0 81
+ 15 57 00
+ 39 F0 AA 19
+ 39 D1 00 04 04 06 07 08 08 09 00 FE FC FA FA F9 F7 F7 00 04 04 06 07 08 08 09 00 FE FC FA FA F9 F7 F7 00 04 04 06 07 08 08 09 00 FE FC FA FA F9 F7 F7
+ 39 D2 00 04 04 07 07 09 09 0A 00 FC FC FA FA F9 F7 F7 00 04 04 07 07 09 09 0A 00 FC FC FA FA F9 F7 F7 00 04 04 07 07 09 09 0A 00 FC FC FA FA F9 F7 F7
+ 39 D4 00 00 00 00 00 FF FF FF 00 01 01 01 02 02 03 03 00 00 00 00 00 FF FF FF 00 01 01 01 02 02 03 03 00 00 00 00 00 FF FF FF 00 01 01 01 02 02 03 03
+ 39 D5 00 FE FE FE FF FF FF FF 00 01 01 01 02 02 03 03 00 FE FE FE FF FF FF FF 00 01 01 01 02 02 03 03 00 FE FE FE FF FF FF FF 00 01 01 01 02 02 03 03
+ 39 D6 00 03 02 02 01 00 00 00 00 00 FF FF 00 00 00 00 00 03 02 02 01 00 00 00 00 00 FF FF 00 00 00 00 00 03 02 02 01 00 00 00 00 00 FF FF 00 00 00 00
+ 39 F0 AA 10
+ 39 D0 84 35
+ 39 FF 5A 00
+ 39 F0 AA 00
+ 05 11
+ FF 78
+ 05 29
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 14
+ 05 10
+ FF 64
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>15</BacklightDefault>
+ <DisplayResetInfo>0 2000 2000 20000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_boe_amoled_fhd_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_boe_amoled_fhd_dsc_cmd.xml
new file mode 100644
index 0000000..2a4898d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_boe_amoled_fhd_dsc_cmd.xml
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>BOE sw43404 AMOLED fhd</PanelName>
+<PanelDescription>BOE Single DSI Cmd Mode AMOLED Panel with DSC (1080x2160 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>160</HorizontalFrontPorch>
+ <HorizontalBackPorch>72</HorizontalBackPorch>
+ <HorizontalSyncPulse>16</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2160</VerticalActive>
+ <VerticalFrontPorch>8</VerticalFrontPorch>
+ <VerticalBackPorch>8</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIDisableEoTAfterHSXfer>True</DSIDisableEoTAfterHSXfer>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>2</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2160</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2160</DSITEvSyncInitVal>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>7</DSIDSCProfileID>
+ <DSIDSCSliceWidth>540</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>270</DSIDSCSliceHeight>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+39 B0 A5 00
+07 01 00
+0a 11 00 00 89 30 80 08 70 04 38 02 1c 02 1c 02 1c 02 00 02 0e 00 20 34 29 00 07 00 0C 00 2e 00 31 18 00 10 F0 03 0C 20 00 06 0B 0B 33 0E 1C 2A 38 46 54 62 69 70 77 79 7B 7D 7E 01 02 01 00 09 40 09 BE 19 FC 19 FA 19 F8 1A 38 1A 78 1A B6 2A F6 2B 34 2B 74 3B 74 6B F4 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+39 b0 a5 00
+15 5e 10
+39 b9 bf 11 40 00 30
+39 F8 00 08 10 08 2D 00 00 2D
+15 55 08
+05 11 00
+FF 1E
+15 3D 01
+39 B0 a5 00
+05 35 00
+FF 78
+05 29 00
+FF 3C
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultHigh>0x1A</TLMMGPIODefaultHigh>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightBitWidth>10</BacklightBitWidth>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_boe_amoled_wqhd_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_boe_amoled_wqhd_dsc_cmd.xml
new file mode 100644
index 0000000..acbcf26
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_boe_amoled_wqhd_dsc_cmd.xml
@@ -0,0 +1,83 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>BOE AMOLED</PanelName>
+<PanelDescription>BOE Single DSI Cmd Mode AMOLED Panel with DSC (1440x2880 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1440</HorizontalActive>
+ <HorizontalFrontPorch>60</HorizontalFrontPorch>
+ <HorizontalBackPorch>30</HorizontalBackPorch>
+ <HorizontalSyncPulse>12</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2880</VerticalActive>
+ <VerticalFrontPorch>8</VerticalFrontPorch>
+ <VerticalBackPorch>8</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>2</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2880</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2880</DSITEvSyncInitVal>
+ <DSIDisableEoTAfterHSXfer>True</DSIDisableEoTAfterHSXfer>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>7</DSIDSCProfileID>
+ <DSIDSCSliceWidth>720</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>180</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>1</DSIDSCSlicePerPacket>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 B0 A5 00
+ 39 5C 42 00
+ 07 01 00
+ 0A 11 00 00 89 30 80 0B 40 05 A0 05 A0 02 D0 02 D0 02 00 02 68 00 20 9A DB 00 0A 00 0C 00 12 00 0E 18 00 10 F0 03 0C 20 00 06 0B 0B 33 0E 1C 2A 38 46 54 62 69 70 77 79 7B 7D 7E 01 02 01 00 09 40 09 BE 19 FC 19 FA 19 F8 1A 38 1A 78 1A B6 2A F6 2B 34 2B 74 3B 74 6B F4 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+ 39 B0 A5 00
+ 39 F8 00 08 10 08 2D 00 00 2D
+ 15 55 08
+ 05 11 00
+ FF 1E
+ 39 B0 A5 00
+ 15 E0 18
+ 39 C0 00 53 6F 51 50 51 34 4F 5A 33 19
+ 05 35 00
+ FF 78
+ 05 29 00
+ FF 3C
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultHigh>0x1A</TLMMGPIODefaultHigh>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightBitWidth>10</BacklightBitWidth>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_boe_amoled_wqhd_dsc_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_boe_amoled_wqhd_dsc_vid.xml
new file mode 100644
index 0000000..37e3dbd
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_boe_amoled_wqhd_dsc_vid.xml
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>BOE AMOLED</PanelName>
+<PanelDescription>BOE Single DSI Video Mode AMOLED Panel with DSC (1440x2880 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1440</HorizontalActive>
+ <HorizontalFrontPorch>10</HorizontalFrontPorch>
+ <HorizontalBackPorch>10</HorizontalBackPorch>
+ <HorizontalSyncPulse>12</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2880</VerticalActive>
+ <VerticalFrontPorch>10</VerticalFrontPorch>
+ <VerticalBackPorch>10</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>8</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>1</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIDisableEoTAfterHSXfer>True</DSIDisableEoTAfterHSXfer>
+ <DSIDynamicRefreshRates>0x3B8000 0x3BC000 0x3C0000</DSIDynamicRefreshRates>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>7</DSIDSCProfileID>
+ <DSIDSCSliceWidth>720</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>180</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>2</DSIDSCSlicePerPacket>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 B0 A5 00
+ 07 01 00
+ 39 B2 00 5D 04 80 49
+ 15 3D 10
+ 15 36 00
+ 15 55 08
+ 39 F8 00 08 10 08 2D 00 00 2D
+ 39 51 00 00
+ FF 3C
+ 05 11 00
+ FF 50
+ 39 B0 34 04
+ 39 C1 00 00 00 46
+ 39 B0 A5 00
+ 0A 11 00 00 89 30 80 0B 40 05 A0 02 D0 02 D0 02 D0 02 00 02 68 00 20 4E A8 00 0A 00 0C 00 23 00 1C 18 00 10 F0 03 0C 20 00 06 0B 0B 33 0E 1C 2A 38 46 54 62 69 70 77 79 7B 7D 7E 01 02 01 00 09 40 09 BE 19 FC 19 FA 19 F8 1A 38 1A 78 1A B6 2A F6 2B 34 2B 74 3B 74 6B F4 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+ 39 B0 A5 00
+ 15 E0 18
+ 39 C0 00 53 6F 51 50 51 34 4F 5A 33 19
+ 05 29 00
+ FF 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultHigh>0x1A</TLMMGPIODefaultHigh>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightBitWidth>10</BacklightBitWidth>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_120hz_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_120hz_vid.xml
new file mode 100644
index 0000000..d349889
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_120hz_vid.xml
@@ -0,0 +1,298 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelDescription>NT36672e DSI Video Mode Panel (1080x2408 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>76</HorizontalFrontPorch>
+ <HorizontalBackPorch>60</HorizontalBackPorch>
+ <HorizontalSyncPulse>10</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2408</VerticalActive>
+ <VerticalFrontPorch>46</VerticalFrontPorch>
+ <VerticalBackPorch>10</VerticalBackPorch>
+ <VerticalSyncPulse>10</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>8</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>1</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>2</DSITrafficMode>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>4</DSIDSCProfileID>
+ <DSIDSCSliceWidth>540</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>8</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>2</DSIDSCSlicePerPacket>
+ <DSILanes>4</DSILanes>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate>0x780000</DSIRefreshRate>
+ <DSIDynamicRefreshRates>0x770000 0x778000 0x780000</DSIDynamicRefreshRates>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 15 FB 01
+ 15 B0 00
+ 15 C0 03
+ 39 C1 89 28 00 08 00 AA 02 0E 00 2B 00 07 0D B7 0C B7
+ 39 C2 1B A0
+ 15 FF 20
+ 15 FB 01
+ 15 01 66
+ 15 06 40
+ 15 07 38
+ 15 2F 83
+ 15 69 91
+ 15 95 D1
+ 15 96 D1
+ 15 F2 64
+ 15 F4 64
+ 15 F6 64
+ 15 F8 64
+ 15 89 1C
+ 15 8A 1C
+ 15 8B 1C
+ 15 8C 1C
+ 15 FF 24
+ 15 FB 01
+ 15 01 0F
+ 15 03 0C
+ 15 05 1D
+ 15 08 2F
+ 15 09 2E
+ 15 0A 2D
+ 15 0B 2C
+ 15 11 17
+ 15 12 13
+ 15 13 15
+ 15 15 14
+ 15 16 16
+ 15 17 18
+ 15 1B 01
+ 15 1D 1D
+ 15 20 2F
+ 15 21 2E
+ 15 22 2D
+ 15 23 2C
+ 15 29 17
+ 15 2A 13
+ 15 2B 15
+ 15 2F 14
+ 15 30 16
+ 15 31 18
+ 15 32 04
+ 15 34 10
+ 15 35 1F
+ 15 36 1F
+ 15 4D 14
+ 15 4E 36
+ 15 4F 36
+ 15 53 36
+ 15 71 30
+ 15 79 11
+ 15 7A 82
+ 15 7B 8F
+ 15 7D 04
+ 15 80 04
+ 15 81 04
+ 15 82 13
+ 15 84 31
+ 15 85 00
+ 15 86 00
+ 15 87 00
+ 15 90 13
+ 15 92 31
+ 15 93 00
+ 15 94 00
+ 15 95 00
+ 15 9C F4
+ 15 9D 01
+ 15 A0 0F
+ 15 A2 0F
+ 15 A3 02
+ 15 A4 04
+ 15 A5 04
+ 15 C4 40
+ 15 C6 C0
+ 15 C9 00
+ 15 D9 80
+ 15 E9 02
+ 15 FF 25
+ 15 FB 01
+ 15 19 E4
+ 15 21 40
+ 15 66 D8
+ 15 68 50
+ 15 69 10
+ 15 6B 00
+ 15 6D 0D
+ 15 6E 48
+ 15 72 41
+ 15 73 4A
+ 15 74 D0
+ 15 77 62
+ 15 79 81
+ 15 7D 03
+ 15 7E 15
+ 15 7F 00
+ 15 84 4D
+ 15 CF 80
+ 15 D6 80
+ 15 D7 80
+ 15 EF 20
+ 15 F0 84
+ 15 FF 26
+ 15 FB 01
+ 15 80 05
+ 15 81 0F
+ 15 83 01
+ 15 84 03
+ 15 85 01
+ 15 86 03
+ 15 87 01
+ 15 88 05
+ 15 8A 1A
+ 15 8B 11
+ 15 8C 24
+ 15 8E 42
+ 15 8F 11
+ 15 90 11
+ 15 91 11
+ 15 9A 80
+ 15 9B 04
+ 15 9C 00
+ 15 9D 00
+ 15 9E 00
+ 15 FF 27
+ 15 FB 01
+ 15 01 68
+ 15 20 81
+ 15 21 6A
+ 15 25 81
+ 15 26 94
+ 15 6E 00
+ 15 6F 00
+ 15 70 00
+ 15 71 00
+ 15 72 00
+ 15 75 00
+ 15 76 00
+ 15 77 00
+ 15 7D 09
+ 15 7E 67
+ 15 80 23
+ 15 82 09
+ 15 83 67
+ 15 88 01
+ 15 89 10
+ 15 A5 10
+ 15 A6 23
+ 15 A7 01
+ 15 B6 40
+ 15 FF 2A
+ 15 FB 01
+ 15 00 91
+ 15 03 20
+ 15 07 50
+ 15 0A 70
+ 15 0C 04
+ 15 0D 40
+ 15 0F 01
+ 15 11 E0
+ 15 15 0F
+ 15 16 A4
+ 15 19 0F
+ 15 1A 78
+ 15 1B 23
+ 15 1D 36
+ 15 1E 3E
+ 15 1F 3E
+ 15 20 3E
+ 15 28 FD
+ 15 29 12
+ 15 2A E1
+ 15 2D 0A
+ 15 30 49
+ 15 33 96
+ 15 34 FF
+ 15 35 40
+ 15 36 DE
+ 15 37 F9
+ 15 38 45
+ 15 39 D9
+ 15 3A 49
+ 15 4A F0
+ 15 FF 20
+ 15 FB 01
+ 39 B0 00 00 00 17 00 46 00 63 00 81 00 96 00 AB 00 BD
+ 39 B1 00 CF 01 03 01 2F 01 6E 01 9D 01 E7 02 22 02 24
+ 39 B2 02 5D 02 9B 02 C4 02 F9 03 1B 03 48 03 56 03 65
+ 39 B3 03 75 03 87 03 9B 03 B1 03 CA 03 D7 00 00
+ 39 B4 00 00 00 19 00 4B 00 69 00 87 00 9C 00 B2 00 C3
+ 39 B5 00 D5 01 0B 01 35 01 73 01 A3 01 EC 02 27 02 29
+ 39 B6 02 60 02 9F 02 C7 02 FB 03 1D 03 4C 03 5A 03 69
+ 39 B7 03 7A 03 8C 03 A0 03 B5 03 CB 03 D7 00 00
+ 39 B8 00 00 00 19 00 4D 00 6A 00 87 00 9C 00 B1 00 C2
+ 39 B9 00 D3 01 08 01 32 01 70 01 9F 01 E8 02 23 02 25
+ 39 BA 02 5C 02 9B 02 C3 02 F8 03 1A 03 4C 03 5B 03 6B
+ 39 BB 03 7D 03 92 03 A7 03 BB 03 CE 03 D7 00 00
+ 15 FF 21
+ 15 FB 01
+ 39 B0 00 00 00 17 00 46 00 63 00 81 00 96 00 AB 00 BD
+ 39 B1 00 CF 01 03 01 2F 01 6E 01 9D 01 E7 02 22 02 24
+ 39 B2 02 5D 02 9B 02 C4 02 F9 03 1B 03 48 03 56 03 65
+ 39 B3 03 75 03 87 03 9B 03 B1 03 CA 03 D7 00 00
+ 39 B4 00 00 00 19 00 4B 00 69 00 87 00 9C 00 B2 00 C3
+ 39 B5 00 D5 01 0B 01 35 01 73 01 A3 01 EC 02 27 02 29
+ 39 B6 02 60 02 9F 02 C7 02 FB 03 1D 03 4C 03 5A 03 69
+ 39 B7 03 7A 03 8C 03 A0 03 B5 03 CB 03 D7 00 00
+ 39 B8 00 00 00 19 00 4D 00 6A 00 87 00 9C 00 B1 00 C2
+ 39 B9 00 D3 01 08 01 32 01 70 01 9F 01 E8 02 23 02 25
+ 39 BA 02 5C 02 9B 02 C3 02 F8 03 1A 03 4C 03 5B 03 6B
+ 39 BB 03 7D 03 92 03 A7 03 BB 03 CE 03 D7 00 00
+ 15 FF 10
+ 15 FF F0
+ 15 FB 01
+ 15 5A 00
+ 15 FF 10
+ 15 FF 10
+ 15 FB 01
+ 15 51 FF
+ 15 53 2C
+ 15 55 01
+ 05 11
+ FF C8
+ 05 29
+ FF 96
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 10
+ 05 10
+ FF 32
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_144hz_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_144hz_vid.xml
new file mode 100644
index 0000000..ce88205
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_144hz_vid.xml
@@ -0,0 +1,368 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelDescription>nt36672e DSI Video Mode Panel (1080x2408 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>30</HorizontalFrontPorch>
+ <HorizontalBackPorch>36</HorizontalBackPorch>
+ <HorizontalSyncPulse>20</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2408</VerticalActive>
+ <VerticalFrontPorch>46</VerticalFrontPorch>
+ <VerticalBackPorch>10</VerticalBackPorch>
+ <VerticalSyncPulse>10</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>8</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>1</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>2</DSITrafficMode>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>4</DSIDSCProfileID>
+ <DSIDSCSliceWidth>540</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>8</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>2</DSIDSCSlicePerPacket>
+ <DSILanes>4</DSILanes>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate>0x900000</DSIRefreshRate>
+ <DSIDynamicRefreshRates>0x8F0000 0x8F4000 0x8F8000 0x8Fc000 0x900000</DSIDynamicRefreshRates>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 29 01 00 00 00 00 02 FF 10
+ 29 FB 01
+ 29 B0 00
+ 29 C1 89 28 00 08 00 AA 02 0E 00 2B 00 07 0D B7 0C B7
+ 29 C2 1B A0
+ 29 E9 01
+ 29 FF 20
+ 29 FB 01
+ 29 01 66
+ 29 06 40
+ 29 07 38
+ 29 1B 01
+ 29 2D 00
+ 29 2F 83
+ 29 69 91
+ 29 95 D1
+ 29 96 D1
+ 29 F2 64
+ 29 F4 64
+ 29 F6 64
+ 29 F8 64
+ 29 FF 23
+ 29 FB 01
+ 29 00 00
+ 29 04 05
+ 29 05 2D
+ 29 06 01
+ 29 07 60
+ 29 08 01
+ 29 09 C7
+ 29 11 01
+ 29 12 95
+ 29 15 68
+ 29 16 0B
+ 29 A0 00
+ 29 30 FF
+ 29 31 F0
+ 29 32 EB
+ 29 33 E5
+ 29 34 DD
+ 29 35 DA
+ 29 36 D5
+ 29 37 D0
+ 29 38 CE
+ 29 39 CD
+ 29 3A CD
+ 29 3B CD
+ 29 3D CB
+ 29 3F CB
+ 29 40 C6
+ 29 41 BF
+ 29 45 FF
+ 29 46 F0
+ 29 47 E8
+ 29 48 CE
+ 29 49 BC
+ 29 4A B8
+ 29 4B B5
+ 29 4C B0
+ 29 4D A8
+ 29 4E A0
+ 29 4F 9B
+ 29 50 98
+ 29 51 98
+ 29 52 88
+ 29 53 80
+ 29 54 7F
+ 29 58 FF
+ 29 59 F6
+ 29 5A ED
+ 29 5B E6
+ 29 5C DF
+ 29 5D D8
+ 29 5E D3
+ 29 5F CE
+ 29 60 C9
+ 29 61 C4
+ 29 62 C1
+ 29 63 BE
+ 29 64 BB
+ 29 65 B8
+ 29 66 B6
+ 29 67 B5
+ 29 FF 24
+ 29 FB 01
+ 29 01 0F
+ 29 03 0C
+ 29 05 1D
+ 29 08 2F
+ 29 09 2E
+ 29 0A 2D
+ 29 0B 2C
+ 29 11 17
+ 29 12 13
+ 29 13 15
+ 29 15 14
+ 29 16 16
+ 29 17 18
+ 29 1B 01
+ 29 1D 1D
+ 29 20 2F
+ 29 21 2E
+ 29 22 2D
+ 29 23 2C
+ 29 29 17
+ 29 2A 13
+ 29 2B 15
+ 29 2F 14
+ 29 30 16
+ 29 31 18
+ 29 32 04
+ 29 34 10
+ 29 35 19
+ 29 36 19
+ 29 4D 11
+ 29 4E 2B
+ 29 4F 2B
+ 29 53 2B
+ 29 71 30
+ 29 79 11
+ 29 7A 82
+ 29 7B 8B
+ 29 7D 04
+ 29 80 04
+ 29 81 04
+ 29 82 13
+ 29 84 31
+ 29 85 00
+ 29 86 00
+ 29 87 00
+ 29 90 13
+ 29 92 31
+ 29 93 00
+ 29 94 00
+ 29 95 00
+ 29 9C F4
+ 29 9D 01
+ 29 A0 0B
+ 29 A2 0B
+ 29 A3 02
+ 29 A4 04
+ 29 A5 04
+ 29 C6 C0
+ 29 C9 00
+ 29 D9 80
+ 29 E9 02
+ 29 FF 25
+ 29 FB 01
+ 29 19 E4
+ 29 21 00
+ 29 66 D8
+ 29 68 50
+ 29 69 10
+ 29 6B 00
+ 29 6D 0D
+ 29 6E 48
+ 29 72 41
+ 29 73 4A
+ 29 74 D0
+ 29 77 62
+ 29 79 81
+ 29 7D 03
+ 29 7E 15
+ 29 7F 00
+ 29 84 4D
+ 29 CF 00
+ 29 D6 80
+ 29 D7 80
+ 29 EF 20
+ 29 F0 84
+ 29 FF 26
+ 29 FB 01
+ 29 80 05
+ 29 81 0B
+ 29 83 01
+ 29 84 03
+ 29 85 01
+ 29 86 03
+ 29 87 01
+ 29 88 06
+ 29 8A 1A
+ 29 8B 11
+ 29 8C 24
+ 29 8E 42
+ 29 8F 11
+ 29 90 11
+ 29 91 11
+ 29 9A 80
+ 29 9B 04
+ 29 9C 00
+ 29 9D 00
+ 29 9E 00
+ 29 FF 27
+ 29 FB 01
+ 29 01 68
+ 29 20 81
+ 29 21 30
+ 29 25 81
+ 29 26 67
+ 29 6E 00
+ 29 6F 00
+ 29 70 00
+ 29 71 00
+ 29 72 00
+ 29 75 00
+ 29 76 00
+ 29 77 00
+ 29 7D 09
+ 29 7E 67
+ 29 80 23
+ 29 82 09
+ 29 83 67
+ 29 88 01
+ 29 89 10
+ 29 A5 10
+ 29 A6 23
+ 29 A7 01
+ 29 B6 40
+ 29 FF 2A
+ 29 FB 01
+ 29 00 91
+ 29 03 20
+ 29 04 78
+ 29 07 60
+ 29 0A 70
+ 29 0C 04
+ 29 0D 40
+ 29 0F 01
+ 29 11 E0
+ 29 15 0F
+ 29 16 03
+ 29 19 0E
+ 29 1A D7
+ 29 1B 14
+ 29 1D 2E
+ 29 1E 33
+ 29 1F 33
+ 29 20 33
+ 29 28 FD
+ 29 29 0D
+ 29 2A B7
+ 29 2D 09
+ 29 2F 02
+ 29 30 47
+ 29 33 D8
+ 29 34 FF
+ 29 35 40
+ 29 36 B8
+ 29 37 F9
+ 29 38 45
+ 29 39 B3
+ 29 3A 47
+ 29 4A F0
+ 29 FF 20
+ 29 FB 01
+ 29 B0 00 E2 00 E9 00 F6 01 01 01 0C 01 15 01 20 01 28
+ 29 B1 01 33 01 51 01 6E 01 9A 01 C0 01 FD 02 34 02 35
+ 29 B2 02 6B 02 A9 02 D1 03 04 03 25 03 51 03 5F 03 6D
+ 29 B3 03 7D 03 90 03 A7 03 BB 03 D4 03 D8 00 00
+ 29 B4 00 AA 00 B3 00 C4 00 D4 00 E2 00 F0 00 FC 01 08
+ 29 B5 01 12 01 39 01 58 01 8C 01 B5 01 F7 02 30 02 31
+ 29 B6 02 68 02 A6 02 CE 03 01 03 23 03 4E 03 5C 03 6A
+ 29 B7 03 7B 03 8E 03 A5 03 BB 03 D4 03 D8 00 00
+ 29 B8 00 00 00 20 00 47 00 65 00 85 00 99 00 AD 00 C0
+ 29 B9 00 D2 01 06 01 30 01 70 01 9F 01 E8 02 25 02 26
+ 29 BA 02 5F 02 9F 02 C7 02 FD 03 20 03 52 03 63 03 67
+ 29 BB 03 78 03 8B 03 A3 03 B9 03 D4 03 D8 00 00
+ 29 FF 21
+ 29 FB 01
+ 29 B0 00 E2 00 E9 00 F6 01 01 01 0C 01 15 01 20 01 28
+ 29 B1 01 33 01 51 01 6E 01 9A 01 C0 01 FD 02 34 02 35
+ 29 B2 02 6B 02 A9 02 D1 03 04 03 25 03 51 03 5F 03 6D
+ 29 B3 03 7D 03 90 03 A7 03 BB 03 D4 03 D8 00 00
+ 29 B4 00 AA 00 B3 00 C4 00 D4 00 E2 00 F0 00 FC 01 08
+ 29 B5 01 12 01 39 01 58 01 8C 01 B5 01 F7 02 30 02 31
+ 29 B6 02 68 02 A6 02 CE 03 01 03 23 03 4E 03 5C 03 6A
+ 29 B7 03 7B 03 8E 03 A5 03 BB 03 D4 03 D8 00 00
+ 29 B8 00 00 00 20 00 47 00 65 00 85 00 99 00 AD 00 C0
+ 29 B9 00 D2 01 06 01 30 01 70 01 9F 01 E8 02 25 02 26
+ 29 BA 02 5F 02 9F 02 C7 02 FD 03 20 03 52 03 63 03 67
+ 29 BB 03 78 03 8B 03 A3 03 B9 03 D4 03 D8 00 00
+ 29 FF C0
+ 29 FB 01
+ 29 9C 11
+ 29 9D 11
+ 29 FF F0
+ 29 FB 01
+ 29 5A 00
+ 29 9F 0C
+ 29 FF D0
+ 29 FB 01
+ 29 53 22
+ 29 54 02
+ 29 FF E0
+ 29 FB 01
+ 29 35 82
+ 29 FF 10
+ 29 FB 01
+ 15 35 01
+ 05 11
+ FF C8
+ 05 29
+ FF 96
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 10
+ 05 10
+ FF 32
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_60hz_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_60hz_vid.xml
new file mode 100644
index 0000000..9914e41
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_60hz_vid.xml
@@ -0,0 +1,318 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelDescription>NT36672e DSI Video Mode Panel (1080x2408 24bpp)PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>76</HorizontalFrontPorch>
+ <HorizontalBackPorch>56</HorizontalBackPorch>
+ <HorizontalSyncPulse>12</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2408</VerticalActive>
+ <VerticalFrontPorch>46</VerticalFrontPorch>
+ <VerticalBackPorch>10</VerticalBackPorch>
+ <VerticalSyncPulse>10</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>8</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>1</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>2</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 FF 10
+ 39 FB 01
+ 39 B0 00
+ 39 C0 00
+ 39 C1 89 28 00 08 00 AA 02 0E 00 2B 00 07 0D B7 0C B7
+ 39 C2 1B A0
+ 39 FF 20
+ 39 FB 01
+ 39 01 66
+ 39 06 40
+ 39 07 38
+ 39 2F 83
+ 39 69 91
+ 39 95 D1
+ 39 96 D1
+ 39 F2 64
+ 39 F3 54
+ 39 F4 64
+ 39 F5 54
+ 39 F6 64
+ 39 F7 54
+ 39 F8 64
+ 39 F9 54
+ 39 FF 24
+ 39 FB 01
+ 39 01 0F
+ 39 03 0C
+ 39 05 1D
+ 39 08 2F
+ 39 09 2E
+ 39 0A 2D
+ 39 0B 2C
+ 39 11 17
+ 39 12 13
+ 39 13 15
+ 39 15 14
+ 39 16 16
+ 39 17 18
+ 39 1B 01
+ 39 1D 1D
+ 39 20 2F
+ 39 21 2E
+ 39 22 2D
+ 39 23 2C
+ 39 29 17
+ 39 2A 13
+ 39 2B 15
+ 39 2F 14
+ 39 30 16
+ 39 31 18
+ 39 32 04
+ 39 34 10
+ 39 35 1F
+ 39 36 1F
+ 39 4D 14
+ 39 4E 36
+ 39 4F 36
+ 39 53 36
+ 39 71 30
+ 39 79 11
+ 39 7A 82
+ 39 7B 8F
+ 39 7D 04
+ 39 80 04
+ 39 81 04
+ 39 82 13
+ 39 84 31
+ 39 85 00
+ 39 86 00
+ 39 87 00
+ 39 90 13
+ 39 92 31
+ 39 93 00
+ 39 94 00
+ 39 95 00
+ 39 9C F4
+ 39 9D 01
+ 39 A0 0F
+ 39 A2 0F
+ 39 A3 02
+ 39 A4 04
+ 39 A5 04
+ 39 C6 C0
+ 39 C9 00
+ 39 D9 80
+ 39 E9 02
+ 39 FF 25
+ 39 FB 01
+ 39 18 22
+ 39 19 E4
+ 39 21 40
+ 39 66 D8
+ 39 68 50
+ 39 69 10
+ 39 6B 00
+ 39 6D 0D
+ 39 6E 48
+ 39 72 41
+ 39 73 4A
+ 39 74 D0
+ 39 77 62
+ 39 79 7E
+ 39 7D 03
+ 39 7E 15
+ 39 7F 00
+ 39 84 4D
+ 39 CF 80
+ 39 D6 80
+ 39 D7 80
+ 39 EF 20
+ 39 F0 84
+ 39 FF 26
+ 39 FB 01
+ 39 81 0F
+ 39 83 01
+ 39 84 03
+ 39 85 01
+ 39 86 03
+ 39 87 01
+ 39 88 05
+ 39 8A 1A
+ 39 8B 11
+ 39 8C 24
+ 39 8E 42
+ 39 8F 11
+ 39 90 11
+ 39 91 11
+ 39 9A 80
+ 39 9B 04
+ 39 9C 00
+ 39 9D 00
+ 39 9E 00
+ 39 FF 27
+ 39 FB 01
+ 39 01 68
+ 39 20 81
+ 39 21 6A
+ 39 25 81
+ 39 26 94
+ 39 6E 00
+ 39 6F 00
+ 39 70 00
+ 39 71 00
+ 39 72 00
+ 39 75 00
+ 39 76 00
+ 39 77 00
+ 39 7D 09
+ 39 7E 67
+ 39 80 23
+ 39 82 09
+ 39 83 67
+ 39 88 01
+ 39 89 10
+ 39 A5 10
+ 39 A6 23
+ 39 A7 01
+ 39 B6 40
+ 39 E5 02
+ 39 E6 D3
+ 39 EB 03
+ 39 EC 28
+ 39 FF 2A
+ 39 FB 01
+ 39 00 91
+ 39 03 20
+ 39 07 50
+ 39 0A 70
+ 39 0C 04
+ 39 0D 40
+ 39 0F 01
+ 39 11 E0
+ 39 15 0F
+ 39 16 A4
+ 39 19 0F
+ 39 1A 78
+ 39 1B 23
+ 39 1D 36
+ 39 1E 3E
+ 39 1F 3E
+ 39 20 3E
+ 39 28 FD
+ 39 29 12
+ 39 2A E1
+ 39 2D 0A
+ 39 30 49
+ 39 33 96
+ 39 34 FF
+ 39 35 40
+ 39 36 DE
+ 39 37 F9
+ 39 38 45
+ 39 39 D9
+ 39 3A 49
+ 39 4A F0
+ 39 7A 09
+ 39 7B 40
+ 39 7F F0
+ 39 83 0F
+ 39 84 A4
+ 39 87 0F
+ 39 88 78
+ 39 89 23
+ 39 8B 36
+ 39 8C 7D
+ 39 8D 7D
+ 39 8E 7D
+ 39 FF 20
+ 39 FB 01
+ 39 B0 00 00 00 17 00 49 00 6A 00 89 00 9F 00 B6 00 C8
+ 39 B1 00 D9 01 10 01 3A 01 7A 01 A9 01 F2 02 2D 02 2E
+ 39 B2 02 64 02 A3 02 CA 03 00 03 1E 03 4A 03 59 03 6A
+ 39 B3 03 7D 03 93 03 AB 03 C8 03 EC 03 FE 00 00
+ 39 B4 00 00 00 1B 00 51 00 71 00 90 00 A7 00 BF 00 D1
+ 39 B5 00 E2 01 1A 01 43 01 83 01 B2 01 FA 02 34 02 36
+ 39 B6 02 6B 02 A8 02 D0 03 03 03 21 03 4D 03 5B 03 6B
+ 39 B7 03 7E 03 94 03 AC 03 C8 03 EC 03 FE 00 00
+ 39 B8 00 00 00 1B 00 51 00 72 00 92 00 A8 00 BF 00 D1
+ 39 B9 00 E2 01 18 01 42 01 81 01 AF 01 F5 02 2F 02 31
+ 39 BA 02 68 02 A6 02 CD 03 01 03 1F 03 4A 03 59 03 6A
+ 39 BB 03 7D 03 93 03 AB 03 C8 03 EC 03 FE 00 00
+ 39 FF 21
+ 39 FB 01
+ 39 B0 00 00 00 17 00 49 00 6A 00 89 00 9F 00 B6 00 C8
+ 39 B1 00 D9 01 10 01 3A 01 7A 01 A9 01 F2 02 2D 02 2E
+ 39 B2 02 64 02 A3 02 CA 03 00 03 1E 03 4A 03 59 03 6A
+ 39 B3 03 7D 03 93 03 AB 03 C8 03 EC 03 FE 00 00
+ 39 B4 00 00 00 1B 00 51 00 71 00 90 00 A7 00 BF 00 D1
+ 39 B5 00 E2 01 1A 01 43 01 83 01 B2 01 FA 02 34 02 36
+ 39 B6 02 6B 02 A8 02 D0 03 03 03 21 03 4D 03 5B 03 6B
+ 39 B7 03 7E 03 94 03 AC 03 C8 03 EC 03 FE 00 00
+ 39 B8 00 00 00 1B 00 51 00 72 00 92 00 A8 00 BF 00 D1
+ 39 B9 00 E2 01 18 01 42 01 81 01 AF 01 F5 02 2F 02 31
+ 39 BA 02 68 02 A6 02 CD 03 01 03 1F 03 4A 03 59 03 6A
+ 39 BB 03 7D 03 93 03 AB 03 C8 03 EC 03 FE 00 00
+ 39 FF 2C
+ 39 FB 01
+ 39 61 1F
+ 39 62 1F
+ 39 7E 03
+ 39 6A 14
+ 39 6B 36
+ 39 6C 36
+ 39 6D 36
+ 39 53 04
+ 39 54 04
+ 39 55 04
+ 39 56 0F
+ 39 58 0F
+ 39 59 0F
+ 39 FF F0
+ 39 FB 01
+ 39 5A 00
+ 15 FF 10
+ 15 FB 01
+ 15 51 FF
+ 15 53 24
+ 15 55 01
+ 05 11
+ FF C8
+ 05 29
+ FF 96
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ FF 10
+ 05 10
+ FF 32
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_nt36860_wqhd_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36860_wqhd_dsc_cmd.xml
new file mode 100644
index 0000000..a48b464
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36860_wqhd_dsc_cmd.xml
@@ -0,0 +1,242 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>NT36860</PanelName>
+<PanelDescription>NT36860 Single DSI CPhy DSC Cmd Mode Panel (1440x2560 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1440</HorizontalActive>
+ <HorizontalFrontPorch>152</HorizontalFrontPorch>
+ <HorizontalBackPorch>32</HorizontalBackPorch>
+ <HorizontalSyncPulse>16</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2560</VerticalActive>
+ <VerticalFrontPorch>10</VerticalFrontPorch>
+ <VerticalBackPorch>6</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSICPhyMode>True</DSICPhyMode>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>4</DSIDSCProfileID>
+ <DSIDSCSliceWidth>720</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>32</DSIDSCSliceHeight>
+ <DSILanes>3</DSILanes>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate>0x390000</DSIRefreshRate>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+ <DSITimingHSZeroOverride>True</DSITimingHSZeroOverride>
+ <DSITimingHSZeroValue>47</DSITimingHSZeroValue>
+ <DSITimingHSTrailOverride>True</DSITimingHSTrailOverride>
+ <DSITimingHSTrailValue>31</DSITimingHSTrailValue>
+</Group>
+<DSIInitSequence>
+ 15 ff d0
+ 15 fb 01
+ 15 ab 70
+ 15 c0 70
+ 15 c1 31
+ 15 c8 40
+ 15 c9 44
+ 15 ff e0
+ 15 fb 01
+ 15 18 00
+ 15 ae 09
+ 15 53 22
+ 15 ff f0
+ 15 fb 01
+ 15 8d 00
+ 15 ce 0a
+ 15 ff 20
+ 15 fb 01
+ 15 00 01
+ 15 01 55
+ 15 02 45
+ 15 05 40
+ 15 06 19
+ 15 07 23
+ 15 97 73
+ 15 98 73
+ 15 99 73
+ 15 9a 73
+ 15 ff 20
+ 15 fb 01
+ 15 0e b0
+ 15 0f b3
+ 15 11 b8
+ 15 13 00
+ 15 ff 24
+ 15 fb 01
+ 15 19 05
+ 15 1a 01
+ 15 1b 01
+ 15 1c 01
+ 15 1d 68
+ 15 1e 6d
+ 15 1f 01
+ 15 20 68
+ 15 2a 2b
+ 15 2b 02
+ 15 2d 02
+ 15 2f 00
+ 15 30 13
+ 15 31 00
+ 15 32 02
+ 15 33 64
+ 15 35 2d
+ 15 36 08
+ 15 37 02
+ 15 38 64
+ 15 59 c4
+ 15 5a c0
+ 15 5d 05
+ 15 5e 14
+ 15 61 01
+ 15 63 07
+ 15 9c 2a
+ 15 9d 0a
+ 15 9e 45
+ 15 a6 f3
+ 15 b3 00
+ 15 b5 53
+ 15 b6 22
+ 15 b7 06
+ 15 b8 17
+ 15 b9 64
+ 15 bb 03
+ 15 bc 17
+ 15 bd 64
+ 15 bf 02
+ 15 c0 02
+ 15 c3 05
+ 15 c4 00
+ 15 c5 00
+ 15 c6 00
+ 15 c7 f0
+ 15 ca 60
+ 15 cd 5b
+ 15 d1 00
+ 15 d8 00
+ 15 d9 00
+ 15 da 00
+ 15 db 02
+ 15 dc 01
+ 15 dd 0f
+ 15 de 0f
+ 15 df 33
+ 15 e2 30
+ 15 e5 8b
+ 15 eb 10
+ 15 f8 00
+ 15 ff 25
+ 15 fb 01
+ 15 00 00
+ 15 01 03
+ 15 02 05
+ 15 03 00
+ 15 04 00
+ 15 05 0b
+ 15 06 0c
+ 15 07 01
+ 15 08 00
+ 15 09 00
+ 15 0a 00
+ 15 0b 00
+ 15 0c 00
+ 15 0d 17
+ 15 0e 15
+ 15 0f 13
+ 15 12 00
+ 15 13 04
+ 15 14 06
+ 15 15 00
+ 15 16 00
+ 15 17 00
+ 15 18 0f
+ 15 19 01
+ 15 1a 10
+ 15 1b 90
+ 15 1c 00
+ 15 1d 00
+ 15 1e 00
+ 15 1f 17
+ 15 20 15
+ 15 21 13
+ 15 26 34
+ 15 27 12
+ 15 28 21
+ 15 29 44
+ 15 c0 00
+ 15 c2 00
+ 15 c3 6a
+ 15 c6 6a
+ 15 c9 00
+ 15 ca 0a
+ 15 cb 00
+ 15 cc 0a
+ 15 d8 90
+ 15 da 90
+ 15 ff 21
+ 15 fb 01
+ 39 e0 22 04 0a 00 06 08 03 05 0b 01 07 09
+ 15 ff d0
+ 15 fb 01
+ 15 97 04
+ 15 c7 00
+ 15 c8 40
+ 15 c9 44
+ 15 90 1f
+ 15 ff 10
+ 15 fb 01
+ 15 ba 03
+ 15 35 00
+ 39 44 05 00
+ 15 bb 10
+ 39 3b 00 0a 00 0a
+ 15 c0 03
+ 39 c1 ab 28 00 20 02 00 02 68 03 87 00 0a 03 19 02 63
+ 39 c2 10 f0
+ 05 11
+ ff 78
+ 15 51 ff
+ 15 53 20
+ 15 ff 10
+ 05 29
+ ff 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultHigh>0x1A</TLMMGPIODefaultHigh>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_nt36860_wqhd_dsc_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36860_wqhd_dsc_vid.xml
new file mode 100644
index 0000000..81dfa1e
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_nt36860_wqhd_dsc_vid.xml
@@ -0,0 +1,240 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>NT36860</PanelName>
+<PanelDescription>NT36860 Single DSI CPhy DSC Video Mode Panel (1440x2560 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1440</HorizontalActive>
+ <HorizontalFrontPorch>152</HorizontalFrontPorch>
+ <HorizontalBackPorch>32</HorizontalBackPorch>
+ <HorizontalSyncPulse>16</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2560</VerticalActive>
+ <VerticalFrontPorch>10</VerticalFrontPorch>
+ <VerticalBackPorch>9</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>8</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>1</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSICPhyMode>True</DSICPhyMode>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>7</DSIDSCProfileID>
+ <DSIDSCSliceWidth>720</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>32</DSIDSCSliceHeight>
+ <DSILanes>3</DSILanes>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate>0x390000</DSIRefreshRate>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+ <DSITimingHSZeroOverride>True</DSITimingHSZeroOverride>
+ <DSITimingHSZeroValue>47</DSITimingHSZeroValue>
+ <DSITimingHSTrailOverride>True</DSITimingHSTrailOverride>
+ <DSITimingHSTrailValue>31</DSITimingHSTrailValue>
+</Group>
+<DSIInitSequence>
+ 15 ff d0
+ 15 fb 01
+ 15 ab 70
+ 15 c0 70
+ 15 c1 31
+ 15 c8 40
+ 15 c9 44
+ 15 ff e0
+ 15 fb 01
+ 15 18 00
+ 15 ae 09
+ 15 53 22
+ 15 ff f0
+ 15 fb 01
+ 15 8d 00
+ 15 ce 0a
+ 15 ff 20
+ 15 fb 01
+ 15 00 01
+ 15 01 55
+ 15 02 45
+ 15 05 40
+ 15 06 19
+ 15 07 23
+ 15 97 73
+ 15 98 73
+ 15 99 73
+ 15 9a 73
+ 15 ff 20
+ 15 fb 01
+ 15 0e b0
+ 15 0f b3
+ 15 11 b8
+ 15 13 00
+ 15 ff 24
+ 15 fb 01
+ 15 19 05
+ 15 1a 01
+ 15 1b 01
+ 15 1c 01
+ 15 1d 68
+ 15 1e 6d
+ 15 1f 01
+ 15 20 68
+ 15 2a 2b
+ 15 2b 02
+ 15 2d 02
+ 15 2f 00
+ 15 30 13
+ 15 31 00
+ 15 32 02
+ 15 33 64
+ 15 35 2d
+ 15 36 08
+ 15 37 02
+ 15 38 64
+ 15 59 c4
+ 15 5a c0
+ 15 5d 05
+ 15 5e 14
+ 15 61 01
+ 15 63 07
+ 15 9c 2a
+ 15 9d 0a
+ 15 9e 45
+ 15 a6 f3
+ 15 b3 00
+ 15 b5 53
+ 15 b6 22
+ 15 b7 06
+ 15 b8 17
+ 15 b9 64
+ 15 bb 03
+ 15 bc 17
+ 15 bd 64
+ 15 bf 02
+ 15 c0 02
+ 15 c3 05
+ 15 c4 00
+ 15 c5 00
+ 15 c6 00
+ 15 c7 f0
+ 15 ca 60
+ 15 cd 5b
+ 15 d1 00
+ 15 d8 00
+ 15 d9 00
+ 15 da 00
+ 15 db 02
+ 15 dc 01
+ 15 dd 0f
+ 15 de 0f
+ 15 df 33
+ 15 e2 30
+ 15 e5 8b
+ 15 eb 10
+ 15 f8 00
+ 15 ff 25
+ 15 fb 01
+ 15 00 00
+ 15 01 03
+ 15 02 05
+ 15 03 00
+ 15 04 00
+ 15 05 0b
+ 15 06 0c
+ 15 07 01
+ 15 08 00
+ 15 09 00
+ 15 0a 00
+ 15 0b 00
+ 15 0c 00
+ 15 0d 17
+ 15 0e 15
+ 15 0f 13
+ 15 12 00
+ 15 13 04
+ 15 14 06
+ 15 15 00
+ 15 16 00
+ 15 17 00
+ 15 18 0f
+ 15 19 01
+ 15 1a 10
+ 15 1b 90
+ 15 1c 00
+ 15 1d 00
+ 15 1e 00
+ 15 1f 17
+ 15 20 15
+ 15 21 13
+ 15 26 34
+ 15 27 12
+ 15 28 21
+ 15 29 44
+ 15 c0 00
+ 15 c2 00
+ 15 c3 6a
+ 15 c6 6a
+ 15 c9 00
+ 15 ca 0a
+ 15 cb 00
+ 15 cc 0a
+ 15 d8 90
+ 15 da 90
+ 15 ff 21
+ 15 fb 01
+ 39 e0 22 04 0a 00 06 08 03 05 0b 01 07 09
+ 15 ff d0
+ 15 fb 01
+ 15 97 04
+ 15 c7 00
+ 15 c8 40
+ 15 c9 44
+ 15 90 1f
+ 15 ff 10
+ 15 fb 01
+ 15 ba 03
+ 15 bb 03
+ 39 3b 00 0a 00 0a
+ 15 c0 03
+ 39 c1 ab 28 00 20 02 00 02 68 03 87 00 0a 03 19 02 63
+ 39 c2 10 f0
+ 05 11
+ ff 78
+ 15 51 ff
+ 15 53 20
+ 15 ff 10
+ 05 29
+ ff 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultHigh>0x1A</TLMMGPIODefaultHigh>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_primary_sim_vdo.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_primary_sim_vdo.xml
new file mode 100644
index 0000000..f599795
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_primary_sim_vdo.xml
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelDescription>Primary Sim Video Panel (1080x1920 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>8</HorizontalFrontPorch>
+ <HorizontalBackPorch>8</HorizontalBackPorch>
+ <HorizontalSyncPulse>8</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>1920</VerticalActive>
+ <VerticalFrontPorch>6</VerticalFrontPorch>
+ <VerticalBackPorch>6</VerticalBackPorch>
+ <VerticalSyncPulse>2</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>8</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>1</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 05 11
+ FF 78
+ 05 29
+ FF 28
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <BacklightBitWidth>11</BacklightBitWidth>
+ <BacklightDefault>50</BacklightDefault>
+ <DisplayResetInfo>0 1000 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_r66451_120hz_fhd_plus_dsc_cmd_cphy.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_r66451_120hz_fhd_plus_dsc_cmd_cphy.xml
new file mode 100644
index 0000000..4cd6e26
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_r66451_120hz_fhd_plus_dsc_cmd_cphy.xml
@@ -0,0 +1,108 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>R66451 Visionox</PanelName>
+<PanelDescription>R66451 Visionox Single DSI DSC Command Mode Amoled Panel (1080x2340 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>96</HorizontalFrontPorch>
+ <HorizontalBackPorch>40</HorizontalBackPorch>
+ <HorizontalSyncPulse>32</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2340</VerticalActive>
+ <VerticalFrontPorch>25</VerticalFrontPorch>
+ <VerticalBackPorch>4</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSICPhyMode>True</DSICPhyMode>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2340</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2340</DSITEvSyncInitVal>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>4</DSIDSCProfileID>
+ <DSIDSCSliceWidth>540</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>20</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>2</DSIDSCSlicePerPacket>
+ <DSILanes>3</DSILanes>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate>0x780000</DSIRefreshRate>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 b0 00
+ 39 c2 09 24 0c 00 00 0c 00 00 00 09 3c
+ 39 d7 00 b9 3c 00 40 04 00 a0 0a 00 40 00 00 00 00 00 00 19 3c 00 40 04 00 a0 0a
+ 39 b0 80
+ 39 de 40 00 18 00 18 00 18 00 18 10 00 18 00 18 00 18 02 00 00
+ 39 b0 04
+ 39 e8 00 02
+ 39 e4 00 08
+ 39 b4 20 1c
+ 39 b6 6c 00 06 23 af 13 1a 05 04 fa 05 20
+ 39 b0 00
+ 39 c4 00 00 00 00 00 00 00 00 10 00 00 02 00 00 00 29 00 01 00 00 00 00 00 00 00 00 00 00 00 22 00 00 00 00 11 00 00 0c 00 00 00 00 30 00 00 00 00 00 00
+ 39 d3 49 00 00 01 1a 15 00 15 07 0f 77 77 77 37 b2 11 00 a0 3c 9a
+ 39 d8 00 00 00 00 00 00 00 00 00 3a 00 3a 00 3a 00 3a 00 3a 05 00 00 00 00 00 00 00 00 00 0f 00 0f 00 00 00 00 00 00 00 00 00 00 00 00 00 0f 00 2f 00 0f 00 20
+ 39 df 50 42 58 81 2d 00 00 00 00 00 00 6b 00 00 00 00 00 00 00 00 01 0f ff d4 0e 00 00 00 00 00 00 0f 53 18 00 0f 00 00 00 00 00 00
+ 39 eb 8b 8b
+ 39 f7 01
+ 39 b0 80
+ 39 e4 34 b4 00 00 00 30 04 0c e2
+ 39 e6 00
+ 39 b0 04
+ 39 df 50 40
+ 39 f3 50 00 00 00 00
+ 39 f2 11
+ 39 f3 01 00 00 00 01
+ 39 f4 00 02
+ 39 f2 19
+ 39 df 50 42
+ 39 35 00
+ 39 2a 00 00 04 37
+ 39 2b 00 00 09 23
+ 05 11
+ ff 78
+ 05 29
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ ff 14
+ 05 10
+ ff 78
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightBitWidth>12</BacklightBitWidth>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_r66451_144hz_fhd_plus_dsc_cmd_cphy.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_r66451_144hz_fhd_plus_dsc_cmd_cphy.xml
new file mode 100644
index 0000000..28492c4
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_r66451_144hz_fhd_plus_dsc_cmd_cphy.xml
@@ -0,0 +1,105 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>R66451 Visionox</PanelName>
+<PanelDescription>R66451 Visionox Single DSI DSC Command Mode Amoled Panel (1080x2340 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>96</HorizontalFrontPorch>
+ <HorizontalBackPorch>40</HorizontalBackPorch>
+ <HorizontalSyncPulse>32</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2340</VerticalActive>
+ <VerticalFrontPorch>25</VerticalFrontPorch>
+ <VerticalBackPorch>4</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSICPhyMode>True</DSICPhyMode>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2340</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2340</DSITEvSyncInitVal>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>4</DSIDSCProfileID>
+ <DSIDSCSliceWidth>540</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>20</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>2</DSIDSCSlicePerPacket>
+ <DSILanes>3</DSILanes>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate>0x900000</DSIRefreshRate>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 b0 04
+ 39 e8 00 02
+ 39 e4 00 08
+ 39 b4 20 1c
+ 39 b6 6c 00 06 23 af 13 1a 05 04 fa 05 20
+ 39 b0 00
+ 39 c4 00 00 00 00 00 00 00 00 10 00 00 02 00 00 00 29 00 01 00 00 00 00 00 00 00 00 00 00 00 22 00 00 00 00 11 00 00 0c 00 00 00 00 30 00 00 00 00 00 00
+ 39 d0 44 44 b2 28 00 28 5a 00 5a 03 0d 01
+ 39 d3 49 00 00 01 1a 15 00 15 07 0f 77 77 77 37 b2 11 00 a0 3c 9a
+ 39 d8 00 00 00 00 00 00 00 00 00 30 00 30 00 30 00 30 00 30 05 00 00 00 00 00 00 00 00 00 0f 00 0f 00 00 00 00 00 00 00 00 00 00 00 00 00 0f 00 2f 00 0f 00 20
+ 39 df 50 42 58 81 2d 00 00 00 00 00 00 6b 00 00 00 00 00 00 00 00 01 0f ff d4 0e 00 00 00 00 00 00 0f 53 18 00 0f 00 00 00 00 00 00
+ 39 eb 8b 8b
+ 39 f7 01
+ 39 b0 80
+ 39 e4 34 b4 00 00 00 30 04 0c e2
+ 39 e6 00
+ 39 b0 04
+ 39 df 50 40
+ 39 f3 50 00 00 00 00
+ 39 f2 11
+ 39 f3 01 00 00 00 01
+ 39 f4 00 02
+ 39 f2 19
+ 39 df 50 42
+ 39 35 00
+ 39 2a 00 00 04 37
+ 39 2b 00 00 09 23
+ 05 11
+ ff 78
+ 05 29
+ ff 14
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ ff 14
+ 05 10
+ ff 78
+</DSITermSequence>
+<Group id='Backlight Configuration'>
+ <BacklightType>3</BacklightType>
+ <BacklightBitWidth>12</BacklightBitWidth>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_sharp_1080p_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_sharp_1080p_cmd.xml
new file mode 100644
index 0000000..a917d25
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_sharp_1080p_cmd.xml
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelDescription>Sharp DSI Command Mode Panel (1080x1920 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>0</HorizontalFrontPorch>
+ <HorizontalBackPorch>0</HorizontalBackPorch>
+ <HorizontalSyncPulse>0</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>1920</VerticalActive>
+ <VerticalFrontPorch>0</VerticalFrontPorch>
+ <VerticalBackPorch>0</VerticalBackPorch>
+ <VerticalSyncPulse>0</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>1</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>1920</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>1920</DSITEvSyncInitVal>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 15 bb 10
+ 15 b0 03
+ 05 11 00
+ ff 78
+ 15 51 ff
+ 15 53 24
+ 15 ff 23
+ 15 08 05
+ 15 46 90
+ 15 ff 10
+ 15 ff f0
+ 15 92 01
+ 15 ff 10
+ 15 35 00
+ 05 29 00
+ ff 64
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultHigh>0x1A</TLMMGPIODefaultHigh>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_sharp_4k_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_sharp_4k_dsc_cmd.xml
new file mode 100644
index 0000000..2d1af52
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_sharp_4k_dsc_cmd.xml
@@ -0,0 +1,86 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>LS055D1SX04</PanelName>
+<PanelDescription>Sharp Dual DSI Command Mode DSC Panel (2160x3840 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>2160</HorizontalActive>
+ <HorizontalFrontPorch>30</HorizontalFrontPorch>
+ <HorizontalBackPorch>100</HorizontalBackPorch>
+ <HorizontalSyncPulse>4</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>3840</VerticalActive>
+ <VerticalFrontPorch>8</VerticalFrontPorch>
+ <VerticalBackPorch>7</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>2</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>3840</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>3840</DSITEvSyncInitVal>
+ <DSICmdModePixelAlignment>1</DSICmdModePixelAlignment>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>4</DSIDSCProfileID>
+ <DSIDSCSliceWidth>1080</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>32</DSIDSCSliceHeight>
+ <DSIControllerMapping>
+ 00 01
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 91 09 20 00 20 02 00 03 1c 04 21 00 0f 03 19 01 97
+ 39 92 10 f0
+ 15 90 03
+ 15 03 01
+ 39 f0 55 aa 52 08 04
+ 15 c0 03
+ 39 f0 55 aa 52 08 07
+ 15 ef 01
+ 39 f0 55 aa 52 08 00
+ 15 b4 01
+ 15 35 00
+ 39 f0 55 aa 52 08 01
+ 39 ff aa 55 a5 80
+ 15 6f 01
+ 15 f3 10
+ 39 ff aa 55 a5 00
+ 05 11
+ ff 78
+ 05 29
+ ff 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultLow>0x1A</TLMMGPIODefaultLow>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_sharp_4k_dsc_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_sharp_4k_dsc_vid.xml
new file mode 100644
index 0000000..2b4a7fb
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_sharp_4k_dsc_vid.xml
@@ -0,0 +1,84 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>LS055D1SX04</PanelName>
+<PanelDescription>Sharp Dual DSI Video Mode Panel with DSC (2160x3840 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>2160</HorizontalActive>
+ <HorizontalFrontPorch>30</HorizontalFrontPorch>
+ <HorizontalBackPorch>100</HorizontalBackPorch>
+ <HorizontalSyncPulse>4</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>3840</VerticalActive>
+ <VerticalFrontPorch>8</VerticalFrontPorch>
+ <VerticalBackPorch>7</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>8</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>1</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>4</DSIDSCProfileID>
+ <DSIDSCSliceWidth>1080</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>32</DSIDSCSliceHeight>
+ <DSILanes>4</DSILanes>
+ <DSIHsaHseAfterVsVe>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSIPhyDCDCMode>True</DSIPhyDCDCMode>
+ <DSIControllerMapping>
+ 00 01
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 39 91 09 20 00 20 02 00 03 1c 04 21 00 0f 03 19 01 97
+ 39 92 10 f0
+ 15 90 03
+ 15 03 01
+ 39 f0 55 aa 52 08 04
+ 15 c0 03
+ 39 f0 55 aa 52 08 07
+ 15 ef 01
+ 39 f0 55 aa 52 08 00
+ 15 b4 10
+ 15 35 00
+ 39 f0 55 aa 52 08 01
+ 39 ff aa 55 a5 80
+ 15 6f 01
+ 15 f3 10
+ 39 ff aa 55 a5 00
+ 05 11
+ ff 78
+ 05 29
+ ff 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultLow>0x1A</TLMMGPIODefaultLow>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_truly_1080p_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_1080p_cmd.xml
new file mode 100644
index 0000000..414cf36
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_1080p_cmd.xml
@@ -0,0 +1,186 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>NT35695b</PanelName>
+<PanelDescription>Truly FHD Command Mode Panel (1080x1920 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1080</HorizontalActive>
+ <HorizontalFrontPorch>120</HorizontalFrontPorch>
+ <HorizontalBackPorch>60</HorizontalBackPorch>
+ <HorizontalSyncPulse>12</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>1920</VerticalActive>
+ <VerticalFrontPorch>12</VerticalFrontPorch>
+ <VerticalBackPorch>2</VerticalBackPorch>
+ <VerticalSyncPulse>2</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>2</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>1920</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>1920</DSITEvSyncInitVal>
+ <DSICmdModePixelAlignment>1</DSICmdModePixelAlignment>
+ <DSITimingMargin>1</DSITimingMargin>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 15 ff 20
+ 15 fb 01
+ 15 00 01
+ 15 01 55
+ 15 02 45
+ 15 03 55
+ 15 05 50
+ 15 06 a8
+ 15 07 ad
+ 15 08 0c
+ 15 0b aa
+ 15 0c aa
+ 15 0e b0
+ 15 0f b3
+ 15 11 28
+ 15 12 10
+ 15 13 01
+ 15 14 4a
+ 15 15 12
+ 15 16 12
+ 15 30 01
+ 15 72 11
+ 15 58 82
+ 15 59 00
+ 15 5a 02
+ 15 5b 00
+ 15 5c 82
+ 15 5d 80
+ 15 5e 02
+ 15 5f 00
+ 15 ff 24
+ 15 fb 01
+ 15 00 01
+ 15 01 0b
+ 15 02 0c
+ 15 03 89
+ 15 04 8a
+ 15 05 0f
+ 15 06 10
+ 15 07 10
+ 15 08 1c
+ 15 09 00
+ 15 0a 00
+ 15 0b 00
+ 15 0c 00
+ 15 0d 13
+ 15 0e 15
+ 15 0f 17
+ 15 10 01
+ 15 11 0b
+ 15 12 0c
+ 15 13 89
+ 15 14 8a
+ 15 15 0f
+ 15 16 10
+ 15 17 10
+ 15 18 1c
+ 15 19 00
+ 15 1a 00
+ 15 1b 00
+ 15 1c 00
+ 15 1d 13
+ 15 1e 15
+ 15 1f 17
+ 15 20 00
+ 15 21 01
+ 15 22 00
+ 15 23 40
+ 15 24 40
+ 15 25 6d
+ 15 26 40
+ 15 27 40
+ 15 29 d8
+ 15 2a 2a
+ 15 4b 03
+ 15 4c 11
+ 15 4d 10
+ 15 4e 01
+ 15 4f 01
+ 15 50 10
+ 15 51 00
+ 15 52 80
+ 15 53 00
+ 15 54 07
+ 15 55 25
+ 15 56 00
+ 15 58 07
+ 15 5b 43
+ 15 5c 00
+ 15 5f 73
+ 15 60 73
+ 15 63 22
+ 15 64 00
+ 15 67 08
+ 15 68 04
+ 15 7a 80
+ 15 7b 91
+ 15 7c d8
+ 15 7d 60
+ 15 93 06
+ 15 94 06
+ 15 8a 00
+ 15 9b 0f
+ 15 b3 c0
+ 15 b4 00
+ 15 b5 00
+ 15 b6 21
+ 15 b7 22
+ 15 b8 07
+ 15 b9 07
+ 15 ba 22
+ 15 bd 20
+ 15 be 07
+ 15 bf 07
+ 15 c1 6d
+ 15 c4 24
+ 15 e3 00
+ 15 ec 00
+ 15 ff 10
+ 15 bb 10
+ 15 35 00
+ 05 11 00
+ ff 78
+ 05 29 00
+ ff 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultLow>0x1A</TLMMGPIODefaultLow>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
+
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_truly_1080p_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_1080p_vid.xml
new file mode 100644
index 0000000..deeee55
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_1080p_vid.xml
@@ -0,0 +1,185 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>NT35695b</PanelName>
+<PanelDescription>Truly FHD Video Mode Panel (1080x1920 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive units="Dot Clocks">1080</HorizontalActive>
+ <HorizontalFrontPorch units="Dot Clocks">120</HorizontalFrontPorch>
+ <HorizontalBackPorch units="Dot Clocks">60</HorizontalBackPorch>
+ <HorizontalSyncPulse units="Dot Clocks">12</HorizontalSyncPulse>
+ <HorizontalSyncSkew units="Dot Clocks">0</HorizontalSyncSkew>
+ <HorizontalLeftBorder units="Dot Clocks">0</HorizontalLeftBorder>
+ <HorizontalRightBorder units="Dot Clocks">0</HorizontalRightBorder>
+ <VerticalActive units="Dot Clocks">1920</VerticalActive>
+ <VerticalFrontPorch units="Lines">12</VerticalFrontPorch>
+ <VerticalBackPorch units="Lines">2</VerticalBackPorch>
+ <VerticalSyncPulse units="Lines">2</VerticalSyncPulse>
+ <VerticalSyncSkew units="Lines">0</VerticalSyncSkew>
+ <VerticalTopBorder units="Lines">0</VerticalTopBorder>
+ <VerticalBottomBorder units="Lines">0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType units="QDI_DisplayConnectType">8</InterfaceType>
+ <InterfaceColorFormat units="QDI_PixelFormatType">3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId units="DSI_Channel_IDType">1</DSIChannelId>
+ <DSIVirtualId units="DSI_Display_VCType">0</DSIVirtualId>
+ <DSIColorFormat units="DSI_ColorFormatType">36</DSIColorFormat>
+ <DSITrafficMode units="DSI_TrafficModeType">1</DSITrafficMode>
+ <DSILanes units="integer">4</DSILanes>
+ <DSIHsaHseAfterVsVe units='Bool'>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP units='Bool'>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP units='Bool'>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA units='Bool'>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF units='Bool'>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP units='Bool'>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate units='integer Q16.16'>0x3C0000</DSIRefreshRate>
+ <DSIPhyDCDCMode units='Bool'>True</DSIPhyDCDCMode>
+ <DSIControllerMapping>
+ 00
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 15 ff 20
+ 15 fb 01
+ 15 00 01
+ 15 01 55
+ 15 02 45
+ 15 03 55
+ 15 05 50
+ 15 06 a8
+ 15 07 ad
+ 15 08 0c
+ 15 0b aa
+ 15 0c aa
+ 15 0e b0
+ 15 0f b3
+ 15 11 28
+ 15 12 10
+ 15 13 01
+ 15 14 4a
+ 15 15 12
+ 15 16 12
+ 15 30 01
+ 15 72 11
+ 15 58 82
+ 15 59 00
+ 15 5a 02
+ 15 5b 00
+ 15 5c 82
+ 15 5d 80
+ 15 5e 02
+ 15 5f 00
+ 15 ff 24
+ 15 fb 01
+ 15 00 01
+ 15 01 0b
+ 15 02 0c
+ 15 03 89
+ 15 04 8a
+ 15 05 0f
+ 15 06 10
+ 15 07 10
+ 15 08 1c
+ 15 09 00
+ 15 0a 00
+ 15 0b 00
+ 15 0c 00
+ 15 0d 13
+ 15 0e 15
+ 15 0f 17
+ 15 10 01
+ 15 11 0b
+ 15 12 0c
+ 15 13 89
+ 15 14 8a
+ 15 15 0f
+ 15 16 10
+ 15 17 10
+ 15 18 1c
+ 15 19 00
+ 15 1a 00
+ 15 1b 00
+ 15 1c 00
+ 15 1d 13
+ 15 1e 15
+ 15 1f 17
+ 15 20 00
+ 15 21 01
+ 15 22 00
+ 15 23 40
+ 15 24 40
+ 15 25 6d
+ 15 26 40
+ 15 27 40
+ 15 29 d8
+ 15 2a 2a
+ 15 4b 03
+ 15 4c 11
+ 15 4d 10
+ 15 4e 01
+ 15 4f 01
+ 15 50 10
+ 15 51 00
+ 15 52 80
+ 15 53 00
+ 15 54 07
+ 15 55 25
+ 15 56 00
+ 15 58 07
+ 15 5b 43
+ 15 5c 00
+ 15 5f 73
+ 15 60 73
+ 15 63 22
+ 15 64 00
+ 15 67 08
+ 15 68 04
+ 15 7a 80
+ 15 7b 91
+ 15 7c d8
+ 15 7d 60
+ 15 93 06
+ 15 94 06
+ 15 8a 00
+ 15 9b 0f
+ 15 b3 c0
+ 15 b4 00
+ 15 b5 00
+ 15 b6 21
+ 15 b7 22
+ 15 b8 07
+ 15 b9 07
+ 15 ba 22
+ 15 bd 20
+ 15 be 07
+ 15 bf 07
+ 15 c1 6d
+ 15 c4 24
+ 15 e3 00
+ 15 ec 00
+ 15 ff 10
+ 15 bb 03
+ 05 11 00
+ ff 78
+ 05 29 00
+ ff 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultLow>0x1A</TLMMGPIODefaultLow>
+<Group id='Backlight Configuration'>
+ <BacklightType units='MDP_Panel_BacklightType'>1</BacklightType>
+ <BacklightPmicControlType units='MDP_PmicBacklightControlType'>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
+
+
+
+
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dsc_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dsc_cmd.xml
new file mode 100644
index 0000000..bf7208d
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dsc_cmd.xml
@@ -0,0 +1,198 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>TFT2P2827-E</PanelName>
+<PanelDescription>Truly Single DSI Cmd Mode Panel with DSC (1440x2560 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1440</HorizontalActive>
+ <HorizontalFrontPorch>100</HorizontalFrontPorch>
+ <HorizontalBackPorch>32</HorizontalBackPorch>
+ <HorizontalSyncPulse>16</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2560</VerticalActive>
+ <VerticalFrontPorch>10</VerticalFrontPorch>
+ <VerticalBackPorch>8</VerticalBackPorch>
+ <VerticalSyncPulse>2</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>2</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2560</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2560</DSITEvSyncInitVal>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>7</DSIDSCProfileID>
+ <DSIDSCSliceWidth>720</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>16</DSIDSCSliceHeight>
+ <DSIControllerMapping>
+ 01
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 15 FF 20
+ 15 FB 01
+ 15 00 01
+ 15 01 55
+ 15 02 45
+ 15 05 40
+ 15 06 19
+ 15 07 1E
+ 15 0B 73
+ 15 0C 73
+ 15 0E B0
+ 15 0F AE
+ 15 11 B8
+ 15 13 00
+ 15 58 80
+ 15 59 01
+ 15 5A 00
+ 15 5B 01
+ 15 5C 80
+ 15 5D 81
+ 15 5E 00
+ 15 5F 01
+ 15 72 11
+ 15 68 03
+ 15 ff 24
+ 15 fb 01
+ 15 00 1C
+ 15 01 0B
+ 15 02 0C
+ 15 03 01
+ 15 04 0F
+ 15 05 10
+ 15 06 10
+ 15 07 10
+ 15 08 89
+ 15 09 8A
+ 15 0A 13
+ 15 0B 13
+ 15 0C 15
+ 15 0D 15
+ 15 0E 17
+ 15 0F 17
+ 15 10 1C
+ 15 11 0B
+ 15 12 0C
+ 15 13 01
+ 15 14 0F
+ 15 15 10
+ 15 16 10
+ 15 17 10
+ 15 18 89
+ 15 19 8A
+ 15 1A 13
+ 15 1B 13
+ 15 1C 15
+ 15 1D 15
+ 15 1E 17
+ 15 1F 17
+ 15 20 40
+ 15 21 01
+ 15 22 00
+ 15 23 40
+ 15 24 40
+ 15 25 6D
+ 15 26 40
+ 15 27 40
+ 15 E0 00
+ 15 DC 21
+ 15 DD 22
+ 15 DE 07
+ 15 DF 07
+ 15 E3 6D
+ 15 E1 07
+ 15 E2 07
+ 15 29 D8
+ 15 2A 2A
+ 15 4B 03
+ 15 4C 11
+ 15 4D 10
+ 15 4E 01
+ 15 4F 01
+ 15 50 10
+ 15 51 00
+ 15 52 80
+ 15 53 00
+ 15 56 00
+ 15 54 07
+ 15 58 07
+ 15 55 25
+ 15 5B 43
+ 15 5C 00
+ 15 5F 73
+ 15 60 73
+ 15 63 22
+ 15 64 00
+ 15 67 08
+ 15 68 04
+ 15 72 02
+ 15 7A 80
+ 15 7B 91
+ 15 7C D8
+ 15 7D 60
+ 15 7F 15
+ 15 75 15
+ 15 B3 C0
+ 15 B4 00
+ 15 B5 00
+ 15 78 00
+ 15 79 00
+ 15 80 00
+ 15 83 00
+ 15 93 0A
+ 15 94 0A
+ 15 8A 00
+ 15 9B FF
+ 15 9D B0
+ 15 9F 63
+ 15 98 10
+ 15 EC 00
+ 15 FF 10
+ 39 C1 09 20 00 10 02 00 02 68 01 BB 00 0A 06 67 04 C5
+ 39 C2 10 F0
+ 15 C0 03
+ 39 3B 03 0A 0A
+
+ 15 35 00
+ 15 E5 01
+ 15 BB 10
+ 15 FB 01
+ 05 11
+ FF 78
+ 05 29
+ FF 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultHigh>0x1A</TLMMGPIODefaultHigh>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dsc_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dsc_vid.xml
new file mode 100644
index 0000000..36f92e4
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dsc_vid.xml
@@ -0,0 +1,199 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>TFT2P2827-E</PanelName>
+<PanelDescription>Truly Single DSI Video Mode Panel with DSC (1440x2560 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive units="Dot Clocks">1440</HorizontalActive>
+ <HorizontalFrontPorch units="Dot Clocks">100</HorizontalFrontPorch>
+ <HorizontalBackPorch units="Dot Clocks">32</HorizontalBackPorch>
+ <HorizontalSyncPulse units="Dot Clocks">16</HorizontalSyncPulse>
+ <HorizontalSyncSkew units="Dot Clocks">0</HorizontalSyncSkew>
+ <HorizontalLeftBorder units="Dot Clocks">0</HorizontalLeftBorder>
+ <HorizontalRightBorder units="Dot Clocks">0</HorizontalRightBorder>
+ <VerticalActive units="Dot Clocks">2560</VerticalActive>
+ <VerticalFrontPorch units="Lines">10</VerticalFrontPorch>
+ <VerticalBackPorch units="Lines">8</VerticalBackPorch>
+ <VerticalSyncPulse units="Lines">2</VerticalSyncPulse>
+ <VerticalSyncSkew units="Lines">0</VerticalSyncSkew>
+ <VerticalTopBorder units="Lines">0</VerticalTopBorder>
+ <VerticalBottomBorder units="Lines">0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType units="QDI_DisplayConnectType">8</InterfaceType>
+ <InterfaceColorFormat units="QDI_PixelFormatType">3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId units="DSI_Channel_IDType">1</DSIChannelId>
+ <DSIVirtualId units="DSI_Display_VCType">0</DSIVirtualId>
+ <DSIColorFormat units="DSI_ColorFormatType">36</DSIColorFormat>
+ <DSITrafficMode units="DSI_TrafficModeType">1</DSITrafficMode>
+ <DSIDSCEnable>True</DSIDSCEnable>
+ <DSIDSCMajor>1</DSIDSCMajor>
+ <DSIDSCMinor>1</DSIDSCMinor>
+ <DSIDSCScr>0</DSIDSCScr>
+ <DSIDSCProfileID>7</DSIDSCProfileID>
+ <DSIDSCSliceWidth>720</DSIDSCSliceWidth>
+ <DSIDSCSliceHeight>16</DSIDSCSliceHeight>
+ <DSIDSCSlicePerPacket>2</DSIDSCSlicePerPacket>
+ <DSILanes units="integer">4</DSILanes>
+ <DSIHsaHseAfterVsVe units='Bool'>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP units='Bool'>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP units='Bool'>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA units='Bool'>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF units='Bool'>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP units='Bool'>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate units='integer Q16.16'>0x3C0000</DSIRefreshRate>
+ <DSIPhyDCDCMode units='Bool'>True</DSIPhyDCDCMode>
+ <DSIControllerMapping>
+ 01
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ FF 20
+ 15 FF 20
+ 15 FB 01
+ 15 00 01
+ 15 01 55
+ 15 02 45
+ 15 05 40
+ 15 06 19
+ 15 07 1E
+ 15 0B 73
+ 15 0C 73
+ 15 0E B0
+ 15 0F AE
+ 15 11 B8
+ 15 13 00
+ 15 58 80
+ 15 59 01
+ 15 5A 00
+ 15 5B 01
+ 15 5C 80
+ 15 5D 81
+ 15 5E 00
+ 15 5F 01
+ 15 72 11
+ 15 68 03
+ 15 FF 24
+ 15 FB 01
+ 15 00 1C
+ 15 01 0B
+ 15 02 0C
+ 15 03 01
+ 15 04 0F
+ 15 05 10
+ 15 06 10
+ 15 07 10
+ 15 08 89
+ 15 09 8A
+ 15 0A 13
+ 15 0B 13
+ 15 0C 15
+ 15 0D 15
+ 15 0E 17
+ 15 0F 17
+ 15 10 1C
+ 15 11 0B
+ 15 12 0C
+ 15 13 01
+ 15 14 0F
+ 15 15 10
+ 15 16 10
+ 15 17 10
+ 15 18 89
+ 15 19 8A
+ 15 1A 13
+ 15 1B 13
+ 15 1C 15
+ 15 1D 15
+ 15 1E 17
+ 15 1F 17
+ 15 20 40
+ 15 21 01
+ 15 22 00
+ 15 23 40
+ 15 24 40
+ 15 25 6D
+ 15 26 40
+ 15 27 40
+ 15 E0 00
+ 15 DC 21
+ 15 DD 22
+ 15 DE 07
+ 15 DF 07
+ 15 E3 6D
+ 15 E1 07
+ 15 E2 07
+ 15 29 D8
+ 15 2A 2A
+ 15 4B 03
+ 15 4C 11
+ 15 4D 10
+ 15 4E 01
+ 15 4F 01
+ 15 50 10
+ 15 51 00
+ 15 52 80
+ 15 53 00
+ 15 56 00
+ 15 54 07
+ 15 58 07
+ 15 55 25
+ 15 5B 43
+ 15 5C 00
+ 15 5F 73
+ 15 60 73
+ 15 63 22
+ 15 64 00
+ 15 67 08
+ 15 68 04
+ 15 72 02
+ 15 7A 80
+ 15 7B 91
+ 15 7C D8
+ 15 7D 60
+ 15 7F 15
+ 15 75 15
+ 15 B3 C0
+ 15 B4 00
+ 15 B5 00
+ 15 78 00
+ 15 79 00
+ 15 80 00
+ 15 83 00
+ 15 93 0A
+ 15 94 0A
+ 15 8A 00
+ 15 9B FF
+ 15 9D B0
+ 15 9F 63
+ 15 98 10
+ 15 EC 00
+ 15 FF 10
+ 39 C1 09 20 00 10 02 00 02 68 01 BB 00 0A 06 67 04 C5
+ 39 C2 10 F0
+ 15 C0 03
+ 39 3B 03 0A 0A
+ 15 35 00
+ 15 E5 01
+ 15 BB 03
+ 15 FB 01
+ 05 11 00
+ FF 78
+ 05 29
+ FF 78
+ 07 01
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultHigh>0x1A</TLMMGPIODefaultHigh>
+<Group id='Backlight Configuration'>
+ <BacklightType units='MDP_Panel_BacklightType'>1</BacklightType>
+ <BacklightPmicControlType units='MDP_PmicBacklightControlType'>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dual_cmd.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dual_cmd.xml
new file mode 100644
index 0000000..927b909
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dual_cmd.xml
@@ -0,0 +1,188 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>TFT2P2827-E</PanelName>
+<PanelDescription>Truly Dual DSI Command Mode Panel (1440x2560 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive>1440</HorizontalActive>
+ <HorizontalFrontPorch>100</HorizontalFrontPorch>
+ <HorizontalBackPorch>32</HorizontalBackPorch>
+ <HorizontalSyncPulse>16</HorizontalSyncPulse>
+ <HorizontalSyncSkew>0</HorizontalSyncSkew>
+ <HorizontalLeftBorder>0</HorizontalLeftBorder>
+ <HorizontalRightBorder>0</HorizontalRightBorder>
+ <VerticalActive>2560</VerticalActive>
+ <VerticalFrontPorch>8</VerticalFrontPorch>
+ <VerticalBackPorch>7</VerticalBackPorch>
+ <VerticalSyncPulse>1</VerticalSyncPulse>
+ <VerticalSyncSkew>0</VerticalSyncSkew>
+ <VerticalTopBorder>0</VerticalTopBorder>
+ <VerticalBottomBorder>0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType>9</InterfaceType>
+ <InterfaceColorFormat>3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId>2</DSIChannelId>
+ <DSIVirtualId>0</DSIVirtualId>
+ <DSIColorFormat>36</DSIColorFormat>
+ <DSITrafficMode>1</DSITrafficMode>
+ <DSILanes>4</DSILanes>
+ <DSIRefreshRate>0x3C0000</DSIRefreshRate>
+ <DSICmdSwapInterface>False</DSICmdSwapInterface>
+ <DSICmdUsingTrigger>False</DSICmdUsingTrigger>
+ <DSIEnableAutoRefresh>True</DSIEnableAutoRefresh>
+ <DSIAutoRefreshFrameNumDiv>2</DSIAutoRefreshFrameNumDiv>
+ <DSITECheckEnable>True</DSITECheckEnable>
+ <DSITEUsingDedicatedTEPin>True</DSITEUsingDedicatedTEPin>
+ <DSITEvSyncStartPos>2560</DSITEvSyncStartPos>
+ <DSITEvSyncInitVal>2560</DSITEvSyncInitVal>
+ <DSICmdModePixelAlignment>1</DSICmdModePixelAlignment>
+ <DSITimingMargin>1</DSITimingMargin>
+ <DSIControllerMapping>
+ 00 01
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ 15 FF 20
+ 15 FB 01
+ 15 00 01
+ 15 01 55
+ 15 02 45
+ 15 05 40
+ 15 06 19
+ 15 07 1E
+ 15 0B 73
+ 15 0C 73
+ 15 0E B0
+ 15 0F AE
+ 15 11 B8
+ 15 13 00
+ 15 58 80
+ 15 59 01
+ 15 5A 00
+ 15 5B 01
+ 15 5C 80
+ 15 5D 81
+ 15 5E 00
+ 15 5F 01
+ 15 72 11
+ 15 68 03
+ 15 ff 24
+ 15 fb 01
+ 15 00 1C
+ 15 01 0B
+ 15 02 0C
+ 15 03 01
+ 15 04 0F
+ 15 05 10
+ 15 06 10
+ 15 07 10
+ 15 08 89
+ 15 09 8A
+ 15 0A 13
+ 15 0B 13
+ 15 0C 15
+ 15 0D 15
+ 15 0E 17
+ 15 0F 17
+ 15 10 1C
+ 15 11 0B
+ 15 12 0C
+ 15 13 01
+ 15 14 0F
+ 15 15 10
+ 15 16 10
+ 15 17 10
+ 15 18 89
+ 15 19 8A
+ 15 1A 13
+ 15 1B 13
+ 15 1C 15
+ 15 1D 15
+ 15 1E 17
+ 15 1F 17
+ 15 20 40
+ 15 21 01
+ 15 22 00
+ 15 23 40
+ 15 24 40
+ 15 25 6D
+ 15 26 40
+ 15 27 40
+ 15 E0 00
+ 15 DC 21
+ 15 DD 22
+ 15 DE 07
+ 15 DF 07
+ 15 E3 6D
+ 15 E1 07
+ 15 E2 07
+ 15 29 D8
+ 15 2A 2A
+ 15 4B 03
+ 15 4C 11
+ 15 4D 10
+ 15 4E 01
+ 15 4F 01
+ 15 50 10
+ 15 51 00
+ 15 52 80
+ 15 53 00
+ 15 56 00
+ 15 54 07
+ 15 58 07
+ 15 55 25
+ 15 5B 43
+ 15 5C 00
+ 15 5F 73
+ 15 60 73
+ 15 63 22
+ 15 64 00
+ 15 67 08
+ 15 68 04
+ 15 72 02
+ 15 7A 80
+ 15 7B 91
+ 15 7C D8
+ 15 7D 60
+ 15 7F 15
+ 15 75 15
+ 15 B3 C0
+ 15 B4 00
+ 15 B5 00
+ 15 78 00
+ 15 79 00
+ 15 80 00
+ 15 83 00
+ 15 93 0A
+ 15 94 0A
+ 15 8A 00
+ 15 9B FF
+ 15 9D B0
+ 15 9F 63
+ 15 98 10
+ 15 EC 00
+ 15 ff 10
+ 15 35 00
+ 15 E5 01
+ 15 BB 10
+ 15 FB 01
+ 05 11 00
+ FF 78
+ 05 29 00
+ FF 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultLow>0x1A</TLMMGPIODefaultLow>
+<Group id='Backlight Configuration'>
+ <BacklightType>1</BacklightType>
+ <BacklightPmicControlType>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dual_vid.xml b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dual_vid.xml
new file mode 100644
index 0000000..c6832dc
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/Panel_truly_wqxga_dual_vid.xml
@@ -0,0 +1,187 @@
+<?xml version="1.0" encoding="utf-8"?>
+<PanelName>TFT2P2827-E</PanelName>
+<PanelDescription>Truly Dual DSI Video Mode Panel (1440x2560 24bpp)</PanelDescription>
+<Group id="Active Timing">
+ <HorizontalActive units="Dot Clocks">1440</HorizontalActive>
+ <HorizontalFrontPorch units="Dot Clocks">100</HorizontalFrontPorch>
+ <HorizontalBackPorch units="Dot Clocks">32</HorizontalBackPorch>
+ <HorizontalSyncPulse units="Dot Clocks">16</HorizontalSyncPulse>
+ <HorizontalSyncSkew units="Dot Clocks">0</HorizontalSyncSkew>
+ <HorizontalLeftBorder units="Dot Clocks">0</HorizontalLeftBorder>
+ <HorizontalRightBorder units="Dot Clocks">0</HorizontalRightBorder>
+ <VerticalActive units="Dot Clocks">2560</VerticalActive>
+ <VerticalFrontPorch units="Lines">8</VerticalFrontPorch>
+ <VerticalBackPorch units="Lines">7</VerticalBackPorch>
+ <VerticalSyncPulse units="Lines">1</VerticalSyncPulse>
+ <VerticalSyncSkew units="Lines">0</VerticalSyncSkew>
+ <VerticalTopBorder units="Lines">0</VerticalTopBorder>
+ <VerticalBottomBorder units="Lines">0</VerticalBottomBorder>
+ <InvertDataPolarity>False</InvertDataPolarity>
+ <InvertVsyncPolairty>False</InvertVsyncPolairty>
+ <InvertHsyncPolarity>False</InvertHsyncPolarity>
+ <BorderColor>0x0</BorderColor>
+</Group>
+<Group id="Display Interface">
+ <InterfaceType units="QDI_DisplayConnectType">8</InterfaceType>
+ <InterfaceColorFormat units="QDI_PixelFormatType">3</InterfaceColorFormat>
+</Group>
+<Group id="DSI Interface">
+ <DSIChannelId units="DSI_Channel_IDType">1</DSIChannelId>
+ <DSIVirtualId units="DSI_Display_VCType">0</DSIVirtualId>
+ <DSIColorFormat units="DSI_ColorFormatType">36</DSIColorFormat>
+ <DSITrafficMode units="DSI_TrafficModeType">1</DSITrafficMode>
+ <DSILanes units="integer">4</DSILanes>
+ <DSIHsaHseAfterVsVe units='Bool'>False</DSIHsaHseAfterVsVe>
+ <DSILowPowerModeInHFP units='Bool'>False</DSILowPowerModeInHFP>
+ <DSILowPowerModeInHBP units='Bool'>False</DSILowPowerModeInHBP>
+ <DSILowPowerModeInHSA units='Bool'>False</DSILowPowerModeInHSA>
+ <DSILowPowerModeInBLLPEOF units='Bool'>True</DSILowPowerModeInBLLPEOF>
+ <DSILowPowerModeInBLLP units='Bool'>True</DSILowPowerModeInBLLP>
+ <DSIRefreshRate units='integer Q16.16'>0x3C0000</DSIRefreshRate>
+ <DSIPhyDCDCMode units='Bool'>True</DSIPhyDCDCMode>
+ <DSIControllerMapping>
+ 00 01
+ </DSIControllerMapping>
+</Group>
+<DSIInitSequence>
+ FF 20
+ 15 FF 20
+ 15 FB 01
+ 15 00 01
+ 15 01 55
+ 15 02 45
+ 15 05 40
+ 15 06 19
+ 15 07 1E
+ 15 0B 73
+ 15 0C 73
+ 15 0E B0
+ 15 0F AE
+ 15 11 B8
+ 15 13 00
+ 15 58 80
+ 15 59 01
+ 15 5A 00
+ 15 5B 01
+ 15 5C 80
+ 15 5D 81
+ 15 5E 00
+ 15 5F 01
+ 15 72 11
+ 15 68 03
+ 15 FF 24
+ 15 FB 01
+ 15 00 1C
+ 15 01 0B
+ 15 02 0C
+ 15 03 01
+ 15 04 0F
+ 15 05 10
+ 15 06 10
+ 15 07 10
+ 15 08 89
+ 15 09 8A
+ 15 0A 13
+ 15 0B 13
+ 15 0C 15
+ 15 0D 15
+ 15 0E 17
+ 15 0F 17
+ 15 10 1C
+ 15 11 0B
+ 15 12 0C
+ 15 13 01
+ 15 14 0F
+ 15 15 10
+ 15 16 10
+ 15 17 10
+ 15 18 89
+ 15 19 8A
+ 15 1A 13
+ 15 1B 13
+ 15 1C 15
+ 15 1D 15
+ 15 1E 17
+ 15 1F 17
+ 15 20 40
+ 15 21 01
+ 15 22 00
+ 15 23 40
+ 15 24 40
+ 15 25 6D
+ 15 26 40
+ 15 27 40
+ 15 E0 00
+ 15 DC 21
+ 15 DD 22
+ 15 DE 07
+ 15 DF 07
+ 15 E3 6D
+ 15 E1 07
+ 15 E2 07
+ 15 29 D8
+ 15 2A 2A
+ 15 4B 03
+ 15 4C 11
+ 15 4D 10
+ 15 4E 01
+ 15 4F 01
+ 15 50 10
+ 15 51 00
+ 15 52 80
+ 15 53 00
+ 15 56 00
+ 15 54 07
+ 15 58 07
+ 15 55 25
+ 15 5B 43
+ 15 5C 00
+ 15 5F 73
+ 15 60 73
+ 15 63 22
+ 15 64 00
+ 15 67 08
+ 15 68 04
+ 15 72 02
+ 15 7A 80
+ 15 7B 91
+ 15 7C D8
+ 15 7D 60
+ 15 7F 15
+ 15 75 15
+ 15 B3 C0
+ 15 B4 00
+ 15 B5 00
+ 15 78 00
+ 15 79 00
+ 15 80 00
+ 15 83 00
+ 15 93 0A
+ 15 94 0A
+ 15 8A 00
+ 15 9B FF
+ 15 9D B0
+ 15 9F 63
+ 15 98 10
+ 15 EC 00
+ 15 FF 10
+ 39 3B 03 0A 0A
+ 15 35 00
+ 15 E5 01
+ 15 BB 03
+ 15 FB 01
+ 05 11 00
+ FF 78
+ 05 29 00
+ FF 78
+</DSIInitSequence>
+<DSITermSequence>
+ 05 28
+ 05 10
+</DSITermSequence>
+<TLMMGPIODefaultLow>0x1A</TLMMGPIODefaultLow>
+<Group id='Backlight Configuration'>
+ <BacklightType units='MDP_Panel_BacklightType'>1</BacklightType>
+ <BacklightPmicControlType units='MDP_PmicBacklightControlType'>2</BacklightPmicControlType>
+ <DisplayResetInfo>0 10 1000 10000 0</DisplayResetInfo>
+</Group>
diff --git a/uefi/files/Binaries/redwood/RawFiles/QcomChargerCfg.cfg b/uefi/files/Binaries/redwood/RawFiles/QcomChargerCfg.cfg
new file mode 100644
index 0000000..102fc4e
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/QcomChargerCfg.cfg
@@ -0,0 +1,765 @@
+#
+# Default Charger App Config settings
+#
+# CHARGER Config file
+
+#
+# Version/Information:
+# file QcomChargerConfig_VbattTh_SDM855.cfg
+#
+# Implements the Qualcomm's Charger application config parameters
+#
+# Copyright (c) 2017-2021, Qualcomm Technologies Inc. All rights reserved.
+#
+# 1 : Initial revision
+# 2 : Deleting not needed config params and removing dummy battery2 support
+# 3: Adding Jeita Compensation params
+# 4 : Adding parameters for different battery types and QC 3.0 and QC 2.0 chargergers
+# 5 : Added parameter to support enabling watchdog when charging is enabled
+# 6 : Adding parameters for Aux Coffes, SkinHot and Charger Hot settings
+# 7 : Update for Battery profile load
+# 8 : Added SupportHostMode
+# 9 : Adding Thermal configs
+# 10 : Adding support for Charger Fg Peripheral dumps
+# 11 : Adding HVDCP Enable control
+# 12 : Adding WIPOWER configs
+# 13 : Removed config item for setting IUSB_MAX in case of SDP
+# 14 : Adding Restarting FG flag
+# 15 : Adding Charger led indication config, rasing skin hot to 70-80C, disabling watchdog as default
+# 16 : Added changes for supporting different platforms, MTP, QRD, etc.
+# 17 : Removed SupportHostMode config (hostmode settings will be done in USB driver) and other unused config parameters
+# 18 : Enable battery profile loading by default
+# 19 : Added VBattEstDiffThreshold configuration
+# 20 : Add aux coffs
+# 21 : Removed HVDCP Enable control config parameter
+# 22 : Adding Config VBatEmpty threshold
+# 23 : Adding PBS triggered APF temperature threshold
+# 24 : Adding Rconn configuration
+# 25 : Adding thermal source configuration to enable/disable INOV
+# 26 : Updated config file to platform based sections.
+# 27 : Adding debug level mask for file logging
+# 28 : ABL min battery voltage config
+# 29 : Adding ship mode for factor use case
+# 30 : Adding delay before enable batt missing detection
+# 31 : Adding Platform HW configuration Override
+# 32 : Adding config item to choose pull-up for BATT_ID detection
+# 33 : Disable Sink DAM support
+#
+[PlatformCommon]
+
+CfgVersion = 35
+
+#Override default HW configuration assignment
+# 0 - None
+# 1 - PMIC
+#PlatHWCfgOverrdie = 0
+
+#Enable/disable chargerFW
+# 0 - disable loading chargerFW
+# 1 - enable loading chargerFW
+EnableChargerFW = 1
+
+#Enable/Disable Ship Mode - when enabled durign factory mode if persistant ShipMode variable is set then perform shipmode
+EnShipMode = FALSE
+
+#shipmode string to query variable status
+ShipModeVarStr = ShipMode
+
+#Minimum Battery Voltage to allow SW Flash Image
+SWFlashMinBattVoltageMv = 3600
+
+# Configure Battery Voltage and Current limit
+BattVoltLimHighDelta = 80
+
+#Enable Debug Accessory Mode and Factory Mode Boot (FMB)
+EnDebugAccessMode = TRUE
+EnFMB = FALSE
+
+#Select ICL for factory mode
+DAMSelIcl3AorFMB = 1
+
+#Enable SW thermal mitigation during charging by default FALSE
+# Mitigation is based on MSM Tsens max avg temp reading
+SWThermalMitigationEnable = FALSE
+
+# Print Charger DEBUG Messages
+PrintChargerAppDbgMsg = FALSE
+
+#Print Charger DEBUG Messages to ULOG File..Default is false
+PrintChargerAppDbgMsgToFile = FALSE
+
+#Debug level mask (in hex)for file logging.. refer to DebugLib.h
+FileLoggingDbgLevelMask = 80000042
+
+#Charging termination current in milliamps
+ChargingTermCurrent = 200
+
+#Battery ID Tolerance Percentage 8%
+BatteryIdTolerance = 8
+
+#Debug board ID range, value in Ohms
+DebugBoardBatteryIdMin = 2000
+DebugBoardBatteryIdMax = 14000
+
+#Regular battery ID range, value in Ohms
+RegularBatteryIdMin = 15000
+RegularBatteryIdMax = 137000
+
+#Smart battery ID range, value in Ohms
+SmartBatteryIdMin = 240000
+SmartBatteryIdMax = 450000
+
+# Voltage (in mV) to be reduced from FV_MAX during conservative charging
+ConservChgFvDelta = 200
+
+#Support unknown battery charging behavior
+# 0: Shuts down device, 1: Boot to HLOS if battery more than threshold else shutdown
+# 2: Conservative Charging 3: Regular charging
+UnknownBatteryBehavior = 3
+
+#Debug board behavior
+# 0: Show low battery icon, disable PON1/USBIN trigger to prevent reboot and shutdown
+# 1: Show low battery icon and stay on until device is turned off by user.
+# 2: Boot to HLOS
+DebugBoardBehavior = 2
+
+#Boot device to HLOS in case of unsupported battery or battery emulator. In millivolt*/
+BootToHLOSThresholdInMv = 3400
+
+#Minimum SOC Threshold before allowing to boot to HLOS
+#below param is considered only when SocBasedBoot = TRUE and LoadBatteryProfile = TRUE
+OsStandardBootSocThreshold = 7
+
+#device behaviour if temp is outside charging range but within operational range
+# 1= Disable charging and wait. 0 = Shutdown device is temp outside
+NoChargeAndWait = TRUE
+
+#Lowest Voltage at which device should shutdown gracefully
+#value in mV
+EmergencyShutdownVbatt = 3200
+
+#Battery missing config
+# 0 = using batt id 1 = using batt therm 2 = both
+BattMissingCfg = 0
+
+#Charger WDOG Support options
+# 0: Do not enable Charger WDOG
+# 1: Enable Charger WDOG during charging and Disable before exiting
+# 2: Enable Charger WDOG during charging and leave enabled when exiting
+EnableChargerWdog = 1
+
+#Program BATT_THERM configs
+#BiasWait 0 = 0 ms; 1 = 1 ms; 2 = 4 ms; 3 = 12 ms; 4 = 20 ms; 5 = 40 ms; 6 = 60 ms; 7 = 80 ms
+#GndSel TRUE = thermistor is located on the battery pack, FALSE = thermistor on the PCB(skin temp)
+BattThermBiasWait = 4
+BattThermGndSel = TRUE
+
+#Program AUX_THERM configs
+AuxThermBiasWait = 4
+AuxThermGndSel = FALSE
+
+#Program device Skin and Charger Hot threhsolds
+ProgramSkinAndChargerHotThreshold = TRUE
+DeviceSkinHotInC = 70
+DeviceSkinTooHotInC = 80
+ChargerHotInC = 80
+ChargerTooHotInC = 90
+
+#enable/disable charger therm source
+SkinTempSrc = TRUE
+DieTempSrc = TRUE
+DieTempCompSrc = TRUE
+
+#Use Battery SOC or voltage based threshold charging criteria
+#FALSE: Voltage threshold based boot-up; TRUE: SOC threshold based boot-up
+SocBasedBoot = FALSE
+
+#Load Fuel Gauge Battery Profile profile for SOC estimation and accuracy
+LoadBatteryProfile = FALSE
+
+#Below VBAT threhsold is used to decide on showing sign of life first before FG Module Initialization and continuing with threshold charging
+DispSignOfLifeMaxThresholdMv = 3700
+
+#dump SRAM contents default value is FALSE
+DumpSram = FALSE
+
+#dump SRAM Start and End Address in Hex Format
+#SRAM Block SRAM Address
+#System 0x00 - 0x23
+#Profile 0x41 - 0x10F
+#Scratchpad 0x12C - 0x1DF
+#values in decimal
+DumpSramStartAddr = 0
+#values in decimal
+DumpSramEndAddr = 485
+
+#dump SRAM contents timer Duration in s
+DumpSramDuration = 30
+
+## TSENS ##
+#High Temperature limit for thermal wait
+TsensHighTemp = 85
+#High Temperature limit for battey and device safety (battery disconnect)
+TsensExtremeTemp = 90
+#Low Temperature limit for end of thermal wait
+TsensLowTemp = 75
+# Give up time in thermal wait for battery disconnect - support up to 60min
+TsensTimeoutMins = 90
+
+#Enable/disable Charger/FG Dump support
+EnableChargerFgDump = FALSE
+
+#Boot device to HLOS in case of DCIn Charging
+DCInBootToHLOSThresholdInMv = 3800
+
+#suspend DCIn or not after exiting UEFI
+SuspendDCIn = FALSE
+
+# FG Conditional Restart on Device reset
+FgCondRestart = TRUE
+
+# VBat Threshold value for conditional restart check, value in mV
+VBattEstDiffThreshold = 300
+
+# Charging status indication via led
+# 0 = Disable 1 = solid during charging 2 = led blinks during charging
+# if turned on LED will be turned off after threhsold charging is completed i.e. when device boot to HLOS
+ChargerLedConfig = 1
+
+#Rconn compensation Resistance, value in mOhms - range is +/- 1000 mOhms
+RconnComp = 0
+
+#Display time in ms for Charger FW Missing message
+ChargerFWMissingDisplayTime = 5000
+
+#force to offmode charging power testing mode even with debug board, CDP, MTP.
+ForcePowerTesting = 0
+#Action to take when GLink communication goes down
+# Shutdown :0, Recovery : 1
+GLinkDownAction = 0
+
+ChargerPDLoggingCategories = 1
+
+#Set chargerPD logging level via PMIC GLINK
+ChargerPDLoggingLevel = 4
+
+#Request chargerPD log buffer of specific size via PMIC GLINK
+ChargerPDLoggingSize = 8192
+
+#ChargerPD logging interval
+ChargerpdReadInterval = 0
+
+#add hysteresis(in mV) to boot_to_hlos_threshold_in_mv above which device will boot to HLOS
+VbattThresholdMarginInMv = 50
+
+
+[PlatformMTP]
+## Parameter values with respect to MTP Platform (Platform 1)
+# Configure FVMax and Fcc values
+ChgFvMax = 4350
+ChgFccMax = 2000
+
+
+# Configure limits for Battery Temperature (For negative values, use negative sign. Ex: -30)
+JeitaCriticalTempLowLimit = -20
+JeitaHardColdLimit = 0
+JeitaSoftColdLimit = 15
+JeitaSoftHotLimit = 45
+JeitaHardHotLimit = 55
+JeitaCriticalTempHighLimit = 60
+
+# Configure battery temperature limits in deg Cfor PBS temperature monitoring if SW is stuck,
+# when battery temperature goes out of bound, pbs will trigger AFP (shutdown device).
+# setting cold to -273 to disablecold shutdown
+HwAfpHotLimit = 72
+HwAfpColdLimit = -273
+
+#JEITA Charge Current Compensation when in battery temperature soft-limit
+#JEITA CC = min is 0 ma and max is 1575 ma - stpe size is 25mA
+JeitaCcCompHotCfg = 1000
+JeitaCcCompColdCfg = 1000
+
+#JEITA Float Voltage Compensation when in battery temperature soft-limit
+#min is 0 and max .4725 V step size is 7.5 mV - unit is in mV
+JeitaFvCompHotCfg = 105
+JeitaFvCompColdCfg = 105
+
+#JEITA Hard Limit
+JeitaHardLimitEnable = TRUE
+
+#JEITA Float Voltage compensation during soft cold
+JeitaSoftColdFvCompEnable = FALSE
+
+#JEITA Float Voltage compensation during soft hot
+JeitaSoftHotFvCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft cold
+JeitaSoftColdCcCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft hot
+JeitaSoftHotCcCompEnable = TRUE
+
+#Vbat Empty threshold in mv
+VBatEmpty = 2850
+
+#BATT missing delay in msec
+BattMissingDelay = 0
+
+#BATT PullUp resistance value to be used for BattId detection
+# 0: 100K PullUp (default)
+# 1: 30K PullUp
+# 2: 400K PullUp
+BattIdPullUp = 0
+
+[PlatformQRD]
+## Parameter values with respect to QRD Platform (Platform 2)
+# Configure VddMax and IbatMax values
+# Set to 0 to configure through API
+ChgFvMax = 4400
+ChgFccMax = 5325
+
+# Configure limits for Battery Temperature (For negative values, use negative sign. Ex: -30)
+JeitaCriticalTempLowLimit = -20
+JeitaHardColdLimit = 0
+JeitaSoftColdLimit = 10
+JeitaSoftHotLimit = 40
+JeitaHardHotLimit = 45
+JeitaCriticalTempHighLimit = 55
+
+# Configure battery temperature limits in deg Cfor PBS temperature monitoring if SW is stuck,
+# when battery temperature goes out of bound, pbs will trigger AFP (shutdown device).
+# setting cold to -273 to disablecold shutdown
+HwAfpHotLimit = 72
+HwAfpColdLimit = -273
+
+#JEITA Charge Current Compensation when in battery temperature soft-limit
+#JEITA CC = min is 0 ma and max is 1575 ma - stpe size is 25mA
+JeitaCcCompHotCfg = 1000
+JeitaCcCompColdCfg = 1000
+
+#JEITA Float Voltage Compensation when in battery temperature soft-limit
+#min is 0 and max .4725 V step size is 7.5 mV - unit is in mV
+JeitaFvCompHotCfg = 105
+JeitaFvCompColdCfg = 105
+
+#JEITA Hard Limit
+JeitaHardLimitEnable = TRUE
+
+#JEITA Float Voltage compensation during soft cold
+JeitaSoftColdFvCompEnable = FALSE
+
+#JEITA Float Voltage compensation during soft hot
+JeitaSoftHotFvCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft cold
+JeitaSoftColdCcCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft hot
+JeitaSoftHotCcCompEnable = TRUE
+
+#Vbat Empty threshold in mv
+VBatEmpty = 2850
+
+#BATT missing delay in msec
+BattMissingDelay = 100
+
+#BATT PullUp resistance value to be used for BattId detection
+# 0: 100K PullUp (default)
+# 1: 30K PullUp
+# 2: 400K PullUp
+BattIdPullUp = 0
+
+[PlatformK9B]
+## Parameter values with respect to MTP Platform (Platform 1)
+# Configure FVMax and Fcc values
+ChgFvMax = 4450
+ChgFccMax = 1500
+
+#Override default HW configuration assignment
+# 0 - None
+# 1 - PMIC
+PlatHWCfgOverrdie = 1
+
+#Boot device to HLOS in case of unsupported battery or battery emulator. In millivolt*/
+BootToHLOSThresholdInMv = 3590
+
+# Configure limits for Battery Temperature (For negative values, use negative sign. Ex: -30)
+JeitaCriticalTempLowLimit = -20
+JeitaHardColdLimit = -10
+JeitaSoftColdLimit = 10
+JeitaSoftHotLimit = 45
+JeitaHardHotLimit = 60
+JeitaCriticalTempHighLimit = 68
+
+# Configure battery temperature limits in deg Cfor PBS temperature monitoring if SW is stuck,
+# when battery temperature goes out of bound, pbs will trigger AFP (shutdown device).
+# setting cold to -273 to disablecold shutdown
+HwAfpHotLimit = 62
+HwAfpColdLimit = -273
+
+#JEITA Charge Current Compensation when in battery temperature soft-limit
+#JEITA CC = min is 0 ma and max is 1575 ma - stpe size is 25mA
+JeitaCcCompHotCfg = 1000
+JeitaCcCompColdCfg = 1000
+
+#JEITA Float Voltage Compensation when in battery temperature soft-limit
+#min is 0 and max .4725 V step size is 7.5 mV - unit is in mV
+JeitaFvCompHotCfg = 105
+JeitaFvCompColdCfg = 105
+
+#JEITA Hard Limit
+JeitaHardLimitEnable = TRUE
+
+#JEITA Float Voltage compensation during soft cold
+JeitaSoftColdFvCompEnable = FALSE
+
+#JEITA Float Voltage compensation during soft hot
+JeitaSoftHotFvCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft cold
+JeitaSoftColdCcCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft hot
+JeitaSoftHotCcCompEnable = TRUE
+
+#Vbat Empty threshold in mv
+VBatEmpty = 2850
+
+#BATT missing delay in msec
+BattMissingDelay = 0
+
+#BATT PullUp resistance value to be used for BattId detection
+# 0: 100K PullUp (default)
+# 1: 30K PullUp
+# 2: 400K PullUp
+BattIdPullUp = 0
+
+[PlatformK9D]
+## Parameter values with respect to MTP Platform (Platform 1)
+# Configure FVMax and Fcc values
+ChgFvMax = 4450
+ChgFccMax = 1500
+
+#Override default HW configuration assignment
+# 0 - None
+# 1 - PMIC
+PlatHWCfgOverrdie = 1
+
+#Boot device to HLOS in case of unsupported battery or battery emulator. In millivolt*/
+BootToHLOSThresholdInMv = 3600
+
+# Configure limits for Battery Temperature (For negative values, use negative sign. Ex: -30)
+JeitaCriticalTempLowLimit = -20
+JeitaHardColdLimit = -10
+JeitaSoftColdLimit = 10
+JeitaSoftHotLimit = 45
+JeitaHardHotLimit = 60
+JeitaCriticalTempHighLimit = 68
+
+# Configure battery temperature limits in deg Cfor PBS temperature monitoring if SW is stuck,
+# when battery temperature goes out of bound, pbs will trigger AFP (shutdown device).
+# setting cold to -273 to disablecold shutdown
+HwAfpHotLimit = 62
+HwAfpColdLimit = -273
+
+#JEITA Charge Current Compensation when in battery temperature soft-limit
+#JEITA CC = min is 0 ma and max is 1575 ma - stpe size is 25mA
+JeitaCcCompHotCfg = 1000
+JeitaCcCompColdCfg = 1000
+
+#JEITA Float Voltage Compensation when in battery temperature soft-limit
+#min is 0 and max .4725 V step size is 7.5 mV - unit is in mV
+JeitaFvCompHotCfg = 105
+JeitaFvCompColdCfg = 105
+
+#JEITA Hard Limit
+JeitaHardLimitEnable = TRUE
+
+#JEITA Float Voltage compensation during soft cold
+JeitaSoftColdFvCompEnable = FALSE
+
+#JEITA Float Voltage compensation during soft hot
+JeitaSoftHotFvCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft cold
+JeitaSoftColdCcCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft hot
+JeitaSoftHotCcCompEnable = TRUE
+
+#Vbat Empty threshold in mv
+VBatEmpty = 2850
+
+#BATT missing delay in msec
+BattMissingDelay = 0
+
+#BATT PullUp resistance value to be used for BattId detection
+# 0: 100K PullUp (default)
+# 1: 30K PullUp
+# 2: 400K PullUp
+BattIdPullUp = 0
+
+[PlatformL9B]
+## Parameter values with respect to MTP Platform (Platform 1)
+# Configure FVMax and Fcc values
+ChgFvMax = 4450
+ChgFccMax = 1500
+
+#Override default HW configuration assignment
+# 0 - None
+# 1 - PMIC
+PlatHWCfgOverrdie = 1
+
+#Boot device to HLOS in case of unsupported battery or battery emulator. In millivolt*/
+BootToHLOSThresholdInMv = 3590
+
+# Configure limits for Battery Temperature (For negative values, use negative sign. Ex: -30)
+JeitaCriticalTempLowLimit = -20
+JeitaHardColdLimit = -10
+JeitaSoftColdLimit = 10
+JeitaSoftHotLimit = 45
+JeitaHardHotLimit = 60
+JeitaCriticalTempHighLimit = 68
+
+# Configure battery temperature limits in deg Cfor PBS temperature monitoring if SW is stuck,
+# when battery temperature goes out of bound, pbs will trigger AFP (shutdown device).
+# setting cold to -273 to disablecold shutdown
+HwAfpHotLimit = 62
+HwAfpColdLimit = -273
+
+#JEITA Charge Current Compensation when in battery temperature soft-limit
+#JEITA CC = min is 0 ma and max is 1575 ma - stpe size is 25mA
+JeitaCcCompHotCfg = 1000
+JeitaCcCompColdCfg = 1000
+
+#JEITA Float Voltage Compensation when in battery temperature soft-limit
+#min is 0 and max .4725 V step size is 7.5 mV - unit is in mV
+JeitaFvCompHotCfg = 105
+JeitaFvCompColdCfg = 105
+
+#JEITA Hard Limit
+JeitaHardLimitEnable = TRUE
+
+#JEITA Float Voltage compensation during soft cold
+JeitaSoftColdFvCompEnable = FALSE
+
+#JEITA Float Voltage compensation during soft hot
+JeitaSoftHotFvCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft cold
+JeitaSoftColdCcCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft hot
+JeitaSoftHotCcCompEnable = TRUE
+
+#Vbat Empty threshold in mv
+VBatEmpty = 2850
+
+#BATT missing delay in msec
+BattMissingDelay = 0
+
+#BATT PullUp resistance value to be used for BattId detection
+# 0: 100K PullUp (default)
+# 1: 30K PullUp
+# 2: 400K PullUp
+BattIdPullUp = 0
+
+[PlatformL9]
+## Parameter values with respect to MTP Platform (Platform 1)
+# Configure FVMax and Fcc values
+ChgFvMax = 4450
+ChgFccMax = 1500
+
+#Override default HW configuration assignment
+# 0 - None
+# 1 - PMIC
+PlatHWCfgOverrdie = 1
+
+#Boot device to HLOS in case of unsupported battery or battery emulator. In millivolt*/
+BootToHLOSThresholdInMv = 3590
+
+# Configure limits for Battery Temperature (For negative values, use negative sign. Ex: -30)
+JeitaCriticalTempLowLimit = -20
+JeitaHardColdLimit = -10
+JeitaSoftColdLimit = 10
+JeitaSoftHotLimit = 45
+JeitaHardHotLimit = 60
+JeitaCriticalTempHighLimit = 68
+
+# Configure battery temperature limits in deg Cfor PBS temperature monitoring if SW is stuck,
+# when battery temperature goes out of bound, pbs will trigger AFP (shutdown device).
+# setting cold to -273 to disablecold shutdown
+HwAfpHotLimit = 62
+HwAfpColdLimit = -273
+
+#JEITA Charge Current Compensation when in battery temperature soft-limit
+#JEITA CC = min is 0 ma and max is 1575 ma - stpe size is 25mA
+JeitaCcCompHotCfg = 1000
+JeitaCcCompColdCfg = 1000
+
+#JEITA Float Voltage Compensation when in battery temperature soft-limit
+#min is 0 and max .4725 V step size is 7.5 mV - unit is in mV
+JeitaFvCompHotCfg = 105
+JeitaFvCompColdCfg = 105
+
+#JEITA Hard Limit
+JeitaHardLimitEnable = TRUE
+
+#JEITA Float Voltage compensation during soft cold
+JeitaSoftColdFvCompEnable = FALSE
+
+#JEITA Float Voltage compensation during soft hot
+JeitaSoftHotFvCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft cold
+JeitaSoftColdCcCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft hot
+JeitaSoftHotCcCompEnable = TRUE
+
+#Vbat Empty threshold in mv
+VBatEmpty = 2850
+
+#BATT missing delay in msec
+BattMissingDelay = 0
+
+#BATT PullUp resistance value to be used for BattId detection
+# 0: 100K PullUp (default)
+# 1: 30K PullUp
+# 2: 400K PullUp
+BattIdPullUp = 0
+
+
+[PlatformM20]
+## Parameter values with respect to MTP Platform (Platform 1)
+# Configure FVMax and Fcc values
+ChgFvMax = 4450
+ChgFccMax = 1500
+
+#Override default HW configuration assignment
+# 0 - None
+# 1 - PMIC
+PlatHWCfgOverrdie = 1
+
+#Boot device to HLOS in case of unsupported battery or battery emulator. In millivolt*/
+BootToHLOSThresholdInMv = 3590
+
+# Configure limits for Battery Temperature (For negative values, use negative sign. Ex: -30)
+JeitaCriticalTempLowLimit = -20
+JeitaHardColdLimit = -10
+JeitaSoftColdLimit = 10
+JeitaSoftHotLimit = 45
+JeitaHardHotLimit = 60
+JeitaCriticalTempHighLimit = 68
+
+# Configure battery temperature limits in deg Cfor PBS temperature monitoring if SW is stuck,
+# when battery temperature goes out of bound, pbs will trigger AFP (shutdown device).
+# setting cold to -273 to disablecold shutdown
+HwAfpHotLimit = 62
+HwAfpColdLimit = -273
+
+#JEITA Charge Current Compensation when in battery temperature soft-limit
+#JEITA CC = min is 0 ma and max is 1575 ma - stpe size is 25mA
+JeitaCcCompHotCfg = 1000
+JeitaCcCompColdCfg = 1000
+
+#JEITA Float Voltage Compensation when in battery temperature soft-limit
+#min is 0 and max .4725 V step size is 7.5 mV - unit is in mV
+JeitaFvCompHotCfg = 105
+JeitaFvCompColdCfg = 105
+
+#JEITA Hard Limit
+JeitaHardLimitEnable = TRUE
+
+#JEITA Float Voltage compensation during soft cold
+JeitaSoftColdFvCompEnable = FALSE
+
+#JEITA Float Voltage compensation during soft hot
+JeitaSoftHotFvCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft cold
+JeitaSoftColdCcCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft hot
+JeitaSoftHotCcCompEnable = TRUE
+
+#Vbat Empty threshold in mv
+VBatEmpty = 2850
+
+#BATT missing delay in msec
+BattMissingDelay = 0
+
+#BATT PullUp resistance value to be used for BattId detection
+# 0: 100K PullUp (default)
+# 1: 30K PullUp
+# 2: 400K PullUp
+BattIdPullUp = 0
+
+[PlatformK9E]
+## Parameter values with respect to MTP Platform (Platform 1)
+# Configure FVMax and Fcc values
+ChgFvMax = 4450
+ChgFccMax = 1500
+
+#Override default HW configuration assignment
+# 0 - None
+# 1 - PMIC
+PlatHWCfgOverrdie = 1
+
+#Boot device to HLOS in case of unsupported battery or battery emulator. In millivolt*/
+BootToHLOSThresholdInMv = 3590
+
+# Configure limits for Battery Temperature (For negative values, use negative sign. Ex: -30)
+JeitaCriticalTempLowLimit = -20
+JeitaHardColdLimit = -10
+JeitaSoftColdLimit = 10
+JeitaSoftHotLimit = 45
+JeitaHardHotLimit = 60
+JeitaCriticalTempHighLimit = 68
+
+# Configure battery temperature limits in deg Cfor PBS temperature monitoring if SW is stuck,
+# when battery temperature goes out of bound, pbs will trigger AFP (shutdown device).
+# setting cold to -273 to disablecold shutdown
+HwAfpHotLimit = 62
+HwAfpColdLimit = -273
+
+#JEITA Charge Current Compensation when in battery temperature soft-limit
+#JEITA CC = min is 0 ma and max is 1575 ma - stpe size is 25mA
+JeitaCcCompHotCfg = 1000
+JeitaCcCompColdCfg = 1000
+
+#JEITA Float Voltage Compensation when in battery temperature soft-limit
+#min is 0 and max .4725 V step size is 7.5 mV - unit is in mV
+JeitaFvCompHotCfg = 105
+JeitaFvCompColdCfg = 105
+
+#JEITA Hard Limit
+JeitaHardLimitEnable = TRUE
+
+#JEITA Float Voltage compensation during soft cold
+JeitaSoftColdFvCompEnable = FALSE
+
+#JEITA Float Voltage compensation during soft hot
+JeitaSoftHotFvCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft cold
+JeitaSoftColdCcCompEnable = TRUE
+
+#JEITA Charge Current compensation during soft hot
+JeitaSoftHotCcCompEnable = TRUE
+
+#Vbat Empty threshold in mv
+VBatEmpty = 2850
+
+#BATT missing delay in msec
+BattMissingDelay = 0
+
+#BATT PullUp resistance value to be used for BattId detection
+# 0: 100K PullUp (default)
+# 1: 30K PullUp
+# 2: 400K PullUp
+BattIdPullUp = 0
+#
+# End of config
+# Blank line needed after the last config
+#
diff --git a/uefi/files/Binaries/redwood/RawFiles/SecParti.cfg b/uefi/files/Binaries/redwood/RawFiles/SecParti.cfg
new file mode 100644
index 0000000..c56a5e8
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/SecParti.cfg
@@ -0,0 +1,177 @@
+##
+## RPMB/GPT Partition configuration file
+##
+
+## This version number needs to match the partition table version in TZ
+[VersionNum]
+Version = 0x0100
+
+########################################################################
+##
+## List of Device IDs
+## 0 = User Partition
+## 1 = Boot1 Partition
+## 2 = Boot2 Partition
+## 3 = RPMB Partition
+## 4 = GPP1 Partition
+## 5 = GPP2 Partition
+## 6 = GPP3 Partition
+## 7 = GPP4 Partition
+## 8 = All Partitions (GPT only; we will search all the GPT partitions
+## and find the physical partition that contains
+## the partition GUID specified)
+##
+########################################################################
+
+########################################################################
+##
+## For RPMB partitions, the section chosen will be based off the RPMB
+## size. So, a eMMC that has a RPMB of size 128KB will use section
+## [RPMB.128KB].
+##
+## Note: Maintain multiple sections in descending order of sizes from
+## start of file to end to minimize boot time impact.
+##
+## Each section should look like the following:
+##
+## The first line of the RPMB section should contain the device ID.
+## Example first line:
+## DevId = 3
+##
+## The subsequent lines for the RPMB section will contain information about
+## the partitions to be added. For each partition added, you will provide the
+## following:
+## AppName: The application that will use the partition
+## AppPartitionId: Partition type (values are up to the user)
+## SizeInSectors: Size of the partition in sectors
+##
+## Example new partition:
+## AppNameId = qcom.tz.sampleapp
+## AppPartitionId = 9
+## SizeInSectors = 4
+##
+## Repeat the step above for all partitions to be added.
+##
+########################################################################
+## Example of a RPMB section for RPMB partition of size 128KB with 2
+## partitions:
+##
+## [RPMB.128KB]
+## DevId = 3
+##
+## AppNameId = qcom.tz.sampleapp
+## AppPartitionId = 9
+## SizeInSectors = 4
+##
+## AppNameId = qcom.tz.sampleapp
+## AppPartitionId = 11
+## SizeInSectors = 6
+##
+###############################################################################\
+
+## RPMB Partitions
+
+## RPMB Size = 384KB or greater
+[RPMB.384KB]
+DevId = 3
+
+## UEFI BS_NS_NV
+AppNameId = qcom.tz.uefisecapp
+AppPartitionId = 2
+SizeInSectors = 128
+
+## UEFI RT_S_NV
+AppNameId = qcom.tz.uefisecapp
+AppPartitionId = 3
+SizeInSectors = 256
+
+## UEFI_RT_NS_NV
+AppNameId = qcom.tz.uefisecapp
+AppPartitionId = 4
+SizeInSectors = 128
+
+## fTPM
+AppNameId = qcom.tz.winsecapp
+AppPartitionId = 5
+SizeInSectors = 80
+
+## UEFI_RT_NS_NV_HR
+AppNameId = qcom.tz.uefisecapp
+AppPartitionId = 6
+SizeInSectors = 12
+
+########################################################################
+##
+## For GPT partitions, there will be one section only. The section name
+## must be [GPT].
+##
+## Each section should look like the following:
+##
+## The first part of the GPT section should contain the device ID and
+## the partition GUID
+## Example:
+## DevId = 4
+## PartitionGuid = "2275A3E4 6727 4D06 9EF1 EEE2ABDD38E1"
+##
+## The next part of the GPT section will contain information about the
+## partitions to be added. For each partition added, you will provide
+## the following:
+## AppPartitionId: Partition type (values are up to the user)
+## SizeInBytes: Partition size in bytes
+##
+## Example new partition:
+## AppPartitionId = 9
+## SizeInBytes = 2048
+##
+## Repeat all the steps above for each subsequent device (i.e. whenever
+## there is a different device ID or partition GUID) to be added. Keep
+## everything in one section; don't create a new one.
+##
+########################################################################
+## Example of a GPT section with 2 partitions
+##
+## [GPT]
+## DevId = 8
+## PartitionGuid = "5F85FC54 55DE 4D8B 9C81 99B464F39DEC"
+##
+## AppPartitionId = 1
+## SizeInSectors = 12
+##
+## AppPartitionId = 2
+## SizeInSectors = 16
+##
+#######################################################################\
+
+## GPT Partitions
+
+## Note: GUID should not have "-" char, instead replace them with spaces
+## Note: Leave 1 block per app partition for soft partition header
+
+## Note: Variable Partitions should be at least 6 sectors or more
+## (24 kb size or more)
+## Additionally reserve 1 sector for storage and a blank sector in
+## between each table. So table size addition total below, should
+## not exceed the reserve carveouts (512KB - 5 sectors)
+
+[GPT]
+## UEFI BS_NS_NV
+DevId = 8
+PartitionGuid = "165BD6BC 9250 4AC8 95A7 A93F4A440066"
+AppPartitionId = 2
+SizeInBytes = 192512
+
+## UEFI RT_S_NV
+DevId = 8
+AppPartitionId = 3
+SizeInBytes = 221184
+
+## UEFI_RT_NS_NV
+DevId = 8
+AppPartitionId = 4
+SizeInBytes = 61440
+
+## AppPartitionId = 5 reserved for WinsecApp Ftm since ID's are globally unique
+#UEFI_RT_NS_NV_HR
+DevId = 8
+AppPartitionId = 6
+SizeInBytes = 32768
diff --git a/uefi/files/Binaries/redwood/RawFiles/logo1.bmp b/uefi/files/Binaries/redwood/RawFiles/logo1.bmp
new file mode 100644
index 0000000..10e6089
Binary files /dev/null and b/uefi/files/Binaries/redwood/RawFiles/logo1.bmp differ
diff --git a/uefi/files/Binaries/redwood/RawFiles/uefipil.cfg b/uefi/files/Binaries/redwood/RawFiles/uefipil.cfg
new file mode 100644
index 0000000..5e906e3
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/uefipil.cfg
@@ -0,0 +1,170 @@
+[PIL]
+CfgVersion = 1
+
+########################################################################
+##
+## PIL configuration, contains the base address and size of image load
+## information region in IMEM
+##
+########################################################################\
+
+[IMAGE_LOAD_INFO_REGION]
+ImageLoadInfoBase = 0x146AA94C
+ImageLoadInfoSize = 200
+
+########################################################################
+##
+## PIL configuration, contains the list of images which is allowed
+## to be loaded by PIL in retail. PIL does not support images beyond
+## the list
+##
+########################################################################\
+
+[RETAIL]
+ABL
+SPSS
+FULL_ADSP
+ImageFv
+
+########################################################################
+##
+## PIL configuration, contains the list of images which will be
+## loaded by PIL by default
+##
+########################################################################\
+
+[AUTO]
+ABL
+
+########################################################################
+##
+## PIL image configuration, updated to Lahaina V3 memory map
+##
+########################################################################\
+[FULL_ADSP]
+Type = elf_split
+#PartiLabel = modem_a
+#PartiRootGuid =
+PartiGuid = "EBD0A0A2 B9E5 4433 87C0 68B6B72699C7"
+ImagePath = \image\adsp
+SubsysID = 1
+ResvMemoryStart = 0x86700000
+ResvMemorySize = 0x4000000
+ImageLoadInfo = Yes
+OverrideElfAddr = Yes
+ProxyGuid = "36fe27e1 33e9 45ad 98da c88438ca8816"
+QfpromSkuAddr = 0x0
+
+[FULL_CDSP]
+Type = elf_split
+PartiLabe#l = modem_a
+#PartiRootGuid =
+PartiGuid = "EBD0A0A2 B9E5 4433 87C0 68B6B72699C7"
+ImagePath = \image\cdsp
+SubsysID = 18
+ResvMemoryStart = 0x9C700000
+ResvMemorySize = 0x01E00000
+ImageLoadInfo = Yes
+OverrideElfAddr = Yes
+ProxyGuid = "45E14C04 D134 4EE4 AC13 7098F0A9F261"
+
+
+[FULL_MODEM]
+Type = elf_split
+#PartiLabel = modem_a
+#PartiRootGuid =
+PartiGuid = "EBD0A0A2 B9E5 4433 87C0 68B6B72699C7"
+ImagePath = \image\modem
+SubsysID = 4
+ResvMemoryStart = 0x8B800000
+ResvMemorySize = 0x0F600000
+ImageLoadInfo = Yes
+OverrideElfAddr = Yes
+ProxyGuid = "61513695 e0c6 4f07 bf41 a51a7770640e"
+
+[CORE_ADSP]
+Type = elf_split
+PartiLabel = core_nhlos_a
+#PartiRootGuid =
+#PartiGuid = "EBD0A0A2 B9E5 4433 87C0 68B6B72699C7"
+ImagePath = \image\adsp
+SubsysID = 1
+ResvMemoryStart = 0x86700000
+ResvMemorySize = 0x03800000
+ImageLoadInfo = Yes
+OverrideElfAddr = Yes
+ProxyGuid = "36fe27e1 33e9 45ad 98da c88438ca8816"
+QfpromSkuAddr = 0x7841F4
+
+[CORE_CDSP]
+Type = elf_split
+PartiLabel = core_nhlos_a
+#PartiRootGuid =
+#PartiGuid = "EBD0A0A2 B9E5 4433 87C0 68B6B72699C7"
+ImagePath = \image\cdsp
+SubsysID = 18
+ResvMemoryStart = 0x9C700000
+ResvMemorySize = 0x01E00000
+ImageLoadInfo = Yes
+OverrideElfAddr = Yes
+ProxyGuid = "45E14C04 D134 4EE4 AC13 7098F0A9F261"
+
+[CORE_WPSS]
+Type = elf_split
+PartiLabel = core_nhlos_a
+#PartiRootGuid =
+#PartiGuid = "EBD0A0A2 B9E5 4433 87C0 68B6B72699C7"
+ImagePath = \image\wpss
+SubsysID = 6
+ResvMemoryStart = 0x9AE00000
+ResvMemorySize = 0x01900000
+ImageLoadInfo = Yes
+OverrideElfAddr = Yes
+
+
+ProxyGuid = "45654140 778E 4384 8EEC 703FDACE3172"
+
+[CORE_MODEM]
+Type = elf_split
+PartiLabel = core_nhlos_a
+#PartiRootGuid =
+#PartiGuid = "EBD0A0A2 B9E5 4433 87C0 68B6B72699C7"
+ImagePath = \image\modem
+SubsysID = 4
+ResvMemoryStart = 0x8B800000
+ResvMemorySize = 0x0F600000
+ImageLoadInfo = Yes
+OverrideElfAddr = Yes
+ProxyGuid = "61513695 e0c6 4f07 bf41 a51a7770640e"
+
+[SPSS]
+Type = elf_split
+#PartiLabel = modem_a
+#PartiRootGuid =
+PartiGuid = "EBD0A0A2 B9E5 4433 87C0 68B6B72699C7"
+ImagePath = \image\spss2t
+SubsysID = 14
+ResvMemoryStart = 0x8AA00000
+ResvMemorySize = 0x100000
+ImageLoadInfo = Yes
+OverrideElfAddr = Yes
+ProxyGuid = "2B4DE7E9 B796 4FE7 B210 49F11C6BABC2"
+
+[ABL]
+Type = elf_fv
+#PartiLabel = abl_a
+#PartiRootGuid =
+PartiGuid = "BD6928A1 4CE0 A038 4F3A 1495E3EDDFFB"
+SubsysID = 21
+ImageLoadInfo = No
+Unlock = Yes
+
+[ImageFv]
+Type = elf_fv
+#PartiLabel = imagefv_a
+#PartiRootGuid =
+PartiGuid = "17911177 C9E6 4372 933C 804B678E666F"
+SubsysID = 20
+ImageLoadInfo = No
+Unlock = Yes
+
diff --git a/uefi/files/Binaries/redwood/RawFiles/uefiplat.cfg b/uefi/files/Binaries/redwood/RawFiles/uefiplat.cfg
new file mode 100644
index 0000000..f631113
--- /dev/null
+++ b/uefi/files/Binaries/redwood/RawFiles/uefiplat.cfg
@@ -0,0 +1,197 @@
+[Config]
+Version = 3
+MaxMemoryRegions = 74
+UnusableDDRMemoryAtBeginning = 1
+UnusableDDRMemoryStartAddr = 0x80000000
+UnusableDDRMemorySizeAtBeginning = 0x600000
+
+[MemoryMap]
+# EFI_RESOURCE_ EFI_RESOURCE_ATTRIBUTE_ EFI_MEMORY_TYPE ARM_REGION_ATTRIBUTE_
+#MemBase, MemSize, MemLabel(32 Char.), BuildHob, ResourceType, ResourceAttribute, MemoryType, CacheAttributes
+#--------------------- DDR -----
+0x80000000, 0x00600000, "HYP", AddMem, MEM_RES, SYS_MEM_CAP, Reserv, WRITE_BACK_XN
+0x80600000, 0x00100000, "Axon DMA", AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN
+0x80700000, 0x00100000, "BOOT", AddMem, MEM_RES, SYS_MEM_CAP, BsData, WRITE_BACK_XN
+0x80800000, 0x00060000, "AOP CMD", AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN
+0x80860000, 0x00020000, "AOP CMD DB", AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN
+0x80884000, 0x00010000, "XBL Log Buffer", AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN
+0x80900000, 0x00200000, "SMEM", AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN
+0x83600000, 0x00400000, "Sched Heap", AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN
+0x85800000, 0x16F00000, "PIL Reserved", AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN
+0x9C700000, 0x03100000, "DXE Heap", AddMem, SYS_MEM, SYS_MEM_CAP, Conv, WRITE_BACK_XN
+0x9F800000, 0x00200000, "FV Region", AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN
+0x9FA00000, 0x00200000, "ABOOT FV", AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN
+0x9FC00000, 0x00300000, "UEFI FD", AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK
+0x9FF00000, 0x0008C000, "SEC Heap", AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN
+0x9FF8C000, 0x00001000, "CPU Vectors", AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK
+0x9FF8D000, 0x00003000, "MMU PageTables", AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN
+0x9FF90000, 0x00040000, "UEFI Stack", AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN
+0x9FFF7000, 0x00008000, "Log Buffer", AddMem, SYS_MEM, SYS_MEM_CAP, RtData, WRITE_BACK_XN
+0x9FFFF000, 0x00001000, "Info Blk", AddMem, SYS_MEM, SYS_MEM_CAP, RtData, WRITE_BACK_XN
+0xA0000000, 0x10000000, "Kernel", AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN
+0xB0000000, 0x10000000, "HYP RESERVED", AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN
+0xC1800000, 0x05000000, "TZApps Reserved", HobOnlyNoCacheSetting, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN
+0xD0000000, 0x10000000, "Guest VM", AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN
+0xE0000000, 0x00F00000, "DBI Dump", NoHob, MMAP_IO, INITIALIZED, Conv, UNCACHED_UNBUFFERED_XN
+0xE1000000, 0x02400000, "Display Reserved", AddMem, MEM_RES, SYS_MEM_CAP, Reserv, WRITE_THROUGH_XN
+
+[RegisterMap]
+#--------------------- Other -----
+0x14680000, 0x0002B000, "IMEM Base", NoHob, MMAP_IO, INITIALIZED, Conv, NS_DEVICE
+0x146AA000, 0x00001000, "IMEM Cookie Base", AddDev, MMAP_IO, INITIALIZED, Conv, NS_DEVICE
+#--------------------- Register --
+0x00400000, 0x00100000, "IPC_ROUTER_TOP", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x00780000, 0x00010000, "SECURITY CONTROL", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x00900000, 0x00200000, "QUP", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x010D0000, 0x00010000, "PRNG_CFG_PRNG", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x01DC0000, 0x00040000, "CRYPTO0 CRYPTO", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x01FC0000, 0x00030000, "TCSR_TCSR_REGS", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x007C0000, 0x00100000, "PERIPH_SS_SDC1", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x08800000, 0x00200000, "PERIPH_SS", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x0A600000, 0x04000000, "USB", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x0B000000, 0x04000000, "AOSS", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x0F100000, 0x00300000, "TLMM", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x15000000, 0x00200000, "SMMU", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+0x17800000, 0x00E00000, "APSS_HM", AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE
+
+[ConfigParameters]
+# Update count if more than default 30 entries #
+ConfigParameterCount = 64
+
+## UEFI CORE ##
+PlatConfigFileName = "uefiplatLA.cfg"
+OsTypeString = "LA"
+NumCpusFuseAddr = 0x5C04C
+
+# Force booting to shell whilst in pre-silicon phase
+EnableShell = 0x1
+
+# Tune based on heap needs for Initial tables, FV decompression and MMU tables through Dxe/BDS
+InitialPagePoolCount = 0x700
+
+## Shared IMEM (Cookies, Offsets)
+SharedIMEMBaseAddr = 0x146AA000
+
+DloadCookieAddr = 0x01FD3000
+# for full dump 0x10, for minidump 0x20
+DloadCookieValue = 0x10
+
+## NumCpus - max number of cores
+NumCpus = 8
+## NumActiveCores - number of cores used
+NumActiveCores = 8
+
+## ULogFile ##
+SpecialLogPartition = "LOGFS:\"
+MaxLogFileSize = 0x400000
+
+## UEFI memory use
+UefiMemUseThreshold = 0xE1
+
+## USB ##
+USBHS1_Config = 0x0
+UsbFnIoRevNum = 0x00010001
+
+## Buttons / KeyPad ##
+PwrBtnShutdownFlag = 0x0
+
+## SDCC ##
+Sdc1GpioConfigOn = 0x1E92
+Sdc2GpioConfigOn = 0x1E92
+Sdc1GpioConfigOff = 0xA00
+Sdc2GpioConfigOff = 0xA00
+
+## SDHC Mode 0:Legacy Mode, Non-zero: SDHC Mode ##
+EnableSDHCSwitch = 0x1
+
+## UFS ##
+EnableUfsIOC = 1
+UfsSmmuConfigForOtherBootDev = 1
+UEFIExitUfsSSURequired = 1
+
+## PCIE ##
+#PCIeRPNumber BIT 7:0 -> number of RPs to be enabled
+#PCIeRPNumber BIT 15:8 -> BIT mask to identify which RPs are enabled
+#Eg. value: 0x0502 -> Total two numbers of RPs, RP0 and RP2 are enabled
+#Total RPs supported 8 numbers and bits allocated are 16 bits
+
+#PCIeRPNumber=0x0101
+
+## Security flag ##
+SecurityFlag = 0xC4
+# SecBootEnableFlag = 0x1 i.e. 0b00000001
+# TreeTpmEnableFlag = 0x2 i.e. 0b00000010
+# CommonMbnLoadFlag = 0x4 i.e. 0b00000100
+# DxHdcp2LoadFlag = 0x8 i.e. 0b00001000
+# VariableServicesFlag = 0x10 i.e. 0b00010000
+# WinsecappFlag = 0x20 i.e. 0b00100000
+# LoadSecAppFlag = 0x40 i.e. 0b01000000
+# LoadKeymasterFlag = 0x80 i.e. 0b10000000
+# EnableQseeLogsFlag = 0x100 i.e. 0b 00000001 00000000
+
+## Default app to boot in platform BDS init
+DefaultChargerApp = "QcomChargerApp"
+DefaultBDSBootApp = "LinuxLoader"
+
+## Enable HotKey detection in RETAIL devices
+DetectRetailUserAttentionHotkey = 0x00
+## 0x17 is SCAN_ESC
+DetectRetailUserAttentionHotkeyCode = 0x17
+## Enable OEM Setup App launch in Retail ##
+EnableOEMSetupAppInRetail = 0x0
+
+
+## LogFs partition ##
+## NOTE: Ensure logs 8MB bin is flashed from /Tools/binaries ##
+EnableLogFsSyncInRetail = 0x1
+
+## ShmBridge Memory Size
+ShmBridgememSize = 0xA00000
+
+#
+# Multithreading options
+#
+EnableMultiThreading = 1
+MaxCoreCnt = 8
+# Keep the following number of cores active, including the boot core
+EarlyInitCoreCnt = 2
+
+## Get TZ App Logs ##
+EnableUefiSecAppDebugLogDump = 0x0
+
+## Allow Non Persistent Varialbes in Retail ##
+## NOTE: Recommend disabling feature for Retail devices
+AllowNonPersistentVarsInRetail = 0x1
+
+# Initialize Display panel in its own thread to run in parallel to booting
+EnableDisplayThread = 0x0
+
+# Using imagefv to load display logo
+EnableDisplayImageFv = 0x1
+
+## Dynamic UART Log Buffer Size
+#Refer to boot_images/QcomPkg/Docs/UefiLogBufferSizeConfigReadme.txt for usage.
+#UARTLogBufferSize = 0x19000
+
+#DDRInfoDxe EnvDxe event callback flag
+DDRInfoNotifyFlag = 0x0
+
+## Enable/Disable Variable Policy Engine ##
+EnableVariablePolicyEngine = 0
+
+## Allow individual ACPI tables loading ##
+EnableACPIFallback = 0x0
+
+#
+# FV Decompression on multicore option
+#
+EnableMultiCoreFvDecompression = 1
+
+# EUD Enable Address
+EUDEnableAddr = 0x88E2000
+
+## Minidump Compression TA loading configuration (0x0 or 0x1)
+MinidumpTALoadingCfg = 0x0
+
+## NOTE: Do not remove last newline, required by parser ##
+
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/DeviceBuild.py b/uefi/files/Platforms/Xiaomi/redwoodPkg/DeviceBuild.py
new file mode 100644
index 0000000..2b56dd4
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/DeviceBuild.py
@@ -0,0 +1,204 @@
+##
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+import datetime
+import logging
+import os
+import uuid
+
+from io import StringIO
+from pathlib import Path
+
+from edk2toolext.environment import shell_environment
+from edk2toolext.environment.uefi_build import UefiBuilder
+from edk2toolext.invocables.edk2_platform_build import BuildSettingsManager
+from edk2toolext.invocables.edk2_pr_eval import PrEvalSettingsManager
+from edk2toolext.invocables.edk2_setup import (RequiredSubmodule, SetupSettingsManager)
+from edk2toolext.invocables.edk2_update import UpdateSettingsManager
+from edk2toolext.invocables.edk2_parse import ParseSettingsManager
+from edk2toollib.utility_functions import RunCmd
+
+# ####################################################################################### #
+# Common Configuration #
+# ####################################################################################### #
+class CommonPlatform ():
+ PackagesSupported = ("redwoodPkg")
+ ArchSupported = ("AARCH64")
+ TargetsSupported = ("DEBUG", "RELEASE")
+ Scopes = ('redwood', 'gcc_aarch64_linux', 'edk2-build')
+ WorkspaceRoot = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+ PackagesPath = (
+ "Platforms/Xiaomi",
+ "Common/Mu",
+ "Common/Mu_OEM_Sample",
+ "Mu_Basecore",
+ "Silicon/Qualcomm",
+ "Silicon/Silicium",
+ "Silicium-ACPI",
+ "Silicium-ACPI/Platforms/Xiaomi",
+ "Silicium-ACPI/Silicon/Qualcomm"
+ )
+
+# ####################################################################################### #
+# Configuration for Update & Setup #
+# ####################################################################################### #
+class SettingsManager (UpdateSettingsManager, SetupSettingsManager, PrEvalSettingsManager, ParseSettingsManager):
+
+ def GetPackagesSupported (self):
+ return CommonPlatform.PackagesSupported
+
+ def GetArchitecturesSupported (self):
+ return CommonPlatform.ArchSupported
+
+ def GetTargetsSupported (self):
+ return CommonPlatform.TargetsSupported
+
+ def GetRequiredSubmodules (self):
+ return [
+ RequiredSubmodule ("Binaries", True),
+ RequiredSubmodule ("Common/Mu", True),
+ RequiredSubmodule ("Common/Mu_OEM_Sample", True),
+ RequiredSubmodule ("Mu_Basecore", True),
+ RequiredSubmodule ("Silicium-ACPI", True),
+ RequiredSubmodule ("Silicon/Silicium/OpensslPkg/Library/OpensslLib/openssl", True)
+ ]
+
+ def SetArchitectures (self, list_of_requested_architectures):
+ unsupported = set(list_of_requested_architectures) - set(self.GetArchitecturesSupported())
+
+ if (len(unsupported) > 0):
+ errorString = ("Unsupported Architecture Requested: " + " ".join(unsupported))
+ logging.critical (errorString)
+ raise Exception (errorString)
+
+ self.ActualArchitectures = list_of_requested_architectures
+
+ def GetWorkspaceRoot (self):
+ return CommonPlatform.WorkspaceRoot
+
+ def GetActiveScopes (self):
+ return CommonPlatform.Scopes
+
+ def FilterPackagesToTest (self, changedFilesList: list, potentialPackagesList: list) -> list:
+ build_these_packages = []
+ possible_packages = potentialPackagesList.copy ()
+
+ for f in changedFilesList:
+ if "BaseTools" in f:
+ if os.path.splitext(f) not in [".txt", ".md"]:
+ build_these_packages = possible_packages
+ break
+
+ if "platform-build-run-steps.yml" in f:
+ build_these_packages = possible_packages
+ break
+
+ return build_these_packages
+
+ def GetPlatformDscAndConfig (self) -> tuple:
+ return ("redwoodPkg/redwood.dsc", {})
+
+ def GetName (self):
+ return "redwood"
+
+ def GetPackagesPath (self):
+ return CommonPlatform.PackagesPath
+
+# ####################################################################################### #
+# Actual Configuration for Platform Build #
+# ####################################################################################### #
+class PlatformBuilder (UefiBuilder, BuildSettingsManager):
+ def __init__ (self):
+ UefiBuilder.__init__ (self)
+
+ def AddCommandLineOptions (self, parserObj):
+ parserObj.add_argument('-a', "--arch", dest="build_arch", type=str, default="AARCH64", help="Optional - CSV of architecture to build. AARCH64 is used for PEI and DXE and is the only valid option for this platform.")
+
+ def RetrieveCommandLineOptions (self, args):
+ if args.build_arch.upper() != "AARCH64":
+ raise Exception("Invalid Arch Specified. Please see comments in DeviceBuild.py::PlatformBuilder::AddCommandLineOptions")
+
+ def GetWorkspaceRoot (self):
+ return CommonPlatform.WorkspaceRoot
+
+ def GetPackagesPath (self):
+ result = [ shell_environment.GetBuildVars().GetValue("FEATURE_CONFIG_PATH", "") ]
+
+ for a in CommonPlatform.PackagesPath:
+ result.append(a)
+
+ return result
+
+ def GetActiveScopes (self):
+ return CommonPlatform.Scopes
+
+ def GetName (self):
+ return "redwoodPkg"
+
+ def GetLoggingLevel (self, loggerType):
+ return logging.INFO
+ return super().GetLoggingLevel(loggerType)
+
+ def SetPlatformEnv (self):
+ logging.debug ("PlatformBuilder SetPlatformEnv")
+
+ self.env.SetValue ("PRODUCT_NAME", "redwood", "Platform Hardcoded")
+ self.env.SetValue ("ACTIVE_PLATFORM", "redwoodPkg/redwood.dsc", "Platform Hardcoded")
+ self.env.SetValue ("TARGET_ARCH", "AARCH64", "Platform Hardcoded")
+ self.env.SetValue ("TOOL_CHAIN_TAG", "CLANGPDB", "set default to clangpdb")
+ self.env.SetValue ("EMPTY_DRIVE", "FALSE", "Default to false")
+ self.env.SetValue ("RUN_TESTS", "FALSE", "Default to false")
+ self.env.SetValue ("SHUTDOWN_AFTER_RUN", "FALSE", "Default to false")
+ self.env.SetValue ("BLD_*_BUILDID_STRING", "Unknown", "Default")
+ self.env.SetValue ("BUILDREPORTING", "TRUE", "Enabling build report")
+ self.env.SetValue ("BUILDREPORT_TYPES", "PCD DEPEX FLASH BUILD_FLAGS LIBRARY FIXED_ADDRESS HASH", "Setting build report types")
+ self.env.SetValue ("BLD_*_MEMORY_PROTECTION", "TRUE", "Default")
+ self.env.SetValue ("BLD_*_SHIP_MODE", "FALSE", "Default")
+ self.env.SetValue ("BLD_*_ENABLE_SECUREBOOT", self.env.GetValue("ENABLE_SECUREBOOT"), "Default")
+ self.env.SetValue ("BLD_*_FD_BASE", self.env.GetValue("FD_BASE"), "Default")
+ self.env.SetValue ("BLD_*_FD_SIZE", self.env.GetValue("FD_SIZE"), "Default")
+ self.env.SetValue ("BLD_*_FD_BLOCKS", self.env.GetValue("FD_BLOCKS"), "Default")
+
+ return 0
+
+ def PlatformPreBuild (self):
+ return 0
+
+ def PlatformPostBuild (self):
+ return 0
+
+ def FlashRomImage (self):
+ return 0
+
+if __name__ == "__main__":
+ import argparse
+ import sys
+
+ from edk2toolext.invocables.edk2_platform_build import Edk2PlatformBuild
+ from edk2toolext.invocables.edk2_setup import Edk2PlatformSetup
+ from edk2toolext.invocables.edk2_update import Edk2Update
+
+ SCRIPT_PATH = os.path.relpath (__file__)
+
+ parser = argparse.ArgumentParser (add_help=False)
+
+ parse_group = parser.add_mutually_exclusive_group()
+
+ parse_group.add_argument ("--update", "--UPDATE", action='store_true', help="Invokes stuart_update")
+ parse_group.add_argument ("--setup", "--SETUP", action='store_true', help="Invokes stuart_setup")
+
+ args, remaining = parser.parse_known_args()
+
+ new_args = ["stuart", "-c", SCRIPT_PATH]
+ new_args = new_args + remaining
+
+ sys.argv = new_args
+
+ if args.setup:
+ Edk2PlatformSetup().Invoke()
+ elif args.update:
+ Edk2Update().Invoke()
+ else:
+ Edk2PlatformBuild().Invoke()
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/Include/APRIORI.inc b/uefi/files/Platforms/Xiaomi/redwoodPkg/Include/APRIORI.inc
new file mode 100644
index 0000000..ffd79bf
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/Include/APRIORI.inc
@@ -0,0 +1,107 @@
+APRIORI DXE {
+ INF MdeModulePkg/Core/Dxe/DxeMain.inf
+ INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.inf
+
+ INF MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf
+ INF MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf
+ INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+ INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+ INF ArmPkg/Drivers/ArmGicDxe/ArmGicDxe.inf
+ INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
+ INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.inf
+ INF Binaries/redwood/QcomPkg/Drivers/TzDxe/ScmDxeLA.inf
+ INF Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.inf
+
+ INF MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.inf
+
+ INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+ INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+ INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.inf
+
+ INF FatPkg/EnhancedFatDxe/Fat.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.inf
+
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/FeatureEnablerDxe/FeatureEnablerDxe.inf
+
+!if $(USE_CUSTOM_DISPLAY_DRIVER) == 1
+ INF Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.inf
+!else
+ INF SiliciumPkg/Drivers/SimpleFbDxe/SimpleFbDxe.inf
+!endif
+
+ INF Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.inf
+!if $(USE_CUSTOM_DISPLAY_DRIVER) == 1
+ INF Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.inf
+!endif
+
+ INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
+ INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
+ INF EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
+ INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
+ INF MdeModulePkg/Universal/PrintDxe/PrintDxe.inf
+ INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+ INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+ INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
+ INF MdeModulePkg/Universal/BdsDxe/BdsDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/XhciDxe/XhciDxe.inf
+
+ INF MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf
+ INF MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf
+ INF MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UCDxe/UCDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/RNGDxe/RngDxe.inf
+
+ INF EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
+ INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
+ INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
+ INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
+}
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/Include/DXE.inc b/uefi/files/Platforms/Xiaomi/redwoodPkg/Include/DXE.inc
new file mode 100644
index 0000000..35b9500
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/Include/DXE.inc
@@ -0,0 +1,100 @@
+ INF MdeModulePkg/Core/Dxe/DxeMain.inf
+ INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/EnvDxe/EnvDxe.inf
+
+ INF MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf
+ INF MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf
+ INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+ INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+ INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/ShmBridgeDxe/ShmBridgeDxeLA.inf
+ INF Binaries/redwood/QcomPkg/Drivers/TzDxe/ScmDxeLA.inf
+ INF Binaries/redwood/QcomPkg/Drivers/TzDxe/TzDxeLA.inf
+
+ INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
+ INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+ INF EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
+ INF MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
+ INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
+ INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
+ INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
+ INF ArmPkg/Drivers/ArmGicDxe/ArmGicDxe.inf
+ INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/ChipInfoDxe/ChipInfoDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PlatformInfoDxe/PlatformInfoDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ProjectInfoDxe/ProjectInfoDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/DALSYSDxe/DALSYSDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/HALIOMMUDxe/HALIOMMUDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/HWIODxe/HWIODxe.inf
+
+ INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+ INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+ INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+ INF FatPkg/EnhancedFatDxe/Fat.inf
+ INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/ClockDxe/ClockDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/SdccDxe/SdccDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/I2CDxe/I2CDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/SPMIDxe/SPMIDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/TLMMDxe/TLMMDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PmicDxe/PmicDxeLa.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UFSDxe/UFSDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/CmdDbDxe/CmdDbDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PwrUtilsDxe/PwrUtilsDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/RpmhDxe/RpmhDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/NpaDxe/NpaDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ULogDxe/ULogDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/VcsDxe/VcsDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ICBDxe/ICBDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/SmemDxe/SmemDxe.inf
+ INF MdeModulePkg/Universal/BdsDxe/BdsDxe.inf
+ INF EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
+ INF MdeModulePkg/Universal/PrintDxe/PrintDxe.inf
+ INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
+ INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
+ INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
+
+!if $(USE_CUSTOM_DISPLAY_DRIVER) == 1
+ INF Binaries/redwood/QcomPkg/Drivers/CPRDxe/CPRDxe.inf
+!endif
+ INF Binaries/redwood/QcomPkg/Drivers/GpiDxe/GpiDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/SPIDxe/SPIDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/FeatureEnablerDxe/FeatureEnablerDxe.inf
+
+!if $(USE_CUSTOM_DISPLAY_DRIVER) == 1
+ INF Binaries/redwood/QcomPkg/Drivers/DisplayDxe/DisplayDxe.inf
+!else
+ INF SiliciumPkg/Drivers/SimpleFbDxe/SimpleFbDxe.inf
+!endif
+
+ INF Binaries/redwood/QcomPkg/Drivers/ButtonsDxe/ButtonsDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/ChargerExDxe/ChargerExDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/IPCCDxe/IPCCDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/GLinkDxe/GLinkDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PmicGlinkDxe/PmicGlinkDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/QcomChargerDxe/QcomChargerDxeLA.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UsbPwrCtrlDxe/UsbPwrCtrlDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/TsensDxe/TsensDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/LimitsDxe/LimitsDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/DDRInfoDxe/DDRInfoDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UsbfnDwc3Dxe/UsbfnDwc3Dxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/XhciPciEmulationDxe/XhciPciEmulationDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/XhciDxe/XhciDxe.inf
+
+ INF MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf
+ INF MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf
+ INF MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf
+
+ INF Binaries/redwood/QcomPkg/Drivers/UsbMsdDxe/UsbMsdDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UsbDeviceDxe/UsbDeviceDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UsbConfigDxe/UsbConfigDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UsbInitDxe/UsbInitDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/UCDxe/UCDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/RNGDxe/RngDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PILDxe/PILDxe.inf
+ INF Binaries/redwood/QcomPkg/Drivers/PILProxyDxe/PILProxyDxe.inf
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/Include/RAW.inc b/uefi/files/Platforms/Xiaomi/redwoodPkg/Include/RAW.inc
new file mode 100644
index 0000000..d429a45
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/Include/RAW.inc
@@ -0,0 +1,166 @@
+ FILE FREEFORM = A1E235DE-E825-4591-9623-C43175811826 {
+ SECTION UI = "SecParti.cfg"
+ SECTION RAW = Binaries/redwood/RawFiles/SecParti.cfg
+ }
+
+ FILE FREEFORM = 21E9BDD9-6C3F-4F10-84A5-BBEC322741F1 {
+ SECTION UI = "uefipil.cfg"
+ SECTION RAW = Binaries/redwood/RawFiles/uefipil.cfg
+ }
+
+!if $(USE_CUSTOM_DISPLAY_DRIVER) == 1
+ FILE FREEFORM = 8CAE2C55-FC5A-410B-812B-8CA22F572F36 {
+ SECTION UI = "Panel_truly_wqxga_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_truly_wqxga_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 13AC9DC9-0092-4374-AE1A-06FF35950FD0 {
+ SECTION UI = "Panel_truly_wqxga_dsc_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_truly_wqxga_dsc_vid.xml
+ }
+
+ FILE FREEFORM = FC6315F9-F8FE-4222-A1E3-226DF55D7592 {
+ SECTION UI = "Panel_truly_wqxga_dual_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_truly_wqxga_dual_cmd.xml
+ }
+
+ FILE FREEFORM = 95E7B040-26A2-4511-9ABB-1D95D6DA7082 {
+ SECTION UI = "Panel_truly_wqxga_dual_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_truly_wqxga_dual_vid.xml
+ }
+
+ FILE FREEFORM = 8BC595B7-391A-4A9A-8256-5B9983B30392 {
+ SECTION UI = "Panel_sharp_4k_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_sharp_4k_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 19B58ACD-B1F8-4078-B9A5-A33584B680E2 {
+ SECTION UI = "Panel_sharp_4k_dsc_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_sharp_4k_dsc_vid.xml
+ }
+
+ FILE FREEFORM = 9601EEEE-A8A3-4830-9C1B-EEB7440F566C {
+ SECTION UI = "Panel_K9D_36_02_0a_amoled_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_K9D_36_02_0a_amoled_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = DD66FE9B-CE71-40B7-AC3A-F3F950ABAF5F {
+ SECTION UI = "Panel_K9D_42_0d_0b_amoled_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_K9D_42_0d_0b_amoled_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 1D790C01-DC9F-4C53-ABC3-4C9DE4AC4B9D {
+ SECTION UI = "Panel_K9B_42_02_0a_amoled_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_K9B_42_02_0a_amoled_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 246C6105-BF46-4953-821A-C4C873781780 {
+ SECTION UI = "Panel_K9E_42_02_0a_amoled_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_K9E_42_02_0a_amoled_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 2E058E2E-1C30-415A-8A49-BBE517DE73A3 {
+ SECTION UI = "Panel_K9E_35_02_0b_amoled_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_K9E_35_02_0b_amoled_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 7372316C-C2E9-414F-B7FA-1884ABB80830 {
+ SECTION UI = "Panel_L9_42_02_0a_amoled_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_L9_42_02_0a_amoled_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 8397BAC4-FE69-11EC-9F40-23333AA31BF8 {
+ SECTION UI = "Panel_M20_36_02_0a_amoled_dsc_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_M20_36_02_0a_amoled_dsc_vid.xml
+ }
+
+ FILE FREEFORM = 6546055D-AD36-48A9-9F8D-B3CA2E895D4A {
+ SECTION UI = "Panel_M20_42_0d_0b_amoled_dsc_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_M20_42_0d_0b_amoled_dsc_vid.xml
+ }
+
+ FILE FREEFORM = 76D0C92F-FF79-4800-919E-B6CE7695F269 {
+ SECTION UI = "Panel_L9_36_02_0b_amoled_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_L9_36_02_0b_amoled_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 62AD1E9F-7964-42F1-BF31-01AD9A71EB53 {
+ SECTION UI = "Panel_primary_sim_vdo.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_primary_sim_vdo.xml
+ }
+
+ FILE FREEFORM = 0AE323D6-2EBE-11E8-8349-9BA636A0D80C {
+ SECTION UI = "Panel_sharp_1080p_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_sharp_1080p_cmd.xml
+ }
+
+ FILE FREEFORM = 87273B42-311D-11E8-9324-DFB2DADFC3D1 {
+ SECTION UI = "Panel_truly_1080p_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_truly_1080p_cmd.xml
+ }
+
+ FILE FREEFORM = BAFD3200-311D-11E8-8651-0FB3CACF38FB {
+ SECTION UI = "Panel_truly_1080p_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_truly_1080p_vid.xml
+ }
+
+ FILE FREEFORM = 88CA5ABF-D0AC-4093-A68C-0CFAE1EF9635 {
+ SECTION UI = "Panel_boe_amoled_wqhd_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_boe_amoled_wqhd_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 6523A5C9-91CB-45C0-A2DC-25997CF23369 {
+ SECTION UI = "Panel_boe_amoled_wqhd_dsc_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_boe_amoled_wqhd_dsc_vid.xml
+ }
+
+ FILE FREEFORM = D7170685-5965-4B44-9305-37CDB199B9BE {
+ SECTION UI = "Panel_boe_amoled_fhd_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_boe_amoled_fhd_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 8F276EE4-E75E-4C3B-8BCC-C37771E26478 {
+ SECTION UI = "Panel_nt36860_wqhd_dsc_cmd.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_nt36860_wqhd_dsc_cmd.xml
+ }
+
+ FILE FREEFORM = 6F2D4884-D8A0-11E9-AF7A-D77B1FE990EC {
+ SECTION UI = "Panel_nt36860_wqhd_dsc_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_nt36860_wqhd_dsc_vid.xml
+ }
+
+ FILE FREEFORM = D7170685-5965-4B44-9305-37CDB199B9BF {
+ SECTION UI = "Panel_nt36672e_fhd_plus_60hz_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_60hz_vid.xml
+ }
+
+ FILE FREEFORM = 8F276EE4-E75E-4C3B-8BCC-C37771E26479 {
+ SECTION UI = "Panel_nt36672e_fhd_plus_120hz_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_120hz_vid.xml
+ }
+
+ FILE FREEFORM = 6F2D4884-D8A0-11E9-AF7A-D77B1FE990ED {
+ SECTION UI = "Panel_nt36672e_fhd_plus_144hz_vid.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_nt36672e_fhd_plus_144hz_vid.xml
+ }
+
+ FILE FREEFORM = 9874B60A-6B80-4D76-8EEB-7862C780EC03 {
+ SECTION UI = "Panel_r66451_144hz_fhd_plus_dsc_cmd_cphy.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_r66451_144hz_fhd_plus_dsc_cmd_cphy.xml
+ }
+
+ FILE FREEFORM = 0256CEAF-99CF-49F4-A9C8-D9F1755A5E6C {
+ SECTION UI = "Panel_r66451_120hz_fhd_plus_dsc_cmd_cphy.xml"
+ SECTION RAW = Binaries/redwood/RawFiles/Panel_r66451_120hz_fhd_plus_dsc_cmd_cphy.xml
+ }
+!endif
+
+ FILE FREEFORM = 45FE4B7C-150C-45DA-A021-4BEB2048EC6F {
+ SECTION UI = "QcomChargerCfg.cfg"
+ SECTION RAW = Binaries/redwood/RawFiles/QcomChargerCfg.cfg
+ }
+
+ FILE FREEFORM = F780C779-DD7C-47CD-BD1A-5EB414C51704 {
+ SECTION UI = "BATTERY.PROVISION"
+ SECTION RAW = Binaries/redwood/RawFiles/BATTERY.PROVISION
+ }
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/ConfigurationMapLib/ConfigurationMapLib.c b/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/ConfigurationMapLib/ConfigurationMapLib.c
new file mode 100644
index 0000000..d812a5f
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/ConfigurationMapLib/ConfigurationMapLib.c
@@ -0,0 +1,57 @@
+#include <Library/ConfigurationMapLib.h>
+
+STATIC
+EFI_CONFIGURATION_ENTRY_DESCRIPTOR
+gConfigurationDescriptor[] = {
+ // Configuration Map
+ {"NumCpusFuseAddr", 0x5C04C},
+ {"EnableShell", 0x1},
+ {"InitialPagePoolCount", 0x700},
+ {"SharedIMEMBaseAddr", 0x146AA000},
+ {"DloadCookieAddr", 0x01FD3000},
+ {"DloadCookieValue", 0x10},
+ {"NumCpus", 8},
+ {"NumActiveCores", 8},
+ {"MaxLogFileSize", 0x400000},
+ {"UefiMemUseThreshold", 0xE1},
+ {"USBHS1_Config", 0x0},
+ {"UsbFnIoRevNum", 0x00010001},
+ {"PwrBtnShutdownFlag", 0x0},
+ {"Sdc1GpioConfigOn", 0x1E92},
+ {"Sdc2GpioConfigOn", 0x1E92},
+ {"Sdc1GpioConfigOff", 0xA00},
+ {"Sdc2GpioConfigOff", 0xA00},
+ {"EnableSDHCSwitch", 0x1},
+ {"EnableUfsIOC", 1},
+ {"UfsSmmuConfigForOtherBootDev", 1},
+ {"UEFIExitUfsSSURequired", 1},
+ {"SecurityFlag", 0xC4},
+ {"DetectRetailUserAttentionHotkey", 0x00},
+ {"DetectRetailUserAttentionHotkeyCode", 0x17},
+ {"EnableOEMSetupAppInRetail", 0x0},
+ {"EnableLogFsSyncInRetail", 0x1},
+ {"ShmBridgememSize", 0xA00000},
+ {"EnableMultiThreading", 1},
+ {"MaxCoreCnt", 8},
+ {"EarlyInitCoreCnt", 2},
+ {"EnableUefiSecAppDebugLogDump", 0x0},
+ {"AllowNonPersistentVarsInRetail", 0x1},
+ {"EnableDisplayThread", 0x0},
+ {"EnableDisplayImageFv", 0x1},
+ {"DDRInfoNotifyFlag", 0x0},
+ {"EnableVariablePolicyEngine", 0},
+ {"EnableACPIFallback", 0x0},
+ {"EnableMultiCoreFvDecompression", 1},
+ {"EUDEnableAddr", 0x88E2000},
+ {"MinidumpTALoadingCfg", 0x0}
+};
+
+VOID
+GetConfigurationMap (
+ OUT EFI_CONFIGURATION_ENTRY_DESCRIPTOR **ConfigurationDescriptor,
+ OUT UINT8 *ConfigurationDescriptorCount)
+{
+ // Pass Data
+ *ConfigurationDescriptor = gConfigurationDescriptor;
+ *ConfigurationDescriptorCount = ARRAY_SIZE (gConfigurationDescriptor);
+}
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/ConfigurationMapLib/ConfigurationMapLib.inf b/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/ConfigurationMapLib/ConfigurationMapLib.inf
new file mode 100644
index 0000000..780dbd4
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/ConfigurationMapLib/ConfigurationMapLib.inf
@@ -0,0 +1,14 @@
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ConfigurationMapLib
+ FILE_GUID = 5F4798D0-24A3-4519-B4D5-AEE08C3EAAB3
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ConfigurationMapLib
+
+[Sources]
+ ConfigurationMapLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ QcomPkg/QcomPkg.dec
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/MemoryMapLib/MemoryMapLib.c b/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/MemoryMapLib/MemoryMapLib.c
new file mode 100644
index 0000000..b902cd4
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/MemoryMapLib/MemoryMapLib.c
@@ -0,0 +1,78 @@
+#include <Library/MemoryMapLib.h>
+
+STATIC
+EFI_MEMORY_REGION_DESCRIPTOR
+gMemoryDescriptor[] = {
+ // Name, Address, Length, HobOption, ResourceType, ResourceAttribute, MemoryType, ArmAttribute
+
+ // DDR Regions
+ {"HYP", 0x80000000, 0x00600000, AddMem, MEM_RES, SYS_MEM_CAP, Reserv, WRITE_BACK_XN},
+ {"AOP CMD", 0x80600000, 0x00260000, AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"AOP CMD DB", 0x80860000, 0x00020000, AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"Reserved", 0x80880000, 0x00004000, AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"XBL Log Buffer", 0x80884000, 0x00010000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN},
+ {"GPU PRR", 0x80894000, 0x00001000, AddMem, MEM_RES, WRITE_COMBINEABLE, Reserv, UNCACHED_UNBUFFERED_XN },
+ {"TPMControl", 0x808A4000, 0x00010000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"APSS", 0x808FF000, 0x00001000, AddMem, SYS_MEM, SYS_MEM_CAP, Conv, WRITE_BACK_XN},
+ {"SMEM", 0x80900000, 0x00200000, AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"CPUCP", 0x80B00000, 0x00100000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"WLAN FW", 0x80C00000, 0x00C00000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"CDSP Secure Heap", 0x81800000, 0x01E00000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"Sched Heap", 0x83600000, 0x00400000, AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN},
+ {"PIL Reserved", 0x85300000, 0x19300000, AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"FV Region", 0x9F800000, 0x00200000, AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN},
+ {"ABOOT FV", 0x9FA00000, 0x00200000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN},
+ {"FD Reserved", 0x9FC00000, 0x00100000, AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK},
+ {"UEFI FD", 0x9FD00000, 0x00200000, AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK},
+ {"SEC Heap", 0x9FF00000, 0x0008C000, AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN},
+ {"MMU PageTables", 0x9FF8D000, 0x00003000, AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN},
+ {"UEFI Stack", 0x9FF90000, 0x00040000, AddMem, SYS_MEM, SYS_MEM_CAP, BsData, WRITE_BACK_XN},
+ {"Log Buffer", 0x9FFF7000, 0x00008000, AddMem, SYS_MEM, SYS_MEM_CAP, RtData, WRITE_BACK_XN},
+ {"Info Blk", 0x9FFFF000, 0x00001000, AddMem, SYS_MEM, SYS_MEM_CAP, RtData, WRITE_BACK_XN},
+ {"USB UCSI Temp", 0xA0000000, 0x00002000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"MPSS_EFS", 0xA0800000, 0x00300000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"HYP RESERVED", 0xB0000000, 0x09700000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN},
+ {"Reserv", 0xC0000000, 0x00100000, AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"TAGS", 0xC0100000, 0x01200000, AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"QTEE", 0xC1300000, 0x00500000, AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"TZApps Reserved", 0xC1800000, 0x05000000, HobOnlyNoCacheSetting, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"ADSP RPC", 0xC6800000, 0x00500000, AddMem, MEM_RES, UNCACHEABLE, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"DXE Heap", 0xC6D00000, 0x07800000, AddMem, SYS_MEM, SYS_MEM_CAP, Conv, WRITE_BACK_XN},
+ {"TGCM", 0xCE500000, 0x01400000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, UNCACHED_UNBUFFERED_XN},
+ {"Guest VM", 0xD0000000, 0x10000000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN},
+ {"DBI Dump", 0xE0000000, 0x00F00000, NoHob, MMAP_IO, INITIALIZED, Conv, UNCACHED_UNBUFFERED_XN},
+ {"Display Reserved", 0xE1000000, 0x02400000, AddMem, MEM_RES, SYS_MEM_CAP, Reserv, WRITE_THROUGH_XN},
+ {"APSS Ext", 0xE3400000, 0x01700000, AddMem, SYS_MEM, SYS_MEM_CAP, Conv, WRITE_BACK_XN},
+ {"XNU Payload", 0xF0000000, 0x04000000, AddMem, SYS_MEM, SYS_MEM_CAP, Reserv, WRITE_BACK_XN},
+
+ // Other Memory Regions
+ {"IMEM Base", 0x14680000, 0x0002B000, NoHob, MMAP_IO, INITIALIZED, Conv, NS_DEVICE},
+ {"IMEM Cookie Base", 0x146AA000, 0x00001000, AddDev, MMAP_IO, INITIALIZED, Conv, NS_DEVICE},
+
+ // Register Regions
+ {"IPC_ROUTER_TOP", 0x00400000, 0x00100000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"SECURITY CONTROL", 0x00780000, 0x00010000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"PERIPH_SS_SDC1", 0x007C0000, 0x00100000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"QUP", 0x00900000, 0x00200000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"PRNG_CFG_PRNG", 0x010D0000, 0x00010000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"PCIE_1_AHB", 0x01C08000, 0x00008000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"CRYPTO0 CRYPTO", 0x01DC0000, 0x00040000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"TCSR_TCSR_REGS", 0x01FC0000, 0x00030000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"PERIPH_SS", 0x08800000, 0x00200000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"USB", 0x0A600000, 0x04000000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"AOSS", 0x0B000000, 0x04000000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"TLMM", 0x0F100000, 0x00300000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"SMMU", 0x15000000, 0x00200000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"APSS_HM", 0x17800000, 0x00E00000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE},
+ {"PCIE_1_AXI", 0x40000000, 0x02000000, AddDev, MMAP_IO, UNCACHEABLE, MmIO, NS_DEVICE}
+};
+
+VOID
+GetMemoryMap (
+ OUT EFI_MEMORY_REGION_DESCRIPTOR **MemoryDescriptor,
+ OUT UINT8 *MemoryDescriptorCount)
+{
+ // Pass Data
+ *MemoryDescriptor = gMemoryDescriptor;
+ *MemoryDescriptorCount = ARRAY_SIZE (gMemoryDescriptor);
+}
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/MemoryMapLib/MemoryMapLib.inf b/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/MemoryMapLib/MemoryMapLib.inf
new file mode 100644
index 0000000..3ba49ad
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/Library/MemoryMapLib/MemoryMapLib.inf
@@ -0,0 +1,15 @@
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = MemoryMapLib
+ FILE_GUID = D664A3B1-AF81-48F9-9412-A99D81AE96CE
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = MemoryMapLib
+
+[Sources]
+ MemoryMapLib.c
+
+[Packages]
+ ArmPkg/ArmPkg.dec
+ MdePkg/MdePkg.dec
+ SiliciumPkg/SiliciumPkg.dec
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/redwood.dec b/uefi/files/Platforms/Xiaomi/redwoodPkg/redwood.dec
new file mode 100644
index 0000000..e69de29
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/redwood.dsc b/uefi/files/Platforms/Xiaomi/redwoodPkg/redwood.dsc
new file mode 100644
index 0000000..2cd307a
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/redwood.dsc
@@ -0,0 +1,90 @@
+##
+# Copyright (c) 2011 - 2022, ARM Limited. All rights reserved.
+# Copyright (c) 2014, Linaro Limited. All rights reserved.
+# Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.
+# Copyright (c) 2018, Bingxing Wang. All rights reserved.
+# Copyright (c) Microsoft Corporation.
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+################################################################################
+#
+# Defines Section - statements that will be processed to create a Makefile.
+#
+################################################################################
+[Defines]
+ PLATFORM_NAME = redwood
+ PLATFORM_GUID = 62B40F33-4011-4ACB-8348-1A6BB928C8A6
+ PLATFORM_VERSION = 0.1
+ DSC_SPECIFICATION = 0x00010005
+ OUTPUT_DIRECTORY = Build/redwoodPkg
+ SUPPORTED_ARCHITECTURES = AARCH64
+ BUILD_TARGETS = RELEASE|DEBUG
+ SKUID_IDENTIFIER = DEFAULT
+ FLASH_DEFINITION = redwoodPkg/redwood.fdf
+ USE_CUSTOM_DISPLAY_DRIVER = 0
+
+ #
+ # 0 = SM7325
+ # 1 = SM7325-AE
+ # 2 = SM7325-AF
+ #
+ SOC_TYPE = 0
+
+!include KodiakPkg/KodiakPkg.dsc.inc
+
+[PcdsFixedAtBuild]
+ #
+ # DDR Memory
+ #
+ gArmTokenSpaceGuid.PcdSystemMemoryBase|0x80000000
+
+ #
+ # UEFI Stack
+ #
+ gArmPlatformTokenSpaceGuid.PcdCPUCoresStackBase|0x9FF90000
+ gArmPlatformTokenSpaceGuid.PcdCPUCorePrimaryStackSize|0x40000
+
+ #
+ # SMBIOS
+ #
+ gSiliciumPkgTokenSpaceGuid.PcdSmbiosSystemManufacturer|"Xiaomi"
+ gSiliciumPkgTokenSpaceGuid.PcdSmbiosSystemModel|"POCO X5 Pro 5G"
+ gSiliciumPkgTokenSpaceGuid.PcdSmbiosSystemRetailModel|"redwood"
+ gSiliciumPkgTokenSpaceGuid.PcdSmbiosSystemRetailSku|"POCO_X5_Pro_5G_redwood"
+ gSiliciumPkgTokenSpaceGuid.PcdSmbiosSystemBoardModel|"POCO X5 Pro 5G"
+
+ #
+ # Simple Frame Buffer
+ #
+ gSiliciumPkgTokenSpaceGuid.PcdFrameBufferWidth|1080
+ gSiliciumPkgTokenSpaceGuid.PcdFrameBufferHeight|2400
+ gSiliciumPkgTokenSpaceGuid.PcdFrameBufferColorDepth|32
+
+ #
+ # Platform PEI
+ #
+ gQcomPkgTokenSpaceGuid.PcdPlatformType|"LA"
+
+ #
+ # Storage
+ #
+ gQcomPkgTokenSpaceGuid.PcdStorageIsUfs3|FALSE
+
+[LibraryClasses]
+ #
+ # Memory Libraries
+ #
+ MemoryMapLib|redwoodPkg/Library/MemoryMapLib/MemoryMapLib.inf
+
+ #
+ # QCOM Libraries
+ #
+ ConfigurationMapLib|redwoodPkg/Library/ConfigurationMapLib/ConfigurationMapLib.inf
+
+[Components]
+ #
+ # ACPI Tables
+ #
+ lisa/AcpiTables.inf
diff --git a/uefi/files/Platforms/Xiaomi/redwoodPkg/redwood.fdf b/uefi/files/Platforms/Xiaomi/redwoodPkg/redwood.fdf
new file mode 100644
index 0000000..eec4720
--- /dev/null
+++ b/uefi/files/Platforms/Xiaomi/redwoodPkg/redwood.fdf
@@ -0,0 +1,133 @@
+##
+# Copyright (c) 2018, Linaro Limited. All rights reserved.
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+################################################################################
+#
+# FD Section
+# The [FD] Section is made up of the definition statements and a
+# description of what goes into the Flash Device Image. Each FD section
+# defines one flash "device" image. A flash device image may be one of
+# the following: Removable media bootable image (like a boot floppy
+# image,) an Option ROM image (that would be "flashed" into an add-in
+# card,) a System "Flash" image (that would be burned into a system's
+# flash) or an Update ("Capsule") image that will be used to update and
+# existing system flash.
+#
+################################################################################
+
+[FD.SILICIUM_UEFI]
+BaseAddress = $(FD_BASE)|gArmTokenSpaceGuid.PcdFdBaseAddress # The base address of the FLASH Device.
+Size = $(FD_SIZE)|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the FLASH Device
+ErasePolarity = 1
+
+# This one is tricky, it must be: BlockSize * NumBlocks = Size
+BlockSize = 0x1000
+NumBlocks = $(FD_BLOCKS)
+
+################################################################################
+#
+# Following are lists of FD Region layout which correspond to the locations of different
+# images within the flash device.
+#
+# Regions must be defined in ascending order and may not overlap.
+#
+# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
+# the pipe "|" character, followed by the size of the region, also in hex with the leading
+# "0x" characters. Like:
+# Offset|Size
+# PcdOffsetCName|PcdSizeCName
+# RegionType <FV, DATA, or FILE>
+#
+################################################################################
+
+0x00000000|$(FD_SIZE)
+gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
+FV = FVMAIN_COMPACT
+
+################################################################################
+#
+# FV Section
+#
+# [FV] section is used to define what components or modules are placed within a flash
+# device file. This section also defines order the components and modules are positioned
+# within the image. The [FV] section consists of define statements, set statements and
+# module statements.
+#
+################################################################################
+
+[FV.FvMain]
+FvNameGuid = CD8D4C84-20AD-4073-8A28-3400FAE05941
+BlockSize = 0x1000
+NumBlocks = 0 # This FV gets compressed so make it just big enough
+FvAlignment = 8 # FV alignment and FV attributes setting.
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ !include Include/APRIORI.inc
+ !include Include/DXE.inc
+ !include Include/RAW.inc
+
+ # RAM Manager
+ INF SiliciumPkg/Drivers/RamManagerDxe/RamManagerDxe.inf
+
+ # SmBios
+ INF MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf
+ INF SiliciumPkg/Drivers/SmBiosTableDxe/SmBiosTableDxe.inf
+
+ # ACPI
+ INF MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf
+ INF MdeModulePkg/Universal/Acpi/AcpiPlatformDxe/AcpiPlatformDxe.inf
+ INF RuleOverride = ACPITABLE lisa/AcpiTables.inf
+
+ # Device Tree
+ #INF EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.inf
+ #FILE FREEFORM = 25462CDA-221F-47DF-AC1D-259CFAA4E326 {
+ # SECTION RAW = redwoodPkg/FdtBlob/sm7325-xiaomi-lisa.dtb
+ # SECTION UI = "DeviceTreeBlob"
+ #}
+
+ !include QcomPkg/Extra.fdf.inc
+
+[FV.FVMAIN_COMPACT]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF SiliciumPkg/Sec/Sec.inf
+
+ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
+ SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
+ SECTION FV_IMAGE = FVMAIN
+ }
+ }
+
+ !include SiliciumPkg/Common.fdf.inc
diff --git a/uefi/files/Resources/Configs/redwood.toml b/uefi/files/Resources/Configs/redwood.toml
new file mode 100755
index 0000000..4b2e1a7
--- /dev/null
+++ b/uefi/files/Resources/Configs/redwood.toml
@@ -0,0 +1,25 @@
+#
+# Boot Shim Configs
+#
+[boot_shim]
+requires_kernel_header = true
+
+#
+# UEFI FD Configs
+#
+[uefi_fd]
+base = 0x9FD00000
+size = 0x200000
+
+#
+# Android Boot Image Kernel Configs
+#
+[boot_image_kernel]
+kernel_compression = "gzip"
+append_dtb = true
+
+#
+# Android Boot Image Configs
+#
+[boot_image]
+header_version = 1
diff --git a/uefi/files/Resources/DTBs/redwood.dtb b/uefi/files/Resources/DTBs/redwood.dtb
new file mode 100644
index 0000000..123163c
Binary files /dev/null and b/uefi/files/Resources/DTBs/redwood.dtb differ
diff --git a/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.c b/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.c
new file mode 100644
index 0000000..65ef539
--- /dev/null
+++ b/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.c
@@ -0,0 +1,304 @@
+/**
+ XNU loader for redwood, stage 0: diagnostics only.
+
+ Runs when BDS finds nothing to boot. Collects what the real loader will need
+ (exception level, CPU feature registers, framebuffer, memory map, payload),
+ writes it as text to the raw "logdump" partition so it can be read back from
+ Android over adb, and cold-resets. Nothing is shown to the user on purpose:
+ the phone is driven unattended.
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <Uefi.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PrintLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+
+#include <Protocol/BlockIo.h>
+#include <Protocol/GraphicsOutput.h>
+#include <Protocol/PartitionInfo.h>
+
+#include "XnuLoader.h"
+
+#define LOG_SIZE SIZE_256KB
+
+STATIC CHAR8 *mLog;
+STATIC UINTN mLogLen;
+
+STATIC
+VOID
+EFIAPI
+Log (
+ IN CONST CHAR8 *Format,
+ ...)
+{
+ VA_LIST Marker;
+
+ if (mLog == NULL || mLogLen >= LOG_SIZE - 512) {
+ return;
+ }
+
+ VA_START (Marker, Format);
+ mLogLen += AsciiVSPrint (mLog + mLogLen, LOG_SIZE - mLogLen, Format, Marker);
+ VA_END (Marker);
+}
+
+#define READ_SYSREG(Name) ({ UINT64 _Value; __asm__ volatile ("mrs %0, " #Name : "=r" (_Value)); _Value; })
+
+STATIC
+EFI_BLOCK_IO_PROTOCOL *
+FindPartition (
+ IN CONST CHAR16 *Name)
+{
+ EFI_STATUS Status;
+ EFI_HANDLE *Handles;
+ UINTN Count;
+
+ Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiPartitionInfoProtocolGuid, NULL, &Count, &Handles);
+ if (EFI_ERROR (Status)) {
+ return NULL;
+ }
+
+ for (UINTN i = 0; i < Count; i++) {
+ EFI_PARTITION_INFO_PROTOCOL *Info;
+ EFI_BLOCK_IO_PROTOCOL *BlockIo;
+
+ Status = gBS->HandleProtocol (Handles[i], &gEfiPartitionInfoProtocolGuid, (VOID **)&Info);
+ if (EFI_ERROR (Status) || Info->Type != PARTITION_TYPE_GPT) {
+ continue;
+ }
+
+ if (StrnCmp (Info->Info.Gpt.PartitionName, Name, 36) != 0) {
+ continue;
+ }
+
+ Status = gBS->HandleProtocol (Handles[i], &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
+ if (!EFI_ERROR (Status)) {
+ return BlockIo;
+ }
+ }
+
+ return NULL;
+}
+
+STATIC
+VOID
+LogCpu ()
+{
+ Log ("[cpu]\n");
+ Log ("CurrentEL=%lx\n", READ_SYSREG (CurrentEL) >> 2);
+ Log ("MIDR_EL1=%016lx\n", READ_SYSREG (MIDR_EL1));
+ Log ("ID_AA64MMFR0_EL1=%016lx\n", READ_SYSREG (ID_AA64MMFR0_EL1));
+ Log ("ID_AA64MMFR1_EL1=%016lx\n", READ_SYSREG (ID_AA64MMFR1_EL1));
+ Log ("ID_AA64MMFR2_EL1=%016lx\n", READ_SYSREG (ID_AA64MMFR2_EL1));
+ Log ("ID_AA64PFR0_EL1=%016lx\n", READ_SYSREG (ID_AA64PFR0_EL1));
+ Log ("ID_AA64PFR1_EL1=%016lx\n", READ_SYSREG (ID_AA64PFR1_EL1));
+ Log ("ID_AA64ISAR0_EL1=%016lx\n", READ_SYSREG (ID_AA64ISAR0_EL1));
+ Log ("ID_AA64ISAR1_EL1=%016lx\n", READ_SYSREG (ID_AA64ISAR1_EL1));
+ Log ("ID_AA64DFR0_EL1=%016lx\n", READ_SYSREG (ID_AA64DFR0_EL1));
+ Log ("SCTLR_EL1=%016lx\n", READ_SYSREG (SCTLR_EL1));
+ Log ("TCR_EL1=%016lx\n", READ_SYSREG (TCR_EL1));
+ Log ("MAIR_EL1=%016lx\n", READ_SYSREG (MAIR_EL1));
+ Log ("TTBR0_EL1=%016lx\n", READ_SYSREG (TTBR0_EL1));
+ Log ("VBAR_EL1=%016lx\n", READ_SYSREG (VBAR_EL1));
+ Log ("CNTFRQ_EL0=%ld\n", READ_SYSREG (CNTFRQ_EL0));
+ Log ("MPIDR_EL1=%016lx\n", READ_SYSREG (MPIDR_EL1));
+ Log ("DAIF=%lx\n", READ_SYSREG (DAIF));
+}
+
+STATIC
+VOID
+LogDisplay ()
+{
+ EFI_STATUS Status;
+ EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop;
+
+ Log ("[display]\n");
+
+ Status = gBS->LocateProtocol (&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&Gop);
+ if (EFI_ERROR (Status)) {
+ Log ("gop=missing status=%r\n", Status);
+ return;
+ }
+
+ Log ("fb_base=%lx fb_size=%lx\n", Gop->Mode->FrameBufferBase, (UINT64)Gop->Mode->FrameBufferSize);
+ Log ("width=%d height=%d stride=%d format=%d\n",
+ Gop->Mode->Info->HorizontalResolution, Gop->Mode->Info->VerticalResolution,
+ Gop->Mode->Info->PixelsPerScanLine, Gop->Mode->Info->PixelFormat);
+}
+
+STATIC
+VOID
+LogMemoryMap ()
+{
+ EFI_STATUS Status;
+ EFI_MEMORY_DESCRIPTOR *Map;
+ UINTN MapSize = 0;
+ UINTN MapKey;
+ UINTN DescSize;
+ UINT32 DescVersion;
+
+ Log ("[memmap]\n");
+
+ Status = gBS->GetMemoryMap (&MapSize, NULL, &MapKey, &DescSize, &DescVersion);
+ if (Status != EFI_BUFFER_TOO_SMALL) {
+ Log ("getmemorymap status=%r\n", Status);
+ return;
+ }
+
+ MapSize += SIZE_4KB;
+ Map = AllocatePool (MapSize);
+ if (Map == NULL) {
+ return;
+ }
+
+ Status = gBS->GetMemoryMap (&MapSize, Map, &MapKey, &DescSize, &DescVersion);
+ if (EFI_ERROR (Status)) {
+ Log ("getmemorymap status=%r\n", Status);
+ return;
+ }
+
+ for (UINTN Offset = 0; Offset < MapSize; Offset += DescSize) {
+ EFI_MEMORY_DESCRIPTOR *Desc = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)Map + Offset);
+
+ Log ("%016lx %016lx type=%d attr=%lx\n", Desc->PhysicalStart,
+ Desc->PhysicalStart + EFI_PAGES_TO_SIZE (Desc->NumberOfPages), Desc->Type, Desc->Attribute);
+ }
+
+ FreePool (Map);
+}
+
+STATIC
+VOID
+LogPayload ()
+{
+ XNU_PAYLOAD_HEADER *Header = (XNU_PAYLOAD_HEADER *)XNU_PAYLOAD_BASE;
+
+ Log ("[payload]\n");
+ Log ("base=%lx magic=%08x size=%x\n", (UINT64)XNU_PAYLOAD_BASE, Header->Magic, Header->Size);
+
+}
+
+STATIC
+VOID
+LogPersistence ()
+{
+ //
+ // Does RAM written before a reset survive it? The kernel bring-up needs a
+ // place for progress markers. Uses the tail of the reserved payload region.
+ // (Device registers are deliberately not probed here: an MMIO read of the
+ // IMEM / watchdog blocks took a synchronous exception on this platform.)
+ //
+ UINT32 *Ram = (UINT32 *)(UINTN)(XNU_PAYLOAD_BASE + XNU_PAYLOAD_MAX_SIZE - SIZE_4KB);
+
+ Log ("[persistence]\n");
+ Log ("ram_before=%08x %08x\n", Ram[0], Ram[1]);
+
+ Ram[1] = (Ram[0] == XNU_MARKER_MAGIC) ? Ram[1] + 1 : 1;
+ Ram[0] = XNU_MARKER_MAGIC;
+
+ Log ("ram_after=%08x %08x\n", Ram[0], Ram[1]);
+}
+
+STATIC
+VOID
+FlushLog ()
+{
+ EFI_STATUS Status;
+ EFI_BLOCK_IO_PROTOCOL *BlockIo;
+ UINTN BlockSize;
+ UINTN WriteSize;
+
+ BlockIo = FindPartition (XNU_LOG_PARTITION);
+ if (BlockIo == NULL) {
+ return;
+ }
+
+ BlockSize = BlockIo->Media->BlockSize;
+ WriteSize = ALIGN_VALUE (mLogLen + 1, BlockSize);
+
+ Status = BlockIo->WriteBlocks (BlockIo, BlockIo->Media->MediaId, 0, WriteSize, mLog);
+ if (!EFI_ERROR (Status)) {
+ BlockIo->FlushBlocks (BlockIo);
+ }
+}
+
+//
+// The payload is a list of named blobs. If it carries "loader.efi", that is
+// the real XNU loader: start it straight from memory, so the loader can be
+// iterated on without rebuilding this firmware.
+//
+STATIC
+VOID
+StartPayloadLoader ()
+{
+ XNU_PAYLOAD_HEADER *Header = (XNU_PAYLOAD_HEADER *)XNU_PAYLOAD_BASE;
+ UINT8 *Cursor;
+ UINT8 *End;
+
+ if (Header->Magic != XNU_PAYLOAD_MAGIC || Header->Size > XNU_PAYLOAD_MAX_SIZE) {
+ return;
+ }
+
+ Cursor = (UINT8 *)(Header + 1);
+ End = Cursor + Header->Size;
+
+ while (Cursor + sizeof (XNU_PAYLOAD_ENTRY) <= End) {
+ XNU_PAYLOAD_ENTRY *Entry = (XNU_PAYLOAD_ENTRY *)Cursor;
+
+ if (Entry->Name[0] == 0) {
+ break;
+ }
+
+ if (AsciiStrnCmp (Entry->Name, "loader.efi", sizeof (Entry->Name)) == 0) {
+ EFI_HANDLE Handle;
+
+ if (!EFI_ERROR (gBS->LoadImage (FALSE, gImageHandle, NULL, Entry + 1, Entry->Size, &Handle))) {
+ gBS->StartImage (Handle, NULL, NULL);
+ }
+
+ return;
+ }
+
+ Cursor += sizeof (XNU_PAYLOAD_ENTRY) + ALIGN_VALUE (Entry->Size, 16);
+ }
+}
+
+VOID
+XnuLoaderMain ()
+{
+ EFI_TIME Time;
+
+ // Normally does not return
+ StartPayloadLoader ();
+
+ mLog = AllocateZeroPool (LOG_SIZE);
+ if (mLog != NULL) {
+ Log ("== XNULOADER LOG v1 ==\n");
+
+ if (!EFI_ERROR (gRT->GetTime (&Time, NULL))) {
+ Log ("time=%04d-%02d-%02d %02d:%02d:%02d\n", Time.Year, Time.Month, Time.Day, Time.Hour, Time.Minute, Time.Second);
+ }
+
+ FlushLog ();
+ LogCpu ();
+ FlushLog ();
+ LogDisplay ();
+ FlushLog ();
+ LogMemoryMap ();
+ FlushLog ();
+ LogPayload ();
+ FlushLog ();
+ LogPersistence ();
+ Log ("== END ==\n");
+ FlushLog ();
+ }
+
+ // The phone is unattended: always come back to Android.
+ gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL);
+}
diff --git a/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.h b/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.h
new file mode 100644
index 0000000..d620606
--- /dev/null
+++ b/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.h
@@ -0,0 +1,33 @@
+#ifndef _XNU_LOADER_H_
+#define _XNU_LOADER_H_
+
+//
+// The boot shim copies everything appended after the UEFI FD to this address.
+// The region is marked reserved in the device memory map.
+//
+#define XNU_PAYLOAD_BASE 0xF0000000ULL
+#define XNU_PAYLOAD_MAX_SIZE 0x04000000ULL
+#define XNU_PAYLOAD_MAGIC 0x50554E58 // "XNUP"
+
+typedef struct {
+ UINT32 Magic;
+ UINT32 Size;
+} XNU_PAYLOAD_HEADER;
+
+// The header is followed by entries; an empty name ends the list.
+typedef struct {
+ CHAR8 Name[16];
+ UINT32 Size;
+ UINT32 Reserved;
+ // UINT8 Data[Size], padded to 16 bytes
+} XNU_PAYLOAD_ENTRY;
+
+// Raw GPT partition that receives the text log (read back from Android).
+#define XNU_LOG_PARTITION L"logdump"
+
+#define XNU_MARKER_MAGIC 0x584E5521 // "XNU!"
+
+VOID
+XnuLoaderMain ();
+
+#endif /* _XNU_LOADER_H_ */
diff --git a/uefi/mu-silicium.patch b/uefi/mu-silicium.patch
new file mode 100644
index 0000000..f2a117e
--- /dev/null
+++ b/uefi/mu-silicium.patch
@@ -0,0 +1,633 @@
+diff --git a/BootShim/BootShim.S b/BootShim/BootShim.S
+index 4d20855..3c3b17b 100644
+--- a/BootShim/BootShim.S
++++ b/BootShim/BootShim.S
+@@ -28,6 +28,27 @@ _CopyLoop:
+ stp x2, x3, [x5], #16
+ subs x6, x6, #16
+ b.ne _CopyLoop
++
++#ifdef PAYLOAD_BASE
++ /* x4 now points just past the FD: an optional "XNUP" payload may follow */
++ ldr w2, [x4]
++ movz w3, #0x4E58
++ movk w3, #0x5055, lsl #16
++ cmp w2, w3
++ b.ne _NoPayload
++ ldr w6, [x4, #4] /* Payload Size */
++ add x6, x6, #23 /* Header + Round Up to 16 */
++ and x6, x6, #~15
++ movz x5, #(PAYLOAD_BASE >> 16), lsl #16
++
++_PayloadLoop:
++ ldp x2, x3, [x4], #16
++ stp x2, x3, [x5], #16
++ subs x6, x6, #16
++ b.ne _PayloadLoop
++
++_NoPayload:
++#endif
+ ldr x5, =FD_BASE
+
+ _Entry:
+diff --git a/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/BootManager.c b/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/BootManager.c
+index 9b18ddb..f5bff32 100644
+--- a/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/BootManager.c
++++ b/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/BootManager.c
+@@ -1,241 +1,245 @@
+-/**
+- Copyright (C) DuoWoA authors. All rights reserved.
+- Copyright (C) Microsoft Corporation. All rights reserved.
+-
+- SPDX-License-Identifier: BSD-2-Clause-Patent
+-**/
+-
+-#include <Library/PcdLib.h>
+-#include <Library/DebugLib.h>
+-#include <Library/AcpiTableUpdateLib.h>
+-#include <Library/DeviceBootManagerLib.h>
+-#include <Library/PlatformBootManagerLib.h>
+-#include <Library/UefiRuntimeServicesTableLib.h>
+-#include <Library/UefiBootServicesTableLib.h>
+-#include <Library/SecureBootHandlerLib.h>
+-#include <Library/MemoryAllocationLib.h>
+-#include <Library/MsBootOptionsLib.h>
+-#include <Library/BootGraphicsLib.h>
+-#include <Library/BootGraphics.h>
+-#include <Library/PrintLib.h>
+-
+-#include <Configuration/BootDevices.h>
+-
+-#include "BootManager.h"
+-
+-//
+-// Global Variables
+-//
+-STATIC UINTN XPos = 0;
+-STATIC UINTN YPos = 0;
+-
+-//
+-// BDS Combo Message
+-//
+-STATIC CONST CHAR8 *ComboMessage = "[Volume Up] Boot Manager";
+-
+-VOID
+-EFIAPI
+-PlatformBootManagerBeforeConsole ()
+-{
+- // Signal End Of DXE
+- EfiEventGroupSignal (&gEfiEndOfDxeEventGroupGuid);
+-
+- // Dispatch Deferred Images
+- EfiBootManagerDispatchDeferredImages ();
+-
+- // Register Boot Options
+- MsBootOptionsLibRegisterDefaultBootOptions ();
+-
+- // Register Console Variables
+- EfiBootManagerUpdateConsoleVariable (ConIn, (EFI_DEVICE_PATH_PROTOCOL *)&KeypadDevicePath, NULL);
+- EfiBootManagerUpdateConsoleVariable (ConOut, (EFI_DEVICE_PATH_PROTOCOL *)&DisplayDevicePath, NULL);
+- EfiBootManagerUpdateConsoleVariable (ErrOut, (EFI_DEVICE_PATH_PROTOCOL *)&DisplayDevicePath, NULL);
+-
+- // Execute Secondary Before Console
+- DeviceBootManagerBeforeConsole (NULL, NULL);
+-}
+-
+-VOID
+-PostGopSetup (OUT EFI_GRAPHICS_OUTPUT_PROTOCOL **GopProtocol)
+-{
+- EFI_STATUS Status;
+- EFI_GRAPHICS_OUTPUT_PROTOCOL *LocalGopProtocol;
+-
+- // Verify Parameters
+- if (GopProtocol == NULL) {
+- return;
+- }
+-
+- // Locate GOP Protocol
+- Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID *)&LocalGopProtocol);
+- if (EFI_ERROR (Status) && Status != EFI_UNSUPPORTED) {
+- DEBUG ((EFI_D_ERROR, "%a: Failed to Locate GOP Protocol from Handle! Status = %r\n", __FUNCTION__, Status));
+- return;
+- }
+-
+- // Check Status
+- if (Status == EFI_UNSUPPORTED) {
+- // Locate GOP Protocol
+- Status = gBS->LocateProtocol (&gEfiGraphicsOutputProtocolGuid, NULL, (VOID *)&LocalGopProtocol);
+- if (EFI_ERROR (Status)) {
+- DEBUG ((EFI_D_ERROR, "%a: Failed to Locate GOP Protocol! Status = %r\n", __FUNCTION__, Status));
+- return;
+- }
+-
+- // Install GOP Protocol
+- Status = gBS->InstallProtocolInterface (&gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, EFI_NATIVE_INTERFACE, LocalGopProtocol);
+- if (EFI_ERROR (Status)) {
+- DEBUG ((EFI_D_ERROR, "%a: Failed to Install GOP Protocol onto \"ConsoleOutHandle\"! Status = %r\n", __FUNCTION__, Status));
+- }
+- }
+-
+- // Pass GOP Protocol
+- *GopProtocol = LocalGopProtocol;
+-}
+-
+-VOID
+-EFIAPI
+-PlatformBootManagerAfterConsole ()
+-{
+- EFI_STATUS Status = EFI_SUCCESS;
+- EFI_GRAPHICS_OUTPUT_PROTOCOL *GopProtocol = NULL;
+-
+- // Post Setup GOP
+- PostGopSetup (&GopProtocol);
+-
+- // Display Boot Logo
+- Status = DisplayBootGraphic (BG_SYSTEM_LOGO);
+- if (EFI_ERROR (Status)) {
+- DEBUG ((EFI_D_ERROR, "%a: Failed to Display Boot Logo! Status = %r\n", __FUNCTION__, Status));
+- }
+-
+- // Register Key Callback
+- Status = RegisterKeyCallback ((EFI_DEVICE_PATH_PROTOCOL *)&KeypadDevicePath);
+- if (!EFI_ERROR (Status) && GopProtocol != NULL) {
+- // Set Screen Resolution
+- UINT32 ScreenWidth = GopProtocol->Mode->Info->HorizontalResolution;
+- UINT32 ScreenHeight = GopProtocol->Mode->Info->VerticalResolution;
+-
+- // Set Combo Message Position
+- XPos = (ScreenWidth - AsciiStrLen (ComboMessage) * EFI_GLYPH_WIDTH) / 2;
+- YPos = ScreenHeight * 48 / 50;
+- }
+-
+- // Execute Secondary After Console
+- DeviceBootManagerAfterConsole ();
+-}
+-
+-VOID
+-EFIAPI
+-PlatformBootManagerOnDemandConInConnect ()
+-{
+- // Execute Secondary On Demand
+- DeviceBootManagerOnDemandConInConnect ();
+-}
+-
+-VOID
+-EFIAPI
+-PlatformBootManagerProcessBootCompletion (OUT EFI_BOOT_MANAGER_LOAD_OPTION *BootOption)
+-{
+- return;
+-}
+-
+-VOID
+-EFIAPI
+-PlatformBootManagerPriorityBoot (IN OUT UINT16 **BootNext)
+-{
+- EFI_STATUS Status;
+- EFI_BOOT_MANAGER_LOAD_OPTION LoadOption;
+- BOOLEAN BootManagerFlag;
+-
+- // Unregister Key Callback
+- UnregisterKeyCallback ();
+-
+- // Get Boot Manager Flag
+- BootManagerFlag = EnterBootManager ();
+- if (BootManagerFlag == FALSE) {
+- return;
+- }
+-
+- // Get Boot Manager Load Option
+- Status = MsBootOptionsLibGetBootManagerMenu (&LoadOption, NULL);
+- if (EFI_ERROR (Status)) {
+- DEBUG ((EFI_D_ERROR, "%a: Failed to get Boot Manager Load Option! Status = %r", __FUNCTION__, Status));
+- return;
+- }
+-
+- // Execute Boot Manager Load Option
+- EfiBootManagerBoot (&LoadOption);
+- EfiBootManagerFreeLoadOption (&LoadOption);
+-}
+-
+-VOID
+-EFIAPI
+-PlatformBootManagerWaitCallback (IN UINT16 TimeoutRemain)
+-{
+- EFI_GRAPHICS_OUTPUT_BLT_PIXEL Color;
+-
+- // Verify Combo Message Position
+- if (XPos == 0 && YPos == 0) {
+- return;
+- }
+-
+- // Get Timeout Time
+- UINT16 Timeout = PcdGet16 (PcdPlatformBootTimeOut);
+-
+- // Check Remaining Timeout
+- if (TimeoutRemain == Timeout || TimeoutRemain == 0) {
+- // Set Draw Color
+- UINT8 DrawColor = (TimeoutRemain == Timeout) ? 0xFF : 0x00;
+-
+- // Set GOP Draw Color
+- Color.Red = Color.Green = Color.Blue = DrawColor;
+-
+- // Print Combo Message
+- AsciiPrintXY (XPos, YPos, &Color, NULL, ComboMessage);
+- }
+-}
+-
+-VOID
+-EFIAPI
+-PlatformBootManagerUnableToBoot ()
+-{
+- EFI_STATUS Status;
+-
+- // Execute Secondary Unable To Boot
+- DeviceBootManagerUnableToBoot ();
+-
+- // Display No Boot OS Logo
+- Status = DisplayBootGraphic (BG_NO_BOOT_OS);
+- if (EFI_ERROR (Status)) {
+- DEBUG ((EFI_D_ERROR, "%a: Failed to Display No Boot OS Logo! Status = %r\n", __FUNCTION__, Status));
+- Print (L"No Operating System Found! Please make sure that an OS is Installed.\n");
+- }
+-
+- // Wait 10s
+- gBS->Stall (10000000);
+-
+- // Shutdown
+- gRT->ResetSystem (EfiResetShutdown, EFI_SUCCESS, 0, NULL);
+-
+- // Do Cpu Dead Loop
+- CpuDeadLoop ();
+-}
+-
+-VOID
+-EFIAPI
+-PlatformBootManagerBdsEntry ()
+-{
+- EFI_STATUS Status;
+-
+- // Setup Secure Boot
+- Status = SetupSecureBoot ();
+- ASSERT_EFI_ERROR (Status);
+-
+- // Update ACPI Tables
+- UpdateAcpiTables ();
+-
+- // Execute Secondary BDS Entry
+- DeviceBootManagerBdsEntry ();
+-}
++/**
++ Copyright (C) DuoWoA authors. All rights reserved.
++ Copyright (C) Microsoft Corporation. All rights reserved.
++
++ SPDX-License-Identifier: BSD-2-Clause-Patent
++**/
++
++#include <Library/PcdLib.h>
++#include <Library/DebugLib.h>
++#include <Library/AcpiTableUpdateLib.h>
++#include <Library/DeviceBootManagerLib.h>
++#include <Library/PlatformBootManagerLib.h>
++#include <Library/UefiRuntimeServicesTableLib.h>
++#include <Library/UefiBootServicesTableLib.h>
++#include <Library/SecureBootHandlerLib.h>
++#include <Library/MemoryAllocationLib.h>
++#include <Library/MsBootOptionsLib.h>
++#include <Library/BootGraphicsLib.h>
++#include <Library/BootGraphics.h>
++#include <Library/PrintLib.h>
++
++#include <Configuration/BootDevices.h>
++
++#include "BootManager.h"
++#include "XnuLoader.h"
++
++//
++// Global Variables
++//
++STATIC UINTN XPos = 0;
++STATIC UINTN YPos = 0;
++
++//
++// BDS Combo Message
++//
++STATIC CONST CHAR8 *ComboMessage = "[Volume Up] Boot Manager";
++
++VOID
++EFIAPI
++PlatformBootManagerBeforeConsole ()
++{
++ // Signal End Of DXE
++ EfiEventGroupSignal (&gEfiEndOfDxeEventGroupGuid);
++
++ // Dispatch Deferred Images
++ EfiBootManagerDispatchDeferredImages ();
++
++ // Register Boot Options
++ MsBootOptionsLibRegisterDefaultBootOptions ();
++
++ // Register Console Variables
++ EfiBootManagerUpdateConsoleVariable (ConIn, (EFI_DEVICE_PATH_PROTOCOL *)&KeypadDevicePath, NULL);
++ EfiBootManagerUpdateConsoleVariable (ConOut, (EFI_DEVICE_PATH_PROTOCOL *)&DisplayDevicePath, NULL);
++ EfiBootManagerUpdateConsoleVariable (ErrOut, (EFI_DEVICE_PATH_PROTOCOL *)&DisplayDevicePath, NULL);
++
++ // Execute Secondary Before Console
++ DeviceBootManagerBeforeConsole (NULL, NULL);
++}
++
++VOID
++PostGopSetup (OUT EFI_GRAPHICS_OUTPUT_PROTOCOL **GopProtocol)
++{
++ EFI_STATUS Status;
++ EFI_GRAPHICS_OUTPUT_PROTOCOL *LocalGopProtocol;
++
++ // Verify Parameters
++ if (GopProtocol == NULL) {
++ return;
++ }
++
++ // Locate GOP Protocol
++ Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID *)&LocalGopProtocol);
++ if (EFI_ERROR (Status) && Status != EFI_UNSUPPORTED) {
++ DEBUG ((EFI_D_ERROR, "%a: Failed to Locate GOP Protocol from Handle! Status = %r\n", __FUNCTION__, Status));
++ return;
++ }
++
++ // Check Status
++ if (Status == EFI_UNSUPPORTED) {
++ // Locate GOP Protocol
++ Status = gBS->LocateProtocol (&gEfiGraphicsOutputProtocolGuid, NULL, (VOID *)&LocalGopProtocol);
++ if (EFI_ERROR (Status)) {
++ DEBUG ((EFI_D_ERROR, "%a: Failed to Locate GOP Protocol! Status = %r\n", __FUNCTION__, Status));
++ return;
++ }
++
++ // Install GOP Protocol
++ Status = gBS->InstallProtocolInterface (&gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, EFI_NATIVE_INTERFACE, LocalGopProtocol);
++ if (EFI_ERROR (Status)) {
++ DEBUG ((EFI_D_ERROR, "%a: Failed to Install GOP Protocol onto \"ConsoleOutHandle\"! Status = %r\n", __FUNCTION__, Status));
++ }
++ }
++
++ // Pass GOP Protocol
++ *GopProtocol = LocalGopProtocol;
++}
++
++VOID
++EFIAPI
++PlatformBootManagerAfterConsole ()
++{
++ EFI_STATUS Status = EFI_SUCCESS;
++ EFI_GRAPHICS_OUTPUT_PROTOCOL *GopProtocol = NULL;
++
++ // Post Setup GOP
++ PostGopSetup (&GopProtocol);
++
++ // Display Boot Logo
++ Status = DisplayBootGraphic (BG_SYSTEM_LOGO);
++ if (EFI_ERROR (Status)) {
++ DEBUG ((EFI_D_ERROR, "%a: Failed to Display Boot Logo! Status = %r\n", __FUNCTION__, Status));
++ }
++
++ // Register Key Callback
++ Status = RegisterKeyCallback ((EFI_DEVICE_PATH_PROTOCOL *)&KeypadDevicePath);
++ if (!EFI_ERROR (Status) && GopProtocol != NULL) {
++ // Set Screen Resolution
++ UINT32 ScreenWidth = GopProtocol->Mode->Info->HorizontalResolution;
++ UINT32 ScreenHeight = GopProtocol->Mode->Info->VerticalResolution;
++
++ // Set Combo Message Position
++ XPos = (ScreenWidth - AsciiStrLen (ComboMessage) * EFI_GLYPH_WIDTH) / 2;
++ YPos = ScreenHeight * 48 / 50;
++ }
++
++ // Execute Secondary After Console
++ DeviceBootManagerAfterConsole ();
++}
++
++VOID
++EFIAPI
++PlatformBootManagerOnDemandConInConnect ()
++{
++ // Execute Secondary On Demand
++ DeviceBootManagerOnDemandConInConnect ();
++}
++
++VOID
++EFIAPI
++PlatformBootManagerProcessBootCompletion (OUT EFI_BOOT_MANAGER_LOAD_OPTION *BootOption)
++{
++ return;
++}
++
++VOID
++EFIAPI
++PlatformBootManagerPriorityBoot (IN OUT UINT16 **BootNext)
++{
++ EFI_STATUS Status;
++ EFI_BOOT_MANAGER_LOAD_OPTION LoadOption;
++ BOOLEAN BootManagerFlag;
++
++ // Unregister Key Callback
++ UnregisterKeyCallback ();
++
++ // Get Boot Manager Flag
++ BootManagerFlag = EnterBootManager ();
++ if (BootManagerFlag == FALSE) {
++ return;
++ }
++
++ // Get Boot Manager Load Option
++ Status = MsBootOptionsLibGetBootManagerMenu (&LoadOption, NULL);
++ if (EFI_ERROR (Status)) {
++ DEBUG ((EFI_D_ERROR, "%a: Failed to get Boot Manager Load Option! Status = %r", __FUNCTION__, Status));
++ return;
++ }
++
++ // Execute Boot Manager Load Option
++ EfiBootManagerBoot (&LoadOption);
++ EfiBootManagerFreeLoadOption (&LoadOption);
++}
++
++VOID
++EFIAPI
++PlatformBootManagerWaitCallback (IN UINT16 TimeoutRemain)
++{
++ EFI_GRAPHICS_OUTPUT_BLT_PIXEL Color;
++
++ // Verify Combo Message Position
++ if (XPos == 0 && YPos == 0) {
++ return;
++ }
++
++ // Get Timeout Time
++ UINT16 Timeout = PcdGet16 (PcdPlatformBootTimeOut);
++
++ // Check Remaining Timeout
++ if (TimeoutRemain == Timeout || TimeoutRemain == 0) {
++ // Set Draw Color
++ UINT8 DrawColor = (TimeoutRemain == Timeout) ? 0xFF : 0x00;
++
++ // Set GOP Draw Color
++ Color.Red = Color.Green = Color.Blue = DrawColor;
++
++ // Print Combo Message
++ AsciiPrintXY (XPos, YPos, &Color, NULL, ComboMessage);
++ }
++}
++
++VOID
++EFIAPI
++PlatformBootManagerUnableToBoot ()
++{
++ EFI_STATUS Status;
++
++ // Nothing else to boot: hand over to the XNU loader (does not return)
++ XnuLoaderMain ();
++
++ // Execute Secondary Unable To Boot
++ DeviceBootManagerUnableToBoot ();
++
++ // Display No Boot OS Logo
++ Status = DisplayBootGraphic (BG_NO_BOOT_OS);
++ if (EFI_ERROR (Status)) {
++ DEBUG ((EFI_D_ERROR, "%a: Failed to Display No Boot OS Logo! Status = %r\n", __FUNCTION__, Status));
++ Print (L"No Operating System Found! Please make sure that an OS is Installed.\n");
++ }
++
++ // Wait 10s
++ gBS->Stall (10000000);
++
++ // Shutdown
++ gRT->ResetSystem (EfiResetShutdown, EFI_SUCCESS, 0, NULL);
++
++ // Do Cpu Dead Loop
++ CpuDeadLoop ();
++}
++
++VOID
++EFIAPI
++PlatformBootManagerBdsEntry ()
++{
++ EFI_STATUS Status;
++
++ // Setup Secure Boot
++ Status = SetupSecureBoot ();
++ ASSERT_EFI_ERROR (Status);
++
++ // Update ACPI Tables
++ UpdateAcpiTables ();
++
++ // Execute Secondary BDS Entry
++ DeviceBootManagerBdsEntry ();
++}
+diff --git a/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/BootManagerLib.inf b/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/BootManagerLib.inf
+index 2310dc6..12a5a5d 100644
+--- a/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/BootManagerLib.inf
++++ b/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/BootManagerLib.inf
+@@ -1,50 +1,55 @@
+-##
+-# Copyright (C) Microsoft Corporation. All rights reserved.
+-# SPDX-License-Identifier: BSD-2-Clause-Patent
+-##
+-
+-[Defines]
+- INF_VERSION = 0x00010018
+- BASE_NAME = BootManagerLib
+- FILE_GUID = DF8F3324-5448-46BC-872C-BE198ECF2F76
+- VERSION_STRING = 1.0
+- MODULE_TYPE = DXE_DRIVER
+- UEFI_SPECIFICATION_VERSION = 2.7
+- LIBRARY_CLASS = PlatformBootManagerLib|DXE_DRIVER
+-
+-[Sources]
+- BootManager.c
+- KeyCallback.c
+-
+-[Packages]
+- MdePkg/MdePkg.dec
+- PcBdsPkg/PcBdsPkg.dec
+- MsCorePkg/MsCorePkg.dec
+- MsGraphicsPkg/MsGraphicsPkg.dec
+- MdeModulePkg/MdeModulePkg.dec
+- SiliciumPkg/SiliciumPkg.dec
+-
+-[LibraryClasses]
+- PcdLib
+- DebugLib
+- AcpiTableUpdateLib
+- DeviceBootManagerLib
+- UefiRuntimeServicesTableLib
+- UefiBootServicesTableLib
+- SecureBootHandlerLib
+- MemoryAllocationLib
+- MsBootOptionsLib
+- BootGraphicsLib
+- DevicePathLib
+- PrintLib
+-
+-[Pcd]
+- gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut
+-
+-[Guids]
+- gEfiEndOfDxeEventGroupGuid
+-
+-[Protocols]
+- gKeypadDeviceProtocolGuid
+- gEfiGraphicsOutputProtocolGuid
+- gEfiSimpleTextInputExProtocolGuid
++##
++# Copyright (C) Microsoft Corporation. All rights reserved.
++# SPDX-License-Identifier: BSD-2-Clause-Patent
++##
++
++[Defines]
++ INF_VERSION = 0x00010018
++ BASE_NAME = BootManagerLib
++ FILE_GUID = DF8F3324-5448-46BC-872C-BE198ECF2F76
++ VERSION_STRING = 1.0
++ MODULE_TYPE = DXE_DRIVER
++ UEFI_SPECIFICATION_VERSION = 2.7
++ LIBRARY_CLASS = PlatformBootManagerLib|DXE_DRIVER
++
++[Sources]
++ BootManager.c
++ XnuLoader.c
++ KeyCallback.c
++
++[Packages]
++ MdePkg/MdePkg.dec
++ PcBdsPkg/PcBdsPkg.dec
++ MsCorePkg/MsCorePkg.dec
++ MsGraphicsPkg/MsGraphicsPkg.dec
++ MdeModulePkg/MdeModulePkg.dec
++ SiliciumPkg/SiliciumPkg.dec
++
++[LibraryClasses]
++ PcdLib
++ DebugLib
++ AcpiTableUpdateLib
++ DeviceBootManagerLib
++ UefiRuntimeServicesTableLib
++ UefiBootServicesTableLib
++ SecureBootHandlerLib
++ MemoryAllocationLib
++ MsBootOptionsLib
++ BootGraphicsLib
++ DevicePathLib
++ PrintLib
++ BaseLib
++ BaseMemoryLib
++
++[Pcd]
++ gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut
++
++[Guids]
++ gEfiEndOfDxeEventGroupGuid
++
++[Protocols]
++ gKeypadDeviceProtocolGuid
++ gEfiGraphicsOutputProtocolGuid
++ gEfiSimpleTextInputExProtocolGuid
++ gEfiBlockIoProtocolGuid
++ gEfiPartitionInfoProtocolGuid
diff --git a/userland/build.sh b/userland/build.sh
new file mode 100755
index 0000000..e241614
--- /dev/null
+++ b/userland/build.sh
@@ -0,0 +1,154 @@
+#!/bin/bash
+# Build the user-space side of the bring-up.
+#
+# hello one raw-syscall program; as a RAM disk on its own it boots through mockfs
+# root.packfs the small image: our init and test programs, etc/rc, and the launchd jobs
+# (LaunchDaemons/). It travels in the payload next to the kernel (first RAM
+# disk, /dev/md0) 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)
+# REST=1 ... and the rest of them, started only when asked for (see mkjobs.py)
+# 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
+# (default: src/inject.c in backboardd, src/inject_sb.c in SpringBoard);
+# init hands the list to the kernel (etc/inject.conf -> sysctl kern.exec_inject)
+# RC_JOBS=<file> what the job com.redwood.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)
+# system.packfs the system image, the root filesystem (second RAM disk, /dev/md1): the part of
+# iOS 16.5 chosen by ../ios165/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). 3 GB; upload once per loader session with
+# `xl ramdisk userland/system.packfs`. Rebuilt when missing, when its inputs
+# (stage0, the manifest, the cryptex files) are newer, or with SYSTEM=1 (after
+# changing the recipe below).
+#
+# 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 + liblz4)
+set -e
+cd "$(dirname "$(readlink -f "$0")")"
+source ../xnu-env.sh
+
+CC="xnu-clang -arch arm64 -Os -static -nostdlib -ffreestanding -fno-stack-protector -fno-builtin -Wall -Wextra"
+LD="-Wl,-e,_start -Wl,-pagezero_size,0x100000000"
+DYN="xnu-clang -arch arm64 -isysroot ${THEOS:-$HOME/theos}/sdks/iPhoneOS16.5.sdk -O1"
+IOS=../ios165
+CACHE=$IOS/20F66__iPhone10,3_6
+# The stock iOS jobs given to launchd, roughly in the order they were brought up.
+IOS_JOBS=${JOBS-"
+ com.apple.notifyd com.apple.cfprefsd.xpc.daemon com.apple.cfprefsd.xpc.daemon.system com.apple.logd
+ com.apple.syslogd com.apple.distnoted.xpc.daemon com.apple.diagnosticd com.apple.fseventsd
+ com.apple.containermanagerd com.apple.containermanagerd.system com.apple.runningboardd
+ com.apple.backboardd com.apple.mobile.usermanagerd com.apple.mobilegestalt.xpc com.apple.lsd
+ com.apple.powerd com.apple.analyticsd com.apple.logd_helper
+ com.apple.iconservices.iconservicesagent com.apple.pluginkit.pkd
+ com.apple.SpringBoard
+"}
+# The programs (file names) started with a library of ours inside them: "LIBRARY NAME..." per line
+# (src/inject.c is libredwood.dylib, src/inject_sb.c is libredwood-sb.dylib).
+INJECT=${INJECT-"/redwood/lib/libredwood.dylib backboardd containermanagerd containermanagerd_system
+/redwood/lib/libredwood-sb.dylib SpringBoard"}
+mkdir -p obj
+
+if [ -z "$PREBUILT" ] && ! command -v ld64 >/dev/null; then PREBUILT=1; fi
+if [ -n "$PREBUILT" ]; then
+ echo "build.sh: not compiling, using the programs in prebuilt/userland"
+ for f in ../prebuilt/userland/*; do
+ # keep a file that did not change (and its time stamp): system.packfs depends on stage0
+ cmp -s "$f" "obj/$(basename "$f")" || cp "$f" obj/
+ done
+ cp obj/hello hello
+else
+ $CC $LD -o hello src/hello.c
+ $CC -Ilibmini -c libmini/mini.c -o obj/mini.o
+ $CC -c libmini/start.S -o obj/start.o
+ for prog in init child stage0; do
+ $CC -Ilibmini $LD -o obj/$prog.new src/$prog.c obj/mini.o obj/start.o
+ # keep the old file (and its time stamp) when nothing changed: system.packfs depends on stage0
+ cmp -s obj/$prog.new obj/$prog && rm obj/$prog.new || mv obj/$prog.new obj/$prog
+ done
+fi
+
+# --- the small image ------------------------------------------------------------------------------
+rm -rf root
+mkdir -p root/sbin root/bin root/etc root/share root/LaunchDaemons
+cp obj/init root/sbin/init
+cp obj/child root/bin/child
+echo "Darwin on redwood: image built $(date '+%Y-%m-%d %H:%M')" > root/etc/motd
+# 300000 bytes, byte i = (i*31 + (i>>8)) & 0xff; init verifies it through read() and mmap()
+python3 -c "import sys; sys.stdout.buffer.write(bytes((i*31 + (i>>8)) & 0xff for i in range(300000)))" > root/share/pattern.bin
+if [ -d $IOS/rootfs/usr/lib ]; then
+ if [ -z "$PREBUILT" ]; then
+ # ordinary dynamically linked programs of our own, built against the iOS 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
+ $DYN -o obj/rwtouch src/rwtouch.c
+ $DYN -framework CoreFoundation -lMobileGestalt -o obj/mg_test src/mg_test.c
+ # our library for inside stock iOS programs (the jobs in INJECT are started with it)
+ $DYN -dynamiclib -install_name /redwood/lib/libredwood.dylib -framework CoreFoundation -framework IOKit -lobjc \
+ -o obj/libredwood.dylib src/inject.c
+ $DYN -dynamiclib -install_name /redwood/lib/libredwood-sb.dylib -framework CoreFoundation -lobjc \
+ -o obj/libredwood-sb.dylib src/inject_sb.c
+ fi
+ cp obj/hello_dyn obj/svc_test obj/surf_test obj/rwtouch obj/mg_test root/bin/
+ mkdir -p root/lib
+ cp obj/libredwood.dylib obj/libredwood-sb.dylib root/lib/
+ echo "$INJECT" > root/etc/inject.conf
+ cp $IOS/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 zone
+ zone=$(timedatectl show -p Timezone --value 2>/dev/null); zone=${zone:-UTC}
+ sed -i -e 's|^l\t/usr/share/zoneinfo\t/private/var/db/timezone/zoneinfo$|l\t/usr/share/zoneinfo.default\t/private/var/db/timezone/zoneinfo|' \
+ -e "s|^l\t/var/db/timezone/zoneinfo/[^\t]*\t/private/var/db/timezone/localtime\$|l\t/var/db/timezone/zoneinfo/$zone\t/private/var/db/timezone/localtime|" root/etc/var.skel
+ # ... and the files of ours it puts there (var/): those under mobile/ belong to the user mobile
+ cp -r var root/var
+ (cd var && find . -type f | sed 's|^\./||' | sort) | while read -r f; do
+ case $f in mobile/*) owner=501 ;; *) owner=0 ;; esac
+ printf 'f\t644\t%s\t%s\t/private/var/%s\t/var/%s\n' $owner $owner "$f" "$f"
+ done >> root/etc/var.skel
+ cp ${RC:-rc.launchd} root/etc/rc
+ cp ${RC_JOBS:-rc.jobs} root/etc/rc.jobs
+ # the jobs the iOS launchd will see (/System/Library/LaunchDaemons is a symlink to this directory)
+ cp com.redwood.demo.plist root/LaunchDaemons/
+ [ -n "$IOS_JOBS" ] && OSLOG=${OSLOG-com.apple.backboardd} ./mkjobs.py ${REST:+--rest} $IOS/rootfs root/LaunchDaemons $IOS_JOBS
+fi
+../mkpackfs.py -o root.packfs root
+
+# --- the system image -----------------------------------------------------------------------------
+if [ -f $IOS/system.manifest ] && [ -f $CACHE/dyld_shared_cache_arm64 ] &&
+ { [ ! -f system.packfs ] || [ obj/stage0 -nt system.packfs ] || [ $IOS/system.manifest -nt system.packfs ] ||
+ [ $IOS/cryptex -nt system.packfs ] || [ -n "$SYSTEM" ]; }; then
+ rm -rf sysroot
+ cp -al $IOS/rootfs sysroot # hard links: no copies of the 0.5 GB
+ # launchd must load our choice of jobs, not all 500 that iOS has
+ rm -rf sysroot/System/Library/LaunchDaemons sysroot/System/Library/NanoLaunchDaemons \
+ sysroot/System/Library/LaunchAngels sysroot/System/Library/xpc/launchd.plist
+ ln -s /redwood/LaunchDaemons sysroot/System/Library/LaunchDaemons
+ mkdir -p sysroot/redwood sysroot/sbin
+ # the applications iOS installs on its first boot are system applications here (see select-system.py)
+ if [ -d sysroot/private/var/staged_system_apps ]; then
+ mv sysroot/private/var/staged_system_apps/* sysroot/Applications/
+ rm -rf sysroot/private/var
+ fi
+ mv sysroot/sbin/launchd sysroot/sbin/launchd.ios
+ cp obj/stage0 sysroot/sbin/launchd
+ # 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 cp -al $IOS/cryptex sysroot/System/Cryptexes/OS; fi
+ D=sysroot/System/Cryptexes/OS/System/Library/Caches/com.apple.dyld
+ mkdir -p $D
+ for f in $CACHE/dyld_shared_cache_arm64*; do
+ case "$f" in *.symbols) continue ;; esac # symbolication data, never mapped
+ ln "$f" $D/
+ done
+ # thousands of small files: 4K blocks for them, the kernel's 16K pages for everything bigger
+ # compressed (LZ4, read in place by packfs): half the size, which is what fits into the phone's RAM;
+ # PLAIN=1 builds the image uncompressed instead
+ ../mkpackfs.py ${PLAIN:+-b 4096 -a 16384} ${PLAIN:--z} -m $IOS/system.manifest -o system.packfs sysroot
+ rm -rf sysroot
+fi
diff --git a/userland/com.redwood.demo.plist b/userland/com.redwood.demo.plist
new file mode 100644
index 0000000..eca91e4
--- /dev/null
+++ b/userland/com.redwood.demo.plist
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.redwood.demo</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>/redwood/sbin/init</string>
+ <string>/redwood/etc/rc.jobs</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>AbandonProcessGroup</key>
+ <true/>
+ <!-- not a background job: those get their timers rounded up by a tenth of a second,
+ and the touch gestures replayed from here are a matter of milliseconds -->
+ <key>ProcessType</key>
+ <string>Interactive</string>
+ <key>StandardOutPath</key>
+ <string>/dev/console</string>
+ <key>StandardErrorPath</key>
+ <string>/dev/console</string>
+</dict>
+</plist>
diff --git a/userland/jobinfo.py b/userland/jobinfo.py
new file mode 100755
index 0000000..22ed491
--- /dev/null
+++ b/userland/jobinfo.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+"""Show stock iOS launchd jobs: jobinfo.py [-s SERVICE | LABEL...]
+With -s, find the jobs that provide a Mach service whose name contains SERVICE."""
+import glob, json, os, plistlib, sys
+ROOTFS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'ios165/rootfs')
+D = ROOTFS + '/System/Library/LaunchDaemons'
+def show(path):
+ d = plistlib.load(open(path, 'rb'))
+ prog = d.get('Program') or (d.get('ProgramArguments') or ['?'])[0]
+ keys = {k: d[k] for k in d if k in ('UserName', 'RunAtLoad', 'KeepAlive', 'LaunchEvents', 'Sockets', '_LimitLoadToBootMode',
+ 'LimitLoadToHardware', 'LimitLoadFromHardware', 'EnableTransactions', 'ProcessType',
+ '_AdditionalProperties', 'EnvironmentVariables', 'ProgramArguments')}
+ exists = os.path.isfile(ROOTFS + prog)
+ print(f"{os.path.basename(path)[:-6]}: {prog}{'' if exists else ' [not extracted]'}")
+ print(' ', json.dumps(keys, default=str)[:300])
+ print(' services:', ' '.join(sorted(d.get('MachServices', {})))[:400])
+if sys.argv[1:2] == ['-s']:
+ for path in sorted(glob.glob(D + '/*.plist')):
+ d = plistlib.load(open(path, 'rb'))
+ if any(sys.argv[2] in name for name in d.get('MachServices', {})):
+ show(path)
+else:
+ for label in sys.argv[1:]:
+ show(f'{D}/{label}.plist')
diff --git a/userland/libmini/mini.c b/userland/libmini/mini.c
new file mode 100644
index 0000000..d277543
--- /dev/null
+++ b/userland/libmini/mini.c
@@ -0,0 +1,550 @@
+/*
+ * libmini: system call wrappers, string routines and a small printf.
+ */
+#include "mini.h"
+
+int errno;
+char **environ;
+
+#define SC(n, a, b, c, d, e, f) mini_syscall((n), (long)(a), (long)(b), (long)(c), (long)(d), (long)(e), (long)(f))
+
+void
+__mini_start(long *sp)
+{
+ int argc = (int)sp[0];
+ char **argv = (char **)(sp + 1);
+
+ environ = argv + argc + 1;
+ _exit(main(argc, argv, environ));
+}
+
+void
+_exit(int status)
+{
+ for (;;) {
+ SC(SYS_exit, status, 0, 0, 0, 0, 0);
+ }
+}
+
+ssize_t
+read(int fd, void *buf, size_t count)
+{
+ return SC(SYS_read, fd, buf, count, 0, 0, 0);
+}
+
+ssize_t
+write(int fd, const void *buf, size_t count)
+{
+ return SC(SYS_write, fd, buf, count, 0, 0, 0);
+}
+
+int
+open(const char *path, int flags, int mode)
+{
+ return (int)SC(SYS_open, path, flags, mode, 0, 0, 0);
+}
+
+int
+close(int fd)
+{
+ return (int)SC(SYS_close, fd, 0, 0, 0, 0, 0);
+}
+
+off_t
+lseek(int fd, off_t offset, int whence)
+{
+ return SC(SYS_lseek, fd, offset, whence, 0, 0, 0);
+}
+
+int
+dup2(int from, int to)
+{
+ return (int)SC(SYS_dup2, from, to, 0, 0, 0, 0);
+}
+
+int
+chdir(const char *path)
+{
+ return (int)SC(SYS_chdir, path, 0, 0, 0, 0, 0);
+}
+
+pid_t
+getpid(void)
+{
+ return (pid_t)SC(SYS_getpid, 0, 0, 0, 0, 0, 0);
+}
+
+pid_t
+getppid(void)
+{
+ return (pid_t)SC(SYS_getppid, 0, 0, 0, 0, 0, 0);
+}
+
+int
+getuid(void)
+{
+ return (int)SC(SYS_getuid, 0, 0, 0, 0, 0, 0);
+}
+
+pid_t
+wait4(pid_t pid, int *status, int options, void *rusage)
+{
+ return (pid_t)SC(SYS_wait4, pid, status, options, rusage, 0, 0);
+}
+
+int
+execve(const char *path, char *const argv[], char *const envp[])
+{
+ return (int)SC(SYS_execve, path, argv, envp, 0, 0, 0);
+}
+
+int
+stat(const char *path, struct stat *st)
+{
+ return (int)SC(SYS_stat64, path, st, 0, 0, 0, 0);
+}
+
+int
+lstat(const char *path, struct stat *st)
+{
+ return (int)SC(SYS_lstat64, path, st, 0, 0, 0, 0);
+}
+
+int
+fstat(int fd, struct stat *st)
+{
+ return (int)SC(SYS_fstat64, fd, st, 0, 0, 0, 0);
+}
+
+ssize_t
+readlink(const char *path, char *buf, size_t size)
+{
+ return SC(SYS_readlink, path, buf, size, 0, 0, 0);
+}
+
+ssize_t
+getdirentries(int fd, void *buf, size_t size, off_t *position)
+{
+ return SC(SYS_getdirentries64, fd, buf, size, position, 0, 0);
+}
+
+void *
+mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
+{
+ return (void *)SC(SYS_mmap, addr, length, prot, flags, fd, offset);
+}
+
+int
+munmap(void *addr, size_t length)
+{
+ return (int)SC(SYS_munmap, addr, length, 0, 0, 0, 0);
+}
+
+int
+gettimeofday(struct timeval *tv, void *tz)
+{
+ return (int)SC(SYS_gettimeofday, tv, tz, 0, 0, 0, 0);
+}
+
+/* Sleep with select(): the kernel has no dedicated sleep system call. */
+int
+usleep(unsigned microseconds)
+{
+ struct timeval tv = { .tv_sec = microseconds / 1000000, .tv_usec = (int)(microseconds % 1000000) };
+
+ return (int)SC(SYS_select, 0, 0, 0, 0, &tv, 0);
+}
+
+int
+sysctlbyname(const char *name, void *oldp, size_t *oldlenp, const void *newp, size_t newlen)
+{
+ return (int)SC(SYS_sysctlbyname, name, strlen(name), oldp, oldlenp, newp, newlen);
+}
+
+int
+mount(const char *type, const char *dir, int flags, void *data)
+{
+ return (int)SC(SYS_mount, type, dir, flags, data, 0, 0);
+}
+
+int
+mkdir(const char *path, int mode)
+{
+ return (int)SC(SYS_mkdir, path, mode, 0, 0, 0, 0);
+}
+
+int
+rmdir(const char *path)
+{
+ return (int)SC(SYS_rmdir, path, 0, 0, 0, 0, 0);
+}
+
+int
+unlink(const char *path)
+{
+ return (int)SC(SYS_unlink, path, 0, 0, 0, 0, 0);
+}
+
+int
+rename(const char *from, const char *to)
+{
+ return (int)SC(SYS_rename, from, to, 0, 0, 0, 0);
+}
+
+int
+link(const char *from, const char *to)
+{
+ return (int)SC(SYS_link, from, to, 0, 0, 0, 0);
+}
+
+int
+symlink(const char *target, const char *path)
+{
+ return (int)SC(SYS_symlink, target, path, 0, 0, 0, 0);
+}
+
+int
+chmod(const char *path, int mode)
+{
+ return (int)SC(SYS_chmod, path, mode, 0, 0, 0, 0);
+}
+
+int
+chown(const char *path, int uid, int gid)
+{
+ return (int)SC(SYS_chown, path, uid, gid, 0, 0, 0);
+}
+
+int
+ftruncate(int fd, off_t length)
+{
+ return (int)SC(SYS_ftruncate, fd, length, 0, 0, 0, 0);
+}
+
+int
+fsync(int fd)
+{
+ return (int)SC(SYS_fsync, fd, 0, 0, 0, 0, 0);
+}
+
+ssize_t
+pread(int fd, void *buf, size_t count, off_t offset)
+{
+ return SC(SYS_pread, fd, buf, count, offset, 0, 0);
+}
+
+ssize_t
+pwrite(int fd, const void *buf, size_t count, off_t offset)
+{
+ return SC(SYS_pwrite, fd, buf, count, offset, 0, 0);
+}
+
+int
+socket(int domain, int type, int protocol)
+{
+ return (int)SC(SYS_socket, domain, type, protocol, 0, 0, 0);
+}
+
+int
+bind(int fd, const void *address, unsigned length)
+{
+ return (int)SC(SYS_bind, fd, address, length, 0, 0, 0);
+}
+
+int
+reboot(int howto)
+{
+ return (int)SC(SYS_reboot, howto, 0, 0, 0, 0, 0);
+}
+
+size_t
+strlen(const char *s)
+{
+ size_t n = 0;
+
+ while (s[n]) {
+ n++;
+ }
+ return n;
+}
+
+int
+strcmp(const char *a, const char *b)
+{
+ while (*a && *a == *b) {
+ a++, b++;
+ }
+ return (unsigned char)*a - (unsigned char)*b;
+}
+
+int
+strncmp(const char *a, const char *b, size_t n)
+{
+ for (; n; n--, a++, b++) {
+ if (*a != *b || !*a) {
+ return (unsigned char)*a - (unsigned char)*b;
+ }
+ }
+ return 0;
+}
+
+char *
+strcpy(char *dst, const char *src)
+{
+ char *d = dst;
+
+ while ((*d++ = *src++)) {
+ }
+ return dst;
+}
+
+char *
+strchr(const char *s, int c)
+{
+ for (;; s++) {
+ if (*s == (char)c) {
+ return (char *)s;
+ }
+ if (!*s) {
+ return NULL;
+ }
+ }
+}
+
+void *
+memcpy(void *dst, const void *src, size_t n)
+{
+ unsigned char *d = dst;
+ const unsigned char *s = src;
+
+ while (n--) {
+ *d++ = *s++;
+ }
+ return dst;
+}
+
+void *
+memset(void *dst, int c, size_t n)
+{
+ unsigned char *d = dst;
+
+ while (n--) {
+ *d++ = (unsigned char)c;
+ }
+ return dst;
+}
+
+int
+memcmp(const void *a, const void *b, size_t n)
+{
+ const unsigned char *x = a, *y = b;
+
+ for (; n; n--, x++, y++) {
+ if (*x != *y) {
+ return *x - *y;
+ }
+ }
+ return 0;
+}
+
+const char *
+strerror(int error)
+{
+ static const char *const names[] = {
+ [1] = "Operation not permitted", [2] = "No such file or directory", [3] = "No such process",
+ [4] = "Interrupted system call", [5] = "Input/output error", [6] = "Device not configured",
+ [7] = "Argument list too long", [8] = "Exec format error", [9] = "Bad file descriptor",
+ [10] = "No child processes", [12] = "Cannot allocate memory", [13] = "Permission denied",
+ [14] = "Bad address", [16] = "Resource busy", [17] = "File exists", [19] = "Operation not supported by device",
+ [20] = "Not a directory", [21] = "Is a directory", [22] = "Invalid argument", [25] = "Inappropriate ioctl for device",
+ [28] = "No space left on device", [30] = "Read-only file system", [45] = "Operation not supported",
+ [78] = "Function not implemented",
+ };
+
+ if (error >= 0 && (size_t)error < sizeof(names) / sizeof(names[0]) && names[error]) {
+ return names[error];
+ }
+ return "Unknown error";
+}
+
+/* printf: %c %s %d %i %u %x %X %p %%, flags '-' and '0', a width, length modifiers l, ll and z. */
+
+struct out {
+ int fd;
+ int total;
+ size_t used;
+ char buf[256];
+};
+
+static void
+out_flush(struct out *o)
+{
+ size_t done = 0;
+
+ while (done < o->used) {
+ ssize_t n = write(o->fd, o->buf + done, o->used - done);
+
+ if (n <= 0) {
+ break;
+ }
+ done += (size_t)n;
+ }
+ o->used = 0;
+}
+
+static void
+out_char(struct out *o, char c)
+{
+ if (o->used == sizeof(o->buf)) {
+ out_flush(o);
+ }
+ o->buf[o->used++] = c;
+ o->total++;
+}
+
+static void
+out_field(struct out *o, const char *s, size_t len, int width, int left, char pad)
+{
+ int fill = width > (int)len ? width - (int)len : 0;
+
+ while (!left && fill-- > 0) {
+ out_char(o, pad);
+ }
+ while (len--) {
+ out_char(o, *s++);
+ }
+ while (left && fill-- > 0) {
+ out_char(o, ' ');
+ }
+}
+
+int
+vdprintf(int fd, const char *format, va_list ap)
+{
+ struct out o = { .fd = fd };
+
+ for (const char *p = format; *p; p++) {
+ char digits[24], pad = ' ';
+ int left = 0, width = 0, longs = 0, base = 10, negative = 0, upper = 0;
+ unsigned long long value;
+ size_t len;
+
+ if (*p != '%') {
+ out_char(&o, *p);
+ continue;
+ }
+ for (p++; *p == '-' || *p == '0'; p++) {
+ if (*p == '-') {
+ left = 1;
+ } else {
+ pad = '0';
+ }
+ }
+ for (; *p >= '0' && *p <= '9'; p++) {
+ width = width * 10 + (*p - '0');
+ }
+ for (; *p == 'l' || *p == 'z'; p++) {
+ longs++;
+ }
+
+ switch (*p) {
+ case '%':
+ out_char(&o, '%');
+ continue;
+ case 'c':
+ digits[0] = (char)va_arg(ap, int);
+ out_field(&o, digits, 1, width, left, ' ');
+ continue;
+ case 's': {
+ const char *s = va_arg(ap, const char *);
+
+ if (!s) {
+ s = "(null)";
+ }
+ out_field(&o, s, strlen(s), width, left, ' ');
+ continue;
+ }
+ case 'd':
+ case 'i': {
+ long long v = longs ? va_arg(ap, long long) : va_arg(ap, int);
+
+ negative = v < 0;
+ value = negative ? 0ULL - (unsigned long long)v : (unsigned long long)v;
+ break;
+ }
+ case 'p':
+ longs = 1;
+ base = 16;
+ value = va_arg(ap, unsigned long long);
+ break;
+ case 'X':
+ upper = 1;
+ /* fall through */
+ case 'x':
+ base = 16;
+ /* fall through */
+ case 'u':
+ value = longs ? va_arg(ap, unsigned long long) : va_arg(ap, unsigned int);
+ break;
+ default:
+ /* unknown conversion: show it as written */
+ out_char(&o, '%');
+ if (*p) {
+ out_char(&o, *p);
+ } else {
+ p--;
+ }
+ continue;
+ }
+
+ len = sizeof(digits);
+ do {
+ unsigned digit = (unsigned)(value % (unsigned)base);
+
+ digits[--len] = (char)(digit < 10 ? '0' + digit : (upper ? 'A' : 'a') + digit - 10);
+ value /= (unsigned)base;
+ } while (value);
+ if (negative) {
+ if (pad == '0' && !left) {
+ /* the sign goes before the zero padding */
+ out_char(&o, '-');
+ width = width > 0 ? width - 1 : 0;
+ } else {
+ digits[--len] = '-';
+ }
+ }
+ out_field(&o, digits + len, sizeof(digits) - len, width, left, left ? ' ' : pad);
+ }
+ out_flush(&o);
+ return o.total;
+}
+
+int
+dprintf(int fd, const char *format, ...)
+{
+ va_list ap;
+ int n;
+
+ va_start(ap, format);
+ n = vdprintf(fd, format, ap);
+ va_end(ap);
+ return n;
+}
+
+int
+printf(const char *format, ...)
+{
+ va_list ap;
+ int n;
+
+ va_start(ap, format);
+ n = vdprintf(1, format, ap);
+ va_end(ap);
+ return n;
+}
+
+int
+puts(const char *s)
+{
+ return printf("%s\n", s);
+}
diff --git a/userland/libmini/mini.h b/userland/libmini/mini.h
new file mode 100644
index 0000000..39f0d54
--- /dev/null
+++ b/userland/libmini/mini.h
@@ -0,0 +1,179 @@
+/*
+ * libmini: just enough C library for the static test programs of the
+ * Darwin bring-up. No dyld, no libSystem: the programs talk to the kernel
+ * directly (see start.S).
+ */
+#ifndef MINI_H
+#define MINI_H
+
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdint.h>
+
+typedef long ssize_t;
+typedef long long off_t;
+typedef int pid_t;
+
+extern int errno;
+extern char **environ;
+
+/* system call numbers (xnu bsd/kern/syscalls.master) */
+enum {
+ SYS_exit = 1, SYS_read = 3, SYS_write = 4, SYS_open = 5, SYS_close = 6, SYS_wait4 = 7, SYS_link = 9,
+ SYS_unlink = 10, SYS_chdir = 12, SYS_chmod = 15, SYS_chown = 16, SYS_getpid = 20, SYS_getuid = 24,
+ SYS_kill = 37, SYS_getppid = 39, SYS_dup = 41, SYS_ioctl = 54, SYS_reboot = 55, SYS_symlink = 57,
+ SYS_readlink = 58, SYS_execve = 59, SYS_msync = 65, SYS_munmap = 73, SYS_dup2 = 90, SYS_select = 93,
+ SYS_fsync = 95, SYS_socket = 97, SYS_bind = 104, SYS_gettimeofday = 116, SYS_rename = 128, SYS_mkdir = 136,
+ SYS_rmdir = 137, SYS_pread = 153, SYS_pwrite = 154, SYS_mount = 167, SYS_mmap = 197, SYS_lseek = 199,
+ SYS_ftruncate = 201, SYS_sysctlbyname = 274, SYS_stat64 = 338, SYS_fstat64 = 339, SYS_lstat64 = 340,
+ SYS_getdirentries64 = 344,
+};
+
+/*
+ * Not variadic on purpose: the Apple arm64 ABI passes variadic arguments on
+ * the stack, and the kernel wants them in registers.
+ */
+long mini_syscall(long number, long a, long b, long c, long d, long e, long f);
+pid_t fork(void);
+int pipe(int fds[2]);
+
+#define O_RDONLY 0
+#define O_WRONLY 1
+#define O_RDWR 2
+#define O_APPEND 0x8
+#define O_CREAT 0x200
+#define O_TRUNC 0x400
+#define O_EXCL 0x800
+#define O_DIRECTORY 0x100000
+
+#define AF_UNIX 1
+#define SOCK_STREAM 1
+
+/* local socket address */
+struct sockaddr_un {
+ uint8_t sun_len;
+ uint8_t sun_family;
+ char sun_path[104];
+};
+
+#define SEEK_SET 0
+#define SEEK_END 2
+
+#define PROT_READ 1
+#define PROT_WRITE 2
+#define MAP_SHARED 1
+#define MAP_PRIVATE 2
+#define MAP_ANON 0x1000
+#define MAP_FAILED ((void *)-1)
+
+#define MNT_RDONLY 1
+
+#define S_IFMT 0170000
+#define S_IFDIR 0040000
+#define S_IFCHR 0020000
+#define S_IFBLK 0060000
+#define S_IFREG 0100000
+#define S_IFLNK 0120000
+#define S_IFSOCK 0140000
+
+#define DT_DIR 4
+#define DT_REG 8
+#define DT_LNK 10
+
+struct timespec { long tv_sec; long tv_nsec; };
+struct timeval { long tv_sec; int tv_usec; };
+
+/* struct stat as stat64() fills it in */
+struct stat {
+ int32_t st_dev;
+ uint16_t st_mode;
+ uint16_t st_nlink;
+ uint64_t st_ino;
+ uint32_t st_uid;
+ uint32_t st_gid;
+ int32_t st_rdev;
+ struct timespec st_atimespec;
+ struct timespec st_mtimespec;
+ struct timespec st_ctimespec;
+ struct timespec st_birthtimespec;
+ off_t st_size;
+ int64_t st_blocks;
+ int32_t st_blksize;
+ uint32_t st_flags;
+ uint32_t st_gen;
+ int32_t st_lspare;
+ int64_t st_qspare[2];
+};
+
+/* directory entry as getdirentries64() returns it */
+struct dirent {
+ uint64_t d_ino;
+ uint64_t d_seekoff;
+ uint16_t d_reclen;
+ uint16_t d_namlen;
+ uint8_t d_type;
+ char d_name[1024];
+};
+
+#define WEXITSTATUS(s) (((s) >> 8) & 0xff)
+#define WTERMSIG(s) ((s) & 0x7f)
+#define WIFEXITED(s) (WTERMSIG(s) == 0)
+
+void _exit(int status) __attribute__((noreturn));
+ssize_t read(int fd, void *buf, size_t count);
+ssize_t write(int fd, const void *buf, size_t count);
+int open(const char *path, int flags, int mode);
+int close(int fd);
+off_t lseek(int fd, off_t offset, int whence);
+int dup2(int from, int to);
+int chdir(const char *path);
+pid_t getpid(void);
+pid_t getppid(void);
+int getuid(void);
+pid_t wait4(pid_t pid, int *status, int options, void *rusage);
+int execve(const char *path, char *const argv[], char *const envp[]);
+int stat(const char *path, struct stat *st);
+int lstat(const char *path, struct stat *st);
+int fstat(int fd, struct stat *st);
+ssize_t readlink(const char *path, char *buf, size_t size);
+ssize_t getdirentries(int fd, void *buf, size_t size, off_t *position);
+void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
+int munmap(void *addr, size_t length);
+int gettimeofday(struct timeval *tv, void *tz);
+int usleep(unsigned microseconds);
+int sysctlbyname(const char *name, void *oldp, size_t *oldlenp, const void *newp, size_t newlen);
+int reboot(int howto);
+int mount(const char *type, const char *dir, int flags, void *data);
+int mkdir(const char *path, int mode);
+int rmdir(const char *path);
+int unlink(const char *path);
+int rename(const char *from, const char *to);
+int link(const char *from, const char *to);
+int symlink(const char *target, const char *path);
+int chmod(const char *path, int mode);
+int chown(const char *path, int uid, int gid);
+int ftruncate(int fd, off_t length);
+int fsync(int fd);
+ssize_t pread(int fd, void *buf, size_t count, off_t offset);
+ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
+int socket(int domain, int type, int protocol);
+int bind(int fd, const void *address, unsigned length);
+
+size_t strlen(const char *s);
+int strcmp(const char *a, const char *b);
+int strncmp(const char *a, const char *b, size_t n);
+char *strcpy(char *dst, const char *src);
+char *strchr(const char *s, int c);
+void *memcpy(void *dst, const void *src, size_t n);
+void *memset(void *dst, int c, size_t n);
+int memcmp(const void *a, const void *b, size_t n);
+const char *strerror(int error);
+
+int printf(const char *format, ...) __attribute__((format(printf, 1, 2)));
+int dprintf(int fd, const char *format, ...) __attribute__((format(printf, 2, 3)));
+int vdprintf(int fd, const char *format, va_list ap);
+int puts(const char *s);
+
+int main(int argc, char **argv, char **envp);
+
+#endif /* MINI_H */
diff --git a/userland/libmini/start.S b/userland/libmini/start.S
new file mode 100644
index 0000000..da1ad17
--- /dev/null
+++ b/userland/libmini/start.S
@@ -0,0 +1,60 @@
+/*
+ * Program entry and the raw system call interface for static arm64 programs.
+ *
+ * XNU arm64 convention: call number in x16, arguments in x0-x7, "svc #0x80".
+ * On failure the carry flag is set and x0 holds the error number.
+ */
+ .text
+ .align 2
+
+/* The kernel enters here with sp pointing at argc, argv[], NULL, envp[], NULL. */
+ .globl _start
+_start:
+ mov x0, sp
+ and sp, x0, #0xfffffffffffffff0
+ mov x29, #0
+ mov x30, #0
+ bl ___mini_start
+ brk #1
+
+/* long mini_syscall(long number, long a, long b, long c, long d, long e, long f) */
+ .globl _mini_syscall
+_mini_syscall:
+ mov x16, x0
+ mov x0, x1
+ mov x1, x2
+ mov x2, x3
+ mov x3, x4
+ mov x4, x5
+ mov x5, x6
+ svc #0x80
+ b.cs Lerror
+ ret
+
+/* fork returns twice; the kernel marks the child with x1 = 1 */
+ .globl _fork
+_fork:
+ mov x16, #2
+ svc #0x80
+ b.cs Lerror
+ cbz x1, 1f
+ mov x0, #0
+1: ret
+
+/* pipe returns the two descriptors in x0 and x1 */
+ .globl _pipe
+_pipe:
+ mov x9, x0
+ mov x16, #42
+ svc #0x80
+ b.cs Lerror
+ str w0, [x9]
+ str w1, [x9, #4]
+ mov x0, #0
+ ret
+
+Lerror:
+ adrp x9, _errno@PAGE
+ str w0, [x9, _errno@PAGEOFF]
+ mov x0, #-1
+ ret
diff --git a/userland/mkjobs.py b/userland/mkjobs.py
new file mode 100755
index 0000000..c583938
--- /dev/null
+++ b/userland/mkjobs.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""Copy stock iOS launchd job definitions into the small image, adjusted for the bring-up.
+
+usage: mkjobs.py [--rest] IOS_ROOTFS DEST_DIR label...
+
+For every label, IOS_ROOTFS/System/Library/LaunchDaemons/<label>.plist is copied to DEST_DIR with
+its standard error sent to the console, which is where a daemon's last words are read (there
+is 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:
+everything the daemon has to say -- SpringBoard alone says a megabyte in half a minute, which
+costs time and pushes everybody else out of the log that comes back from the phone.
+The program itself must be in the system image; a warning is printed if it was not extracted.
+
+With --rest, the other jobs of iOS follow, but strictly on demand: whatever starts them by
+itself (RunAtLoad, KeepAlive) is taken out, so that launchd runs one only when a program asks
+for one of its Mach services. That is how an application finds the daemons it needs without
+all 490 of them being started at boot. Left out: jobs without Mach services (nothing could
+ever start them), jobs whose program is not in the system image, and those in DENY, which
+drive hardware that is not there or do things nobody wants here.
+"""
+import os
+import plistlib
+import sys
+
+# substrings of labels
+DENY = ('watchdog', 'CommCenter', 'wifi', 'WiFi', 'bluetooth', 'BTServer', 'locationd', 'softwareupdate',
+ 'datamigrator', 'backupd', 'thermalmonitord', 'keybagd', 'nfcd', 'biometrickitd', 'pearld',
+ 'obliterat', 'storage_mounter', 'com.apple.fud', 'sepd', 'seputil', 'camera', 'ReportCrash',
+ 'osanalytics', 'lockdown', 'mediaserverd', 'audio', 'jetsamproperties', 'mobileactivationd',
+ 'mobile.installd', 'installcoordinationd', 'purplebuddy', 'restore', 'usb', 'accessoryd',
+ 'mobileassetd', 'nsurlsessiond', 'apsd', 'itunesstored', 'appstored', 'cloudd', 'bird',
+ # these start, crash and are asked for again, over and over
+ 'aggregated', 'homed', 'routined', 'duetexpertd', 'com.apple.dmd', 'syncdefaultsd')
+
+args = sys.argv[1:]
+rest = args[:1] == ['--rest']
+if rest:
+ args = args[1:]
+src_root, dest, labels = args[0], args[1], args[2:]
+oslog = os.environ.get('OSLOG', '').split()
+src = f'{src_root}/System/Library/LaunchDaemons'
+os.makedirs(dest, exist_ok=True)
+for label in labels:
+ with open(f'{src}/{label}.plist', 'rb') as f:
+ job = plistlib.load(f)
+ job['StandardErrorPath'] = '/dev/console'
+ if 'all' in oslog or label in oslog:
+ job.setdefault('EnvironmentVariables', {})['OS_ACTIVITY_DT_MODE'] = 'YES'
+ 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 os.path.isfile(f'{src_root}{program}') else ' (NOT in the system image!)'
+ print(f' job {label}: {program}{missing}')
+
+if rest:
+ count = 0
+ for name in sorted(os.listdir(src)):
+ label = name[:-len('.plist')]
+ if not name.endswith('.plist') or label in labels or any(word in label for word in DENY):
+ continue
+ with open(f'{src}/{name}', 'rb') as f:
+ job = plistlib.load(f)
+ program = job.get('Program') or (job.get('ProgramArguments') or [''])[0]
+ if not job.get('MachServices') or not os.path.isfile(f'{src_root}{program}'):
+ continue
+ for key in ('RunAtLoad', 'KeepAlive', 'StartInterval', 'StartCalendarInterval', 'WatchPaths',
+ 'QueueDirectories', 'StartOnMount', 'LaunchEvents'):
+ job.pop(key, None)
+ with open(f'{dest}/{name}', 'wb') as f:
+ plistlib.dump(job, f, fmt=plistlib.FMT_BINARY)
+ count += 1
+ print(f' ... and {count} more jobs, started on demand only')
diff --git a/userland/rc.ios b/userland/rc.ios
new file mode 100644
index 0000000..694a8a9
--- /dev/null
+++ b/userland/rc.ios
@@ -0,0 +1,8 @@
+# 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.
+/redwood/bin/hello_dyn one two
+/bin/df
+/sbin/mount
+/bin/ps -A
+/usr/bin/vm_stat
+/usr/sbin/ioreg
diff --git a/userland/rc.jobs b/userland/rc.jobs
new file mode 100644
index 0000000..30a3fff
--- /dev/null
+++ b/userland/rc.jobs
@@ -0,0 +1,6 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+/redwood/bin/hello_dyn started by launchd
+/redwood/bin/svc_test
+/redwood/bin/surf_test
+/bin/ps -A
+/redwood/bin/mg_test
diff --git a/userland/rc.jobs.demo b/userland/rc.jobs.demo
new file mode 100644
index 0000000..419960f
--- /dev/null
+++ b/userland/rc.jobs.demo
@@ -0,0 +1,9 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+/redwood/bin/hello_dyn started by launchd
+/redwood/bin/svc_test
+/redwood/bin/surf_test
+/bin/ps -A
+# A tour for the screen recording (xl run with rec_secs=...): unlock, Settings > General > About, home;
+# the Clock's stopwatch, home; the Calendar, home.
+/redwood/bin/rwtouch wait 26 swipe 0.5 0.985 0.5 0.3 200 wait 4 tap 0.615 0.71 wait 5 tap 0.3 0.795 wait 4 tap 0.15 0.18 wait 5 swipe 0.5 0.995 0.5 0.55 150
+/redwood/bin/rwtouch wait 7 tap 0.615 0.475 wait 6 tap 0.625 0.925 wait 3 tap 0.845 0.514 wait 7 swipe 0.5 0.995 0.5 0.55 150 wait 5 tap 0.385 0.36 wait 6 button home
diff --git a/userland/rc.jobs.unlock b/userland/rc.jobs.unlock
new file mode 100644
index 0000000..24dae6b
--- /dev/null
+++ b/userland/rc.jobs.unlock
@@ -0,0 +1,7 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+/redwood/bin/hello_dyn started by launchd
+/redwood/bin/svc_test
+/redwood/bin/surf_test
+/bin/ps -A
+# "swipe up to open": until somebody can do it with a finger
+/redwood/bin/rwtouch wait 32 swipe 0.5 0.985 0.5 0.3 250 &
diff --git a/userland/rc.launchd b/userland/rc.launchd
new file mode 100644
index 0000000..1a04d07
--- /dev/null
+++ b/userland/rc.launchd
@@ -0,0 +1,2 @@
+# Experiment: hand process 1 over to the real iOS launchd.
+exec /sbin/launchd.ios
diff --git a/userland/src/child.c b/userland/src/child.c
new file mode 100644
index 0000000..ac6774e
--- /dev/null
+++ b/userland/src/child.c
@@ -0,0 +1,20 @@
+/*
+ * Helper for the fork/exec test: reports how it was started and exits with
+ * a status the parent checks.
+ */
+#include "mini.h"
+
+int
+main(int argc, char **argv, char **envp)
+{
+ printf(" child: pid %d, parent %d, %d arguments:", getpid(), getppid(), argc);
+ for (int i = 0; i < argc; i++) {
+ printf(" [%s]", argv[i]);
+ }
+ printf("\n child: environment:");
+ for (char **e = envp; *e; e++) {
+ printf(" [%s]", *e);
+ }
+ printf("\n");
+ return argc == 3 && strcmp(argv[2], "two") == 0 ? 42 : 1;
+}
diff --git a/userland/src/hello.c b/userland/src/hello.c
new file mode 100644
index 0000000..64b97c8
--- /dev/null
+++ b/userland/src/hello.c
@@ -0,0 +1,76 @@
+/*
+ * First user-space program for the Darwin-on-redwood bring-up.
+ *
+ * A static arm64 Mach-O with no libc and no dyld: it talks to the kernel with
+ * raw system calls. The kernel's mockfs presents the ramdisk (this very file)
+ * as /sbin/launchd, so this runs as process 1.
+ */
+typedef unsigned long u64;
+
+/* XNU arm64 system call: number in x16, arguments in x0.., "svc #0x80"; carry set on error */
+static long
+syscall3(long num, long a, long b, long c)
+{
+ register long x16 __asm__("x16") = num;
+ register long x0 __asm__("x0") = a;
+ register long x1 __asm__("x1") = b;
+ register long x2 __asm__("x2") = c;
+ __asm__ volatile ("svc #0x80" : "+r" (x0) : "r" (x16), "r" (x1), "r" (x2) : "memory", "cc");
+ return x0;
+}
+
+#define SYS_exit 1
+#define SYS_write 4
+#define SYS_open 5
+#define SYS_getpid 20
+#define SYS_getuid 24
+#define O_RDWR 2
+
+static unsigned
+length(const char *s)
+{
+ unsigned n = 0;
+ while (s[n]) {
+ n++;
+ }
+ return n;
+}
+
+static void
+put(int fd, const char *s)
+{
+ syscall3(SYS_write, fd, (long)s, length(s));
+}
+
+static void
+put_number(int fd, long v)
+{
+ char buf[24];
+ int i = sizeof(buf);
+ buf[--i] = 0;
+ do {
+ buf[--i] = (char)('0' + v % 10);
+ v /= 10;
+ } while (v);
+ put(fd, buf + i);
+}
+
+void
+start(void)
+{
+ int fd = (int)syscall3(SYS_open, (long)"/dev/console", O_RDWR, 0);
+
+ put(fd, "\nHello from user space on Darwin!\n");
+ put(fd, "I am process ");
+ put_number(fd, syscall3(SYS_getpid, 0, 0, 0));
+ put(fd, ", uid ");
+ put_number(fd, syscall3(SYS_getuid, 0, 0, 0));
+ put(fd, ", console fd ");
+ put_number(fd, fd);
+ put(fd, ".\n");
+
+ /* Process 1 is not supposed to exit; doing so panics the kernel, which ends the test run. */
+ syscall3(SYS_exit, 0, 0, 0);
+ for (;;) {
+ }
+}
diff --git a/userland/src/hello_dyn.c b/userland/src/hello_dyn.c
new file mode 100644
index 0000000..0e589ad
--- /dev/null
+++ b/userland/src/hello_dyn.c
@@ -0,0 +1,27 @@
+/*
+ * The first ordinary program: dynamically linked against the real iOS
+ * libSystem, loaded by the real dyld out of the dyld shared cache.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/utsname.h>
+
+int
+main(int argc, char **argv)
+{
+ struct utsname u;
+ char *copy = strdup("malloc works");
+
+ printf("Hello from a dynamically linked program! pid %d, %d argument(s)\n", getpid(), argc);
+ if (uname(&u) == 0) {
+ printf("uname: %s %s %s\n", u.sysname, u.release, u.machine);
+ }
+ printf("heap: %s (%p), stack near %p, main at %p, printf at %p\n", copy, (void *)copy, (void *)&u, (void *)main, (void *)printf);
+ for (int i = 0; i < argc; i++) {
+ printf("argv[%d] = %s\n", i, argv[i]);
+ }
+ free(copy);
+ return 7;
+}
diff --git a/userland/src/init.c b/userland/src/init.c
new file mode 100644
index 0000000..a248cb2
--- /dev/null
+++ b/userland/src/init.c
@@ -0,0 +1,794 @@
+/*
+ * Process 1 of the Darwin bring-up, until it hands over to the real launchd.
+ *
+ * It lives in the small image mounted on /redwood (see stage0.c) and
+ * - mounts a memory filesystem on /private/var and creates the directories
+ * 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;
+ * - 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
+ * how a launchd job (LaunchDaemons/com.redwood.demo.plist) runs a list of
+ * commands.
+ */
+#include "mini.h"
+
+#define PATTERN_SIZE 300000
+#define RB_HALT 0x08
+
+static int checks, failures;
+
+/* Where this program's own image is mounted ("" when it is the root itself). */
+static const char *base = "";
+
+/* A path inside our own image; the result is valid until the next call. */
+static const char *
+in_image(const char *path)
+{
+ static char buf[256];
+
+ strcpy(buf, base);
+ strcpy(buf + strlen(buf), path);
+ return buf;
+}
+
+static void
+check(int ok, const char *what)
+{
+ checks++;
+ if (!ok) {
+ failures++;
+ }
+ printf("[%s] %s\n", ok ? " ok " : "FAIL", what);
+}
+
+/* Same formula as build.sh uses to generate the file. */
+static unsigned char
+pattern(unsigned long i)
+{
+ return (unsigned char)(i * 31 + (i >> 8));
+}
+
+static void
+show_system(void)
+{
+ char type[32] = "?", release[32] = "?", machine[32] = "?", version[256] = "?";
+ unsigned long long memsize = 0, pagesize = 0;
+ int ncpu = 0;
+ size_t len;
+
+ len = sizeof(type), sysctlbyname("kern.ostype", type, &len, NULL, 0);
+ len = sizeof(release), sysctlbyname("kern.osrelease", release, &len, NULL, 0);
+ len = sizeof(version), sysctlbyname("kern.version", version, &len, NULL, 0);
+ len = sizeof(machine), sysctlbyname("hw.machine", machine, &len, NULL, 0);
+ len = sizeof(memsize), sysctlbyname("hw.memsize", &memsize, &len, NULL, 0);
+ len = sizeof(pagesize), sysctlbyname("hw.pagesize", &pagesize, &len, NULL, 0);
+ len = sizeof(ncpu), sysctlbyname("hw.ncpu", &ncpu, &len, NULL, 0);
+
+ printf("%s %s %s\n%s\n", type, release, machine, version);
+ printf("memory %llu MB, page size %llu, %d cpu\n\n", memsize >> 20, pagesize, ncpu);
+ check(strcmp(type, "Darwin") == 0 && memsize != 0, "sysctl: kernel identifies itself");
+}
+
+static void
+mode_string(unsigned mode, char *out)
+{
+ static const char bits[] = "rwxrwxrwx";
+
+ out[0] = (mode & S_IFMT) == S_IFDIR ? 'd' : (mode & S_IFMT) == S_IFLNK ? 'l' :
+ (mode & S_IFMT) == S_IFCHR ? 'c' : (mode & S_IFMT) == S_IFBLK ? 'b' : (mode & S_IFMT) == S_IFSOCK ? 's' : '-';
+ for (int i = 0; i < 9; i++) {
+ out[1 + i] = (mode & (0400 >> i)) ? bits[i] : '-';
+ }
+ out[10] = 0;
+}
+
+/* ls -lR; returns the number of entries seen, or -1 */
+static int
+list_tree(const char *path, int depth)
+{
+ static char buf[8192]; /* one directory at a time: the contents are copied out before recursing */
+ char names[32][64];
+ int count = 0, subdirs = 0, total = 0;
+ off_t position = 0;
+ ssize_t n;
+ int fd = open(path, O_RDONLY | O_DIRECTORY, 0);
+
+ if (fd < 0) {
+ printf(" %s: %s\n", path, strerror(errno));
+ return -1;
+ }
+ while ((n = getdirentries(fd, buf, sizeof(buf), &position)) > 0) {
+ for (ssize_t at = 0; at < n;) {
+ struct dirent *de = (struct dirent *)(buf + at);
+ char full[256], mode[12], target[128];
+ struct stat st;
+
+ at += de->d_reclen;
+ if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) {
+ continue;
+ }
+ strcpy(full, path);
+ if (full[strlen(full) - 1] != '/') {
+ strcpy(full + strlen(full), "/");
+ }
+ strcpy(full + strlen(full), de->d_name);
+ if (lstat(full, &st) != 0) {
+ printf(" %s: %s\n", full, strerror(errno));
+ close(fd);
+ return -1;
+ }
+ mode_string(st.st_mode, mode);
+ printf(" %s %2u %8lld %s", mode, st.st_nlink, st.st_size, full);
+ if ((st.st_mode & S_IFMT) == S_IFLNK) {
+ ssize_t t = readlink(full, target, sizeof(target) - 1);
+
+ target[t > 0 ? t : 0] = 0;
+ printf(" -> %s", target);
+ }
+ printf("\n");
+ count++;
+ if (de->d_type == DT_DIR && depth > 0 && subdirs < 32 && strlen(full) < 64) {
+ strcpy(names[subdirs++], full);
+ }
+ }
+ }
+ close(fd);
+ if (n < 0) {
+ return -1;
+ }
+ total = count;
+ for (int i = 0; i < subdirs; i++) {
+ int sub = list_tree(names[i], depth - 1);
+
+ if (sub < 0) {
+ return -1;
+ }
+ total += sub;
+ }
+ return total;
+}
+
+static void
+test_files(void)
+{
+ static unsigned char buf[65536];
+ char text[128];
+ struct stat st;
+ int fd, good;
+ ssize_t n;
+ unsigned long done;
+ unsigned char *map;
+
+ printf("\n-- read-only filesystem --\n");
+ check(list_tree(*base ? base : "/", 3) >= 8, "packfs: walk our image (readdir, lstat, readlink)");
+ check(stat("/usr/lib/dyld", &st) != 0 || st.st_size > 100000, "the system image has the dynamic linker");
+
+ fd = open(in_image("/etc/motd"), O_RDONLY, 0);
+ n = fd >= 0 ? read(fd, text, sizeof(text) - 1) : -1;
+ text[n > 0 ? n : 0] = 0;
+ close(fd);
+ printf(" etc/motd: %s", text);
+ check(n > 0 && strncmp(text, "Darwin", 6) == 0, "read a small file");
+
+ check(stat("/tmp", &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR, "follow a symlink to a directory");
+ check(open("/nonexistent", O_RDONLY, 0) < 0 && errno == 2, "missing file gives ENOENT");
+ check(open(in_image("/etc/newfile"), O_WRONLY | O_CREAT, 0644) < 0 && errno == 30, "creating a file gives EROFS");
+
+ fd = open(in_image("/share/pattern.bin"), O_RDONLY, 0);
+ good = fd >= 0 && fstat(fd, &st) == 0 && st.st_size == PATTERN_SIZE;
+ for (done = 0; good && done < PATTERN_SIZE; done += (unsigned long)n) {
+ n = read(fd, buf, sizeof(buf));
+ if (n <= 0) {
+ good = 0;
+ break;
+ }
+ for (ssize_t i = 0; i < n; i++) {
+ if (buf[i] != pattern(done + (unsigned long)i)) {
+ good = 0;
+ }
+ }
+ }
+ check(good && done == PATTERN_SIZE, "read a 300 KB file and verify every byte");
+
+ good = fd >= 0 && lseek(fd, 123457, SEEK_SET) == 123457 && read(fd, buf, 1000) == 1000;
+ for (int i = 0; good && i < 1000; i++) {
+ good = buf[i] == pattern(123457 + (unsigned long)i);
+ }
+ check(good, "seek into the middle and read");
+
+ map = fd >= 0 ? mmap(NULL, PATTERN_SIZE, PROT_READ, MAP_PRIVATE, fd, 0) : MAP_FAILED;
+ good = map != MAP_FAILED;
+ for (unsigned long i = 0; good && i < PATTERN_SIZE; i++) {
+ good = map[i] == pattern(i);
+ }
+ check(good, "mmap the file and verify every byte (page-in)");
+ if (map != MAP_FAILED) {
+ munmap(map, PATTERN_SIZE);
+ }
+ close(fd);
+}
+
+static void
+test_memory(void)
+{
+ const size_t size = 64u << 20, step = 4096;
+ unsigned long *mem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
+ int good = mem != MAP_FAILED;
+
+ printf("\n-- memory --\n");
+ for (size_t off = 0; good && off < size; off += step) {
+ mem[off / sizeof(*mem)] = off ^ 0x5a5a5a5a5a5a5a5aUL;
+ }
+ for (size_t off = 0; good && off < size; off += step) {
+ good = mem[off / sizeof(*mem)] == (off ^ 0x5a5a5a5a5a5a5a5aUL);
+ }
+ check(good, "64 MB of anonymous memory: touch every page, read it back");
+ check(good && munmap(mem, size) == 0, "unmap it");
+}
+
+static void
+test_processes(void)
+{
+ char program[128];
+ char *argv[] = { program, "one", "two", NULL };
+ char *envp[] = { "GREETING=hello from init", NULL };
+ int status = 0, fds[2];
+ char text[16] = "";
+ pid_t pid;
+
+ strcpy(program, in_image("/bin/child"));
+ printf("\n-- processes --\n");
+ pid = fork();
+ if (pid == 0) {
+ execve(argv[0], argv, envp);
+ printf(" execve: %s\n", strerror(errno));
+ _exit(127);
+ }
+ check(pid > 1, "fork");
+ check(pid > 0 && wait4(pid, &status, 0, NULL) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 42,
+ "exec a second program from the image, collect its exit status");
+
+ if (pipe(fds) == 0) {
+ pid = fork();
+ if (pid == 0) {
+ close(fds[0]);
+ write(fds[1], "ping", 4);
+ _exit(0);
+ }
+ close(fds[1]);
+ read(fds[0], text, sizeof(text) - 1);
+ close(fds[0]);
+ wait4(pid, &status, 0, NULL);
+ }
+ check(strcmp(text, "ping") == 0, "pipe from a child process");
+}
+
+/*
+ * Present only in the image that carries the iOS dyld and shared cache:
+ * an ordinary dynamically linked program.
+ */
+static void
+test_dynamic(void)
+{
+ char program[128];
+ char *argv[] = { program, "from", "init", NULL };
+ char *envp[] = { "PATH=/bin:/usr/bin", "HOME=/", NULL };
+ struct stat st;
+ int status = 0;
+ pid_t pid;
+
+ strcpy(program, in_image("/bin/hello_dyn"));
+ if (stat(argv[0], &st) != 0 || stat("/usr/lib/dyld", &st) != 0) {
+ return;
+ }
+ printf("\n-- dynamic linking --\n");
+ pid = fork();
+ if (pid == 0) {
+ execve(argv[0], argv, envp);
+ printf(" execve: %s\n", strerror(errno));
+ _exit(127);
+ }
+ if (pid > 0 && wait4(pid, &status, 0, NULL) == pid) {
+ if (WIFEXITED(status)) {
+ printf(" %s exited with status %d\n", argv[0], WEXITSTATUS(status));
+ } else {
+ printf(" %s was killed by signal %d\n", argv[0], WTERMSIG(status));
+ }
+ }
+ check(pid > 0 && WIFEXITED(status) && WEXITSTATUS(status) == 7, "run a program through dyld and the shared cache");
+}
+
+/* One line of the skeleton list: fields are separated by tabs. Returns the number of fields found. */
+static int
+split_tabs(char *line, char **fields, int max)
+{
+ int n = 0;
+
+ while (n < max) {
+ fields[n++] = line;
+ line = strchr(line, '\t');
+ if (line == NULL) {
+ break;
+ }
+ *line++ = 0;
+ }
+ return n;
+}
+
+static long
+parse_number(const char *text, int radix)
+{
+ long value = 0;
+
+ for (; *text >= '0' && *text < '0' + radix; text++) {
+ value = value * radix + (*text - '0');
+ }
+ return value;
+}
+
+/*
+ * /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.)
+ */
+static int
+copy_file(const char *from, const char *to, int mode, int uid, int gid)
+{
+ static char buf[4096];
+ int in = open(from, O_RDONLY, 0), out, ok = 0;
+ ssize_t n;
+
+ if (in < 0) {
+ return 0;
+ }
+ out = open(to, O_WRONLY | O_CREAT | O_TRUNC, mode);
+ if (out >= 0) {
+ ok = 1;
+ while ((n = read(in, buf, sizeof(buf))) > 0) {
+ ok = ok && write(out, buf, (size_t)n) == n;
+ }
+ close(out);
+ ok = ok && n == 0 && chmod(to, mode) == 0 && chown(to, uid, gid) == 0;
+ }
+ close(in);
+ return ok;
+}
+
+static void
+mount_writable(void)
+{
+ static char skeleton[16384];
+ static const char *const markers[] = { "/private/var/db/diagnostics/.migrated",
+ "/private/var/db/diagnostics/timesync/.migrated", "/private/var/db/uuidtext/.migrated" };
+ int ok, fd, made = 0, files = 0;
+ ssize_t n;
+
+ printf("\n-- writable filesystem --\n");
+ ok = mount("ramfs", "/private/var", 0, NULL) == 0;
+ if (!ok) {
+ printf(" mount: %s\n", strerror(errno));
+ }
+ check(ok, "mount a memory filesystem on /private/var");
+
+ /* the directories of the data volume, as listed in the template that ships with iOS (ios165/mkvarskel.py) */
+ fd = open(in_image("/etc/var.skel"), O_RDONLY, 0);
+ n = fd >= 0 ? read(fd, skeleton, sizeof(skeleton) - 1) : -1;
+ close(fd);
+ skeleton[n > 0 ? n : 0] = 0;
+ for (char *line = skeleton; ok && *line;) {
+ char *end = strchr(line, '\n'), *f[6];
+ int count;
+
+ if (end) {
+ *end = 0;
+ }
+ count = split_tabs(line, f, 6);
+ if (count == 5 && f[0][0] == 'd') {
+ int mode = (int)parse_number(f[1], 8);
+
+ ok = mkdir(f[4], mode) == 0 && chmod(f[4], mode) == 0 &&
+ chown(f[4], (int)parse_number(f[2], 10), (int)parse_number(f[3], 10)) == 0;
+ if (!ok) {
+ printf(" %s: %s\n", f[4], strerror(errno));
+ }
+ made++;
+ } else if (count == 3 && f[0][0] == 'l') {
+ 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 */
+ if (!copy_file(in_image(f[5]), f[4], (int)parse_number(f[1], 8), (int)parse_number(f[2], 10),
+ (int)parse_number(f[3], 10))) {
+ printf(" %s: %s\n", f[4], strerror(errno));
+ }
+ files++;
+ }
+ if (!end) {
+ break;
+ }
+ line = end + 1;
+ }
+ /*
+ * logd takes a log directory without this marker for one left by an
+ * older system, to be converted by logd_helper; these are brand new.
+ */
+ for (unsigned i = 0; ok && i < sizeof(markers) / sizeof(markers[0]); i++) {
+ fd = open(markers[i], O_WRONLY | O_CREAT, 0644);
+ ok = fd >= 0 && chown(markers[i], 272, 272) == 0;
+ close(fd);
+ }
+ printf(" %d directories, %d files\n", made, files);
+ check(ok && made > 50, "create the directories of the data volume");
+}
+
+static int
+count_entries(const char *path)
+{
+ static char buf[4096];
+ off_t position = 0;
+ ssize_t n;
+ int count = 0, fd = open(path, O_RDONLY | O_DIRECTORY, 0);
+
+ if (fd < 0) {
+ return -1;
+ }
+ while ((n = getdirentries(fd, buf, sizeof(buf), &position)) > 0) {
+ for (ssize_t at = 0; at < n; at += ((struct dirent *)(buf + at))->d_reclen) {
+ const char *name = ((struct dirent *)(buf + at))->d_name;
+
+ count += strcmp(name, ".") != 0 && strcmp(name, "..") != 0;
+ }
+ }
+ close(fd);
+ return n < 0 ? -1 : count;
+}
+
+static void
+test_writable(void)
+{
+ static unsigned char buf[65536];
+ const unsigned long total = 100000;
+ struct sockaddr_un sun = { .sun_len = sizeof(sun), .sun_family = AF_UNIX, .sun_path = "/tmp/t/socket" };
+ struct stat st;
+ char text[64];
+ unsigned char *map;
+ unsigned long done;
+ int fd, fd2, good, s;
+ ssize_t n;
+
+ if (mkdir("/tmp/t", 0755) != 0) {
+ return; /* no writable filesystem in this configuration */
+ }
+ printf("\n-- writing files --\n");
+
+ fd = open("/tmp/t/file", O_RDWR | O_CREAT | O_EXCL, 0644);
+ good = fd >= 0;
+ for (done = 0; good && done < total; done += (unsigned long)n) {
+ unsigned long piece = total - done < 7777 ? total - done : 7777;
+
+ for (unsigned long i = 0; i < piece; i++) {
+ buf[i] = pattern(done + i);
+ }
+ n = write(fd, buf, piece);
+ good = n == (ssize_t)piece;
+ }
+ good = good && fstat(fd, &st) == 0 && st.st_size == (off_t)total && lseek(fd, 0, SEEK_SET) == 0;
+ for (done = 0; good && done < total; done += (unsigned long)n) {
+ n = read(fd, buf, sizeof(buf));
+ good = n > 0;
+ for (ssize_t i = 0; good && i < n; i++) {
+ good = buf[i] == pattern(done + (unsigned long)i);
+ }
+ }
+ check(good && done == total, "create a file, write 100 KB, read it back");
+
+ good = pwrite(fd, "0123456789", 10, 50000) == 10 && pread(fd, text, 12, 49999) == 12 &&
+ (unsigned char)text[0] == pattern(49999) && memcmp(text + 1, "0123456789", 10) == 0 &&
+ (unsigned char)text[11] == pattern(50010);
+ check(good, "overwrite in the middle");
+
+ fd2 = open("/tmp/t/file", O_WRONLY | O_APPEND, 0);
+ good = fd2 >= 0 && write(fd2, "tail!", 5) == 5 && fstat(fd, &st) == 0 && st.st_size == (off_t)total + 5 &&
+ pread(fd, text, 5, (off_t)total) == 5 && memcmp(text, "tail!", 5) == 0;
+ close(fd2);
+ check(good, "append");
+
+ good = ftruncate(fd, 1000) == 0 && fstat(fd, &st) == 0 && st.st_size == 1000 && ftruncate(fd, 40000) == 0 &&
+ pread(fd, buf, 2000, 0) == 2000;
+ for (int i = 0; good && i < 2000; i++) {
+ good = buf[i] == (i < 1000 ? pattern((unsigned long)i) : 0);
+ }
+ good = good && pread(fd, buf, 100, 30000) == 100 && buf[0] == 0 && buf[99] == 0 && pread(fd, buf, 10, 40000) == 0;
+ check(good, "truncate, then extend: the new part reads as zeros");
+
+ good = rename("/tmp/t/file", "/tmp/t/renamed") == 0 && stat("/tmp/t/file", &st) != 0 && errno == 2 &&
+ stat("/tmp/t/renamed", &st) == 0 && st.st_size == 40000;
+ check(good, "rename");
+
+ good = link("/tmp/t/renamed", "/tmp/t/hard") == 0 && fstat(fd, &st) == 0 && st.st_nlink == 2 &&
+ unlink("/tmp/t/renamed") == 0 && fstat(fd, &st) == 0 && st.st_nlink == 1;
+ check(good, "hard link, remove the first name");
+
+ good = unlink("/tmp/t/hard") == 0 && stat("/tmp/t/hard", &st) != 0 && fstat(fd, &st) == 0 && st.st_nlink == 0 &&
+ pread(fd, buf, 100, 0) == 100 && buf[5] == pattern(5) && pwrite(fd, "x", 1, 0) == 1;
+ close(fd);
+ check(good, "a removed file stays usable while it is open");
+
+ n = symlink("some/where else", "/tmp/t/symlink") == 0 ? readlink("/tmp/t/symlink", text, sizeof(text) - 1) : -1;
+ text[n > 0 ? n : 0] = 0;
+ check(n == 15 && strcmp(text, "some/where else") == 0 && lstat("/tmp/t/symlink", &st) == 0 &&
+ (st.st_mode & S_IFMT) == S_IFLNK, "symbolic link");
+
+ good = mkdir("/tmp/t/a", 0700) == 0 && mkdir("/tmp/t/a/b", 0700) == 0 && rmdir("/tmp/t/a") != 0 && errno == 66 &&
+ rename("/tmp/t/a", "/tmp/t/c") == 0 && stat("/tmp/t/c/b", &st) == 0 && stat("/tmp/t/c/b/..", &st) == 0 &&
+ rename("/tmp/t/c", "/tmp/t/c/b/inside") != 0 && rmdir("/tmp/t/c/b") == 0 && rmdir("/tmp/t/c") == 0 &&
+ stat("/tmp/t/c", &st) != 0;
+ check(good, "directories: nest, refuse to remove a full one, rename, remove");
+
+ fd = open("/tmp/t/mapped", O_RDWR | O_CREAT, 0600);
+ map = fd >= 0 && ftruncate(fd, 65536) == 0 ? mmap(NULL, 65536, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0) : MAP_FAILED;
+ good = map != MAP_FAILED;
+ if (good) {
+ memset(map + 1000, 'M', 100);
+ good = pread(fd, buf, 102, 999) == 102 && buf[0] == 0 && buf[1] == 'M' && buf[100] == 'M' && buf[101] == 0;
+ }
+ check(good, "shared mapping: what is stored through memory is seen by read()");
+ good = good && pwrite(fd, "WWWW", 4, 40000) == 4 && map[40000] == 'W' && map[40003] == 'W' && map[1000] == 'M';
+ check(good, "and what write() stores is seen through the mapping");
+ if (map != MAP_FAILED) {
+ munmap(map, 65536);
+ }
+ close(fd);
+
+ s = socket(AF_UNIX, SOCK_STREAM, 0);
+ good = s >= 0 && bind(s, &sun, sizeof(sun)) == 0 && stat(sun.sun_path, &st) == 0 && (st.st_mode & S_IFMT) == S_IFSOCK;
+ close(s);
+ check(good, "bind a local socket to a name");
+
+ good = mkdir("/tmp/t/many", 0755) == 0;
+ for (int i = 0; good && i < 300; i++) {
+ char name[32] = "/tmp/t/many/f000";
+
+ name[13] = (char)('0' + i / 100), name[14] = (char)('0' + i / 10 % 10), name[15] = (char)('0' + i % 10);
+ fd = open(name, O_WRONLY | O_CREAT, 0644);
+ good = fd >= 0 && write(fd, name, 16) == 16;
+ close(fd);
+ }
+ good = good && count_entries("/tmp/t/many") == 300;
+ for (int i = 0; good && i < 300; i++) {
+ char name[32] = "/tmp/t/many/f000";
+
+ name[13] = (char)('0' + i / 100), name[14] = (char)('0' + i / 10 % 10), name[15] = (char)('0' + i % 10);
+ good = unlink(name) == 0;
+ }
+ check(good && count_entries("/tmp/t/many") == 0 && rmdir("/tmp/t/many") == 0, "300 files in one directory: create, list, remove");
+
+ list_tree("/tmp/t", 1);
+}
+
+/* Run one line of /etc/rc: words separated by blanks, no quoting; a last word "&" = do not wait. */
+static void
+run_command(char *line)
+{
+ char *argv[64];
+ char *envp[] = { "PATH=/bin:/sbin:/usr/bin:/usr/sbin", "HOME=/", "TERM=dumb", NULL };
+ int argc = 0, status = 0, background = 0;
+ pid_t pid;
+
+ for (char *p = line; *p && argc < 63;) {
+ while (*p == ' ' || *p == '\t') {
+ *p++ = 0;
+ }
+ if (!*p) {
+ break;
+ }
+ argv[argc++] = p;
+ while (*p && *p != ' ' && *p != '\t') {
+ p++;
+ }
+ }
+ argv[argc] = NULL;
+ if (argc == 0) {
+ return;
+ }
+
+ printf("\n$");
+ for (int i = 0; i < argc; i++) {
+ printf(" %s", argv[i]);
+ }
+ printf("\n");
+ if (argc > 1 && strcmp(argv[argc - 1], "&") == 0) {
+ background = 1;
+ argv[--argc] = NULL;
+ }
+
+ /* "exec program args": become that program, keeping process number 1 */
+ if (strcmp(argv[0], "exec") == 0 && argc > 1) {
+ execve(argv[1], argv + 1, envp);
+ printf("%s: %s\n", argv[1], strerror(errno));
+ return;
+ }
+
+ pid = fork();
+ if (pid == 0) {
+ execve(argv[0], argv, envp);
+ printf("%s: %s\n", argv[0], strerror(errno));
+ _exit(127);
+ }
+ if (background && pid > 0) {
+ return;
+ }
+ if (pid < 0 || wait4(pid, &status, 0, NULL) != pid) {
+ printf("[could not run: %s]\n", strerror(errno));
+ } else if (!WIFEXITED(status)) {
+ printf("[killed by signal %d]\n", WTERMSIG(status));
+ } else if (WEXITSTATUS(status) != 0) {
+ printf("[exit status %d]\n", WEXITSTATUS(status));
+ }
+}
+
+static void
+run_rc(const char *path)
+{
+ static char script[8192];
+ int fd = open(path, O_RDONLY, 0);
+ ssize_t n;
+
+ if (fd < 0) {
+ return;
+ }
+ n = read(fd, script, sizeof(script) - 1);
+ close(fd);
+ script[n > 0 ? n : 0] = 0;
+
+ printf("\n=== %s ===\n", path);
+ for (char *line = script; *line;) {
+ char *end = strchr(line, '\n');
+
+ if (end) {
+ *end = 0;
+ }
+ if (*line != '#') {
+ run_command(line);
+ }
+ if (!end) {
+ break;
+ }
+ line = end + 1;
+ }
+}
+
+static void
+test_devices(void)
+{
+ unsigned char buf[16];
+ unsigned sum = 0;
+ int fd, good;
+
+ printf("\n-- devices --\n");
+ check(list_tree("/dev", 0) > 3, "devfs is mounted on /dev");
+
+ fd = open("/dev/zero", O_RDONLY, 0);
+ memset(buf, 0xff, sizeof(buf));
+ good = fd >= 0 && read(fd, buf, sizeof(buf)) == (ssize_t)sizeof(buf);
+ for (unsigned i = 0; i < sizeof(buf); i++) {
+ sum += buf[i];
+ }
+ close(fd);
+ check(good && sum == 0, "/dev/zero");
+
+ fd = open("/dev/null", O_WRONLY, 0);
+ check(fd >= 0 && write(fd, "x", 1) == 1, "/dev/null");
+ close(fd);
+
+ fd = open("/dev/random", O_RDONLY, 0);
+ memset(buf, 0, sizeof(buf));
+ good = fd >= 0 && read(fd, buf, sizeof(buf)) == (ssize_t)sizeof(buf);
+ close(fd);
+ printf(" /dev/random:");
+ for (unsigned i = 0; i < sizeof(buf); i++) {
+ printf(" %02x", buf[i]);
+ sum += buf[i];
+ }
+ printf("\n");
+ check(good && sum != 0, "/dev/random");
+}
+
+static void
+test_time(void)
+{
+ struct timeval before = { 0 }, after = { 0 };
+ long elapsed;
+
+ printf("\n-- time --\n");
+ gettimeofday(&before, NULL);
+ usleep(200000);
+ gettimeofday(&after, NULL);
+ elapsed = (after.tv_sec - before.tv_sec) * 1000 + (after.tv_usec - before.tv_usec) / 1000;
+ printf(" slept 200 ms, the clock advanced %ld ms\n", elapsed);
+ check(elapsed >= 190 && elapsed < 1000, "sleep and wall clock agree");
+}
+
+/*
+ * etc/inject.conf is one line, "LIBRARY NAME NAME ...": the kernel starts the programs with
+ * these file names with the library inserted (sysctl kern.exec_inject, see libredwood).
+ */
+static void
+configure_inject(void)
+{
+ char conf[512];
+ int fd = open(in_image("/etc/inject.conf"), O_RDONLY, 0);
+ long n;
+
+ if (fd < 0) {
+ return;
+ }
+ n = read(fd, conf, sizeof(conf) - 1);
+ close(fd);
+ while (n > 0 && (conf[n - 1] == '\n' || conf[n - 1] == ' ')) {
+ n--;
+ }
+ if (n <= 0) {
+ return;
+ }
+ conf[n] = 0;
+ /* one "LIBRARY NAME..." per line in the file; the kernel wants them separated by ";" */
+ for (long i = 0; i < n; i++) {
+ if (conf[i] == '\n') {
+ conf[i] = ';';
+ }
+ }
+ if (sysctlbyname("kern.exec_inject", NULL, NULL, conf, (size_t)n + 1) == 0) {
+ printf("init: library insertion: %s\n", conf);
+ } else {
+ printf("init: kern.exec_inject: error %d\n", errno);
+ }
+}
+
+int
+main(int argc, char **argv, char **envp)
+{
+ int fd = open("/dev/console", O_RDWR, 0);
+
+ dup2(fd, 0);
+ dup2(fd, 1);
+ dup2(fd, 2);
+ if (fd > 2) {
+ close(fd);
+ }
+
+ (void)envp;
+ if (argc > 0 && strncmp(argv[0], "/redwood/", 9) == 0) {
+ base = "/redwood";
+ }
+ /* Not process 1: a command runner, "init FILE" (this is how a launchd job runs a list of commands). */
+ if (getpid() != 1) {
+ if (argc > 1) {
+ run_rc(argv[1]);
+ }
+ return 0;
+ }
+
+ printf("\n=== init: process %d, started as %s ===\n", getpid(), argc > 0 ? argv[0] : "?");
+
+ show_system();
+ mount_writable();
+ test_files();
+ test_writable();
+ test_memory();
+ test_processes();
+ test_dynamic();
+ test_devices();
+ test_time();
+
+ printf("\n=== %d checks, %d failed ===\n", checks, failures);
+ /* daemons that do not run as root get the console as their standard error too */
+ chmod("/dev/console", 0666);
+ configure_inject();
+ run_rc(in_image("/etc/rc"));
+ printf("\n=== init: done ===\n");
+ reboot(RB_HALT);
+ return failures != 0;
+}
diff --git a/userland/src/inject.c b/userland/src/inject.c
new file mode 100644
index 0000000..8d32871
--- /dev/null
+++ b/userland/src/inject.c
@@ -0,0 +1,628 @@
+/*
+ * libredwood.dylib: code of ours inside stock iOS 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
+ * says so. What is done depends on the program:
+ *
+ * backboardd the window server (CoreAnimation in QuartzCore). There is no GPU, so the
+ * render server must use CoreAnimation's own software rasterizer, and we want to
+ * see why a frame is or is not drawn. The C++ objects are reached by replacing
+ * entries of their virtual tables.
+ * It is also where input enters the system: backboardd is the HID event server,
+ * and without Apple's multitouch driver it has no touch screen. We give it one:
+ * a "virtual" HID service that turns the samples of /dev/redwood-touch into the
+ * events that driver would have sent.
+ *
+ * And it does not wait five seconds for an ambient light sensor.
+ *
+ * containermanagerd (both of them)
+ * They ask the user manager for the "personas" of the user, of which this
+ * system has none, twenty times a second apart before they give up -- and
+ * 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;
+ * every one is checked against what is expected to be there before it is touched.
+ */
+#include <CoreFoundation/CoreFoundation.h>
+#include <dispatch/dispatch.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <mach/mach.h>
+#include <objc/runtime.h>
+#include <pthread.h>
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "redwood_input.h"
+
+extern const void *_dyld_get_shared_cache_range(size_t *length);
+
+#define CACHE_BASE 0x180000000UL /* where the cache was built to be, before the slide */
+
+static uintptr_t slide;
+
+static void
+say(const char *format, ...)
+{
+ char line[256];
+ va_list ap;
+ int n;
+
+ va_start(ap, format);
+ n = vsnprintf(line, sizeof(line), format, ap);
+ va_end(ap);
+ if (n > (int)sizeof(line) - 1) {
+ n = sizeof(line) - 1;
+ }
+ write(2, line, (size_t)n);
+}
+
+/* Replace one entry of a virtual table (unslid address `slot`) that must now hold `expected`. */
+static void *
+replace_virtual(const char *what, uintptr_t slot, uintptr_t expected, void *replacement)
+{
+ uintptr_t *entry = (uintptr_t *)(slot + slide);
+ vm_address_t page = (vm_address_t)entry & ~(vm_address_t)(vm_page_size - 1);
+ kern_return_t kr;
+ void *original;
+
+ if (*entry != expected + slide) {
+ say("redwood: %s: found %#lx, expected %#lx; left alone\n", what, *entry - slide, expected);
+ return NULL;
+ }
+ /* the tables are in read-only memory shared by every process: get a private writable copy of the page */
+ kr = vm_protect(mach_task_self(), page, vm_page_size, FALSE, VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
+ if (kr != KERN_SUCCESS) {
+ say("redwood: %s: cannot make the table writable (%d)\n", what, kr);
+ return NULL;
+ }
+ original = (void *)*entry;
+ *entry = (uintptr_t)replacement;
+ vm_protect(mach_task_self(), page, vm_page_size, FALSE, VM_PROT_READ);
+ return original;
+}
+
+/* ---- backboardd: CA::WindowServer ------------------------------------------------------------ */
+
+#define VT_APPLE_CLCD_DISPLAY 0x1d5b44520UL /* vtable for CA::WindowServer::AppleCLCDDisplay */
+#define VT_EAGL_SERVER 0x1d5b45c58UL /* vtable for CA::WindowServer::EAGLServer */
+#define VSLOT(vtable, offset) ((vtable) + 0x10 + (offset))
+
+#define DISPLAY_FLAGS(display) (*(uint64_t *)((char *)(display) + 0x9f2))
+#define DISPLAY_B233(display) (*(uint8_t *)((char *)(display) + 0x233))
+
+static int (*orig_is_ready)(void *display);
+static int (*orig_ignore_update_p)(void *display, void *update);
+static uintptr_t (*orig_begin_update)(void *display, void *update);
+static uintptr_t (*orig_finish_update)(void *display, void *update, unsigned flags);
+static void *(*orig_renderer)(void *server);
+static uintptr_t (*orig_render_update)(void *server, void *update, unsigned *flags);
+
+static unsigned calls_ready, calls_ignore, calls_begin, calls_finish, calls_render;
+static int last_ready = -1, last_ignore = -1;
+
+static int
+my_is_ready(void *display)
+{
+ int ready = orig_is_ready(display);
+
+ if (ready != last_ready || calls_ready < 3) {
+ say("redwood: is_ready -> %d (call %u, flags %#llx, b233 %#x)\n", ready, calls_ready,
+ (unsigned long long)DISPLAY_FLAGS(display), DISPLAY_B233(display));
+ last_ready = ready;
+ }
+ calls_ready++;
+ return ready;
+}
+
+static int
+my_ignore_update_p(void *display, void *update)
+{
+ int ignore = orig_ignore_update_p(display, update) & 1;
+
+ if (ignore != last_ignore || calls_ignore < 3) {
+ uint64_t *q = (uint64_t *)((char *)display + 0x220);
+
+ say("redwood: ignore_update_p -> %d (call %u, flags %#llx, update flags %#x)\n", ignore, calls_ignore,
+ (unsigned long long)DISPLAY_FLAGS(display), *(uint32_t *)((char *)update + 0xf0));
+ say("redwood: display +0x220: %#llx %#llx %#llx %#llx %#llx %#llx\n", (unsigned long long)q[0],
+ (unsigned long long)q[1], (unsigned long long)q[2], (unsigned long long)q[3], (unsigned long long)q[4],
+ (unsigned long long)q[5]);
+ last_ignore = ignore;
+ }
+ calls_ignore++;
+ return ignore;
+}
+
+static uintptr_t
+my_begin_update(void *display, void *update)
+{
+ uintptr_t r = orig_begin_update(display, update);
+
+ if (calls_begin++ < 6) {
+ say("redwood: begin_update -> %#lx (flags %#llx)\n", r, (unsigned long long)DISPLAY_FLAGS(display));
+ }
+ return r;
+}
+
+static uintptr_t
+my_finish_update(void *display, void *update, unsigned flags)
+{
+ uintptr_t r = orig_finish_update(display, update, flags);
+
+ if (calls_finish++ < 6) {
+ say("redwood: finish_update(%#x) -> %#lx\n", flags, r);
+ }
+ return r;
+}
+
+/*
+ * Every frame the server asks for its renderer, and while there is none it tries again to make a
+ * Metal and then an OpenGL ES context, which costs a lot and cannot succeed here. One try is enough:
+ * without a renderer the server draws with CA::WindowServer::Server::sw_renderer().
+ */
+static void *
+my_renderer(void *server)
+{
+ static int failed;
+ void *renderer;
+
+ if (failed) {
+ return NULL;
+ }
+ renderer = orig_renderer(server);
+ if (renderer == NULL) {
+ failed = 1;
+ say("redwood: no accelerated renderer; the software one will draw\n");
+ }
+ return renderer;
+}
+
+static uintptr_t
+my_render_update(void *server, void *update, unsigned *flags)
+{
+ uintptr_t r = orig_render_update(server, update, flags);
+
+ if (calls_render++ < 6) {
+ say("redwood: render_update -> %#lx (flags %#x)\n", r, flags ? *flags : 0);
+ }
+ return r;
+}
+
+static void
+window_server_fixes(void)
+{
+ orig_is_ready = replace_virtual("is_ready", VSLOT(VT_APPLE_CLCD_DISPLAY, 0xb0), 0x1882f0908UL, my_is_ready);
+ orig_ignore_update_p = replace_virtual("ignore_update_p", VSLOT(VT_APPLE_CLCD_DISPLAY, 0x138), 0x1882e0c90UL,
+ my_ignore_update_p);
+ orig_begin_update = replace_virtual("begin_update", VSLOT(VT_APPLE_CLCD_DISPLAY, 0x170), 0x1882ddda4UL,
+ my_begin_update);
+ orig_finish_update = replace_virtual("finish_update", VSLOT(VT_APPLE_CLCD_DISPLAY, 0x178), 0x1882c8568UL,
+ my_finish_update);
+ orig_renderer = replace_virtual("renderer", VSLOT(VT_EAGL_SERVER, 0x1a0), 0x1882e2548UL, my_renderer);
+ orig_render_update = replace_virtual("render_update", VSLOT(VT_EAGL_SERVER, 0x178), 0x18835770cUL,
+ my_render_update);
+ say("redwood: window server hooks %s\n", orig_is_ready && orig_ignore_update_p && orig_begin_update &&
+ orig_finish_update && orig_renderer && orig_render_update ? "installed" : "INCOMPLETE");
+}
+
+/* ---- backboardd: no ambient light sensor ------------------------------------------------------------ */
+
+/*
+ * CoreBrightness (-[BLControl waitForALSArrival], called while the window server starts) waits
+ * five seconds for the ambient light sensor to turn up among the HID services. There is none
+ * and none will come: do not wait for that.
+ *
+ * Wait for something else instead, at this convenient point: our own touch screen service.
+ * backboardd takes for its touch screen a service that is there when its touch processing
+ * starts, a moment later; one that turns up afterwards it does not notice. (For as long as
+ * the five seconds were waited here, ours was always in time by accident.)
+ */
+static dispatch_semaphore_t input_services_made;
+
+static void
+wait_for_als_arrival(__unused id self, __unused SEL selector)
+{
+ if (input_services_made != NULL &&
+ dispatch_semaphore_wait(input_services_made, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) != 0) {
+ say("redwood: input: no touch screen service after five seconds; going on without\n");
+ }
+}
+
+__attribute__((unused)) static void
+brightness_fixes(void)
+{
+ Class cls = objc_getClass("BLControl");
+ Method method = cls ? class_getInstanceMethod(cls, sel_registerName("waitForALSArrival")) : NULL;
+ IMP original = method ? method_getImplementation(method) : NULL;
+
+ if (original == NULL || (uintptr_t)original != 0x1af043734UL + slide) {
+ say("redwood: -[BLControl waitForALSArrival]: found %#lx, not what was expected; left alone\n",
+ original ? (uintptr_t)original - slide : 0);
+ return;
+ }
+ method_setImplementation(method, (IMP)wait_for_als_arrival);
+}
+
+/* ---- 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) */
+typedef struct __IOHIDEvent *IOHIDEventRef;
+typedef struct __IOHIDEventSystemClient *IOHIDEventSystemClientRef;
+typedef struct __IOHIDServiceClient *IOHIDServiceClientRef;
+
+/* IOHIDVirtualServiceClientCallbacksV2 */
+struct virtual_service_callbacks {
+ uint64_t version; /* 2 */
+ void (*notification)(void *target, void *refcon, IOHIDServiceClientRef service, uint32_t type, CFDictionaryRef property);
+ Boolean (*setProperty)(void *target, void *refcon, IOHIDServiceClientRef service, CFStringRef key, CFTypeRef value);
+ CFTypeRef (*copyProperty)(void *target, void *refcon, IOHIDServiceClientRef service, CFStringRef key);
+ IOHIDEventRef (*copyEvent)(void *target, void *refcon, IOHIDServiceClientRef service, uint32_t type, IOHIDEventRef matching, uint32_t options);
+ int (*setOutputEvent)(void *target, void *refcon, IOHIDServiceClientRef service, IOHIDEventRef event);
+ CFTypeRef (*copyMatchingEvent)(void *target, void *refcon, IOHIDServiceClientRef service, CFDictionaryRef matching);
+};
+
+extern IOHIDEventSystemClientRef IOHIDEventSystemClientCreateWithType(CFAllocatorRef allocator, int type, CFDictionaryRef attributes);
+extern void IOHIDEventSystemClientScheduleWithDispatchQueue(IOHIDEventSystemClientRef client, dispatch_queue_t queue);
+extern IOHIDServiceClientRef IOHIDVirtualServiceClientCreateWithCallbacks(IOHIDEventSystemClientRef client, CFDictionaryRef attributes,
+ const struct virtual_service_callbacks *callbacks, void *target, void *refcon);
+extern Boolean IOHIDVirtualServiceClientDispatchEvent(IOHIDServiceClientRef service, IOHIDEventRef event);
+extern IOHIDEventRef IOHIDEventCreateDigitizerEvent(CFAllocatorRef allocator, uint64_t time, uint32_t transducer, uint32_t index,
+ uint32_t identity, uint32_t event_mask, uint32_t button_mask, double x, double y, double z, double tip_pressure,
+ double barrel_pressure, double twist, Boolean range, Boolean touch, uint32_t options);
+extern IOHIDEventRef IOHIDEventCreateDigitizerFingerEvent(CFAllocatorRef allocator, uint64_t time, uint32_t index, uint32_t identity,
+ uint32_t event_mask, double x, double y, double z, double tip_pressure, double twist, Boolean range, Boolean touch,
+ uint32_t options);
+extern IOHIDEventRef IOHIDEventCreateKeyboardEvent(CFAllocatorRef allocator, uint64_t time, uint32_t usage_page, uint32_t usage,
+ Boolean down, uint32_t options);
+extern void IOHIDEventAppendEvent(IOHIDEventRef parent, IOHIDEventRef child, uint32_t options);
+extern void IOHIDEventSetIntegerValue(IOHIDEventRef event, uint32_t field, CFIndex value);
+
+#define HID_CLIENT_SIMPLE 4 /* a client that only sends */
+#define HID_CLIENT_RATE_CONTROLLED 3 /* what IOHIDEventSystemClientCreate() makes */
+#define HID_PAGE_DIGITIZER 0x0d
+#define HID_USAGE_TOUCH_SCREEN 0x04
+#define HID_PAGE_CONSUMER 0x0c
+#define HID_USAGE_CONSUMER_CONTROL 0x01
+#define HID_USAGE_POWER 0x30 /* the lock button */
+#define HID_USAGE_MENU 0x40 /* the home button */
+#define HID_USAGE_VOLUME_UP 0xe9
+#define HID_USAGE_VOLUME_DOWN 0xea
+#define DIGITIZER_HAND 3 /* kIOHIDDigitizerTransducerTypeHand */
+#define DIGITIZER_RANGE 0x1 /* event mask: what has changed */
+#define DIGITIZER_TOUCH 0x2
+#define DIGITIZER_POSITION 0x4
+#define DIGITIZER_FROM_EDGE_TIP 0x800 /* not a change: this finger came in over an edge of the screen */
+#define FIELD_IS_BUILT_IN 0x4
+#define FIELD_DIGITIZER_DISPLAY_INTEGRATED 0xb0019
+
+#define MAX_FINGERS 10
+
+/*
+ * A finger that lands this close to an edge of the screen (a fraction of the width or the height)
+ * is said to have come in over that edge. Apple's touch controller tells that from the shape of
+ * the contact and marks the finger's events; UIKit's screen edge recognizers (the swipe up that
+ * leaves an application, the swipe back in a navigation stack, the pull down from the top) take
+ * no touch that is not so marked, whatever its path. All we have is where the finger landed.
+ */
+#define EDGE_SIDE (16.0 / 375)
+#define EDGE_TOP (16.0 / 812)
+#define EDGE_BOTTOM (24.0 / 812)
+
+static struct {
+ bool touching, edge;
+ double x, y;
+} fingers[MAX_FINGERS];
+
+static CFNumberRef
+number(int value)
+{
+ return CFNumberCreate(NULL, kCFNumberIntType, &value);
+}
+
+/* The properties of a service of ours; the event server asks for them one at a time. */
+static CFTypeRef
+service_copy_property(__unused void *target, void *refcon, __unused IOHIDServiceClientRef service, CFStringRef key)
+{
+ static CFMutableSetRef asked;
+ CFTypeRef value = CFDictionaryGetValue((CFDictionaryRef)refcon, key);
+
+ if (asked == NULL) {
+ asked = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);
+ }
+ if (value == NULL && !CFSetContainsValue(asked, key) && CFSetGetCount(asked) < 40) {
+ char name[96] = "?";
+
+ CFSetAddValue(asked, key);
+ CFStringGetCString(key, name, sizeof(name), kCFStringEncodingUTF8);
+ say("redwood: input: the event server asks for property \"%s\", which we do not have\n", name);
+ }
+ return value ? CFRetain(value) : NULL;
+}
+
+/*
+ * What the window server last asked of the touch screen ("TouchDetectionMode"), in the low
+ * byte: 1 = report touches; TOUCH_MODE_WAKE while the display is off and a tap is to wake it
+ * -- which Apple's multitouch controller then does on its own; TOUCH_MODE_OFF = nothing at
+ * all. (Seen: 0xff and 0xfe during the boot, 0x1 with the display on, 0x1fe after the lock
+ * button.)
+ */
+#define TOUCH_MODE_WAKE 0xfe
+#define TOUCH_MODE_OFF 0xff
+static volatile int touch_mode;
+
+/* What the event server tells a service of ours: said once per name, to learn what there is. */
+static Boolean
+service_set_property(__unused void *target, __unused void *refcon, __unused IOHIDServiceClientRef service, CFStringRef key,
+ CFTypeRef value)
+{
+ static CFMutableSetRef told;
+ char name[96] = "?", text[160] = "?";
+ CFStringRef description;
+
+ if (key != NULL && value != NULL && CFEqual(key, CFSTR("TouchDetectionMode")) && CFGetTypeID(value) == CFNumberGetTypeID()) {
+ int mode = 0;
+
+ CFNumberGetValue(value, kCFNumberIntType, &mode);
+ if (mode != touch_mode) {
+ say("redwood: input: touch detection mode %#x\n", mode);
+ }
+ touch_mode = mode;
+ }
+ if (told == NULL) {
+ told = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);
+ }
+ if (key != NULL && !CFSetContainsValue(told, key) && CFSetGetCount(told) < 24) {
+ CFSetAddValue(told, key);
+ CFStringGetCString(key, name, sizeof(name), kCFStringEncodingUTF8);
+ description = value ? CFCopyDescription(value) : NULL;
+ if (description != NULL) {
+ CFStringGetCString(description, text, sizeof(text), kCFStringEncodingUTF8);
+ CFRelease(description);
+ }
+ say("redwood: input: the event server sets \"%s\" = %s\n", name, text);
+ }
+ return true;
+}
+
+static void
+service_notification(__unused void *target, __unused void *refcon, __unused IOHIDServiceClientRef service,
+ __unused uint32_t type, __unused CFDictionaryRef property)
+{
+}
+
+static const struct virtual_service_callbacks service_callbacks = {
+ .version = 2, .notification = service_notification, .setProperty = service_set_property,
+ .copyProperty = service_copy_property,
+};
+
+/* A HID service of ours inside the event server: built in, with one usage. */
+static IOHIDServiceClientRef
+make_service(IOHIDEventSystemClientRef client, const char *product, int page, int usage, bool display)
+{
+ CFMutableDictionaryRef properties = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks);
+ CFMutableDictionaryRef pair = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks);
+ CFStringRef name = CFStringCreateWithCString(NULL, product, kCFStringEncodingUTF8);
+ CFNumberRef page_number = number(page), usage_number = number(usage), zero = number(0);
+ CFArrayRef pairs;
+
+ CFDictionarySetValue(pair, CFSTR("DeviceUsagePage"), page_number);
+ CFDictionarySetValue(pair, CFSTR("DeviceUsage"), usage_number);
+ pairs = CFArrayCreate(NULL, (const void **)&pair, 1, &kCFTypeArrayCallBacks);
+ CFDictionarySetValue(properties, CFSTR("PrimaryUsagePage"), page_number);
+ CFDictionarySetValue(properties, CFSTR("PrimaryUsage"), usage_number);
+ CFDictionarySetValue(properties, CFSTR("DeviceUsagePage"), page_number);
+ CFDictionarySetValue(properties, CFSTR("DeviceUsage"), usage_number);
+ CFDictionarySetValue(properties, CFSTR("DeviceUsagePairs"), pairs);
+ CFDictionarySetValue(properties, CFSTR("Built-In"), kCFBooleanTrue);
+ CFDictionarySetValue(properties, CFSTR("Transport"), CFSTR("SPI"));
+ CFDictionarySetValue(properties, CFSTR("Manufacturer"), CFSTR("redwood"));
+ CFDictionarySetValue(properties, CFSTR("Product"), name);
+ CFDictionarySetValue(properties, CFSTR("VendorID"), zero);
+ CFDictionarySetValue(properties, CFSTR("ProductID"), zero);
+ if (display) {
+ CFDictionarySetValue(properties, CFSTR("DisplayIntegrated"), kCFBooleanTrue);
+ }
+ /* the dictionary stays: it is what service_copy_property() answers from */
+ return IOHIDVirtualServiceClientCreateWithCallbacks(client, properties, &service_callbacks, NULL, properties);
+}
+
+/* One frame of the touch screen: the hand, and under it every finger that is down or has just lifted. */
+static void
+send_touch(IOHIDServiceClientRef screen, const struct redwood_touch *t)
+{
+ uint32_t change = t->type == REDWOOD_TOUCH_MOVE ? DIGITIZER_POSITION : DIGITIZER_RANGE | DIGITIZER_TOUCH;
+ IOHIDEventRef hand, finger;
+ bool any = false;
+ unsigned f = t->finger;
+
+ if (f >= MAX_FINGERS || (t->type != REDWOOD_TOUCH_DOWN && !fingers[f].touching)) {
+ return;
+ }
+ fingers[f].touching = t->type != REDWOOD_TOUCH_UP;
+ fingers[f].x = t->x / 65535.0;
+ fingers[f].y = t->y / 65535.0;
+ if (t->type == REDWOOD_TOUCH_DOWN) {
+ fingers[f].edge = fingers[f].x < EDGE_SIDE || fingers[f].x > 1 - EDGE_SIDE || fingers[f].y < EDGE_TOP ||
+ fingers[f].y > 1 - EDGE_BOTTOM;
+ }
+ for (unsigned i = 0; i < MAX_FINGERS; i++) {
+ any |= fingers[i].touching;
+ }
+
+ hand = IOHIDEventCreateDigitizerEvent(NULL, t->time, DIGITIZER_HAND, 0, 0, change & ~DIGITIZER_RANGE, 0, fingers[f].x,
+ fingers[f].y, 0, 0, 0, 0, any, any, 0);
+ IOHIDEventSetIntegerValue(hand, FIELD_DIGITIZER_DISPLAY_INTEGRATED, 1);
+ IOHIDEventSetIntegerValue(hand, FIELD_IS_BUILT_IN, 1);
+ for (unsigned i = 0; i < MAX_FINGERS; i++) {
+ if (!fingers[i].touching && i != f) {
+ continue;
+ }
+ finger = IOHIDEventCreateDigitizerFingerEvent(NULL, t->time, i + 1, i + 2,
+ (i == f ? change : 0) | (fingers[i].edge ? DIGITIZER_FROM_EDGE_TIP : 0), fingers[i].x, fingers[i].y, 0,
+ fingers[i].touching ? 1.0 : 0.0, 0, fingers[i].touching, fingers[i].touching, 0);
+ IOHIDEventSetIntegerValue(finger, FIELD_DIGITIZER_DISPLAY_INTEGRATED, 1);
+ IOHIDEventAppendEvent(hand, finger, 0);
+ CFRelease(finger);
+ }
+ IOHIDVirtualServiceClientDispatchEvent(screen, hand);
+ CFRelease(hand);
+}
+
+static void
+send_button(IOHIDServiceClientRef buttons, const struct redwood_touch *t)
+{
+ uint32_t usage = t->finger == REDWOOD_BUTTON_LOCK ? HID_USAGE_POWER : t->finger == REDWOOD_BUTTON_HOME ? HID_USAGE_MENU :
+ t->finger == REDWOOD_BUTTON_VOLUME_UP ? HID_USAGE_VOLUME_UP : t->finger == REDWOOD_BUTTON_VOLUME_DOWN ?
+ HID_USAGE_VOLUME_DOWN : 0;
+ IOHIDEventRef event;
+
+ if (usage == 0) {
+ return;
+ }
+ event = IOHIDEventCreateKeyboardEvent(NULL, t->time, HID_PAGE_CONSUMER, usage, t->type == REDWOOD_BUTTON_DOWN, 0);
+ IOHIDEventSetIntegerValue(event, FIELD_IS_BUILT_IN, 1);
+ IOHIDVirtualServiceClientDispatchEvent(buttons, event);
+ CFRelease(event);
+}
+
+static void *
+input_thread(__unused void *arg)
+{
+ static const int types[] = { HID_CLIENT_SIMPLE, HID_CLIENT_RATE_CONTROLLED };
+ IOHIDEventSystemClientRef client = NULL;
+ IOHIDServiceClientRef screen = NULL, buttons = NULL;
+ struct redwood_touch t;
+ unsigned count = 0, waking = 0; /* waking: the fingers whose touch went into waking the display */
+ int device;
+
+ pthread_setname_np("redwood input");
+ device = open(REDWOOD_TOUCH_DEVICE, O_RDONLY);
+ if (device < 0) {
+ say("redwood: input: %s: %s\n", REDWOOD_TOUCH_DEVICE, strerror(errno));
+ return NULL;
+ }
+ sleep(3); /* let backboardd get as far as starting its event server */
+ for (unsigned i = 0; screen == NULL && i < sizeof(types) / sizeof(types[0]); i++) {
+ /* this waits until the server (this very program) answers */
+ client = IOHIDEventSystemClientCreateWithType(NULL, types[i], NULL);
+ if (client == NULL) {
+ say("redwood: input: no HID client of type %d\n", types[i]);
+ continue;
+ }
+ IOHIDEventSystemClientScheduleWithDispatchQueue(client, dispatch_queue_create("redwood.input", NULL));
+ screen = make_service(client, "Redwood touch screen", HID_PAGE_DIGITIZER, HID_USAGE_TOUCH_SCREEN, true);
+ if (screen == NULL) {
+ say("redwood: input: a HID client of type %d may not create services\n", types[i]);
+ }
+ }
+ if (screen != NULL) {
+ buttons = make_service(client, "Redwood buttons", HID_PAGE_CONSUMER, HID_USAGE_CONSUMER_CONTROL, false);
+ }
+ say("redwood: input: touch screen service %p, buttons %p\n", (void *)screen, (void *)buttons);
+ dispatch_semaphore_signal(input_services_made); /* see wait_for_als_arrival() */
+ if (screen == NULL) {
+ return NULL;
+ }
+
+ while (read(device, &t, sizeof(t)) == (ssize_t)sizeof(t)) {
+ if (count++ < 4) {
+ say("redwood: input: sample type %u finger %u at %u %u\n", t.type, t.finger, t.x, t.y);
+ }
+ if (t.type > REDWOOD_TOUCH_UP) {
+ if (buttons != NULL) {
+ send_button(buttons, &t);
+ }
+ } else if (t.type == REDWOOD_TOUCH_DOWN && (touch_mode & 0xff) == TOUCH_MODE_WAKE && buttons != NULL) {
+ /*
+ * The display is off and a tap is to wake it. The lock button is what wakes it here:
+ * press it for the finger, and keep the rest of this touch to ourselves.
+ */
+ struct redwood_touch press = { .time = t.time, .type = REDWOOD_BUTTON_DOWN, .finger = REDWOOD_BUTTON_LOCK };
+
+ send_button(buttons, &press);
+ press.type = REDWOOD_BUTTON_UP;
+ send_button(buttons, &press);
+ waking |= 1u << (t.finger & 31);
+ } else if (waking & (1u << (t.finger & 31))) {
+ if (t.type == REDWOOD_TOUCH_UP) {
+ waking &= ~(1u << (t.finger & 31));
+ }
+ } else {
+ send_touch(screen, &t);
+ }
+ }
+ say("redwood: input: %s: %s\n", REDWOOD_TOUCH_DEVICE, strerror(errno));
+ return NULL;
+}
+
+static void
+input_start(void)
+{
+ pthread_t thread;
+
+ input_services_made = dispatch_semaphore_create(0);
+ if (pthread_create(&thread, NULL, input_thread, NULL) == 0) {
+ pthread_detach(thread);
+ }
+}
+
+/* ---- containermanagerd ---------------------------------------------------------------------------- */
+
+static BOOL
+personas_are_supported(__unused id self, __unused SEL selector)
+{
+ return NO;
+}
+
+static void
+container_manager_fixes(void)
+{
+ Class cls = objc_getClass("MCMUserIdentityCache");
+ Method method = cls ? class_getClassMethod(cls, sel_registerName("personasAreSupported")) : NULL;
+ IMP original = method ? method_getImplementation(method) : NULL;
+
+ if (original == NULL || (uintptr_t)original != 0x1c3ea6298UL + slide) {
+ say("redwood: +[MCMUserIdentityCache personasAreSupported]: found %#lx, not what was expected; left alone\n",
+ original ? (uintptr_t)original - slide : 0);
+ return;
+ }
+ method_setImplementation(method, (IMP)personas_are_supported);
+ say("redwood: container manager: no personas\n");
+}
+
+/* ---------------------------------------------------------------------------------------------- */
+
+__attribute__((constructor))
+static void
+redwood_init(void)
+{
+ const char *name = getprogname();
+ size_t length = 0;
+ const void *cache = _dyld_get_shared_cache_range(&length);
+
+ if (name == NULL || cache == NULL) {
+ return;
+ }
+ slide = (uintptr_t)cache - CACHE_BASE;
+ if (strcmp(name, "backboardd") == 0) {
+ window_server_fixes();
+ /*
+ * brightness_fixes() is not used for now: with it backboardd no longer takes our touch
+ * screen service for its own ("still waiting for a main screen digitizer"), whether the
+ * service is made before or after the touch processing starts. Why is not known yet;
+ * until it is, the five seconds stay.
+ */
+ input_start();
+ } else if (strncmp(name, "containermanagerd", 17) == 0) {
+ container_manager_fixes();
+ }
+}
diff --git a/userland/src/inject_sb.c b/userland/src/inject_sb.c
new file mode 100644
index 0000000..e255f79
--- /dev/null
+++ b/userland/src/inject_sb.c
@@ -0,0 +1,164 @@
+/*
+ * libredwood-sb.dylib: code of ours inside SpringBoard (see inject.c for how it gets there).
+ *
+ * - The phone is "activated". SpringBoard asks mobileactivationd, which is not running (and
+ * could not talk to Apple anyway); without an answer it treats the device as bricked and
+ * shows the first-boot setup ("hello") instead of the lock screen.
+ * - The setup assistant is never needed, whatever the reason: nobody is going to go through
+ * it here.
+ * - SpringBoard starts a few seconds late where the kernel's boot-args say so (sb_delay=N;
+ * "xl run" does for the phone). /private/var is empty at every boot, so the applications
+ * are registered anew each time, one after another; one that is registered after
+ * SpringBoard has laid out the home screen ends up on a later page, and which one that is
+ * differs from boot to boot. On the phone that happens; under QEMU, where everything takes
+ * five times as long, it does not -- and there the delay is harmful: for a reason not yet
+ * found the window server then never takes our touch screen service for its own.
+ * (A wrapper program in the launchd job would be the obvious way to wait; launchd panics
+ * the system when a system job runs anything that is not Apple's.)
+ * - Darwin notifications as a remote control, for scripts (rwtouch notify NAME):
+ * com.redwood.unlock what the lock screen does after "swipe up to open"
+ */
+#include <CoreFoundation/CoreFoundation.h>
+#include <dispatch/dispatch.h>
+#include <notify.h>
+#include <objc/message.h>
+#include <objc/runtime.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/sysctl.h>
+#include <unistd.h>
+
+static void
+say(const char *format, ...)
+{
+ char line[256];
+ va_list ap;
+ int n;
+
+ va_start(ap, format);
+ n = vsnprintf(line, sizeof(line), format, ap);
+ va_end(ap);
+ if (n > (int)sizeof(line) - 1) {
+ n = sizeof(line) - 1;
+ }
+ write(2, line, (size_t)n);
+}
+
+/* ---- methods of SpringBoard's classes, replaced --------------------------------------------------- */
+
+extern const void *_dyld_get_shared_cache_range(size_t *length);
+
+#define CACHE_BASE 0x180000000UL /* where the cache was built to be, before the slide */
+
+static uintptr_t slide;
+
+/*
+ * Replace -[CLASS SELECTOR], whose code must now be at the unslid address `expected` (iOS 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.)
+ */
+static IMP
+replace_method(const char *class_name, const char *selector, uintptr_t expected, IMP replacement)
+{
+ Class cls = objc_getClass(class_name);
+ Method method = cls ? class_getInstanceMethod(cls, sel_registerName(selector)) : NULL;
+ IMP original = method ? method_getImplementation(method) : NULL;
+
+ if (original == NULL || (uintptr_t)original != expected + slide) {
+ say("redwood: -[%s %s]: found %#lx, expected %#lx; left alone\n", class_name, selector,
+ original ? (uintptr_t)original - slide : 0, expected);
+ return NULL;
+ }
+ method_setImplementation(method, replacement);
+ return original;
+}
+
+/*
+ * -[SBLockdownManager _setupActivationState] asks MobileActivation and keeps the answer in the
+ * int at +8: 2 = activated, 1 = not, 3 = unknown; it stays 0 when there is no answer.
+ */
+#define LOCKDOWN_STATE(manager) (*(int *)((char *)(manager) + 8))
+#define LOCKDOWN_ACTIVATED 2
+
+static void
+setup_activation_state(id self, __unused SEL selector)
+{
+ LOCKDOWN_STATE(self) = LOCKDOWN_ACTIVATED;
+}
+
+/* -[SBSetupManager _setSetupRequiredReason:]: 0 = no need for the setup assistant */
+static void (*original_set_setup_required_reason)(id self, SEL selector, long reason);
+
+static void
+set_setup_required_reason(id self, SEL selector, long reason)
+{
+ if (reason != 0) {
+ say("redwood: SpringBoard wants the setup assistant (reason %ld); not here\n", reason);
+ }
+ original_set_setup_required_reason(self, selector, 0);
+}
+
+/* ---- remote control ------------------------------------------------------------------------------ */
+
+#define UNLOCK_SOURCE_COVER_SHEET 24 /* what the lock screen itself passes */
+
+static void
+unlock(void)
+{
+ Class cls = objc_getClass("SBLockScreenManager");
+ SEL shared = sel_registerName("sharedInstance"), locked = sel_registerName("isUILocked");
+ SEL unlock_ui = sel_registerName("unlockUIFromSource:withOptions:");
+ id manager;
+
+ if (cls == NULL || class_getClassMethod(cls, shared) == NULL || class_getInstanceMethod(cls, locked) == NULL ||
+ class_getInstanceMethod(cls, unlock_ui) == NULL) {
+ say("redwood: unlock: SBLockScreenManager is not what it was\n");
+ return;
+ }
+ manager = ((id (*)(Class, SEL))objc_msgSend)(cls, shared);
+ if (manager == NULL) {
+ say("redwood: unlock: no lock screen manager yet\n");
+ } else if (!((BOOL (*)(id, SEL))objc_msgSend)(manager, locked)) {
+ say("redwood: unlock: not locked\n");
+ } else {
+ BOOL done = ((BOOL (*)(id, SEL, long, id))objc_msgSend)(manager, unlock_ui, UNLOCK_SOURCE_COVER_SHEET, NULL);
+
+ say("redwood: unlock: asked, answer %d\n", done);
+ }
+}
+
+__attribute__((constructor))
+static void
+redwood_springboard_init(void)
+{
+ const char *name = getprogname();
+ size_t length = 0;
+ IMP activation;
+ int token;
+
+ if (name == NULL || strcmp(name, "SpringBoard") != 0) {
+ return;
+ }
+ slide = (uintptr_t)_dyld_get_shared_cache_range(&length) - CACHE_BASE;
+ activation = replace_method("SBLockdownManager", "_setupActivationState", 0x1c4bc8dfcUL, (IMP)setup_activation_state);
+ original_set_setup_required_reason = (void (*)(id, SEL, long))replace_method("SBSetupManager",
+ "_setSetupRequiredReason:", 0x1c4cdd3a4UL, (IMP)set_setup_required_reason);
+ say("redwood: SpringBoard: activation %s, setup assistant %s\n", activation ? "answered here" : "NOT replaced",
+ original_set_setup_required_reason ? "refused" : "NOT replaced");
+ {
+ char args[1024] = "";
+ size_t size = sizeof(args) - 1;
+ const char *delay;
+
+ if (sysctlbyname("kern.bootargs", args, &size, NULL, 0) == 0 && (delay = strstr(args, "sb_delay=")) != NULL &&
+ (delay == args || delay[-1] == ' ')) {
+ usleep((useconds_t)(atof(delay + 9) * 1e6));
+ }
+ }
+ notify_register_dispatch("com.redwood.unlock", &token, dispatch_get_main_queue(), ^(__unused int t) {
+ unlock();
+ });
+}
diff --git a/userland/src/mg_test.c b/userland/src/mg_test.c
new file mode 100644
index 0000000..96260b9
--- /dev/null
+++ b/userland/src/mg_test.c
@@ -0,0 +1,41 @@
+/*
+ * mg_test: what MobileGestalt says about this device (the answers iOS builds its idea of the
+ * hardware from). usage: mg_test [KEY...]
+ */
+#include <CoreFoundation/CoreFoundation.h>
+#include <stdio.h>
+
+extern CFTypeRef MGCopyAnswer(CFStringRef key);
+
+static const char *const keys[] = {
+ "DeviceClass", "DeviceClassNumber", "DeviceName", "ProductType", "HWModelStr", "ModelNumber", "ProductName",
+ "marketing-name", "UserAssignedDeviceName", "ComputerName", "SerialNumber", "UniqueDeviceID", "HasBaseband",
+ "telephony", "cellular-data", "wifi", "bluetooth", "DeviceSupportsTelephonyOverUSB", "main-screen-scale",
+ "main-screen-width", "main-screen-height", "main-screen-class", "ArtworkDeviceSubType", "DeviceColor", "CPUArchitecture",
+ "BuildVersion", "ProductVersion", "RegionInfo", "front-facing-camera", "rear-facing-camera", "still-camera",
+};
+
+int
+main(int argc, char **argv)
+{
+ int count = argc > 1 ? argc - 1 : (int)(sizeof(keys) / sizeof(keys[0]));
+
+ for (int i = 0; i < count; i++) {
+ const char *name = argc > 1 ? argv[i + 1] : keys[i];
+ CFStringRef key = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);
+ CFTypeRef answer = MGCopyAnswer(key);
+ CFStringRef text = answer ? CFCopyDescription(answer) : NULL;
+ char line[256] = "(none)";
+
+ if (text) {
+ CFStringGetCString(text, line, sizeof(line), kCFStringEncodingUTF8);
+ CFRelease(text);
+ }
+ printf("mg_test: %s = %s\n", name, line);
+ if (answer) {
+ CFRelease(answer);
+ }
+ CFRelease(key);
+ }
+ return 0;
+}
diff --git a/userland/src/redwood_input.h b/userland/src/redwood_input.h
new file mode 100644
index 0000000..3944100
--- /dev/null
+++ b/userland/src/redwood_input.h
@@ -0,0 +1,47 @@
+/*
+ * /dev/redwood-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
+ * 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.
+ *
+ * write(): one or more records (time is ignored; the kernel stamps them)
+ * read(): blocks until there is at least one record, returns as many whole ones as fit
+ */
+#ifndef _SYS_REDWOOD_INPUT_H_
+#define _SYS_REDWOOD_INPUT_H_
+
+#include <stdint.h>
+
+#define REDWOOD_TOUCH_DEVICE "/dev/redwood-touch"
+
+#define REDWOOD_TOUCH_DOWN 1 /* a finger has landed */
+#define REDWOOD_TOUCH_MOVE 2
+#define REDWOOD_TOUCH_UP 3 /* it has lifted (x, y: where it was last) */
+#define REDWOOD_BUTTON_DOWN 4 /* a hardware button; `finger` says which (REDWOOD_BUTTON_*), x and y are 0 */
+#define REDWOOD_BUTTON_UP 5
+
+#define REDWOOD_BUTTON_LOCK 1 /* the side button */
+#define REDWOOD_BUTTON_VOLUME_UP 2
+#define REDWOOD_BUTTON_VOLUME_DOWN 3
+#define REDWOOD_BUTTON_HOME 4
+
+struct redwood_touch {
+ uint64_t time; /* mach_absolute_time() when the sample was posted */
+ uint32_t type; /* REDWOOD_TOUCH_* or REDWOOD_BUTTON_DOWN/UP */
+ uint32_t finger; /* which finger, from 0 (or which button) */
+ uint32_t x, y; /* position on the display, 0 = left/top edge, 65535 = right/bottom edge */
+};
+
+#ifdef KERNEL
+/* For drivers; not from interrupt context. */
+void redwood_touch_post(uint32_t type, uint32_t finger, uint32_t x, uint32_t y);
+void redwood_input_init(void);
+void redwood_virtio_input_init(void); /* boot-arg virtio_input=1: QEMU's virtio pointer and keyboard */
+void redwood_goodix_init(void); /* boot-arg touchscreen=1: the phone's touch screen */
+void redwood_cpufreq_init(void); /* boot-arg cpufreq=1: the phone's processor at full speed */
+#endif
+
+#endif /* _SYS_REDWOOD_INPUT_H_ */
diff --git a/userland/src/rwtouch.c b/userland/src/rwtouch.c
new file mode 100644
index 0000000..1144f2f
--- /dev/null
+++ b/userland/src/rwtouch.c
@@ -0,0 +1,162 @@
+/*
+ * rwtouch: replay touches through /dev/redwood-touch (see redwood_input.h).
+ *
+ * usage: rwtouch STEP...
+ * wait SECONDS pause
+ * tap X Y a short touch
+ * swipe X0 Y0 X1 Y1 [MS] drag from one point to the other in MS milliseconds (default 300)
+ * hold X Y MS touch and stay
+ * button NAME [MS] press a button: home, lock, volup, voldown
+ * read print the samples that arrive, forever (to watch the queue)
+ * notify NAME post a Darwin notification (com.redwood.unlock: see inject_sb.c)
+ * clock how long short sleeps really take (a check of the kernel's timers)
+ * Positions are fractions of the screen: 0 0 is the top left corner, 1 1 the bottom right.
+ * Example, "swipe up from the bottom edge two minutes after boot":
+ * rwtouch wait 120 swipe 0.5 0.99 0.5 0.4 250
+ */
+#include <fcntl.h>
+#include <mach/mach_time.h>
+#include <notify.h>
+#include <pthread.h>
+#include <sys/qos.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "redwood_input.h"
+
+static int device;
+
+static void
+post(uint32_t type, double x, double y)
+{
+ struct redwood_touch t = { .type = type, .finger = 0, .x = (uint32_t)(x * 65535.0 + 0.5), .y = (uint32_t)(y * 65535.0 + 0.5) };
+
+ if (write(device, &t, sizeof(t)) != (ssize_t)sizeof(t)) {
+ perror("rwtouch: write");
+ exit(1);
+ }
+}
+
+static void
+button(uint32_t which, int ms)
+{
+ struct redwood_touch t = { .type = REDWOOD_BUTTON_DOWN, .finger = which };
+
+ if (write(device, &t, sizeof(t)) != (ssize_t)sizeof(t)) {
+ perror("rwtouch: write");
+ exit(1);
+ }
+ usleep((useconds_t)ms * 1000);
+ t.type = REDWOOD_BUTTON_UP;
+ write(device, &t, sizeof(t));
+}
+
+static void
+drag(double x0, double y0, double x1, double y1, int ms)
+{
+ int steps = ms / 16 > 2 ? ms / 16 : 2; /* a sample per display frame */
+
+ post(REDWOOD_TOUCH_DOWN, x0, y0);
+ for (int i = 1; i <= steps; i++) {
+ usleep((useconds_t)ms * 1000 / (useconds_t)steps);
+ post(REDWOOD_TOUCH_MOVE, x0 + (x1 - x0) * i / steps, y0 + (y1 - y0) * i / steps);
+ }
+ usleep(16000);
+ post(REDWOOD_TOUCH_UP, x1, y1);
+}
+
+int
+main(int argc, char **argv)
+{
+ /* a gesture is a matter of timing: do not let the rest of a busy system stretch it */
+ pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
+ device = open(REDWOOD_TOUCH_DEVICE, O_RDWR);
+ if (device < 0) {
+ perror("rwtouch: " REDWOOD_TOUCH_DEVICE);
+ return 1;
+ }
+ for (int i = 1; i < argc; i++) {
+ const char *step = argv[i];
+ int left = argc - i - 1;
+
+ if (strcmp(step, "wait") == 0 && left >= 1) {
+ usleep((useconds_t)(atof(argv[i + 1]) * 1e6));
+ i += 1;
+ } else if (strcmp(step, "tap") == 0 && left >= 2) {
+ double x = atof(argv[i + 1]), y = atof(argv[i + 2]);
+
+ post(REDWOOD_TOUCH_DOWN, x, y);
+ usleep(60000);
+ post(REDWOOD_TOUCH_UP, x, y);
+ i += 2;
+ } else if (strcmp(step, "hold") == 0 && left >= 3) {
+ double x = atof(argv[i + 1]), y = atof(argv[i + 2]);
+
+ post(REDWOOD_TOUCH_DOWN, x, y);
+ usleep((useconds_t)atoi(argv[i + 3]) * 1000);
+ post(REDWOOD_TOUCH_UP, x, y);
+ i += 3;
+ } else if (strcmp(step, "button") == 0 && left >= 1) {
+ const char *name = argv[i + 1];
+ uint32_t which = strcmp(name, "home") == 0 ? REDWOOD_BUTTON_HOME : strcmp(name, "lock") == 0 ?
+ REDWOOD_BUTTON_LOCK : strcmp(name, "volup") == 0 ? REDWOOD_BUTTON_VOLUME_UP :
+ strcmp(name, "voldown") == 0 ? REDWOOD_BUTTON_VOLUME_DOWN : 0;
+ int ms = left >= 2 && argv[i + 2][0] >= '0' && argv[i + 2][0] <= '9' ? atoi(argv[i + 2]) : 0;
+
+ if (which == 0) {
+ fprintf(stderr, "rwtouch: buttons are home, lock, volup and voldown\n");
+ return 2;
+ }
+ button(which, ms ? ms : 80);
+ i += ms ? 2 : 1;
+ } else if (strcmp(step, "swipe") == 0 && left >= 4) {
+ int ms = left >= 5 && argv[i + 5][0] >= '0' && argv[i + 5][0] <= '9' ? atoi(argv[i + 5]) : 0;
+
+ drag(atof(argv[i + 1]), atof(argv[i + 2]), atof(argv[i + 3]), atof(argv[i + 4]), ms ? ms : 300);
+ i += ms ? 5 : 4;
+ } else if (strcmp(step, "notify") == 0 && left >= 1) {
+ uint32_t status = notify_post(argv[i + 1]);
+
+ printf("rwtouch: notification %s: %s\n", argv[i + 1], status == NOTIFY_STATUS_OK ? "posted" : "FAILED");
+ i += 1;
+ } else if (strcmp(step, "clock") == 0) {
+ static const useconds_t lengths[] = { 1000, 16000, 100000 };
+ mach_timebase_info_data_t timebase;
+
+ mach_timebase_info(&timebase);
+ for (unsigned k = 0; k < sizeof(lengths) / sizeof(lengths[0]); k++) {
+ uint64_t start = mach_absolute_time(), worst = 0, total;
+
+ for (int n = 0; n < 20; n++) {
+ uint64_t before = mach_absolute_time(), took;
+
+ usleep(lengths[k]);
+ took = mach_absolute_time() - before;
+ worst = took > worst ? took : worst;
+ }
+ total = (mach_absolute_time() - start) * timebase.numer / timebase.denom / 1000;
+ printf("rwtouch: 20 sleeps of %u us took %llu us (the longest %llu us)\n", lengths[k],
+ (unsigned long long)total, (unsigned long long)(worst * timebase.numer / timebase.denom / 1000));
+ }
+ } else if (strcmp(step, "read") == 0) {
+ struct redwood_touch t;
+
+ while (read(device, &t, sizeof(t)) == (ssize_t)sizeof(t)) {
+ if (t.type >= REDWOOD_BUTTON_DOWN) {
+ printf("rwtouch: button %u %s\n", t.finger, t.type == REDWOOD_BUTTON_DOWN ? "down" : "up");
+ continue;
+ }
+ printf("rwtouch: %s finger %u at %.3f %.3f\n", t.type == REDWOOD_TOUCH_DOWN ? "down" :
+ t.type == REDWOOD_TOUCH_MOVE ? "move" : "up ", t.finger, t.x / 65535.0, t.y / 65535.0);
+ }
+ return 0;
+ } else {
+ fprintf(stderr, "rwtouch: bad step \"%s\"\n", step);
+ return 2;
+ }
+ usleep(50000);
+ }
+ return 0;
+}
diff --git a/userland/src/stage0.c b/userland/src/stage0.c
new file mode 100644
index 0000000..c4bf4f8
--- /dev/null
+++ b/userland/src/stage0.c
@@ -0,0 +1,39 @@
+/*
+ * /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
+ * 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,
+ * /dev/md1). This program mounts it on /redwood and hands over.
+ */
+#include "mini.h"
+
+struct device_mount_args {
+ const char *fspec;
+};
+
+int
+main(int argc, char **argv, char **envp)
+{
+ struct device_mount_args args = { .fspec = "/dev/md1" };
+ char *init_argv[] = { "/redwood/sbin/init", NULL };
+ int fd = open("/dev/console", O_RDWR, 0);
+
+ (void)argc, (void)argv;
+ dup2(fd, 0);
+ dup2(fd, 1);
+ dup2(fd, 2);
+ if (fd > 2) {
+ close(fd);
+ }
+
+ if (mount("packfs", "/redwood", MNT_RDONLY, &args) != 0) {
+ printf("stage0: cannot mount /dev/md1 on /redwood: %s\n", strerror(errno));
+ } else {
+ execve(init_argv[0], init_argv, envp);
+ printf("stage0: cannot run %s: %s\n", init_argv[0], strerror(errno));
+ }
+ reboot(0x08 /* RB_HALT */);
+ return 1;
+}
diff --git a/userland/src/surf_test.c b/userland/src/surf_test.c
new file mode 100644
index 0000000..df32a8b
--- /dev/null
+++ b/userland/src/surf_test.c
@@ -0,0 +1,214 @@
+/*
+ * surf_test: exercises the kernel's IOSurface stand-in through the real IOSurface.framework.
+ *
+ * surf_test the tests; starts itself again as a second process for the sharing part
+ * surf_test child ID (internal) look surface ID up, check the pattern, change one pixel
+ */
+#include <CoreFoundation/CoreFoundation.h>
+#include <IOSurface/IOSurfaceRef.h>
+#include <mach/mach.h>
+#include <spawn.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+extern char **environ;
+
+static int failed, checks;
+
+#define CHECK(cond, ...) do { \
+ checks++; \
+ if (!(cond)) { failed++; printf("surf_test: FAILED: " __VA_ARGS__); printf("\n"); } \
+ } while (0)
+
+static CFNumberRef
+num(int value)
+{
+ return CFNumberCreate(NULL, kCFNumberIntType, &value);
+}
+
+static IOSurfaceRef
+make_surface(int width, int height, uint32_t format, int bytes_per_element)
+{
+ CFMutableDictionaryRef props = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks);
+ CFNumberRef n;
+ IOSurfaceRef surface;
+
+ n = num(width); CFDictionarySetValue(props, kIOSurfaceWidth, n); CFRelease(n);
+ n = num(height); CFDictionarySetValue(props, kIOSurfaceHeight, n); CFRelease(n);
+ n = num((int) format); CFDictionarySetValue(props, kIOSurfacePixelFormat, n); CFRelease(n);
+ if (bytes_per_element) {
+ n = num(bytes_per_element); CFDictionarySetValue(props, kIOSurfaceBytesPerElement, n); CFRelease(n);
+ }
+ surface = IOSurfaceCreate(props);
+ CFRelease(props);
+ return surface;
+}
+
+static uint32_t
+pattern(int x, int y)
+{
+ return 0xff000000u | (uint32_t) (x * 7 + y * 13) << 8 | (uint32_t) ((x ^ y) & 0xff);
+}
+
+static int
+child(uint32_t sid)
+{
+ IOSurfaceRef surface = IOSurfaceLookup(sid);
+ uint32_t *row;
+ int bad = 0;
+
+ if (surface == NULL) {
+ printf("surf_test: child: no surface %u\n", sid);
+ return 2;
+ }
+ IOSurfaceLock(surface, 0, NULL);
+ for (int y = 0; y < (int) IOSurfaceGetHeight(surface); y++) {
+ row = (uint32_t *) ((char *) IOSurfaceGetBaseAddress(surface) + y * IOSurfaceGetBytesPerRow(surface));
+ for (int x = 0; x < (int) IOSurfaceGetWidth(surface); x++) {
+ bad += row[x] != pattern(x, y);
+ }
+ }
+ row = (uint32_t *) IOSurfaceGetBaseAddress(surface);
+ row[3] = 0x12345678;
+ IOSurfaceUnlock(surface, 0, NULL);
+ CFRelease(surface);
+ printf("surf_test: child: surface %u, %d wrong pixels\n", sid, bad);
+ return bad ? 3 : 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ IOSurfaceRef surface, again, yuv;
+ uint32_t sid, seed, *row;
+ mach_port_t port;
+ CFStringRef text;
+ CFTypeRef value;
+
+ if (argc == 3 && strcmp(argv[1], "child") == 0) {
+ return child((uint32_t) atoi(argv[2]));
+ }
+
+ surface = make_surface(64, 48, 'BGRA', 4);
+ CHECK(surface != NULL, "IOSurfaceCreate");
+ if (surface == NULL) {
+ printf("surf_test: no IOSurface service, giving up\n");
+ return 1;
+ }
+ sid = IOSurfaceGetID(surface);
+ printf("surf_test: surface %u: %zux%zu, %zu bytes per row, %zu bytes, base %p\n", sid, IOSurfaceGetWidth(surface),
+ IOSurfaceGetHeight(surface), IOSurfaceGetBytesPerRow(surface), IOSurfaceGetAllocSize(surface),
+ IOSurfaceGetBaseAddress(surface));
+ CHECK(sid != 0, "surface number");
+ CHECK(IOSurfaceGetWidth(surface) == 64 && IOSurfaceGetHeight(surface) == 48, "size");
+ CHECK(IOSurfaceGetBytesPerRow(surface) >= 256, "bytes per row");
+ CHECK(IOSurfaceGetAllocSize(surface) >= 48 * 256, "alloc size");
+ CHECK(IOSurfaceGetPixelFormat(surface) == 'BGRA', "pixel format");
+ CHECK(IOSurfaceGetBytesPerElement(surface) == 4, "bytes per element");
+ CHECK(IOSurfaceGetBaseAddress(surface) != NULL, "base address");
+
+ seed = IOSurfaceGetSeed(surface);
+ CHECK(IOSurfaceLock(surface, 0, NULL) == KERN_SUCCESS, "lock");
+ for (int y = 0; y < 48; y++) {
+ row = (uint32_t *) ((char *) IOSurfaceGetBaseAddress(surface) + y * IOSurfaceGetBytesPerRow(surface));
+ CHECK(row[0] == 0 && row[63] == 0, "new surface not zeroed, row %d", y);
+ for (int x = 0; x < 64; x++) {
+ row[x] = pattern(x, y);
+ }
+ }
+ CHECK(IOSurfaceUnlock(surface, 0, NULL) == KERN_SUCCESS, "unlock");
+ CHECK(IOSurfaceGetSeed(surface) != seed, "seed did not change after writing (%u)", seed);
+ seed = IOSurfaceGetSeed(surface);
+ IOSurfaceLock(surface, kIOSurfaceLockReadOnly, NULL);
+ IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, NULL);
+ CHECK(IOSurfaceGetSeed(surface) == seed, "seed changed after a read-only lock");
+
+ /* values */
+ text = CFSTR("a value");
+ IOSurfaceSetValue(surface, CFSTR("redwood.test"), text);
+ value = IOSurfaceCopyValue(surface, CFSTR("redwood.test"));
+ CHECK(value != NULL && CFEqual(value, text), "value did not come back");
+ if (value) {
+ CFRelease(value);
+ }
+ value = num(42);
+ IOSurfaceSetValue(surface, CFSTR("redwood.number"), value);
+ CFRelease(value);
+ value = IOSurfaceCopyAllValues(surface);
+ CHECK(value != NULL && CFGetTypeID(value) == CFDictionaryGetTypeID() && CFDictionaryGetCount(value) >= 2,
+ "all values");
+ if (value) {
+ CFRelease(value);
+ }
+ IOSurfaceRemoveValue(surface, CFSTR("redwood.test"));
+ value = IOSurfaceCopyValue(surface, CFSTR("redwood.test"));
+ CHECK(value == NULL, "value still there after removing it");
+ value = IOSurfaceCopyValue(surface, CFSTR("redwood.number"));
+ CHECK(value != NULL, "the other value is gone");
+ if (value) {
+ CFRelease(value);
+ }
+
+ /* use count */
+ CHECK(!IOSurfaceIsInUse(surface), "in use from the start");
+ IOSurfaceIncrementUseCount(surface);
+ CHECK(IOSurfaceIsInUse(surface), "not in use after increment");
+ IOSurfaceDecrementUseCount(surface);
+ CHECK(!IOSurfaceIsInUse(surface), "in use after decrement");
+
+ /* the same surface through a Mach port and by number */
+ port = IOSurfaceCreateMachPort(surface);
+ CHECK(port != MACH_PORT_NULL, "IOSurfaceCreateMachPort");
+ again = IOSurfaceLookupFromMachPort(port);
+ CHECK(again != NULL && IOSurfaceGetID(again) == sid, "lookup from the Mach port");
+ if (again) {
+ CHECK(IOSurfaceGetBaseAddress(again) == IOSurfaceGetBaseAddress(surface), "second view of the same surface");
+ CFRelease(again);
+ }
+ mach_port_deallocate(mach_task_self(), port);
+ again = IOSurfaceLookup(sid);
+ CHECK(again != NULL && IOSurfaceGetID(again) == sid, "lookup by number");
+ if (again) {
+ CFRelease(again);
+ }
+ CHECK(IOSurfaceLookup(sid + 1000) == NULL, "found a surface that does not exist");
+
+ /* another process */
+ {
+ char number[16];
+ char *args[] = { argv[0], "child", number, NULL };
+ pid_t pid;
+ int status = -1;
+
+ snprintf(number, sizeof(number), "%u", sid);
+ seed = IOSurfaceGetSeed(surface);
+ if (posix_spawn(&pid, argv[0], NULL, NULL, args, environ) == 0) {
+ waitpid(pid, &status, 0);
+ }
+ CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 0, "second process: status 0x%x", status);
+ row = (uint32_t *) IOSurfaceGetBaseAddress(surface);
+ CHECK(row[3] == 0x12345678, "the pixel written by the second process: 0x%x", row[3]);
+ CHECK(IOSurfaceGetSeed(surface) != seed, "seed did not change after the second process wrote");
+ }
+ CFRelease(surface);
+ CHECK(IOSurfaceLookup(sid) == NULL, "surface still exists after the last release");
+
+ /* two planes */
+ yuv = make_surface(100, 50, '420v', 0);
+ CHECK(yuv != NULL, "IOSurfaceCreate 420v");
+ if (yuv) {
+ CHECK(IOSurfaceGetPlaneCount(yuv) == 2, "plane count %zu", IOSurfaceGetPlaneCount(yuv));
+ CHECK(IOSurfaceGetWidthOfPlane(yuv, 1) == 50 && IOSurfaceGetHeightOfPlane(yuv, 1) == 25, "chroma plane %zux%zu",
+ IOSurfaceGetWidthOfPlane(yuv, 1), IOSurfaceGetHeightOfPlane(yuv, 1));
+ CHECK((char *) IOSurfaceGetBaseAddressOfPlane(yuv, 1) >= (char *) IOSurfaceGetBaseAddressOfPlane(yuv, 0) +
+ 50 * IOSurfaceGetBytesPerRowOfPlane(yuv, 0), "planes overlap");
+ CFRelease(yuv);
+ }
+
+ printf("surf_test: %d checks, %d failed\n", checks, failed);
+ return failed != 0;
+}
diff --git a/userland/src/svc_test.c b/userland/src/svc_test.c
new file mode 100644
index 0000000..8ec6dea
--- /dev/null
+++ b/userland/src/svc_test.c
@@ -0,0 +1,74 @@
+/*
+ * A client of the first real iOS services: each call below is answered by a
+ * daemon that launchd starts on demand.
+ * notifyd - Darwin notifications (libnotify)
+ * cfprefsd - preferences (CoreFoundation)
+ * logd - unified logging (os_log)
+ */
+#include <CoreFoundation/CoreFoundation.h>
+#include <notify.h>
+#include <os/log.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+static int failures;
+
+static void
+check(int ok, const char *what)
+{
+ failures += !ok;
+ printf("[%s] %s\n", ok ? " ok " : "FAIL", what);
+ fflush(stdout);
+}
+
+int
+main(void)
+{
+ int token = -1, changed = 0;
+ uint32_t status;
+ uint64_t state = 0;
+
+ setvbuf(stdout, NULL, _IONBF, 0);
+ printf("svc_test: pid %d, uid %d\n", getpid(), getuid());
+
+ /* notifyd */
+ status = notify_register_check("com.redwood.test", &token);
+ check(status == NOTIFY_STATUS_OK, "notifyd: register for a notification");
+ if (status == NOTIFY_STATUS_OK) {
+ notify_check(token, &changed); /* the first check always reports a change */
+ status = notify_set_state(token, 0x1234abcd);
+ check(status == NOTIFY_STATUS_OK && notify_get_state(token, &state) == NOTIFY_STATUS_OK && state == 0x1234abcd,
+ "notifyd: store and fetch a state value");
+ changed = 0;
+ status = notify_post("com.redwood.test");
+ usleep(100000);
+ check(status == NOTIFY_STATUS_OK && notify_check(token, &changed) == NOTIFY_STATUS_OK && changed,
+ "notifyd: post a notification and see it arrive");
+ } else {
+ printf(" status %u\n", status);
+ }
+
+ /* cfprefsd */
+ {
+ CFStringRef app = CFSTR("com.redwood.test"), key = CFSTR("greeting");
+ CFStringRef value;
+ char text[64] = "";
+
+ CFPreferencesSetAppValue(key, CFSTR("hello from preferences"), app);
+ check(CFPreferencesAppSynchronize(app), "cfprefsd: write a preference");
+ value = CFPreferencesCopyAppValue(key, app);
+ if (value != NULL && CFGetTypeID(value) == CFStringGetTypeID()) {
+ CFStringGetCString(value, text, sizeof(text), kCFStringEncodingUTF8);
+ }
+ printf(" greeting = \"%s\"\n", text);
+ check(strcmp(text, "hello from preferences") == 0, "cfprefsd: read it back");
+ }
+
+ /* logd */
+ os_log(OS_LOG_DEFAULT, "svc_test says hello to the unified log (pid %d)", getpid());
+ check(1, "logd: os_log does not crash");
+
+ printf("svc_test: %d failed\n", failures);
+ return failures;
+}
diff --git a/userland/var/mobile/Library/Preferences/com.apple.coremedia.plist b/userland/var/mobile/Library/Preferences/com.apple.coremedia.plist
new file mode 100644
index 0000000..7d397b0
--- /dev/null
+++ b/userland/var/mobile/Library/Preferences/com.apple.coremedia.plist
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- MediaToolbox gives the window server this many "wireless" (AirPlay) displays; there is nobody to serve them here -->
+ <key>wirelessdisplay_max_count</key>
+ <integer>0</integer>
+</dict>
+</plist>
diff --git a/userland/var/mobile/Library/Preferences/com.apple.frontboard.plist b/userland/var/mobile/Library/Preferences/com.apple.frontboard.plist
new file mode 100644
index 0000000..fbfa4b6
--- /dev/null
+++ b/userland/var/mobile/Library/Preferences/com.apple.frontboard.plist
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- one processor core and a software renderer: applications need more time to come up than the
+ watchdog gives them on Apple's hardware (20 s for the first frame) -->
+ <key>FBLaunchWatchdogScale</key>
+ <real>20</real>
+</dict>
+</plist>
diff --git a/userland/var/mobile/Library/Preferences/com.apple.migration.plist b/userland/var/mobile/Library/Preferences/com.apple.migration.plist
new file mode 100644
index 0000000..0a3f423
--- /dev/null
+++ b/userland/var/mobile/Library/Preferences/com.apple.migration.plist
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- /private/var starts empty on every boot; without this record of the build that last ran the
+ data migration, backboardd runs all the migrators (the progress bar under the logo) each time -->
+ <key>LastSystemVersion</key>
+ <string>20F66</string>
+ <key>DMLastMigrationResults</key>
+ <dict>
+ <key>success</key>
+ <true/>
+ <key>buildVersion</key>
+ <string>20F66</string>
+ </dict>
+</dict>
+</plist>
diff --git a/userland/var/mobile/Library/Preferences/com.apple.purplebuddy.plist b/userland/var/mobile/Library/Preferences/com.apple.purplebuddy.plist
new file mode 100644
index 0000000..a8908e4
--- /dev/null
+++ b/userland/var/mobile/Library/Preferences/com.apple.purplebuddy.plist
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!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-boot setup assistant ("hello") has been gone through; nobody can do that here -->
+ <key>SetupDone</key>
+ <true/>
+ <key>SetupVersion</key>
+ <integer>11</integer>
+ <key>SetupState</key>
+ <string>SetupUsingAssistant</string>
+ <key>ForceNoBuddy</key>
+ <true/>
+</dict>
+</plist>
diff --git a/userland/var/mobile/Library/Preferences/com.apple.springboard.plist b/userland/var/mobile/Library/Preferences/com.apple.springboard.plist
new file mode 100644
index 0000000..fbfa4b6
--- /dev/null
+++ b/userland/var/mobile/Library/Preferences/com.apple.springboard.plist
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- one processor core and a software renderer: applications need more time to come up than the
+ watchdog gives them on Apple's hardware (20 s for the first frame) -->
+ <key>FBLaunchWatchdogScale</key>
+ <real>20</real>
+</dict>
+</plist>
diff --git a/xl b/xl
new file mode 100755
index 0000000..b17206c
--- /dev/null
+++ b/xl
@@ -0,0 +1,177 @@
+#!/bin/bash
+# xl — drive the XNU loader on the phone over USB (fastboot protocol).
+#
+# xl enter get the phone into the resident loader (from Android or stock fastboot)
+# xl run [N] upload the current kernel, run it (optionally stop at checkpoint N), fetch the log
+# xl ramdisk [FILE] upload the big system image (default userland/system.packfs) once; it stays in
+# the phone's RAM across kernel runs and is the root filesystem (/dev/md0)
+# ("xl ramdisk none" forgets it; the image sent with the kernel is then the root)
+# xl screenshot [F] save what is in the phone's framebuffer as a PNG (default logs/screen.png)
+# 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 selftest exercise only the kernel->loader return path
+# xl log fetch the loader's current log
+# xl hang watchdog test: make the loader hang on purpose
+# xl reboot cold-reset the phone (back to Android)
+# xl reload restart the phone into a freshly built loader (after changing xnuloader/)
+# xl memmap the phone's memory map as its firmware reports it
+# xl state where is the phone right now
+#
+# Logs land in logs/. Environment for `run`:
+# XL_CMDLINE extra kernel boot-args; default "-v": the boot is shown as text on the phone's screen
+# (XL_CMDLINE="" for a blank screen, XL_CMDLINE="-v systrace=1" to trace failing syscalls)
+# XL_SECS seconds after which the kernel returns to the loader on its own (default 8)
+# XL_SB_DELAY seconds SpringBoard waits before it starts (default 8; see userland/src/inject_sb.c)
+# Among XL_CMDLINE, for the phone: bootcpu=7 runs the kernel on the biggest core instead of
+# the small one the firmware starts on (the loader then watches from the first core, and a
+# kernel that hangs still gets its log out); cpufreq=1 sets that core to its top speed;
+# touchscreen=1 turns the touch screen on.
+# XL_RAMDISK the image sent with the kernel: the small one that is mounted on /redwood
+# (default userland/root.packfs; "none" sends none). Without a system image in the
+# phone's RAM it is the root itself (e.g. XL_RAMDISK=userland/hello).
+cd "$(dirname "$(readlink -f "$0")")" || exit 1
+# the kernel and the loader built here, or else the ones that come with the repository
+K=xnu-src/xnu-8796.121.2/BUILD/obj/DEVELOPMENT_ARM64_BCM2837/mach.development.bcm2837
+[ -f $K ] || K=prebuilt/mach.development.bcm2837
+L=xnuloader/loader.efi
+[ -f $L ] || L=prebuilt/loader.efi
+mkdir -p logs
+
+fb() { timeout "${FB_TIMEOUT:-10}" fastboot "$@" 2>&1; }
+in_fastboot() { fastboot devices 2>/dev/null | grep -q fastboot; }
+is_loader() { in_fastboot && fb getvar product | grep -q 'product: xnuloader'; }
+state() {
+ if is_loader; then echo loader
+ elif in_fastboot; then echo fastboot
+ elif [ "$(adb get-state 2>/dev/null)" = device ]; then echo android
+ else echo absent; fi
+}
+wait_for() { # wait_for <state> <seconds>
+ local i
+ for ((i = 0; i < $2; i += 2)); do [ "$(state)" = "$1" ] && return 0; sleep 2; done
+ return 1
+}
+
+enter() {
+ case "$(state)" in
+ loader) return 0 ;;
+ android) adb reboot bootloader; wait_for fastboot 60 || { echo "xl: phone did not reach fastboot"; return 1; } ;;
+ fastboot) ;;
+ absent) echo "xl: waiting for the phone (Android or fastboot)..."
+ local i; for ((i = 0; i < 180; i += 3)); do [ "$(state)" != absent ] && break; sleep 3; done
+ [ "$(state)" = absent ] && { echo "xl: phone not reachable"; return 1; }
+ enter; return ;;
+ esac
+ xnuloader/mkpayload.py -o usb-payload.bin loader.efi=$L --usb >/dev/null &&
+ ./mkxnuimg.py -p usb-payload.bin -o xnu-usb.img >/dev/null || { echo "xl: image build failed"; return 1; }
+ # Right after the phone enters fastboot the first "boot" is sometimes not taken: try twice.
+ local try
+ for try in 1 2; do
+ FB_TIMEOUT=40 fb boot xnu-usb.img | grep -q OKAY || { sleep 3; continue; }
+ sleep 6
+ wait_for loader 30 && return 0
+ [ "$(state)" = fastboot ] || break
+ done
+ echo "xl: loader did not come up on USB (state: $(state))"; return 1
+}
+
+fetch_log() { # fetch_log <file>
+ rm -f "$1"
+ FB_TIMEOUT=20 fb get_staged "$1" >/dev/null
+ [ -s "$1" ] && tr -d '\0' < "$1" > "$1.tmp" && mv "$1.tmp" "$1"
+}
+
+run() { # run <oem command> <label>
+ enter || return 1
+ local stamp log result
+ stamp=$(date +%H%M%S); log="logs/$stamp-$2.log"
+ if [ "$1" != "oem selftest" ]; then
+ # The kernel hands control back after XL_SECS seconds even if it is just waiting.
+ local rd=${XL_RAMDISK:-userland/root.packfs}
+ case "$rd" in
+ none|resident) rd= ;;
+ *) [ -f "$rd" ] || { echo "xl: ramdisk $rd not found"; return 1; } ;;
+ esac
+ case $K in prebuilt/*) echo "xl: no kernel built here, running $K" >&2 ;; esac
+ xnuloader/mkpayload.py -o run-payload.bin kernel=$K ${rd:+ramdisk=$rd} --cmdline "loader_return_after=${XL_SECS:-8} epoch=$(date +%s) sb_delay=${XL_SB_DELAY:-8} ${XL_CMDLINE--v}" >/dev/null || return 1
+ FB_TIMEOUT=30 fb stage run-payload.bin | grep -q OKAY || { echo "xl: upload failed"; return 1; }
+ fi
+ fb $1 >/dev/null
+ result=$(FB_TIMEOUT=$(( ${XL_SECS:-8} + 100 )) fb getvar result | grep '^result:')
+ if [ -z "$result" ]; then
+ echo "xl: no answer — the kernel hung; waiting for the watchdog to reset the phone"
+ wait_for android 120 && echo "xl: phone is back in Android" || echo "xl: phone did not come back (state: $(state))"
+ return 2
+ fi
+ fetch_log "$log"
+ ln -sf "$(basename "$log")" logs/last.log
+ echo "$result [$log]"
+ case "$result" in
+ *hung*|*no-such-core*)
+ # (bootcpu=N) the kernel is stuck on the core it was given and nothing can take the core back
+ echo "xl: the kernel did not come back from its core; restarting the phone"
+ fb reboot >/dev/null
+ return 2 ;;
+ esac
+}
+
+recording() { # recording [file.mp4]
+ enter || return 1
+ local out=${1:-logs/recording.mp4}
+ fb oem recording | grep -q OKAY || { echo "xl: the last run left no recording (boot-arg rec_secs=N)"; return 1; }
+ FB_TIMEOUT=120 fb get_staged logs/recording.raw >/dev/null
+ tools/recording.py logs/recording.raw "$out" && rm -f logs/recording.raw
+}
+
+ramdisk() { # ramdisk [<file>|none]
+ enter || return 1
+ if [ "$1" = none ]; then fb oem ramdisk none >/dev/null; echo "xl: resident ramdisk dropped"; return; fi
+ set -- "${1:-userland/system.packfs}"
+ [ -f "$1" ] || { echo "xl: $1 not found"; return 1; }
+ local t0=$(date +%s) size=$(stat -c %s "$1")
+ fb oem ramdisk | grep -q OKAY || { echo "xl: the loader refused (no memory window?)"; return 1; }
+ FB_TIMEOUT=1800 fb stage "$1" | grep -q OKAY || { echo "xl: upload failed"; return 1; }
+ local dt=$(( $(date +%s) - t0 )); [ $dt -lt 1 ] && dt=1
+ echo "xl: $(( size / 1048576 )) MB uploaded in $dt s ($(( size / 1048576 / dt )) MB/s)"
+}
+
+screenshot() { # screenshot [file.png]
+ enter || return 1
+ local out=${1:-logs/screen.png} geom
+ geom=$(fb getvar screen | sed -n 's/^screen: //p')
+ [ -n "$geom" ] && fb oem screenshot | grep -q OKAY || { echo "xl: the loader has no display"; return 1; }
+ FB_TIMEOUT=60 fb get_staged logs/screen.raw >/dev/null
+ python3 - logs/screen.raw "$out" $geom <<'PY' && rm -f logs/screen.raw && echo "xl: $out ($geom)"
+import struct, sys, zlib
+raw, out, width, height, stride = sys.argv[1], sys.argv[2], *map(int, sys.argv[3:6])
+data = open(raw, 'rb').read()
+rows = bytearray()
+for y in range(height):
+ line = data[y * stride:y * stride + width * 4]
+ rows.append(0) # PNG filter type: none
+ rgb = bytearray(width * 3)
+ rgb[0::3], rgb[1::3], rgb[2::3] = line[2::4], line[1::4], line[0::4] # the panel is BGRX
+ rows += rgb
+def chunk(kind, body):
+ return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body))
+with open(out, 'wb') as f:
+ f.write(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)) +
+ chunk(b'IDAT', zlib.compress(bytes(rows), 6)) + chunk(b'IEND', b''))
+PY
+}
+
+case "$1" in
+enter) enter && echo "xl: loader is up" ;;
+screenshot) screenshot "$2" ;;
+recording) recording "$2" ;;
+ramdisk) ramdisk "$2" ;;
+run) run "oem run $2" "run${2:+-cp$2}" ;;
+selftest) run "oem selftest" selftest ;;
+log) enter && fb oem log >/dev/null && fetch_log logs/loader.log && cat logs/loader.log ;;
+memmap) enter && fb oem memmap >/dev/null && fb oem log >/dev/null && fetch_log logs/loader.log && sed -n '/^memory map/,$p' logs/loader.log ;;
+hang) enter && fb oem hang; echo "xl: waiting for the watchdog..."; t0=$(date +%s); wait_for android 150 && echo "xl: back in Android after $(( $(date +%s) - t0 )) s" || echo "xl: not back (state: $(state))" ;;
+reboot) fb reboot; ;;
+reload) [ "$(state)" = loader ] && { fb reboot >/dev/null; wait_for android 120; }; enter && echo "xl: loader is up" ;;
+state) state ;;
+*) sed -n '2,23p' "$0" ;;
+esac
diff --git a/xnu-build.sh b/xnu-build.sh
new file mode 100755
index 0000000..d32226c
--- /dev/null
+++ b/xnu-build.sh
@@ -0,0 +1,7 @@
+#!/bin/bash
+# Build XNU for redwood on Linux. Extra make args are passed through.
+source "$(dirname "${BASH_SOURCE[0]}")/xnu-env.sh"
+cd "$XNU_SRC" || exit 1
+exec make SDKROOT=iphoneos ARCH_CONFIGS=ARM64 MACHINE_CONFIGS=${MACHINE:-BCM2837} KERNEL_CONFIGS=DEVELOPMENT \
+ ARCH_STRING_FOR_CURRENT_MACHINE_CONFIG=arm64 BUILD_WERROR=0 BUILD_LTO=0 DO_CTFMERGE=0 \
+ HOST_CC="clang -include $XNUDEPS/hostinc/hostcompat.h -I$XNUDEPS/hostinc -Wno-unused-command-line-argument -Wno-error=implicit-function-declaration" HOST_FLEX=flex HOST_BISON=bison HOST_GM4=m4 CC=xnu-clang CXX=xnu-clang++ LOGCOLORS=n "$@"
diff --git a/xnu-deps/build/lzbitmap/compress.c b/xnu-deps/build/lzbitmap/compress.c
new file mode 100644
index 0000000..2e05e7a
--- /dev/null
+++ b/xnu-deps/build/lzbitmap/compress.c
@@ -0,0 +1,478 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2020 Corellium LLC
+ */
+
+#include <linux/slab.h>
+#include <linux/zlib.h>
+#include <linux/mutex.h>
+
+#include "apfs.h"
+#include "libzbitmap.h"
+#include "lzfse/lzfse.h"
+#include "lzfse/lzvn_decode_base.h"
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 12, 0)
+
+#include <linux/vmalloc.h>
+
+static inline void *kvmalloc(size_t size, gfp_t flags)
+{
+ gfp_t kmalloc_flags = flags;
+ void *ret;
+
+ if ((flags & GFP_KERNEL) != GFP_KERNEL)
+ return kmalloc(size, flags);
+
+ if (size > PAGE_SIZE)
+ kmalloc_flags |= __GFP_NOWARN | __GFP_NORETRY;
+
+ ret = kmalloc(size, flags);
+ if (ret || size < PAGE_SIZE)
+ return ret;
+
+ return vmalloc(size);
+}
+
+#endif /* LINUX_VERSION_CODE < KERNEL_VERSION(4, 12, 0) */
+
+struct apfs_compress_file_data {
+ struct apfs_compress_hdr hdr;
+ u8 *buf;
+ ssize_t bufblk;
+ size_t bufsize;
+ struct mutex mtx;
+ struct super_block *sb;
+ struct apfs_compressed_data cdata;
+};
+
+static inline int apfs_compress_is_rsrc(u32 algo)
+{
+ return (algo & 1) == 0;
+}
+
+static inline bool apfs_compress_is_supported(u32 algo)
+{
+ switch (algo) {
+ case APFS_COMPRESS_ZLIB_RSRC:
+ case APFS_COMPRESS_ZLIB_ATTR:
+ case APFS_COMPRESS_LZVN_RSRC:
+ case APFS_COMPRESS_LZVN_ATTR:
+ case APFS_COMPRESS_PLAIN_RSRC:
+ case APFS_COMPRESS_PLAIN_ATTR:
+ case APFS_COMPRESS_LZFSE_RSRC:
+ case APFS_COMPRESS_LZFSE_ATTR:
+ case APFS_COMPRESS_LZBITMAP_RSRC:
+ case APFS_COMPRESS_LZBITMAP_ATTR:
+ return true;
+ default:
+ /* Once will usually be enough, don't flood the console */
+ pr_err_once("APFS: unsupported compression algorithm (%u)\n", algo);
+ return false;
+ }
+}
+
+static int apfs_compress_file_open(struct inode *inode, struct file *filp)
+{
+ struct super_block *sb = inode->i_sb;
+ struct apfs_nxsb_info *nxi = APFS_NXI(sb);
+ struct apfs_compress_file_data *fd;
+ ssize_t res;
+ bool is_rsrc;
+
+ /*
+ * The official implementation seems to transparently decompress files
+ * when you write to them. Doing that atomically inside the kernel is
+ * probably a chore, so for now I'll just leave it to the user to make
+ * an uncompressed copy themselves and replace the original. I might
+ * fix this in the future, but only if people complain (TODO).
+ */
+ if (filp->f_mode & FMODE_WRITE) {
+ apfs_warn(sb, "writes to compressed files are not supported");
+ apfs_warn(sb, "you can work with a copy of the file instead");
+ return -EOPNOTSUPP;
+ }
+
+ if (!(filp->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS)
+ return -EOVERFLOW;
+
+ fd = kzalloc(sizeof(*fd), GFP_KERNEL);
+ if (!fd)
+ return -ENOMEM;
+ mutex_init(&fd->mtx);
+ fd->sb = sb;
+
+ down_read(&nxi->nx_big_sem);
+
+ res = ____apfs_xattr_get(inode, APFS_XATTR_NAME_COMPRESSED, &fd->hdr, sizeof(fd->hdr), 0);
+ if (res != sizeof(fd->hdr)) {
+ apfs_err(sb, "decmpfs header read failed");
+ goto fail;
+ }
+
+ if (!apfs_compress_is_supported(le32_to_cpu(fd->hdr.algo))) {
+ res = -EOPNOTSUPP;
+ goto fail;
+ }
+
+ fd->buf = kvmalloc(APFS_COMPRESS_BLOCK, GFP_KERNEL);
+ if (!fd->buf) {
+ res = -ENOMEM;
+ goto fail;
+ }
+ fd->bufblk = -1;
+
+ is_rsrc = apfs_compress_is_rsrc(le32_to_cpu(fd->hdr.algo));
+ res = apfs_xattr_get_compressed_data(inode, is_rsrc ? APFS_XATTR_NAME_RSRC_FORK : APFS_XATTR_NAME_COMPRESSED, &fd->cdata);
+ if (res) {
+ apfs_err(sb, "failed to get compressed data");
+ goto fail;
+ }
+
+ up_read(&nxi->nx_big_sem);
+
+ filp->private_data = fd;
+ return 0;
+
+fail:
+ apfs_release_compressed_data(&fd->cdata);
+ if (fd->buf)
+ kvfree(fd->buf);
+ up_read(&nxi->nx_big_sem);
+ kfree(fd);
+ if (res > 0)
+ res = -EINVAL;
+ return res;
+}
+
+static int apfs_compress_file_read_block(struct apfs_compress_file_data *fd, loff_t block)
+{
+ struct super_block *sb = fd->sb;
+ struct apfs_compressed_data *comp_data = &fd->cdata;
+ u8 *cdata = NULL;
+ u8 *tmp = fd->buf;
+ u32 doffs = 0, coffs;
+ size_t csize, bsize;
+ int res = 0;
+
+ if (apfs_compress_is_rsrc(le32_to_cpu(fd->hdr.algo)) &&
+ le32_to_cpu(fd->hdr.algo) != APFS_COMPRESS_LZBITMAP_RSRC &&
+ le32_to_cpu(fd->hdr.algo) != APFS_COMPRESS_LZVN_RSRC &&
+ le32_to_cpu(fd->hdr.algo) != APFS_COMPRESS_LZFSE_RSRC) {
+ struct apfs_compress_rsrc_hdr hdr = {0};
+ struct apfs_compress_rsrc_data cd = {0};
+ struct apfs_compress_rsrc_block blk = {0};
+ u32 blk_off;
+
+ res = apfs_compressed_data_read(comp_data, &hdr, sizeof(hdr), 0 /* offset */);
+ if (res) {
+ apfs_err(sb, "failed to read resource header");
+ return res;
+ }
+
+ doffs = be32_to_cpu(hdr.data_offs);
+ res = apfs_compressed_data_read(comp_data, &cd, sizeof(cd), doffs);
+ if (res) {
+ apfs_err(sb, "failed to read resource data header");
+ return res;
+ }
+ if (block >= le32_to_cpu(cd.num))
+ return 0;
+
+ blk_off = doffs + sizeof(cd) + sizeof(blk) * block;
+ res = apfs_compressed_data_read(comp_data, &blk, sizeof(blk), blk_off);
+ if (res) {
+ apfs_err(sb, "failed to read resource block metadata");
+ return res;
+ }
+
+ bsize = le64_to_cpu(fd->hdr.size) - block * APFS_COMPRESS_BLOCK;
+ if (bsize > APFS_COMPRESS_BLOCK)
+ bsize = APFS_COMPRESS_BLOCK;
+
+ csize = le32_to_cpu(blk.size);
+ coffs = le32_to_cpu(blk.offs) + 4;
+ } else if (apfs_compress_is_rsrc(le32_to_cpu(fd->hdr.algo))) {
+ __le32 blks[2];
+ u32 blk_off;
+
+ blk_off = doffs + sizeof(__le32) * block;
+ res = apfs_compressed_data_read(comp_data, blks, sizeof(blks), blk_off);
+ if (res) {
+ apfs_err(sb, "failed to read resource block metadata");
+ return res;
+ }
+
+ bsize = le64_to_cpu(fd->hdr.size) - block * APFS_COMPRESS_BLOCK;
+ if (bsize > APFS_COMPRESS_BLOCK)
+ bsize = APFS_COMPRESS_BLOCK;
+
+ coffs = le32_to_cpu(blks[0]);
+ csize = le32_to_cpu(blks[1]) - coffs;
+ } else {
+ /*
+ * I think attr compression is only for single-block files, in
+ * fact none of these files ever seem to decompress to more than
+ * 2048 bytes.
+ */
+ bsize = le64_to_cpu(fd->hdr.size);
+ if (block != 0 || bsize > APFS_COMPRESS_BLOCK) {
+ apfs_err(sb, "file too big for inline compression");
+ return -EFSCORRUPTED;
+ }
+
+ /* The first few bytes are the decmpfs header */
+ coffs = sizeof(struct apfs_compress_hdr);
+ csize = comp_data->size - sizeof(struct apfs_compress_hdr);
+ }
+
+ cdata = kvmalloc(csize, GFP_KERNEL);
+ if (!cdata)
+ return -ENOMEM;
+ res = apfs_compressed_data_read(comp_data, cdata, csize, doffs + coffs);
+ if (res) {
+ apfs_err(sb, "failed to read compressed block");
+ goto fail;
+ }
+
+ switch (le32_to_cpu(fd->hdr.algo)) {
+ case APFS_COMPRESS_ZLIB_RSRC:
+ case APFS_COMPRESS_ZLIB_ATTR:
+ if (cdata[0] == 0x78 && csize >= 2) {
+ res = zlib_inflate_blob(tmp, bsize, cdata + 2, csize - 2);
+ if (res <= 0) {
+ apfs_err(sb, "zlib decompression failed");
+ goto fail;
+ }
+ bsize = res;
+ res = 0;
+ } else if ((cdata[0] & 0x0F) == 0x0F) {
+ memcpy(tmp, &cdata[1], csize - 1);
+ bsize = csize - 1;
+ } else {
+ apfs_err(sb, "zlib decompression failed");
+ res = -EINVAL;
+ goto fail;
+ }
+ break;
+ case APFS_COMPRESS_LZVN_RSRC:
+ case APFS_COMPRESS_LZVN_ATTR:
+ if (cdata[0] == 0x06) {
+ memcpy(tmp, &cdata[1], csize - 1);
+ bsize = csize - 1;
+ } else {
+ lzvn_decoder_state dstate = {0};
+
+ dstate.src = cdata;
+ dstate.src_end = dstate.src + csize;
+ dstate.dst = dstate.dst_begin = tmp;
+ dstate.dst_end = dstate.dst + bsize;
+ lzvn_decode(&dstate);
+ bsize = dstate.dst - tmp;
+ }
+ break;
+ case APFS_COMPRESS_LZBITMAP_RSRC:
+ case APFS_COMPRESS_LZBITMAP_ATTR:
+ if (cdata[0] == 0x5a) {
+ res = zbm_decompress(tmp, bsize, cdata, csize, &bsize);
+ if (res < 0) {
+ apfs_err(sb, "lzbitmap decompression failed");
+ goto fail;
+ }
+ res = 0;
+ } else if ((cdata[0] & 0x0F) == 0x0F) {
+ memcpy(tmp, &cdata[1], csize - 1);
+ bsize = csize - 1;
+ } else {
+ apfs_err(sb, "lzbitmap decompression failed");
+ res = -EINVAL;
+ goto fail;
+ }
+ break;
+ case APFS_COMPRESS_LZFSE_RSRC:
+ case APFS_COMPRESS_LZFSE_ATTR:
+ if (cdata[0] == 0x62 && csize >= 2) {
+ res = lzfse_decode_buffer(tmp, bsize, cdata, csize, NULL);
+ if (res == 0) {
+ apfs_err(sb, "lzfse decompression failed");
+ /* Could be ENOMEM too... */
+ res = -EINVAL;
+ goto fail;
+ }
+ bsize = res;
+ res = 0;
+ } else {
+ /* cdata[0] == 0xff, apparently */
+ memcpy(tmp, &cdata[1], csize - 1);
+ bsize = csize - 1;
+ }
+ break;
+ case APFS_COMPRESS_PLAIN_RSRC:
+ case APFS_COMPRESS_PLAIN_ATTR:
+ memcpy(tmp, &cdata[1], csize - 1);
+ bsize = csize - 1;
+ break;
+ default:
+ res = -EINVAL;
+ goto fail;
+ }
+ fd->bufblk = block;
+ fd->bufsize = bsize;
+fail:
+ kvfree(cdata);
+ return res;
+}
+
+static int apfs_compress_file_release(struct inode *inode, struct file *filp)
+{
+ struct apfs_compress_file_data *fd = filp->private_data;
+
+ apfs_release_compressed_data(&fd->cdata);
+ if (fd->buf)
+ kvfree(fd->buf);
+ kfree(fd);
+ return 0;
+}
+
+static ssize_t apfs_compress_file_read_from_block(struct apfs_compress_file_data *fd, char *buf, size_t size, loff_t off)
+{
+ struct super_block *sb = fd->sb;
+ struct apfs_nxsb_info *nxi = APFS_NXI(sb);
+ struct apfs_compressed_data cdata = fd->cdata;
+ loff_t block;
+ size_t bsize;
+ ssize_t res;
+
+ /*
+ * Request reads of all blocks before actually working with any of them.
+ * The compressed data is typically small enough that this is effective.
+ * It would be much better to make an inode for the xattr dstream and
+ * work with readahead as usual, but I'm not confident I can get that
+ * right (TODO).
+ */
+ if (cdata.has_dstream && off == 0) {
+ down_read(&nxi->nx_big_sem);
+ apfs_nonsparse_dstream_preread(cdata.dstream);
+ up_read(&nxi->nx_big_sem);
+ }
+
+ if (off >= le64_to_cpu(fd->hdr.size))
+ return 0;
+ if (size > le64_to_cpu(fd->hdr.size) - off)
+ size = le64_to_cpu(fd->hdr.size) - off;
+
+ block = off / APFS_COMPRESS_BLOCK;
+ off -= block * APFS_COMPRESS_BLOCK;
+ if (block != fd->bufblk) {
+ down_read(&nxi->nx_big_sem);
+ res = apfs_compress_file_read_block(fd, block);
+ up_read(&nxi->nx_big_sem);
+ if (res) {
+ apfs_err(sb, "failed to read block into buffer");
+ return res;
+ }
+ }
+ bsize = fd->bufsize;
+
+ if (bsize < off)
+ return 0;
+ bsize -= off;
+ if (size > bsize)
+ size = bsize;
+ memcpy(buf, fd->buf + off, size);
+ return size;
+}
+
+static ssize_t apfs_compress_file_read_page(struct file *filp, char *buf, loff_t off)
+{
+ struct apfs_compress_file_data *fd = filp->private_data;
+ loff_t step;
+ ssize_t block, res;
+ size_t size = PAGE_SIZE;
+
+ step = 0;
+ while (step < size) {
+ block = APFS_COMPRESS_BLOCK - ((off + step) & (APFS_COMPRESS_BLOCK - 1));
+ if (block > size - step)
+ block = size - step;
+ mutex_lock(&fd->mtx);
+ res = apfs_compress_file_read_from_block(fd, buf + step, block, off + step);
+ mutex_unlock(&fd->mtx);
+ if (res < block) {
+ if (res < 0 && !step)
+ return res;
+ step += res > 0 ? res : 0;
+ break;
+ }
+ step += block;
+ }
+ return step;
+}
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 19, 0) || RHEL_VERSION_GE(9, 3)
+static int apfs_compress_read_folio(struct file *filp, struct folio *folio)
+{
+ struct page *page = &folio->page;
+#else
+static int apfs_compress_readpage(struct file *filp, struct page *page)
+{
+#endif
+ char *addr = NULL;
+ ssize_t ret;
+ loff_t off;
+
+ /* Mostly copied from ext4_read_inline_page() */
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 16, 0)
+ off = page_folio(page)->index << PAGE_SHIFT;
+#else
+ off = page->index << PAGE_SHIFT;
+#endif
+ addr = kmap(page);
+ ret = apfs_compress_file_read_page(filp, addr, off);
+ flush_dcache_page(page);
+ kunmap(page);
+ if (ret >= 0) {
+ zero_user_segment(page, ret, PAGE_SIZE);
+ SetPageUptodate(page);
+ ret = 0;
+ }
+
+ unlock_page(page);
+ return ret;
+}
+
+const struct address_space_operations apfs_compress_aops = {
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 19, 0) || RHEL_VERSION_GE(9, 3)
+ .read_folio = apfs_compress_read_folio,
+#else
+ .readpage = apfs_compress_readpage,
+#endif
+};
+
+/* TODO: these operations are all happening without proper locks */
+const struct file_operations apfs_compress_file_operations = {
+ .open = apfs_compress_file_open,
+ .llseek = generic_file_llseek,
+ .read_iter = generic_file_read_iter,
+ .release = apfs_compress_file_release,
+ .mmap = apfs_file_mmap,
+};
+
+int apfs_compress_get_size(struct inode *inode, loff_t *size)
+{
+ struct apfs_compress_hdr hdr;
+ int res = ____apfs_xattr_get(inode, APFS_XATTR_NAME_COMPRESSED, &hdr, sizeof(hdr), 0);
+
+ if (res < 0)
+ return res;
+ if (res != sizeof(hdr)) {
+ apfs_err(inode->i_sb, "decmpfs header read failed");
+ return 1;
+ }
+
+ if (!apfs_compress_is_supported(le32_to_cpu(hdr.algo)))
+ return 1;
+
+ *size = le64_to_cpu(hdr.size);
+ return 0;
+}
diff --git a/xnu-deps/build/lzbitmap/libzbitmap.c b/xnu-deps/build/lzbitmap/libzbitmap.c
new file mode 100644
index 0000000..fca09a5
--- /dev/null
+++ b/xnu-deps/build/lzbitmap/libzbitmap.c
@@ -0,0 +1,442 @@
+// SPDX-License-Identifier: GPL-2.0+ OR MIT
+/*
+ * Copyright (C) 2022 Corellium LLC
+ *
+ * Author: Ernesto A. Fernández <[email protected]>
+ *
+ * Ported from libzbitmap (https://github.com/eafer/libzbitmap). Only the
+ * decompression code is included.
+ */
+
+#include <errno.h>
+#include <string.h>
+#include "libzbitmap.h"
+
+#define ZBM_MAGIC "ZBM\x09"
+#define ZBM_MAGIC_SZ 4
+
+#define ZBM_MAX_DECMP_CHUNK_SIZE 0x8000
+#define ZBM_MAX_DECMP_CHUNK_SIZE_BITS 15
+
+struct uint24 {
+ uint8_t low;
+ uint8_t mid;
+ uint8_t hig;
+};
+
+/* This header is shared by both compressed and decompressed chunks */
+struct zbm_chunk_hdr {
+ struct uint24 len; /* Length of the chunk */
+ struct uint24 decmp_len; /* Length of the chunk after decompression */
+};
+
+/* The full header for compressed chunks */
+struct zbm_cmp_chunk_hdr {
+ /* Shared with decompressed chunks */
+ struct zbm_chunk_hdr hdr;
+
+ /* Offset for each of the three metadata areas */
+ struct uint24 meta_off_1;
+ struct uint24 meta_off_2;
+ struct uint24 meta_off_3;
+};
+
+/* Pointer to a half-byte */
+struct nybl_ptr {
+ uint8_t *addr; /* Address of the byte */
+ int nibble; /* Which of the two nibbles? */
+};
+
+/* 0-2 and 0xf are not real bitmap indexes */
+#define ZBM_BITMAP_COUNT (16 - 1 - 3)
+#define ZBM_BITMAP_BASE 3
+#define ZBM_BITMAP_BYTECNT 17
+#define ZBM_MAX_PERIOD_BYTECNT 2
+
+struct zbm_bmap {
+ uint8_t bitmap; /* The bitmap */
+ uint8_t period_bytecnt; /* Read this many bytes to get the new period */
+};
+
+struct zbm_state {
+ /* Updated during a chunk read */
+ uint8_t *dest; /* Write the next byte here */
+ size_t dest_left; /* Room left in destination buffer */
+ uint32_t written; /* Bytes written so far for current chunk */
+ uint16_t period; /* Repetition period for decompression, in bytes */
+
+ /* Updated right before a chunk read */
+ const uint8_t *src_end; /* End of current chunk */
+ uint32_t len; /* Length of the chunk */
+ uint32_t decmp_len; /* Expected chunk length after decompression */
+
+ /* Updated after a chunk read */
+ const uint8_t *src; /* Start of buffer, or current chunk if any */
+ size_t src_left; /* Room left in the source buffer */
+ size_t prewritten; /* Bytes written for previous chunks */
+
+ /* Current position in data and metadata areas for this chunk */
+ const uint8_t *data;
+ const uint8_t *meta_1;
+ const uint8_t *meta_2;
+ struct nybl_ptr meta_3;
+
+ /* Array of bitmaps for the current chunk */
+ struct zbm_bmap bitmaps[ZBM_BITMAP_COUNT];
+};
+
+static int zbm_check_magic(struct zbm_state *state)
+{
+ if(state->src_left < ZBM_MAGIC_SZ)
+ return -EINVAL;
+
+ if(memcmp(state->src, ZBM_MAGIC, ZBM_MAGIC_SZ))
+ return -EINVAL;
+
+ state->src += ZBM_MAGIC_SZ;
+ state->src_left -= ZBM_MAGIC_SZ;
+ return 0;
+}
+
+static uint32_t zbm_u24_to_u32(struct uint24 n)
+{
+ uint32_t res;
+
+ res = n.hig;
+ res <<= 8;
+ res += n.mid;
+ res <<= 8;
+ res += n.low;
+ return res;
+}
+
+/* Some chunks just have regular uncompressed data, but with a header */
+static int zbm_chunk_is_uncompressed(struct zbm_state *state)
+{
+ return state->len == state->decmp_len + sizeof(struct zbm_chunk_hdr);
+}
+
+static int zbm_handle_uncompressed_chunk(struct zbm_state *state)
+{
+ state->meta_1 = state->meta_2 = NULL;
+ state->meta_3.addr = NULL;
+ state->meta_3.nibble = 0;
+ state->data = state->src + sizeof(struct zbm_chunk_hdr);
+ memcpy(state->dest, state->data, state->decmp_len);
+
+ state->dest += state->decmp_len;
+ state->dest_left -= state->decmp_len;
+ state->written = state->decmp_len;
+ return 0;
+}
+
+static int zbm_read_nibble(struct nybl_ptr *nybl, const uint8_t *limit, uint8_t *result)
+{
+ if(nybl->addr >= limit)
+ return -EINVAL;
+
+ if(nybl->nibble == 0) {
+ *result = *nybl->addr & 0xf;
+ nybl->nibble = 1;
+ } else {
+ *result = (*nybl->addr >> 4) & 0xf;
+ nybl->nibble = 0;
+ ++nybl->addr;
+ }
+ return 0;
+}
+
+static void zbm_rewind_nibble(struct nybl_ptr *nybl)
+{
+ if(nybl->nibble == 0) {
+ nybl->nibble = 1;
+ --nybl->addr;
+ } else {
+ nybl->nibble = 0;
+ }
+}
+
+static int zbm_apply_bitmap(struct zbm_state *state, struct zbm_bmap *bitmap)
+{
+ int i;
+
+ /* The periods are stored in the first metadata area */
+ if(bitmap->period_bytecnt) {
+ state->period = 0;
+ for(i = 0; i < bitmap->period_bytecnt; ++i) {
+ if(state->meta_1 >= state->src_end)
+ return -EINVAL;
+ state->period |= *state->meta_1 << i * 8;
+ ++state->meta_1;
+ }
+ }
+ if(state->period == 0)
+ return -EINVAL;
+
+ for(i = 0; i < 8; ++i) {
+ if(state->written == state->decmp_len)
+ break;
+ if(bitmap->bitmap & 1 << i) {
+ if(state->data >= state->src_end)
+ return -EINVAL;
+ *state->dest = *state->data;
+ ++state->data;
+ } else {
+ if(state->prewritten + state->written < state->period)
+ return -EINVAL;
+ *state->dest = *(state->dest - state->period);
+ }
+ ++state->dest;
+ --state->dest_left;
+ ++state->written;
+ }
+
+ return 0;
+}
+
+static int zbm_apply_bitmap_number(struct zbm_state *state, uint8_t bmp_num)
+{
+ struct zbm_bmap next = {0};
+
+ /* Not a valid bitmap number (it signals a repetition) */
+ if(bmp_num == 0xf)
+ return -EINVAL;
+
+ /* An actual index in the bitmap array */
+ if(bmp_num > ZBM_MAX_PERIOD_BYTECNT)
+ return zbm_apply_bitmap(state, &state->bitmaps[bmp_num - ZBM_BITMAP_BASE]);
+
+ /* For < 2, use the next bitmap in the second metadata area */
+ if(state->meta_2 >= state->src_end)
+ return -EINVAL;
+ next.bitmap = *state->meta_2;
+ next.period_bytecnt = bmp_num;
+ ++state->meta_2;
+ return zbm_apply_bitmap(state, &next);
+}
+
+/* Find out how many times we need to repeat the current bitmap operation */
+static int zbm_read_repetition_count(struct zbm_state *state, uint16_t *repeat)
+{
+ uint8_t nibble;
+ uint16_t total;
+ int err;
+
+ /* Don't confuse the trailing bitmaps with a repetition count */
+ if(state->decmp_len - state->written <= 8) {
+ *repeat = 1;
+ return 0;
+ }
+
+ err = zbm_read_nibble(&state->meta_3, state->src_end, &nibble);
+ if(err)
+ return err;
+
+ if(nibble != 0xf) {
+ /* No repetition count: the previous bitmap number gets applied once */
+ zbm_rewind_nibble(&state->meta_3);
+ *repeat = 1;
+ return 0;
+ }
+
+ /*
+ * Under this scheme, repeating a bitmap number 3 times wouldn't save any
+ * space, so the repetition count starts from 4.
+ */
+ total = 4;
+ while(nibble == 0xf) {
+ err = zbm_read_nibble(&state->meta_3, state->src_end, &nibble);
+ if(err)
+ return err;
+ total += nibble;
+ if(total < nibble)
+ return -EINVAL;
+ }
+
+ *repeat = total;
+ return 0;
+}
+
+static int zbm_decompress_single_bitmap(struct zbm_state *state)
+{
+ uint8_t bmp_num;
+ uint16_t repeat;
+ int i;
+ int err;
+
+ /* The current nibble is the offset of the next bitmap to apply */
+ err = zbm_read_nibble(&state->meta_3, state->src_end, &bmp_num);
+ if(err)
+ return err;
+
+ err = zbm_read_repetition_count(state, &repeat);
+ if(err)
+ return err;
+
+ for(i = 0; i < repeat; ++i) {
+ err = zbm_apply_bitmap_number(state, bmp_num);
+ if(err)
+ return err;
+ }
+ return 0;
+}
+
+/* Pointer to a bit */
+struct bit_ptr {
+ uint8_t *addr; /* Address of the byte */
+ int offset; /* Bit number */
+};
+
+/* This function does not perform boundary checks, the caller must do it */
+static int zbm_read_single_bit(struct bit_ptr *bit)
+{
+ int res = *bit->addr >> bit->offset & 1;
+
+ ++bit->offset;
+ if(bit->offset != 8)
+ return res;
+ bit->offset = 0;
+ ++bit->addr;
+ return res;
+}
+
+static int zbm_read_single_bitmap(struct bit_ptr *bit, const uint8_t *limit, struct zbm_bmap *result)
+{
+ int i;
+
+ result->bitmap = 0;
+ result->period_bytecnt = 0;
+
+ /* The bitmap itself */
+ for(i = 0; i < 8; ++i) {
+ if(bit->addr >= limit)
+ return -EINVAL;
+ result->bitmap |= zbm_read_single_bit(bit) << i;
+ }
+
+ /*
+ * The two trailing bits tell us how many bytes to read for the next
+ * repetition period
+ */
+ for(i = 0; i < 2; ++i) {
+ if(bit->addr >= limit)
+ return -EINVAL;
+ result->period_bytecnt |= zbm_read_single_bit(bit) << i;
+ }
+
+ return 0;
+}
+
+static int zbm_read_bitmaps(struct zbm_state *state)
+{
+ struct bit_ptr bmap = {0};
+ int err, i;
+
+ if(state->len < ZBM_BITMAP_BYTECNT)
+ return -EINVAL;
+
+ bmap.addr = (uint8_t *)state->src_end - ZBM_BITMAP_BYTECNT;
+ bmap.offset = 0;
+
+ for(i = 0; i < ZBM_BITMAP_COUNT; ++i) {
+ err = zbm_read_single_bitmap(&bmap, state->src_end, &state->bitmaps[i]);
+ if(err)
+ return err;
+ if(state->bitmaps[i].period_bytecnt > ZBM_MAX_PERIOD_BYTECNT)
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int zbm_handle_compressed_chunk(struct zbm_state *state)
+{
+ const struct zbm_cmp_chunk_hdr *hdr = NULL;
+ uint32_t meta_off_1, meta_off_2, meta_off_3;
+ int err;
+
+ state->written = 0;
+ state->period = 8;
+
+ if(state->len < sizeof(*hdr))
+ return -EINVAL;
+ hdr = (struct zbm_cmp_chunk_hdr *)state->src;
+ state->data = state->src + sizeof(*hdr);
+
+ meta_off_1 = zbm_u24_to_u32(hdr->meta_off_1);
+ meta_off_2 = zbm_u24_to_u32(hdr->meta_off_2);
+ meta_off_3 = zbm_u24_to_u32(hdr->meta_off_3);
+ if(meta_off_1 >= state->len || meta_off_2 >= state->len || meta_off_3 >= state->len)
+ return -EINVAL;
+ state->meta_1 = state->src + meta_off_1;
+ state->meta_2 = state->src + meta_off_2;
+ state->meta_3.addr = (uint8_t *)state->src + meta_off_3;
+ state->meta_3.nibble = 0;
+
+ err = zbm_read_bitmaps(state);
+ if(err)
+ return err;
+
+ while(state->written < state->decmp_len) {
+ err = zbm_decompress_single_bitmap(state);
+ if(err)
+ return err;
+ }
+
+ return 0;
+}
+
+static int zbm_handle_chunk(struct zbm_state *state)
+{
+ const struct zbm_chunk_hdr *decmp_hdr = NULL;
+
+ if(state->src_left < sizeof(*decmp_hdr))
+ return -EINVAL;
+ decmp_hdr = (struct zbm_chunk_hdr *)state->src;
+
+ state->len = zbm_u24_to_u32(decmp_hdr->len);
+ if(state->len > state->src_left)
+ return -EINVAL;
+ state->src_end = state->src + state->len;
+
+ state->decmp_len = zbm_u24_to_u32(decmp_hdr->decmp_len);
+ if(state->decmp_len > ZBM_MAX_DECMP_CHUNK_SIZE)
+ return -EINVAL;
+ if(!state->dest) /* We just wanted the length, so we are done */
+ return 0;
+ if(state->decmp_len > state->dest_left)
+ return -ERANGE;
+
+ if(zbm_chunk_is_uncompressed(state))
+ return zbm_handle_uncompressed_chunk(state);
+
+ return zbm_handle_compressed_chunk(state);
+}
+
+int zbm_decompress(void *dest, size_t dest_size, const void *src, size_t src_size, size_t *out_len)
+{
+ struct zbm_state state = {0};
+ int err;
+
+ state.src = src;
+ state.src_left = src_size;
+ state.dest = dest;
+ state.dest_left = dest_size;
+ state.prewritten = 0;
+
+ err = zbm_check_magic(&state);
+ if(err)
+ return err;
+
+ /* The final chunk has zero decompressed length */
+ do {
+ err = zbm_handle_chunk(&state);
+ if(err)
+ return err;
+ state.src += state.len;
+ state.src_left -= state.len;
+ state.prewritten += state.decmp_len;
+ } while(state.decmp_len != 0);
+
+ *out_len = state.prewritten;
+ return 0;
+}
diff --git a/xnu-deps/build/lzbitmap/libzbitmap.h b/xnu-deps/build/lzbitmap/libzbitmap.h
new file mode 100644
index 0000000..8ea24bd
--- /dev/null
+++ b/xnu-deps/build/lzbitmap/libzbitmap.h
@@ -0,0 +1,32 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+/*
+ * Copyright (c) 2022 Corellium LLC
+ *
+ * Author: Ernesto A. Fernández <[email protected]>
+ *
+ * Ported from libzbitmap (https://github.com/eafer/libzbitmap). Only the
+ * decompression code is included.
+ */
+
+#ifndef _LIBZBITMAP_H
+#define _LIBZBITMAP_H
+
+#include <errno.h>
+#include <stdint.h>
+#include <stddef.h>
+
+/**
+ * zbm_decompress - Decompress an LZBITMAP buffer
+ * @dest: destination buffer (may be NULL)
+ * @dest_size: size of the destination buffer
+ * @src: source buffer
+ * @src_size: size of the source buffer
+ * @out_len: on return, the length of the decompressed output
+ *
+ * May be called with a NULL destination buffer to retrieve the expected length
+ * of the decompressed data. Returns 0 on success, or a negative error code in
+ * case of failure.
+ */
+int zbm_decompress(void *dest, size_t dest_size, const void *src, size_t src_size, size_t *out_len);
+
+#endif /* _LIBZBITMAP_H */
diff --git a/xnu-deps/build/lzbitmap/unzbm.c b/xnu-deps/build/lzbitmap/unzbm.c
new file mode 100644
index 0000000..f33cf5f
--- /dev/null
+++ b/xnu-deps/build/lzbitmap/unzbm.c
@@ -0,0 +1,113 @@
+/*
+ * unzbm: finish what 7z leaves undone for files compressed with LZBITMAP.
+ *
+ * 7z extracts such a file from an APFS image as an empty file plus its two
+ * attributes, "NAME:com.apple.decmpfs" (the compression header) and
+ * "NAME:com.apple.ResourceFork" (the compressed data, in 64K blocks behind a
+ * table of offsets). For every NAME given, this writes the real contents and
+ * removes the two attribute files.
+ *
+ * The decompressor is libzbitmap (Ernesto A. Fernandez, GPL-2.0+ OR MIT),
+ * as shipped with the linux-apfs-rw driver.
+ */
+#include <errno.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "libzbitmap.h"
+
+#define BLOCK 0x10000u
+#define LZBITMAP_RSRC 14
+
+static uint8_t *
+slurp(const char *path, size_t *size)
+{
+ FILE *f = fopen(path, "rb");
+ uint8_t *data;
+
+ if (!f) {
+ return NULL;
+ }
+ fseek(f, 0, SEEK_END);
+ *size = (size_t)ftell(f);
+ rewind(f);
+ data = malloc(*size + 1);
+ if (fread(data, 1, *size, f) != *size) {
+ free(data);
+ data = NULL;
+ }
+ fclose(f);
+ return data;
+}
+
+static uint32_t
+le32(const uint8_t *p)
+{
+ return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24;
+}
+
+static int
+expand(const char *name)
+{
+ char header_path[4096], fork_path[4096];
+ size_t header_size, fork_size;
+ uint8_t *header, *fork, *out;
+ uint64_t size, blocks;
+ FILE *f;
+
+ snprintf(header_path, sizeof(header_path), "%s:com.apple.decmpfs", name);
+ snprintf(fork_path, sizeof(fork_path), "%s:com.apple.ResourceFork", name);
+ header = slurp(header_path, &header_size);
+ fork = slurp(fork_path, &fork_size);
+ if (!header || !fork || header_size < 16 || memcmp(header, "fpmc", 4) != 0 || le32(header + 4) != LZBITMAP_RSRC) {
+ fprintf(stderr, "unzbm: %s: not an LZBITMAP resource-fork file\n", name);
+ return 1;
+ }
+ size = le32(header + 8) | (uint64_t)le32(header + 12) << 32;
+ blocks = (size + BLOCK - 1) / BLOCK;
+ if ((blocks + 1) * 4 > fork_size) {
+ fprintf(stderr, "unzbm: %s: block table does not fit\n", name);
+ return 1;
+ }
+ out = malloc(size ? size : 1);
+ for (uint64_t b = 0; b < blocks; b++) {
+ uint32_t from = le32(fork + 4 * b), to = le32(fork + 4 * (b + 1));
+ size_t want = size - b * BLOCK > BLOCK ? BLOCK : (size_t)(size - b * BLOCK), got = 0;
+
+ /* a block that did not shrink is stored as it is behind one byte, 0xff */
+ if (from < to && to <= fork_size && to - from == want + 1 && fork[from] == 0xff) {
+ memcpy(out + b * BLOCK, fork + from + 1, want);
+ continue;
+ }
+ if (from > to || to > fork_size || zbm_decompress(out + b * BLOCK, want, fork + from, to - from, &got) != 0 ||
+ got != want) {
+ fprintf(stderr, "unzbm: %s: block %llu does not decompress\n", name, (unsigned long long)b);
+ return 1;
+ }
+ }
+ f = fopen(name, "wb");
+ if (!f || fwrite(out, 1, size, f) != size || fclose(f) != 0) {
+ fprintf(stderr, "unzbm: %s: %s\n", name, strerror(errno));
+ return 1;
+ }
+ unlink(header_path);
+ unlink(fork_path);
+ free(out);
+ free(fork);
+ free(header);
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ int failed = 0;
+
+ for (int i = 1; i < argc; i++) {
+ failed += expand(argv[i]);
+ }
+ return failed != 0;
+}
diff --git a/xnu-deps/build/pthread/build.sh b/xnu-deps/build/pthread/build.sh
new file mode 100755
index 0000000..764f49d
--- /dev/null
+++ b/xnu-deps/build/pthread/build.sh
@@ -0,0 +1,20 @@
+#!/bin/bash
+# Build the open-source pthread kernel extension (libpthread/kern) as a static
+# library that gets linked into the XNU kernel image (there is no kext loader
+# in this setup). Requires an XNU build tree for the exported kernel headers.
+set -e
+# The two -D renames below avoid clashes with kernel symbols of the same name:
+# as a real kext these live in a separate link unit.
+cd "$(dirname "${BASH_SOURCE[0]}")"
+source ../../../xnu-env.sh
+X=$XNU_SRC; E=$X/BUILD/obj/EXPORT_HDRS; P=$XNUDEPS/libpthread
+[ -d $E/osfmk ] || { echo "pthread kext: no exported kernel headers in $E (run: xnu-build.sh exporthdrs)" >&2; exit 1; }
+mkdir -p $XNU_SDK_PATH/usr/local/lib/kernel
+for f in kern_init kern_support kern_synch; do
+ xnu-clang -arch arm64 -c -Os -mkernel -nostdinc -fno-builtin -fno-common -Wno-int-conversion \
+ -DKERNEL=1 -DKERNEL_PRIVATE=1 -DPRIVATE=1 -D__PTHREAD_EXPOSE_INTERNALS__=1 -Dpthread_kern=pthread_kext_kern -Dcurrent_uthread=pthread_kext_current_uthread -D__DARWIN_64_BIT_INO_T=1 -DARM64_BOARD_CONFIG_BCM2837 \
+ -Iinc -I$P -I$E/osfmk -I$E/bsd -I$E/libkern -I$E/pexpert -I$E/iokit -I$E/security -I$X/EXTERNAL_HEADERS \
+ -I$P/include -I$P/private -o pthread_$f.o $P/kern/$f.c
+done
+libtool -static -o $XNU_SDK_PATH/usr/local/lib/kernel/libpthread_kext.a pthread_kern_init.o pthread_kern_support.o pthread_kern_synch.o
+ls -la $XNU_SDK_PATH/usr/local/lib/kernel/libpthread_kext.a
diff --git a/xnu-deps/gen-iig-stubs.py b/xnu-deps/gen-iig-stubs.py
new file mode 100644
index 0000000..c023941
--- /dev/null
+++ b/xnu-deps/gen-iig-stubs.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""
+Generate stand-in DriverKit implementation files for the XNU build.
+
+Apple's `iig` tool (closed source) normally generates <Class>.iig.cpp: the RPC
+marshalling for DriverKit (user-space driver) interfaces. Without it the kernel
+fails to link. This script reads the linker's undefined-symbol list and emits:
+ * metaclass definitions for classes that only exist as DriverKit interfaces
+ * a stub returning kIOReturnUnsupported for every remaining generated method
+The kernel then links and runs; user-space DriverKit drivers are non-functional.
+
+usage: gen-iig-stubs.py <undefined.txt> <outdir> [kernel-symbols (nm -n output)]
+"""
+import re, sys, os
+
+undefined = [l.strip() for l in open(sys.argv[1]) if l.strip()]
+outdir = sys.argv[2]
+
+# class -> superclass, for classes whose OSMetaClass the generated code owns
+META = {
+ 'IODispatchSource': ('OSObject', True),
+ 'IOEventLink': ('OSObject', False),
+ 'IOWorkGroup': ('OSObject', False),
+ 'IODispatchQueue': ('OSObject', False),
+ 'OSAction': ('OSObject', False),
+ 'IODataQueueDispatchSource': ('IODispatchSource', False),
+ 'IOInterruptDispatchSource': ('IODispatchSource', False),
+ 'IOServiceNotificationDispatchSource': ('IODispatchSource', False),
+ 'IOServiceStateNotificationDispatchSource': ('IODispatchSource', False),
+}
+
+meta_needed, funcs = [], []
+for sym in undefined:
+ m = re.match(r'__ZN(\d+)', sym)
+ if not m:
+ continue
+ n = int(m.group(1)); cls = sym[len(m.group(0)):len(m.group(0)) + n]
+ if sym.endswith('9metaClassE') and sym == '__ZN%d%s9metaClassE' % (n, cls):
+ meta_needed.append(cls)
+ else:
+ funcs.append(sym)
+vt = [s for s in undefined if s.startswith('__ZTV')]
+
+out = ['/* Generated by gen-iig-stubs.py: stand-in for iig output. Do not edit. */',
+ '#include <IOKit/IOLib.h>', '#include <IOKit/IOReturn.h>', '#include <IOKit/IOService.h>',
+ '#include <IOKit/IOUserClient.h>', '#include <IOKit/IOUserServer.h>',
+ '#include <DriverKit/IODispatchSource.h>', '#include <DriverKit/IODispatchQueue.h>',
+ '#include <DriverKit/IOEventLink.h>', '#include <DriverKit/IOWorkGroup.h>', '#include <DriverKit/OSAction.h>',
+ '#include <DriverKit/IODataQueueDispatchSource.h>', '#include <DriverKit/IOInterruptDispatchSource.h>',
+ '#include <DriverKit/IOServiceNotificationDispatchSource.h>',
+ '#include <DriverKit/IOServiceStateNotificationDispatchSource.h>', '']
+want = set(meta_needed)
+if any(META.get(c, ('', 0))[0] == 'IODispatchSource' for c in want) or vt:
+ want.add('IODispatchSource')
+for cls, (sup, abstract) in META.items():
+ if cls in want:
+ macro = 'OSDefineMetaClassAndAbstractStructors' if abstract else 'OSDefineMetaClassAndStructors'
+ out.append('%s(%s, %s);' % (macro, cls, sup))
+out.append('')
+# Kernel-implemented methods: the real generated wrapper marshals the call into
+# an RPC and dispatches it back to Class::Method_Impl(). For objects that live
+# in the kernel that round trip is equivalent to calling _Impl directly, and
+# the kernel itself relies on it (e.g. IOService::StateNotificationItemCreate).
+# The wrapper only has one extra trailing argument (the "supermethod"), so a
+# tail branch is argument-compatible on arm64.
+SUPER = 'PFiP15OSMetaClassBase5IORPCE'
+defined = set()
+if len(sys.argv) > 3:
+ for line in open(sys.argv[3]):
+ parts = line.split()
+ if len(parts) == 3 and parts[1] in 'tTsS': # kernel text lives in __TEXT_EXEC, which nm reports as 'S'
+ defined.add(parts[2])
+
+def impl_name(sym):
+ m = re.match(r'__ZN(\d+)', sym)
+ if not m or not sym.endswith(SUPER):
+ return None
+ pos = len(m.group(0)) + int(m.group(1))
+ m2 = re.match(r'(\d+)', sym[pos:])
+ if not m2:
+ return None
+ mlen = int(m2.group(1)); mstart = pos + len(m2.group(1))
+ method = sym[mstart:mstart + mlen]
+ rest = sym[mstart + mlen:]
+ if not rest.startswith('E'):
+ return None
+ params = rest[1:-len(SUPER)] or 'v'
+ return '%s%d%s_ImplE%s' % (sym[:pos], mlen + 5, method, params)
+
+direct, unsupported = [], []
+for sym in sorted(set(funcs)):
+ impl = impl_name(sym)
+ if impl and impl in defined:
+ direct.append((sym, impl))
+ else:
+ unsupported.append(sym)
+
+out.append('/* wrappers forwarded straight to their kernel implementation */')
+for sym, impl in direct:
+ out.append('__asm__(".text\\n.globl %s\\n.p2align 2\\n%s:\\n\\tb %s\\n");' % (sym, sym, impl))
+out.append('')
+out.append('/* everything else (RPC dispatch, user-space-only methods) is not available */')
+out.append('extern "C" {')
+for i, sym in enumerate(unsupported):
+ # sym carries the Mach-O leading underscore already
+ out.append('kern_return_t __iig_stub_%d(void) __asm__("%s");' % (i, sym))
+ out.append('kern_return_t __iig_stub_%d(void) { return kIOReturnUnsupported; }' % i)
+out.append('}')
+os.makedirs(outdir, exist_ok=True)
+open(os.path.join(outdir, 'OSObject.iig.cpp'), 'w').write('\n'.join(out) + '\n')
+print('metaclasses:', len(want), 'forwarded to _Impl:', len(direct), 'unsupported stubs:', len(unsupported))
diff --git a/xnu-deps/host/bin/codesign b/xnu-deps/host/bin/codesign
new file mode 100755
index 0000000..039e4d0
--- /dev/null
+++ b/xnu-deps/host/bin/codesign
@@ -0,0 +1,2 @@
+#!/bin/sh
+exit 0
diff --git a/xnu-deps/host/bin/iig b/xnu-deps/host/bin/iig
new file mode 100755
index 0000000..2773787
--- /dev/null
+++ b/xnu-deps/host/bin/iig
@@ -0,0 +1,17 @@
+#!/bin/bash
+# Stand-in for Apple's closed-source iig (DriverKit interface generator).
+# Headers: taken pre-generated from the macOS 13.3 SDK (same xnu-8796 family).
+# Implementation: taken from $XNUDEPS/iig-impl/<name>.iig.cpp if present, else an empty TU.
+XNUDEPS=${XNUDEPS:-$(cd "$(dirname "$0")/../.." && pwd)}
+SDKH="$XNUDEPS/MacOSX13.3.sdk/System/Library/Frameworks/Kernel.framework/Headers"
+def=""; hdr=""; impl=""
+while [ $# -gt 0 ]; do case "$1" in
+ --def) def="$2"; shift 2;; --header) hdr="$2"; shift 2;; --impl) impl="$2"; shift 2;;
+ --) break;; *) shift;; esac; done
+name="$(basename "$def" .iig)"
+src="$(find "$SDKH" -name "$name.h" -path '*DriverKit*' | head -1)"
+[ -z "$src" ] && src="$(find "$SDKH" -name "$name.h" | xargs grep -l 'iig(DriverKit' 2>/dev/null | head -1)"
+if [ -z "$src" ]; then echo "iig shim: no pre-generated header for $name" >&2; exit 1; fi
+cp "$src" "$hdr"
+if [ -f "$XNUDEPS/iig-impl/$name.iig.cpp" ]; then cp "$XNUDEPS/iig-impl/$name.iig.cpp" "$impl"
+else echo "/* $name: no DriverKit implementation generated (iig shim) */" > "$impl"; fi
diff --git a/xnu-deps/host/bin/install b/xnu-deps/host/bin/install
new file mode 100755
index 0000000..48bbc58
--- /dev/null
+++ b/xnu-deps/host/bin/install
@@ -0,0 +1,4 @@
+#!/bin/bash
+# BSD-style install wrapper: drop the BSD-only -S (safe copy) flag
+args=(); for a in "$@"; do [ "$a" = "-S" ] || args+=("$a"); done
+exec /usr/bin/install "${args[@]}"
diff --git a/xnu-deps/host/bin/plutil b/xnu-deps/host/bin/plutil
new file mode 100755
index 0000000..2fc410b
--- /dev/null
+++ b/xnu-deps/host/bin/plutil
@@ -0,0 +1,3 @@
+#!/bin/sh
+# no-op plutil: plists stay XML
+exit 0
diff --git a/xnu-deps/host/bin/sw_vers b/xnu-deps/host/bin/sw_vers
new file mode 100755
index 0000000..b7dfb82
--- /dev/null
+++ b/xnu-deps/host/bin/sw_vers
@@ -0,0 +1,2 @@
+#!/bin/sh
+echo 13.4
diff --git a/xnu-deps/host/bin/xcrun b/xnu-deps/host/bin/xcrun
new file mode 100755
index 0000000..c74c918
--- /dev/null
+++ b/xnu-deps/host/bin/xcrun
@@ -0,0 +1,23 @@
+#!/bin/bash
+# Minimal xcrun replacement for building XNU on Linux
+HB="$(cd "$(dirname "$0")" && pwd)"
+sdk=""; find=""; show=""
+while [ $# -gt 0 ]; do case "$1" in
+ -sdk) sdk="$2"; shift 2;; -verbose) shift;;
+ -find|--find|-f) find="$2"; shift 2;;
+ -show-sdk-path|--show-sdk-path) show=path; shift;;
+ -show-sdk-version|--show-sdk-version) show=version; shift;;
+ -show-sdk-platform-path|--show-sdk-platform-path) show=platform; shift;;
+ -show-sdk-platform-version) show=version; shift;;
+ *) break;; esac; done
+SDKP="${XNU_SDK_PATH:?XNU_SDK_PATH not set}"
+case "$show" in
+ path) case "$sdk" in /*) echo "$sdk";; *) echo "$SDKP";; esac; exit 0;;
+ version) echo "${XNU_SDK_VERSION:-16.5}"; exit 0;;
+ platform) echo "${XNU_PLATFORM_PATH:-/Platforms/iPhoneOS.platform}"; exit 0;;
+esac
+if [ -n "$find" ]; then
+ for d in "$HB" /usr/bin; do [ -x "$d/$find" ] && { echo "$d/$find"; exit 0; }; done
+ exit 1
+fi
+[ $# -gt 0 ] && exec "$@"
diff --git a/xnu-deps/host/bin/xnu-clang b/xnu-deps/host/bin/xnu-clang
new file mode 100755
index 0000000..6ea04a7
--- /dev/null
+++ b/xnu-deps/host/bin/xnu-clang
@@ -0,0 +1,18 @@
+#!/bin/bash
+# clang wrapper for cross-building XNU on Linux:
+# - forces an Apple Mach-O target (stock Linux clang defaults to ELF)
+# - drops flags only Apple's clang understands
+# - links with the cctools ld64
+HB="$(cd "$(dirname "$0")" && pwd)"
+case "$(basename "$0")" in *++) drv=clang++; extra=(-fno-use-cxa-atexit);; *) drv=clang; extra=();; esac
+args=()
+for a in "$@"; do
+ case "$a" in
+ -enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang) ;;
+ -fapple-kext-vtable-verify|-Wno-vla-cxx-extension) ;;
+ -Werror|-Werror=*|-Weverything|-pedantic-errors) ;;
+ *) args+=("$a");;
+ esac
+done
+exec /usr/bin/$drv -include "$HB/../../hostinc/xnu_clang_compat.h" -target arm64-apple-ios${XNU_SDK_VERSION:-16.5} --ld-path="$HB/ld64" \
+ -w "${extra[@]}" "${args[@]}"
diff --git a/xnu-deps/hostinc/architecture/byte_order.h b/xnu-deps/hostinc/architecture/byte_order.h
new file mode 100644
index 0000000..f547167
--- /dev/null
+++ b/xnu-deps/hostinc/architecture/byte_order.h
@@ -0,0 +1,4 @@
+#ifndef HOST_BYTE_ORDER_H
+#define HOST_BYTE_ORDER_H
+enum NXByteOrder { NX_UnknownByteOrder, NX_LittleEndian, NX_BigEndian };
+#endif
diff --git a/xnu-deps/hostinc/copyfile.h b/xnu-deps/hostinc/copyfile.h
new file mode 100644
index 0000000..d828864
--- /dev/null
+++ b/xnu-deps/hostinc/copyfile.h
@@ -0,0 +1,14 @@
+#ifndef HOST_COPYFILE_H
+#define HOST_COPYFILE_H
+#include <unistd.h>
+#define COPYFILE_DATA 8
+typedef void *copyfile_state_t;
+static inline int fcopyfile(int from, int to, copyfile_state_t s, unsigned flags) {
+ char buf[65536]; ssize_t n;
+ (void)s; (void)flags;
+ while ((n = read(from, buf, sizeof buf)) > 0) {
+ char *p = buf; while (n > 0) { ssize_t w = write(to, p, n); if (w < 0) return -1; p += w; n -= w; }
+ }
+ return n < 0 ? -1 : 0;
+}
+#endif
diff --git a/xnu-deps/hostinc/hostcompat.h b/xnu-deps/hostinc/hostcompat.h
new file mode 100644
index 0000000..87b18a2
--- /dev/null
+++ b/xnu-deps/hostinc/hostcompat.h
@@ -0,0 +1,71 @@
+/* Force-included into XNU's SETUP host tools when building on Linux */
+#ifndef XNU_HOSTCOMPAT_H
+#define XNU_HOSTCOMPAT_H
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE 1
+#endif
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+extern char *program_invocation_short_name;
+static inline const char *getprogname(void) { return program_invocation_short_name; }
+#ifndef __unused
+#define __unused __attribute__((unused))
+#endif
+#ifndef __dead2
+#define __dead2 __attribute__((noreturn))
+#endif
+#ifndef __printflike
+#define __printflike(a,b) __attribute__((format(printf,a,b)))
+#endif
+#include <libgen.h>
+#include <sys/param.h>
+typedef uintptr_t vm_offset_t;
+typedef uintptr_t vm_size_t;
+typedef uintptr_t vm_address_t;
+typedef int boolean_t;
+typedef int kern_return_t;
+#ifndef TRUE
+#define TRUE 1
+#define FALSE 0
+#endif
+#define KERN_SUCCESS 0
+#include <byteswap.h>
+#define OSSwapInt16(x) bswap_16(x)
+#define OSSwapInt32(x) bswap_32(x)
+#define OSSwapInt64(x) bswap_64(x)
+#include <uuid/uuid.h>
+static inline void host_uuid_generate(unsigned char *out) {
+ FILE *f = fopen("/dev/urandom", "rb");
+ if (!f || fread(out, 1, 16, f) != 16) abort();
+ fclose(f);
+ out[6] = (out[6] & 0x0f) | 0x40; out[8] = (out[8] & 0x3f) | 0x80;
+}
+#define uuid_generate(x) host_uuid_generate(x)
+/* BSD setmode/getmode: only absolute octal modes are used by the XNU build */
+static inline void *setmode(const char *s) {
+ char *end; long v = strtol(s, &end, 8);
+ if (*end || v < 0) return NULL;
+ mode_t *m = malloc(sizeof *m); *m = (mode_t)v; return m;
+}
+static inline mode_t getmode(const void *set, mode_t omode) { (void)omode; return *(const mode_t *)set; }
+#ifndef O_EXLOCK
+#define O_EXLOCK 0
+#endif
+#ifndef O_SHLOCK
+#define O_SHLOCK 0
+#endif
+#ifndef O_SYMLINK
+#define O_SYMLINK 0
+#endif
+#ifndef EFTYPE
+#define EFTYPE EINVAL
+#endif
+#endif
diff --git a/xnu-deps/hostinc/libc.h b/xnu-deps/hostinc/libc.h
new file mode 100644
index 0000000..f5bc330
--- /dev/null
+++ b/xnu-deps/hostinc/libc.h
@@ -0,0 +1,11 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/param.h>
+#include <sys/mman.h>
+#include <sys/file.h>
+#include <stdarg.h>
diff --git a/xnu-deps/hostinc/mach-o/arch.h b/xnu-deps/hostinc/mach-o/arch.h
new file mode 100644
index 0000000..0ee9c79
--- /dev/null
+++ b/xnu-deps/hostinc/mach-o/arch.h
@@ -0,0 +1,10 @@
+#ifndef HOST_MACHO_ARCH_H
+#define HOST_MACHO_ARCH_H
+#include <mach/machine.h>
+#include <architecture/byte_order.h>
+typedef struct { const char *name; cpu_type_t cputype; cpu_subtype_t cpusubtype; enum NXByteOrder byteorder; const char *description; } NXArchInfo;
+static inline const NXArchInfo *NXGetLocalArchInfo(void) {
+ static const NXArchInfo host = { "x86_64", CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL, NX_LittleEndian, "host" };
+ return &host;
+}
+#endif
diff --git a/xnu-deps/hostinc/mach-o/fat.h b/xnu-deps/hostinc/mach-o/fat.h
new file mode 100644
index 0000000..e2bcf43
--- /dev/null
+++ b/xnu-deps/hostinc/mach-o/fat.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ *
+ * This file contains Original Code and/or Modifications of Original Code
+ * as defined in and that are subject to the Apple Public Source License
+ * Version 2.0 (the 'License'). You may not use this file except in
+ * compliance with the License. Please obtain a copy of the License at
+ * http://www.opensource.apple.com/apsl/ and read it before using this
+ * file.
+ *
+ * The Original Code and all software distributed under the License are
+ * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
+ * Please see the License for the specific language governing rights and
+ * limitations under the License.
+ *
+ * @APPLE_LICENSE_HEADER_END@
+ */
+#ifndef _MACH_O_FAT_H_
+#define _MACH_O_FAT_H_
+/*
+ * This header file describes the structures of the file format for "fat"
+ * architecture specific file (wrapper design). At the begining of the file
+ * there is one fat_header structure followed by a number of fat_arch
+ * structures. For each architecture in the file, specified by a pair of
+ * cputype and cpusubtype, the fat_header describes the file offset, file
+ * size and alignment in the file of the architecture specific member.
+ * The padded bytes in the file to place each member on it's specific alignment
+ * are defined to be read as zeros and can be left as "holes" if the file system
+ * can support them as long as they read as zeros.
+ *
+ * All structures defined here are always written and read to/from disk
+ * in big-endian order.
+ */
+
+/*
+ * <mach/machine.h> is needed here for the cpu_type_t and cpu_subtype_t types
+ * and contains the constants for the possible values of these types.
+ */
+#include <stdint.h>
+#include <mach/machine.h>
+#include <architecture/byte_order.h>
+
+#define FAT_MAGIC 0xcafebabe
+#define FAT_CIGAM 0xbebafeca /* NXSwapLong(FAT_MAGIC) */
+
+struct fat_header {
+ uint32_t magic; /* FAT_MAGIC */
+ uint32_t nfat_arch; /* number of structs that follow */
+};
+
+struct fat_arch {
+ cpu_type_t cputype; /* cpu specifier (int) */
+ cpu_subtype_t cpusubtype; /* machine specifier (int) */
+ uint32_t offset; /* file offset to this object file */
+ uint32_t size; /* size of this object file */
+ uint32_t align; /* alignment as a power of 2 */
+};
+
+#endif /* _MACH_O_FAT_H_ */
diff --git a/xnu-deps/hostinc/mach-o/loader.h b/xnu-deps/hostinc/mach-o/loader.h
new file mode 100644
index 0000000..4d1b930
--- /dev/null
+++ b/xnu-deps/hostinc/mach-o/loader.h
@@ -0,0 +1,1590 @@
+/*
+ * Copyright (c) 1999-2019 Apple Inc. All Rights Reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ *
+ * This file contains Original Code and/or Modifications of Original Code
+ * as defined in and that are subject to the Apple Public Source License
+ * Version 2.0 (the 'License'). You may not use this file except in
+ * compliance with the License. Please obtain a copy of the License at
+ * http://www.opensource.apple.com/apsl/ and read it before using this
+ * file.
+ *
+ * The Original Code and all software distributed under the License are
+ * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
+ * Please see the License for the specific language governing rights and
+ * limitations under the License.
+ *
+ * @APPLE_LICENSE_HEADER_END@
+ */
+#ifndef _MACHO_LOADER_H_
+#define _MACHO_LOADER_H_
+
+/*
+ * This file describes the format of mach object files.
+ */
+#include <stdint.h>
+
+/*
+ * <mach/machine.h> is needed here for the cpu_type_t and cpu_subtype_t types
+ * and contains the constants for the possible values of these types.
+ */
+#include <mach/machine.h>
+
+/*
+ * <mach/vm_prot.h> is needed here for the vm_prot_t type and contains the
+ * constants that are or'ed together for the possible values of this type.
+ */
+#include <mach/vm_prot.h>
+
+/*
+ * <machine/thread_status.h> is expected to define the flavors of the thread
+ * states and the structures of those flavors for each machine.
+ */
+#include <mach/machine/thread_status.h>
+#include <architecture/byte_order.h>
+
+/*
+ * The 32-bit mach header appears at the very beginning of the object file for
+ * 32-bit architectures.
+ */
+struct mach_header {
+ uint32_t magic; /* mach magic number identifier */
+ cpu_type_t cputype; /* cpu specifier */
+ cpu_subtype_t cpusubtype; /* machine specifier */
+ uint32_t filetype; /* type of file */
+ uint32_t ncmds; /* number of load commands */
+ uint32_t sizeofcmds; /* the size of all the load commands */
+ uint32_t flags; /* flags */
+};
+
+/* Constant for the magic field of the mach_header (32-bit architectures) */
+#define MH_MAGIC 0xfeedface /* the mach magic number */
+#define MH_CIGAM 0xcefaedfe /* NXSwapInt(MH_MAGIC) */
+
+/*
+ * The 64-bit mach header appears at the very beginning of object files for
+ * 64-bit architectures.
+ */
+struct mach_header_64 {
+ uint32_t magic; /* mach magic number identifier */
+ cpu_type_t cputype; /* cpu specifier */
+ cpu_subtype_t cpusubtype; /* machine specifier */
+ uint32_t filetype; /* type of file */
+ uint32_t ncmds; /* number of load commands */
+ uint32_t sizeofcmds; /* the size of all the load commands */
+ uint32_t flags; /* flags */
+ uint32_t reserved; /* reserved */
+};
+
+/* Constant for the magic field of the mach_header_64 (64-bit architectures) */
+#define MH_MAGIC_64 0xfeedfacf /* the 64-bit mach magic number */
+#define MH_CIGAM_64 0xcffaedfe /* NXSwapInt(MH_MAGIC_64) */
+
+/*
+ * The layout of the file depends on the filetype. For all but the MH_OBJECT
+ * file type the segments are padded out and aligned on a segment alignment
+ * boundary for efficient demand pageing. The MH_EXECUTE, MH_FVMLIB, MH_DYLIB,
+ * MH_DYLINKER and MH_BUNDLE file types also have the headers included as part
+ * of their first segment.
+ *
+ * The file type MH_OBJECT is a compact format intended as output of the
+ * assembler and input (and possibly output) of the link editor (the .o
+ * format). All sections are in one unnamed segment with no segment padding.
+ * This format is used as an executable format when the file is so small the
+ * segment padding greatly increases its size.
+ *
+ * The file type MH_PRELOAD is an executable format intended for things that
+ * are not executed under the kernel (proms, stand alones, kernels, etc). The
+ * format can be executed under the kernel but may demand paged it and not
+ * preload it before execution.
+ *
+ * A core file is in MH_CORE format and can be any in an arbritray legal
+ * Mach-O file.
+ *
+ * Constants for the filetype field of the mach_header
+ */
+#define MH_OBJECT 0x1 /* relocatable object file */
+#define MH_EXECUTE 0x2 /* demand paged executable file */
+#define MH_FVMLIB 0x3 /* fixed VM shared library file */
+#define MH_CORE 0x4 /* core file */
+#define MH_PRELOAD 0x5 /* preloaded executable file */
+#define MH_DYLIB 0x6 /* dynamically bound shared library */
+#define MH_DYLINKER 0x7 /* dynamic link editor */
+#define MH_BUNDLE 0x8 /* dynamically bound bundle file */
+#define MH_DYLIB_STUB 0x9 /* shared library stub for static */
+ /* linking only, no section contents */
+#define MH_DSYM 0xa /* companion file with only debug */
+ /* sections */
+#define MH_KEXT_BUNDLE 0xb /* x86_64 kexts */
+#define MH_FILESET 0xc /* set of mach-o's */
+
+/* Constants for the flags field of the mach_header */
+#define MH_NOUNDEFS 0x1 /* the object file has no undefined
+ references */
+#define MH_INCRLINK 0x2 /* the object file is the output of an
+ incremental link against a base file
+ and can't be link edited again */
+#define MH_DYLDLINK 0x4 /* the object file is input for the
+ dynamic linker and can't be staticly
+ link edited again */
+#define MH_BINDATLOAD 0x8 /* the object file's undefined
+ references are bound by the dynamic
+ linker when loaded. */
+#define MH_PREBOUND 0x10 /* the file has its dynamic undefined
+ references prebound. */
+#define MH_SPLIT_SEGS 0x20 /* the file has its read-only and
+ read-write segments split */
+#define MH_LAZY_INIT 0x40 /* the shared library init routine is
+ to be run lazily via catching memory
+ faults to its writeable segments
+ (obsolete) */
+#define MH_TWOLEVEL 0x80 /* the image is using two-level name
+ space bindings */
+#define MH_FORCE_FLAT 0x100 /* the executable is forcing all images
+ to use flat name space bindings */
+#define MH_NOMULTIDEFS 0x200 /* this umbrella guarantees no multiple
+ defintions of symbols in its
+ sub-images so the two-level namespace
+ hints can always be used. */
+#define MH_NOFIXPREBINDING 0x400 /* do not have dyld notify the
+ prebinding agent about this
+ executable */
+#define MH_PREBINDABLE 0x800 /* the binary is not prebound but can
+ have its prebinding redone. only used
+ when MH_PREBOUND is not set. */
+#define MH_ALLMODSBOUND 0x1000 /* indicates that this binary binds to
+ all two-level namespace modules of
+ its dependent libraries. only used
+ when MH_PREBINDABLE and MH_TWOLEVEL
+ are both set. */
+#define MH_SUBSECTIONS_VIA_SYMBOLS 0x2000/* safe to divide up the sections into
+ sub-sections via symbols for dead
+ code stripping */
+#define MH_CANONICAL 0x4000 /* the binary has been canonicalized
+ via the unprebind operation */
+#define MH_WEAK_DEFINES 0x8000 /* the final linked image contains
+ external weak symbols */
+#define MH_BINDS_TO_WEAK 0x10000 /* the final linked image uses
+ weak symbols */
+
+#define MH_ALLOW_STACK_EXECUTION 0x20000/* When this bit is set, all stacks
+ in the task will be given stack
+ execution privilege. Only used in
+ MH_EXECUTE filetypes. */
+#define MH_ROOT_SAFE 0x40000 /* When this bit is set, the binary
+ declares it is safe for use in
+ processes with uid zero */
+
+#define MH_SETUID_SAFE 0x80000 /* When this bit is set, the binary
+ declares it is safe for use in
+ processes when issetugid() is true */
+
+#define MH_NO_REEXPORTED_DYLIBS 0x100000 /* When this bit is set on a dylib,
+ the static linker does not need to
+ examine dependent dylibs to see
+ if any are re-exported */
+#define MH_PIE 0x200000 /* When this bit is set, the OS will
+ load the main executable at a
+ random address. Only used in
+ MH_EXECUTE filetypes. */
+#define MH_DEAD_STRIPPABLE_DYLIB 0x400000 /* Only for use on dylibs. When
+ linking against a dylib that
+ has this bit set, the static linker
+ will automatically not create a
+ LC_LOAD_DYLIB load command to the
+ dylib if no symbols are being
+ referenced from the dylib. */
+#define MH_HAS_TLV_DESCRIPTORS 0x800000 /* Contains a section of type
+ S_THREAD_LOCAL_VARIABLES */
+
+#define MH_NO_HEAP_EXECUTION 0x1000000 /* When this bit is set, the OS will
+ run the main executable with
+ a non-executable heap even on
+ platforms (e.g. i386) that don't
+ require it. Only used in MH_EXECUTE
+ filetypes. */
+
+#define MH_APP_EXTENSION_SAFE 0x02000000 /* The code was linked for use in an
+ application extension. */
+
+#define MH_NLIST_OUTOFSYNC_WITH_DYLDINFO 0x04000000 /* The external symbols
+ listed in the nlist symbol table do
+ not include all the symbols listed in
+ the dyld info. */
+
+#define MH_SIM_SUPPORT 0x08000000 /* Allow LC_MIN_VERSION_MACOS and
+ LC_BUILD_VERSION load commands with
+ the platforms macOS, iOSMac,
+ iOSSimulator, tvOSSimulator and
+ watchOSSimulator. */
+
+#define MH_DYLIB_IN_CACHE 0x80000000 /* Only for use on dylibs. When this bit
+ is set, the dylib is part of the dyld
+ shared cache, rather than loose in
+ the filesystem. */
+
+/*
+ * The load commands directly follow the mach_header. The total size of all
+ * of the commands is given by the sizeofcmds field in the mach_header. All
+ * load commands must have as their first two fields cmd and cmdsize. The cmd
+ * field is filled in with a constant for that command type. Each command type
+ * has a structure specifically for it. The cmdsize field is the size in bytes
+ * of the particular load command structure plus anything that follows it that
+ * is a part of the load command (i.e. section structures, strings, etc.). To
+ * advance to the next load command the cmdsize can be added to the offset or
+ * pointer of the current load command. The cmdsize for 32-bit architectures
+ * MUST be a multiple of 4 bytes and for 64-bit architectures MUST be a multiple
+ * of 8 bytes (these are forever the maximum alignment of any load commands).
+ * The padded bytes must be zero. All tables in the object file must also
+ * follow these rules so the file can be memory mapped. Otherwise the pointers
+ * to these tables will not work well or at all on some machines. With all
+ * padding zeroed like objects will compare byte for byte.
+ */
+struct load_command {
+ uint32_t cmd; /* type of load command */
+ uint32_t cmdsize; /* total size of command in bytes */
+};
+
+/*
+ * After MacOS X 10.1 when a new load command is added that is required to be
+ * understood by the dynamic linker for the image to execute properly the
+ * LC_REQ_DYLD bit will be or'ed into the load command constant. If the dynamic
+ * linker sees such a load command it it does not understand will issue a
+ * "unknown load command required for execution" error and refuse to use the
+ * image. Other load commands without this bit that are not understood will
+ * simply be ignored.
+ */
+#define LC_REQ_DYLD 0x80000000
+
+/* Constants for the cmd field of all load commands, the type */
+#define LC_SEGMENT 0x1 /* segment of this file to be mapped */
+#define LC_SYMTAB 0x2 /* link-edit stab symbol table info */
+#define LC_SYMSEG 0x3 /* link-edit gdb symbol table info (obsolete) */
+#define LC_THREAD 0x4 /* thread */
+#define LC_UNIXTHREAD 0x5 /* unix thread (includes a stack) */
+#define LC_LOADFVMLIB 0x6 /* load a specified fixed VM shared library */
+#define LC_IDFVMLIB 0x7 /* fixed VM shared library identification */
+#define LC_IDENT 0x8 /* object identification info (obsolete) */
+#define LC_FVMFILE 0x9 /* fixed VM file inclusion (internal use) */
+#define LC_PREPAGE 0xa /* prepage command (internal use) */
+#define LC_DYSYMTAB 0xb /* dynamic link-edit symbol table info */
+#define LC_LOAD_DYLIB 0xc /* load a dynamically linked shared library */
+#define LC_ID_DYLIB 0xd /* dynamically linked shared lib ident */
+#define LC_LOAD_DYLINKER 0xe /* load a dynamic linker */
+#define LC_ID_DYLINKER 0xf /* dynamic linker identification */
+#define LC_PREBOUND_DYLIB 0x10 /* modules prebound for a dynamically */
+ /* linked shared library */
+#define LC_ROUTINES 0x11 /* image routines */
+#define LC_SUB_FRAMEWORK 0x12 /* sub framework */
+#define LC_SUB_UMBRELLA 0x13 /* sub umbrella */
+#define LC_SUB_CLIENT 0x14 /* sub client */
+#define LC_SUB_LIBRARY 0x15 /* sub library */
+#define LC_TWOLEVEL_HINTS 0x16 /* two-level namespace lookup hints */
+#define LC_PREBIND_CKSUM 0x17 /* prebind checksum */
+
+/*
+ * load a dynamically linked shared library that is allowed to be missing
+ * (all symbols are weak imported).
+ */
+#define LC_LOAD_WEAK_DYLIB (0x18 | LC_REQ_DYLD)
+
+#define LC_SEGMENT_64 0x19 /* 64-bit segment of this file to be
+ mapped */
+#define LC_ROUTINES_64 0x1a /* 64-bit image routines */
+#define LC_UUID 0x1b /* the uuid */
+#define LC_RPATH (0x1c | LC_REQ_DYLD) /* runpath additions */
+#define LC_CODE_SIGNATURE 0x1d /* local of code signature */
+#define LC_SEGMENT_SPLIT_INFO 0x1e /* local of info to split segments */
+#define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD) /* load and re-export dylib */
+#define LC_LAZY_LOAD_DYLIB 0x20 /* delay load of dylib until first use */
+#define LC_ENCRYPTION_INFO 0x21 /* encrypted segment information */
+#define LC_DYLD_INFO 0x22 /* compressed dyld information */
+#define LC_DYLD_INFO_ONLY (0x22|LC_REQ_DYLD) /* compressed dyld information only */
+#define LC_LOAD_UPWARD_DYLIB (0x23 | LC_REQ_DYLD) /* load upward dylib */
+#define LC_VERSION_MIN_MACOSX 0x24 /* build for MacOSX min OS version */
+#define LC_VERSION_MIN_IPHONEOS 0x25 /* build for iPhoneOS min OS version */
+#define LC_FUNCTION_STARTS 0x26 /* compressed table of function start addresses */
+#define LC_DYLD_ENVIRONMENT 0x27 /* string for dyld to treat
+ like environment variable */
+#define LC_MAIN (0x28|LC_REQ_DYLD) /* replacement for LC_UNIXTHREAD */
+#define LC_DATA_IN_CODE 0x29 /* table of non-instructions in __text */
+#define LC_SOURCE_VERSION 0x2A /* source version used to build binary */
+#define LC_DYLIB_CODE_SIGN_DRS 0x2B /* Code signing DRs copied from linked dylibs */
+#define LC_ENCRYPTION_INFO_64 0x2C /* 64-bit encrypted segment information */
+#define LC_LINKER_OPTION 0x2D /* linker options in MH_OBJECT files */
+#define LC_LINKER_OPTIMIZATION_HINT 0x2E /* optimization hints in MH_OBJECT files */
+#define LC_VERSION_MIN_TVOS 0x2F /* build for AppleTV min OS version */
+#define LC_VERSION_MIN_WATCHOS 0x30 /* build for Watch min OS version */
+#define LC_NOTE 0x31 /* arbitrary data included within a Mach-O file */
+#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */
+#define LC_DYLD_EXPORTS_TRIE (0x33 | LC_REQ_DYLD) /* used with linkedit_data_command, payload is trie */
+#define LC_DYLD_CHAINED_FIXUPS (0x34 | LC_REQ_DYLD) /* used with linkedit_data_command */
+#define LC_FILESET_ENTRY (0x35 | LC_REQ_DYLD) /* used with fileset_entry_command */
+
+/*
+ * A variable length string in a load command is represented by an lc_str
+ * union. The strings are stored just after the load command structure and
+ * the offset is from the start of the load command structure. The size
+ * of the string is reflected in the cmdsize field of the load command.
+ * Once again any padded bytes to bring the cmdsize field to a multiple
+ * of 4 bytes must be zero.
+ */
+union lc_str {
+ uint32_t offset; /* offset to the string */
+#ifndef __LP64__
+ char *ptr; /* pointer to the string */
+#endif
+};
+
+/*
+ * The segment load command indicates that a part of this file is to be
+ * mapped into the task's address space. The size of this segment in memory,
+ * vmsize, maybe equal to or larger than the amount to map from this file,
+ * filesize. The file is mapped starting at fileoff to the beginning of
+ * the segment in memory, vmaddr. The rest of the memory of the segment,
+ * if any, is allocated zero fill on demand. The segment's maximum virtual
+ * memory protection and initial virtual memory protection are specified
+ * by the maxprot and initprot fields. If the segment has sections then the
+ * section structures directly follow the segment command and their size is
+ * reflected in cmdsize.
+ */
+struct segment_command { /* for 32-bit architectures */
+ uint32_t cmd; /* LC_SEGMENT */
+ uint32_t cmdsize; /* includes sizeof section structs */
+ char segname[16]; /* segment name */
+ uint32_t vmaddr; /* memory address of this segment */
+ uint32_t vmsize; /* memory size of this segment */
+ uint32_t fileoff; /* file offset of this segment */
+ uint32_t filesize; /* amount to map from the file */
+ vm_prot_t maxprot; /* maximum VM protection */
+ vm_prot_t initprot; /* initial VM protection */
+ uint32_t nsects; /* number of sections in segment */
+ uint32_t flags; /* flags */
+};
+
+/*
+ * The 64-bit segment load command indicates that a part of this file is to be
+ * mapped into a 64-bit task's address space. If the 64-bit segment has
+ * sections then section_64 structures directly follow the 64-bit segment
+ * command and their size is reflected in cmdsize.
+ */
+struct segment_command_64 { /* for 64-bit architectures */
+ uint32_t cmd; /* LC_SEGMENT_64 */
+ uint32_t cmdsize; /* includes sizeof section_64 structs */
+ char segname[16]; /* segment name */
+ uint64_t vmaddr; /* memory address of this segment */
+ uint64_t vmsize; /* memory size of this segment */
+ uint64_t fileoff; /* file offset of this segment */
+ uint64_t filesize; /* amount to map from the file */
+ vm_prot_t maxprot; /* maximum VM protection */
+ vm_prot_t initprot; /* initial VM protection */
+ uint32_t nsects; /* number of sections in segment */
+ uint32_t flags; /* flags */
+};
+
+/* Constants for the flags field of the segment_command */
+#define SG_HIGHVM 0x1 /* the file contents for this segment is for
+ the high part of the VM space, the low part
+ is zero filled (for stacks in core files) */
+#define SG_FVMLIB 0x2 /* this segment is the VM that is allocated by
+ a fixed VM library, for overlap checking in
+ the link editor */
+#define SG_NORELOC 0x4 /* this segment has nothing that was relocated
+ in it and nothing relocated to it, that is
+ it maybe safely replaced without relocation*/
+#define SG_PROTECTED_VERSION_1 0x8 /* This segment is protected. If the
+ segment starts at file offset 0, the
+ first page of the segment is not
+ protected. All other pages of the
+ segment are protected. */
+#define SG_READ_ONLY 0x10 /* This segment is made read-only after fixups */
+
+
+
+/*
+ * A segment is made up of zero or more sections. Non-MH_OBJECT files have
+ * all of their segments with the proper sections in each, and padded to the
+ * specified segment alignment when produced by the link editor. The first
+ * segment of a MH_EXECUTE and MH_FVMLIB format file contains the mach_header
+ * and load commands of the object file before its first section. The zero
+ * fill sections are always last in their segment (in all formats). This
+ * allows the zeroed segment padding to be mapped into memory where zero fill
+ * sections might be. The gigabyte zero fill sections, those with the section
+ * type S_GB_ZEROFILL, can only be in a segment with sections of this type.
+ * These segments are then placed after all other segments.
+ *
+ * The MH_OBJECT format has all of its sections in one segment for
+ * compactness. There is no padding to a specified segment boundary and the
+ * mach_header and load commands are not part of the segment.
+ *
+ * Sections with the same section name, sectname, going into the same segment,
+ * segname, are combined by the link editor. The resulting section is aligned
+ * to the maximum alignment of the combined sections and is the new section's
+ * alignment. The combined sections are aligned to their original alignment in
+ * the combined section. Any padded bytes to get the specified alignment are
+ * zeroed.
+ *
+ * The format of the relocation entries referenced by the reloff and nreloc
+ * fields of the section structure for mach object files is described in the
+ * header file <reloc.h>.
+ */
+struct section { /* for 32-bit architectures */
+ char sectname[16]; /* name of this section */
+ char segname[16]; /* segment this section goes in */
+ uint32_t addr; /* memory address of this section */
+ uint32_t size; /* size in bytes of this section */
+ uint32_t offset; /* file offset of this section */
+ uint32_t align; /* section alignment (power of 2) */
+ uint32_t reloff; /* file offset of relocation entries */
+ uint32_t nreloc; /* number of relocation entries */
+ uint32_t flags; /* flags (section type and attributes)*/
+ uint32_t reserved1; /* reserved (for offset or index) */
+ uint32_t reserved2; /* reserved (for count or sizeof) */
+};
+
+struct section_64 { /* for 64-bit architectures */
+ char sectname[16]; /* name of this section */
+ char segname[16]; /* segment this section goes in */
+ uint64_t addr; /* memory address of this section */
+ uint64_t size; /* size in bytes of this section */
+ uint32_t offset; /* file offset of this section */
+ uint32_t align; /* section alignment (power of 2) */
+ uint32_t reloff; /* file offset of relocation entries */
+ uint32_t nreloc; /* number of relocation entries */
+ uint32_t flags; /* flags (section type and attributes)*/
+ uint32_t reserved1; /* reserved (for offset or index) */
+ uint32_t reserved2; /* reserved (for count or sizeof) */
+ uint32_t reserved3; /* reserved */
+};
+
+/*
+ * The flags field of a section structure is separated into two parts a section
+ * type and section attributes. The section types are mutually exclusive (it
+ * can only have one type) but the section attributes are not (it may have more
+ * than one attribute).
+ */
+#define SECTION_TYPE 0x000000ff /* 256 section types */
+#define SECTION_ATTRIBUTES 0xffffff00 /* 24 section attributes */
+
+/* Constants for the type of a section */
+#define S_REGULAR 0x0 /* regular section */
+#define S_ZEROFILL 0x1 /* zero fill on demand section */
+#define S_CSTRING_LITERALS 0x2 /* section with only literal C strings*/
+#define S_4BYTE_LITERALS 0x3 /* section with only 4 byte literals */
+#define S_8BYTE_LITERALS 0x4 /* section with only 8 byte literals */
+#define S_LITERAL_POINTERS 0x5 /* section with only pointers to */
+ /* literals */
+/*
+ * For the two types of symbol pointers sections and the symbol stubs section
+ * they have indirect symbol table entries. For each of the entries in the
+ * section the indirect symbol table entries, in corresponding order in the
+ * indirect symbol table, start at the index stored in the reserved1 field
+ * of the section structure. Since the indirect symbol table entries
+ * correspond to the entries in the section the number of indirect symbol table
+ * entries is inferred from the size of the section divided by the size of the
+ * entries in the section. For symbol pointers sections the size of the entries
+ * in the section is 4 bytes and for symbol stubs sections the byte size of the
+ * stubs is stored in the reserved2 field of the section structure.
+ */
+#define S_NON_LAZY_SYMBOL_POINTERS 0x6 /* section with only non-lazy
+ symbol pointers */
+#define S_LAZY_SYMBOL_POINTERS 0x7 /* section with only lazy symbol
+ pointers */
+#define S_SYMBOL_STUBS 0x8 /* section with only symbol
+ stubs, byte size of stub in
+ the reserved2 field */
+#define S_MOD_INIT_FUNC_POINTERS 0x9 /* section with only function
+ pointers for initialization*/
+#define S_MOD_TERM_FUNC_POINTERS 0xa /* section with only function
+ pointers for termination */
+#define S_COALESCED 0xb /* section contains symbols that
+ are to be coalesced */
+#define S_GB_ZEROFILL 0xc /* zero fill on demand section
+ (that can be larger than 4
+ gigabytes) */
+#define S_INTERPOSING 0xd /* section with only pairs of
+ function pointers for
+ interposing */
+#define S_16BYTE_LITERALS 0xe /* section with only 16 byte
+ literals */
+#define S_DTRACE_DOF 0xf /* section contains
+ DTrace Object Format */
+#define S_LAZY_DYLIB_SYMBOL_POINTERS 0x10 /* section with only lazy
+ symbol pointers to lazy
+ loaded dylibs */
+/*
+ * Section types to support thread local variables
+ */
+#define S_THREAD_LOCAL_REGULAR 0x11 /* template of initial
+ values for TLVs */
+#define S_THREAD_LOCAL_ZEROFILL 0x12 /* template of initial
+ values for TLVs */
+#define S_THREAD_LOCAL_VARIABLES 0x13 /* TLV descriptors */
+#define S_THREAD_LOCAL_VARIABLE_POINTERS 0x14 /* pointers to TLV
+ descriptors */
+#define S_THREAD_LOCAL_INIT_FUNCTION_POINTERS 0x15 /* functions to call
+ to initialize TLV
+ values */
+#define S_INIT_FUNC_OFFSETS 0x16 /* 32-bit offsets to
+ initializers */
+
+/*
+ * Constants for the section attributes part of the flags field of a section
+ * structure.
+ */
+#define SECTION_ATTRIBUTES_USR 0xff000000 /* User setable attributes */
+#define S_ATTR_PURE_INSTRUCTIONS 0x80000000 /* section contains only true
+ machine instructions */
+#define S_ATTR_NO_TOC 0x40000000 /* section contains coalesced
+ symbols that are not to be
+ in a ranlib table of
+ contents */
+#define S_ATTR_STRIP_STATIC_SYMS 0x20000000 /* ok to strip static symbols
+ in this section in files
+ with the MH_DYLDLINK flag */
+#define S_ATTR_NO_DEAD_STRIP 0x10000000 /* no dead stripping */
+#define S_ATTR_LIVE_SUPPORT 0x08000000 /* blocks are live if they
+ reference live blocks */
+#define S_ATTR_SELF_MODIFYING_CODE 0x04000000 /* Used with i386 code stubs
+ written on by dyld */
+/*
+ * If a segment contains any sections marked with S_ATTR_DEBUG then all
+ * sections in that segment must have this attribute. No section other than
+ * a section marked with this attribute may reference the contents of this
+ * section. A section with this attribute may contain no symbols and must have
+ * a section type S_REGULAR. The static linker will not copy section contents
+ * from sections with this attribute into its output file. These sections
+ * generally contain DWARF debugging info.
+ */
+#define S_ATTR_DEBUG 0x02000000 /* a debug section */
+#define SECTION_ATTRIBUTES_SYS 0x00ffff00 /* system setable attributes */
+#define S_ATTR_SOME_INSTRUCTIONS 0x00000400 /* section contains some
+ machine instructions */
+#define S_ATTR_EXT_RELOC 0x00000200 /* section has external
+ relocation entries */
+#define S_ATTR_LOC_RELOC 0x00000100 /* section has local
+ relocation entries */
+
+
+/*
+ * The names of segments and sections in them are mostly meaningless to the
+ * link-editor. But there are few things to support traditional UNIX
+ * executables that require the link-editor and assembler to use some names
+ * agreed upon by convention.
+ *
+ * The initial protection of the "__TEXT" segment has write protection turned
+ * off (not writeable).
+ *
+ * The link-editor will allocate common symbols at the end of the "__common"
+ * section in the "__DATA" segment. It will create the section and segment
+ * if needed.
+ */
+
+/* The currently known segment names and the section names in those segments */
+
+#define SEG_PAGEZERO "__PAGEZERO" /* the pagezero segment which has no */
+ /* protections and catches NULL */
+ /* references for MH_EXECUTE files */
+
+
+#define SEG_TEXT "__TEXT" /* the tradition UNIX text segment */
+#define SECT_TEXT "__text" /* the real text part of the text */
+ /* section no headers, and no padding */
+#define SECT_FVMLIB_INIT0 "__fvmlib_init0" /* the fvmlib initialization */
+ /* section */
+#define SECT_FVMLIB_INIT1 "__fvmlib_init1" /* the section following the */
+ /* fvmlib initialization */
+ /* section */
+
+#define SEG_DATA "__DATA" /* the tradition UNIX data segment */
+#define SECT_DATA "__data" /* the real initialized data section */
+ /* no padding, no bss overlap */
+#define SECT_BSS "__bss" /* the real uninitialized data section*/
+ /* no padding */
+#define SECT_COMMON "__common" /* the section common symbols are */
+ /* allocated in by the link editor */
+
+#define SEG_OBJC "__OBJC" /* objective-C runtime segment */
+#define SECT_OBJC_SYMBOLS "__symbol_table" /* symbol table */
+#define SECT_OBJC_MODULES "__module_info" /* module information */
+#define SECT_OBJC_STRINGS "__selector_strs" /* string table */
+#define SECT_OBJC_REFS "__selector_refs" /* string table */
+
+#define SEG_ICON "__ICON" /* the icon segment */
+#define SECT_ICON_HEADER "__header" /* the icon headers */
+#define SECT_ICON_TIFF "__tiff" /* the icons in tiff format */
+
+#define SEG_LINKEDIT "__LINKEDIT" /* the segment containing all structs */
+ /* created and maintained by the link */
+ /* editor. Created with -seglinkedit */
+ /* option to ld(1) for MH_EXECUTE and */
+ /* FVMLIB file types only */
+
+#define SEG_LINKINFO "__LINKINFO" /* the segment overlapping with linkedit */
+ /* containing linking information */
+
+#define SEG_UNIXSTACK "__UNIXSTACK" /* the unix stack segment */
+
+#define SEG_IMPORT "__IMPORT" /* the segment for the self (dyld) */
+ /* modifing code stubs that has read, */
+ /* write and execute permissions */
+
+/*
+ * Fixed virtual memory shared libraries are identified by two things. The
+ * target pathname (the name of the library as found for execution), and the
+ * minor version number. The address of where the headers are loaded is in
+ * header_addr. (THIS IS OBSOLETE and no longer supported).
+ */
+struct fvmlib {
+ union lc_str name; /* library's target pathname */
+ uint32_t minor_version; /* library's minor version number */
+ uint32_t header_addr; /* library's header address */
+};
+
+/*
+ * A fixed virtual shared library (filetype == MH_FVMLIB in the mach header)
+ * contains a fvmlib_command (cmd == LC_IDFVMLIB) to identify the library.
+ * An object that uses a fixed virtual shared library also contains a
+ * fvmlib_command (cmd == LC_LOADFVMLIB) for each library it uses.
+ * (THIS IS OBSOLETE and no longer supported).
+ */
+struct fvmlib_command {
+ uint32_t cmd; /* LC_IDFVMLIB or LC_LOADFVMLIB */
+ uint32_t cmdsize; /* includes pathname string */
+ struct fvmlib fvmlib; /* the library identification */
+};
+
+/*
+ * Dynamicly linked shared libraries are identified by two things. The
+ * pathname (the name of the library as found for execution), and the
+ * compatibility version number. The pathname must match and the compatibility
+ * number in the user of the library must be greater than or equal to the
+ * library being used. The time stamp is used to record the time a library was
+ * built and copied into user so it can be use to determined if the library used
+ * at runtime is exactly the same as used to built the program.
+ */
+struct dylib {
+ union lc_str name; /* library's path name */
+ uint32_t timestamp; /* library's build time stamp */
+ uint32_t current_version; /* library's current version number */
+ uint32_t compatibility_version; /* library's compatibility vers number*/
+};
+
+/*
+ * A dynamically linked shared library (filetype == MH_DYLIB in the mach header)
+ * contains a dylib_command (cmd == LC_ID_DYLIB) to identify the library.
+ * An object that uses a dynamically linked shared library also contains a
+ * dylib_command (cmd == LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, or
+ * LC_REEXPORT_DYLIB) for each library it uses.
+ */
+struct dylib_command {
+ uint32_t cmd; /* LC_ID_DYLIB, LC_LOAD_{,WEAK_}DYLIB,
+ LC_REEXPORT_DYLIB */
+ uint32_t cmdsize; /* includes pathname string */
+ struct dylib dylib; /* the library identification */
+};
+
+/*
+ * A dynamically linked shared library may be a subframework of an umbrella
+ * framework. If so it will be linked with "-umbrella umbrella_name" where
+ * Where "umbrella_name" is the name of the umbrella framework. A subframework
+ * can only be linked against by its umbrella framework or other subframeworks
+ * that are part of the same umbrella framework. Otherwise the static link
+ * editor produces an error and states to link against the umbrella framework.
+ * The name of the umbrella framework for subframeworks is recorded in the
+ * following structure.
+ */
+struct sub_framework_command {
+ uint32_t cmd; /* LC_SUB_FRAMEWORK */
+ uint32_t cmdsize; /* includes umbrella string */
+ union lc_str umbrella; /* the umbrella framework name */
+};
+
+/*
+ * For dynamically linked shared libraries that are subframework of an umbrella
+ * framework they can allow clients other than the umbrella framework or other
+ * subframeworks in the same umbrella framework. To do this the subframework
+ * is built with "-allowable_client client_name" and an LC_SUB_CLIENT load
+ * command is created for each -allowable_client flag. The client_name is
+ * usually a framework name. It can also be a name used for bundles clients
+ * where the bundle is built with "-client_name client_name".
+ */
+struct sub_client_command {
+ uint32_t cmd; /* LC_SUB_CLIENT */
+ uint32_t cmdsize; /* includes client string */
+ union lc_str client; /* the client name */
+};
+
+/*
+ * A dynamically linked shared library may be a sub_umbrella of an umbrella
+ * framework. If so it will be linked with "-sub_umbrella umbrella_name" where
+ * Where "umbrella_name" is the name of the sub_umbrella framework. When
+ * staticly linking when -twolevel_namespace is in effect a twolevel namespace
+ * umbrella framework will only cause its subframeworks and those frameworks
+ * listed as sub_umbrella frameworks to be implicited linked in. Any other
+ * dependent dynamic libraries will not be linked it when -twolevel_namespace
+ * is in effect. The primary library recorded by the static linker when
+ * resolving a symbol in these libraries will be the umbrella framework.
+ * Zero or more sub_umbrella frameworks may be use by an umbrella framework.
+ * The name of a sub_umbrella framework is recorded in the following structure.
+ */
+struct sub_umbrella_command {
+ uint32_t cmd; /* LC_SUB_UMBRELLA */
+ uint32_t cmdsize; /* includes sub_umbrella string */
+ union lc_str sub_umbrella; /* the sub_umbrella framework name */
+};
+
+/*
+ * A dynamically linked shared library may be a sub_library of another shared
+ * library. If so it will be linked with "-sub_library library_name" where
+ * Where "library_name" is the name of the sub_library shared library. When
+ * staticly linking when -twolevel_namespace is in effect a twolevel namespace
+ * shared library will only cause its subframeworks and those frameworks
+ * listed as sub_umbrella frameworks and libraries listed as sub_libraries to
+ * be implicited linked in. Any other dependent dynamic libraries will not be
+ * linked it when -twolevel_namespace is in effect. The primary library
+ * recorded by the static linker when resolving a symbol in these libraries
+ * will be the umbrella framework (or dynamic library). Zero or more sub_library
+ * shared libraries may be use by an umbrella framework or (or dynamic library).
+ * The name of a sub_library framework is recorded in the following structure.
+ * For example /usr/lib/libobjc_profile.A.dylib would be recorded as "libobjc".
+ */
+struct sub_library_command {
+ uint32_t cmd; /* LC_SUB_LIBRARY */
+ uint32_t cmdsize; /* includes sub_library string */
+ union lc_str sub_library; /* the sub_library name */
+};
+
+/*
+ * A program (filetype == MH_EXECUTE) that is
+ * prebound to its dynamic libraries has one of these for each library that
+ * the static linker used in prebinding. It contains a bit vector for the
+ * modules in the library. The bits indicate which modules are bound (1) and
+ * which are not (0) from the library. The bit for module 0 is the low bit
+ * of the first byte. So the bit for the Nth module is:
+ * (linked_modules[N/8] >> N%8) & 1
+ */
+struct prebound_dylib_command {
+ uint32_t cmd; /* LC_PREBOUND_DYLIB */
+ uint32_t cmdsize; /* includes strings */
+ union lc_str name; /* library's path name */
+ uint32_t nmodules; /* number of modules in library */
+ union lc_str linked_modules; /* bit vector of linked modules */
+};
+
+/*
+ * A program that uses a dynamic linker contains a dylinker_command to identify
+ * the name of the dynamic linker (LC_LOAD_DYLINKER). And a dynamic linker
+ * contains a dylinker_command to identify the dynamic linker (LC_ID_DYLINKER).
+ * A file can have at most one of these.
+ * This struct is also used for the LC_DYLD_ENVIRONMENT load command and
+ * contains string for dyld to treat like environment variable.
+ */
+struct dylinker_command {
+ uint32_t cmd; /* LC_ID_DYLINKER, LC_LOAD_DYLINKER or
+ LC_DYLD_ENVIRONMENT */
+ uint32_t cmdsize; /* includes pathname string */
+ union lc_str name; /* dynamic linker's path name */
+};
+
+/*
+ * Thread commands contain machine-specific data structures suitable for
+ * use in the thread state primitives. The machine specific data structures
+ * follow the struct thread_command as follows.
+ * Each flavor of machine specific data structure is preceded by an uint32_t
+ * constant for the flavor of that data structure, an uint32_t that is the
+ * count of uint32_t's of the size of the state data structure and then
+ * the state data structure follows. This triple may be repeated for many
+ * flavors. The constants for the flavors, counts and state data structure
+ * definitions are expected to be in the header file <machine/thread_status.h>.
+ * These machine specific data structures sizes must be multiples of
+ * 4 bytes. The cmdsize reflects the total size of the thread_command
+ * and all of the sizes of the constants for the flavors, counts and state
+ * data structures.
+ *
+ * For executable objects that are unix processes there will be one
+ * thread_command (cmd == LC_UNIXTHREAD) created for it by the link-editor.
+ * This is the same as a LC_THREAD, except that a stack is automatically
+ * created (based on the shell's limit for the stack size). Command arguments
+ * and environment variables are copied onto that stack.
+ */
+struct thread_command {
+ uint32_t cmd; /* LC_THREAD or LC_UNIXTHREAD */
+ uint32_t cmdsize; /* total size of this command */
+ /* uint32_t flavor flavor of thread state */
+ /* uint32_t count count of uint32_t's in thread state */
+ /* struct XXX_thread_state state thread state for this flavor */
+ /* ... */
+};
+
+/*
+ * The routines command contains the address of the dynamic shared library
+ * initialization routine and an index into the module table for the module
+ * that defines the routine. Before any modules are used from the library the
+ * dynamic linker fully binds the module that defines the initialization routine
+ * and then calls it. This gets called before any module initialization
+ * routines (used for C++ static constructors) in the library.
+ */
+struct routines_command { /* for 32-bit architectures */
+ uint32_t cmd; /* LC_ROUTINES */
+ uint32_t cmdsize; /* total size of this command */
+ uint32_t init_address; /* address of initialization routine */
+ uint32_t init_module; /* index into the module table that */
+ /* the init routine is defined in */
+ uint32_t reserved1;
+ uint32_t reserved2;
+ uint32_t reserved3;
+ uint32_t reserved4;
+ uint32_t reserved5;
+ uint32_t reserved6;
+};
+
+/*
+ * The 64-bit routines command. Same use as above.
+ */
+struct routines_command_64 { /* for 64-bit architectures */
+ uint32_t cmd; /* LC_ROUTINES_64 */
+ uint32_t cmdsize; /* total size of this command */
+ uint64_t init_address; /* address of initialization routine */
+ uint64_t init_module; /* index into the module table that */
+ /* the init routine is defined in */
+ uint64_t reserved1;
+ uint64_t reserved2;
+ uint64_t reserved3;
+ uint64_t reserved4;
+ uint64_t reserved5;
+ uint64_t reserved6;
+};
+
+/*
+ * The symtab_command contains the offsets and sizes of the link-edit 4.3BSD
+ * "stab" style symbol table information as described in the header files
+ * <nlist.h> and <stab.h>.
+ */
+struct symtab_command {
+ uint32_t cmd; /* LC_SYMTAB */
+ uint32_t cmdsize; /* sizeof(struct symtab_command) */
+ uint32_t symoff; /* symbol table offset */
+ uint32_t nsyms; /* number of symbol table entries */
+ uint32_t stroff; /* string table offset */
+ uint32_t strsize; /* string table size in bytes */
+};
+
+/*
+ * This is the second set of the symbolic information which is used to support
+ * the data structures for the dynamically link editor.
+ *
+ * The original set of symbolic information in the symtab_command which contains
+ * the symbol and string tables must also be present when this load command is
+ * present. When this load command is present the symbol table is organized
+ * into three groups of symbols:
+ * local symbols (static and debugging symbols) - grouped by module
+ * defined external symbols - grouped by module (sorted by name if not lib)
+ * undefined external symbols (sorted by name if MH_BINDATLOAD is not set,
+ * and in order the were seen by the static
+ * linker if MH_BINDATLOAD is set)
+ * In this load command there are offsets and counts to each of the three groups
+ * of symbols.
+ *
+ * This load command contains a the offsets and sizes of the following new
+ * symbolic information tables:
+ * table of contents
+ * module table
+ * reference symbol table
+ * indirect symbol table
+ * The first three tables above (the table of contents, module table and
+ * reference symbol table) are only present if the file is a dynamically linked
+ * shared library. For executable and object modules, which are files
+ * containing only one module, the information that would be in these three
+ * tables is determined as follows:
+ * table of contents - the defined external symbols are sorted by name
+ * module table - the file contains only one module so everything in the
+ * file is part of the module.
+ * reference symbol table - is the defined and undefined external symbols
+ *
+ * For dynamically linked shared library files this load command also contains
+ * offsets and sizes to the pool of relocation entries for all sections
+ * separated into two groups:
+ * external relocation entries
+ * local relocation entries
+ * For executable and object modules the relocation entries continue to hang
+ * off the section structures.
+ */
+struct dysymtab_command {
+ uint32_t cmd; /* LC_DYSYMTAB */
+ uint32_t cmdsize; /* sizeof(struct dysymtab_command) */
+
+ /*
+ * The symbols indicated by symoff and nsyms of the LC_SYMTAB load command
+ * are grouped into the following three groups:
+ * local symbols (further grouped by the module they are from)
+ * defined external symbols (further grouped by the module they are from)
+ * undefined symbols
+ *
+ * The local symbols are used only for debugging. The dynamic binding
+ * process may have to use them to indicate to the debugger the local
+ * symbols for a module that is being bound.
+ *
+ * The last two groups are used by the dynamic binding process to do the
+ * binding (indirectly through the module table and the reference symbol
+ * table when this is a dynamically linked shared library file).
+ */
+ uint32_t ilocalsym; /* index to local symbols */
+ uint32_t nlocalsym; /* number of local symbols */
+
+ uint32_t iextdefsym;/* index to externally defined symbols */
+ uint32_t nextdefsym;/* number of externally defined symbols */
+
+ uint32_t iundefsym; /* index to undefined symbols */
+ uint32_t nundefsym; /* number of undefined symbols */
+
+ /*
+ * For the for the dynamic binding process to find which module a symbol
+ * is defined in the table of contents is used (analogous to the ranlib
+ * structure in an archive) which maps defined external symbols to modules
+ * they are defined in. This exists only in a dynamically linked shared
+ * library file. For executable and object modules the defined external
+ * symbols are sorted by name and is use as the table of contents.
+ */
+ uint32_t tocoff; /* file offset to table of contents */
+ uint32_t ntoc; /* number of entries in table of contents */
+
+ /*
+ * To support dynamic binding of "modules" (whole object files) the symbol
+ * table must reflect the modules that the file was created from. This is
+ * done by having a module table that has indexes and counts into the merged
+ * tables for each module. The module structure that these two entries
+ * refer to is described below. This exists only in a dynamically linked
+ * shared library file. For executable and object modules the file only
+ * contains one module so everything in the file belongs to the module.
+ */
+ uint32_t modtaboff; /* file offset to module table */
+ uint32_t nmodtab; /* number of module table entries */
+
+ /*
+ * To support dynamic module binding the module structure for each module
+ * indicates the external references (defined and undefined) each module
+ * makes. For each module there is an offset and a count into the
+ * reference symbol table for the symbols that the module references.
+ * This exists only in a dynamically linked shared library file. For
+ * executable and object modules the defined external symbols and the
+ * undefined external symbols indicates the external references.
+ */
+ uint32_t extrefsymoff; /* offset to referenced symbol table */
+ uint32_t nextrefsyms; /* number of referenced symbol table entries */
+
+ /*
+ * The sections that contain "symbol pointers" and "routine stubs" have
+ * indexes and (implied counts based on the size of the section and fixed
+ * size of the entry) into the "indirect symbol" table for each pointer
+ * and stub. For every section of these two types the index into the
+ * indirect symbol table is stored in the section header in the field
+ * reserved1. An indirect symbol table entry is simply a 32bit index into
+ * the symbol table to the symbol that the pointer or stub is referring to.
+ * The indirect symbol table is ordered to match the entries in the section.
+ */
+ uint32_t indirectsymoff; /* file offset to the indirect symbol table */
+ uint32_t nindirectsyms; /* number of indirect symbol table entries */
+
+ /*
+ * To support relocating an individual module in a library file quickly the
+ * external relocation entries for each module in the library need to be
+ * accessed efficiently. Since the relocation entries can't be accessed
+ * through the section headers for a library file they are separated into
+ * groups of local and external entries further grouped by module. In this
+ * case the presents of this load command who's extreloff, nextrel,
+ * locreloff and nlocrel fields are non-zero indicates that the relocation
+ * entries of non-merged sections are not referenced through the section
+ * structures (and the reloff and nreloc fields in the section headers are
+ * set to zero).
+ *
+ * Since the relocation entries are not accessed through the section headers
+ * this requires the r_address field to be something other than a section
+ * offset to identify the item to be relocated. In this case r_address is
+ * set to the offset from the vmaddr of the first LC_SEGMENT command.
+ * For MH_SPLIT_SEGS images r_address is set to the the offset from the
+ * vmaddr of the first read-write LC_SEGMENT command.
+ *
+ * The relocation entries are grouped by module and the module table
+ * entries have indexes and counts into them for the group of external
+ * relocation entries for that the module.
+ *
+ * For sections that are merged across modules there must not be any
+ * remaining external relocation entries for them (for merged sections
+ * remaining relocation entries must be local).
+ */
+ uint32_t extreloff; /* offset to external relocation entries */
+ uint32_t nextrel; /* number of external relocation entries */
+
+ /*
+ * All the local relocation entries are grouped together (they are not
+ * grouped by their module since they are only used if the object is moved
+ * from it staticly link edited address).
+ */
+ uint32_t locreloff; /* offset to local relocation entries */
+ uint32_t nlocrel; /* number of local relocation entries */
+
+};
+
+/*
+ * An indirect symbol table entry is simply a 32bit index into the symbol table
+ * to the symbol that the pointer or stub is refering to. Unless it is for a
+ * non-lazy symbol pointer section for a defined symbol which strip(1) as
+ * removed. In which case it has the value INDIRECT_SYMBOL_LOCAL. If the
+ * symbol was also absolute INDIRECT_SYMBOL_ABS is or'ed with that.
+ */
+#define INDIRECT_SYMBOL_LOCAL 0x80000000
+#define INDIRECT_SYMBOL_ABS 0x40000000
+
+
+/* a table of contents entry */
+struct dylib_table_of_contents {
+ uint32_t symbol_index; /* the defined external symbol
+ (index into the symbol table) */
+ uint32_t module_index; /* index into the module table this symbol
+ is defined in */
+};
+
+/* a module table entry */
+struct dylib_module {
+ uint32_t module_name; /* the module name (index into string table) */
+
+ uint32_t iextdefsym; /* index into externally defined symbols */
+ uint32_t nextdefsym; /* number of externally defined symbols */
+ uint32_t irefsym; /* index into reference symbol table */
+ uint32_t nrefsym; /* number of reference symbol table entries */
+ uint32_t ilocalsym; /* index into symbols for local symbols */
+ uint32_t nlocalsym; /* number of local symbols */
+
+ uint32_t iextrel; /* index into external relocation entries */
+ uint32_t nextrel; /* number of external relocation entries */
+
+ uint32_t iinit_iterm; /* low 16 bits are the index into the init
+ section, high 16 bits are the index into
+ the term section */
+ uint32_t ninit_nterm; /* low 16 bits are the number of init section
+ entries, high 16 bits are the number of
+ term section entries */
+
+ uint32_t /* for this module address of the start of */
+ objc_module_info_addr; /* the (__OBJC,__module_info) section */
+ uint32_t /* for this module size of */
+ objc_module_info_size; /* the (__OBJC,__module_info) section */
+};
+
+/* a 64-bit module table entry */
+struct dylib_module_64 {
+ uint32_t module_name; /* the module name (index into string table) */
+
+ uint32_t iextdefsym; /* index into externally defined symbols */
+ uint32_t nextdefsym; /* number of externally defined symbols */
+ uint32_t irefsym; /* index into reference symbol table */
+ uint32_t nrefsym; /* number of reference symbol table entries */
+ uint32_t ilocalsym; /* index into symbols for local symbols */
+ uint32_t nlocalsym; /* number of local symbols */
+
+ uint32_t iextrel; /* index into external relocation entries */
+ uint32_t nextrel; /* number of external relocation entries */
+
+ uint32_t iinit_iterm; /* low 16 bits are the index into the init
+ section, high 16 bits are the index into
+ the term section */
+ uint32_t ninit_nterm; /* low 16 bits are the number of init section
+ entries, high 16 bits are the number of
+ term section entries */
+
+ uint32_t /* for this module size of */
+ objc_module_info_size; /* the (__OBJC,__module_info) section */
+ uint64_t /* for this module address of the start of */
+ objc_module_info_addr; /* the (__OBJC,__module_info) section */
+};
+
+/*
+ * The entries in the reference symbol table are used when loading the module
+ * (both by the static and dynamic link editors) and if the module is unloaded
+ * or replaced. Therefore all external symbols (defined and undefined) are
+ * listed in the module's reference table. The flags describe the type of
+ * reference that is being made. The constants for the flags are defined in
+ * <mach-o/nlist.h> as they are also used for symbol table entries.
+ */
+struct dylib_reference {
+ uint32_t isym:24, /* index into the symbol table */
+ flags:8; /* flags to indicate the type of reference */
+};
+
+/*
+ * The twolevel_hints_command contains the offset and number of hints in the
+ * two-level namespace lookup hints table.
+ */
+struct twolevel_hints_command {
+ uint32_t cmd; /* LC_TWOLEVEL_HINTS */
+ uint32_t cmdsize; /* sizeof(struct twolevel_hints_command) */
+ uint32_t offset; /* offset to the hint table */
+ uint32_t nhints; /* number of hints in the hint table */
+};
+
+/*
+ * The entries in the two-level namespace lookup hints table are twolevel_hint
+ * structs. These provide hints to the dynamic link editor where to start
+ * looking for an undefined symbol in a two-level namespace image. The
+ * isub_image field is an index into the sub-images (sub-frameworks and
+ * sub-umbrellas list) that made up the two-level image that the undefined
+ * symbol was found in when it was built by the static link editor. If
+ * isub-image is 0 the the symbol is expected to be defined in library and not
+ * in the sub-images. If isub-image is non-zero it is an index into the array
+ * of sub-images for the umbrella with the first index in the sub-images being
+ * 1. The array of sub-images is the ordered list of sub-images of the umbrella
+ * that would be searched for a symbol that has the umbrella recorded as its
+ * primary library. The table of contents index is an index into the
+ * library's table of contents. This is used as the starting point of the
+ * binary search or a directed linear search.
+ */
+struct twolevel_hint {
+ uint32_t
+ isub_image:8, /* index into the sub images */
+ itoc:24; /* index into the table of contents */
+};
+
+/*
+ * The prebind_cksum_command contains the value of the original check sum for
+ * prebound files or zero. When a prebound file is first created or modified
+ * for other than updating its prebinding information the value of the check sum
+ * is set to zero. When the file has it prebinding re-done and if the value of
+ * the check sum is zero the original check sum is calculated and stored in
+ * cksum field of this load command in the output file. If when the prebinding
+ * is re-done and the cksum field is non-zero it is left unchanged from the
+ * input file.
+ */
+struct prebind_cksum_command {
+ uint32_t cmd; /* LC_PREBIND_CKSUM */
+ uint32_t cmdsize; /* sizeof(struct prebind_cksum_command) */
+ uint32_t cksum; /* the check sum or zero */
+};
+
+/*
+ * The uuid load command contains a single 128-bit unique random number that
+ * identifies an object produced by the static link editor.
+ */
+struct uuid_command {
+ uint32_t cmd; /* LC_UUID */
+ uint32_t cmdsize; /* sizeof(struct uuid_command) */
+ uint8_t uuid[16]; /* the 128-bit uuid */
+};
+
+/*
+ * The rpath_command contains a path which at runtime should be added to
+ * the current run path used to find @rpath prefixed dylibs.
+ */
+struct rpath_command {
+ uint32_t cmd; /* LC_RPATH */
+ uint32_t cmdsize; /* includes string */
+ union lc_str path; /* path to add to run path */
+};
+
+/*
+ * The linkedit_data_command contains the offsets and sizes of a blob
+ * of data in the __LINKEDIT segment.
+ */
+struct linkedit_data_command {
+ uint32_t cmd; /* LC_CODE_SIGNATURE, LC_SEGMENT_SPLIT_INFO,
+ LC_FUNCTION_STARTS, LC_DATA_IN_CODE,
+ LC_DYLIB_CODE_SIGN_DRS,
+ LC_LINKER_OPTIMIZATION_HINT,
+ LC_DYLD_EXPORTS_TRIE, or
+ LC_DYLD_CHAINED_FIXUPS. */
+ uint32_t cmdsize; /* sizeof(struct linkedit_data_command) */
+ uint32_t dataoff; /* file offset of data in __LINKEDIT segment */
+ uint32_t datasize; /* file size of data in __LINKEDIT segment */
+};
+
+struct fileset_entry_command {
+ uint32_t cmd; /* LC_FILESET_ENTRY */
+ uint32_t cmdsize; /* includes id string */
+ uint64_t vmaddr; /* memory address of the dylib */
+ uint64_t fileoff; /* file offset of the dylib */
+ union lc_str entry_id; /* contained entry id */
+ uint32_t reserved; /* entry_id is 32-bits long, so this is the reserved padding */
+};
+
+/*
+ * The encryption_info_command contains the file offset and size of an
+ * of an encrypted segment.
+ */
+struct encryption_info_command {
+ uint32_t cmd; /* LC_ENCRYPTION_INFO */
+ uint32_t cmdsize; /* sizeof(struct encryption_info_command) */
+ uint32_t cryptoff; /* file offset of encrypted range */
+ uint32_t cryptsize; /* file size of encrypted range */
+ uint32_t cryptid; /* which enryption system,
+ 0 means not-encrypted yet */
+};
+
+/*
+ * The encryption_info_command_64 contains the file offset and size of an
+ * of an encrypted segment (for use in x86_64 targets).
+ */
+struct encryption_info_command_64 {
+ uint32_t cmd; /* LC_ENCRYPTION_INFO_64 */
+ uint32_t cmdsize; /* sizeof(struct encryption_info_command_64) */
+ uint32_t cryptoff; /* file offset of encrypted range */
+ uint32_t cryptsize; /* file size of encrypted range */
+ uint32_t cryptid; /* which enryption system,
+ 0 means not-encrypted yet */
+ uint32_t pad; /* padding to make this struct's size a multiple
+ of 8 bytes */
+};
+
+/*
+ * The version_min_command contains the min OS version on which this
+ * binary was built to run.
+ */
+struct version_min_command {
+ uint32_t cmd; /* LC_VERSION_MIN_MACOSX or
+ LC_VERSION_MIN_IPHONEOS or
+ LC_VERSION_MIN_WATCHOS or
+ LC_VERSION_MIN_TVOS */
+ uint32_t cmdsize; /* sizeof(struct min_version_command) */
+ uint32_t version; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+ uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+};
+
+/*
+ * The build_version_command contains the min OS version on which this
+ * binary was built to run for its platform. The list of known platforms and
+ * tool values following it.
+ */
+struct build_version_command {
+ uint32_t cmd; /* LC_BUILD_VERSION */
+ uint32_t cmdsize; /* sizeof(struct build_version_command) plus */
+ /* ntools * sizeof(struct build_tool_version) */
+ uint32_t platform; /* platform */
+ uint32_t minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+ uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+ uint32_t ntools; /* number of tool entries following this */
+};
+
+struct build_tool_version {
+ uint32_t tool; /* enum for the tool */
+ uint32_t version; /* version number of the tool */
+};
+
+/* Known values for the platform field above. */
+#define PLATFORM_MACOS 1
+#define PLATFORM_IOS 2
+#define PLATFORM_TVOS 3
+#define PLATFORM_WATCHOS 4
+#define PLATFORM_BRIDGEOS 5
+#define PLATFORM_MACCATALYST 6
+#define PLATFORM_IOSSIMULATOR 7
+#define PLATFORM_TVOSSIMULATOR 8
+#define PLATFORM_WATCHOSSIMULATOR 9
+#define PLATFORM_DRIVERKIT 10
+#define PLATFORM_MAX PLATFORM_DRIVERKIT
+/* Addition of simulated platfrom also needs to update proc_is_simulated() */
+
+/* Known values for the tool field above. */
+#define TOOL_CLANG 1
+#define TOOL_SWIFT 2
+#define TOOL_LD 3
+
+/*
+ * The dyld_info_command contains the file offsets and sizes of
+ * the new compressed form of the information dyld needs to
+ * load the image. This information is used by dyld on Mac OS X
+ * 10.6 and later. All information pointed to by this command
+ * is encoded using byte streams, so no endian swapping is needed
+ * to interpret it.
+ */
+struct dyld_info_command {
+ uint32_t cmd; /* LC_DYLD_INFO or LC_DYLD_INFO_ONLY */
+ uint32_t cmdsize; /* sizeof(struct dyld_info_command) */
+
+ /*
+ * Dyld rebases an image whenever dyld loads it at an address different
+ * from its preferred address. The rebase information is a stream
+ * of byte sized opcodes whose symbolic names start with REBASE_OPCODE_.
+ * Conceptually the rebase information is a table of tuples:
+ * <seg-index, seg-offset, type>
+ * The opcodes are a compressed way to encode the table by only
+ * encoding when a column changes. In addition simple patterns
+ * like "every n'th offset for m times" can be encoded in a few
+ * bytes.
+ */
+ uint32_t rebase_off; /* file offset to rebase info */
+ uint32_t rebase_size; /* size of rebase info */
+
+ /*
+ * Dyld binds an image during the loading process, if the image
+ * requires any pointers to be initialized to symbols in other images.
+ * The bind information is a stream of byte sized
+ * opcodes whose symbolic names start with BIND_OPCODE_.
+ * Conceptually the bind information is a table of tuples:
+ * <seg-index, seg-offset, type, symbol-library-ordinal, symbol-name, addend>
+ * The opcodes are a compressed way to encode the table by only
+ * encoding when a column changes. In addition simple patterns
+ * like for runs of pointers initialzed to the same value can be
+ * encoded in a few bytes.
+ */
+ uint32_t bind_off; /* file offset to binding info */
+ uint32_t bind_size; /* size of binding info */
+
+ /*
+ * Some C++ programs require dyld to unique symbols so that all
+ * images in the process use the same copy of some code/data.
+ * This step is done after binding. The content of the weak_bind
+ * info is an opcode stream like the bind_info. But it is sorted
+ * alphabetically by symbol name. This enable dyld to walk
+ * all images with weak binding information in order and look
+ * for collisions. If there are no collisions, dyld does
+ * no updating. That means that some fixups are also encoded
+ * in the bind_info. For instance, all calls to "operator new"
+ * are first bound to libstdc++.dylib using the information
+ * in bind_info. Then if some image overrides operator new
+ * that is detected when the weak_bind information is processed
+ * and the call to operator new is then rebound.
+ */
+ uint32_t weak_bind_off; /* file offset to weak binding info */
+ uint32_t weak_bind_size; /* size of weak binding info */
+
+ /*
+ * Some uses of external symbols do not need to be bound immediately.
+ * Instead they can be lazily bound on first use. The lazy_bind
+ * are contains a stream of BIND opcodes to bind all lazy symbols.
+ * Normal use is that dyld ignores the lazy_bind section when
+ * loading an image. Instead the static linker arranged for the
+ * lazy pointer to initially point to a helper function which
+ * pushes the offset into the lazy_bind area for the symbol
+ * needing to be bound, then jumps to dyld which simply adds
+ * the offset to lazy_bind_off to get the information on what
+ * to bind.
+ */
+ uint32_t lazy_bind_off; /* file offset to lazy binding info */
+ uint32_t lazy_bind_size; /* size of lazy binding infs */
+
+ /*
+ * The symbols exported by a dylib are encoded in a trie. This
+ * is a compact representation that factors out common prefixes.
+ * It also reduces LINKEDIT pages in RAM because it encodes all
+ * information (name, address, flags) in one small, contiguous range.
+ * The export area is a stream of nodes. The first node sequentially
+ * is the start node for the trie.
+ *
+ * Nodes for a symbol start with a uleb128 that is the length of
+ * the exported symbol information for the string so far.
+ * If there is no exported symbol, the node starts with a zero byte.
+ * If there is exported info, it follows the length.
+ *
+ * First is a uleb128 containing flags. Normally, it is followed by
+ * a uleb128 encoded offset which is location of the content named
+ * by the symbol from the mach_header for the image. If the flags
+ * is EXPORT_SYMBOL_FLAGS_REEXPORT, then following the flags is
+ * a uleb128 encoded library ordinal, then a zero terminated
+ * UTF8 string. If the string is zero length, then the symbol
+ * is re-export from the specified dylib with the same name.
+ * If the flags is EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER, then following
+ * the flags is two uleb128s: the stub offset and the resolver offset.
+ * The stub is used by non-lazy pointers. The resolver is used
+ * by lazy pointers and must be called to get the actual address to use.
+ *
+ * After the optional exported symbol information is a byte of
+ * how many edges (0-255) that this node has leaving it,
+ * followed by each edge.
+ * Each edge is a zero terminated UTF8 of the addition chars
+ * in the symbol, followed by a uleb128 offset for the node that
+ * edge points to.
+ *
+ */
+ uint32_t export_off; /* file offset to lazy binding info */
+ uint32_t export_size; /* size of lazy binding infs */
+};
+
+/*
+ * The following are used to encode rebasing information
+ */
+#define REBASE_TYPE_POINTER 1
+#define REBASE_TYPE_TEXT_ABSOLUTE32 2
+#define REBASE_TYPE_TEXT_PCREL32 3
+
+#define REBASE_OPCODE_MASK 0xF0
+#define REBASE_IMMEDIATE_MASK 0x0F
+#define REBASE_OPCODE_DONE 0x00
+#define REBASE_OPCODE_SET_TYPE_IMM 0x10
+#define REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x20
+#define REBASE_OPCODE_ADD_ADDR_ULEB 0x30
+#define REBASE_OPCODE_ADD_ADDR_IMM_SCALED 0x40
+#define REBASE_OPCODE_DO_REBASE_IMM_TIMES 0x50
+#define REBASE_OPCODE_DO_REBASE_ULEB_TIMES 0x60
+#define REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB 0x70
+#define REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB 0x80
+
+
+/*
+ * The following are used to encode binding information
+ */
+#define BIND_TYPE_POINTER 1
+#define BIND_TYPE_TEXT_ABSOLUTE32 2
+#define BIND_TYPE_TEXT_PCREL32 3
+
+#define BIND_SPECIAL_DYLIB_SELF 0
+#define BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE -1
+#define BIND_SPECIAL_DYLIB_FLAT_LOOKUP -2
+#define BIND_SPECIAL_DYLIB_WEAK_LOOKUP -3
+
+#define BIND_SYMBOL_FLAGS_WEAK_IMPORT 0x1
+#define BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION 0x8
+
+#define BIND_OPCODE_MASK 0xF0
+#define BIND_IMMEDIATE_MASK 0x0F
+#define BIND_OPCODE_DONE 0x00
+#define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
+#define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
+#define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
+#define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
+#define BIND_OPCODE_SET_TYPE_IMM 0x50
+#define BIND_OPCODE_SET_ADDEND_SLEB 0x60
+#define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
+#define BIND_OPCODE_ADD_ADDR_ULEB 0x80
+#define BIND_OPCODE_DO_BIND 0x90
+#define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xA0
+#define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xB0
+#define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xC0
+#define BIND_OPCODE_THREADED 0xD0
+#define BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB 0x00
+#define BIND_SUBOPCODE_THREADED_APPLY 0x01
+
+
+/*
+ * The following are used on the flags byte of a terminal node
+ * in the export information.
+ */
+#define EXPORT_SYMBOL_FLAGS_KIND_MASK 0x03
+#define EXPORT_SYMBOL_FLAGS_KIND_REGULAR 0x00
+#define EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL 0x01
+#define EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE 0x02
+#define EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION 0x04
+#define EXPORT_SYMBOL_FLAGS_REEXPORT 0x08
+#define EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER 0x10
+
+/*
+ * The linker_option_command contains linker options embedded in object files.
+ */
+struct linker_option_command {
+ uint32_t cmd; /* LC_LINKER_OPTION only used in MH_OBJECT filetypes */
+ uint32_t cmdsize;
+ uint32_t count; /* number of strings */
+ /* concatenation of zero terminated UTF8 strings.
+ Zero filled at end to align */
+};
+
+/*
+ * The symseg_command contains the offset and size of the GNU style
+ * symbol table information as described in the header file <symseg.h>.
+ * The symbol roots of the symbol segments must also be aligned properly
+ * in the file. So the requirement of keeping the offsets aligned to a
+ * multiple of a 4 bytes translates to the length field of the symbol
+ * roots also being a multiple of a long. Also the padding must again be
+ * zeroed. (THIS IS OBSOLETE and no longer supported).
+ */
+struct symseg_command {
+ uint32_t cmd; /* LC_SYMSEG */
+ uint32_t cmdsize; /* sizeof(struct symseg_command) */
+ uint32_t offset; /* symbol segment offset */
+ uint32_t size; /* symbol segment size in bytes */
+};
+
+/*
+ * The ident_command contains a free format string table following the
+ * ident_command structure. The strings are null terminated and the size of
+ * the command is padded out with zero bytes to a multiple of 4 bytes/
+ * (THIS IS OBSOLETE and no longer supported).
+ */
+struct ident_command {
+ uint32_t cmd; /* LC_IDENT */
+ uint32_t cmdsize; /* strings that follow this command */
+};
+
+/*
+ * The fvmfile_command contains a reference to a file to be loaded at the
+ * specified virtual address. (Presently, this command is reserved for
+ * internal use. The kernel ignores this command when loading a program into
+ * memory).
+ */
+struct fvmfile_command {
+ uint32_t cmd; /* LC_FVMFILE */
+ uint32_t cmdsize; /* includes pathname string */
+ union lc_str name; /* files pathname */
+ uint32_t header_addr; /* files virtual address */
+};
+
+
+/*
+ * The entry_point_command is a replacement for thread_command.
+ * It is used for main executables to specify the location (file offset)
+ * of main(). If -stack_size was used at link time, the stacksize
+ * field will contain the stack size need for the main thread.
+ */
+struct entry_point_command {
+ uint32_t cmd; /* LC_MAIN only used in MH_EXECUTE filetypes */
+ uint32_t cmdsize; /* 24 */
+ uint64_t entryoff; /* file (__TEXT) offset of main() */
+ uint64_t stacksize;/* if not zero, initial stack size */
+};
+
+
+/*
+ * The source_version_command is an optional load command containing
+ * the version of the sources used to build the binary.
+ */
+struct source_version_command {
+ uint32_t cmd; /* LC_SOURCE_VERSION */
+ uint32_t cmdsize; /* 16 */
+ uint64_t version; /* A.B.C.D.E packed as a24.b10.c10.d10.e10 */
+};
+
+
+/*
+ * The LC_DATA_IN_CODE load commands uses a linkedit_data_command
+ * to point to an array of data_in_code_entry entries. Each entry
+ * describes a range of data in a code section.
+ */
+struct data_in_code_entry {
+ uint32_t offset; /* from mach_header to start of data range*/
+ uint16_t length; /* number of bytes in data range */
+ uint16_t kind; /* a DICE_KIND_* value */
+};
+#define DICE_KIND_DATA 0x0001
+#define DICE_KIND_JUMP_TABLE8 0x0002
+#define DICE_KIND_JUMP_TABLE16 0x0003
+#define DICE_KIND_JUMP_TABLE32 0x0004
+#define DICE_KIND_ABS_JUMP_TABLE32 0x0005
+
+
+
+/*
+ * Sections of type S_THREAD_LOCAL_VARIABLES contain an array
+ * of tlv_descriptor structures.
+ */
+struct tlv_descriptor
+{
+ void* (*thunk)(struct tlv_descriptor*);
+ unsigned long key;
+ unsigned long offset;
+};
+
+/*
+ * LC_NOTE commands describe a region of arbitrary data included in a Mach-O
+ * file. Its initial use is to record extra data in MH_CORE files.
+ */
+struct note_command {
+ uint32_t cmd; /* LC_NOTE */
+ uint32_t cmdsize; /* sizeof(struct note_command) */
+ char data_owner[16]; /* owner name for this LC_NOTE */
+ uint64_t offset; /* file offset of this data */
+ uint64_t size; /* length of data region */
+};
+
+#endif /* _MACHO_LOADER_H_ */
diff --git a/xnu-deps/hostinc/mach-o/nlist.h b/xnu-deps/hostinc/mach-o/nlist.h
new file mode 100644
index 0000000..133e36b
--- /dev/null
+++ b/xnu-deps/hostinc/mach-o/nlist.h
@@ -0,0 +1,318 @@
+/*
+ * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ *
+ * This file contains Original Code and/or Modifications of Original Code
+ * as defined in and that are subject to the Apple Public Source License
+ * Version 2.0 (the 'License'). You may not use this file except in
+ * compliance with the License. Please obtain a copy of the License at
+ * http://www.opensource.apple.com/apsl/ and read it before using this
+ * file.
+ *
+ * The Original Code and all software distributed under the License are
+ * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
+ * Please see the License for the specific language governing rights and
+ * limitations under the License.
+ *
+ * @APPLE_LICENSE_HEADER_END@
+ */
+#ifndef _MACHO_NLIST_H_
+#define _MACHO_NLIST_H_
+/* $NetBSD: nlist.h,v 1.5 1994/10/26 00:56:11 cgd Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ * This product includes software developed by the University of
+ * California, Berkeley and its contributors.
+ * 4. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)nlist.h 8.2 (Berkeley) 1/21/94
+ */
+#include <stdint.h>
+
+/*
+ * Format of a symbol table entry of a Mach-O file for 32-bit architectures.
+ * Modified from the BSD format. The modifications from the original format
+ * were changing n_other (an unused field) to n_sect and the addition of the
+ * N_SECT type. These modifications are required to support symbols in a larger
+ * number of sections not just the three sections (text, data and bss) in a BSD
+ * file.
+ */
+struct nlist {
+ union {
+#ifndef __LP64__
+ char *n_name; /* for use when in-core */
+#endif
+ uint32_t n_strx; /* index into the string table */
+ } n_un;
+ uint8_t n_type; /* type flag, see below */
+ uint8_t n_sect; /* section number or NO_SECT */
+ int16_t n_desc; /* see <mach-o/stab.h> */
+ uint32_t n_value; /* value of this symbol (or stab offset) */
+};
+
+/*
+ * This is the symbol table entry structure for 64-bit architectures.
+ */
+struct nlist_64 {
+ union {
+ uint32_t n_strx; /* index into the string table */
+ } n_un;
+ uint8_t n_type; /* type flag, see below */
+ uint8_t n_sect; /* section number or NO_SECT */
+ uint16_t n_desc; /* see <mach-o/stab.h> */
+ uint64_t n_value; /* value of this symbol (or stab offset) */
+};
+
+/*
+ * Symbols with a index into the string table of zero (n_un.n_strx == 0) are
+ * defined to have a null, "", name. Therefore all string indexes to non null
+ * names must not have a zero string index. This is bit historical information
+ * that has never been well documented.
+ */
+
+/*
+ * The n_type field really contains four fields:
+ * unsigned char N_STAB:3,
+ * N_PEXT:1,
+ * N_TYPE:3,
+ * N_EXT:1;
+ * which are used via the following masks.
+ */
+#define N_STAB 0xe0 /* if any of these bits set, a symbolic debugging entry */
+#define N_PEXT 0x10 /* private external symbol bit */
+#define N_TYPE 0x0e /* mask for the type bits */
+#define N_EXT 0x01 /* external symbol bit, set for external symbols */
+
+/*
+ * Only symbolic debugging entries have some of the N_STAB bits set and if any
+ * of these bits are set then it is a symbolic debugging entry (a stab). In
+ * which case then the values of the n_type field (the entire field) are given
+ * in <mach-o/stab.h>
+ */
+
+/*
+ * Values for N_TYPE bits of the n_type field.
+ */
+#define N_UNDF 0x0 /* undefined, n_sect == NO_SECT */
+#define N_ABS 0x2 /* absolute, n_sect == NO_SECT */
+#define N_SECT 0xe /* defined in section number n_sect */
+#define N_PBUD 0xc /* prebound undefined (defined in a dylib) */
+#define N_INDR 0xa /* indirect */
+
+/*
+ * If the type is N_INDR then the symbol is defined to be the same as another
+ * symbol. In this case the n_value field is an index into the string table
+ * of the other symbol's name. When the other symbol is defined then they both
+ * take on the defined type and value.
+ */
+
+/*
+ * If the type is N_SECT then the n_sect field contains an ordinal of the
+ * section the symbol is defined in. The sections are numbered from 1 and
+ * refer to sections in order they appear in the load commands for the file
+ * they are in. This means the same ordinal may very well refer to different
+ * sections in different files.
+ *
+ * The n_value field for all symbol table entries (including N_STAB's) gets
+ * updated by the link editor based on the value of it's n_sect field and where
+ * the section n_sect references gets relocated. If the value of the n_sect
+ * field is NO_SECT then it's n_value field is not changed by the link editor.
+ */
+#define NO_SECT 0 /* symbol is not in any section */
+#define MAX_SECT 255 /* 1 thru 255 inclusive */
+
+/*
+ * Common symbols are represented by undefined (N_UNDF) external (N_EXT) types
+ * who's values (n_value) are non-zero. In which case the value of the n_value
+ * field is the size (in bytes) of the common symbol. The n_sect field is set
+ * to NO_SECT. The alignment of a common symbol may be set as a power of 2
+ * between 2^1 and 2^15 as part of the n_desc field using the macros below. If
+ * the alignment is not set (a value of zero) then natural alignment based on
+ * the size is used.
+ */
+#define GET_COMM_ALIGN(n_desc) (((n_desc) >> 8) & 0x0f)
+#define SET_COMM_ALIGN(n_desc,align) \
+ (n_desc) = (((n_desc) & 0xf0ff) | (((align) & 0x0f) << 8))
+
+/*
+ * To support the lazy binding of undefined symbols in the dynamic link-editor,
+ * the undefined symbols in the symbol table (the nlist structures) are marked
+ * with the indication if the undefined reference is a lazy reference or
+ * non-lazy reference. If both a non-lazy reference and a lazy reference is
+ * made to the same symbol the non-lazy reference takes precedence. A reference
+ * is lazy only when all references to that symbol are made through a symbol
+ * pointer in a lazy symbol pointer section.
+ *
+ * The implementation of marking nlist structures in the symbol table for
+ * undefined symbols will be to use some of the bits of the n_desc field as a
+ * reference type. The mask REFERENCE_TYPE will be applied to the n_desc field
+ * of an nlist structure for an undefined symbol to determine the type of
+ * undefined reference (lazy or non-lazy).
+ *
+ * The constants for the REFERENCE FLAGS are propagated to the reference table
+ * in a shared library file. In that case the constant for a defined symbol,
+ * REFERENCE_FLAG_DEFINED, is also used.
+ */
+/* Reference type bits of the n_desc field of undefined symbols */
+#define REFERENCE_TYPE 0x7
+/* types of references */
+#define REFERENCE_FLAG_UNDEFINED_NON_LAZY 0
+#define REFERENCE_FLAG_UNDEFINED_LAZY 1
+#define REFERENCE_FLAG_DEFINED 2
+#define REFERENCE_FLAG_PRIVATE_DEFINED 3
+#define REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY 4
+#define REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY 5
+
+/*
+ * To simplify stripping of objects that use are used with the dynamic link
+ * editor, the static link editor marks the symbols defined an object that are
+ * referenced by a dynamicly bound object (dynamic shared libraries, bundles).
+ * With this marking strip knows not to strip these symbols.
+ */
+#define REFERENCED_DYNAMICALLY 0x0010
+
+/*
+ * For images created by the static link editor with the -twolevel_namespace
+ * option in effect the flags field of the mach header is marked with
+ * MH_TWOLEVEL. And the binding of the undefined references of the image are
+ * determined by the static link editor. Which library an undefined symbol is
+ * bound to is recorded by the static linker in the high 8 bits of the n_desc
+ * field using the SET_LIBRARY_ORDINAL macro below. The ordinal recorded
+ * references the libraries listed in the Mach-O's LC_LOAD_DYLIB,
+ * LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB, LC_LOAD_UPWARD_DYLIB, and
+ * LC_LAZY_LOAD_DYLIB, etc. load commands in the order they appear in the
+ * headers. The library ordinals start from 1.
+ * For a dynamic library that is built as a two-level namespace image the
+ * undefined references from module defined in another use the same nlist struct
+ * an in that case SELF_LIBRARY_ORDINAL is used as the library ordinal. For
+ * defined symbols in all images they also must have the library ordinal set to
+ * SELF_LIBRARY_ORDINAL. The EXECUTABLE_ORDINAL refers to the executable
+ * image for references from plugins that refer to the executable that loads
+ * them.
+ *
+ * The DYNAMIC_LOOKUP_ORDINAL is for undefined symbols in a two-level namespace
+ * image that are looked up by the dynamic linker with flat namespace semantics.
+ * This ordinal was added as a feature in Mac OS X 10.3 by reducing the
+ * value of MAX_LIBRARY_ORDINAL by one. So it is legal for existing binaries
+ * or binaries built with older tools to have 0xfe (254) dynamic libraries. In
+ * this case the ordinal value 0xfe (254) must be treated as a library ordinal
+ * for compatibility.
+ */
+#define GET_LIBRARY_ORDINAL(n_desc) (((n_desc) >> 8) & 0xff)
+#define SET_LIBRARY_ORDINAL(n_desc,ordinal) \
+ (n_desc) = (((n_desc) & 0x00ff) | (((ordinal) & 0xff) << 8))
+#define SELF_LIBRARY_ORDINAL 0x0
+#define MAX_LIBRARY_ORDINAL 0xfd
+#define DYNAMIC_LOOKUP_ORDINAL 0xfe
+#define EXECUTABLE_ORDINAL 0xff
+
+/*
+ * The bit 0x0020 of the n_desc field is used for two non-overlapping purposes
+ * and has two different symbolic names, N_NO_DEAD_STRIP and N_DESC_DISCARDED.
+ */
+
+/*
+ * The N_NO_DEAD_STRIP bit of the n_desc field only ever appears in a
+ * relocatable .o file (MH_OBJECT filetype). And is used to indicate to the
+ * static link editor it is never to dead strip the symbol.
+ */
+#define N_NO_DEAD_STRIP 0x0020 /* symbol is not to be dead stripped */
+
+/*
+ * The N_DESC_DISCARDED bit of the n_desc field never appears in linked image.
+ * But is used in very rare cases by the dynamic link editor to mark an in
+ * memory symbol as discared and longer used for linking.
+ */
+#define N_DESC_DISCARDED 0x0020 /* symbol is discarded */
+
+/*
+ * The N_WEAK_REF bit of the n_desc field indicates to the dynamic linker that
+ * the undefined symbol is allowed to be missing and is to have the address of
+ * zero when missing.
+ */
+#define N_WEAK_REF 0x0040 /* symbol is weak referenced */
+
+/*
+ * The N_WEAK_DEF bit of the n_desc field indicates to the static and dynamic
+ * linkers that the symbol definition is weak, allowing a non-weak symbol to
+ * also be used which causes the weak definition to be discared. Currently this
+ * is only supported for symbols in coalesed sections.
+ */
+#define N_WEAK_DEF 0x0080 /* coalesed symbol is a weak definition */
+
+/*
+ * The N_REF_TO_WEAK bit of the n_desc field indicates to the dynamic linker
+ * that the undefined symbol should be resolved using flat namespace searching.
+ */
+#define N_REF_TO_WEAK 0x0080 /* reference to a weak symbol */
+
+/*
+ * The N_ARM_THUMB_DEF bit of the n_desc field indicates that the symbol is
+ * a defintion of a Thumb function.
+ */
+#define N_ARM_THUMB_DEF 0x0008 /* symbol is a Thumb function (ARM) */
+
+/*
+ * The N_SYMBOL_RESOLVER bit of the n_desc field indicates that the
+ * that the function is actually a resolver function and should
+ * be called to get the address of the real function to use.
+ * This bit is only available in .o files (MH_OBJECT filetype)
+ */
+#define N_SYMBOL_RESOLVER 0x0100
+
+/*
+ * The N_ALT_ENTRY bit of the n_desc field indicates that the
+ * symbol is pinned to the previous content.
+ */
+#define N_ALT_ENTRY 0x0200
+
+#ifndef __STRICT_BSD__
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+/*
+ * The function nlist(3) from the C library.
+ */
+extern int nlist (const char *filename, struct nlist *list);
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __STRICT_BSD__ */
+
+#endif /* _MACHO_LIST_H_ */
diff --git a/xnu-deps/hostinc/mach-o/swap.h b/xnu-deps/hostinc/mach-o/swap.h
new file mode 100644
index 0000000..85edc26
--- /dev/null
+++ b/xnu-deps/hostinc/mach-o/swap.h
@@ -0,0 +1,23 @@
+/* Host and target are both little-endian: swapping is never needed. */
+#ifndef HOST_MACHO_SWAP_H
+#define HOST_MACHO_SWAP_H
+#include <mach-o/loader.h>
+#include <mach-o/nlist.h>
+#include <mach-o/fat.h>
+#include <architecture/byte_order.h>
+#include <stdlib.h>
+#define HOST_SWAP_STUB(name, ...) static inline void name(__VA_ARGS__) { abort(); }
+HOST_SWAP_STUB(swap_mach_header, struct mach_header *h, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_mach_header_64, struct mach_header_64 *h, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_segment_command, struct segment_command *h, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_segment_command_64, struct segment_command_64 *h, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_section, struct section *h, uint32_t n, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_section_64, struct section_64 *h, uint32_t n, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_symtab_command, struct symtab_command *h, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_uuid_command, struct uuid_command *h, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_load_command, struct load_command *h, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_nlist, struct nlist *h, uint32_t n, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_nlist_64, struct nlist_64 *h, uint32_t n, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_fat_header, struct fat_header *h, enum NXByteOrder o)
+HOST_SWAP_STUB(swap_fat_arch, struct fat_arch *h, uint32_t n, enum NXByteOrder o)
+#endif
diff --git a/xnu-deps/hostinc/mach/mach_init.h b/xnu-deps/hostinc/mach/mach_init.h
new file mode 100644
index 0000000..aa44e50
--- /dev/null
+++ b/xnu-deps/hostinc/mach/mach_init.h
@@ -0,0 +1,7 @@
+#ifndef HOST_MACH_INIT_H
+#define HOST_MACH_INIT_H
+#include <unistd.h>
+#include <stdint.h>
+#define mach_vm_round_page(x) (((uint64_t)(x) + 4095ULL) & ~4095ULL)
+#define round_page(x) mach_vm_round_page(x)
+#endif
diff --git a/xnu-deps/hostinc/mach/machine.h b/xnu-deps/hostinc/mach/machine.h
new file mode 100644
index 0000000..78c48ba
--- /dev/null
+++ b/xnu-deps/hostinc/mach/machine.h
@@ -0,0 +1,18 @@
+#ifndef HOST_MACH_MACHINE_H
+#define HOST_MACH_MACHINE_H
+#include <stdint.h>
+typedef int integer_t;
+typedef integer_t cpu_type_t;
+typedef integer_t cpu_subtype_t;
+typedef integer_t cpu_threadtype_t;
+#define CPU_ARCH_ABI64 0x01000000
+#define CPU_TYPE_X86 7
+#define CPU_TYPE_I386 CPU_TYPE_X86
+#define CPU_TYPE_X86_64 (CPU_TYPE_X86 | CPU_ARCH_ABI64)
+#define CPU_TYPE_ARM 12
+#define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64)
+#define CPU_SUBTYPE_X86_64_ALL 3
+#define CPU_SUBTYPE_ARM64_ALL 0
+#define CPU_SUBTYPE_ARM64E 2
+#define CPU_SUBTYPE_MASK 0xff000000
+#endif
diff --git a/xnu-deps/hostinc/mach/machine/thread_status.h b/xnu-deps/hostinc/mach/machine/thread_status.h
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/xnu-deps/hostinc/mach/machine/thread_status.h
@@ -0,0 +1 @@
+
diff --git a/xnu-deps/hostinc/mach/vm_prot.h b/xnu-deps/hostinc/mach/vm_prot.h
new file mode 100644
index 0000000..694890a
--- /dev/null
+++ b/xnu-deps/hostinc/mach/vm_prot.h
@@ -0,0 +1,8 @@
+#ifndef HOST_MACH_VM_PROT_H
+#define HOST_MACH_VM_PROT_H
+typedef int vm_prot_t;
+#define VM_PROT_NONE 0
+#define VM_PROT_READ 1
+#define VM_PROT_WRITE 2
+#define VM_PROT_EXECUTE 4
+#endif
diff --git a/xnu-deps/hostinc/xnu_clang_compat.h b/xnu-deps/hostinc/xnu_clang_compat.h
new file mode 100644
index 0000000..dd781d3
--- /dev/null
+++ b/xnu-deps/hostinc/xnu_clang_compat.h
@@ -0,0 +1,21 @@
+/*
+ * Force-included into every XNU translation unit when building with stock
+ * (non-Apple) clang. Apple's clang has builtins that describe the pointer/data
+ * layout of a type for kalloc_type; upstream clang lacks them, so every type
+ * is conservatively described as "mixed pointers and data".
+ */
+#ifndef XNU_CLANG_COMPAT_H
+#define XNU_CLANG_COMPAT_H
+#if !defined(ASSEMBLER) && !defined(__ASSEMBLER__)
+#if !__has_builtin(__builtin_xnu_type_signature)
+#define XNU_NO_TYPE_BUILTINS 1
+#define __builtin_xnu_type_signature(type) "12"
+#define __builtin_xnu_type_summary(type) ((1U << 1) | (1U << 2))
+#ifdef __cplusplus
+#define __builtin_xnu_types_compatible(a, b) __is_same(a, b)
+#else
+#define __builtin_xnu_types_compatible(a, b) __builtin_types_compatible_p(a, b)
+#endif
+#endif
+#endif
+#endif
diff --git a/xnu-deps/iig-impl/OSObject.iig.cpp b/xnu-deps/iig-impl/OSObject.iig.cpp
new file mode 100644
index 0000000..02053f0
--- /dev/null
+++ b/xnu-deps/iig-impl/OSObject.iig.cpp
@@ -0,0 +1,140 @@
+/* Generated by gen-iig-stubs.py: stand-in for iig output. Do not edit. */
+#include <IOKit/IOLib.h>
+#include <IOKit/IOReturn.h>
+#include <IOKit/IOService.h>
+#include <IOKit/IOUserClient.h>
+#include <IOKit/IOUserServer.h>
+#include <DriverKit/IODispatchSource.h>
+#include <DriverKit/IODispatchQueue.h>
+#include <DriverKit/IOEventLink.h>
+#include <DriverKit/IOWorkGroup.h>
+#include <DriverKit/OSAction.h>
+#include <DriverKit/IODataQueueDispatchSource.h>
+#include <DriverKit/IOInterruptDispatchSource.h>
+#include <DriverKit/IOServiceNotificationDispatchSource.h>
+#include <DriverKit/IOServiceStateNotificationDispatchSource.h>
+
+OSDefineMetaClassAndAbstractStructors(IODispatchSource, OSObject);
+OSDefineMetaClassAndStructors(IOEventLink, OSObject);
+OSDefineMetaClassAndStructors(IOWorkGroup, OSObject);
+OSDefineMetaClassAndStructors(IODispatchQueue, OSObject);
+OSDefineMetaClassAndStructors(OSAction, OSObject);
+OSDefineMetaClassAndStructors(IODataQueueDispatchSource, IODispatchSource);
+OSDefineMetaClassAndStructors(IOInterruptDispatchSource, IODispatchSource);
+OSDefineMetaClassAndStructors(IOServiceNotificationDispatchSource, IODispatchSource);
+OSDefineMetaClassAndStructors(IOServiceStateNotificationDispatchSource, IODispatchSource);
+
+/* wrappers forwarded straight to their kernel implementation */
+__asm__(".text\n.globl __ZN11IOEventLink16SetEventlinkPortEP8ipc_portPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN11IOEventLink16SetEventlinkPortEP8ipc_portPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN11IOEventLink21SetEventlinkPort_ImplEP8ipc_port\n");
+__asm__(".text\n.globl __ZN11IOWorkGroup16SetWorkGroupPortEP8ipc_portPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN11IOWorkGroup16SetWorkGroupPortEP8ipc_portPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN11IOWorkGroup21SetWorkGroupPort_ImplEP8ipc_port\n");
+__asm__(".text\n.globl __ZN12IODMACommand11CompleteDMAEyPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN12IODMACommand11CompleteDMAEyPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN12IODMACommand16CompleteDMA_ImplEy\n");
+__asm__(".text\n.globl __ZN12IOUserClient15_ExternalMethodEyPKyjP6OSDataP18IOMemoryDescriptorPyPjyPS3_S5_P8OSActionPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN12IOUserClient15_ExternalMethodEyPKyjP6OSDataP18IOMemoryDescriptorPyPjyPS3_S5_P8OSActionPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN12IOUserClient20_ExternalMethod_ImplEyPKyjP6OSDataP18IOMemoryDescriptorPyPjyPS3_S5_P8OSAction\n");
+__asm__(".text\n.globl __ZN12IOUserServer10LoadModuleEPKcPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN12IOUserServer10LoadModuleEPKcPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN12IOUserServer15LoadModule_ImplEPKc\n");
+__asm__(".text\n.globl __ZN12IOUserServer4ExitEPKcPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN12IOUserServer4ExitEPKcPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN12IOUserServer9Exit_ImplEPKc\n");
+__asm__(".text\n.globl __ZN25IODataQueueDispatchSource23CopyDataServicedHandlerEPP8OSActionPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN25IODataQueueDispatchSource23CopyDataServicedHandlerEPP8OSActionPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN25IODataQueueDispatchSource28CopyDataServicedHandler_ImplEPP8OSAction\n");
+__asm__(".text\n.globl __ZN25IODataQueueDispatchSource24CopyDataAvailableHandlerEPP8OSActionPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN25IODataQueueDispatchSource24CopyDataAvailableHandlerEPP8OSActionPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN25IODataQueueDispatchSource29CopyDataAvailableHandler_ImplEPP8OSAction\n");
+__asm__(".text\n.globl __ZN8OSAction7AbortedEPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN8OSAction7AbortedEPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN8OSAction12Aborted_ImplEv\n");
+__asm__(".text\n.globl __ZN9IOService10Stop_asyncEPS_PFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService10Stop_asyncEPS_PFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService15Stop_async_ImplEPS_\n");
+__asm__(".text\n.globl __ZN9IOService12UpdateReportEP6OSDatajPjyyP18IOMemoryDescriptorPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService12UpdateReportEP6OSDatajPjyyP18IOMemoryDescriptorPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService17UpdateReport_ImplEP6OSDatajPjyyP18IOMemoryDescriptor\n");
+__asm__(".text\n.globl __ZN9IOService13ClientCrashedEPS_yPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService13ClientCrashedEPS_yPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService18ClientCrashed_ImplEPS_y\n");
+__asm__(".text\n.globl __ZN9IOService13SetPowerStateEjPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService13SetPowerStateEjPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService18SetPowerState_ImplEj\n");
+__asm__(".text\n.globl __ZN9IOService14_NewUserClientEjP12OSDictionaryPP12IOUserClientPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService14_NewUserClientEjP12OSDictionaryPP12IOUserClientPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService19_NewUserClient_ImplEjP12OSDictionaryPP12IOUserClient\n");
+__asm__(".text\n.globl __ZN9IOService15ConfigureReportEP6OSDatajPjPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService15ConfigureReportEP6OSDatajPjPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService20ConfigureReport_ImplEP6OSDatajPj\n");
+__asm__(".text\n.globl __ZN9IOService17UserSetPropertiesEP8OSObjectPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService17UserSetPropertiesEP8OSObjectPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService22UserSetProperties_ImplEP8OSObject\n");
+__asm__(".text\n.globl __ZN9IOService24StateNotificationItemSetEP8OSStringP12OSDictionaryPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService24StateNotificationItemSetEP8OSStringP12OSDictionaryPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService29StateNotificationItemSet_ImplEP8OSStringP12OSDictionary\n");
+__asm__(".text\n.globl __ZN9IOService25StateNotificationItemCopyEP8OSStringPP12OSDictionaryPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService25StateNotificationItemCopyEP8OSStringPP12OSDictionaryPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService30StateNotificationItemCopy_ImplEP8OSStringPP12OSDictionary\n");
+__asm__(".text\n.globl __ZN9IOService27StateNotificationItemCreateEP8OSStringP12OSDictionaryPFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService27StateNotificationItemCreateEP8OSStringP12OSDictionaryPFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService32StateNotificationItemCreate_ImplEP8OSStringP12OSDictionary\n");
+__asm__(".text\n.globl __ZN9IOService4StopEPS_PFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService4StopEPS_PFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService9Stop_ImplEPS_\n");
+__asm__(".text\n.globl __ZN9IOService5StartEPS_PFiP15OSMetaClassBase5IORPCE\n.p2align 2\n__ZN9IOService5StartEPS_PFiP15OSMetaClassBase5IORPCE:\n\tb __ZN9IOService10Start_ImplEPS_\n");
+
+/* everything else (RPC dispatch, user-space-only methods) is not available */
+extern "C" {
+kern_return_t __iig_stub_0(void) __asm__("__ZN11IOEventLink8DispatchE5IORPC");
+kern_return_t __iig_stub_0(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_1(void) __asm__("__ZN11IOEventLink9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_1(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_2(void) __asm__("__ZN11IOMemoryMap8DispatchE5IORPC");
+kern_return_t __iig_stub_2(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_3(void) __asm__("__ZN11IOMemoryMap9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_3(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_4(void) __asm__("__ZN11IOWorkGroup8DispatchE5IORPC");
+kern_return_t __iig_stub_4(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_5(void) __asm__("__ZN11IOWorkGroup9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_5(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_6(void) __asm__("__ZN12IODMACommand8DispatchE5IORPC");
+kern_return_t __iig_stub_6(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_7(void) __asm__("__ZN12IODMACommand9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_7(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_8(void) __asm__("__ZN12IOUserClient23CopyClientMemoryForTypeEyPyPP18IOMemoryDescriptorPFiP15OSMetaClassBase5IORPCE");
+kern_return_t __iig_stub_8(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_9(void) __asm__("__ZN12IOUserClient28CreateActionKernelCompletionEmPP8OSAction");
+kern_return_t __iig_stub_9(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_10(void) __asm__("__ZN12IOUserClient8DispatchE5IORPC");
+kern_return_t __iig_stub_10(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_11(void) __asm__("__ZN12IOUserClient9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_11(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_12(void) __asm__("__ZN12IOUserServer8DispatchE5IORPC");
+kern_return_t __iig_stub_12(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_13(void) __asm__("__ZN12IOUserServer9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_13(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_14(void) __asm__("__ZN15IODispatchQueue8DispatchE5IORPC");
+kern_return_t __iig_stub_14(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_15(void) __asm__("__ZN15IODispatchQueue9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_15(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_16(void) __asm__("__ZN16IODispatchSource23SetEnableWithCompletionEbU13block_pointerFvvEPFiP15OSMetaClassBase5IORPCE");
+kern_return_t __iig_stub_16(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_17(void) __asm__("__ZN16IODispatchSource8DispatchE5IORPC");
+kern_return_t __iig_stub_17(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_18(void) __asm__("__ZN16IODispatchSource9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_18(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_19(void) __asm__("__ZN18IOMemoryDescriptor8DispatchE5IORPC");
+kern_return_t __iig_stub_19(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_20(void) __asm__("__ZN18IOMemoryDescriptor9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_20(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_21(void) __asm__("__ZN24IOBufferMemoryDescriptor8DispatchE5IORPC");
+kern_return_t __iig_stub_21(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_22(void) __asm__("__ZN24IOBufferMemoryDescriptor9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_22(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_23(void) __asm__("__ZN25IODataQueueDispatchSource12DataServicedEP8OSActionPFiP15OSMetaClassBase5IORPCE");
+kern_return_t __iig_stub_23(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_24(void) __asm__("__ZN25IODataQueueDispatchSource13DataAvailableEP8OSActionPFiP15OSMetaClassBase5IORPCE");
+kern_return_t __iig_stub_24(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_25(void) __asm__("__ZN25IODataQueueDispatchSource6CreateEyP15IODispatchQueuePPS_");
+kern_return_t __iig_stub_25(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_26(void) __asm__("__ZN25IODataQueueDispatchSource8DispatchE5IORPC");
+kern_return_t __iig_stub_26(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_27(void) __asm__("__ZN25IODataQueueDispatchSource9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_27(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_28(void) __asm__("__ZN25IOInterruptDispatchSource17InterruptOccurredE5IORPCP8OSActionyyPFiP15OSMetaClassBaseS0_E");
+kern_return_t __iig_stub_28(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_29(void) __asm__("__ZN25IOInterruptDispatchSource8DispatchE5IORPC");
+kern_return_t __iig_stub_29(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_30(void) __asm__("__ZN25IOInterruptDispatchSource9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_30(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_31(void) __asm__("__ZN35IOServiceNotificationDispatchSource24ServiceNotificationReadyEP8OSActionPFiP15OSMetaClassBase5IORPCE");
+kern_return_t __iig_stub_31(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_32(void) __asm__("__ZN35IOServiceNotificationDispatchSource8DispatchE5IORPC");
+kern_return_t __iig_stub_32(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_33(void) __asm__("__ZN35IOServiceNotificationDispatchSource9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_33(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_34(void) __asm__("__ZN40IOServiceStateNotificationDispatchSource22StateNotificationReadyEP8OSActionPFiP15OSMetaClassBase5IORPCE");
+kern_return_t __iig_stub_34(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_35(void) __asm__("__ZN40IOServiceStateNotificationDispatchSource8DispatchE5IORPC");
+kern_return_t __iig_stub_35(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_36(void) __asm__("__ZN40IOServiceStateNotificationDispatchSource9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_36(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_37(void) __asm__("__ZN8OSAction8DispatchE5IORPC");
+kern_return_t __iig_stub_37(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_38(void) __asm__("__ZN8OSAction9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_38(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_39(void) __asm__("__ZN8OSObject17CopyDispatchQueueEPKcPP15IODispatchQueuePFiP15OSMetaClassBase5IORPCE");
+kern_return_t __iig_stub_39(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_40(void) __asm__("__ZN8OSObject8DispatchE5IORPC");
+kern_return_t __iig_stub_40(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_41(void) __asm__("__ZN8OSObject9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_41(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_42(void) __asm__("__ZN9IOService8DispatchE5IORPC");
+kern_return_t __iig_stub_42(void) { return kIOReturnUnsupported; }
+kern_return_t __iig_stub_43(void) __asm__("__ZN9IOService9MetaClass8DispatchE5IORPC");
+kern_return_t __iig_stub_43(void) { return kIOReturnUnsupported; }
+}
diff --git a/xnu-deps/setup.sh b/xnu-deps/setup.sh
new file mode 100755
index 0000000..dbedc32
--- /dev/null
+++ b/xnu-deps/setup.sh
@@ -0,0 +1,198 @@
+#!/bin/bash
+# Everything the kernel build needs that this repository does not carry: open sources of
+# Apple's and others' that are fetched and built here, and the SDK the kernel is compiled
+# against. What is already there is left alone, so this can be run again at any time.
+#
+# xnu-deps/setup.sh both stages (the second only once the kernel tree exists)
+# xnu-deps/setup.sh --stage1 sources, host tools, the SDK
+# xnu-deps/setup.sh --stage2 the two static libraries that are compiled against the
+# kernel's own exported headers (needs xnu/apply.sh first)
+# xnu-deps/setup.sh --rebuild-libs stage 2 again from scratch (after the kernel headers changed)
+#
+# Needs on the machine: git curl tar xz make cc clang flex bison m4 perl python3 autoconf
+# automake, and theos ($THEOS, default ~/theos) with its Linux toolchain
+# (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
+# 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
+# host/bin mig, migcom, unifdef, tcsh, csh, unzbm, and links
+# to the cctools (next to our own wrappers)
+# sdk/iPhoneOS16.5.xnu.sdk the theos SDK (as links) plus usr/local: what
+# Apple's internal SDK has and the public one lacks
+set -e -o pipefail
+HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+source "$HERE/../xnu-env.sh"
+cd "$XNUDEPS"
+JOBS=${JOBS:-$(nproc)}
+CCTOOLS=$THEOS/toolchain/linux/iphone/bin
+IOS_SDK=$THEOS/sdks/iPhoneOS16.5.sdk
+MACOS_SDK_URL=https://github.com/joseluisq/macosx-sdks/releases/download/13.3/MacOSX13.3.sdk.tar.xz
+
+log() { echo "setup: $*"; }
+die() { echo "setup: $*" >&2; exit 1; }
+
+# fetch DIR URL COMMIT: one commit of a repository, without its history
+fetch() {
+ git -C "$1" rev-parse -q --verify HEAD >/dev/null 2>&1 && [ "$(git -C "$1" rev-parse --show-toplevel)" = "$XNUDEPS/$1" ] && return 0
+ log "fetching $1"
+ rm -rf "$1"
+ git init -q "$1"
+ git -C "$1" remote add origin "$2"
+ git -C "$1" fetch -q --depth 1 origin "$3" || die "cannot fetch $3 from $2"
+ git -C "$1" -c advice.detachedHead=false checkout -q FETCH_HEAD
+}
+
+# link TARGET NAME: a symbolic link, made only when it is not there already
+link() {
+ [ "$(readlink "$2" 2>/dev/null)" = "$1" ] || ln -sfn "$1" "$2"
+}
+
+# replace FILE with what is on standard input, unless it is the same already (make looks at time stamps)
+update() {
+ cat > "$1.new"
+ if cmp -s "$1.new" "$1"; then rm "$1.new"; else mv "$1.new" "$1"; fi
+}
+
+stage1() {
+ local missing= tool
+ for tool in git curl tar xz make cc clang clang++ flex bison m4 perl python3 autoreconf automake; do
+ command -v $tool >/dev/null || missing="$missing $tool"
+ 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)"
+
+ # --- sources -------------------------------------------------------------------------------
+ fetch AvailabilityVersions https://github.com/apple-oss-distributions/AvailabilityVersions.git \
+ 5d9baee345b3bc72b26c71adc65f94f2d5e9ced2 # AvailabilityVersions-115.4
+ fetch libdispatch https://github.com/apple-oss-distributions/libdispatch.git \
+ a641558f447659d90ad002ef0ee6f0212273fbfc # libdispatch-1415.100.11
+ fetch libpthread https://github.com/apple-oss-distributions/libpthread.git \
+ a6c70ca0e544347a0377babf748f831577ec24f9 # libpthread-514.100.2
+ fetch mm_bootstrap_cmds https://github.com/markmentovai/bootstrap_cmds \
+ f337e600741638896fb6056ce87c6479f74b89a3 # cross_platform/bootstrap_cmds-138
+ fetch tcsh https://github.com/tcsh-org/tcsh.git b7db07931546178c4cb2542b5fc850c483628ed5
+ fetch unifdef https://github.com/fanf2/unifdef.git 08d12cd3059fe072929ea001ad9833f5487fd355
+
+ # Apple's iig (the DriverKit interface generator) is closed. host/bin/iig hands out the headers it
+ # would generate, which the macOS SDK of the same XNU release ships ready-made.
+ if [ ! -d MacOSX13.3.sdk/System/Library/Frameworks/Kernel.framework/Headers/DriverKit ]; then
+ log "downloading the macOS 13.3 SDK for its DriverKit headers"
+ curl -L --fail --retry 3 -s -o macos-sdk.tar.xz "$MACOS_SDK_URL" || die "download failed: $MACOS_SDK_URL"
+ tar -xJf macos-sdk.tar.xz --wildcards '*MacOSX13.3.sdk/System/Library/Frameworks/Kernel.framework*' ||
+ die "cannot unpack the macOS SDK"
+ rm -f macos-sdk.tar.xz
+ fi
+
+ # --- host tools ----------------------------------------------------------------------------
+ mkdir -p host/bin
+ # mig: Apple's own does not build on glibc; this is a port that does
+ if [ ! -x host/bin/migcom ] || [ ! -x host/bin/mig ]; then
+ log "building mig"
+ (cd mm_bootstrap_cmds && autoreconf --install && sh configure --prefix="$XNUDEPS/host" &&
+ make -j$JOBS && make install) > mig-build.log 2>&1 || die "mig did not build, see xnu-deps/mig-build.log"
+ fi
+ if [ ! -x host/bin/unifdef ]; then
+ log "building unifdef"
+ # its makefile takes the version from the git history; any text will do
+ [ -f unifdef/version.h ] || printf '"@(#) $Version: unifdef-2.12 $\\n"\n"@(#) $Date: 2020-11-06 11:22:51 +0000 $\\n"\n' > unifdef/version.h
+ # gnu11: "constexpr", a variable name in unifdef.c, is a keyword in C23
+ cc -std=gnu11 -O2 -w -o host/bin/unifdef unifdef/unifdef.c
+ fi
+ # csh: XNU's SETUP/config/doconf is a csh script
+ if [ ! -x host/bin/tcsh ]; then
+ log "building tcsh"
+ (cd tcsh && ./configure --prefix="$XNUDEPS/host" && make -j$JOBS) > tcsh-build.log 2>&1 ||
+ die "tcsh did not build, see xnu-deps/tcsh-build.log"
+ cp tcsh/tcsh host/bin/tcsh
+ fi
+ link tcsh host/bin/csh
+ # what 7z leaves undone when it extracts files of the iOS images (see build/lzbitmap/unzbm.c)
+ if [ ! -x host/bin/unzbm ]; then
+ cc -O2 -w -o host/bin/unzbm build/lzbitmap/unzbm.c build/lzbitmap/libzbitmap.c
+ fi
+ # the Mach-O linker and its companions come with theos
+ for tool in nm otool strip lipo libtool nmedit ctf_insert codesign_allocate install_name_tool; do
+ link "$CCTOOLS/$tool" host/bin/$tool
+ done
+ link "$CCTOOLS/ld" host/bin/ld64
+ link xnu-clang host/bin/xnu-clang++
+
+ # --- the SDK -------------------------------------------------------------------------------
+ # The makefiles ask xcrun (ours: host/bin/xcrun) for an SDK and a platform directory.
+ mkdir -p sdk/Platforms/iPhoneOS.platform
+ if [ ! -d "$XNU_SDK_PATH/usr/include" ]; then
+ log "making the SDK: links to $IOS_SDK"
+ rm -rf "$XNU_SDK_PATH"
+ cp -rs "$(cd "$IOS_SDK" && pwd)" "$XNU_SDK_PATH"
+ fi
+ local sdk_local=$XNU_SDK_PATH/usr/local
+ mkdir -p $sdk_local/include/kernel/os $sdk_local/include/os $sdk_local/lib/kernel $sdk_local/libexec
+ update $sdk_local/libexec/availability.pl < AvailabilityVersions/availability.pl
+ [ -x $sdk_local/libexec/availability.pl ] || chmod +x $sdk_local/libexec/availability.pl
+ # the kernel's half of a private libdispatch header (unifdef exits with 1 when it removed something)
+ { host/bin/unifdef -DOS_FIREHOSE_SPI=1 -DKERNEL=1 libdispatch/os/firehose_buffer_private.h || [ $? -eq 1 ]; } |
+ update $sdk_local/include/kernel/os/firehose_buffer_private.h
+ update $sdk_local/include/kernel/os/firehose_types.defs < libdispatch/src/firehose/firehose_types.defs
+ log "stage 1 done"
+}
+
+# The firehose (os_log) buffer code of libdispatch and the pthread kernel extension are open
+# source but not part of XNU: Apple links the first from its internal SDK and loads the second
+# as a kext. Here both become static libraries in the SDK (makedefs/MakeInc.def links them into
+# the kernel). They are compiled against the headers the kernel build exports, so that step
+# of the kernel build comes first.
+stage2() {
+ [ -f "$XNU_SRC/makedefs/MakeInc.def" ] || die "no kernel tree in $XNU_SRC (xnu/apply.sh makes it)"
+ [ -x host/bin/migcom ] && [ -d "$XNU_SDK_PATH/usr/local/lib/kernel" ] || die "stage 1 has not been done"
+ local lib=$XNU_SDK_PATH/usr/local/lib/kernel hdrs=$XNU_SRC/BUILD/obj/EXPORT_HDRS file
+ # three Mach-O headers for the build tools the kernel build compiles for this machine (SETUP/)
+ mkdir -p hostinc/mach-o
+ for file in loader.h nlist.h fat.h; do
+ [ -f hostinc/mach-o/$file ] || cp "$XNU_SRC/EXTERNAL_HEADERS/mach-o/$file" hostinc/mach-o/
+ done
+ if [ -n "$REBUILD_LIBS" ]; then rm -f $lib/libfirehose_kernel.a $lib/libpthread_kext.a; fi
+ if [ -f $lib/libfirehose_kernel.a ] && [ -f $lib/libpthread_kext.a ]; then
+ log "stage 2: nothing to do"
+ return 0
+ fi
+ log "exporting the kernel's headers (xnu-build.sh exporthdrs)"
+ "$DARWIN_REDWOOD/xnu-build.sh" -j$JOBS exporthdrs > exporthdrs.log 2>&1 && [ -d "$hdrs/osfmk" ] ||
+ die "the kernel headers were not exported, see xnu-deps/exporthdrs.log"
+ if [ ! -f $lib/libfirehose_kernel.a ]; then
+ log "building libfirehose_kernel.a"
+ mkdir -p build/firehose
+ xnu-clang -arch arm64 -c -Os -mkernel -nostdinc -fno-builtin \
+ -DKERNEL=1 -DKERNEL_PRIVATE=1 -DXNU_KERNEL_PRIVATE=0 -DPRIVATE=1 -D__DARWIN_64_BIT_INO_T=1 \
+ -DDISPATCH_USE_DTRACE=0 -DOS_ATOMIC_CONFIG_MEMORY_ORDER_DEPENDENCY=1 \
+ -DOS_ATOMIC_CONFIG_STARVATION_FREE_ONLY=0 -DOS_FIREHOSE_SPI=1 -DARM64_BOARD_CONFIG_BCM2837 \
+ -Ilibdispatch -Ilibdispatch/src -Ilibdispatch/src/firehose \
+ -I$hdrs/osfmk -I$hdrs/bsd -I$hdrs/libkern -I$hdrs/pexpert -I$hdrs/iokit -I$hdrs/security \
+ -I$XNU_SRC/libkern/firehose -I$hdrs/libkern/os -I$XNU_SRC/EXTERNAL_HEADERS \
+ -I$XNU_SDK_PATH/usr/local/include/kernel \
+ -o build/firehose/firehose_buffer.o libdispatch/src/firehose/firehose_buffer.c
+ libtool -static -o $lib/libfirehose_kernel.a build/firehose/firehose_buffer.o
+ fi
+ if [ ! -f $lib/libpthread_kext.a ]; then
+ log "building libpthread_kext.a"
+ build/pthread/build.sh
+ fi
+ log "stage 2 done; now: ./xnu-build.sh -j$JOBS -k"
+}
+
+case "$1" in
+--stage1) stage1 ;;
+--stage2) stage2 ;;
+--rebuild-libs) REBUILD_LIBS=1 stage2 ;;
+"")
+ stage1
+ if [ -f "$XNU_SRC/makedefs/MakeInc.def" ]; then
+ stage2
+ else
+ log "no kernel tree yet: run xnu/apply.sh, then this script again"
+ fi ;;
+*) sed -n '2,12p' "$HERE/setup.sh"; exit 1 ;;
+esac
diff --git a/xnu-env.sh b/xnu-env.sh
new file mode 100644
index 0000000..f2c6b83
--- /dev/null
+++ b/xnu-env.sh
@@ -0,0 +1,12 @@
+# 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_REDWOOD=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+export DARWIN_REDWOOD
+export THEOS=${THEOS:-$HOME/theos}
+export XNU_SRC=${XNU_SRC:-$DARWIN_REDWOOD/xnu-src/xnu-8796.121.2}
+export XNUDEPS=$DARWIN_REDWOOD/xnu-deps
+export PATH=$XNUDEPS/host/bin:$PATH
+export XNU_SDK_PATH=$XNUDEPS/sdk/iPhoneOS16.5.xnu.sdk
+export XNU_SDK_VERSION=16.5
+export XNU_PLATFORM_PATH=$XNUDEPS/sdk/Platforms/iPhoneOS.platform
diff --git a/xnu/apply.sh b/xnu/apply.sh
new file mode 100755
index 0000000..55ce722
--- /dev/null
+++ b/xnu/apply.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# Get Apple's XNU sources (the release that iOS 16.5 was built from) and put the redwood
+# work on top of them: redwood.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 clone
+# that has the tag will do: XNU_URL=file:///path/to/xnu)
+# The result is a git tree on the branch "redwood" with the work uncommitted, which is how
+# xnu/export.sh expects to find it. A directory that already exists is left alone.
+set -e
+HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+DIR=${1:-${XNU_SRC:-$HERE/../xnu-src/xnu-8796.121.2}}
+URL=${XNU_URL:-https://github.com/apple-oss-distributions/xnu.git}
+TAG=xnu-8796.121.2
+BASE=c54f35ca767986246321eb901baf8f5ff7923f6a
+
+[ -e "$DIR" ] && { echo "apply.sh: $DIR already exists; not touching it" >&2; exit 1; }
+[ -s "$HERE/redwood.patch" ] && [ -d "$HERE/files" ] || { echo "apply.sh: no redwood.patch and files/ in $HERE" >&2; exit 1; }
+mkdir -p "$(dirname "$DIR")"
+DIR=$(cd "$(dirname "$DIR")" && pwd)/$(basename "$DIR")
+git init -q "$DIR"
+trap 'echo "apply.sh: failed; removing the incomplete $DIR" >&2; rm -rf "$DIR"' ERR
+cd "$DIR"
+git remote add origin "$URL"
+git fetch -q --depth 1 origin "refs/tags/$TAG" # that one release, without the history
+git checkout -q -b redwood FETCH_HEAD
+[ "$(git rev-parse HEAD)" = "$BASE" ] || { echo "apply.sh: $TAG is $(git rev-parse HEAD), expected $BASE" >&2; false; }
+echo 'BUILD/' >> .git/info/exclude
+git apply --whitespace=nowarn "$HERE/redwood.patch"
+cp -a "$HERE/files/." .
+echo "apply.sh: $DIR: $TAG + $(grep -c '^diff --git' "$HERE/redwood.patch") changed and $(find "$HERE/files" -type f | wc -l) new files"
diff --git a/xnu/export.sh b/xnu/export.sh
new file mode 100755
index 0000000..0940781
--- /dev/null
+++ b/xnu/export.sh
@@ -0,0 +1,35 @@
+#!/bin/bash
+# Save the kernel work as it is in the working tree, in the two forms apply.sh puts back:
+# redwood.patch the changes to Apple's files (against the tag the work sits on)
+# files/ the files that are not in Apple's tree, at their paths
+# usage: xnu/export.sh [KERNEL-TREE] (default: $XNU_SRC, else xnu-src/xnu-8796.121.2)
+# Run it before committing whenever the kernel tree has changed. Committed or not makes no
+# difference there: everything is compared with the base commit.
+set -e
+HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+SRC=${1:-${XNU_SRC:-$HERE/../xnu-src/xnu-8796.121.2}}
+BASE=c54f35ca767986246321eb901baf8f5ff7923f6a # tag xnu-8796.121.2
+# never part of the work: build output and what editors, patch and python leave behind
+JUNK='^BUILD/|(^|/)__pycache__/|\.(orig|rej|pyc|o|swp)$|\.bak[0-9]*$|~$|(^|/)\.DS_Store$'
+
+cd "$SRC"
+git cat-file -e "$BASE^{commit}" 2>/dev/null || { echo "export.sh: $SRC is not a clone of xnu at $BASE" >&2; exit 1; }
+
+# no renames: a moved file is a deletion in the patch and a new file in files/
+git -c core.abbrev=12 diff --binary --no-renames --no-color --no-ext-diff --diff-filter=MDT "$BASE" -- . > "$HERE/redwood.patch.new"
+mv "$HERE/redwood.patch.new" "$HERE/redwood.patch"
+
+rm -rf "$HERE/files.new"
+mkdir "$HERE/files.new"
+{ git diff --no-renames --name-only --diff-filter=A "$BASE" -- .; git ls-files --others --exclude-standard; } |
+ sort -u | grep -Ev "$JUNK" > "$HERE/files.list"
+while IFS= read -r f; do
+ [ -f "$f" ] || [ -L "$f" ] || continue # added in a commit, deleted since
+ mkdir -p "$HERE/files.new/$(dirname "$f")"
+ cp -P --preserve=mode "$f" "$HERE/files.new/$f"
+done < "$HERE/files.list"
+rm -rf "$HERE/files" "$HERE/files.list"
+mv "$HERE/files.new" "$HERE/files"
+
+echo "xnu/redwood.patch: $(grep -c '^diff --git' "$HERE/redwood.patch") files changed, $(wc -c < "$HERE/redwood.patch") bytes"
+echo "xnu/files: $(find "$HERE/files" -type f | wc -l) new files, $(du -sk "$HERE/files" | cut -f1) KB"
diff --git a/xnu/files/bsd/dev/redwood_cpufreq.c b/xnu/files/bsd/dev/redwood_cpufreq.c
new file mode 100644
index 0000000..494c427
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_cpufreq.c
@@ -0,0 +1,71 @@
+/*
+ * The clock speed of the processor core the kernel runs on, on the POCO X5 Pro (redwood).
+ * Only with boot-arg cpufreq=1: the addresses are this phone's.
+ *
+ * The boot loader leaves each group of cores at a modest frequency and expects the operating
+ * system to ask for more. On this SoC that is one register write: the hardware ("EPSS") has
+ * a table of frequencies per group and switches the clock source and the supply voltage by
+ * itself when told which row is wanted. There is no reason for us ever to want less than the
+ * top row: one core is all the kernel uses.
+ *
+ * Register layout: Linux drivers/cpufreq/qcom-cpufreq-hw.c ("epss" variant).
+ */
+#include <kern/clock.h>
+#include <libkern/libkern.h>
+#include <mach/mach_types.h>
+#include <pexpert/pexpert.h>
+#include <sys/redwood_input.h>
+#include <sys/systm.h>
+
+extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
+
+#define EPSS_PHYS 0x18591000UL /* three groups ("domains") of 0x1000: small cores, big, biggest */
+#define EPSS_DOMAIN_SIZE 0x1000UL
+#define EPSS_FREQ_TABLE 0x100 /* a word per row: [31:30] clock source, [7:0] multiple of 19.2 MHz */
+#define EPSS_TABLE_ROWS 40
+#define EPSS_PERF_STATE 0x320 /* the row that is wanted */
+#define XO_KHZ 19200
+#define ALTERNATE_KHZ 300000 /* source 0: a fixed 300 MHz */
+
+/* How fast a simple loop runs, in thousands of iterations per millisecond. */
+static uint32_t
+loop_speed(void)
+{
+ volatile uint64_t sink = 0;
+ uint64_t start = mach_absolute_time(), nanos;
+
+ for (uint32_t i = 0; i < 2000000; i++) {
+ sink += i;
+ }
+ absolutetime_to_nanoseconds(mach_absolute_time() - start, &nanos);
+ return nanos ? (uint32_t)(2000000ULL * 1000 / nanos) : 0;
+}
+
+void
+redwood_cpufreq_init(void)
+{
+ uint64_t mpidr = __builtin_arm_rsr64("MPIDR_EL1");
+ uint32_t core = (uint32_t)(mpidr >> 8) & 0xff, domain = core < 4 ? 0 : core < 7 ? 1 : 2;
+ uint32_t enabled = 0, top = 0, top_khz = 0, before = loop_speed(), was;
+ vm_offset_t base;
+
+ if (!PE_parse_boot_argn("cpufreq", &enabled, sizeof(enabled)) || !enabled) {
+ return;
+ }
+ base = ml_io_map(EPSS_PHYS + domain * EPSS_DOMAIN_SIZE, EPSS_DOMAIN_SIZE);
+ for (uint32_t row = 0; row < EPSS_TABLE_ROWS; row++) {
+ uint32_t entry = *(volatile uint32_t *)(base + EPSS_FREQ_TABLE + 4 * row);
+ uint32_t khz = (entry >> 30) ? XO_KHZ * (entry & 0xff) : ALTERNATE_KHZ;
+
+ if (row > 0 && khz <= top_khz) {
+ break; /* the table ends by repeating its last row */
+ }
+ top = row;
+ top_khz = khz;
+ }
+ was = *(volatile uint32_t *)(base + EPSS_PERF_STATE);
+ *(volatile uint32_t *)(base + EPSS_PERF_STATE) = top;
+ delay_for_interval(20, NSEC_PER_MSEC);
+ printf("cpufreq: core %u (group %u): row %u -> %u of the frequency table, %u MHz; a loop ran at %u, now at %u\n", core,
+ domain, was, top, top_khz / 1000, before, loop_speed());
+}
diff --git a/xnu/files/bsd/dev/redwood_goodix.c b/xnu/files/bsd/dev/redwood_goodix.c
new file mode 100644
index 0000000..003870d
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_goodix.c
@@ -0,0 +1,957 @@
+/*
+ * The touch screen of the POCO X5 Pro (redwood): a Goodix GT9916 ("Berlin-D") on the SPI bus of
+ * the SoC's serial engine 13, as a source of touches for /dev/redwood-touch (sys/redwood_input.h).
+ * Only with boot-arg touchscreen=1: every address below belongs to this phone.
+ *
+ * There is no clock, pin, regulator or SPI framework in this kernel, so the driver does all of
+ * it itself, in the order the vendor's Linux driver does:
+ * power the chip's I/O supply is LDO2 of the PM8350C, switched through RPMh (one request
+ * written into the "always on" processor's command slots); the analog supply is
+ * behind a GPIO
+ * clocks the serial engine's three clocks, by vote in the global clock controller
+ * pins four GPIOs to the serial engine, plus reset, interrupt and the analog supply switch
+ * SPI the serial engine ("GENI") in FIFO mode, polled; or, if the engine cannot be used,
+ * the same four pins driven by hand
+ * Goodix find where the chip keeps its touch report, then read the report whenever the
+ * interrupt line says there is one
+ * No interrupt is used: a thread looks at the interrupt line 125 times a second.
+ *
+ * Register layouts: Linux drivers/spi/spi-geni-qcom.c, drivers/soc/qcom/{qcom-geni-se,rpmh-rsc,
+ * cmd-db}.c, drivers/clk/qcom/gcc-sc7280.c, drivers/pinctrl/qcom/pinctrl-sc7280.c,
+ * drivers/input/touchscreen/goodix_berlin_*.c, and the phone's own device tree.
+ */
+#include <kern/clock.h>
+#include <kern/thread.h>
+#include <libkern/libkern.h>
+#include <mach/mach_types.h>
+#include <pexpert/pexpert.h>
+#include <sys/redwood_input.h>
+#include <sys/systm.h>
+
+extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
+extern vm_offset_t ml_io_map_wcomb(vm_offset_t phys_addr, vm_size_t size);
+extern kern_return_t thread_terminate(thread_t thread);
+
+static vm_offset_t tlmm, gcc, se, rsc, cmd_db;
+
+static inline uint32_t
+rd(vm_offset_t address)
+{
+ return *(volatile uint32_t *)address;
+}
+
+static inline void
+wr(vm_offset_t address, uint32_t value)
+{
+ *(volatile uint32_t *)address = value;
+}
+
+static void
+sleep_us(uint32_t us)
+{
+ delay_for_interval(us, NSEC_PER_USEC);
+}
+
+static void
+sleep_ms(uint32_t ms)
+{
+ delay_for_interval(ms, NSEC_PER_MSEC);
+}
+
+/* ---- pins (TLMM) ------------------------------------------------------------------------------- */
+
+#define TLMM_PHYS 0x0f100000UL
+#define TLMM_SIZE 0x100000UL
+#define GPIO_CFG(n) (tlmm + 0x1000UL * (n)) /* [1:0] pull, [5:2] function, [8:6] drive, [9] output */
+#define GPIO_IO(n) (tlmm + 0x1000UL * (n) + 4) /* bit 0 in, bit 1 out */
+#define PULL_NONE 0
+#define PULL_UP 3
+
+#define PIN_MISO 52
+#define PIN_MOSI 53
+#define PIN_CLK 54
+#define PIN_CS 55
+#define PIN_INT 81 /* low = the chip has a report */
+#define PIN_RESET 105 /* low = in reset */
+#define PIN_AVDD 107 /* high = analog supply on */
+#define PIN_FUNCTION_SPI 1 /* "qup15" */
+
+static void
+gpio_configure(unsigned pin, unsigned function, unsigned pull, unsigned ma, bool output)
+{
+ wr(GPIO_CFG(pin), pull | function << 2 | (ma / 2 - 1) << 6 | (output ? 1u << 9 : 0));
+}
+
+static void
+gpio_set(unsigned pin, bool high)
+{
+ wr(GPIO_IO(pin), high ? 2 : 0);
+}
+
+static bool
+gpio_get(unsigned pin)
+{
+ return rd(GPIO_IO(pin)) & 1;
+}
+
+static void
+gpio_output(unsigned pin, bool high, unsigned pull, unsigned ma)
+{
+ gpio_set(pin, high); /* the level first, so that the pin never drives the wrong one */
+ gpio_configure(pin, 0, pull, ma, true);
+}
+
+/* ---- the I/O supply (RPMh) ----------------------------------------------------------------------- */
+
+#define CMD_DB_PHYS 0x80860000UL
+#define CMD_DB_SIZE 0x20000UL
+#define RSC_PHYS 0x18220000UL /* the application processor's "DRV 2" */
+#define RSC_SIZE 0x10000UL
+#define TCS(reg) (rsc + 0xd00 + (reg)) /* command slot set 0, an "active" one */
+#define TCS_IRQ_ENABLE 0x00
+#define TCS_IRQ_STATUS 0x04
+#define TCS_IRQ_CLEAR 0x08
+#define TCS_WAIT_FOR_COMPLETION 0x10
+#define TCS_CONTROL 0x14
+#define TCS_CONTROL_ENABLE (1u << 16)
+#define TCS_CONTROL_TRIGGER (1u << 24)
+#define TCS_STATUS 0x18 /* 0 while busy */
+#define TCS_CMD_ENABLE 0x1c
+#define TCS_CMD_MSGID(n) (0x30 + 20 * (n))
+#define TCS_CMD_ADDR(n) (0x34 + 20 * (n))
+#define TCS_CMD_DATA(n) (0x38 + 20 * (n))
+#define MSGID_WRITE_4_BYTES 0x10008
+#define MSGID_RESPONSE 0x100
+
+#define VRM_VOLTAGE 0 /* a regulator's registers, from its address: millivolts */
+#define VRM_ENABLE 4
+#define VRM_MODE 8
+#define VRM_MODE_LDO_HPM 7
+
+struct cmd_db_slave {
+ uint16_t id, header_offset, data_offset, count, version, reserved[3];
+};
+struct cmd_db_header {
+ uint32_t version;
+ uint8_t magic[4];
+ struct cmd_db_slave slave[8];
+ uint32_t checksum, reserved;
+ uint8_t data[];
+};
+struct cmd_db_entry {
+ char id[8];
+ uint32_t priority[2];
+ uint32_t address;
+ uint16_t length, offset;
+};
+
+/* The RPMh address of a resource by its name in the command database the boot loader left; 0 = none. */
+static uint32_t
+rpmh_address(const char *name)
+{
+ const struct cmd_db_header *db = (const struct cmd_db_header *)cmd_db;
+ char id[8] = { 0 };
+
+ if (db->magic[0] != 0xdb || db->magic[1] != 0x30 || db->magic[2] != 0x03 || db->magic[3] != 0x0c) {
+ printf("goodix: no command database (magic %02x %02x %02x %02x)\n", db->magic[0], db->magic[1], db->magic[2],
+ db->magic[3]);
+ return 0;
+ }
+ strlcpy(id, name, sizeof(id));
+ for (unsigned s = 0; s < 8; s++) {
+ const struct cmd_db_slave *slave = &db->slave[s];
+ const struct cmd_db_entry *entry = (const struct cmd_db_entry *)(db->data + slave->header_offset);
+
+ if (slave->id == 0 || slave->header_offset >= CMD_DB_SIZE - 0x1000 || slave->count > 512) {
+ continue;
+ }
+ for (unsigned i = 0; i < slave->count; i++) {
+ if (memcmp(entry[i].id, id, sizeof(id)) == 0) {
+ return entry[i].address;
+ }
+ }
+ }
+ return 0;
+}
+
+static bool
+rpmh_wait(uint32_t reg, uint32_t mask, uint32_t value, const char *what)
+{
+ for (int i = 0; i < 2000; i++) {
+ if ((rd(TCS(reg)) & mask) == value) {
+ return true;
+ }
+ sleep_us(100);
+ }
+ printf("goodix: RPMh: timeout waiting for %s (register %#x = %#x)\n", what, reg, rd(TCS(reg)));
+ return false;
+}
+
+/* Send up to three register writes to RPMh and wait until they are done. */
+static bool
+rpmh_write(const uint32_t *address, const uint32_t *data, unsigned count)
+{
+ uint32_t irq_enable = rd(TCS(TCS_IRQ_ENABLE));
+ bool done;
+
+ /* the slot set must be idle, and switched off the way the hardware wants it: trigger, then enable */
+ for (int i = 0; rd(TCS(TCS_STATUS)) == 0; i++) {
+ if (i > 2000) {
+ printf("goodix: RPMh: the command slots stay busy\n");
+ return false;
+ }
+ sleep_us(100);
+ }
+ wr(TCS(TCS_CONTROL), rd(TCS(TCS_CONTROL)) & ~TCS_CONTROL_TRIGGER);
+ wr(TCS(TCS_CONTROL), rd(TCS(TCS_CONTROL)) & ~TCS_CONTROL_ENABLE);
+ wr(TCS(TCS_IRQ_CLEAR), 1);
+ for (unsigned i = 0; i < count; i++) {
+ wr(TCS(TCS_CMD_MSGID(i)), MSGID_WRITE_4_BYTES | MSGID_RESPONSE);
+ wr(TCS(TCS_CMD_ADDR(i)), address[i]);
+ wr(TCS(TCS_CMD_DATA(i)), data[i]);
+ }
+ wr(TCS(TCS_WAIT_FOR_COMPLETION), (1u << count) - 1);
+ wr(TCS(TCS_CMD_ENABLE), (1u << count) - 1);
+ wr(TCS(TCS_IRQ_ENABLE), irq_enable | 1); /* the status bit follows the enable; the interrupt itself stays masked */
+ wr(TCS(TCS_CONTROL), TCS_CONTROL_ENABLE);
+ wr(TCS(TCS_CONTROL), TCS_CONTROL_ENABLE | TCS_CONTROL_TRIGGER);
+
+ done = rpmh_wait(TCS_IRQ_STATUS, 1, 1, "the request");
+ wr(TCS(TCS_CONTROL), rd(TCS(TCS_CONTROL)) & ~TCS_CONTROL_TRIGGER);
+ wr(TCS(TCS_CONTROL), rd(TCS(TCS_CONTROL)) & ~TCS_CONTROL_ENABLE);
+ wr(TCS(TCS_CMD_ENABLE), 0);
+ wr(TCS(TCS_WAIT_FOR_COMPLETION), 0);
+ wr(TCS(TCS_IRQ_CLEAR), 1);
+ wr(TCS(TCS_IRQ_ENABLE), irq_enable);
+ return done;
+}
+
+/* The chip's I/O supply: 1.8 V from LDO2 of the PM8350C ("ldoc2"). Nothing else is connected to it. */
+static bool
+io_supply_on(void)
+{
+ uint32_t base = rpmh_address("ldoc2");
+ uint32_t address[3] = { base + VRM_VOLTAGE, base + VRM_ENABLE, base + VRM_MODE };
+ uint32_t data[3] = { 1800, 1, VRM_MODE_LDO_HPM };
+
+ /* addresses of regulators ("VRM") have 4 in bits 19:16; anything else is not what we are looking for */
+ if (base == 0 || (base >> 16 & 0xf) != 4) {
+ printf("goodix: RPMh: no regulator \"ldoc2\" (address %#x)\n", base);
+ return false;
+ }
+ printf("goodix: RPMh: ldoc2 is at %#x; slot status %#x, control %#x, irq enable %#x status %#x\n", base,
+ rd(TCS(TCS_STATUS)), rd(TCS(TCS_CONTROL)), rd(TCS(TCS_IRQ_ENABLE)), rd(TCS(TCS_IRQ_STATUS)));
+ if (!rpmh_write(address, data, 3)) {
+ return false;
+ }
+ printf("goodix: I/O supply on (1.8 V)\n");
+ return true;
+}
+
+/* ---- clocks (GCC) -------------------------------------------------------------------------------- */
+
+#define GCC_PHYS 0x00100000UL
+#define GCC_SIZE 0x60000UL
+#define GCC_VOTE (gcc + 0x52008) /* the application processor's votes */
+#define VOTE_QUP1_CORE_2X (1u << 18)
+#define VOTE_QUP1_CORE (1u << 19)
+#define VOTE_QUP1_M_AHB (1u << 20)
+#define VOTE_QUP1_S_AHB (1u << 21)
+#define VOTE_QUP1_SE5 (1u << 27) /* serial engine 13 is the 6th of the second group */
+#define GCC_QUP1_M_AHB_CBCR (gcc + 0x18004) /* bit 31: the clock is off */
+#define GCC_QUP1_S_AHB_CBCR (gcc + 0x18008)
+#define GCC_QUP1_SE5_CBCR (gcc + 0x185fc)
+#define GCC_QUP1_SE5_CMD (gcc + 0x18600) /* bit 0: take the new configuration */
+#define GCC_QUP1_SE5_CFG (gcc + 0x18604) /* [4:0] 2*divider-1, [10:8] source, [13:12] mode */
+#define GCC_QUP1_SE5_DFSR (gcc + 0x18614) /* bit 0: the engine chooses among preset rates itself */
+#define GCC_QUP1_SE5_PERF_CFG(l) (gcc + 0x1861c + 4 * (l))
+#define GCC_QUP1_SE5_PERF_M(l) (gcc + 0x1865c + 4 * (l))
+#define GCC_QUP1_SE5_PERF_N(l) (gcc + 0x1869c + 4 * (l))
+#define CLOCK_OFF (1u << 31)
+#define XO_HZ 19200000
+
+static uint32_t se_source_hz, se_clock_select;
+
+static uint32_t
+rcg_rate(uint32_t cfg, uint32_t m, uint32_t not_n_minus_m)
+{
+ static const uint32_t parent[8] = { XO_HZ, 600000000, 0, 0, 0, 0, 300000000, 0 };
+ uint64_t hz = parent[cfg >> 8 & 7];
+ uint32_t divider = cfg & 0x1f, mode = cfg >> 12 & 3;
+
+ if (divider) {
+ hz = hz * 2 / (divider + 1);
+ }
+ if (mode) {
+ uint32_t n = (~not_n_minus_m & 0xffff) + (m & 0xffff);
+
+ if (n) {
+ hz = hz * (m & 0xffff) / n;
+ }
+ }
+ return (uint32_t)hz;
+}
+
+static bool
+clocks_on(void)
+{
+ wr(GCC_VOTE, rd(GCC_VOTE) | VOTE_QUP1_CORE_2X | VOTE_QUP1_CORE | VOTE_QUP1_M_AHB | VOTE_QUP1_S_AHB);
+ if (rd(GCC_QUP1_SE5_DFSR) & 1) {
+ /* preset rates: the lowest that is at least 4 MHz */
+ for (uint32_t level = 0; level < 8; level++) {
+ uint32_t hz = rcg_rate(rd(GCC_QUP1_SE5_PERF_CFG(level)), rd(GCC_QUP1_SE5_PERF_M(level)),
+ rd(GCC_QUP1_SE5_PERF_N(level)));
+
+ if (hz >= 4000000 && (se_source_hz == 0 || hz < se_source_hz)) {
+ se_source_hz = hz;
+ se_clock_select = level;
+ }
+ }
+ if (se_source_hz == 0) {
+ printf("goodix: no usable preset clock rate\n");
+ return false;
+ }
+ } else {
+ /* the crystal, undivided: nothing else has to be running */
+ wr(GCC_QUP1_SE5_CFG, (rd(GCC_QUP1_SE5_CFG) & ~0x371fu) | 1);
+ wr(GCC_QUP1_SE5_CMD, rd(GCC_QUP1_SE5_CMD) | 1);
+ for (int i = 0; i < 500 && (rd(GCC_QUP1_SE5_CMD) & 1); i++) {
+ sleep_us(10);
+ }
+ if (rd(GCC_QUP1_SE5_CMD) & 1) {
+ printf("goodix: the serial engine's clock does not take its configuration (%#x)\n", rd(GCC_QUP1_SE5_CMD));
+ return false;
+ }
+ se_source_hz = XO_HZ;
+ se_clock_select = 0;
+ }
+ wr(GCC_VOTE, rd(GCC_VOTE) | VOTE_QUP1_SE5);
+ for (int i = 0; i < 1000; i++) {
+ if (!((rd(GCC_QUP1_M_AHB_CBCR) | rd(GCC_QUP1_S_AHB_CBCR) | rd(GCC_QUP1_SE5_CBCR)) & CLOCK_OFF)) {
+ return true;
+ }
+ sleep_us(10);
+ }
+ printf("goodix: clocks stay off: %#x %#x %#x\n", rd(GCC_QUP1_M_AHB_CBCR), rd(GCC_QUP1_S_AHB_CBCR),
+ rd(GCC_QUP1_SE5_CBCR));
+ return false;
+}
+
+/* ---- SPI through the serial engine (GENI) ---------------------------------------------------------- */
+
+#define SE_PHYS 0x00a94000UL
+#define SE_SIZE 0x4000UL
+#define GENI_FORCE_DEFAULT (se + 0x020)
+#define GENI_OUTPUT_CTRL (se + 0x024)
+#define GENI_CGC_CTRL (se + 0x028)
+#define GENI_STATUS (se + 0x040) /* bit 0: a command is running */
+#define GENI_SER_M_CLK_CFG (se + 0x048) /* bit 0 enable, [15:4] divider */
+#define GENI_IF_DISABLE_RO (se + 0x064) /* bit 0: no FIFO interface */
+#define GENI_FW_REVISION_RO (se + 0x068) /* [15:8] protocol: 1 = SPI */
+#define GENI_CLK_SEL (se + 0x07c)
+#define SPI_CPHA (se + 0x224)
+#define SPI_LOOPBACK (se + 0x22c)
+#define SPI_CPOL (se + 0x230)
+#define SPI_DEMUX_OUTPUT_INV (se + 0x24c)
+#define SPI_DEMUX_SEL (se + 0x250)
+#define GENI_BYTE_GRAN (se + 0x254)
+#define GENI_DMA_MODE_EN (se + 0x258)
+#define SPI_TRANS_CFG (se + 0x25c)
+#define GENI_TX_PACKING_CFG0 (se + 0x260)
+#define GENI_TX_PACKING_CFG1 (se + 0x264)
+#define SPI_WORD_LEN (se + 0x268)
+#define SPI_TX_TRANS_LEN (se + 0x26c)
+#define SPI_RX_TRANS_LEN (se + 0x270)
+#define SPI_DELAY_COUNTERS (se + 0x278)
+#define GENI_RX_PACKING_CFG0 (se + 0x284)
+#define GENI_RX_PACKING_CFG1 (se + 0x288)
+#define GENI_M_CMD0 (se + 0x600) /* [31:27] operation */
+#define GENI_M_CMD_CTRL (se + 0x604) /* bit 2 cancel, bit 1 abort */
+#define GENI_M_IRQ_STATUS (se + 0x610)
+#define GENI_M_IRQ_EN (se + 0x614)
+#define GENI_M_IRQ_CLEAR (se + 0x618)
+#define GENI_S_IRQ_CLEAR (se + 0x648)
+#define GENI_TX_FIFO (se + 0x700)
+#define GENI_RX_FIFO (se + 0x780)
+#define GENI_TX_FIFO_STATUS (se + 0x800) /* [27:0] words */
+#define GENI_RX_FIFO_STATUS (se + 0x804) /* bit 31 last, [30:28] bytes of the last word, [24:0] words */
+#define GENI_TX_WATERMARK (se + 0x80c)
+#define GENI_RX_WATERMARK (se + 0x810)
+#define GENI_RX_RFR_WATERMARK (se + 0x814)
+#define SE_DMA_TX_IRQ_CLR (se + 0xc44)
+#define SE_DMA_RX_IRQ_CLR (se + 0xd44)
+#define SE_GSI_EVENT_EN (se + 0xe18)
+#define SE_IRQ_EN (se + 0xe1c)
+#define SE_HW_PARAM_0 (se + 0xe24) /* [21:16] FIFO depth in words */
+#define SE_DMA_GENERAL_CFG (se + 0xe30)
+
+#define M_CMD_DONE (1u << 0)
+#define M_CMD_CANCEL (1u << 4)
+#define M_CMD_ABORT (1u << 5)
+#define M_ERRORS ((1u << 1) | (1u << 2) | (1u << 3) | (1u << 24) | (1u << 25) | (1u << 28) | (1u << 29))
+#define SPI_FULL_DUPLEX (3u << 27)
+
+static uint32_t fifo_depth;
+
+/* 0 = ready; otherwise why the engine cannot be used */
+static const char *
+geni_spi_init(uint32_t hz)
+{
+ uint32_t divider;
+
+ if ((rd(GENI_FW_REVISION_RO) >> 8 & 0xff) != 1) {
+ return "the serial engine has no SPI firmware";
+ }
+ if (rd(GENI_IF_DISABLE_RO) & 1) {
+ return "the serial engine's FIFO interface is disabled";
+ }
+ fifo_depth = rd(SE_HW_PARAM_0) >> 16 & 0x3f;
+ if (fifo_depth < 4) {
+ return "the serial engine reports no FIFO";
+ }
+ wr(SE_GSI_EVENT_EN, 0);
+ wr(GENI_M_IRQ_CLEAR, 0xffffffff);
+ wr(GENI_S_IRQ_CLEAR, 0xffffffff);
+ wr(SE_DMA_TX_IRQ_CLR, 0xffffffff);
+ wr(SE_DMA_RX_IRQ_CLR, 0xffffffff);
+ wr(GENI_CGC_CTRL, rd(GENI_CGC_CTRL) | 0x7f);
+ wr(SE_DMA_GENERAL_CFG, rd(SE_DMA_GENERAL_CFG) | 0xf);
+ wr(GENI_OUTPUT_CTRL, 0x7f);
+ wr(GENI_FORCE_DEFAULT, 1);
+ wr(GENI_DMA_MODE_EN, rd(GENI_DMA_MODE_EN) & ~1u);
+ wr(GENI_RX_WATERMARK, fifo_depth - 3);
+ wr(GENI_RX_RFR_WATERMARK, fifo_depth - 2);
+ wr(GENI_TX_WATERMARK, 0);
+ /* the status bits we poll follow these enables; the interrupt itself stays masked at the GIC */
+ wr(SE_IRQ_EN, rd(SE_IRQ_EN) | 0xf);
+ wr(GENI_M_IRQ_EN, rd(GENI_M_IRQ_EN) | 0x7fc0007f);
+
+ /* mode 0, chip select 0, 8 bits, most significant first, four bytes in a FIFO word */
+ wr(SPI_LOOPBACK, 0);
+ wr(SPI_DEMUX_SEL, 0);
+ wr(SPI_CPHA, 0);
+ wr(SPI_CPOL, 0);
+ wr(SPI_DEMUX_OUTPUT_INV, 0);
+ wr(SPI_TRANS_CFG, rd(SPI_TRANS_CFG) & ~2u);
+ wr(SPI_DELAY_COUNTERS, 0);
+ wr(GENI_TX_PACKING_CFG0, 0x0007f8fe);
+ wr(GENI_TX_PACKING_CFG1, 0x000ffefe);
+ wr(GENI_RX_PACKING_CFG0, 0x0007f8fe);
+ wr(GENI_RX_PACKING_CFG1, 0x000ffefe);
+ wr(GENI_BYTE_GRAN, 0);
+ wr(SPI_WORD_LEN, 8 - 4);
+
+ divider = (se_source_hz + hz - 1) / hz;
+ wr(GENI_CLK_SEL, se_clock_select & 7);
+ wr(GENI_SER_M_CLK_CFG, (divider ? divider : 1) << 4 | 1);
+ return NULL;
+}
+
+static void
+geni_drain(uint8_t *rx, uint32_t length, uint32_t *received)
+{
+ uint32_t status = rd(GENI_RX_FIFO_STATUS), words = status & 0x01ffffff, bytes = words * 4;
+
+ if (status & 0x80000000u) {
+ uint32_t valid = status >> 28 & 7;
+
+ if (valid && valid < 4) {
+ bytes -= 4 - valid;
+ }
+ }
+ for (uint32_t i = 0; i < words; i++) {
+ uint32_t word = rd(GENI_RX_FIFO);
+
+ for (int j = 0; j < 4 && bytes; j++, bytes--) {
+ if (*received < length) {
+ if (rx) {
+ rx[*received] = (uint8_t)(word >> (8 * j));
+ }
+ (*received)++;
+ }
+ }
+ }
+}
+
+static void
+geni_recover(void)
+{
+ wr(GENI_M_CMD_CTRL, 1u << 2);
+ for (int i = 0; i < 2000 && !(rd(GENI_M_IRQ_STATUS) & M_CMD_CANCEL); i++) {
+ sleep_us(100);
+ }
+ if (!(rd(GENI_M_IRQ_STATUS) & M_CMD_CANCEL)) {
+ wr(GENI_M_CMD_CTRL, 1u << 1);
+ for (int i = 0; i < 2000 && !(rd(GENI_M_IRQ_STATUS) & M_CMD_ABORT); i++) {
+ sleep_us(100);
+ }
+ }
+ for (int i = 0; i < 64 && (rd(GENI_RX_FIFO_STATUS) & 0x01ffffff); i++) {
+ (void)rd(GENI_RX_FIFO);
+ }
+ wr(GENI_M_IRQ_CLEAR, 0xffffffff);
+}
+
+/* One transfer with the chip selected throughout: `length` bytes out (zeros without tx) and as many in. */
+static bool
+geni_transfer(const uint8_t *tx, uint8_t *rx, uint32_t length)
+{
+ static unsigned complaints;
+ uint32_t sent = 0, received = 0, status = 0;
+ uint64_t deadline;
+
+ for (int i = 0; rd(GENI_STATUS) & 1; i++) {
+ if (i > 2000) {
+ geni_recover();
+ break;
+ }
+ sleep_us(100);
+ }
+ wr(GENI_M_IRQ_CLEAR, 0xffffffff);
+ wr(SPI_TX_TRANS_LEN, length);
+ wr(SPI_RX_TRANS_LEN, length);
+ wr(GENI_M_CMD0, SPI_FULL_DUPLEX);
+ clock_interval_to_deadline(200, NSEC_PER_MSEC, &deadline);
+ while (mach_absolute_time() < deadline) {
+ while (sent < length && (rd(GENI_TX_FIFO_STATUS) & 0x0fffffff) + 1 < fifo_depth) {
+ uint32_t word = 0;
+
+ for (int j = 0; j < 4 && sent < length; j++, sent++) {
+ word |= (uint32_t)(tx ? tx[sent] : 0) << (8 * j);
+ }
+ wr(GENI_TX_FIFO, word);
+ }
+ status = rd(GENI_M_IRQ_STATUS);
+ geni_drain(rx, length, &received);
+ if (status & M_ERRORS) {
+ break;
+ }
+ if (status & M_CMD_DONE) {
+ geni_drain(rx, length, &received);
+ wr(GENI_M_IRQ_CLEAR, status);
+ if (received == length) {
+ return true;
+ }
+ break;
+ }
+ }
+ if (complaints++ < 8) {
+ printf("goodix: SPI transfer of %u bytes failed: status %#x, sent %u, received %u\n", length, status, sent,
+ received);
+ }
+ geni_recover();
+ return false;
+}
+
+/* ---- SPI by hand, on the same pins ----------------------------------------------------------------- */
+
+static unsigned bitbang_in = PIN_MISO, bitbang_out = PIN_MOSI;
+
+static void
+bitbang_init(void)
+{
+ gpio_output(PIN_CS, true, PULL_NONE, 6);
+ gpio_output(PIN_CLK, false, PULL_NONE, 6);
+ gpio_output(bitbang_out, false, PULL_NONE, 6);
+ gpio_configure(bitbang_in, 0, PULL_NONE, 2, false);
+}
+
+static bool
+bitbang_transfer(const uint8_t *tx, uint8_t *rx, uint32_t length)
+{
+ gpio_set(PIN_CS, false);
+ for (uint32_t i = 0; i < length; i++) {
+ uint8_t out = tx ? tx[i] : 0, in = 0;
+
+ for (int bit = 7; bit >= 0; bit--) {
+ gpio_set(bitbang_out, out >> bit & 1);
+ gpio_set(PIN_CLK, true);
+ in = (uint8_t)(in << 1 | gpio_get(bitbang_in));
+ gpio_set(PIN_CLK, false);
+ }
+ if (rx) {
+ rx[i] = in;
+ }
+ }
+ gpio_set(PIN_CS, true);
+ return true;
+}
+
+static bool (*spi_transfer)(const uint8_t *tx, uint8_t *rx, uint32_t length);
+
+/* ---- the Goodix chip ------------------------------------------------------------------------------- */
+
+#define GOODIX_FW_VERSION 0x10014 /* 28 bytes */
+#define GOODIX_IC_INFO 0x10070 /* a 16-bit length, then that many bytes */
+#define GOODIX_MAX_READ 1024
+#define GOODIX_MAX_TOUCHES 10
+#define GOODIX_STATUS_TOUCH 0x80
+#define GOODIX_STATUS_REQUEST 0x40
+#define GOODIX_REQUEST_RESET 3
+
+static uint8_t spi_tx[8 + GOODIX_MAX_READ], spi_rx[8 + GOODIX_MAX_READ];
+static uint32_t touch_address;
+static uint32_t max_x = 10800, max_y = 24000; /* the device tree's; the chip may say otherwise */
+
+static bool
+goodix_read(uint32_t address, uint8_t *data, uint32_t length)
+{
+ if (length > GOODIX_MAX_READ) {
+ return false;
+ }
+ spi_tx[0] = 0xf1;
+ spi_tx[1] = (uint8_t)(address >> 24);
+ spi_tx[2] = (uint8_t)(address >> 16);
+ spi_tx[3] = (uint8_t)(address >> 8);
+ spi_tx[4] = (uint8_t)address;
+ spi_tx[5] = spi_tx[6] = spi_tx[7] = 0xff;
+ memset(spi_tx + 8, 0, length);
+ if (!spi_transfer(spi_tx, spi_rx, 8 + length)) {
+ return false;
+ }
+ memcpy(data, spi_rx + 8, length);
+ return true;
+}
+
+static bool
+goodix_write(uint32_t address, const uint8_t *data, uint32_t length)
+{
+ if (length > GOODIX_MAX_READ) {
+ return false;
+ }
+ spi_tx[0] = 0xf0;
+ spi_tx[1] = (uint8_t)(address >> 24);
+ spi_tx[2] = (uint8_t)(address >> 16);
+ spi_tx[3] = (uint8_t)(address >> 8);
+ spi_tx[4] = (uint8_t)address;
+ memcpy(spi_tx + 5, data, length);
+ return spi_transfer(spi_tx, NULL, 5 + length);
+}
+
+/* The chip's blocks end in the 16-bit sum of their bytes; all zeros or all ones is no answer at all. */
+static bool
+goodix_checksum_ok(const uint8_t *data, uint32_t length)
+{
+ uint32_t sum = 0;
+ bool blank = true;
+
+ if (length < 2) {
+ return false;
+ }
+ for (uint32_t i = 0; i < length - 2; i++) {
+ sum += data[i];
+ blank &= data[i] == 0 || data[i] == 0xff;
+ }
+ return !blank && (uint16_t)sum == (uint16_t)(data[length - 2] | data[length - 1] << 8);
+}
+
+static uint16_t
+le16(const uint8_t *p)
+{
+ return (uint16_t)(p[0] | p[1] << 8);
+}
+
+static uint32_t
+le32(const uint8_t *p)
+{
+ return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24;
+}
+
+static void
+goodix_reset(void)
+{
+ gpio_set(PIN_RESET, false);
+ sleep_ms(2);
+ gpio_set(PIN_RESET, true);
+ sleep_ms(100);
+}
+
+/* Is the chip there and running its firmware? Finds where it keeps the touch report. */
+static bool
+goodix_probe(bool verbose)
+{
+ static uint8_t info[GOODIX_MAX_READ];
+ uint8_t version[28];
+ uint32_t length, offset;
+
+ if (!goodix_read(GOODIX_FW_VERSION, version, sizeof(version))) {
+ return false;
+ }
+ if (!goodix_checksum_ok(version, sizeof(version))) {
+ if (verbose) {
+ printf("goodix: no valid firmware version: %02x %02x %02x %02x %02x %02x %02x %02x ... %02x %02x\n",
+ version[0], version[1], version[2], version[3], version[4], version[5], version[6], version[7],
+ version[26], version[27]);
+ }
+ return false;
+ }
+ printf("goodix: chip \"%.6s\", firmware \"%.8s\" %02x.%02x.%02x.%02x, sensor %u\n", (const char *)version,
+ (const char *)version + 10, version[18], version[19], version[20], version[21], version[23]);
+
+ if (!goodix_read(GOODIX_IC_INFO, info, 2)) {
+ return false;
+ }
+ length = le16(info);
+ if (length < 40 || length >= GOODIX_MAX_READ || !goodix_read(GOODIX_IC_INFO, info, length) ||
+ !goodix_checksum_ok(info, length)) {
+ printf("goodix: bad chip description (length %u)\n", length);
+ return false;
+ }
+ /* the length, the version (16 bytes), the features (10), four counts, then five lists of 16-bit numbers */
+ offset = 2 + 16 + 10 + 4;
+ for (int i = 0; i < 5; i++) {
+ if (offset >= length) {
+ return false;
+ }
+ offset += 1 + 2u * info[offset];
+ }
+ if (offset + 48 + 2 > length) {
+ printf("goodix: chip description too short (%u, lists end at %u)\n", length, offset);
+ return false;
+ }
+ touch_address = le32(info + offset + 44);
+ if (offset + 122 + 20 + 2 <= length) {
+ uint16_t x = le16(info + offset + 122 + 16), y = le16(info + offset + 122 + 18);
+
+ if (x && y) {
+ max_x = x;
+ max_y = y;
+ }
+ }
+ printf("goodix: touch report at %#x, coordinates up to %u x %u\n", touch_address, max_x, max_y);
+ return touch_address != 0;
+}
+
+/* What has been seen so far: said once a minute, so that the end of the log always tells. */
+static struct {
+ uint32_t polls, reports, touches, bad, last_x, last_y;
+} seen;
+
+/* Which fingers were down in the last report, and where. */
+static struct {
+ bool down, seen;
+ uint32_t x, y;
+} contact[GOODIX_MAX_TOUCHES];
+static uint32_t flip; /* boot-arg touch_flip: 1 = mirror left-right, 2 = mirror top-bottom */
+
+static void
+goodix_report(const uint8_t *touches, uint32_t count)
+{
+ static unsigned shown;
+
+ for (int i = 0; i < GOODIX_MAX_TOUCHES; i++) {
+ contact[i].seen = false;
+ }
+ for (uint32_t i = 0; i < count; i++) {
+ const uint8_t *t = touches + 8 * i;
+ uint32_t id = t[0] >> 4, kind = t[0] & 0xf;
+ uint32_t x = le16(t + 2), y = le16(t + 4);
+
+ if (id >= GOODIX_MAX_TOUCHES || kind == 1 || kind == 3) { /* 1 and 3: a stylus */
+ continue;
+ }
+ if (shown < 40) {
+ shown++;
+ printf("goodix: finger %u at %u, %u (of %u x %u)\n", id, x, y, max_x, max_y);
+ }
+ seen.touches++;
+ seen.last_x = x;
+ seen.last_y = y;
+ x = x >= max_x ? 65535 : x * 65535 / max_x;
+ y = y >= max_y ? 65535 : y * 65535 / max_y;
+ if (flip & 1) {
+ x = 65535 - x;
+ }
+ if (flip & 2) {
+ y = 65535 - y;
+ }
+ contact[id].seen = true;
+ if (!contact[id].down) {
+ redwood_touch_post(REDWOOD_TOUCH_DOWN, id, x, y);
+ } else if (contact[id].x != x || contact[id].y != y) {
+ redwood_touch_post(REDWOOD_TOUCH_MOVE, id, x, y);
+ }
+ contact[id].down = true;
+ contact[id].x = x;
+ contact[id].y = y;
+ }
+ /* a finger that is no longer in the report has lifted */
+ for (uint32_t id = 0; id < GOODIX_MAX_TOUCHES; id++) {
+ if (contact[id].down && !contact[id].seen) {
+ contact[id].down = false;
+ redwood_touch_post(REDWOOD_TOUCH_UP, id, contact[id].x, contact[id].y);
+ }
+ }
+}
+
+/* Read the report if there is one, and tell the chip it has been read. */
+static void
+goodix_poll(void)
+{
+ static uint8_t report[8 + 8 * GOODIX_MAX_TOUCHES + 2];
+ static unsigned bad;
+ const uint8_t zero = 0;
+ const uint32_t first = 8 + 8 * 2 + 2; /* the header and two fingers: all there is, most of the time */
+ uint32_t count;
+
+ seen.polls++;
+ if (!goodix_read(touch_address, report, first) || report[0] == 0) {
+ return;
+ }
+ seen.reports++;
+ count = report[2] & 0xf;
+ if ((report[0] & GOODIX_STATUS_TOUCH) && count > 2 && count <= GOODIX_MAX_TOUCHES &&
+ !goodix_read(touch_address + 8, report + 8, 8 * count + 2)) {
+ return;
+ }
+ goodix_write(touch_address, &zero, 1);
+ if (!goodix_checksum_ok(report, 8)) {
+ seen.bad++;
+ if (bad++ < 8) {
+ printf("goodix: bad report header: %02x %02x %02x %02x %02x %02x %02x %02x\n", report[0], report[1],
+ report[2], report[3], report[4], report[5], report[6], report[7]);
+ }
+ return;
+ }
+ if (report[0] & GOODIX_STATUS_REQUEST) {
+ if ((report[2] & 0xf) == GOODIX_REQUEST_RESET || report[2] == GOODIX_REQUEST_RESET) {
+ printf("goodix: the chip asks to be reset\n");
+ goodix_reset();
+ }
+ return;
+ }
+ if (!(report[0] & GOODIX_STATUS_TOUCH)) {
+ return;
+ }
+ if (count > GOODIX_MAX_TOUCHES || (count && !goodix_checksum_ok(report + 8, count * 8 + 2))) {
+ seen.bad++;
+ if (bad++ < 8) {
+ printf("goodix: bad report (%u touches)\n", count);
+ }
+ return;
+ }
+ goodix_report(report + 8, count);
+}
+
+/* ---- all of it together ---------------------------------------------------------------------------- */
+
+static void
+show_state(const char *when)
+{
+ printf("goodix: %s: votes %#x, clocks %#x %#x %#x, rate cfg %#x dfs %#x; pins cs/clk/mosi/miso cfg %#x %#x %#x %#x,"
+ " reset %#x/%u, int %#x/%u, avdd %#x/%u, straps %u %u\n", when, rd(GCC_VOTE), rd(GCC_QUP1_M_AHB_CBCR),
+ rd(GCC_QUP1_S_AHB_CBCR), rd(GCC_QUP1_SE5_CBCR), rd(GCC_QUP1_SE5_CFG), rd(GCC_QUP1_SE5_DFSR), rd(GPIO_CFG(PIN_CS)),
+ rd(GPIO_CFG(PIN_CLK)), rd(GPIO_CFG(PIN_MOSI)), rd(GPIO_CFG(PIN_MISO)), rd(GPIO_CFG(PIN_RESET)),
+ rd(GPIO_IO(PIN_RESET)), rd(GPIO_CFG(PIN_INT)), rd(GPIO_IO(PIN_INT)), rd(GPIO_CFG(PIN_AVDD)), rd(GPIO_IO(PIN_AVDD)),
+ gpio_get(68), gpio_get(96));
+}
+
+/* Power the chip up from nothing, in the vendor driver's order. */
+static void
+power_on(void)
+{
+ gpio_output(PIN_RESET, false, PULL_UP, 8);
+ gpio_configure(PIN_INT, 0, PULL_UP, 8, false);
+ io_supply_on();
+ sleep_ms(3);
+ gpio_output(PIN_AVDD, true, PULL_NONE, 2);
+ sleep_ms(15);
+}
+
+static void
+use_engine_pins(void)
+{
+ gpio_configure(PIN_MISO, PIN_FUNCTION_SPI, PULL_NONE, 6, false);
+ gpio_configure(PIN_MOSI, PIN_FUNCTION_SPI, PULL_NONE, 6, false);
+ gpio_configure(PIN_CLK, PIN_FUNCTION_SPI, PULL_NONE, 6, false);
+ gpio_configure(PIN_CS, PIN_FUNCTION_SPI, PULL_NONE, 6, false);
+}
+
+static bool
+bring_up(void)
+{
+ const char *problem = "its clocks cannot be turned on";
+
+ show_state("as found");
+ power_on();
+
+ if (clocks_on()) {
+ printf("goodix: serial engine: firmware %#x, interface %#x, parameters %#x, source clock %u Hz (select %u)\n",
+ rd(GENI_FW_REVISION_RO), rd(GENI_IF_DISABLE_RO), rd(SE_HW_PARAM_0), se_source_hz, se_clock_select);
+ problem = geni_spi_init(1000000);
+ }
+ if (problem == NULL) {
+ use_engine_pins();
+ spi_transfer = geni_transfer;
+ goodix_reset();
+ show_state("powered, on the serial engine");
+ if (goodix_probe(true)) {
+ return true;
+ }
+ printf("goodix: no answer through the serial engine; trying the pins by hand\n");
+ } else {
+ printf("goodix: %s; driving the pins by hand\n", problem);
+ }
+
+ /* by hand; which of the two data pins is the input is not written down anywhere, so try both */
+ spi_transfer = bitbang_transfer;
+ for (int attempt = 0; attempt < 2; attempt++) {
+ bitbang_in = attempt == 0 ? PIN_MISO : PIN_MOSI;
+ bitbang_out = attempt == 0 ? PIN_MOSI : PIN_MISO;
+ bitbang_init();
+ goodix_reset();
+ if (goodix_probe(true)) {
+ printf("goodix: answers on pins driven by hand (data in on gpio%u)\n", bitbang_in);
+ return true;
+ }
+ }
+ show_state("no answer");
+ return false;
+}
+
+static void
+goodix_thread(__unused void *parameter, __unused wait_result_t result)
+{
+ unsigned idle = 0;
+
+ tlmm = ml_io_map(TLMM_PHYS, TLMM_SIZE);
+ gcc = ml_io_map(GCC_PHYS, GCC_SIZE);
+ se = ml_io_map(SE_PHYS, SE_SIZE);
+ rsc = ml_io_map(RSC_PHYS, RSC_SIZE);
+ cmd_db = ml_io_map_wcomb(CMD_DB_PHYS, CMD_DB_SIZE); /* memory, not registers: no alignment rules */
+
+ if (!bring_up()) {
+ printf("goodix: no touch screen\n");
+ thread_terminate(current_thread());
+ return;
+ }
+ printf("goodix: touch screen ready\n");
+ for (unsigned tick = 1;; tick++) {
+ /* the interrupt line is low while a report waits; look anyway every 80 ms in case it is missed */
+ if (!gpio_get(PIN_INT) || ++idle >= 10) {
+ idle = 0;
+ goodix_poll();
+ }
+ if (tick % (60 * 125) == 0) {
+ printf("goodix: so far %u reports in %u looks (%u bad), %u finger positions, the last at %u, %u; "
+ "interrupt line %s\n", seen.reports, seen.polls, seen.bad, seen.touches, seen.last_x, seen.last_y,
+ gpio_get(PIN_INT) ? "high" : "low");
+ }
+ sleep_ms(8);
+ }
+}
+
+void
+redwood_goodix_init(void)
+{
+ uint32_t enabled = 0;
+ thread_t thread;
+
+ if (!PE_parse_boot_argn("touchscreen", &enabled, sizeof(enabled)) || !enabled) {
+ return;
+ }
+ PE_parse_boot_argn("touch_flip", &flip, sizeof(flip));
+ if (kernel_thread_start(goodix_thread, NULL, &thread) == KERN_SUCCESS) {
+ thread_deallocate(thread);
+ }
+}
diff --git a/xnu/files/bsd/dev/redwood_input.c b/xnu/files/bsd/dev/redwood_input.c
new file mode 100644
index 0000000..325de10
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_input.c
@@ -0,0 +1,117 @@
+/*
+ * /dev/redwood-touch: a queue of touch samples (see sys/redwood_input.h).
+ */
+#include <kern/clock.h>
+#include <kern/locks.h>
+#include <libkern/libkern.h>
+#include <miscfs/devfs/devfs.h>
+#include <sys/conf.h>
+#include <sys/errno.h>
+#include <sys/proc.h>
+#include <sys/redwood_input.h>
+#include <sys/systm.h>
+#include <sys/uio.h>
+
+#define TOUCH_QUEUE 512 /* records; a power of two */
+
+static LCK_GRP_DECLARE(touch_lck_grp, "redwood-touch");
+static LCK_MTX_DECLARE(touch_lock, &touch_lck_grp);
+static struct redwood_touch touch_queue[TOUCH_QUEUE];
+static uint32_t touch_head, touch_tail; /* read from head, add at tail */
+
+void
+redwood_touch_post(uint32_t type, uint32_t finger, uint32_t x, uint32_t y)
+{
+ struct redwood_touch *t;
+
+ lck_mtx_lock(&touch_lock);
+ if (touch_tail - touch_head == TOUCH_QUEUE) {
+ touch_head++; /* nobody reads: drop the oldest */
+ }
+ t = &touch_queue[touch_tail++ % TOUCH_QUEUE];
+ t->time = mach_absolute_time();
+ t->type = type;
+ t->finger = finger;
+ t->x = x > 65535 ? 65535 : x;
+ t->y = y > 65535 ? 65535 : y;
+ lck_mtx_unlock(&touch_lock);
+ wakeup(&touch_queue);
+}
+
+static int
+touch_open(__unused dev_t dev, __unused int flags, __unused int devtype, __unused struct proc *p)
+{
+ return 0;
+}
+
+static int
+touch_close(__unused dev_t dev, __unused int flags, __unused int devtype, __unused struct proc *p)
+{
+ return 0;
+}
+
+static int
+touch_read(__unused dev_t dev, struct uio *uio, __unused int ioflag)
+{
+ struct redwood_touch t;
+ int error = 0, moved = 0;
+
+ lck_mtx_lock(&touch_lock);
+ while (touch_head == touch_tail) {
+ error = msleep(&touch_queue, &touch_lock, PZERO | PCATCH, "redwood-touch", NULL);
+ if (error) {
+ lck_mtx_unlock(&touch_lock);
+ return error;
+ }
+ }
+ while (touch_head != touch_tail && uio_resid(uio) >= (user_ssize_t)sizeof(t)) {
+ t = touch_queue[touch_head++ % TOUCH_QUEUE];
+ lck_mtx_unlock(&touch_lock);
+ error = uiomove((caddr_t)&t, sizeof(t), uio);
+ lck_mtx_lock(&touch_lock);
+ if (error) {
+ break;
+ }
+ moved++;
+ }
+ lck_mtx_unlock(&touch_lock);
+ return moved ? 0 : error;
+}
+
+static int
+touch_write(__unused dev_t dev, struct uio *uio, __unused int ioflag)
+{
+ struct redwood_touch t;
+ int error = 0;
+
+ while (uio_resid(uio) >= (user_ssize_t)sizeof(t)) {
+ error = uiomove((caddr_t)&t, sizeof(t), uio);
+ if (error) {
+ break;
+ }
+ if (t.type < REDWOOD_TOUCH_DOWN || t.type > REDWOOD_BUTTON_UP) {
+ return EINVAL;
+ }
+ redwood_touch_post(t.type, t.finger, t.x, t.y);
+ }
+ return error;
+}
+
+static const struct cdevsw touch_cdevsw = {
+ .d_open = touch_open, .d_close = touch_close, .d_read = touch_read, .d_write = touch_write,
+ .d_ioctl = eno_ioctl, .d_stop = eno_stop, .d_reset = eno_reset, .d_select = eno_select,
+ .d_mmap = eno_mmap, .d_strategy = eno_strat, .d_type = 0
+};
+
+void
+redwood_input_init(void)
+{
+ int major = cdevsw_add(-1, &touch_cdevsw);
+
+ if (major < 0 || devfs_make_node(makedev(major, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666, "redwood-touch") == NULL) {
+ printf("redwood-touch: cannot create the device\n");
+ }
+ redwood_cpufreq_init();
+ redwood_virtio_input_init();
+ redwood_goodix_init();
+}
diff --git a/xnu/files/bsd/dev/redwood_virtio_input.c b/xnu/files/bsd/dev/redwood_virtio_input.c
new file mode 100644
index 0000000..96cf03c
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_virtio_input.c
@@ -0,0 +1,358 @@
+/*
+ * Virtio input devices as a source of touches and buttons (see sys/redwood_input.h).
+ *
+ * Under QEMU's "virt" machine a "virtio-tablet-device" stands for the touch screen (the pointer
+ * with its button held is a finger) and a "virtio-keyboard-device" for the phone's buttons. They
+ * sit on the machine's virtio-mmio bus, which must be the current one, not "legacy"
+ * (-global virtio-mmio.force-legacy=false). Only with boot-arg virtio_input=1: the bus address
+ * is QEMU's and means nothing on the phone.
+ *
+ * No interrupt is used; the event queues are looked at 125 times a second.
+ *
+ * The keyboard is also a way to tell the kernel something from the host while the system runs:
+ * F12, a process name, Enter prints where every thread of that process is (ustacks_now(); the
+ * host side is "qemu/touch.py stacks NAME").
+ */
+#include <kern/clock.h>
+#include <kern/thread_call.h>
+#include <libkern/libkern.h>
+#include <mach/mach_types.h>
+#include <mach/vm_param.h>
+#include <pexpert/pexpert.h>
+#include <sys/redwood_input.h>
+#include <sys/systm.h>
+#include <vm/vm_kern.h>
+
+extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
+extern uint64_t kvtophys(vm_offset_t va); /* pmap_paddr_t */
+
+#define VIRTIO_BUS 0x0a000000UL /* QEMU virt: 32 transports of 0x200 bytes */
+#define VIRTIO_SLOTS 32
+#define VIRTIO_SLOT_SIZE 0x200
+
+#define VIRTIO_MAGIC 0x000 /* "virt" */
+#define VIRTIO_VERSION 0x004
+#define VIRTIO_DEVICE_ID 0x008
+#define VIRTIO_DRIVER_FEATURES 0x020
+#define VIRTIO_DRIVER_FEATURES_SEL 0x024
+#define VIRTIO_QUEUE_SEL 0x030
+#define VIRTIO_QUEUE_NUM_MAX 0x034
+#define VIRTIO_QUEUE_NUM 0x038
+#define VIRTIO_QUEUE_READY 0x044
+#define VIRTIO_QUEUE_NOTIFY 0x050
+#define VIRTIO_STATUS 0x070
+#define VIRTIO_QUEUE_DESC 0x080
+#define VIRTIO_QUEUE_DRIVER 0x090
+#define VIRTIO_QUEUE_DEVICE 0x0a0
+
+#define VIRTIO_ID_INPUT 18
+#define STATUS_ACKNOWLEDGE 1
+#define STATUS_DRIVER 2
+#define STATUS_DRIVER_OK 4
+#define STATUS_FEATURES_OK 8
+
+#define QUEUE_SIZE 64
+#define DESC_F_WRITE 2
+#define AVAIL_F_NO_INTERRUPT 1
+
+struct vq_desc {
+ uint64_t addr;
+ uint32_t len;
+ uint16_t flags;
+ uint16_t next;
+};
+struct vq_avail {
+ uint16_t flags;
+ uint16_t idx;
+ uint16_t ring[QUEUE_SIZE];
+};
+struct vq_used {
+ uint16_t flags;
+ uint16_t idx;
+ struct {
+ uint32_t id;
+ uint32_t len;
+ } ring[QUEUE_SIZE];
+};
+struct input_event {
+ uint16_t type;
+ uint16_t code;
+ uint32_t value;
+};
+
+/* everything the device reads and writes is in one page */
+#define OFFSET_DESC 0x0000
+#define OFFSET_AVAIL 0x0400
+#define OFFSET_USED 0x0800
+#define OFFSET_EVENTS 0x1000
+
+/* Linux input event numbers, which is what virtio input speaks */
+#define EV_SYN 0
+#define EV_KEY 1
+#define EV_ABS 3
+#define ABS_X 0
+#define ABS_Y 1
+#define ABS_RANGE 0x7fff /* QEMU's tablet: 0..0x7fff across the screen */
+#define BTN_LEFT 0x110
+#define BTN_TOUCH 0x14a
+
+struct input_device {
+ vm_offset_t regs;
+ struct vq_avail * avail;
+ struct vq_used * used;
+ struct input_event * events;
+ uint16_t seen; /* how far the used ring has been read */
+ /* the pointer */
+ uint32_t x, y;
+ bool pressed, touching, moved;
+};
+
+#define MAX_DEVICES 4
+static struct input_device devices[MAX_DEVICES];
+static int device_count;
+static thread_call_t poll_call;
+
+static inline uint32_t
+reg_read(struct input_device *d, uint32_t reg)
+{
+ return *(volatile uint32_t *)(d->regs + reg);
+}
+
+static inline void
+reg_write(struct input_device *d, uint32_t reg, uint32_t value)
+{
+ *(volatile uint32_t *)(d->regs + reg) = value;
+}
+
+static inline void
+reg_write64(struct input_device *d, uint32_t reg, uint64_t value)
+{
+ reg_write(d, reg, (uint32_t)value);
+ reg_write(d, reg + 4, (uint32_t)(value >> 32));
+}
+
+extern void ustacks_now(const char *name);
+
+#define KEY_ENTER 28
+#define KEY_LEFTSHIFT 42
+#define KEY_RIGHTSHIFT 54
+#define KEY_F12 88
+
+/* F12 NAME Enter: the keys in between spell a process name. Returns true if the key was taken. */
+static bool
+command_key(uint16_t key, uint32_t value)
+{
+ static const char plain[] =
+ "\0\0001234567890-=\0\0qwertyuiop[]\0\0asdfghjkl;'`\0\\zxcvbnm,./\0\0\0 ";
+ static char name[32];
+ static unsigned length;
+ static bool active, shift;
+
+ if (key == KEY_F12) {
+ if (value == 1) {
+ active = true;
+ length = 0;
+ }
+ return true;
+ }
+ if (!active) {
+ return false;
+ }
+ if (key == KEY_LEFTSHIFT || key == KEY_RIGHTSHIFT) {
+ shift = value != 0;
+ } else if (value != 1) {
+ /* a release or a repeat */
+ } else if (key == KEY_ENTER) {
+ active = false;
+ name[length] = 0;
+ if (length) {
+ printf("virtio-input: stacks of \"%s\" asked for\n", name);
+ ustacks_now(name);
+ }
+ } else if (key < sizeof(plain) - 1 && plain[key] != 0 && length < sizeof(name) - 1) {
+ char c = plain[key];
+
+ if (shift && c >= 'a' && c <= 'z') {
+ c -= 'a' - 'A';
+ } else if (shift && c == '-') {
+ c = '_';
+ }
+ name[length++] = c;
+ }
+ return true;
+}
+
+/* Which of the phone's buttons a key stands for; 0 = none. */
+static uint32_t
+button_for_key(uint16_t key)
+{
+ switch (key) {
+ case 116: /* KEY_POWER */
+ case 38: /* KEY_L */
+ return REDWOOD_BUTTON_LOCK;
+ case 115: /* KEY_VOLUMEUP */
+ case 103: /* KEY_UP */
+ return REDWOOD_BUTTON_VOLUME_UP;
+ case 114: /* KEY_VOLUMEDOWN */
+ case 108: /* KEY_DOWN */
+ return REDWOOD_BUTTON_VOLUME_DOWN;
+ case 102: /* KEY_HOME */
+ case 35: /* KEY_H */
+ return REDWOOD_BUTTON_HOME;
+ }
+ return 0;
+}
+
+static void
+input_event(struct input_device *d, const struct input_event *e)
+{
+ uint32_t button;
+
+ switch (e->type) {
+ case EV_ABS:
+ if (e->code == ABS_X) {
+ d->x = e->value * 65535 / ABS_RANGE;
+ d->moved = true;
+ } else if (e->code == ABS_Y) {
+ d->y = e->value * 65535 / ABS_RANGE;
+ d->moved = true;
+ }
+ break;
+ case EV_KEY:
+ if (e->code == BTN_LEFT || e->code == BTN_TOUCH) {
+ d->pressed = e->value != 0;
+ } else if (command_key(e->code, e->value)) {
+ break;
+ } else if ((button = button_for_key(e->code)) != 0 && e->value < 2) { /* 2 = key repeat */
+ redwood_touch_post(e->value ? REDWOOD_BUTTON_DOWN : REDWOOD_BUTTON_UP, button, 0, 0);
+ }
+ break;
+ case EV_SYN:
+ if (d->pressed && !d->touching) {
+ redwood_touch_post(REDWOOD_TOUCH_DOWN, 0, d->x, d->y);
+ } else if (d->pressed && d->moved) {
+ redwood_touch_post(REDWOOD_TOUCH_MOVE, 0, d->x, d->y);
+ } else if (!d->pressed && d->touching) {
+ redwood_touch_post(REDWOOD_TOUCH_UP, 0, d->x, d->y);
+ }
+ d->touching = d->pressed;
+ d->moved = false;
+ break;
+ }
+}
+
+static void
+input_poll(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
+{
+ uint64_t deadline;
+
+ for (int i = 0; i < device_count; i++) {
+ struct input_device *d = &devices[i];
+ bool returned = false;
+
+ while (d->seen != *(volatile uint16_t *)&d->used->idx) {
+ uint32_t id = d->used->ring[d->seen++ % QUEUE_SIZE].id % QUEUE_SIZE;
+
+ input_event(d, &d->events[id]);
+ /* give the buffer back */
+ d->avail->ring[d->avail->idx % QUEUE_SIZE] = (uint16_t)id;
+ __builtin_arm_dmb(0xb); /* ISH */
+ d->avail->idx++;
+ returned = true;
+ }
+ if (returned) {
+ __builtin_arm_dmb(0xb);
+ reg_write(d, VIRTIO_QUEUE_NOTIFY, 0);
+ }
+ }
+ clock_interval_to_deadline(8, NSEC_PER_MSEC, &deadline);
+ thread_call_enter_delayed(poll_call, deadline);
+}
+
+static bool
+input_attach(struct input_device *d, int slot)
+{
+ vm_offset_t page = 0;
+ struct vq_desc *desc;
+ uint64_t phys;
+
+ if (kmem_alloc(kernel_map, &page, PAGE_SIZE, KMA_KOBJECT | KMA_ZERO | KMA_DATA, VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS) {
+ return false;
+ }
+ phys = kvtophys(page);
+ desc = (struct vq_desc *)(page + OFFSET_DESC);
+ d->avail = (struct vq_avail *)(page + OFFSET_AVAIL);
+ d->used = (struct vq_used *)(page + OFFSET_USED);
+ d->events = (struct input_event *)(page + OFFSET_EVENTS);
+
+ reg_write(d, VIRTIO_STATUS, 0); /* reset */
+ reg_write(d, VIRTIO_STATUS, STATUS_ACKNOWLEDGE);
+ reg_write(d, VIRTIO_STATUS, STATUS_ACKNOWLEDGE | STATUS_DRIVER);
+ reg_write(d, VIRTIO_DRIVER_FEATURES_SEL, 0);
+ reg_write(d, VIRTIO_DRIVER_FEATURES, 0);
+ reg_write(d, VIRTIO_DRIVER_FEATURES_SEL, 1);
+ reg_write(d, VIRTIO_DRIVER_FEATURES, 1); /* bit 32: VIRTIO_F_VERSION_1 */
+ reg_write(d, VIRTIO_STATUS, STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK);
+ if (!(reg_read(d, VIRTIO_STATUS) & STATUS_FEATURES_OK)) {
+ printf("virtio-input: slot %d: features refused\n", slot);
+ return false;
+ }
+
+ /* queue 0 brings the events: hand the device all the buffers */
+ reg_write(d, VIRTIO_QUEUE_SEL, 0);
+ if (reg_read(d, VIRTIO_QUEUE_NUM_MAX) < QUEUE_SIZE) {
+ printf("virtio-input: slot %d: event queue of %u\n", slot, reg_read(d, VIRTIO_QUEUE_NUM_MAX));
+ return false;
+ }
+ for (int i = 0; i < QUEUE_SIZE; i++) {
+ desc[i].addr = phys + OFFSET_EVENTS + (uint64_t)i * sizeof(struct input_event);
+ desc[i].len = sizeof(struct input_event);
+ desc[i].flags = DESC_F_WRITE;
+ d->avail->ring[i] = (uint16_t)i;
+ }
+ d->avail->flags = AVAIL_F_NO_INTERRUPT;
+ d->avail->idx = QUEUE_SIZE;
+ reg_write(d, VIRTIO_QUEUE_NUM, QUEUE_SIZE);
+ reg_write64(d, VIRTIO_QUEUE_DESC, phys + OFFSET_DESC);
+ reg_write64(d, VIRTIO_QUEUE_DRIVER, phys + OFFSET_AVAIL);
+ reg_write64(d, VIRTIO_QUEUE_DEVICE, phys + OFFSET_USED);
+ __builtin_arm_dmb(0xb);
+ reg_write(d, VIRTIO_QUEUE_READY, 1);
+ reg_write(d, VIRTIO_STATUS, STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK | STATUS_DRIVER_OK);
+ reg_write(d, VIRTIO_QUEUE_NOTIFY, 0);
+ return true;
+}
+
+void
+redwood_virtio_input_init(void)
+{
+ uint32_t enabled = 0;
+ vm_offset_t bus;
+
+ if (!PE_parse_boot_argn("virtio_input", &enabled, sizeof(enabled)) || !enabled) {
+ return;
+ }
+ bus = ml_io_map(VIRTIO_BUS, VIRTIO_SLOTS * VIRTIO_SLOT_SIZE);
+ for (int slot = 0; slot < VIRTIO_SLOTS && device_count < MAX_DEVICES; slot++) {
+ struct input_device *d = &devices[device_count];
+
+ d->regs = bus + (vm_offset_t)slot * VIRTIO_SLOT_SIZE;
+ if (reg_read(d, VIRTIO_MAGIC) != 0x74726976 || reg_read(d, VIRTIO_DEVICE_ID) != VIRTIO_ID_INPUT) {
+ continue;
+ }
+ if (reg_read(d, VIRTIO_VERSION) != 2) {
+ printf("virtio-input: slot %d is a legacy transport; start QEMU with -global virtio-mmio.force-legacy=false\n", slot);
+ continue;
+ }
+ if (input_attach(d, slot)) {
+ printf("virtio-input: device in slot %d\n", slot);
+ device_count++;
+ }
+ }
+ if (device_count) {
+ poll_call = thread_call_allocate(input_poll, NULL);
+ input_poll(NULL, NULL);
+ } else {
+ printf("virtio-input: no input devices\n");
+ }
+}
diff --git a/xnu/files/bsd/kern/kern_minimac.c b/xnu/files/bsd/kern/kern_minimac.c
new file mode 100644
index 0000000..ff4ab9d
--- /dev/null
+++ b/xnu/files/bsd/kern/kern_minimac.c
@@ -0,0 +1,163 @@
+/*
+ * Stand-ins for the two closed security policies user space cannot do
+ * without: AMFI and the Sandbox. On a device they are kexts that register
+ * MAC policies of those names; system software talks to them through
+ * __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
+ * user space needs in order to run at all:
+ *
+ * AMFI The binaries of the operating system carry ad hoc signatures
+ * (no certificate chain); on a device AMFI finds their hashes
+ * in the trust cache and flags them as platform binaries.
+ * launchd panics if a system daemon is not one. There is no
+ * trust cache here, so every ad hoc signed binary is taken for
+ * a platform binary. Unsigned programs (our own) are not.
+ *
+ * Sandbox Every query (may this process look up that service?) is
+ * answered "allowed", and every request to apply a profile
+ * succeeds without applying anything.
+ */
+
+#include <sys/param.h>
+#include <sys/systm.h>
+#include <sys/kernel.h>
+#include <sys/codesign.h>
+#include <sys/errno.h>
+#include <sys/kpi_socket.h>
+#include <sys/priv.h>
+#include <sys/proc_internal.h>
+#include <sys/ubc_internal.h>
+#include <sys/vnode_internal.h>
+#include <libkern/libkern.h>
+#include <security/mac_framework.h>
+#include <security/mac_policy.h>
+
+void minimac_policy_init(void);
+
+static int
+miniamfi_vnode_check_signature(__unused struct vnode *vp, __unused struct label *label, __unused cpu_type_t cpu_type,
+ struct cs_blob *cs_blob, unsigned int *cs_flags, __unused unsigned int *signer_type, __unused int flags,
+ __unused unsigned int platform, __unused char **fatal_failure_desc, __unused size_t *fatal_failure_desc_len)
+{
+ if (cs_blob == NULL) {
+ return 0;
+ }
+ /*
+ * Accepting a signature is what marks the process as signed; the
+ * kernel consults the signature of a process only when that is set.
+ */
+ *cs_flags |= CS_SIGNED;
+ if (*cs_flags & CS_ADHOC) {
+ *cs_flags |= CS_PLATFORM_BINARY;
+ }
+ return 0;
+}
+
+/*
+ * dyld asks AMFI what it may do for the process it is starting (request 0x5a, "check dyld
+ * policy"): the argument is { flags in, pointer to flags out }. Everything is allowed --
+ * @paths, the DYLD_* variables, inserted libraries and interposing -- which is what lets
+ * our own library be loaded into stock daemons (DYLD_INSERT_LIBRARIES).
+ */
+#define AMFI_SYSCALL_CHECK_DYLD_POLICY 0x5a
+#define AMFI_DYLD_OUTPUT_ALLOW_ALL 0xffULL
+
+static int
+miniamfi_policy_syscall(__unused struct proc *p, int call, user_addr_t arg)
+{
+ struct {
+ uint64_t input_flags;
+ user_addr_t output_flags;
+ } args;
+ uint64_t flags = AMFI_DYLD_OUTPUT_ALLOW_ALL;
+ int error;
+
+ if (call != AMFI_SYSCALL_CHECK_DYLD_POLICY) {
+ return ENOPOLICY; /* what user space got before there was a handler */
+ }
+ error = copyin(arg, &args, sizeof(args));
+ if (error == 0) {
+ error = copyout(&flags, args.output_flags, sizeof(flags));
+ }
+ return error;
+}
+
+static const struct mac_policy_ops miniamfi_ops = {
+ .mpo_vnode_check_signature = miniamfi_vnode_check_signature,
+ .mpo_policy_syscall = miniamfi_policy_syscall,
+};
+
+SECURITY_READ_ONLY_LATE(static struct mac_policy_conf) miniamfi_conf = {
+ .mpc_name = "AMFI",
+ .mpc_fullname = "Apple Mobile File Integrity (stand-in)",
+ .mpc_ops = &miniamfi_ops,
+};
+SECURITY_READ_ONLY_LATE(static mac_policy_handle_t) miniamfi_handle;
+
+/* Which request numbers have been seen: one log line each, to learn what user space asks for. */
+static uint64_t minisandbox_seen;
+
+static int
+minisandbox_policy_syscall(struct proc *p, int call, __unused user_addr_t arg)
+{
+ if (call >= 0 && call < 64 && (minisandbox_seen & (1ULL << call)) == 0) {
+ minisandbox_seen |= 1ULL << call;
+ printf("minisandbox: request %d (first seen from %s[%d]): allowed\n", call, p->p_comm, proc_getpid(p));
+ }
+ return 0;
+}
+
+/*
+ * Privileges for processes that are not root. On a device the sandbox hands them out by
+ * entitlement; here the ones the user interface cannot do without are simply granted:
+ *
+ * PRIV_WORK_INTERVAL telling the scheduler about the work of drawing a frame. UIKit does
+ * it as soon as anything scrolls, and takes a refusal for a programming
+ * error ("Failed to create work interval"): SpringBoard died of it on
+ * the first swipe between pages of the home screen.
+ *
+ * Whatever else is asked for is refused as before, and said once, to learn what there is.
+ */
+static int
+minisandbox_priv_grant(__unused kauth_cred_t cred, int priv)
+{
+ static int seen[16];
+ static unsigned seen_count;
+
+ if (priv == PRIV_WORK_INTERVAL) {
+ return 0;
+ }
+ for (unsigned i = 0; i < seen_count; i++) {
+ if (seen[i] == priv) {
+ return EPERM;
+ }
+ }
+ if (seen_count < sizeof(seen) / sizeof(seen[0])) {
+ seen[seen_count++] = priv;
+ printf("minisandbox: privilege %d refused to %s[%d] (first time)\n", priv, current_proc()->p_comm,
+ proc_getpid(current_proc()));
+ }
+ return EPERM;
+}
+
+static const struct mac_policy_ops minisandbox_ops = {
+ .mpo_policy_syscall = minisandbox_policy_syscall,
+ .mpo_priv_grant = minisandbox_priv_grant,
+};
+
+SECURITY_READ_ONLY_LATE(static struct mac_policy_conf) minisandbox_conf = {
+ .mpc_name = "Sandbox",
+ .mpc_fullname = "Seatbelt sandbox policy (stand-in)",
+ .mpc_ops = &minisandbox_ops,
+};
+SECURITY_READ_ONLY_LATE(static mac_policy_handle_t) minisandbox_handle;
+
+/* Called from kernel_bootstrap_thread() once the MAC framework is up. */
+void
+minimac_policy_init(void)
+{
+ mac_policy_register(&miniamfi_conf, &miniamfi_handle, NULL);
+ mac_policy_register(&minisandbox_conf, &minisandbox_handle, NULL);
+}
diff --git a/xnu/files/bsd/miscfs/packfs/packfs.h b/xnu/files/bsd/miscfs/packfs/packfs.h
new file mode 100644
index 0000000..46e3ffc
--- /dev/null
+++ b/xnu/files/bsd/miscfs/packfs/packfs.h
@@ -0,0 +1,114 @@
+/*
+ * packfs: a read-only filesystem for a boot image.
+ *
+ * The open-source kernel has no on-disk filesystem of its own (HFS and APFS
+ * are separate kexts, mockfs shows exactly one file), so the root of the
+ * bring-up system lives in this deliberately simple format. An image is
+ * built on the host by mkpackfs.py and consists of:
+ *
+ * superblock | node table | name strings | file data
+ *
+ * Node 0 is the root directory. The children of a directory occupy a
+ * contiguous run of the node table, sorted by name.
+ *
+ * A file is stored in one of two ways:
+ * - plain: one contiguous extent aligned to the image block size; the
+ * generic cluster layer does all the I/O through the block device;
+ * - chunked (PACKFS_F_CHUNKED): cut into chunks of PACKFS_CHUNK_SIZE bytes,
+ * each stored either LZ4-compressed (a raw LZ4 block) or, when that
+ * does not make it smaller, as it is. The extent starts with a table of
+ * 32-bit offsets, one per chunk and one more for the end, counted from
+ * the start of the extent; a chunk whose stored length equals its real
+ * length is not compressed. Chunked files are read straight out of the
+ * memory of a RAM disk, so an image that has them mounts only from a
+ * memory device. This is what lets a system that does not fit into RAM
+ * twice (once as the disk, once in the page cache) run from a RAM disk.
+ *
+ * Everything is little-endian. Nothing is ever written.
+ */
+#ifndef _MISCFS_PACKFS_H_
+#define _MISCFS_PACKFS_H_
+
+#include <stdint.h>
+
+#define PACKFS_MAGIC "PACKFS1" /* 8 bytes with the terminator */
+#define PACKFS_SUPER_SIZE 4096
+#define PACKFS_ROOT_NODE 0
+#define PACKFS_MAX_NAME 255
+
+struct packfs_super {
+ char ps_magic[8];
+ uint32_t ps_block_size; /* alignment of file data; a power of two, at least 4096 */
+ uint32_t ps_node_count;
+ uint64_t ps_nodes_off; /* byte offset of the node table */
+ uint64_t ps_strings_off; /* byte offset of the string area */
+ uint64_t ps_strings_size;
+ uint64_t ps_data_off; /* byte offset of the first file extent */
+ uint64_t ps_image_size;
+ uint64_t ps_create_time; /* seconds since the epoch */
+};
+
+struct packfs_dnode {
+ uint32_t pd_mode; /* file type and permission bits, as in st_mode */
+ uint32_t pd_uid;
+ uint32_t pd_gid;
+ uint32_t pd_nlink;
+ uint64_t pd_size; /* file: bytes; symlink: target length; directory: number of children */
+ uint64_t pd_data; /* file: byte offset of the extent; symlink: offset of the target in the
+ * string area; directory: node index of the first child */
+ uint32_t pd_parent; /* node index of the containing directory (the root is its own parent) */
+ uint32_t pd_name; /* offset of the name in the string area */
+ uint32_t pd_name_len;
+ uint32_t pd_rdev;
+ uint64_t pd_mtime; /* seconds since the epoch */
+ uint64_t pd_flags; /* PACKFS_F_* */
+};
+
+#define PACKFS_F_CHUNKED 0x1 /* the extent is a chunk table followed by the chunks */
+#define PACKFS_CHUNK_SIZE 65536 /* a multiple of every page size we run with */
+
+#ifdef KERNEL
+
+#include <kern/locks.h>
+#include <sys/mount.h>
+#include <sys/vnode.h>
+
+/* In-core state of one node: the vnode currently standing for it, if any. */
+struct packfs_inode {
+ vnode_t pi_vp;
+ uint32_t pi_vid;
+ uint32_t pi_flags;
+};
+#define PACKFS_I_CREATING 0x1 /* a thread is in vnode_create() for this node */
+#define PACKFS_I_WANTED 0x2 /* somebody sleeps on the node */
+
+struct packfs_mount {
+ mount_t pm_mp;
+ vnode_t pm_devvp;
+ struct packfs_super pm_super;
+ struct packfs_dnode *pm_nodes; /* the whole node table */
+ char *pm_strings; /* the whole string area */
+ struct packfs_inode *pm_inodes; /* one per node */
+ const uint8_t *pm_membase; /* the image in kernel memory, when the device is a RAM disk */
+ uint64_t pm_memsize;
+ lck_mtx_t pm_lock; /* guards pm_inodes */
+};
+
+#define PACKFS_MP(mp) ((struct packfs_mount *)vfs_fsprivate(mp))
+#define PACKFS_VP_MOUNT(vp) PACKFS_MP(vnode_mount(vp))
+/* File numbers start at 2, the traditional number of a root directory. */
+#define PACKFS_INO(index) ((uint64_t)(index) + 2)
+
+static inline uint32_t
+packfs_vp_index(struct packfs_mount *pm, vnode_t vp)
+{
+ return (uint32_t)((struct packfs_inode *)vnode_fsnode(vp) - pm->pm_inodes);
+}
+
+int packfs_mountroot(mount_t mp, vnode_t devvp, vfs_context_t ctx);
+int packfs_node_vnode(struct packfs_mount *pm, uint32_t index, vnode_t dvp, struct componentname *cnp, vnode_t *vpp);
+
+extern int(**packfs_vnodeop_p)(void *);
+
+#endif /* KERNEL */
+#endif /* _MISCFS_PACKFS_H_ */
diff --git a/xnu/files/bsd/miscfs/packfs/packfs_vfsops.c b/xnu/files/bsd/miscfs/packfs/packfs_vfsops.c
new file mode 100644
index 0000000..0b94794
--- /dev/null
+++ b/xnu/files/bsd/miscfs/packfs/packfs_vfsops.c
@@ -0,0 +1,417 @@
+/*
+ * packfs mount-level operations. See packfs.h for the image format.
+ */
+
+#include <kern/assert.h>
+#include <kern/kalloc.h>
+#include <libkern/libkern.h>
+#include <miscfs/packfs/packfs.h>
+#include <sys/attr.h>
+#include <sys/buf.h>
+#include <sys/disk.h>
+#include <sys/errno.h>
+#include <sys/kauth.h>
+#include <sys/mount_internal.h>
+#include <sys/stat.h>
+#include <sys/systm.h>
+#include <sys/vnode_internal.h>
+
+extern int mdevgetkernelrange(dev_t dev, vm_offset_t *base, uint64_t *size);
+
+static LCK_GRP_DECLARE(packfs_lck_grp, "packfs");
+
+/* Metadata is read from the device in pieces of this size; all metadata offsets are multiples of it. */
+#define PACKFS_META_CHUNK 4096
+/* Refuse absurd images instead of trying to allocate for them. */
+#define PACKFS_MAX_NODES (4u * 1024 * 1024)
+#define PACKFS_MAX_STRINGS (256ull * 1024 * 1024)
+
+static int
+packfs_read_meta(vnode_t devvp, uint32_t devblock, uint64_t offset, void *dst, uint64_t length)
+{
+ char *out = dst;
+
+ while (length > 0) {
+ buf_t bp = NULL;
+ uint64_t chunk = MIN(length, PACKFS_META_CHUNK);
+ int error = (int)buf_meta_bread(devvp, (daddr64_t)(offset / devblock), PACKFS_META_CHUNK, NOCRED, &bp);
+
+ if (error) {
+ if (bp) {
+ buf_brelse(bp);
+ }
+ return error;
+ }
+ memcpy(out, (const void *)buf_dataptr(bp), chunk);
+ buf_markinvalid(bp);
+ buf_brelse(bp);
+
+ out += chunk;
+ offset += chunk;
+ length -= chunk;
+ }
+ return 0;
+}
+
+static bool
+packfs_range_ok(uint64_t start, uint64_t length, uint64_t limit)
+{
+ return start <= limit && length <= limit - start;
+}
+
+/* Reject an image the vnode operations could not walk safely; they do not re-check. */
+static int
+packfs_validate(const struct packfs_mount *pm)
+{
+ const struct packfs_super *ps = &pm->pm_super;
+
+ for (uint32_t i = 0; i < ps->ps_node_count; i++) {
+ const struct packfs_dnode *dn = &pm->pm_nodes[i];
+
+ if (dn->pd_name_len > PACKFS_MAX_NAME ||
+ !packfs_range_ok(dn->pd_name, (uint64_t)dn->pd_name_len + 1, ps->ps_strings_size) ||
+ pm->pm_strings[dn->pd_name + dn->pd_name_len] != '\0' ||
+ dn->pd_parent >= ps->ps_node_count || !S_ISDIR(pm->pm_nodes[dn->pd_parent].pd_mode)) {
+ return EINVAL;
+ }
+
+ switch (dn->pd_mode & S_IFMT) {
+ case S_IFDIR:
+ if (!packfs_range_ok(dn->pd_data, dn->pd_size, ps->ps_node_count)) {
+ return EINVAL;
+ }
+ for (uint64_t c = 0; c < dn->pd_size; c++) {
+ if (pm->pm_nodes[dn->pd_data + c].pd_parent != i || dn->pd_data + c == PACKFS_ROOT_NODE) {
+ return EINVAL;
+ }
+ }
+ break;
+ case S_IFREG:
+ if (dn->pd_size == 0) {
+ break;
+ }
+ if (dn->pd_flags & PACKFS_F_CHUNKED) {
+ uint64_t chunks = (dn->pd_size + PACKFS_CHUNK_SIZE - 1) / PACKFS_CHUNK_SIZE;
+ uint32_t previous = (uint32_t)((chunks + 1) * sizeof(uint32_t)), offset;
+
+ /* read in place: only from a RAM disk, and the whole table must make sense */
+ if (pm->pm_membase == NULL || (dn->pd_data & 7) != 0 || dn->pd_data < ps->ps_data_off ||
+ !packfs_range_ok(dn->pd_data, (chunks + 1) * sizeof(uint32_t), ps->ps_image_size)) {
+ return pm->pm_membase == NULL ? ENOTSUP : EINVAL;
+ }
+ for (uint64_t c = 0; c <= chunks; c++) {
+ memcpy(&offset, pm->pm_membase + dn->pd_data + c * sizeof(uint32_t), sizeof(offset));
+ if (offset < previous || (c == 0 && offset != previous) ||
+ (c != 0 && offset - previous > PACKFS_CHUNK_SIZE) ||
+ !packfs_range_ok(dn->pd_data, offset, ps->ps_image_size)) {
+ return EINVAL;
+ }
+ previous = offset;
+ }
+ } else if ((dn->pd_data & (ps->ps_block_size - 1)) != 0 || dn->pd_data < ps->ps_data_off ||
+ !packfs_range_ok(dn->pd_data, dn->pd_size, ps->ps_image_size)) {
+ return EINVAL;
+ }
+ break;
+ case S_IFLNK:
+ if (dn->pd_size == 0 || dn->pd_size >= MAXPATHLEN ||
+ !packfs_range_ok(dn->pd_data, dn->pd_size, ps->ps_strings_size)) {
+ return EINVAL;
+ }
+ break;
+ default:
+ return EINVAL;
+ }
+ }
+
+ if (!S_ISDIR(pm->pm_nodes[PACKFS_ROOT_NODE].pd_mode) || pm->pm_nodes[PACKFS_ROOT_NODE].pd_parent != PACKFS_ROOT_NODE) {
+ return EINVAL;
+ }
+ return 0;
+}
+
+static void
+packfs_free_mount(struct packfs_mount *pm)
+{
+ const struct packfs_super *ps = &pm->pm_super;
+
+ if (pm->pm_inodes) {
+ kfree_type(struct packfs_inode, ps->ps_node_count, pm->pm_inodes);
+ }
+ if (pm->pm_strings) {
+ kfree_data(pm->pm_strings, ps->ps_strings_size);
+ }
+ if (pm->pm_nodes) {
+ kfree_data(pm->pm_nodes, (vm_size_t)ps->ps_node_count * sizeof(struct packfs_dnode));
+ }
+ lck_mtx_destroy(&pm->pm_lock, &packfs_lck_grp);
+ kfree_type(struct packfs_mount, pm);
+}
+
+/*
+ * Mount the image on devvp, an opened block device. EINVAL means "this is
+ * not a packfs image".
+ */
+static int
+packfs_mount_common(mount_t mp, vnode_t devvp, vfs_context_t ctx)
+{
+ struct packfs_mount *pm;
+ struct packfs_super *ps;
+ struct vfsstatfs *sp;
+ uint32_t devblock = 0;
+ char *block0;
+ int error;
+
+ if (VNOP_IOCTL(devvp, DKIOCGETBLOCKSIZE, (caddr_t)&devblock, 0, ctx) != 0 ||
+ devblock == 0 || (PACKFS_META_CHUNK % devblock) != 0) {
+ return EINVAL;
+ }
+
+ pm = kalloc_type(struct packfs_mount, Z_WAITOK | Z_ZERO | Z_NOFAIL);
+ lck_mtx_init(&pm->pm_lock, &packfs_lck_grp, LCK_ATTR_NULL);
+ pm->pm_mp = mp;
+ pm->pm_devvp = devvp;
+ ps = &pm->pm_super;
+
+ block0 = kalloc_data(PACKFS_SUPER_SIZE, Z_WAITOK | Z_NOFAIL);
+ error = packfs_read_meta(devvp, devblock, 0, block0, PACKFS_SUPER_SIZE);
+ if (!error) {
+ memcpy(ps, block0, sizeof(*ps));
+ }
+ kfree_data(block0, PACKFS_SUPER_SIZE);
+ if (error) {
+ goto fail;
+ }
+
+ error = EINVAL;
+ if (memcmp(ps->ps_magic, PACKFS_MAGIC, sizeof(ps->ps_magic)) != 0) {
+ /* Leave the counts alone for packfs_free_mount(): nothing was allocated yet. */
+ goto fail;
+ }
+ if (ps->ps_block_size < PACKFS_META_CHUNK || (ps->ps_block_size & (ps->ps_block_size - 1)) != 0 ||
+ ps->ps_node_count == 0 || ps->ps_node_count > PACKFS_MAX_NODES ||
+ ps->ps_strings_size == 0 || ps->ps_strings_size > PACKFS_MAX_STRINGS ||
+ (ps->ps_nodes_off % PACKFS_META_CHUNK) != 0 || (ps->ps_strings_off % PACKFS_META_CHUNK) != 0 ||
+ !packfs_range_ok(ps->ps_nodes_off, (uint64_t)ps->ps_node_count * sizeof(struct packfs_dnode), ps->ps_image_size) ||
+ !packfs_range_ok(ps->ps_strings_off, ps->ps_strings_size, ps->ps_image_size) ||
+ ps->ps_data_off > ps->ps_image_size) {
+ printf("packfs: bad superblock\n");
+ goto fail;
+ }
+
+ pm->pm_nodes = kalloc_data((vm_size_t)ps->ps_node_count * sizeof(struct packfs_dnode), Z_WAITOK);
+ pm->pm_strings = kalloc_data(ps->ps_strings_size, Z_WAITOK);
+ pm->pm_inodes = kalloc_type(struct packfs_inode, ps->ps_node_count, Z_WAITOK | Z_ZERO);
+ if (!pm->pm_nodes || !pm->pm_strings || !pm->pm_inodes) {
+ error = ENOMEM;
+ goto fail;
+ }
+
+ /* a RAM disk can be read where it lies (needed for chunked files) */
+ {
+ vm_offset_t membase = 0;
+ uint64_t memsize = 0;
+
+ if (mdevgetkernelrange(vnode_specrdev(devvp), &membase, &memsize) == 0 && memsize >= ps->ps_image_size) {
+ pm->pm_membase = (const uint8_t *)membase;
+ pm->pm_memsize = memsize;
+ }
+ }
+
+ error = packfs_read_meta(devvp, devblock, ps->ps_nodes_off, pm->pm_nodes,
+ (uint64_t)ps->ps_node_count * sizeof(struct packfs_dnode));
+ if (!error) {
+ error = packfs_read_meta(devvp, devblock, ps->ps_strings_off, pm->pm_strings, ps->ps_strings_size);
+ }
+ if (!error) {
+ error = packfs_validate(pm);
+ if (error == ENOTSUP) {
+ printf("packfs: an image with compressed files mounts only from a RAM disk\n");
+ } else if (error) {
+ printf("packfs: inconsistent image\n");
+ }
+ }
+ if (error) {
+ goto fail;
+ }
+
+ vfs_setfsprivate(mp, pm);
+ vfs_setflags(mp, MNT_RDONLY | MNT_LOCAL);
+ /* Advisory locks need nothing from the filesystem: let VFS keep them. */
+ vfs_setlocklocal(mp);
+
+ sp = vfs_statfs(mp);
+ sp->f_bsize = ps->ps_block_size;
+ sp->f_iosize = ps->ps_block_size;
+ sp->f_blocks = ps->ps_image_size / ps->ps_block_size;
+ sp->f_bfree = 0;
+ sp->f_bavail = 0;
+ sp->f_bused = sp->f_blocks;
+ sp->f_files = ps->ps_node_count;
+ sp->f_ffree = 0;
+ sp->f_fsid.val[0] = (int32_t)vnode_specrdev(devvp);
+ sp->f_fsid.val[1] = vfs_typenum(mp);
+
+ printf("packfs: image with %u nodes, %llu KB%s\n", ps->ps_node_count, (unsigned long long)ps->ps_image_size / 1024,
+ pm->pm_membase ? ", read in place" : "");
+ return 0;
+
+fail:
+ if (error == EINVAL && pm->pm_nodes == NULL) {
+ /* Not ours, or rejected before any table was allocated: the counts may be garbage. */
+ ps->ps_node_count = 0;
+ ps->ps_strings_size = 0;
+ }
+ packfs_free_mount(pm);
+ return error;
+}
+
+/* As the root filesystem: EINVAL lets vfs_mountroot() try the next filesystem quietly. */
+int
+packfs_mountroot(mount_t mp, vnode_t devvp, vfs_context_t ctx)
+{
+ return packfs_mount_common(mp, devvp, ctx);
+}
+
+/*
+ * mount(2). The argument block starts with a pointer to the device path
+ * (struct { char *fspec; }); VFS has already resolved and opened it as devvp.
+ */
+static int
+packfs_mount(mount_t mp, vnode_t devvp, __unused user_addr_t data, vfs_context_t ctx)
+{
+ if (vfs_isupdate(mp)) {
+ /* nothing about a mounted image can change, least of all to read-write */
+ return vfs_iswriteupgrade(mp) ? EROFS : 0;
+ }
+ if (devvp == NULLVP) {
+ return EINVAL;
+ }
+ return packfs_mount_common(mp, devvp, ctx);
+}
+
+static int
+packfs_unmount(mount_t mp, int mntflags, __unused vfs_context_t ctx)
+{
+ struct packfs_mount *pm = PACKFS_MP(mp);
+ int error;
+
+ error = vflush(mp, NULLVP, (mntflags & MNT_FORCE) ? FORCECLOSE : 0);
+ if (error) {
+ return error;
+ }
+ vfs_setfsprivate(mp, NULL);
+ packfs_free_mount(pm);
+ return 0;
+}
+
+static int
+packfs_root(mount_t mp, vnode_t *vpp, __unused vfs_context_t ctx)
+{
+ return packfs_node_vnode(PACKFS_MP(mp), PACKFS_ROOT_NODE, NULLVP, NULL, vpp);
+}
+
+static int
+packfs_vget(mount_t mp, ino64_t ino, vnode_t *vpp, __unused vfs_context_t ctx)
+{
+ struct packfs_mount *pm = PACKFS_MP(mp);
+
+ if (ino < PACKFS_INO(0) || ino - PACKFS_INO(0) >= pm->pm_super.ps_node_count) {
+ return ENOENT;
+ }
+ return packfs_node_vnode(pm, (uint32_t)(ino - PACKFS_INO(0)), NULLVP, NULL, vpp);
+}
+
+static int
+packfs_vfs_getattr(mount_t mp, struct vfs_attr *fsap, __unused vfs_context_t ctx)
+{
+ const struct packfs_super *ps = &PACKFS_MP(mp)->pm_super;
+ uint64_t blocks = ps->ps_image_size / ps->ps_block_size;
+
+ VFSATTR_RETURN(fsap, f_objcount, ps->ps_node_count);
+ VFSATTR_RETURN(fsap, f_bsize, ps->ps_block_size);
+ VFSATTR_RETURN(fsap, f_iosize, ps->ps_block_size);
+ VFSATTR_RETURN(fsap, f_blocks, blocks);
+ VFSATTR_RETURN(fsap, f_bfree, 0);
+ VFSATTR_RETURN(fsap, f_bavail, 0);
+ VFSATTR_RETURN(fsap, f_bused, blocks);
+ VFSATTR_RETURN(fsap, f_files, ps->ps_node_count);
+ VFSATTR_RETURN(fsap, f_ffree, 0);
+
+ if (VFSATTR_IS_ACTIVE(fsap, f_capabilities)) {
+ vol_capabilities_attr_t *cap = &fsap->f_capabilities;
+
+ bzero(cap, sizeof(*cap));
+ cap->capabilities[VOL_CAPABILITIES_FORMAT] =
+ VOL_CAP_FMT_SYMBOLICLINKS |
+ VOL_CAP_FMT_NO_ROOT_TIMES |
+ VOL_CAP_FMT_CASE_SENSITIVE |
+ VOL_CAP_FMT_CASE_PRESERVING |
+ VOL_CAP_FMT_FAST_STATFS |
+ VOL_CAP_FMT_2TB_FILESIZE;
+ cap->capabilities[VOL_CAPABILITIES_INTERFACES] =
+ VOL_CAP_INT_ADVLOCK |
+ VOL_CAP_INT_FLOCK;
+ cap->valid[VOL_CAPABILITIES_FORMAT] =
+ VOL_CAP_FMT_PERSISTENTOBJECTIDS |
+ VOL_CAP_FMT_SYMBOLICLINKS |
+ VOL_CAP_FMT_HARDLINKS |
+ VOL_CAP_FMT_JOURNAL |
+ VOL_CAP_FMT_JOURNAL_ACTIVE |
+ VOL_CAP_FMT_NO_ROOT_TIMES |
+ VOL_CAP_FMT_SPARSE_FILES |
+ VOL_CAP_FMT_ZERO_RUNS |
+ VOL_CAP_FMT_CASE_SENSITIVE |
+ VOL_CAP_FMT_CASE_PRESERVING |
+ VOL_CAP_FMT_FAST_STATFS |
+ VOL_CAP_FMT_2TB_FILESIZE |
+ VOL_CAP_FMT_OPENDENYMODES |
+ VOL_CAP_FMT_HIDDEN_FILES |
+ VOL_CAP_FMT_PATH_FROM_ID;
+ cap->valid[VOL_CAPABILITIES_INTERFACES] =
+ VOL_CAP_INT_SEARCHFS |
+ VOL_CAP_INT_ATTRLIST |
+ VOL_CAP_INT_NFSEXPORT |
+ VOL_CAP_INT_READDIRATTR |
+ VOL_CAP_INT_EXCHANGEDATA |
+ VOL_CAP_INT_COPYFILE |
+ VOL_CAP_INT_ALLOCATE |
+ VOL_CAP_INT_VOL_RENAME |
+ VOL_CAP_INT_ADVLOCK |
+ VOL_CAP_INT_FLOCK |
+ VOL_CAP_INT_EXTENDED_SECURITY |
+ VOL_CAP_INT_USERACCESS |
+ VOL_CAP_INT_MANLOCK |
+ VOL_CAP_INT_EXTENDED_ATTR |
+ VOL_CAP_INT_NAMEDSTREAMS;
+ VFSATTR_SET_SUPPORTED(fsap, f_capabilities);
+ }
+
+ if (VFSATTR_IS_ACTIVE(fsap, f_vol_name)) {
+ strlcpy(fsap->f_vol_name, "packfs", MAXPATHLEN);
+ VFSATTR_SET_SUPPORTED(fsap, f_vol_name);
+ }
+ return 0;
+}
+
+static int
+packfs_sync(__unused mount_t mp, __unused int waitfor, __unused vfs_context_t ctx)
+{
+ return 0;
+}
+
+static int
+packfs_init(__unused struct vfsconf *vfsc)
+{
+ return 0;
+}
+
+struct vfsops packfs_vfsops = {
+ .vfs_mount = packfs_mount,
+ .vfs_unmount = packfs_unmount,
+ .vfs_root = packfs_root,
+ .vfs_getattr = packfs_vfs_getattr,
+ .vfs_sync = packfs_sync,
+ .vfs_vget = packfs_vget,
+ .vfs_init = packfs_init,
+};
diff --git a/xnu/files/bsd/miscfs/packfs/packfs_vnops.c b/xnu/files/bsd/miscfs/packfs/packfs_vnops.c
new file mode 100644
index 0000000..54a623d
--- /dev/null
+++ b/xnu/files/bsd/miscfs/packfs/packfs_vnops.c
@@ -0,0 +1,733 @@
+/*
+ * packfs vnode operations. See packfs.h for the image format.
+ *
+ * The node table and all names are in memory after mount, so every
+ * operation except reading file data is a table walk. File data goes through
+ * the cluster layer: a file is a single extent of the backing device.
+ */
+
+#include <kern/assert.h>
+#include <kern/kalloc.h>
+#include <libkern/libkern.h>
+#include <miscfs/packfs/packfs.h>
+#include <sys/buf.h>
+#include <sys/dirent.h>
+#include <sys/errno.h>
+#include <sys/mount_internal.h>
+#include <sys/namei.h>
+#include <sys/stat.h>
+#include <sys/systm.h>
+#include <sys/ubc.h>
+#include <sys/uio.h>
+#include <sys/unistd.h>
+#include <sys/vnode_internal.h>
+#include <vfs/vfs_support.h>
+
+static const char *
+packfs_name(const struct packfs_mount *pm, const struct packfs_dnode *dn)
+{
+ return pm->pm_strings + dn->pd_name;
+}
+
+static enum vtype
+packfs_vtype(const struct packfs_dnode *dn)
+{
+ switch (dn->pd_mode & S_IFMT) {
+ case S_IFDIR:
+ return VDIR;
+ case S_IFLNK:
+ return VLNK;
+ default:
+ return VREG;
+ }
+}
+
+/* The space a file occupies on the device: its size rounded up to whole image blocks. */
+static uint64_t
+packfs_extent_size(const struct packfs_mount *pm, const struct packfs_dnode *dn)
+{
+ uint64_t block = pm->pm_super.ps_block_size;
+
+ if (dn->pd_flags & PACKFS_F_CHUNKED) {
+ uint64_t chunks = (dn->pd_size + PACKFS_CHUNK_SIZE - 1) / PACKFS_CHUNK_SIZE;
+ uint32_t end;
+
+ memcpy(&end, pm->pm_membase + dn->pd_data + chunks * sizeof(uint32_t), sizeof(end));
+ return end;
+ }
+ return (dn->pd_size + block - 1) & ~(block - 1);
+}
+
+/*
+ * Chunked files (see packfs.h). Nothing goes through the block device: a chunk is
+ * decompressed, or copied, from the RAM disk straight into pages of the file's cache.
+ */
+extern size_t lz4raw_decode_buffer(uint8_t *dst_buffer, size_t dst_size, const uint8_t *src_buffer, size_t src_size,
+ void *work);
+
+/* Put chunk `index` of the file at dst and fill the rest of dst_size (at least the chunk's length) with zeros. */
+static int
+packfs_chunk(const struct packfs_mount *pm, const struct packfs_dnode *dn, uint64_t index, uint8_t *dst, size_t dst_size)
+{
+ const uint8_t *extent = pm->pm_membase + dn->pd_data;
+ uint64_t raw = MIN((uint64_t)PACKFS_CHUNK_SIZE, dn->pd_size - index * PACKFS_CHUNK_SIZE);
+ uint32_t begin, end;
+
+ memcpy(&begin, extent + index * sizeof(uint32_t), sizeof(begin));
+ memcpy(&end, extent + (index + 1) * sizeof(uint32_t), sizeof(end));
+ if (dst_size < raw) {
+ return EINVAL;
+ }
+ if (end - begin == raw) {
+ memcpy(dst, extent + begin, raw);
+ } else if (lz4raw_decode_buffer(dst, raw, extent + begin, end - begin, NULL) != raw) {
+ printf("packfs: chunk %llu of node %u does not decompress\n", (unsigned long long)index,
+ (uint32_t)(dn - pm->pm_nodes));
+ return EIO;
+ }
+ if (dst_size > raw) {
+ bzero(dst + raw, dst_size - raw);
+ }
+ return 0;
+}
+
+/*
+ * read() of a chunked file. What is in the file's cache already is copied from there; where
+ * it is not, the chunk is brought into the cache (so that the next reader, or a mapping,
+ * finds it) and copied out from the same pages.
+ */
+static int
+packfs_read_chunked(vnode_t vp, struct uio *uio, const struct packfs_mount *pm, const struct packfs_dnode *dn)
+{
+ off_t size = (off_t)dn->pd_size;
+ int error = 0;
+
+ while (uio_resid(uio) > 0 && uio_offset(uio) < size) {
+ off_t offset = uio_offset(uio);
+ int wanted = (int)MIN((off_t)MIN(uio_resid(uio), (user_ssize_t)INT_MAX), size - offset);
+ int left = wanted;
+ off_t start, length;
+ upl_page_info_t *pages;
+ vm_offset_t address;
+ upl_t upl;
+
+ error = cluster_copy_ubc_data(vp, uio, &left, 0);
+ if (error) {
+ break;
+ }
+ if (left != wanted) {
+ continue; /* got something from the cache: see what is still missing */
+ }
+
+ start = offset - (offset % PACKFS_CHUNK_SIZE);
+ length = MIN((off_t)PACKFS_CHUNK_SIZE, (off_t)round_page_64((uint64_t)size) - start);
+ if (ubc_create_upl_kernel(vp, start, (int)length, &upl, &pages, UPL_SET_LITE, VM_KERN_MEMORY_FILE) != KERN_SUCCESS) {
+ error = EIO;
+ break;
+ }
+ if (ubc_upl_map(upl, &address) != KERN_SUCCESS) {
+ ubc_upl_abort_range(upl, 0, (upl_size_t)length, UPL_ABORT_FREE_ON_EMPTY);
+ error = ENOMEM;
+ break;
+ }
+ error = packfs_chunk(pm, dn, (uint64_t)start / PACKFS_CHUNK_SIZE, (uint8_t *)address, (size_t)length);
+ if (!error) {
+ error = uiomove((caddr_t)address + (offset - start),
+ (int)MIN((off_t)wanted, MIN(size, start + length) - offset), uio);
+ }
+ ubc_upl_unmap(upl);
+ if (error) {
+ ubc_upl_abort_range(upl, 0, (upl_size_t)length, UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_ERROR);
+ break;
+ }
+ ubc_upl_commit_range(upl, 0, (upl_size_t)length, UPL_COMMIT_FREE_ON_EMPTY | UPL_COMMIT_INACTIVATE);
+ }
+ return error;
+}
+
+/* Page-in for a chunked file: fill the pages the VM system asks for. */
+static int
+packfs_pagein_chunked(struct vnop_pagein_args *ap, const struct packfs_mount *pm, const struct packfs_dnode *dn)
+{
+ upl_t upl = ap->a_pl;
+ upl_offset_t upl_offset = ap->a_pl_offset;
+ off_t offset = ap->a_f_offset, end = ap->a_f_offset + (off_t)ap->a_size;
+ off_t size = (off_t)dn->pd_size;
+ vm_offset_t address;
+ uint8_t *bounce = NULL;
+ int error = 0;
+
+ if (upl == NULL) {
+ return EINVAL;
+ }
+ if (offset < 0 || (offset & PAGE_MASK_64) || (ap->a_size & PAGE_MASK) || (upl_offset & PAGE_MASK)) {
+ error = EINVAL;
+ } else if (ubc_upl_map(upl, &address) != KERN_SUCCESS) {
+ error = ENOMEM;
+ }
+ if (error) {
+ if (!(ap->a_flags & UPL_NOCOMMIT)) {
+ ubc_upl_abort_range(upl, upl_offset, (upl_size_t)ap->a_size, UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_ERROR);
+ }
+ return error;
+ }
+
+ for (off_t at = offset; at < end && !error;) {
+ uint8_t *dst = (uint8_t *)address + upl_offset + (at - offset);
+ off_t chunk_start = at - (at % PACKFS_CHUNK_SIZE);
+ off_t take = MIN(end, chunk_start + PACKFS_CHUNK_SIZE) - at;
+
+ if (at >= size) {
+ bzero(dst, (size_t)(end - at)); /* past the end of the file */
+ break;
+ }
+ if (at == chunk_start && take >= MIN((off_t)PACKFS_CHUNK_SIZE, size - chunk_start)) {
+ /* the whole chunk is wanted: decompress into place */
+ error = packfs_chunk(pm, dn, (uint64_t)chunk_start / PACKFS_CHUNK_SIZE, dst, (size_t)take);
+ } else {
+ /* a part of the chunk: decompress aside and copy the part */
+ if (bounce == NULL) {
+ bounce = kalloc_data(PACKFS_CHUNK_SIZE, Z_WAITOK);
+ }
+ error = bounce ? packfs_chunk(pm, dn, (uint64_t)chunk_start / PACKFS_CHUNK_SIZE, bounce, PACKFS_CHUNK_SIZE)
+ : ENOMEM;
+ if (!error) {
+ memcpy(dst, bounce + (at - chunk_start), (size_t)take);
+ }
+ }
+ at += take;
+ }
+ if (bounce != NULL) {
+ kfree_data(bounce, PACKFS_CHUNK_SIZE);
+ }
+ ubc_upl_unmap(upl);
+ if (!(ap->a_flags & UPL_NOCOMMIT)) {
+ if (error) {
+ ubc_upl_abort_range(upl, upl_offset, (upl_size_t)ap->a_size, UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_ERROR);
+ } else {
+ ubc_upl_commit_range(upl, upl_offset, (upl_size_t)ap->a_size, UPL_COMMIT_FREE_ON_EMPTY);
+ }
+ }
+ return error;
+}
+
+/*
+ * Return the vnode for a node with an iocount, creating it if there is none.
+ * dvp and cnp are the directory and the name it was looked up by, when known.
+ */
+int
+packfs_node_vnode(struct packfs_mount *pm, uint32_t index, vnode_t dvp, struct componentname *cnp, vnode_t *vpp)
+{
+ struct packfs_inode *ip = &pm->pm_inodes[index];
+ const struct packfs_dnode *dn = &pm->pm_nodes[index];
+ struct vnode_fsparam param;
+ vnode_t parent = NULLVP;
+ vnode_t vp;
+ int error;
+
+ lck_mtx_lock(&pm->pm_lock);
+ for (;;) {
+ uint32_t vid;
+
+ if (ip->pi_flags & PACKFS_I_CREATING) {
+ ip->pi_flags |= PACKFS_I_WANTED;
+ msleep(ip, &pm->pm_lock, PINOD, "packfs_create", NULL);
+ continue;
+ }
+ vp = ip->pi_vp;
+ if (vp == NULLVP) {
+ break;
+ }
+ vid = ip->pi_vid;
+ lck_mtx_unlock(&pm->pm_lock);
+
+ if (vnode_getwithvid(vp, vid) == 0) {
+ if (cnp && dvp && (cnp->cn_flags & MAKEENTRY)) {
+ cache_enter(dvp, vp, cnp);
+ }
+ *vpp = vp;
+ return 0;
+ }
+
+ /* The vnode is being reclaimed; packfs_reclaim() wakes us once it has let go of the node. */
+ lck_mtx_lock(&pm->pm_lock);
+ if (ip->pi_vp == vp && ip->pi_vid == vid) {
+ ip->pi_flags |= PACKFS_I_WANTED;
+ msleep(ip, &pm->pm_lock, PINOD, "packfs_reclaim", NULL);
+ }
+ }
+ ip->pi_flags |= PACKFS_I_CREATING;
+ lck_mtx_unlock(&pm->pm_lock);
+
+ /* Every vnode but the root knows its parent, which is what path reconstruction relies on. */
+ error = 0;
+ if (index != PACKFS_ROOT_NODE && dvp == NULLVP) {
+ error = packfs_node_vnode(pm, dn->pd_parent, NULLVP, NULL, &parent);
+ dvp = parent;
+ }
+
+ vp = NULLVP;
+ if (!error) {
+ bool enter = cnp && (cnp->cn_flags & MAKEENTRY);
+
+ bzero(&param, sizeof(param));
+ param.vnfs_mp = pm->pm_mp;
+ param.vnfs_vtype = packfs_vtype(dn);
+ param.vnfs_str = "packfs";
+ param.vnfs_dvp = dvp;
+ param.vnfs_fsnode = ip;
+ param.vnfs_vops = packfs_vnodeop_p;
+ param.vnfs_markroot = (index == PACKFS_ROOT_NODE);
+ param.vnfs_marksystem = 0;
+ param.vnfs_rdev = 0;
+ param.vnfs_filesize = S_ISREG(dn->pd_mode) ? (off_t)dn->pd_size : 0;
+ param.vnfs_cnp = enter ? cnp : NULL;
+ param.vnfs_flags = enter ? 0 : VNFS_NOCACHE;
+
+ error = vnode_create(VNCREATE_FLAVOR, VCREATESIZE, &param, &vp);
+ if (!error && !enter && index != PACKFS_ROOT_NODE) {
+ vnode_update_identity(vp, NULLVP, packfs_name(pm, dn), (int)dn->pd_name_len, 0, VNODE_UPDATE_NAME);
+ }
+ }
+ if (parent != NULLVP) {
+ vnode_put(parent);
+ }
+
+ lck_mtx_lock(&pm->pm_lock);
+ if (!error) {
+ ip->pi_vp = vp;
+ ip->pi_vid = vnode_vid(vp);
+ }
+ if (ip->pi_flags & PACKFS_I_WANTED) {
+ wakeup(ip);
+ }
+ ip->pi_flags &= ~(PACKFS_I_CREATING | PACKFS_I_WANTED);
+ lck_mtx_unlock(&pm->pm_lock);
+
+ if (!error) {
+ *vpp = vp;
+ }
+ return error;
+}
+
+/* Children are sorted by name (byte order, shorter first on a common prefix): binary search. */
+static bool
+packfs_find_child(const struct packfs_mount *pm, const struct packfs_dnode *dir, const char *name, size_t len,
+ uint32_t *index)
+{
+ uint64_t lo = 0, hi = dir->pd_size;
+
+ while (lo < hi) {
+ uint64_t mid = lo + (hi - lo) / 2;
+ const struct packfs_dnode *dn = &pm->pm_nodes[dir->pd_data + mid];
+ size_t common = MIN(len, (size_t)dn->pd_name_len);
+ int cmp = memcmp(name, packfs_name(pm, dn), common);
+
+ if (cmp == 0) {
+ cmp = (len > dn->pd_name_len) - (len < dn->pd_name_len);
+ }
+ if (cmp == 0) {
+ *index = (uint32_t)(dir->pd_data + mid);
+ return true;
+ }
+ if (cmp < 0) {
+ hi = mid;
+ } else {
+ lo = mid + 1;
+ }
+ }
+ return false;
+}
+
+static int
+packfs_lookup(struct vnop_lookup_args *ap)
+{
+ vnode_t dvp = ap->a_dvp;
+ struct componentname *cnp = ap->a_cnp;
+ struct packfs_mount *pm = PACKFS_VP_MOUNT(dvp);
+ uint32_t dir_index = packfs_vp_index(pm, dvp);
+ const struct packfs_dnode *dir = &pm->pm_nodes[dir_index];
+ uint32_t index;
+
+ *ap->a_vpp = NULLVP;
+
+ if (!S_ISDIR(dir->pd_mode)) {
+ return ENOTDIR;
+ }
+ if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
+ int error = vnode_get(dvp);
+
+ if (!error) {
+ *ap->a_vpp = dvp;
+ }
+ return error;
+ }
+ if (cnp->cn_flags & ISDOTDOT) {
+ return packfs_node_vnode(pm, dir->pd_parent, NULLVP, NULL, ap->a_vpp);
+ }
+
+ if (!packfs_find_child(pm, dir, cnp->cn_nameptr, (size_t)cnp->cn_namelen, &index)) {
+ /* Nothing can be created here, so say why instead of inviting the caller to try. */
+ if ((cnp->cn_flags & ISLASTCN) && (cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME)) {
+ return EROFS;
+ }
+ return ENOENT;
+ }
+ return packfs_node_vnode(pm, index, dvp, cnp, ap->a_vpp);
+}
+
+static int
+packfs_open(__unused struct vnop_open_args *ap)
+{
+ return 0;
+}
+
+static int
+packfs_close(__unused struct vnop_close_args *ap)
+{
+ return 0;
+}
+
+static int
+packfs_getattr(struct vnop_getattr_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct vnode_attr *vap = ap->a_vap;
+ struct packfs_mount *pm = PACKFS_VP_MOUNT(vp);
+ uint32_t index = packfs_vp_index(pm, vp);
+ const struct packfs_dnode *dn = &pm->pm_nodes[index];
+ uint64_t size = S_ISDIR(dn->pd_mode) ? pm->pm_super.ps_block_size : dn->pd_size;
+ uint64_t alloc = S_ISREG(dn->pd_mode) ? packfs_extent_size(pm, dn) : 0;
+ struct timespec when = { .tv_sec = (time_t)dn->pd_mtime, .tv_nsec = 0 };
+
+ VATTR_RETURN(vap, va_rdev, 0);
+ VATTR_RETURN(vap, va_nlink, dn->pd_nlink);
+ VATTR_RETURN(vap, va_total_size, size);
+ VATTR_RETURN(vap, va_total_alloc, alloc);
+ VATTR_RETURN(vap, va_data_size, size);
+ VATTR_RETURN(vap, va_data_alloc, alloc);
+ VATTR_RETURN(vap, va_iosize, pm->pm_super.ps_block_size);
+ VATTR_RETURN(vap, va_uid, dn->pd_uid);
+ VATTR_RETURN(vap, va_gid, dn->pd_gid);
+ VATTR_RETURN(vap, va_mode, dn->pd_mode & ALLPERMS);
+ VATTR_RETURN(vap, va_flags, 0);
+ VATTR_RETURN(vap, va_create_time, when);
+ VATTR_RETURN(vap, va_access_time, when);
+ VATTR_RETURN(vap, va_modify_time, when);
+ VATTR_RETURN(vap, va_change_time, when);
+ VATTR_RETURN(vap, va_fileid, PACKFS_INO(index));
+ VATTR_RETURN(vap, va_linkid, PACKFS_INO(index));
+ VATTR_RETURN(vap, va_parentid, PACKFS_INO(dn->pd_parent));
+ VATTR_RETURN(vap, va_fsid, vfs_statfs(vnode_mount(vp))->f_fsid.val[0]);
+ VATTR_RETURN(vap, va_filerev, 0);
+ VATTR_RETURN(vap, va_gen, 0);
+
+ if (VATTR_IS_ACTIVE(vap, va_name) && index != PACKFS_ROOT_NODE) {
+ strlcpy(vap->va_name, packfs_name(pm, dn), MAXPATHLEN);
+ VATTR_SET_SUPPORTED(vap, va_name);
+ }
+ return 0;
+}
+
+static int
+packfs_read(struct vnop_read_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct packfs_mount *pm = PACKFS_VP_MOUNT(vp);
+ const struct packfs_dnode *dn = &pm->pm_nodes[packfs_vp_index(pm, vp)];
+
+ if (vnode_isdir(vp)) {
+ return EISDIR;
+ }
+ if (!vnode_isreg(vp)) {
+ return EINVAL;
+ }
+ if (uio_offset(ap->a_uio) < 0) {
+ return EINVAL;
+ }
+ if (dn->pd_flags & PACKFS_F_CHUNKED) {
+ return packfs_read_chunked(vp, ap->a_uio, pm, dn);
+ }
+ return cluster_read(vp, ap->a_uio, (off_t)dn->pd_size, ap->a_ioflag);
+}
+
+/*
+ * Directory entries are produced in the classic 32-bit-inode layout (VFS
+ * converts them for getdirentries64). The directory offset is a byte count
+ * of the entries before it, as in devfs.
+ */
+static int
+packfs_readdir(struct vnop_readdir_args *ap)
+{
+#define PACKFS_DIRSIZ(namlen) ((sizeof(struct dirent) - (MAXNAMLEN + 1)) + (((namlen) + 1 + 3) & ~3))
+ vnode_t vp = ap->a_vp;
+ struct uio *uio = ap->a_uio;
+ struct packfs_mount *pm = PACKFS_VP_MOUNT(vp);
+ uint32_t dir_index = packfs_vp_index(pm, vp);
+ const struct packfs_dnode *dir = &pm->pm_nodes[dir_index];
+ off_t start = uio_offset(uio);
+ off_t pos = 0;
+ uint64_t entry;
+ int count = 0;
+ int error = 0;
+
+ if (ap->a_flags & (VNODE_READDIR_EXTENDED | VNODE_READDIR_REQSEEKOFF)) {
+ return EINVAL;
+ }
+ if (!S_ISDIR(dir->pd_mode)) {
+ return ENOTDIR;
+ }
+
+ /* Entries 0 and 1 are "." and "..", the children follow. */
+ for (entry = 0; entry < dir->pd_size + 2; entry++) {
+ struct dirent de;
+ const char *name;
+
+ bzero(&de, sizeof(de));
+ if (entry == 0) {
+ de.d_fileno = (ino_t)PACKFS_INO(dir_index);
+ de.d_type = DT_DIR;
+ de.d_namlen = 1;
+ name = ".";
+ } else if (entry == 1) {
+ de.d_fileno = (ino_t)PACKFS_INO(dir->pd_parent);
+ de.d_type = DT_DIR;
+ de.d_namlen = 2;
+ name = "..";
+ } else {
+ uint32_t child = (uint32_t)(dir->pd_data + entry - 2);
+ const struct packfs_dnode *dn = &pm->pm_nodes[child];
+
+ de.d_fileno = (ino_t)PACKFS_INO(child);
+ de.d_type = (uint8_t)IFTODT(dn->pd_mode);
+ de.d_namlen = (uint8_t)dn->pd_name_len;
+ name = packfs_name(pm, dn);
+ }
+ de.d_reclen = (uint16_t)PACKFS_DIRSIZ(de.d_namlen);
+
+ if (pos >= start) {
+ if (uio_resid(uio) < (user_ssize_t)de.d_reclen) {
+ break;
+ }
+ memcpy(de.d_name, name, de.d_namlen);
+ error = uiomove((caddr_t)&de, de.d_reclen, uio);
+ if (error) {
+ break;
+ }
+ count++;
+ }
+ pos += de.d_reclen;
+ }
+
+ if (!error) {
+ uio_setoffset(uio, pos);
+ if (ap->a_eofflag) {
+ *ap->a_eofflag = (entry >= dir->pd_size + 2);
+ }
+ if (ap->a_numdirent) {
+ *ap->a_numdirent = count;
+ }
+ }
+ return error;
+#undef PACKFS_DIRSIZ
+}
+
+static int
+packfs_readlink(struct vnop_readlink_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct packfs_mount *pm = PACKFS_VP_MOUNT(vp);
+ const struct packfs_dnode *dn = &pm->pm_nodes[packfs_vp_index(pm, vp)];
+
+ if (!S_ISLNK(dn->pd_mode)) {
+ return EINVAL;
+ }
+ return uiomove(pm->pm_strings + dn->pd_data, (int)dn->pd_size, ap->a_uio);
+}
+
+static int
+packfs_inactive(__unused struct vnop_inactive_args *ap)
+{
+ return 0;
+}
+
+static int
+packfs_reclaim(struct vnop_reclaim_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct packfs_mount *pm = PACKFS_VP_MOUNT(vp);
+ struct packfs_inode *ip = vnode_fsnode(vp);
+
+ lck_mtx_lock(&pm->pm_lock);
+ if (ip->pi_vp == vp) {
+ ip->pi_vp = NULLVP;
+ ip->pi_vid = 0;
+ }
+ if (ip->pi_flags & PACKFS_I_WANTED) {
+ ip->pi_flags &= ~PACKFS_I_WANTED;
+ wakeup(ip);
+ }
+ lck_mtx_unlock(&pm->pm_lock);
+
+ vnode_clearfsnode(vp);
+ return 0;
+}
+
+static int
+packfs_pathconf(struct vnop_pathconf_args *ap)
+{
+ switch (ap->a_name) {
+ case _PC_LINK_MAX:
+ *ap->a_retval = 1;
+ return 0;
+ case _PC_NAME_MAX:
+ *ap->a_retval = PACKFS_MAX_NAME;
+ return 0;
+ case _PC_PATH_MAX:
+ *ap->a_retval = MAXPATHLEN;
+ return 0;
+ case _PC_PIPE_BUF:
+ *ap->a_retval = PIPE_BUF;
+ return 0;
+ case _PC_CHOWN_RESTRICTED:
+ *ap->a_retval = 200112; /* _POSIX_CHOWN_RESTRICTED */
+ return 0;
+ case _PC_NO_TRUNC:
+ *ap->a_retval = 200112; /* _POSIX_NO_TRUNC */
+ return 0;
+ case _PC_CASE_SENSITIVE:
+ case _PC_CASE_PRESERVING:
+ *ap->a_retval = 1;
+ return 0;
+ case _PC_FILESIZEBITS:
+ *ap->a_retval = 64;
+ return 0;
+ default:
+ return EINVAL;
+ }
+}
+
+/*
+ * No ioctl or fsctl means anything here. ENOTTY is the answer callers treat
+ * as "this filesystem does not have that"; the default ENOTSUP is not (the
+ * iOS dyld, probing the root volume for APFS features, gives up on it).
+ */
+static int
+packfs_ioctl(__unused struct vnop_ioctl_args *ap)
+{
+ return ENOTTY;
+}
+
+static int
+packfs_mmap(__unused struct vnop_mmap_args *ap)
+{
+ return 0;
+}
+
+static int
+packfs_mnomap(__unused struct vnop_mnomap_args *ap)
+{
+ return 0;
+}
+
+static int
+packfs_pagein(struct vnop_pagein_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct packfs_mount *pm = PACKFS_VP_MOUNT(vp);
+ const struct packfs_dnode *dn = &pm->pm_nodes[packfs_vp_index(pm, vp)];
+
+ if (dn->pd_flags & PACKFS_F_CHUNKED) {
+ return packfs_pagein_chunked(ap, pm, dn);
+ }
+ return cluster_pagein(vp, ap->a_pl, ap->a_pl_offset, ap->a_f_offset, (int)ap->a_size, (off_t)dn->pd_size, ap->a_flags);
+}
+
+/* The cluster layer builds the buffers; all that is left is to hand them to the device. */
+static int
+packfs_strategy(struct vnop_strategy_args *ap)
+{
+ return buf_strategy(PACKFS_VP_MOUNT(buf_vnode(ap->a_bp))->pm_devvp, ap);
+}
+
+/* A file is one extent: file offset N lives at device byte pd_data + N. */
+static int
+packfs_blockmap(struct vnop_blockmap_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct packfs_mount *pm = PACKFS_VP_MOUNT(vp);
+ const struct packfs_dnode *dn = &pm->pm_nodes[packfs_vp_index(pm, vp)];
+ uint64_t extent = packfs_extent_size(pm, dn);
+ uint32_t devblock = (uint32_t)vfs_devblocksize(vnode_mount(vp));
+
+ if (!vnode_isreg(vp)) {
+ return ENOTSUP;
+ }
+ if (dn->pd_flags & PACKFS_F_CHUNKED) {
+ return ENOTSUP; /* no device blocks stand for the bytes of such a file */
+ }
+ if (ap->a_bpn == NULL) {
+ return 0;
+ }
+ if (ap->a_foffset < 0 || (uint64_t)ap->a_foffset >= extent) {
+ /* Past the end of the file: a hole. */
+ *ap->a_bpn = -1;
+ if (ap->a_run) {
+ *ap->a_run = ap->a_size;
+ }
+ } else {
+ *ap->a_bpn = (daddr64_t)((dn->pd_data + (uint64_t)ap->a_foffset) / devblock);
+ if (ap->a_run) {
+ *ap->a_run = (size_t)MIN((uint64_t)ap->a_size, extent - (uint64_t)ap->a_foffset);
+ }
+ }
+ if (ap->a_poff) {
+ *(int *)ap->a_poff = 0;
+ }
+ return 0;
+}
+
+static int
+packfs_blktooff(struct vnop_blktooff_args *ap)
+{
+ *ap->a_offset = (off_t)ap->a_lblkno * PACKFS_VP_MOUNT(ap->a_vp)->pm_super.ps_block_size;
+ return 0;
+}
+
+static int
+packfs_offtoblk(struct vnop_offtoblk_args *ap)
+{
+ *ap->a_lblkno = (daddr64_t)(ap->a_offset / PACKFS_VP_MOUNT(ap->a_vp)->pm_super.ps_block_size);
+ return 0;
+}
+
+#define VOPFUNC int (*)(void *)
+
+int(**packfs_vnodeop_p)(void *);
+const struct vnodeopv_entry_desc packfs_vnodeop_entries[] = {
+ { .opve_op = &vnop_default_desc, .opve_impl = (VOPFUNC)vn_default_error },
+ { .opve_op = &vnop_lookup_desc, .opve_impl = (VOPFUNC)packfs_lookup },
+ { .opve_op = &vnop_open_desc, .opve_impl = (VOPFUNC)packfs_open },
+ { .opve_op = &vnop_close_desc, .opve_impl = (VOPFUNC)packfs_close },
+ { .opve_op = &vnop_getattr_desc, .opve_impl = (VOPFUNC)packfs_getattr },
+ { .opve_op = &vnop_read_desc, .opve_impl = (VOPFUNC)packfs_read },
+ { .opve_op = &vnop_ioctl_desc, .opve_impl = (VOPFUNC)packfs_ioctl },
+ { .opve_op = &vnop_fsync_desc, .opve_impl = (VOPFUNC)nop_fsync },
+ { .opve_op = &vnop_readdir_desc, .opve_impl = (VOPFUNC)packfs_readdir },
+ { .opve_op = &vnop_readlink_desc, .opve_impl = (VOPFUNC)packfs_readlink },
+ { .opve_op = &vnop_inactive_desc, .opve_impl = (VOPFUNC)packfs_inactive },
+ { .opve_op = &vnop_reclaim_desc, .opve_impl = (VOPFUNC)packfs_reclaim },
+ { .opve_op = &vnop_pathconf_desc, .opve_impl = (VOPFUNC)packfs_pathconf },
+ { .opve_op = &vnop_mmap_desc, .opve_impl = (VOPFUNC)packfs_mmap },
+ { .opve_op = &vnop_mnomap_desc, .opve_impl = (VOPFUNC)packfs_mnomap },
+ { .opve_op = &vnop_pagein_desc, .opve_impl = (VOPFUNC)packfs_pagein },
+ { .opve_op = &vnop_strategy_desc, .opve_impl = (VOPFUNC)packfs_strategy },
+ { .opve_op = &vnop_blockmap_desc, .opve_impl = (VOPFUNC)packfs_blockmap },
+ { .opve_op = &vnop_blktooff_desc, .opve_impl = (VOPFUNC)packfs_blktooff },
+ { .opve_op = &vnop_offtoblk_desc, .opve_impl = (VOPFUNC)packfs_offtoblk },
+ { .opve_op = (struct vnodeop_desc *)NULL, .opve_impl = (VOPFUNC)NULL }
+};
+const struct vnodeopv_desc packfs_vnodeop_opv_desc = {
+ .opv_desc_vector_p = &packfs_vnodeop_p,
+ .opv_desc_ops = packfs_vnodeop_entries
+};
diff --git a/xnu/files/bsd/miscfs/ramfs/ramfs.c b/xnu/files/bsd/miscfs/ramfs/ramfs.c
new file mode 100644
index 0000000..b39e115
--- /dev/null
+++ b/xnu/files/bsd/miscfs/ramfs/ramfs.c
@@ -0,0 +1,1725 @@
+/*
+ * ramfs: a read-write filesystem that lives entirely in kernel memory.
+ *
+ * The open-source kernel has no writable filesystem of its own, and the
+ * bring-up system has no storage driver, so /private/var and /tmp are kept
+ * here. Everything is lost at shutdown.
+ *
+ * Nodes (files, directories, symlinks, socket names) are plain kernel
+ * structures; a directory is a list of (name, node) entries, so hard links
+ * are just two entries naming one node. File contents are kept in
+ * individually allocated pages hanging off the node. That copy is the truth:
+ * read() and write() go straight to it, and the page cache is used only for
+ * mmap, with page-in and page-out copying between the two.
+ *
+ * One mutex per mount guards all of it. It is never held while user memory
+ * is touched (a fault there could come back to this filesystem as a
+ * page-in): data moves through a bounce buffer instead.
+ *
+ * A node lives while it is named by a directory or has a vnode; after the
+ * last unlink it is freed when its vnode is reclaimed.
+ */
+
+#include <kern/assert.h>
+#include <kern/kalloc.h>
+#include <kern/locks.h>
+#include <libkern/libkern.h>
+#include <mach/vm_param.h>
+#include <sys/attr.h>
+#include <sys/dirent.h>
+#include <sys/errno.h>
+#include <sys/fcntl.h>
+#include <sys/mount_internal.h>
+#include <sys/namei.h>
+#include <sys/proc.h>
+#include <sys/queue.h>
+#include <sys/stat.h>
+#include <sys/systm.h>
+#include <sys/time.h>
+#include <sys/ubc.h>
+#include <sys/uio.h>
+#include <sys/unistd.h>
+#include <sys/vnode_internal.h>
+#include <sys/xattr.h>
+#include <vfs/vfs_support.h>
+
+#define RAMFS_MAX_NAME 255
+#define RAMFS_MAX_XATTR (16u * 1024 * 1024)
+#define RAMFS_ROOT_INO 2
+
+struct ramfs_mount;
+struct ramfs_node;
+
+struct ramfs_dirent {
+ TAILQ_ENTRY(ramfs_dirent) rd_link;
+ struct ramfs_node *rd_node;
+ char *rd_name; /* rd_namelen bytes and a terminator */
+ uint32_t rd_namelen;
+};
+
+/* An extended attribute: iOS 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 */
+ size_t rx_namelen;
+ void *rx_data;
+ size_t rx_size;
+};
+
+struct ramfs_node {
+ struct ramfs_mount *rn_mount;
+ uint64_t rn_ino;
+ enum vtype rn_type;
+ uint32_t rn_mode; /* permission bits only */
+ uid_t rn_uid;
+ gid_t rn_gid;
+ uint32_t rn_bsdflags;
+ uint32_t rn_nlink;
+ uint32_t rn_state;
+ vnode_t rn_vp;
+ uint32_t rn_vid;
+ struct timespec rn_atime, rn_mtime, rn_ctime, rn_btime;
+ uint64_t rn_size; /* file: bytes; symlink: target length */
+
+ /* directory */
+ struct ramfs_node *rn_parent; /* NULL once the directory has been removed */
+ TAILQ_HEAD(, ramfs_dirent) rn_entries;
+ uint32_t rn_nentries;
+
+ /* regular file */
+ void **rn_pages; /* rn_nslots slots; NULL is a hole that reads as zeros */
+ uint64_t rn_nslots;
+ uint64_t rn_nalloc; /* pages actually allocated */
+ bool rn_mapped_write; /* has been mapped writable: the page cache may be ahead of us */
+
+ /* symlink */
+ char *rn_target;
+
+ TAILQ_HEAD(, ramfs_xattr) rn_xattrs;
+};
+#define RAMFS_N_CREATING 0x1 /* a thread is in vnode_create() for this node */
+#define RAMFS_N_WANTED 0x2 /* somebody sleeps on the node */
+
+struct ramfs_mount {
+ mount_t rm_mp;
+ lck_mtx_t rm_lock;
+ struct ramfs_node *rm_root;
+ uint64_t rm_next_ino;
+ uint64_t rm_nodes;
+ uint64_t rm_pages; /* file pages in use */
+ uint64_t rm_max_pages;
+};
+
+#define RAMFS_MP(mp) ((struct ramfs_mount *)vfs_fsprivate(mp))
+#define RAMFS_NODE(vp) ((struct ramfs_node *)vnode_fsnode(vp))
+
+static LCK_GRP_DECLARE(ramfs_lck_grp, "ramfs");
+
+extern int(**ramfs_vnodeop_p)(void *);
+
+/* ------------------------------------------------------------------------ */
+/* Nodes */
+
+static struct ramfs_node *
+ramfs_node_alloc(struct ramfs_mount *rm, enum vtype type, struct vnode_attr *vap)
+{
+ struct ramfs_node *node = kalloc_type(struct ramfs_node, Z_WAITOK | Z_ZERO | Z_NOFAIL);
+ struct timespec now;
+
+ nanotime(&now);
+ node->rn_mount = rm;
+ node->rn_type = type;
+ node->rn_mode = type == VLNK ? 0755 : (type == VDIR ? 0755 : 0644);
+ node->rn_atime = node->rn_mtime = node->rn_ctime = node->rn_btime = now;
+ TAILQ_INIT(&node->rn_entries);
+ TAILQ_INIT(&node->rn_xattrs);
+
+ if (vap != NULL) {
+ if (VATTR_IS_ACTIVE(vap, va_mode)) {
+ node->rn_mode = vap->va_mode & ALLPERMS;
+ VATTR_SET_SUPPORTED(vap, va_mode);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_uid)) {
+ node->rn_uid = vap->va_uid;
+ VATTR_SET_SUPPORTED(vap, va_uid);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_gid)) {
+ node->rn_gid = vap->va_gid;
+ VATTR_SET_SUPPORTED(vap, va_gid);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_flags)) {
+ node->rn_bsdflags = vap->va_flags;
+ VATTR_SET_SUPPORTED(vap, va_flags);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_create_time)) {
+ node->rn_btime = vap->va_create_time;
+ VATTR_SET_SUPPORTED(vap, va_create_time);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_modify_time)) {
+ node->rn_mtime = vap->va_modify_time;
+ VATTR_SET_SUPPORTED(vap, va_modify_time);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_access_time)) {
+ node->rn_atime = vap->va_access_time;
+ VATTR_SET_SUPPORTED(vap, va_access_time);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_change_time)) {
+ node->rn_ctime = vap->va_change_time;
+ VATTR_SET_SUPPORTED(vap, va_change_time);
+ }
+ VATTR_SET_SUPPORTED(vap, va_type);
+ }
+ return node;
+}
+
+/* Drop file pages from slot `from` on. The mount lock is held. */
+static void
+ramfs_free_pages(struct ramfs_node *node, uint64_t from)
+{
+ for (uint64_t i = from; i < node->rn_nslots; i++) {
+ if (node->rn_pages[i] != NULL) {
+ kfree_data(node->rn_pages[i], PAGE_SIZE);
+ node->rn_pages[i] = NULL;
+ node->rn_nalloc--;
+ node->rn_mount->rm_pages--;
+ }
+ }
+}
+
+static void
+ramfs_xattr_free(struct ramfs_xattr *xa)
+{
+ kfree_data(xa->rx_name, xa->rx_namelen + 1);
+ if (xa->rx_data != NULL) {
+ kfree_data(xa->rx_data, xa->rx_size);
+ }
+ kfree_type(struct ramfs_xattr, xa);
+}
+
+/* The node is named by nothing and has no vnode. The mount lock is held. */
+static void
+ramfs_node_free(struct ramfs_node *node)
+{
+ struct ramfs_xattr *xa;
+
+ assert(TAILQ_EMPTY(&node->rn_entries));
+ while ((xa = TAILQ_FIRST(&node->rn_xattrs)) != NULL) {
+ TAILQ_REMOVE(&node->rn_xattrs, xa, rx_link);
+ ramfs_xattr_free(xa);
+ }
+ ramfs_free_pages(node, 0);
+ if (node->rn_pages != NULL) {
+ kfree_type(void *, node->rn_nslots, node->rn_pages);
+ }
+ if (node->rn_target != NULL) {
+ kfree_data(node->rn_target, node->rn_size + 1);
+ }
+ node->rn_mount->rm_nodes--;
+ kfree_type(struct ramfs_node, node);
+}
+
+static void
+ramfs_touch(struct ramfs_node *node, bool modified)
+{
+ struct timespec now;
+
+ nanotime(&now);
+ node->rn_ctime = now;
+ if (modified) {
+ node->rn_mtime = now;
+ }
+}
+
+static struct ramfs_dirent *
+ramfs_dirent_alloc(const char *name, size_t len)
+{
+ struct ramfs_dirent *de = kalloc_type(struct ramfs_dirent, Z_WAITOK | Z_ZERO | Z_NOFAIL);
+
+ de->rd_name = kalloc_data(len + 1, Z_WAITOK | Z_NOFAIL);
+ memcpy(de->rd_name, name, len);
+ de->rd_name[len] = '\0';
+ de->rd_namelen = (uint32_t)len;
+ return de;
+}
+
+static void
+ramfs_dirent_free(struct ramfs_dirent *de)
+{
+ kfree_data(de->rd_name, de->rd_namelen + 1);
+ kfree_type(struct ramfs_dirent, de);
+}
+
+static struct ramfs_dirent *
+ramfs_dir_find(struct ramfs_node *dir, const char *name, size_t len)
+{
+ struct ramfs_dirent *de;
+
+ TAILQ_FOREACH(de, &dir->rn_entries, rd_link) {
+ if (de->rd_namelen == len && memcmp(de->rd_name, name, len) == 0) {
+ return de;
+ }
+ }
+ return NULL;
+}
+
+static void
+ramfs_dir_add(struct ramfs_node *dir, struct ramfs_dirent *de, struct ramfs_node *node)
+{
+ de->rd_node = node;
+ TAILQ_INSERT_TAIL(&dir->rn_entries, de, rd_link);
+ dir->rn_nentries++;
+ ramfs_touch(dir, true);
+}
+
+static void
+ramfs_dir_remove(struct ramfs_node *dir, struct ramfs_dirent *de)
+{
+ TAILQ_REMOVE(&dir->rn_entries, de, rd_link);
+ dir->rn_nentries--;
+ ramfs_touch(dir, true);
+ ramfs_dirent_free(de);
+}
+
+/*
+ * Get the vnode of a node that is known to exist (it was just found in a
+ * directory, or is the root). Called with the mount lock held; returns with
+ * it dropped. 0: *vpp carries an iocount. EAGAIN: the node could not be
+ * pinned (its vnode is on the way out, or another thread is creating one)
+ * and may be gone by now; the caller must find it again.
+ */
+static int
+ramfs_vget_locked(struct ramfs_mount *rm, struct ramfs_node *node, vnode_t dvp, struct componentname *cnp, vnode_t *vpp)
+{
+ struct vnode_fsparam param;
+ vnode_t vp;
+ int error;
+
+ if (node->rn_state & RAMFS_N_CREATING) {
+ node->rn_state |= RAMFS_N_WANTED;
+ msleep(node, &rm->rm_lock, PINOD | PDROP, "ramfs_create", NULL);
+ return EAGAIN;
+ }
+ if (node->rn_vp != NULLVP) {
+ uint32_t vid = node->rn_vid;
+
+ vp = node->rn_vp;
+ lck_mtx_unlock(&rm->rm_lock);
+ if (vnode_getwithvid(vp, vid) == 0) {
+ *vpp = vp;
+ return 0;
+ }
+ /* being reclaimed: give it a moment */
+ tsleep(rm, PINOD, "ramfs_reclaim", 1);
+ return EAGAIN;
+ }
+
+ /* The CREATING mark keeps the node in place: nobody can unlink what they cannot get a vnode for. */
+ node->rn_state |= RAMFS_N_CREATING;
+ lck_mtx_unlock(&rm->rm_lock);
+
+ bzero(&param, sizeof(param));
+ param.vnfs_mp = rm->rm_mp;
+ param.vnfs_vtype = node->rn_type;
+ param.vnfs_str = "ramfs";
+ param.vnfs_dvp = dvp;
+ param.vnfs_fsnode = node;
+ param.vnfs_vops = ramfs_vnodeop_p;
+ param.vnfs_markroot = (node == rm->rm_root);
+ param.vnfs_filesize = node->rn_type == VREG ? (off_t)node->rn_size : 0;
+ param.vnfs_cnp = cnp;
+ /* names change under rename and unlink at any time: keep them out of the name cache */
+ param.vnfs_flags = VNFS_NOCACHE | VNFS_CANTCACHE;
+ error = vnode_create(VNCREATE_FLAVOR, VCREATESIZE, &param, &vp);
+
+ lck_mtx_lock(&rm->rm_lock);
+ if (!error) {
+ node->rn_vp = vp;
+ node->rn_vid = vnode_vid(vp);
+ }
+ if (node->rn_state & RAMFS_N_WANTED) {
+ wakeup(node);
+ }
+ node->rn_state &= ~(RAMFS_N_CREATING | RAMFS_N_WANTED);
+ lck_mtx_unlock(&rm->rm_lock);
+
+ if (!error) {
+ *vpp = vp;
+ }
+ return error;
+}
+
+/* ------------------------------------------------------------------------ */
+/* File contents */
+
+/* Make sure the page array has a slot for page `index`. The mount lock is held. */
+static int
+ramfs_grow_slots(struct ramfs_node *node, uint64_t index)
+{
+ uint64_t want = node->rn_nslots ? node->rn_nslots : 4;
+ void **slots;
+
+ if (index < node->rn_nslots) {
+ return 0;
+ }
+ while (want <= index) {
+ want *= 2;
+ }
+ slots = kalloc_type(void *, want, Z_NOWAIT | Z_ZERO);
+ if (slots == NULL) {
+ return ENOSPC;
+ }
+ if (node->rn_pages != NULL) {
+ memcpy(slots, node->rn_pages, node->rn_nslots * sizeof(void *));
+ kfree_type(void *, node->rn_nslots, node->rn_pages);
+ }
+ node->rn_pages = slots;
+ node->rn_nslots = want;
+ return 0;
+}
+
+/*
+ * Copy len bytes (within one page) into the file at offset off, extending
+ * the file if needed. *spare is a zeroed page the caller allocated without
+ * the lock; it is consumed if the slot was empty. The mount lock is held.
+ */
+static int
+ramfs_store(struct ramfs_node *node, uint64_t off, const void *src, size_t len, void **spare)
+{
+ struct ramfs_mount *rm = node->rn_mount;
+ uint64_t index = off / PAGE_SIZE;
+ int error = ramfs_grow_slots(node, index);
+
+ if (error) {
+ return error;
+ }
+ if (node->rn_pages[index] == NULL) {
+ if (*spare == NULL || rm->rm_pages >= rm->rm_max_pages) {
+ return ENOSPC;
+ }
+ node->rn_pages[index] = *spare;
+ *spare = NULL;
+ node->rn_nalloc++;
+ rm->rm_pages++;
+ }
+ memcpy((char *)node->rn_pages[index] + (off & PAGE_MASK), src, len);
+ if (off + len > node->rn_size) {
+ node->rn_size = off + len;
+ }
+ return 0;
+}
+
+/* Copy len bytes (within one page) out of the file; holes read as zeros. The mount lock is held. */
+static void
+ramfs_fetch(struct ramfs_node *node, uint64_t off, void *dst, size_t len)
+{
+ uint64_t index = off / PAGE_SIZE;
+
+ if (index < node->rn_nslots && node->rn_pages[index] != NULL) {
+ memcpy(dst, (char *)node->rn_pages[index] + (off & PAGE_MASK), len);
+ } else {
+ bzero(dst, len);
+ }
+}
+
+/* Change the file size; shrinking frees pages and clears the tail of the last one. The mount lock is held. */
+static void
+ramfs_resize(struct ramfs_node *node, uint64_t size)
+{
+ if (size < node->rn_size) {
+ uint64_t keep = (size + PAGE_MASK) / PAGE_SIZE;
+
+ ramfs_free_pages(node, keep);
+ if ((size & PAGE_MASK) != 0 && keep - 1 < node->rn_nslots && node->rn_pages[keep - 1] != NULL) {
+ bzero((char *)node->rn_pages[keep - 1] + (size & PAGE_MASK), PAGE_SIZE - (size & PAGE_MASK));
+ }
+ }
+ node->rn_size = size;
+ ramfs_touch(node, true);
+}
+
+/* A mapping may hold changes that have not been paged out to us yet: get them. */
+static void
+ramfs_sync_mapping(vnode_t vp, struct ramfs_node *node)
+{
+ if (node->rn_mapped_write) {
+ (void)ubc_msync(vp, 0, ubc_getsize(vp), NULL, UBC_PUSHDIRTY | UBC_SYNC);
+ }
+}
+
+/* ------------------------------------------------------------------------ */
+/* Vnode operations */
+
+static int
+ramfs_lookup(struct vnop_lookup_args *ap)
+{
+ vnode_t dvp = ap->a_dvp;
+ struct componentname *cnp = ap->a_cnp;
+ struct ramfs_node *dir = RAMFS_NODE(dvp);
+ struct ramfs_mount *rm = dir->rn_mount;
+ int error;
+
+ *ap->a_vpp = NULLVP;
+ if (dir->rn_type != VDIR) {
+ return ENOTDIR;
+ }
+ if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
+ error = vnode_get(dvp);
+ if (!error) {
+ *ap->a_vpp = dvp;
+ }
+ return error;
+ }
+
+ do {
+ struct ramfs_node *target;
+ bool dotdot = (cnp->cn_flags & ISDOTDOT) != 0;
+
+ lck_mtx_lock(&rm->rm_lock);
+ if (dotdot) {
+ target = dir->rn_parent;
+ } else {
+ struct ramfs_dirent *de = ramfs_dir_find(dir, cnp->cn_nameptr, (size_t)cnp->cn_namelen);
+
+ target = de ? de->rd_node : NULL;
+ }
+ if (target == NULL) {
+ lck_mtx_unlock(&rm->rm_lock);
+ /* a name that may be created: tell VFS to go ahead (unless the directory itself is gone) */
+ if (!dotdot && dir->rn_nlink != 0 && (cnp->cn_flags & ISLASTCN) &&
+ (cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME)) {
+ return EJUSTRETURN;
+ }
+ return ENOENT;
+ }
+ error = ramfs_vget_locked(rm, target, dotdot ? NULLVP : dvp, dotdot ? NULL : cnp, ap->a_vpp);
+ } while (error == EAGAIN);
+ return error;
+}
+
+/* create, mkdir, symlink and mknod are one operation with different node types */
+static int
+ramfs_make(vnode_t dvp, vnode_t *vpp, struct componentname *cnp, struct vnode_attr *vap, enum vtype type, const char *target)
+{
+ struct ramfs_node *dir = RAMFS_NODE(dvp);
+ struct ramfs_mount *rm = dir->rn_mount;
+ struct ramfs_node *node;
+ struct ramfs_dirent *de;
+ int error;
+
+ if (cnp->cn_namelen > RAMFS_MAX_NAME) {
+ return ENAMETOOLONG;
+ }
+ node = ramfs_node_alloc(rm, type, vap);
+ de = ramfs_dirent_alloc(cnp->cn_nameptr, (size_t)cnp->cn_namelen);
+ if (type == VLNK) {
+ node->rn_size = strlen(target);
+ node->rn_target = kalloc_data(node->rn_size + 1, Z_WAITOK | Z_NOFAIL);
+ memcpy(node->rn_target, target, node->rn_size + 1);
+ }
+
+ lck_mtx_lock(&rm->rm_lock);
+ rm->rm_nodes++;
+ if (dir->rn_nlink == 0) {
+ error = ENOENT; /* the directory has been removed */
+ } else if (ramfs_dir_find(dir, cnp->cn_nameptr, (size_t)cnp->cn_namelen) != NULL) {
+ error = EEXIST;
+ } else {
+ error = 0;
+ }
+ if (error) {
+ ramfs_node_free(node);
+ lck_mtx_unlock(&rm->rm_lock);
+ ramfs_dirent_free(de);
+ return error;
+ }
+ node->rn_ino = rm->rm_next_ino++;
+ if (type == VDIR) {
+ node->rn_nlink = 2;
+ node->rn_parent = dir;
+ dir->rn_nlink++;
+ } else {
+ node->rn_nlink = 1;
+ }
+ ramfs_dir_add(dir, de, node);
+
+ /* a fresh node has no vnode and no other suitor: this cannot ask for a retry */
+ error = ramfs_vget_locked(rm, node, dvp, cnp, vpp);
+ if (error) {
+ lck_mtx_lock(&rm->rm_lock);
+ ramfs_dir_remove(dir, de);
+ if (type == VDIR) {
+ dir->rn_nlink--;
+ }
+ ramfs_node_free(node);
+ lck_mtx_unlock(&rm->rm_lock);
+ }
+ return error;
+}
+
+static int
+ramfs_create(struct vnop_create_args *ap)
+{
+ return ramfs_make(ap->a_dvp, ap->a_vpp, ap->a_cnp, ap->a_vap, VREG, NULL);
+}
+
+static int
+ramfs_mkdir(struct vnop_mkdir_args *ap)
+{
+ return ramfs_make(ap->a_dvp, ap->a_vpp, ap->a_cnp, ap->a_vap, VDIR, NULL);
+}
+
+static int
+ramfs_symlink(struct vnop_symlink_args *ap)
+{
+ if (strlen(ap->a_target) >= MAXPATHLEN) {
+ return ENAMETOOLONG;
+ }
+ return ramfs_make(ap->a_dvp, ap->a_vpp, ap->a_cnp, ap->a_vap, VLNK, ap->a_target);
+}
+
+/* Only the name of a local socket can be made here (bind); devices live in devfs. */
+static int
+ramfs_mknod(struct vnop_mknod_args *ap)
+{
+ if (ap->a_vap->va_type != VSOCK) {
+ return ENOTSUP;
+ }
+ return ramfs_make(ap->a_dvp, ap->a_vpp, ap->a_cnp, ap->a_vap, VSOCK, NULL);
+}
+
+static int
+ramfs_remove(struct vnop_remove_args *ap)
+{
+ struct ramfs_node *dir = RAMFS_NODE(ap->a_dvp);
+ struct ramfs_node *node = RAMFS_NODE(ap->a_vp);
+ struct ramfs_mount *rm = dir->rn_mount;
+ struct ramfs_dirent *de;
+
+ if (node->rn_type == VDIR) {
+ return EPERM;
+ }
+ if ((ap->a_flags & VNODE_REMOVE_NODELETEBUSY) && vnode_isinuse(ap->a_vp, 0)) {
+ return EBUSY;
+ }
+ lck_mtx_lock(&rm->rm_lock);
+ de = ramfs_dir_find(dir, ap->a_cnp->cn_nameptr, (size_t)ap->a_cnp->cn_namelen);
+ if (de == NULL || de->rd_node != node) {
+ lck_mtx_unlock(&rm->rm_lock);
+ return ENOENT;
+ }
+ ramfs_dir_remove(dir, de);
+ node->rn_nlink--;
+ ramfs_touch(node, false);
+ lck_mtx_unlock(&rm->rm_lock);
+ /* with no links left the node goes away when its vnode does: see ramfs_inactive() */
+ return 0;
+}
+
+static int
+ramfs_rmdir(struct vnop_rmdir_args *ap)
+{
+ struct ramfs_node *dir = RAMFS_NODE(ap->a_dvp);
+ struct ramfs_node *node = RAMFS_NODE(ap->a_vp);
+ struct ramfs_mount *rm = dir->rn_mount;
+ struct ramfs_dirent *de;
+ int error = 0;
+
+ if (node->rn_type != VDIR) {
+ return ENOTDIR;
+ }
+ lck_mtx_lock(&rm->rm_lock);
+ de = ramfs_dir_find(dir, ap->a_cnp->cn_nameptr, (size_t)ap->a_cnp->cn_namelen);
+ if (de == NULL || de->rd_node != node) {
+ error = ENOENT;
+ } else if (node->rn_nentries != 0) {
+ error = ENOTEMPTY;
+ } else {
+ ramfs_dir_remove(dir, de);
+ dir->rn_nlink--;
+ node->rn_nlink = 0;
+ node->rn_parent = NULL;
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+ return error;
+}
+
+static int
+ramfs_link(struct vnop_link_args *ap)
+{
+ struct ramfs_node *node = RAMFS_NODE(ap->a_vp);
+ struct ramfs_node *dir = RAMFS_NODE(ap->a_tdvp);
+ struct ramfs_mount *rm = dir->rn_mount;
+ struct componentname *cnp = ap->a_cnp;
+ struct ramfs_dirent *de;
+ int error = 0;
+
+ if (node->rn_type == VDIR) {
+ return EPERM;
+ }
+ if (cnp->cn_namelen > RAMFS_MAX_NAME) {
+ return ENAMETOOLONG;
+ }
+ de = ramfs_dirent_alloc(cnp->cn_nameptr, (size_t)cnp->cn_namelen);
+
+ lck_mtx_lock(&rm->rm_lock);
+ if (dir->rn_nlink == 0 || node->rn_nlink == 0) {
+ error = ENOENT;
+ } else if (ramfs_dir_find(dir, cnp->cn_nameptr, (size_t)cnp->cn_namelen) != NULL) {
+ error = EEXIST;
+ } else {
+ ramfs_dir_add(dir, de, node);
+ node->rn_nlink++;
+ ramfs_touch(node, false);
+ de = NULL;
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+ if (de != NULL) {
+ ramfs_dirent_free(de);
+ }
+ return error;
+}
+
+static int
+ramfs_rename(struct vnop_rename_args *ap)
+{
+ struct ramfs_node *fdir = RAMFS_NODE(ap->a_fdvp);
+ struct ramfs_node *tdir = RAMFS_NODE(ap->a_tdvp);
+ struct ramfs_node *node = RAMFS_NODE(ap->a_fvp);
+ struct ramfs_mount *rm = node->rn_mount;
+ struct componentname *fcnp = ap->a_fcnp, *tcnp = ap->a_tcnp;
+ struct ramfs_dirent *fde, *tde, *spare;
+ int error = 0;
+
+ if (tcnp->cn_namelen > RAMFS_MAX_NAME) {
+ return ENAMETOOLONG;
+ }
+ spare = ramfs_dirent_alloc(tcnp->cn_nameptr, (size_t)tcnp->cn_namelen);
+
+ lck_mtx_lock(&rm->rm_lock);
+ fde = ramfs_dir_find(fdir, fcnp->cn_nameptr, (size_t)fcnp->cn_namelen);
+ tde = ramfs_dir_find(tdir, tcnp->cn_nameptr, (size_t)tcnp->cn_namelen);
+
+ if (fde == NULL || fde->rd_node != node || tdir->rn_nlink == 0) {
+ error = ENOENT;
+ goto out;
+ }
+ if (node->rn_type == VDIR) {
+ /* a directory cannot move into itself or below itself */
+ for (struct ramfs_node *up = tdir; up != NULL; up = (up == rm->rm_root) ? NULL : up->rn_parent) {
+ if (up == node) {
+ error = EINVAL;
+ goto out;
+ }
+ }
+ }
+ if (tde != NULL && tde->rd_node == node) {
+ /* two names of the same file: POSIX wants the rename to do nothing */
+ goto out;
+ }
+
+ if (tde != NULL) {
+ struct ramfs_node *victim = tde->rd_node;
+
+ if (victim->rn_type == VDIR) {
+ if (node->rn_type != VDIR) {
+ error = EISDIR;
+ } else if (victim->rn_nentries != 0) {
+ error = ENOTEMPTY;
+ }
+ } else if (node->rn_type == VDIR) {
+ error = ENOTDIR;
+ }
+ if (error) {
+ goto out;
+ }
+ if (victim->rn_type == VDIR) {
+ victim->rn_nlink = 0;
+ victim->rn_parent = NULL;
+ tdir->rn_nlink--;
+ } else {
+ victim->rn_nlink--;
+ ramfs_touch(victim, false);
+ }
+ tde->rd_node = node;
+ ramfs_touch(tdir, true);
+ } else {
+ ramfs_dir_add(tdir, spare, node);
+ spare = NULL;
+ }
+ ramfs_dir_remove(fdir, fde);
+ if (node->rn_type == VDIR && fdir != tdir) {
+ fdir->rn_nlink--;
+ tdir->rn_nlink++;
+ node->rn_parent = tdir;
+ }
+ ramfs_touch(node, false);
+out:
+ lck_mtx_unlock(&rm->rm_lock);
+ if (spare != NULL) {
+ ramfs_dirent_free(spare);
+ }
+ if (!error) {
+ vnode_update_identity(ap->a_fvp, ap->a_tdvp, tcnp->cn_nameptr, tcnp->cn_namelen, tcnp->cn_hash,
+ VNODE_UPDATE_PARENT | VNODE_UPDATE_NAME);
+ }
+ return error;
+}
+
+static int
+ramfs_open(__unused struct vnop_open_args *ap)
+{
+ return 0;
+}
+
+static int
+ramfs_close(__unused struct vnop_close_args *ap)
+{
+ return 0;
+}
+
+static int
+ramfs_getattr(struct vnop_getattr_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct vnode_attr *vap = ap->a_vap;
+ struct ramfs_node *node = RAMFS_NODE(vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ uint64_t size, alloc;
+
+ lck_mtx_lock(&rm->rm_lock);
+ size = node->rn_type == VDIR ? (uint64_t)(node->rn_nentries + 2) * 32 : node->rn_size;
+ alloc = node->rn_nalloc * PAGE_SIZE;
+
+ VATTR_RETURN(vap, va_rdev, 0);
+ VATTR_RETURN(vap, va_nlink, node->rn_nlink);
+ VATTR_RETURN(vap, va_total_size, size);
+ VATTR_RETURN(vap, va_total_alloc, alloc);
+ VATTR_RETURN(vap, va_data_size, size);
+ VATTR_RETURN(vap, va_data_alloc, alloc);
+ VATTR_RETURN(vap, va_iosize, PAGE_SIZE);
+ VATTR_RETURN(vap, va_uid, node->rn_uid);
+ VATTR_RETURN(vap, va_gid, node->rn_gid);
+ VATTR_RETURN(vap, va_mode, node->rn_mode);
+ VATTR_RETURN(vap, va_flags, node->rn_bsdflags);
+ VATTR_RETURN(vap, va_create_time, node->rn_btime);
+ VATTR_RETURN(vap, va_access_time, node->rn_atime);
+ VATTR_RETURN(vap, va_modify_time, node->rn_mtime);
+ VATTR_RETURN(vap, va_change_time, node->rn_ctime);
+ VATTR_RETURN(vap, va_fileid, node->rn_ino);
+ VATTR_RETURN(vap, va_linkid, node->rn_ino);
+ VATTR_RETURN(vap, va_fsid, vfs_statfs(vnode_mount(vp))->f_fsid.val[0]);
+ VATTR_RETURN(vap, va_filerev, 0);
+ VATTR_RETURN(vap, va_gen, 0);
+ if (node->rn_type == VDIR && node->rn_parent != NULL) {
+ VATTR_RETURN(vap, va_parentid, node->rn_parent->rn_ino);
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+ return 0;
+}
+
+static int
+ramfs_setattr(struct vnop_setattr_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct vnode_attr *vap = ap->a_vap;
+ struct ramfs_node *node = RAMFS_NODE(vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ bool resized = false;
+ uint64_t size = 0;
+
+ if (VATTR_IS_ACTIVE(vap, va_data_size)) {
+ if (node->rn_type == VDIR) {
+ return EISDIR;
+ }
+ if (node->rn_type != VREG) {
+ return EINVAL;
+ }
+ /* what a mapping changed must reach us before the size moves under it */
+ ramfs_sync_mapping(vp, node);
+ }
+
+ lck_mtx_lock(&rm->rm_lock);
+ if (VATTR_IS_ACTIVE(vap, va_data_size)) {
+ size = vap->va_data_size;
+ ramfs_resize(node, size);
+ resized = true;
+ VATTR_SET_SUPPORTED(vap, va_data_size);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_mode)) {
+ node->rn_mode = vap->va_mode & ALLPERMS;
+ VATTR_SET_SUPPORTED(vap, va_mode);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_uid)) {
+ node->rn_uid = vap->va_uid;
+ VATTR_SET_SUPPORTED(vap, va_uid);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_gid)) {
+ node->rn_gid = vap->va_gid;
+ VATTR_SET_SUPPORTED(vap, va_gid);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_flags)) {
+ node->rn_bsdflags = vap->va_flags;
+ VATTR_SET_SUPPORTED(vap, va_flags);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_create_time)) {
+ node->rn_btime = vap->va_create_time;
+ VATTR_SET_SUPPORTED(vap, va_create_time);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_access_time)) {
+ node->rn_atime = vap->va_access_time;
+ VATTR_SET_SUPPORTED(vap, va_access_time);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_modify_time)) {
+ node->rn_mtime = vap->va_modify_time;
+ VATTR_SET_SUPPORTED(vap, va_modify_time);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_change_time)) {
+ node->rn_ctime = vap->va_change_time;
+ VATTR_SET_SUPPORTED(vap, va_change_time);
+ } else {
+ ramfs_touch(node, false);
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+
+ if (resized) {
+ (void)ubc_setsize(vp, (off_t)size);
+ }
+ return 0;
+}
+
+static int
+ramfs_read(struct vnop_read_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct uio *uio = ap->a_uio;
+ struct ramfs_node *node = RAMFS_NODE(vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ char *bounce;
+ int error = 0;
+
+ if (node->rn_type == VDIR) {
+ return EISDIR;
+ }
+ if (node->rn_type != VREG || uio_offset(uio) < 0) {
+ return EINVAL;
+ }
+ ramfs_sync_mapping(vp, node);
+
+ bounce = kalloc_data(PAGE_SIZE, Z_WAITOK | Z_NOFAIL);
+ while (uio_resid(uio) > 0 && !error) {
+ uint64_t off = (uint64_t)uio_offset(uio);
+ size_t len;
+
+ lck_mtx_lock(&rm->rm_lock);
+ if (off >= node->rn_size) {
+ lck_mtx_unlock(&rm->rm_lock);
+ break;
+ }
+ len = MIN((size_t)MIN((uint64_t)uio_resid(uio), node->rn_size - off), PAGE_SIZE - (size_t)(off & PAGE_MASK));
+ ramfs_fetch(node, off, bounce, len);
+ lck_mtx_unlock(&rm->rm_lock);
+
+ error = uiomove(bounce, (int)len, uio);
+ }
+ kfree_data(bounce, PAGE_SIZE);
+ return error;
+}
+
+static int
+ramfs_write(struct vnop_write_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct uio *uio = ap->a_uio;
+ struct ramfs_node *node = RAMFS_NODE(vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ void *spare = NULL;
+ char *bounce;
+ uint64_t start, old_size;
+ int error = 0;
+
+ if (node->rn_type == VDIR) {
+ return EISDIR;
+ }
+ if (node->rn_type != VREG || uio_offset(uio) < 0) {
+ return EINVAL;
+ }
+ if (uio_resid(uio) == 0) {
+ return 0;
+ }
+ ramfs_sync_mapping(vp, node);
+
+ lck_mtx_lock(&rm->rm_lock);
+ old_size = node->rn_size;
+ if (ap->a_ioflag & IO_APPEND) {
+ uio_setoffset(uio, (off_t)old_size);
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+ start = (uint64_t)uio_offset(uio);
+
+ bounce = kalloc_data(PAGE_SIZE, Z_WAITOK | Z_NOFAIL);
+ while (uio_resid(uio) > 0) {
+ uint64_t off = (uint64_t)uio_offset(uio);
+ size_t len = MIN((size_t)uio_resid(uio), PAGE_SIZE - (size_t)(off & PAGE_MASK));
+
+ error = uiomove(bounce, (int)len, uio);
+ if (error) {
+ break;
+ }
+ if (spare == NULL) {
+ spare = kalloc_data(PAGE_SIZE, Z_WAITOK | Z_ZERO);
+ }
+ lck_mtx_lock(&rm->rm_lock);
+ error = ramfs_store(node, off, bounce, len, &spare);
+ lck_mtx_unlock(&rm->rm_lock);
+ if (error) {
+ /* nothing of this piece was stored: hand it back to the caller's count */
+ uio_setoffset(uio, (off_t)off);
+ uio_setresid(uio, uio_resid(uio) + (user_ssize_t)len);
+ break;
+ }
+ }
+ kfree_data(bounce, PAGE_SIZE);
+ if (spare != NULL) {
+ kfree_data(spare, PAGE_SIZE);
+ }
+
+ if ((uint64_t)uio_offset(uio) > start) {
+ uint64_t new_size;
+
+ lck_mtx_lock(&rm->rm_lock);
+ ramfs_touch(node, true);
+ new_size = node->rn_size;
+ lck_mtx_unlock(&rm->rm_lock);
+
+ if (new_size != old_size) {
+ (void)ubc_setsize(vp, (off_t)new_size);
+ }
+ /* cached pages of the range are stale now; they will be paged in again when wanted */
+ if (ubc_pages_resident(vp)) {
+ (void)ubc_msync(vp, (off_t)trunc_page_64(start), (off_t)round_page_64((uint64_t)uio_offset(uio)), NULL,
+ UBC_INVALIDATE);
+ }
+ /* a partial write is a success */
+ if (error == ENOSPC) {
+ error = 0;
+ }
+ }
+ return error;
+}
+
+/* Classic 32-bit-inode directory entries; the offset is a byte count of the entries before it. */
+static int
+ramfs_readdir(struct vnop_readdir_args *ap)
+{
+#define RAMFS_DIRSIZ(namlen) ((sizeof(struct dirent) - (MAXNAMLEN + 1)) + (((namlen) + 1 + 3) & ~3))
+ vnode_t vp = ap->a_vp;
+ struct uio *uio = ap->a_uio;
+ struct ramfs_node *dir = RAMFS_NODE(vp);
+ struct ramfs_mount *rm = dir->rn_mount;
+ struct ramfs_dirent *de;
+ off_t start = uio_offset(uio), pos = 0;
+ size_t room = (size_t)MIN((user_ssize_t)PAGE_SIZE, uio_resid(uio));
+ size_t used = 0;
+ uint32_t entry = 0;
+ bool eof = false;
+ int count = 0, error;
+ char *buf;
+
+ if (ap->a_flags & (VNODE_READDIR_EXTENDED | VNODE_READDIR_REQSEEKOFF)) {
+ return EINVAL;
+ }
+ if (dir->rn_type != VDIR) {
+ return ENOTDIR;
+ }
+ /* the entries are collected under the lock and copied out after it is dropped */
+ buf = kalloc_data(PAGE_SIZE, Z_WAITOK | Z_NOFAIL);
+
+ lck_mtx_lock(&rm->rm_lock);
+ de = TAILQ_FIRST(&dir->rn_entries);
+ for (;; entry++) {
+ struct dirent d;
+ const char *name;
+
+ bzero(&d, sizeof(d));
+ if (entry == 0) {
+ d.d_fileno = (ino_t)dir->rn_ino;
+ d.d_type = DT_DIR;
+ d.d_namlen = 1;
+ name = ".";
+ } else if (entry == 1) {
+ d.d_fileno = (ino_t)(dir->rn_parent ? dir->rn_parent->rn_ino : dir->rn_ino);
+ d.d_type = DT_DIR;
+ d.d_namlen = 2;
+ name = "..";
+ } else {
+ if (de == NULL) {
+ eof = true;
+ break;
+ }
+ d.d_fileno = (ino_t)de->rd_node->rn_ino;
+ d.d_type = (uint8_t)IFTODT(VTTOIF(de->rd_node->rn_type));
+ d.d_namlen = (uint8_t)de->rd_namelen;
+ name = de->rd_name;
+ de = TAILQ_NEXT(de, rd_link);
+ }
+ d.d_reclen = (uint16_t)RAMFS_DIRSIZ(d.d_namlen);
+ if (pos >= start) {
+ if (used + d.d_reclen > room) {
+ break;
+ }
+ memcpy(d.d_name, name, d.d_namlen);
+ memcpy(buf + used, &d, d.d_reclen);
+ used += d.d_reclen;
+ count++;
+ }
+ pos += d.d_reclen;
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+
+ error = used ? uiomove(buf, (int)used, uio) : 0;
+ kfree_data(buf, PAGE_SIZE);
+ if (!error) {
+ uio_setoffset(uio, pos);
+ if (ap->a_eofflag) {
+ *ap->a_eofflag = eof;
+ }
+ if (ap->a_numdirent) {
+ *ap->a_numdirent = count;
+ }
+ }
+ return error;
+#undef RAMFS_DIRSIZ
+}
+
+static int
+ramfs_readlink(struct vnop_readlink_args *ap)
+{
+ struct ramfs_node *node = RAMFS_NODE(ap->a_vp);
+
+ if (node->rn_type != VLNK) {
+ return EINVAL;
+ }
+ /* a symlink never changes after it is made */
+ return uiomove(node->rn_target, (int)node->rn_size, ap->a_uio);
+}
+
+static int
+ramfs_ioctl(__unused struct vnop_ioctl_args *ap)
+{
+ return ENOTTY;
+}
+
+/* Last reference gone: a node without a name has no reason to linger in the vnode cache. */
+static int
+ramfs_inactive(struct vnop_inactive_args *ap)
+{
+ if (RAMFS_NODE(ap->a_vp)->rn_nlink == 0) {
+ vnode_recycle(ap->a_vp);
+ }
+ return 0;
+}
+
+static int
+ramfs_reclaim(struct vnop_reclaim_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct ramfs_node *node = RAMFS_NODE(vp);
+ struct ramfs_mount *rm = node->rn_mount;
+
+ lck_mtx_lock(&rm->rm_lock);
+ node->rn_vp = NULLVP;
+ node->rn_vid = 0;
+ if (node->rn_nlink == 0 && node != rm->rm_root) {
+ ramfs_node_free(node);
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+
+ vnode_clearfsnode(vp);
+ return 0;
+}
+
+static int
+ramfs_pathconf(struct vnop_pathconf_args *ap)
+{
+ switch (ap->a_name) {
+ case _PC_LINK_MAX:
+ *ap->a_retval = 32767;
+ return 0;
+ case _PC_NAME_MAX:
+ *ap->a_retval = RAMFS_MAX_NAME;
+ return 0;
+ case _PC_PATH_MAX:
+ *ap->a_retval = MAXPATHLEN;
+ return 0;
+ case _PC_PIPE_BUF:
+ *ap->a_retval = PIPE_BUF;
+ return 0;
+ case _PC_CHOWN_RESTRICTED:
+ case _PC_NO_TRUNC:
+ *ap->a_retval = 200112;
+ return 0;
+ case _PC_CASE_SENSITIVE:
+ case _PC_CASE_PRESERVING:
+ *ap->a_retval = 1;
+ return 0;
+ case _PC_FILESIZEBITS:
+ *ap->a_retval = 64;
+ return 0;
+ default:
+ return EINVAL;
+ }
+}
+
+static int
+ramfs_mmap(struct vnop_mmap_args *ap)
+{
+ if (ap->a_fflags & VM_PROT_WRITE) {
+ RAMFS_NODE(ap->a_vp)->rn_mapped_write = true;
+ }
+ return 0;
+}
+
+static int
+ramfs_mnomap(__unused struct vnop_mnomap_args *ap)
+{
+ return 0;
+}
+
+/* Fill pages of the page cache from the file. */
+static int
+ramfs_pagein(struct vnop_pagein_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct ramfs_node *node = RAMFS_NODE(vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ upl_t upl = ap->a_pl;
+ upl_size_t size = (upl_size_t)ap->a_size;
+ uint64_t off = (uint64_t)ap->a_f_offset;
+ bool commit = (ap->a_flags & UPL_NOCOMMIT) == 0;
+ upl_size_t valid = 0;
+ vm_offset_t addr;
+
+ if (upl == NULL || node->rn_type != VREG || ap->a_f_offset < 0 || (off & PAGE_MASK) != 0 ||
+ ubc_upl_map(upl, &addr) != KERN_SUCCESS) {
+ if (commit && upl != NULL) {
+ ubc_upl_abort_range(upl, ap->a_pl_offset, size, UPL_ABORT_ERROR | UPL_ABORT_FREE_ON_EMPTY);
+ }
+ return EINVAL;
+ }
+ addr += ap->a_pl_offset;
+
+ lck_mtx_lock(&rm->rm_lock);
+ for (upl_size_t done = 0; done < size && off + done < node->rn_size; done += PAGE_SIZE) {
+ size_t len = (size_t)MIN((uint64_t)PAGE_SIZE, node->rn_size - (off + done));
+
+ ramfs_fetch(node, off + done, (void *)(addr + done), len);
+ bzero((void *)(addr + done + len), PAGE_SIZE - len);
+ valid = done + PAGE_SIZE;
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+ ubc_upl_unmap(upl);
+
+ if (commit) {
+ if (valid != 0) {
+ ubc_upl_commit_range(upl, ap->a_pl_offset, valid, UPL_COMMIT_CLEAR_DIRTY | UPL_COMMIT_FREE_ON_EMPTY);
+ }
+ /* pages wholly past the end of the file do not exist */
+ if (valid < size) {
+ ubc_upl_abort_range(upl, ap->a_pl_offset + valid, size - valid, UPL_ABORT_ERROR | UPL_ABORT_FREE_ON_EMPTY);
+ }
+ }
+ return valid != 0 ? 0 : EINVAL;
+}
+
+/* Take back what a mapping changed: copy dirty pages of the page cache into the file. */
+static int
+ramfs_pageout(struct vnop_pageout_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct ramfs_node *node = RAMFS_NODE(vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ upl_t upl = ap->a_pl;
+ upl_size_t size = (upl_size_t)ap->a_size;
+ uint64_t off = (uint64_t)ap->a_f_offset;
+ bool commit = (ap->a_flags & UPL_NOCOMMIT) == 0;
+ vm_offset_t addr;
+ int error = 0;
+
+ if (upl == NULL) {
+ return EINVAL;
+ }
+ if (node->rn_type != VREG || ap->a_f_offset < 0 || (off & PAGE_MASK) != 0 ||
+ ubc_upl_map(upl, &addr) != KERN_SUCCESS) {
+ if (commit) {
+ ubc_upl_abort_range(upl, ap->a_pl_offset, size, UPL_ABORT_FREE_ON_EMPTY);
+ }
+ return EINVAL;
+ }
+ addr += ap->a_pl_offset;
+
+ lck_mtx_lock(&rm->rm_lock);
+ for (upl_size_t done = 0; done < size && off + done < node->rn_size && !error; done += PAGE_SIZE) {
+ size_t len = (size_t)MIN((uint64_t)PAGE_SIZE, node->rn_size - (off + done));
+ /* this may be the pageout daemon looking for memory: never wait for more of it here */
+ void *spare = kalloc_data(PAGE_SIZE, Z_NOWAIT | Z_ZERO);
+
+ error = ramfs_store(node, off + done, (const void *)(addr + done), len, &spare);
+ if (spare != NULL) {
+ kfree_data(spare, PAGE_SIZE);
+ }
+ }
+ if (!error) {
+ ramfs_touch(node, true);
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+ ubc_upl_unmap(upl);
+
+ if (commit) {
+ if (error) {
+ /* the pages stay dirty and will be offered again */
+ ubc_upl_abort_range(upl, ap->a_pl_offset, size, UPL_ABORT_FREE_ON_EMPTY);
+ } else {
+ ubc_upl_commit_range(upl, ap->a_pl_offset, size, UPL_COMMIT_CLEAR_DIRTY | UPL_COMMIT_FREE_ON_EMPTY);
+ }
+ }
+ return error;
+}
+
+/* ---- extended attributes ---- */
+
+static struct ramfs_xattr *
+ramfs_xattr_find(struct ramfs_node *node, const char *name)
+{
+ struct ramfs_xattr *xa;
+ size_t len = strlen(name);
+
+ TAILQ_FOREACH(xa, &node->rn_xattrs, rx_link) {
+ if (xa->rx_namelen == len && memcmp(xa->rx_name, name, len) == 0) {
+ return xa;
+ }
+ }
+ return NULL;
+}
+
+static int
+ramfs_getxattr(struct vnop_getxattr_args *ap)
+{
+ struct ramfs_node *node = RAMFS_NODE(ap->a_vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ struct ramfs_xattr *xa;
+ void *copy = NULL;
+ size_t size = 0;
+ int error = 0;
+
+ lck_mtx_lock(&rm->rm_lock);
+ xa = ramfs_xattr_find(node, ap->a_name);
+ if (xa == NULL) {
+ error = ENOATTR;
+ } else {
+ size = xa->rx_size;
+ if (ap->a_uio != NULL) {
+ if ((size_t)uio_resid(ap->a_uio) < size) {
+ error = ERANGE;
+ } else if (size != 0) {
+ /* copied out after the lock is dropped: the attribute may be replaced meanwhile */
+ copy = kalloc_data(size, Z_NOWAIT);
+ if (copy == NULL) {
+ error = ENOMEM;
+ } else {
+ memcpy(copy, xa->rx_data, size);
+ }
+ }
+ }
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+
+ if (!error) {
+ if (ap->a_uio == NULL) {
+ *ap->a_size = size;
+ } else if (copy != NULL) {
+ error = uiomove(copy, (int)size, ap->a_uio);
+ }
+ }
+ if (copy != NULL) {
+ kfree_data(copy, size);
+ }
+ return error;
+}
+
+static int
+ramfs_setxattr(struct vnop_setxattr_args *ap)
+{
+ struct ramfs_node *node = RAMFS_NODE(ap->a_vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ struct ramfs_xattr *xa, *fresh, *old = NULL;
+ size_t size = (size_t)uio_resid(ap->a_uio);
+ size_t namelen = strlen(ap->a_name);
+ void *data = NULL;
+ int error = 0;
+
+ if (size > RAMFS_MAX_XATTR || namelen > XATTR_MAXNAMELEN) {
+ return E2BIG;
+ }
+ if (size != 0) {
+ data = kalloc_data(size, Z_WAITOK);
+ if (data == NULL) {
+ return ENOMEM;
+ }
+ error = uiomove(data, (int)size, ap->a_uio);
+ if (error) {
+ kfree_data(data, size);
+ return error;
+ }
+ }
+ fresh = kalloc_type(struct ramfs_xattr, Z_WAITOK | Z_ZERO | Z_NOFAIL);
+ fresh->rx_name = kalloc_data(namelen + 1, Z_WAITOK | Z_NOFAIL);
+ memcpy(fresh->rx_name, ap->a_name, namelen + 1);
+ fresh->rx_namelen = namelen;
+ fresh->rx_data = data;
+ fresh->rx_size = size;
+
+ lck_mtx_lock(&rm->rm_lock);
+ xa = ramfs_xattr_find(node, ap->a_name);
+ if (xa != NULL && (ap->a_options & XATTR_CREATE)) {
+ error = EEXIST;
+ } else if (xa == NULL && (ap->a_options & XATTR_REPLACE)) {
+ error = ENOATTR;
+ } else {
+ if (xa != NULL) {
+ TAILQ_REMOVE(&node->rn_xattrs, xa, rx_link);
+ old = xa;
+ }
+ TAILQ_INSERT_TAIL(&node->rn_xattrs, fresh, rx_link);
+ fresh = NULL;
+ ramfs_touch(node, false);
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+
+ if (fresh != NULL) {
+ ramfs_xattr_free(fresh);
+ }
+ if (old != NULL) {
+ ramfs_xattr_free(old);
+ }
+ return error;
+}
+
+static int
+ramfs_removexattr(struct vnop_removexattr_args *ap)
+{
+ struct ramfs_node *node = RAMFS_NODE(ap->a_vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ struct ramfs_xattr *xa;
+
+ lck_mtx_lock(&rm->rm_lock);
+ xa = ramfs_xattr_find(node, ap->a_name);
+ if (xa != NULL) {
+ TAILQ_REMOVE(&node->rn_xattrs, xa, rx_link);
+ ramfs_touch(node, false);
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+
+ if (xa == NULL) {
+ return ENOATTR;
+ }
+ ramfs_xattr_free(xa);
+ return 0;
+}
+
+/* The names, each with its terminator, one after another. */
+static int
+ramfs_listxattr(struct vnop_listxattr_args *ap)
+{
+ struct ramfs_node *node = RAMFS_NODE(ap->a_vp);
+ struct ramfs_mount *rm = node->rn_mount;
+ struct ramfs_xattr *xa;
+ char *copy = NULL;
+ size_t total = 0, at = 0;
+ int error = 0;
+
+ lck_mtx_lock(&rm->rm_lock);
+ TAILQ_FOREACH(xa, &node->rn_xattrs, rx_link) {
+ total += xa->rx_namelen + 1;
+ }
+ if (ap->a_uio != NULL && total != 0) {
+ if ((size_t)uio_resid(ap->a_uio) < total) {
+ error = ERANGE;
+ } else if ((copy = kalloc_data(total, Z_NOWAIT)) == NULL) {
+ error = ENOMEM;
+ } else {
+ TAILQ_FOREACH(xa, &node->rn_xattrs, rx_link) {
+ memcpy(copy + at, xa->rx_name, xa->rx_namelen + 1);
+ at += xa->rx_namelen + 1;
+ }
+ }
+ }
+ lck_mtx_unlock(&rm->rm_lock);
+
+ if (!error) {
+ if (ap->a_uio == NULL) {
+ *ap->a_size = total;
+ } else if (copy != NULL) {
+ error = uiomove(copy, (int)total, ap->a_uio);
+ }
+ }
+ if (copy != NULL) {
+ kfree_data(copy, total);
+ }
+ return error;
+}
+
+static int
+ramfs_blktooff(struct vnop_blktooff_args *ap)
+{
+ *ap->a_offset = (off_t)ap->a_lblkno * PAGE_SIZE;
+ return 0;
+}
+
+static int
+ramfs_offtoblk(struct vnop_offtoblk_args *ap)
+{
+ *ap->a_lblkno = (daddr64_t)(ap->a_offset / PAGE_SIZE);
+ return 0;
+}
+
+#define VOPFUNC int (*)(void *)
+
+int(**ramfs_vnodeop_p)(void *);
+const struct vnodeopv_entry_desc ramfs_vnodeop_entries[] = {
+ { .opve_op = &vnop_default_desc, .opve_impl = (VOPFUNC)vn_default_error },
+ { .opve_op = &vnop_lookup_desc, .opve_impl = (VOPFUNC)ramfs_lookup },
+ { .opve_op = &vnop_create_desc, .opve_impl = (VOPFUNC)ramfs_create },
+ { .opve_op = &vnop_mknod_desc, .opve_impl = (VOPFUNC)ramfs_mknod },
+ { .opve_op = &vnop_open_desc, .opve_impl = (VOPFUNC)ramfs_open },
+ { .opve_op = &vnop_close_desc, .opve_impl = (VOPFUNC)ramfs_close },
+ { .opve_op = &vnop_getattr_desc, .opve_impl = (VOPFUNC)ramfs_getattr },
+ { .opve_op = &vnop_setattr_desc, .opve_impl = (VOPFUNC)ramfs_setattr },
+ { .opve_op = &vnop_read_desc, .opve_impl = (VOPFUNC)ramfs_read },
+ { .opve_op = &vnop_write_desc, .opve_impl = (VOPFUNC)ramfs_write },
+ { .opve_op = &vnop_ioctl_desc, .opve_impl = (VOPFUNC)ramfs_ioctl },
+ { .opve_op = &vnop_fsync_desc, .opve_impl = (VOPFUNC)nop_fsync },
+ { .opve_op = &vnop_remove_desc, .opve_impl = (VOPFUNC)ramfs_remove },
+ { .opve_op = &vnop_link_desc, .opve_impl = (VOPFUNC)ramfs_link },
+ { .opve_op = &vnop_rename_desc, .opve_impl = (VOPFUNC)ramfs_rename },
+ { .opve_op = &vnop_mkdir_desc, .opve_impl = (VOPFUNC)ramfs_mkdir },
+ { .opve_op = &vnop_rmdir_desc, .opve_impl = (VOPFUNC)ramfs_rmdir },
+ { .opve_op = &vnop_symlink_desc, .opve_impl = (VOPFUNC)ramfs_symlink },
+ { .opve_op = &vnop_readdir_desc, .opve_impl = (VOPFUNC)ramfs_readdir },
+ { .opve_op = &vnop_readlink_desc, .opve_impl = (VOPFUNC)ramfs_readlink },
+ { .opve_op = &vnop_inactive_desc, .opve_impl = (VOPFUNC)ramfs_inactive },
+ { .opve_op = &vnop_reclaim_desc, .opve_impl = (VOPFUNC)ramfs_reclaim },
+ { .opve_op = &vnop_pathconf_desc, .opve_impl = (VOPFUNC)ramfs_pathconf },
+ { .opve_op = &vnop_mmap_desc, .opve_impl = (VOPFUNC)ramfs_mmap },
+ { .opve_op = &vnop_mnomap_desc, .opve_impl = (VOPFUNC)ramfs_mnomap },
+ { .opve_op = &vnop_pagein_desc, .opve_impl = (VOPFUNC)ramfs_pagein },
+ { .opve_op = &vnop_pageout_desc, .opve_impl = (VOPFUNC)ramfs_pageout },
+ { .opve_op = &vnop_getxattr_desc, .opve_impl = (VOPFUNC)ramfs_getxattr },
+ { .opve_op = &vnop_setxattr_desc, .opve_impl = (VOPFUNC)ramfs_setxattr },
+ { .opve_op = &vnop_removexattr_desc, .opve_impl = (VOPFUNC)ramfs_removexattr },
+ { .opve_op = &vnop_listxattr_desc, .opve_impl = (VOPFUNC)ramfs_listxattr },
+ { .opve_op = &vnop_blktooff_desc, .opve_impl = (VOPFUNC)ramfs_blktooff },
+ { .opve_op = &vnop_offtoblk_desc, .opve_impl = (VOPFUNC)ramfs_offtoblk },
+ { .opve_op = (struct vnodeop_desc *)NULL, .opve_impl = (VOPFUNC)NULL }
+};
+const struct vnodeopv_desc ramfs_vnodeop_opv_desc = {
+ .opv_desc_vector_p = &ramfs_vnodeop_p,
+ .opv_desc_ops = ramfs_vnodeop_entries
+};
+
+/* ------------------------------------------------------------------------ */
+/* Mount operations */
+
+/* mount(2) with no arguments: an empty filesystem appears. */
+static int
+ramfs_mount(mount_t mp, __unused vnode_t devvp, __unused user_addr_t data, __unused vfs_context_t ctx)
+{
+ struct ramfs_mount *rm;
+ struct vfsstatfs *sp;
+
+ if (vfs_isupdate(mp)) {
+ return 0;
+ }
+ rm = kalloc_type(struct ramfs_mount, Z_WAITOK | Z_ZERO | Z_NOFAIL);
+ lck_mtx_init(&rm->rm_lock, &ramfs_lck_grp, LCK_ATTR_NULL);
+ rm->rm_mp = mp;
+ rm->rm_next_ino = RAMFS_ROOT_INO + 1;
+ /* a runaway writer must not be able to take the whole machine: a quarter of memory at most */
+ rm->rm_max_pages = (max_mem / 4) / PAGE_SIZE;
+
+ rm->rm_root = ramfs_node_alloc(rm, VDIR, NULL);
+ rm->rm_root->rn_ino = RAMFS_ROOT_INO;
+ rm->rm_root->rn_nlink = 2;
+ rm->rm_root->rn_parent = rm->rm_root;
+ rm->rm_nodes = 1;
+
+ vfs_setfsprivate(mp, rm);
+ vfs_setlocklocal(mp);
+ /* ACLs and owner UUIDs: VFS keeps them in an extended attribute of the file */
+ vfs_setextendedsecurity(mp);
+ vfs_getnewfsid(mp);
+
+ sp = vfs_statfs(mp);
+ sp->f_bsize = PAGE_SIZE;
+ sp->f_iosize = PAGE_SIZE;
+ sp->f_blocks = rm->rm_max_pages;
+ sp->f_bfree = sp->f_bavail = rm->rm_max_pages;
+ sp->f_bused = 0;
+ /* there is no table of nodes to run out of; report as many as there could be pages */
+ sp->f_files = rm->rm_max_pages;
+ sp->f_ffree = rm->rm_max_pages - 1;
+ strlcpy(sp->f_mntfromname, "ramfs", sizeof(sp->f_mntfromname));
+ return 0;
+}
+
+/* Free a directory's subtree; every vnode is gone, so nothing else can be looking. */
+static void
+ramfs_free_tree(struct ramfs_node *dir)
+{
+ struct ramfs_dirent *de;
+
+ while ((de = TAILQ_FIRST(&dir->rn_entries)) != NULL) {
+ struct ramfs_node *node = de->rd_node;
+
+ TAILQ_REMOVE(&dir->rn_entries, de, rd_link);
+ ramfs_dirent_free(de);
+ if (node->rn_type == VDIR) {
+ ramfs_free_tree(node);
+ ramfs_node_free(node);
+ } else if (--node->rn_nlink == 0) {
+ ramfs_node_free(node);
+ }
+ }
+}
+
+static int
+ramfs_unmount(mount_t mp, int mntflags, __unused vfs_context_t ctx)
+{
+ struct ramfs_mount *rm = RAMFS_MP(mp);
+ int error = vflush(mp, NULLVP, (mntflags & MNT_FORCE) ? FORCECLOSE : 0);
+
+ if (error) {
+ return error;
+ }
+ lck_mtx_lock(&rm->rm_lock);
+ ramfs_free_tree(rm->rm_root);
+ ramfs_node_free(rm->rm_root);
+ lck_mtx_unlock(&rm->rm_lock);
+
+ vfs_setfsprivate(mp, NULL);
+ lck_mtx_destroy(&rm->rm_lock, &ramfs_lck_grp);
+ kfree_type(struct ramfs_mount, rm);
+ return 0;
+}
+
+static int
+ramfs_root(mount_t mp, vnode_t *vpp, __unused vfs_context_t ctx)
+{
+ struct ramfs_mount *rm = RAMFS_MP(mp);
+ int error;
+
+ do {
+ lck_mtx_lock(&rm->rm_lock);
+ error = ramfs_vget_locked(rm, rm->rm_root, NULLVP, NULL, vpp);
+ } while (error == EAGAIN);
+ return error;
+}
+
+static int
+ramfs_vfs_getattr(mount_t mp, struct vfs_attr *fsap, __unused vfs_context_t ctx)
+{
+ struct ramfs_mount *rm = RAMFS_MP(mp);
+ uint64_t used, nodes;
+
+ lck_mtx_lock(&rm->rm_lock);
+ used = rm->rm_pages;
+ nodes = rm->rm_nodes;
+ lck_mtx_unlock(&rm->rm_lock);
+
+ VFSATTR_RETURN(fsap, f_objcount, nodes);
+ VFSATTR_RETURN(fsap, f_bsize, PAGE_SIZE);
+ VFSATTR_RETURN(fsap, f_iosize, PAGE_SIZE);
+ VFSATTR_RETURN(fsap, f_blocks, rm->rm_max_pages);
+ VFSATTR_RETURN(fsap, f_bfree, rm->rm_max_pages - MIN(used, rm->rm_max_pages));
+ VFSATTR_RETURN(fsap, f_bavail, rm->rm_max_pages - MIN(used, rm->rm_max_pages));
+ VFSATTR_RETURN(fsap, f_bused, used);
+ VFSATTR_RETURN(fsap, f_files, rm->rm_max_pages);
+ VFSATTR_RETURN(fsap, f_ffree, rm->rm_max_pages - MIN(nodes, rm->rm_max_pages));
+
+ if (VFSATTR_IS_ACTIVE(fsap, f_capabilities)) {
+ vol_capabilities_attr_t *cap = &fsap->f_capabilities;
+
+ bzero(cap, sizeof(*cap));
+ cap->capabilities[VOL_CAPABILITIES_FORMAT] =
+ VOL_CAP_FMT_SYMBOLICLINKS |
+ VOL_CAP_FMT_HARDLINKS |
+ VOL_CAP_FMT_SPARSE_FILES |
+ VOL_CAP_FMT_CASE_SENSITIVE |
+ VOL_CAP_FMT_CASE_PRESERVING |
+ VOL_CAP_FMT_FAST_STATFS |
+ VOL_CAP_FMT_2TB_FILESIZE;
+ cap->capabilities[VOL_CAPABILITIES_INTERFACES] =
+ VOL_CAP_INT_ADVLOCK |
+ VOL_CAP_INT_FLOCK |
+ VOL_CAP_INT_EXTENDED_SECURITY |
+ VOL_CAP_INT_EXTENDED_ATTR;
+ cap->valid[VOL_CAPABILITIES_FORMAT] =
+ VOL_CAP_FMT_PERSISTENTOBJECTIDS |
+ VOL_CAP_FMT_SYMBOLICLINKS |
+ VOL_CAP_FMT_HARDLINKS |
+ VOL_CAP_FMT_JOURNAL |
+ VOL_CAP_FMT_JOURNAL_ACTIVE |
+ VOL_CAP_FMT_NO_ROOT_TIMES |
+ VOL_CAP_FMT_SPARSE_FILES |
+ VOL_CAP_FMT_ZERO_RUNS |
+ VOL_CAP_FMT_CASE_SENSITIVE |
+ VOL_CAP_FMT_CASE_PRESERVING |
+ VOL_CAP_FMT_FAST_STATFS |
+ VOL_CAP_FMT_2TB_FILESIZE |
+ VOL_CAP_FMT_OPENDENYMODES |
+ VOL_CAP_FMT_HIDDEN_FILES |
+ VOL_CAP_FMT_PATH_FROM_ID;
+ cap->valid[VOL_CAPABILITIES_INTERFACES] =
+ VOL_CAP_INT_SEARCHFS |
+ VOL_CAP_INT_ATTRLIST |
+ VOL_CAP_INT_NFSEXPORT |
+ VOL_CAP_INT_READDIRATTR |
+ VOL_CAP_INT_EXCHANGEDATA |
+ VOL_CAP_INT_COPYFILE |
+ VOL_CAP_INT_ALLOCATE |
+ VOL_CAP_INT_VOL_RENAME |
+ VOL_CAP_INT_ADVLOCK |
+ VOL_CAP_INT_FLOCK |
+ VOL_CAP_INT_EXTENDED_SECURITY |
+ VOL_CAP_INT_USERACCESS |
+ VOL_CAP_INT_MANLOCK |
+ VOL_CAP_INT_EXTENDED_ATTR |
+ VOL_CAP_INT_NAMEDSTREAMS;
+ VFSATTR_SET_SUPPORTED(fsap, f_capabilities);
+ }
+ if (VFSATTR_IS_ACTIVE(fsap, f_vol_name)) {
+ strlcpy(fsap->f_vol_name, "ramfs", MAXPATHLEN);
+ VFSATTR_SET_SUPPORTED(fsap, f_vol_name);
+ }
+ return 0;
+}
+
+static int
+ramfs_sync(__unused mount_t mp, __unused int waitfor, __unused vfs_context_t ctx)
+{
+ return 0;
+}
+
+static int
+ramfs_init(__unused struct vfsconf *vfsc)
+{
+ return 0;
+}
+
+struct vfsops ramfs_vfsops = {
+ .vfs_mount = ramfs_mount,
+ .vfs_unmount = ramfs_unmount,
+ .vfs_root = ramfs_root,
+ .vfs_getattr = ramfs_vfs_getattr,
+ .vfs_sync = ramfs_sync,
+ .vfs_init = ramfs_init,
+};
diff --git a/xnu/files/bsd/pthread/pthread_kext_static.c b/xnu/files/bsd/pthread/pthread_kext_static.c
new file mode 100644
index 0000000..0200bd0
--- /dev/null
+++ b/xnu/files/bsd/pthread/pthread_kext_static.c
@@ -0,0 +1,26 @@
+/*
+ * Starts the pthread kernel extension when it is linked statically into the
+ * kernel image.
+ *
+ * com.apple.kec.pthread (open source, libpthread/kern) normally arrives as a
+ * prelinked kext whose start routine registers its function table with
+ * pthread_shims.c. This configuration has no kext loading at all, so the kext
+ * is built as libpthread_kext.a, linked in, and started from here before
+ * bsd_init() needs it.
+ */
+#include <mach/kmod.h>
+#include <kern/startup.h>
+#include <kern/debug.h>
+
+extern kern_return_t pthread_start(kmod_info_t *ki, void *d);
+
+__startup_func
+static void
+pthread_kext_static_start(void)
+{
+ kern_return_t kr = pthread_start(NULL, NULL);
+ if (kr != KERN_SUCCESS) {
+ panic("static pthread kext failed to start: %d", kr);
+ }
+}
+STARTUP(EARLY_BOOT, STARTUP_RANK_LAST, pthread_kext_static_start);
diff --git a/xnu/files/bsd/sys/redwood_input.h b/xnu/files/bsd/sys/redwood_input.h
new file mode 100644
index 0000000..3944100
--- /dev/null
+++ b/xnu/files/bsd/sys/redwood_input.h
@@ -0,0 +1,47 @@
+/*
+ * /dev/redwood-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
+ * 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.
+ *
+ * write(): one or more records (time is ignored; the kernel stamps them)
+ * read(): blocks until there is at least one record, returns as many whole ones as fit
+ */
+#ifndef _SYS_REDWOOD_INPUT_H_
+#define _SYS_REDWOOD_INPUT_H_
+
+#include <stdint.h>
+
+#define REDWOOD_TOUCH_DEVICE "/dev/redwood-touch"
+
+#define REDWOOD_TOUCH_DOWN 1 /* a finger has landed */
+#define REDWOOD_TOUCH_MOVE 2
+#define REDWOOD_TOUCH_UP 3 /* it has lifted (x, y: where it was last) */
+#define REDWOOD_BUTTON_DOWN 4 /* a hardware button; `finger` says which (REDWOOD_BUTTON_*), x and y are 0 */
+#define REDWOOD_BUTTON_UP 5
+
+#define REDWOOD_BUTTON_LOCK 1 /* the side button */
+#define REDWOOD_BUTTON_VOLUME_UP 2
+#define REDWOOD_BUTTON_VOLUME_DOWN 3
+#define REDWOOD_BUTTON_HOME 4
+
+struct redwood_touch {
+ uint64_t time; /* mach_absolute_time() when the sample was posted */
+ uint32_t type; /* REDWOOD_TOUCH_* or REDWOOD_BUTTON_DOWN/UP */
+ uint32_t finger; /* which finger, from 0 (or which button) */
+ uint32_t x, y; /* position on the display, 0 = left/top edge, 65535 = right/bottom edge */
+};
+
+#ifdef KERNEL
+/* For drivers; not from interrupt context. */
+void redwood_touch_post(uint32_t type, uint32_t finger, uint32_t x, uint32_t y);
+void redwood_input_init(void);
+void redwood_virtio_input_init(void); /* boot-arg virtio_input=1: QEMU's virtio pointer and keyboard */
+void redwood_goodix_init(void); /* boot-arg touchscreen=1: the phone's touch screen */
+void redwood_cpufreq_init(void); /* boot-arg cpufreq=1: the phone's processor at full speed */
+#endif
+
+#endif /* _SYS_REDWOOD_INPUT_H_ */
diff --git a/xnu/files/iokit/Kernel/GenericARMPE.cpp b/xnu/files/iokit/Kernel/GenericARMPE.cpp
new file mode 100644
index 0000000..00fe3d8
--- /dev/null
+++ b/xnu/files/iokit/Kernel/GenericARMPE.cpp
@@ -0,0 +1,292 @@
+/*
+ * GenericARMPE: a minimal platform expert for non-Apple ARMv8 boards.
+ *
+ * On Apple hardware the platform expert comes from a closed kext
+ * (AppleARMPlatform). Without one, IOKit falls through to IOPanicPlatform
+ * ("Unable to find driver for this platform"). This class is the least that
+ * lets IOKit start on a board described by a loader-built device tree:
+ * it publishes the device-tree nodes as nubs and names the machine.
+ */
+extern "C" {
+#include <pexpert/pexpert.h>
+#include <kern/cpu_number.h>
+}
+#include <machine/machine_routines.h>
+#include <IOKit/IOPlatformExpert.h>
+#include <IOKit/IODeviceTreeSupport.h>
+#include <IOKit/IOLib.h>
+#include <IOKit/IOCPU.h>
+#include <kern/clock.h>
+
+#include "MiniDrivers.h"
+
+extern "C" kern_return_t processor_start(processor_t processor);
+
+/*
+ * GenericARMCPU: registers a device-tree CPU node with the kernel. The closed
+ * AppleARMCPU driver does this on Apple hardware; without it the kernel waits
+ * forever for the CPU count (ml_wait_max_cpus) and never calls
+ * cpu_machine_init() on the boot processor.
+ *
+ * Only the boot CPU is brought up for now. Secondary CPUs need a start
+ * method (PSCI CPU_ON) and inter-processor interrupts through the GIC.
+ */
+class GenericARMCPU : public IOCPU
+{
+ OSDeclareDefaultStructors(GenericARMCPU);
+
+public:
+ virtual bool start(IOService * provider) APPLE_KEXT_OVERRIDE;
+ virtual void initCPU(bool boot) APPLE_KEXT_OVERRIDE;
+ virtual void quiesceCPU(void) APPLE_KEXT_OVERRIDE;
+ virtual kern_return_t startCPU(vm_offset_t start_paddr, vm_offset_t arg_paddr) APPLE_KEXT_OVERRIDE;
+ virtual void haltCPU(void) APPLE_KEXT_OVERRIDE;
+ virtual const OSSymbol * getCPUName(void) APPLE_KEXT_OVERRIDE;
+};
+
+OSDefineMetaClassAndStructors(GenericARMCPU, IOCPU);
+
+bool
+GenericARMCPU::start(IOService * provider)
+{
+ ml_processor_info_t info;
+ perfmon_interrupt_handler_func pmi_handler = NULL;
+ uint32_t phys_id = 0;
+
+ if (!IOCPU::start(provider)) {
+ return false;
+ }
+
+ OSData * reg = OSDynamicCast(OSData, provider->getProperty("reg"));
+ if (reg != NULL && reg->getLength() >= sizeof(uint32_t)) {
+ phys_id = *(const uint32_t *)reg->getBytesNoCopy();
+ }
+
+ setCPUNumber((UInt32)ml_get_boot_cpu_number());
+
+ bzero(&info, sizeof(info));
+ info.cpu_id = (cpu_id_t)this;
+ info.log_id = getCPUNumber();
+ info.phys_id = phys_id;
+ info.cluster_type = CLUSTER_TYPE_SMP;
+ if (ml_processor_register(&info, &machProcessor, &ipi_handler, &pmi_handler) != KERN_SUCCESS) {
+ IOLog("GenericARMCPU: ml_processor_register failed\n");
+ return false;
+ }
+
+ /* Unblocks everything that waits for the CPU count to be known. */
+ ml_set_max_cpus(1);
+
+ setCPUState(kIOCPUStateUninitalized);
+ registerService();
+
+ /* Runs cpu_machine_init() -> initCPU(true) on this (the boot) processor. */
+ processor_start(machProcessor);
+ IOLog("GenericARMCPU: cpu %u (phys id 0x%x) registered\n", (unsigned)getCPUNumber(), phys_id);
+ return true;
+}
+
+void
+GenericARMCPU::initCPU(bool boot)
+{
+ /* The interrupt controller and timer were set up in arm_init (pe_init_fiq). */
+ setCPUState(kIOCPUStateRunning);
+}
+
+void
+GenericARMCPU::quiesceCPU(void)
+{
+}
+
+kern_return_t
+GenericARMCPU::startCPU(vm_offset_t start_paddr, vm_offset_t arg_paddr)
+{
+ return KERN_NOT_SUPPORTED;
+}
+
+void
+GenericARMCPU::haltCPU(void)
+{
+}
+
+const OSSymbol *
+GenericARMCPU::getCPUName(void)
+{
+ char name[32];
+ snprintf(name, sizeof(name), "Primary%u", (unsigned)getCPUNumber());
+ return OSSymbol::withCString(name);
+}
+
+class GenericARMPE : public IODTPlatformExpert
+{
+ OSDeclareDefaultStructors(GenericARMPE);
+
+public:
+ virtual IOService * probe(IOService * provider, SInt32 * score) APPLE_KEXT_OVERRIDE;
+ virtual bool start(IOService * provider) APPLE_KEXT_OVERRIDE;
+ virtual const char * deleteList(void) APPLE_KEXT_OVERRIDE;
+ virtual const char * excludeList(void) APPLE_KEXT_OVERRIDE;
+ virtual bool getMachineName(char * name, int maxLength) APPLE_KEXT_OVERRIDE;
+ virtual long getGMTTimeOfDay(void) APPLE_KEXT_OVERRIDE;
+ virtual void setGMTTimeOfDay(long secs) APPLE_KEXT_OVERRIDE;
+};
+
+#define super IODTPlatformExpert
+
+OSDefineMetaClassAndStructors(GenericARMPE, IODTPlatformExpert);
+
+IOService *
+GenericARMPE::probe(IOService * provider, SInt32 * score)
+{
+ /*
+ * IODTPlatformExpert::probe() wants an IONameMatch against the root
+ * node; this expert is the only one built in, so it takes any board.
+ */
+ if (!IOPlatformExpert::probe(provider, score)) {
+ return NULL;
+ }
+ return this;
+}
+
+bool
+GenericARMPE::start(IOService * provider)
+{
+ if (!super::start(provider)) {
+ return false;
+ }
+ IOLog("GenericARMPE: platform \"%s\"\n", provider->getName());
+
+ /*
+ * super::start() published the /cpus children as nubs. Attach a CPU
+ * driver to the boot processor's nub (device-tree state "running").
+ */
+ OSIterator * iter = getChildIterator(gIOServicePlane);
+ if (iter != NULL) {
+ OSObject * obj;
+ while ((obj = iter->getNextObject()) != NULL) {
+ IOService * nub = OSDynamicCast(IOService, obj);
+ OSData * state = nub ? OSDynamicCast(OSData, nub->getProperty("state")) : NULL;
+
+ if (state == NULL || strncmp((const char *)state->getBytesNoCopy(), "running", state->getLength()) != 0) {
+ continue;
+ }
+ GenericARMCPU * cpu = new GenericARMCPU;
+ if (cpu != NULL && cpu->init() && cpu->attach(nub)) {
+ if (!cpu->start(nub)) {
+ cpu->detach(nub);
+ }
+ }
+ if (cpu != NULL) {
+ cpu->release();
+ }
+ }
+ iter->release();
+ }
+
+ /* BSD looks the platform expert up by class (IOSecureBSDRoot). */
+ registerService();
+
+ /* Stand-ins for the closed graphics drivers that the iOS window server talks to. */
+ MiniIOSurfaceStart(this);
+ MiniIOMobileFramebufferStart(this);
+ MiniAppleKeyStoreStart();
+ return true;
+}
+
+/*
+ * The time of day. There is no driver for a real-time clock here; whoever started the kernel
+ * says what time it was then -- the boot-arg epoch= (seconds since 1970, put there by the
+ * host scripts) or, failing that, the property boot-epoch of /chosen (the loader, from the
+ * firmware's clock) -- and the kernel's own timer counts from there. Without either the
+ * calendar starts in 1970, as before.
+ */
+static long gBootEpoch; /* the calendar time at which the system timer read zero */
+static bool gBootEpochKnown;
+
+static void
+findBootEpoch(void)
+{
+ uint64_t epoch = 0;
+
+ if (gBootEpochKnown) {
+ return;
+ }
+ gBootEpochKnown = true;
+ if (!PE_parse_boot_argn("epoch", &epoch, sizeof(epoch)) || epoch == 0) {
+ IORegistryEntry * chosen = IORegistryEntry::fromPath("/chosen", gIODTPlane);
+ OSData * data = chosen ? OSDynamicCast(OSData, chosen->getProperty("boot-epoch")) : NULL;
+
+ if (data != NULL && data->getLength() == sizeof(epoch)) {
+ memcpy(&epoch, data->getBytesNoCopy(), sizeof(epoch));
+ }
+ OSSafeReleaseNULL(chosen);
+ }
+ if (epoch != 0) {
+ clock_sec_t secs;
+ clock_usec_t usecs;
+
+ clock_get_system_microtime(&secs, &usecs);
+ gBootEpoch = (long) epoch - (long) secs;
+ }
+}
+
+long
+GenericARMPE::getGMTTimeOfDay(void)
+{
+ clock_sec_t secs;
+ clock_usec_t usecs;
+
+ findBootEpoch();
+ if (gBootEpoch == 0) {
+ return 0;
+ }
+ clock_get_system_microtime(&secs, &usecs);
+ return gBootEpoch + (long) secs;
+}
+
+void
+GenericARMPE::setGMTTimeOfDay(long secs)
+{
+ clock_sec_t uptime;
+ clock_usec_t usecs;
+
+ clock_get_system_microtime(&uptime, &usecs);
+ gBootEpoch = secs - (long) uptime;
+ gBootEpochKnown = true;
+}
+
+/* Device-tree nodes to drop entirely. */
+const char *
+GenericARMPE::deleteList(void)
+{
+ return "('packages', 'psuedo-usb', 'psuedo-hid', 'multiboot', 'rtas')";
+}
+
+/* Top-level nodes that describe boot state rather than devices: no nubs for these. */
+const char *
+GenericARMPE::excludeList(void)
+{
+ return "('chosen', 'memory', 'options', 'aliases', 'defaults', 'pram', 'cpus')";
+}
+
+/*
+ * 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
+ * MobileGestalt settles for an iPod touch.
+ */
+bool
+GenericARMPE::getMachineName(char * name, int maxLength)
+{
+ uint32_t real = 0;
+
+ /*
+ * (boot-arg machine_name=1 for the real thing. Not the default yet: as an "iPhone10,3"
+ * backboardd no longer takes our virtual touch screen for the phone's own, and without
+ * touches the name of the device matters little.)
+ */
+ if (!PE_parse_boot_argn("machine_name", &real, sizeof(real)) || !real ||
+ !IODTPlatformExpert::getMachineName(name, maxLength) || name[0] == 0) {
+ strlcpy(name, "arm64", maxLength);
+ }
+ return true;
+}
diff --git a/xnu/files/iokit/Kernel/MiniAppleKeyStore.cpp b/xnu/files/iokit/Kernel/MiniAppleKeyStore.cpp
new file mode 100644
index 0000000..13be44b
--- /dev/null
+++ b/xnu/files/iokit/Kernel/MiniAppleKeyStore.cpp
@@ -0,0 +1,281 @@
+/*
+ * MiniAppleKeyStore: a stand-in for Apple's AppleKeyStore (the kernel side of the keybag,
+ * which on real hardware talks to the Secure Enclave), as seen by MobileKeyBag.framework
+ * and libaks.
+ *
+ * It describes one fixed situation: a device that has no passcode -- never locked, unlocked
+ * since boot. Nothing is encrypted here and no keys exist; requests that would need them
+ * (wrapping keys for the keychain, creating or loading bags) are refused, logged once.
+ *
+ * The protocol was worked out from the user-space side of iOS 16.5: selectors, and the
+ * DER-encoded answers ("SET of SEQUENCE { UTF8String key, INTEGER value }").
+ */
+
+#include <IOKit/IOLib.h>
+#include <IOKit/IOKitKeys.h>
+#include <IOKit/IOService.h>
+#include <IOKit/IOUserClient.h>
+#include <IOKit/IOMemoryDescriptor.h>
+#include <sys/systm.h>
+#include <sys/proc.h>
+
+#include "MiniDrivers.h"
+
+enum {
+ kAKSOpenCheck = 0x00,
+ kAKSGetLockState = 0x07, /* in: handle; out: state flags */
+ kAKSLockDevice = 0x08,
+ kAKSUnlockDevice = 0x09,
+ kAKSUnlockBag = 0x0c,
+ kAKSGetSystem = 0x0e, /* out: the handle of the system keybag */
+ kAKSGetDeviceState = 0x11, /* in: handle; out: DER */
+ kAKSGetBagUUID = 0x17, /* out: 16 bytes */
+ kAKSAssertHold = 0x1a,
+ kAKSAssertDrop = 0x1b,
+ kAKSGetConfiguration = 0x1f, /* in: handle; out: DER (a big buffer, so out of line) */
+ kAKSLockDeviceNow = 0x20,
+ kAKSGetExtendedState = 0x23, /* as kAKSGetDeviceState */
+ kAKSGeneration = 0x28,
+ kAKSAssertPromote = 0x64,
+ kAKSAssertConsume = 0x65,
+ kAKSNotifyStateSet = 0x66, /* "the first-unlock notification has been posted" */
+ kAKSNotifyStateIsSet = 0x67,
+ kAKSPrewarm = 0x73,
+};
+
+/* state flags: bit 1 no passcode, bit 2 unlocked since boot */
+#define kAKSStateFlags 0x6
+/* lock state: 0 unlocked, 1 locked, 2 locking, 3 disabled (no passcode) */
+#define kAKSLockStateDisabled 3
+
+static uint64_t gAKSLogged[4]; /* selectors already reported */
+static bool gAKSNotifyState;
+
+/* Append SEQUENCE { UTF8String key, INTEGER value } for a value below 128; returns the new length. */
+static size_t
+derPut(uint8_t * buf, size_t length, const char * key, uint8_t value)
+{
+ size_t keyLength = strlen(key);
+
+ buf[length++] = 0x30;
+ buf[length++] = (uint8_t) (keyLength + 5);
+ buf[length++] = 0x0c;
+ buf[length++] = (uint8_t) keyLength;
+ memcpy(buf + length, key, keyLength);
+ length += keyLength;
+ buf[length++] = 0x02;
+ buf[length++] = 0x01;
+ buf[length++] = value;
+ return length;
+}
+
+/* The answer to "device state": every field zero, except the two that say "no passcode, unlocked". */
+static size_t
+deviceState(uint8_t * buf)
+{
+ size_t length = 2;
+
+ length = derPut(buf, length, "sb", 0); /* backoff */
+ length = derPut(buf, length, "sr", 0);
+ length = derPut(buf, length, "ss", kAKSStateFlags);
+ length = derPut(buf, length, "sas", 0); /* assertion set */
+ length = derPut(buf, length, "sfa", 0); /* failed attempts */
+ length = derPut(buf, length, "sgs", 0); /* generation state */
+ length = derPut(buf, length, "sls", kAKSLockStateDisabled);
+ length = derPut(buf, length, "sgpe", 0); /* grace period enabled */
+ length = derPut(buf, length, "srcd", 0); /* recovery countdown */
+ buf[0] = 0x31;
+ buf[1] = (uint8_t) (length - 2);
+ return length;
+}
+
+static size_t
+configuration(uint8_t * buf)
+{
+ size_t length = 2;
+
+ length = derPut(buf, length, "bd", 0); /* backoff delay */
+ length = derPut(buf, length, "gp", 0); /* grace period */
+ length = derPut(buf, length, "mua", 10); /* maximum unlock attempts */
+ buf[0] = 0x31;
+ buf[1] = (uint8_t) (length - 2);
+ return length;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+class AppleKeyStore : public IOService
+{
+ OSDeclareDefaultStructors(AppleKeyStore);
+
+public:
+ virtual bool start(IOService * provider) APPLE_KEXT_OVERRIDE;
+};
+
+OSDefineMetaClassAndStructors(AppleKeyStore, IOService);
+
+bool
+AppleKeyStore::start(IOService * provider)
+{
+ if (!IOService::start(provider)) {
+ return false;
+ }
+ setProperty(kIOUserClientClassKey, "AppleKeyStoreUserClient");
+ setName("AppleKeyStore");
+ registerService();
+ return true;
+}
+
+class AppleKeyStoreUserClient : public IOUserClient
+{
+ OSDeclareDefaultStructors(AppleKeyStoreUserClient);
+
+ static IOReturn answer(IOExternalMethodArguments * args, const uint8_t * bytes, size_t length);
+
+public:
+ virtual IOReturn clientClose(void) APPLE_KEXT_OVERRIDE;
+ virtual IOReturn registerNotificationPort(mach_port_t port, UInt32 type, io_user_reference_t refCon) APPLE_KEXT_OVERRIDE;
+ virtual IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments * args,
+ IOExternalMethodDispatch * dispatch, OSObject * target, void * reference) APPLE_KEXT_OVERRIDE;
+};
+
+OSDefineMetaClassAndStructors(AppleKeyStoreUserClient, IOUserClient);
+
+IOReturn
+AppleKeyStoreUserClient::clientClose(void)
+{
+ if (!isInactive()) {
+ terminate();
+ }
+ return kIOReturnSuccess;
+}
+
+/* keybagd asks to be told about keys to back up and bags to save; there never are any. */
+IOReturn
+AppleKeyStoreUserClient::registerNotificationPort(mach_port_t port, UInt32 type, io_user_reference_t refCon)
+{
+ releaseNotificationPort(port);
+ return kIOReturnSuccess;
+}
+
+/* A structure answer; a big buffer on the other side arrives as a memory descriptor. */
+IOReturn
+AppleKeyStoreUserClient::answer(IOExternalMethodArguments * args, const uint8_t * bytes, size_t length)
+{
+ if (args->structureOutputDescriptor != NULL) {
+ IOMemoryDescriptor * out = args->structureOutputDescriptor;
+ IOReturn ret;
+
+ if (out->getLength() < length) {
+ return kIOReturnNoSpace;
+ }
+ ret = out->prepare();
+ if (ret == kIOReturnSuccess) {
+ out->writeBytes(0, bytes, length);
+ out->complete();
+ args->structureOutputDescriptorSize = (uint32_t) length;
+ }
+ return ret;
+ }
+ if (args->structureOutput == NULL || args->structureOutputSize < length) {
+ return kIOReturnNoSpace;
+ }
+ memcpy(args->structureOutput, bytes, length);
+ args->structureOutputSize = (uint32_t) length;
+ return kIOReturnSuccess;
+}
+
+IOReturn
+AppleKeyStoreUserClient::externalMethod(uint32_t selector, IOExternalMethodArguments * args,
+ IOExternalMethodDispatch * dispatch, OSObject * target, void * reference)
+{
+ static const uint8_t bagUUID[16] = { 0x72, 0x65, 0x64, 0x77, 0x6f, 0x6f, 0x64, 0x00, 0x6b, 0x65, 0x79, 0x62, 0x61, 0x67, 0x00, 0x01 };
+ uint8_t der[128];
+ uint64_t * out = args->scalarOutput;
+
+ switch (selector) {
+ case kAKSOpenCheck:
+ case kAKSLockDevice:
+ case kAKSLockDeviceNow:
+ case kAKSUnlockDevice:
+ case kAKSUnlockBag:
+ case kAKSAssertHold:
+ case kAKSAssertDrop:
+ case kAKSAssertPromote:
+ case kAKSAssertConsume:
+ case kAKSPrewarm:
+ return kIOReturnSuccess;
+
+ case kAKSGetLockState:
+ if (args->scalarOutputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ out[0] = kAKSStateFlags;
+ args->scalarOutputCount = 1;
+ return kIOReturnSuccess;
+
+ case kAKSGetSystem:
+ case kAKSGeneration:
+ if (args->scalarOutputCount >= 1) {
+ out[0] = 0;
+ args->scalarOutputCount = 1;
+ }
+ return kIOReturnSuccess;
+
+ case kAKSGetDeviceState:
+ case kAKSGetExtendedState:
+ return answer(args, der, deviceState(der));
+
+ case kAKSGetConfiguration:
+ return answer(args, der, configuration(der));
+
+ case kAKSGetBagUUID:
+ return answer(args, bagUUID, sizeof(bagUUID));
+
+ case kAKSNotifyStateSet:
+ gAKSNotifyState = true;
+ return kIOReturnSuccess;
+
+ case kAKSNotifyStateIsSet:
+ if (args->scalarOutputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ out[0] = gAKSNotifyState;
+ args->scalarOutputCount = 1;
+ return kIOReturnSuccess;
+
+ default:
+ break;
+ }
+
+ if (selector < 256 && !(gAKSLogged[selector / 64] & (1ULL << (selector % 64)))) {
+ char procname[32] = "?";
+
+ gAKSLogged[selector / 64] |= 1ULL << (selector % 64);
+ proc_selfname(procname, sizeof(procname));
+ IOLog("MiniAppleKeyStore: %s[%d] selector 0x%x not implemented (scalars %u in, %u out; structure %u in, %u out)\n",
+ procname, proc_selfpid(), selector, args->scalarInputCount, args->scalarOutputCount, args->structureInputSize,
+ args->structureOutputSize);
+ }
+ return kIOReturnUnsupported;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+MiniAppleKeyStoreStart(void)
+{
+ /* user space looks for it by class, and by the path IOService:/IOResources/AppleKeyStore */
+ IOService * resources = IOService::getResourceService();
+ AppleKeyStore * store = OSTypeAlloc(AppleKeyStore);
+
+ if (resources == NULL || store == NULL || !store->init() || !store->attach(resources)) {
+ OSSafeReleaseNULL(store);
+ IOLog("MiniAppleKeyStore: cannot create the service\n");
+ return;
+ }
+ if (!store->start(resources)) {
+ store->detach(resources);
+ }
+ store->release();
+}
diff --git a/xnu/files/iokit/Kernel/MiniDrivers.h b/xnu/files/iokit/Kernel/MiniDrivers.h
new file mode 100644
index 0000000..ed58101
--- /dev/null
+++ b/xnu/files/iokit/Kernel/MiniDrivers.h
@@ -0,0 +1,19 @@
+/*
+ * Stand-ins for Apple's closed kernel extensions: just enough of each for the stock iOS
+ * user space to work on a machine without Apple hardware. The platform expert
+ * (GenericARMPE) starts them once the registry is up.
+ *
+ * MiniIOSurface.cpp IOSurface: pixel buffers shared between processes
+ * MiniIOMobileFramebuffer.cpp IOMobileFramebuffer: the display (the boot framebuffer)
+ * MiniAppleKeyStore.cpp AppleKeyStore: the keybag of a device without a passcode
+ */
+#ifndef _IOKIT_MINIDRIVERS_H
+#define _IOKIT_MINIDRIVERS_H
+
+#include <IOKit/IOService.h>
+
+void MiniIOSurfaceStart(IOService * provider);
+void MiniIOMobileFramebufferStart(IOService * provider);
+void MiniAppleKeyStoreStart(void);
+
+#endif /* _IOKIT_MINIDRIVERS_H */
diff --git a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
new file mode 100644
index 0000000..1b1915d
--- /dev/null
+++ b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
@@ -0,0 +1,883 @@
+/*
+ * MiniIOMobileFramebuffer: a stand-in for Apple's display driver family, as seen by
+ * IOMobileFramebuffer.framework (and through it by CoreAnimation's window server).
+ *
+ * The display is the framebuffer the boot loader left us (the one the kernel's text console
+ * draws on). There is no hardware behind it that we drive: a "swap" copies the pixels of the
+ * 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.
+ */
+
+#include <IOKit/IOLib.h>
+#include <IOKit/IOLocks.h>
+#include <IOKit/IOKitKeys.h>
+#include <IOKit/IOService.h>
+#include <IOKit/IOUserClient.h>
+#include <IOKit/IODeviceTreeSupport.h>
+#include <libkern/c++/OSData.h>
+#include <libkern/c++/OSNumber.h>
+#include <libkern/c++/OSDictionary.h>
+#include <libkern/c++/OSArray.h>
+#include <libkern/c++/OSBoolean.h>
+#include <kern/thread_call.h>
+#include <kern/clock.h>
+#include <pexpert/pexpert.h>
+#include <sys/systm.h>
+#include <sys/proc.h>
+
+extern "C" {
+#include <console/video_console.h>
+extern struct vc_info vinfo; /* the boot framebuffer, as the text console knows it */
+}
+
+#include <IOKit/IOBufferMemoryDescriptor.h>
+
+#include "MiniIOSurface.h"
+
+/* IOConnectCallMethod selectors of the framebuffer user client (iOS 16.5) */
+enum {
+ kFBMethodGetLayerDefaultSurface = 3,
+ kFBMethodSwapBegin = 4,
+ kFBMethodSwapEnd = 5,
+ kFBMethodSwapWait = 6,
+ kFBMethodGetID = 7,
+ kFBMethodGetDisplaySize = 8,
+ kFBMethodRequestPowerChange = 12,
+ kFBMethodSwapSignal = 20,
+ kFBMethodGetDigitalOutState = 25,
+ kFBMethodGetDotPitch = 28,
+ kFBMethodGetDisplayArea = 29,
+ kFBMethodSwapCancel = 52,
+ kFBMethodGetColorRemapMode = 57,
+ kFBMethodNotifications = 72,
+ kFBMethodChangeFrameInfo = 73,
+ kFBMethodSupportedFrameInfo = 74,
+ kFBMethodGetCurrentAbsoluteTime = 77,
+ kFBMethodGetBlock = 79,
+ kFBMethodSwapCancelAll = 81,
+ kFBMethodGetProtectionOptions = 82,
+};
+
+/* The swap request (IOMobileFramebufferSwapEnd): 0x46c bytes, of which we read these. */
+#define SWAP_SIZE 0x46c
+#define SWAP_ID 0x50
+#define SWAP_SURFACE(layer) (0x54 + 4 * (layer)) /* surface number, 0 = none */
+#define SWAP_SOURCE(layer) (0x64 + 16 * (layer)) /* x, y, width, height in the surface */
+#define SWAP_ENABLED(layer) (0xa4 + 4 * (layer))
+#define SWAP_DEST(layer) (0xc4 + 16 * (layer)) /* x, y, width, height on the display */
+#define SWAP_LAYERS_SET 0x104 /* bit per layer given in this swap */
+#define SWAP_LAYERS_CLEARED 0x108
+#define SWAP_LAYERS 4
+
+#define kFBNotifyVSync 5
+#define kFBNotifyTypes 8
+#define kFBRefreshHz 60
+
+#define FOURCC(a, b, c, d) ((uint32_t)(a) << 24 | (uint32_t)(b) << 16 | (uint32_t)(c) << 8 | (uint32_t)(d))
+
+static uint64_t gFBLogged[2]; /* selectors already reported */
+static uint8_t gFBCalls[128]; /* how many calls of each selector were traced */
+
+/*
+ * 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
+ * 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).
+ * Boot-args fbwidth= and fbheight= change the size reported.
+ */
+#define kFBDefaultWidth 1125
+#define kFBDefaultHeight 2436
+#define kFBDotsPerInch 458
+
+static TUNABLE(uint32_t, gFBWidth, "fbwidth", kFBDefaultWidth);
+static TUNABLE(uint32_t, gFBHeight, "fbheight", kFBDefaultHeight);
+/* Boot-arg fbtrace=N: log the first N calls of every selector (default 3). */
+static TUNABLE(uint32_t, gFBTrace, "fbtrace", 3);
+
+/*
+ * A recording of the screen, for a machine one cannot look at while it runs (the phone is
+ * reached only through the boot loader, before and after the kernel).
+ * Boot-args rec_secs=N [rec_start=S] [rec_mb=M]: from S seconds after the first frame, for N
+ * seconds, every frame that is shown is also kept -- one pixel of every REC_STEP in each
+ * direction, three bytes a pixel -- in a piece of memory of M megabytes (default 480, which
+ * is 520 frames) that is left in place when the kernel returns to the loader. The loader
+ * hands it to the host ("xl recording"), where tools/recording.py makes a video of it.
+ *
+ * struct rec_header, then per frame: struct rec_frame, width * height pixels (R, G, B)
+ */
+static TUNABLE(uint32_t, gRecSeconds, "rec_secs", 0);
+static TUNABLE(uint32_t, gRecStart, "rec_start", 0);
+static TUNABLE(uint32_t, gRecMegabytes, "rec_mb", 480);
+#define REC_STEP 3
+
+struct rec_header {
+ char magic[8]; /* "RWREC002" */
+ uint32_t width, height;
+ uint32_t frames;
+ uint32_t reserved;
+};
+struct rec_frame {
+ uint64_t nanoseconds; /* since the first frame of the recording */
+};
+
+extern "C" uint64_t loader_recording[3]; /* { physical address, bytes, kernel address }: osfmk/arm64/loader_return.c */
+
+static uint32_t
+swapWord(const uint8_t * swap, unsigned offset)
+{
+ uint32_t value;
+
+ memcpy(&value, swap + offset, sizeof(value));
+ return value;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+class IOMobileFramebuffer : public IOService
+{
+ OSDeclareDefaultStructors(IOMobileFramebuffer);
+
+public:
+ IOLock * fLock;
+ uint8_t * fBase; /* the boot framebuffer: the panel */
+ uint32_t fPanelWidth, fPanelHeight, fRowBytes;
+ uint32_t fWidth, fHeight; /* the display as user space sees it */
+ MiniIOSurface * fDefaultSurface;
+ uint32_t fSwapID;
+ uint32_t fSwapsShown;
+ bool fGraphics; /* the text console has been told to stop */
+ /* how the display is doing: frames and time spent drawing them here since fStatSince */
+ uint32_t fStatFrames;
+ uint64_t fStatSince, fStatDrawing;
+ /* the screen recording, if one was asked for */
+ uint32_t * fColumn; /* drawLayer(): source column for every panel column */
+ uint8_t * fRecBase;
+ uint64_t fRecSize, fRecUsed;
+ uint64_t fFirstFrame, fRecFirst; /* when the first frame was shown, and the first recorded */
+ bool fRecDone;
+
+ virtual bool start(IOService * provider) APPLE_KEXT_OVERRIDE;
+ void publishModes(void);
+ MiniIOSurface * defaultSurface(void);
+ void present(const uint8_t * swap);
+ void drawLayer(MiniIOSurface * s, const int32_t * src, const int32_t * dst);
+ void record(MiniIOSurface * s);
+};
+
+OSDefineMetaClassAndStructors(IOMobileFramebuffer, IOService);
+
+static void
+setNumber(OSDictionary * dict, const char * key, uint64_t value)
+{
+ OSNumber * n = OSNumber::withNumber(value, 32);
+
+ if (n != NULL) {
+ dict->setObject(key, n);
+ n->release();
+ }
+}
+
+/*
+ * The modes of the display, the way CoreAnimation reads them (the properties TimingElements
+ * and ColorElements; without a mode it draws nothing). One timing, the panel's size at
+ * 60 Hz, with one colour mode, 8-bit RGB. The identifiers are what "the current mode"
+ * (block 0x40) answers with.
+ */
+#define kFBTimingID 1
+#define kFBColorID 1
+
+void
+IOMobileFramebuffer::publishModes(void)
+{
+ OSDictionary * timing = OSDictionary::withCapacity(8);
+ OSDictionary * horizontal = OSDictionary::withCapacity(4);
+ OSDictionary * vertical = OSDictionary::withCapacity(4);
+ OSDictionary * color = OSDictionary::withCapacity(8);
+ OSArray * timings = OSArray::withCapacity(1);
+ OSArray * colors = OSArray::withCapacity(1);
+ const uint32_t rate = kFBRefreshHz << 16; /* 16.16 fixed point */
+
+ if (timing == NULL || horizontal == NULL || vertical == NULL || color == NULL || timings == NULL || colors == NULL) {
+ return;
+ }
+ setNumber(color, "ID", kFBColorID);
+ setNumber(color, "PixelEncoding", 0); /* RGB 4:4:4 */
+ setNumber(color, "Depth", 8);
+ setNumber(color, "Colorimetry", 1);
+ setNumber(color, "EOTF", 1);
+ setNumber(color, "DynamicRange", 0);
+ setNumber(color, "Score", 1);
+ color->setObject("IsVirtual", kOSBooleanFalse);
+ colors->setObject(color);
+
+ setNumber(horizontal, "Active", fWidth);
+ setNumber(horizontal, "Total", fWidth);
+ setNumber(horizontal, "SyncRate", rate);
+ setNumber(horizontal, "PreciseSyncRate", rate);
+ setNumber(vertical, "Active", fHeight);
+ setNumber(vertical, "Total", fHeight);
+ setNumber(vertical, "SyncRate", rate);
+ setNumber(vertical, "PreciseSyncRate", rate);
+ setNumber(timing, "ID", kFBTimingID);
+ setNumber(timing, "Score", 1);
+ timing->setObject("IsVirtual", kOSBooleanFalse);
+ timing->setObject("IsOverscanned", kOSBooleanFalse);
+ timing->setObject("HorizontalAttributes", horizontal);
+ timing->setObject("VerticalAttributes", vertical);
+ timing->setObject("ColorModes", colors);
+ timings->setObject(timing);
+
+ setProperty("TimingElements", timings);
+ setProperty("ColorElements", colors);
+ OSSafeReleaseNULL(timings);
+ OSSafeReleaseNULL(colors);
+ OSSafeReleaseNULL(timing);
+ OSSafeReleaseNULL(horizontal);
+ OSSafeReleaseNULL(vertical);
+ OSSafeReleaseNULL(color);
+}
+
+bool
+IOMobileFramebuffer::start(IOService * provider)
+{
+ if (!IOService::start(provider)) {
+ return false;
+ }
+ if (vinfo.v_baseaddr == 0 || vinfo.v_width == 0 || vinfo.v_height == 0 || vinfo.v_depth != 32) {
+ IOLog("MiniIOMobileFramebuffer: no usable boot framebuffer (%ux%u, depth %u)\n", vinfo.v_width, vinfo.v_height,
+ vinfo.v_depth);
+ return false;
+ }
+ fLock = IOLockAlloc();
+ fBase = (uint8_t *) vinfo.v_baseaddr;
+ fPanelWidth = vinfo.v_width;
+ fPanelHeight = vinfo.v_height;
+ fRowBytes = vinfo.v_rowbytes;
+ fWidth = gFBWidth ? gFBWidth : fPanelWidth;
+ fHeight = gFBHeight ? gFBHeight : fPanelHeight;
+ fColumn = IONewZero(uint32_t, fPanelWidth);
+ IOLog("MiniIOMobileFramebuffer: display %ux%u on a panel of %ux%u (%u bytes per row)\n", fWidth, fHeight,
+ fPanelWidth, fPanelHeight, fRowBytes);
+
+ if (gRecSeconds != 0) {
+ /* one piece of physical memory: the loader will send it over USB as it lies */
+ IOBufferMemoryDescriptor * memory = IOBufferMemoryDescriptor::inTaskWithPhysicalMask(kernel_task,
+ kIODirectionInOut | kIOMemoryPhysicallyContiguous, (mach_vm_size_t) gRecMegabytes << 20, ~0ULL);
+
+ if (memory != NULL) {
+ struct rec_header * header = (struct rec_header *) memory->getBytesNoCopy();
+
+ fRecBase = (uint8_t *) header;
+ fRecSize = (uint64_t) gRecMegabytes << 20;
+ fRecUsed = sizeof(*header);
+ bzero(header, sizeof(*header));
+ memcpy(header->magic, "RWREC002", 8);
+ header->width = fWidth / REC_STEP;
+ header->height = fHeight / REC_STEP;
+ loader_recording[0] = memory->getPhysicalSegment(0, NULL);
+ loader_recording[1] = fRecUsed;
+ loader_recording[2] = (uint64_t) (uintptr_t) fRecBase;
+ IOLog("MiniIOMobileFramebuffer: recording %u s of the screen at %ux%u from second %u, into %u MB at %#llx\n",
+ gRecSeconds, header->width, header->height, gRecStart, gRecMegabytes, loader_recording[0]);
+ } else {
+ IOLog("MiniIOMobileFramebuffer: no memory for a recording of %u MB\n", gRecMegabytes);
+ }
+ }
+
+ setProperty(kIOUserClientClassKey, "IOMobileFramebufferUserClient");
+ publishModes();
+ setName("disp0");
+ registerService();
+ return true;
+}
+
+/* Keep a small copy of the frame that is about to be shown (the surface is the whole screen). */
+void
+IOMobileFramebuffer::record(MiniIOSurface * s)
+{
+ struct rec_header * header = (struct rec_header *) fRecBase;
+ uint64_t now = mach_absolute_time(), since_first, since_start = 0;
+ struct rec_frame * frame;
+ uint8_t * to;
+
+ if (fFirstFrame == 0) {
+ fFirstFrame = now;
+ }
+ if (fRecBase == NULL || fRecDone || s->info.width < fWidth || s->info.height < fHeight) {
+ return;
+ }
+ absolutetime_to_nanoseconds(now - fFirstFrame, &since_first);
+ if (since_first < (uint64_t) gRecStart * NSEC_PER_SEC) {
+ return;
+ }
+ if (fRecFirst == 0) {
+ fRecFirst = now;
+ }
+ absolutetime_to_nanoseconds(now - fRecFirst, &since_start);
+ if (since_start > (uint64_t) gRecSeconds * NSEC_PER_SEC ||
+ fRecUsed + sizeof(*frame) + (uint64_t) header->width * header->height * 3 > fRecSize) {
+ fRecDone = true;
+ IOLog("MiniIOMobileFramebuffer: recording finished: %u frames, %llu MB\n", header->frames, fRecUsed >> 20);
+ return;
+ }
+ frame = (struct rec_frame *) (fRecBase + fRecUsed);
+ frame->nanoseconds = since_start;
+ to = (uint8_t *) (frame + 1);
+ for (uint32_t y = 0; y < header->height; y++) {
+ const uint32_t * from = (const uint32_t *) (s->pixels() + (size_t) (y * REC_STEP + 1) * s->info.bytesPerRow);
+
+ for (uint32_t x = 0; x < header->width; x++) {
+ uint32_t pixel = from[x * REC_STEP + 1]; /* B G R A in memory */
+
+ *to++ = (uint8_t) (pixel >> 16);
+ *to++ = (uint8_t) (pixel >> 8);
+ *to++ = (uint8_t) pixel;
+ }
+ }
+ fRecUsed += sizeof(*frame) + (uint64_t) header->width * header->height * 3;
+ header->frames++;
+ loader_recording[1] = fRecUsed;
+}
+
+MiniIOSurface *
+IOMobileFramebuffer::defaultSurface(void)
+{
+ IOLockLock(fLock);
+ if (fDefaultSurface == NULL) {
+ fDefaultSurface = MiniIOSurfaceCreateSimple(fWidth, fHeight, FOURCC('B', 'G', 'R', 'A'));
+ }
+ IOLockUnlock(fLock);
+ return fDefaultSurface;
+}
+
+/*
+ * Put a rectangle of a 32-bit surface on the screen. `dst` is in display coordinates; the
+ * panel may be of another size, and the layer itself may be scaled: both are done in one
+ * step, nearest neighbour.
+ */
+void
+IOMobileFramebuffer::drawLayer(MiniIOSurface * s, const int32_t * src, const int32_t * dst)
+{
+ int32_t sx = src[0], sy = src[1], sw = src[2], sh = src[3];
+ int32_t dx = dst[0], dy = dst[1], dw = dst[2], dh = dst[3];
+ const uint8_t * pixels = s->pixels();
+ uint32_t stride = s->info.bytesPerRow;
+ int32_t px0, py0, px1, py1, cx0, cx1;
+
+ if (sw <= 0 || sh <= 0) {
+ sx = sy = 0;
+ sw = (int32_t) s->info.width;
+ sh = (int32_t) s->info.height;
+ }
+ if (dw <= 0 || dh <= 0) {
+ dx = dy = 0;
+ dw = (int32_t) fWidth;
+ dh = (int32_t) fHeight;
+ }
+ if (sx < 0 || sy < 0 || (uint32_t) (sx + sw) > s->info.width || (uint32_t) (sy + sh) > s->info.height) {
+ return;
+ }
+ /* the rectangle on the panel */
+ px0 = (int32_t) ((int64_t) dx * fPanelWidth / fWidth);
+ py0 = (int32_t) ((int64_t) dy * fPanelHeight / fHeight);
+ px1 = (int32_t) ((int64_t) (dx + dw) * fPanelWidth / fWidth);
+ py1 = (int32_t) ((int64_t) (dy + dh) * fPanelHeight / fHeight);
+ if (px1 <= px0 || py1 <= py0) {
+ return;
+ }
+ /* which pixel of a source row each pixel of a panel row takes: worked out once, not 2.6 million times */
+ cx0 = px0 < 0 ? 0 : px0;
+ cx1 = (uint32_t) px1 > fPanelWidth ? (int32_t) fPanelWidth : px1;
+ for (int32_t x = cx0; x < cx1; x++) {
+ fColumn[x] = (uint32_t) (sx + (int64_t) (x - px0) * sw / (px1 - px0));
+ }
+ for (int32_t y = py0; y < py1; y++) {
+ const uint32_t * from;
+ uint32_t * to;
+
+ if (y < 0 || (uint32_t) y >= fPanelHeight) {
+ continue;
+ }
+ from = (const uint32_t *) (pixels + (size_t) (sy + (int64_t) (y - py0) * sh / (py1 - py0)) * stride);
+ to = (uint32_t *) (fBase + (size_t) y * fRowBytes);
+ if (px1 - px0 == sw && px0 >= 0 && (uint32_t) px1 <= fPanelWidth) {
+ memcpy(to + px0, from + sx, (size_t) sw * 4);
+ continue;
+ }
+ for (int32_t x = cx0; x < cx1; x++) {
+ to[x] = from[fColumn[x]];
+ }
+ }
+}
+
+void
+IOMobileFramebuffer::present(const uint8_t * swap)
+{
+ uint32_t set = swapWord(swap, SWAP_LAYERS_SET);
+ uint64_t began = mach_absolute_time(), nanos;
+ bool report;
+
+ IOLockLock(fLock);
+ report = fSwapsShown < 8;
+ if (report) {
+ IOLog("MiniIOMobileFramebuffer: swap %u (#%u): surfaces %u %u %u %u, layers set 0x%x cleared 0x%x\n",
+ swapWord(swap, SWAP_ID), fSwapsShown, swapWord(swap, SWAP_SURFACE(0)), swapWord(swap, SWAP_SURFACE(1)),
+ swapWord(swap, SWAP_SURFACE(2)), swapWord(swap, SWAP_SURFACE(3)), set, swapWord(swap, SWAP_LAYERS_CLEARED));
+ }
+ for (unsigned layer = 0; layer < SWAP_LAYERS; layer++) {
+ uint32_t sid = swapWord(swap, SWAP_SURFACE(layer));
+ int32_t src[4], dst[4];
+ MiniIOSurface * s;
+
+ if (sid == 0) {
+ /* the bottom layer taken away: nothing is shown, the screen is black */
+ if (layer == 0 && (set & 1) && fGraphics) {
+ for (uint32_t y = 0; y < fPanelHeight; y++) {
+ bzero(fBase + (size_t) y * fRowBytes, (size_t) fPanelWidth * 4);
+ }
+ }
+ continue;
+ }
+ memcpy(src, swap + SWAP_SOURCE(layer), sizeof(src));
+ memcpy(dst, swap + SWAP_DEST(layer), sizeof(dst));
+ s = MiniIOSurfaceCopy(sid);
+ if (report) {
+ IOLog("MiniIOMobileFramebuffer: swap %u layer %u: surface %u%s (%ux%u '%c%c%c%c') "
+ "from %d,%d %dx%d to %d,%d %dx%d, layers set 0x%x\n", swapWord(swap, SWAP_ID), layer, sid,
+ s ? "" : " MISSING", s ? s->info.width : 0, s ? s->info.height : 0,
+ s ? (int) (s->info.pixelFormat >> 24 & 0xff) : '?', s ? (int) (s->info.pixelFormat >> 16 & 0xff) : '?',
+ s ? (int) (s->info.pixelFormat >> 8 & 0xff) : '?', s ? (int) (s->info.pixelFormat & 0xff) : '?',
+ src[0], src[1], src[2], src[3], dst[0], dst[1], dst[2], dst[3], set);
+ }
+ if (s == NULL) {
+ continue;
+ }
+ if (s->info.bytesPerElement == 4 && s->info.planeCount == 0) {
+ if (!fGraphics) {
+ /* the first picture: the kernel's text console must stop drawing over it */
+ fGraphics = true;
+ PE_initialize_console(NULL, kPEGraphicsMode);
+ }
+ drawLayer(s, src, dst);
+ if (layer == 0) {
+ record(s);
+ }
+ }
+ MiniIOSurfaceDrop(s);
+ }
+ fSwapsShown++;
+
+ /* every five seconds in which something was drawn: how many frames, and what each cost here */
+ fStatFrames++;
+ fStatDrawing += mach_absolute_time() - began;
+ if (fStatSince == 0) {
+ fStatSince = began;
+ }
+ absolutetime_to_nanoseconds(mach_absolute_time() - fStatSince, &nanos);
+ if (nanos >= 5 * NSEC_PER_SEC) {
+ uint64_t drawing;
+
+ absolutetime_to_nanoseconds(fStatDrawing, &drawing);
+ IOLog("MiniIOMobileFramebuffer: %u frames in %llu ms (%llu a second), %llu us each in the driver\n", fStatFrames,
+ nanos / NSEC_PER_MSEC, fStatFrames * NSEC_PER_SEC / nanos, drawing / fStatFrames / NSEC_PER_USEC);
+ fStatFrames = 0;
+ fStatDrawing = 0;
+ fStatSince = 0;
+ }
+ IOLockUnlock(fLock);
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+class IOMobileFramebufferUserClient : public IOUserClient
+{
+ OSDeclareDefaultStructors(IOMobileFramebufferUserClient);
+
+ task_t fTask;
+ IOMobileFramebuffer * fOwner;
+ IOLock * fLock;
+ mach_port_t fPorts[kFBNotifyTypes];
+ mach_vm_address_t fCallbacks[kFBNotifyTypes];
+ io_user_reference_t fRefcons[kFBNotifyTypes];
+ thread_call_t fVSyncCall;
+ uint64_t fVSyncCount;
+ bool fVSyncRunning;
+ bool fClosed;
+
+ static void vsyncFired(thread_call_param_t self, thread_call_param_t unused);
+ void vsync(void);
+ void armVSync(void);
+
+public:
+ virtual bool initWithTask(task_t owningTask, void * securityID, UInt32 type, OSDictionary * properties) APPLE_KEXT_OVERRIDE;
+ virtual bool start(IOService * provider) APPLE_KEXT_OVERRIDE;
+ virtual IOReturn clientClose(void) APPLE_KEXT_OVERRIDE;
+ virtual void free(void) APPLE_KEXT_OVERRIDE;
+ virtual IOReturn registerNotificationPort(mach_port_t port, UInt32 type, io_user_reference_t refCon) APPLE_KEXT_OVERRIDE;
+ virtual IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments * args,
+ IOExternalMethodDispatch * dispatch, OSObject * target, void * reference) APPLE_KEXT_OVERRIDE;
+};
+
+OSDefineMetaClassAndStructors(IOMobileFramebufferUserClient, IOUserClient);
+
+bool
+IOMobileFramebufferUserClient::initWithTask(task_t owningTask, void * securityID, UInt32 type, OSDictionary * properties)
+{
+ if (!IOUserClient::initWithTask(owningTask, securityID, type, properties)) {
+ return false;
+ }
+ fTask = owningTask;
+ return true;
+}
+
+bool
+IOMobileFramebufferUserClient::start(IOService * provider)
+{
+ fOwner = OSDynamicCast(IOMobileFramebuffer, provider);
+ if (fOwner == NULL || !IOUserClient::start(provider)) {
+ return false;
+ }
+ fLock = IOLockAlloc();
+ fVSyncCall = thread_call_allocate(&IOMobileFramebufferUserClient::vsyncFired, this);
+ return fLock != NULL && fVSyncCall != NULL;
+}
+
+IOReturn
+IOMobileFramebufferUserClient::clientClose(void)
+{
+ if (fLock != NULL) {
+ IOLockLock(fLock);
+ fClosed = true;
+ IOLockUnlock(fLock);
+ }
+ if (fVSyncCall != NULL) {
+ thread_call_cancel_wait(fVSyncCall);
+ }
+ if (!isInactive()) {
+ terminate();
+ }
+ return kIOReturnSuccess;
+}
+
+void
+IOMobileFramebufferUserClient::free(void)
+{
+ if (fVSyncCall != NULL) {
+ thread_call_cancel_wait(fVSyncCall);
+ thread_call_free(fVSyncCall);
+ fVSyncCall = NULL;
+ }
+ for (unsigned i = 0; i < kFBNotifyTypes; i++) {
+ if (fPorts[i] != NULL) {
+ releaseNotificationPort(fPorts[i]);
+ fPorts[i] = NULL;
+ }
+ }
+ if (fLock != NULL) {
+ IOLockFree(fLock);
+ fLock = NULL;
+ }
+ IOUserClient::free();
+}
+
+IOReturn
+IOMobileFramebufferUserClient::registerNotificationPort(mach_port_t port, UInt32 type, io_user_reference_t refCon)
+{
+ mach_port_t old;
+
+ IOLog("MiniIOMobileFramebuffer: notification port for type %u\n", (unsigned) type);
+ if (type >= kFBNotifyTypes) {
+ return kIOReturnBadArgument;
+ }
+ IOLockLock(fLock);
+ old = fPorts[type];
+ fPorts[type] = port;
+ IOLockUnlock(fLock);
+ if (old != NULL) {
+ releaseNotificationPort(old);
+ }
+ return kIOReturnSuccess;
+}
+
+void
+IOMobileFramebufferUserClient::vsyncFired(thread_call_param_t self, thread_call_param_t unused)
+{
+ ((IOMobileFramebufferUserClient *) self)->vsync();
+}
+
+/* With the lock held. */
+void
+IOMobileFramebufferUserClient::armVSync(void)
+{
+ uint64_t deadline;
+
+ clock_interval_to_deadline(1000000 / kFBRefreshHz, NSEC_PER_USEC, &deadline);
+ thread_call_enter_delayed(fVSyncCall, deadline);
+}
+
+/*
+ * One refresh: tell the client, which gets three 64-bit numbers as six 32-bit halves --
+ * the time of this refresh, the same again (the time it was presented), and a counter.
+ */
+void
+IOMobileFramebufferUserClient::vsync(void)
+{
+ OSAsyncReference64 ref;
+ io_user_reference_t args[6];
+ uint64_t now = mach_absolute_time();
+ bool send = false;
+
+ IOLockLock(fLock);
+ if (fClosed || fCallbacks[kFBNotifyVSync] == 0 || fPorts[kFBNotifyVSync] == NULL) {
+ fVSyncRunning = false;
+ } else {
+ fVSyncCount++;
+ setAsyncReference64(ref, fPorts[kFBNotifyVSync], fCallbacks[kFBNotifyVSync], fRefcons[kFBNotifyVSync], fTask);
+ args[0] = (uint32_t) now;
+ args[1] = now >> 32;
+ args[2] = (uint32_t) now;
+ args[3] = now >> 32;
+ args[4] = (uint32_t) fVSyncCount;
+ args[5] = fVSyncCount >> 32;
+ send = true;
+ armVSync();
+ }
+ IOLockUnlock(fLock);
+ if (send) {
+ sendAsyncResult64WithOptions(ref, kIOReturnSuccess, args, 6, kIOUserNotifyOptionCanDrop);
+ }
+}
+
+IOReturn
+IOMobileFramebufferUserClient::externalMethod(uint32_t selector, IOExternalMethodArguments * args,
+ IOExternalMethodDispatch * dispatch, OSObject * target, void * reference)
+{
+ const uint64_t * in = args->scalarInput;
+ uint64_t * out = args->scalarOutput;
+ MiniIOSurface * s;
+
+ if (selector < 128 && gFBCalls[selector] < gFBTrace) {
+ char procname[32] = "?";
+
+ gFBCalls[selector]++;
+ proc_selfname(procname, sizeof(procname));
+ IOLog("MiniIOMobileFramebuffer: %s[%d] selector %u (scalars %u in [0x%llx 0x%llx 0x%llx 0x%llx], %u out; "
+ "structure %u in, %u out)\n", procname, proc_selfpid(), selector, args->scalarInputCount,
+ args->scalarInputCount > 0 ? in[0] : 0, args->scalarInputCount > 1 ? in[1] : 0,
+ args->scalarInputCount > 2 ? in[2] : 0, args->scalarInputCount > 3 ? in[3] : 0, args->scalarOutputCount,
+ args->structureInputSize, args->structureOutputSize);
+ }
+
+ switch (selector) {
+ case kFBMethodGetDisplaySize: /* out: width, height */
+ if (args->scalarOutputCount < 2) {
+ return kIOReturnBadArgument;
+ }
+ out[0] = fOwner->fWidth;
+ out[1] = fOwner->fHeight;
+ args->scalarOutputCount = 2;
+ return kIOReturnSuccess;
+
+ case kFBMethodGetID:
+ if (args->scalarOutputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ out[0] = 1;
+ args->scalarOutputCount = 1;
+ return kIOReturnSuccess;
+
+ case kFBMethodGetDotPitch: /* out: pixels per inch */
+ if (args->scalarOutputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ out[0] = kFBDotsPerInch;
+ args->scalarOutputCount = 1;
+ return kIOReturnSuccess;
+
+ case kFBMethodGetLayerDefaultSurface: /* in: size wanted (or 0, 0); out: a send right for the surface */
+ if (args->scalarOutputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ s = fOwner->defaultSurface();
+ if (s == NULL) {
+ return kIOReturnNoMemory;
+ }
+ out[0] = MiniIOSurfaceMakeSendRight(fTask, s);
+ args->scalarOutputCount = 1;
+ return out[0] != 0 ? kIOReturnSuccess : kIOReturnNoMemory;
+
+ case kFBMethodSwapBegin: /* out: the number of the new swap */
+ if (args->scalarOutputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ out[0] = OSIncrementAtomic(&fOwner->fSwapID) + 1;
+ args->scalarOutputCount = 1;
+ return kIOReturnSuccess;
+
+ case kFBMethodSwapEnd:
+ if (args->structureInput == NULL || args->structureInputSize < SWAP_SIZE) {
+ IOLog("MiniIOMobileFramebuffer: swap request of %u bytes, expected %u\n", args->structureInputSize, SWAP_SIZE);
+ return kIOReturnBadArgument;
+ }
+ fOwner->present((const uint8_t *) args->structureInput);
+ return kIOReturnSuccess;
+
+ case kFBMethodSwapWait: /* a swap is on the screen as soon as it is made */
+ case kFBMethodSwapSignal:
+ case kFBMethodSwapCancel:
+ case kFBMethodSwapCancelAll:
+ case kFBMethodRequestPowerChange:
+ case kFBMethodChangeFrameInfo:
+ return kIOReturnSuccess;
+
+ case kFBMethodNotifications: /* in: callback (0 = off), its argument, type, 0 */
+ if (args->scalarInputCount < 3 || in[2] >= kFBNotifyTypes) {
+ return kIOReturnBadArgument;
+ }
+ IOLockLock(fLock);
+ fCallbacks[in[2]] = in[0];
+ fRefcons[in[2]] = in[1];
+ if (in[2] == kFBNotifyVSync && in[0] != 0 && !fVSyncRunning && !fClosed) {
+ fVSyncRunning = true;
+ armVSync();
+ }
+ IOLockUnlock(fLock);
+ return kIOReturnSuccess;
+
+ case kFBMethodSupportedFrameInfo: /* in: type; out: how many, and their tags: none */
+ if (args->scalarOutputCount >= 1) {
+ out[0] = 0;
+ args->scalarOutputCount = 1;
+ }
+ if (args->structureOutput != NULL) {
+ bzero(args->structureOutput, args->structureOutputSize);
+ }
+ return kIOReturnSuccess;
+
+ case kFBMethodGetBlock: /* in: which block; out: its bytes */
+ if (args->structureOutput == NULL) {
+ return kIOReturnBadArgument;
+ }
+ bzero(args->structureOutput, args->structureOutputSize);
+ if (args->scalarInputCount >= 1 && in[0] == 0x40 && args->structureOutputSize >= 12) {
+ /* the current mode: its colour and timing identifiers */
+ uint32_t ids[2] = { kFBColorID, kFBTimingID };
+
+ memcpy((uint8_t *) args->structureOutput + 4, ids, sizeof(ids));
+ }
+ return kIOReturnSuccess;
+
+ case kFBMethodGetCurrentAbsoluteTime:
+ if (args->scalarOutputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ out[0] = mach_absolute_time();
+ args->scalarOutputCount = 1;
+ return kIOReturnSuccess;
+
+ default:
+ break;
+ }
+
+ if (selector < 128 && !(gFBLogged[selector / 64] & (1ULL << (selector % 64)))) {
+ gFBLogged[selector / 64] |= 1ULL << (selector % 64);
+ IOLog("MiniIOMobileFramebuffer: selector %u not implemented (scalars %u in [0x%llx 0x%llx 0x%llx], %u out; "
+ "structure %u in, %u out)\n", selector, args->scalarInputCount, args->scalarInputCount > 0 ? in[0] : 0,
+ args->scalarInputCount > 1 ? in[1] : 0, args->scalarInputCount > 2 ? in[2] : 0, args->scalarOutputCount,
+ args->structureInputSize, args->structureOutputSize);
+ }
+ /* a request that only sets something is accepted; one that wants an answer gets zeros */
+ if (args->scalarOutputCount != 0) {
+ bzero(out, args->scalarOutputCount * sizeof(out[0]));
+ }
+ if (args->structureOutput != NULL && args->structureOutputSize != 0) {
+ bzero(args->structureOutput, args->structureOutputSize);
+ }
+ return kIOReturnSuccess;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+/*
+ * IOMobileFramebuffer.framework counts the displays it should wait for by looking for
+ * children of /arm-io in the device tree whose device_type is "display-subsystem".
+ */
+static void
+publishDisplayNode(void)
+{
+ IORegistryEntry * armio = IORegistryEntry::fromPath("/arm-io", gIODTPlane);
+ IORegistryEntry * node;
+ OSDictionary * props;
+ OSData * data;
+
+ if (armio == NULL) {
+ IOLog("MiniIOMobileFramebuffer: no /arm-io in the device tree\n");
+ return;
+ }
+ node = OSTypeAlloc(IORegistryEntry);
+ props = OSDictionary::withCapacity(4);
+ if (node != NULL && props != NULL) {
+ data = OSData::withBytes("display-subsystem", sizeof("display-subsystem"));
+ props->setObject("device_type", data);
+ OSSafeReleaseNULL(data);
+ data = OSData::withBytes("redwood,framebuffer", sizeof("redwood,framebuffer"));
+ props->setObject("compatible", data);
+ OSSafeReleaseNULL(data);
+ data = OSData::withBytes("disp0", sizeof("disp0"));
+ props->setObject("name", data);
+ OSSafeReleaseNULL(data);
+ if (node->init(props)) {
+ node->setName("disp0");
+ node->attachToParent(armio, gIODTPlane);
+ }
+ }
+ OSSafeReleaseNULL(props);
+ OSSafeReleaseNULL(node);
+ armio->release();
+}
+
+/*
+ * The graphics accelerator. There is none, but CoreAnimation waits half a minute for a
+ * service of this class to appear before it looks for a GPU at all (once per process). An
+ * accelerator without the properties that name its Metal and OpenGL ES drivers is passed
+ * over by both, which leaves CoreAnimation with its software renderer, as before.
+ */
+class IOAcceleratorES : public IOService
+{
+ OSDeclareDefaultStructors(IOAcceleratorES);
+};
+
+OSDefineMetaClassAndStructors(IOAcceleratorES, IOService);
+
+static void
+publishAccelerator(IOService * provider)
+{
+ IOAcceleratorES * accelerator = OSTypeAlloc(IOAcceleratorES);
+
+ if (accelerator != NULL && accelerator->init() && accelerator->attach(provider)) {
+ accelerator->setName("sgx");
+ accelerator->registerService();
+ }
+ OSSafeReleaseNULL(accelerator);
+}
+
+void
+MiniIOMobileFramebufferStart(IOService * provider)
+{
+ IOMobileFramebuffer * fb = OSTypeAlloc(IOMobileFramebuffer);
+
+ if (fb == NULL || !fb->init() || !fb->attach(provider)) {
+ OSSafeReleaseNULL(fb);
+ return;
+ }
+ if (fb->start(provider)) {
+ publishDisplayNode();
+ publishAccelerator(provider);
+ } else {
+ fb->detach(provider);
+ }
+ fb->release();
+}
diff --git a/xnu/files/iokit/Kernel/MiniIOSurface.cpp b/xnu/files/iokit/Kernel/MiniIOSurface.cpp
new file mode 100644
index 0000000..0899cdb
--- /dev/null
+++ b/xnu/files/iokit/Kernel/MiniIOSurface.cpp
@@ -0,0 +1,1422 @@
+/*
+ * MiniIOSurface: a stand-in for Apple's closed IOSurface.kext (see MiniIOSurface.h).
+ *
+ * A surface is a piece of wired kernel memory: one page of state that clients read directly,
+ * followed by the pixels. Every client that knows a surface has the whole of it mapped once.
+ * Surfaces travel between processes as Mach send rights (IOSurfaceSendRight) or by number.
+ *
+ * What is not here: child surfaces, wrapping of client memory, purgeability, compression,
+ * notifications. Calls that are not implemented are logged once and refused.
+ */
+
+#include <IOKit/IOLib.h>
+#include <IOKit/IOLocks.h>
+#include <IOKit/IOKitKeys.h>
+#include <IOKit/IOMemoryDescriptor.h>
+#include <libkern/c++/OSSerialize.h>
+#include <libkern/c++/OSUnserialize.h>
+#include <libkern/c++/OSDictionary.h>
+#include <libkern/c++/OSArray.h>
+#include <libkern/c++/OSNumber.h>
+#include <libkern/c++/OSBoolean.h>
+#include <libkern/c++/OSString.h>
+#include <libkern/c++/OSSymbol.h>
+#include <sys/systm.h>
+#include <sys/proc.h>
+
+#include "MiniIOSurface.h"
+
+static_assert(sizeof(struct minisurf_plane) == 0x80, "plane layout");
+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) */
+enum {
+ kSurfaceMethodCreate = 0,
+ kSurfaceMethodLookup = 4,
+ kSurfaceMethodSetYCbCrMatrix = 5,
+ kSurfaceMethodWrapClientImage = 6,
+ kSurfaceMethodWrapClientMemory = 7,
+ kSurfaceMethodSetValue = 9,
+ kSurfaceMethodCopyValue = 10,
+ kSurfaceMethodRemoveValue = 11,
+ kSurfaceMethodBindAccel = 12,
+ kSurfaceMethodInit = 13,
+ kSurfaceMethodLog = 19,
+ kSurfaceMethodSetPurgeable = 20,
+ kSurfaceMethodSetOwnership = 21,
+ kSurfaceMethodSetTiled = 22,
+ kSurfaceMethodSetTimestamp = 24,
+ kSurfaceMethodSetBulkAttachments = 27,
+ kSurfaceMethodCommPageAddress = 32,
+ kSurfaceMethodSetIndexedTimestamp = 33,
+ kSurfaceMethodLookupFromPort = 34,
+ kSurfaceMethodCreatePort = 35,
+ kSurfaceMethodDetachModeCode = 43,
+ kSurfaceMethodSetOwnershipIdentity = 44,
+};
+
+/* IOConnectTrap indices */
+enum {
+ kSurfaceTrapIncrementUseCount = 0,
+ kSurfaceTrapDecrementUseCount = 1,
+ kSurfaceTrapLock = 2,
+ kSurfaceTrapUnlock = 3,
+ kSurfaceTrapDetach = 4, /* the client is about to release: forget it has the surface */
+ kSurfaceTrapRelease = 5,
+ kSurfaceTrapCount
+};
+
+#define kSurfaceLockReadOnly 1u
+
+#define MINISURF_TABLE_SIZE 16384
+#define MINISURF_MAX_DIMENSION 16384
+#define MINISURF_MAX_ALLOC (512u << 20)
+#define MINISURF_ROW_ALIGN 64
+
+#define FOURCC(a, b, c, d) ((uint32_t)(a) << 24 | (uint32_t)(b) << 16 | (uint32_t)(c) << 8 | (uint32_t)(d))
+
+static IOLock * gSurfaceLock;
+static MiniIOSurface * gSurfaceTable[MINISURF_TABLE_SIZE]; /* index = surface number; [0] unused */
+static uint32_t gSurfaceNext = 1;
+static uint32_t gSurfaceCount;
+static uint64_t gSurfaceBytes;
+static uint64_t gSurfaceLogged[2]; /* selectors already complained about */
+/* Boot-arg surftrace=N: log the first N surfaces created (default 24). */
+static TUNABLE(uint32_t, gSurfaceTrace, "surftrace", 24);
+static uint32_t gSurfaceTraced; /* (a tunable is read-only after boot) */
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+OSDefineMetaClassAndStructors(MiniIOSurface, OSObject);
+
+void
+MiniIOSurface::free(void)
+{
+ OSSafeReleaseNULL(values);
+ OSSafeReleaseNULL(memory);
+ OSObject::free();
+}
+
+/* The values changed: a new seed, and how much room a client needs to fetch them. */
+void
+MiniIOSurface::updateValuesState(void)
+{
+ struct minisurf_shared * sh = shared();
+ uint32_t size = 0;
+
+ if (values != NULL && values->getCount() != 0) {
+ OSSerialize * s = OSSerialize::binaryWithCapacity(4096);
+ if (s != NULL) {
+ if (values->serialize(s)) {
+ size = s->getLength() + 8;
+ }
+ s->release();
+ }
+ }
+ sh->valuesSeed = (sh->valuesSeed + 2) | 1;
+ sh->valuesSize = size;
+}
+
+static uint32_t
+dictNumber(OSDictionary * dict, const char * key, uint32_t missing)
+{
+ OSObject * obj = dict ? dict->getObject(key) : NULL;
+ OSNumber * num = OSDynamicCast(OSNumber, obj);
+
+ if (num != NULL) {
+ return num->unsigned32BitValue();
+ }
+ if (obj == kOSBooleanTrue) {
+ return 1;
+ }
+ if (obj == kOSBooleanFalse) {
+ return 0;
+ }
+ return missing;
+}
+
+static uint32_t
+alignUp(uint64_t value, uint32_t to)
+{
+ return (uint32_t) ((value + to - 1) / to * to);
+}
+
+/* Bytes per element when the client did not say. */
+static uint32_t
+defaultBytesPerElement(uint32_t format)
+{
+ switch (format) {
+ case FOURCC('L', '0', '0', '8'):
+ case FOURCC('A', '0', '0', '8'):
+ case 0x00000008:
+ return 1;
+ case FOURCC('L', '5', '6', '5'):
+ case FOURCC('B', '5', '6', '5'):
+ case FOURCC('L', '5', '5', '5'):
+ case FOURCC('2', 'v', 'u', 'y'):
+ case FOURCC('y', 'u', 'v', 's'):
+ case FOURCC('y', 'u', 'v', 'f'):
+ case FOURCC('L', '0', '1', '6'):
+ case FOURCC('L', '0', '0', 'h'):
+ return 2;
+ case FOURCC('R', 'G', 'h', 'A'):
+ return 8;
+ case FOURCC('R', 'G', 'f', 'A'):
+ return 16;
+ default:
+ return 4;
+ }
+}
+
+/*
+ * Two-plane YCbCr formats: luma, then interleaved chroma.
+ * Returns false for anything else. *wide: 10-bit samples in 16 bits.
+ */
+static bool
+biplanarLayout(uint32_t format, uint32_t * hsub, uint32_t * vsub, bool * wide)
+{
+ switch (format) {
+ case FOURCC('4', '2', '0', 'v'): case FOURCC('4', '2', '0', 'f'):
+ *hsub = 2; *vsub = 2; *wide = false; return true;
+ case FOURCC('4', '2', '2', 'v'): case FOURCC('4', '2', '2', 'f'):
+ *hsub = 2; *vsub = 1; *wide = false; return true;
+ case FOURCC('4', '4', '4', 'v'): case FOURCC('4', '4', '4', 'f'):
+ *hsub = 1; *vsub = 1; *wide = false; return true;
+ case FOURCC('x', '4', '2', '0'): case FOURCC('x', 'f', '2', '0'):
+ *hsub = 2; *vsub = 2; *wide = true; return true;
+ case FOURCC('x', '4', '2', '2'): case FOURCC('x', 'f', '2', '2'):
+ *hsub = 2; *vsub = 1; *wide = true; return true;
+ case FOURCC('x', '4', '4', '4'): case FOURCC('x', 'f', '4', '4'):
+ *hsub = 1; *vsub = 1; *wide = true; return true;
+ default:
+ return false;
+ }
+}
+
+static void
+describeComponents(struct minisurf_plane * plane, uint32_t format)
+{
+ /* in memory order; names: 1 alpha, 2 red, 3 green, 4 blue */
+ static const uint8_t bgra[4] = { 4, 3, 2, 1 };
+ static const uint8_t rgba[4] = { 2, 3, 4, 1 };
+ const uint8_t * names;
+
+ if (format == FOURCC('B', 'G', 'R', 'A')) {
+ names = bgra;
+ } else if (format == FOURCC('R', 'G', 'B', 'A')) {
+ names = rgba;
+ } else {
+ return;
+ }
+ plane->componentCount = 4;
+ for (unsigned i = 0; i < 4; i++) {
+ plane->componentBitDepth[i] = 8;
+ plane->componentBitOffset[i] = (uint8_t) (8 * i);
+ plane->componentName[i] = names[i];
+ plane->componentType[i] = 1; /* unsigned integer */
+ plane->componentRange[i] = 1; /* full range */
+ }
+}
+
+/*
+ * Make a surface from the properties a client gave to IOSurfaceCreate().
+ * Returned with one holder, and entered in the table.
+ */
+static MiniIOSurface *
+surfaceCreate(OSDictionary * props, IOReturn * error)
+{
+ MiniIOSurface * s;
+ struct minisurf_result * info;
+ uint32_t width, height, format, bpe, ew, eh, bpr, alloc, offset, planeCount = 0;
+ uint32_t hsub, vsub;
+ bool wide;
+ OSArray * planeInfo;
+ uint64_t needed;
+
+ *error = kIOReturnBadArgument;
+ width = dictNumber(props, "IOSurfaceWidth", 0);
+ height = dictNumber(props, "IOSurfaceHeight", 0);
+ format = dictNumber(props, "IOSurfacePixelFormat", 0);
+ /*
+ * Ten bits a colour, packed into 32-bit pixels: what a device with a wide-gamut display
+ * (the iPhone X is one) asks for when it wants a picture of the screen, a snapshot for a
+ * transition for instance. CoreAnimation's software renderer does not draw into those
+ * ("SW renderer invalid destination format w30r": the transition comes out black), and
+ * there is no wide gamut on this panel anyway. The surface is made as ordinary BGRA of
+ * the same geometry, and says so: whoever uses it reads the format back from the surface.
+ */
+ if (format == 'w30r' || format == 'l10r' || format == 'w30R') {
+ format = 'BGRA';
+ }
+ ew = dictNumber(props, "IOSurfaceElementWidth", 1);
+ eh = dictNumber(props, "IOSurfaceElementHeight", 1);
+ bpe = dictNumber(props, "IOSurfaceBytesPerElement", 0);
+ offset = dictNumber(props, "IOSurfaceOffset", 0);
+ if (width > MINISURF_MAX_DIMENSION || height > MINISURF_MAX_DIMENSION || ew == 0 || eh == 0 || ew > 255 || eh > 255) {
+ return NULL;
+ }
+ if (props->getObject("IOSurfaceAddress") != NULL || props->getObject("IOSurfaceAddressRanges") != NULL) {
+ IOLog("MiniIOSurface: wrapping client memory is not supported\n");
+ *error = kIOReturnUnsupported;
+ return NULL;
+ }
+
+ s = OSTypeAlloc(MiniIOSurface);
+ if (s == NULL || !s->init()) {
+ OSSafeReleaseNULL(s);
+ *error = kIOReturnNoMemory;
+ return NULL;
+ }
+ info = &s->info;
+
+ planeInfo = OSDynamicCast(OSArray, props->getObject("IOSurfacePlaneInfo"));
+ needed = 0;
+ if (planeInfo != NULL && planeInfo->getCount() != 0) {
+ planeCount = planeInfo->getCount();
+ if (planeCount > MINISURF_MAX_PLANES) {
+ IOLog("MiniIOSurface: %u planes asked for, %u supported\n", planeCount, MINISURF_MAX_PLANES);
+ s->release();
+ return NULL;
+ }
+ for (uint32_t i = 0; i < planeCount; i++) {
+ OSDictionary * pd = OSDynamicCast(OSDictionary, planeInfo->getObject(i));
+ struct minisurf_plane * p = &s->planes[i];
+ uint32_t pew = dictNumber(pd, "IOSurfacePlaneElementWidth", 1);
+ uint32_t peh = dictNumber(pd, "IOSurfacePlaneElementHeight", 1);
+
+ if (pew == 0 || peh == 0 || pew > 255 || peh > 255) {
+ s->release();
+ return NULL;
+ }
+ p->width = dictNumber(pd, "IOSurfacePlaneWidth", width);
+ p->height = dictNumber(pd, "IOSurfacePlaneHeight", height);
+ p->bytesPerElement = (uint16_t) dictNumber(pd, "IOSurfacePlaneBytesPerElement", bpe ? bpe : 1);
+ p->elementWidth = (uint8_t) pew;
+ p->elementHeight = (uint8_t) peh;
+ p->bytesPerRow = dictNumber(pd, "IOSurfacePlaneBytesPerRow", 0);
+ if (p->bytesPerRow == 0) {
+ p->bytesPerRow = alignUp((uint64_t) ((p->width + pew - 1) / pew) * p->bytesPerElement, MINISURF_ROW_ALIGN);
+ }
+ p->size = dictNumber(pd, "IOSurfacePlaneSize", 0);
+ if (p->size == 0) {
+ p->size = p->bytesPerRow * ((p->height + peh - 1) / peh);
+ }
+ p->offset = dictNumber(pd, "IOSurfacePlaneOffset", dictNumber(pd, "IOSurfacePlaneBase", (uint32_t) needed));
+ p->extendedPixels[0] = dictNumber(pd, "IOSurfacePlaneExtendedPixelsOnLeft", 0);
+ p->extendedPixels[1] = dictNumber(pd, "IOSurfacePlaneExtendedPixelsOnRight", 0);
+ p->extendedPixels[2] = dictNumber(pd, "IOSurfacePlaneExtendedPixelsOnTop", 0);
+ p->extendedPixels[3] = dictNumber(pd, "IOSurfacePlaneExtendedPixelsOnBottom", 0);
+ if ((uint64_t) p->offset + p->size > needed) {
+ needed = (uint64_t) p->offset + p->size;
+ }
+ }
+ } else if (biplanarLayout(format, &hsub, &vsub, &wide) && width != 0 && height != 0) {
+ struct minisurf_plane * y = &s->planes[0], * c = &s->planes[1];
+
+ planeCount = 2;
+ y->width = width;
+ y->height = height;
+ y->bytesPerElement = wide ? 2 : 1;
+ y->elementWidth = y->elementHeight = 1;
+ y->bytesPerRow = alignUp((uint64_t) width * y->bytesPerElement, MINISURF_ROW_ALIGN);
+ y->size = y->bytesPerRow * height;
+ y->offset = 0;
+ c->width = (width + hsub - 1) / hsub;
+ c->height = (height + vsub - 1) / vsub;
+ c->bytesPerElement = wide ? 4 : 2;
+ c->elementWidth = c->elementHeight = 1;
+ c->bytesPerRow = alignUp((uint64_t) c->width * c->bytesPerElement, MINISURF_ROW_ALIGN);
+ c->size = c->bytesPerRow * c->height;
+ c->offset = y->size;
+ needed = (uint64_t) c->offset + c->size;
+ }
+
+ if (bpe == 0) {
+ bpe = planeCount ? s->planes[0].bytesPerElement : defaultBytesPerElement(format);
+ }
+ bpr = dictNumber(props, "IOSurfaceBytesPerRow", 0);
+ if (bpr == 0) {
+ bpr = planeCount ? s->planes[0].bytesPerRow
+ : alignUp((uint64_t) ((width + ew - 1) / ew) * bpe, MINISURF_ROW_ALIGN);
+ }
+ if (planeCount == 0) {
+ needed = (uint64_t) bpr * ((height + eh - 1) / eh);
+ /* the one implicit plane, for the per-plane getters */
+ s->planes[0].width = width;
+ s->planes[0].height = height;
+ s->planes[0].bytesPerRow = bpr;
+ s->planes[0].bytesPerElement = (uint16_t) bpe;
+ s->planes[0].elementWidth = (uint8_t) ew;
+ s->planes[0].elementHeight = (uint8_t) eh;
+ s->planes[0].size = (uint32_t) needed;
+ describeComponents(&s->planes[0], format);
+ }
+ needed += offset;
+ alloc = dictNumber(props, "IOSurfaceAllocSize", 0);
+ if (alloc < needed) {
+ if (alloc != 0) {
+ IOLog("MiniIOSurface: alloc size %u too small for %ux%u '%.4s', using %llu\n", alloc, width, height,
+ (const char *) &format, needed);
+ }
+ if (needed > MINISURF_MAX_ALLOC) {
+ s->release();
+ return NULL;
+ }
+ alloc = (uint32_t) needed;
+ }
+ if (alloc == 0 || alloc > MINISURF_MAX_ALLOC) {
+ s->release();
+ return NULL;
+ }
+ alloc = alignUp(alloc, (uint32_t) PAGE_SIZE);
+
+ s->memory = IOBufferMemoryDescriptor::inTaskWithOptions(kernel_task,
+ kIODirectionInOut | kIOMemoryKernelUserShared, (vm_size_t) PAGE_SIZE + alloc, PAGE_SIZE);
+ if (s->memory == NULL) {
+ IOLog("MiniIOSurface: no memory for %u bytes (%u surfaces, %llu MB in use)\n", alloc, gSurfaceCount,
+ gSurfaceBytes >> 20);
+ s->release();
+ *error = kIOReturnNoMemory;
+ return NULL;
+ }
+ s->kbase = (uint8_t *) s->memory->getBytesNoCopy();
+ s->values = OSDictionary::withCapacity(4);
+
+ info->allocSize = alloc;
+ info->width = width;
+ info->height = height;
+ info->bytesPerRow = bpr;
+ info->offset = offset;
+ info->pixelFormat = format;
+ info->planeCount = planeCount;
+ info->bytesPerElement = (uint16_t) bpe;
+ info->elementWidth = (uint8_t) ew;
+ info->elementHeight = (uint8_t) eh;
+ info->cacheMode = dictNumber(props, "IOSurfaceCacheMode", 0);
+ info->subsampling = (uint8_t) dictNumber(props, "IOSurfaceSubsampling", 0);
+ info->prohibitUseCount = (uint8_t) dictNumber(props, "IOSurfaceProhibitUseCount", 0);
+ info->sliceCount = dictNumber(props, "IOSurfaceSliceCount", 0);
+ info->protectionOptions = dictNumber(props, "IOSurfaceProtectionOptions", 0);
+
+ IOLockLock(gSurfaceLock);
+ uint32_t sid = 0;
+ for (uint32_t tries = 0; tries < MINISURF_TABLE_SIZE - 1; tries++) {
+ uint32_t candidate = gSurfaceNext;
+
+ gSurfaceNext = (gSurfaceNext + 1 < MINISURF_TABLE_SIZE) ? gSurfaceNext + 1 : 1;
+ if (gSurfaceTable[candidate] == NULL) {
+ sid = candidate;
+ break;
+ }
+ }
+ if (sid == 0) {
+ IOLockUnlock(gSurfaceLock);
+ IOLog("MiniIOSurface: the surface table is full\n");
+ s->release();
+ *error = kIOReturnNoResources;
+ return NULL;
+ }
+ s->sid = sid;
+ s->holders = 1;
+ info->sid = sid;
+ info->traceID = sid;
+ gSurfaceTable[sid] = s; /* the table owns the object until the last holder goes */
+ gSurfaceCount++;
+ gSurfaceBytes += alloc;
+
+ struct minisurf_shared * sh = s->shared();
+ sh->registryID = 0x100000000ULL + sid;
+ sh->seed = 1;
+ sh->valuesSeed = 1;
+ sh->pixelSizeCasting = (uint8_t) dictNumber(props, "IOSurfacePixelSizeCastingAllowed", 1);
+ sh->displayable = 1;
+ sh->sysMemOnly = (uint8_t) dictNumber(props, "IOSurfaceSysMemOnly", 0);
+ IOLockUnlock(gSurfaceLock);
+
+ *error = kIOReturnSuccess;
+ return s;
+}
+
+/* With the lock held. */
+static void
+surfaceHold(MiniIOSurface * s)
+{
+ s->holders++;
+}
+
+/* With the lock held. The caller must not touch the surface afterwards. */
+static void
+surfaceUnhold(MiniIOSurface * s)
+{
+ if (--s->holders != 0) {
+ return;
+ }
+ gSurfaceTable[s->sid] = NULL;
+ gSurfaceCount--;
+ gSurfaceBytes -= s->info.allocSize;
+ s->release();
+}
+
+MiniIOSurface *
+MiniIOSurfaceCopy(uint32_t sid)
+{
+ MiniIOSurface * s = NULL;
+
+ if (gSurfaceLock == NULL || sid == 0 || sid >= MINISURF_TABLE_SIZE) {
+ return NULL;
+ }
+ IOLockLock(gSurfaceLock);
+ s = gSurfaceTable[sid];
+ if (s != NULL) {
+ surfaceHold(s);
+ }
+ IOLockUnlock(gSurfaceLock);
+ return s;
+}
+
+void
+MiniIOSurfaceDrop(MiniIOSurface * s)
+{
+ if (s == NULL) {
+ return;
+ }
+ IOLockLock(gSurfaceLock);
+ surfaceUnhold(s);
+ IOLockUnlock(gSurfaceLock);
+}
+
+MiniIOSurface *
+MiniIOSurfaceCreateSimple(uint32_t width, uint32_t height, uint32_t pixelFormat)
+{
+ OSDictionary * props = OSDictionary::withCapacity(4);
+ MiniIOSurface * s = NULL;
+ IOReturn error;
+
+ if (props == NULL || gSurfaceLock == NULL) {
+ OSSafeReleaseNULL(props);
+ return NULL;
+ }
+ OSNumber * n;
+ n = OSNumber::withNumber(width, 32); props->setObject("IOSurfaceWidth", n); n->release();
+ n = OSNumber::withNumber(height, 32); props->setObject("IOSurfaceHeight", n); n->release();
+ n = OSNumber::withNumber(pixelFormat, 32); props->setObject("IOSurfacePixelFormat", n); n->release();
+ s = surfaceCreate(props, &error);
+ props->release();
+ return s;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+/* What a Mach send right for a surface points at. Holds the surface while any right exists. */
+class IOSurfaceSendRight : public OSObject
+{
+ OSDeclareDefaultStructors(IOSurfaceSendRight);
+
+public:
+ MiniIOSurface * surface;
+
+ virtual bool
+ init(void) APPLE_KEXT_OVERRIDE
+ {
+ return OSObject::init();
+ }
+ virtual void free(void) APPLE_KEXT_OVERRIDE;
+};
+
+OSDefineMetaClassAndStructors(IOSurfaceSendRight, OSObject);
+
+void
+IOSurfaceSendRight::free(void)
+{
+ MiniIOSurfaceDrop(surface);
+ surface = NULL;
+ OSObject::free();
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+class IOCoreSurfaceRoot : public IOService
+{
+ OSDeclareDefaultStructors(IOCoreSurfaceRoot);
+
+public:
+ virtual bool start(IOService * provider) APPLE_KEXT_OVERRIDE;
+};
+
+OSDefineMetaClassAndStructors(IOCoreSurfaceRoot, IOService);
+
+bool
+IOCoreSurfaceRoot::start(IOService * provider)
+{
+ if (!IOService::start(provider)) {
+ return false;
+ }
+ setProperty(kIOUserClientClassKey, "IOSurfaceRootUserClient");
+ setName("IOCoreSurfaceRoot");
+ registerService();
+ return true;
+}
+
+void
+MiniIOSurfaceStart(IOService * provider)
+{
+ IOCoreSurfaceRoot * root;
+
+ gSurfaceLock = IOLockAlloc();
+ root = OSTypeAlloc(IOCoreSurfaceRoot);
+ if (root == NULL || !root->init() || !root->attach(provider)) {
+ OSSafeReleaseNULL(root);
+ IOLog("MiniIOSurface: cannot create the root service\n");
+ return;
+ }
+ if (!root->start(provider)) {
+ root->detach(provider);
+ IOLog("MiniIOSurface: the root service did not start\n");
+ }
+ root->release();
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+/* One surface as one client has it. */
+struct minisurf_client_ref {
+ MiniIOSurface * surface; /* held */
+ IOMemoryMap * map; /* the whole of it in the client's address space */
+ uint32_t use[2]; /* what this client added to the use counts */
+ bool detached; /* the client let go of it and will release shortly */
+};
+
+class IOSurfaceRootUserClient : public IOUserClient
+{
+ OSDeclareDefaultStructors(IOSurfaceRootUserClient);
+
+ task_t fTask;
+ struct minisurf_client_ref * fRefs;
+ uint32_t fRefCount;
+ uint32_t fRefCapacity;
+ IOExternalTrap fTraps[kSurfaceTrapCount];
+
+ struct minisurf_client_ref * findRef(uint32_t sid, bool detached);
+ struct minisurf_client_ref * addRef(MiniIOSurface * surface);
+ void dropRef(struct minisurf_client_ref * ref);
+ IOReturn returnSurface(struct minisurf_client_ref * ref, bool known, IOExternalMethodArguments * args);
+
+ IOReturn methodInit(IOExternalMethodArguments * args);
+ IOReturn methodCreate(IOExternalMethodArguments * args);
+ IOReturn methodLookup(IOExternalMethodArguments * args);
+ IOReturn methodLookupFromPort(IOExternalMethodArguments * args);
+ IOReturn methodCreatePort(IOExternalMethodArguments * args);
+ IOReturn methodSetValue(IOExternalMethodArguments * args, const uint8_t * in, size_t inSize);
+ IOReturn methodCopyValue(IOExternalMethodArguments * args, const uint8_t * in, size_t inSize);
+ IOReturn methodRemoveValue(IOExternalMethodArguments * args, const uint8_t * in, size_t inSize);
+ IOReturn methodSetBulkAttachments(const uint8_t * in, size_t inSize);
+
+ IOReturn trapIncrementUseCount(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6);
+ IOReturn trapDecrementUseCount(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6);
+ IOReturn trapLock(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6);
+ IOReturn trapUnlock(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6);
+ IOReturn trapDetach(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6);
+ IOReturn trapRelease(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6);
+ IOReturn lockCommon(uint32_t sid, uint32_t options, user_addr_t seedOut);
+ IOReturn useCountCommon(uint32_t sid, uint32_t category, int delta);
+
+public:
+ virtual bool initWithTask(task_t owningTask, void * securityID, UInt32 type, OSDictionary * properties) APPLE_KEXT_OVERRIDE;
+ virtual bool start(IOService * provider) APPLE_KEXT_OVERRIDE;
+ virtual IOReturn clientClose(void) APPLE_KEXT_OVERRIDE;
+ virtual void free(void) APPLE_KEXT_OVERRIDE;
+ virtual IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments * args,
+ IOExternalMethodDispatch * dispatch, OSObject * target, void * reference) APPLE_KEXT_OVERRIDE;
+ virtual IOExternalTrap * getTargetAndTrapForIndex(IOService ** targetP, UInt32 index) APPLE_KEXT_OVERRIDE;
+ static mach_port_name_t makeSendRight(task_t task, MiniIOSurface * surface);
+};
+
+OSDefineMetaClassAndStructors(IOSurfaceRootUserClient, IOUserClient);
+
+bool
+IOSurfaceRootUserClient::initWithTask(task_t owningTask, void * securityID, UInt32 type, OSDictionary * properties)
+{
+ if (!IOUserClient::initWithTask(owningTask, securityID, type, properties)) {
+ return false;
+ }
+ fTask = owningTask;
+ return true;
+}
+
+bool
+IOSurfaceRootUserClient::start(IOService * provider)
+{
+ if (!IOUserClient::start(provider)) {
+ return false;
+ }
+ fTraps[kSurfaceTrapIncrementUseCount].func = (IOTrap) & IOSurfaceRootUserClient::trapIncrementUseCount;
+ fTraps[kSurfaceTrapDecrementUseCount].func = (IOTrap) & IOSurfaceRootUserClient::trapDecrementUseCount;
+ fTraps[kSurfaceTrapLock].func = (IOTrap) & IOSurfaceRootUserClient::trapLock;
+ fTraps[kSurfaceTrapUnlock].func = (IOTrap) & IOSurfaceRootUserClient::trapUnlock;
+ fTraps[kSurfaceTrapDetach].func = (IOTrap) & IOSurfaceRootUserClient::trapDetach;
+ fTraps[kSurfaceTrapRelease].func = (IOTrap) & IOSurfaceRootUserClient::trapRelease;
+ for (unsigned i = 0; i < kSurfaceTrapCount; i++) {
+ fTraps[i].object = this;
+ }
+ return true;
+}
+
+IOReturn
+IOSurfaceRootUserClient::clientClose(void)
+{
+ IOLockLock(gSurfaceLock);
+ while (fRefCount != 0) {
+ dropRef(&fRefs[fRefCount - 1]);
+ }
+ IOLockUnlock(gSurfaceLock);
+ if (!isInactive()) {
+ terminate();
+ }
+ return kIOReturnSuccess;
+}
+
+void
+IOSurfaceRootUserClient::free(void)
+{
+ if (fRefs != NULL) {
+ if (gSurfaceLock != NULL) {
+ IOLockLock(gSurfaceLock);
+ while (fRefCount != 0) {
+ dropRef(&fRefs[fRefCount - 1]);
+ }
+ IOLockUnlock(gSurfaceLock);
+ }
+ IODelete(fRefs, struct minisurf_client_ref, fRefCapacity);
+ fRefs = NULL;
+ }
+ IOUserClient::free();
+}
+
+/* All three with the lock held. */
+struct minisurf_client_ref *
+IOSurfaceRootUserClient::findRef(uint32_t sid, bool detached)
+{
+ for (uint32_t i = 0; i < fRefCount; i++) {
+ if (fRefs[i].surface->sid == sid && fRefs[i].detached == detached) {
+ return &fRefs[i];
+ }
+ }
+ return NULL;
+}
+
+struct minisurf_client_ref *
+IOSurfaceRootUserClient::addRef(MiniIOSurface * surface)
+{
+ struct minisurf_client_ref * ref;
+ IOMemoryMap * map;
+
+ if (fRefCount == fRefCapacity) {
+ uint32_t capacity = fRefCapacity ? fRefCapacity * 2 : 16;
+ struct minisurf_client_ref * refs = IONew(struct minisurf_client_ref, capacity);
+
+ if (refs == NULL) {
+ return NULL;
+ }
+ if (fRefs != NULL) {
+ memcpy(refs, fRefs, fRefCount * sizeof(*refs));
+ IODelete(fRefs, struct minisurf_client_ref, fRefCapacity);
+ }
+ fRefs = refs;
+ fRefCapacity = capacity;
+ }
+ map = surface->memory->createMappingInTask(fTask, 0, kIOMapAnywhere);
+ if (map == NULL) {
+ IOLog("MiniIOSurface: cannot map surface %u (%u bytes) into the client\n", surface->sid, surface->info.allocSize);
+ return NULL;
+ }
+ ref = &fRefs[fRefCount++];
+ bzero(ref, sizeof(*ref));
+ ref->surface = surface;
+ ref->map = map;
+ surfaceHold(surface);
+ return ref;
+}
+
+void
+IOSurfaceRootUserClient::dropRef(struct minisurf_client_ref * ref)
+{
+ MiniIOSurface * s = ref->surface;
+
+ for (unsigned c = 0; c < 2; c++) {
+ s->useCount[c] -= ref->use[c];
+ }
+ s->shared()->useCount = (uint64_t) s->useCount[1] << 32 | s->useCount[0];
+ OSSafeReleaseNULL(ref->map);
+ *ref = fRefs[--fRefCount];
+ surfaceUnhold(s);
+}
+
+static uint32_t
+resultSize(const MiniIOSurface * s)
+{
+ uint32_t planes = s->info.planeCount ? s->info.planeCount : 1;
+
+ return (uint32_t) (sizeof(struct minisurf_result) + planes * sizeof(struct minisurf_plane));
+}
+
+/* Describe the surface to the client. known: it has the surface already, do not build a second view. */
+IOReturn
+IOSurfaceRootUserClient::returnSurface(struct minisurf_client_ref * ref, bool known, IOExternalMethodArguments * args)
+{
+ MiniIOSurface * s = ref->surface;
+ uint32_t size = resultSize(s);
+ struct minisurf_result * r = (struct minisurf_result *) args->structureOutput;
+ mach_vm_address_t address = ref->map->getAddress();
+
+ if (r == NULL || args->structureOutputSize < size) {
+ return kIOReturnBadArgument;
+ }
+ *r = s->info;
+ memcpy(r + 1, s->planes, size - sizeof(*r));
+ r->shared = address;
+ r->aux = address + MINISURF_AUX_OFFSET;
+ r->base = known ? ~0ULL : address + PAGE_SIZE;
+ args->structureOutputSize = size;
+ return kIOReturnSuccess;
+}
+
+IOReturn
+IOSurfaceRootUserClient::methodInit(IOExternalMethodArguments * args)
+{
+ struct {
+ uint32_t allocAlignMask;
+ uint32_t rowAlignMask;
+ uint32_t maxBytesPerRow;
+ uint32_t maxWidth;
+ uint32_t maxHeight;
+ uint16_t reserved;
+ uint16_t version;
+ } reply;
+
+ static_assert(sizeof(reply) == 0x18, "init reply");
+ if (args->structureOutput == NULL || args->structureOutputSize < sizeof(reply)) {
+ return kIOReturnBadArgument;
+ }
+ reply.allocAlignMask = (uint32_t) PAGE_MASK;
+ reply.rowAlignMask = MINISURF_ROW_ALIGN - 1;
+ reply.maxBytesPerRow = MINISURF_MAX_DIMENSION * 16;
+ reply.maxWidth = MINISURF_MAX_DIMENSION;
+ reply.maxHeight = MINISURF_MAX_DIMENSION;
+ reply.reserved = 0;
+ reply.version = 1;
+ memcpy(args->structureOutput, &reply, sizeof(reply));
+ args->structureOutputSize = sizeof(reply);
+ return kIOReturnSuccess;
+}
+
+/* The serialized object in a request, or NULL. */
+static OSObject *
+unserialize(const uint8_t * data, size_t size)
+{
+ if (data == NULL || size < 4) {
+ return NULL;
+ }
+ return OSUnserializeXML((const char *) data, size, NULL);
+}
+
+IOReturn
+IOSurfaceRootUserClient::methodCreate(IOExternalMethodArguments * args)
+{
+ IOReturn ret;
+ IOMemoryMap * inMap = NULL;
+ const uint8_t * in = (const uint8_t *) args->structureInput;
+ size_t inSize = args->structureInputSize;
+ OSObject * obj;
+ OSDictionary * props;
+ MiniIOSurface * s;
+ struct minisurf_client_ref * ref;
+
+ if (args->scalarInputCount >= 1 && args->scalarInput[0] != 0) {
+ IOLog("MiniIOSurface: child surfaces are not supported (parent %llu)\n", args->scalarInput[0]);
+ return kIOReturnUnsupported;
+ }
+ if (args->structureInputDescriptor != NULL) {
+ inMap = args->structureInputDescriptor->map(kIOMapReadOnly);
+ if (inMap == NULL) {
+ return kIOReturnNoMemory;
+ }
+ in = (const uint8_t *) inMap->getVirtualAddress();
+ inSize = inMap->getLength();
+ }
+ obj = unserialize(in, inSize);
+ OSSafeReleaseNULL(inMap);
+ props = OSDynamicCast(OSDictionary, obj);
+ if (props == NULL) {
+ OSSafeReleaseNULL(obj);
+ return kIOReturnBadArgument;
+ }
+ s = surfaceCreate(props, &ret);
+ if (s == NULL) {
+ IOLog("MiniIOSurface: create failed 0x%x: %ux%u format 0x%x alloc %u\n", ret,
+ dictNumber(props, "IOSurfaceWidth", 0), dictNumber(props, "IOSurfaceHeight", 0),
+ dictNumber(props, "IOSurfacePixelFormat", 0), dictNumber(props, "IOSurfaceAllocSize", 0));
+ props->release();
+ return ret;
+ }
+ props->release();
+ if (gSurfaceTraced < gSurfaceTrace) {
+ char procname[32] = "?";
+
+ gSurfaceTraced++;
+ proc_selfname(procname, sizeof(procname));
+ IOLog("MiniIOSurface: %s[%d] created surface %u: %ux%u '%c%c%c%c', %u bytes per row, %u planes, %u bytes\n",
+ procname, proc_selfpid(), s->sid, s->info.width, s->info.height, (int) (s->info.pixelFormat >> 24 & 0xff),
+ (int) (s->info.pixelFormat >> 16 & 0xff), (int) (s->info.pixelFormat >> 8 & 0xff),
+ (int) (s->info.pixelFormat & 0xff), s->info.bytesPerRow, s->info.planeCount, s->info.allocSize);
+ }
+
+ IOLockLock(gSurfaceLock);
+ ref = addRef(s);
+ ret = ref ? returnSurface(ref, false, args) : kIOReturnNoMemory;
+ if (ref != NULL && ret != kIOReturnSuccess) {
+ dropRef(ref);
+ }
+ surfaceUnhold(s); /* the creator's hold; the client's own is in the ref */
+ IOLockUnlock(gSurfaceLock);
+ return ret;
+}
+
+IOReturn
+IOSurfaceRootUserClient::methodLookup(IOExternalMethodArguments * args)
+{
+ IOReturn ret = kIOReturnNotFound;
+ uint32_t sid;
+ struct minisurf_client_ref * ref;
+
+ if (args->scalarInputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ sid = (uint32_t) args->scalarInput[0];
+ IOLockLock(gSurfaceLock);
+ ref = findRef(sid, false);
+ if (ref == NULL && sid != 0 && sid < MINISURF_TABLE_SIZE && gSurfaceTable[sid] != NULL) {
+ ref = addRef(gSurfaceTable[sid]);
+ if (ref == NULL) {
+ ret = kIOReturnNoMemory;
+ }
+ }
+ if (ref != NULL) {
+ ret = returnSurface(ref, false, args);
+ }
+ IOLockUnlock(gSurfaceLock);
+ return ret;
+}
+
+IOReturn
+IOSurfaceRootUserClient::methodLookupFromPort(IOExternalMethodArguments * args)
+{
+ IOReturn ret;
+ OSObject * obj = NULL;
+ IOSurfaceSendRight * right;
+ struct minisurf_client_ref * ref;
+ bool known;
+
+ if (args->scalarInputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ ret = copyObjectForPortNameInTask(fTask, (mach_port_name_t) args->scalarInput[0], &obj);
+ right = OSDynamicCast(IOSurfaceSendRight, obj);
+ if (ret != kIOReturnSuccess || right == NULL || right->surface == NULL) {
+ OSSafeReleaseNULL(obj);
+ return kIOReturnBadArgument;
+ }
+ IOLockLock(gSurfaceLock);
+ ref = findRef(right->surface->sid, false);
+ known = ref != NULL;
+ if (ref == NULL) {
+ ref = addRef(right->surface);
+ }
+ ret = ref ? returnSurface(ref, known, args) : kIOReturnNoMemory;
+ IOLockUnlock(gSurfaceLock);
+ obj->release();
+ return ret;
+}
+
+mach_port_name_t
+IOSurfaceRootUserClient::makeSendRight(task_t task, MiniIOSurface * s)
+{
+ IOSurfaceSendRight * right;
+ mach_port_name_t name = 0;
+
+ right = OSTypeAlloc(IOSurfaceSendRight);
+ if (right == NULL || !right->init()) {
+ OSSafeReleaseNULL(right);
+ return 0;
+ }
+ IOLockLock(gSurfaceLock);
+ surfaceHold(s); /* for as long as the send right exists */
+ IOLockUnlock(gSurfaceLock);
+ right->surface = s;
+ copyPortNameForObjectInTask(task, right, &name);
+ right->release();
+ return name;
+}
+
+mach_port_name_t
+MiniIOSurfaceMakeSendRight(task_t task, MiniIOSurface * surface)
+{
+ return IOSurfaceRootUserClient::makeSendRight(task, surface);
+}
+
+IOReturn
+IOSurfaceRootUserClient::methodCreatePort(IOExternalMethodArguments * args)
+{
+ MiniIOSurface * s;
+ mach_port_name_t name;
+
+ if (args->scalarInputCount < 1 || args->scalarOutputCount < 1) {
+ return kIOReturnBadArgument;
+ }
+ s = MiniIOSurfaceCopy((uint32_t) args->scalarInput[0]);
+ if (s == NULL) {
+ return kIOReturnNotFound;
+ }
+ name = makeSendRight(fTask, s);
+ MiniIOSurfaceDrop(s);
+ args->scalarOutput[0] = name;
+ args->scalarOutputCount = 1;
+ return name != 0 ? kIOReturnSuccess : kIOReturnNoMemory;
+}
+
+/* Requests about values start with the surface number in 8 bytes; the reply to a change is the new seed. */
+static IOReturn
+returnSeed(IOExternalMethodArguments * args, uint32_t seed)
+{
+ if (args->structureOutput != NULL && args->structureOutputSize >= sizeof(seed)) {
+ memcpy(args->structureOutput, &seed, sizeof(seed));
+ args->structureOutputSize = sizeof(seed);
+ }
+ return kIOReturnSuccess;
+}
+
+IOReturn
+IOSurfaceRootUserClient::methodSetValue(IOExternalMethodArguments * args, const uint8_t * in, size_t inSize)
+{
+ uint32_t sid, seed = 0;
+ OSObject * obj;
+ OSArray * array;
+ struct minisurf_client_ref * ref;
+ IOReturn ret = kIOReturnBadArgument;
+
+ if (inSize < 12) {
+ return kIOReturnBadArgument;
+ }
+ memcpy(&sid, in, sizeof(sid));
+ obj = unserialize(in + 8, inSize - 8);
+ array = OSDynamicCast(OSArray, obj);
+ if (array == NULL) {
+ OSSafeReleaseNULL(obj);
+ return kIOReturnBadArgument;
+ }
+ IOLockLock(gSurfaceLock);
+ ref = findRef(sid, false);
+ if (ref == NULL) {
+ ret = kIOReturnNotFound;
+ } else if (ref->surface->values != NULL) {
+ MiniIOSurface * s = ref->surface;
+ OSString * key = OSDynamicCast(OSString, array->getObject(1));
+ OSDictionary * all = OSDynamicCast(OSDictionary, array->getObject(0));
+
+ if (array->getCount() == 2 && key != NULL) {
+ s->values->setObject(key, array->getObject(0)); /* [value, key] */
+ ret = kIOReturnSuccess;
+ } else if (array->getCount() == 1 && all != NULL) {
+ s->values->merge(all); /* [all the values] */
+ ret = kIOReturnSuccess;
+ }
+ if (ret == kIOReturnSuccess) {
+ s->updateValuesState();
+ seed = s->shared()->valuesSeed;
+ }
+ }
+ IOLockUnlock(gSurfaceLock);
+ obj->release();
+ return ret == kIOReturnSuccess ? returnSeed(args, seed) : ret;
+}
+
+IOReturn
+IOSurfaceRootUserClient::methodRemoveValue(IOExternalMethodArguments * args, const uint8_t * in, size_t inSize)
+{
+ uint32_t sid, seed = 0;
+ struct minisurf_client_ref * ref;
+ IOReturn ret = kIOReturnNotFound;
+
+ if (inSize < 9 || in[inSize - 1] != 0) {
+ return kIOReturnBadArgument;
+ }
+ memcpy(&sid, in, sizeof(sid));
+ IOLockLock(gSurfaceLock);
+ ref = findRef(sid, false);
+ if (ref != NULL && ref->surface->values != NULL) {
+ MiniIOSurface * s = ref->surface;
+ const char * key = (const char *) in + 8;
+
+ if (key[0] == 0) {
+ s->values->flushCollection();
+ } else {
+ s->values->removeObject(key);
+ }
+ s->updateValuesState();
+ seed = s->shared()->valuesSeed;
+ ret = kIOReturnSuccess;
+ }
+ IOLockUnlock(gSurfaceLock);
+ return ret == kIOReturnSuccess ? returnSeed(args, seed) : ret;
+}
+
+/* The reply: 4 bytes unused, the seed, then the serialized value (a dictionary when all were asked for). */
+IOReturn
+IOSurfaceRootUserClient::methodCopyValue(IOExternalMethodArguments * args, const uint8_t * in, size_t inSize)
+{
+ uint32_t sid, header[2] = { 0, 0 };
+ struct minisurf_client_ref * ref;
+ OSSerialize * s = NULL;
+ IOReturn ret = kIOReturnNotFound;
+ uint32_t length = 0, total;
+
+ if (inSize < 9 || in[inSize - 1] != 0) {
+ return kIOReturnBadArgument;
+ }
+ memcpy(&sid, in, sizeof(sid));
+ IOLockLock(gSurfaceLock);
+ ref = findRef(sid, false);
+ if (ref != NULL && ref->surface->values != NULL) {
+ const char * key = (const char *) in + 8;
+ OSObject * value = key[0] ? ref->surface->values->getObject(key) : ref->surface->values;
+
+ header[1] = ref->surface->shared()->valuesSeed;
+ ret = kIOReturnSuccess;
+ if (value != NULL && (key[0] != 0 || ref->surface->values->getCount() != 0)) {
+ s = OSSerialize::binaryWithCapacity(4096);
+ if (s == NULL || !value->serialize(s)) {
+ ret = kIOReturnNoMemory;
+ } else {
+ length = s->getLength();
+ }
+ }
+ }
+ IOLockUnlock(gSurfaceLock);
+
+ total = (uint32_t) sizeof(header) + length;
+ if (ret == kIOReturnSuccess) {
+ if (args->structureOutputDescriptor != NULL) {
+ IOMemoryDescriptor * out = args->structureOutputDescriptor;
+
+ if (out->getLength() < total) {
+ ret = kIOReturnNoSpace;
+ } else if ((ret = out->prepare()) == kIOReturnSuccess) {
+ out->writeBytes(0, header, sizeof(header));
+ if (length != 0) {
+ out->writeBytes(sizeof(header), s->text(), length);
+ }
+ out->complete();
+ args->structureOutputDescriptorSize = total;
+ }
+ } else if (args->structureOutput == NULL || args->structureOutputSize < total) {
+ ret = kIOReturnNoSpace;
+ } else {
+ memcpy(args->structureOutput, header, sizeof(header));
+ if (length != 0) {
+ memcpy((uint8_t *) args->structureOutput + sizeof(header), s->text(), length);
+ }
+ args->structureOutputSize = total;
+ }
+ }
+ OSSafeReleaseNULL(s);
+ return ret;
+}
+
+/*
+ * Colour space, transfer function and the like: a fixed structure kept in the shared page.
+ * The request: the structure, its size, a mask of the fields that changed, the surface number.
+ */
+IOReturn
+IOSurfaceRootUserClient::methodSetBulkAttachments(const uint8_t * in, size_t inSize)
+{
+ static const struct {
+ uint8_t from, to;
+ } fields[15] = {
+ { 0x00, 0x20 }, { 0x20, 0x30 }, { 0x30, 0x38 }, { 0x38, 0x39 }, { 0x39, 0x3a }, { 0x3a, 0x3b }, { 0x3b, 0x3c },
+ { 0x3c, 0x3d }, { 0x3d, 0x3e }, { 0x3e, 0x3f }, { 0x3f, 0x40 }, { 0x40, 0x58 }, { 0x58, 0x5c }, { 0x5c, 0x64 },
+ { 0x64, 0x65 },
+ };
+ uint64_t size, mask;
+ uint32_t sid;
+ struct minisurf_client_ref * ref;
+ IOReturn ret = kIOReturnNotFound;
+
+ if (inSize < 0x88) {
+ return kIOReturnBadArgument;
+ }
+ memcpy(&size, in + 0x70, sizeof(size));
+ memcpy(&mask, in + 0x78, sizeof(mask));
+ memcpy(&sid, in + 0x80, sizeof(sid));
+ if (size > 0x70) {
+ return kIOReturnBadArgument;
+ }
+ IOLockLock(gSurfaceLock);
+ ref = findRef(sid, false);
+ if (ref != NULL) {
+ uint8_t * attachments = ref->surface->shared()->attachments;
+
+ for (unsigned i = 0; i < 15; i++) {
+ if ((mask & (1ULL << i)) && fields[i].to <= size) {
+ memcpy(attachments + fields[i].from, in + fields[i].from, fields[i].to - fields[i].from);
+ }
+ }
+ ret = kIOReturnSuccess;
+ }
+ IOLockUnlock(gSurfaceLock);
+ return ret;
+}
+
+IOReturn
+IOSurfaceRootUserClient::externalMethod(uint32_t selector, IOExternalMethodArguments * args,
+ IOExternalMethodDispatch * dispatch, OSObject * target, void * reference)
+{
+ const uint8_t * in = (const uint8_t *) args->structureInput;
+ size_t inSize = args->structureInputSize;
+ IOMemoryMap * inMap = NULL;
+ struct minisurf_client_ref * ref;
+ IOReturn ret;
+
+ switch (selector) {
+ case kSurfaceMethodInit:
+ return methodInit(args);
+ case kSurfaceMethodCreate:
+ return methodCreate(args);
+ case kSurfaceMethodLookup:
+ return methodLookup(args);
+ case kSurfaceMethodLookupFromPort:
+ return methodLookupFromPort(args);
+ case kSurfaceMethodCreatePort:
+ return methodCreatePort(args);
+
+ case kSurfaceMethodSetValue:
+ case kSurfaceMethodCopyValue:
+ case kSurfaceMethodRemoveValue:
+ case kSurfaceMethodSetBulkAttachments:
+ if (args->structureInputDescriptor != NULL) {
+ inMap = args->structureInputDescriptor->map(kIOMapReadOnly);
+ if (inMap == NULL) {
+ return kIOReturnNoMemory;
+ }
+ in = (const uint8_t *) inMap->getVirtualAddress();
+ inSize = inMap->getLength();
+ }
+ if (in == NULL) {
+ ret = kIOReturnBadArgument;
+ } else if (selector == kSurfaceMethodSetValue) {
+ ret = methodSetValue(args, in, inSize);
+ } else if (selector == kSurfaceMethodCopyValue) {
+ ret = methodCopyValue(args, in, inSize);
+ } else if (selector == kSurfaceMethodRemoveValue) {
+ ret = methodRemoveValue(args, in, inSize);
+ } else {
+ ret = methodSetBulkAttachments(in, inSize);
+ }
+ OSSafeReleaseNULL(inMap);
+ return ret;
+
+ case kSurfaceMethodSetPurgeable: /* in: surface, new state; out: old state */
+ if (args->scalarInputCount < 2) {
+ return kIOReturnBadArgument;
+ }
+ ret = kIOReturnNotFound;
+ IOLockLock(gSurfaceLock);
+ ref = findRef((uint32_t) args->scalarInput[0], false);
+ if (ref != NULL) {
+ if (args->scalarOutputCount >= 1) {
+ args->scalarOutput[0] = ref->surface->purgeable;
+ args->scalarOutputCount = 1;
+ }
+ if (args->scalarInput[1] != 3) { /* 3 = keep current */
+ ref->surface->purgeable = (uint32_t) args->scalarInput[1];
+ }
+ ret = kIOReturnSuccess;
+ }
+ IOLockUnlock(gSurfaceLock);
+ return ret;
+
+ case kSurfaceMethodBindAccel: /* in: surface, accelerator, sub-id */
+ if (args->scalarInputCount < 3) {
+ return kIOReturnBadArgument;
+ }
+ IOLockLock(gSurfaceLock);
+ ref = findRef((uint32_t) args->scalarInput[0], false);
+ if (ref != NULL) {
+ ref->surface->shared()->accelID = (uint16_t) args->scalarInput[1];
+ ref->surface->shared()->accelSubID = (uint16_t) args->scalarInput[2];
+ }
+ IOLockUnlock(gSurfaceLock);
+ return ref ? kIOReturnSuccess : kIOReturnNotFound;
+
+ case kSurfaceMethodSetYCbCrMatrix: /* in: surface, matrix */
+ if (args->scalarInputCount < 2) {
+ break;
+ }
+ IOLockLock(gSurfaceLock);
+ ref = findRef((uint32_t) args->scalarInput[0], false);
+ if (ref != NULL) {
+ ref->surface->shared()->ycbcrMatrix = (uint32_t) args->scalarInput[1];
+ }
+ IOLockUnlock(gSurfaceLock);
+ return ref ? kIOReturnSuccess : kIOReturnNotFound;
+
+ case kSurfaceMethodSetOwnership:
+ case kSurfaceMethodSetOwnershipIdentity:
+ case kSurfaceMethodSetTimestamp:
+ case kSurfaceMethodSetIndexedTimestamp:
+ case kSurfaceMethodDetachModeCode:
+ case kSurfaceMethodLog:
+ /* accounting and diagnostics: nothing depends on them here */
+ if (args->scalarOutputCount != 0) {
+ bzero(args->scalarOutput, args->scalarOutputCount * sizeof(args->scalarOutput[0]));
+ }
+ return kIOReturnSuccess;
+
+ default:
+ break;
+ }
+
+ if (selector < 128 && !(gSurfaceLogged[selector / 64] & (1ULL << (selector % 64)))) {
+ gSurfaceLogged[selector / 64] |= 1ULL << (selector % 64);
+ IOLog("MiniIOSurface: selector %u not implemented (scalars %u in, %u out; structure %u in, %u out)\n", selector,
+ args->scalarInputCount, args->scalarOutputCount, args->structureInputSize, args->structureOutputSize);
+ }
+ return kIOReturnUnsupported;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+IOExternalTrap *
+IOSurfaceRootUserClient::getTargetAndTrapForIndex(IOService ** targetP, UInt32 index)
+{
+ if (index >= kSurfaceTrapCount) {
+ return NULL;
+ }
+ *targetP = this;
+ return &fTraps[index];
+}
+
+IOReturn
+IOSurfaceRootUserClient::useCountCommon(uint32_t sid, uint32_t category, int delta)
+{
+ struct minisurf_client_ref * ref;
+ IOReturn ret = kIOReturnNotFound;
+
+ if (category > 1) {
+ return kIOReturnBadArgument;
+ }
+ IOLockLock(gSurfaceLock);
+ ref = findRef(sid, false);
+ if (ref != NULL) {
+ MiniIOSurface * s = ref->surface;
+
+ if (delta > 0 || ref->use[category] != 0) {
+ ref->use[category] += delta;
+ s->useCount[category] += delta;
+ s->shared()->useCount = (uint64_t) s->useCount[1] << 32 | s->useCount[0];
+ }
+ ret = kIOReturnSuccess;
+ }
+ IOLockUnlock(gSurfaceLock);
+ return ret;
+}
+
+IOReturn
+IOSurfaceRootUserClient::trapIncrementUseCount(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6)
+{
+ return useCountCommon((uint32_t) (uintptr_t) p1, (uint32_t) (uintptr_t) p2, 1);
+}
+
+IOReturn
+IOSurfaceRootUserClient::trapDecrementUseCount(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6)
+{
+ return useCountCommon((uint32_t) (uintptr_t) p1, (uint32_t) (uintptr_t) p2, -1);
+}
+
+/*
+ * Lock and unlock do not exclude anybody: the memory is shared and always mapped.
+ * What matters is the seed, which tells readers that the pixels may have changed.
+ */
+IOReturn
+IOSurfaceRootUserClient::lockCommon(uint32_t sid, uint32_t options, user_addr_t seedOut)
+{
+ struct minisurf_client_ref * ref;
+ uint32_t seed = 0;
+
+ IOLockLock(gSurfaceLock);
+ ref = findRef(sid, false);
+ if (ref != NULL) {
+ struct minisurf_shared * sh = ref->surface->shared();
+
+ if (!(options & kSurfaceLockReadOnly)) {
+ sh->seed++;
+ }
+ seed = sh->seed;
+ }
+ IOLockUnlock(gSurfaceLock);
+ if (ref == NULL) {
+ return kIOReturnNotFound;
+ }
+ if (seedOut != 0) {
+ copyout(&seed, seedOut, sizeof(seed));
+ }
+ return kIOReturnSuccess;
+}
+
+IOReturn
+IOSurfaceRootUserClient::trapLock(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6)
+{
+ return lockCommon((uint32_t) (uintptr_t) p1, (uint32_t) (uintptr_t) p2, (user_addr_t) (uintptr_t) p3);
+}
+
+IOReturn
+IOSurfaceRootUserClient::trapUnlock(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6)
+{
+ return lockCommon((uint32_t) (uintptr_t) p1, (uint32_t) (uintptr_t) p2, (user_addr_t) (uintptr_t) p3);
+}
+
+/*
+ * A client drops a surface in two steps: "detach" while it still holds its own lock, and
+ * "release" after it. A lookup of the same surface in between must make a fresh view.
+ */
+IOReturn
+IOSurfaceRootUserClient::trapDetach(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6)
+{
+ struct minisurf_client_ref * ref;
+
+ IOLockLock(gSurfaceLock);
+ ref = findRef((uint32_t) (uintptr_t) p1, false);
+ if (ref != NULL) {
+ ref->detached = true;
+ }
+ IOLockUnlock(gSurfaceLock);
+ return kIOReturnSuccess;
+}
+
+IOReturn
+IOSurfaceRootUserClient::trapRelease(void * p1, void * p2, void * p3, void * p4, void * p5, void * p6)
+{
+ struct minisurf_client_ref * ref;
+ uint32_t sid = (uint32_t) (uintptr_t) p1;
+
+ IOLockLock(gSurfaceLock);
+ ref = findRef(sid, true);
+ if (ref == NULL) {
+ ref = findRef(sid, false);
+ }
+ if (ref != NULL) {
+ dropRef(ref);
+ }
+ IOLockUnlock(gSurfaceLock);
+ return ref ? kIOReturnSuccess : kIOReturnNotFound;
+}
diff --git a/xnu/files/iokit/Kernel/MiniIOSurface.h b/xnu/files/iokit/Kernel/MiniIOSurface.h
new file mode 100644
index 0000000..79890ac
--- /dev/null
+++ b/xnu/files/iokit/Kernel/MiniIOSurface.h
@@ -0,0 +1,153 @@
+/*
+ * MiniIOSurface: a stand-in for Apple's closed IOSurface.kext, enough of it for the iOS
+ * 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.
+ */
+#ifndef _IOKIT_MINIIOSURFACE_H
+#define _IOKIT_MINIIOSURFACE_H
+
+#include <IOKit/IOService.h>
+#include <IOKit/IOUserClient.h>
+#include <IOKit/IOBufferMemoryDescriptor.h>
+
+#include "MiniDrivers.h"
+
+#define MINISURF_MAX_PLANES 4
+#define MINISURF_RESULT_MAX 0xa68 /* what IOSurface.framework reserves for a result */
+
+/* One plane, as IOSurface.framework reads it (0x80 bytes). */
+struct minisurf_plane {
+ uint32_t width; /* 0x00 */
+ uint32_t height; /* 0x04 */
+ uint32_t reserved08;
+ uint32_t offset; /* 0x0c from the base address */
+ uint32_t bytesPerRow; /* 0x10 */
+ uint32_t size; /* 0x14 */
+ uint16_t bytesPerElement; /* 0x18 */
+ uint8_t elementWidth; /* 0x1a */
+ uint8_t elementHeight; /* 0x1b */
+ uint8_t componentCount; /* 0x1c */
+ uint8_t addressFormat; /* 0x1d */
+ uint8_t reserved1e[2];
+ uint8_t componentBitDepth[4]; /* 0x20 */
+ uint8_t componentBitOffset[4]; /* 0x24 */
+ uint8_t componentName[4]; /* 0x28 */
+ uint8_t componentType[4]; /* 0x2c */
+ uint8_t componentRange[4]; /* 0x30 */
+ uint8_t reserved34[0x20];
+ uint8_t compression; /* 0x54: 1 = compressed, then there is no base address */
+ uint8_t reserved55[0x1b];
+ uint32_t extendedPixels[4]; /* 0x70 */
+};
+
+/* What "create" and the lookups return: this header, then the planes (at least one). */
+struct minisurf_result {
+ uint64_t base; /* 0x00 where the memory is mapped in the client */
+ uint64_t shared; /* 0x08 struct minisurf_shared, mapped in the client */
+ uint64_t aux; /* 0x10 struct minisurf_aux, mapped in the client */
+ uint32_t sid; /* 0x18 */
+ uint32_t allocSize; /* 0x1c */
+ uint32_t width; /* 0x20 */
+ uint32_t height; /* 0x24 */
+ uint32_t bytesPerRow; /* 0x28 */
+ uint32_t offset; /* 0x2c */
+ uint32_t pixelFormat; /* 0x30 */
+ uint32_t reserved34;
+ uint32_t planeCount; /* 0x38 */
+ uint32_t reserved3c;
+ uint16_t bytesPerElement; /* 0x40 */
+ uint8_t elementWidth; /* 0x42 */
+ uint8_t elementHeight; /* 0x43 */
+ uint32_t cacheMode; /* 0x44 */
+ uint32_t lockSeed; /* 0x48 the client keeps the seed of its last lock here */
+ uint8_t subsampling; /* 0x4c */
+ uint8_t prohibitUseCount; /* 0x4d */
+ uint16_t reserved4e;
+ uint32_t parentID; /* 0x50 */
+ uint32_t sliceCount; /* 0x54 */
+ uint64_t traceID; /* 0x58 */
+ uint64_t protectionOptions; /* 0x60 */
+};
+
+/* State that every client reads straight from memory shared with the kernel. */
+struct minisurf_shared {
+ uint64_t registryID; /* 0x00 */
+ uint16_t accelID; /* 0x08 */
+ uint16_t accelSubID; /* 0x0a */
+ uint32_t seed; /* 0x0c changes when somebody has written the pixels */
+ uint32_t reserved10;
+ uint8_t tiled; /* 0x14 */
+ uint8_t reserved15[3];
+ uint64_t useCount; /* 0x18 two 32-bit counters, one per category */
+ uint32_t valuesSeed; /* 0x20 */
+ uint32_t ycbcrMatrix; /* 0x24 */
+ uint32_t valuesSize; /* 0x28 room needed to fetch the values; 0 = none */
+ uint8_t pixelSizeCasting; /* 0x2c */
+ uint8_t displayable; /* 0x2d */
+ uint8_t sysMemOnly; /* 0x2e */
+ uint8_t reserved2f;
+ uint8_t attachments[0x70]; /* 0x30 the "bulk attachments" */
+};
+
+struct minisurf_aux {
+ uint64_t timestamps[4];
+ uint64_t detachModeCode;
+};
+
+#define MINISURF_AUX_OFFSET 0x400 /* of the aux structure inside the shared page */
+
+class MiniIOSurface : public OSObject
+{
+ OSDeclareDefaultStructors(MiniIOSurface);
+
+public:
+ uint32_t sid;
+ uint32_t holders; /* clients, send rights, kernel users */
+ IOBufferMemoryDescriptor * memory; /* one page of shared state, then the pixels */
+ uint8_t * kbase; /* the same, in the kernel */
+ struct minisurf_result info; /* addresses not filled in */
+ struct minisurf_plane planes[MINISURF_MAX_PLANES];
+ OSDictionary * values;
+ uint32_t useCount[2];
+ uint32_t purgeable;
+
+ virtual bool
+ init(void) APPLE_KEXT_OVERRIDE
+ {
+ return OSObject::init();
+ }
+ virtual void free(void) APPLE_KEXT_OVERRIDE;
+
+ struct minisurf_shared *
+ shared(void) const
+ {
+ return (struct minisurf_shared *) kbase;
+ }
+ struct minisurf_aux *
+ aux(void) const
+ {
+ return (struct minisurf_aux *) (kbase + MINISURF_AUX_OFFSET);
+ }
+ /* The first byte of the pixels (the "base address" clients see). */
+ uint8_t *
+ pixels(void) const
+ {
+ return kbase + PAGE_SIZE + info.offset;
+ }
+ void updateValuesState(void);
+};
+
+/*
+ * For other parts of the kernel (the framebuffer).
+ * A surface found or made here is held until MiniIOSurfaceDrop().
+ */
+MiniIOSurface * MiniIOSurfaceCopy(uint32_t sid);
+MiniIOSurface * MiniIOSurfaceCreateSimple(uint32_t width, uint32_t height, uint32_t pixelFormat);
+void MiniIOSurfaceDrop(MiniIOSurface * surface);
+/* A Mach send right for the surface in the task (what IOSurfaceCreateMachPort gives); 0 on failure. */
+mach_port_name_t MiniIOSurfaceMakeSendRight(task_t task, MiniIOSurface * surface);
+
+
+#endif /* _IOKIT_MINIIOSURFACE_H */
diff --git a/xnu/files/libkern/amfi/miniamfi.c b/xnu/files/libkern/amfi/miniamfi.c
new file mode 100644
index 0000000..d270c26
--- /dev/null
+++ b/xnu/files/libkern/amfi/miniamfi.c
@@ -0,0 +1,264 @@
+/*
+ * Stand-in for the AppleMobileFileIntegrity kext interface.
+ *
+ * The kernel reaches AMFI through a table of function pointers that the kext
+ * registers at load time. That kext is closed, so this file registers a table
+ * of its own. No trust cache contains anything, and there is no signature
+ * policy behind it; a process holds the entitlements that the signature of
+ * its program lists (miniamfi_entitlements.cpp), and a program without a
+ * signature holds none.
+ *
+ * The CoreEntitlements part of the table is left empty; only the PPL build of
+ * the pmap reaches into it.
+ */
+
+#include <kern/startup.h>
+#include <kern/kern_types.h>
+#include <libkern/libkern.h>
+#include <libkern/amfi/amfi.h>
+
+static void
+mini_OSEntitlements_invalidate(__unused void *osentitlements)
+{
+}
+
+static void *
+mini_OSEntitlements_asdict(__unused void *osentitlements)
+{
+ return NULL;
+}
+
+static bool
+mini_OSEntitlements_get_transmuted(__unused void *osentitlements, const CS_GenericBlob **blob)
+{
+ *blob = NULL;
+ return false;
+}
+
+static bool
+mini_OSEntitlements_get_xml(__unused void *osentitlements, CS_GenericBlob **blob)
+{
+ *blob = NULL;
+ return false;
+}
+
+static bool
+mini_get_legacy_profile_exemptions(const uint8_t **profile, size_t *profileLength)
+{
+ *profile = NULL;
+ *profileLength = 0;
+ return false;
+}
+
+static bool
+mini_get_udid(const uint8_t **udid, size_t *udidLength)
+{
+ *udid = NULL;
+ *udidLength = 0;
+ return false;
+}
+
+static void *
+mini_query_context_to_object(__unused CEQueryContext_t ctx)
+{
+ return NULL;
+}
+
+/* OSEntitlements */
+
+static kern_return_t
+mini_adjustContextWithMonitor(__unused void *os_entitlements, __unused const CEQueryContext_t ce_ctx,
+ __unused const void *monitor_sig_obj, __unused const char *identity, __unused const uint32_t code_signing_flags)
+{
+ return KERN_SUCCESS;
+}
+
+static kern_return_t
+mini_adjustContextWithoutMonitor(__unused void *os_entitlements, __unused struct cs_blob *code_signing_blob)
+{
+ return KERN_SUCCESS;
+}
+
+static kern_return_t
+mini_queryEntitlementBoolean(__unused const void *os_entitlements, __unused const char *entitlement_name)
+{
+ return KERN_NOT_FOUND;
+}
+
+/* Queries about a process are answered from the entitlements in its code signature: miniamfi_entitlements.cpp */
+extern kern_return_t miniamfi_entitlement_boolean(struct proc *proc, const char *name);
+extern kern_return_t miniamfi_entitlement_string(struct proc *proc, const char *name, const char *value);
+extern kern_return_t miniamfi_entitlement_object(struct proc *proc, const char *name, void **object);
+
+static kern_return_t
+mini_queryEntitlementBooleanWithProc(const proc_t proc, const char *entitlement_name)
+{
+ return miniamfi_entitlement_boolean(proc, entitlement_name);
+}
+
+static kern_return_t
+mini_queryEntitlementString(__unused const void *os_entitlements, __unused const char *entitlement_name,
+ __unused const char *entitlement_value)
+{
+ return KERN_NOT_FOUND;
+}
+
+static kern_return_t
+mini_queryEntitlementStringWithProc(const proc_t proc, const char *entitlement_name, const char *entitlement_value)
+{
+ return miniamfi_entitlement_string(proc, entitlement_name, entitlement_value);
+}
+
+static kern_return_t
+mini_copyEntitlementAsOSObject(__unused const void *os_entitlements, __unused const char *entitlement_name,
+ void **entitlement_object)
+{
+ *entitlement_object = NULL;
+ return KERN_NOT_FOUND;
+}
+
+static kern_return_t
+mini_copyEntitlementAsOSObjectWithProc(const proc_t proc, const char *entitlement_name, void **entitlement_object)
+{
+ return miniamfi_entitlement_object(proc, entitlement_name, entitlement_object);
+}
+
+/* libTrustCache: there are no trust caches, so nothing loads and nothing is found */
+
+static TCReturn_t
+mini_tc_loadModule(__unused TrustCacheRuntime_t *runtime, __unused const TCType_t type, __unused TrustCache_t *trustCache,
+ __unused const uintptr_t dataAddr, __unused const size_t dataSize)
+{
+ return buildTCRet(kTCComponentLoadModule, kTCReturnUnsupported, 0);
+}
+
+static TCReturn_t
+mini_tc_load(__unused TrustCacheRuntime_t *runtime, __unused TCType_t type, __unused TrustCache_t *trustCache,
+ __unused const uintptr_t payloadAddr, __unused const size_t payloadSize,
+ __unused const uintptr_t manifestAddr, __unused const size_t manifestSize)
+{
+ return buildTCRet(kTCComponentLoad, kTCReturnUnsupported, 0);
+}
+
+static TCReturn_t
+mini_tc_query(__unused const TrustCacheRuntime_t *runtime, __unused TCQueryType_t queryType,
+ __unused const uint8_t CDHash[kTCEntryHashSize], __unused TrustCacheQueryToken_t *queryToken)
+{
+ return buildTCRet(kTCComponentQuery, kTCReturnNotFound, 0);
+}
+
+static TCReturn_t
+mini_tc_getCapabilities(__unused const TrustCache_t *trustCache, TCCapabilities_t *capabilities)
+{
+ *capabilities = 0;
+ return buildTCRet(kTCComponentModuleCapabilities, kTCReturnSuccess, 0);
+}
+
+static TCReturn_t
+mini_tc_queryGetTCType(__unused const TrustCacheQueryToken_t *queryToken, __unused TCType_t *typeRet)
+{
+ return buildTCRet(kTCComponentQueryTCType, kTCReturnInvalidArguments, 0);
+}
+
+static TCReturn_t
+mini_tc_queryGetCapabilities(__unused const TrustCacheQueryToken_t *queryToken, __unused TCCapabilities_t *capabilities)
+{
+ return buildTCRet(kTCComponentModuleCapabilities, kTCReturnInvalidArguments, 0);
+}
+
+static TCReturn_t
+mini_tc_queryGetHashType(__unused const TrustCacheQueryToken_t *queryToken, __unused uint8_t *hashTypeRet)
+{
+ return buildTCRet(kTCComponentQueryHashType, kTCReturnInvalidArguments, 0);
+}
+
+static TCReturn_t
+mini_tc_queryGetFlags(__unused const TrustCacheQueryToken_t *queryToken, __unused uint64_t *flagsRet)
+{
+ return buildTCRet(kTCComponentQueryFlags, kTCReturnInvalidArguments, 0);
+}
+
+static TCReturn_t
+mini_tc_queryGetConstraintCategory(__unused const TrustCacheQueryToken_t *queryToken, __unused uint8_t *constraintCategoryRet)
+{
+ return buildTCRet(kTCComponentQueryConstraintCategory, kTCReturnInvalidArguments, 0);
+}
+
+static TCReturn_t
+mini_tc_constructInvalid(__unused TrustCache_t *trustCache, __unused const uint8_t *moduleAddr, __unused size_t moduleSize)
+{
+ return buildTCRet(kTCComponentConstructInvalid, kTCReturnUnsupported, 0);
+}
+
+static TCReturn_t
+mini_tc_checkRuntimeForUUID(__unused const TrustCacheRuntime_t *runtime, __unused const uint8_t checkUUID[kUUIDSize],
+ __unused const TrustCache_t **trustCacheRet)
+{
+ return buildTCRet(kTCComponentCheckRuntimeForUUID, kTCReturnNotFound, 0);
+}
+
+static TCReturn_t
+mini_tc_extractModule(__unused TrustCache_t *trustCache, __unused const uint8_t *dataAddr, __unused size_t dataSize)
+{
+ return buildTCRet(kTCComponentExtractModule, kTCReturnUnsupported, 0);
+}
+
+static TCReturn_t
+mini_tc_getModule(__unused const TrustCache_t *trustCache, __unused const uint8_t **moduleAddrRet, __unused size_t *moduleSizeRet)
+{
+ return buildTCRet(kTCComponentGetModule, kTCReturnUnsupported, 0);
+}
+
+static TCReturn_t
+mini_tc_getUUID(__unused const TrustCache_t *trustCache, __unused uint8_t returnUUID[kUUIDSize])
+{
+ return buildTCRet(kTCComponentGetUUID, kTCReturnUnsupported, 0);
+}
+
+static const amfi_t miniamfi = {
+ .OSEntitlements_invalidate = mini_OSEntitlements_invalidate,
+ .OSEntitlements_asdict = mini_OSEntitlements_asdict,
+ .OSEntitlements_get_transmuted = mini_OSEntitlements_get_transmuted,
+ .OSEntitlements_get_xml = mini_OSEntitlements_get_xml,
+ .get_legacy_profile_exemptions = mini_get_legacy_profile_exemptions,
+ .get_udid = mini_get_udid,
+ .query_context_to_object = mini_query_context_to_object,
+
+ .TrustCache = {
+ .version = TRUST_CACHE_INTERFACE_VERSION,
+ .loadModule = mini_tc_loadModule,
+ .load = mini_tc_load,
+ .query = mini_tc_query,
+ .getCapabilities = mini_tc_getCapabilities,
+ .queryGetTCType = mini_tc_queryGetTCType,
+ .queryGetCapabilities = mini_tc_queryGetCapabilities,
+ .queryGetHashType = mini_tc_queryGetHashType,
+ .queryGetFlags = mini_tc_queryGetFlags,
+ .queryGetConstraintCategory = mini_tc_queryGetConstraintCategory,
+ .constructInvalid = mini_tc_constructInvalid,
+ .checkRuntimeForUUID = mini_tc_checkRuntimeForUUID,
+ .extractModule = mini_tc_extractModule,
+ .getModule = mini_tc_getModule,
+ .getUUID = mini_tc_getUUID,
+ },
+
+ .OSEntitlements = {
+ .version = OSENTITLEMENTS_INTERFACE_VERSION,
+ .adjustContextWithMonitor = mini_adjustContextWithMonitor,
+ .adjustContextWithoutMonitor = mini_adjustContextWithoutMonitor,
+ .queryEntitlementBoolean = mini_queryEntitlementBoolean,
+ .queryEntitlementBooleanWithProc = mini_queryEntitlementBooleanWithProc,
+ .queryEntitlementString = mini_queryEntitlementString,
+ .queryEntitlementStringWithProc = mini_queryEntitlementStringWithProc,
+ .copyEntitlementAsOSObject = mini_copyEntitlementAsOSObject,
+ .copyEntitlementAsOSObjectWithProc = mini_copyEntitlementAsOSObjectWithProc,
+ },
+};
+
+__startup_func
+static void
+miniamfi_init(void)
+{
+ amfi_interface_register(&miniamfi);
+}
+STARTUP(EARLY_BOOT, STARTUP_RANK_FIRST, miniamfi_init);
diff --git a/xnu/files/libkern/amfi/miniamfi_entitlements.cpp b/xnu/files/libkern/amfi/miniamfi_entitlements.cpp
new file mode 100644
index 0000000..b13c6e5
--- /dev/null
+++ b/xnu/files/libkern/amfi/miniamfi_entitlements.cpp
@@ -0,0 +1,123 @@
+/*
+ * Entitlement queries for the AMFI stand-in (see miniamfi.c).
+ *
+ * The kernel asks AMFI whether a process holds an entitlement: a key in the
+ * property list that is part of the program's code signature. The real kext
+ * answers from its own validated copy. Here the list embedded in the
+ * signature of the running program is read directly; nothing vouches for it,
+ * in keeping with a kernel that checks no signatures at all. A program
+ * without a signature has no entitlements.
+ */
+
+#include <libkern/c++/OSArray.h>
+#include <libkern/c++/OSBoolean.h>
+#include <libkern/c++/OSDictionary.h>
+#include <libkern/c++/OSString.h>
+#include <libkern/c++/OSUnserialize.h>
+#include <kern/cs_blobs.h>
+#include <mach/kern_return.h>
+#include <kern/kalloc.h>
+#include <string.h>
+
+extern "C" {
+struct proc;
+int cs_entitlements_blob_get(struct proc *p, void **out_start, size_t *out_length);
+
+kern_return_t miniamfi_entitlement_boolean(struct proc *proc, const char *name);
+kern_return_t miniamfi_entitlement_string(struct proc *proc, const char *name, const char *value);
+kern_return_t miniamfi_entitlement_object(struct proc *proc, const char *name, void **object);
+}
+
+/* The entitlements of a process as a dictionary, or NULL; the caller releases it. */
+static OSDictionary *
+copy_entitlements(struct proc *proc)
+{
+ void *start = NULL;
+ size_t length = 0, text_length;
+ OSObject *parsed;
+ OSDictionary *dict;
+ char *text;
+
+ if (proc == NULL || cs_entitlements_blob_get(proc, &start, &length) != 0 || start == NULL ||
+ length <= sizeof(CS_GenericBlob)) {
+ return NULL;
+ }
+ /*
+ * The blob is a header followed by the text of an XML property list.
+ * The parser wants that text terminated, which in the blob it is not.
+ */
+ text_length = length - sizeof(CS_GenericBlob);
+ text = (char *)kalloc_data(text_length + 1, Z_WAITOK);
+ if (text == NULL) {
+ return NULL;
+ }
+ memcpy(text, ((const CS_GenericBlob *)start)->data, text_length);
+ text[text_length] = '\0';
+ parsed = OSUnserializeXML(text, NULL);
+ kfree_data(text, text_length + 1);
+
+ dict = OSDynamicCast(OSDictionary, parsed);
+ if (dict == NULL && parsed != NULL) {
+ parsed->release();
+ }
+ return dict;
+}
+
+kern_return_t
+miniamfi_entitlement_boolean(struct proc *proc, const char *name)
+{
+ OSDictionary *entitlements = copy_entitlements(proc);
+ kern_return_t result = KERN_NOT_FOUND;
+
+ if (entitlements != NULL) {
+ if (entitlements->getObject(name) == kOSBooleanTrue) {
+ result = KERN_SUCCESS;
+ }
+ entitlements->release();
+ }
+ return result;
+}
+
+/* True if the entitlement is that string, or an array that contains it. */
+kern_return_t
+miniamfi_entitlement_string(struct proc *proc, const char *name, const char *value)
+{
+ OSDictionary *entitlements = copy_entitlements(proc);
+ kern_return_t result = KERN_NOT_FOUND;
+
+ if (entitlements != NULL) {
+ OSObject *object = entitlements->getObject(name);
+ OSString *string = OSDynamicCast(OSString, object);
+ OSArray *array = OSDynamicCast(OSArray, object);
+
+ if (string != NULL && string->isEqualTo(value)) {
+ result = KERN_SUCCESS;
+ }
+ for (unsigned int i = 0; array != NULL && i < array->getCount(); i++) {
+ string = OSDynamicCast(OSString, array->getObject(i));
+ if (string != NULL && string->isEqualTo(value)) {
+ result = KERN_SUCCESS;
+ }
+ }
+ entitlements->release();
+ }
+ return result;
+}
+
+/* The value itself, retained, as IOKit wants it. */
+kern_return_t
+miniamfi_entitlement_object(struct proc *proc, const char *name, void **object)
+{
+ OSDictionary *entitlements = copy_entitlements(proc);
+ OSObject *value = NULL;
+
+ if (entitlements != NULL) {
+ value = entitlements->getObject(name);
+ if (value != NULL) {
+ value->retain();
+ }
+ entitlements->release();
+ }
+ *object = value;
+ return value != NULL ? KERN_SUCCESS : KERN_NOT_FOUND;
+}
diff --git a/xnu/files/osfmk/arm64/generic_arm64_support.c b/xnu/files/osfmk/arm64/generic_arm64_support.c
new file mode 100644
index 0000000..49de008
--- /dev/null
+++ b/xnu/files/osfmk/arm64/generic_arm64_support.c
@@ -0,0 +1,57 @@
+/*
+ * Routines the open-source tree references but only defines for Apple SoCs.
+ * Needed when building for a generic ARMv8 board without a monitor (PPL).
+ */
+#include <mach/mach_types.h>
+#include <arm/machine_routines.h>
+#include <arm/caches_internal.h>
+#include <arm/pmap.h>
+
+/* No PPL / secure monitor to switch on. */
+void
+ml_enable_monitor(void)
+{
+}
+
+/*
+ * On Apple cores the "_nohid" variant skips toggling a HID chicken bit;
+ * elsewhere it is simply a forced clean to the point of coherency.
+ */
+void
+CleanPoC_DcacheRegion_Force_nopreempt_nohid(vm_offset_t va, size_t length)
+{
+ CleanPoC_DcacheRegion_Force(va, length);
+}
+
+/*
+ * Stock LLVM lowers Mach-O static destructors to __cxa_atexit registrations
+ * (Apple's clang emits __mod_term_func entries in kernel mode instead).
+ * The kernel never exits, so registration is a no-op.
+ */
+int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
+int
+__cxa_atexit(void (*func)(void *) __unused, void *arg __unused, void *dso __unused)
+{
+ return 0;
+}
+
+/*
+ * Profile-guided-optimisation runtime hooks, normally supplied by Apple's
+ * compiler-rt build for the kernel. Report "no profile data".
+ */
+uint64_t __llvm_profile_get_size_for_buffer_internal(const void *, const void *, const void *, const void *, const void *, const void *);
+int __llvm_profile_write_buffer_internal(char *, const void *, const void *, const void *, const void *, const void *, const void *);
+
+uint64_t
+__llvm_profile_get_size_for_buffer_internal(const void *a __unused, const void *b __unused,
+ const void *c __unused, const void *d __unused, const void *e __unused, const void *f __unused)
+{
+ return 0;
+}
+
+int
+__llvm_profile_write_buffer_internal(char *buf __unused, const void *a __unused, const void *b __unused,
+ const void *c __unused, const void *d __unused, const void *e __unused, const void *f __unused)
+{
+ return -1;
+}
diff --git a/xnu/files/osfmk/arm64/gic_v3_irq.c b/xnu/files/osfmk/arm64/gic_v3_irq.c
new file mode 100644
index 0000000..d56a7dd
--- /dev/null
+++ b/xnu/files/osfmk/arm64/gic_v3_irq.c
@@ -0,0 +1,216 @@
+/*
+ * Minimal GICv3 support for generic (non-Apple) ARMv8 boards.
+ *
+ * Open-source XNU has no interrupt controller driver: on Apple hardware that
+ * is a kext (AppleInterruptController), and the timer arrives as FIQ. Here
+ * everything is a Group 1 IRQ, which is what an EL1 guest gets from a stock
+ * hypervisor or from QEMU's virt machine:
+ *
+ * - the CPU interface is driven through the ICC_*_EL1 system registers
+ * - the EL1 virtual timer PPI is routed to the kernel's rtclock
+ * - any other interrupt that fires is masked and counted, until a real
+ * driver registers a handler for it
+ *
+ * Registers come from the device tree node /arm-io/gic:
+ * reg = <distributor offset, size, redistributor offset, size>
+ */
+#include <mach/mach_types.h>
+#include <kern/debug.h>
+#include <arm/cpu_data_internal.h>
+#include <arm/machine_routines.h>
+#include <arm/rtclock.h>
+#include <arm64/proc_reg.h>
+#include <pexpert/pexpert.h>
+#include <pexpert/device_tree.h>
+#include <pexpert/arm64/board_config.h>
+
+#if defined(GENERIC_GIC_V3_IRQ)
+
+#define GICD_CTLR 0x0000
+#define GICD_CTLR_ENABLE_G1NS (1u << 1)
+#define GICD_CTLR_ARE_NS (1u << 4)
+#define GICD_CTLR_RWP (1u << 31)
+#define GICD_ICENABLER(n) (0x0180 + 4 * (n))
+
+#define GICR_FRAME_SIZE 0x20000 /* RD_base + SGI_base per CPU */
+#define GICR_TYPER 0x0008
+#define GICR_TYPER_LAST (1u << 4)
+#define GICR_WAKER 0x0014
+#define GICR_WAKER_PROCSLEEP (1u << 1)
+#define GICR_WAKER_CHILDASLEEP (1u << 2)
+#define GICR_SGI_BASE 0x10000
+#define GICR_IGROUPR0 (GICR_SGI_BASE + 0x0080)
+#define GICR_ISENABLER0 (GICR_SGI_BASE + 0x0100)
+#define GICR_ICENABLER0 (GICR_SGI_BASE + 0x0180)
+#define GICR_IPRIORITYR(n) (GICR_SGI_BASE + 0x0400 + (n))
+#define GICR_IGRPMODR0 (GICR_SGI_BASE + 0x0d00)
+
+#define GIC_INTID_VTIMER 27 /* EL1 virtual timer PPI */
+#define GIC_INTID_SPURIOUS_MIN 1020
+#define GIC_PRIORITY_DEFAULT 0xa0
+
+static vm_offset_t gicd_base, gicr_base;
+static vm_size_t gicr_size;
+static vm_offset_t gicr_cpu_base; /* boot CPU's redistributor frame */
+
+static uint64_t gic_active_iar; /* acknowledged, not yet EOI'd */
+uint64_t gic_unhandled_count;
+uint32_t gic_last_unhandled;
+
+void gic_v3_irq_cpu_init(void);
+void gic_v3_irq_quiesce(void);
+
+static inline uint32_t
+gic_read32(vm_offset_t addr)
+{
+ return *(volatile uint32_t *)addr;
+}
+
+static inline void
+gic_write32(vm_offset_t addr, uint32_t value)
+{
+ *(volatile uint32_t *)addr = value;
+}
+
+static void
+gic_mask(uint32_t intid)
+{
+ if (intid < 32) {
+ gic_write32(gicr_cpu_base + GICR_ICENABLER0, 1u << intid);
+ } else {
+ gic_write32(gicd_base + GICD_ICENABLER(intid / 32), 1u << (intid % 32));
+ }
+}
+
+static void
+gic_irq_handler(__unused void *target, __unused void *refCon, __unused void *nub, __unused int source)
+{
+ for (;;) {
+ uint64_t iar = __builtin_arm_rsr64("ICC_IAR1_EL1");
+ uint32_t intid = (uint32_t)(iar & 0xffffff);
+
+ if (intid >= GIC_INTID_SPURIOUS_MIN) {
+ break;
+ }
+ gic_active_iar = iar;
+
+ if (intid == GIC_INTID_VTIMER) {
+ /* same sequence as the FIQ path in sleh_fiq() */
+ getCpuDatap()->cpu_decrementer = -1; /* Large */
+ rtclock_intr(TRUE);
+ } else {
+ /* nobody owns this interrupt yet: keep it from storming */
+ gic_mask(intid);
+ gic_unhandled_count++;
+ gic_last_unhandled = intid;
+ }
+
+ __builtin_arm_wsr64("ICC_EOIR1_EL1", iar);
+ __builtin_arm_isb(ISB_SY);
+ gic_active_iar = 0;
+ }
+}
+
+/*
+ * Leave the controller in a state another environment can take over from:
+ * finish any interrupt that was acknowledged but not completed. Used when
+ * control goes back to the boot loader (see loader_return.c).
+ */
+void
+gic_v3_irq_quiesce(void)
+{
+ if (gic_active_iar != 0) {
+ __builtin_arm_wsr64("ICC_EOIR1_EL1", gic_active_iar);
+ __builtin_arm_isb(ISB_SY);
+ gic_active_iar = 0;
+ }
+}
+
+static vm_offset_t
+gic_find_redistributor(void)
+{
+ uint64_t mpidr = __builtin_arm_rsr64("MPIDR_EL1");
+ /* GICR_TYPER[63:32] packs Aff3.Aff2.Aff1.Aff0 */
+ uint32_t affinity = (uint32_t)(((mpidr >> 32) & 0xff) << 24 | (mpidr & 0xffffff));
+
+ for (vm_offset_t frame = gicr_base; frame + GICR_FRAME_SIZE <= gicr_base + gicr_size; frame += GICR_FRAME_SIZE) {
+ uint64_t typer = *(volatile uint64_t *)(frame + GICR_TYPER);
+
+ if ((uint32_t)(typer >> 32) == affinity) {
+ return frame;
+ }
+ if (typer & GICR_TYPER_LAST) {
+ break;
+ }
+ }
+ panic("gic: no redistributor for MPIDR 0x%llx", mpidr);
+}
+
+/* Per-CPU bring-up; only the boot CPU is supported for now. */
+void
+gic_v3_irq_cpu_init(void)
+{
+ if (gicd_base == 0) {
+ DTEntry entry;
+ void const *prop;
+ unsigned int prop_size;
+
+ if (SecureDTLookupEntry(NULL, "/arm-io/gic", &entry) != kSuccess ||
+ SecureDTGetProperty(entry, "reg", &prop, &prop_size) != kSuccess ||
+ prop_size < 4 * sizeof(uint64_t)) {
+ panic("gic: no usable /arm-io/gic node in the device tree");
+ }
+ uint64_t const *reg = prop;
+ vm_offset_t soc_base = pe_arm_get_soc_base_phys();
+
+ gicd_base = ml_io_map(soc_base + reg[0], reg[1]);
+ gicr_base = ml_io_map(soc_base + reg[2], reg[3]);
+ gicr_size = reg[3];
+ if (gicd_base == 0 || gicr_base == 0) {
+ panic("gic: cannot map the distributor/redistributor");
+ }
+ } else if (gicr_cpu_base != 0) {
+ return;
+ }
+
+ /* System-register CPU interface */
+ __builtin_arm_wsr64("ICC_SRE_EL1", __builtin_arm_rsr64("ICC_SRE_EL1") | 1);
+ __builtin_arm_isb(ISB_SY);
+
+ gicr_cpu_base = gic_find_redistributor();
+
+ uint32_t waker = gic_read32(gicr_cpu_base + GICR_WAKER);
+ if (waker & (GICR_WAKER_PROCSLEEP | GICR_WAKER_CHILDASLEEP)) {
+ gic_write32(gicr_cpu_base + GICR_WAKER, waker & ~GICR_WAKER_PROCSLEEP);
+ while (gic_read32(gicr_cpu_base + GICR_WAKER) & GICR_WAKER_CHILDASLEEP) {
+ /* spin until the redistributor is awake */
+ }
+ }
+
+ /* Virtual timer PPI: Group 1 (IRQ), default priority, enabled */
+ gic_write32(gicr_cpu_base + GICR_IGROUPR0, gic_read32(gicr_cpu_base + GICR_IGROUPR0) | (1u << GIC_INTID_VTIMER));
+ gic_write32(gicr_cpu_base + GICR_IGRPMODR0, gic_read32(gicr_cpu_base + GICR_IGRPMODR0) & ~(1u << GIC_INTID_VTIMER));
+ *(volatile uint8_t *)(gicr_cpu_base + GICR_IPRIORITYR(GIC_INTID_VTIMER)) = GIC_PRIORITY_DEFAULT;
+ gic_write32(gicr_cpu_base + GICR_ISENABLER0, 1u << GIC_INTID_VTIMER);
+
+ /* Distributor: affinity routing, Group 1 enabled (normally already so) */
+ uint32_t ctlr = gic_read32(gicd_base + GICD_CTLR);
+ if ((ctlr & (GICD_CTLR_ENABLE_G1NS | GICD_CTLR_ARE_NS)) != (GICD_CTLR_ENABLE_G1NS | GICD_CTLR_ARE_NS)) {
+ gic_write32(gicd_base + GICD_CTLR, ctlr | GICD_CTLR_ENABLE_G1NS | GICD_CTLR_ARE_NS);
+ while (gic_read32(gicd_base + GICD_CTLR) & GICD_CTLR_RWP) {
+ /* wait for the write to take effect */
+ }
+ }
+
+ /* CPU interface: accept all priorities, no preemption grouping, Group 1 on */
+ __builtin_arm_wsr64("ICC_PMR_EL1", 0xff);
+ __builtin_arm_wsr64("ICC_BPR1_EL1", 0);
+ __builtin_arm_wsr64("ICC_IGRPEN1_EL1", 1);
+ __builtin_arm_isb(ISB_SY);
+
+ ml_install_interrupt_handler(NULL, 0, NULL, gic_irq_handler, NULL);
+ kprintf("gic: v3, distributor %p, redistributor %p, virtual timer on PPI %d\n",
+ (void *)gicd_base, (void *)gicr_cpu_base, GIC_INTID_VTIMER);
+}
+
+#endif /* GENERIC_GIC_V3_IRQ */
diff --git a/xnu/files/osfmk/arm64/kpc.c b/xnu/files/osfmk/arm64/kpc.c
new file mode 100644
index 0000000..76ab6c8
--- /dev/null
+++ b/xnu/files/osfmk/arm64/kpc.c
@@ -0,0 +1,152 @@
+/*
+ * Machine-dependent kpc (kernel performance counters) for non-Apple ARMv8
+ * cores. Apple does not publish its arm64 kpc.c. This version reports a PMU
+ * with no counters, so the kpc/kperf machinery stays linked but inert.
+ */
+#include <kern/kpc.h>
+#include <kern/kern_types.h>
+#include <mach/kern_return.h>
+#include <sys/errno.h>
+
+int kpc_pc_capture = 0;
+
+void
+kpc_arch_init(void)
+{
+}
+
+uint32_t
+kpc_get_classes(void)
+{
+ return 0;
+}
+
+int
+kpc_get_pmu_version(void)
+{
+ return KPC_PMU_ERROR;
+}
+
+int
+kpc_set_sw_inc(uint32_t mask __unused)
+{
+ return ENOTSUP;
+}
+
+void
+kpc_idle(void)
+{
+}
+
+void
+kpc_idle_exit(void)
+{
+}
+
+int
+kpc_get_all_cpus_counters(uint32_t classes __unused, int *curcpu __unused, uint64_t *buf __unused)
+{
+ return 0;
+}
+
+int
+kpc_get_fixed_counters(uint64_t *counterv __unused)
+{
+ return 0;
+}
+
+int
+kpc_get_configurable_counters(uint64_t *counterv __unused, uint64_t pmc_mask __unused)
+{
+ return 0;
+}
+
+boolean_t
+kpc_is_running_fixed(void)
+{
+ return FALSE;
+}
+
+boolean_t
+kpc_is_running_configurable(uint64_t pmc_mask __unused)
+{
+ return FALSE;
+}
+
+uint32_t
+kpc_fixed_count(void)
+{
+ return 0;
+}
+
+uint32_t
+kpc_configurable_count(void)
+{
+ return 0;
+}
+
+uint32_t
+kpc_fixed_config_count(void)
+{
+ return 0;
+}
+
+uint32_t
+kpc_configurable_config_count(uint64_t pmc_mask __unused)
+{
+ return 0;
+}
+
+uint32_t
+kpc_rawpmu_config_count(void)
+{
+ return 0;
+}
+
+int
+kpc_get_fixed_config(kpc_config_t *configv __unused)
+{
+ return 0;
+}
+
+int
+kpc_get_configurable_config(kpc_config_t *configv __unused, uint64_t pmc_mask __unused)
+{
+ return 0;
+}
+
+int
+kpc_get_rawpmu_config(kpc_config_t *configv __unused)
+{
+ return 0;
+}
+
+uint64_t
+kpc_fixed_max(void)
+{
+ return 0;
+}
+
+uint64_t
+kpc_configurable_max(void)
+{
+ return 0;
+}
+
+int
+kpc_set_config_arch(struct kpc_config_remote *mp_config __unused)
+{
+ return ENOTSUP;
+}
+
+int
+kpc_set_period_arch(struct kpc_config_remote *mp_config __unused)
+{
+ return ENOTSUP;
+}
+
+int
+kpc_set_running_arch(struct kpc_running_remote *mp_config __unused)
+{
+ return ENOTSUP;
+}
diff --git a/xnu/files/osfmk/arm64/loader_return.c b/xnu/files/osfmk/arm64/loader_return.c
new file mode 100644
index 0000000..92aeaba
--- /dev/null
+++ b/xnu/files/osfmk/arm64/loader_return.c
@@ -0,0 +1,364 @@
+/*
+ * Return-to-loader debug channel.
+ *
+ * On hardware without a serial port there is no way to get the kernel log
+ * out. The XNU loader therefore leaves UEFI intact (no ExitBootServices) and
+ * publishes the physical address of a return stub in /chosen/loader-return.
+ * When the kernel has nothing more to do (panic, halt, timer) it collects its
+ * message buffer, the panic buffer and any kprintf output, maps the stub 1:1
+ * through TTBR0 and jumps to it with that log. The loader then restores the UEFI environment and writes
+ * the log to storage.
+ *
+ * Only valid while the kernel does not drive hardware that UEFI also uses.
+ */
+#include <mach/mach_types.h>
+#include <kern/debug.h>
+#include <kern/startup.h>
+#include <kern/thread_call.h>
+#include <kern/clock.h>
+#include <arm64/proc_reg.h>
+#include <pexpert/pexpert.h>
+#include <pexpert/arm64/board_config.h>
+
+/*
+ * The console log handed back to the loader. A long session writes more than fits, and both
+ * ends matter: the start of the boot is kept as it is, and of everything after it the most
+ * recent part (a ring); room is left for what is appended on the way out (the kernel message
+ * buffer, a panic's text). loader_log_linearize() puts the pieces in order before returning.
+ */
+#define LOADER_LOG_SIZE (1536 * 1024)
+#define LOADER_LOG_HEAD (256 * 1024)
+#define LOADER_LOG_RING (1024 * 1024)
+
+#if defined(GENERIC_GIC_V3_IRQ)
+extern void gic_v3_irq_quiesce(void);
+#endif
+
+void loader_log_putc(char c);
+void loader_return(void);
+void loader_checkpoint(uint64_t n);
+
+/* Also referenced from the early exception vector in start.s. */
+char loader_log[LOADER_LOG_SIZE];
+uint32_t loader_log_len;
+static bool loader_return_entered;
+
+/* One L1 table and one L2 table are enough to map a single 2 MB block. */
+static uint64_t loader_l1[512] __attribute__((aligned(4096)));
+static uint64_t loader_l2[512] __attribute__((aligned(4096)));
+
+static uint32_t loader_log_ring_at; /* where the next character goes in the ring */
+static bool loader_log_wrapped;
+static bool loader_log_linear; /* the pieces have been put in order: only appending from now on */
+static char loader_log_scratch[LOADER_LOG_RING];
+
+void
+loader_log_putc(char c)
+{
+ if (c == '\r') {
+ return;
+ }
+ if (loader_log_linear || loader_log_len < LOADER_LOG_HEAD) {
+ if (loader_log_len < LOADER_LOG_SIZE) {
+ loader_log[loader_log_len++] = c;
+ }
+ return;
+ }
+ loader_log[LOADER_LOG_HEAD + loader_log_ring_at] = c;
+ if (++loader_log_ring_at == LOADER_LOG_RING) {
+ loader_log_ring_at = 0;
+ loader_log_wrapped = true;
+ }
+ if (!loader_log_wrapped) {
+ loader_log_len = LOADER_LOG_HEAD + loader_log_ring_at;
+ }
+}
+
+/* Oldest first: the head, a note about what was dropped, then the ring from its oldest character. */
+static void
+loader_log_linearize(void)
+{
+ static const char note[] = "\n\n[... the log between the first 256 KB and the last 1 MB was dropped ...]\n\n";
+ uint32_t older = LOADER_LOG_RING - loader_log_ring_at, n = LOADER_LOG_HEAD;
+
+ if (loader_log_linear) {
+ return;
+ }
+ loader_log_linear = true;
+ if (!loader_log_wrapped) {
+ return;
+ }
+ __builtin_memcpy(loader_log_scratch, loader_log + LOADER_LOG_HEAD + loader_log_ring_at, older);
+ __builtin_memcpy(loader_log_scratch + older, loader_log + LOADER_LOG_HEAD, loader_log_ring_at);
+ /* the note takes the place of the oldest characters of the ring */
+ __builtin_memcpy(loader_log + n, note, sizeof(note) - 1);
+ n += sizeof(note) - 1;
+ __builtin_memcpy(loader_log + n, loader_log_scratch + sizeof(note) - 1, LOADER_LOG_RING - (sizeof(note) - 1));
+ loader_log_len = LOADER_LOG_HEAD + LOADER_LOG_RING;
+}
+
+/* Patched by the loader: { magic, PA of its return stub, checkpoint to stop at, PA - VA }. See start.s. */
+extern uint64_t loader_stub_slot[4];
+
+/*
+ * For a loader that watches from another processor core while the kernel runs (it starts the
+ * kernel on a core of its choice and stays on the first one): a sign of life, and where the log
+ * is, so that the log of a kernel that hangs -- or dies before it has said a word through any
+ * other channel -- is not lost with it. The loader finds this by its first word in the kernel
+ * it has loaded. The addresses are the kernel's virtual ones, filled in by the linker and so
+ * valid from the first instruction; the loader knows the distance to the physical ones.
+ */
+struct loader_live {
+ uint64_t magic; /* "XNULIVE!" */
+ uint64_t heartbeat; /* goes up every HV_WDT_PET_SECONDS while the kernel is alive */
+ const char *log; /* loader_log */
+ const uint32_t *log_len; /* how much of it is in use */
+ const uint32_t *log_ring_at; /* where the ring part is being written */
+ const bool *log_wrapped; /* the ring has gone round */
+ uint64_t log_head, log_ring; /* sizes of the two parts */
+ const uint64_t *recording; /* loader_recording: { physical address, length } of a screen recording */
+};
+
+/*
+ * A screen recording (the display driver makes one with boot-arg rec_secs): where it is, for the
+ * loader to hand to the host once the kernel is back. { physical address, bytes, kernel address }.
+ */
+uint64_t loader_recording[3];
+
+struct loader_live loader_live = {
+ .magic = 0x214556494c554e58ULL, .log = loader_log, .log_len = &loader_log_len, .log_ring_at = &loader_log_ring_at,
+ .log_wrapped = &loader_log_wrapped, .log_head = LOADER_LOG_HEAD, .log_ring = LOADER_LOG_RING,
+ .recording = loader_recording,
+};
+
+/* Valid from the first instruction of C code: does not depend on gVirtBase/gPhysBase being set up. */
+static inline uint64_t
+static_kvtophys(const void *va)
+{
+ return (uint64_t)va + loader_stub_slot[3];
+}
+
+/*
+ * Jump to the loader's return stub. reason: 0 = orderly end, 2 = checkpoint.
+ * Returns only if no loader is listening.
+ */
+static void
+loader_jump(uint64_t reason, uint64_t code)
+{
+#if ARM_PGSHIFT == 12
+ uint64_t stub = loader_stub_slot[1];
+ uint64_t tcr, t0sz;
+
+ if (stub == 0 || loader_return_entered) {
+ return;
+ }
+
+ tcr = __builtin_arm_rsr64("TCR_EL1");
+ t0sz = tcr & 0x3f;
+ /* The TTBR0 walk must start at L1 (1 GB per entry) and reach the stub. */
+ if (t0sz < 25 || t0sz > 33 || (stub >> (64 - t0sz)) != 0) {
+ return;
+ }
+ loader_return_entered = true;
+#if defined(GENERIC_GIC_V3_IRQ)
+ gic_v3_irq_quiesce();
+#endif
+
+ loader_l1[stub >> 30] = static_kvtophys(loader_l2) | ARM_TTE_TYPE_TABLE | ARM_TTE_VALID;
+ loader_l2[(stub >> 21) & 0x1ff] = (stub & ~0x1fffffULL) | ARM_TTE_VALID | ARM_TTE_TYPE_BLOCK |
+ ARM_TTE_BLOCK_AF | ARM_TTE_BLOCK_SH(SH_OUTER_MEMORY) | ARM_TTE_BLOCK_AP(AP_RWNA) |
+ ARM_TTE_BLOCK_ATTRINDX(CACHE_ATTRINDX_WRITEBACK);
+
+ /*
+ * The stub turns the MMU off, and on real hardware dirty cache lines do
+ * not survive that: write the log back to RAM first.
+ */
+ for (uintptr_t p = (uintptr_t)loader_log & ~63UL; p < (uintptr_t)loader_log + loader_log_len; p += 64) {
+ __asm__ volatile ("dc cvac, %0" : : "r" (p));
+ }
+ /* ... and a screen recording, and the note of where it is */
+ for (uintptr_t p = loader_recording[2] & ~63UL; p < loader_recording[2] + loader_recording[1]; p += 64) {
+ __asm__ volatile ("dc cvac, %0" : : "r" (p));
+ }
+ __asm__ volatile ("dc cvac, %0" : : "r" ((uintptr_t)loader_recording));
+ __asm__ volatile ("dc cvac, %0" : : "r" ((uintptr_t)loader_recording + 16));
+ __asm__ volatile ("dsb sy");
+
+ register uint64_t r_ttbr0 __asm__("x0") = static_kvtophys(loader_l1);
+ register uint64_t r_log __asm__("x2") = static_kvtophys(loader_log);
+ register uint64_t r_len __asm__("x3") = loader_log_len;
+ register uint64_t r_tcr __asm__("x4") = tcr;
+ register uint64_t r_stub __asm__("x5") = stub;
+ register uint64_t r_reason __asm__("x6") = reason;
+ register uint64_t r_code __asm__("x7") = code;
+
+ __asm__ volatile (
+ "msr DAIFSet, #0xf\n"
+ "bic x4, x4, #0x80\n" /* TCR_EL1.EPD0: allow TTBR0 walks */
+ "msr TCR_EL1, x4\n"
+ "msr TTBR0_EL1, x0\n"
+ "isb\n"
+ "tlbi vmalle1\n"
+ "dsb sy\n"
+ "isb\n"
+ "mov x0, x2\n"
+ "mov x1, x3\n"
+ "mov x2, x6\n"
+ "mov x3, x7\n"
+ "br x5\n"
+ : : "r" (r_ttbr0), "r" (r_log), "r" (r_len), "r" (r_tcr), "r" (r_stub), "r" (r_reason), "r" (r_code));
+ __builtin_unreachable();
+#else
+ (void)reason; (void)code;
+#endif /* ARM_PGSHIFT == 12 */
+}
+
+extern char *debug_buf_base, *debug_buf_ptr;
+
+/* bsd/sys/msgbuf.h (not includable from osfmk) */
+struct msgbuf {
+ int msg_magic;
+ int msg_size;
+ int msg_bufx; /* write pointer */
+ int msg_bufr; /* read pointer */
+ char *msg_bufc; /* buffer */
+};
+extern struct msgbuf *msgbufp;
+
+static void
+loader_log_puts(const char *s)
+{
+ for (; *s; s++) {
+ loader_log_putc(*s);
+ }
+}
+
+/*
+ * Everything printf()/IOLog()/os_log wrote ends up in the kernel message
+ * buffer (what dmesg shows), whether or not a console displayed it.
+ */
+static void
+loader_log_append_msgbuf(void)
+{
+ struct msgbuf *mb = msgbufp;
+
+ if (mb == NULL || mb->msg_bufc == NULL || mb->msg_size <= 0 || mb->msg_bufx < 0 || mb->msg_bufx > mb->msg_size) {
+ return;
+ }
+ loader_log_puts("\n--- kernel message buffer ---\n");
+ /* oldest data first: [bufx, size) is only meaningful once the buffer has wrapped */
+ for (int pass = 0; pass < 2; pass++) {
+ int from = pass == 0 ? mb->msg_bufx : 0;
+ int to = pass == 0 ? mb->msg_size : mb->msg_bufx;
+ for (int i = from; i < to; i++) {
+ if (mb->msg_bufc[i] != 0) {
+ loader_log_putc(mb->msg_bufc[i]);
+ }
+ }
+ }
+}
+
+void
+loader_return(void)
+{
+ /*
+ * A panic's text is first collected in the panic buffer and only later
+ * flushed to the console; if the console itself is what failed, that
+ * never happens. Append the buffer so the loader gets it either way.
+ */
+ loader_log_linearize();
+ if (!loader_return_entered) {
+ loader_log_append_msgbuf();
+ }
+ if (!loader_return_entered && debug_buf_base != NULL && debug_buf_ptr > debug_buf_base &&
+ (size_t)(debug_buf_ptr - debug_buf_base) < 256 * 1024) {
+ loader_log_puts("\n--- panic buffer ---\n");
+ for (const char *c = debug_buf_base; c < debug_buf_ptr; c++) {
+ loader_log_putc(*c);
+ }
+ }
+ loader_jump(0, 0);
+}
+
+/* Bring-up aid: stop here if the loader asked for checkpoint n. */
+void
+loader_checkpoint(uint64_t n)
+{
+ if (loader_stub_slot[2] == n) {
+ loader_jump(2, n);
+ }
+}
+
+/*
+ * boot-arg loader_return_after=<seconds>: hand control back to the loader
+ * after that long, whatever the kernel is doing. This is how the log gets out
+ * when the kernel does not panic but simply waits (e.g. for a root device).
+ */
+static void
+loader_return_timer(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
+{
+ static const char banner[] = "\n--- loader_return_after expired ---\n";
+ for (const char *c = banner; *c; c++) {
+ loader_log_putc(*c);
+ }
+ loader_return();
+}
+
+__startup_func
+static void
+loader_return_timer_init(void)
+{
+ uint32_t seconds = 0;
+ uint64_t deadline;
+
+ if (!PE_parse_boot_argn("loader_return_after", &seconds, sizeof(seconds)) || seconds == 0) {
+ return;
+ }
+ thread_call_t call = thread_call_allocate(loader_return_timer, NULL);
+ clock_interval_to_deadline(seconds, NSEC_PER_SEC, &deadline);
+ thread_call_enter_delayed(call, deadline);
+}
+STARTUP(EARLY_BOOT, STARTUP_RANK_LAST, loader_return_timer_init);
+
+/*
+ * boot-arg hv_wdt_pet=1: the loader has armed the Qualcomm hypervisor's
+ * virtual watchdog (it resets the phone when a kernel hangs, so that test
+ * runs need nobody at the device). Its timeout is at most 65 seconds; feed
+ * it from a timer so that a healthy kernel can run for as long as it likes.
+ */
+#define VIRT_WDT_PET 0x86000007u
+#define HV_WDT_PET_SECONDS 10
+
+static thread_call_t hv_wdt_call;
+static uint32_t hv_wdt_enabled;
+
+/* Every HV_WDT_PET_SECONDS: feed the watchdog if there is one, and show any watching loader a sign of life. */
+static void
+hv_wdt_pet(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
+{
+ uint64_t deadline;
+
+ if (hv_wdt_enabled) {
+ register uint64_t x0 __asm__("x0") = VIRT_WDT_PET;
+ register uint64_t x1 __asm__("x1") = 0;
+ register uint64_t x2 __asm__("x2") = 0;
+ register uint64_t x3 __asm__("x3") = 0;
+
+ __asm__ volatile ("smc #0" : "+r" (x0), "+r" (x1), "+r" (x2), "+r" (x3) : :
+ "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17");
+ }
+ loader_live.heartbeat++;
+
+ clock_interval_to_deadline(HV_WDT_PET_SECONDS, NSEC_PER_SEC, &deadline);
+ thread_call_enter_delayed(hv_wdt_call, deadline);
+}
+
+__startup_func
+static void
+hv_wdt_pet_init(void)
+{
+ PE_parse_boot_argn("hv_wdt_pet", &hv_wdt_enabled, sizeof(hv_wdt_enabled));
+ hv_wdt_call = thread_call_allocate(hv_wdt_pet, NULL);
+ hv_wdt_pet(NULL, NULL);
+}
+STARTUP(EARLY_BOOT, STARTUP_RANK_LAST, hv_wdt_pet_init);
diff --git a/xnu/files/osfmk/arm64/ppl/sart.h b/xnu/files/osfmk/arm64/ppl/sart.h
new file mode 100644
index 0000000..ced2c5f
--- /dev/null
+++ b/xnu/files/osfmk/arm64/ppl/sart.h
@@ -0,0 +1,11 @@
+/*
+ * Stand-in for a header Apple omits from the open-source XNU drop.
+ * SART is an Apple-SoC DMA filter; there is none on this platform.
+ */
+#ifndef _ARM64_PPL_SART_H_
+#define _ARM64_PPL_SART_H_
+static inline void
+sart_bootstrap(void)
+{
+}
+#endif /* _ARM64_PPL_SART_H_ */
diff --git a/xnu/files/osfmk/arm64/ppl/uat.h b/xnu/files/osfmk/arm64/ppl/uat.h
new file mode 100644
index 0000000..0ece76d
--- /dev/null
+++ b/xnu/files/osfmk/arm64/ppl/uat.h
@@ -0,0 +1,11 @@
+/*
+ * Stand-in for a header Apple omits from the open-source XNU drop.
+ * UAT is the Apple GPU address translator; there is none on this platform.
+ */
+#ifndef _ARM64_PPL_UAT_H_
+#define _ARM64_PPL_UAT_H_
+static inline void
+uat_bootstrap(void)
+{
+}
+#endif /* _ARM64_PPL_UAT_H_ */
diff --git a/xnu/files/osfmk/arm64/tunables/tunables.s b/xnu/files/osfmk/arm64/tunables/tunables.s
new file mode 100644
index 0000000..46f4b1d
--- /dev/null
+++ b/xnu/files/osfmk/arm64/tunables/tunables.s
@@ -0,0 +1,7 @@
+/*
+ * Stand-in for a file Apple omits from the open-source XNU drop.
+ * Apple's version applies per-SoC chicken-bit tunables keyed on MIDR;
+ * non-Apple cores need none.
+ */
+.macro APPLY_TUNABLES
+.endmacro
diff --git a/xnu/files/osfmk/arm64/user_exception_trace.c b/xnu/files/osfmk/arm64/user_exception_trace.c
new file mode 100644
index 0000000..72dab39
--- /dev/null
+++ b/xnu/files/osfmk/arm64/user_exception_trace.c
@@ -0,0 +1,300 @@
+/*
+ * Bring-up aid: with boot-arg systrace set, describe every fatal-looking
+ * exception a user thread takes, before it is delivered. There is no crash
+ * reporter in this system, so this is the only place a crash is recorded.
+ *
+ * Besides the registers it prints the shared cache slide (most crashes are
+ * inside system libraries: subtract the slide and look the address up in
+ * the cache with "ipsw dyld a2s"), any text a register points at (the
+ * library crash helpers leave their message in one) and the return
+ * addresses found by walking the frame pointers.
+ */
+
+#include <arm/thread.h>
+#include <kern/debug.h>
+#include <kern/misc_protos.h>
+#include <kern/startup.h>
+#include <kern/task.h>
+#include <kern/thread.h>
+#include <mach/exception_types.h>
+#include <mach/machine/thread_status.h>
+#include <string.h>
+#include <vm/vm_map.h>
+#include <vm/vm_shared_region.h>
+
+extern char *proc_name_address(struct proc *p);
+
+void user_exception_trace(exception_type_t exception, mach_exception_data_t code, mach_msg_type_number_t count, thread_t thread);
+
+static TUNABLE(uint32_t, user_exception_trace_enabled, "systrace", 0);
+
+static bool
+plausible_user_address(uint64_t address)
+{
+ return address >= 0x100000000ULL && address < MACH_VM_MAX_ADDRESS;
+}
+
+void
+user_exception_trace(exception_type_t exception, mach_exception_data_t code, mach_msg_type_number_t count, thread_t thread)
+{
+ static const unsigned message_registers[] = { 0, 1, 2, 3, 8, 16 };
+ const arm_saved_state_t *state;
+ vm_shared_region_t region;
+ uint64_t frame[2], fp;
+ uint32_t slide = 0;
+ task_t task;
+ struct proc *proc;
+
+ if (!user_exception_trace_enabled || thread != current_thread()) {
+ return;
+ }
+ if (exception != EXC_BAD_ACCESS && exception != EXC_BAD_INSTRUCTION && exception != EXC_ARITHMETIC &&
+ exception != EXC_BREAKPOINT) {
+ return;
+ }
+ task = get_threadtask(thread);
+ state = get_user_regs(thread);
+ if (task == kernel_task || state == NULL || !is_saved_state64(state)) {
+ return;
+ }
+ region = vm_shared_region_get(task);
+ if (region != NULL) {
+ slide = region->sr_slide;
+ vm_shared_region_deallocate(region);
+ }
+ proc = get_bsdtask_info(task);
+
+ printf("usertrap: %s[%d] exception %d code 0x%llx 0x%llx: pc 0x%llx lr 0x%llx sp 0x%llx, shared cache slide 0x%x\n",
+ proc ? proc_name_address(proc) : "?", proc ? proc_pid(proc) : -1, exception,
+ count > 0 ? (unsigned long long)code[0] : 0, count > 1 ? (unsigned long long)code[1] : 0,
+ (unsigned long long)get_saved_state_pc(state), (unsigned long long)get_saved_state_lr(state),
+ (unsigned long long)get_saved_state_sp(state), slide);
+
+ for (unsigned i = 0; i < sizeof(message_registers) / sizeof(message_registers[0]); i++) {
+ uint64_t value = (uint64_t)get_saved_state_reg(state, message_registers[i]);
+ char text[128];
+ vm_size_t length = 0;
+ bool printable = true;
+
+ if (!plausible_user_address(value)) {
+ continue;
+ }
+ bzero(text, sizeof(text));
+ (void)copyinstr((user_addr_t)value, text, sizeof(text) - 1, &length);
+ for (unsigned c = 0; c < 6; c++) {
+ printable = printable && text[c] >= 0x20 && text[c] < 0x7f;
+ }
+ if (printable) {
+ printf("usertrap: x%u -> \"%s\"\n", message_registers[i], text);
+ }
+ }
+
+ fp = (uint64_t)get_saved_state_fp(state);
+ for (int depth = 0; depth < 10 && plausible_user_address(fp) && (fp & 7) == 0; depth++) {
+ if (copyin((user_addr_t)fp, frame, sizeof(frame)) != 0) {
+ break;
+ }
+ printf("usertrap: called from 0x%llx\n", (unsigned long long)frame[1]);
+ if (frame[0] <= fp) {
+ break;
+ }
+ fp = frame[0];
+ }
+}
+
+/*
+ * A program calls abort(): say which, and from where. The reason is usually an exception nobody
+ * caught, or an assertion; the text of it goes to the program's standard error (boot-arg applog=1
+ * puts that on the console), the stack is here.
+ */
+void user_abort_trace(void);
+
+void
+user_abort_trace(void)
+{
+ thread_t thread = current_thread();
+ task_t task = get_threadtask(thread);
+ const arm_saved_state_t *state = get_user_regs(thread);
+ struct proc *proc = get_bsdtask_info(task);
+ vm_shared_region_t region;
+ uint64_t frame[2], fp;
+ uint32_t slide = 0;
+
+ if (task == kernel_task || state == NULL || !is_saved_state64(state)) {
+ return;
+ }
+ region = vm_shared_region_get(task);
+ if (region != NULL) {
+ slide = region->sr_slide;
+ vm_shared_region_deallocate(region);
+ }
+ printf("userabort: %s[%d] aborts, shared cache slide 0x%x; called from:", proc ? proc_name_address(proc) : "?",
+ proc ? proc_pid(proc) : -1, slide);
+ fp = (uint64_t)get_saved_state_fp(state);
+ for (int depth = 0; depth < 24 && plausible_user_address(fp) && (fp & 7) == 0; depth++) {
+ if (copyin((user_addr_t)fp, frame, sizeof(frame)) != 0) {
+ break;
+ }
+ printf(" 0x%llx", (unsigned long long)frame[1]);
+ if (frame[0] <= fp) {
+ break;
+ }
+ fp = frame[0];
+ }
+ printf("\n");
+}
+
+/*
+ * Boot-args ustacks=NAME ustacks_at=SECONDS [ustacks_ms=MILLISECONDS]: that long after boot
+ * (and then periodically) print where every thread of every process called NAME is -- pc, lr
+ * and the return addresses up the stack. Shows what a daemon that "does nothing" waits for.
+ * ustacks_now(NAME) does it at once: under QEMU, "qemu/touch.py stacks NAME" on the host.
+ * The addresses are symbolized on the host (qemu/symstack.py).
+ */
+#include <kern/thread_call.h>
+#include <kern/clock.h>
+#include <kern/queue.h>
+#include <pexpert/pexpert.h>
+
+extern queue_head_t tasks;
+extern lck_mtx_t tasks_threads_lock;
+
+#define USTACKS_MAX_THREADS 96
+#define USTACKS_MAX_FRAMES 14
+
+static char ustacks_name[32];
+static uint32_t ustacks_every;
+static thread_call_t ustacks_call;
+
+static void
+ustacks_task(task_t task, struct proc *proc)
+{
+ static struct {
+ uint64_t tid, pc, lr, fp;
+ } snap[USTACKS_MAX_THREADS];
+ vm_shared_region_t region;
+ vm_map_t map, old_map;
+ thread_t thread;
+ uint32_t slide = 0;
+ unsigned count = 0;
+
+ task_lock(task);
+ queue_iterate(&task->threads, thread, thread_t, task_threads) {
+ const arm_saved_state_t *state = get_user_regs(thread);
+
+ if (count == USTACKS_MAX_THREADS || state == NULL || !is_saved_state64(state)) {
+ continue;
+ }
+ snap[count].tid = thread_tid(thread);
+ snap[count].pc = get_saved_state_pc(state);
+ snap[count].lr = get_saved_state_lr(state);
+ snap[count].fp = get_saved_state_fp(state);
+ count++;
+ }
+ map = task->map;
+ if (map != VM_MAP_NULL) {
+ vm_map_reference(map);
+ }
+ task_unlock(task);
+ if (map == VM_MAP_NULL) {
+ return;
+ }
+ region = vm_shared_region_get(task);
+ if (region != NULL) {
+ slide = region->sr_slide;
+ vm_shared_region_deallocate(region);
+ }
+ clock_sec_t secs;
+ clock_usec_t usecs;
+
+ clock_get_system_microtime(&secs, &usecs);
+ printf("ustacks: %s[%d] %u threads, shared cache slide 0x%x, uptime %lu.%03u\n", proc_name_address(proc),
+ proc_pid(proc), count, slide, (unsigned long)secs, (unsigned)usecs / 1000);
+
+ old_map = vm_map_switch(map);
+ for (unsigned i = 0; i < count; i++) {
+ uint64_t frame[2], fp = snap[i].fp;
+
+ printf("ustacks: thread 0x%llx: 0x%llx 0x%llx", (unsigned long long)snap[i].tid,
+ (unsigned long long)snap[i].pc, (unsigned long long)snap[i].lr);
+ for (int depth = 0; depth < USTACKS_MAX_FRAMES && plausible_user_address(fp) && (fp & 7) == 0; depth++) {
+ if (copyin((user_addr_t)fp, frame, sizeof(frame)) != 0) {
+ break;
+ }
+ printf(" 0x%llx", (unsigned long long)frame[1]);
+ if (frame[0] <= fp) {
+ break;
+ }
+ fp = frame[0];
+ }
+ printf("\n");
+ }
+ vm_map_switch(old_map);
+ vm_map_deallocate(map);
+}
+
+static void
+ustacks_fire(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
+{
+ static task_t found[8];
+ unsigned count = 0;
+ task_t task;
+
+ lck_mtx_lock(&tasks_threads_lock);
+ queue_iterate(&tasks, task, task_t, tasks) {
+ struct proc *proc = get_bsdtask_info(task);
+
+ if (count < 8 && proc != NULL && strncmp(proc_name_address(proc), ustacks_name, sizeof(ustacks_name)) == 0) {
+ task_reference(task);
+ found[count++] = task;
+ }
+ }
+ lck_mtx_unlock(&tasks_threads_lock);
+ if (count == 0) {
+ printf("ustacks: no process called %s\n", ustacks_name);
+ }
+ for (unsigned i = 0; i < count; i++) {
+ struct proc *proc = get_bsdtask_info(found[i]);
+
+ if (proc != NULL) {
+ ustacks_task(found[i], proc);
+ }
+ task_deallocate(found[i]);
+ }
+ if (ustacks_every != 0) {
+ uint64_t deadline;
+
+ clock_interval_to_deadline(ustacks_every, NSEC_PER_MSEC, &deadline);
+ thread_call_enter_delayed(ustacks_call, deadline);
+ }
+}
+
+/* The same at once, for whoever asks (a debugging key sequence, see bsd/dev/redwood_virtio_input.c). */
+void ustacks_now(const char *name);
+
+void
+ustacks_now(const char *name)
+{
+ strlcpy(ustacks_name, name, sizeof(ustacks_name));
+ if (ustacks_call == NULL) {
+ ustacks_call = thread_call_allocate(ustacks_fire, NULL);
+ }
+ thread_call_enter(ustacks_call);
+}
+
+static void
+ustacks_init(void)
+{
+ uint32_t at = 0;
+ uint64_t deadline;
+
+ if (!PE_parse_boot_argn("ustacks", ustacks_name, sizeof(ustacks_name)) ||
+ !PE_parse_boot_argn("ustacks_at", &at, sizeof(at)) || at == 0) {
+ return;
+ }
+ PE_parse_boot_argn("ustacks_ms", &ustacks_every, sizeof(ustacks_every));
+ ustacks_call = thread_call_allocate(ustacks_fire, NULL);
+ clock_interval_to_deadline(at, NSEC_PER_SEC, &deadline);
+ thread_call_enter_delayed(ustacks_call, deadline);
+}
+STARTUP(EARLY_BOOT, STARTUP_RANK_LAST, ustacks_init);
diff --git a/xnu/files/osfmk/minicrypto/mc_aes.c b/xnu/files/osfmk/minicrypto/mc_aes.c
new file mode 100644
index 0000000..fd3d92c
--- /dev/null
+++ b/xnu/files/osfmk/minicrypto/mc_aes.c
@@ -0,0 +1,393 @@
+/*
+ * minicrypto: AES (FIPS 197) with ECB, CBC and CTR modes, in the descriptor
+ * format the kernel's crypto interface expects (struct ccmode_*).
+ *
+ * A compact byte-oriented implementation written from the specification; the
+ * S-boxes were generated from their definition. It is not constant-time and
+ * not fast: it exists so that kernel code which merely needs a block cipher
+ * at boot (the TCP stack keys an AES context during initialisation) works.
+ * Checked at boot against FIPS-197 / OpenSSL vectors (mc_aes_selftest).
+ *
+ * Not implemented: XTS, GCM.
+ */
+#include <corecrypto/ccmode.h>
+#include <corecrypto/ccmode_impl.h>
+#include <corecrypto/ccaes.h>
+#include <string.h>
+
+#include "minicrypto.h"
+
+static const uint8_t aes_sbox[256] = {
+ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
+ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
+ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
+ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
+ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
+ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
+ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
+ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
+ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
+ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
+ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
+ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
+ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
+ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
+ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
+ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
+};
+
+static const uint8_t aes_inv_sbox[256] = {
+ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
+ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
+ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
+ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
+ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
+ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
+ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
+ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
+ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
+ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
+ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
+ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
+ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
+ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
+ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
+ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d,
+};
+
+struct mc_aes_key {
+ uint32_t rounds;
+ uint8_t rk[240]; /* (rounds + 1) round keys of 16 bytes */
+};
+
+static inline uint8_t
+xtime(uint8_t x)
+{
+ return (uint8_t)((x << 1) ^ ((x >> 7) * 0x1b));
+}
+
+static inline uint8_t
+gmul(uint8_t a, uint8_t b)
+{
+ uint8_t p = 0;
+ while (b) {
+ if (b & 1) {
+ p ^= a;
+ }
+ a = xtime(a);
+ b >>= 1;
+ }
+ return p;
+}
+
+static int
+mc_aes_setkey(struct mc_aes_key *k, size_t key_len, const uint8_t *key)
+{
+ uint32_t nk = (uint32_t)key_len / 4;
+ uint8_t rcon = 1;
+
+ if (key_len != 16 && key_len != 24 && key_len != 32) {
+ return -1;
+ }
+ k->rounds = nk + 6;
+ memcpy(k->rk, key, key_len);
+ for (uint32_t i = nk; i < 4 * (k->rounds + 1); i++) {
+ uint8_t t[4];
+ memcpy(t, k->rk + 4 * (i - 1), 4);
+ if (i % nk == 0) {
+ uint8_t first = t[0];
+ t[0] = aes_sbox[t[1]] ^ rcon;
+ t[1] = aes_sbox[t[2]];
+ t[2] = aes_sbox[t[3]];
+ t[3] = aes_sbox[first];
+ rcon = xtime(rcon);
+ } else if (nk > 6 && i % nk == 4) {
+ for (int j = 0; j < 4; j++) {
+ t[j] = aes_sbox[t[j]];
+ }
+ }
+ for (int j = 0; j < 4; j++) {
+ k->rk[4 * i + j] = k->rk[4 * (i - nk) + j] ^ t[j];
+ }
+ }
+ return 0;
+}
+
+static void
+mc_aes_encrypt_block(const struct mc_aes_key *k, const uint8_t *in, uint8_t *out)
+{
+ uint8_t s[16], t[16];
+
+ for (int i = 0; i < 16; i++) {
+ s[i] = in[i] ^ k->rk[i];
+ }
+ for (uint32_t r = 1; r <= k->rounds; r++) {
+ /* SubBytes + ShiftRows (state is column-major: s[4*col + row]) */
+ for (int c = 0; c < 4; c++) {
+ for (int row = 0; row < 4; row++) {
+ t[4 * c + row] = aes_sbox[s[4 * ((c + row) & 3) + row]];
+ }
+ }
+ if (r != k->rounds) {
+ for (int c = 0; c < 4; c++) {
+ uint8_t *p = t + 4 * c;
+ uint8_t a0 = p[0], a1 = p[1], a2 = p[2], a3 = p[3];
+ p[0] = (uint8_t)(xtime(a0) ^ xtime(a1) ^ a1 ^ a2 ^ a3);
+ p[1] = (uint8_t)(a0 ^ xtime(a1) ^ xtime(a2) ^ a2 ^ a3);
+ p[2] = (uint8_t)(a0 ^ a1 ^ xtime(a2) ^ xtime(a3) ^ a3);
+ p[3] = (uint8_t)(xtime(a0) ^ a0 ^ a1 ^ a2 ^ xtime(a3));
+ }
+ }
+ for (int i = 0; i < 16; i++) {
+ s[i] = t[i] ^ k->rk[16 * r + i];
+ }
+ }
+ memcpy(out, s, 16);
+}
+
+static void
+mc_aes_decrypt_block(const struct mc_aes_key *k, const uint8_t *in, uint8_t *out)
+{
+ uint8_t s[16], t[16];
+
+ for (int i = 0; i < 16; i++) {
+ s[i] = in[i] ^ k->rk[16 * k->rounds + i];
+ }
+ for (uint32_t r = k->rounds; r-- > 0;) {
+ /* InvShiftRows + InvSubBytes */
+ for (int c = 0; c < 4; c++) {
+ for (int row = 0; row < 4; row++) {
+ t[4 * ((c + row) & 3) + row] = aes_inv_sbox[s[4 * c + row]];
+ }
+ }
+ for (int i = 0; i < 16; i++) {
+ t[i] ^= k->rk[16 * r + i];
+ }
+ if (r != 0) {
+ for (int c = 0; c < 4; c++) {
+ uint8_t *p = t + 4 * c;
+ uint8_t a0 = p[0], a1 = p[1], a2 = p[2], a3 = p[3];
+ p[0] = (uint8_t)(gmul(a0, 14) ^ gmul(a1, 11) ^ gmul(a2, 13) ^ gmul(a3, 9));
+ p[1] = (uint8_t)(gmul(a0, 9) ^ gmul(a1, 14) ^ gmul(a2, 11) ^ gmul(a3, 13));
+ p[2] = (uint8_t)(gmul(a0, 13) ^ gmul(a1, 9) ^ gmul(a2, 14) ^ gmul(a3, 11));
+ p[3] = (uint8_t)(gmul(a0, 11) ^ gmul(a1, 13) ^ gmul(a2, 9) ^ gmul(a3, 14));
+ }
+ }
+ memcpy(s, t, 16);
+ }
+ memcpy(out, s, 16);
+}
+
+/* ---------------------------------------------------------------- ECB --- */
+
+static int
+mc_ecb_init(const struct ccmode_ecb *ecb __unused, ccecb_ctx *ctx, size_t key_nbytes, const void *key)
+{
+ return mc_aes_setkey((struct mc_aes_key *)ctx, key_nbytes, key);
+}
+
+static int
+mc_ecb_encrypt(const ccecb_ctx *ctx, size_t nblocks, const void *in, void *out)
+{
+ const uint8_t *i = in;
+ uint8_t *o = out;
+ for (; nblocks > 0; nblocks--, i += 16, o += 16) {
+ mc_aes_encrypt_block((const struct mc_aes_key *)ctx, i, o);
+ }
+ return 0;
+}
+
+static int
+mc_ecb_decrypt(const ccecb_ctx *ctx, size_t nblocks, const void *in, void *out)
+{
+ const uint8_t *i = in;
+ uint8_t *o = out;
+ for (; nblocks > 0; nblocks--, i += 16, o += 16) {
+ mc_aes_decrypt_block((const struct mc_aes_key *)ctx, i, o);
+ }
+ return 0;
+}
+
+const struct ccmode_ecb mc_aes_ecb_encrypt = {
+ .size = sizeof(struct mc_aes_key),
+ .block_size = 16,
+ .init = mc_ecb_init,
+ .ecb = mc_ecb_encrypt,
+};
+
+const struct ccmode_ecb mc_aes_ecb_decrypt = {
+ .size = sizeof(struct mc_aes_key),
+ .block_size = 16,
+ .init = mc_ecb_init,
+ .ecb = mc_ecb_decrypt,
+};
+
+/* ---------------------------------------------------------------- CBC --- */
+
+static int
+mc_cbc_init(const struct ccmode_cbc *cbc __unused, cccbc_ctx *ctx, size_t key_len, const void *key)
+{
+ return mc_aes_setkey((struct mc_aes_key *)ctx, key_len, key);
+}
+
+static int
+mc_cbc_encrypt(const cccbc_ctx *ctx, cccbc_iv *iv, size_t nblocks, const void *in, void *out)
+{
+ const uint8_t *i = in;
+ uint8_t *o = out, *chain = (uint8_t *)iv;
+
+ for (; nblocks > 0; nblocks--, i += 16, o += 16) {
+ for (int b = 0; b < 16; b++) {
+ chain[b] ^= i[b];
+ }
+ mc_aes_encrypt_block((const struct mc_aes_key *)ctx, chain, chain);
+ memcpy(o, chain, 16);
+ }
+ return 0;
+}
+
+static int
+mc_cbc_decrypt(const cccbc_ctx *ctx, cccbc_iv *iv, size_t nblocks, const void *in, void *out)
+{
+ const uint8_t *i = in;
+ uint8_t *o = out, *chain = (uint8_t *)iv;
+
+ for (; nblocks > 0; nblocks--, i += 16, o += 16) {
+ uint8_t cipher[16], plain[16];
+ memcpy(cipher, i, 16); /* in and out may be the same buffer */
+ mc_aes_decrypt_block((const struct mc_aes_key *)ctx, cipher, plain);
+ for (int b = 0; b < 16; b++) {
+ o[b] = plain[b] ^ chain[b];
+ }
+ memcpy(chain, cipher, 16);
+ }
+ return 0;
+}
+
+const struct ccmode_cbc mc_aes_cbc_encrypt = {
+ .size = sizeof(struct mc_aes_key),
+ .block_size = 16,
+ .init = mc_cbc_init,
+ .cbc = mc_cbc_encrypt,
+};
+
+const struct ccmode_cbc mc_aes_cbc_decrypt = {
+ .size = sizeof(struct mc_aes_key),
+ .block_size = 16,
+ .init = mc_cbc_init,
+ .cbc = mc_cbc_decrypt,
+};
+
+/* ---------------------------------------------------------------- CTR --- */
+
+struct mc_aes_ctr {
+ struct mc_aes_key key;
+ uint8_t counter[16]; /* 128-bit big-endian counter */
+ uint8_t stream[16];
+ uint32_t used; /* bytes of stream[] already consumed */
+};
+
+static int
+mc_ctr_setctr(const struct ccmode_ctr *mode __unused, ccctr_ctx *ctx, const void *ctr)
+{
+ struct mc_aes_ctr *c = (struct mc_aes_ctr *)ctx;
+ memcpy(c->counter, ctr, 16);
+ c->used = 16;
+ return 0;
+}
+
+static int
+mc_ctr_init(const struct ccmode_ctr *mode, ccctr_ctx *ctx, size_t key_len, const void *key, const void *iv)
+{
+ struct mc_aes_ctr *c = (struct mc_aes_ctr *)ctx;
+ int rc = mc_aes_setkey(&c->key, key_len, key);
+ if (rc == 0) {
+ rc = mc_ctr_setctr(mode, ctx, iv);
+ }
+ return rc;
+}
+
+static int
+mc_ctr_crypt(ccctr_ctx *ctx, size_t nbytes, const void *in, void *out)
+{
+ struct mc_aes_ctr *c = (struct mc_aes_ctr *)ctx;
+ const uint8_t *i = in;
+ uint8_t *o = out;
+
+ for (; nbytes > 0; nbytes--) {
+ if (c->used == 16) {
+ mc_aes_encrypt_block(&c->key, c->counter, c->stream);
+ for (int b = 15; b >= 0 && ++c->counter[b] == 0; b--) {
+ }
+ c->used = 0;
+ }
+ *o++ = *i++ ^ c->stream[c->used++];
+ }
+ return 0;
+}
+
+const struct ccmode_ctr mc_aes_ctr_crypt = {
+ .size = sizeof(struct mc_aes_ctr),
+ .block_size = 1,
+ .ecb_block_size = 16,
+ .init = mc_ctr_init,
+ .setctr = mc_ctr_setctr,
+ .ctr = mc_ctr_crypt,
+};
+
+/* ---------------------------------------------------------- self test --- */
+
+/* Returns a description of the first failing check, or NULL if all pass. */
+const char *
+mc_aes_selftest(void)
+{
+ static const uint8_t key[32] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
+ static const uint8_t iv[16] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
+ static const uint8_t plain[48] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51 };
+ static const uint8_t ecb128[16] = { 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a }; /* FIPS 197 C.1 */
+ static const uint8_t ecb256[16] = { 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 }; /* FIPS 197 C.3 */
+ static const uint8_t cbc128[48] = { 0x77, 0x02, 0xfc, 0x9b, 0x71, 0xc6, 0x3d, 0x26, 0xa2, 0xf0, 0x9d, 0xf5, 0xc4, 0x45, 0x10, 0x2a, 0x12, 0x4e, 0x7d, 0x18, 0xd9, 0x0f, 0xb7, 0x68, 0x47, 0x71, 0xd3, 0xb9, 0x5b, 0x9b, 0x45, 0xcd, 0x56, 0x95, 0x95, 0xd6, 0xeb, 0x0c, 0x39, 0x43, 0x74, 0xf8, 0x70, 0x7e, 0xa5, 0x3e, 0xe7, 0x03 }; /* OpenSSL */
+ static const uint8_t ctr256[40] = { 0x92, 0x11, 0xef, 0xbe, 0x67, 0xc3, 0xe6, 0xbc, 0xd2, 0xf0, 0x4c, 0xef, 0x8c, 0xef, 0x8d, 0xeb, 0xa1, 0x9e, 0xc5, 0xa2, 0xdf, 0x6a, 0xab, 0x57, 0x87, 0x9a, 0x2b, 0x30, 0x39, 0xe4, 0x91, 0xa4, 0x37, 0x41, 0xab, 0x0c, 0x0a, 0x1b, 0x59, 0x04 }; /* OpenSSL */
+ struct mc_aes_key k;
+ struct mc_aes_ctr c;
+ uint8_t chain[16], out[48];
+
+ mc_aes_setkey(&k, 16, key);
+ mc_aes_encrypt_block(&k, plain, out);
+ if (memcmp(out, ecb128, 16) != 0) {
+ return "aes-128 encrypt";
+ }
+ mc_aes_decrypt_block(&k, ecb128, out);
+ if (memcmp(out, plain, 16) != 0) {
+ return "aes-128 decrypt";
+ }
+ mc_aes_setkey(&k, 32, key);
+ mc_aes_encrypt_block(&k, plain, out);
+ if (memcmp(out, ecb256, 16) != 0) {
+ return "aes-256 encrypt";
+ }
+ mc_aes_decrypt_block(&k, ecb256, out);
+ if (memcmp(out, plain, 16) != 0) {
+ return "aes-256 decrypt";
+ }
+
+ mc_aes_setkey(&k, 16, key);
+ memcpy(chain, iv, 16);
+ mc_cbc_encrypt((const cccbc_ctx *)&k, (cccbc_iv *)chain, 3, plain, out);
+ if (memcmp(out, cbc128, 48) != 0) {
+ return "aes-128-cbc encrypt";
+ }
+ memcpy(chain, iv, 16);
+ mc_cbc_decrypt((const cccbc_ctx *)&k, (cccbc_iv *)chain, 3, out, out); /* in place */
+ if (memcmp(out, plain, 48) != 0) {
+ return "aes-128-cbc decrypt";
+ }
+
+ mc_ctr_init(&mc_aes_ctr_crypt, (ccctr_ctx *)&c, 32, key, iv);
+ mc_ctr_crypt((ccctr_ctx *)&c, 7, plain, out); /* uneven pieces */
+ mc_ctr_crypt((ccctr_ctx *)&c, 33, plain + 7, out + 7);
+ if (memcmp(out, ctr256, 40) != 0) {
+ return "aes-256-ctr";
+ }
+ return NULL;
+}
diff --git a/xnu/files/osfmk/minicrypto/mc_digests.c b/xnu/files/osfmk/minicrypto/mc_digests.c
new file mode 100644
index 0000000..a207057
--- /dev/null
+++ b/xnu/files/osfmk/minicrypto/mc_digests.c
@@ -0,0 +1,410 @@
+/*
+ * minicrypto: message digests that the kernel's crypto interface needs but
+ * that are not part of the SHA-256-only "built-in corecrypto" shipped in the
+ * XNU sources: MD5, SHA-1, SHA-384 and SHA-512.
+ *
+ * Written from the public algorithm specifications (RFC 1321, FIPS 180-4).
+ * The constant tables were generated from their mathematical definitions.
+ * Plain portable C, no assembly; correctness is checked at boot against
+ * reference vectors (see mc_digest_selftest).
+ */
+#include <corecrypto/ccdigest.h>
+#include <corecrypto/ccdigest_priv.h>
+#include <corecrypto/cc_priv.h>
+#include <corecrypto/ccsha1.h>
+#include <corecrypto/ccsha2.h>
+#include <string.h>
+
+#include "minicrypto.h"
+
+/* from the kernel's built-in corecrypto subset (osfmk/corecrypto) */
+extern void ccdigest_final_64be(const struct ccdigest_info *di, ccdigest_ctx_t ctx, unsigned char *digest);
+
+#define ROL32(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
+#define ROR64(x, n) (((x) >> (n)) | ((x) << (64 - (n))))
+
+/* ---------------------------------------------------------------- MD5 --- */
+
+#define MD5_STATE_SIZE 16
+#define MD5_BLOCK_SIZE 64
+#define MD5_OUTPUT_SIZE 16
+
+static const uint32_t md5_initial_state[4] = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 };
+
+static const uint32_t md5_k[64] = {
+ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
+ 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
+ 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
+ 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
+ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
+ 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
+ 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
+ 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
+ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
+ 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
+ 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
+ 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
+ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
+ 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
+ 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
+ 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
+};
+
+static const uint8_t md5_s[64] = {
+ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
+ 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
+ 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
+ 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
+};
+
+static void
+md5_compress(ccdigest_state_t state, size_t nblocks, const void *in)
+{
+ uint32_t *s = ccdigest_u32(state);
+ const uint8_t *buf = in;
+
+ for (; nblocks > 0; nblocks--, buf += MD5_BLOCK_SIZE) {
+ uint32_t m[16], a = s[0], b = s[1], c = s[2], d = s[3];
+
+ for (int i = 0; i < 16; i++) {
+ m[i] = cc_load32_le(buf + 4 * i);
+ }
+ for (int i = 0; i < 64; i++) {
+ uint32_t f;
+ int g;
+ if (i < 16) {
+ f = (b & c) | (~b & d);
+ g = i;
+ } else if (i < 32) {
+ f = (d & b) | (~d & c);
+ g = (5 * i + 1) & 15;
+ } else if (i < 48) {
+ f = b ^ c ^ d;
+ g = (3 * i + 5) & 15;
+ } else {
+ f = c ^ (b | ~d);
+ g = (7 * i) & 15;
+ }
+ f += a + md5_k[i] + m[g];
+ a = d;
+ d = c;
+ c = b;
+ b += ROL32(f, md5_s[i]);
+ }
+ s[0] += a;
+ s[1] += b;
+ s[2] += c;
+ s[3] += d;
+ }
+}
+
+/* Finalisation for digests with a 64-byte block and a little-endian bit count. */
+static void
+mc_final_64le(const struct ccdigest_info *di, ccdigest_ctx_t ctx, unsigned char *digest)
+{
+ if (ccdigest_num(di, ctx) >= di->block_size) {
+ ccdigest_num(di, ctx) = 0;
+ }
+ ccdigest_di_decl(di, tmp);
+ memcpy(tmp, ctx, ccdigest_di_size(di));
+
+ ccdigest_nbits(di, tmp) += ccdigest_num(di, tmp) * 8;
+ ccdigest_data(di, tmp)[ccdigest_num(di, tmp)++] = 0x80;
+ if (ccdigest_num(di, tmp) > 64 - 8) {
+ while (ccdigest_num(di, tmp) < 64) {
+ ccdigest_data(di, tmp)[ccdigest_num(di, tmp)++] = 0;
+ }
+ di->compress(ccdigest_state(di, tmp), 1, ccdigest_data(di, tmp));
+ ccdigest_num(di, tmp) = 0;
+ }
+ while (ccdigest_num(di, tmp) < 64 - 8) {
+ ccdigest_data(di, tmp)[ccdigest_num(di, tmp)++] = 0;
+ }
+ uint64_t nbits = ccdigest_nbits(di, tmp);
+ cc_store32_le((uint32_t)nbits, ccdigest_data(di, tmp) + 56);
+ cc_store32_le((uint32_t)(nbits >> 32), ccdigest_data(di, tmp) + 60);
+ di->compress(ccdigest_state(di, tmp), 1, ccdigest_data(di, tmp));
+
+ for (unsigned int i = 0; i < di->output_size / 4; i++) {
+ cc_store32_le(ccdigest_state_u32(di, tmp)[i], digest + 4 * i);
+ }
+ ccdigest_di_clear(di, tmp);
+}
+
+const struct ccdigest_info mc_md5_di = {
+ .output_size = MD5_OUTPUT_SIZE,
+ .state_size = MD5_STATE_SIZE,
+ .block_size = MD5_BLOCK_SIZE,
+ .oid_size = 10,
+ .oid = CC_DIGEST_OID_MD5,
+ .initial_state = md5_initial_state,
+ .compress = md5_compress,
+ .final = mc_final_64le,
+};
+
+/* -------------------------------------------------------------- SHA-1 --- */
+
+static const uint32_t sha1_initial_state[5] = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 };
+
+static void
+sha1_compress(ccdigest_state_t state, size_t nblocks, const void *in)
+{
+ uint32_t *s = ccdigest_u32(state);
+ const uint8_t *buf = in;
+
+ for (; nblocks > 0; nblocks--, buf += CCSHA1_BLOCK_SIZE) {
+ uint32_t w[80], a = s[0], b = s[1], c = s[2], d = s[3], e = s[4];
+
+ for (int i = 0; i < 16; i++) {
+ w[i] = cc_load32_be(buf + 4 * i);
+ }
+ for (int i = 16; i < 80; i++) {
+ w[i] = ROL32(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
+ }
+ for (int i = 0; i < 80; i++) {
+ uint32_t f, k;
+ if (i < 20) {
+ f = (b & c) | (~b & d);
+ k = 0x5a827999;
+ } else if (i < 40) {
+ f = b ^ c ^ d;
+ k = 0x6ed9eba1;
+ } else if (i < 60) {
+ f = (b & c) | (b & d) | (c & d);
+ k = 0x8f1bbcdc;
+ } else {
+ f = b ^ c ^ d;
+ k = 0xca62c1d6;
+ }
+ uint32_t t = ROL32(a, 5) + f + e + k + w[i];
+ e = d;
+ d = c;
+ c = ROL32(b, 30);
+ b = a;
+ a = t;
+ }
+ s[0] += a;
+ s[1] += b;
+ s[2] += c;
+ s[3] += d;
+ s[4] += e;
+ }
+}
+
+const struct ccdigest_info mc_sha1_di = {
+ .output_size = CCSHA1_OUTPUT_SIZE,
+ .state_size = CCSHA1_STATE_SIZE,
+ .block_size = CCSHA1_BLOCK_SIZE,
+ .oid_size = ccoid_sha1_len,
+ .oid = CC_DIGEST_OID_SHA1,
+ .initial_state = sha1_initial_state,
+ .compress = sha1_compress,
+ .final = ccdigest_final_64be,
+};
+
+/* ------------------------------------------------- SHA-512 / SHA-384 --- */
+
+static const uint64_t sha512_initial_state[8] = {
+ 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
+ 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
+ 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
+ 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL,
+};
+
+static const uint64_t sha384_initial_state[8] = {
+ 0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL,
+ 0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL,
+ 0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL,
+ 0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL,
+};
+
+static const uint64_t sha512_k[80] = {
+ 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
+ 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
+ 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
+ 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
+ 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
+ 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
+ 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
+ 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
+ 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
+ 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
+ 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
+ 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
+ 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
+ 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
+ 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
+ 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
+ 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
+ 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
+ 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
+ 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
+ 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
+ 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
+ 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
+ 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
+ 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
+ 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
+ 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
+ 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
+ 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
+ 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
+ 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
+ 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
+ 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
+ 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
+ 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
+ 0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
+ 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
+ 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
+ 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
+ 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL,
+};
+
+static void
+sha512_compress(ccdigest_state_t state, size_t nblocks, const void *in)
+{
+ uint64_t *s = ccdigest_u64(state);
+ const uint8_t *buf = in;
+
+ for (; nblocks > 0; nblocks--, buf += CCSHA512_BLOCK_SIZE) {
+ uint64_t w[80], v[8];
+
+ for (int i = 0; i < 16; i++) {
+ w[i] = cc_load64_be(buf + 8 * i);
+ }
+ for (int i = 16; i < 80; i++) {
+ uint64_t s0 = ROR64(w[i - 15], 1) ^ ROR64(w[i - 15], 8) ^ (w[i - 15] >> 7);
+ uint64_t s1 = ROR64(w[i - 2], 19) ^ ROR64(w[i - 2], 61) ^ (w[i - 2] >> 6);
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1;
+ }
+ memcpy(v, s, sizeof(v));
+ for (int i = 0; i < 80; i++) {
+ uint64_t S1 = ROR64(v[4], 14) ^ ROR64(v[4], 18) ^ ROR64(v[4], 41);
+ uint64_t ch = (v[4] & v[5]) ^ (~v[4] & v[6]);
+ uint64_t t1 = v[7] + S1 + ch + sha512_k[i] + w[i];
+ uint64_t S0 = ROR64(v[0], 28) ^ ROR64(v[0], 34) ^ ROR64(v[0], 39);
+ uint64_t maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
+ uint64_t t2 = S0 + maj;
+ v[7] = v[6];
+ v[6] = v[5];
+ v[5] = v[4];
+ v[4] = v[3] + t1;
+ v[3] = v[2];
+ v[2] = v[1];
+ v[1] = v[0];
+ v[0] = t1 + t2;
+ }
+ for (int i = 0; i < 8; i++) {
+ s[i] += v[i];
+ }
+ }
+}
+
+/* Finalisation for 128-byte-block digests with a 128-bit big-endian bit count. */
+static void
+mc_final_128be(const struct ccdigest_info *di, ccdigest_ctx_t ctx, unsigned char *digest)
+{
+ if (ccdigest_num(di, ctx) >= di->block_size) {
+ ccdigest_num(di, ctx) = 0;
+ }
+ ccdigest_di_decl(di, tmp);
+ memcpy(tmp, ctx, ccdigest_di_size(di));
+
+ ccdigest_nbits(di, tmp) += ccdigest_num(di, tmp) * 8;
+ ccdigest_data(di, tmp)[ccdigest_num(di, tmp)++] = 0x80;
+ if (ccdigest_num(di, tmp) > 128 - 16) {
+ while (ccdigest_num(di, tmp) < 128) {
+ ccdigest_data(di, tmp)[ccdigest_num(di, tmp)++] = 0;
+ }
+ di->compress(ccdigest_state(di, tmp), 1, ccdigest_data(di, tmp));
+ ccdigest_num(di, tmp) = 0;
+ }
+ while (ccdigest_num(di, tmp) < 128 - 8) {
+ ccdigest_data(di, tmp)[ccdigest_num(di, tmp)++] = 0;
+ }
+ cc_store64_be(ccdigest_nbits(di, tmp), ccdigest_data(di, tmp) + 128 - 8);
+ di->compress(ccdigest_state(di, tmp), 1, ccdigest_data(di, tmp));
+
+ for (unsigned int i = 0; i < di->output_size / 8; i++) {
+ cc_store64_be(ccdigest_state_u64(di, tmp)[i], digest + 8 * i);
+ }
+ ccdigest_di_clear(di, tmp);
+}
+
+const struct ccdigest_info mc_sha512_di = {
+ .output_size = CCSHA512_OUTPUT_SIZE,
+ .state_size = CCSHA512_STATE_SIZE,
+ .block_size = CCSHA512_BLOCK_SIZE,
+ .oid_size = ccoid_sha512_len,
+ .oid = CC_DIGEST_OID_SHA512,
+ .initial_state = sha512_initial_state,
+ .compress = sha512_compress,
+ .final = mc_final_128be,
+};
+
+const struct ccdigest_info mc_sha384_di = {
+ .output_size = CCSHA384_OUTPUT_SIZE,
+ .state_size = CCSHA512_STATE_SIZE,
+ .block_size = CCSHA512_BLOCK_SIZE,
+ .oid_size = ccoid_sha384_len,
+ .oid = CC_DIGEST_OID_SHA384,
+ .initial_state = sha384_initial_state,
+ .compress = sha512_compress,
+ .final = mc_final_128be,
+};
+
+/* ---------------------------------------------------------- self test --- */
+
+void
+mc_digest(const struct ccdigest_info *di, size_t len, const void *data, void *digest)
+{
+ ccdigest_di_decl(di, ctx);
+ ccdigest_init(di, ctx);
+ ccdigest_update(di, ctx, len, data);
+ di->final(di, ctx, digest);
+ ccdigest_di_clear(di, ctx);
+}
+
+/* Reference digests of "abc" and of the 300-byte pattern msg[i] = 7*i + 3 (computed with OpenSSL). */
+static const struct mc_vector {
+ const struct ccdigest_info *di;
+ const char *name;
+ uint8_t abc[64];
+ uint8_t pattern[64];
+} mc_vectors[] = {
+ { &mc_md5_di, "md5", { 0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, 0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72 }, { 0x3e, 0xa7, 0x4b, 0x65, 0x67, 0x3e, 0x13, 0x90, 0xb9, 0x0d, 0xa3, 0xe4, 0x62, 0xc0, 0x2f, 0x9f } },
+ { &mc_sha1_di, "sha1", { 0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a, 0xba, 0x3e, 0x25, 0x71, 0x78, 0x50, 0xc2, 0x6c, 0x9c, 0xd0, 0xd8, 0x9d }, { 0x2b, 0x49, 0x8a, 0x21, 0x77, 0xb1, 0x81, 0xad, 0x0e, 0x5e, 0xdd, 0xbd, 0x5c, 0xb5, 0x8b, 0x8d, 0x52, 0xcf, 0x69, 0x41 } },
+ { &mc_sha384_di, "sha384", { 0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b, 0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07, 0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63, 0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed, 0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23, 0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7 }, { 0x06, 0x0e, 0xb8, 0xe1, 0xc0, 0x1c, 0xc6, 0xc6, 0xc8, 0xc0, 0x3f, 0xcb, 0x78, 0x98, 0x15, 0x5f, 0x2b, 0x83, 0x6f, 0xb9, 0x7c, 0x9d, 0x33, 0x1a, 0x7a, 0x29, 0x6a, 0x1a, 0x20, 0x9a, 0xac, 0x9d, 0x26, 0x1b, 0x2b, 0x26, 0x8c, 0x4b, 0xa3, 0xc7, 0x29, 0x9a, 0x3d, 0xd1, 0x2b, 0x5b, 0xf8, 0x1f } },
+ { &mc_sha512_di, "sha512", { 0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31, 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a, 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd, 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e, 0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f }, { 0x46, 0xe5, 0x6a, 0xd3, 0x0d, 0xb9, 0xef, 0x50, 0xf8, 0xb6, 0x76, 0x2b, 0xa5, 0x58, 0x39, 0x73, 0x7f, 0x3f, 0xba, 0x34, 0xab, 0x47, 0x86, 0x3c, 0x9d, 0xaf, 0xf7, 0xb3, 0xf5, 0x8f, 0x97, 0xfe, 0x34, 0x65, 0xa5, 0x2d, 0xd3, 0x64, 0x56, 0x0d, 0xb4, 0x7f, 0x80, 0x29, 0x09, 0xce, 0xd4, 0x90, 0x93, 0x32, 0x26, 0x21, 0xea, 0x0a, 0xeb, 0xf8, 0xe0, 0x69, 0x6b, 0x85, 0xca, 0x8f, 0x81, 0xf0 } },
+};
+
+/* Returns the name of the first digest that fails, or NULL if all pass. */
+const char *
+mc_digest_selftest(void)
+{
+ uint8_t pattern[300], out[64];
+
+ for (unsigned i = 0; i < sizeof(pattern); i++) {
+ pattern[i] = (uint8_t)(i * 7 + 3);
+ }
+ for (unsigned v = 0; v < sizeof(mc_vectors) / sizeof(mc_vectors[0]); v++) {
+ const struct mc_vector *vec = &mc_vectors[v];
+
+ mc_digest(vec->di, 3, "abc", out);
+ if (memcmp(out, vec->abc, vec->di->output_size) != 0) {
+ return vec->name;
+ }
+ /* feed the pattern in uneven pieces to exercise the buffering */
+ ccdigest_di_decl(vec->di, ctx);
+ ccdigest_init(vec->di, ctx);
+ ccdigest_update(vec->di, ctx, 1, pattern);
+ ccdigest_update(vec->di, ctx, 130, pattern + 1);
+ ccdigest_update(vec->di, ctx, 169, pattern + 131);
+ vec->di->final(vec->di, ctx, out);
+ if (memcmp(out, vec->pattern, vec->di->output_size) != 0) {
+ return vec->name;
+ }
+ }
+ return NULL;
+}
diff --git a/xnu/files/osfmk/minicrypto/mc_provider.c b/xnu/files/osfmk/minicrypto/mc_provider.c
new file mode 100644
index 0000000..8a272c0
--- /dev/null
+++ b/xnu/files/osfmk/minicrypto/mc_provider.c
@@ -0,0 +1,470 @@
+/*
+ * minicrypto provider: registers a crypto backend with the kernel in place
+ * of Apple's corecrypto kext (com.apple.kec.corecrypto), which is not part
+ * of the open-source release and cannot be loaded into this static kernel.
+ *
+ * Provided:
+ * - digests: MD5, SHA-1, SHA-256 (the kernel's built-in), SHA-384, SHA-512
+ * - HMAC over those digests
+ * - the kernel PRNG, an HMAC-DRBG (SHA-256) seeded from the boot seed and
+ * reseeded from the kernel entropy collector
+ * - the small non-cryptographic generator the VM layer asks for
+ *
+ * - AES in ECB, CBC and CTR modes (mc_aes.c; the TCP stack needs it at boot)
+ *
+ * NOT provided (function pointers left NULL; using them will fault): AES-XTS,
+ * AES-GCM, DES/3DES, ChaCha20-Poly1305, RSA. Encrypted volumes, IPsec and
+ * signature checks need those; the boot path to a ramdisk shell does not.
+ */
+#include <mach/mach_types.h>
+#include <kern/debug.h>
+#include <kern/startup.h>
+#include <kern/simple_lock.h>
+#include <machine/machine_routines.h>
+#include <libkern/crypto/register_crypto.h>
+#include <libkern/crypto/rand.h>
+#include <corecrypto/cc_priv.h>
+#include <corecrypto/ccdigest.h>
+#include <corecrypto/ccdrbg.h>
+#include <corecrypto/cchmac.h>
+#include <corecrypto/cckprng.h>
+#include <corecrypto/ccrng.h>
+#include <corecrypto/ccsha2.h>
+#include <prng/random.h>
+#include <string.h>
+
+#include "minicrypto.h"
+
+#ifndef MIN
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+#endif
+
+extern void read_random(void *buffer, u_int numBytes);
+extern int printf(const char *format, ...) __printflike(1, 2);
+
+/* ------------------------------------------------------- kernel PRNG --- */
+
+static struct {
+ struct ccdrbg_info info;
+ struct ccdrbg_nisthmac_custom custom;
+ uint8_t state[512];
+ cckprng_getentropy getentropy;
+ void *getentropy_arg;
+ bool ready;
+ simple_lock_data_t lock;
+} mc_prng;
+
+static boolean_t
+mc_prng_lock(void)
+{
+ boolean_t intr = ml_set_interrupts_enabled(FALSE);
+ simple_lock(&mc_prng.lock, LCK_GRP_NULL);
+ return intr;
+}
+
+static void
+mc_prng_unlock(boolean_t intr)
+{
+ simple_unlock(&mc_prng.lock);
+ ml_set_interrupts_enabled(intr);
+}
+
+static void
+mc_prng_init_with_getentropy(struct cckprng_ctx *ctx __unused, unsigned max_ngens __unused, size_t seed_nbytes,
+ const void *seed, size_t nonce_nbytes, const void *nonce, cckprng_getentropy getentropy, void *getentropy_arg)
+{
+ static const char ps[] = "xnu minicrypto kernel prng";
+
+ simple_lock_init(&mc_prng.lock, 0);
+ mc_prng.custom.di = &ccsha256_ltc_di;
+ mc_prng.custom.strictFIPS = 0;
+ ccdrbg_factory_nisthmac(&mc_prng.info, &mc_prng.custom);
+ if (mc_prng.info.size > sizeof(mc_prng.state)) {
+ panic("minicrypto: DRBG state does not fit (%zu)", mc_prng.info.size);
+ }
+ int rc = ccdrbg_init(&mc_prng.info, (struct ccdrbg_state *)mc_prng.state, seed_nbytes, seed, nonce_nbytes, nonce,
+ sizeof(ps) - 1, ps);
+ if (rc != CCDRBG_STATUS_OK) {
+ panic("minicrypto: ccdrbg_init failed (%d)", rc);
+ }
+ mc_prng.getentropy = getentropy;
+ mc_prng.getentropy_arg = getentropy_arg;
+ mc_prng.ready = true;
+}
+
+static void
+mc_prng_init(struct cckprng_ctx *ctx, size_t seed_nbytes, const void *seed, size_t nonce_nbytes, const void *nonce,
+ cckprng_getentropy getentropy, void *getentropy_arg)
+{
+ mc_prng_init_with_getentropy(ctx, 1, seed_nbytes, seed, nonce_nbytes, nonce, getentropy, getentropy_arg);
+}
+
+static void
+mc_prng_initgen(struct cckprng_ctx *ctx __unused, unsigned gen_idx __unused)
+{
+ /* one generator shared by all CPUs */
+}
+
+/* Mix caller-supplied bytes into the generator (HMAC-DRBG "additional input"). */
+static void
+mc_prng_reseed(struct cckprng_ctx *ctx __unused, size_t nbytes, const void *seed)
+{
+ uint8_t discard[32];
+
+ if (!mc_prng.ready || nbytes == 0) {
+ return;
+ }
+ boolean_t intr = mc_prng_lock();
+ (void)ccdrbg_generate(&mc_prng.info, (struct ccdrbg_state *)mc_prng.state, sizeof(discard), discard, nbytes, seed);
+ mc_prng_unlock(intr);
+ cc_clear(sizeof(discard), discard);
+}
+
+/* Pull whatever the kernel entropy collector has accumulated and mix it in. */
+static void
+mc_prng_refresh(struct cckprng_ctx *ctx)
+{
+ uint8_t entropy[CCKPRNG_ENTROPY_SIZE];
+ size_t nbytes = sizeof(entropy);
+
+ if (!mc_prng.ready || mc_prng.getentropy == NULL) {
+ return;
+ }
+ if (mc_prng.getentropy(&nbytes, entropy, mc_prng.getentropy_arg) > 0 && nbytes > 0) {
+ mc_prng_reseed(ctx, nbytes, entropy);
+ }
+ cc_clear(sizeof(entropy), entropy);
+}
+
+static void
+mc_prng_generate(struct cckprng_ctx *ctx __unused, unsigned gen_idx __unused, size_t nbytes, void *out)
+{
+ uint8_t *p = out;
+
+ while (nbytes > 0) {
+ size_t n = MIN(nbytes, (size_t)1024);
+ boolean_t intr = mc_prng_lock();
+ int rc = ccdrbg_generate(&mc_prng.info, (struct ccdrbg_state *)mc_prng.state, n, p, 0, NULL);
+ mc_prng_unlock(intr);
+ if (rc != CCDRBG_STATUS_OK) {
+ panic("minicrypto: ccdrbg_generate failed (%d)", rc);
+ }
+ p += n;
+ nbytes -= n;
+ }
+}
+
+static const struct cckprng_funcs mc_prng_funcs = {
+ .init = mc_prng_init,
+ .initgen = mc_prng_initgen,
+ .reseed = mc_prng_reseed,
+ .refresh = mc_prng_refresh,
+ .generate = mc_prng_generate,
+ .init_with_getentropy = mc_prng_init_with_getentropy,
+};
+
+/* ccrng handle: random bytes straight from the kernel PRNG. */
+static int
+mc_rng_generate(struct ccrng_state *rng __unused, size_t outlen, void *out)
+{
+ read_random(out, (u_int)outlen);
+ return 0;
+}
+
+static struct ccrng_state mc_rng_state = { .generate = mc_rng_generate };
+
+static struct ccrng_state *
+mc_ccrng(int *error)
+{
+ if (error != NULL) {
+ *error = 0;
+ }
+ return &mc_rng_state;
+}
+
+/* ------------------------------------- lock-free generator for kmem --- */
+/* xoshiro256**: fast, no locks, explicitly not cryptographic (see rand.h). */
+
+struct mc_random_ctx {
+ uint64_t s[4];
+};
+
+static inline uint64_t
+mc_rotl(uint64_t x, int k)
+{
+ return (x << k) | (x >> (64 - k));
+}
+
+static uint64_t
+mc_random_next(struct mc_random_ctx *r)
+{
+ uint64_t result = mc_rotl(r->s[1] * 5, 7) * 9;
+ uint64_t t = r->s[1] << 17;
+
+ r->s[2] ^= r->s[0];
+ r->s[3] ^= r->s[1];
+ r->s[1] ^= r->s[2];
+ r->s[0] ^= r->s[3];
+ r->s[2] ^= t;
+ r->s[3] = mc_rotl(r->s[3], 45);
+ return result;
+}
+
+static size_t
+mc_random_kmem_ctx_size(void)
+{
+ return sizeof(struct mc_random_ctx);
+}
+
+static void
+mc_random_kmem_init(crypto_random_ctx_t ctx)
+{
+ struct mc_random_ctx *r = ctx;
+
+ read_random(r->s, sizeof(r->s));
+ r->s[0] |= 1; /* the all-zero state is invalid */
+}
+
+static void
+mc_random_generate(crypto_random_ctx_t ctx, void *random, size_t random_size)
+{
+ uint8_t *p = random;
+
+ while (random_size > 0) {
+ uint64_t v = mc_random_next(ctx);
+ size_t n = MIN(random_size, sizeof(v));
+ memcpy(p, &v, n);
+ p += n;
+ random_size -= n;
+ }
+}
+
+static void
+mc_random_uniform(crypto_random_ctx_t ctx, uint64_t bound, uint64_t *random)
+{
+ if (bound < 2) {
+ *random = 0;
+ return;
+ }
+ /* rejection sampling keeps the distribution flat */
+ uint64_t limit = UINT64_MAX - (UINT64_MAX % bound);
+ uint64_t v;
+ do {
+ v = mc_random_next(ctx);
+ } while (v >= limit);
+ *random = v % bound;
+}
+
+/* ---------------------------------------- generic digest / HMAC API --- */
+
+static const struct ccdigest_info *
+mc_di(crypto_digest_alg_t alg)
+{
+ switch (alg) {
+ case CRYPTO_DIGEST_ALG_MD5:
+ return &mc_md5_di;
+ case CRYPTO_DIGEST_ALG_SHA1:
+ return &mc_sha1_di;
+ case CRYPTO_DIGEST_ALG_SHA256:
+ return ccsha256_di();
+ case CRYPTO_DIGEST_ALG_SHA384:
+ return &mc_sha384_di;
+ case CRYPTO_DIGEST_ALG_SHA512:
+ return &mc_sha512_di;
+ default:
+ panic("minicrypto: unsupported digest algorithm %d", (int)alg);
+ }
+}
+
+static void
+mc_ccdigest_final(const struct ccdigest_info *di, ccdigest_ctx_t ctx, void *digest)
+{
+ di->final(di, ctx, digest);
+}
+
+static void
+mc_ccdigest(const struct ccdigest_info *di, unsigned long len, const void *data, void *digest)
+{
+ mc_digest(di, len, data, digest);
+}
+
+static size_t
+mc_digest_ctx_size(crypto_digest_alg_t alg)
+{
+ return ccdigest_di_size(mc_di(alg));
+}
+
+static void
+mc_digest_init(crypto_digest_alg_t alg, void *ctx, size_t ctx_size __unused)
+{
+ ccdigest_init(mc_di(alg), ctx);
+}
+
+static void
+mc_digest_update(crypto_digest_alg_t alg, void *ctx, size_t ctx_size __unused, const void *data, size_t data_size)
+{
+ ccdigest_update(mc_di(alg), ctx, data_size, data);
+}
+
+static void
+mc_digest_final(crypto_digest_alg_t alg, void *ctx, size_t ctx_size __unused, void *digest, size_t digest_size)
+{
+ const struct ccdigest_info *di = mc_di(alg);
+ uint8_t out[64];
+
+ di->final(di, ctx, out);
+ memcpy(digest, out, MIN(digest_size, di->output_size));
+}
+
+static void
+mc_digest_oneshot(crypto_digest_alg_t alg, const void *data, size_t data_size, void *digest, size_t digest_size)
+{
+ const struct ccdigest_info *di = mc_di(alg);
+ uint8_t out[64];
+
+ mc_digest(di, data_size, data, out);
+ memcpy(digest, out, MIN(digest_size, di->output_size));
+}
+
+static size_t
+mc_hmac_ctx_size(crypto_digest_alg_t alg)
+{
+ return cchmac_di_size(mc_di(alg));
+}
+
+static void
+mc_hmac_init(crypto_digest_alg_t alg, void *ctx, size_t ctx_size __unused, const void *key, size_t key_size)
+{
+ cchmac_init(mc_di(alg), ctx, key_size, key);
+}
+
+static void
+mc_hmac_update(crypto_digest_alg_t alg, void *ctx, size_t ctx_size __unused, const void *data, size_t data_size)
+{
+ cchmac_update(mc_di(alg), ctx, data_size, data);
+}
+
+static void
+mc_hmac_final_generate(crypto_digest_alg_t alg, void *ctx, size_t ctx_size __unused, void *tag, size_t tag_size)
+{
+ const struct ccdigest_info *di = mc_di(alg);
+ uint8_t out[64];
+
+ cchmac_final(di, ctx, out);
+ memcpy(tag, out, MIN(tag_size, di->output_size));
+ cc_clear(sizeof(out), out);
+}
+
+static bool
+mc_hmac_final_verify(crypto_digest_alg_t alg, void *ctx, size_t ctx_size __unused, const void *tag, size_t tag_size)
+{
+ const struct ccdigest_info *di = mc_di(alg);
+ uint8_t out[64];
+
+ if (tag_size == 0 || tag_size > di->output_size) {
+ return false;
+ }
+ cchmac_final(di, ctx, out);
+ bool ok = (cc_cmp_safe(tag_size, out, tag) == 0);
+ cc_clear(sizeof(out), out);
+ return ok;
+}
+
+static void
+mc_hmac_generate(crypto_digest_alg_t alg, const void *key, size_t key_size, const void *data, size_t data_size,
+ void *tag, size_t tag_size)
+{
+ const struct ccdigest_info *di = mc_di(alg);
+ uint8_t out[64];
+
+ cchmac(di, key_size, key, data_size, data, out);
+ memcpy(tag, out, MIN(tag_size, di->output_size));
+ cc_clear(sizeof(out), out);
+}
+
+static bool
+mc_hmac_verify(crypto_digest_alg_t alg, const void *key, size_t key_size, const void *data, size_t data_size,
+ const void *tag, size_t tag_size)
+{
+ const struct ccdigest_info *di = mc_di(alg);
+ uint8_t out[64];
+
+ if (tag_size == 0 || tag_size > di->output_size) {
+ return false;
+ }
+ cchmac(di, key_size, key, data_size, data, out);
+ bool ok = (cc_cmp_safe(tag_size, out, tag) == 0);
+ cc_clear(sizeof(out), out);
+ return ok;
+}
+
+/* ------------------------------------------------------ registration --- */
+
+static struct crypto_functions mc_funcs = {
+ .ccdigest_init_fn = ccdigest_init,
+ .ccdigest_update_fn = ccdigest_update,
+ .ccdigest_final_fn = mc_ccdigest_final,
+ .ccdigest_fn = mc_ccdigest,
+ .ccmd5_di = &mc_md5_di,
+ .ccsha1_di = &mc_sha1_di,
+ .ccsha384_di = &mc_sha384_di,
+ .ccsha512_di = &mc_sha512_di,
+
+ .cchmac_init_fn = cchmac_init,
+ .cchmac_update_fn = cchmac_update,
+ .cchmac_final_fn = cchmac_final,
+ .cchmac_fn = cchmac,
+
+ .ccaes_ecb_encrypt = &mc_aes_ecb_encrypt,
+ .ccaes_ecb_decrypt = &mc_aes_ecb_decrypt,
+ .ccaes_cbc_encrypt = &mc_aes_cbc_encrypt,
+ .ccaes_cbc_decrypt = &mc_aes_cbc_decrypt,
+ .ccaes_ctr_crypt = &mc_aes_ctr_crypt,
+
+ .ccrng_fn = mc_ccrng,
+
+ .random_generate_fn = mc_random_generate,
+ .random_uniform_fn = mc_random_uniform,
+ .random_kmem_ctx_size_fn = mc_random_kmem_ctx_size,
+ .random_kmem_init_fn = mc_random_kmem_init,
+
+ .digest_ctx_size_fn = mc_digest_ctx_size,
+ .digest_init_fn = mc_digest_init,
+ .digest_update_fn = mc_digest_update,
+ .digest_final_fn = mc_digest_final,
+ .digest_fn = mc_digest_oneshot,
+
+ .hmac_ctx_size_fn = mc_hmac_ctx_size,
+ .hmac_init_fn = mc_hmac_init,
+ .hmac_update_fn = mc_hmac_update,
+ .hmac_final_generate_fn = mc_hmac_final_generate,
+ .hmac_final_verify_fn = mc_hmac_final_verify,
+ .hmac_generate_fn = mc_hmac_generate,
+ .hmac_verify_fn = mc_hmac_verify,
+};
+
+/*
+ * Runs where the corecrypto kext would normally have been started: before
+ * the first consumer in the EARLY_BOOT stage (kmem's random generator).
+ */
+__startup_func
+static void
+minicrypto_init(void)
+{
+ const char *failed = mc_digest_selftest();
+ if (failed == NULL) {
+ failed = mc_aes_selftest();
+ }
+ if (failed != NULL) {
+ panic("minicrypto: %s self-test failed", failed);
+ }
+
+ mc_funcs.ccsha256_di = ccsha256_di();
+ if (register_crypto_functions(&mc_funcs) != 0) {
+ return; /* a real provider got there first */
+ }
+ /* The PRNG context is ours; the kernel only hands the pointer back to us. */
+ register_and_init_prng((struct cckprng_ctx *)(void *)&mc_prng, &mc_prng_funcs);
+ printf("minicrypto: registered (md5, sha1, sha2, hmac, aes-ecb/cbc/ctr, hmac-drbg prng); no xts/gcm, no RSA\n");
+}
+STARTUP(EARLY_BOOT, STARTUP_RANK_FIRST, minicrypto_init);
diff --git a/xnu/files/osfmk/minicrypto/minicrypto.h b/xnu/files/osfmk/minicrypto/minicrypto.h
new file mode 100644
index 0000000..c20d5f7
--- /dev/null
+++ b/xnu/files/osfmk/minicrypto/minicrypto.h
@@ -0,0 +1,27 @@
+/*
+ * minicrypto: a minimal stand-in for Apple's corecrypto kext, enough for the
+ * open-source kernel to boot without it. See mc_provider.c.
+ */
+#ifndef _MINICRYPTO_H_
+#define _MINICRYPTO_H_
+
+#include <corecrypto/ccdigest.h>
+
+extern const struct ccdigest_info mc_md5_di;
+extern const struct ccdigest_info mc_sha1_di;
+extern const struct ccdigest_info mc_sha384_di;
+extern const struct ccdigest_info mc_sha512_di;
+
+void mc_digest(const struct ccdigest_info *di, size_t len, const void *data, void *digest);
+const char *mc_digest_selftest(void);
+
+/* AES (mc_aes.c) */
+struct ccmode_ecb;
+struct ccmode_cbc;
+struct ccmode_ctr;
+extern const struct ccmode_ecb mc_aes_ecb_encrypt, mc_aes_ecb_decrypt;
+extern const struct ccmode_cbc mc_aes_cbc_encrypt, mc_aes_cbc_decrypt;
+extern const struct ccmode_ctr mc_aes_ctr_crypt;
+const char *mc_aes_selftest(void);
+
+#endif /* _MINICRYPTO_H_ */
diff --git a/xnu/redwood.patch b/xnu/redwood.patch
new file mode 100644
index 0000000..1158b22
--- /dev/null
+++ b/xnu/redwood.patch
@@ -0,0 +1,2152 @@
+diff --git a/Makefile b/Makefile
+index e78d8476c346..03fc3ff646b8 100644
+--- a/Makefile
++++ b/Makefile
+@@ -143,8 +143,8 @@ installsrc:
+
+ else ifneq ($(findstring xnu_tests,$(RC_ProjectName)),)
+
+-export SYSCTL_HW_PHYSICALCPU := $(shell /usr/sbin/sysctl -n hw.physicalcpu)
+-export SYSCTL_HW_LOGICALCPU := $(shell /usr/sbin/sysctl -n hw.logicalcpu)
++export SYSCTL_HW_PHYSICALCPU := $(shell nproc)
++export SYSCTL_HW_LOGICALCPU := $(shell nproc)
+ MAKEJOBS := --jobs=$(shell expr $(SYSCTL_HW_LOGICALCPU) + 1)
+
+ default: install
+@@ -160,8 +160,8 @@ installsrc:
+
+ else ifeq ($(RC_ProjectName),xnu_tests_driverkit)
+
+-export SYSCTL_HW_PHYSICALCPU := $(shell /usr/sbin/sysctl -n hw.physicalcpu)
+-export SYSCTL_HW_LOGICALCPU := $(shell /usr/sbin/sysctl -n hw.logicalcpu)
++export SYSCTL_HW_PHYSICALCPU := $(shell nproc)
++export SYSCTL_HW_LOGICALCPU := $(shell nproc)
+ MAKEJOBS := --jobs=$(shell expr $(SYSCTL_HW_LOGICALCPU) + 1)
+
+ default: install
+@@ -193,8 +193,8 @@ endif
+ # CPUs. If the system does not support SMT, use N+1.
+ # If MAKEJOBS or -jN is passed on the make line, that takes precedence.
+ #
+-export SYSCTL_HW_PHYSICALCPU := $(shell /usr/sbin/sysctl -n hw.physicalcpu)
+-export SYSCTL_HW_LOGICALCPU := $(shell /usr/sbin/sysctl -n hw.logicalcpu)
++export SYSCTL_HW_PHYSICALCPU := $(shell nproc)
++export SYSCTL_HW_LOGICALCPU := $(shell nproc)
+ MAKEJOBS := --jobs=$(shell expr $(SYSCTL_HW_LOGICALCPU) + 1)
+
+ TOP_TARGETS = \
+diff --git a/SETUP/config/doconf b/SETUP/config/doconf
+index 222158a93918..68bb0f3e56bf 100755
+--- a/SETUP/config/doconf
++++ b/SETUP/config/doconf
+@@ -1,4 +1,4 @@
+-#!/bin/csh -f
++#!/usr/bin/env -S csh -f
+ set path = ($path .)
+ ######################################################################
+ # HISTORY
+diff --git a/bsd/conf/files b/bsd/conf/files
+index 44274016a4cf..417e1fdc9e93 100644
+--- a/bsd/conf/files
++++ b/bsd/conf/files
+@@ -109,6 +109,10 @@ bsd/dev/munge.c optional config_requires_u32_munging
+ bsd/dev/unix_startup.c standard
+
+ bsd/dev/monotonic.c optional monotonic
++bsd/dev/redwood_input.c standard
++bsd/dev/redwood_virtio_input.c standard
++bsd/dev/redwood_goodix.c standard
++bsd/dev/redwood_cpufreq.c standard
+ bsd/dev/dev_perfmon.c optional config_perfmon
+
+ bsd/libkern/crc32.c standard
+@@ -155,6 +159,9 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs
+ bsd/miscfs/mockfs/mockfs_fsnode.c optional mockfs
+ bsd/miscfs/mockfs/mockfs_vfsops.c optional mockfs
+ bsd/miscfs/mockfs/mockfs_vnops.c optional mockfs
++bsd/miscfs/packfs/packfs_vfsops.c optional packfs
++bsd/miscfs/packfs/packfs_vnops.c optional packfs
++bsd/miscfs/ramfs/ramfs.c optional ramfs
+
+ bsd/miscfs/routefs/routefs_ops.c optional routefs
+
+@@ -361,6 +368,7 @@ bsd/security/audit/audit_syscalls.c standard
+ bsd/security/audit/audit_worker.c optional config_audit
+
+ bsd/pthread/pthread_shims.c standard
++bsd/pthread/pthread_kext_static.c standard
+ bsd/pthread/pthread_priority.c standard
+ bsd/pthread/pthread_workqueue.c standard
+
+@@ -383,6 +391,7 @@ bsd/kern/kern_debug.c standard
+ bsd/kern/kern_symfile.c standard
+ bsd/kern/kern_descrip.c standard
+ bsd/kern/kern_guarded.c standard
++bsd/kern/kern_minimac.c optional config_macf
+ bsd/kern/kern_event.c standard
+ bsd/kern/kern_control.c optional networking
+ bsd/kern/kern_exec.c standard
+diff --git a/bsd/dev/arm/km.c b/bsd/dev/arm/km.c
+index fd7a94b20794..69eaceedd248 100644
+--- a/bsd/dev/arm/km.c
++++ b/bsd/dev/arm/km.c
+@@ -205,6 +205,15 @@ kmioctl(dev_t dev, u_long cmd, caddr_t data, int flag, proc_t p)
+ error = EINVAL;
+ break;
+
++ case TIOCSCTTY:
++ /*
++ * The console is every daemon's standard error in this system. If
++ * the first session leader to open it took it for its controlling
++ * terminal, its exit would revoke the console for all the others.
++ */
++ error = ENOTTY;
++ break;
++
+ /* Bodge in the CLOCAL flag as the km device is always local */
+ case TIOCSETA_32:
+ case TIOCSETAW_32:
+@@ -252,6 +261,9 @@ fallthrough:
+ * assumptions here, this routine should be static (and
+ * inlined, given there is only one call site).
+ */
++
++extern void loader_log_putc(char c);
++
+ int
+ kmputc(__unused dev_t dev, char c)
+ {
+@@ -363,6 +375,8 @@ kmoutput(struct tty * tp)
+ for (cp = buf; cp < &buf[cc]; cp++) {
+ /* output the buffer one charatcer at a time */
+ *cp = *cp & 0x7f;
++ /* What user space writes to /dev/console also goes to the loader's log. */
++ loader_log_putc((char)*cp);
+ }
+ if (cc > 1) {
+ console_write((char *)buf, cc);
+diff --git a/bsd/dev/arm/systemcalls.c b/bsd/dev/arm/systemcalls.c
+index 7fd9be1a5f38..f158f323a071 100644
+--- a/bsd/dev/arm/systemcalls.c
++++ b/bsd/dev/arm/systemcalls.c
+@@ -36,6 +36,52 @@
+ #include <security/mac_framework.h>
+ #endif
+
++/*
++ * Bring-up aid: boot-arg systrace=1 logs every BSD system call that fails,
++ * systrace=2 logs all of them (to the kernel message buffer). For calls that
++ * take a path, the path is shown.
++ */
++static TUNABLE(uint32_t, systrace_level, "systrace", 0);
++extern const char *syscallnames[];
++
++static void
++systrace_report(struct proc *proc, unsigned short syscode, struct uthread *uthread, int error)
++{
++ /* system calls whose first (or, for the second list, second) argument is a path */
++ static const unsigned short path_arg0[] = {
++ SYS_open, SYS_link, SYS_unlink, SYS_chdir, SYS_mknod, SYS_chmod, SYS_chown, SYS_access, SYS_readlink,
++ SYS_execve, SYS_chroot, SYS_rename, SYS_mkdir, SYS_rmdir, SYS_pathconf, SYS_getattrlist, SYS_setattrlist,
++ SYS_getxattr, SYS_listxattr, SYS_fsctl, SYS_stat64, SYS_lstat64, SYS_statfs64, SYS_open_nocancel,
++ SYS_open_dprotected_np, SYS_symlink, SYS_unmount, SYS_stat64_extended, SYS_lstat64_extended,
++ };
++ static const unsigned short path_arg1[] = {
++ SYS_mount, SYS_posix_spawn, SYS_openat, SYS_openat_nocancel, SYS_fstatat64, SYS_faccessat, SYS_readlinkat,
++ SYS_getattrlistat, SYS_mkdirat, SYS_unlinkat,
++ };
++ char path[160] = "";
++ size_t done;
++
++ if (systrace_level < 2 && (error == 0 || error == EJUSTRETURN || error == ERESTART)) {
++ return;
++ }
++ for (unsigned i = 0; i < sizeof(path_arg0) / sizeof(path_arg0[0]); i++) {
++ if (path_arg0[i] == syscode) {
++ (void)copyinstr((user_addr_t)uthread->uu_arg[0], path, sizeof(path), &done);
++ }
++ }
++ for (unsigned i = 0; i < sizeof(path_arg1) / sizeof(path_arg1[0]); i++) {
++ if (path_arg1[i] == syscode) {
++ (void)copyinstr((user_addr_t)uthread->uu_arg[1], path, sizeof(path), &done);
++ }
++ }
++ path[sizeof(path) - 1] = 0;
++ printf("systrace: %s[%d] %s(0x%llx, 0x%llx, 0x%llx, 0x%llx)%s%s%s = %d\n",
++ proc->p_comm, proc_getpid(proc), syscallnames[syscode],
++ (unsigned long long)uthread->uu_arg[0], (unsigned long long)uthread->uu_arg[1],
++ (unsigned long long)uthread->uu_arg[2], (unsigned long long)uthread->uu_arg[3],
++ path[0] ? " \"" : "", path, path[0] ? "\"" : "", error);
++}
++
+ #if CONFIG_DTRACE
+ extern int32_t dtrace_systrace_syscall(struct proc *, void *, int *);
+ extern void dtrace_systrace_syscall_return(unsigned short, int, int *);
+@@ -181,6 +227,10 @@ unix_syscall(
+ error = (*(callp->sy_call))(proc, &uthread->uu_arg[0], &(uthread->uu_rval[0]));
+ AUDIT_SYSCALL_EXIT(code, proc, uthread, error);
+
++ if (__improbable(systrace_level != 0)) {
++ systrace_report(proc, syscode, uthread, error);
++ }
++
+ #if CONFIG_MACF
+ skip_syscall:
+ #endif /* CONFIG_MACF */
+diff --git a/bsd/dev/memdev.c b/bsd/dev/memdev.c
+index 3e6bffa8c48e..43cffb98bdcc 100644
+--- a/bsd/dev/memdev.c
++++ b/bsd/dev/memdev.c
+@@ -159,7 +159,8 @@ static const struct cdevsw mdevcdevsw = {
+
+ struct mdev {
+ uint64_t mdBase; /* base page number (pages are assumed to be 4K). Multiply by 4096 to find actual address */
+- uint32_t mdSize; /* size in pages (pages are assumed to be 4K). Multiply by 4096 to find actual size. */
++ uint64_t mdSize; /* size in pages (pages are assumed to be 4K). Multiply by 4096 to find actual size.
++ * 64 bits wide so that "mdSize << 12" does not wrap for a disk of 4 GB or more. */
+ int mdFlags; /* flags */
+ int mdSecsize; /* sector size */
+ int mdBDev; /* Block device number */
+@@ -179,6 +180,7 @@ int mdevCMajor = -1;
+ static int mdevioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p, int is_char);
+ dev_t mdevadd(int devid, uint64_t base, unsigned int size, int phys);
+ dev_t mdevlookup(int devid);
++int mdevgetkernelrange(dev_t dev, vm_offset_t *base, uint64_t *size);
+ void mdevremoveall(void);
+ int mdevgetrange(int devid, uint64_t *base, uint64_t *size);
+
+@@ -250,7 +252,9 @@ mdevrw(dev_t dev, struct uio *uio, __unused int ioflag)
+ if (uio->uio_offset > (mdev[devid].mdSize << 12)) {
+ count = 0;
+ } else {
+- count = imin(uio_resid(uio), (mdev[devid].mdSize << 12) - uio->uio_offset);
++ uint64_t room = (mdev[devid].mdSize << 12) - (uint64_t)uio->uio_offset;
++
++ count = (uint64_t)uio_resid(uio) < room ? (int)uio_resid(uio) : (int)(room > INT_MAX ? INT_MAX : room);
+ }
+
+ status = uiomove64(mdata, count, uio); /* Move the data */
+@@ -455,8 +459,8 @@ mdevioctl(dev_t dev, u_long cmd, caddr_t data, __unused int flag,
+ }
+ memdev_info->mi_mdev = TRUE;
+ memdev_info->mi_phys = (mdev[devid].mdFlags & mdPhys) ? TRUE : FALSE;
+- memdev_info->mi_base = (uint32_t)mdev[devid].mdBase;
+- memdev_info->mi_size = mdev[devid].mdSize;
++ memdev_info->mi_base = mdev[devid].mdBase;
++ memdev_info->mi_size = (typeof(memdev_info->mi_size))mdev[devid].mdSize;
+ break;
+
+ default:
+@@ -725,6 +729,26 @@ mdevlookup(int devid)
+ return mdev[devid].mdBDev; /* Return the device number */
+ }
+
++/*
++ * For a filesystem that reads a memory disk in place: where the disk is in the kernel's
++ * address space. Not for disks given by physical address (those are not mapped).
++ */
++int
++mdevgetkernelrange(dev_t dev, vm_offset_t *base, uint64_t *size)
++{
++ for (int i = 0; i < NB_MAX_MDEVICES; i++) {
++ if ((mdev[i].mdFlags & mdInited) && mdev[i].mdBDev == dev) {
++ if (mdev[i].mdFlags & mdPhys) {
++ return ENOTSUP;
++ }
++ *base = (vm_offset_t)(mdev[i].mdBase << 12);
++ *size = mdev[i].mdSize << 12;
++ return 0;
++ }
++ }
++ return ENXIO;
++}
++
+ void
+ mdevremoveall(void)
+ {
+diff --git a/bsd/kern/bsd_init.c b/bsd/kern/bsd_init.c
+index 4df41ba1f61b..abe2352d6a61 100644
+--- a/bsd/kern/bsd_init.c
++++ b/bsd/kern/bsd_init.c
+@@ -147,6 +147,7 @@
+ #include <net/if_ether.h> /* for ether_family_init() */
+ #include <net/if_gif.h> /* for gif_init() */
+ #include <miscfs/devfs/devfsdefs.h> /* for devfs_kernel_mount() */
++#include <sys/redwood_input.h>
+ #include <vm/vm_kern.h> /* for kmem_suballoc() */
+ #include <sys/proc_uuid_policy.h> /* proc_uuid_policy_init() */
+ #include <netinet/flow_divert.h> /* flow_divert_init() */
+@@ -490,7 +491,7 @@ bsd_init(void)
+ platform_stall_panic_or_spin(PLATFORM_STALL_XNU_LOCATION_BSD_INIT);
+ #endif
+
+-#define DEBUG_BSDINIT 0
++#define DEBUG_BSDINIT 1 /* bring-up: trace bsd_init steps (only visible with -enable_kprintf_spam) */
+
+ #if DEBUG_BSDINIT
+ #define bsd_init_kprintf(x, ...) kprintf("bsd_init: " x, ## __VA_ARGS__)
+@@ -976,6 +977,7 @@ bsd_init(void)
+
+ bsd_init_kprintf("calling devfs_kernel_mount\n");
+ devfs_kernel_mount(mounthere);
++ redwood_input_init(); /* /dev/redwood-touch */
+ }
+ #endif /* DEVFS */
+
+diff --git a/bsd/kern/decmpfs.c b/bsd/kern/decmpfs.c
+index 95192dd62449..b00da803b5b4 100644
+--- a/bsd/kern/decmpfs.c
++++ b/bsd/kern/decmpfs.c
+@@ -515,7 +515,7 @@ decmpfs_fetch_compressed_header(vnode_t vp, decmpfs_cnode *cp, decmpfs_header **
+ const bool no_additional_data = ((cp != NULL)
+ && (cp->cmp_type != 0)
+ && (cp->cmp_minimal_xattr != 0));
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ decmpfs_header *hdr = NULL;
+
+ /*
+diff --git a/bsd/kern/kern_exec.c b/bsd/kern/kern_exec.c
+index 1d71c66629fb..57cd16eed941 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,
+ * activators should not be given the opportunity to attempt
+ * to activate the image.
+ */
++/* Bring-up aid: with boot-arg systrace set, say which stage of an exec refused the image. */
++static TUNABLE(uint32_t, exec_trace, "systrace", 0);
++
+ static int
+ exec_mach_imgact(struct image_params *imgp)
+ {
+@@ -1315,6 +1318,9 @@ grade:
+ * Actually load the image file we previously decided to load.
+ */
+ lret = load_machfile(imgp, mach_header, thread, &map, &load_result);
++ if (lret != LOAD_SUCCESS && exec_trace) {
++ printf("exectrace: %s: load_machfile failed: %d\n", imgp->ip_ndp->ni_cnd.cn_pnbuf, lret);
++ }
+ if (lret != LOAD_SUCCESS) {
+ error = load_return_to_errno(lret);
+
+@@ -2197,6 +2203,9 @@ again:
+ }
+
+ error = exec_check_permissions(imgp);
++ if (error && exec_trace) {
++ printf("exectrace: %s: exec_check_permissions failed: %d\n", imgp->ip_ndp->ni_cnd.cn_pnbuf, error);
++ }
+ if (error) {
+ goto bad;
+ }
+@@ -2640,6 +2649,25 @@ done:
+ return ret;
+ }
+
++/*
++ * Bring-up aid, boot-arg applog=1: what applications and other programs started without a
++ * terminal say is worth reading here. Their standard output and error, which launchd opens on
++ * /dev/null, go to the console instead (that shows NSLog and the "Terminating app due to
++ * uncaught exception" kind of message). With applog=2 every program also gets
++ * OS_ACTIVITY_DT_MODE in its environment, which makes os_log write to standard error as well:
++ * everything any program logs, and a much slower system.
++ */
++static TUNABLE(uint32_t, exec_applog, "applog", 0);
++
++static const char *
++exec_applog_path(int fd, const char *path)
++{
++ if (exec_applog && (fd == 1 || fd == 2) && strcmp(path, "/dev/null") == 0) {
++ return "/dev/console";
++ }
++ return path;
++}
++
+ /*
+ * exec_handle_file_actions
+ *
+@@ -2709,7 +2737,7 @@ exec_handle_file_actions(struct image_params *imgp, short psa_flags)
+ AUDIT_SUBCALL_ENTER(OPEN, p, uthread);
+
+ NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE,
+- CAST_USER_ADDR_T(psfa->psfaa_openargs.psfao_path),
++ CAST_USER_ADDR_T(exec_applog_path(psfa->psfaa_filedes, psfa->psfaa_openargs.psfao_path)),
+ imgp->ip_vfs_context);
+
+ error = open1(imgp->ip_vfs_context, ndp,
+@@ -5586,10 +5614,61 @@ bad:
+ * Note: The argument and environment vectors are user space pointers
+ * to arrays of user space pointers.
+ */
++/*
++ * Bring-up aid: the sysctl kern.exec_inject holds "LIBRARY NAME NAME ..."; every program
++ * whose file name is one of the NAMEs is started with DYLD_INSERT_LIBRARIES=LIBRARY in its
++ * environment, so that dyld loads our library into it. Several such groups may follow each
++ * other, separated by ";". launchd refuses to pass DYLD_ variables from a job description,
++ * which is why the kernel adds this one. Set once by our init (from etc/inject.conf) before
++ * it hands over to launchd.
++ */
++static char exec_inject_conf[512];
++SYSCTL_STRING(_kern, OID_AUTO, exec_inject, CTLFLAG_RW | CTLFLAG_LOCKED, exec_inject_conf, sizeof(exec_inject_conf),
++ "LIBRARY NAME... [; LIBRARY NAME...]: programs started with the library inserted");
++
++static bool
++exec_inject_env(struct image_params *imgp, char *env, size_t size)
++{
++ const char *name, *p = exec_inject_conf;
++ size_t namelen;
++
++ if (*p == 0 || imgp->ip_ndp == NULL) {
++ return false;
++ }
++ name = imgp->ip_ndp->ni_cnd.cn_nameptr;
++ namelen = imgp->ip_ndp->ni_cnd.cn_namelen;
++ while (*p != 0) {
++ const char *library;
++ size_t liblen;
++
++ while (*p == ' ' || *p == ';') {
++ p++;
++ }
++ library = p;
++ while (*p != 0 && *p != ' ' && *p != ';') {
++ p++;
++ }
++ liblen = (size_t)(p - library);
++ while (*p == ' ') {
++ const char *word = ++p;
++
++ while (*p != 0 && *p != ' ' && *p != ';') {
++ p++;
++ }
++ if ((size_t)(p - word) == namelen && namelen != 0 && liblen != 0 && strncmp(word, name, namelen) == 0) {
++ snprintf(env, size, "DYLD_INSERT_LIBRARIES=%.*s", (int)liblen, library);
++ return true;
++ }
++ }
++ }
++ return false;
++}
++
+ __attribute__((noinline))
+ static int
+ exec_extract_strings(struct image_params *imgp)
+ {
++ char inject_env[300];
+ int error = 0;
+ int ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT_ADDR) ? 8 : 4;
+ int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;
+@@ -5759,6 +5838,33 @@ exec_extract_strings(struct image_params *imgp)
+ imgp->ip_envc++;
+ }
+
++ /* one more variable for the programs that get our library inside them (see exec_inject_env) */
++ if (exec_inject_env(imgp, inject_env, sizeof(inject_env))) {
++ error = exec_add_user_string(imgp, CAST_USER_ADDR_T(inject_env), UIO_SYSSPACE, TRUE);
++ if (error) {
++ goto bad;
++ }
++ if (imgp->ip_argspace < new_ptr_size) {
++ error = E2BIG;
++ goto bad;
++ }
++ imgp->ip_argspace -= new_ptr_size;
++ imgp->ip_envc++;
++ }
++ /* ... and one for everybody when the logs are wanted on the console (see exec_applog_path) */
++ if (exec_applog >= 2) {
++ error = exec_add_user_string(imgp, CAST_USER_ADDR_T("OS_ACTIVITY_DT_MODE=YES"), UIO_SYSSPACE, TRUE);
++ if (error) {
++ goto bad;
++ }
++ if (imgp->ip_argspace < new_ptr_size) {
++ error = E2BIG;
++ goto bad;
++ }
++ imgp->ip_argspace -= new_ptr_size;
++ imgp->ip_envc++;
++ }
++
+ /* Save space for envv[] NULL terminator */
+ if (imgp->ip_argspace < new_ptr_size) {
+ error = E2BIG;
+@@ -7538,6 +7644,11 @@ process_signature(proc_t p, struct image_params *imgp)
+ }
+
+ done:
++ if (error && exec_trace) {
++ printf("exectrace: %s[%d]: process_signature failed: %d (csflags 0x%x, mac %d, cs_error %d)\n",
++ p->p_comm, proc_getpid(p), error, imgp->ip_csflags, imgp->ip_mac_return,
++ signature_failure_reason != OS_REASON_NULL);
++ }
+ if (0 == error) {
+ /*
+ * Update the new process's signature-dependent process state.
+diff --git a/bsd/kern/kern_sig.c b/bsd/kern/kern_sig.c
+index ae4a5f33df1e..986b517dfd18 100644
+--- a/bsd/kern/kern_sig.c
++++ b/bsd/kern/kern_sig.c
+@@ -1099,6 +1099,14 @@ __pthread_kill(__unused proc_t p, struct __pthread_kill_args *uap,
+ thread_t target_act;
+ int error = 0;
+ int signum = uap->sig;
++
++#if defined(__arm64__)
++ if (signum == SIGABRT) {
++ extern void user_abort_trace(void);
++
++ user_abort_trace(); /* no crash reporter here: this is where an abort() gets recorded */
++ }
++#endif
+ struct uthread *uth;
+
+ target_act = (thread_t)port_name_to_thread(uap->thread_port,
+diff --git a/bsd/kern/kpi_socket.c b/bsd/kern/kpi_socket.c
+index 003cfb074a99..c597065f24f1 100644
+--- a/bsd/kern/kpi_socket.c
++++ b/bsd/kern/kpi_socket.c
+@@ -727,7 +727,7 @@ sock_receive_internal(socket_t sock, struct msghdr *msg, mbuf_t *data,
+ int error = 0;
+ user_ssize_t length = 0;
+ struct sockaddr *fromsa = NULL;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF((msg != NULL) ? msg->msg_iovlen : 0)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF((msg != NULL) ? msg->msg_iovlen : 0) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ if (sock == NULL) {
+ return EINVAL;
+diff --git a/bsd/kern/sys_generic.c b/bsd/kern/sys_generic.c
+index 4ca22ee4371a..e95e618b4cb6 100644
+--- a/bsd/kern/sys_generic.c
++++ b/bsd/kern/sys_generic.c
+@@ -303,7 +303,7 @@ dofileread(vfs_context_t ctx, struct fileproc *fp,
+ user_addr_t bufp, user_size_t nbyte, off_t offset, int flags,
+ user_ssize_t *retval)
+ {
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ uio_t uio;
+ int spacetype;
+
+@@ -350,7 +350,7 @@ static int
+ read_internal(struct proc *p, int fd, user_addr_t buf, user_size_t nbyte,
+ off_t offset, int flags, user_ssize_t *retval)
+ {
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ uio_t uio;
+ int spacetype = IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;
+
+@@ -631,7 +631,7 @@ dofilewrite(vfs_context_t ctx, struct fileproc *fp,
+ user_addr_t bufp, user_size_t nbyte, off_t offset, int flags,
+ user_ssize_t *retval)
+ {
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ uio_t uio;
+ int spacetype;
+
+@@ -678,7 +678,7 @@ int
+ write_internal(struct proc *p, int fd, user_addr_t buf, user_size_t nbyte,
+ off_t offset, int flags, guardid_t *puguard, user_ssize_t *retval)
+ {
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ uio_t uio;
+ int spacetype = IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;
+
+diff --git a/bsd/kern/uipc_syscalls.c b/bsd/kern/uipc_syscalls.c
+index dce802fc36f1..e2e6b3a3f3db 100644
+--- a/bsd/kern/uipc_syscalls.c
++++ b/bsd/kern/uipc_syscalls.c
+@@ -3561,7 +3561,7 @@ sendfile(proc_ref_t p, struct sendfile_args *uap, __unused int *retval)
+ mbuf_t m;
+ unsigned int nbufs = SFUIOBUFS, i;
+ uio_t auio;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(SFUIOBUFS)]; /* 1 KB !!! */
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(SFUIOBUFS) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)]; /* 1 KB !!! */
+ size_t uiolen;
+ user_ssize_t rlen;
+ off_t pgoff;
+diff --git a/bsd/miscfs/mockfs/mockfs.h b/bsd/miscfs/mockfs/mockfs.h
+index 07c91ffaf686..5ce41d043901 100644
+--- a/bsd/miscfs/mockfs/mockfs.h
++++ b/bsd/miscfs/mockfs/mockfs.h
+@@ -59,7 +59,7 @@ struct mockfs_mount {
+ mockfs_fsnode_t mockfs_root; /* Root of the node tree */
+ boolean_t mockfs_memory_backed; /* Does the backing store reside in memory */
+ boolean_t mockfs_physical_memory; /* (valid if memory backed) */
+- uint32_t mockfs_memdev_base; /* Base page of the backing store (valid if memory backed) */
++ uint64_t mockfs_memdev_base; /* Base page of the backing store (valid if memory backed) */
+ uint64_t mockfs_memdev_size; /* Size of the backing store (valid if memory backed) */
+ };
+
+diff --git a/bsd/miscfs/mockfs/mockfs_fsnode.c b/bsd/miscfs/mockfs/mockfs_fsnode.c
+index e00012622e77..4f993b3cd47f 100644
+--- a/bsd/miscfs/mockfs/mockfs_fsnode.c
++++ b/bsd/miscfs/mockfs/mockfs_fsnode.c
+@@ -85,7 +85,7 @@ mockfs_fsnode_create(mount_t mp, uint8_t type, mockfs_fsnode_t * fsnpp)
+ goto done;
+ }
+
+- *fsnpp = kalloc_type(mockfs_fsnode_t, Z_WAITOK | Z_ZERO | Z_NOFAIL);
++ *fsnpp = kalloc_type(struct mockfs_fsnode, Z_WAITOK | Z_ZERO | Z_NOFAIL);
+ (*fsnpp)->size = new_size;
+ (*fsnpp)->type = type;
+ (*fsnpp)->mnt = mp;
+@@ -154,7 +154,7 @@ mockfs_fsnode_destroy(mockfs_fsnode_t fsnp)
+ }
+ }
+
+- kfree_type(mockfs_fsnode_t, fsnp);
++ kfree_type(struct mockfs_fsnode, fsnp);
+ done:
+ return rvalue;
+ }
+@@ -345,10 +345,12 @@ mockfs_fsnode_vnode(mockfs_fsnode_t fsnp, vnode_t * vpp)
+ panic("mockfs_fsvnode failed to get ubc_mem_object for a new vnode");
+ }
+
+- rvalue = pager_map_to_phys_contiguous(ubc_mem_object, 0, (mockfs_mnt->mockfs_memdev_base << PAGE_SHIFT), fsnp->size);
++ /* memdev counts its base in 4K pages whatever the kernel page size is (see bsd/dev/memdev.c) */
++ rvalue = pager_map_to_phys_contiguous(ubc_mem_object, 0, (mockfs_mnt->mockfs_memdev_base << 12), fsnp->size);
+
+ if (rvalue) {
+- panic("mockfs_fsnode_vnode failed to create fictitious pages for a memory-backed device; rvalue = %d", rvalue);
++ panic("mockfs_fsnode_vnode failed to create fictitious pages for a memory-backed device; rvalue = %d, base page 0x%llx, size 0x%llx",
++ rvalue, (unsigned long long)mockfs_mnt->mockfs_memdev_base, (unsigned long long)fsnp->size);
+ }
+ }
+
+diff --git a/bsd/nfs/nfs_serv.c b/bsd/nfs/nfs_serv.c
+index 6ae9b6bc3fde..58556c324b67 100644
+--- a/bsd/nfs/nfs_serv.c
++++ b/bsd/nfs/nfs_serv.c
+@@ -769,8 +769,8 @@ nfsrv_readlink(
+ struct nfsm_chain *nmreq, nmrep;
+ mbuf_t mpath, mp;
+ uio_t auio = NULL;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(4)];
+- char *uio_bufp = &uio_buf[0];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(4) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
++ char *uio_bufp = (char *)&uio_buf[0];
+ int uio_buflen = UIO_SIZEOF(4);
+
+ error = 0;
+@@ -917,7 +917,7 @@ nfsrv_read(
+ struct vnode_attr vattr, *vap = &vattr;
+ off_t off;
+ uid_t saved_uid;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(0)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(0) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ struct nfsm_chain *nmreq, nmrep;
+
+ error = 0;
+@@ -3559,7 +3559,7 @@ nfsrv_symlink(
+ struct nfs_export *nx = NULL;
+ struct nfs_export_options *nxo = NULL;
+ uio_t auio = NULL;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ struct nfsm_chain *nmreq, nmrep;
+ __unused const int nfs_vers = nd->nd_vers;
+ assert(nd->nd_vers == NFS_VER2 || nd->nd_vers == NFS_VER3);
+@@ -4215,7 +4215,7 @@ nfsrv_readdir(
+ struct nfs_export *nx;
+ struct nfs_export_options *nxo;
+ uio_t auio = NULL;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ int len, nlen, rem, xfer, error, attrerr;
+ int siz, count, fullsiz, eofflag, nentries;
+ u_quad_t off, toff, verf = 0;
+@@ -4462,7 +4462,7 @@ nfsrv_readdirplus(
+ struct nfs_export *nx;
+ struct nfs_export_options *nxo;
+ uio_t auio = NULL;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ struct vnode_attr attr, va, *vap = &va;
+ int len, nlen, rem, xfer, error, attrerr, gotfh, gotattr;
+ int siz, dircount, maxcount, fullsiz, eofflag, dirlen, nentries, isdotdot;
+diff --git a/bsd/sys/disk.h b/bsd/sys/disk.h
+index 82efb4fcc000..47a4cd98e59f 100644
+--- a/bsd/sys/disk.h
++++ b/bsd/sys/disk.h
+@@ -284,7 +284,7 @@ typedef struct{
+ typedef struct{
+ boolean_t mi_mdev; /* Is this a memdev device? */
+ boolean_t mi_phys; /* Physical memory? */
+- uint32_t mi_base; /* Base page number of the device? */
++ uint64_t mi_base; /* Base page number of the device (a kernel VA page number does not fit in 32 bits) */
+ uint64_t mi_size; /* Size of the device (in ) */
+ } dk_memdev_info_t;
+
+diff --git a/bsd/sys/uio_internal.h b/bsd/sys/uio_internal.h
+index 74a2036cf69e..a68b79ce48fa 100644
+--- a/bsd/sys/uio_internal.h
++++ b/bsd/sys/uio_internal.h
+@@ -170,7 +170,7 @@ __END_DECLS
+ #define UIO_SIZEOF( a_iovcount ) \
+ ( sizeof(struct uio) + UIO_SIZEOF_IOVS(a_iovcount) )
+
+-typedef char __attribute__((aligned(_Alignof(union iovecs)))) uio_stackbuf_t;
++typedef uint64_t uio_stackbuf_t; /* was over-aligned char; array of those is rejected by clang >= 16 */
+
+ #define UIO_IS_USER_SPACE32( a_uio_t ) \
+ ( (a_uio_t)->uio_segflg == UIO_USERSPACE32 || (a_uio_t)->uio_segflg == UIO_PHYS_USERSPACE32 || \
+diff --git a/bsd/vfs/vfs_attrlist.c b/bsd/vfs/vfs_attrlist.c
+index cbaa0b221894..78315a2d54cf 100644
+--- a/bsd/vfs/vfs_attrlist.c
++++ b/bsd/vfs/vfs_attrlist.c
+@@ -878,7 +878,7 @@ static int
+ setattrlist_setfinderinfo(vnode_t vp, char *fndrinfo, struct vfs_context *ctx)
+ {
+ uio_t auio;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ int error;
+
+ if ((auio = uio_createwithbuffer(1, 0, UIO_SYSSPACE, UIO_WRITE, uio_buf, sizeof(uio_buf))) == NULL) {
+@@ -1847,7 +1847,7 @@ attr_pack_common(vfs_context_t ctx, mount_t mp, vnode_t vp, struct attrlist *alp
+ error = 0;
+ if (vp && !is_bulk) {
+ uio_t auio;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ if ((auio = uio_createwithbuffer(1, 0, UIO_SYSSPACE,
+ UIO_READ, uio_buf, sizeof(uio_buf))) == NULL) {
+@@ -3120,7 +3120,7 @@ getattrlist_internal(vfs_context_t ctx, vnode_t vp, struct attrlist *alp,
+ int pack_invalid;
+ int vtype = 0;
+ uio_t auio;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ // must be true for fork attributes to be used as new common attributes
+ const int use_fork = (options & FSOPT_ATTR_CMN_EXTENDED) != 0;
+
+@@ -3474,7 +3474,7 @@ refill_fd_direntries(vfs_context_t ctx, vnode_t dvp, struct fd_vn_data *fvd,
+ int *eofflagp)
+ {
+ uio_t rdir_uio;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ size_t rdirbufsiz;
+ size_t rdirbufused;
+ int eofflag;
+@@ -4048,7 +4048,7 @@ getattrlistbulk(proc_t p, struct getattrlistbulk_args *uap, int32_t *retval)
+ enum uio_seg segflg;
+ int count;
+ uio_t auio = NULL;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ kauth_action_t action;
+ int eofflag;
+ uint64_t options;
+diff --git a/bsd/vfs/vfs_conf.c b/bsd/vfs/vfs_conf.c
+index bae70cda3a96..d0e50606b15e 100644
+--- a/bsd/vfs/vfs_conf.c
++++ b/bsd/vfs/vfs_conf.c
+@@ -103,6 +103,15 @@ extern struct vfsops mockfs_vfsops;
+ extern int mockfs_mountroot(mount_t, vnode_t, vfs_context_t);
+ #endif /* MOCKFS */
+
++#if PACKFS
++extern struct vfsops packfs_vfsops;
++extern int packfs_mountroot(mount_t, vnode_t, vfs_context_t);
++#endif /* PACKFS */
++
++#if RAMFS
++extern struct vfsops ramfs_vfsops;
++#endif /* RAMFS */
++
+ enum fs_type_num {
+ FT_NFS = 2,
+ FT_DEVFS = 19,
+@@ -110,7 +119,9 @@ enum fs_type_num {
+ FT_ROUTEFS = 21,
+ FT_NULLFS = 22,
+ FT_BINDFS = 23,
+- FT_MOCKFS = 0x6D6F636B
++ FT_MOCKFS = 0x6D6F636B,
++ FT_PACKFS = 0x7061636B,
++ FT_RAMFS = 0x72616D66
+ };
+
+ int fstypenumstart = FT_BINDFS + 1;
+@@ -194,6 +205,44 @@ static struct vfstable vfstbllist[] = {
+ },
+ #endif /* BINDFS */
+
++#if RAMFS
++ /* Read-write filesystem in memory (no device, no mount arguments) */
++ {
++ .vfc_vfsops = &ramfs_vfsops,
++ .vfc_name = "ramfs",
++ .vfc_typenum = FT_RAMFS,
++ .vfc_refcount = 0,
++ .vfc_flags = MNT_LOCAL,
++ .vfc_mountroot = NULL,
++ .vfc_next = NULL,
++ .vfc_reserved1 = 0,
++ .vfc_reserved2 = 0,
++ .vfc_vfsflags = VFC_VFSGENERICARGS | VFC_VFS64BITREADY | VFC_VFSNATIVEXATTR,
++ .vfc_descptr = NULL,
++ .vfc_descsize = 0,
++ .vfc_sysctl = NULL
++ },
++#endif /* RAMFS */
++
++#if PACKFS
++ /* Read-only boot image; must come before mockfs, which accepts any root device */
++ {
++ .vfc_vfsops = &packfs_vfsops,
++ .vfc_name = "packfs",
++ .vfc_typenum = FT_PACKFS,
++ .vfc_refcount = 0,
++ .vfc_flags = MNT_LOCAL | MNT_RDONLY,
++ .vfc_mountroot = packfs_mountroot,
++ .vfc_next = NULL,
++ .vfc_reserved1 = 0,
++ .vfc_reserved2 = 0,
++ .vfc_vfsflags = VFC_VFSLOCALARGS | VFC_VFS64BITREADY,
++ .vfc_descptr = NULL,
++ .vfc_descsize = 0,
++ .vfc_sysctl = NULL
++ },
++#endif /* PACKFS */
++
+ #if MOCKFS
+ /* If we are configured for it, mockfs should always be the last standard entry (and thus the last FS we attempt mountroot with) */
+ {
+@@ -298,6 +347,14 @@ extern const struct vnodeopv_desc devfs_fdesc_vnodeop_opv_desc;
+ extern const struct vnodeopv_desc mockfs_vnodeop_opv_desc;
+ #endif /* MOCKFS */
+
++#if PACKFS
++extern const struct vnodeopv_desc packfs_vnodeop_opv_desc;
++#endif /* PACKFS */
++
++#if RAMFS
++extern const struct vnodeopv_desc ramfs_vnodeop_opv_desc;
++#endif /* RAMFS */
++
+ extern const struct vnodeopv_desc nullfs_vnodeop_opv_desc;
+ extern const struct vnodeopv_desc bindfs_vnodeop_opv_desc;
+
+@@ -327,5 +384,11 @@ const struct vnodeopv_desc *vfs_opv_descs[] = {
+ #if MOCKFS
+ &mockfs_vnodeop_opv_desc,
+ #endif /* MOCKFS */
++#if PACKFS
++ &packfs_vnodeop_opv_desc,
++#endif /* PACKFS */
++#if RAMFS
++ &ramfs_vnodeop_opv_desc,
++#endif /* RAMFS */
+ NULL
+ };
+diff --git a/bsd/vfs/vfs_lookup.c b/bsd/vfs/vfs_lookup.c
+index a05c8e767b33..5f2846cb8893 100644
+--- a/bsd/vfs/vfs_lookup.c
++++ b/bsd/vfs/vfs_lookup.c
+@@ -1670,7 +1670,7 @@ lookup_handle_symlink(struct nameidata *ndp, vnode_t *new_dp, bool *new_dp_has_i
+ int error;
+ char *cp; /* pointer into pathname argument */
+ uio_t auio;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ int need_newpathbuf;
+ u_int linklen = 0;
+ struct componentname *cnp = &ndp->ni_cnd;
+diff --git a/bsd/vfs/vfs_quota.c b/bsd/vfs/vfs_quota.c
+index d0476214e5f0..c81cadfab1d4 100644
+--- a/bsd/vfs/vfs_quota.c
++++ b/bsd/vfs/vfs_quota.c
+@@ -382,7 +382,7 @@ dqfileopen(struct quotafile *qfp, int type)
+ off_t file_size;
+ uio_t auio;
+ int error = 0;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ context.vc_thread = current_thread();
+ context.vc_ucred = qfp->qf_cred;
+@@ -440,7 +440,7 @@ dqfileclose(struct quotafile *qfp, __unused int type)
+ struct dqfilehdr header;
+ struct vfs_context context;
+ uio_t auio;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ auio = uio_createwithbuffer(1, 0, UIO_SYSSPACE, UIO_READ,
+ &uio_buf[0], sizeof(uio_buf));
+@@ -767,7 +767,7 @@ dqlookup(struct quotafile *qfp, u_int32_t id, struct dqblk *dqb, uint32_t *index
+ int i, skip, last;
+ u_int32_t mask;
+ int error = 0;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+
+ qf_lock(qfp);
+@@ -986,7 +986,7 @@ dqsync_locked(struct dquot *dq)
+ struct dqblk dqb, *dqblkp;
+ uio_t auio;
+ int error;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ if (dq->dq_id == 0) {
+ dq->dq_flags &= ~DQ_MOD;
+diff --git a/bsd/vfs/vfs_subr.c b/bsd/vfs/vfs_subr.c
+index f64d8c647365..f2e13c1aa7f3 100644
+--- a/bsd/vfs/vfs_subr.c
++++ b/bsd/vfs/vfs_subr.c
+@@ -10995,7 +10995,7 @@ rmdir_remove_orphaned_appleDouble(vnode_t vp, vfs_context_t ctx, int * restart_f
+ uio_t auio = NULL;
+ int eofflag, siz = UIO_BUFF_SIZE, alloc_size = 0, nentries = 0;
+ int open_flag = 0, full_erase_flag = 0;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ char *rbuf = NULL;
+ void *dir_pos;
+ void *dir_end;
+diff --git a/bsd/vfs/vfs_syscalls.c b/bsd/vfs/vfs_syscalls.c
+index 2bbba037c2dd..ee65d5943196 100644
+--- a/bsd/vfs/vfs_syscalls.c
++++ b/bsd/vfs/vfs_syscalls.c
+@@ -7261,7 +7261,7 @@ readlinkat_internal(vfs_context_t ctx, int fd, vnode_t lnk_vp, user_addr_t path,
+ uio_t auio;
+ int error;
+ struct nameidata nd;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ bool put_vnode;
+
+ if (bufsize > INT32_MAX) {
+@@ -10314,7 +10314,7 @@ getdirentries_common(int fd, user_addr_t bufp, user_size_t bufsize, ssize_t *byt
+ int spacetype = proc_is64bit(vfs_context_proc(&context)) ? UIO_USERSPACE64 : UIO_USERSPACE32;
+ off_t loff;
+ int error, numdirent;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ get_from_fd:
+ error = fp_getfvp(vfs_context_proc(&context), fd, &fp, &vp);
+@@ -10613,7 +10613,7 @@ getdirentriesattr(proc_t p, struct getdirentriesattr_args *uap, int32_t *retval)
+ struct attrlist attributelist;
+ vfs_context_t ctx = vfs_context_current();
+ int fd = uap->fd;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ kauth_action_t action;
+
+ AUDIT_ARG(fd, fd);
+@@ -10954,7 +10954,7 @@ searchfs(proc_t p, struct searchfs_args *uap, __unused int32_t *retval)
+ size_t mallocsize;
+ uint32_t nameiflags;
+ vfs_context_t ctx = vfs_context_current();
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ /* Start by copying in fsearchblock parameter list */
+ if (IS_64BIT_PROCESS(p)) {
+@@ -12906,7 +12906,7 @@ getxattr(proc_t p, struct getxattr_args *uap, user_ssize_t *retval)
+ size_t namelen;
+ u_int32_t nameiflags;
+ int error;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ if (uap->options & (XATTR_NOSECURITY | XATTR_NODEFAULT)) {
+ return EINVAL;
+@@ -12990,7 +12990,7 @@ fgetxattr(proc_t p, struct fgetxattr_args *uap, user_ssize_t *retval)
+ size_t attrsize = 0;
+ size_t namelen;
+ int error;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ if (uap->options & (XATTR_NOFOLLOW | XATTR_NOSECURITY | XATTR_NODEFAULT)) {
+ return EINVAL;
+@@ -13038,7 +13038,7 @@ out:
+ struct setxattr_ctx {
+ struct nameidata nd;
+ char attrname[XATTR_MAXNAMELEN + 1];
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ };
+
+ /*
+@@ -13134,7 +13134,7 @@ fsetxattr(proc_t p, struct fsetxattr_args *uap, int *retval)
+ int spacetype = IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;
+ size_t namelen;
+ int error;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ if (uap->options & (XATTR_NOFOLLOW | XATTR_NOSECURITY | XATTR_NODEFAULT)) {
+ return EINVAL;
+@@ -13311,7 +13311,7 @@ listxattr(proc_t p, struct listxattr_args *uap, user_ssize_t *retval)
+ size_t attrsize = 0;
+ u_int32_t nameiflags;
+ int error;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ if (uap->options & (XATTR_NOSECURITY | XATTR_NODEFAULT)) {
+ return EINVAL;
+@@ -13353,7 +13353,7 @@ flistxattr(proc_t p, struct flistxattr_args *uap, user_ssize_t *retval)
+ int spacetype = proc_is64bit(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;
+ size_t attrsize = 0;
+ int error;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ if (uap->options & (XATTR_NOFOLLOW | XATTR_NOSECURITY | XATTR_NODEFAULT)) {
+ return EINVAL;
+diff --git a/bsd/vfs/vfs_vnops.c b/bsd/vfs/vfs_vnops.c
+index 5b51e9c46a8d..6872b94631c9 100644
+--- a/bsd/vfs/vfs_vnops.c
++++ b/bsd/vfs/vfs_vnops.c
+@@ -964,7 +964,7 @@ vn_rdwr_64(
+ int spacetype;
+ struct vfs_context context;
+ int error = 0;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+
+ context.vc_thread = current_thread();
+ context.vc_ucred = cred;
+diff --git a/config/MASTER b/config/MASTER
+index 07147cb3188b..a6e1990998c8 100644
+--- a/config/MASTER
++++ b/config/MASTER
+@@ -113,6 +113,8 @@ options CONFIG_WORKLOOP_DEBUG # <config_workloop_debug>
+ # 4.4 filesystems
+ #
+ options MOCKFS # Boot from an executable # <mockfs>
++options PACKFS # Read-only boot image filesystem # <packfs>
++options RAMFS # Read-write filesystem in memory # <ramfs>
+ options FIFO # fifo support # <fifo>
+ options FDESC # fdesc_fs support # <fdesc>
+ options DEVFS # devfs support # <devfs>
+diff --git a/config/MASTER.arm64.bcm2837 b/config/MASTER.arm64.bcm2837
+index 1ed75eea2052..551cfb9d5126 100644
+--- a/config/MASTER.arm64.bcm2837
++++ b/config/MASTER.arm64.bcm2837
+@@ -16,15 +16,15 @@
+ # Standard Apple OS Configurations:
+ # -------- ----- -- ---------------
+ #
+-# KERNEL_BASE = [ arm64 config_pmap_ppl xsmall msgb_small config_embedded config_requires_u32_munging ARM_EXTRAS_BASE ]
++# KERNEL_BASE = [ arm64 config_pmap_ppl xsmall msgb_small config_embedded config_requires_u32_munging nos_arm_pmap nos_arm_asm ]
+ # KERNEL_RELEASE = [ KERNEL_BASE ]
+ # KERNEL_DEV = [ KERNEL_BASE development mach_assert config_xnupost proc_ref_debug ]
+ # KERNEL_DEBUG = [ KERNEL_BASE debug mach_assert config_xnupost config_waitq_stats config_workloop_debug ]
+ # BSD_BASE = [ mach_bsd psynch config_proc_uuid_policy config_personas ]
+ # BSD_RELEASE = [ BSD_BASE no_printf_str no_kprintf_str secure_kernel ]
+-# BSD_DEV = [ BSD_BASE config_netboot config_imageboot config_coredump pgo config_vnguard ]
+-# BSD_DEBUG = [ BSD_BASE config_netboot config_imageboot config_coredump pgo config_vnguard ]
+-# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_fse routefs namedstreams bindfs]
++# BSD_DEV = [ BSD_BASE config_netboot config_imageboot config_coredump config_vnguard ]
++# BSD_DEBUG = [ BSD_BASE config_netboot config_imageboot config_coredump config_vnguard ]
++# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_fse routefs namedstreams bindfs mockfs packfs ramfs ]
+ # FILESYS_RELEASE= [ FILESYS_BASE ]
+ # FILESYS_DEV = [ FILESYS_BASE config_union_mounts fdesc ]
+ # FILESYS_DEBUG = [ FILESYS_BASE config_union_mounts fdesc ]
+@@ -50,8 +50,8 @@
+ # LIBKERN_DEBUG = [ LIBKERN_BASE iotracking ]
+ # PERF_DBG_BASE = [ mach_kdp config_serial_kdp kperf kpc ]
+ # PERF_DBG_RELEASE=[ PERF_DBG_BASE ist_kdebug ]
+-# PERF_DBG_DEV = [ PERF_DBG_BASE config_dtrace zleaks kdp_interactive_debugging alternate_debugger sched_hygiene_debug config_iotrace]
+-# PERF_DBG_DEBUG = [ PERF_DBG_BASE config_dtrace zleaks kdp_interactive_debugging alternate_debugger sched_hygiene_debug config_iotrace]
++# PERF_DBG_DEV = [ PERF_DBG_BASE config_dtrace zleaks kdp_interactive_debugging alternate_debugger config_iotrace]
++# PERF_DBG_DEBUG = [ PERF_DBG_BASE config_dtrace zleaks kdp_interactive_debugging alternate_debugger config_iotrace]
+ # MACH_BASE = [ mach config_ecc_logging vc_progress_white importance_inheritance config_atm config_coalitions config_iosched config_library_validation config_sysdiagnose config_telemetry config_mach_bridge_recv_time config_quiesce_counter config_service_port_info ]
+ # MACH_RELEASE = [ MACH_BASE config_skip_precise_user_kernel_time debugger_for_zone_info ]
+ # MACH_DEV = [ MACH_BASE config_io_accounting importance_trace ]
+diff --git a/iokit/Kernel/IOPlatformExpert.cpp b/iokit/Kernel/IOPlatformExpert.cpp
+index 7a32a23e4bb1..35dc7b503846 100644
+--- a/iokit/Kernel/IOPlatformExpert.cpp
++++ b/iokit/Kernel/IOPlatformExpert.cpp
+@@ -51,6 +51,9 @@
+ #include <libkern/c++/OSContainers.h>
+ #include <libkern/c++/OSSharedPtr.h>
+ #include <libkern/crypto/sha1.h>
++#include <libkern/crypto/register_crypto.h>
++
++extern "C" crypto_functions_t g_crypto_funcs; /* NULL until a crypto provider has registered */
+ #include <libkern/OSAtomic.h>
+
+ #if defined(__arm64__)
+@@ -2176,6 +2179,14 @@ IOPlatformExpertDevice::generatePlatformUUID( void )
+ uuid_string_t uuid;
+
+ #if !defined(__x86_64__)
++ /*
++ * The first call (configureDefaults, from InitIOKit) comes before the crypto provider
++ * has registered when that provider is not Apple's corecrypto; the identifier is then
++ * made by the second call, when the platform expert starts.
++ */
++ if (g_crypto_funcs == NULL) {
++ return;
++ }
+ entry = IORegistryEntry::fromPath( "/chosen", gIODTPlane );
+ if (entry) {
+ OSData * data1;
+diff --git a/iokit/Kernel/IOService.cpp b/iokit/Kernel/IOService.cpp
+index d2442944e5f0..e90ba6738516 100644
+--- a/iokit/Kernel/IOService.cpp
++++ b/iokit/Kernel/IOService.cpp
+@@ -5179,7 +5179,10 @@ IOService::setRootMedia(IOService * root)
+ bool unhide;
+
+ ioblockstoragedriverClass = OSMetaClass::getMetaClassWithName(gIOBlockStorageDriverKey);
+- assert(ioblockstoragedriverClass);
++ if (!ioblockstoragedriverClass) {
++ // No IOStorageFamily in this kernel: the root cannot be a block storage device
++ root = NULL;
++ }
+
+ while (root) {
+ if (root->metaCast(ioblockstoragedriverClass)) {
+diff --git a/iokit/Kernel/IOUserClient.cpp b/iokit/Kernel/IOUserClient.cpp
+index 07aa0be4a0ca..3832eaff2184 100644
+--- a/iokit/Kernel/IOUserClient.cpp
++++ b/iokit/Kernel/IOUserClient.cpp
+@@ -3536,6 +3536,25 @@ IOCopyPropertyCompatible(IORegistryEntry * regEntry, const char * name)
+ return obj;
+ }
+
++/*
++ * Boot-arg regtrace=1: report the registry properties user space asks for and does not
++ * find (regtrace=2: every property asked for). Shows what a daemon expects of a driver.
++ */
++static TUNABLE(uint32_t, regtrace_level, "regtrace", 0);
++
++static void
++regtrace_report(IORegistryEntry * entry, const char * property, bool found)
++{
++ char procname[32] = "?";
++
++ if (regtrace_level == 0 || (found && regtrace_level < 2)) {
++ return;
++ }
++ proc_selfname(procname, sizeof(procname));
++ IOLog("regtrace: %s[%d] %s(%s).%s %s\n", procname, proc_selfpid(), entry->getName(),
++ entry->getMetaClass()->getClassName(), property, found ? "found" : "MISSING");
++}
++
+ /* Routine io_registry_entry_get_property */
+ kern_return_t
+ is_io_registry_entry_get_property_bytes(
+@@ -3563,6 +3582,7 @@ is_io_registry_entry_get_property_bytes(
+ #endif
+
+ obj = IOCopyPropertyCompatible(entry, property_name);
++ regtrace_report(entry, property_name, obj != NULL);
+ if (!obj) {
+ return kIOReturnNoResources;
+ }
+@@ -3631,6 +3651,7 @@ is_io_registry_entry_get_property(
+ #endif
+
+ obj = IOCopyPropertyCompatible(entry, property_name);
++ regtrace_report(entry, property_name, obj != NULL);
+ if (!obj) {
+ return kIOReturnNotFound;
+ }
+@@ -3679,6 +3700,7 @@ is_io_registry_entry_get_property_recursively(
+
+ obj = entry->copyProperty( property_name,
+ IORegistryEntry::getPlane( plane ), options );
++ regtrace_report(entry, property_name, obj != NULL);
+ if (!obj) {
+ return kIOReturnNotFound;
+ }
+@@ -3873,6 +3895,7 @@ is_io_registry_entry_get_property_bin_buf(
+ }
+
+ err = kIOReturnNotFound;
++ IORegistryEntry * asked = entry;
+ if (gIORegistryEntryPropertyKeysKey == sym) {
+ obj = entry->copyPropertyKeys();
+ } else {
+@@ -3905,6 +3928,7 @@ is_io_registry_entry_get_property_bin_buf(
+ }
+
+ sym->release();
++ regtrace_report(asked, property_name, obj != NULL);
+ if (!obj) {
+ return err;
+ }
+diff --git a/iokit/KernelConfigTables.cpp b/iokit/KernelConfigTables.cpp
+index 2b14eda8f68f..09337bad5b01 100644
+--- a/iokit/KernelConfigTables.cpp
++++ b/iokit/KernelConfigTables.cpp
+@@ -32,6 +32,10 @@
+ * Version 2.0.
+ */
+
++#if defined(__arm64__)
++#include <pexpert/arm64/board_config.h>
++#endif
++
+ const char * gIOKernelConfigTables =
+ "("
+ " {"
+@@ -39,4 +43,11 @@ const char * gIOKernelConfigTables =
+ " 'IOProviderClass' = IOPlatformExpertDevice;"
+ " 'IOProbeScore' = 0:32;"
+ " }"
++#if defined(__arm64__) && !defined(APPLE_ARM64_ARCH_FAMILY)
++ " ,{"
++ " 'IOClass' = GenericARMPE;"
++ " 'IOProviderClass' = IOPlatformExpertDevice;"
++ " 'IOProbeScore' = 1000:32;"
++ " }"
++#endif
+ ")";
+diff --git a/iokit/bsddev/IOKitBSDInit.cpp b/iokit/bsddev/IOKitBSDInit.cpp
+index 5219fb0d9ed6..29978e9cff43 100644
+--- a/iokit/bsddev/IOKitBSDInit.cpp
++++ b/iokit/bsddev/IOKitBSDInit.cpp
+@@ -683,7 +683,14 @@ IOFindBSDRoot( char * rootName, unsigned int rootNameSize,
+ assert(matching);
+ matching->setObject(gIOResourceMatchedKey, gIOBSDKey);
+
+- if ((service = IOService::waitForMatchingService(matching, 30ULL * kSecondScale))) {
++ // A memory-device root needs no filesystem kext, so do not sit out the timeout for one
++ char rdEarly[kMaxBootVar];
++ uint64_t bsdWait = 30ULL * kSecondScale;
++ if (PE_parse_boot_argn("rd", rdEarly, sizeof(rdEarly)) && rdEarly[0] == 'm' && rdEarly[1] == 'd') {
++ bsdWait = kSecondScale / 10;
++ }
++
++ if ((service = IOService::waitForMatchingService(matching, bsdWait))) {
+ OSSafeReleaseNULL(service);
+ } else {
+ IOLog("!BSD\n");
+@@ -762,6 +769,17 @@ IOFindBSDRoot( char * rootName, unsigned int rootNameSize,
+ #endif /* __LP64__ */
+ (void)mdevadd(-1, ml_static_ptovirt(ramdParms[0]) >> 12, (unsigned int) (ramdParms[1] >> 12), 0); /* Initialize it and pass back the device number */
+ }
++ /*
++ * A second image the loader may have left in memory (it becomes
++ * /dev/md1): a volume for user space to mount, never the root.
++ */
++ data = (OSData *)regEntry->getProperty("RAMDisk1");
++ if (data && data->getLength() >= 2 * sizeof(uintptr_t)) {
++ uintptr_t *ramdParms = (uintptr_t *)data->getBytesNoCopy();
++ if (ramdParms[1] <= (((uint64_t)UINT_MAX) << 12)) {
++ (void)mdevadd(-1, ml_static_ptovirt(ramdParms[0]) >> 12, (unsigned int) (ramdParms[1] >> 12), 0);
++ }
++ }
+ regEntry->release(); /* Toss the entry */
+ }
+ }
+diff --git a/iokit/conf/files b/iokit/conf/files
+index 5fb0a52062e0..8dab3e0a364d 100644
+--- a/iokit/conf/files
++++ b/iokit/conf/files
+@@ -79,6 +79,10 @@ iokit/Kernel/IOSubMemoryDescriptor.cpp optional iokitcpp
+ iokit/Kernel/IOGuardPageMemoryDescriptor.cpp optional iokitcpp
+
+ iokit/Kernel/IOPlatformExpert.cpp optional iokitcpp
++iokit/Kernel/GenericARMPE.cpp optional iokitcpp
++iokit/Kernel/MiniIOSurface.cpp optional iokitcpp
++iokit/Kernel/MiniIOMobileFramebuffer.cpp optional iokitcpp
++iokit/Kernel/MiniAppleKeyStore.cpp optional iokitcpp
+ iokit/Kernel/IOPlatformIO.cpp optional iokitcpp
+
+ iokit/Kernel/IOCPU.cpp optional iokitcpp
+diff --git a/libkern/conf/files b/libkern/conf/files
+index ece14c7d41d3..4a903f73a9ef 100644
+--- a/libkern/conf/files
++++ b/libkern/conf/files
+@@ -109,6 +109,8 @@ libkern/apple_encrypted_archive/apple_encrypted_archive.c standard
+ libkern/img4/interface.c standard
+
+ libkern/amfi/amfi.c standard
++libkern/amfi/miniamfi.c standard
++libkern/amfi/miniamfi_entitlements.cpp standard
+
+ libkern/stack_protector.c standard
+ libkern/ptrauth_utils.c standard
+diff --git a/libkern/libkern/c++/OSData.h b/libkern/libkern/c++/OSData.h
+index 28ea44c2ae9d..9c7a1fe9e23e 100644
+--- a/libkern/libkern/c++/OSData.h
++++ b/libkern/libkern/c++/OSData.h
+@@ -965,7 +965,7 @@ private:
+ "only trivially copyable types can be contained");
+ static_assert(!__is_pointer(T) || (acquisition == kValueNoCopy),
+ "pointers cannot be contained");
+- static_assert(KALLOC_TYPE_IS_DATA_ONLY(T) || (acquisition == kValueNoCopy),
++ static_assert(XNU_NO_TYPE_BUILTINS || KALLOC_TYPE_IS_DATA_ONLY(T) || (acquisition == kValueNoCopy),
+ "only plain data types can be contained (consider using OSValueObject)");
+ return 0; // C++11 does not support void-returning constexpr functions
+ }
+diff --git a/makedefs/MakeInc.cmd b/makedefs/MakeInc.cmd
+index bc39e19b3b8e..0a72a2d43908 100644
+--- a/makedefs/MakeInc.cmd
++++ b/makedefs/MakeInc.cmd
+@@ -100,12 +100,12 @@ ifeq ($(VERBOSE),YES)
+ _v =
+ _vstdout =
+ _vstderr =
+- XCRUN = /usr/bin/xcrun -verbose
++ XCRUN = xcrun -verbose
+ else
+ _v = @
+ _vstdout = > /dev/null
+ _vstderr = 2> /dev/null
+- XCRUN = /usr/bin/xcrun
++ XCRUN = xcrun
+ endif
+
+ VERBOSE_GENERATED_MAKE_FRAGMENTS = NO
+@@ -275,27 +275,27 @@ REPLACECONTENTS = $(OBJROOT)/SETUP/replacecontents/replacecontents
+ JSONCOMPILATIONDB = $(OBJROOT)/SETUP/json_compilation_db/json_compilation_db
+
+ # Standard BSD tools
+-RM = /bin/rm -f
+-RMDIR = /bin/rmdir
+-CP = /bin/cp
+-MV = /bin/mv
+-LN = /bin/ln -fs
+-CAT = /bin/cat
+-MKDIR = /bin/mkdir -p
+-CHMOD = /bin/chmod
+-FIND = /usr/bin/find
+-XARGS = /usr/bin/xargs
+-PAX = /bin/pax
+-BASENAME = /usr/bin/basename
+-DIRNAME = /usr/bin/dirname
+-TR = /usr/bin/tr
+-TOUCH = /usr/bin/touch
+-SLEEP = /bin/sleep
+-AWK = /usr/bin/awk
+-SED = /usr/bin/sed
+-PLUTIL = /usr/bin/plutil
+-PATCH = /usr/bin/patch
+-GREP = /usr/bin/grep
++RM = rm -f
++RMDIR = rmdir
++CP = cp
++MV = mv
++LN = ln -fs
++CAT = cat
++MKDIR = mkdir -p
++CHMOD = chmod
++FIND = find
++XARGS = xargs
++PAX = pax
++BASENAME = basename
++DIRNAME = dirname
++TR = tr
++TOUCH = touch
++SLEEP = sleep
++AWK = awk
++SED = sed
++PLUTIL = plutil
++PATCH = patch
++GREP = grep
+
+ #
+ # Command to generate host binaries. Intentionally not
+@@ -317,7 +317,7 @@ ifeq ($(origin HOST_GM4),undefined)
+ export HOST_GM4 := $(shell $(XCRUN) -sdk $(HOST_SDKROOT) -find gm4)
+ endif
+ ifeq ($(origin HOST_CODESIGN),undefined)
+- export HOST_CODESIGN := /usr/bin/codesign
++ export HOST_CODESIGN := codesign
+ endif
+ ifeq ($(origin HOST_CODESIGN_ALLOCATE),undefined)
+ export HOST_CODESIGN_ALLOCATE := $(shell $(XCRUN) -sdk $(HOST_SDKROOT) -find codesign_allocate)
+diff --git a/makedefs/MakeInc.def b/makedefs/MakeInc.def
+index 5bd6f23dd10c..ac87cd36d158 100644
+--- a/makedefs/MakeInc.def
++++ b/makedefs/MakeInc.def
+@@ -60,7 +60,7 @@ MACHINE_FLAGS_ARM64_T8101 = -DARM64_BOARD_CONFIG_T8101 -mcpu=apple-a14
+ MACHINE_FLAGS_ARM64_T8103 = -DARM64_BOARD_CONFIG_T8103 -mcpu=apple-a14
+ MACHINE_FLAGS_ARM64_T6000 = -DARM64_BOARD_CONFIG_T6000 -mcpu=apple-a14
+ MACHINE_FLAGS_ARM64_VMAPPLE = -DARM64_BOARD_CONFIG_VMAPPLE -march=armv8.5a
+-MACHINE_FLAGS_ARM64_BCM2837 = -DARM64_BOARD_CONFIG_BCM2837
++MACHINE_FLAGS_ARM64_BCM2837 = -DARM64_BOARD_CONFIG_BCM2837 -Xclang -target-feature -Xclang +pan
+
+
+ #
+@@ -857,7 +857,7 @@ LDFILES_KERNEL_ONLY = $(TARGET)/all-kpi.exp $(TARGET)/all-alias.exp $(TARGET)/sy
+ # Default runtime libraries to be linked with the kernel
+ #
+ LD_KERNEL_LIBS = -lcc_kext
+-LD_KERNEL_ARCHIVES = $(LDFLAGS_KERNEL_SDK) -lfirehose_kernel
++LD_KERNEL_ARCHIVES = $(LDFLAGS_KERNEL_SDK) -lfirehose_kernel -lpthread_kext
+ # Link opensource binary library
+ ifneq ($(filter T6000 T8101 VMAPPLE T6000 T8101 VMAPPLE,$(CURRENT_MACHINE_CONFIG)),)
+ LDFLAGS_KERNEL_ONLY += -rdynamic -Wl,-force_load,$(KDKROOT)/System/Library/KernelSupport/lib$(CURRENT_MACHINE_CONFIG).os.$(CURRENT_KERNEL_CONFIG).a
+diff --git a/makedefs/MakeInc.top b/makedefs/MakeInc.top
+index 0316792a3f42..bbef0a4b26d4 100644
+--- a/makedefs/MakeInc.top
++++ b/makedefs/MakeInc.top
+@@ -285,7 +285,7 @@ endif
+ # $(warning PRIMARY_KERNEL_CONFIGS is $(PRIMARY_KERNEL_CONFIGS))
+ # $(warning VARIANT_CONFIGS is $(VARIANT_CONFIGS))
+
+-MEMORY_SIZE := $(shell /usr/sbin/sysctl -n hw.memsize)
++MEMORY_SIZE := $(shell awk '/MemTotal/{printf "%d", $$2*1024}' /proc/meminfo)
+
+ # Assume LTO scaling by default, unless it is being explicitly passed on the command-line
+ LARGE_BUILD_FOOTPRINT := $(if $(BUILD_LTO),$(BUILD_LTO),1)
+diff --git a/osfmk/arm/arm_init.c b/osfmk/arm/arm_init.c
+index e26a1d70f470..5bd6037e6b02 100644
+--- a/osfmk/arm/arm_init.c
++++ b/osfmk/arm/arm_init.c
+@@ -335,7 +335,11 @@ arm_setup_pre_sign(void)
+ */
+
+ __startup_func
++/* Bring-up checkpoints, see osfmk/arm64/loader_return.c */
++extern void loader_checkpoint(uint64_t n);
++
+ void
++
+ arm_init(
+ boot_args *args)
+ {
+@@ -354,6 +358,7 @@ arm_init(
+ const_boot_args = *args;
+ BootArgs = args = &const_boot_args;
+
++ loader_checkpoint(10);
+ cpu_data_init(&BootCpuData);
+ #if defined(HAS_APPLE_PAC)
+ /* bootstrap cpu process dependent key for kernel has been loaded by start.s */
+@@ -362,14 +367,19 @@ arm_init(
+ #endif /* defined(HAS_APPLE_PAC) */
+
+ PE_init_platform(FALSE, args); /* Get platform expert set up */
++ loader_checkpoint(11);
+
+ #if __arm64__
+ configure_timer_apple_regs();
++ loader_checkpoint(30);
+ wfe_timeout_configure();
++ loader_checkpoint(31);
+ wfe_timeout_init();
++ loader_checkpoint(32);
+
+ configure_misc_apple_boot_args();
+ configure_misc_apple_regs();
++ loader_checkpoint(33);
+
+ #if (DEVELOPMENT || DEBUG)
+ unsigned long const *platform_stall_ptr = NULL;
+@@ -385,6 +395,7 @@ arm_init(
+ }
+
+ platform_stall_panic_or_spin(PLATFORM_STALL_XNU_LOCATION_ARM_INIT);
++ loader_checkpoint(34);
+
+ chosen = NULL; // Force a re-lookup later on since VM addresses are not final at this point
+ dt_entry_size = 0;
+@@ -422,10 +433,13 @@ arm_init(
+ }
+ #endif
+
++ loader_checkpoint(35);
+ ml_parse_cpu_topology();
++ loader_checkpoint(12);
+
+
+ master_cpu = ml_get_boot_cpu_number();
++ loader_checkpoint(40);
+ assert(master_cpu >= 0 && master_cpu <= ml_get_max_cpu_number());
+
+ BootCpuData.cpu_number = (unsigned short)master_cpu;
+@@ -439,11 +453,14 @@ arm_init(
+ CpuDataEntries[master_cpu].cpu_data_paddr = (void *)((uintptr_t)(args->physBase)
+ + ((uintptr_t)&BootCpuData
+ - (uintptr_t)(args->virtBase)));
++ loader_checkpoint(41);
+
+ thread = thread_bootstrap();
++ loader_checkpoint(42);
+ thread->machine.CpuDatap = &BootCpuData;
+ thread->machine.pcpu_data_base = (vm_offset_t)0;
+ machine_set_current_thread(thread);
++ loader_checkpoint(43);
+
+ /*
+ * Preemption is enabled for this thread so that it can lock mutexes without
+@@ -452,12 +469,16 @@ arm_init(
+ * preemption level is not really meaningful for the bootstrap thread.
+ */
+ thread->machine.preemption_count = 0;
++ loader_checkpoint(44);
+ cpu_bootstrap();
++ loader_checkpoint(13);
+
+ rtclock_early_init();
++ loader_checkpoint(14);
+
+ kernel_debug_string_early("kernel_startup_bootstrap");
+ kernel_startup_bootstrap();
++ loader_checkpoint(15);
+
+ /*
+ * Initialize the timer callout world
+@@ -465,6 +486,7 @@ arm_init(
+ timer_call_init();
+
+ cpu_init();
++ loader_checkpoint(16);
+
+ processor_bootstrap();
+
+@@ -514,6 +536,7 @@ arm_init(
+ #endif /* __ARM_PAN_AVAILABLE__ */
+
+ arm_vm_init(xmaxmem, args);
++ loader_checkpoint(17);
+
+ if (debug_boot_arg) {
+ patch_low_glo();
+@@ -527,7 +550,9 @@ arm_init(
+
+ /* Setup debugging output. */
+ const unsigned int serial_exists = serial_init();
++ loader_checkpoint(18);
+ kernel_startup_initialize_upto(STARTUP_SUB_KPRINTF);
++ loader_checkpoint(19);
+ kprintf("kprintf initialized\n");
+
+ serialmode = 0;
+@@ -569,6 +594,7 @@ arm_init(
+ disableConsoleOutput = FALSE; /* Allow printfs to happen */
+ }
+ PE_create_console();
++ loader_checkpoint(20);
+
+ /* setup console output */
+ PE_init_printf(FALSE);
+@@ -647,6 +673,7 @@ arm_init(
+ * against string vulnerabilities
+ */
+ __stack_chk_guard &= ~(0xFFULL << 8);
++ loader_checkpoint(21);
+ machine_startup(args);
+ }
+
+diff --git a/osfmk/arm/pmap/pmap.c b/osfmk/arm/pmap/pmap.c
+index fc2096fa0010..d71b2640cb8c 100644
+--- a/osfmk/arm/pmap/pmap.c
++++ b/osfmk/arm/pmap/pmap.c
+@@ -93,6 +93,8 @@
+
+ #include <pexpert/device_tree.h>
+
++MARK_AS_PMAP_TEXT static void pmap_phys_write_disable(vm_address_t va);
++
+ #include <san/kasan.h>
+ #include <sys/cdefs.h>
+
+@@ -4676,8 +4678,8 @@ pmap_page_protect_options_with_flush_range(
+ }
+ #endif
+ if (remove && (options & PMAP_OPTIONS_COMPRESSOR)) {
+- panic("pmap_page_protect: attempt to compress ppnum 0x%x owned by iommu %p, pve_p=%p",
+- ppnum, ptep_get_iommu(pte_p), pve_p);
++ panic("pmap_page_protect: attempt to compress ppnum 0x%x owned by iommu, pte_p=%p, pve_p=%p",
++ ppnum, pte_p, pve_p);
+ }
+ goto protect_skip_pve_pass1;
+ }
+@@ -11623,7 +11625,8 @@ pmap_cs_lockdown_pages(vm_address_t kva, vm_size_t size, bool ppl_writable)
+ #if XNU_MONITOR
+ pmap_ppl_lockdown_pages(kva, size, PVH_FLAG_LOCKDOWN_CS, ppl_writable);
+ #else
+- pmap_ppl_lockdown_pages(kva, size, 0, ppl_writable);
++ /* No PPL on this platform: nothing to lock down. */
++ (void)kva; (void)size; (void)ppl_writable;
+ #endif
+ }
+
+@@ -11633,7 +11636,8 @@ pmap_cs_unlockdown_pages(vm_address_t kva, vm_size_t size, bool ppl_writable)
+ #if XNU_MONITOR
+ pmap_ppl_unlockdown_pages(kva, size, PVH_FLAG_LOCKDOWN_CS, ppl_writable);
+ #else
+- pmap_ppl_unlockdown_pages(kva, size, 0, ppl_writable);
++ /* No PPL on this platform: nothing to lock down. */
++ (void)kva; (void)size; (void)ppl_writable;
+ #endif
+ }
+
+diff --git a/osfmk/arm/pmap/pmap.h b/osfmk/arm/pmap/pmap.h
+index df672c65b144..d7e1da7c5db2 100644
+--- a/osfmk/arm/pmap/pmap.h
++++ b/osfmk/arm/pmap/pmap.h
+@@ -112,7 +112,13 @@
+ */
+ #define BOOTSTRAP_TABLE_SIZE (ARM_PGBYTES * 34)
+ #else /* defined(ARM_LARGE_MEMORY) */
+-#define BOOTSTRAP_TABLE_SIZE (ARM_PGBYTES * 8)
++/*
++ * With 4K pages every GB of DRAM costs one L2 page in each of the two
++ * bootstrap mappings (start.s maps all of memSize). Apple sized this for a
++ * 2 GB device (8 pages); 20 pages cover 8 GB, enough for a boot image of
++ * several GB next to the kernel.
++ */
++#define BOOTSTRAP_TABLE_SIZE (ARM_PGBYTES * 20)
+ #endif /* defined(ARM_LARGE_MEMORY) */
+
+ typedef uint64_t tt_entry_t; /* translation table entry type */
+@@ -442,7 +448,7 @@ struct pmap {
+ #if HAS_APPLE_PAC
+ bool disable_jop;
+ #else
+- bool reserved10;
++ bool reserved12;
+ #endif /* HAS_APPLE_PAC */
+
+ bool reserved11;
+diff --git a/osfmk/arm64/corecrypto/arm64_isa_compatibility.h b/osfmk/arm64/corecrypto/arm64_isa_compatibility.h
+index b9549da357b4..cca31ea32502 100644
+--- a/osfmk/arm64/corecrypto/arm64_isa_compatibility.h
++++ b/osfmk/arm64/corecrypto/arm64_isa_compatibility.h
+@@ -28,7 +28,7 @@
+ // #include <Availability.h>
+ #include <sys/cdefs.h>
+
+-#if defined(__clang__) && ((defined(__apple_build_version__) && __apple_build_version__ > 5010000))
++#if defined(__clang__) && (!defined(__apple_build_version__) || __apple_build_version__ > 5010000)
+ #define __USES_V_CRYPTO_INTRINSICS 1
+ #else
+ #define __USES_V_CRYPTO_INTRINSICS 0
+diff --git a/osfmk/arm64/machine_routines.c b/osfmk/arm64/machine_routines.c
+index e76e7e70ab9c..d702d171e3d1 100644
+--- a/osfmk/arm64/machine_routines.c
++++ b/osfmk/arm64/machine_routines.c
+@@ -734,6 +734,8 @@ ml_get_machine_mem(void)
+ return machine_info.memory_size;
+ }
+
++extern void loader_return(void);
++
+ __attribute__((noreturn))
+ void
+ halt_all_cpus(boolean_t reboot)
+@@ -745,6 +747,8 @@ halt_all_cpus(boolean_t reboot)
+ printf("CPU halted\n");
+ PEHaltRestart(kPEHaltCPU);
+ }
++ /* No platform driver powers the machine off: hand control (and the log) back to the loader. */
++ loader_return();
+ while (1) {
+ ;
+ }
+@@ -2237,8 +2241,16 @@ _enable_virtual_timer(void)
+ uint64_t cntvctl = CNTV_CTL_EL0_ENABLE; /* One wants to use 32 bits, but "mrs" prefers it this way */
+
+ __builtin_arm_wsr64("CNTV_CTL_EL0", cntvctl);
++#if defined(APPLE_ARM64_ARCH_FAMILY)
+ /* disable the physical timer as a precaution, as its registers reset to architecturally unknown values */
+ __builtin_arm_wsr64("CNTP_CTL_EL0", CNTP_CTL_EL0_IMASKED);
++#else
++ /*
++ * When running at EL1 under a third-party hypervisor (e.g. Qualcomm's),
++ * the EL1 physical timer registers are trapped and the access faults.
++ * The guest only owns the virtual timer.
++ */
++#endif
+ }
+
+ void
+diff --git a/osfmk/arm64/start.s b/osfmk/arm64/start.s
+index e5336e5a1cce..df132aa3c772 100644
+--- a/osfmk/arm64/start.s
++++ b/osfmk/arm64/start.s
+@@ -233,40 +233,88 @@ LEXT(_start)
+ .global EXT(LowExceptionVectorBase)
+ LEXT(LowExceptionVectorBase)
+ /* EL1 SP 0 */
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ /* EL1 SP1 */
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ /* EL0 64 */
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ /* EL0 32 */
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
+ .align 7
+- b .
++ b Lloader_early_exception
++
++/*
++ * Early-boot exceptions used to spin here. When the XNU loader has patched
++ * the address of its return stub into the slot below, report the exception
++ * to it instead (see osfmk/arm64/loader_return.c):
++ * x0/x1 = PA/length of the captured kernel log, x2 = 1 (early exception),
++ * x3 = ESR, x4 = ELR, x5 = FAR, x6 = LR, x7 = SP
++ * This vector is only installed while VBAR holds a physical address, so
++ * PC-relative addressing yields physical addresses, MMU on (V=P) or off.
++ */
++ .align 3
++Lloader_early_exception:
++ mov x6, lr
++ mov x7, sp
++ mrs x3, ESR_EL1
++ mrs x4, ELR_EL1
++ mrs x5, FAR_EL1
++ adrp x0, EXT(loader_log)@page
++ add x0, x0, EXT(loader_log)@pageoff
++ adrp x1, EXT(loader_log_len)@page
++ add x1, x1, EXT(loader_log_len)@pageoff
++ ldr w1, [x1]
++ // Write the log back to RAM: cached copies are lost once the MMU is off
++ mov x9, x0
++ add x10, x0, x1
++1:
++ dc cvac, x9
++ add x9, x9, #64
++ cmp x9, x10
++ b.lo 1b
++ dsb sy
++ mov x2, #1
++ mrs x9, SCTLR_EL1
++ bic x9, x9, #1
++ msr SCTLR_EL1, x9
++ isb
++ adr x9, Lloader_stub_slot
++ ldr x9, [x9, #8]
++ cbz x9, .
++ br x9
++ .align 3
++ .globl EXT(loader_stub_slot)
++LEXT(loader_stub_slot)
++Lloader_stub_slot:
++ .ascii "XNULDRST" // magic the loader searches for
++ .quad 0 // PA of the loader's return stub
++ .quad 0 // checkpoint number to stop at (0 = none)
++ .quad 0 // (physical - virtual) offset of the static kernel image
+ .align 12, 0
+
+ #if defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR)
+@@ -452,22 +500,51 @@ start_cpu:
+ * Cold boot init routine. Called from __start
+ * x0 - Boot args
+ */
++/*
++ * LOADER_CHECKPOINT n
++ * Bring-up aid: if the loader asked to stop at checkpoint n, return to it
++ * right here (reason 2, code n). Usable while executing at physical
++ * addresses, MMU off or on (V=P). Clobbers x0-x3, x9-x11.
++ */
++.macro LOADER_CHECKPOINT
++ adrp x9, EXT(loader_stub_slot)@page
++ add x9, x9, EXT(loader_stub_slot)@pageoff
++ ldr x10, [x9, #16]
++ cmp x10, #$0
++ b.ne 1f
++ mov x0, #0
++ mov x1, #0
++ mov x2, #2
++ mov x3, #$0
++ mrs x11, SCTLR_EL1
++ bic x11, x11, #1
++ msr SCTLR_EL1, x11
++ isb
++ ldr x9, [x9, #8]
++ br x9
++1:
++.endmacro
++
+ .align 2
+ .globl EXT(start_first_cpu)
+ LEXT(start_first_cpu)
+
+- // Unlock the core for debugging
+- msr OSLAR_EL1, xzr
+ msr DAIFSet, #(DAIFSC_ALL) // Disable all interrupts
+
+ mov x20, x0
+ mov x21, #0
++ LOADER_CHECKPOINT 1
+
+- // Set low reset vector before attempting any loads
++ // Set low reset vector before attempting anything that might trap
++ // (under a third-party hypervisor even the OS lock write below can).
+ adrp x0, EXT(LowExceptionVectorBase)@page
+ add x0, x0, EXT(LowExceptionVectorBase)@pageoff
+ MSR_VBAR_EL1_X0
+
++ // Unlock the core for debugging
++ msr OSLAR_EL1, xzr
++ LOADER_CHECKPOINT 2
++
+
+ // Get the kernel memory parameters from the boot args
+ ldr x22, [x20, BA_VIRT_BASE] // Get the kernel virt base
+@@ -612,6 +689,7 @@ Lkernelcache_base_found:
+ /* Ensure TTEs are visible */
+ dsb ish
+
++ LOADER_CHECKPOINT 3
+
+ b common_start
+
+@@ -686,7 +764,10 @@ common_start:
+ dsb ish
+
+
+-#if defined(BCM2837)
++#if defined(BCM2837) && defined(BCM2837_CORE_TIMER_ROUTING)
++ // Raspberry Pi 3 only: pokes the SoC's local-interrupt block at a fixed
++ // physical address (0x4000004X). Fatal on any other board, so it is
++ // disabled unless explicitly requested.
+ // Setup timer interrupt routing; must be done before MMU is enabled
+ mrs x15, MPIDR_EL1 // Load MPIDR to get CPU number
+ and x15, x15, #0xFF // CPU number is in MPIDR Affinity Level 0
+@@ -740,10 +821,17 @@ common_start:
+ PAC_INIT_KEY_STATE tmp=x0, tmp2=x1
+ #endif /* HAS_APPLE_PAC */
+
++ cbnz x21, 1f // boot CPU cold start only
++ LOADER_CHECKPOINT 4
++1:
+ // Enable caches, MMU, ROP and JOP
+ MOV64 x0, SCTLR_EL1_DEFAULT
+ MSR_SCTLR_EL1_X0
+ isb sy
++ cbnz x21, 1f
++ LOADER_CHECKPOINT 5
++ MOV64 x0, SCTLR_EL1_DEFAULT // restore what the checkpoint clobbered
++1:
+
+ #if !VMAPPLE
+ MOV64 x1, SCTLR_EL1_DEFAULT
+diff --git a/osfmk/conf/files b/osfmk/conf/files
+index 9d98c50094a0..9e3476124e54 100644
+--- a/osfmk/conf/files
++++ b/osfmk/conf/files
+@@ -361,3 +361,6 @@ osfmk/corecrypto/ccsha256_ltc_di.c standard
+
+ osfmk/prng/prng_random.c standard
+ osfmk/prng/entropy.c standard
++osfmk/minicrypto/mc_digests.c standard
++osfmk/minicrypto/mc_provider.c standard
++osfmk/minicrypto/mc_aes.c standard
+diff --git a/osfmk/conf/files.arm64 b/osfmk/conf/files.arm64
+index c40d57bcc677..6e1041216be1 100644
+--- a/osfmk/conf/files.arm64
++++ b/osfmk/conf/files.arm64
+@@ -25,8 +25,8 @@ osfmk/arm64/WKdmCompress_4k.s standard
+ osfmk/arm64/WKdmData.s standard
+ osfmk/arm64/lz4_decode_arm64.s standard
+ osfmk/arm64/lz4_encode_arm64.s standard
+-osfmk/arm64/amcc_rorgn_ppl.c optional nos_arm_asm config_pmap_ppl
+-osfmk/arm64/amcc_rorgn_common.c optional nos_arm_asm
++#osfmk/arm64/amcc_rorgn_ppl.c optional nos_arm_asm config_pmap_ppl
++#osfmk/arm64/amcc_rorgn_common.c optional nos_arm_asm
+ osfmk/arm64/bcopy.s standard
+ osfmk/arm64/bzero.s standard
+ osfmk/arm/caches.c standard
+@@ -104,3 +104,7 @@ osfmk/arm64/machine_remote_time.c optional config_mach_bridge_recv_time
+ osfmk/arm64/corecrypto/sha256_compress_arm64.s standard
+
+ osfmk/arm/counter.c standard
++osfmk/arm64/generic_arm64_support.c optional nos_arm_asm
++osfmk/arm64/loader_return.c optional nos_arm_asm
++osfmk/arm64/user_exception_trace.c standard
++osfmk/arm64/gic_v3_irq.c optional nos_arm_asm
+diff --git a/osfmk/console/video_console.c b/osfmk/console/video_console.c
+index 384118e8d7a9..2573d2ebd4e6 100644
+--- a/osfmk/console/video_console.c
++++ b/osfmk/console/video_console.c
+@@ -2855,8 +2855,12 @@ initialize_screen(PE_Video * boot_vinfo, unsigned int op)
+ gc_acquired = TRUE;
+ } else {
+ if (makeMapping) {
+-#if HAS_UCNORMAL_MEM
++#if HAS_UCNORMAL_MEM || defined(BCM2837)
+ /*
++ * (Generic ARM boards too: scrolling reads the framebuffer
++ * back, and as device memory that is one bus access per
++ * word - seconds per line on a phone-sized screen.)
++ *
+ * Framebuffers would normally use VM_WIMG_RT, which
+ * io_map doesn't support. However this buffer is set up
+ * by the bootloader and doesn't require D$ cleaning, so
+diff --git a/osfmk/kern/debug.c b/osfmk/kern/debug.c
+index 0a00656a0fdd..bfad3cbca5bc 100644
+--- a/osfmk/kern/debug.c
++++ b/osfmk/kern/debug.c
+@@ -1147,9 +1147,12 @@ panic_trap_to_debugger(const char *panic_format_str, va_list *panic_args, unsign
+ __builtin_unreachable();
+ }
+
++extern void loader_return(void);
++
+ void
+ panic_spin_forever(void)
+ {
++ loader_return();
+ for (;;) {
+ #if defined(__arm__) || defined(__arm64__)
+ /* On arm32, which doesn't have a WFE timeout, this may not return. But that should be OK on this path. */
+@@ -1163,6 +1166,7 @@ panic_spin_forever(void)
+ static void
+ kdp_machine_reboot_type(unsigned int type, uint64_t debugger_flags)
+ {
++ loader_return();
+ if ((type == kPEPanicRestartCPU) && (debugger_flags & DEBUGGER_OPTION_SKIP_PANICEND_CALLOUTS)) {
+ PEHaltRestart(kPEPanicRestartCPUNoCallouts);
+ } else {
+diff --git a/osfmk/kern/exception.c b/osfmk/kern/exception.c
+index 809dafaaa2a7..71c6580f44e2 100644
+--- a/osfmk/kern/exception.c
++++ b/osfmk/kern/exception.c
+@@ -636,6 +636,11 @@ check_exc_receiver_dependency(
+ * Returns:
+ * KERN_SUCCESS if exception is handled by any of the handlers.
+ */
++#if defined(__arm64__)
++extern void user_exception_trace(exception_type_t exception, mach_exception_data_t code,
++ mach_msg_type_number_t count, thread_t thread);
++#endif
++
+ kern_return_t
+ exception_triage_thread(
+ exception_type_t exception,
+@@ -650,6 +655,11 @@ exception_triage_thread(
+ struct exception_action *actions;
+ kern_return_t kr = KERN_FAILURE;
+
++#if defined(__arm64__)
++ /* bring-up aid, see osfmk/arm64/user_exception_trace.c */
++ user_exception_trace(exception, code, codeCnt, thread);
++#endif
++
+ assert(exception != EXC_RPC_ALERT);
+
+ /*
+diff --git a/osfmk/kern/kalloc.h b/osfmk/kern/kalloc.h
+index dfa89c7b0d29..07e0ba5bf44c 100644
+--- a/osfmk/kern/kalloc.h
++++ b/osfmk/kern/kalloc.h
+@@ -821,12 +821,16 @@ __options_decl(kt_granule_t, uint32_t, {
+ * @param ptr the pointer whose type needs to be checked.
+ * @param type the type which the pointer will be checked against.
+ */
++#if XNU_NO_TYPE_BUILTINS
++#define KALLOC_TYPE_IS_COMPATIBLE_PTR(ptr, type) (1)
++#else
+ #define KALLOC_TYPE_IS_COMPATIBLE_PTR(ptr, type) \
+ _Pragma("clang diagnostic push") \
+ _Pragma("clang diagnostic ignored \"-Wvoid-ptr-dereference\"") \
+ (__builtin_xnu_types_compatible(__typeof__(*(ptr)), type) || \
+ __builtin_xnu_types_compatible(__typeof__(*(ptr)), void)) \
+ _Pragma("clang diagnostic pop")
++#endif /* XNU_NO_TYPE_BUILTINS */
+
+ #define KALLOC_TYPE_ASSERT_COMPATIBLE_POINTER(ptr, type) \
+ _Static_assert(KALLOC_TYPE_IS_COMPATIBLE_PTR(ptr, type), \
+diff --git a/osfmk/kern/percpu.h b/osfmk/kern/percpu.h
+index 4fb223ee9788..df563bc04910 100644
+--- a/osfmk/kern/percpu.h
++++ b/osfmk/kern/percpu.h
+@@ -236,15 +236,22 @@ extern vm_offset_t other_percpu_base(int cpu_number);
+ * @param it the name of the iterator
+ * @param name the per-CPU variable name
+ */
++/*
++ * (redwood) All of the arithmetic is on integers here. As Apple wrote it, the end was a pointer
++ * computed from the start, and a compiler may then take "start <= start + n" for "n >= 0":
++ * with one processor start is VM_MAX_KERNEL_ADDRESS and end is 0, n looks positive, and the
++ * loop that must not run at all runs once on memory that does not exist (clang 18+ does this;
++ * the panic was in mbuf_mtypes_sync(), the first time a daemon asked for the mbuf statistics).
++ */
+ #define percpu_foreach_secondary(it, name) \
+ for (__PERCPU_TYPE(name) it, \
+- __base_ ## it = (typeof(it))__unsafe_forge_bidi_indexable(void *, percpu_base.start, percpu_base.end - percpu_base.start), \
+- __end_ ## it = (typeof(it))((caddr_t)__base_ ## it + percpu_base.end - percpu_base.start); \
++ __base_ ## it = (typeof(it))percpu_base.start, \
++ __end_ ## it = (typeof(it))percpu_base.end; \
+ \
+- (it = (typeof(it))((caddr_t)__base_ ## it + __PERCPU_ADDR(name)), \
+- __base_ ## it <= __end_ ## it); \
++ (it = (typeof(it))((vm_address_t)__base_ ## it + __PERCPU_ADDR(name)), \
++ (vm_address_t)__base_ ## it <= (vm_address_t)__end_ ## it); \
+ \
+- __base_ ## it = (typeof(it))((caddr_t)__base_ ## it + percpu_section_size()))
++ __base_ ## it = (typeof(it))((vm_address_t)__base_ ## it + percpu_section_size()))
+
+ #pragma mark - implementation details
+
+diff --git a/osfmk/kern/startup.c b/osfmk/kern/startup.c
+index bec97fbf7243..203e1f48783f 100644
+--- a/osfmk/kern/startup.c
++++ b/osfmk/kern/startup.c
+@@ -156,6 +156,7 @@
+ #include <security/mac_mach_internal.h>
+ #if CONFIG_VNGUARD
+ extern void vnguard_policy_init(void);
++extern void minimac_policy_init(void);
+ #endif
+ #endif
+
+@@ -721,6 +722,9 @@ kernel_bootstrap_thread(void)
+ kernel_bootstrap_log("vnguard_policy_init");
+ vnguard_policy_init();
+ #endif
++ /* stand-ins for the AMFI and Sandbox policies (bsd/kern/kern_minimac.c) */
++ kernel_bootstrap_log("minimac_policy_init");
++ minimac_policy_init();
+ #endif
+
+ #if CONFIG_DTRACE
+diff --git a/pexpert/arm/pe_fiq.c b/pexpert/arm/pe_fiq.c
+index 3ad743fc3efb..ce036c5a2c26 100644
+--- a/pexpert/arm/pe_fiq.c
++++ b/pexpert/arm/pe_fiq.c
+@@ -169,6 +169,15 @@ pe_init_fiq()
+ __builtin_arm_wsr64("ICC_IGRPEN0_EL1", 1);
+ __builtin_arm_isb(ISB_SY);
+ }
++#elif defined(GENERIC_GIC_V3_IRQ)
++/* Generic boards: Group 1 IRQs through a GICv3, see osfmk/arm64/gic_v3_irq.c */
++extern void gic_v3_irq_cpu_init(void);
++
++void
++pe_init_fiq()
++{
++ gic_v3_irq_cpu_init();
++}
+ #else
+ void
+ pe_init_fiq()
+diff --git a/pexpert/arm/pe_kprintf.c b/pexpert/arm/pe_kprintf.c
+index 65144c74239c..ab6260d52d84 100644
+--- a/pexpert/arm/pe_kprintf.c
++++ b/pexpert/arm/pe_kprintf.c
+@@ -29,6 +29,7 @@ SECURITY_READ_ONLY_LATE(bool) enable_dklog_serial_output = false;
+ static SIMPLE_LOCK_DECLARE(kprintf_lock, 0);
+
+ static void serial_putc_crlf(char c);
++extern void loader_log_putc(char c);
+
+ __startup_func
+ static void
+@@ -159,6 +160,7 @@ serial_putc_crlf(char c)
+ if (c == '\n') {
+ uart_putc('\r');
+ }
++ loader_log_putc(c);
+ uart_putc(c);
+ }
+
+diff --git a/pexpert/pexpert/arm64/BCM2837.h b/pexpert/pexpert/arm64/BCM2837.h
+index d9f0723244e5..e78fb263d98a 100644
+--- a/pexpert/pexpert/arm64/BCM2837.h
++++ b/pexpert/pexpert/arm64/BCM2837.h
+@@ -11,6 +11,14 @@
+ #define BCM2837
+ #define BCM2837_BRINGUP
+ #define ARM_ARCH_TIMER
++#define GENERIC_GIC_V3_IRQ 1 /* interrupts via GICv3 Group 1, see osfmk/arm64/gic_v3_irq.c */
++
++/*
++ * The cores this kernel really runs on (Cortex-A55/A78, QEMU cortex-a76) are
++ * ARMv8.2: they set PSTATE.PAN on every exception entry, so the kernel must
++ * know to lift it around user memory accesses.
++ */
++#define __ARM_PAN_AVAILABLE__ 1
+
+ #define __ARM_ARCH__ 8
+ #define __ARM_VMSA__ 8
+@@ -22,6 +30,7 @@
+ #ifndef ASSEMBLER
+
+ #define PI3_UART
++#define VMAPPLE_UART /* PL011, as found on QEMU virt */
+
+ #define PI3_BREAK asm volatile("brk #0");
+
+@@ -60,8 +69,11 @@
+ #define BCM2837_PUT32(addr, value) do { *((volatile uint32_t *) addr) = value; } while(0)
+ #define BCM2837_GET32(addr) *((volatile uint32_t *) addr)
+
+-#define PLATFORM_PANIC_LOG_PADDR 0x3c0fc000
+-#define PLATFORM_PANIC_LOG_SIZE 16384 // 16kb
++/*
++ * No fixed PLATFORM_PANIC_LOG_PADDR: the Raspberry Pi address (0x3c0fc000) is
++ * not RAM on other boards. The panic log region comes from the device tree
++ * instead (/pram and /chosen/embedded-panic-log-size), like on Apple devices.
++ */
+ #endif /* ! ASSEMBLER */
+
+ #endif /* ! _PEXPERT_ARM_BCM2837_H */
+diff --git a/security/mac_vfs_subr.c b/security/mac_vfs_subr.c
+index 97028c06bb92..0daad830d0c0 100644
+--- a/security/mac_vfs_subr.c
++++ b/security/mac_vfs_subr.c
+@@ -167,7 +167,7 @@ mac_vnop_setxattr(struct vnode *vp, const char *name, char *buf, size_t len)
+ {
+ vfs_context_t ctx;
+ int options = XATTR_NOSECURITY;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ uio_t auio;
+ int error;
+
+@@ -198,7 +198,7 @@ mac_vnop_getxattr(struct vnode *vp, const char *name, char *buf, size_t len,
+ {
+ vfs_context_t ctx = vfs_context_current();
+ int options = XATTR_NOSECURITY;
+- uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
++ uio_stackbuf_t uio_buf[(UIO_SIZEOF(1) + sizeof(uio_stackbuf_t) - 1) / sizeof(uio_stackbuf_t)];
+ uio_t auio;
+ int error;
+
diff --git a/xnuloader/build.sh b/xnuloader/build.sh
new file mode 100755
index 0000000..d2a3129
--- /dev/null
+++ b/xnuloader/build.sh
@@ -0,0 +1,10 @@
+#!/bin/bash
+# Build the XNU loader as a freestanding AArch64 UEFI application.
+set -e
+cd "$(dirname "$0")"
+clang --target=aarch64-unknown-windows -ffreestanding -fno-builtin -fno-stack-protector -fshort-wchar \
+ -mgeneral-regs-only -O1 -Wall -Wextra -Wno-unused-parameter -c loader.c -o loader.obj
+# /base: UEFI loads an image at its preferred address when that is free. The PE default (0x140000000)
+# is in the middle of the phone's largest block of RAM, which XNU needs in one piece.
+lld-link /subsystem:efi_application /entry:efi_main /nodefaultlib /base:0xA1000000 /out:loader.efi loader.obj
+ls -la loader.efi
diff --git a/xnuloader/efi.h b/xnuloader/efi.h
new file mode 100644
index 0000000..808678b
--- /dev/null
+++ b/xnuloader/efi.h
@@ -0,0 +1,206 @@
+/*
+ * Minimal UEFI definitions for the XNU loader (freestanding, no EDK2).
+ * Only what the loader touches is declared; unused slots are void pointers
+ * so that structure layouts still match the UEFI specification.
+ */
+#ifndef XNULOADER_EFI_H
+#define XNULOADER_EFI_H
+
+#include <stdint.h>
+#include <stddef.h>
+
+#define EFIAPI
+typedef uint64_t efi_status;
+typedef void *efi_handle;
+typedef uint16_t char16;
+
+#define EFI_ERROR_BIT 0x8000000000000000ULL
+#define EFI_ERROR(s) (((s) & EFI_ERROR_BIT) != 0)
+#define EFI_BUFFER_TOO_SMALL (EFI_ERROR_BIT | 5)
+
+typedef struct {
+ uint32_t a; uint16_t b; uint16_t c; uint8_t d[8];
+} efi_guid;
+
+typedef struct {
+ uint64_t signature; uint32_t revision; uint32_t header_size; uint32_t crc32; uint32_t reserved;
+} efi_table_header;
+
+struct efi_text_output;
+typedef struct efi_text_output {
+ void *reset;
+ efi_status (EFIAPI *output_string)(struct efi_text_output *self, const char16 *str);
+} efi_text_output;
+
+enum { EfiLoaderData = 2, EfiConventionalMemory = 7 };
+enum { AllocateAnyPages = 0, AllocateMaxAddress = 1, AllocateAddress = 2 };
+enum { ByProtocol = 2 };
+
+typedef struct {
+ uint32_t type; uint32_t pad; uint64_t phys_start; uint64_t virt_start; uint64_t pages; uint64_t attribute;
+} efi_memory_descriptor;
+
+typedef struct {
+ efi_table_header hdr;
+ void *raise_tpl, *restore_tpl;
+ efi_status (EFIAPI *allocate_pages)(int type, int mem_type, uint64_t pages, uint64_t *addr);
+ efi_status (EFIAPI *free_pages)(uint64_t addr, uint64_t pages);
+ efi_status (EFIAPI *get_memory_map)(uint64_t *size, void *map, uint64_t *key, uint64_t *desc_size, uint32_t *desc_ver);
+ efi_status (EFIAPI *allocate_pool)(int type, uint64_t size, void **buf);
+ efi_status (EFIAPI *free_pool)(void *buf);
+ void *create_event, *set_timer, *wait_for_event;
+ efi_status (EFIAPI *signal_event)(void *event);
+ efi_status (EFIAPI *close_event)(void *event);
+ void *check_event;
+ void *install_protocol_interface, *reinstall_protocol_interface, *uninstall_protocol_interface;
+ efi_status (EFIAPI *handle_protocol)(efi_handle h, const efi_guid *guid, void **iface);
+ void *reserved, *register_protocol_notify, *locate_handle, *locate_device_path, *install_configuration_table;
+ void *load_image, *start_image, *exit, *unload_image;
+ efi_status (EFIAPI *exit_boot_services)(efi_handle image, uint64_t map_key);
+ void *get_next_monotonic_count;
+ efi_status (EFIAPI *stall)(uint64_t microseconds);
+ efi_status (EFIAPI *set_watchdog_timer)(uint64_t timeout, uint64_t code, uint64_t size, char16 *data);
+ void *connect_controller, *disconnect_controller, *open_protocol, *close_protocol, *open_protocol_information;
+ void *protocols_per_handle;
+ efi_status (EFIAPI *locate_handle_buffer)(int type, const efi_guid *guid, void *key, uint64_t *count, efi_handle **buf);
+ efi_status (EFIAPI *locate_protocol)(const efi_guid *guid, void *registration, void **iface);
+ void *install_multiple_protocol_interfaces, *uninstall_multiple_protocol_interfaces;
+ void *calculate_crc32, *copy_mem, *set_mem;
+ efi_status (EFIAPI *create_event_ex)(uint32_t type, uint64_t tpl, void (EFIAPI *notify)(void *event, void *ctx),
+ const void *ctx, const efi_guid *group, void **event);
+} efi_boot_services;
+
+struct efi_time {
+ uint16_t year;
+ uint8_t month, day, hour, minute, second, pad1;
+ uint32_t nanosecond;
+ int16_t timezone; /* minutes; 0x7FF = not specified */
+ uint8_t daylight, pad2;
+};
+
+typedef struct {
+ efi_table_header hdr;
+ efi_status (EFIAPI *get_time)(struct efi_time *time, void *capabilities);
+ void *set_time, *get_wakeup_time, *set_wakeup_time;
+ void *set_virtual_address_map, *convert_pointer;
+ void *get_variable, *get_next_variable_name, *set_variable;
+ void *get_next_high_mono_count;
+ void (EFIAPI *reset_system)(int type, efi_status status, uint64_t size, void *data);
+} efi_runtime_services;
+
+typedef struct {
+ efi_table_header hdr;
+ char16 *vendor; uint32_t revision; uint32_t pad;
+ efi_handle con_in_handle; void *con_in;
+ efi_handle con_out_handle; efi_text_output *con_out;
+ efi_handle stderr_handle; efi_text_output *std_err;
+ efi_runtime_services *rt;
+ efi_boot_services *bs;
+} efi_system_table;
+
+/* Graphics Output */
+typedef struct {
+ uint32_t version, width, height, pixel_format;
+ uint32_t pixel_mask[4];
+ uint32_t pixels_per_scanline;
+} efi_gop_mode_info;
+
+typedef struct {
+ uint32_t max_mode, mode;
+ efi_gop_mode_info *info;
+ uint64_t info_size;
+ uint64_t fb_base;
+ uint64_t fb_size;
+} efi_gop_mode;
+
+typedef struct efi_gop {
+ efi_status (EFIAPI *query_mode)(struct efi_gop *self, uint32_t mode, uint64_t *info_size, efi_gop_mode_info **info);
+ efi_status (EFIAPI *set_mode)(struct efi_gop *self, uint32_t mode);
+ void *blt;
+ efi_gop_mode *mode;
+} efi_gop;
+
+/* Block I/O + Partition Info (used to persist the log on the phone) */
+typedef struct {
+ uint32_t media_id; uint8_t removable, present, logical, read_only, write_caching; uint8_t pad[3];
+ uint32_t block_size; uint32_t io_align; uint64_t last_block;
+} efi_block_media;
+
+typedef struct efi_block_io {
+ uint64_t revision;
+ efi_block_media *media;
+ void *reset;
+ efi_status (EFIAPI *read_blocks)(struct efi_block_io *self, uint32_t media_id, uint64_t lba, uint64_t size, void *buf);
+ efi_status (EFIAPI *write_blocks)(struct efi_block_io *self, uint32_t media_id, uint64_t lba, uint64_t size, void *buf);
+ efi_status (EFIAPI *flush_blocks)(struct efi_block_io *self);
+} efi_block_io;
+
+#pragma pack(push, 1)
+typedef struct {
+ uint32_t revision; uint32_t type; uint8_t system;
+ uint8_t reserved[7];
+ /* GPT entry */
+ efi_guid type_guid, unique_guid;
+ uint64_t start_lba, end_lba, attributes;
+ char16 name[36];
+} efi_partition_info;
+#pragma pack(pop)
+
+/* CPU architectural protocol: only the exception-handler hook is used */
+typedef struct efi_cpu_arch {
+ void *flush_data_cache, *enable_interrupt, *disable_interrupt, *get_interrupt_state, *init;
+ efi_status (EFIAPI *register_interrupt_handler)(struct efi_cpu_arch *self, int64_t type,
+ void (EFIAPI *handler)(int64_t type, uint64_t *context));
+} efi_cpu_arch;
+
+/* Index of fields in EFI_SYSTEM_CONTEXT_AARCH64 viewed as an array of u64 */
+enum { EXC_CTX_FP = 29, EXC_CTX_LR = 30, EXC_CTX_SP = 31, EXC_CTX_ELR = 96, EXC_CTX_SPSR = 97, EXC_CTX_ESR = 99, EXC_CTX_FAR = 100 };
+
+/*
+ * Qualcomm EFI_USB_DEVICE_PROTOCOL (interface as published in the open-source
+ * ABL, QcomModulePkg/Include/Protocol/EFIUsbDevice.h): a polled USB
+ * peripheral-mode API. The stock fastboot is built on it.
+ */
+enum { UsbDeviceEventNoEvent, UsbDeviceEventDeviceStateChange, UsbDeviceEventTransferNotification, UsbDeviceEventOemEvent };
+enum { UsbDeviceTransferStatusActive, UsbDeviceTransferStatusCompleteOK, UsbDeviceTransferStatusCancelled,
+ UsbDeviceTransferStatusCompleteError };
+enum { UsbDeviceStateConnected, UsbDeviceStateDisconnected };
+
+typedef union {
+ uint32_t device_state;
+ struct { uint32_t status; uint8_t endpoint_index; uint64_t bytes_completed; void *data_buffer; } transfer;
+ uint64_t raw[8];
+} usb_device_event_data;
+
+typedef struct {
+ const void *device_descriptor;
+ const void **descriptors;
+ const void *ss_device_descriptor;
+ const void **ss_descriptors;
+ const void *device_qualifier;
+ const void *bos;
+ uint8_t string_count;
+ const void **strings;
+} usb_device_descriptor_set;
+
+typedef struct {
+ uint64_t revision;
+ void *start;
+ efi_status (*send)(uint8_t endpoint, uint64_t size, void *buffer);
+ efi_status (EFIAPI *handle_event)(uint32_t *event, uint64_t *size, usb_device_event_data *data);
+ efi_status (EFIAPI *allocate_transfer_buffer)(uint64_t size, void **buffer);
+ efi_status (EFIAPI *free_transfer_buffer)(void *buffer);
+ efi_status (*stop)(void);
+ efi_status (*abort_xfer)(uint8_t endpoint);
+ efi_status (EFIAPI *set_endpoint_stall_state)(uint8_t endpoint, uint8_t state);
+ efi_status (*start_ex)(usb_device_descriptor_set *set);
+} usb_device_protocol;
+
+#define EFI_CPU_ARCH_GUID { 0x26baccb1, 0x6f42, 0x11d4, { 0xbc, 0xe7, 0x00, 0x80, 0xc7, 0x3c, 0x88, 0x81 } }
+#define QCOM_USB_DEVICE_GUID { 0xd9d9ce48, 0x44b8, 0x4f49, { 0x8e, 0x3e, 0x2a, 0x3b, 0x92, 0x7d, 0xc6, 0xc1 } }
+#define QCOM_USB_INIT_EVENT_GUID { 0x1c0cffce, 0xfc8d, 0x4e44, { 0x8c, 0x78, 0x9c, 0x9e, 0x5b, 0x53, 0x0d, 0x36 } }
+#define EFI_GOP_GUID { 0x9042a9de, 0x23dc, 0x4a38, { 0x96, 0xfb, 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a } }
+#define EFI_BLOCK_IO_GUID { 0x964e5b21, 0x6459, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }
+#define EFI_PARTITION_INFO_GUID { 0x8cf2f62c, 0xbc9b, 0x4821, { 0x80, 0x8d, 0xec, 0x9e, 0xc4, 0x21, 0xa1, 0xa0 } }
+
+#endif /* XNULOADER_EFI_H */
diff --git a/xnuloader/identity.h b/xnuloader/identity.h
new file mode 100644
index 0000000..799ee77
--- /dev/null
+++ b/xnuloader/identity.h
@@ -0,0 +1,105 @@
+/* Generated by mkidentity.py from the device tree of the iOS firmware. Do not edit. */
+struct identity_prop { const char *name; unsigned offset, length; };
+
+/* 6 properties */
+static const struct identity_prop identity_root[] = {
+ { "target-type", 0, 4 },
+ { "manufacturer", 4, 11 },
+ { "target-sub-type", 15, 6 },
+ { "compatible", 21, 26 },
+ { "model", 47, 11 },
+ { "device_type", 58, 8 },
+};
+static const unsigned char identity_root_data[] = {
+ 0x44, 0x32, 0x32, 0x00, 0x41, 0x70, 0x70, 0x6c, 0x65, 0x20, 0x49, 0x6e, 0x63, 0x2e, 0x00, 0x44, 0x32, 0x32, 0x41, 0x50,
+ 0x00, 0x44, 0x32, 0x32, 0x41, 0x50, 0x00, 0x69, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x31, 0x30, 0x2c, 0x33, 0x00, 0x41, 0x70,
+ 0x70, 0x6c, 0x65, 0x41, 0x52, 0x4d, 0x00, 0x69, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x31, 0x30, 0x2c, 0x33, 0x00, 0x62, 0x6f,
+ 0x6f, 0x74, 0x72, 0x6f, 0x6d, 0x00,
+};
+
+/* 61 properties */
+static const struct identity_prop identity_product[] = {
+ { "sandman-support", 0, 4 },
+ { "display-mirroring", 4, 4 },
+ { "car-integration", 8, 4 },
+ { "assistant", 12, 4 },
+ { "lockdown-certtype", 16, 4 },
+ { "ui-pip", 20, 4 },
+ { "wifi-chipset", 24, 5 },
+ { "product-name", 29, 9 },
+ { "hearingaid-audio-equalization", 38, 4 },
+ { "RF-exposure-separation-distance", 42, 4 },
+ { "mobiledevice-min-ver", 46, 5 },
+ { "product-id", 51, 20 },
+ { "gps-capable", 71, 4 },
+ { "product-description", 75, 9 },
+ { "allow-32bit-apps", 84, 4 },
+ { "low-power-wallet-mode", 88, 4 },
+ { "builtin-mics", 92, 4 },
+ { "has-boot-chime", 96, 4 },
+ { "supports-burnin-mitigation", 100, 4 },
+ { "compatible-device-fallback", 104, 10 },
+ { "device-perf-memory-class", 114, 4 },
+ { "artwork-scale-factor", 118, 4 },
+ { "baseband-chipset", 122, 6 },
+ { "hearingaid-low-energy-audio", 128, 4 },
+ { "ui-background-quality", 132, 4 },
+ { "supports-avatars", 136, 0 },
+ { "public-key-accelerator", 136, 4 },
+ { "disable-globe-map", 140, 0 },
+ { "artwork-device-idiom", 140, 6 },
+ { "device-color-policy", 146, 4 },
+ { "graphics-featureset-class", 150, 7 },
+ { "siri-gesture", 157, 4 },
+ { "supports-maps-optical-heading", 161, 0 },
+ { "compatible-app-variant", 161, 2 },
+ { "artwork-dynamic-displaymode", 163, 2 },
+ { "bluetooth-le", 165, 4 },
+ { "watch-companion", 169, 4 },
+ { "has-applelpm", 173, 4 },
+ { "iap2-protocol-supported", 177, 4 },
+ { "ephemeral-data-mode", 181, 4 },
+ { "activation-protocol-version", 185, 4 },
+ { "volume-up-button-location", 189, 20 },
+ { "ptp-large-files", 209, 4 },
+ { "udid-version", 213, 4 },
+ { "offline-dictation", 217, 4 },
+ { "location-reminders", 221, 4 },
+ { "ui-weather-quality", 225, 4 },
+ { "graphics-featureset-fallbacks", 229, 38 },
+ { "dictation", 267, 4 },
+ { "itunes-min-ver", 271, 4 },
+ { "artwork-display-gamut", 275, 3 },
+ { "front-cam-offset-from-center", 278, 16 },
+ { "ui-reachability", 294, 4 },
+ { "volume-down-button-location", 298, 20 },
+ { "personal-hotspot", 318, 4 },
+ { "single-stage-boot", 322, 4 },
+ { "mobiledevice-beta-min-ver", 326, 11 },
+ { "oled-display", 337, 4 },
+ { "thin-bezel", 341, 4 },
+ { "artwork-device-subtype", 345, 4 },
+ { "side-button-location", 349, 20 },
+};
+static const unsigned char identity_product_data[] = {
+ 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x34, 0x33, 0x35, 0x37, 0x00, 0x69, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x20, 0x58, 0x00, 0x01, 0x00,
+ 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x31, 0x34, 0x30, 0x30, 0x00, 0xfd, 0x07, 0x9b, 0x29, 0x81, 0x44, 0xa7, 0xde, 0xb4,
+ 0xd7, 0xc8, 0x7f, 0xef, 0x3e, 0xb4, 0x74, 0xd8, 0xf0, 0xe7, 0xeb, 0x01, 0x00, 0x00, 0x00, 0x69, 0x50, 0x68, 0x6f, 0x6e,
+ 0x65, 0x20, 0x58, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x69, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x39, 0x2c, 0x32, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00,
+ 0x00, 0x00, 0x6d, 0x61, 0x76, 0x31, 0x37, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+ 0x70, 0x68, 0x6f, 0x6e, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x50, 0x50, 0x4c, 0x45, 0x34, 0x00, 0x01, 0x00, 0x00,
+ 0x00, 0x30, 0x00, 0x30, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x78, 0xb0, 0x09, 0x00, 0xff, 0x96, 0x14, 0x00, 0x30, 0xe0, 0x03,
+ 0x00, 0xca, 0x9d, 0x01, 0x00, 0x10, 0x27, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x41, 0x50, 0x50, 0x4c, 0x45, 0x33, 0x3a, 0x41, 0x50, 0x50, 0x4c,
+ 0x45, 0x33, 0x76, 0x31, 0x3a, 0x41, 0x50, 0x50, 0x4c, 0x45, 0x32, 0x3a, 0x41, 0x50, 0x50, 0x4c, 0x45, 0x31, 0x3a, 0x47,
+ 0x4c, 0x45, 0x53, 0x32, 0x2c, 0x30, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x07, 0x0c, 0x00, 0x50, 0x33, 0x00, 0xd0, 0x01,
+ 0x01, 0x00, 0x9e, 0x1d, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 0xb0,
+ 0x09, 0x00, 0xff, 0x96, 0x14, 0x00, 0x48, 0xd0, 0x05, 0x00, 0xca, 0x9d, 0x01, 0x00, 0x10, 0x27, 0x00, 0x00, 0x01, 0x00,
+ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x31, 0x31, 0x39, 0x30, 0x2e, 0x31, 0x30, 0x30, 0x2e, 0x32, 0x00, 0x01, 0x00, 0x00,
+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x84, 0x09, 0x00, 0x00, 0x75, 0xf3, 0x00, 0x00, 0x2a, 0x0f, 0x02, 0x00, 0x00, 0x71, 0x00,
+ 0x00, 0xea, 0x3f, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
+};
+
diff --git a/xnuloader/loader.c b/xnuloader/loader.c
new file mode 100644
index 0000000..86cec63
--- /dev/null
+++ b/xnuloader/loader.c
@@ -0,0 +1,2285 @@
+/*
+ * XNU loader: a UEFI application that plays the role of iBoot for an
+ * open-source arm64 XNU kernel on non-Apple hardware.
+ *
+ * - finds the "XNUP" payload in RAM (placed there by the boot shim on the
+ * phone, by `-device loader` under QEMU) and the Mach-O kernel inside it
+ * - picks a block of free RAM to be XNU's [physBase, physBase + memSize)
+ * - copies the Mach-O segments there, builds an Apple-format device tree
+ * and a boot_args structure behind the kernel
+ * - 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) */
+
+/* ------------------------------------------------------------------------ */
+/* Fixed conventions shared with the boot shim, the packer and the kernel */
+
+#define PAYLOAD_BASE 0xF0000000ULL
+#define PAYLOAD_MAGIC 0x50554E58u /* "XNUP" */
+
+struct payload_header { uint32_t magic; uint32_t size; };
+struct payload_entry { char name[16]; uint32_t size; uint32_t reserved; };
+
+#define KERNEL_VIRT_BASE 0xFFFFFFF004000000ULL /* boot_args.virtBase */
+#define KERNEL_LINK_OFFSET 0x03000000ULL /* kernel text sits 48 MB above the base */
+#define BASE_ALIGN 0x02000000ULL /* 32 MB: L2 block size with 16K pages */
+#define MAX_MEM_SIZE 0x180000000ULL /* 6 GB; the kernel's bootstrap page tables cover 8 */
+/*
+ * A root image too big for the payload area is placed here, at a fixed
+ * offset inside the kernel's memory window, once; it then survives any
+ * number of kernel runs (nothing writes to it: the root is read-only).
+ */
+#define RESIDENT_RD_OFFSET 0x08000000ULL
+#define RESIDENT_RD_RESERVE 0x30000000ULL /* RAM that must remain for the kernel itself */
+#define PAGE_SIZE_MAX 0x4000ULL
+
+#define LOG_PARTITION u"logdump"
+#define CHECKPOINT_SELFTEST 999
+#define PANIC_LOG_SIZE 0x80000u
+#define NVRAM_BANK_SIZE 0x2000u
+#define PANIC_LOG_BASE (PAYLOAD_BASE + PAYLOAD_MAX_SIZE - 0x100000ULL)
+#define PAYLOAD_MAX_SIZE 0x04000000ULL /* RAM reserved for the payload in the UEFI memory map */
+
+/* ------------------------------------------------------------------------ */
+/* XNU structures (pexpert/pexpert/arm64/boot.h, mach-o/loader.h) */
+
+struct boot_video {
+ uint64_t v_baseAddr, v_display, v_rowBytes, v_width, v_height, v_depth;
+};
+
+#define BOOT_LINE_LENGTH 608
+
+struct boot_args {
+ uint16_t revision;
+ uint16_t version;
+ uint64_t virtBase;
+ uint64_t physBase;
+ uint64_t memSize;
+ uint64_t topOfKernelData;
+ struct boot_video video;
+ uint32_t machineType;
+ uint64_t deviceTreeP;
+ uint32_t deviceTreeLength;
+ char commandLine[BOOT_LINE_LENGTH];
+ uint64_t bootFlags;
+ uint64_t memSizeActual;
+};
+
+#define MH_MAGIC_64 0xFEEDFACFu
+#define LC_SEGMENT_64 0x19
+#define LC_UNIXTHREAD 0x5
+
+struct mach_header_64 { uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags, reserved; };
+struct load_command { uint32_t cmd, cmdsize; };
+struct segment_command_64 {
+ uint32_t cmd, cmdsize; char segname[16];
+ uint64_t vmaddr, vmsize, fileoff, filesize;
+ uint32_t maxprot, initprot, nsects, flags;
+};
+
+/* ------------------------------------------------------------------------ */
+/* Globals and small helpers */
+
+static efi_system_table *ST;
+static efi_boot_services *BS;
+static efi_handle IMAGE;
+
+static char log_buf[32768];
+static uint32_t log_len;
+
+void *
+memset(void *dst, int c, size_t n)
+{
+ uint8_t *d = dst;
+ while (n--) {
+ *d++ = (uint8_t)c;
+ }
+ return dst;
+}
+
+void *
+memcpy(void *dst, const void *src, size_t n)
+{
+ uint8_t *d = dst;
+ const uint8_t *s = src;
+
+ /*
+ * Word at a time when possible: USB transfer buffers are uncached, where
+ * a byte loop costs one bus access per byte (6 MB/s instead of 30+).
+ */
+ if ((((uintptr_t)d | (uintptr_t)s) & 7) == 0) {
+ uint64_t *dw = (uint64_t *)d;
+ const uint64_t *sw = (const uint64_t *)s;
+
+ for (; n >= 32; n -= 32, dw += 4, sw += 4) {
+ uint64_t a = sw[0], b = sw[1], c = sw[2], e = sw[3];
+ dw[0] = a;
+ dw[1] = b;
+ dw[2] = c;
+ dw[3] = e;
+ }
+ for (; n >= 8; n -= 8) {
+ *dw++ = *sw++;
+ }
+ d = (uint8_t *)dw;
+ s = (const uint8_t *)sw;
+ }
+ while (n--) {
+ *d++ = *s++;
+ }
+ return dst;
+}
+
+static size_t
+str_len(const char *s)
+{
+ size_t n = 0;
+ while (s[n]) {
+ n++;
+ }
+ return n;
+}
+
+static int
+str_eq(const char *a, const char *b)
+{
+ while (*a && *a == *b) {
+ a++, b++;
+ }
+ return *a == *b;
+}
+
+/*
+ * Set once the loader takes commands over USB: its log travels that way, and
+ * the screen is left to the kernel (and to "oem screenshot").
+ */
+static int screen_quiet;
+
+static void
+put_char(char c)
+{
+ char16 w[3] = { 0, 0, 0 };
+
+ if (log_len < sizeof(log_buf) - 1) {
+ log_buf[log_len++] = c;
+ }
+ if (ST->con_out != NULL && !screen_quiet) {
+ if (c == '\n') {
+ w[0] = '\r', w[1] = '\n';
+ } else {
+ w[0] = (char16)c;
+ }
+ ST->con_out->output_string(ST->con_out, w);
+ }
+}
+
+/* printf subset: %s %x %d (64-bit values), %% */
+static void
+print(const char *fmt, ...)
+{
+ __builtin_va_list ap;
+ __builtin_va_start(ap, fmt);
+ for (; *fmt; fmt++) {
+ if (*fmt != '%') {
+ put_char(*fmt);
+ continue;
+ }
+ fmt++;
+ if (*fmt == 's') {
+ const char *s = __builtin_va_arg(ap, const char *);
+ while (*s) {
+ put_char(*s++);
+ }
+ } else if (*fmt == 'x' || *fmt == 'd') {
+ uint64_t v = __builtin_va_arg(ap, uint64_t);
+ unsigned base = (*fmt == 'x') ? 16 : 10;
+ char tmp[24];
+ int i = 0;
+ do {
+ tmp[i++] = "0123456789abcdef"[v % base];
+ v /= base;
+ } while (v);
+ while (i) {
+ put_char(tmp[--i]);
+ }
+ } else {
+ put_char(*fmt);
+ }
+ }
+ __builtin_va_end(ap);
+}
+
+#define READ_SYSREG(name) ({ uint64_t _v; __asm__ volatile ("mrs %0, " #name : "=r" (_v)); _v; })
+
+/*
+ * Write back and drop cached copies of a range. Required for memory the
+ * kernel will touch with the MMU (and so the data cache) off: its early code
+ * builds page tables that way, and a stale cached copy of those pages would
+ * be what the table walker sees once caches are turned on again.
+ */
+static void
+flush_dcache(uint64_t start, uint64_t end)
+{
+ uint64_t line = 4ULL << ((READ_SYSREG(CTR_EL0) >> 16) & 0xF);
+ for (uint64_t p = start & ~(line - 1); p < end; p += line) {
+ __asm__ volatile ("dc civac, %0" : : "r" (p));
+ }
+ __asm__ volatile ("dsb sy");
+}
+
+static void
+clean_dcache(uint64_t start, uint64_t end)
+{
+ uint64_t line = 4ULL << ((READ_SYSREG(CTR_EL0) >> 16) & 0xF);
+ for (uint64_t p = start & ~(line - 1); p < end; p += line) {
+ __asm__ volatile ("dc cvac, %0" : : "r" (p));
+ }
+ __asm__ volatile ("dsb sy");
+}
+
+/* ------------------------------------------------------------------------ */
+/* Log persistence: raw write to a GPT partition (phone only) */
+
+static efi_block_io *
+find_log_partition(void)
+{
+ static const efi_guid part_guid = EFI_PARTITION_INFO_GUID;
+ static const efi_guid blk_guid = EFI_BLOCK_IO_GUID;
+ static const char16 want[] = LOG_PARTITION;
+ efi_handle *handles;
+ uint64_t count;
+
+ if (EFI_ERROR(BS->locate_handle_buffer(ByProtocol, &part_guid, NULL, &count, &handles))) {
+ return NULL;
+ }
+ for (uint64_t i = 0; i < count; i++) {
+ efi_partition_info *info;
+ efi_block_io *bio;
+ int match = 1;
+
+ if (EFI_ERROR(BS->handle_protocol(handles[i], &part_guid, (void **)&info)) || info->type != 2) {
+ continue;
+ }
+ for (unsigned k = 0; k < sizeof(want) / sizeof(want[0]); k++) {
+ if (info->name[k] != want[k]) {
+ match = 0;
+ break;
+ }
+ }
+ if (match && !EFI_ERROR(BS->handle_protocol(handles[i], &blk_guid, (void **)&bio))) {
+ return bio;
+ }
+ }
+ return NULL;
+}
+
+/*
+ * The "staged" buffer holds the loader log followed by the kernel log of the
+ * last run. It is what gets written to the log partition and what the host
+ * fetches over USB (fastboot get_staged).
+ */
+static char out_buf[2 * 1024 * 1024];
+static const char *staged_data = out_buf; /* what "upload" sends: normally the log in out_buf */
+static uint64_t staged_len;
+
+static void
+compose_logs(const char *klog, uint64_t klog_len)
+{
+ static const char sep[] = "\n== KERNEL LOG ==\n", end[] = "\n== END OF LOG ==\n";
+ uint64_t n = log_len;
+
+ staged_data = out_buf;
+ memset(out_buf, 0, sizeof(out_buf));
+ memcpy(out_buf, log_buf, log_len);
+ if (klog != NULL) {
+ if (klog_len > sizeof(out_buf) - n - 8192) {
+ klog_len = sizeof(out_buf) - n - 8192;
+ }
+ memcpy(out_buf + n, sep, sizeof(sep) - 1);
+ n += sizeof(sep) - 1;
+ memcpy(out_buf + n, klog, klog_len);
+ n += klog_len;
+ memcpy(out_buf + n, end, sizeof(end) - 1);
+ n += sizeof(end) - 1;
+ }
+ staged_len = n;
+}
+
+static void
+write_logs(const char *klog, uint64_t klog_len)
+{
+ efi_block_io *bio = find_log_partition();
+
+ compose_logs(klog, klog_len);
+ if (bio == NULL) {
+ /* No log partition (QEMU): echo the returned kernel log on the console instead. */
+ if (klog != NULL) {
+ print("\n== KERNEL LOG ==\n");
+ for (uint64_t i = 0; i < klog_len; i++) {
+ put_char(klog[i]);
+ }
+ print("\n== END OF LOG ==\n");
+ }
+ return;
+ }
+ uint64_t bs = bio->media->block_size;
+ uint64_t len = (staged_len + 1 + bs - 1) / bs * bs;
+ if (!EFI_ERROR(bio->write_blocks(bio, bio->media->media_id, 0, len, out_buf))) {
+ bio->flush_blocks(bio);
+ }
+}
+
+static void
+flush_log(void)
+{
+ write_logs(NULL, 0);
+}
+
+/* ------------------------------------------------------------------------ */
+/* Apple device tree writer */
+/* */
+/* node := u32 nProperties, u32 nChildren, props[], children[] */
+/* prop := char name[32], u32 length, value padded to 4 bytes */
+
+struct dt_writer {
+ uint8_t *base, *cur;
+ uint32_t *counts[16]; /* [depth] -> {nProperties, nChildren} of the open node */
+ int depth;
+};
+
+static void
+dt_prop(struct dt_writer *w, const char *name, const void *data, uint32_t len)
+{
+ memset(w->cur, 0, 32);
+ memcpy(w->cur, name, str_len(name));
+ *(uint32_t *)(w->cur + 32) = len;
+ memset(w->cur + 36, 0, (len + 3) & ~3u);
+ memcpy(w->cur + 36, data, len);
+ w->cur += 36 + ((len + 3) & ~3u);
+ w->counts[w->depth - 1][0]++;
+}
+
+static void
+dt_prop_str(struct dt_writer *w, const char *name, const char *value)
+{
+ dt_prop(w, name, value, (uint32_t)str_len(value) + 1);
+}
+
+static void
+dt_prop_u32(struct dt_writer *w, const char *name, uint32_t value)
+{
+ dt_prop(w, name, &value, sizeof(value));
+}
+
+static void
+dt_prop_u64(struct dt_writer *w, const char *name, uint64_t value)
+{
+ dt_prop(w, name, &value, sizeof(value));
+}
+
+/* Seconds since 1970 by the firmware's real-time clock, or 0 when it has none or it is not set. */
+static uint64_t
+firmware_epoch(void)
+{
+ static const uint16_t before_month[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
+ struct efi_time t;
+ uint64_t days;
+
+ if (ST->rt == NULL || ST->rt->get_time == NULL || EFI_ERROR(ST->rt->get_time(&t, NULL)) ||
+ t.year < 2024 || t.year > 2099 || t.month < 1 || t.month > 12) {
+ return 0;
+ }
+ days = (uint64_t)(t.year - 1970) * 365 + (t.year - 1969) / 4 + before_month[t.month - 1] + (t.day - 1);
+ if (t.month > 2 && t.year % 4 == 0) {
+ days++;
+ }
+ uint64_t secs = days * 86400 + (uint64_t)t.hour * 3600 + (uint64_t)t.minute * 60 + t.second;
+ if (t.timezone != 0x7FF) {
+ secs += (int64_t)t.timezone * 60; /* local time = UTC - timezone */
+ }
+ return secs;
+}
+
+/* A string in a field of fixed size, the rest zeros. */
+static void
+dt_prop_padded(struct dt_writer *w, const char *name, const char *value, uint32_t size)
+{
+ uint8_t field[64];
+
+ memset(field, 0, sizeof(field));
+ memcpy(field, value, str_len(value));
+ dt_prop(w, name, field, size);
+}
+
+/* Properties copied from the iPhone's device tree (identity.h). */
+static void
+dt_identity(struct dt_writer *w, const struct identity_prop *props, uint32_t count, const unsigned char *data)
+{
+ for (uint32_t i = 0; i < count; i++) {
+ dt_prop(w, props[i].name, data + props[i].offset, props[i].length);
+ }
+}
+
+static void
+dt_begin(struct dt_writer *w, const char *name)
+{
+ if (w->depth > 0) {
+ w->counts[w->depth - 1][1]++;
+ }
+ w->counts[w->depth++] = (uint32_t *)w->cur;
+ memset(w->cur, 0, 8);
+ w->cur += 8;
+ dt_prop_str(w, "name", name);
+}
+
+static void
+dt_end(struct dt_writer *w)
+{
+ w->depth--;
+}
+
+/* ------------------------------------------------------------------------ */
+/* Platform description */
+
+struct platform {
+ const char *name;
+ uint64_t io_base, io_size; /* one window covering the SoC peripherals */
+ uint64_t gic_dist, gic_redist; /* GICv3 */
+ uint64_t uart; /* PL011, 0 if none */
+ int psci_hvc; /* the firmware's power interface is called with HVC, not SMC */
+ int log_other_cpu; /* keep notes in the log partition while a kernel starts on another core */
+};
+
+static const struct platform platform_qemu_virt = {
+ .name = "qemu-virt", .io_base = 0x08000000, .io_size = 0x08000000,
+ .gic_dist = 0x08000000, .gic_redist = 0x080A0000, .uart = 0x09000000, .psci_hvc = 1,
+};
+
+static const struct platform platform_redwood = {
+ /* io_base must be non-zero: XNU treats a zero SoC base as "no SoC" and skips clock setup. */
+ .name = "redwood", .io_base = 0x00400000, .io_size = 0x3FC00000,
+ .gic_dist = 0x17A00000, .gic_redist = 0x17A60000, .uart = 0, .log_other_cpu = 1,
+};
+
+/* ------------------------------------------------------------------------ */
+
+static void
+reboot(void)
+{
+ flush_log();
+ ST->rt->reset_system(0 /* EfiResetCold */, 0, 0, NULL);
+ for (;;) {
+ }
+}
+
+/*
+ * Return-from-kernel support.
+ *
+ * Boot services are never exited: UEFI stays resident outside XNU's memory
+ * window. loader_save_ctx() records the UEFI execution environment and
+ * returns 0. When the kernel is done it jumps to loader_return_stub (mapped
+ * 1:1 or with the MMU off) with x0 = PA of its log, x1 = length, x2 = reason
+ * (0 = orderly, 1 = early exception, then x3..x7 = ESR, ELR, FAR, LR, SP).
+ * The stub switches the MMU off, reinstates the saved environment and makes
+ * loader_save_ctx() return a second time, with 1.
+ *
+ * The EL1 physical timer (CNTP_*) is deliberately left alone: the Qualcomm
+ * hypervisor traps it. The CTX_CNTP_* slots are unused.
+ */
+enum {
+ CTX_TTBR0, CTX_TCR, CTX_MAIR, CTX_SCTLR, CTX_VBAR, CTX_CPACR, CTX_SP, CTX_SPSEL, CTX_DAIF,
+ CTX_CNTV_CTL, CTX_CNTV_CVAL, CTX_CNTP_CTL, CTX_CNTP_CVAL, CTX_CNTKCTL,
+ CTX_X18, CTX_X19, /* ... x30 */
+ CTX_LOG_PA = CTX_X19 + 12, CTX_LOG_LEN, CTX_REASON, CTX_ESR, CTX_ELR, CTX_FAR, CTX_LR, CTX_KSP,
+ CTX_TPIDR_EL1, CTX_TPIDR_EL0, CTX_TPIDRRO_EL0, CTX_SP_EL0, CTX_CONTEXTIDR, CTX_MDSCR, CTX_FPCR, CTX_FPSR,
+ CTX_ICC_PMR, CTX_ICC_IGRPEN1, CTX_ICC_BPR1, CTX_COUNT
+};
+uint64_t loader_ctx[CTX_COUNT];
+int loader_save_ctx(void);
+void loader_return_stub(void);
+
+__asm__ (
+ ".text\n"
+ ".balign 64\n"
+ ".globl loader_save_ctx\n"
+ "loader_save_ctx:\n"
+ " adrp x10, loader_ctx\n"
+ " add x10, x10, :lo12:loader_ctx\n"
+ " mrs x9, ttbr0_el1\n str x9, [x10, #0]\n"
+ " mrs x9, tcr_el1\n str x9, [x10, #8]\n"
+ " mrs x9, mair_el1\n str x9, [x10, #16]\n"
+ " mrs x9, sctlr_el1\n str x9, [x10, #24]\n"
+ " mrs x9, vbar_el1\n str x9, [x10, #32]\n"
+ " mrs x9, cpacr_el1\n str x9, [x10, #40]\n"
+ " mov x9, sp\n str x9, [x10, #48]\n"
+ " mrs x9, spsel\n str x9, [x10, #56]\n"
+ " mrs x9, daif\n str x9, [x10, #64]\n"
+ " mrs x9, cntv_ctl_el0\n str x9, [x10, #72]\n"
+ " mrs x9, cntv_cval_el0\n str x9, [x10, #80]\n"
+ " mrs x9, cntkctl_el1\n str x9, [x10, #104]\n"
+ /* Qualcomm's UEFI has its own thread scheduler and keeps its current-thread
+ * pointer in TPIDR_EL1; the kernel overwrites it, so it must come back intact. */
+ " mrs x9, tpidr_el1\n str x9, [x10, #280]\n"
+ " mrs x9, tpidr_el0\n str x9, [x10, #288]\n"
+ " mrs x9, tpidrro_el0\n str x9, [x10, #296]\n"
+ " mrs x9, contextidr_el1\n str x9, [x10, #312]\n"
+ " mrs x9, mdscr_el1\n str x9, [x10, #320]\n"
+ " mrs x9, s3_3_c4_c4_0\n str x9, [x10, #328]\n"
+ " mrs x9, s3_3_c4_c4_1\n str x9, [x10, #336]\n"
+ /* GICv3 CPU interface: the kernel reprograms it for its own interrupts */
+ " mrs x9, icc_pmr_el1\n str x9, [x10, #344]\n"
+ " mrs x9, icc_igrpen1_el1\n str x9, [x10, #352]\n"
+ " mrs x9, icc_bpr1_el1\n str x9, [x10, #360]\n"
+ " mrs x9, spsel\n"
+ " cbz x9, 1f\n" /* SP_EL0 is only accessible while running on SP_EL1 */
+ " mrs x9, sp_el0\n str x9, [x10, #304]\n"
+ "1:\n"
+ " str x18, [x10, #112]\n"
+ " stp x19, x20, [x10, #120]\n"
+ " stp x21, x22, [x10, #136]\n"
+ " stp x23, x24, [x10, #152]\n"
+ " stp x25, x26, [x10, #168]\n"
+ " stp x27, x28, [x10, #184]\n"
+ " stp x29, x30, [x10, #200]\n"
+ " mov x0, #0\n"
+ " ret\n"
+ ".balign 64\n"
+ ".globl loader_return_stub\n"
+ "loader_return_stub:\n"
+ " msr daifset, #0xf\n"
+ /* PSTATE bits the kernel may have left set. PAN in particular is fatal:
+ * UEFI maps its memory as EL0-accessible, so with PAN every data access
+ * (including the exception handler's own stack push) faults. */
+ " .inst 0xd500409f\n" /* msr PAN, #0 */
+ " .inst 0xd500407f\n" /* msr UAO, #0 */
+ " mrs x9, sctlr_el1\n"
+ " bic x9, x9, #0x1\n"
+ " bic x9, x9, #0x4\n"
+ " bic x9, x9, #0x1000\n"
+ " msr sctlr_el1, x9\n"
+ " isb\n"
+ " adrp x10, loader_ctx\n"
+ " add x10, x10, :lo12:loader_ctx\n"
+ " ldr x9, [x10, #0]\n msr ttbr0_el1, x9\n"
+ " ldr x9, [x10, #8]\n msr tcr_el1, x9\n"
+ " ldr x9, [x10, #16]\n msr mair_el1, x9\n"
+ " ldr x9, [x10, #32]\n msr vbar_el1, x9\n"
+ " ldr x9, [x10, #40]\n msr cpacr_el1, x9\n"
+ " isb\n"
+ " tlbi vmalle1\n"
+ " dsb sy\n"
+ " ic iallu\n"
+ " isb\n"
+ " ldr x9, [x10, #24]\n msr sctlr_el1, x9\n"
+ " isb\n"
+ " ldr x9, [x10, #56]\n"
+ " cbz x9, 1f\n"
+ " msr spsel, #1\n"
+ " ldr x9, [x10, #304]\n msr sp_el0, x9\n"
+ " b 2f\n"
+ "1:\n"
+ " msr spsel, #0\n"
+ "2:\n"
+ " ldr x9, [x10, #48]\n mov sp, x9\n"
+ " ldr x9, [x10, #280]\n msr tpidr_el1, x9\n"
+ " ldr x9, [x10, #288]\n msr tpidr_el0, x9\n"
+ " ldr x9, [x10, #296]\n msr tpidrro_el0, x9\n"
+ " ldr x9, [x10, #312]\n msr contextidr_el1, x9\n"
+ " ldr x9, [x10, #320]\n msr mdscr_el1, x9\n"
+ " ldr x9, [x10, #344]\n msr icc_pmr_el1, x9\n"
+ " ldr x9, [x10, #360]\n msr icc_bpr1_el1, x9\n"
+ " ldr x9, [x10, #352]\n msr icc_igrpen1_el1, x9\n"
+ " ldr x9, [x10, #328]\n msr s3_3_c4_c4_0, x9\n"
+ " ldr x9, [x10, #336]\n msr s3_3_c4_c4_1, x9\n"
+ " ldr x9, [x10, #104]\n msr cntkctl_el1, x9\n"
+ " ldr x9, [x10, #80]\n msr cntv_cval_el0, x9\n"
+ " ldr x9, [x10, #72]\n msr cntv_ctl_el0, x9\n"
+ " ldr x18, [x10, #112]\n"
+ " ldp x19, x20, [x10, #120]\n"
+ " ldp x21, x22, [x10, #136]\n"
+ " ldp x23, x24, [x10, #152]\n"
+ " ldp x25, x26, [x10, #168]\n"
+ " ldp x27, x28, [x10, #184]\n"
+ " ldp x29, x30, [x10, #200]\n"
+ " stp x0, x1, [x10, #216]\n" /* kernel log PA and length, stored with caches on */
+ " stp x2, x3, [x10, #232]\n" /* reason, ESR */
+ " stp x4, x5, [x10, #248]\n" /* ELR, FAR */
+ " stp x6, x7, [x10, #264]\n" /* LR, SP */
+ " ldr x9, [x10, #64]\n msr daif, x9\n"
+ " mov x0, #1\n"
+ " ret\n"
+ );
+
+__attribute__((noreturn)) static void
+jump_to_kernel(uint64_t entry, uint64_t boot_args_pa)
+{
+ __asm__ volatile (
+ "msr daifset, #0xf\n"
+ /* Last thing before the MMU goes off: write this stack back to RAM
+ * (dirty cache lines do not survive, and we come back to this frame). */
+ "mov x2, sp\n"
+ "sub x2, x2, #0x400\n"
+ "bic x2, x2, #63\n"
+ "add x3, x2, #0x4000\n"
+ "1: dc cvac, x2\n"
+ "add x2, x2, #64\n"
+ "cmp x2, x3\n"
+ "b.lo 1b\n"
+ "dsb sy\n"
+ "mrs x2, sctlr_el1\n"
+ "bic x2, x2, #0x1\n" /* M: MMU off */
+ "bic x2, x2, #0x4\n" /* C: data cache off */
+ "bic x2, x2, #0x1000\n" /* I: instruction cache off */
+ "msr sctlr_el1, x2\n"
+ "isb\n"
+ "ic iallu\n"
+ "dsb sy\n"
+ "isb\n"
+ "mov x0, %1\n"
+ "br %0\n"
+ : : "r" (entry), "r" (boot_args_pa) : "x0", "x2", "x3");
+ __builtin_unreachable();
+}
+
+/* ------------------------------------------------------------------------ */
+/* The kernel on another core. */
+/* */
+/* The firmware runs on core 0, one of the four small ones (Cortex-A55); the */
+/* kernel uses a single core, and it had better be a big one (the A78s are */
+/* about 2.5 times as fast). With "bootcpu=N" among the kernel's arguments */
+/* the loader does not jump into the kernel itself: it has the firmware */
+/* (PSCI) start core N at other_cpu_entry, which enters the kernel exactly */
+/* as core 0 would have, and waits. UEFI stays resident and lives on core 0, */
+/* so the kernel's way back is different too: other_cpu_return_stub, on core */
+/* N, leaves what the kernel returned where core 0 looks for it, wakes core */
+/* 0 and switches its own core off. */
+
+#define PSCI_CPU_OFF 0x84000002u
+#define PSCI_CPU_ON 0xC4000003u
+
+/* each alone in a cache line: one core reads them with its caches off */
+static struct {
+ uint64_t entry, boot_args;
+} other_cpu_start __attribute__((aligned(64)));
+volatile uint64_t other_cpu_stage __attribute__((aligned(64))); /* 1: that core has reached other_cpu_entry */
+volatile uint64_t other_cpu_done __attribute__((aligned(64))); /* 1: the kernel is back (other_cpu_return_stub) */
+uint64_t psci_by_hvc __attribute__((aligned(64)));
+void other_cpu_entry(void);
+void other_cpu_return_stub(void);
+
+__asm__ (
+ ".text\n"
+ ".balign 64\n"
+ ".globl other_cpu_entry\n"
+ "other_cpu_entry:\n" /* x0 = &other_cpu_start; MMU and caches are off */
+ " msr daifset, #0xf\n"
+ /* until the kernel has vectors of its own, an exception must not go nowhere */
+ " adrp x9, other_cpu_vectors\n"
+ " add x9, x9, :lo12:other_cpu_vectors\n"
+ " msr vbar_el1, x9\n"
+ /* what the firmware had set up on the core the kernel used to start on, the kernel may take
+ * for granted: floating point allowed (CPACR), the fixed bits of SCTLR */
+ " adrp x10, loader_ctx\n"
+ " add x10, x10, :lo12:loader_ctx\n"
+ " ldr x9, [x10, #40]\n"
+ " msr cpacr_el1, x9\n"
+ " ldr x9, [x10, #24]\n"
+ " bic x9, x9, #0x1\n"
+ " bic x9, x9, #0x4\n"
+ " bic x9, x9, #0x1000\n"
+ " msr sctlr_el1, x9\n"
+ " isb\n"
+ " adrp x9, other_cpu_stage\n"
+ " add x9, x9, :lo12:other_cpu_stage\n"
+ " mov x10, #1\n"
+ " str x10, [x9]\n"
+ " ldp x9, x10, [x0]\n"
+ " mov x0, x10\n"
+ " br x9\n"
+ "other_cpu_fault:\n" /* as an early exception in the kernel: reason 1 */
+ " mrs x3, esr_el1\n"
+ " mrs x4, elr_el1\n"
+ " mrs x5, far_el1\n"
+ " mov x6, x30\n"
+ " mov x7, sp\n"
+ " mov x0, #0\n"
+ " mov x1, #0\n"
+ " mov x2, #1\n"
+ " b other_cpu_return_stub\n"
+ ".balign 0x800\n"
+ "other_cpu_vectors:\n"
+ " b other_cpu_fault\n .balign 0x80\n b other_cpu_fault\n .balign 0x80\n"
+ " b other_cpu_fault\n .balign 0x80\n b other_cpu_fault\n .balign 0x80\n"
+ " b other_cpu_fault\n .balign 0x80\n b other_cpu_fault\n .balign 0x80\n"
+ " b other_cpu_fault\n .balign 0x80\n b other_cpu_fault\n .balign 0x80\n"
+ " b other_cpu_fault\n .balign 0x80\n b other_cpu_fault\n .balign 0x80\n"
+ " b other_cpu_fault\n .balign 0x80\n b other_cpu_fault\n .balign 0x80\n"
+ " b other_cpu_fault\n .balign 0x80\n b other_cpu_fault\n .balign 0x80\n"
+ " b other_cpu_fault\n .balign 0x80\n b other_cpu_fault\n .balign 0x80\n"
+ ".balign 64\n"
+ ".globl other_cpu_return_stub\n"
+ "other_cpu_return_stub:\n" /* x0..x7 as for loader_return_stub */
+ " msr daifset, #0xf\n"
+ " .inst 0xd500409f\n" /* msr PAN, #0 */
+ " .inst 0xd500407f\n" /* msr UAO, #0 */
+ " mrs x9, sctlr_el1\n"
+ " bic x9, x9, #0x1\n"
+ " bic x9, x9, #0x4\n"
+ " bic x9, x9, #0x1000\n"
+ " msr sctlr_el1, x9\n"
+ " isb\n"
+ " adrp x10, loader_ctx\n"
+ " add x10, x10, :lo12:loader_ctx\n"
+ " stp x0, x1, [x10, #216]\n" /* kernel log PA and length */
+ " stp x2, x3, [x10, #232]\n" /* reason, ESR */
+ " stp x4, x5, [x10, #248]\n" /* ELR, FAR */
+ " stp x6, x7, [x10, #264]\n" /* LR, SP */
+ " adrp x10, other_cpu_done\n"
+ " add x10, x10, :lo12:other_cpu_done\n"
+ " mov x9, #1\n"
+ " str x9, [x10]\n"
+ " dsb sy\n"
+ " sev\n"
+ " adrp x10, psci_by_hvc\n"
+ " add x10, x10, :lo12:psci_by_hvc\n"
+ " ldr x9, [x10]\n"
+ " mov x0, #0x0002\n" /* PSCI CPU_OFF: does not return */
+ " movk x0, #0x8400, lsl #16\n"
+ " cbnz x9, 2f\n"
+ " smc #0\n"
+ "1: wfi\n"
+ " b 1b\n"
+ "2: hvc #0\n"
+ " b 1b\n"
+ );
+
+static uint64_t smc_call(uint64_t id, uint64_t a1, uint64_t a2, uint64_t *r1, uint64_t *r2);
+static uint64_t smc_x3;
+static const struct platform *PLAT;
+static void clean_dcache(uint64_t start, uint64_t end);
+static void flush_dcache(uint64_t start, uint64_t end);
+
+/* What the kernel shows a watching loader (struct loader_live in XNU's loader_return.c). */
+struct kernel_live {
+ uint64_t magic; /* "XNULIVE!" */
+ uint64_t heartbeat; /* goes up every 10 seconds while the kernel is alive */
+ uint64_t log, log_len, log_ring_at, log_wrapped; /* the kernel's virtual addresses: add the slide */
+ uint64_t log_head, log_ring; /* the log: this much from the start of the boot, then a ring this big */
+ uint64_t recording; /* (a virtual address too) { physical address, bytes } of a screen recording */
+};
+
+/* The screen recording the last kernel left in memory, if it made one ("oem recording" stages it). */
+static const char *recording_data;
+static uint64_t recording_len;
+#define KERNEL_LIVE_MAGIC 0x214556494c554e58ULL
+#define OTHER_CPU_NOT_STARTED 1000 /* run_on_other_cpu(): the firmware said yes but the core never arrived */
+#define OTHER_CPU_HUNG 1001 /* ... the kernel stopped giving signs of life */
+#define START_SECONDS 5
+#define SILENCE_SECONDS 50
+#define NOTE_SECONDS 24 /* how long the kernel's progress is written down as it happens */
+
+static void wdt_pet(void);
+static int wdt_armed;
+
+static uint64_t
+seconds_since(uint64_t then)
+{
+ return (READ_SYSREG(CNTVCT_EL0) - then) / READ_SYSREG(CNTFRQ_EL0);
+}
+
+/* Reverse a stretch of memory in place. */
+static void
+reverse(char *p, uint64_t n)
+{
+ for (uint64_t i = 0; i < n / 2; i++) {
+ char c = p[i];
+
+ p[i] = p[n - 1 - i];
+ p[n - 1 - i] = c;
+ }
+}
+
+/*
+ * The log of a kernel that did not come back to hand it over: put its two parts in order
+ * (the ring's oldest character first) and say where it is and how long.
+ */
+static void
+log_of_hung_kernel(const struct kernel_live *live, uint64_t slide)
+{
+ char *log = (char *)(live->log + slide);
+ uint32_t len, ring_at;
+
+ loader_ctx[CTX_LOG_PA] = loader_ctx[CTX_LOG_LEN] = 0;
+ len = *(volatile uint32_t *)(live->log_len + slide);
+ ring_at = *(volatile uint32_t *)(live->log_ring_at + slide);
+ if (*(volatile uint8_t *)(live->log_wrapped + slide) && ring_at < live->log_ring) {
+ /* rotate the ring left by ring_at: three reversals */
+ reverse(log + live->log_head, ring_at);
+ reverse(log + live->log_head + ring_at, live->log_ring - ring_at);
+ reverse(log + live->log_head, live->log_ring);
+ len = (uint32_t)(live->log_head + live->log_ring);
+ }
+ if (len <= live->log_head + live->log_ring) {
+ loader_ctx[CTX_LOG_PA] = (uint64_t)(uintptr_t)log;
+ loader_ctx[CTX_LOG_LEN] = len;
+ }
+}
+
+static void print(const char *fmt, ...);
+static void flush_log(void);
+static void put_char(char c);
+
+/* For the record: how much the kernel on the other core has logged so far, and the end of it. */
+static void
+note_kernel_progress(const struct kernel_live *live, uint64_t slide, uint64_t seconds)
+{
+ const char *log;
+ uint32_t len, from;
+
+ if (live == NULL) {
+ print("%d s\n", seconds);
+ return;
+ }
+ log = (const char *)(live->log + slide);
+ /* its first words are written with the caches off: look at memory */
+ flush_dcache(live->log_len + slide, live->log_len + slide + 4);
+ len = *(volatile uint32_t *)(live->log_len + slide);
+ if (len > live->log_head + live->log_ring) {
+ len = 0;
+ }
+ from = len > 240 ? len - 240 : 0;
+ flush_dcache((uint64_t)(uintptr_t)log + from, (uint64_t)(uintptr_t)log + len);
+ print("%d s: the kernel has logged %d bytes, heartbeat %d; the last of it:\n", seconds, (uint64_t)len, live->heartbeat);
+ for (uint32_t i = from; i < len; i++) {
+ put_char(log[i] >= 0x20 && log[i] < 0x7f ? log[i] : log[i] == '\n' ? '\n' : '.');
+ }
+ print("\n");
+}
+
+/*
+ * Run the kernel on the core with that MPIDR and wait until it is back. Returns 0 when it has
+ * been and gone (the caller goes on as after loader_return_stub), a negative number if the
+ * firmware refused to start the core, OTHER_CPU_NOT_STARTED, or OTHER_CPU_HUNG: then the kernel
+ * is still sitting on that core, but what it logged is there to be read (loader_ctx, as after a
+ * return). `live` is where the kernel shows its signs of life, if it has such a place;
+ * `budget` is how many seconds it has said it will run.
+ */
+static int64_t
+run_on_other_cpu(uint64_t mpidr, uint64_t entry, uint64_t boot_args_pa, const struct kernel_live *live, uint64_t slide,
+ uint64_t budget)
+{
+ uint64_t daif = 0, group1 = 0, started, last_pet, last_beat_at, last_beat = 0, noted = 0;
+ int64_t status;
+ int arrived = 0, watching_only = 0;
+
+ other_cpu_start.entry = entry;
+ other_cpu_start.boot_args = boot_args_pa;
+ other_cpu_stage = 0;
+ other_cpu_done = 0;
+ psci_by_hvc = PLAT->psci_hvc;
+ /* that core starts with its caches off: all it reads must be in memory, not in this core's cache */
+ clean_dcache((uint64_t)(uintptr_t)&other_cpu_start, (uint64_t)(uintptr_t)&other_cpu_start + sizeof(other_cpu_start));
+ clean_dcache((uint64_t)(uintptr_t)&other_cpu_stage, (uint64_t)(uintptr_t)&other_cpu_stage + 8);
+ clean_dcache((uint64_t)(uintptr_t)&other_cpu_done, (uint64_t)(uintptr_t)&other_cpu_done + 8);
+ clean_dcache((uint64_t)(uintptr_t)&psci_by_hvc, (uint64_t)(uintptr_t)&psci_by_hvc + 8);
+ clean_dcache((uint64_t)(uintptr_t)&other_cpu_entry, (uint64_t)(uintptr_t)&other_cpu_entry + 0x1000);
+ clean_dcache((uint64_t)(uintptr_t)loader_ctx, (uint64_t)(uintptr_t)loader_ctx + sizeof(loader_ctx));
+
+ if (psci_by_hvc) {
+ register uint64_t x0 __asm__("x0") = PSCI_CPU_ON;
+ register uint64_t x1 __asm__("x1") = mpidr;
+ register uint64_t x2 __asm__("x2") = (uint64_t)(uintptr_t)&other_cpu_entry;
+ register uint64_t x3 __asm__("x3") = (uint64_t)(uintptr_t)&other_cpu_start;
+
+ __asm__ volatile ("hvc #0" : "+r" (x0), "+r" (x1), "+r" (x2), "+r" (x3)
+ : : "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17");
+ status = (int64_t)x0;
+ } else {
+ smc_x3 = (uint64_t)(uintptr_t)&other_cpu_start; /* arrives in that core's x0 */
+ status = (int64_t)smc_call(PSCI_CPU_ON, mpidr, (uint64_t)(uintptr_t)&other_cpu_entry, NULL, NULL);
+ smc_x3 = 0;
+ }
+
+ started = last_pet = last_beat_at = READ_SYSREG(CNTVCT_EL0);
+ print("core %x: the firmware answers %d to the request to start it\n", mpidr, (uint64_t)status);
+ if (PLAT->log_other_cpu) {
+ flush_log();
+ }
+ while (status == 0) {
+ /*
+ * The first seconds are the ones in which a new arrangement goes wrong, and a machine
+ * that resets takes this loader's memory with it: where there is storage for the log,
+ * what the kernel is seen to do goes there as it happens. That needs UEFI's services,
+ * so until NOTE_SECONDS are over this core keeps its interrupts.
+ */
+ if (!watching_only && seconds_since(started) >= noted + 2) {
+ noted = seconds_since(started);
+ if (PLAT->log_other_cpu) {
+ if (!arrived) {
+ print("%d s: the core has not arrived\n", noted);
+ } else {
+ note_kernel_progress(live, slide, noted);
+ }
+ flush_log();
+ }
+ }
+ /*
+ * After that this core only watches: no interrupts (the kernel reprograms the interrupt
+ * controller's shared half; UEFI's handlers had better not run on top of that for long).
+ */
+ if (!watching_only && seconds_since(started) >= NOTE_SECONDS) {
+ watching_only = 1;
+ daif = READ_SYSREG(DAIF);
+ __asm__ volatile ("msr daifset, #0xf");
+ group1 = READ_SYSREG(S3_0_C12_C12_7); /* ICC_IGRPEN1_EL1 */
+ __asm__ volatile ("msr S3_0_C12_C12_7, %0\nisb" : : "r" ((uint64_t)0));
+ }
+ /* both are written by a core with its caches off: look at memory, not at our copy */
+ flush_dcache((uint64_t)(uintptr_t)&other_cpu_done, (uint64_t)(uintptr_t)&other_cpu_done + 8);
+ if (other_cpu_done) {
+ /* what the kernel returned, written the same way */
+ flush_dcache((uint64_t)(uintptr_t)&loader_ctx[CTX_LOG_PA], (uint64_t)(uintptr_t)&loader_ctx[CTX_KSP + 1]);
+ break;
+ }
+ if (!arrived) {
+ flush_dcache((uint64_t)(uintptr_t)&other_cpu_stage, (uint64_t)(uintptr_t)&other_cpu_stage + 8);
+ arrived = other_cpu_stage != 0;
+ if (!arrived && seconds_since(started) >= START_SECONDS) {
+ status = OTHER_CPU_NOT_STARTED;
+ }
+ }
+ /*
+ * The watchdog is this core's to feed for as long as the kernel is expected to run:
+ * the kernel does it too, but whether that counts from another core is not known.
+ * After that a kernel that neither returns nor hangs visibly meets the watchdog.
+ */
+ if (wdt_armed && seconds_since(last_pet) >= 5 && seconds_since(started) < budget + 60) {
+ wdt_pet();
+ last_pet = READ_SYSREG(CNTVCT_EL0);
+ }
+ if (arrived && live != NULL) {
+ if (live->heartbeat != last_beat) {
+ last_beat = live->heartbeat;
+ last_beat_at = READ_SYSREG(CNTVCT_EL0);
+ } else if (seconds_since(last_beat_at) >= SILENCE_SECONDS) {
+ log_of_hung_kernel(live, slide);
+ status = OTHER_CPU_HUNG;
+ }
+ }
+ for (volatile int i = 0; i < 20000; i++) {
+ }
+ }
+
+ if (watching_only) {
+ __asm__ volatile ("msr S3_0_C12_C12_7, %0\nisb" : : "r" (group1));
+ __asm__ volatile ("msr daif, %0" : : "r" (daif));
+ }
+ return status;
+}
+
+/* ------------------------------------------------------------------------ */
+/* Hypervisor watchdog (Qualcomm "Haven" virtual watchdog, SMC interface as */
+/* used by Linux drivers/virt/haven/hh_virt_wdt.c). Armed for the whole stay */
+/* in the loader and the kernel: any hang ends in a reset without a human. */
+
+#define VIRT_WDT_CONTROL 0x86000005u
+#define VIRT_WDT_STATUS 0x86000006u
+#define VIRT_WDT_PET 0x86000007u
+#define VIRT_WDT_SET_TIME 0x86000008u
+#define WDT_BITE_MS 30000u
+
+static const struct platform *PLAT;
+static int wdt_armed;
+
+static uint64_t smc_x3; /* the fourth argument register, for the one call that has one */
+
+static uint64_t
+smc_call(uint64_t id, uint64_t a1, uint64_t a2, uint64_t *r1, uint64_t *r2)
+{
+ register uint64_t x0 __asm__("x0") = id;
+ register uint64_t x1 __asm__("x1") = a1;
+ register uint64_t x2 __asm__("x2") = a2;
+ register uint64_t x3 __asm__("x3") = smc_x3;
+
+ __asm__ volatile ("smc #0" : "+r" (x0), "+r" (x1), "+r" (x2), "+r" (x3)
+ : : "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17");
+ if (r1 != NULL) {
+ *r1 = x1;
+ }
+ if (r2 != NULL) {
+ *r2 = x2;
+ }
+ return x0;
+}
+
+static void
+wdt_pet(void)
+{
+ if (wdt_armed) {
+ smc_call(VIRT_WDT_PET, 0, 0, NULL, NULL);
+ }
+}
+
+/* Change the time to the bite, and start counting again. The hypervisor takes 16 bits of milliseconds. */
+static void
+wdt_set_ms(uint64_t ms)
+{
+ if (ms > 65000) {
+ ms = 65000;
+ }
+ if (wdt_armed) {
+ smc_call(VIRT_WDT_SET_TIME, ms, ms, NULL, NULL);
+ smc_call(VIRT_WDT_PET, 0, 0, NULL, NULL);
+ }
+}
+
+static void
+wdt_arm(void)
+{
+ uint64_t ctl = 0, since = 0;
+
+ if (PLAT != &platform_redwood) {
+ return; /* SMC is not routed anywhere useful on QEMU virt */
+ }
+ uint64_t st = smc_call(VIRT_WDT_STATUS, 0, 0, &ctl, &since);
+ uint64_t r_time = smc_call(VIRT_WDT_SET_TIME, WDT_BITE_MS, WDT_BITE_MS, NULL, NULL);
+ uint64_t r_ctl = smc_call(VIRT_WDT_CONTROL, 3, 0, NULL, NULL);
+ uint64_t r_pet = smc_call(VIRT_WDT_PET, 0, 0, NULL, NULL);
+ print("watchdog: status ret=%x ctl=%x since_pet=%x; set_time=%x enable=%x pet=%x\n", st, ctl, since, r_time,
+ r_ctl, r_pet);
+ wdt_armed = (r_pet == 0);
+}
+
+/* ------------------------------------------------------------------------ */
+/* UEFI exception hook: put the fault into the log instead of on the screen */
+
+extern char __ImageBase;
+
+static void EFIAPI
+exception_handler(int64_t type, uint64_t *ctx)
+{
+ print("\nUEFI EXCEPTION type=%d elr=%x esr=%x far=%x lr=%x sp=%x spsr=%x\n", (uint64_t)type, ctx[EXC_CTX_ELR],
+ ctx[EXC_CTX_ESR], ctx[EXC_CTX_FAR], ctx[EXC_CTX_LR], ctx[EXC_CTX_SP], ctx[EXC_CTX_SPSR]);
+ print("loader image base %x (elr offset %x)\n", (uint64_t)(uintptr_t)&__ImageBase,
+ ctx[EXC_CTX_ELR] - (uint64_t)(uintptr_t)&__ImageBase);
+ flush_log();
+ ST->rt->reset_system(0 /* EfiResetCold */, 0, 0, NULL);
+ for (;;) {
+ }
+}
+
+static void
+install_exception_hook(void)
+{
+ static const efi_guid cpu_guid = EFI_CPU_ARCH_GUID;
+ efi_cpu_arch *cpu;
+
+ if (EFI_ERROR(BS->locate_protocol(&cpu_guid, NULL, (void **)&cpu))) {
+ return;
+ }
+ for (int64_t type = 0; type <= 3; type += 3) { /* synchronous, SError */
+ cpu->register_interrupt_handler(cpu, type, NULL);
+ efi_status s = cpu->register_interrupt_handler(cpu, type, exception_handler);
+ if (EFI_ERROR(s)) {
+ print("exception hook %d: status %x\n", (uint64_t)type, s);
+ }
+ }
+}
+
+/* ------------------------------------------------------------------------ */
+/* Payload */
+
+struct payload_info {
+ const uint8_t *kernel;
+ const uint8_t *ramdisk;
+ uint32_t ramdisk_size;
+ const char *cmdline;
+ uint64_t checkpoint;
+ uint64_t forced_base;
+ uint64_t resident_rd; /* size of a root image the host put at the resident address */
+ int usb_mode;
+};
+
+static uint64_t
+parse_number(const char *c, unsigned base)
+{
+ uint64_t v = 0;
+ for (; *c; c++) {
+ uint64_t d = (*c >= '0' && *c <= '9') ? (uint64_t)(*c - '0') : (*c >= 'a' && *c <= 'f') ? (uint64_t)(*c - 'a' + 10) : 16;
+ if (d >= base) {
+ break;
+ }
+ v = v * base + d;
+ }
+ return v;
+}
+
+static int
+parse_payload(struct payload_info *pi, int verbose)
+{
+ struct payload_header *ph = (struct payload_header *)PAYLOAD_BASE;
+
+ memset(pi, 0, sizeof(*pi));
+ pi->cmdline = "";
+ if (ph->magic != PAYLOAD_MAGIC) {
+ print("no payload at %x (magic %x)\n", PAYLOAD_BASE, (uint64_t)ph->magic);
+ return 0;
+ }
+ const uint8_t *p = (const uint8_t *)(ph + 1), *pend = p + ph->size;
+ while (p + sizeof(struct payload_entry) <= pend) {
+ const struct payload_entry *e = (const struct payload_entry *)p;
+ const char *text = (const char *)(p + sizeof(*e));
+ if (e->name[0] == 0) {
+ break;
+ }
+ if (verbose) {
+ print("payload entry '%s' size %x\n", e->name, (uint64_t)e->size);
+ }
+ if (str_eq(e->name, "ramdisk")) {
+ pi->ramdisk = p + sizeof(*e); /* becomes /dev/md0, the root device */
+ pi->ramdisk_size = e->size;
+ } else if (str_eq(e->name, "kernel")) {
+ pi->kernel = p + sizeof(*e);
+ } else if (str_eq(e->name, "cmdline")) {
+ pi->cmdline = text;
+ } else if (str_eq(e->name, "physbase")) {
+ pi->forced_base = parse_number(text, 16); /* testing aid; must be free RAM */
+ } else if (str_eq(e->name, "rdres")) {
+ pi->resident_rd = parse_number(text, 16); /* e.g. loaded there by QEMU; see RESIDENT_RD_OFFSET */
+ } else if (str_eq(e->name, "checkpoint")) {
+ pi->checkpoint = parse_number(text, 10); /* where the kernel should stop and come back */
+ } else if (str_eq(e->name, "usb")) {
+ pi->usb_mode = 1; /* stay in the loader and take commands over USB */
+ }
+ p += sizeof(*e) + ((e->size + 15) & ~15u);
+ }
+ return 1;
+}
+
+/* ------------------------------------------------------------------------ */
+/* NVRAM image */
+/* */
+/* iBoot hands the kernel a copy of the NVRAM contents in CHRP format */
+/* (iokit/Kernel/IONVRAMCHRPHandler.cpp). There is no NVRAM here, so build */
+/* an image with a valid header and one empty "common" partition. */
+
+static void
+nvram_chrp_header(uint8_t *h, uint8_t sig, uint32_t bytes, const char *name)
+{
+ uint16_t blocks = (uint16_t)(bytes / 16), sum;
+
+ memset(h, 0, 16);
+ h[0] = sig;
+ h[2] = (uint8_t)blocks;
+ h[3] = (uint8_t)(blocks >> 8);
+ memcpy(h + 4, name, str_len(name));
+ /* checksum over signature, length and name, folded to 8 bits */
+ sum = h[0];
+ for (int i = 2; i < 16; i++) {
+ sum += h[i];
+ }
+ while (sum > 0xff) {
+ sum = (sum & 0xff) + (sum >> 8);
+ }
+ h[1] = (uint8_t)sum;
+}
+
+static void
+build_nvram_image(uint8_t *image)
+{
+ uint32_t lo = 1, hi = 0, generation = 1;
+
+ memset(image, 0, NVRAM_BANK_SIZE);
+ nvram_chrp_header(image, 0x5a, 0x20, "nvram"); /* Apple header: 32 bytes */
+ nvram_chrp_header(image + 0x20, 0x70, NVRAM_BANK_SIZE - 0x20, "common"); /* the rest: common partition */
+ memcpy(image + 20, &generation, 4);
+ /* Adler-32 over everything after the checksum field itself */
+ for (uint32_t i = 20; i < NVRAM_BANK_SIZE; i++) {
+ lo = (lo + image[i]) % 65521;
+ hi = (hi + lo) % 65521;
+ }
+ uint32_t adler = (hi << 16) | lo;
+ memcpy(image + 16, &adler, 4);
+}
+
+/* ------------------------------------------------------------------------ */
+/* Running the kernel */
+
+static efi_gop *GOP;
+/* The display handed to the kernel: the firmware's, or one we set up ourselves (QEMU). base 0 = none. */
+static struct {
+ uint64_t base;
+ uint32_t width, height, stride;
+} SCREEN;
+static uint64_t win_base, win_size; /* XNU's physical memory window, claimed once */
+static uint64_t resident_rd_size; /* root image kept at win_base + RESIDENT_RD_OFFSET, 0 if none */
+static char last_result[64] = "idle";
+
+static void
+set_result(const char *what, uint64_t a, uint64_t b)
+{
+ uint32_t saved = log_len;
+ uint32_t start = log_len;
+ print("%s %d %x", what, a, b);
+ uint32_t n = log_len - start;
+ if (n > sizeof(last_result) - 1) {
+ n = sizeof(last_result) - 1;
+ }
+ memcpy(last_result, log_buf + start, n);
+ last_result[n] = 0;
+ log_len = saved;
+}
+
+/* Every range of the firmware's memory map of 1 MB or more, and the total of each type. */
+static void
+print_memory_map(void)
+{
+ static uint8_t map_buf[65536];
+ uint64_t map_size = sizeof(map_buf), map_key, desc_size, totals[16];
+ uint32_t desc_ver;
+
+ if (EFI_ERROR(BS->get_memory_map(&map_size, map_buf, &map_key, &desc_size, &desc_ver))) {
+ print("GetMemoryMap failed\n");
+ return;
+ }
+ memset(totals, 0, sizeof(totals));
+ print("memory map (type 7 = free, 1/2 = loader, 3/4 = boot services, 5/6 = runtime, 0 = reserved):\n");
+ for (uint64_t off = 0; off < map_size; off += desc_size) {
+ efi_memory_descriptor *d = (efi_memory_descriptor *)(map_buf + off);
+
+ if (d->type < 16) {
+ totals[d->type] += d->pages << 12;
+ }
+ if (d->pages >= 256) {
+ print(" %x - %x type %d %d MB\n", d->phys_start, d->phys_start + (d->pages << 12), (uint64_t)d->type,
+ d->pages >> 8);
+ }
+ }
+ for (int t = 0; t < 16; t++) {
+ if (totals[t] != 0) {
+ print(" total of type %d: %d MB\n", (uint64_t)t, totals[t] >> 20);
+ }
+ }
+}
+
+static int
+choose_window(const struct payload_info *pi)
+{
+ static uint8_t map_buf[65536];
+ uint64_t map_size = sizeof(map_buf), map_key, desc_size;
+ uint32_t desc_ver;
+ uint64_t best_base = 0, best_size = 0;
+ uint64_t pay_lo = PAYLOAD_BASE, pay_hi = PAYLOAD_BASE + PAYLOAD_MAX_SIZE;
+
+ if (win_size != 0) {
+ return 1;
+ }
+ if (EFI_ERROR(BS->get_memory_map(&map_size, map_buf, &map_key, &desc_size, &desc_ver))) {
+ print("GetMemoryMap failed\n");
+ return 0;
+ }
+ for (uint64_t off = 0; off < map_size; off += desc_size) {
+ efi_memory_descriptor *d = (efi_memory_descriptor *)(map_buf + off);
+ if (d->type != EfiConventionalMemory) {
+ continue;
+ }
+ uint64_t lo = d->phys_start, hi = d->phys_start + (d->pages << 12);
+ /* the payload sits in RAM that UEFI may consider free: stay clear of it */
+ if (lo < pay_hi && hi > pay_lo) {
+ if (pay_lo - lo > hi - pay_hi && pay_lo > lo) {
+ hi = pay_lo;
+ } else {
+ lo = pay_hi;
+ }
+ }
+ lo = (lo + BASE_ALIGN - 1) & ~(BASE_ALIGN - 1);
+ hi &= ~(BASE_ALIGN - 1);
+ if (hi > lo && hi - lo > best_size) {
+ best_base = lo;
+ best_size = hi - lo;
+ }
+ }
+ print("largest free block %x size %x\n", best_base, best_size);
+ if (pi->forced_base != 0) {
+ best_base = pi->forced_base;
+ best_size = MAX_MEM_SIZE;
+ }
+ if (best_size > MAX_MEM_SIZE) {
+ best_size = MAX_MEM_SIZE;
+ }
+ /* UEFI stays alive while the kernel runs, so the kernel must own all of its window. */
+ uint64_t claim = best_base;
+ efi_status s = BS->allocate_pages(AllocateAddress, EfiLoaderData, best_size >> 12, &claim);
+ print("phys window %x size %x, claim status %x\n", best_base, best_size, s);
+ if (EFI_ERROR(s)) {
+ return 0;
+ }
+ win_base = best_base;
+ win_size = best_size;
+ return 1;
+}
+
+/*
+ * Load and run the kernel from the payload. Returns when the kernel comes
+ * back (panic, checkpoint, early exception); the combined log is staged and
+ * written to the log partition. Returns 0 if the kernel could not be started.
+ */
+static int starts_with(const char *s, const char *prefix);
+
+static int
+run_kernel(int have_checkpoint, uint64_t checkpoint)
+{
+ static uint8_t map_buf[65536];
+ uint64_t map_size, map_key, desc_size;
+ uint32_t desc_ver;
+ struct payload_info pi;
+
+ if (!parse_payload(&pi, 1) || pi.kernel == NULL) {
+ print("no kernel in payload\n");
+ return 0;
+ }
+ if (!have_checkpoint) {
+ checkpoint = pi.checkpoint;
+ }
+ const uint8_t *kernel = pi.kernel;
+ const struct mach_header_64 *mh = (const struct mach_header_64 *)kernel;
+ if (mh->magic != MH_MAGIC_64) {
+ print("kernel is not a 64-bit Mach-O\n");
+ return 0;
+ }
+
+ /* --- kernel extent -------------------------------------------------- */
+ uint64_t vm_lo = ~0ULL, vm_hi = 0, entry_va = 0;
+ const struct load_command *lc = (const struct load_command *)(mh + 1);
+ for (uint32_t i = 0; i < mh->ncmds; i++, lc = (const void *)((const uint8_t *)lc + lc->cmdsize)) {
+ if (lc->cmd == LC_SEGMENT_64) {
+ const struct segment_command_64 *sg = (const void *)lc;
+ if (sg->vmsize == 0) {
+ continue;
+ }
+ if (sg->vmaddr < vm_lo) {
+ vm_lo = sg->vmaddr;
+ }
+ if (sg->vmaddr + sg->vmsize > vm_hi) {
+ vm_hi = sg->vmaddr + sg->vmsize;
+ }
+ } else if (lc->cmd == LC_UNIXTHREAD) {
+ /* cmd, cmdsize, flavor, count, x0..x28, fp, lr, sp, pc */
+ entry_va = ((const uint64_t *)((const uint8_t *)lc + 16))[32];
+ }
+ }
+ print("kernel va %x..%x entry %x\n", vm_lo, vm_hi, entry_va);
+ if (vm_lo < KERNEL_VIRT_BASE + KERNEL_LINK_OFFSET || entry_va == 0) {
+ print("unexpected kernel layout\n");
+ return 0;
+ }
+ if (!choose_window(&pi)) {
+ return 0;
+ }
+
+ uint64_t phys_base = win_base;
+ uint64_t slide = phys_base - KERNEL_VIRT_BASE; /* pa = va + slide */
+ uint64_t kern_lo = vm_lo + slide, kern_hi = (vm_hi + slide + PAGE_SIZE_MAX - 1) & ~(PAGE_SIZE_MAX - 1);
+ /* The ramdisk must sit inside the kernel's static mapping, i.e. below topOfKernelData. */
+ uint64_t rd_pa = kern_hi;
+ uint64_t rd_size = (pi.ramdisk_size + PAGE_SIZE_MAX - 1) & ~(PAGE_SIZE_MAX - 1);
+ int rd_resident = 0;
+ /* A resident image next to a payload ramdisk: two disks (which is which is decided where the device tree is written). */
+ uint64_t rd1_pa = 0, rd1_size = 0;
+
+ if (pi.resident_rd != 0) {
+ resident_rd_size = pi.resident_rd;
+ }
+ if (resident_rd_size != 0) {
+ uint64_t res_pa = phys_base + RESIDENT_RD_OFFSET;
+ uint64_t res_size = (resident_rd_size + PAGE_SIZE_MAX - 1) & ~(PAGE_SIZE_MAX - 1);
+
+ if (kern_hi + rd_size > res_pa) {
+ print("kernel and ramdisk overlap the resident image\n");
+ return 0;
+ }
+ if (rd_size == 0) {
+ rd_pa = res_pa;
+ rd_size = res_size;
+ rd_resident = 1;
+ } else {
+ rd1_pa = res_pa;
+ rd1_size = res_size;
+ }
+ }
+ /* everything up to topOfKernelData is the kernel's static region: it must cover both images */
+ uint64_t dt_pa = rd1_size != 0 ? rd1_pa + rd1_size : rd_pa + rd_size;
+ uint64_t dt_max = 0x10000;
+ uint64_t ba_pa = dt_pa + dt_max;
+ uint64_t top = ba_pa + PAGE_SIZE_MAX;
+
+ if (win_size < top - phys_base + 0x4000000ULL) {
+ print("not enough contiguous RAM\n");
+ return 0;
+ }
+
+ /* --- load segments -------------------------------------------------- */
+ lc = (const struct load_command *)(mh + 1);
+ for (uint32_t i = 0; i < mh->ncmds; i++, lc = (const void *)((const uint8_t *)lc + lc->cmdsize)) {
+ const struct segment_command_64 *sg = (const void *)lc;
+ if (lc->cmd != LC_SEGMENT_64 || sg->vmsize == 0) {
+ continue;
+ }
+ memset((void *)(sg->vmaddr + slide), 0, sg->vmsize);
+ memcpy((void *)(sg->vmaddr + slide), kernel + sg->fileoff, sg->filesize);
+ }
+ print("kernel loaded at pa %x..%x\n", kern_lo, kern_hi);
+ if (rd_resident) {
+ print("resident ramdisk at pa %x size %x\n", rd_pa, rd_size);
+ } else if (rd_size != 0) {
+ memset((void *)rd_pa, 0, rd_size);
+ memcpy((void *)rd_pa, pi.ramdisk, pi.ramdisk_size);
+ print("ramdisk at pa %x size %x\n", rd_pa, rd_size);
+ }
+ if (rd1_size != 0) {
+ print("resident image at pa %x size %x: it is the root (md0), the payload ramdisk is md1\n", rd1_pa, rd1_size);
+ }
+
+ /* "bootcpu=N" among the kernel's arguments: run it on core N (see run_on_other_cpu) */
+ uint64_t this_mpidr = READ_SYSREG(MPIDR_EL1) & 0xFFFFFF, kernel_mpidr = this_mpidr;
+ for (const char *c = pi.cmdline; *c; c++) {
+ if (starts_with(c, "bootcpu=") && (c == pi.cmdline || c[-1] == ' ') && c[8] >= '0' && c[8] <= '7') {
+ /* this phone numbers its cores in the second affinity field, QEMU in the first */
+ kernel_mpidr = (uint64_t)(c[8] - '0') << (PLAT == &platform_redwood ? 8 : 0);
+ }
+ }
+ if (checkpoint == CHECKPOINT_SELFTEST) {
+ kernel_mpidr = this_mpidr;
+ }
+
+ /* where the kernel will show its signs of life, and how long it has said it will run */
+ const struct kernel_live *kernel_live = NULL;
+ uint64_t kernel_budget = 0;
+ for (uint64_t *q = (uint64_t *)kern_lo; q < (uint64_t *)kern_hi; q++) {
+ if (*q == KERNEL_LIVE_MAGIC) {
+ kernel_live = (const struct kernel_live *)q;
+ break;
+ }
+ }
+ for (const char *c = pi.cmdline; *c; c++) {
+ if (starts_with(c, "loader_return_after=")) {
+ for (c += 20; *c >= '0' && *c <= '9'; c++) {
+ kernel_budget = kernel_budget * 10 + (uint64_t)(*c - '0');
+ }
+ break;
+ }
+ }
+
+ /* Give the kernel the address of our return stub and the checkpoint to stop at. */
+ for (uint64_t *q = (uint64_t *)kern_lo; q < (uint64_t *)kern_hi; q++) {
+ if (*q == 0x545352444C554E58ULL /* "XNULDRST" */) {
+ q[1] = kernel_mpidr != this_mpidr ? (uint64_t)(uintptr_t)&other_cpu_return_stub :
+ (uint64_t)(uintptr_t)&loader_return_stub;
+ q[2] = checkpoint;
+ q[3] = slide;
+ print("return slot patched at %x, checkpoint %d\n", (uint64_t)(uintptr_t)q, checkpoint);
+ break;
+ }
+ }
+
+ /* --- boot_args ------------------------------------------------------ */
+ struct boot_args *ba = (struct boot_args *)ba_pa;
+ memset(ba, 0, sizeof(*ba));
+ ba->revision = 2;
+ ba->version = 2;
+ ba->virtBase = KERNEL_VIRT_BASE;
+ ba->physBase = phys_base;
+ ba->memSize = win_size;
+ ba->memSizeActual = win_size;
+ ba->topOfKernelData = top;
+ /* any display the firmware has set up: the phone's panel, or QEMU's ramfb */
+ if (SCREEN.base != 0) {
+ /*
+ * v_display is how iBoot says "graphics mode": the kernel then keeps
+ * its text off the screen. A verbose boot (-v) wants the text.
+ */
+ int verbose = 0;
+ for (const char *c = pi.cmdline; *c; c++) {
+ verbose |= starts_with(c, "-v") && (c[2] == ' ' || c[2] == 0) && (c == pi.cmdline || c[-1] == ' ');
+ }
+ ba->video.v_baseAddr = SCREEN.base;
+ ba->video.v_display = verbose ? 0 : 1;
+ ba->video.v_rowBytes = SCREEN.stride;
+ ba->video.v_width = SCREEN.width;
+ ba->video.v_height = SCREEN.height;
+ ba->video.v_depth = 32;
+ }
+ /*
+ * No "-v" by default: on the phone the verbose console is a text
+ * framebuffer that scrolls 10 MB per line and slows boot to a crawl.
+ * The log comes back through the loader instead. Add -v via the
+ * payload's cmdline entry to watch the boot on screen.
+ */
+ /*
+ * serial=3 sends the console to the UART. Where there is none it would
+ * only silence the screen; and a "serial=" in the payload's own
+ * arguments must win, which means ours must not come first.
+ */
+ int own_serial = 0;
+ for (const char *c = pi.cmdline; *c; c++) {
+ own_serial |= starts_with(c, "serial=");
+ }
+ const char *base_cmdline = (PLAT->uart != 0 && !own_serial) ? "debug=0x8 serial=3 cpus=1 " : "debug=0x8 cpus=1 ";
+ uint32_t n = 0;
+ for (const char *c = base_cmdline; *c && n < BOOT_LINE_LENGTH - 1; c++) {
+ ba->commandLine[n++] = *c;
+ }
+ /* the root is the first RAM disk unless the payload says otherwise */
+ int own_root = 0;
+ for (const char *c = pi.cmdline; *c; c++) {
+ own_root |= starts_with(c, "rd=") && (c == pi.cmdline || c[-1] == ' ');
+ }
+ if (rd_size != 0 && !own_root) {
+ for (const char *c = "rd=md0 "; *c && n < BOOT_LINE_LENGTH - 1; c++) {
+ ba->commandLine[n++] = *c;
+ }
+ }
+ if (wdt_armed) {
+ for (const char *c = "hv_wdt_pet=1 "; *c && n < BOOT_LINE_LENGTH - 1; c++) {
+ ba->commandLine[n++] = *c;
+ }
+ }
+ for (const char *c = pi.cmdline; *c && n < BOOT_LINE_LENGTH - 1; c++) {
+ ba->commandLine[n++] = *c;
+ }
+
+ /* --- device tree ---------------------------------------------------- */
+ const struct platform *plat = PLAT;
+ struct dt_writer w = { .base = (uint8_t *)dt_pa, .cur = (uint8_t *)dt_pa, .depth = 0 };
+ uint64_t cntfrq = READ_SYSREG(CNTFRQ_EL0);
+ uint64_t ranges[3] = { 0, plat->io_base, plat->io_size };
+ uint64_t reg2[2];
+ uint8_t seed[64];
+
+ for (unsigned i = 0; i < sizeof(seed); i++) {
+ seed[i] = (uint8_t)(READ_SYSREG(CNTVCT_EL0) >> (i & 7)) ^ (uint8_t)(i * 37);
+ }
+
+ dt_begin(&w, "device-tree");
+ /*
+ * The identity is the iPhone's (model, compatible, target-type ...): iOS 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.
+ */
+ dt_identity(&w, identity_root, sizeof(identity_root) / sizeof(identity_root[0]), identity_root_data);
+ dt_prop_str(&w, "platform-name", "t8015");
+ /* what iBoot takes from the factory configuration of a real phone; fixed size fields */
+ dt_prop_padded(&w, "serial-number", "RDW00POCOX5P", 32);
+ dt_prop_padded(&w, "mlb-serial-number", "RDW00POCOX5PMLB00", 32);
+ dt_prop_padded(&w, "model-number", "MQAC2", 32);
+ dt_prop_padded(&w, "region-info", "LL/A", 32);
+ dt_prop_padded(&w, "regulatory-model-number", "A1865", 32);
+ dt_prop_u32(&w, "#address-cells", 2);
+ dt_prop_u32(&w, "#size-cells", 2);
+
+ dt_begin(&w, "chosen");
+ dt_prop(&w, "random-seed", seed, sizeof(seed));
+ dt_prop_u64(&w, "dram-base", phys_base);
+ dt_prop_u64(&w, "dram-size", win_size);
+ dt_prop_u32(&w, "debug-enabled", 1);
+ /* what MobileGestalt answers "main screen scale" from: 3 device pixels per point */
+ dt_prop_u32(&w, "display-scale", 3);
+ dt_prop_u32(&w, "display-rotation", 0);
+ /* the time now, by the firmware's clock (the kernel has no real-time clock driver) */
+ uint64_t epoch = firmware_epoch();
+ if (epoch != 0) {
+ dt_prop_u64(&w, "boot-epoch", epoch);
+ }
+ /*
+ * More of what iBoot reports about the phone. MobileGestalt builds the device identifier
+ * (UDID) from the serial number, the chip ID and the two addresses; when one is missing it
+ * asks its helper for the factory data, is refused and waits forever (and lsd with it).
+ */
+ static const uint8_t wifi_address[6] = { 0x02, 0x52, 0x44, 0x57, 0x00, 0x01 };
+ static const uint8_t bluetooth_address[6] = { 0x02, 0x52, 0x44, 0x57, 0x00, 0x02 };
+ static const uint8_t manifest_hash[48] = { 0x72, 0x65, 0x64, 0x77, 0x6f, 0x6f, 0x64 };
+ static const uint8_t no_behavior[16];
+ dt_prop_u64(&w, "unique-chip-id", 0x000052445730001ULL);
+ dt_prop_u32(&w, "chip-id", 0x8015);
+ dt_prop_u32(&w, "board-id", 0x06);
+ dt_prop(&w, "mac-address-wifi0", wifi_address, sizeof(wifi_address));
+ dt_prop(&w, "mac-address-bluetooth0", bluetooth_address, sizeof(bluetooth_address));
+ dt_prop(&w, "boot-manifest-hash", manifest_hash, sizeof(manifest_hash));
+ dt_prop(&w, "software-behavior", no_behavior, sizeof(no_behavior));
+ dt_prop_str(&w, "firmware-version", "iBoot-8422.100.650");
+ dt_prop_u32(&w, "certificate-production-status", 1);
+ dt_prop_u32(&w, "certificate-security-mode", 1);
+ dt_prop_u32(&w, "effective-production-status-ap", 1);
+ dt_prop_u32(&w, "effective-security-mode-ap", 1);
+ dt_prop_u32(&w, "secure-boot", 1);
+ dt_prop_u32(&w, "production-cert", 1);
+ dt_prop_u32(&w, "development-cert", 0);
+ dt_prop_u32(&w, "embedded-panic-log-size", PANIC_LOG_SIZE);
+ /* An empty but well-formed NVRAM image: IOKit refuses to start without it. */
+ static uint8_t nvram_image[NVRAM_BANK_SIZE];
+ build_nvram_image(nvram_image);
+ dt_prop_u32(&w, "nvram-bank-size", NVRAM_BANK_SIZE);
+ dt_prop_u32(&w, "nvram-bank-count", 1);
+ dt_prop_u32(&w, "nvram-current-bank", 0);
+ dt_prop(&w, "nvram-proxy-data", nvram_image, sizeof(nvram_image));
+ dt_begin(&w, "memory-map");
+ /*
+ * "RAMDisk" becomes /dev/md0, the root (the kernel and launchd treat
+ * only md0 as a RAM disk boot); "RAMDisk1" becomes /dev/md1. With both
+ * images present the big resident one is the root and the payload's
+ * small one is the second disk.
+ */
+ if (rd_size != 0 || rd1_size != 0) {
+ uint64_t first[2] = { rd1_size != 0 ? rd1_pa : rd_pa, rd1_size != 0 ? rd1_size : rd_size };
+ dt_prop(&w, "RAMDisk", first, sizeof(first));
+ }
+ if (rd_size != 0 && rd1_size != 0) {
+ uint64_t second[2] = { rd_pa, rd_size };
+ dt_prop(&w, "RAMDisk1", second, sizeof(second));
+ }
+ dt_end(&w);
+ dt_end(&w);
+
+ dt_begin(&w, "defaults");
+ dt_end(&w);
+
+ /* the product: screen class, artwork scale, name ... as on the real phone */
+ dt_begin(&w, "product");
+ dt_identity(&w, identity_product, sizeof(identity_product) / sizeof(identity_product[0]), identity_product_data);
+ dt_end(&w);
+
+ /* IOKit publishes its NVRAM object on this node; without it IOKit asserts. */
+ dt_begin(&w, "options");
+ dt_end(&w);
+
+ /* Panic log region: RAM outside XNU's window (tail of the payload reservation). */
+ uint64_t pram_reg[2] = { PANIC_LOG_BASE, PANIC_LOG_SIZE };
+ memset((void *)PANIC_LOG_BASE, 0, PANIC_LOG_SIZE);
+ dt_begin(&w, "pram");
+ dt_prop(&w, "reg", pram_reg, sizeof(pram_reg));
+ dt_end(&w);
+
+ dt_begin(&w, "cpus");
+ dt_begin(&w, "cpu0");
+ dt_prop_str(&w, "device_type", "cpu");
+ dt_prop_str(&w, "state", "running");
+ dt_prop_u32(&w, "reg", (uint32_t)kernel_mpidr);
+ dt_prop_u32(&w, "cpu-id", 0);
+ dt_prop_u64(&w, "timebase-frequency", cntfrq);
+ dt_prop_u64(&w, "fixed-frequency", cntfrq);
+ dt_prop_u64(&w, "clock-frequency", 1800000000ULL);
+ dt_prop_u64(&w, "bus-frequency", 100000000ULL);
+ dt_prop_u64(&w, "memory-frequency", 100000000ULL);
+ dt_prop_u64(&w, "peripheral-frequency", 24000000ULL);
+ dt_end(&w);
+ dt_end(&w);
+
+ dt_begin(&w, "arm-io");
+ dt_prop_str(&w, "device_type", plat->name);
+ dt_prop(&w, "ranges", ranges, sizeof(ranges));
+ dt_prop_u32(&w, "#address-cells", 2);
+ dt_prop_u32(&w, "#size-cells", 2);
+ dt_begin(&w, "gic");
+ dt_prop_str(&w, "device_type", "interrupt-controller");
+ dt_prop_str(&w, "compatible", "arm,gic-v3");
+ uint64_t gic_reg[4] = { plat->gic_dist - plat->io_base, 0x10000, plat->gic_redist - plat->io_base, 0x100000 };
+ dt_prop(&w, "reg", gic_reg, sizeof(gic_reg));
+ dt_end(&w);
+ if (plat->uart != 0) {
+ dt_begin(&w, "uart0");
+ dt_prop_str(&w, "device_type", "uart");
+ dt_prop_str(&w, "compatible", "arm,pl011");
+ reg2[0] = plat->uart - plat->io_base;
+ reg2[1] = 0x1000;
+ dt_prop(&w, "reg", reg2, sizeof(reg2));
+ dt_prop_u32(&w, "boot-console", 1);
+ dt_end(&w);
+ }
+ dt_end(&w);
+
+ dt_end(&w);
+
+ uint32_t dt_len = (uint32_t)(w.cur - w.base);
+ ba->deviceTreeP = dt_pa - slide;
+ ba->deviceTreeLength = dt_len;
+ print("device tree %x len %x, boot_args %x, top %x\n", dt_pa, (uint64_t)dt_len, ba_pa, top);
+ print("cmdline: %s\n", ba->commandLine);
+ if (kernel_mpidr != this_mpidr) {
+ print("the kernel will run on core %x (this is core %x)\n", kernel_mpidr, this_mpidr);
+ }
+ print("jumping to %x\n", entry_va + slide);
+ flush_log();
+ /* From here on the kernel feeds the watchdog (boot-arg hv_wdt_pet, see loader_return.c in XNU). */
+ wdt_set_ms(60000);
+
+ /* --- hand off (UEFI is left resident, see loader_save_ctx) ------------ */
+ if (loader_save_ctx() == 0) {
+ /*
+ * On real hardware (under the Qualcomm hypervisor) dirty data-cache
+ * lines do not survive the MMU-off round trip. UEFI stays resident,
+ * so everything it owns must be written back to RAM first: clean
+ * every allocated region in the memory map, then this stack again.
+ */
+ map_size = sizeof(map_buf);
+ if (!EFI_ERROR(BS->get_memory_map(&map_size, map_buf, &map_key, &desc_size, &desc_ver))) {
+ for (uint64_t off = 0; off < map_size; off += desc_size) {
+ efi_memory_descriptor *d = (efi_memory_descriptor *)(map_buf + off);
+ /* loader/boot-services/runtime code and data, ACPI tables; XNU's own window is handled below */
+ if (d->phys_start >= win_base && d->phys_start < win_base + win_size) {
+ continue;
+ }
+ if ((d->type >= 1 && d->type <= 6) || d->type == 9 || d->type == 10) {
+ clean_dcache(d->phys_start, d->phys_start + (d->pages << 12));
+ }
+ }
+ }
+ uint64_t sp_now = (uint64_t)(uintptr_t)__builtin_frame_address(0);
+ clean_dcache(sp_now - 0x2000, sp_now + 0x2000);
+ flush_dcache(phys_base, top);
+ if (checkpoint == CHECKPOINT_SELFTEST) {
+ /* Do not enter the kernel at all: exercise only the return path. */
+ jump_to_kernel((uint64_t)(uintptr_t)&loader_return_stub, 0);
+ }
+ if (kernel_mpidr != this_mpidr) {
+ int64_t status = run_on_other_cpu(kernel_mpidr, entry_va + slide, ba_pa, kernel_live, slide, kernel_budget);
+
+ wdt_set_ms(WDT_BITE_MS);
+ if (status == OTHER_CPU_HUNG) {
+ /* the kernel still has that core; what it logged can be had all the same */
+ print("THE KERNEL HUNG on core %x: no sign of life for %d seconds; its log follows\n", kernel_mpidr,
+ (uint64_t)SILENCE_SECONDS);
+ set_result("hung", loader_ctx[CTX_LOG_LEN], 0);
+ write_logs((const char *)loader_ctx[CTX_LOG_PA], loader_ctx[CTX_LOG_LEN]);
+ return 1;
+ } else if (status != 0) {
+ /* the kernel was told it would be on that core (return path, device tree): no second try */
+ if (status == OTHER_CPU_NOT_STARTED) {
+ print("core %x was started but never arrived\n", kernel_mpidr);
+ } else {
+ print("core %x did not start: PSCI error %d\n", kernel_mpidr, (uint64_t)-status);
+ }
+ set_result("no-such-core", (uint64_t)(status < 0 ? -status : status), 0);
+ write_logs(NULL, 0);
+ return 1;
+ }
+ } else {
+ jump_to_kernel(entry_va + slide, ba_pa);
+ }
+ }
+
+ /* --- the kernel came back ------------------------------------------- */
+ wdt_set_ms(WDT_BITE_MS);
+ recording_data = NULL;
+ recording_len = 0;
+ if (kernel_live != NULL && kernel_live->recording != 0 && checkpoint != CHECKPOINT_SELFTEST) {
+ const uint64_t *recording = (const uint64_t *)(kernel_live->recording + slide);
+
+ if (recording[0] != 0 && recording[1] > 24 && recording[1] <= (1ULL << 30)) {
+ recording_data = (const char *)recording[0];
+ recording_len = recording[1];
+ print("the kernel left a screen recording: %d bytes at %x\n", recording_len, recording[0]);
+ }
+ }
+ const char *klog = (const char *)loader_ctx[CTX_LOG_PA];
+ uint64_t klog_len = loader_ctx[CTX_LOG_LEN];
+ uint64_t reason = loader_ctx[CTX_REASON];
+ if (checkpoint == CHECKPOINT_SELFTEST) {
+ print("return-path self test passed\n");
+ set_result("selftest-ok", 0, 0);
+ klog = NULL;
+ klog_len = 0;
+ } else {
+ print("kernel returned: log at %x, %d bytes\n", (uint64_t)(uintptr_t)klog, klog_len);
+ if (reason == 2) {
+ print("STOPPED AT CHECKPOINT %d\n", loader_ctx[CTX_ESR]);
+ set_result("checkpoint", loader_ctx[CTX_ESR], 0);
+ } else if (reason == 1) {
+ print("EARLY KERNEL EXCEPTION: esr=%x elr=%x far=%x lr=%x sp=%x\n", loader_ctx[CTX_ESR], loader_ctx[CTX_ELR],
+ loader_ctx[CTX_FAR], loader_ctx[CTX_LR], loader_ctx[CTX_KSP]);
+ print(" (pa-va slide %x: subtract it from physical addresses to symbolicate)\n", slide);
+ set_result("early-exception", 0, loader_ctx[CTX_ELR]);
+ klog_len = klog_len > (1u << 20) ? 0 : klog_len;
+ } else {
+ set_result("returned", klog_len, 0);
+ }
+ }
+ write_logs(klog, klog_len);
+ return 1;
+}
+
+/* ------------------------------------------------------------------------ */
+/* USB command channel: a small fastboot-protocol server. */
+/* */
+/* Host side (stock `fastboot` tool): */
+/* fastboot stage payload.bin download a new "XNUP" payload */
+/* fastboot oem run [N] run its kernel (optionally stop at N) */
+/* fastboot getvar result blocks until the kernel is back */
+/* fastboot get_staged log.txt fetch loader + kernel log */
+/* fastboot oem hang stop petting the watchdog (test) */
+/* fastboot reboot cold reset */
+
+#define USB_EP_OUT 0x01
+#define USB_EP_IN 0x81
+#define USB_CHUNK (1024 * 1024)
+
+static usb_device_protocol *USB;
+static int download_to_ramdisk; /* set by "oem ramdisk" for the one download that follows */
+static uint8_t *usb_rx_buf, *usb_tx_buf;
+static int usb_connected;
+
+static const uint8_t usb_dev_desc[18] = { 18, 1, 0x10, 0x02, 0, 0, 0, 64, 0xd1, 0x18, 0x0d, 0xd0, 0x00, 0x01, 1, 2, 3, 1 };
+static const uint8_t usb_ss_dev_desc[18] = { 18, 1, 0x00, 0x03, 0, 0, 0, 9, 0xd1, 0x18, 0x0d, 0xd0, 0x00, 0x01, 1, 2, 3, 1 };
+static const uint8_t usb_cfg_desc[32] = {
+ 9, 2, 32, 0, 1, 1, 0, 0x80, 0x50,
+ 9, 4, 0, 0, 2, 0xff, 0x42, 0x03, 4, /* fastboot interface */
+ 7, 5, USB_EP_IN, 2, 0x00, 0x02, 0,
+ 7, 5, USB_EP_OUT, 2, 0x00, 0x02, 0,
+};
+static const uint8_t usb_ss_cfg_desc[44] = {
+ 9, 2, 44, 0, 1, 1, 0, 0x80, 0x10,
+ 9, 4, 0, 0, 2, 0xff, 0x42, 0x03, 4,
+ 7, 5, USB_EP_IN, 2, 0x00, 0x04, 0, 6, 0x30, 4, 0, 0, 0,
+ 7, 5, USB_EP_OUT, 2, 0x00, 0x04, 0, 6, 0x30, 4, 0, 0, 0,
+};
+static const uint8_t usb_qualifier[10] = { 10, 6, 0x00, 0x02, 0xff, 0xff, 0xff, 64, 1, 0 };
+static const uint8_t usb_bos[42] = {
+ 5, 0x0f, 42, 0, 3,
+ 7, 0x10, 0x02, 0x06, 0, 0, 0,
+ 10, 0x10, 0x03, 0x00, 0x0e, 0x00, 0x01, 0x07, 0x65, 0x00,
+ 20, 0x10, 0x0a, 0x00, 0x01, 0, 0, 0, 0x00, 0x11, 0, 0, 0x30, 0x40, 0x0a, 0x00, 0xb0, 0x40, 0x0a, 0x00,
+};
+static const uint8_t usb_str0[4] = { 4, 3, 0x09, 0x04 };
+static const uint8_t usb_str_mfr[8] = { 8, 3, 'X', 0, 'N', 0, 'U', 0 };
+static const uint8_t usb_str_prod[20] = { 20, 3, 'x', 0, 'n', 0, 'u', 0, 'l', 0, 'o', 0, 'a', 0, 'd', 0, 'e', 0, 'r', 0 };
+static const uint8_t usb_str_serial[20] = { 20, 3, 'x', 0, 'n', 0, 'u', 0, 'l', 0, 'o', 0, 'a', 0, 'd', 0, 'e', 0, 'r', 0 };
+static const uint8_t usb_str_iface[18] = { 18, 3, 'f', 0, 'a', 0, 's', 0, 't', 0, 'b', 0, 'o', 0, 'o', 0, 't', 0 };
+
+static void EFIAPI
+usb_dummy_notify(void *event, void *ctx)
+{
+}
+
+static int
+usb_start(void)
+{
+ static const efi_guid usb_guid = QCOM_USB_DEVICE_GUID;
+ static const efi_guid init_guid = QCOM_USB_INIT_EVENT_GUID;
+ static const void *cfg = usb_cfg_desc, *ss_cfg = usb_ss_cfg_desc;
+ static const void *strings[5] = { usb_str0, usb_str_mfr, usb_str_prod, usb_str_serial, usb_str_iface };
+ static usb_device_descriptor_set set;
+ void *event;
+
+ /* Ask the platform to bring the controller up in peripheral mode (as the stock fastboot does). */
+ if (!EFI_ERROR(BS->create_event_ex(0x200 /* EVT_NOTIFY_SIGNAL */, 8 /* TPL_CALLBACK */, usb_dummy_notify, NULL,
+ &init_guid, &event))) {
+ BS->signal_event(event);
+ BS->close_event(event);
+ }
+ if (EFI_ERROR(BS->locate_protocol(&usb_guid, NULL, (void **)&USB))) {
+ print("usb: device protocol not found\n");
+ return 0;
+ }
+ set.device_descriptor = usb_dev_desc;
+ set.descriptors = &cfg;
+ set.ss_device_descriptor = usb_ss_dev_desc;
+ set.ss_descriptors = &ss_cfg;
+ set.device_qualifier = usb_qualifier;
+ set.bos = usb_bos;
+ set.string_count = 5;
+ set.strings = strings;
+ efi_status s = USB->start_ex(&set);
+ if (EFI_ERROR(s)) {
+ print("usb: start failed %x\n", s);
+ return 0;
+ }
+ if (EFI_ERROR(USB->allocate_transfer_buffer(USB_CHUNK, (void **)&usb_rx_buf)) ||
+ EFI_ERROR(USB->allocate_transfer_buffer(USB_CHUNK, (void **)&usb_tx_buf))) {
+ print("usb: no transfer buffers\n");
+ return 0;
+ }
+ print("usb: started\n");
+ return 1;
+}
+
+/*
+ * Pump controller events until a transfer on `endpoint` finishes.
+ * Returns the byte count, or -1 if the transfer was cancelled or the cable
+ * state changed. Keeps the watchdog fed while idle.
+ */
+static int64_t
+usb_wait(uint8_t endpoint)
+{
+ /* static: a long transfer is many short waits, and the watchdog must be fed across them */
+ static uint64_t last_pet;
+ uint64_t freq = READ_SYSREG(CNTFRQ_EL0);
+
+ for (;;) {
+ uint32_t msg = UsbDeviceEventNoEvent;
+ uint64_t size = 0;
+ usb_device_event_data data;
+
+ USB->handle_event(&msg, &size, &data);
+ if (msg == UsbDeviceEventDeviceStateChange) {
+ usb_connected = (data.device_state == UsbDeviceStateConnected);
+ return -1;
+ }
+ if (msg == UsbDeviceEventTransferNotification && data.transfer.endpoint_index == endpoint) {
+ return data.transfer.status == UsbDeviceTransferStatusCompleteOK ? (int64_t)data.transfer.bytes_completed : -1;
+ }
+ if (READ_SYSREG(CNTVCT_EL0) - last_pet > freq) {
+ last_pet = READ_SYSREG(CNTVCT_EL0);
+ wdt_pet();
+ }
+ }
+}
+
+static int64_t
+usb_rx(uint8_t *buf, uint64_t len)
+{
+ if (EFI_ERROR(USB->send(USB_EP_OUT, len, buf))) {
+ return -1;
+ }
+ return usb_wait(USB_EP_OUT);
+}
+
+static int64_t
+usb_tx(const uint8_t *data, uint64_t len)
+{
+ if (data != usb_tx_buf) {
+ memcpy(usb_tx_buf, data, len);
+ }
+ if (EFI_ERROR(USB->send(USB_EP_IN, len, usb_tx_buf))) {
+ return -1;
+ }
+ return usb_wait(USB_EP_IN);
+}
+
+static void
+fb_reply(const char *code, const char *text)
+{
+ uint32_t n = 0;
+ for (; *code; code++) {
+ usb_tx_buf[n++] = (uint8_t)*code;
+ }
+ for (; *text && n < 63; text++) {
+ usb_tx_buf[n++] = (uint8_t)*text;
+ }
+ usb_tx(usb_tx_buf, n);
+}
+
+static void
+fb_reply_data(uint64_t len)
+{
+ char msg[13] = "DATA00000000";
+ for (int i = 0; i < 8; i++) {
+ msg[4 + i] = "0123456789abcdef"[(len >> (28 - 4 * i)) & 0xf];
+ }
+ usb_tx((const uint8_t *)msg, 12);
+}
+
+static int
+starts_with(const char *s, const char *prefix)
+{
+ while (*prefix) {
+ if (*s++ != *prefix++) {
+ return 0;
+ }
+ }
+ return 1;
+}
+
+static void
+usb_command_loop(void)
+{
+ screen_quiet = 1;
+ for (;;) {
+ if (!usb_connected) {
+ usb_wait(0xff); /* returns on the next cable state change */
+ continue;
+ }
+ int64_t n = usb_rx(usb_rx_buf, 511);
+ if (n <= 0) {
+ continue;
+ }
+ char cmd[128];
+ if (n > (int64_t)sizeof(cmd) - 1) {
+ n = sizeof(cmd) - 1;
+ }
+ memcpy(cmd, usb_rx_buf, (size_t)n);
+ cmd[n] = 0;
+
+ if (starts_with(cmd, "getvar:")) {
+ const char *var = cmd + 7;
+ if (str_eq(var, "product")) {
+ fb_reply("OKAY", "xnuloader");
+ } else if (str_eq(var, "version")) {
+ fb_reply("OKAY", "0.4");
+ } else if (str_eq(var, "max-download-size")) {
+ fb_reply("OKAY", download_to_ramdisk ? "0xffffffff" : "0x03f00000");
+ } else if (str_eq(var, "result")) {
+ fb_reply("OKAY", last_result);
+ } else if (str_eq(var, "screen") && SCREEN.base != 0) {
+ /* width height bytes-per-row */
+ uint32_t mark = log_len;
+ print("%d %d %d", (uint64_t)SCREEN.width, (uint64_t)SCREEN.height, (uint64_t)SCREEN.stride);
+ log_buf[log_len] = 0;
+ fb_reply("OKAY", log_buf + mark);
+ log_len = mark;
+ } else {
+ fb_reply("OKAY", "");
+ }
+ } else if (starts_with(cmd, "oem ramdisk")) {
+ /* "oem ramdisk": the next download is a root image for the resident area; "oem ramdisk none" drops it */
+ struct payload_info pi;
+
+ if (starts_with(cmd, "oem ramdisk none")) {
+ resident_rd_size = 0;
+ fb_reply("OKAY", "");
+ continue;
+ }
+ parse_payload(&pi, 0);
+ log_len = 0;
+ if (!choose_window(&pi) || win_size <= RESIDENT_RD_OFFSET + RESIDENT_RD_RESERVE) {
+ fb_reply("FAIL", "no memory window");
+ continue;
+ }
+ download_to_ramdisk = 1;
+ fb_reply("OKAY", "");
+ } else if (starts_with(cmd, "download:")) {
+ uint64_t total = parse_number(cmd + 9, 16), got = 0;
+ uint64_t limit = PAYLOAD_MAX_SIZE - 0x100000;
+ uint8_t *dest = (uint8_t *)PAYLOAD_BASE;
+ int to_ramdisk = download_to_ramdisk;
+
+ download_to_ramdisk = 0;
+ if (to_ramdisk) {
+ limit = win_size - RESIDENT_RD_OFFSET - RESIDENT_RD_RESERVE;
+ dest = (uint8_t *)(win_base + RESIDENT_RD_OFFSET);
+ resident_rd_size = 0;
+ }
+ if (total == 0 || total > limit) {
+ fb_reply("FAIL", "bad size");
+ continue;
+ }
+ fb_reply_data(total);
+ while (got < total) {
+ uint64_t want = total - got > USB_CHUNK ? USB_CHUNK : total - got;
+ int64_t r = usb_rx(usb_rx_buf, want);
+ if (r <= 0) {
+ break;
+ }
+ memcpy(dest + got, usb_rx_buf, (size_t)r);
+ got += (uint64_t)r;
+ }
+ if (got == total) {
+ if (to_ramdisk) {
+ resident_rd_size = total;
+ }
+ fb_reply("OKAY", "");
+ } else {
+ fb_reply("FAIL", "short download");
+ }
+ } else if (starts_with(cmd, "upload")) {
+ uint64_t sent = 0;
+ fb_reply_data(staged_len);
+ while (sent < staged_len) {
+ uint64_t chunk = staged_len - sent > USB_CHUNK ? USB_CHUNK : staged_len - sent;
+ if (usb_tx((const uint8_t *)staged_data + sent, chunk) < 0) {
+ break;
+ }
+ sent += chunk;
+ }
+ fb_reply("OKAY", "");
+ } else if (starts_with(cmd, "oem screenshot")) {
+ /* stage the raw framebuffer; "getvar screen" gives its geometry */
+ if (SCREEN.base == 0) {
+ fb_reply("FAIL", "no display");
+ continue;
+ }
+ staged_data = (const char *)(uintptr_t)SCREEN.base;
+ staged_len = (uint64_t)SCREEN.stride * SCREEN.height;
+ fb_reply("OKAY", "");
+ } else if (starts_with(cmd, "oem recording")) {
+ /* stage what the kernel's display driver recorded (boot-arg rec_secs) */
+ if (recording_data == NULL) {
+ fb_reply("FAIL", "no recording");
+ continue;
+ }
+ staged_data = recording_data;
+ staged_len = recording_len;
+ fb_reply("OKAY", "");
+ } else if (starts_with(cmd, "oem clearscreen")) {
+ if (SCREEN.base != 0) {
+ memset((void *)(uintptr_t)SCREEN.base, 0, (size_t)SCREEN.stride * SCREEN.height);
+ }
+ fb_reply("OKAY", "");
+ } else if (starts_with(cmd, "oem run") || starts_with(cmd, "oem selftest")) {
+ int selftest = starts_with(cmd, "oem selftest");
+ const char *arg = cmd + 7;
+ while (*arg == ' ') {
+ arg++;
+ }
+ int have_cp = selftest || (*arg >= '0' && *arg <= '9');
+ uint64_t cp = selftest ? CHECKPOINT_SELFTEST : parse_number(arg, 10);
+
+ set_result("running", cp, 0);
+ fb_reply("OKAY", "");
+ log_len = 0;
+ print("== XNULOADER run (usb) ==\n");
+ if (!run_kernel(have_cp, cp)) {
+ set_result("not-started", 0, 0);
+ compose_logs(NULL, 0);
+ }
+ } else if (starts_with(cmd, "oem hang")) {
+ fb_reply("OKAY", "watchdog test: not petting any more");
+ for (;;) {
+ }
+ } else if (starts_with(cmd, "oem memmap")) {
+ /* the firmware's memory map into the log (then "oem log" and fetch it) */
+ print_memory_map();
+ fb_reply("OKAY", "");
+ } else if (starts_with(cmd, "oem log")) {
+ compose_logs(NULL, 0);
+ fb_reply("OKAY", "");
+ } else if (starts_with(cmd, "reboot") || starts_with(cmd, "oem reboot")) {
+ fb_reply("OKAY", "");
+ BS->stall(200000);
+ ST->rt->reset_system(0 /* EfiResetCold */, 0, 0, NULL);
+ } else {
+ fb_reply("FAIL", "unknown command");
+ }
+ }
+}
+
+/* ------------------------------------------------------------------------ */
+
+/*
+ * 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
+ * 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 */
+#define PHONE_HEIGHT 2436
+#define FW_CFG_BASE 0x09020000ULL /* QEMU virt: data at +0, selector at +8, DMA address at +16 */
+#define FW_CFG_FILE_DIR 0x19
+#define FW_CFG_DMA_SELECT 0x08
+#define FW_CFG_DMA_WRITE 0x10
+
+static uint32_t
+be32(uint32_t v)
+{
+ return __builtin_bswap32(v);
+}
+
+static void
+fw_cfg_read(void *buf, uint32_t len)
+{
+ for (uint32_t i = 0; i < len; i++) {
+ ((uint8_t *)buf)[i] = *(volatile uint8_t *)FW_CFG_BASE;
+ }
+}
+
+static void
+ramfb_phone_screen(void)
+{
+ static struct {
+ uint64_t addr;
+ uint32_t fourcc, flags, width, height, stride;
+ } __attribute__((packed)) cfg;
+ static struct {
+ uint32_t control, length;
+ uint64_t address;
+ } dma;
+ struct {
+ uint32_t size;
+ uint16_t select, reserved;
+ char name[56];
+ } file;
+ uint32_t count, select = 0;
+ uint64_t fb = 0, bytes = (uint64_t)PHONE_WIDTH * 4 * PHONE_HEIGHT;
+
+ *(volatile uint16_t *)(FW_CFG_BASE + 8) = __builtin_bswap16(FW_CFG_FILE_DIR);
+ fw_cfg_read(&count, sizeof(count));
+ count = be32(count);
+ for (uint32_t i = 0; i < count && i < 256 && select == 0; i++) {
+ fw_cfg_read(&file, sizeof(file));
+ if (str_eq(file.name, "etc/ramfb")) {
+ select = __builtin_bswap16(file.select);
+ }
+ }
+ if (select == 0 || EFI_ERROR(BS->allocate_pages(AllocateAnyPages, EfiLoaderData, (bytes + 0xFFF) >> 12, &fb))) {
+ return;
+ }
+ memset((void *)(uintptr_t)fb, 0, (size_t)bytes);
+ cfg.addr = __builtin_bswap64(fb);
+ cfg.fourcc = be32(0x34325258); /* 'XR24': blue, green, red, unused */
+ cfg.flags = 0;
+ cfg.width = be32(PHONE_WIDTH);
+ cfg.height = be32(PHONE_HEIGHT);
+ cfg.stride = be32(PHONE_WIDTH * 4);
+ dma.control = be32(select << 16 | FW_CFG_DMA_SELECT | FW_CFG_DMA_WRITE);
+ dma.length = be32(sizeof(cfg));
+ dma.address = __builtin_bswap64((uint64_t)(uintptr_t)&cfg);
+ *(volatile uint64_t *)(FW_CFG_BASE + 16) = __builtin_bswap64((uint64_t)(uintptr_t)&dma);
+ if (dma.control != 0) {
+ print("ramfb: control %x after the request\n", (uint64_t)be32(dma.control));
+ return;
+ }
+ SCREEN.base = fb;
+ SCREEN.width = PHONE_WIDTH;
+ SCREEN.height = PHONE_HEIGHT;
+ SCREEN.stride = PHONE_WIDTH * 4;
+}
+
+efi_status EFIAPI
+efi_main(efi_handle image, efi_system_table *st)
+{
+ static const efi_guid gop_guid = EFI_GOP_GUID;
+ struct payload_info pi;
+
+ ST = st;
+ BS = st->bs;
+ IMAGE = image;
+
+ BS->set_watchdog_timer(0, 0, 0, NULL);
+ print("== XNULOADER v3 ==\n");
+ print("CurrentEL=%x MIDR=%x MMFR0=%x CNTFRQ=%d image=%x\n", READ_SYSREG(CurrentEL) >> 2, READ_SYSREG(MIDR_EL1),
+ READ_SYSREG(ID_AA64MMFR0_EL1), READ_SYSREG(CNTFRQ_EL0), (uint64_t)(uintptr_t)&__ImageBase);
+
+ PLAT = &platform_qemu_virt;
+ if (EFI_ERROR(BS->locate_protocol(&gop_guid, NULL, (void **)&GOP)) || GOP->mode == NULL ||
+ GOP->mode->info == NULL || GOP->mode->fb_base == 0) {
+ GOP = NULL; /* no display (QEMU without -device ramfb) */
+ } else {
+ SCREEN.base = GOP->mode->fb_base;
+ SCREEN.width = GOP->mode->info->width;
+ SCREEN.height = GOP->mode->info->height;
+ SCREEN.stride = GOP->mode->info->pixels_per_scanline * 4;
+ if (SCREEN.base == 0xE1000000ULL) {
+ PLAT = &platform_redwood;
+ } else {
+ ramfb_phone_screen();
+ }
+ print("display %d x %d at %x\n", (uint64_t)SCREEN.width, (uint64_t)SCREEN.height, SCREEN.base);
+ }
+ print("platform %s\n", PLAT->name);
+
+ install_exception_hook();
+ wdt_arm();
+
+ int have_payload = parse_payload(&pi, 0);
+ if (have_payload && pi.usb_mode && usb_start()) {
+ flush_log();
+ usb_command_loop();
+ }
+
+ /* One-shot mode: run the kernel that came with the image, then reset. */
+ if (have_payload) {
+ run_kernel(0, 0);
+ }
+ reboot();
+ return 0;
+}
diff --git a/xnuloader/mkidentity.py b/xnuloader/mkidentity.py
new file mode 100755
index 0000000..73095da
--- /dev/null
+++ b/xnuloader/mkidentity.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""Take the identity of an iPhone from its real device tree, for the loader to hand to XNU.
+
+usage: mkidentity.py DeviceTree.<board>.bin > identity.h
+
+The input is the device tree itself, i.e. the payload of Firmware/all_flash/DeviceTree.<board>.im4p
+of 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
+tree: the root node's model and compatible, and the /product node (screen class, artwork
+scale, product name ...). 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
+system believes it is the iPhone its files were built for.
+
+Properties that iBoot fills in on a real phone ("syscfg/..." placeholders: serial number,
+colours, calibration data) are left out; the loader adds the few that are needed itself.
+"""
+import struct
+import sys
+
+
+def parse(data, pos=0):
+ """One node of a flattened Apple device tree: (properties, children, next position)."""
+ nprops, nchildren = struct.unpack_from('<II', data, pos)
+ pos += 8
+ props = []
+ for _ in range(nprops):
+ name = data[pos:pos + 32].split(b'\0')[0].decode()
+ length = struct.unpack_from('<I', data, pos + 32)[0] & 0x7FFFFFFF
+ value = data[pos + 36:pos + 36 + length]
+ props.append((name, value))
+ pos += 36 + (length + 3 & ~3)
+ children = []
+ for _ in range(nchildren):
+ child, pos = parse(data, pos)
+ children.append(child)
+ return (props, children), pos
+
+
+def name_of(node):
+ return dict(node[0]).get('name', b'').split(b'\0')[0].decode()
+
+
+def emit(label, props, skip):
+ kept = [(n, v) for n, v in props if n not in skip and not v.startswith((b'syscfg/', b'macaddr/', b'zeroes/'))]
+ blob = bytearray()
+ print(f'/* {len(kept)} properties */')
+ print(f'static const struct identity_prop {label}[] = {{')
+ for name, value in kept:
+ print(f'\t{{ "{name}", {len(blob)}, {len(value)} }},')
+ blob += value
+ print('};')
+ print(f'static const unsigned char {label}_data[] = {{')
+ for i in range(0, len(blob), 20):
+ print('\t' + ' '.join(f'0x{b:02x},' for b in blob[i:i + 20]))
+ print('};\n')
+
+
+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('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',
+ 'platform-name', 'time-stamp', 'secure-root-prefix'))
+ emit('identity_product', children['product'][0], ('name', 'AAPL,phandle'))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/xnuloader/mkpayload.py b/xnuloader/mkpayload.py
new file mode 100755
index 0000000..9afa17e
--- /dev/null
+++ b/xnuloader/mkpayload.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+"""
+Build the "XNUP" payload consumed by the boot shim and the XNU loader.
+
+ header : u32 magic "XNUP", u32 size (bytes after the header)
+ entries: char name[16], u32 size, u32 reserved, data padded to 16 bytes
+ end : an entry whose name is empty
+
+usage: mkpayload.py -o payload.bin name=file [name=file ...] [--cmdline "..."]
+"""
+import argparse, struct
+
+ap = argparse.ArgumentParser()
+ap.add_argument('-o', '--output', required=True)
+ap.add_argument('--cmdline', default='')
+ap.add_argument('--physbase', default='', help='hex: force XNU physical base (testing)')
+ap.add_argument('--usb', action='store_true', help='make the loader stay resident and take commands over USB')
+ap.add_argument('--rdres', default='', help='hex size of a root image already placed at the resident address (QEMU)')
+ap.add_argument('--checkpoint', default='', help='kernel checkpoint to stop at; 999 = loader self test')
+ap.add_argument('items', nargs='*')
+args = ap.parse_args()
+
+body = b''
+def add(name, data):
+ global body
+ body += struct.pack('<16sII', name.encode(), len(data), 0) + data + b'\0' * (-len(data) % 16)
+
+for item in args.items:
+ name, path = item.split('=', 1)
+ add(name, open(path, 'rb').read())
+if args.cmdline:
+ add('cmdline', args.cmdline.encode() + b'\0')
+if args.physbase:
+ add('physbase', args.physbase.lower().replace('0x', '').encode() + b'\0')
+if args.rdres:
+ add('rdres', args.rdres.lower().replace('0x', '').encode() + b'\0')
+if args.usb:
+ add('usb', b'1\0')
+if args.checkpoint:
+ add('checkpoint', args.checkpoint.encode() + b'\0')
+body += b'\0' * 24
+open(args.output, 'wb').write(struct.pack('<II', 0x50554E58, len(body)) + body)
+print(f'{args.output}: {len(body) + 8} bytes')