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

CoreImage works without Metal, and AIR is far more tractable than I said

vcvkk45fba6ebe0d5
diff --git a/README.md b/README.md
index d4f5280..6eea63d 100644
--- a/README.md
+++ b/README.md
@@ -405,7 +405,10 @@ P3 поверхности кадров копировались, и этого
Его и не предполагается: почему — разобрано в `docs/metal.md`. Коротко: граница, которую пришлось бы
реализовать, — это одно имя класса в реестре IOKit (`IOAcceleratorES`) и бандл в
`/System/Library/Extensions` с подклассом приватного `_MTLDevice`, а за ней не драйвер, а компилятор
-AIR (промежуточного языка шейдеров Metal), которого нет ни в Mesa, ни где-либо ещё. Службу
+AIR (промежуточного языка шейдеров Metal), готового читателя которого в мире нет — хотя сам формат
+оказался покладистым: это обычный битовый код LLVM, и все 456 модулей системных `.metallib` читает
+готовый `llvm-dis` (`tools/metallib.py`, раздел 9 `docs/metal.md`; там же, почему «игры на Metal» —
+всё равно нет, а «системный шейдер на нашем GPU» — достижимо). Службу
`IOAcceleratorES` ядро порта как раз публикует — пустую, нарочно, чтобы CoreAnimation не ждал
полминуты и прошёл мимо (`iokit/Kernel/MiniIOMobileFramebuffer.cpp`), — так что
`MTLCreateSystemDefaultDevice()` возвращает `nil` молча, без строки в журнале. Adreno же отдаётся
@@ -439,10 +442,13 @@ Metal загружают 153 библиотеки системы, но поль
самом `Espresso`). Порт уже умеет то, чего CoreImage хочет от библиотеки OpenGL ES: точка входа
`texImageIOSurface:…` написана в `src/eagl.c`.
-Но вход туда ровно один, и это проверено: `+[CIContext contextWithOptions:]` на этом порте **падает
-с SIGSEGV** — и с `nil`, и с `kCIContextUseSoftwareRenderer`. То есть «Фото» и камера без Metal не
-деградируют, а уносят процесс; дорога к рабочему пути начинается с `contextWithEAGLContext:`, а не с
-контекста по умолчанию. Разбор по каждому из шести мест — раздел 7 `docs/metal.md`.
+**И у CoreImage это уже работает.** Вход ровно один: `+[CIContext contextWithOptions:]` падает с
+SIGSEGV (и с `nil`, и с `kCIContextUseSoftwareRenderer`) — он идёт в `CI::GLContext::init()`, которому
+никто не дал контекста OpenGL ES. А `+[CIContext contextWithEAGLContext:]` с нашим `EAGLContext`
+работает: не хватало одного метода, `-sharegroup`, которого в `src/eagl.c` не было, потому что
+CoreAnimation о нём не спрашивает. С ним CoreImage создаёт контекст (`backend: OpenGL ES
+(CI::GLContext)`, `device: nil`), компилирует ядро фильтра и считает его — на Mesa, без всякого
+Metal. Разбор по каждому из шести мест — раздел 7 `docs/metal.md`.
Что система думает про Metal, печатает `bin/metal_test` (`src/metal_test.m`,
`RC_JOBS=rc.jobs.metal`): службы, которых Metal не находит, GPU, который есть под другим именем,
diff --git a/docs/metal.md b/docs/metal.md
index ae6eddf..7b3963f 100644
--- a/docs/metal.md
+++ b/docs/metal.md
@@ -9,9 +9,11 @@
- **Граница узкая.** Служба класса `IOAcceleratorES` в ядре порта уже есть (нарочно пустая), так что
не хватает двух строковых свойств на ней и бандла с подклассом приватного `_MTLDevice`.
-- **За границей не драйвер, а компилятор.** Шейдеры приходят в AIR — битовом коде LLVM; фронтенда
- AIR нет ни в Mesa, ни где-либо ещё, и обойти его нельзя. Это та стена, из-за которой писать Metal
- здесь не стоит.
+- **За границей не драйвер, а компилятор** — но стена оказалась ниже, чем я написал сначала.
+ Шейдеры приходят в AIR, готового читателя которого в мире нет; **однако как формат AIR почти не
+ сопротивляется** (обычный битовый код LLVM, 456 модулей системы из 456 читает готовый `llvm-dis`).
+ Измерено в разделе 9, и вывод там: «игры» — твёрдое нет, «один системный шейдер на нашем GPU» —
+ достижимо.
- **Половина потерь — «пока», а не «нельзя».** У CoreImage в iOS 16.5 есть полный задний конец на
OpenGL ES, у движка CoreML — 127 процессорных ядер и ни одного металлического. Разбор — раздел 7.
- **Первый шаг оказался уже сделанным** (раздел 2), поэтому сделан другой: `metal_test`
@@ -155,12 +157,15 @@ and not supported any longer.`, `0x181b6cccb`), а задняя часть ко
`.metallib` на 3,75 МБ, и Metal знает к ним прямые пути — например
`/System/Library/Frameworks/CoreImage.framework/CoreImage.metallib` (`0x181b6c367`).
-У Mesa компилятор под Adreno (`ir3`) принимает NIR. **Фронтенда AIR нет ни в Mesa, ни где-либо
-ещё**, а обойти его нельзя: всё, что просит Metal — CoreAnimation, CoreImage, MPS, камера — несёт
+У Mesa компилятор под Adreno (`ir3`) принимает NIR. **Готового читателя AIR в мире нет** (обзор —
+9.3), а обойти его нельзя: всё, что просит Metal — CoreAnimation, CoreImage, MPS, камера — несёт
с собой уже скомпилированный AIR. Значит, первым сорвётся не отрисовка, а самый первый
`newLibraryWithData:` на любом системном `.metallib`, то есть раньше, чем что-нибудь будет
нарисовано.
+Оговорка, которую я обязан сделать: «нет читателя» — это про сегодняшний мир, а не про
+невозможность. **Написать его можно, и дешевле, чем я думал** — раздел 9 мерит, насколько.
+
Второе, что ломается, — и ломается тише: наследование от `_MTLDevice` означает, что мы получаем
его 36 приватных ivar'ов, разметка которых принадлежит сборке Metal 306.6.4 и нигде не описана, а
549 его собственных методов эти ivar'ы читают. Ошибка в разметке — порча памяти внутри чужого
@@ -268,6 +273,22 @@ CoreAnimation — рендерер OpenGL ES, который порт уже и
`0; 128; 255`. Это единственная здесь проверка, отвечающая на вопрос «может ли эта система
вообще обработать изображение», а он нужен и камере, и Фото.
+**Каждый опасный вопрос задаёт отдельный процесс**, и это не мелочь, а исправленная ошибка. Сперва
+`metal_test` разветвлялся (`fork`) и спрашивал в потомке — и все проверки до единой стали умирать с
+SIGABRT, но не в CoreImage, а в самой среде Objective-C:
+
+```
+objc[98]: +[__NSCFNumber initialize] may have been in progress in another thread when fork() was
+called. We cannot safely call it or ignore it in the fork() child process. Crashing instead.
+```
+
+Это `objc_initializeAfterForkError`: потомку `fork` нельзя пользоваться Objective-C, если у родителя
+было больше одного потока, а у `metal_test` их больше (довольно слинковаться с CoreImage и
+OpenGLES). Прогон, сделанный так, не говорит о CoreImage ничего. Теперь `metal_test` запускает себя
+заново (`posix_spawn` с именем вопроса в аргументе: `ci-eagl`, `ci-default`, …), потому что `exec`
+начинает среду с нуля. Урок общий: **в этом проекте нельзя проверять что-либо из iOS в потомке
+`fork` — только в новом процессе.**
+
Проверка бандлов идёт **последней** нарочно: взять принципиальный класс — значит загрузить код
бандла и дать выполниться его инициализаторам, а `/System/Library/Extensions/AGXMetalA11.bundle`
в образе порта есть (`apfs.py ls userland/system.apfs /System/Library/Extensions`), и это настоящий
@@ -389,16 +410,106 @@ metal_test: AGXMetalA11.bundle: executable AGXMetalA11, principal class AGXPri
То есть порт уже умеет ровно то, чего CoreImage хочет от библиотеки OpenGL ES.
Но прогон (раздел 6) добавил к этому важное: **дорога по умолчанию не просто закрыта, она
-смертельна**. `+[CIContext contextWithOptions:]` падает с SIGSEGV — и с `nil`, и с
-`kCIContextUseSoftwareRenderer: @YES`. Значит, `kCIContextUseSoftwareRenderer` здесь не выход (на
-iOS он давно ничего не значит), и всякий, кто просто просит у CoreImage контекст, уносит с собой
-процесс. Это объясняет, почему без Metal «Фото» и камера не деградируют, а падают.
+смертельна**, — и, что важнее, видно, **где именно** она обрывается. `metal_test` ловит сигнал сам
+и печатает адреса без сдвига кэша; `ipsw dyld a2s` по ним даёт:
+
+```
++[CIContext contextWithOptions:] + 36
+ -[CIContext initWithOptions:] + 504
+ +[CIContext(Internal) internalContextWithEAGLContext:options:] + 580
+ CI::GLContext::GLContext(CI::GLContext::ShareContextInfo, CGColorSpace*, …) + 500
+ CI::GLContext::init() + 204 <- здесь
+```
+
+Сигнал 11, `si_addr` 0, а программный счётчик после вычитания сдвига — `0xfffffffff9af0000`, то
+есть вызов по мусорному указателю.
+
+Из этого следует самое неожиданное в разборе: **контекст по умолчанию и так выбирает задний конец на
+OpenGL ES, а не на Metal.** Он идёт прямо в `internalContextWithEAGLContext:options:` и строит
+`CI::GLContext` — что в точности согласуется с `CIGLIsUsable()`, скомпилированным в «return 1»
+(выше). И падает он не оттого, что нет Metal, а оттого, что **`CI::GLContext::init()` начинает
+работу, когда никакого контекста OpenGL ES ему не дали**: по этой дороге `EAGLContext` — `nil`.
+
+И `kCIContextUseSoftwareRenderer: @YES` идёт **тем же путём, с тем же стеком и той же смертью**:
+на iOS 16.5 этот ключ ничего не значит, программного растеризатора у CoreImage нет.
+
+Значит вопрос «достижимо ли это» получает хороший ответ: дорога, которой CoreImage и так хочет
+идти, — ровно та, что у порта есть. Не хватает ей того единственного, чего она просит: контекста
+OpenGL ES.
+
+### Опыт на телефоне: CoreImage поверх нашего OpenGL ES
+
+Это и было проверено — на телефоне, с `gpu=1` и образом `GL=1`, то есть когда за `EAGLContext`
+стоит настоящий Adreno через freedreno:
+
+```
+redwood-gl: an OpenGL ES 3 context for CoreAnimation, by Mesa, off-screen (OSMesa):
+ OpenGL ES 3.2 Mesa 25.0.7; Adreno 7c+ Gen 3; shaders OpenGL ES GLSL ES 3.20
+metal_test: EAGLContext: EAGLContext, API 3
+metal_test: signal 11 at address 0x8
+```
+
+`EAGLContext` создался — наш, по-настоящему на GPU телефона. А `CIContext` поверх него — нет, и
+стек (адреса без сдвига, имена по `llvm-nm` извлечённого CoreImage) показывает, где именно:
+
+```
++[CIContext contextWithEAGLContext:] + 36
+ -[CIContext initWithEAGLContext:options:] + 116
+ +[CIContext(Internal) internalContextWithEAGLContext:options:] + 580
+ CI::GLContext::GLContext(CI::GLContext::ShareContextInfo, CGColorSpace*, …) + 380
+ CI::GLContext::_wrapEAGLContextCreate + 128
+ -[EAGLContext sharegroup] + 4 <- здесь, si_addr 0x8
+```
+
+**CoreImage прошёл ровно тем путём, который у порта есть, и остановился на одном нереализованном
+методе.** `src/eagl.c` подменяет у `EAGLContext` семь методов — те, о которых спрашивает
+CoreAnimation, — и `-sharegroup` среди них не было; а `my_initWithAPI()` нарочно не вызывает
+`initWithAPI:` самой Apple (своё состояние он держит в `struct eagl` рядом с объектом), так что
+настоящий `-[EAGLContext sharegroup]` читает ivar'ы, которых никто не заполнял, и падает. С
+программным драйвером Mesa адрес падения тот же — дело не в драйвере.
+
+**Чего CoreImage на самом деле хочет**, видно из `_wrapEAGLContextCreate` (`0x194b0e10c`): он
+собирает словарь свойств тремя `setObject:forKey:`, добавляет четвёртый элемент **только если
+`[наш_контекст sharegroup]` не nil** (`cbz x0`, переход через), и затем зовёт
+`objc_msgSend$initWithAPI:properties:`. То есть он **не делит наш контекст, а создаёт свой** — и
+создаёт его через тот самый метод, который `eagl.c` подменяет первым в своём списке. А группа
+совместного доступа **необязательна**: nil означает «без разделения», и это предусмотренный случай.
+
+### И этого хватило: CoreImage работает
+
+`-sharegroup` добавлен в `src/eagl.c` (возвращает nil — здесь никто контекстами не делится), и
+CoreImage пошёл дальше:
+
+```
+$ /redwood/bin/metal_test ci-eagl-software
+metal_test: /redwood/lib/libredwood-gl.dylib loaded; EAGLContext is ours now
+metal_test: EAGLContext: EAGLContext, API 3
+redwood-gl: -sharegroup asked for: none (nothing here shares a context)
+redwood-gl: an OpenGL ES 3 context for CoreAnimation, by Mesa, off-screen (OSMesa): ...
+metal_test: CIContext: CIContext
+metal_test: backend: OpenGL ES (CI::GLContext)
+metal_test: the context's Metal device: nil
+metal_test: running the filter kernel...
+metal_test: CoreImage rendered: first pixel 0 229 255 255
+```
+
+**CoreImage на этом порте считает, и считает без всякого Metal.** `-isOpenGLBased` отвечает «да»,
+`-device` — nil, ядро фильтра скомпилировалось и посчиталось, пиксели прочитаны обратно. Видно и то,
+что предсказывал разбор `_wrapEAGLContextCreate`: CoreImage сам создал несколько своих контекстов —
+каждый через наш `my_initWithAPI()`, отсюда повторяющиеся строки `an OpenGL ES 3 context`.
-**Вывод: «пока», а не «нельзя», но вход только один.** Нужно дать CoreImage `EAGLContext`
-(`+[CIContext contextWithEAGLContext:]`) — то есть сделать для него то, что `inject.c` делает для
-оконного сервера, — а не надеяться, что контекст по умолчанию сам найдёт путь. И первым делом
-стоит проверить ровно это: создаётся ли `contextWithEAGLContext:` и считает ли он ядро, когда за
-`EAGLContext` стоит наша Mesa (то есть на телефоне, с `gpu=1` и образом `GL=1`).
+Про цвет: ожидалось «примерно 0 128 255», вышло `0 229 255 255`, и **это верно**, а ошибка была в
+ожидании. CoreImage считает в линейном пространстве: sRGB 0,5 → линейное 0,214 → инверсия 0,786 →
+обратно в sRGB ≈ 0,906, то есть 231; измерено 229. Красный 0 и синий 255 точны. Инвертировать в sRGB
+напрямую, как я прикидывал, CoreImage и не должен.
+
+Одной строки в таблице методов `eagl.c` хватило, чтобы «Фото» и камера получили обратно обработку
+изображений, — ровно той, которой не хватало.
+
+**Вывод: «пока», а не «нельзя», и вход только один.** Нужно дать CoreImage `EAGLContext` через
+`+[CIContext contextWithEAGLContext:]` — путь по умолчанию (`contextWithOptions:`) к этому не ведёт,
+он падает раньше в `CI::GLContext::init()`. Дальше — работа в `inject.c`: подставлять такой контекст
+там, где framework просит контекст по умолчанию.
### Espresso (движок CoreML) — не Metal-only; процессорный движок полноправный
@@ -466,3 +577,197 @@ iOS он давно ничего не значит), и всякий, кто п
требуют устройства, а какие идут через CoreImage. Прямо касается ветки `camera`.
- **Не начинать (А) и (Б)** без фронтенда AIR. Если он когда-нибудь появится (чужой проект, не
этот), раздел 4 перечисляет, что останется сделать; до тех пор объём работы не уменьшится.
+
+## 9. Насколько AIR поддаётся: разбор
+
+Раздел 4 назвал AIR стеной. Пользователь хочет **настоящий Metal** — игры и всё прочее, — поэтому
+стену надо было измерить, а не объявить. Измерил. **Я был неправ: как формат AIR почти не
+сопротивляется.** Ниже — чем именно, по файлам и байтам.
+
+### 9.1 Что лежит в `.metallib`
+
+В извлечённой системе десять файлов `.metallib`. Пять из них — контейнеры с магией `MTLB`
+(`4d544c42`); у пяти `*_rt.metallib` внутри `AGXMetalA11.bundle` магия другая — это внутренние
+библиотеки драйвера AGX, не AIR.
+
+Разбор контейнера (разбирает его `tools/metallib.py`; проверено на
+`Extensions/AppleMetalGLRenderer.bundle/default.metallib`, 1 111 748 байт):
+
+| смещение | что |
+| --- | --- |
+| `0x00` | `"MTLB"` |
+| `0x04` | версия контейнера, здесь 1.2 |
+| `0x10` | полный размер файла — `0x10f6c4` = 1 111 748, **совпал побайтово** |
+| `0x18`, `0x20` | начало и конец списка функций |
+| `0x28`, `0x30` | public metadata: смещение и длина |
+| `0x38`, `0x40` | private metadata |
+| `0x48`, `0x50` | **битовый код**: смещение и длина |
+
+Список функций — счётчик `u32`, затем записи; у записи сначала `u32` её длины (считая само это
+поле), затем поля с тегами по образцу `[4 байта тега][u16 длины][значение]` до тега `ENDT`:
+`NAME` (имя), `TYPE` (0 vertex, 1 fragment, 2 kernel, 3 visible, 4 intersection), `HASH` (32 байта),
+`OFFT` (три `u64`: смещения в public, private и битовый код), `VERS`, `MDSZ` (размер модуля),
+`RFLT`. В конце файла ещё секции `RBUF` и `AIRR` (отражение) и тег `ENDT`.
+
+Главное: **у каждой функции свой отдельный модуль**, и он лежит в стандартной обёртке битового кода
+LLVM — `0x0B17C0DE`, а внутри обычная магия `BC\xC0\xDE`:
+
+```
+0000afc0: dec0 170b 0000 0000 1400 0000 900b 0000 (обёртка: версия 0, смещение 0x14, размер 0xb90)
+0000afd0: ffff ffff 4243 c0de 3514 0000 0300 0000 (BC\xC0\xDE — дальше обычный битовый код)
+```
+
+Из пяти контейнеров извлечено **456 модулей**, и все 456 прочитаны обычным `llvm-dis` (LLVM 22.1.8)
+**без единой ошибки**. То есть никакого «своего формата» нет: читать AIR умеет готовый LLVM,
+безо всяких правок.
+
+### 9.2 Насколько AIR отличается от обычного LLVM IR
+
+Отличий ровно три, и все узкие.
+
+**Триплет.** `target triple = "air64-apple-ios16.5.0"` у всех 456 модулей; `datalayout` —
+совершенно обычный. Версия AIR 2.5.3.0, язык «Metal 3.0», компилятор
+`Apple metal version 31001.722 (metalfe-31001.722.3)`.
+
+**Адресные пространства — всего три:** 2 (constant, 3427 обращений), 1 (device, 984), 3
+(threadgroup, 46). Это прямо ложится на модель памяти NIR и SPIR-V. Текстуры и семплеры — **не
+особые типы LLVM, а просто указатели** (`ptr addrspace(1)` и `ptr addrspace(2)`), так что экзотики
+в типах нет вовсе.
+
+**Именованные метаданные — девять видов,** и в них вся «метальность»:
+
+| метаданные | в скольких модулях |
+| --- | --- |
+| `!air.version`, `!air.language_version`, `!air.compile_options` | 456 |
+| `!air.fragment` | 271 |
+| `!air.visible` | 135 |
+| `!air.kernel` | 47 |
+| `!air.function_constants` | 11 |
+| `!air.sampler_states` | 10 |
+| `!air.vertex` | 3 |
+
+Узел точки входа описывает её интерфейс — именно то, что NIR называет переменными ввода-вывода.
+Например у `clearFragment01`:
+
+```
+!16 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"color0"}
+!18 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 48, !"air.location_index", i32 14, i32 1,
+ !"air.read", !"air.address_space", i32 2, ... !"air.arg_name", !"color"}
+```
+
+**Свои функции («интринсики»).** Во всех 456 модулях встречается 125 разных объявлений `air.*`, но
+имена устроены как `air.<операция>.<суффикс типа>`, и после снятия суффиксов остаётся **около 51
+операции** четырёх семейств:
+
+- **арифметика (≈28):** `fast_clamp`, `fast_fmin/fmax`, `fast_sqrt`, `fast_exp`, `fast_pow`,
+ `fast_sin/cos`, `fast_atan2`, `fast_floor/ceil/round/fract`, `fast_fabs`, `fast_ldexp`,
+ `saturate`, `mix`, `dot`, `sign`, `min/max`, `floor`, `convert`, `all`;
+- **текстуры (≈12):** `sample_texture_2d/3d`, `sample_depth_2d`, `read_texture_2d`,
+ `read_texture_2d_ms`, `read_depth_2d_ms`, `write_texture_2d/3d`, `gather_texture_2d`,
+ `get_width/height_texture_2d`, `get_num_samples_texture_2d_ms`;
+- **атомарные (≈9):** `atomic.global.{load,store,add,min,max}`, `atomic.local.{load,store,add}`;
+- **синхронизация (1):** `wg.barrier`.
+
+У каждой есть прямое соответствие в NIR: арифметика — это `nir_op_*`, текстуры — `nir_tex_instr`,
+атомарные — `nir_intrinsic_*_atomic`, барьер — `nir_intrinsic_barrier`. **Это короткий список, а не
+длинный хвост редкостей.**
+
+И ещё одно число, самое говорящее: **283 модуля из 456 (62 %) не зовут ни одного `air.*` вовсе** —
+это чистый LLVM IR.
+
+**Сколько всего в языке.** Выборка из пяти библиотек — не весь Metal, поэтому границу я взял из
+самого заднего конца Apple: в `AGXCompilerCore` 339 разных строк `air.*` (в `MTLCompiler` 276). Из
+них около 117 — варианты `get_*_texture_*` (запросы к текстуре по размерностям и типам, одна
+реализация с параметрами), а значительная часть остального — не интринсики, а **имена атрибутов
+ввода-вывода** (`vertex_id`, `thread_position_in_grid`, `threads_per_simdgroup`,
+`viewport_array_index`, `tile_index`, …), которым в NIR отвечают системные значения. Отдельными
+группами стоят то, чего системным шейдерам не нужно, а игре может понадобиться: `simd_*`/`quad_*`
+(операции в группе потоков), трассировка лучей (`world_to_object_transform`, `world_space_origin`,
+`triangle_data`, `intersection`), mesh-шейдеры (`set_indices_mesh`), таблицы видимых функций
+(`visible_function_table`).
+
+### 9.3 Что уже существует
+
+Разделять надо строго: **в Metal** конвертеров много, **из Metal** — почти ничего.
+
+- **[worthdoingbadly.com/metalbitcode](https://worthdoingbadly.com/metalbitcode/)** — единственный
+ содержательный разбор. Устанавливает то же, что и я: `MTLB` держит обычный битовый код LLVM,
+ `llvm-dis` его читает, `llc` даже собирает шейдер в код x86-64 и ARM64. Но: проверено на одном
+ файле, теги `HASH`/`VERS`/`OFFT` оставлены необъяснёнными, вызов `air.convert...` так и остался
+ неразрешённым, а цель была пустить шейдер на процессоре — автор сам называет результат
+ «любопытством», потому что LLVM не превращает SPMD-шейдер в хороший SIMD-код. **Перевода в чужое
+ GPU-представление там нет.**
+- **[mtl-info](https://lib.rs/crates/mtl-info)** — утилита на Rust: перечисляет функции в
+ `.metallib` и дизассемблирует их. Версия 0.2.0, март 2019, помечена нестабильной; новых
+ контейнеров почти наверняка не знает.
+- **MetalLibraryArchive** — извлекает функции из `.metallib`; снова только распаковка.
+- **[naga](https://docs.rs/crate/naga)** (wgpu) — в таблице форматов AIR упомянут, но клетка пуста;
+ Metal у него только на выходе (`msl-out`).
+- **ANGLE**, Apple Shader Converter, HLSL→Metal — всё это дорога **в** Metal.
+- **Asahi Linux** — те, кто ближе всех к задаче, сознательно пошли мимо: их компилятор — задний
+ конец NIR, а LLVM Apple они сочли необязательным. Читателя AIR у них нет.
+- **SPIRV-LLVM-Translator** — казался бы готовым мостом LLVM IR → SPIR-V, но он поддерживает
+ только OpenCL/Compute-разновидность SPIR-V. Для вершинных и фрагментных шейдеров это не путь, так
+ что дорога «AIR → SPIR-V → `spirv_to_nir`» в лоб не годится; остаётся **AIR → NIR** напрямую.
+
+Итог обзора: **читателя AIR в мире нет, но и запретов на него нет.** Моя прежняя формулировка
+(«фронтенда AIR нет ни в Mesa, ни где-либо ещё») верна как утверждение о сегодняшнем дне и неверна
+как вывод о невозможности.
+
+### 9.4 Честный ответ
+
+**Насколько это большая работа.** Мерка есть: фронтенд SPIR-V → NIR в Mesa
+(`src/compiler/spirv`) — это `spirv_to_nir.c` на 294 871 байт, `vtn_variables.c` 122 904,
+`vtn_structured_cfg.c` 60 724, `vtn_alu.c` 53 648, `vtn_opencl.c` 45 555, `vtn_cfg.c` 27 197,
+`vtn_glsl450.c` 23 284 и ещё десяток файлов — **около 750 КБ написанного руками C**, то есть
+примерно 25 тысяч строк, делавшихся годами множеством людей, причём для представления, которое
+**само задумано для такого перевода и везёт с собой машиночитаемую грамматику**. У AIR грамматики
+нет: смысл каждого `air.*` и каждого ключа метаданных надо выяснять по наблюдению.
+
+С другой стороны, половина работы уже не нужна: **разбор формата бесплатен** (456 из 456 модулей
+читает готовый LLVM), типы обычные, адресных пространств три, а не двадцать.
+
+Оценка по шагам, честная:
+
+| что | объём |
+| --- | --- |
+| один простой шейдер из настоящей `.metallib` посчитан на Adreno | дни, ~1–2 тысячи строк |
+| то, что нужно системным шейдерам: vertex/fragment/kernel, 51 операция, 2D-текстуры | месяцы, ~5–10 тысяч строк |
+| то, что нужно игре: argument buffers, simdgroup, тесселяция, mesh, трассировка лучей, таблицы функций, imageblocks | годы, и это уже масштаб Mesa |
+
+**И главное, чего нельзя забывать: шейдеры — только одна из трёх частей.** Раздел 4 мерил остальные
+две: драйвер (граф объектов `_MTLDevice`/`IOGPUMetalDevice` — 53 класса и 1158 методов у
+`AGXMetalA11`, 711 методов у `IOGPU`) и ABI ядра под клиентом `IOAcceleratorES`. Компилятор AIR я
+называл тем, что «сорвётся первым», — и это по-прежнему так, но теперь видно, что он не самый
+большой из трёх, а самый **измеримый**. Убрать его — значит остаться с двумя другими.
+
+Поэтому ответ пользователю: **настоящий Metal — игры и всё прочее — здесь не выходит**, но причина
+другая, чем я говорил. Не «непреодолимый чужой язык шейдеров», а «три больших подсистемы, каждая
+размером с то, что в проекте уже написано про графику, и ни одной нельзя обойтись». Это **нет**, и
+оно твёрдое для цели «игры». Оно **не** твёрдое для цели «один шейдер из системной библиотеки
+считается нашим GPU» — вот это выходит, и довольно скоро.
+
+### 9.5 Первый шаг, если его захотят
+
+Он уже выбран и полностью описан данными выше. `clearFragment01` из
+`AppleMetalGLRenderer.bundle/default.metallib` — настоящий фрагментный шейдер самой Apple, четыре
+команды LLVM, **ни одного `air.*`**:
+
+```llvm
+define <{ <4 x float> }> @clearFragment01(ptr addrspace(2) noalias readonly captures(none)
+ dereferenceable(48) %0) {
+ %2 = getelementptr inbounds %struct.ClearFragmentInput, ptr addrspace(2) %0, i64 0, i32 0
+ %3 = load <4 x float>, ptr addrspace(2) %2, align 16
+ %4 = insertvalue <{ <4 x float> }> undef, <4 x float> %3, 0
+ ret <{ <4 x float> }> %4
+}
+```
+
+Метаданные говорят остальное: вход — константный буфер по `air.location_index` 14 в адресном
+пространстве 2, 48 байт; выход — `air.render_target` 0. В NIR это **два узла**: `nir_load_ubo` и
+`nir_store_output`. Между «здесь» и «работает» стоит только обвязка: пройти по модулю LLVM, собрать
+`nir_shader`, отдать его `ir3` и нарисовать треугольник — то есть примерно то, что уже делает
+`bin/gl_test`, только шейдер приходит не текстом GLSL, а из `.metallib`.
+
+62 % модулей системы не зовут `air.*` вовсе, так что сразу за первым шагом лежит заметная их доля —
+и только потом начинаются текстуры, за ними всё остальное.
diff --git a/tools/metallib.py b/tools/metallib.py
new file mode 100755
index 0000000..e9c2257
--- /dev/null
+++ b/tools/metallib.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+"""Take a .metallib apart: the MTLB container, its function list, and each function's LLVM bitcode.
+
+The container was worked out by hand against the files of iOS 16.5; what is in it, and what the
+numbers below mean, is written down in docs/metal.md (section 9). Every module of every .metallib
+in the extracted system is ordinary LLVM bitcode in the standard 0x0B17C0DE wrapper, so after
+"metallib.py dump" an ordinary llvm-dis reads them.
+
+usage: metallib.py list FILE the functions, their type, air version, module size
+ metallib.py dump FILE OUTDIR [N] write each function's bitcode as OUTDIR/<name>.bc
+"""
+import os
+import struct
+import sys
+
+TYPES = {0: 'vertex', 1: 'fragment', 2: 'kernel', 3: 'visible', 4: 'intersection', 5: 'none'}
+
+
+def parse(path):
+ b = open(path, 'rb').read()
+ assert b[:4] == b'MTLB', 'not a metallib: %r' % b[:4]
+ (ver_maj, ver_min) = struct.unpack_from('<HH', b, 4)
+ total = struct.unpack_from('<Q', b, 0x10)[0]
+ funcs_off = struct.unpack_from('<Q', b, 0x18)[0]
+ funcs_end = struct.unpack_from('<Q', b, 0x20)[0]
+ pub_off, pub_len = struct.unpack_from('<QQ', b, 0x28)
+ prv_off, prv_len = struct.unpack_from('<QQ', b, 0x38)
+ bc_off, bc_len = struct.unpack_from('<QQ', b, 0x48)
+ header = dict(version=(ver_maj, ver_min), total=total, file=len(b),
+ funcs=(funcs_off, funcs_end), public=(pub_off, pub_len),
+ private=(prv_off, prv_len), bitcode=(bc_off, bc_len))
+
+ p = funcs_off
+ count = struct.unpack_from('<I', b, p)[0]
+ p += 4
+ out = []
+ for _ in range(count):
+ size = struct.unpack_from('<I', b, p)[0] # counts from this field itself
+ q, end = p + 4, p + size
+ f = {}
+ while q < end:
+ tag = b[q:q + 4]
+ if tag == b'ENDT':
+ break
+ ln = struct.unpack_from('<H', b, q + 4)[0]
+ val = b[q + 6:q + 6 + ln]
+ if tag == b'NAME':
+ f['name'] = val.rstrip(b'\0').decode('utf-8', 'replace')
+ elif tag == b'TYPE':
+ f['type'] = TYPES.get(val[0], 'type%d' % val[0])
+ elif tag == b'OFFT':
+ f['offt'] = struct.unpack('<QQQ', val)
+ elif tag == b'VERS':
+ f['vers'] = struct.unpack('<HHHH', val)
+ elif tag == b'MDSZ':
+ f['mdsz'] = struct.unpack('<Q', val)[0]
+ elif tag == b'HASH':
+ f['hash'] = val.hex()[:16]
+ q += 6 + ln
+ out.append(f)
+ p = end
+ return b, header, out
+
+
+def bitcode_of(b, header, f):
+ """The function's module, unwrapped from the LLVM bitcode wrapper if it has one."""
+ start = header['bitcode'][0] + f['offt'][2]
+ blob = b[start:start + f['mdsz']]
+ if blob[:4] == bytes((0xde, 0xc0, 0x17, 0x0b)): # 0x0B17C0DE, little endian
+ off, size = struct.unpack_from('<II', blob, 8)
+ return blob[off:off + size], True
+ return blob, False
+
+
+if __name__ == '__main__':
+ what, path = sys.argv[1], sys.argv[2]
+ b, header, funcs = parse(path)
+ if what == 'list':
+ for k, v in header.items():
+ print('%-10s %s' % (k, v))
+ print('%d functions' % len(funcs))
+ for f in funcs:
+ print(' %-52s %-13s air %s module %d' % (f.get('name', '?'), f.get('type', '?'),
+ '.'.join(map(str, f.get('vers', ()))), f.get('mdsz', 0)))
+ elif what == 'dump':
+ outdir = sys.argv[3]
+ limit = int(sys.argv[4]) if len(sys.argv) > 4 else len(funcs)
+ os.makedirs(outdir, exist_ok=True)
+ for f in funcs[:limit]:
+ bc, wrapped = bitcode_of(b, header, f)
+ name = f.get('name', 'f%d' % funcs.index(f)).replace('/', '_')[:120]
+ with open(os.path.join(outdir, name + '.bc'), 'wb') as fp:
+ fp.write(bc)
+ print('%-52s %6d bytes %s %s' % (name, len(bc), 'unwrapped' if wrapped else 'raw ', bc[:4].hex()))
diff --git a/userland/build.sh b/userland/build.sh
index 86d3e6d..2837202 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -129,9 +129,11 @@ if [ -d $IOS/rootfs/usr/lib ]; then
$DYN -o obj/cpu_test src/cpu_test.c
$DYN -framework CoreFoundation -framework IOSurface -o obj/cow_test src/cow_test.c
$DYN -framework CoreFoundation -framework CoreGraphics -framework IOSurface -o obj/cg_test src/cg_test.c
- # what iOS here believes about Metal, and what CoreImage does without it (src/metal_test.m)
- $DYN -fobjc-arc -framework Foundation -framework CoreGraphics -framework CoreImage \
- -framework IOKit -framework Metal -lMobileGestalt -o obj/metal_test src/metal_test.m
+ # what iOS here believes about Metal, and what CoreImage does without it (src/metal_test.m);
+ # OpenGLES for the CIContext made over an EAGLContext, which is deprecated and the point
+ $DYN -fobjc-arc -Wno-deprecated-declarations -framework Foundation -framework CoreGraphics \
+ -framework CoreImage -framework IOKit -framework Metal -framework OpenGLES \
+ -lMobileGestalt -o obj/metal_test src/metal_test.m
$DYN -o obj/shm_test src/shm_test.c
$DYN -o obj/apfs_mmap_test src/apfs_mmap_test.c
$DYN -o obj/vol_ls src/vol_ls.c
diff --git a/userland/rc.jobs.metal b/userland/rc.jobs.metal
index b81792e..022a7eb 100644
--- a/userland/rc.jobs.metal
+++ b/userland/rc.jobs.metal
@@ -3,4 +3,13 @@
# looks for and does not find, the GPU the registry does have under another name, whether a plug-in bundle
# of this image would load at all, the nil a program gets, what MobileGestalt still says about graphics,
# and whether CoreImage can run a filter kernel without Metal. See src/metal_test.m and docs/metal.md.
+#
+# The wait is so that the run is a realistic one: by then SpringBoard is up and, with gpu=1 on the
+# phone, the window server already holds the GPU and draws with it through src/eagl.c. That is the
+# state in which the question about CoreImage over an EAGLContext of ours is worth asking.
+# Mind the length of the run: on the phone SpringBoard is up in about 20 s, but in QEMU it took 208
+# ("sound_test: the ringer is on after 208 s"), so a QEMU session wants 480 s or more -- a shorter
+# one ends before metal_test is reached at all.
+/redwood/bin/sound_test springboard
+/redwood/bin/rwtouch wait 25
/redwood/bin/metal_test
diff --git a/userland/src/eagl.c b/userland/src/eagl.c
index 0c58368..ae44ac2 100644
--- a/userland/src/eagl.c
+++ b/userland/src/eagl.c
@@ -3387,6 +3387,29 @@ my_API(id self, SEL selector)
return e ? e->api : 0;
}
+/*
+ * -[EAGLContext sharegroup]. CoreAnimation never asks for it, but CoreImage does: a CIContext made
+ * over an EAGLContext goes +[CIContext contextWithEAGLContext:] -> internalContextWithEAGLContext:
+ * -> CI::GLContext::GLContext -> wrapEAGLContextCreate -> -[EAGLContext sharegroup], and iOS's own
+ * accessor reads ivars of an EAGLContext that my_initWithAPI never filled in (it keeps its state in
+ * `struct eagl` beside the object and does not call through to Apple's init). On the phone that
+ * crashed in -[EAGLContext sharegroup]+4 touching address 0x8. Nothing here shares a context with
+ * anybody, so the honest answer is none; what CoreImage then does is the next thing to find out.
+ */
+static id
+my_sharegroup(id self, SEL selector)
+{
+ static int said;
+
+ (void)self;
+ (void)selector;
+ if (!said) {
+ said = 1;
+ say("redwood-gl: -sharegroup asked for: none (nothing here shares a context)\n");
+ }
+ return nil;
+}
+
static unsigned long
my_setParameter(id self, SEL selector, unsigned parameter, const int32_t *values)
{
@@ -3573,6 +3596,7 @@ install(void)
} methods[] = {
{ "initWithAPI:properties:", (IMP)my_initWithAPI },
{ "API", (IMP)my_API },
+ { "sharegroup", (IMP)my_sharegroup },
{ "setParameter:to:", (IMP)my_setParameter },
{ "getMacroContextPrivate", (IMP)my_getMacroContextPrivate },
{ "texImageIOSurface:target:internalFormat:width:height:format:type:plane:invert:", (IMP)my_texImageIOSurface },
diff --git a/userland/src/metal_test.m b/userland/src/metal_test.m
index cfb9910..e55b745 100644
--- a/userland/src/metal_test.m
+++ b/userland/src/metal_test.m
@@ -38,11 +38,14 @@
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
#import <Metal/Metal.h>
+#import <OpenGLES/EAGL.h>
#import <objc/message.h>
#import <objc/runtime.h>
+#import <dlfcn.h>
#import <signal.h>
#import <stdio.h>
#import <stdlib.h>
+#import <spawn.h>
#import <sys/wait.h>
#import <time.h>
#import <unistd.h>
@@ -52,27 +55,82 @@ extern CFTypeRef MGCopyAnswer(CFStringRef key);
#define EXTENSIONS "/System/Library/Extensions"
/*
- * Two of the things asked below can take the process down with them, and did: asking CoreImage for
- * its default context killed metal_test outright on this system (nothing printed, no crash report),
- * and taking a plug-in bundle's principal class runs Apple's own driver code. Each is therefore run
- * in a child of its own: whatever happens to the child, the parent says how it ended and goes on.
- * A child that wedges instead of dying is given `secs` and then killed, which is itself an answer.
+ * Where a crash happened, in the addresses of the dyld shared cache as ipsw prints them.
+ *
+ * The cache is loaded at a sliding address, so a program counter means nothing by itself. The slide
+ * is worked out from one symbol whose unslid address is known from the cache
+ * (MTLCreateSystemDefaultDevice, 0x181a34b3c in 20F66 for iPhone10,3): slide = where it is now
+ * minus where the cache says it is. Subtracting that from a program counter gives an address
+ * `ipsw dyld a2s <cache> <address>` can name. The same trick is what src/inject.c does in reverse.
+ */
+#define MTL_CREATE_DEVICE_UNSLID 0x181a34b3cUL
+
+static uintptr_t
+cache_slide(void)
+{
+ return (uintptr_t)&MTLCreateSystemDefaultDevice - MTL_CREATE_DEVICE_UNSLID;
+}
+
+static void
+fault(int sig, siginfo_t *info, void *uap)
+{
+ ucontext_t *uc = uap;
+ uintptr_t slide = cache_slide();
+ uintptr_t pc = 0, lr = 0, fp = 0;
+
+ if (uc != NULL && uc->uc_mcontext != NULL) {
+ pc = (uintptr_t)uc->uc_mcontext->__ss.__pc;
+ lr = (uintptr_t)uc->uc_mcontext->__ss.__lr;
+ fp = (uintptr_t)uc->uc_mcontext->__ss.__fp;
+ }
+ /* async-signal-safe enough for a diagnostic that is about to exit anyway */
+ printf("metal_test: signal %d at address %p\n", sig, info != NULL ? info->si_addr : NULL);
+ printf("metal_test: pc %#lx unslid (cache slide %#lx)\n", pc - slide, slide);
+ printf("metal_test: lr %#lx unslid\n", lr - slide);
+ for (int i = 0; i < 8 && fp > 0x1000; i++) {
+ uintptr_t next = ((uintptr_t *)fp)[0], ret = ((uintptr_t *)fp)[1];
+
+ if (ret == 0) {
+ break;
+ }
+ printf("metal_test: #%d %#lx unslid\n", i, ret - slide);
+ if (next <= fp) {
+ break;
+ }
+ fp = next;
+ }
+ _exit(99);
+}
+
+/*
+ * Some of what is asked below can take the process down with it, so each such question is asked by
+ * a fresh process: metal_test re-executes itself with the question as its argument (see main()).
+ *
+ * It must be a new process and not just a forked one. A forked child may not use Objective-C at
+ * all when the parent had more than one thread, and metal_test does -- linking CoreImage and
+ * OpenGLES is enough. A first attempt did fork, and every probe then died of SIGABRT inside the
+ * runtime itself:
+ *
+ * objc[98]: +[__NSCFNumber initialize] may have been in progress in another thread when fork()
+ * was called. We cannot safely call it or ignore it in the fork() child process. Crashing
+ * instead.
+ *
+ * -- objc_initializeAfterForkError, which says nothing whatever about CoreImage. exec() clears
+ * that, because the runtime starts afresh.
*/
static void
-in_a_child(const char *what, int secs, void (*body)(void))
+in_a_new_process(const char *what, const char *argument, int secs)
{
- pid_t pid = fork();
+ extern char **environ;
+ char *const argv[] = { (char *)"/redwood/bin/metal_test", (char *)argument, NULL };
+ pid_t pid;
int status = 0, waited = 0;
- if (pid < 0) {
- printf("metal_test: cannot fork to ask about %s\n", what);
+ printf("metal_test: %s (asked by a process of its own)\n", what);
+ if (posix_spawn(&pid, argv[0], NULL, NULL, argv, environ) != 0) {
+ printf("metal_test: cannot start %s %s\n", argv[0], argument);
return;
}
- if (pid == 0) {
- body();
- _exit(0);
- }
- /* waitpid without hanging for ever: a wedged child is news too */
while (waitpid(pid, &status, WNOHANG) == 0) {
struct timespec ts = { .tv_sec = 0, .tv_nsec = 100 * 1000 * 1000 };
@@ -85,7 +143,9 @@ in_a_child(const char *what, int secs, void (*body)(void))
}
}
if (WIFSIGNALED(status)) {
- printf("metal_test: %s: the process died of signal %d right there\n", what, WTERMSIG(status));
+ printf("metal_test: %s: died of signal %d\n", what, WTERMSIG(status));
+ } else if (WEXITSTATUS(status) == 99) {
+ printf("metal_test: %s: it faulted, and said above where\n", what);
} else if (WEXITSTATUS(status) != 0) {
printf("metal_test: %s: ended with status %d\n", what, WEXITSTATUS(status));
}
@@ -283,6 +343,69 @@ gestalt(void)
*/
/* `options` is nil for the default context, or a dictionary to ask for something else. */
static NSDictionary *coreimage_options;
+/* ... or the context is made over an EAGLContext of ours instead (coreimage_eagl). */
+static int coreimage_over_eagl;
+
+/*
+ * The way back for CoreImage, if there is one. iOS 16.5's CoreImage carries a whole second back
+ * end on OpenGL ES -- CI::GLContext, CI::GLMainProgram, CI::GLTextureManager beside the
+ * CI::MetalContext family -- it is linked against OpenGLES, it compiles its shaders as GLSL (not
+ * AIR), and CIGLIsUsable() is compiled to "return 1". The public way in is
+ * +[CIContext contextWithEAGLContext:], and the one thing it wants of the library underneath,
+ * CIEAGLContextTexImageIOSurface, is a call src/eagl.c already answers for CoreAnimation. So: make
+ * an EAGLContext (which on an image built with GL=1, on a phone with gpu=1, is our Mesa behind
+ * src/eagl.c) and hand it over.
+ */
+#define REDWOOD_GL "/redwood/lib/libredwood-gl.dylib"
+
+static EAGLContext *
+make_eagl(void)
+{
+ EAGLContext *gl;
+
+ /*
+ * Our OpenGL ES has to be put behind EAGLContext in THIS process first. libredwood.dylib does
+ * it only for backboardd (src/inject.c, opengl_es(), which is called for that name alone), and
+ * the way it does it -- replacing methods of EAGLContext through the ObjC runtime -- is local
+ * to a process. The library installs itself from a constructor, so loading it is enough; what
+ * it replaced it says itself in lines "redwood-gl:". Without this, EAGLContext here would be
+ * iOS's own, which is AppleMetalGLRenderer over Metal -- the thing that is missing.
+ */
+ if (access(REDWOOD_GL, R_OK) != 0) {
+ printf("metal_test: %s is not in this image: build it with GL=1\n", REDWOOD_GL);
+ return nil;
+ }
+ /*
+ * coreimage_over_eagl == 2: Mesa's software driver instead of the phone's GPU. Worth asking
+ * separately, because the window server already holds the GPU while this runs: if freedreno
+ * cannot have it too, softpipe still answers the question that matters -- whether CoreImage's
+ * OpenGL ES back end works at all behind an EAGLContext of ours.
+ */
+ if (coreimage_over_eagl == 2) {
+ setenv("OSMESA_SOFTWARE", "1", 1);
+ printf("metal_test: OSMESA_SOFTWARE=1: Mesa's software driver, not the GPU\n");
+ }
+ if (dlopen(REDWOOD_GL, RTLD_NOW) == NULL) {
+ printf("metal_test: %s: %s\n", REDWOOD_GL, dlerror());
+ return nil;
+ }
+ printf("metal_test: %s loaded; EAGLContext is ours now\n", REDWOOD_GL);
+ gl = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
+
+ if (gl == nil) {
+ printf("metal_test: no OpenGL ES 3 context; trying 2\n");
+ gl = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
+ }
+ if (gl == nil) {
+ printf("metal_test: no EAGLContext at all: this image has no OpenGL ES\n");
+ return nil;
+ }
+ printf("metal_test: EAGLContext: %s, API %d\n", class_getName([gl class]), (int)[gl API]);
+ if (![EAGLContext setCurrentContext:gl]) {
+ printf("metal_test: the EAGLContext would not become current\n");
+ }
+ return gl;
+}
static void
coreimage(void)
@@ -298,9 +421,18 @@ coreimage(void)
CGContextRef bitmap;
/* said before the call, not after: this is the call that was dying */
- printf("metal_test: asking for a CIContext (%s)...\n",
- coreimage_options == nil ? "the default one" : "software renderer");
- context = [CIContext contextWithOptions:coreimage_options];
+ printf("metal_test: asking for a CIContext (%s)...\n", coreimage_over_eagl ? "over an EAGLContext"
+ : coreimage_options == nil ? "the default one" : "software renderer");
+ if (coreimage_over_eagl) {
+ EAGLContext *gl = make_eagl();
+
+ if (gl == nil) {
+ return;
+ }
+ context = [CIContext contextWithEAGLContext:gl];
+ } else {
+ context = [CIContext contextWithOptions:coreimage_options];
+ }
if (context == nil) {
printf("metal_test: no CIContext: CoreImage cannot work here\n");
return;
@@ -370,10 +502,43 @@ coreimage(void)
}
int
-main(void)
+main(int argc, char **argv)
{
+ struct sigaction sa = { 0 };
+
/* every line as it happens: a call that kills the process must not take the log with it */
setvbuf(stdout, NULL, _IONBF, 0);
+ /* and where it died, since the kernel's report never arrives here (see fault()) */
+ sa.sa_sigaction = fault;
+ sa.sa_flags = SA_SIGINFO;
+ sigaction(SIGSEGV, &sa, NULL);
+ sigaction(SIGBUS, &sa, NULL);
+ sigaction(SIGILL, &sa, NULL);
+ sigaction(SIGABRT, &sa, NULL);
+ sigaction(SIGTRAP, &sa, NULL);
+
+ /* one question, asked by a process of its own (see in_a_new_process) */
+ if (argc > 1) {
+ if (strcmp(argv[1], "ci-default") == 0) {
+ coreimage();
+ } else if (strcmp(argv[1], "ci-software") == 0) {
+ coreimage_options = @{ @"kCIContextUseSoftwareRenderer": @YES };
+ coreimage();
+ } else if (strcmp(argv[1], "ci-eagl") == 0) {
+ coreimage_over_eagl = 1;
+ coreimage();
+ } else if (strcmp(argv[1], "ci-eagl-software") == 0) {
+ coreimage_over_eagl = 2;
+ coreimage();
+ } else if (strcmp(argv[1], "plugins") == 0) {
+ plugins();
+ } else {
+ printf("metal_test: no such question: %s\n", argv[1]);
+ return 2;
+ }
+ return 0;
+ }
+
printf("metal_test: the services Metal looks for (IOAcceleratorES)\n");
accelerators();
printf("metal_test: what the registry has that is a GPU\n");
@@ -383,15 +548,21 @@ main(void)
printf("metal_test: what iOS publishes about graphics (artwork, not rendering)\n");
gestalt();
printf("metal_test: CoreImage, which has a path without Metal\n");
- in_a_child("the default CIContext", 30, coreimage);
- coreimage_options = @{ @"kCIContextUseSoftwareRenderer": @YES };
- in_a_child("a software-renderer CIContext", 30, coreimage);
+ /*
+ * The ones that matter go first: a session can run out before the end, and these are the
+ * answer everything else is waiting for. The default context is known to crash in
+ * CI::GLContext::init() with no GL context to work with (see docs/metal.md), so the question
+ * is whether giving it one -- ours, Mesa behind src/eagl.c -- is enough.
+ */
+ in_a_new_process("a CIContext over an EAGLContext (the GPU)", "ci-eagl", 120);
+ in_a_new_process("a CIContext over an EAGLContext (software Mesa)", "ci-eagl-software", 180);
+ in_a_new_process("the default CIContext", "ci-default", 60);
+ in_a_new_process("a software-renderer CIContext", "ci-software", 60);
/*
* Last on purpose: taking a bundle's principal class loads that bundle's code and runs its
* initialisers -- for AGXMetalA11.bundle, Apple's own driver for the A11's GPU, which this
* image does carry.
*/
- printf("metal_test: the plug-in bundles of %s (loads their code: kept last)\n", EXTENSIONS);
- in_a_child("loading the plug-in bundles", 60, plugins);
+ in_a_new_process("loading the plug-in bundles of " EXTENSIONS, "plugins", 90);
return 0;
}