🆕 Put a guest kext for reims-vgpu's GPU in the OpenCore image

x86-64 macOS guests drive reims-vgpu's GPU through AppleParavirtGPU.kext,
whose setupVersion asks for binary version 6 and turns every later feature
off; arm64 guests ask for 245. ReimsVgpu.kext (kext/), a Lilu plugin,
routes setupVersion to ask for 245 and set its features, and leaves the
driver's own negotiation to a host that does not store it. It also patches
what the x86-64 driver and its Metal plugin hardcode where arm64's ask the
device:

- AppleParavirtResourceHeap::addObject adds a two-plane D32S8 or X32S8
  texture as type 12, as arm64 does, not as type 2, which the host reads as
  one plane and faults on.
- -[AppleParavirtDevice featureProfile] returns 10001, not 10000, adding
  the Mac2 and Common3 families that ANGLE's Metal backend, so
  GPU-accelerated Chrome, needs.
- -[AppleParavirtTexture initTiledWithBuffer:...] no longer refuses
  SkyLight's tiles of a window wider than 2048 px, whose real bytes fit;
  the host accepts them from their real footprint (reims-vgpu's fdf661fee).

The plugin's bytes are patched through UserPatch, since Lilu's own user
patcher is off from macOS 11: it routes _cs_validate_page and rewrites a
page after the kernel has validated its pristine bytes, so code signing
does not notice and no other binary is touched.

The image carries the kext with Lilu 1.7.2's RELEASE build, pinned by
SHA-256 and cached like OpenCore, and loads both on macOS 26 alone (Darwin
25), so every other macOS boots with no kexts, as before. --no-kexts leaves
them out.

A kext builds on a Mac alone, and reims-util builds anywhere, so the built
kext is kept in the repository at kext/ReimsVgpu.kext and included in the
binary. kext/Makefile writes it there, against a DEBUG Lilu.kext and
MacKernelSDK, with the build date Lilu's plugin_start.cpp stamps pinned so
the same sources build the same bytes, and writes kext/sources.sha256,
which a test checks the sources against. The built kext holds Lilu's
plugin_start.cpp, so Lilu's BSD-3-Clause license is kept beside ours.
kext/probes/features.m prints what Metal's device answers in a guest.

Moved from reims-vgpu, where it was ec923f9f9, 4a4a882fb and 2e564d3f8 on
steelbrain/x86-metal-lilu.

Checked on msi-laptop (RTX 5080, macOS 26.6.1 guest): the host stores 245
and the desktop comes up; chrome://gpu reports hardware acceleration; a
clear to a D32S8 target that faulted the host completes. ocvalidate
(OpenCore 1.0.8) finds no issues in the image's config.plist, and the
kexts in the image match the built kext and Lilu's release byte for byte.
Not yet booted from a reims-util image.
This commit is contained in:
Anees Iqbal committed 2026-10-13 19:10:51 +03:00
1 parent 5216d98427
commit 5405b2d13b
18 files changed
+945 -19

No files matched your search

+3
View File
@@ -1 +1,4 @@
/target
# The guest kext's objects, when make runs in kext/; the kext itself is kept.
/kext/build/
+8 -3
View File
@@ -19,7 +19,12 @@ OpenCorePkg's macserial (Copyright (c) 2018-2020 vit9696, Copyright (c) 2020
Matis Schotte), so that file is also under OpenCorePkg's BSD-3-Clause license:
LICENSES/BSD-3-Clause-OpenCorePkg.txt.
What reims-util downloads and writes into images, such as OpenCore and OVMF,
is not part of the repository, and keeps its own license; OVMF's licenses are
written beside OVMF_CODE.fd. The crates the build takes from crates.io keep
kext/ReimsVgpu.kext, the kext built from kext/src, also holds code from Lilu
(Copyright (c) 2016-2018 vit9696): its plugin_start.cpp, and what Lilu's
headers define. That code is under Lilu's BSD-3-Clause license:
LICENSES/BSD-3-Clause-Lilu.txt.
What reims-util downloads and writes into images, such as OpenCore, Lilu and
OVMF, is not part of the repository, and keeps its own license; OVMF's
licenses are written beside OVMF_CODE.fd. The crates the build takes from crates.io keep
their own licenses too.
+12
View File
@@ -0,0 +1,12 @@
Copyright (c) 2016-2018, vit9696
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+31 -8
View File
@@ -63,9 +63,9 @@ reims-util opencore -o OpenCore.qcow2
This writes a 128 MiB disk image with OpenCore 1.0.8 on its EFI partition: qcow2 for a `.qcow2`
name, and a raw disk image for anything else (`.img`). Beside it go `OVMF_CODE.fd` and
`OVMF_VARS.fd`, with OVMF's licenses. What goes in them is downloaded from pinned sources
(OpenCore's release and a commit of its picker icons and boot chime, OcBinaryData, from GitHub;
OVMF from Arch Linux's `edk2-ovmf` package), checked against the hashes reims-util knows, and
cached in `~/.cache/reims-util`, so it's only downloaded once.
(OpenCore's release, a commit of its picker icons and boot chime, OcBinaryData, and Lilu's
release, from GitHub; OVMF from Arch Linux's `edk2-ovmf` package), checked against the hashes
reims-util knows, and cached in `~/.cache/reims-util`, so it's only downloaded once.
Each image gets a Mac identity of its own: a serial number, logic board serial (MLB), system UUID
and ROM, which it prints when it's done. Keep them if you'll want the same identity in another
@@ -79,8 +79,13 @@ another with `--model`:
What's in the image, and why:
- **No kexts.** QEMU's `isa-applesmc` is the SMC, and the GPU is reims-vgpu's, which macOS drives
with its own driver.
- **Two kexts, which load on macOS 26 alone**: Lilu, and its plugin ReimsVgpu.kext, from this
repository's `kext/`. macOS drives reims-vgpu's GPU with its own driver, whose x86-64 build
asks the device for an old interface version (6) and turns every later feature off. The kext
has it ask for the one arm64 guests use (245), and patches what the driver and its Metal plugin
hardcode, so Metal offers the GPU families GPU-accelerated Chrome needs, and D32S8
depth/stencil textures. `--no-kexts` leaves them out, and the boot argument `-reimsvgpuoff`
turns the kext off. There are no others: QEMU's `isa-applesmc` is the SMC.
- **The drivers a VM boots with**: OpenRuntime, OpenHfsPlus (recovery images and installers are
HFS+), OpenPartitionDxe (for older recovery images) and ResetNvramEntry.
- **The graphical picker**, OpenCanopy, with the GoldenGate icons. Pick with the arrow keys, Tab
@@ -168,9 +173,27 @@ made) or, for `list`, the versions, or `{"event":"error","message":"…"}`.
reims-util --json online-installer tahoe -o ~/vms/mac
```
## The ReimsVgpu kext
`kext/` holds ReimsVgpu.kext's source. A kext builds on a Mac alone, while reims-util builds
anywhere, so the built kext is in the repository too, at `kext/ReimsVgpu.kext`, and that's the one
reims-util puts in its images. After changing the source, rebuild it on a Mac with Xcode, and
commit it with the change:
```sh
cd kext
make LILU=path/to/Lilu.kext KERNEL_SDK=path/to/MacKernelSDK
```
`LILU` is a DEBUG build of Lilu 1.7.2, the version the image carries, from
[Lilu's releases](https://github.com/acidanthera/Lilu/releases), and `KERNEL_SDK` a checkout of
[MacKernelSDK](https://github.com/acidanthera/MacKernelSDK). With the same Xcode, the same
source builds the same bytes. `make` also writes `kext/sources.sha256`, what the kext was built
from, and `cargo test` fails when the source no longer matches it.
## License
reims-util is licensed under GPL-2.0-or-later OR LGPL-3.0-or-later; see [LICENSE](LICENSE). The
serial number tables come from OpenCorePkg's macserial, under its BSD-3-Clause license.
OpenCore, its picker icons and chime (OcBinaryData) and OVMF, which reims-util downloads, keep
their own licenses.
serial number tables come from OpenCorePkg's macserial, and the built ReimsVgpu.kext holds code
of Lilu's, each under its BSD-3-Clause license. OpenCore, its picker icons and chime
(OcBinaryData), Lilu and OVMF, which reims-util downloads, keep their own licenses.
+73
View File
@@ -0,0 +1,73 @@
# The guest kext: a Lilu plugin that x86-64 macOS guests load through
# OpenCore, beside Lilu, so their AppleParavirtGPU driver negotiates the
# binary version arm64 guests use (src/ReimsVgpu.cpp).
#
# reims-util puts ReimsVgpu.kext in its OpenCore images
# (../src/opencore/mod.rs), and builds anywhere, while the kext builds on a Mac
# alone. So the kext it takes is the one here, built and kept in the
# repository: rebuild it and commit it with any change to its sources.
# sources.sha256 records what it was built from, and reims-util's tests fail
# when that no longer matches.
#
# make LILU=<Lilu.kext> KERNEL_SDK=<MacKernelSDK>
# ReimsVgpu.kext and sources.sha256
# make clean remove build/, the objects
#
# LILU is a DEBUG build of Lilu 1.7.2, whose Contents/Resources holds the
# plugin headers and plugin_start.cpp; the image carries a RELEASE build of the
# same version. KERNEL_SDK is a checkout of acidanthera's MacKernelSDK. Builds
# on a Mac, with Xcode's clang and ld.
LILU ?=
KERNEL_SDK ?=
BUILD = build
NAME = ReimsVgpu
VERSION = 0.1.0
KEXT = $(NAME).kext
BINARY = $(KEXT)/Contents/MacOS/$(NAME)
# The date Lilu's plugin_start.cpp stamps in the kext's version string, from
# __DATE__: fixed, so the same sources build the same bytes.
DATE = 2026-10-13
export SOURCE_DATE_EPOCH := $(shell date -j -u -f '%Y-%m-%d %H:%M:%S' '$(DATE) 00:00:00' +%s)
RESOURCES = $(LILU)/Contents/Resources
FLAGS = -arch x86_64 -mkernel -nostdlib -fno-builtin -fno-stack-protector \
-mno-red-zone -Os -Wall -Wextra -Werror
CXXFLAGS = $(FLAGS) -std=c++17 -fapple-kext -fno-rtti -fno-exceptions \
-DKERNEL -DKERNEL_PRIVATE -DLILU_KEXTPATCH_SUPPORT \
-DPRODUCT_NAME=$(NAME) -DMODULE_VERSION=$(VERSION) \
-isystem $(RESOURCES) -isystem $(KERNEL_SDK)/Headers
OBJECTS = $(BUILD)/obj/$(NAME).o $(BUILD)/obj/UserPatch.o $(BUILD)/obj/plugin_start.o
all: $(BINARY)
check-sdk:
@test -f "$(RESOURCES)/Library/plugin_start.cpp" || \
{ echo "LILU must name a DEBUG Lilu.kext"; exit 1; }
@test -d "$(KERNEL_SDK)/Headers" || \
{ echo "KERNEL_SDK must name a MacKernelSDK checkout"; exit 1; }
$(BUILD)/obj/%.o: src/%.cpp src/UserPatch.hpp Makefile | check-sdk
@mkdir -p $(dir $@)
xcrun clang++ $(CXXFLAGS) -c $< -o $@
$(BUILD)/obj/plugin_start.o: Makefile | check-sdk
@mkdir -p $(dir $@)
xcrun clang++ $(CXXFLAGS) -Wno-unused-parameter \
-c $(RESOURCES)/Library/plugin_start.cpp -o $@
$(BINARY): $(OBJECTS) src/Info.plist
@mkdir -p $(dir $@)
xcrun ld -arch x86_64 -kext -undefined dynamic_lookup $(OBJECTS) -o $@
sed 's/@VERSION@/$(VERSION)/g' src/Info.plist > $(KEXT)/Contents/Info.plist
shasum -a 256 Makefile src/* > sources.sha256
clean:
rm -rf $(BUILD)
.PHONY: all check-sdk clean
+53
View File
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>ReimsVgpu</string>
<key>CFBundleIdentifier</key>
<string>com.steelbrain.ReimsVgpu</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>ReimsVgpu</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>0.1.0</string>
<key>CFBundleVersion</key>
<string>0.1.0</string>
<key>IOKitPersonalities</key>
<dict>
<key>ReimsVgpu</key>
<dict>
<key>CFBundleIdentifier</key>
<string>com.steelbrain.ReimsVgpu</string>
<key>IOClass</key>
<string>ReimsVgpu</string>
<key>IOMatchCategory</key>
<string>ReimsVgpu</string>
<key>IOProviderClass</key>
<string>IOResources</string>
<key>IOResourceMatch</key>
<string>IOKit</string>
</dict>
</dict>
<key>OSBundleLibraries</key>
<dict>
<key>as.vit9696.Lilu</key>
<string>1.7.2</string>
<key>com.apple.kpi.bsd</key>
<string>12.0.0</string>
<key>com.apple.kpi.iokit</key>
<string>12.0.0</string>
<key>com.apple.kpi.libkern</key>
<string>12.0.0</string>
<key>com.apple.kpi.mach</key>
<string>12.0.0</string>
</dict>
<key>OSBundleRequired</key>
<string>Root</string>
</dict>
</plist>
Binary file not shown.
+85
View File
@@ -0,0 +1,85 @@
// Run in the guest: what Metal's device answers, and whether the objects the
// answers promise can be made. Prints one `name value` line each.
//
// xcrun clang -arch x86_64 -fobjc-arc -framework Metal -framework Foundation \
// features.m -o features
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
static void line(const char *name, long long value) { printf("%s %lld\n", name, value); }
int main(void) {
@autoreleasepool {
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
if (!device) { puts("device none"); return 1; }
printf("device %s\n", device.name.UTF8String);
printf("architecture %s\n", device.architecture.name.UTF8String ?: "nil");
const struct { const char *name; MTLGPUFamily family; } families[] = {
{"family.apple1", MTLGPUFamilyApple1}, {"family.apple2", MTLGPUFamilyApple2},
{"family.apple3", MTLGPUFamilyApple3}, {"family.apple4", MTLGPUFamilyApple4},
{"family.apple5", MTLGPUFamilyApple5}, {"family.apple6", MTLGPUFamilyApple6},
{"family.apple7", MTLGPUFamilyApple7}, {"family.apple8", MTLGPUFamilyApple8},
{"family.apple9", MTLGPUFamilyApple9}, {"family.mac2", MTLGPUFamilyMac2},
{"family.common1", MTLGPUFamilyCommon1}, {"family.common2", MTLGPUFamilyCommon2},
{"family.common3", MTLGPUFamilyCommon3}, {"family.metal3", MTLGPUFamilyMetal3},
{"family.metal4", MTLGPUFamilyMetal4},
};
for (size_t i = 0; i < sizeof(families) / sizeof(*families); ++i)
line(families[i].name, [device supportsFamily:families[i].family]);
line("argumentBuffersSupport", device.argumentBuffersSupport);
line("hasUnifiedMemory", device.hasUnifiedMemory);
line("maxBufferLength", (long long)device.maxBufferLength);
line("maxThreadgroupMemoryLength", (long long)device.maxThreadgroupMemoryLength);
line("maxThreadsPerThreadgroup.width", (long long)device.maxThreadsPerThreadgroup.width);
line("recommendedMaxWorkingSetSize", (long long)device.recommendedMaxWorkingSetSize);
line("supportsRaytracing", device.supportsRaytracing);
line("supportsFunctionPointers", device.supportsFunctionPointers);
line("supportsDynamicLibraries", device.supportsDynamicLibraries);
line("supportsRenderDynamicLibraries", device.supportsRenderDynamicLibraries);
line("supports32BitFloatFiltering", device.supports32BitFloatFiltering);
line("supports32BitMSAA", device.supports32BitMSAA);
line("supportsBCTextureCompression", device.supportsBCTextureCompression);
line("supportsPullModelInterpolation", device.supportsPullModelInterpolation);
line("supportsShaderBarycentricCoordinates", device.supportsShaderBarycentricCoordinates);
line("supportsQueryTextureLOD", device.supportsQueryTextureLOD);
line("supportsVertexAmplificationCount2", [device supportsVertexAmplificationCount:2]);
line("supportsRasterizationRateMap1", [device supportsRasterizationRateMapWithLayerCount:1]);
line("programmableSamplePositions", device.programmableSamplePositionsSupported);
line("rasterOrderGroups", device.rasterOrderGroupsSupported);
line("depth24Stencil8", device.depth24Stencil8PixelFormatSupported);
line("readWriteTextureSupport", device.readWriteTextureSupport);
line("sparseTileSizeInBytes", (long long)device.sparseTileSizeInBytes);
line("binaryArchives", [device respondsToSelector:@selector(newBinaryArchiveWithDescriptor:error:)]);
MTLHeapDescriptor *heapDescriptor = [MTLHeapDescriptor new];
heapDescriptor.size = 1 << 20;
heapDescriptor.storageMode = MTLStorageModePrivate;
id<MTLHeap> heap = [device newHeapWithDescriptor:heapDescriptor];
line("make.heap.private", heap != nil);
line("make.heap.private.buffer", [heap newBufferWithLength:4096 options:MTLResourceStorageModePrivate] != nil);
heapDescriptor.storageMode = MTLStorageModeShared;
line("make.heap.shared", [device newHeapWithDescriptor:heapDescriptor] != nil);
MTLIndirectCommandBufferDescriptor *icb = [MTLIndirectCommandBufferDescriptor new];
icb.commandTypes = MTLIndirectCommandTypeDraw;
icb.maxVertexBufferBindCount = 1;
line("make.icb.render", [device newIndirectCommandBufferWithDescriptor:icb maxCommandCount:4 options:0] != nil);
icb.commandTypes = MTLIndirectCommandTypeConcurrentDispatch;
icb.maxKernelBufferBindCount = 1;
line("make.icb.compute", [device newIndirectCommandBufferWithDescriptor:icb maxCommandCount:4 options:0] != nil);
MTLTextureDescriptor *memoryless = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm width:64 height:64 mipmapped:NO];
memoryless.storageMode = MTLStorageModeMemoryless;
memoryless.usage = MTLTextureUsageRenderTarget;
line("make.texture.memoryless", [device newTextureWithDescriptor:memoryless] != nil);
MTLTextureDescriptor *depth = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatDepth32Float_Stencil8 width:64 height:64 mipmapped:NO];
depth.storageMode = MTLStorageModePrivate;
depth.usage = MTLTextureUsageRenderTarget;
line("make.texture.d32s8", [device newTextureWithDescriptor:depth] != nil);
if (@available(macOS 13.0, *)) {
MTLRasterizationRateMapDescriptor *rate = [MTLRasterizationRateMapDescriptor rasterizationRateMapDescriptorWithScreenSize:MTLSizeMake(64, 64, 0)];
line("make.rateMap", [device newRasterizationRateMapWithDescriptor:rate] != nil);
}
}
return 0;
}
+5
View File
@@ -0,0 +1,5 @@
3ec63afddb95abf8466806bbc82f04ce72700c7f10342fa99159aaae6c08a2b8 Makefile
3d8e398c438d167642e4b049c1fd70e21e7d2a6717139137bebbac7644cc8d4c src/Info.plist
f223b598bfde601dac0adb67e005f821ca78d281e56edfee25df06aab5bb9dfa src/ReimsVgpu.cpp
fe381ec5d40012a54dcbcc171a35ed9680650fb7e65334221a45ee80dff74077 src/UserPatch.cpp
d60b1464920b628f5033a9ddd50de385e3d5e2ccdcb83db114ed621944e94402 src/UserPatch.hpp
+53
View File
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>ReimsVgpu</string>
<key>CFBundleIdentifier</key>
<string>com.steelbrain.ReimsVgpu</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>ReimsVgpu</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>@VERSION@</string>
<key>CFBundleVersion</key>
<string>@VERSION@</string>
<key>IOKitPersonalities</key>
<dict>
<key>ReimsVgpu</key>
<dict>
<key>CFBundleIdentifier</key>
<string>com.steelbrain.ReimsVgpu</string>
<key>IOClass</key>
<string>ReimsVgpu</string>
<key>IOMatchCategory</key>
<string>ReimsVgpu</string>
<key>IOProviderClass</key>
<string>IOResources</string>
<key>IOResourceMatch</key>
<string>IOKit</string>
</dict>
</dict>
<key>OSBundleLibraries</key>
<dict>
<key>as.vit9696.Lilu</key>
<string>1.7.2</string>
<key>com.apple.kpi.bsd</key>
<string>12.0.0</string>
<key>com.apple.kpi.iokit</key>
<string>12.0.0</string>
<key>com.apple.kpi.libkern</key>
<string>12.0.0</string>
<key>com.apple.kpi.mach</key>
<string>12.0.0</string>
</dict>
<key>OSBundleRequired</key>
<string>Root</string>
</dict>
</plist>
+221
View File
@@ -0,0 +1,221 @@
// ReimsVgpu: a Lilu plugin for x86-64 macOS guests of reims-vgpu.
//
// The x86-64 AppleParavirtGPU.kext asks the device for binary version 6 and
// knows no later one: its setupVersion clamps to 6 and leaves every later
// feature off. arm64 guests ask for 245, the highest version the host knows
// (crates/reims-vgpu-core/src/guest/abi/features.rs in reims-vgpu). This
// plugin has the x86-64 driver ask for 245 too, and keeps the driver's own
// negotiation for a host that does not store it. What the x86-64 driver and
// its Metal plugin lack to run at 245, or hardcode where the arm64 ones ask
// the device, is patched here too: two-plane textures added as type 12, and
// the plugin's bytes (UserPatch).
//
// The offsets are AppleParavirtAccelerator's in macOS 26's x86-64 driver, read
// from its setupVersion: the device's registers at 0xe28, the negotiated
// version at 0xf48, and the 60 bytes of guest features after it, laid out as
// reims-vgpu-core's GuestFeatures.
#include <Headers/kern_api.hpp>
#include <Headers/plugin_start.hpp>
#include "UserPatch.hpp"
namespace {
// The Metal plugin (AppleParavirtGPUMetal) is a userspace binary the x86-64
// guest's frameworks load. The x86-64 build hardcodes answers the arm64 build
// derives from the device, so the fixes below live in its bytes, patched for
// every process through UserPatch (Lilu's own user patcher is off on Tahoe).
const char *metalPlugin =
"/System/Library/Extensions/AppleParavirtGPUMetal.bundle/Contents/MacOS/AppleParavirtGPUMetal";
// -[AppleParavirtDevice featureProfile] returns 10000 (0x2710), whose families
// are Common1 and Common2. The arm64 plugin returns 10001 on a host GPU of no
// Apple family, adding Mac2 and Common3, which ANGLE's Metal backend (so a
// GPU-accelerated Chrome) needs. The method is `mov eax, 0x2710; pop rbp; ret`;
// 0x2710 becomes 0x2711. x86-64 guests run on hosts of no Apple family.
const uint8_t featureProfileFind[] {0x55, 0x48, 0x89, 0xe5, 0xb8, 0x10, 0x27, 0x00, 0x00, 0x5d, 0xc3};
const uint8_t featureProfileReplace[] {0x55, 0x48, 0x89, 0xe5, 0xb8, 0x11, 0x27, 0x00, 0x00, 0x5d, 0xc3};
// -[AppleParavirtTexture initTiledWithBuffer:descriptor:offset:bytesPerRow:] refuses a tiled,
// buffer-backed texture whose allocation size, every row counted at its full bytesPerRow stride,
// is larger than the buffer: it logs "Alloc size: %llu larger than provided buffer: %llu" and
// returns nil. SkyLight makes such textures for a window wider than two tiles, and the bytes the
// texture reads all fit, its last row ending at its width, not a full stride (arm64's plugin
// sidesteps this with private textures). The guard is `callq *r13; cmpq rax, r15; jbe ok` --
// continue when the allocation (r15) is within the buffer (rax); forcing the branch (`jbe` 0x76
// to `jmp` 0xeb) builds the texture always, and the host accepts it from its real footprint
// (crates/reims-vgpu-core/src/resources/texture/dimension.rs in reims-vgpu). On a page of its
// own, apart from featureProfile's.
const uint8_t tiledBoundsFind[] {0x4c, 0x89, 0xe7, 0x4c, 0x89, 0xf6, 0x41, 0xff, 0xd5,
0x49, 0x39, 0xc7, 0x76, 0x4e};
const uint8_t tiledBoundsReplace[] {0x4c, 0x89, 0xe7, 0x4c, 0x89, 0xf6, 0x41, 0xff, 0xd5,
0x49, 0x39, 0xc7, 0xeb, 0x4e};
UserPatch::Patch pluginPatches[] {
{metalPlugin, featureProfileFind, featureProfileReplace, sizeof(featureProfileFind)},
{metalPlugin, tiledBoundsFind, tiledBoundsReplace, sizeof(tiledBoundsFind)},
};
constexpr size_t RegistersOffset = 0xe28;
constexpr size_t VersionOffset = 0xf48;
constexpr size_t FeaturesOffset = 0xf4c;
// The binary version register.
constexpr size_t VersionRegister = 0x34;
constexpr uint32_t Version = 245;
// features_for_version(245).to_bytes(): every feature, 64 FIFOs and one byte
// of stencil for D32S8.
constexpr uint8_t Features[60] = {
1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // valid, unsupported, ...
1, 0, 0, 0, // buffer_from_io_surface, padding
64, 0, 0, 0, // max_fifo_count
1, 0, 0, 0, // s8_byte_count_for_d32s8
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // supports_shared_textures, ...
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // ..., supports_multiple_displays
};
mach_vm_address_t originalSetupVersion;
// AppleParavirtAccelerator::setupVersion. A host that stores 245 gets the
// features of 245; any other answer goes back to the driver's negotiation,
// which writes its own version again.
void setupVersion(void *accelerator) {
auto state = static_cast<uint8_t *>(accelerator);
auto registers = *reinterpret_cast<volatile uint32_t **>(state + RegistersOffset);
registers[VersionRegister / 4] = Version;
if (registers[VersionRegister / 4] != Version) {
SYSLOG("version", "the host did not store version %u", Version);
FunctionCast(setupVersion, originalSetupVersion)(accelerator);
return;
}
*reinterpret_cast<uint32_t *>(state + VersionOffset) = Version;
memcpy(state + FeaturesOffset, Features, sizeof(Features));
DBGLOG("version", "negotiated version %u", Version);
}
// The object types of a texture over a descriptor: one plane, and two. From
// version 31 the plugin lays out D32S8 and X32S8 as two planes, as the host
// does, but the x86-64 driver knows object types up to 7 and adds every such
// texture as type 2, which the host reads as one plane. arm64 guests add a
// two-plane texture as type 12.
constexpr uint32_t ObjectTexture = 2;
constexpr uint32_t ObjectTwoPlaneTexture = 12;
// A texture's record: 12 bytes of the object's own, then each plane's 0x18-byte
// dimension header (its low 14 bits the mip count) and 0x24 bytes per mip,
// then the descriptor command, whose type is 1 or 52.
constexpr size_t RecordHeader = 12;
constexpr size_t PlaneHeader = 0x18;
constexpr size_t MipRecord = 0x24;
uint16_t readU16(const uint8_t *record, size_t offset) {
uint16_t value;
memcpy(&value, record + offset, sizeof(value));
return value;
}
bool isDescriptorCommand(const uint8_t *record, size_t length, size_t offset) {
if (offset + sizeof(uint32_t) > length) return false;
uint32_t type;
memcpy(&type, record + offset, sizeof(type));
return type == 1 || type == 52;
}
mach_vm_address_t originalAddObject;
// AppleParavirtResourceHeap::addObject. A type-2 texture whose record holds two
// planes of the same mip count before its descriptor command is added as type
// 12; every other object as the driver asked.
void *addObject(void *heap, uint32_t type, uint32_t index, uint32_t length, const void *data) {
auto record = static_cast<const uint8_t *>(data);
if (type == ObjectTexture && record && length >= RecordHeader + PlaneHeader) {
uint16_t bits = readU16(record, RecordHeader);
size_t plane = PlaneHeader + (bits & 0x3fff) * MipRecord;
if (!isDescriptorCommand(record, length, RecordHeader + plane) &&
isDescriptorCommand(record, length, RecordHeader + 2 * plane) &&
(readU16(record, RecordHeader + plane) & 0x3fff) == (bits & 0x3fff)) {
type = ObjectTwoPlaneTexture;
}
}
return FunctionCast(addObject, originalAddObject)(heap, type, index, length, data);
}
const char *driverPaths[] {
"/System/Library/Extensions/AppleParavirtGPU.kext/Contents/MacOS/AppleParavirtGPU",
};
KernelPatcher::KextInfo driver {
"com.apple.driver.AppleParavirtGPU", driverPaths, arrsize(driverPaths), {true}, {},
KernelPatcher::KextInfo::Unloaded,
};
void driverLoaded(void *, KernelPatcher &patcher, size_t index, mach_vm_address_t address,
size_t size) {
if (index != driver.loadIndex) return;
KernelPatcher::RouteRequest requests[] {
{"__ZN24AppleParavirtAccelerator12setupVersionEv", setupVersion, originalSetupVersion},
{"__ZN25AppleParavirtResourceHeap9addObjectE13APVObjectTypejjPKv", addObject,
originalAddObject},
};
if (!patcher.routeMultiple(index, requests, arrsize(requests), address, size)) {
SYSLOG("version", "cannot route the driver: %d", patcher.getError());
patcher.clearError();
}
// The GPU kext loads after the root filesystem is mounted and before any
// userspace Metal client loads the plugin, so read the plugin and arm the
// patches here (`onPatcherLoad` is too early to read /System).
UserPatch::load(pluginPatches, arrsize(pluginPatches));
}
// Publishes the user patcher's counters on the kext's IOService every few
// seconds, for `ioreg -c ReimsVgpu`: Lilu shows no plugin log on Tahoe.
thread_call_t statusCall;
void publishStatus(thread_call_param_t, thread_call_param_t) {
uint32_t routed = 0, located = 0, calls = 0, patched = 0;
UserPatch::status(routed, located, calls, patched);
if (auto service = ADDPR(selfInstance)) {
service->setProperty("UserPatchRouted", routed, 32);
service->setProperty("UserPatchLocated", located, 32);
service->setProperty("UserPatchValidateCalls", calls, 32);
service->setProperty("UserPatchPagesPatched", patched, 32);
}
uint64_t deadline;
clock_interval_to_deadline(5, kSecondScale, &deadline);
thread_call_enter_delayed(statusCall, deadline);
}
void patcherLoaded(void *, KernelPatcher &patcher) {
statusCall = thread_call_allocate(publishStatus, nullptr);
if (statusCall) {
publishStatus(nullptr, nullptr);
}
// Route code-signing validation early, before any binary is validated; the
// hook stays inert until driverLoaded arms it.
UserPatch::route(patcher);
}
void start() {
lilu.onPatcherLoadForce(patcherLoaded);
lilu.onKextLoadForce(&driver, 1, driverLoaded);
}
const char *bootArgsOff[] {"-reimsvgpuoff"};
const char *bootArgsDebug[] {"-reimsvgpudbg"};
} // namespace
PluginConfiguration ADDPR(config) {
xStringify(PRODUCT_NAME),
parseModuleVersion(xStringify(MODULE_VERSION)),
LiluAPI::AllowNormal,
bootArgsOff, arrsize(bootArgsOff),
bootArgsDebug, arrsize(bootArgsDebug),
nullptr, 0,
KernelVersion::Tahoe, KernelVersion::Tahoe,
start,
};
extern "C" kern_return_t ADDPR(kern_start)(kmod_info_t *, void *);
extern "C" kern_return_t ADDPR(kern_stop)(kmod_info_t *, void *);
KMOD_EXPLICIT_DECL(com.steelbrain.ReimsVgpu, xStringify(MODULE_VERSION), ADDPR(kern_start), ADDPR(kern_stop))
+190
View File
@@ -0,0 +1,190 @@
#include "UserPatch.hpp"
#include <Headers/kern_file.hpp>
#include <Headers/kern_mach.hpp>
#include <Headers/kern_util.hpp>
#include <mach/memory_object_types.h>
namespace UserPatch {
// The x86-64 guest's page is 4 KiB; the pristine page store is sized for it.
static constexpr size_t PageSize = 4096;
static constexpr size_t MaxPagePatches = 8;
static constexpr size_t ReplaceMax = 64;
// The fast reject reads this many bytes of the pattern; patterns are longer.
static constexpr size_t CheckLength = 8;
// A located patch: the file page that holds the pattern, kept whole so a page
// is patched only when its entire content still matches the file.
struct PagePatch {
const char *path;
size_t pageBase;
uint8_t pristine[PageSize];
uint32_t pageLength;
uint32_t patchOffset;
uint8_t replace[ReplaceMax];
uint32_t replaceLength;
};
static PagePatch pagePatches[MaxPagePatches];
static size_t pagePatchCount;
static bool armed;
static mach_vm_address_t orgCsValidatePage;
// Counters published on the IORegistry by [`status`], readable with `ioreg`
// as any user: Lilu writes its debug dump only while its own user patcher is
// active, which it never is on Tahoe, so SYSLOG output is not visible there.
static volatile uint32_t validateCalls;
static volatile uint32_t pagesPatched;
static int routeError = -1;
static const uint8_t *search(const uint8_t *hay, size_t n, const uint8_t *needle, size_t m) {
if (m == 0 || n < m) {
return nullptr;
}
for (size_t i = 0; i + m <= n; i++) {
if (memcmp(hay + i, needle, m) == 0) {
return hay + i;
}
}
return nullptr;
}
// Patch a just-validated page whose whole content still matches a target file
// page. Runs after the kernel has validated the pristine bytes.
static void apply(const uint8_t *page) {
for (size_t i = 0; i < pagePatchCount; i++) {
auto &pp = pagePatches[i];
if (memcmp(page + pp.patchOffset, pp.pristine + pp.patchOffset, CheckLength) != 0) {
continue;
}
if (memcmp(page, pp.pristine, pp.pageLength) != 0) {
continue;
}
if (MachInfo::setKernelWriting(true, KernelPatcher::kernelWriteLock) == KERN_SUCCESS) {
memcpy(const_cast<uint8_t *>(page) + pp.patchOffset, pp.replace, pp.replaceLength);
MachInfo::setKernelWriting(false, KernelPatcher::kernelWriteLock);
pagesPatched = pagesPatched + 1;
}
}
}
// The page fault path (vm_page_validate_cs_mapped_slow) validates one page at
// a time through cs_validate_page, which reports through its out-parameters:
// `validated` and `tainted` are nonzero masks of the page's 4 KiB chunks.
static void csValidatePage(vnode_t vp, memory_object_t pager, memory_object_offset_t page_offset,
const void *data, int *validated, int *tainted, int *nx) {
FunctionCast(csValidatePage, orgCsValidatePage)(vp, pager, page_offset, data, validated,
tainted, nx);
validateCalls = validateCalls + 1;
if (armed && *validated && !*tainted) {
apply(static_cast<const uint8_t *>(data));
}
}
void route(KernelPatcher &patcher) {
KernelPatcher::RouteRequest request {"_cs_validate_page", csValidatePage, orgCsValidatePage};
if (!patcher.routeMultipleLong(KernelPatcher::KernelID, &request, 1)) {
routeError = static_cast<int>(patcher.getError());
SYSLOG("userpatch", "cannot route _cs_validate_page: %d", routeError);
patcher.clearError();
} else {
routeError = 0;
}
}
void status(uint32_t &routed, uint32_t &located, uint32_t &calls, uint32_t &patched) {
routed = static_cast<uint32_t>(routeError);
located = static_cast<uint32_t>(pagePatchCount);
calls = validateCalls;
patched = pagesPatched;
}
static bool samePage(const char *path, size_t pageBase) {
for (size_t i = 0; i < pagePatchCount; i++) {
if (pagePatches[i].pageBase == pageBase && strcmp(pagePatches[i].path, path) == 0) {
return true;
}
}
return false;
}
static bool locate(const Patch &patch) {
if (patch.length < CheckLength || patch.length > ReplaceMax) {
SYSLOG("userpatch", "patch of %s has unusable length %zu", patch.path, patch.length);
return false;
}
size_t fileSize = 0;
auto buffer = FileIO::readFileToBuffer(patch.path, fileSize);
if (!buffer) {
SYSLOG("userpatch", "cannot read %s", patch.path);
return false;
}
bool located = false;
vm_address_t segment = 0, section = 0;
void *text = nullptr;
size_t textSize = 0;
MachInfo::findSectionBounds(buffer, fileSize, segment, section, text, textSize,
"__TEXT", "__text", CPU_TYPE_X86_64);
if (text && textSize) {
auto textEnd = static_cast<uint8_t *>(text) + textSize;
auto hit = search(static_cast<uint8_t *>(text), textSize, patch.find, patch.length);
auto after = hit ? search(hit + 1, static_cast<size_t>(textEnd - (hit + 1)),
patch.find, patch.length)
: nullptr;
if (!hit) {
SYSLOG("userpatch", "pattern not found in %s", patch.path);
} else if (after) {
SYSLOG("userpatch", "pattern not unique in %s", patch.path);
} else {
size_t fileOffset = static_cast<size_t>(hit - buffer);
size_t pageBase = fileOffset & ~(PageSize - 1);
size_t inPage = fileOffset - pageBase;
if (inPage + patch.length > PageSize) {
SYSLOG("userpatch", "pattern spans a page in %s", patch.path);
} else if (pagePatchCount >= MaxPagePatches) {
SYSLOG("userpatch", "too many page patches");
} else if (samePage(patch.path, pageBase)) {
// A page is patched only while it matches its file page whole,
// so a second patch of a patched page would never apply.
SYSLOG("userpatch", "a second patch of one page in %s", patch.path);
} else {
auto &pp = pagePatches[pagePatchCount];
pp.path = patch.path;
pp.pageBase = pageBase;
size_t pageLength = fileSize - pageBase;
if (pageLength > PageSize) {
pageLength = PageSize;
}
memset(pp.pristine, 0, PageSize);
memcpy(pp.pristine, buffer + pageBase, pageLength);
pp.pageLength = static_cast<uint32_t>(pageLength);
pp.patchOffset = static_cast<uint32_t>(inPage);
memcpy(pp.replace, patch.replace, patch.length);
pp.replaceLength = static_cast<uint32_t>(patch.length);
pagePatchCount++;
located = true;
SYSLOG("userpatch", "located %s at file offset %zu", patch.path, fileOffset);
}
}
} else {
SYSLOG("userpatch", "no __text in %s", patch.path);
}
Buffer::deleter(buffer);
return located;
}
void load(const Patch *patches, size_t count) {
if (PAGE_SIZE != PageSize) {
SYSLOG("userpatch", "unexpected page size %u", static_cast<unsigned>(PAGE_SIZE));
return;
}
for (size_t i = 0; i < count; i++) {
locate(patches[i]);
}
armed = pagePatchCount != 0;
SYSLOG("userpatch", "armed %zu page patch(es)", pagePatchCount);
}
} // namespace UserPatch
+63
View File
@@ -0,0 +1,63 @@
//
// UserPatch: patch bytes of an on-disk userspace binary, for every process
// that loads it, from the kext.
//
// Lilu's own user patcher is disabled on macOS 11 and later
// (kern_start.cpp: `isUserDisabled |= getKernelVersion() >= BigSur`), so a
// Lilu plugin cannot patch a userspace binary through `onProcLoad` there. The
// x86-64 AppleParavirtGPUMetal plugin hardcodes answers the arm64 plugin
// derives from the device, such as the GPU families its feature profile
// names, and those answers are the only place some fixes can live. This
// patches them.
//
// The mechanism is the one Lilu used before it gave up on userspace patching:
// route code signing's page validation, let the kernel validate the pristine
// page against its signature, and only then overwrite the bytes in that page.
// Since macOS 11 a page fault validates through `_cs_validate_page`, one page
// at a time; `_cs_validate_range`, which Lilu routed, does not see a binary's
// pages faulted in (measured on macOS 26.6.1's x86-64 kernel). The
// hash check has already passed on the unmodified bytes, so code signing does
// not notice; each time the page is re-read from the file and re-validated it
// is patched again. A patch applies only to a page whose whole content matches
// the target file's page, so no other binary is touched.
//
// Routing and loading are split: the validation hook goes in early
// (`onPatcherLoad`, before any userspace binary is validated), while the
// patterns are read from disk later (`onKextLoad`, once /System is mounted),
// because the plugin's pages must not be validated before the hook is live.
//
#ifndef ReimsVgpu_UserPatch_hpp
#define ReimsVgpu_UserPatch_hpp
#include <Headers/kern_patcher.hpp>
namespace UserPatch {
/// One find/replace in a file's `__TEXT,__text`. `find` must occur exactly
/// once there and within a single page, a page no other patch touches;
/// `replace` is the same length.
struct Patch {
const char *path;
const uint8_t *find;
const uint8_t *replace;
size_t length;
};
/// Routes `_cs_validate_page`. Call early (from `onPatcherLoad`), before any
/// target binary is validated. The hook does nothing until [`load`] runs.
void route(KernelPatcher &patcher);
/// Reads each patch's file and locates its pattern, arming the hook. Call once
/// the root filesystem is mounted (from an `onKextLoad` callback). A patch
/// whose file or pattern cannot be resolved is logged and skipped.
void load(const Patch *patches, size_t count);
/// The patcher's state: the routing result (0 routed, -1 not tried, else the
/// patcher's error), how many patches were located, how many times the
/// validation hook ran, and how many pages it patched.
void status(uint32_t &routed, uint32_t &located, uint32_t &calls, uint32_t &patched);
} // namespace UserPatch
#endif /* ReimsVgpu_UserPatch_hpp */
+1 -1
View File
@@ -1,4 +1,4 @@
//! Files fetched once and kept: the OpenCore release, OcBinaryData and the OVMF package, each
//! Files fetched once and kept: the OpenCore release, OcBinaryData, Lilu and the OVMF package, each
//! pinned to its SHA-256, under `$XDG_CACHE_HOME/reims-util` (`~/.cache/reims-util`).
use crate::http::{self, Dest, Download, NoCheck};
+5
View File
@@ -104,6 +104,10 @@ pub struct OpencoreArgs {
/// Use OpenCore's text picker instead of the graphical one
#[arg(long)]
pub text_picker: bool,
/// Leave out Lilu and ReimsVgpu.kext, so macOS 26 drives reims-vgpu's GPU with its driver as
/// it is
#[arg(long)]
pub no_kexts: bool,
/// Write no OVMF files
#[arg(long)]
pub no_ovmf: bool,
@@ -338,6 +342,7 @@ pub fn opencore_options(a: &OpencoreArgs) -> Result<opencore::Options> {
cpuid_spoof: !a.no_cpuid_spoof,
hide_vm: !a.show_vm,
graphical_picker: !a.text_picker,
kexts: !a.no_kexts,
},
ovmf_dir,
})
+49 -3
View File
@@ -11,8 +11,9 @@
//! picker, when asked for);
//! - the boot chime, which AudioDxe plays on the first Intel HDA controller and codec it finds,
//! when the VM has one, unless macOS's "Play sound on startup" is off (`StartupMute`);
//! - no kexts: QEMU's `isa-applesmc` is the SMC, and the GPU is reims-vgpu's, which macOS drives
//! with its own driver;
//! - on macOS 26, two kexts: Lilu, and its plugin ReimsVgpu (kext/), which has macOS's own driver
//! for reims-vgpu's GPU negotiate the interface version arm64 guests use, and patches what the
//! x86-64 driver and its Metal plugin hardcode; no others, as QEMU's `isa-applesmc` is the SMC;
//! - one ACPI table, the `EC` and `USBX` devices macOS looks for (acpi.rs);
//! - CPUID leaf 1 reported as a Skylake-SP (family 6, model 85, stepping 4), a CPU every x86-64
//! macOS from 10.13 to 26 knows, whatever `-cpu` model the VM has;
@@ -43,6 +44,28 @@ pub fn drivers(o: &Options) -> Vec<&'static str> {
d
}
/// A kext the image carries in `EFI/OC/Kexts`: its bundle, and the executable in its
/// `Contents/MacOS`.
pub struct Kext {
pub bundle: &'static str,
pub executable: &'static str,
}
pub const LILU: Kext = Kext {
bundle: "Lilu.kext",
executable: "Lilu",
};
/// Lilu's plugin, built from kext/.
pub const REIMS_VGPU: Kext = Kext {
bundle: "ReimsVgpu.kext",
executable: "ReimsVgpu",
};
/// The kexts load on Darwin 25 alone, macOS 26, whose GPU driver ReimsVgpu patches.
const KEXT_MIN_KERNEL: &str = "25.0.0";
const KEXT_MAX_KERNEL: &str = "25.99.99";
/// Arguments for every boot: kernel symbols in panic logs, and no panics on a TLB shootdown or a
/// timeout a vCPU took because the host descheduled it.
pub const DEFAULT_BOOT_ARGS: &str = "keepsyms=1 tlbto_us=0 vti=9";
@@ -63,6 +86,8 @@ pub struct Options {
pub hide_vm: bool,
/// OpenCanopy's graphical picker, or OpenCore's text one.
pub graphical_picker: bool,
/// Lilu and ReimsVgpu, for macOS 26.
pub kexts: bool,
}
pub fn make(sample: &[u8], o: &Options) -> Result<Vec<u8>> {
@@ -109,7 +134,28 @@ pub fn make(sample: &[u8], o: &Options) -> Result<Vec<u8>> {
Value::Dictionary(Dictionary::new()),
)?;
set(c, &["Kernel"], "Add", Value::Array(vec![]))?;
let mut kexts = Vec::new();
if o.kexts {
for (k, comment) in [
(LILU, "Patch engine"),
(REIMS_VGPU, "reims-vgpu's GPU features on macOS 26"),
] {
let mut e = template(c, &["Kernel", "Add"])?;
e.insert("Arch".into(), "x86_64".into());
e.insert("BundlePath".into(), k.bundle.into());
e.insert("Comment".into(), comment.into());
e.insert("Enabled".into(), true.into());
e.insert(
"ExecutablePath".into(),
format!("Contents/MacOS/{}", k.executable).into(),
);
e.insert("MaxKernel".into(), KEXT_MAX_KERNEL.into());
e.insert("MinKernel".into(), KEXT_MIN_KERNEL.into());
e.insert("PlistPath".into(), "Contents/Info.plist".into());
kexts.push(Value::Dictionary(e));
}
}
set(c, &["Kernel"], "Add", Value::Array(kexts))?;
set(c, &["Kernel"], "Block", Value::Array(vec![]))?;
set(c, &["Kernel"], "Force", Value::Array(vec![]))?;
let (data, mask) = if o.cpuid_spoof {
+92 -4
View File
@@ -1,8 +1,8 @@
//! The OpenCore boot image: a 128 MiB GPT disk whose EFI system partition holds a pinned
//! OpenCore release, the drivers and ACPI table a VM needs, the picker's icons and the boot chime
//! from a pinned commit of OcBinaryData, and a `config.plist` made for a q35 VM (config.rs) with
//! an SMBIOS identity of its own (smbios.rs). OVMF goes beside it (ovmf.rs), where reims-ctl looks
//! for it.
//! from a pinned commit of OcBinaryData, a pinned Lilu release and its plugin ReimsVgpu.kext
//! (kext/), and a `config.plist` made for a q35 VM (config.rs) with an SMBIOS identity of its own
//! (smbios.rs). OVMF goes beside it (ovmf.rs), where reims-ctl looks for it.
pub mod acpi;
pub mod config;
@@ -38,6 +38,19 @@ const RESOURCES_ROOT: &str = "OcBinaryData-32500d5e3313f11cad00351ba1c6f9a4aa6cb
/// The boot chime, the image's only sound.
const CHIME: &str = "Audio/OCEFIAudio_VoiceOver_Boot.mp3";
/// Lilu, the release ReimsVgpu.kext is built against (kext/Makefile).
const LILU_RELEASE: Pinned = Pinned {
name: "Lilu-1.7.2-RELEASE.zip",
url: "https://github.com/acidanthera/Lilu/releases/download/1.7.2/Lilu-1.7.2-RELEASE.zip",
sha256: "53967d7dcfaab01023a33df2e969a89522f13d6654a6a56ac4711b62dabf3ab8",
what: "Lilu 1.7.2",
};
/// ReimsVgpu.kext as kext/Makefile built it, on a Mac, into the repository.
const REIMS_VGPU_PLIST: &[u8] = include_bytes!("../../kext/ReimsVgpu.kext/Contents/Info.plist");
const REIMS_VGPU_EXECUTABLE: &[u8] =
include_bytes!("../../kext/ReimsVgpu.kext/Contents/MacOS/ReimsVgpu");
/// The image's size: room for OpenCore (about 2 MiB of it here) and for what a person may add.
const DISK_SIZE: u64 = 128 << 20;
@@ -63,9 +76,19 @@ pub fn build(o: &Options, r: &dyn Reporter) -> Result<Outputs> {
progress::check(r)?;
let resources_path = cache::fetch(&RESOURCES, r)?;
progress::check(r)?;
let lilu_path = if o.config.kexts {
let p = cache::fetch(&LILU_RELEASE, r)?;
progress::check(r)?;
Some(p)
} else {
None
};
r.step(&format!("Building the OpenCore {VERSION} image"));
let mut files = files(&zip_path, &o.config)?;
files.extend(resources(&resources_path, o.config.graphical_picker)?);
if let Some(p) = &lilu_path {
files.extend(kexts(p)?);
}
let files: Vec<(String, Data)> = files
.into_iter()
.map(|(p, d)| (p, Data::Bytes(d)))
@@ -132,13 +155,46 @@ fn files(zip_path: &Path, c: &config::Options) -> Result<Vec<(String, Vec<u8>)>>
format!("EFI/OC/ACPI/{}", acpi::FILE_NAME),
acpi::ssdt_ec_usbx(),
));
// The release's other folders, empty, for what a person adds.
// The release's other folders, for what a person adds.
for d in ["EFI/OC/Kexts/", "EFI/OC/Resources/", "EFI/OC/Tools/"] {
files.push((d.to_string(), Vec::new()));
}
Ok(files)
}
/// The kexts' files: Lilu's from its release, and ReimsVgpu's.
fn kexts(lilu_zip: &Path) -> Result<Vec<(String, Vec<u8>)>> {
use config::{LILU, REIMS_VGPU};
let f =
std::fs::File::open(lilu_zip).with_context(|| format!("open {}", lilu_zip.display()))?;
let mut zip = zip::ZipArchive::new(f).context("read Lilu's release")?;
let mut files = Vec::new();
for p in [
"Contents/Info.plist".to_string(),
format!("Contents/MacOS/{}", LILU.executable),
] {
let name = format!("{}/{p}", LILU.bundle);
let mut e = zip
.by_name(&name)
.with_context(|| format!("Lilu's release has no {name}"))?;
let mut v = Vec::new();
e.read_to_end(&mut v)?;
files.push((format!("EFI/OC/Kexts/{name}"), v));
}
files.push((
format!("EFI/OC/Kexts/{}/Contents/Info.plist", REIMS_VGPU.bundle),
REIMS_VGPU_PLIST.to_vec(),
));
files.push((
format!(
"EFI/OC/Kexts/{}/Contents/MacOS/{}",
REIMS_VGPU.bundle, REIMS_VGPU.executable
),
REIMS_VGPU_EXECUTABLE.to_vec(),
));
Ok(files)
}
/// The resources the image carries, from OcBinaryData's archive.
fn resources(zip_path: &Path, graphical: bool) -> Result<Vec<(String, Vec<u8>)>> {
let f =
@@ -184,6 +240,38 @@ fn resource_path(name: &str, graphical: bool) -> Option<String> {
mod tests {
use super::*;
/// kext/ReimsVgpu.kext is built from the sources beside it: kext/sources.sha256, which
/// kext/Makefile writes with the kext, names each of them with its SHA-256 now.
#[test]
fn reims_vgpu_built_from_its_sources() {
let rebuild = "run make in kext/ on a Mac, and commit ReimsVgpu.kext and sources.sha256";
let kext = Path::new(env!("CARGO_MANIFEST_DIR")).join("kext");
let manifest = std::fs::read_to_string(kext.join("sources.sha256")).unwrap();
let mut built = Vec::new();
for line in manifest.lines() {
let (sha256, name) = line.split_once(" ").unwrap();
let now = crate::http::sha256_file(&kext.join(name)).unwrap();
assert_eq!(
now, sha256,
"kext/{name} changed since the kext was built: {rebuild}"
);
built.push(name.to_string());
}
let mut sources = vec!["Makefile".to_string()];
for e in std::fs::read_dir(kext.join("src")).unwrap() {
let name = e.unwrap().file_name().to_string_lossy().into_owned();
if !name.starts_with('.') {
sources.push(format!("src/{name}"));
}
}
built.sort();
sources.sort();
assert_eq!(
built, sources,
"the kext was built from other files: {rebuild}"
);
}
#[test]
fn resources_taken() {
let at = |rel: &str| format!("{RESOURCES_ROOT}{rel}");
+1
View File
@@ -271,6 +271,7 @@ impl App {
no_cpuid_spoof: false,
show_vm: !form.toggle(5),
text_picker: !form.toggle(7),
no_kexts: false,
no_ovmf: !form.toggle(3),
ovmf_dir: None,
};