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

Metal, step two: buffers that hold memory, libraries read from a .metallib, functions with their AIR

shimoku90c937dd3291
diff --git a/configs/redwood.config b/devices/redwood/configs/redwood.config
similarity index 100%
rename from configs/redwood.config
rename to devices/redwood/configs/redwood.config
diff --git a/configs/redwood_defconfig b/devices/redwood/configs/redwood_defconfig
similarity index 100%
rename from configs/redwood_defconfig
rename to devices/redwood/configs/redwood_defconfig
diff --git a/devices/redwood/uefi/BASE b/devices/redwood/uefi/BASE
deleted file mode 100644
index eacc726..0000000
--- a/devices/redwood/uefi/BASE
+++ /dev/null
@@ -1 +0,0 @@
-e51cd877e31c8fbb322032dc4cb6715e83d25ad3
diff --git a/devices/redwood/uefi/mu-silicium.patch b/devices/redwood/uefi/mu-silicium.patch
deleted file mode 100644
index f2a117e..0000000
--- a/devices/redwood/uefi/mu-silicium.patch
+++ /dev/null
@@ -1,633 +0,0 @@
-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/docs/metal-plan.md b/docs/metal-plan.md
index 2c57764..055d310 100644
--- a/docs/metal-plan.md
+++ b/docs/metal-plan.md
@@ -8,7 +8,7 @@ shader compiler) first. This file is the order of work, with how each step is ch
| Part | What it is | State |
|---|---|---|
| **A. The shader compiler** | Apple's shader bitcode (AIR, in a `.metallib`) into Mesa's NIR, so that ir3 (the compiler behind the OpenGL ES that already runs) makes Adreno code | largely done: 321 of the system's 456 shader modules reach ir3, 54 have run on the phone's GPU (`docs/air.md`, `docs/air-report.md`) |
-| **B. The device** | what Metal loads: a bundle with a subclass of Metal's private `_MTLDevice`, and the objects it hands out (buffers, libraries, pipeline states, queues, command buffers, encoders: 53 classes and about 1200 methods in Apple's own) | step 1 is written (below); nothing past it |
+| **B. The device** | what Metal loads: a bundle with a subclass of Metal's private `_MTLDevice`, and the objects it hands out (buffers, libraries, pipeline states, queues, command buffers, encoders: 53 classes and about 1200 methods in Apple's own) | step 1 ran in QEMU; buffers and libraries (step two, below) are written and checked on a Mac |
| **C. The kernel side** | submitting work to the GPU for a Metal client, with memory and fences | the GPU already has a user client for Mesa (`drivers/gpu/hakios.gpu.cpp`, `HakiosGPUUserClient`); it is not connected to B |
What "real Metal" would be, and why games are out of reach, is argued in `docs/ru/metal.md` section 9.4: that has not
@@ -78,6 +78,66 @@ Run in a loop of rebuild-image, boot, read the log; each pass gave the next requ
So the road from here is the library (step 4 of the order below: `newLibraryWithURL:` / `…Data:` through the AIR compiler), then
buffers and textures with real memory, and the command encoders; none of that can be tried without the GPU.
+## Step two: buffers, libraries, functions (27 October 2026)
+
+What the plug-in now makes, in `userland/src/HakiosMetal.m`:
+
+- **Buffers**: `-newBufferWithLength:options:`, `-newBufferWithBytes:length:options:`, `-newBufferWithBytesNoCopy:length:options:deallocator:`
+ give a `HakiosMetalBuffer` (a subclass of `_MTLResource`, declaring `MTLBuffer`, `MTLResource` and their SPI protocols) over
+ memory of the process: zeroed pages, the caller's own for `...NoCopy` (its deallocator called when the buffer goes). `-contents`,
+ `-length`, the storage, cache and hazard modes of its options, `-allocatedSize`, a label. `-gpuAddress` is 0: the GPU's own
+ buffers (`hakios.gpu.cpp`, `kMsmGemNew`, mapped into the GPU's address space) come with the GPU, and since the Adreno shares
+ the system's memory, a shared-storage buffer's bytes can stay where they are when they do.
+- **Libraries**: `-newLibraryWithURL:error:`, `...WithFile:`, `...WithData:`, `-newDefaultLibrary` and `...WithBundle:` read the
+ `.metallib` with `userland/src/hakios_metallib.c` (the reading of `tools/metallib.py` in C, every offset checked; the file is
+ the program's to give), and give a `HakiosMetalLibrary` (on `_MTLLibrary`) with `-functionNames`. A file that is not a metallib
+ is an `MTLLibraryErrorDomain` error that says why.
+- **Functions**: `-newFunctionWithName:` gives a `HakiosMetalFunction` (on `_MTLFunction`) with its name, its `MTLFunctionType`
+ from the container's TYPE tag, and `-hakiosBitcode`, its AIR module unwrapped: what the shader compiler (part A) takes.
+ Function constants are accepted and said not to be applied.
+
+How it was checked, and what that does not show:
+
+- `tools/metallib-test.sh DIR`: the C reading and `tools/metallib.py` agree on every function of every `.metallib` of the iOS 16.5
+ system (the five MTLB files; the five runtime libraries of `AGXMetalA11.bundle` are another format, and both refuse them) and of
+ macOS's; a file made by the test and then cut short at every length, and with each offset and length bent outside it, is refused
+ every time, under the address and undefined-behaviour sanitizers. One correction came out of it: the header's second word at
+ 0x20 is the function list's length after its count, not its end (`tools/metallib.py` calls it `funcs_end` and does not use it).
+- `tools/metal-plugin-test.sh DIR`: the plug-in built for macOS, its device made the way Metal makes it, on the Mac's own
+ `_MTLDevice`, `_MTLResource`, `_MTLLibrary`, `_MTLFunction`: buffers written, read back, copied, refused over `maxBufferLength`,
+ freed (and the caller's deallocator called); the five iOS libraries read (36, 135, 11, 274 and 0 functions; the last is
+ SafariSharedUI's, a header and nothing else), every function made by its name with its type, every module LLVM bitcode. All
+ under the address sanitizer. **macOS's Metal is not iOS 16.5's**: this shows the plug-in's own logic, not that iOS's Metal is
+ content with these objects.
+- Built for iOS 16.5 (`-Wall -Wextra`, no warnings). Not yet run on iOS: `metal_test` asks "what the device makes" in a process of
+ its own (`RC_JOBS=rc.jobs.metal`, `metal=1`), and its line is the result that goes here.
+
+Still nothing is drawn or computed: a pipeline made of these functions is the empty stand-in of step one. The next step is the
+compiler behind `-newComputePipelineStateWithFunction:error:` (part A: the function's bitcode through NIR to ir3), and then the
+command buffer and compute encoder on the GPU's buffers (part C), which need the phone.
+
+## What UniXNU's AdrenoMetal showed, and what was taken
+
+[UniXNU](https://github.com/UniXNU) runs iPadOS 17 on a Xiaomi Pad 6S Pro (SM8550, Adreno 740), and its
+[AdrenoMetal](https://github.com/UniXNU/AdrenoMetal) (MIT) composes the system UI on the GPU. Read on 27 October 2026; no code of
+it is in this repository, the facts below are written here in our own words and code, with the source named where it is used.
+
+- **Their route is Metal on Vulkan**: the plug-in's device is a subclass of `_MTLDevice` (as ours), and every Metal object is
+ translated by a runtime of theirs ("metal2vulkan", `bridge/NativeMetalObjects.rs`) onto Turnip, Mesa's Vulkan driver for Adreno,
+ over the kernel's GPU interface. Ours is AIR through NIR to ir3 directly (part A), on the same Mesa. Turnip supports the A6xx
+ generation our Adreno 642L belongs to, so their route is open to this port as well; which of the two is less work from here is
+ the question of the next step, and it is not decided here.
+- **Universal metallibs.** Newer systems ship framework libraries as a fat container (0xCAFEBABE) of an AIR64 slice and a binary
+ for Apple's GPUs (QuartzCore's `default.metallib` on iPadOS 17). `hakios_metallib_thin()` takes the AIR64 slice, as Metal does;
+ `tools/metallib-test.sh` and `tools/metal-plugin-test.sh` check it. iOS 16.5's libraries are all thin.
+- **CoreImage's limits.** `CIMetalDeviceGetLimits` reads `dedicatedMemorySize` and `sharedMemorySize`, which `_MTLDevice` does
+ not answer; without them every `CIContext` throws (iconservicesagent ended over symbol glyphs there). The device now answers
+ them, `isLowPower`, `isRemovable`, `isHeadless`, and `supportsFeatureSet:` (NO: the base reads Apple's tables).
+- **Clients by a file.** A file beside the bundle names the processes shown the device. `HakiosMetal.clients` does the same here,
+ on top of `metal=N`.
+- **The window server needs QuartzCore's own `default.metallib`.** Their system image has it; iOS 16.5's (this port's) does not,
+ which is the wall of step 7 above. It is not something the plug-in can supply: the library is Apple's.
+
## Frame skips
A dropped frame is not a Metal problem, and Metal would not cure it: the screen of this port is drawn today by
diff --git a/drivers/audio/hakios.guard.c b/drivers/audio/hakios.guard.c
new file mode 100644
index 0000000..955be01
--- /dev/null
+++ b/drivers/audio/hakios.guard.c
@@ -0,0 +1,318 @@
+/*
+ * The speakers' guard: what the samples go through on their way to the phone's two amplifiers
+ * (drivers/audio/hakios.sound.c's feeder), in place of the protection Android has in the audio DSP.
+ *
+ * Under Android the DSP runs Awinic's algorithm (SKTune, "aw882xx_rx_switch") with each
+ * speaker's calibration: it keeps the cone's excursion and the voice coil's temperature in
+ * bounds, measuring both through the amplifiers' current and voltage feedback. None of that runs
+ * here, and nothing here knows the speakers' parameters (Android's files that can be read have
+ * none: the amplifiers' register profile, the battery tables of its "monitor", and in the device
+ * tree a range of 4 to 9 ohms for the calibrated resistance). So the guard holds what reaches the
+ * speakers to levels that are safe for small phone speakers whatever they are exactly, measured
+ * the only way there is without feedback -- from the samples and the amplifiers' level -- and
+ * kept well under what the speakers can take at Android's level:
+ *
+ * high-pass a second-order Butterworth filter at 200 Hz: a phone's speaker gives out next to
+ * nothing below its resonance (several hundred Hz), and what it is given there only
+ * moves the cone further and heats the coil
+ * power the power that would reach a speaker, averaged three ways -- over 0.2 s (the
+ * cone and coil at once), 3 s (the voice coil's warming) and 60 s (the magnet and
+ * the frame) -- and the level turned down so that none of the three averages goes
+ * over its limit: 3, 6 and 9 dB under the power of a full-scale sine at Android's
+ * level. Sound of ordinary loudness never comes near them; a sustained full-scale
+ * tone is turned down at once to the first, after seconds to the second and over a
+ * minute to the third, and the level comes back up as the averages fall, as a
+ * speaker cools. The averages go on falling while the amplifiers are off.
+ * peaks no sample above 3 dB under full scale at Android's level: a limiter that turns
+ * the level down at the sample that would go over (so none does) and lets it come
+ * back with a time constant of 43 ms
+ * monitor a further reduction that the amplifiers' watch asks for (hakios.speaker.c:
+ * Android's table for a cold amplifier, and a low battery)
+ *
+ * Before all that, a gain (sound_gain, at most 12 dB): iOS's own processing for the iPhone X's
+ * speaker keeps even a full-scale tone at its top volume 12.6 to 14.3 dB under full scale, so
+ * without it iOS at the top would stay that much under Android at the top. What it lifts over
+ * full scale is held to full scale by the peak limiter (or to its lower limit), never clipped.
+ *
+ * All the limits are in terms of the speakers: a signal at full scale with the amplifiers at
+ * Android's level (the loudest they are ever set to) is 0 dB. With the amplifiers turned down
+ * (sound_below) the same samples are that much quieter at the speakers, and the guard holds them
+ * back only that much later. Everything is integer arithmetic (the kernel's threads do no
+ * floating point); fractions are in Q30 unless said otherwise.
+ *
+ * One caller at a time (the feeder); hakios_guard_attenuation() and hakios_guard_monitor() may
+ * be called from another thread.
+ */
+#include <stdbool.h>
+#include <stdint.h>
+#include <sys/hakios.audio.h>
+
+#define ONE (1ll << 30)
+#define FULL_SCALE 32768
+
+/* The limits, in eighths of a dB under full scale at Android's level (powers: under a full-scale square wave's) */
+#define PEAK_LIMIT (3 * 8)
+#define RMS_LIMIT (6 * 8) /* a full-scale sine is 3 dB under a square wave: these are 3, 6, 9 dB under it */
+#define FAST_LIMIT (9 * 8)
+#define SLOW_LIMIT (12 * 8)
+/* ... and the averages' time constants, in frames (48 kHz) */
+#define RMS_FRAMES 9600 /* 0.2 s */
+#define FAST_FRAMES 144000 /* 3 s */
+#define SLOW_FRAMES 2880000 /* 60 s */
+#define RELEASE_SHIFT 11 /* the peak limiter lets go with a time constant of 2048 frames, 43 ms */
+#define MAX_FRAMES 1024 /* the most frames processed at once (the feeder's period: 960) */
+
+/* 10^(-n/160), n = 0..47, in Q30: an attenuation of n eighths of a dB, as a factor of amplitude */
+static const uint32_t eighths[48] = {
+ 1073741824, 1058400094, 1043277569, 1028371116, 1013677647, 999194121, 984917536, 970844937, 956973408, 943300077,
+ 929822112, 916536722, 903441154, 890532697, 877808678, 865266461, 852903448, 840717079, 828704830, 816864213,
+ 805192776, 793688102, 782347808, 771169545, 760150998, 749289885, 738583957, 728030996, 717628817, 707375265,
+ 697268218, 687305580, 677485290, 667805313, 658263644, 648858308, 639587356, 630448869, 621440953, 612561743,
+ 603809400, 595182112, 586678091, 578295576, 570032831, 561888146, 553859832, 545946228,
+};
+#define SIX_DB 538145694 /* 10^(-6/20) in Q30 */
+
+/* the high-pass filter, 200 Hz at 48 kHz, Q = 1/sqrt(2): b0, b1, b2, a1, a2 in Q30 (RBJ's cookbook) */
+static const int64_t hpf_b0 = 1054047540, hpf_b1 = -2108095079, hpf_b2 = 1054047540;
+static const int64_t hpf_a1 = -2107733822, hpf_a2 = 1034714513;
+
+static struct {
+ bool hpf;
+ uint64_t gain; /* the gain before everything, Q30 (1 to 4) */
+ volatile uint32_t attenuation; /* the amplifiers' level under Android's, eighths of a dB; HAKIOS_GUARD_SILENT: off */
+ volatile uint32_t monitor; /* the monitor's reduction, eighths of a dB */
+ int64_t x1[2], x2[2], y1[2], y2[2]; /* the filter's past, in 1/256 of a sample */
+ uint64_t rms[2], fast[2], slow[2]; /* average powers at each speaker, Q30 of a full-scale square wave at Android's level */
+ uint64_t level; /* the power guard's and the monitor's gain at the end of the last block */
+ uint64_t envelope; /* the peak limiter's, 1/65536 of a sample */
+ struct hakios_guard_report report;
+} guard = { .hpf = true, .attenuation = HAKIOS_GUARD_SILENT, .gain = ONE, .level = ONE, .report = { .least_gain = ONE, .least_peak_gain = 65536 } };
+
+static int32_t work[2 * MAX_FRAMES];
+
+/* 10^(-n/160) in Q30: n eighths of a dB under, as a factor of amplitude */
+static uint64_t
+amplitude(uint32_t n)
+{
+ uint64_t value = eighths[n % 48];
+
+ for (uint32_t i = 0; i < n / 48 && value != 0; i++) {
+ value = value * SIX_DB >> 30;
+ }
+ return value;
+}
+
+static uint64_t
+isqrt(uint64_t value)
+{
+ uint64_t root = 0, bit = 1ull << 62;
+
+ while (bit > value) {
+ bit >>= 2;
+ }
+ while (bit != 0) {
+ if (value >= root + bit) {
+ value -= root + bit;
+ root = (root >> 1) + bit;
+ } else {
+ root >>= 1;
+ }
+ bit >>= 2;
+ }
+ return root;
+}
+
+/* how much of `limit' a power is, as the square of the gain that would bring it down to it (Q30, at most 1) */
+static uint64_t
+headroom(uint64_t power, uint64_t limit)
+{
+ if (power <= limit) {
+ return ONE;
+ }
+ return (limit << 30) / power;
+}
+
+void
+hakios_guard_configure(bool hpf, uint32_t gain)
+{
+ guard.hpf = hpf;
+ /* 10^(gain/160): one over the attenuation by as much */
+ guard.gain = (1ull << 60) / amplitude(gain > HAKIOS_GUARD_MAX_GAIN ? HAKIOS_GUARD_MAX_GAIN : gain);
+}
+
+void
+hakios_guard_attenuation(uint32_t below)
+{
+ guard.attenuation = below;
+}
+
+void
+hakios_guard_monitor(uint32_t below)
+{
+ guard.monitor = below;
+}
+
+static void
+block(int16_t *frames, uint32_t count)
+{
+ uint32_t attenuation = guard.attenuation;
+ struct hakios_guard_report *r = &guard.report;
+ /* (2 * attenuation is kept from wrapping in 32 bits: a wrapped value says nothing about the level, and for some it is
+ a huge one, which makes the power limits see no power at all while the amplifiers are not turned down) */
+ uint64_t to_speaker = attenuation == HAKIOS_GUARD_SILENT ? 0 :
+ amplitude(attenuation > HAKIOS_GUARD_SILENT / 2 ? HAKIOS_GUARD_SILENT - 1 : 2 * attenuation);
+ uint64_t sum[2] = { 0, 0 }, g2 = ONE, g, start = guard.level, ceiling;
+ uint32_t binding = 0;
+
+ /* the high-pass filter, and what comes out of it: its power, per channel */
+ for (uint32_t i = 0; i < 2 * count; i++) {
+ unsigned c = i & 1;
+ int64_t x = (int64_t)frames[i] * (int64_t)guard.gain >> 22, y; /* (the gain, and 1/256 of a sample) */
+ uint32_t level = frames[i] < 0 ? (uint32_t)-frames[i] : (uint32_t)frames[i];
+
+ if (level > r->peak_in) {
+ r->peak_in = level;
+ }
+ if (guard.hpf) {
+ y = (hpf_b0 * x + hpf_b1 * guard.x1[c] + hpf_b2 * guard.x2[c] - hpf_a1 * guard.y1[c] - hpf_a2 * guard.y2[c]) >> 30;
+ guard.x2[c] = guard.x1[c];
+ guard.x1[c] = x;
+ guard.y2[c] = guard.y1[c];
+ guard.y1[c] = y;
+ } else {
+ y = x;
+ }
+ work[i] = (int32_t)((y + 128) >> 8);
+ sum[c] += (uint64_t)((int64_t)work[i] * work[i]);
+ }
+
+ /* the averages at the speakers, and the gain that keeps all three under their limits */
+ for (unsigned c = 0; c < 2; c++) {
+ /* the block's power, Q30 of full scale (a square wave at 32768), then as it reaches the speaker */
+ uint64_t power = (uint64_t)((unsigned __int128)(sum[c] / count) * to_speaker >> 30), h;
+
+ guard.rms[c] = (uint64_t)((int64_t)guard.rms[c] + ((int64_t)power - (int64_t)guard.rms[c]) * count / RMS_FRAMES);
+ guard.fast[c] = (uint64_t)((int64_t)guard.fast[c] + ((int64_t)power - (int64_t)guard.fast[c]) * count / FAST_FRAMES);
+ guard.slow[c] = (uint64_t)((int64_t)guard.slow[c] + ((int64_t)power - (int64_t)guard.slow[c]) * count / SLOW_FRAMES);
+ if ((h = headroom(guard.rms[c], amplitude(2 * RMS_LIMIT))) < g2) {
+ g2 = h;
+ binding = 1;
+ }
+ if ((h = headroom(guard.fast[c], amplitude(2 * FAST_LIMIT))) < g2) {
+ g2 = h;
+ binding = 2;
+ }
+ if ((h = headroom(guard.slow[c], amplitude(2 * SLOW_LIMIT))) < g2) {
+ g2 = h;
+ binding = 3;
+ }
+ }
+ g = isqrt(g2 << 30) * amplitude(guard.monitor) >> 30;
+ if (g > ONE) {
+ g = ONE;
+ }
+ r->blocks++;
+ if (binding == 1) {
+ r->rms_blocks++;
+ } else if (binding == 2) {
+ r->fast_blocks++;
+ } else if (binding == 3) {
+ r->slow_blocks++;
+ }
+ if (g < r->least_gain) {
+ r->least_gain = g;
+ }
+
+ /* the peaks: no sample over the limit at the speaker (and none over full scale) */
+ ceiling = FULL_SCALE - 1;
+ if (attenuation != HAKIOS_GUARD_SILENT && attenuation < PEAK_LIMIT) {
+ ceiling = (uint64_t)FULL_SCALE * amplitude(PEAK_LIMIT - attenuation) >> 30;
+ }
+ for (uint32_t f = 0; f < count; f++) {
+ /* (the power guard's gain moves from the last block's to this one's across the block) */
+ uint64_t gain = (uint64_t)((int64_t)start + ((int64_t)g - (int64_t)start) * (int64_t)(f + 1) / (int64_t)count);
+ int64_t y[2];
+ uint64_t level, peak_gain = 65536;
+
+ for (unsigned c = 0; c < 2; c++) {
+ y[c] = (int64_t)work[2 * f + c] * (int64_t)gain >> 30;
+ }
+ level = (uint64_t)(y[0] < 0 ? -y[0] : y[0]);
+ if ((uint64_t)(y[1] < 0 ? -y[1] : y[1]) > level) {
+ level = (uint64_t)(y[1] < 0 ? -y[1] : y[1]);
+ }
+ guard.envelope -= guard.envelope >> RELEASE_SHIFT;
+ if (level << 16 > guard.envelope) {
+ guard.envelope = level << 16;
+ }
+ if (guard.envelope > ceiling << 16) {
+ peak_gain = (ceiling << 32) / guard.envelope;
+ r->limited_frames++;
+ if (peak_gain < r->least_peak_gain) {
+ r->least_peak_gain = (uint32_t)peak_gain;
+ }
+ }
+ for (unsigned c = 0; c < 2; c++) {
+ int64_t out = y[c] * (int64_t)peak_gain >> 16;
+ uint32_t magnitude;
+
+ out = out > FULL_SCALE - 1 ? FULL_SCALE - 1 : out < -FULL_SCALE ? -FULL_SCALE : out;
+ frames[2 * f + c] = (int16_t)out;
+ magnitude = (uint32_t)(out < 0 ? -out : out);
+ if (magnitude > r->peak_out) {
+ r->peak_out = magnitude;
+ }
+ }
+ }
+ guard.level = g;
+ r->gain = g;
+ r->rms = guard.rms[0] > guard.rms[1] ? guard.rms[0] : guard.rms[1];
+ r->fast = guard.fast[0] > guard.fast[1] ? guard.fast[0] : guard.fast[1];
+ r->slow = guard.slow[0] > guard.slow[1] ? guard.slow[0] : guard.slow[1];
+}
+
+void
+hakios_guard_process(int16_t *frames, uint32_t count)
+{
+ while (count > 0) {
+ uint32_t n = count < MAX_FRAMES ? count : MAX_FRAMES;
+
+ block(frames, n);
+ frames += 2 * n;
+ count -= n;
+ }
+}
+
+/* What has happened since the last call (and the averages and the gain as they are now). */
+void
+hakios_guard_take_report(struct hakios_guard_report *report)
+{
+ *report = guard.report;
+ guard.report = (struct hakios_guard_report){ .least_gain = ONE, .least_peak_gain = 65536 };
+}
+
+/* 10 log10 of a Q30 ratio, in tenths of a dB (for what is said) */
+int
+hakios_guard_decibels(uint64_t ratio)
+{
+ static const uint16_t fraction[17] = {
+ 0, 5732, 11136, 16248, 21098, 25711, 30109, 34312, 38336, 42196, 45904, 49472, 52911, 56229, 59434, 62534, 65535,
+ };
+ int64_t log2; /* Q16 */
+ unsigned top = 63;
+
+ if (ratio == 0) {
+ return -999;
+ }
+ while (!(ratio >> top)) {
+ top--;
+ }
+ {
+ /* the 4 bits under the top one choose a segment, the next 12 where in it */
+ uint64_t mantissa = top >= 16 ? ratio >> (top - 16) : ratio << (16 - top);
+ unsigned index = (unsigned)(mantissa >> 12) & 15, within = (unsigned)mantissa & 4095;
+
+ log2 = ((int64_t)top - 30) * 65536 + fraction[index] + (int64_t)(fraction[index + 1] - fraction[index]) * within / 4096;
+ }
+ return (int)(log2 * 30103 / 65536 / 1000);
+}
diff --git a/configs/sc7280.config b/socs/sc7280/configs/sc7280.config
similarity index 100%
rename from configs/sc7280.config
rename to socs/sc7280/configs/sc7280.config
diff --git a/tools/metal-plugin-test.sh b/tools/metal-plugin-test.sh
new file mode 100755
index 0000000..0f53e5c
--- /dev/null
+++ b/tools/metal-plugin-test.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# The Metal plug-in's objects on this Mac (tools/metal_plugin_test.m says what that does and does not show), under the address
+# sanitizer, with every .metallib under DIR read as a library (an extracted system: sysimage/rootfs). macOS only.
+# usage: tools/metal-plugin-test.sh [DIR]
+set -e
+cd "$(dirname "$0")/.."
+[ "$(uname)" = Darwin ] || { echo "metal-plugin-test: needs macOS (its Metal stands in for iOS's)"; exit 0; }
+tmp=$(mktemp -d)
+trap 'rm -rf "$tmp"' EXIT
+clang -O1 -g -fsanitize=address -Wall -Wno-unused-parameter -Iuserland/src -framework Foundation -framework Metal -lobjc \
+ tools/metal_plugin_test.m userland/src/HakiosMetal.m userland/src/hakios_metallib.c -o "$tmp/metal_test"
+files=
+if [ -n "$1" ]; then
+ # the MTLB ones (the GPU driver's own runtime libraries are another format: tools/metallib-test.sh)
+ for f in $(find "$1" -name '*.metallib' -type f); do
+ if python3 tools/metallib.py list "$f" >/dev/null 2>&1; then files="$files $f"; fi
+ done
+fi
+"$tmp/metal_test" $files 2>&1 | grep -v '^.*HakiosMetal: ' || true
+"$tmp/metal_test" $files >/dev/null 2>&1
diff --git a/tools/metal_plugin_test.m b/tools/metal_plugin_test.m
new file mode 100644
index 0000000..c45b608
--- /dev/null
+++ b/tools/metal_plugin_test.m
@@ -0,0 +1,142 @@
+/*
+ * The Metal plug-in's objects (userland/src/HakiosMetal.m) on this Mac, against the Mac's own Metal: the same source built for
+ * macOS, its device made by hand the way Metal makes it (-initWithAcceleratorPort:), and what a program does with buffers and
+ * libraries checked. tools/metal-plugin-test.sh builds and runs it, under the address sanitizer.
+ *
+ * What this shows and what it does not. Metal's private classes on macOS are not iOS 16.5's (the plug-in takes _MTLResource,
+ * _MTLLibrary and _MTLFunction where they exist, and both systems have them), so this checks the plug-in's own logic -- the
+ * classes it makes at run time, their state, the buffers' memory, the reading of a .metallib, every object freed -- not that
+ * iOS's Metal is content with them. That is metal_test's to say, in QEMU (userland/rc.jobs.metal).
+ *
+ * The binary must be called metal_test: the plug-in shows its device to that program only (metal=1, the level a Mac's
+ * kern.bootargs gives, having no metal= in it).
+ *
+ * usage: metal_test [FILE.metallib ...] libraries to read besides the one made here
+ */
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#import <objc/message.h>
+#import <objc/runtime.h>
+#include <stdio.h>
+#include <string.h>
+
+static int failures;
+
+static void
+check(const char *what, BOOL ok)
+{
+ printf("%s %s\n", ok ? "ok " : "FAIL", what);
+ failures += !ok;
+}
+
+int
+main(int argc, char **argv)
+{
+ @autoreleasepool {
+ Class cls = objc_getClass("HakiosMetalDevice");
+ id<MTLDevice> device;
+
+ check("the plug-in registered HakiosMetalDevice, a subclass of _MTLDevice",
+ cls != Nil && class_getSuperclass(cls) == objc_getClass("_MTLDevice"));
+ if (cls == Nil) {
+ return 1;
+ }
+ device = ((id (*)(id, SEL, unsigned int))objc_msgSend)([cls alloc], sel_registerName("initWithAcceleratorPort:"), 7);
+ check("-initWithAcceleratorPort: gives a device that conforms to MTLDevice", device != nil && [(id)device conformsToProtocol:@protocol(MTLDevice)]);
+ check("it shares the system's memory", [device hasUnifiedMemory]);
+ check("what CoreImage asks of a device's limits is answered (no memory of its own, the system's shared)",
+ [(id)device respondsToSelector:sel_registerName("sharedMemorySize")] &&
+ ((uint64_t (*)(id, SEL))objc_msgSend)((id)device, sel_registerName("sharedMemorySize")) == [[NSProcessInfo processInfo] physicalMemory] &&
+ ((uint64_t (*)(id, SEL))objc_msgSend)((id)device, sel_registerName("dedicatedMemorySize")) == 0 && ![device isLowPower] &&
+ ![device isRemovable] && ![device isHeadless]);
+
+ /* buffers */
+ id<MTLBuffer> b = [device newBufferWithLength:10000 options:MTLResourceStorageModeShared | MTLResourceCPUCacheModeWriteCombined];
+ check("newBufferWithLength: a buffer of that length, zeroed, conforming to MTLBuffer", b != nil && [b length] == 10000 &&
+ ((uint8_t *)[b contents])[9999] == 0 && [(id)b conformsToProtocol:@protocol(MTLBuffer)]);
+ memset([b contents], 0x5a, [b length]);
+ check("what is written through -contents reads back", ((uint8_t *)[b contents])[0] == 0x5a && ((uint8_t *)[b contents])[9999] == 0x5a);
+ check("its options: shared storage, write-combined", [b storageMode] == MTLStorageModeShared &&
+ [b cpuCacheMode] == MTLCPUCacheModeWriteCombined && [b allocatedSize] >= 10000 && [b device] == device);
+ [b setLabel:@"a buffer"];
+ check("a label is kept", [[b label] isEqualToString:@"a buffer"]);
+ [b release];
+ const char text[] = "copied, not kept";
+ id<MTLBuffer> c = [device newBufferWithBytes:text length:sizeof(text) options:0];
+ check("newBufferWithBytes: a copy", c != nil && [c contents] != text && memcmp([c contents], text, sizeof(text)) == 0);
+ [c release];
+ check("a buffer longer than maxBufferLength is refused", [device newBufferWithLength:[device maxBufferLength] + 1 options:0] == nil);
+ __block int freed = 0;
+ void *page = mmap(NULL, 16384, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
+ id<MTLBuffer> n = [device newBufferWithBytesNoCopy:page length:16384 options:0 deallocator:^(void *p, NSUInteger l) {
+ freed = (p == page && l == 16384);
+ munmap(p, l);
+ }];
+ check("newBufferWithBytesNoCopy: the caller's memory itself", n != nil && [n contents] == page);
+ [n release];
+ check("... and its deallocator is called when the buffer goes", freed == 1);
+
+ /* libraries */
+ NSError *error = nil;
+ const char junk[] = "not a metallib at all, and long enough to have a header's worth of bytes in it......";
+ dispatch_data_t data = dispatch_data_create(junk, sizeof(junk), NULL, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
+ id<MTLLibrary> none = [device newLibraryWithData:data error:&error];
+ check("newLibraryWithData: on bytes that are not a metallib: nil, and an error that says why", none == nil &&
+ [[error domain] isEqualToString:MTLLibraryErrorDomain] && [[error localizedDescription] containsString:@"not a metallib"]);
+ dispatch_release(data);
+ error = nil;
+ check("newLibraryWithURL: of no file: nil, and an error", [device newLibraryWithURL:[NSURL fileURLWithPath:@"/nonexistent.metallib"]
+ error:&error] == nil && error != nil);
+ for (int i = 1; i < argc; i++) {
+ NSString *path = [NSString stringWithUTF8String:argv[i]];
+ id<MTLLibrary> library = [device newLibraryWithURL:[NSURL fileURLWithPath:path] error:&error];
+ NSArray *names = [library functionNames];
+ char label[512];
+
+ /* (a library may have no function at all: SafariSharedUI's default.metallib is 118 bytes of header) */
+ snprintf(label, sizeof(label), "%s: a library with its functions' names (%lu)", argv[i], (unsigned long)[names count]);
+ check(label, library != nil && names != nil && [(id)library conformsToProtocol:@protocol(MTLLibrary)]);
+ if (library == nil || [names count] == 0) {
+ continue;
+ }
+ unsigned typed = 0, bitcode = 0;
+ for (NSString *name in names) {
+ id<MTLFunction> f = [library newFunctionWithName:name];
+ NSData *module = [(id)f performSelector:sel_registerName("hakiosBitcode")];
+
+ typed += f != nil && [[f name] isEqualToString:name] && [f functionType] >= MTLFunctionTypeVertex && [f device] == device;
+ /* LLVM bitcode starts with "BC" 0xC0DE */
+ bitcode += [module length] > 4 && memcmp([module bytes], "BC\xc0\xde", 4) == 0;
+ [f release];
+ }
+ snprintf(label, sizeof(label), "%s: every function by its name, with its type, and its module is LLVM bitcode", argv[i]);
+ check(label, typed == [names count] && bitcode == [names count]);
+ check("a name the library does not have: nil", [library newFunctionWithName:@"no such function"] == nil);
+ [library release];
+ }
+ /* the first library again, as a universal file (an Apple-GPU slice, then the AIR64 one) given as data */
+ if (argc > 1) {
+ NSData *thin = [NSData dataWithContentsOfFile:[NSString stringWithUTF8String:argv[1]]];
+ NSMutableData *fat = [NSMutableData dataWithLength:4096];
+ uint8_t *h = [fat mutableBytes];
+ uint32_t length = (uint32_t)[thin length];
+ const uint8_t header[] = { 0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 2, 0x01, 0, 0, 0x13, 0, 0, 0, 0, 0, 0, 0x08, 0, 0, 0, 0, 0x10, 0, 0, 0, 0,
+ 0x01, 0, 0, 0x17, 0, 0, 0, 0, 0, 0, 0x10, 0, (uint8_t)(length >> 24), (uint8_t)(length >> 16), (uint8_t)(length >> 8),
+ (uint8_t)length, 0, 0, 0, 0 };
+
+ memcpy(h, header, sizeof(header));
+ [fat appendData:thin];
+ dispatch_data_t d = dispatch_data_create([fat bytes], [fat length], NULL, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
+ id<MTLLibrary> universal = [device newLibraryWithData:d error:&error];
+ id<MTLLibrary> plain = [device newLibraryWithURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[1]]] error:&error];
+ check("a universal metallib given as data: its AIR64 slice, the same functions as the thin file",
+ universal != nil && [[universal functionNames] isEqualToArray:[plain functionNames]]);
+ dispatch_release(d);
+ [universal release];
+ [plain release];
+ }
+ [device release];
+ }
+ printf("metal_plugin_test: %s\n", failures ? "FAILED" : "all passed");
+ return failures != 0;
+}
diff --git a/tools/metallib-test.sh b/tools/metallib-test.sh
new file mode 100755
index 0000000..4ba1919
--- /dev/null
+++ b/tools/metallib-test.sh
@@ -0,0 +1,36 @@
+#!/bin/sh
+# The Metal plug-in's reading of a .metallib (userland/src/hakios_metallib.c) on this machine, under the address and
+# undefined-behaviour sanitizers: a file made here and cut and bent every way (each refused, nothing read outside it), then
+# every .metallib under DIR read by it and by tools/metallib.py, which must agree on every function.
+# usage: tools/metallib-test.sh [DIR] DIR: an extracted system (sysimage/rootfs); without one, only the made file
+set -e
+cd "$(dirname "$0")/.."
+tmp=$(mktemp -d)
+trap 'rm -rf "$tmp"' EXIT
+cc -O1 -g -Wall -Wextra -fsanitize=address,undefined -fno-sanitize-recover=all -Iuserland/src \
+ tools/metallib_test.c userland/src/hakios_metallib.c -o "$tmp/metallib_test"
+"$tmp/metallib_test" cuts
+[ -n "$1" ] || exit 0
+n=0
+other=0
+find "$1" -name '*.metallib' -type f > "$tmp/files"
+while IFS= read -r f; do
+ if ! python3 tools/metallib.py list "$f" > "$tmp/py.all" 2>/dev/null; then
+ # not an MTLB container (the GPU driver's own runtime libraries are another format): the C reading must refuse it too
+ if "$tmp/metallib_test" list "$f" > "$tmp/c"; then
+ echo "metallib-test: $f: tools/metallib.py cannot read it and the C reading took it"
+ exit 1
+ fi
+ other=$((other + 1))
+ continue
+ fi
+ sed -n '/ functions$/,$p' "$tmp/py.all" > "$tmp/py"
+ "$tmp/metallib_test" list "$f" > "$tmp/c" || true
+ if ! cmp -s "$tmp/py" "$tmp/c"; then
+ echo "metallib-test: $f: the two readings differ"
+ diff "$tmp/py" "$tmp/c" | head -5
+ exit 1
+ fi
+ n=$((n + 1))
+done < "$tmp/files"
+echo "metallib-test: $n files under $1: the C reading and tools/metallib.py agree on every function; $other that are not MTLB refused by both"
diff --git a/tools/metallib_test.c b/tools/metallib_test.c
new file mode 100644
index 0000000..ab073a5
--- /dev/null
+++ b/tools/metallib_test.c
@@ -0,0 +1,234 @@
+/*
+ * userland/src/hakios_metallib.c on this machine (tools/metallib-test.sh builds it with the address and undefined-behaviour
+ * sanitizers and runs it).
+ *
+ * metallib_test list FILE the functions as tools/metallib.py list prints them (name, type, AIR version, module size),
+ * so that the script can compare the two readings line for line
+ * metallib_test cuts a small metallib made here, then every way of cutting it short and a set of lengths and offsets
+ * made to point outside it: each must be refused (or read), never read past the end
+ */
+#include "hakios_metallib.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int failures;
+
+static void
+put16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
+static void
+put32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> 8 * i); }
+static void
+put64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> 8 * i); }
+
+static size_t
+tag(uint8_t *p, const char *name, const void *value, uint16_t length)
+{
+ memcpy(p, name, 4);
+ put16(p + 4, length);
+ memcpy(p + 6, value, length);
+ return 6 + (size_t)length;
+}
+
+/* two functions, the second's module in the bitcode wrapper; returns the size */
+static size_t
+make(uint8_t *b)
+{
+ size_t list = 0x58, p, entry, modules;
+ uint8_t vers[8] = { 2, 0, 8, 0, 4, 0, 0, 0 }, offt[24] = { 0 }, mdsz[8] = { 0 }, type;
+
+ memset(b, 0, 1024);
+ memcpy(b, "MTLB", 4);
+ put16(b + 4, 0x8001);
+ put16(b + 6, 2);
+ p = list + 4;
+ put32(b + list, 2);
+ for (int i = 0; i < 2; i++) {
+ entry = p;
+ p += 4;
+ p += tag(b + p, "NAME", i == 0 ? "first\0" : "second_one\0", i == 0 ? 6 : 11);
+ type = i == 0 ? 2 : 1;
+ p += tag(b + p, "TYPE", &type, 1);
+ p += tag(b + p, "VERS", vers, 8);
+ put64(offt + 16, i == 0 ? 0 : 16);
+ p += tag(b + p, "OFFT", offt, 24);
+ put64(mdsz, i == 0 ? 16 : 40);
+ p += tag(b + p, "MDSZ", mdsz, 8);
+ memcpy(b + p, "ENDT", 4);
+ p += 4;
+ put32(b + entry, (uint32_t)(p - entry));
+ }
+ put64(b + 0x18, list);
+ put64(b + 0x20, p - list - 4);
+ modules = p;
+ memset(b + modules, 0xab, 16); /* the first module, bare */
+ put32(b + modules + 16, 0x0B17C0DE); /* the second, wrapped: 20 bytes of header, then 20 of bitcode */
+ put32(b + modules + 16 + 8, 20);
+ put32(b + modules + 16 + 12, 20);
+ memcpy(b + modules + 36, "BC\xc0\xde", 4);
+ put64(b + 0x48, modules);
+ put64(b + 0x50, 56);
+ put64(b + 0x10, modules + 56);
+ return modules + 56;
+}
+
+static void
+check(const char *what, int ok)
+{
+ if (!ok) {
+ printf("FAIL %s\n", what);
+ failures++;
+ }
+}
+
+static int
+cuts(void)
+{
+ uint8_t good[1024];
+ size_t size = make(good);
+ struct hakios_metallib info;
+ struct hakios_metallib_function f[4];
+ const char *why = NULL;
+ const uint8_t *bc;
+ uint64_t length;
+
+ check("the made file reads", hakios_metallib_parse(good, size, &info, f, 4, &why) == 0 && info.count == 2);
+ check("names, types, versions", f[0].name_length == 5 && memcmp(f[0].name, "first", 5) == 0 && f[1].name_length == 10 &&
+ f[0].type == HAKIOS_METALLIB_KERNEL && f[1].type == HAKIOS_METALLIB_FRAGMENT && f[0].air[0] == 2 && f[0].air[1] == 8);
+ check("a bare module is itself", hakios_metallib_bitcode(good, size, &f[0], &bc, &length) == 0 && length == 16);
+ check("a wrapped one is what the wrapper points at", hakios_metallib_bitcode(good, size, &f[1], &bc, &length) == 0 &&
+ length == 20 && memcmp(bc, "BC\xc0\xde", 4) == 0);
+ check("counting without keeping", hakios_metallib_parse(good, size, &info, NULL, 0, &why) == 0 && info.count == 2);
+
+ /* every length short of the whole: refused, and (under the sanitizers) nothing read past it */
+ int refused = 0;
+ for (size_t cut = 0; cut < size; cut++) {
+ uint8_t *copy = malloc(cut ? cut : 1);
+
+ memcpy(copy, good, cut);
+ refused += hakios_metallib_parse(copy, cut, &info, f, 4, &why) != 0;
+ free(copy);
+ }
+ check("every file cut short is refused", refused == (int)size);
+
+ /* offsets and lengths made to point outside, each alone */
+ static const struct { size_t at; int width; uint64_t value; const char *what; } bad[] = {
+ { 0x18, 8, 0xfffffffffffffff0ull, "the list's start" },
+ { 0x20, 8, 0xffffffffffffffffull, "the list's length" },
+ { 0x48, 8, 0xfffffffffffffff8ull, "the modules' start" },
+ { 0x50, 8, 0x7fffffffffffffffull, "the modules' length" },
+ { 0x58, 4, 0xffffffffu, "the count of functions" },
+ { 0x5c, 4, 0xfffffff0u, "an entry's size" },
+ { 0x5c, 4, 2, "an entry's size, too small" },
+ };
+ for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
+ uint8_t copy[1024];
+
+ memcpy(copy, good, size);
+ if (bad[i].width == 8) {
+ put64(copy + bad[i].at, bad[i].value);
+ } else {
+ put32(copy + bad[i].at, (uint32_t)bad[i].value);
+ }
+ char label[96];
+ snprintf(label, sizeof(label), "a bad %s is refused", bad[i].what);
+ check(label, hakios_metallib_parse(copy, size, &info, f, 4, &why) != 0);
+ }
+ /* a tag's length that runs past its entry, and a module past the modules */
+ uint8_t copy[1024];
+ memcpy(copy, good, size);
+ put16(copy + 0x58 + 4 + 4 + 4, 0xffff); /* NAME's length of the first function */
+ check("a tag running past its entry is refused", hakios_metallib_parse(copy, size, &info, f, 4, &why) != 0);
+ memcpy(copy, good, size);
+ hakios_metallib_parse(copy, size, &info, f, 4, &why);
+ put64(copy + info.file_size - 56 - 1, 0); /* (no-op: keeps the layout) */
+ /* the wrapper of the second module pointing past it */
+ memcpy(copy, good, size);
+ put32(copy + size - 40 + 12, 1000);
+ check("a wrapper pointing past its module is refused", hakios_metallib_parse(copy, size, &info, f, 4, &why) == 0 &&
+ hakios_metallib_bitcode(copy, size, &f[1], &bc, &length) != 0);
+ /* a universal file: an Apple-GPU slice first, then the AIR64 one, which is what is taken */
+ uint8_t fat[2048] = { 0 };
+ const uint8_t *thin;
+ size_t thin_size;
+ static const uint8_t header[] = { 0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 2,
+ 0x01, 0x00, 0x00, 0x13, 0, 0, 0, 0, 0, 0, 0x01, 0x00, 0, 0, 0, 0x10, 0, 0, 0, 0, /* an Apple GPU's: 16 bytes at 256 */
+ 0x01, 0x00, 0x00, 0x17, 0, 0, 0, 0, 0, 0, 0x02, 0x00, 0, 0, 0, 0, 0, 0, 0, 0 }; /* AIR64 at 512, its length below */
+ memcpy(fat, header, sizeof(header));
+ fat[8 + 20 + 12] = (uint8_t)(size >> 24);
+ fat[8 + 20 + 13] = (uint8_t)(size >> 16);
+ fat[8 + 20 + 14] = (uint8_t)(size >> 8);
+ fat[8 + 20 + 15] = (uint8_t)size;
+ memcpy(fat + 512, good, size);
+ check("a universal file: its AIR64 slice is taken, and reads", hakios_metallib_thin(fat, 512 + size, &thin, &thin_size, &why) == 0 &&
+ thin == fat + 512 && thin_size == size && hakios_metallib_parse(thin, thin_size, &info, f, 4, &why) == 0 && info.count == 2);
+ check("a thin file is itself", hakios_metallib_thin(good, size, &thin, &thin_size, &why) == 0 && thin == good && thin_size == size);
+ check("a universal file cut short of its slice is refused", hakios_metallib_thin(fat, 512 + size - 1, &thin, &thin_size, &why) != 0);
+ fat[8 + 20 + 3] = 0x13; /* no AIR64 slice any more */
+ check("a universal file with no AIR64 slice is refused", hakios_metallib_thin(fat, 512 + size, &thin, &thin_size, &why) != 0);
+ for (size_t cut = 0; cut < 64; cut++) {
+ hakios_metallib_thin(fat, cut, &thin, &thin_size, &why); /* under the sanitizers: nothing read past CUT */
+ }
+ printf("metallib_test: %s\n", failures ? "FAILED" : "the made file reads, thin and universal; every cut and every bad offset is refused");
+ return failures != 0;
+}
+
+static int
+list(const char *path)
+{
+ FILE *file = fopen(path, "rb");
+ uint8_t *data;
+ long size;
+ struct hakios_metallib info;
+ struct hakios_metallib_function *f;
+ const char *why = NULL;
+
+ if (file == NULL || fseek(file, 0, SEEK_END) != 0 || (size = ftell(file)) < 0 || fseek(file, 0, SEEK_SET) != 0) {
+ perror(path);
+ return 1;
+ }
+ data = malloc((size_t)size + 1);
+ if (fread(data, 1, (size_t)size, file) != (size_t)size) {
+ perror(path);
+ return 1;
+ }
+ fclose(file);
+ if (hakios_metallib_parse(data, (size_t)size, &info, NULL, 0, &why) != 0) {
+ printf("%s: %s\n", path, why);
+ return 1;
+ }
+ f = calloc(info.count ? info.count : 1, sizeof(*f));
+ hakios_metallib_parse(data, (size_t)size, &info, f, info.count, &why);
+ printf("%u functions\n", info.count);
+ for (uint32_t i = 0; i < info.count; i++) {
+ char air[32];
+ const uint8_t *bc;
+ uint64_t length;
+
+ snprintf(air, sizeof(air), "%u.%u.%u.%u", f[i].air[0], f[i].air[1], f[i].air[2], f[i].air[3]);
+ if (hakios_metallib_bitcode(data, (size_t)size, &f[i], &bc, &length) != 0) {
+ printf("%.*s: its wrapper points outside its module\n", (int)f[i].name_length, f[i].name);
+ return 1;
+ }
+ printf(" %-52.*s %-13s air %s module %llu\n", (int)f[i].name_length, f[i].name,
+ f[i].type == HAKIOS_METALLIB_NO_TYPE ? "?" : f[i].type < 7 ? hakios_metallib_type_name(f[i].type) : "type?",
+ air, (unsigned long long)f[i].module_size);
+ }
+ free(f);
+ free(data);
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ if (argc == 3 && strcmp(argv[1], "list") == 0) {
+ return list(argv[2]);
+ }
+ if (argc == 2 && strcmp(argv[1], "cuts") == 0) {
+ return cuts();
+ }
+ fprintf(stderr, "usage: metallib_test list FILE | cuts\n");
+ return 2;
+}
diff --git a/devices/redwood/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.c b/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.c
similarity index 100%
rename from devices/redwood/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.c
rename to uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.c
diff --git a/devices/redwood/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.h b/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.h
similarity index 100%
rename from devices/redwood/uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.h
rename to uefi/files/Silicon/Silicium/SiliciumPkg/Library/BootManagerLib/XnuLoader.h
diff --git a/userland/build.sh b/userland/build.sh
index f5ac08b..da667a8 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -232,8 +232,9 @@ if [ -d $IOS/rootfs/usr/lib ]; then
-o obj/libhakios.media.dylib src/inject_media.c src/camera_device.c src/camera_isp.c
# the output device of the audio server: a plug-in for CoreAudio's HAL
$DYN -bundle -framework CoreFoundation -o obj/HakiosAudio src/audio_plugin.c
- # the plug-in Metal loads when the kernel names it (boot-arg metal=1): a device that exists, src/HakiosMetal.m
- $DYN -bundle -framework Foundation -framework Metal -lobjc -o obj/HakiosMetal src/HakiosMetal.m
+ # the plug-in Metal loads when the kernel names it (boot-arg metal=1): a device, its buffers and the libraries it reads
+ # (src/HakiosMetal.m, src/hakios_metallib.c; tools/metal-plugin-test.sh tries the same objects on a Mac)
+ $DYN -bundle -framework Foundation -framework Metal -lobjc -o obj/HakiosMetal src/HakiosMetal.m src/hakios_metallib.c
if [ -n "$GL" ]; then
# the OpenGL ES library, and the table of functions that hands CoreAnimation's calls to it
# (Mesa says beside the library what it was built from: one from other patches is built again)
diff --git a/userland/src/HakiosMetal.m b/userland/src/HakiosMetal.m
index 80a8a46..a11c332 100644
--- a/userland/src/HakiosMetal.m
+++ b/userland/src/HakiosMetal.m
@@ -1,30 +1,34 @@
/*
- * HakiosMetal: the plug-in Metal loads when the kernel names it (boot-arg metal=1), STEP ONE: a device that exists.
+ * HakiosMetal: the plug-in Metal loads when the kernel names it (boot-arg metal=N): a device, and the first objects it makes
+ * that hold something (buffers, libraries, functions: "STEP TWO" below).
*
* What Metal does (docs/ru/metal.md section 1): it finds the IOKit service of class IOAcceleratorES, reads its
* properties MetalPluginName ("HakiosMetal") and MetalPluginClassName ("HakiosMetalDevice"), opens
* /System/Library/Extensions/HakiosMetal.bundle, takes that class, insists that it is a subclass of Metal's private
* _MTLDevice, and sends it -initWithAcceleratorPort:. That object is the system's one device.
*
- * What this is, and is not. It is the first link of that chain and nothing more: HakiosMetalDevice is a subclass of
- * _MTLDevice that answers -initWithAcceleratorPort: and -name. It cannot make a buffer, a library, a pipeline or a command
- * queue yet, and says so: a message it does not know is logged ("HakiosMetal: not implemented: -newBufferWithLength:...")
- * and answers nil/0/NO instead of crashing, so that the question "what does iOS ask a device first, and in what order?" can
- * be read off the log rather than guessed. The compiler for the shaders is a separate piece and is largely done
+ * What this is, and is not. HakiosMetalDevice is a subclass of _MTLDevice that answers -initWithAcceleratorPort: and -name,
+ * makes buffers that hold memory and libraries read from a .metallib, and stand-ins for the rest (a queue that queues nothing,
+ * pipeline and state objects that hold nothing). It cannot run anything on the GPU yet, and says so: a message it does not know
+ * is logged ("HakiosMetal: asked and not implemented: -...") and answers nil/0/NO instead of crashing, so that the question
+ * "what does iOS ask a device first, and in what order?" can be read off the log rather than guessed. The compiler for the shaders is a separate piece and is largely done
* (docs/air.md: Apple's shader bitcode into Mesa's NIR); the command queue and the kernel side are not started (docs/metal-plan.md).
*
* _MTLDevice is not in the SDK's Metal.tbd (it lives in the system's own copy of the framework), so the class is made at run
* time, in the constructor that runs when the bundle is loaded, by objc_allocateClassPair on the _MTLDevice that is there.
* If there is none, nothing is registered, and Metal drops this plug-in as it does any that is not a _MTLDevice.
*
- * Status: written without having been run. Whether _MTLDevice's own -init is safe to call, what Metal asks of the device right
- * after it is made, and whether -name is enough for MTLCreateSystemDefaultDevice() to hand it out, are what the first run (QEMU,
- * userland/rc.jobs.metal with metal=1) is for.
+ * Status. Step one ran in QEMU (docs/metal-plan.md: what it found). Step two -- buffers, libraries, functions -- was built for
+ * iOS 16.5 and run on a Mac only, against the Mac's own Metal (tools/metal-plugin-test.sh, under the address sanitizer: every
+ * buffer written and read back and freed, the system's five MTLB libraries read, all of their functions by name with their
+ * bitcode); it has not run on iOS yet: metal_test's "what the device makes" is the check for that (QEMU, metal=1).
*/
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#import <objc/message.h>
#import <objc/runtime.h>
+#include <dlfcn.h>
+#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sysctl.h>
@@ -32,6 +36,7 @@
static Class gBase; /* Metal's private _MTLDevice */
static unsigned int gPort; /* the IOAcceleratorES service this device was made for */
+static id gDevice; /* the device, once made: there is one */
static void
say(NSString * text)
@@ -48,6 +53,7 @@ deviceInit(id self, SEL _cmd, unsigned int port)
self = send(&sup, @selector(init));
gPort = port;
+ gDevice = self; /* what the objects it hands out answer to -device */
say([NSString stringWithFormat:@"a device for the accelerator port %u (%@)", port, self ? @"made" : @"_MTLDevice's init gave nil"]);
return self;
}
@@ -78,7 +84,6 @@ deviceMaxBufferLength(__unused id self, __unused SEL _cmd)
* nil, and the log says so, which is the next step's list.
*/
static Class gQueueClass;
-static id gDevice;
static id
queueDevice(__unused id self, __unused SEL _cmd)
@@ -120,7 +125,7 @@ deviceNewQueueMax(id self, SEL _cmd, __unused unsigned long maxBuffers)
}
/* the protocols the class declares (the ones Metal checks for), for the signatures below */
-static Protocol * gProtocols[16];
+static Protocol * gProtocols[64];
static unsigned gProtocolCount;
/*
@@ -227,6 +232,737 @@ stubFactory(__unused id self, SEL _cmd)
return nil;
}
+/*
+ * STEP TWO (docs/metal-plan.md, steps 3 and 4 as far as they go without the GPU): objects that hold something.
+ *
+ * buffers -newBufferWithLength:options:, ...WithBytes:..., ...WithBytesNoCopy:...: memory a program writes and reads back
+ * through -contents. The Adreno shares the system's memory, so a buffer in shared storage is the same bytes
+ * for the CPU and, later, the GPU; until the GPU is used (hakios.gpu.cpp's buffers, mapped into its address
+ * space) it is ordinary memory of this process, zeroed, and -gpuAddress is 0.
+ * libraries -newLibraryWithData:error:, -newLibraryWithURL:error:, -newLibraryWithFile:error:, -newDefaultLibrary...:
+ * the .metallib read (hakios_metallib.c, every offset checked), its functions listed by name and type, and
+ * -newFunctionWithName: giving a function that knows its name, its type and its module (the AIR bitcode the
+ * shader compiler of docs/air.md takes). Nothing is compiled yet: a pipeline made of such a function is still
+ * the empty stub above, and the log says so.
+ *
+ * Each is a class of ours made at load time, as the others are (a subclass of Metal's private _MTLResource, _MTLLibrary and
+ * _MTLFunction where this system has them), with one instance variable, _hakios, pointing at its state in C.
+ */
+#include "hakios_metallib.h"
+#include <dispatch/dispatch.h>
+#include <sys/mman.h>
+
+static Class gBufferClass, gLibraryClass, gFunctionClass;
+
+struct buffer {
+ void *memory;
+ uint64_t length;
+ unsigned long options; /* MTLResourceOptions: cache mode, storage mode, hazard tracking */
+ void (^deallocator)(void *, NSUInteger); /* for ...NoCopy: the caller's, called with its memory when the buffer goes */
+ BOOL mapped; /* ours, from mmap */
+ id label;
+};
+
+struct library {
+ NSData *data; /* the file's bytes, kept for as long as a function of it may want its module */
+ struct hakios_metallib info;
+ struct hakios_metallib_function *functions;
+ id label;
+ id names; /* NSArray of the functions' names, made once */
+};
+
+struct function {
+ id library; /* retained: the module is in its bytes */
+ struct hakios_metallib_function f;
+ id name;
+ id label;
+};
+
+static struct library *libraryOf(id self);
+
+static void **
+stateOf(id self)
+{
+ Ivar ivar = class_getInstanceVariable(object_getClass(self), "_hakios");
+
+ return ivar != NULL ? (void **)((char *)(__bridge void *)self + ivar_getOffset(ivar)) : NULL;
+}
+
+/* -dealloc: the state freed by FREE, then the superclass's own */
+static void
+deallocWith(id self, SEL _cmd, Class cls, void (*free_state)(void *))
+{
+ void **slot = stateOf(self);
+ struct objc_super sup = { self, class_getSuperclass(cls) };
+
+ if (slot != NULL && *slot != NULL) {
+ free_state(*slot);
+ *slot = NULL;
+ }
+ ((void (*)(struct objc_super *, SEL))objc_msgSendSuper)(&sup, _cmd);
+}
+
+static id
+labelGet(id self, __unused SEL _cmd)
+{
+ id *label = NULL;
+ void **slot = stateOf(self);
+
+ if (slot == NULL || *slot == NULL) {
+ return nil;
+ }
+ if (object_getClass(self) == gBufferClass) {
+ label = &((struct buffer *)*slot)->label;
+ } else if (object_getClass(self) == gLibraryClass) {
+ label = &((struct library *)*slot)->label;
+ } else {
+ label = &((struct function *)*slot)->label;
+ }
+ return *label;
+}
+
+static void
+labelSet(id self, __unused SEL _cmd, id text)
+{
+ void **slot = stateOf(self);
+ id *label;
+
+ if (slot == NULL || *slot == NULL) {
+ return;
+ }
+ if (object_getClass(self) == gBufferClass) {
+ label = &((struct buffer *)*slot)->label;
+ } else if (object_getClass(self) == gLibraryClass) {
+ label = &((struct library *)*slot)->label;
+ } else {
+ label = &((struct function *)*slot)->label;
+ }
+ [*label release];
+ *label = [text copy];
+}
+
+static id
+objectDevice(__unused id self, __unused SEL _cmd)
+{
+ return gDevice;
+}
+
+/* ---- buffers ---- */
+
+static void
+bufferFree(void *state)
+{
+ struct buffer *b = state;
+
+ if (b->mapped) {
+ munmap(b->memory, b->length ? b->length : 1);
+ } else if (b->deallocator != nil) {
+ b->deallocator(b->memory, (NSUInteger)b->length);
+ }
+ [b->deallocator release];
+ [b->label release];
+ free(b);
+}
+
+static void
+bufferDealloc(id self, SEL _cmd)
+{
+ deallocWith(self, _cmd, gBufferClass, bufferFree);
+}
+
+static struct buffer *
+bufferOf(id self)
+{
+ void **slot = stateOf(self);
+
+ return slot != NULL ? *slot : NULL;
+}
+
+static void *
+bufferContents(id self, __unused SEL _cmd)
+{
+ struct buffer *b = bufferOf(self);
+
+ return b != NULL ? b->memory : NULL;
+}
+
+static unsigned long
+bufferLength(id self, __unused SEL _cmd)
+{
+ struct buffer *b = bufferOf(self);
+
+ return b != NULL ? (unsigned long)b->length : 0;
+}
+
+static unsigned long
+bufferOptions(id self, __unused SEL _cmd)
+{
+ struct buffer *b = bufferOf(self);
+
+ return b != NULL ? b->options : 0;
+}
+
+static unsigned long
+bufferStorageMode(id self, SEL _cmd)
+{
+ return bufferOptions(self, _cmd) >> MTLResourceStorageModeShift & 0xf;
+}
+
+static unsigned long
+bufferCacheMode(id self, SEL _cmd)
+{
+ return bufferOptions(self, _cmd) >> MTLResourceCPUCacheModeShift & 0xf;
+}
+
+static unsigned long
+bufferHazardMode(id self, SEL _cmd)
+{
+ return bufferOptions(self, _cmd) >> MTLResourceHazardTrackingModeShift & 0x3;
+}
+
+/* the memory a buffer takes: its pages */
+static unsigned long
+bufferAllocatedSize(id self, SEL _cmd)
+{
+ unsigned long page = (unsigned long)getpagesize();
+
+ return (bufferLength(self, _cmd) + page - 1) / page * page;
+}
+
+/* shared memory: what the CPU wrote is what there is; nothing to tell anyone */
+static void
+bufferDidModify(__unused id self, __unused SEL _cmd, __unused NSRange range)
+{
+}
+
+/* no GPU address until the GPU's own buffers are used (hakios.gpu.cpp) */
+static uint64_t
+bufferGPUAddress(__unused id self, __unused SEL _cmd)
+{
+ return 0;
+}
+
+static unsigned long
+bufferPurgeable(__unused id self, __unused SEL _cmd, __unused unsigned long state)
+{
+ return MTLPurgeableStateNonVolatile;
+}
+
+static id
+bufferMake(void *memory, uint64_t length, unsigned long options, BOOL mapped, void (^deallocator)(void *, NSUInteger))
+{
+ id (*plain)(id, SEL) = (id (*)(id, SEL))objc_msgSend;
+ struct buffer *b;
+ id buffer;
+ void **slot;
+
+ if (gBufferClass == Nil || (buffer = plain(plain((id)gBufferClass, sel_registerName("alloc")), sel_registerName("init"))) == nil) {
+ say(@"a buffer: the class could not make one (its base's -init gave nil)");
+ return nil;
+ }
+ b = calloc(1, sizeof(*b));
+ slot = stateOf(buffer);
+ if (b == NULL || slot == NULL) {
+ free(b);
+ [buffer release];
+ return nil;
+ }
+ b->memory = memory;
+ b->length = length;
+ b->options = options;
+ b->mapped = mapped;
+ b->deallocator = [deallocator copy];
+ *slot = b;
+ return buffer;
+}
+
+static void *
+pages(uint64_t length)
+{
+ void *memory = mmap(NULL, length ? length : 1, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
+
+ return memory == MAP_FAILED ? NULL : memory;
+}
+
+static id
+deviceNewBuffer(__unused id self, __unused SEL _cmd, unsigned long length, unsigned long options)
+{
+ void *memory;
+ id buffer;
+
+ if (length > deviceMaxBufferLength(nil, NULL) || (memory = pages(length)) == NULL) {
+ say([NSString stringWithFormat:@"newBufferWithLength:%lu: no (more than maxBufferLength, or no memory): nil", length]);
+ return nil;
+ }
+ buffer = bufferMake(memory, length, options, YES, nil);
+ if (buffer == nil) {
+ munmap(memory, length ? length : 1);
+ }
+ return buffer;
+}
+
+static id
+deviceNewBufferBytes(id self, SEL _cmd, const void *bytes, unsigned long length, unsigned long options)
+{
+ id buffer = deviceNewBuffer(self, _cmd, length, options);
+
+ if (buffer != nil && bytes != NULL && length != 0) {
+ memcpy(bufferContents(buffer, NULL), bytes, length);
+ }
+ return buffer;
+}
+
+static id
+deviceNewBufferNoCopy(__unused id self, __unused SEL _cmd, void *bytes, unsigned long length, unsigned long options,
+ void (^deallocator)(void *, NSUInteger))
+{
+ if (bytes == NULL || ((uintptr_t)bytes & (uintptr_t)(getpagesize() - 1)) != 0) {
+ say(@"newBufferWithBytesNoCopy: the memory must start on a page (as Metal says): nil");
+ return nil;
+ }
+ return bufferMake(bytes, length, options, NO, deallocator);
+}
+
+/* ---- functions ---- */
+
+static void
+functionFree(void *state)
+{
+ struct function *f = state;
+
+ [f->library release];
+ [f->name release];
+ [f->label release];
+ free(f);
+}
+
+static void
+functionDealloc(id self, SEL _cmd)
+{
+ deallocWith(self, _cmd, gFunctionClass, functionFree);
+}
+
+static struct function *
+functionOf(id self)
+{
+ void **slot = stateOf(self);
+
+ return slot != NULL ? *slot : NULL;
+}
+
+static id
+functionName(id self, __unused SEL _cmd)
+{
+ struct function *f = functionOf(self);
+
+ return f != NULL ? f->name : nil;
+}
+
+/* MTLFunctionType: the metallib's TYPE as Metal numbers it */
+static unsigned long
+functionType(id self, __unused SEL _cmd)
+{
+ struct function *f = functionOf(self);
+
+ switch (f != NULL ? f->f.type : HAKIOS_METALLIB_NO_TYPE) {
+ case HAKIOS_METALLIB_VERTEX:
+ return MTLFunctionTypeVertex;
+ case HAKIOS_METALLIB_FRAGMENT:
+ return MTLFunctionTypeFragment;
+ case HAKIOS_METALLIB_KERNEL:
+ return MTLFunctionTypeKernel;
+ case HAKIOS_METALLIB_INTERSECTION:
+ return MTLFunctionTypeIntersection;
+ default:
+ return MTLFunctionTypeVisible;
+ }
+}
+
+static id
+functionNoAttributes(__unused id self, __unused SEL _cmd)
+{
+ return [NSArray array];
+}
+
+static id
+functionNoConstants(__unused id self, __unused SEL _cmd)
+{
+ return [NSDictionary dictionary];
+}
+
+/* not Metal's: the function's AIR module, for the shader compiler (docs/air.md) */
+static id
+functionBitcode(id self, __unused SEL _cmd)
+{
+ struct function *f = functionOf(self);
+ struct library *l;
+ const uint8_t *bitcode;
+ uint64_t length;
+
+ if (f == NULL || (l = libraryOf(f->library)) == NULL ||
+ hakios_metallib_bitcode([l->data bytes], [l->data length], &f->f, &bitcode, &length) != 0) {
+ return nil;
+ }
+ return [NSData dataWithBytesNoCopy:(void *)bitcode length:(NSUInteger)length freeWhenDone:NO];
+}
+
+/* ---- libraries ---- */
+
+static void
+libraryFree(void *state)
+{
+ struct library *l = state;
+
+ [l->data release];
+ [l->names release];
+ [l->label release];
+ free(l->functions);
+ free(l);
+}
+
+static void
+libraryDealloc(id self, SEL _cmd)
+{
+ deallocWith(self, _cmd, gLibraryClass, libraryFree);
+}
+
+static struct library *
+libraryOf(id self)
+{
+ void **slot = stateOf(self);
+
+ return slot != NULL ? *slot : NULL;
+}
+
+static id
+libraryFunctionNames(id self, __unused SEL _cmd)
+{
+ struct library *l = libraryOf(self);
+
+ return l != NULL ? l->names : nil;
+}
+
+static id
+libraryNewFunction(id self, __unused SEL _cmd, id name)
+{
+ id (*plain)(id, SEL) = (id (*)(id, SEL))objc_msgSend;
+ struct library *l = libraryOf(self);
+ const char *wanted = [name UTF8String];
+ size_t length = wanted != NULL ? strlen(wanted) : 0;
+
+ if (l == NULL || wanted == NULL) {
+ return nil;
+ }
+ for (uint32_t i = 0; i < l->info.count; i++) {
+ struct hakios_metallib_function *f = &l->functions[i];
+
+ if (f->name_length == length && memcmp(f->name, wanted, length) == 0) {
+ struct function *state = calloc(1, sizeof(*state));
+ id function = gFunctionClass != Nil ? plain(plain((id)gFunctionClass, sel_registerName("alloc")), sel_registerName("init")) : nil;
+ void **slot = function != nil ? stateOf(function) : NULL;
+
+ if (state == NULL || slot == NULL) {
+ free(state);
+ [function release];
+ say([NSString stringWithFormat:@"newFunctionWithName:%@: the function class could not make one: nil", name]);
+ return nil;
+ }
+ state->library = [self retain];
+ state->f = *f;
+ state->name = [name copy];
+ *slot = state;
+ return function;
+ }
+ }
+ return nil;
+}
+
+/* the same, with function constants: there is no compiler yet to specialise with them, so they are only said */
+static id
+libraryNewFunctionConstants(id self, SEL _cmd, id name, id constants, NSError **error)
+{
+ id function = libraryNewFunction(self, _cmd, name);
+
+ say([NSString stringWithFormat:@"newFunctionWithName:%@ constantValues: the constants are not applied (no compiler yet)", name]);
+ (void)constants;
+ if (function == nil && error != NULL) {
+ *error = [NSError errorWithDomain:MTLLibraryErrorDomain code:MTLLibraryErrorFunctionNotFound
+ userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"no function %@ in the library", name] }];
+ }
+ return function;
+}
+
+static unsigned long
+libraryType(__unused id self, __unused SEL _cmd)
+{
+ return MTLLibraryTypeExecutable;
+}
+
+static id
+libraryError(MTLLibraryError code, NSString *text, NSError **error)
+{
+ say(text);
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:MTLLibraryErrorDomain code:code userInfo:@{ NSLocalizedDescriptionKey: text }];
+ }
+ return nil;
+}
+
+/* a library of the bytes of a .metallib (DATA retained by the library); WHERE names them in the log */
+static id
+libraryMake(NSData *data, NSString *where, NSError **error)
+{
+ id (*plain)(id, SEL) = (id (*)(id, SEL))objc_msgSend;
+ struct library *l;
+ const char *why = NULL;
+ id library;
+ void **slot;
+ unsigned kinds[8] = { 0 };
+
+ if (gLibraryClass == Nil) {
+ return libraryError(MTLLibraryErrorInternal, @"a library: this system has no class for one", error);
+ }
+ /* a universal file (AIR64 beside code for Apple's GPUs): its AIR64 slice is the library, as Metal itself takes it */
+ const uint8_t *thin;
+ size_t thin_size;
+ if (hakios_metallib_thin([data bytes], [data length], &thin, &thin_size, &why) != 0) {
+ return libraryError(MTLLibraryErrorInternal, [NSString stringWithFormat:@"a library from %@: %s", where, why], error);
+ }
+ if (thin != [data bytes]) {
+ data = [data subdataWithRange:NSMakeRange((NSUInteger)(thin - (const uint8_t *)[data bytes]), thin_size)];
+ say([NSString stringWithFormat:@"a library from %@: a universal file, its AIR64 slice taken (%zu bytes)", where, thin_size]);
+ }
+ l = calloc(1, sizeof(*l));
+ if (l == NULL) {
+ return libraryError(MTLLibraryErrorInternal, @"a library: no memory", error);
+ }
+ if (hakios_metallib_parse([data bytes], [data length], &l->info, NULL, 0, &why) != 0 ||
+ (l->functions = calloc(l->info.count ? l->info.count : 1, sizeof(*l->functions))) == NULL ||
+ hakios_metallib_parse([data bytes], [data length], &l->info, l->functions, l->info.count, &why) != 0) {
+ free(l->functions);
+ free(l);
+ return libraryError(MTLLibraryErrorInternal, [NSString stringWithFormat:@"a library from %@: %s", where,
+ why ? why : "no memory"], error);
+ }
+ NSMutableArray *names = [NSMutableArray arrayWithCapacity:l->info.count];
+ for (uint32_t i = 0; i < l->info.count; i++) {
+ NSString *name = [[NSString alloc] initWithBytes:l->functions[i].name length:l->functions[i].name_length encoding:NSUTF8StringEncoding];
+
+ if (name != nil) {
+ [names addObject:name];
+ [name release];
+ }
+ kinds[l->functions[i].type < 7 ? l->functions[i].type : 7]++;
+ }
+ library = plain(plain((id)gLibraryClass, sel_registerName("alloc")), sel_registerName("init"));
+ slot = library != nil ? stateOf(library) : NULL;
+ if (slot == NULL) {
+ free(l->functions);
+ free(l);
+ [library release];
+ return libraryError(MTLLibraryErrorInternal, @"a library: the class could not make one (its base's -init gave nil)", error);
+ }
+ l->data = [data retain];
+ l->names = [names copy];
+ *slot = l;
+ say([NSString stringWithFormat:@"a library from %@: %u functions (%u vertex, %u fragment, %u kernel, %u other), container %u.%u",
+ where, l->info.count, kinds[0], kinds[1], kinds[2], l->info.count - kinds[0] - kinds[1] - kinds[2],
+ l->info.version[0], l->info.version[1]]);
+ return library;
+}
+
+static id
+deviceNewLibraryURL(__unused id self, __unused SEL _cmd, NSURL *url, NSError **error)
+{
+ NSData *data = url != nil ? [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:NULL] : nil;
+
+ if (data == nil) {
+ return libraryError(MTLLibraryErrorFileNotFound, [NSString stringWithFormat:@"a library from %@: no such file", url], error);
+ }
+ return libraryMake(data, [url path], error);
+}
+
+static id
+deviceNewLibraryFile(id self, SEL _cmd, NSString *path, NSError **error)
+{
+ return deviceNewLibraryURL(self, _cmd, path != nil ? [NSURL fileURLWithPath:path] : nil, error);
+}
+
+static id
+deviceNewLibraryData(__unused id self, __unused SEL _cmd, dispatch_data_t data, NSError **error)
+{
+ const void *bytes = NULL;
+ size_t size = 0;
+ dispatch_data_t map;
+ NSData *copy;
+
+ if (data == nil) {
+ return libraryError(MTLLibraryErrorFileNotFound, @"a library from data: no data", error);
+ }
+ map = dispatch_data_create_map(data, &bytes, &size);
+ copy = [NSData dataWithBytes:bytes length:size]; /* the caller may let go of its data; the library keeps its own */
+ dispatch_release(map);
+ return libraryMake(copy, @"data", error);
+}
+
+/* a bundle's default.metallib: the main bundle's for -newDefaultLibrary */
+static id
+deviceNewDefaultLibraryBundle(id self, SEL _cmd, NSBundle *bundle, NSError **error)
+{
+ NSURL *url = [bundle URLForResource:@"default" withExtension:@"metallib"];
+
+ if (url == nil) {
+ return libraryError(MTLLibraryErrorFileNotFound, [NSString stringWithFormat:@"the default library of %@: no default.metallib",
+ [bundle bundlePath]], error);
+ }
+ return deviceNewLibraryURL(self, _cmd, url, error);
+}
+
+static id
+deviceNewDefaultLibrary(id self, SEL _cmd)
+{
+ return deviceNewDefaultLibraryBundle(self, _cmd, [NSBundle mainBundle], NULL);
+}
+
+static BOOL
+deviceUnifiedMemory(__unused id self, __unused SEL _cmd)
+{
+ return YES; /* the Adreno has no memory of its own */
+}
+
+/*
+ * What CoreImage's CIMetalDeviceGetLimits reads of a device and _MTLDevice does not answer (Apple's own GPU devices do): without
+ * them every CIContext creation throws, and a process drawing symbols through CoreImage (iconservicesagent) ends. UniXNU's
+ * AdrenoMetal found this on iPadOS 17; the answers are the same here: no memory of its own, the system's shared.
+ */
+static uint64_t
+deviceNoDedicatedMemory(__unused id self, __unused SEL _cmd)
+{
+ return 0;
+}
+
+static uint64_t
+deviceSharedMemory(__unused id self, __unused SEL _cmd)
+{
+ return [[NSProcessInfo processInfo] physicalMemory];
+}
+
+static BOOL
+deviceNo(__unused id self, __unused SEL _cmd)
+{
+ return NO;
+}
+
+/* no legacy feature set is claimed: _MTLDevice's own answer reads tables of Apple's GPUs */
+static BOOL
+deviceNoFeatureSet(__unused id self, __unused SEL _cmd, __unused unsigned long set)
+{
+ return NO;
+}
+
+/*
+ * The public protocol and Metal's private one of the same name (MTLBufferSPI ...), where this system has it: not every protocol
+ * whose name begins the same, as for the stub objects, because MTLFunction begins a dozen others (MTLFunctionStitchingNode ...)
+ * that a function is not.
+ */
+static void
+declareProtocols(Class cls, const char *const *names)
+{
+ char spi[96];
+
+ for (; *names != NULL; names++) {
+ for (int private = 0; private < 2; private++) {
+ Protocol *protocol;
+
+ snprintf(spi, sizeof(spi), "%s%s", *names, private ? "SPI" : "");
+ if ((protocol = objc_getProtocol(spi)) == NULL) {
+ continue;
+ }
+ class_addProtocol(cls, protocol);
+ if (gProtocolCount < sizeof(gProtocols) / sizeof(gProtocols[0])) {
+ gProtocols[gProtocolCount++] = protocol;
+ }
+ }
+ }
+}
+
+/* a class of ours with the _hakios slot, on Metal's private BASE where there is one */
+static Class
+objectClass(const char *name, const char *base, const char *const *protocols, IMP dealloc)
+{
+ Class super = objc_getClass(base);
+ Class cls = objc_allocateClassPair(super != Nil ? super : objc_getClass("NSObject"), name, 0);
+
+ if (cls == Nil) {
+ say([NSString stringWithFormat:@"could not make the class %s", name]);
+ return Nil;
+ }
+ class_addIvar(cls, "_hakios", sizeof(void *), sizeof(void *) == 8 ? 3 : 2, "^v");
+ declareProtocols(cls, protocols);
+ class_addMethod(cls, sel_registerName("dealloc"), dealloc, "v@:");
+ class_addMethod(cls, sel_registerName("device"), (IMP)objectDevice, "@@:");
+ class_addMethod(cls, sel_registerName("label"), (IMP)labelGet, "@@:");
+ class_addMethod(cls, sel_registerName("setLabel:"), (IMP)labelSet, "v@:@");
+ class_addMethod(cls, sel_registerName("methodSignatureForSelector:"), (IMP)deviceSignature, "@@::");
+ class_addMethod(cls, sel_registerName("forwardInvocation:"), (IMP)deviceForward, "v@:@");
+ say([NSString stringWithFormat:@"%s is registered (a subclass of %s)", name, super != Nil ? base : "NSObject: this system has no such class"]);
+ return cls;
+}
+
+static void
+registerObjectClasses(Class device)
+{
+ static const char *const buffer[] = { "MTLBuffer", "MTLResource", NULL }, *const function[] = { "MTLFunction", NULL },
+ *const library[] = { "MTLLibrary", NULL };
+
+ if ((gBufferClass = objectClass("HakiosMetalBuffer", "_MTLResource", buffer, (IMP)bufferDealloc)) != Nil) {
+ class_addMethod(gBufferClass, sel_registerName("contents"), (IMP)bufferContents, "^v@:");
+ class_addMethod(gBufferClass, sel_registerName("length"), (IMP)bufferLength, "Q@:");
+ class_addMethod(gBufferClass, sel_registerName("resourceOptions"), (IMP)bufferOptions, "Q@:");
+ class_addMethod(gBufferClass, sel_registerName("storageMode"), (IMP)bufferStorageMode, "Q@:");
+ class_addMethod(gBufferClass, sel_registerName("cpuCacheMode"), (IMP)bufferCacheMode, "Q@:");
+ class_addMethod(gBufferClass, sel_registerName("hazardTrackingMode"), (IMP)bufferHazardMode, "Q@:");
+ class_addMethod(gBufferClass, sel_registerName("allocatedSize"), (IMP)bufferAllocatedSize, "Q@:");
+ class_addMethod(gBufferClass, sel_registerName("didModifyRange:"), (IMP)bufferDidModify, "v@:{_NSRange=QQ}");
+ class_addMethod(gBufferClass, sel_registerName("gpuAddress"), (IMP)bufferGPUAddress, "Q@:");
+ class_addMethod(gBufferClass, sel_registerName("setPurgeableState:"), (IMP)bufferPurgeable, "Q@:Q");
+ objc_registerClassPair(gBufferClass);
+ class_addMethod(device, sel_registerName("newBufferWithLength:options:"), (IMP)deviceNewBuffer, "@@:QQ");
+ class_addMethod(device, sel_registerName("newBufferWithBytes:length:options:"), (IMP)deviceNewBufferBytes, "@@:r^vQQ");
+ class_addMethod(device, sel_registerName("newBufferWithBytesNoCopy:length:options:deallocator:"), (IMP)deviceNewBufferNoCopy,
+ "@@:^vQQ@?");
+ }
+ if ((gFunctionClass = objectClass("HakiosMetalFunction", "_MTLFunction", function, (IMP)functionDealloc)) != Nil) {
+ class_addMethod(gFunctionClass, sel_registerName("name"), (IMP)functionName, "@@:");
+ class_addMethod(gFunctionClass, sel_registerName("functionType"), (IMP)functionType, "Q@:");
+ class_addMethod(gFunctionClass, sel_registerName("vertexAttributes"), (IMP)functionNoAttributes, "@@:");
+ class_addMethod(gFunctionClass, sel_registerName("stageInputAttributes"), (IMP)functionNoAttributes, "@@:");
+ class_addMethod(gFunctionClass, sel_registerName("functionConstantsDictionary"), (IMP)functionNoConstants, "@@:");
+ class_addMethod(gFunctionClass, sel_registerName("hakiosBitcode"), (IMP)functionBitcode, "@@:");
+ objc_registerClassPair(gFunctionClass);
+ }
+ if ((gLibraryClass = objectClass("HakiosMetalLibrary", "_MTLLibrary", library, (IMP)libraryDealloc)) != Nil) {
+ class_addMethod(gLibraryClass, sel_registerName("functionNames"), (IMP)libraryFunctionNames, "@@:");
+ class_addMethod(gLibraryClass, sel_registerName("newFunctionWithName:"), (IMP)libraryNewFunction, "@@:@");
+ class_addMethod(gLibraryClass, sel_registerName("newFunctionWithName:constantValues:error:"), (IMP)libraryNewFunctionConstants,
+ "@@:@@^@");
+ class_addMethod(gLibraryClass, sel_registerName("type"), (IMP)libraryType, "Q@:");
+ objc_registerClassPair(gLibraryClass);
+ class_addMethod(device, sel_registerName("newLibraryWithURL:error:"), (IMP)deviceNewLibraryURL, "@@:@^@");
+ class_addMethod(device, sel_registerName("newLibraryWithFile:error:"), (IMP)deviceNewLibraryFile, "@@:@^@");
+ class_addMethod(device, sel_registerName("newLibraryWithData:error:"), (IMP)deviceNewLibraryData, "@@:@^@");
+ class_addMethod(device, sel_registerName("newDefaultLibrary"), (IMP)deviceNewDefaultLibrary, "@@:");
+ class_addMethod(device, sel_registerName("newDefaultLibraryWithBundle:error:"), (IMP)deviceNewDefaultLibraryBundle, "@@:@^@");
+ }
+ class_addMethod(device, sel_registerName("hasUnifiedMemory"), (IMP)deviceUnifiedMemory, "B@:");
+ class_addMethod(device, sel_registerName("dedicatedMemorySize"), (IMP)deviceNoDedicatedMemory, "Q@:");
+ class_addMethod(device, sel_registerName("sharedMemorySize"), (IMP)deviceSharedMemory, "Q@:");
+ class_addMethod(device, sel_registerName("isLowPower"), (IMP)deviceNo, "B@:");
+ class_addMethod(device, sel_registerName("isRemovable"), (IMP)deviceNo, "B@:");
+ class_addMethod(device, sel_registerName("isHeadless"), (IMP)deviceNo, "B@:");
+ class_addMethod(device, sel_registerName("supportsFeatureSet:"), (IMP)deviceNoFeatureSet, "B@:Q");
+}
+
/* Declares `protocol` and every private protocol whose name begins with it on `cls`, and keeps them for the stub's signatures. */
static void
declareProtocolFamily(Class cls, const char * protocolName)
@@ -326,7 +1062,42 @@ registerQueueClass(void)
* it), so the window server cannot run on Metal here at all. And mediaserverd, given a device that cannot do anything, ends and
* is started again. A device that is shown to a process that cannot use it costs that process, so it is shown to as few as the
* experiment needs.
+ *
+ * Besides the level, a file HakiosMetal.clients beside the bundle (the way UniXNU's AdrenoMetal chooses its clients) names more
+ * processes, one per line, "*" for every one: an image can show the device to the one program being worked on without a boot-arg.
*/
+static BOOL
+listedBesideTheBundle(const char *name)
+{
+ Dl_info info;
+ char path[1024], line[256];
+ char *slash;
+ FILE *file;
+ BOOL listed = NO;
+
+ if (dladdr((const void *)&listedBesideTheBundle, &info) == 0 || info.dli_fname == NULL) {
+ return NO;
+ }
+ strlcpy(path, info.dli_fname, sizeof(path)); /* <Extensions>/HakiosMetal.bundle/HakiosMetal */
+ if ((slash = strrchr(path, '/')) == NULL) {
+ return NO;
+ }
+ *slash = '\0';
+ if ((slash = strrchr(path, '/')) == NULL) {
+ return NO;
+ }
+ strlcpy(slash + 1, "HakiosMetal.clients", sizeof(path) - (size_t)(slash + 1 - path));
+ if ((file = fopen(path, "r")) == NULL) {
+ return NO;
+ }
+ while (!listed && fgets(line, sizeof(line), file) != NULL) {
+ line[strcspn(line, " \t\r\n#")] = '\0';
+ listed = strcmp(line, "*") == 0 || (line[0] != '\0' && strcmp(line, name) == 0);
+ }
+ fclose(file);
+ return listed;
+}
+
static BOOL
shownToThisProcess(void)
{
@@ -348,6 +1119,10 @@ shownToThisProcess(void)
if (level >= 3 || (level == 2 && strcmp(name, "backboardd") != 0) || (level == 1 && strcmp(name, "metal_test") == 0)) {
return YES;
}
+ if (listedBesideTheBundle(name)) {
+ say([NSString stringWithFormat:@"%s is shown the device: HakiosMetal.clients beside the bundle names it", name]);
+ return YES;
+ }
say([NSString stringWithFormat:@"%s is not shown the device (metal=%d; 1 is metal_test only, 2 all but backboardd, 3 all)", name, level]);
return NO;
}
@@ -408,4 +1183,5 @@ registerDevice(void)
say(@"the class HakiosMetalDevice is registered (a subclass of _MTLDevice)");
registerQueueClass();
registerStubClasses(device);
+ registerObjectClasses(device);
}
diff --git a/userland/src/hakios_metallib.c b/userland/src/hakios_metallib.c
new file mode 100644
index 0000000..34b9c9a
--- /dev/null
+++ b/userland/src/hakios_metallib.c
@@ -0,0 +1,220 @@
+/*
+ * The MTLB container (userland/src/hakios_metallib.h): what tools/metallib.py reads, with every offset checked.
+ *
+ * 0x00 "MTLB"
+ * 0x04 u16 u16 the container's version
+ * 0x10 u64 the file's size
+ * 0x18 u64 u64 the function list: where it starts, and how long it is after its count (tools/metallib.py calls
+ * the second "funcs_end" and does not use it; on every file of the system, the start plus 4 plus it is
+ * where the entries end)
+ * 0x28 u64 u64 the public metadata (offset, length) not read here
+ * 0x38 u64 u64 the private metadata not read here
+ * 0x48 u64 u64 the modules: where they start, how long
+ *
+ * The function list is a u32 count, then one entry per function: a u32 size (counted from the size field itself) and
+ * tags until ENDT. A tag is four letters, a u16 length and that many bytes. NAME is the name with its NUL, TYPE one
+ * byte, VERS four u16, OFFT three u64 (the last is the module's offset from the start of the modules), MDSZ the
+ * module's size.
+ */
+#include "hakios_metallib.h"
+
+#include <string.h>
+
+#define HEADER_SIZE 0x58
+
+static uint16_t
+u16(const uint8_t *p)
+{
+ return (uint16_t)(p[0] | p[1] << 8);
+}
+
+static uint32_t
+u32(const uint8_t *p)
+{
+ return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24;
+}
+
+static uint64_t
+u64(const uint8_t *p)
+{
+ return (uint64_t)u32(p) | (uint64_t)u32(p + 4) << 32;
+}
+
+/* [offset, offset + length) inside a file of SIZE bytes, without the sum wrapping */
+static int
+inside(uint64_t offset, uint64_t length, uint64_t size)
+{
+ return offset <= size && length <= size - offset;
+}
+
+int
+hakios_metallib_parse(const uint8_t *data, size_t size, struct hakios_metallib *info,
+ struct hakios_metallib_function *out, uint32_t max, const char **why)
+{
+ uint64_t list, list_length, list_end, modules, modules_length, p;
+ uint32_t count;
+
+ if (size < HEADER_SIZE || memcmp(data, "MTLB", 4) != 0) {
+ *why = "not a metallib (no MTLB at the start, or shorter than its header)";
+ return -1;
+ }
+ info->version[0] = u16(data + 4);
+ info->version[1] = u16(data + 6);
+ info->file_size = u64(data + 0x10);
+ list = u64(data + 0x18);
+ list_length = u64(data + 0x20);
+ modules = u64(data + 0x48);
+ modules_length = u64(data + 0x50);
+ if (!inside(list, 4, size) || !inside(list + 4, list_length, size)) {
+ *why = "the function list is not inside the file";
+ return -1;
+ }
+ if (!inside(modules, modules_length, size)) {
+ *why = "the modules are not inside the file";
+ return -1;
+ }
+ list_end = list + 4 + list_length;
+ count = u32(data + list);
+ info->count = count;
+ p = list + 4;
+ for (uint32_t i = 0; i < count; i++) {
+ struct hakios_metallib_function f = { .type = HAKIOS_METALLIB_NO_TYPE };
+ uint64_t entry, end, q;
+ int have_offset = 0, have_size = 0;
+
+ if (!inside(p, 4, list_end)) {
+ *why = "the function list ends before its count of functions";
+ return -1;
+ }
+ entry = u32(data + p);
+ if (entry < 4 || !inside(p, entry, list_end)) {
+ *why = "a function's entry is not inside the function list";
+ return -1;
+ }
+ end = p + entry;
+ for (q = p + 4; q + 4 <= end && memcmp(data + q, "ENDT", 4) != 0;) {
+ const uint8_t *value;
+ uint16_t length;
+
+ if (!inside(q, 6, end)) {
+ *why = "a tag runs past the end of its function's entry";
+ return -1;
+ }
+ length = u16(data + q + 4);
+ if (!inside(q + 6, length, end)) {
+ *why = "a tag's value runs past the end of its function's entry";
+ return -1;
+ }
+ value = data + q + 6;
+ if (memcmp(data + q, "NAME", 4) == 0) {
+ f.name = (const char *)value;
+ f.name_length = length;
+ while (f.name_length > 0 && f.name[f.name_length - 1] == '\0') {
+ f.name_length--;
+ }
+ } else if (memcmp(data + q, "TYPE", 4) == 0 && length >= 1) {
+ f.type = value[0];
+ } else if (memcmp(data + q, "VERS", 4) == 0 && length >= 8) {
+ for (int k = 0; k < 4; k++) {
+ f.air[k] = u16(value + 2 * k);
+ }
+ } else if (memcmp(data + q, "OFFT", 4) == 0 && length >= 24) {
+ f.module_offset = u64(value + 16);
+ have_offset = 1;
+ } else if (memcmp(data + q, "MDSZ", 4) == 0 && length >= 8) {
+ f.module_size = u64(value);
+ have_size = 1;
+ }
+ q += 6 + (uint64_t)length;
+ }
+ if (f.name == NULL || !have_offset || !have_size) {
+ *why = "a function has no NAME, OFFT or MDSZ";
+ return -1;
+ }
+ if (!inside(f.module_offset, f.module_size, modules_length)) {
+ *why = "a function's module is not inside the modules";
+ return -1;
+ }
+ f.module_offset += modules;
+ if (i < max) {
+ out[i] = f;
+ }
+ p = end;
+ }
+ return 0;
+}
+
+#define FAT_MAGIC 0xcafebabeu
+#define CPU_TYPE_AIR64 0x01000017u /* the AIR slice's cputype, as Metal looks for it */
+
+static uint32_t
+be32(const uint8_t *p)
+{
+ return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | (uint32_t)p[3];
+}
+
+int
+hakios_metallib_thin(const uint8_t *data, size_t size, const uint8_t **thin, size_t *thin_size, const char **why)
+{
+ uint32_t count;
+
+ if (size < 8 || be32(data) != FAT_MAGIC) {
+ *thin = data;
+ *thin_size = size;
+ return 0;
+ }
+ count = be32(data + 4);
+ for (uint32_t i = 0; i < count && i < 64; i++) {
+ uint64_t at = 8 + 20 * (uint64_t)i;
+
+ if (!inside(at, 20, size)) {
+ break;
+ }
+ if (be32(data + at) == CPU_TYPE_AIR64) {
+ uint32_t offset = be32(data + at + 8), length = be32(data + at + 12);
+
+ if (!inside(offset, length, size)) {
+ *why = "a universal metallib whose AIR64 slice is not inside it";
+ return -1;
+ }
+ *thin = data + offset;
+ *thin_size = length;
+ return 0;
+ }
+ }
+ *why = "a universal metallib with no AIR64 slice (only code for Apple's own GPUs)";
+ return -1;
+}
+
+const char *
+hakios_metallib_type_name(uint8_t type)
+{
+ static const char *const names[] = { "vertex", "fragment", "kernel", "unqualified", "visible", "extern", "intersection" };
+
+ return type < sizeof(names) / sizeof(names[0]) ? names[type] : "?";
+}
+
+int
+hakios_metallib_bitcode(const uint8_t *data, size_t size, const struct hakios_metallib_function *function,
+ const uint8_t **bitcode, uint64_t *length)
+{
+ const uint8_t *module = data + function->module_offset;
+ uint32_t offset, wrapped;
+
+ if (!inside(function->module_offset, function->module_size, size)) {
+ return -1;
+ }
+ if (function->module_size >= 16 && u32(module) == 0x0B17C0DEu) {
+ offset = u32(module + 8);
+ wrapped = u32(module + 12);
+ if (!inside(offset, wrapped, function->module_size)) {
+ return -1;
+ }
+ *bitcode = module + offset;
+ *length = wrapped;
+ return 0;
+ }
+ *bitcode = module;
+ *length = function->module_size;
+ return 0;
+}
diff --git a/userland/src/hakios_metallib.h b/userland/src/hakios_metallib.h
new file mode 100644
index 0000000..ad8a2fd
--- /dev/null
+++ b/userland/src/hakios_metallib.h
@@ -0,0 +1,68 @@
+/*
+ * A .metallib taken apart: the MTLB container Apple's shader compiler writes, its list of functions, and where each
+ * function's module (LLVM bitcode, "AIR") is. The same reading as tools/metallib.py, in C, for the Metal plug-in
+ * (userland/src/HakiosMetal.m: -newLibraryWithData:, -newLibraryWithURL:) and for tools/metallib-test.sh, which checks
+ * the two against each other on every .metallib of the system.
+ *
+ * The file is not trusted: a program hands the device whatever bytes it likes. Every offset and length is checked
+ * against the size before it is used, and a file that does not hold together is refused with the reason.
+ */
+#ifndef HAKIOS_METALLIB_H
+#define HAKIOS_METALLIB_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/* the TYPE tag (tools/metallib.py, checked against the metadata of the system's 456 modules) */
+enum hakios_metallib_type {
+ HAKIOS_METALLIB_VERTEX = 0,
+ HAKIOS_METALLIB_FRAGMENT = 1,
+ HAKIOS_METALLIB_KERNEL = 2,
+ HAKIOS_METALLIB_UNQUALIFIED = 3,
+ HAKIOS_METALLIB_VISIBLE = 4,
+ HAKIOS_METALLIB_EXTERN = 5,
+ HAKIOS_METALLIB_INTERSECTION = 6,
+ HAKIOS_METALLIB_NO_TYPE = 255, /* the entry has no TYPE tag */
+};
+
+struct hakios_metallib_function {
+ const char *name; /* into the file's bytes, NAME_LENGTH long; not NUL-terminated of itself */
+ uint32_t name_length;
+ uint8_t type; /* enum hakios_metallib_type, or the number as the file has it */
+ uint16_t air[4]; /* VERS: the AIR version (2.8.4.0) */
+ uint64_t module_offset; /* the module's first byte, from the start of the file */
+ uint64_t module_size;
+};
+
+struct hakios_metallib {
+ uint16_t version[2]; /* the container's (32769.2 on iOS 16.5) */
+ uint64_t file_size; /* what the header says the file is */
+ uint32_t count; /* the functions in the file (more than were kept, if the caller's array was short) */
+};
+
+/*
+ * Reads DATA (SIZE bytes). Up to MAX functions go into OUT (which may be NULL when MAX is 0, to count them first).
+ * 0 on success; -1 on a file that is not a metallib or does not hold together, with *WHY saying where.
+ */
+int hakios_metallib_parse(const uint8_t *data, size_t size, struct hakios_metallib *info,
+ struct hakios_metallib_function *out, uint32_t max, const char **why);
+
+/*
+ * The AIR of a universal metallib: a fat container (0xCAFEBABE, big endian, 20-byte entries as Mach-O's) of an AIR64 metallib and
+ * a binary for Apple's own GPUs, the way the frameworks of newer systems ship their libraries (QuartzCore's default.metallib on
+ * iPadOS 17: UniXNU's AdrenoMetal found it, and takes the AIR64 slice as Metal itself does). A thin metallib is returned as it is.
+ * 0 with *THIN and *THIN_SIZE, or -1 (with *WHY) for a fat file with no AIR64 slice or one that is not inside it.
+ */
+int hakios_metallib_thin(const uint8_t *data, size_t size, const uint8_t **thin, size_t *thin_size, const char **why);
+
+/* the TYPE number as tools/metallib.py names it: "vertex", "fragment", "kernel", ... */
+const char *hakios_metallib_type_name(uint8_t type);
+
+/*
+ * The function's module without the LLVM bitcode wrapper (0x0B17C0DE: the header that says where the bitcode is in it),
+ * if it has one: *BITCODE and *LENGTH, into DATA. 0, or -1 if the wrapper points outside the module.
+ */
+int hakios_metallib_bitcode(const uint8_t *data, size_t size, const struct hakios_metallib_function *function,
+ const uint8_t **bitcode, uint64_t *length);
+
+#endif
diff --git a/userland/src/hello.c b/userland/src/hello.c
index ad7c8c8..79e3305 100644
--- a/userland/src/hello.c
+++ b/userland/src/hello.c
@@ -145,7 +145,7 @@ start(void)
/*
* The kernel's own version: sysctl kern.hakios.version, which the loader gave the kernel on its command line
- * (hakios_kver, from the payload's kernel.ver). The same string the banner shows under hello hackios-kernel!
+ * (hakios_kver, from the payload's kernel.ver). The same string the banner shows under hello hakios-kernel!
*/
{
char version[96];
diff --git a/userland/src/metal_test.m b/userland/src/metal_test.m
index 2465f73..b0226a0 100644
--- a/userland/src/metal_test.m
+++ b/userland/src/metal_test.m
@@ -310,6 +310,61 @@ the_device(void)
(int)[device supportsFamily:MTLGPUFamilyApple1], (int)[device supportsFamily:MTLGPUFamilyApple4]);
}
+/*
+ * What the device can make (HakiosMetal's step two, docs/metal-plan.md): a buffer written and read back through -contents, a
+ * copy, and the library of the OpenGL ES-on-Metal renderer the system carries, its functions by name. Run in a process of its
+ * own: a device that cannot do something may end the process that asks.
+ */
+#define GL_RENDERER_LIBRARY "/System/Library/Extensions/AppleMetalGLRenderer.bundle/default.metallib"
+
+static void
+device_objects(void)
+{
+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();
+ NSError *error = nil;
+
+ if (device == nil) {
+ printf("metal_test: no device: nothing to ask\n");
+ return;
+ }
+ id<MTLBuffer> buffer = [device newBufferWithLength:65536 options:MTLResourceStorageModeShared];
+ if (buffer == nil) {
+ printf("metal_test: newBufferWithLength:65536 = nil\n");
+ } else {
+ uint32_t *words = [buffer contents], bad = 0;
+
+ for (uint32_t i = 0; i < 16384; i++) {
+ words[i] = i * 2654435761u;
+ }
+ for (uint32_t i = 0; i < 16384; i++) {
+ bad += words[i] != i * 2654435761u;
+ }
+ printf("metal_test: a buffer of %lu bytes (class %s, storage mode %lu): written and read back, %u words wrong\n",
+ (unsigned long)[buffer length], class_getName([(id)buffer class]), (unsigned long)[buffer storageMode], bad);
+ }
+ static const char text[] = "the bytes of a buffer made with newBufferWithBytes:";
+ id<MTLBuffer> copy = [device newBufferWithBytes:text length:sizeof(text) options:0];
+ printf("metal_test: newBufferWithBytes: %s\n", copy == nil ? "nil" :
+ memcmp([copy contents], text, sizeof(text)) == 0 ? "a copy of them" : "SOMETHING ELSE");
+
+ id<MTLLibrary> library = [device newLibraryWithURL:[NSURL fileURLWithPath:@GL_RENDERER_LIBRARY] error:&error];
+ if (library == nil) {
+ printf("metal_test: newLibraryWithURL:%s = nil (%s)\n", GL_RENDERER_LIBRARY, [[error localizedDescription] UTF8String]);
+ return;
+ }
+ NSArray<NSString *> *names = [library functionNames];
+ unsigned kinds[4] = { 0 };
+ for (NSString *name in names) {
+ id<MTLFunction> f = [library newFunctionWithName:name];
+ unsigned long type = f != nil ? [f functionType] : 0;
+
+ kinds[type == MTLFunctionTypeVertex ? 0 : type == MTLFunctionTypeFragment ? 1 : type == MTLFunctionTypeKernel ? 2 : 3]++;
+ }
+ printf("metal_test: the GL renderer's library (class %s): %lu functions, %u vertex, %u fragment, %u kernel, %u other%s%s\n",
+ class_getName([(id)library class]), (unsigned long)[names count], kinds[0], kinds[1], kinds[2], kinds[3],
+ [names count] ? "; the first is " : "", [names count] ? [names[0] UTF8String] : "");
+}
+
/* What iOS publishes about graphics besides: artwork, not rendering (see the note above). */
static void
gestalt(void)
@@ -532,6 +587,8 @@ main(int argc, char **argv)
coreimage();
} else if (strcmp(argv[1], "plugins") == 0) {
plugins();
+ } else if (strcmp(argv[1], "objects") == 0) {
+ device_objects();
} else {
printf("metal_test: no such question: %s\n", argv[1]);
return 2;
@@ -545,6 +602,7 @@ main(int argc, char **argv)
gpu_services();
printf("metal_test: the device a program gets\n");
the_device();
+ in_a_new_process("what the device makes: buffers, a library", "objects", 60);
printf("metal_test: what iOS publishes about graphics (artwork, not rendering)\n");
gestalt();
printf("metal_test: CoreImage, which has a path without Metal\n");