Files
reims-vgpu/guest/loader/tools/gen-shims.py
T
Anees Iqbal 29378fdecf 🆕 Bring the ReimsGraphics loader and its shim tools into guest/
OpenCore links injected kexts against the Boot kernel collection only, and
ReimsGraphics uses IOGraphicsFamily and AppleGraphicsDeviceControl from the
System collection, so it loads through a Lilu plugin that binds it there.
That loader and the tools that generate its shims and tables lived outside
the repo, built with the x86-64 port's kexts as further consumers. Linux
hosts cannot build guest/, so the set reims-ctl carries into images has to
be built from this repo alone.

guest/loader is the loader trimmed to ReimsGraphics as its only consumer:
the route that bound the port's GPU and display kexts behind Apple's driver,
the port's Metal-bundle patch and the legacy route are gone, and the bundle,
its IDs, boot arguments and the shims' IDs are renamed, ReimsGraphicsLoader
and com.steelbrain.*, so an old image's loader cannot be taken for it.
tools/macho.py replaces the Mach-O reader the tools imported from another
repo; for ReimsGraphics ef90881e it gives the original tools' fixup table
byte for byte, but for the shims' IDs, and the same tables. README.md says
where each file came from.
2026-11-05 22:55:45 -08:00

232 lines
9.0 KiB
Python

#!/usr/bin/env python3
"""Generate and build a consumer kext's shims (README.md): one data-only
x86_64 kext per System KC library the consumer links against, which
OpenCore links the consumer against in the Boot KC in that library's place.
python3 -I -B tools/gen-shims.py CONSUMER LIBRARY... --out DIR [--prefix NAME]
CONSUMER is the consumer's executable, each LIBRARY a library's binary in
the KDK (only read). For each library, the shim exports a placeholder for
every symbol of it that bridge.py finds the consumer naming, and nothing
else that a C++ name could collide with:
- a function: a 16-byte stub at a 16-byte boundary, ud2 first, so a site
the loader missed traps instead of running on;
- a superclass's `gMetaClass`, or a class's `metaClass` pointer (which
OSDynamicCast names): zeroes, as many bytes as the library's own symbol
spans (up to its next symbol);
- a superclass's vtable (`__ZTV`): zeroes, as many as the library's own, at
least 24. OpenCore counts a dependency's vtable entries up to the first
zero word (Vtables.c:151-176 in OpenCorePkg 1.0.8), so a zero vtable has
none, and the subclass's patch loop (Vtables.c:424) leaves every slot to
be resolved by name.
Any other data symbol is refused: what OpenCore makes of a placeholder for
it is not measured.
A shim has no constructor, no OSMetaClass and no personality: it never
defines a class or starts. Its bundle ID is `com.steelbrain.<prefix><Binary>Bridge`,
its libraries com.apple.kpi.libkern and com.apple.kpi.mach, and it carries
OSBundleCompatibleVersion, which OpenCore requires of a library. --prefix is
the consumer's own name, so its shims cannot stand in for another kext's.
Writes under DIR (build output, never committed): `<prefix><Binary>Bridge.kext`,
built with Xcode's clang and ld from the generated `src/<prefix><Binary>Bridge.c`,
and `fixups.json`, bridge.py's table, each site with the offset of the
placeholder it must hold in its shim once OpenCore has linked the consumer
(the loader checks that before it writes the library's real address), and
`consumer_sha256`, the SHA-256 of the consumer it was made from, so the next
steps refuse a consumer the table does not describe. Checks that each shim
exports exactly its placeholders and `_kmod_info`. Ours. Run with `python3 -I`.
"""
import argparse
import hashlib
import json
import os
import plistlib
import re
import shutil
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bridge # noqa: E402
STUB = 16
VTABLE_MIN = 24
# A class's OSMetaClass object and its pointer to it, by their mangled tails.
METACLASS_DATA = ("10gMetaClassE", "9metaClassE")
PREFIX = "com.steelbrain."
CFLAGS = ["-arch", "x86_64", "-mkernel", "-nostdlib", "-fno-builtin",
"-fno-stack-protector", "-mno-red-zone", "-Os", "-Wall", "-Wextra",
"-Werror", "-DKERNEL", "-DKERNEL_PRIVATE", "-ffreestanding", "-fno-common"]
def run(cmd):
out = subprocess.run(cmd, capture_output=True, text=True)
if out.returncode != 0:
raise SystemExit(f"{' '.join(cmd)}: exit {out.returncode}\n{out.stderr}")
return out.stdout
def data_sizes(sl, names):
"""Each named data symbol's span in the library: up to its section's
next symbol."""
spans = {}
for value, end, name in bridge.Ranges(sl).rows:
if name in names:
spans[name] = end - value
missing = names - spans.keys()
if missing:
raise SystemExit(f"no span for {sorted(missing)}")
return spans
def asm_name(name):
return name if re.fullmatch(r"[A-Za-z0-9_.$]+", name) else f'"{name}"'
def source(shim, functions, data, sizes):
"""The shim's C source: its placeholders in one asm block, then kmod_info."""
out = [
f"// {shim}: generated by guest/loader/tools/gen-shims.py; do not edit.",
"// Placeholders only: no class, no constructor.",
"",
"#include <mach/mach_types.h>",
"#include <libkern/OSKextLib.h>",
"",
"__asm__(",
' ".section __TEXT,__text\\n"',
]
for name in functions:
out += [f' ".p2align 4\\n"',
f' ".globl {asm_name(name)}\\n"',
f' "{asm_name(name)}:\\n"',
f' " ud2\\n"',
f' " .space {STUB - 2}\\n"']
out += [' ".section __DATA,__data\\n"']
for name in data:
size = sizes[name]
if name.startswith("__ZTV"):
size = max(size, VTABLE_MIN)
out += [f' ".p2align 3\\n"',
f' ".globl {asm_name(name)}\\n"',
f' "{asm_name(name)}:\\n"',
f' " .space {size}\\n"']
out += [
");",
"",
f"static kern_return_t {shim}_start(kmod_info_t *ki, void *d)",
"{",
" (void)ki;",
" (void)d;",
" return KERN_SUCCESS;",
"}",
"",
f"static kern_return_t {shim}_stop(kmod_info_t *ki, void *d)",
"{",
" (void)ki;",
" (void)d;",
" return KERN_SUCCESS;",
"}",
"",
f'KMOD_EXPLICIT_DECL({PREFIX}{shim}, "1.0.0", {shim}_start, {shim}_stop)',
"",
]
return "\n".join(out)
def info_plist(shim):
return {
"CFBundleDevelopmentRegion": "en",
"CFBundleExecutable": shim,
"CFBundleIdentifier": PREFIX + shim,
"CFBundleInfoDictionaryVersion": "6.0",
"CFBundleName": shim,
"CFBundlePackageType": "KEXT",
"CFBundleShortVersionString": "1.0.0",
"CFBundleVersion": "1.0.0",
"OSBundleCompatibleVersion": "1.0.0",
"OSBundleLibraries": {"com.apple.kpi.libkern": "8.0.0",
"com.apple.kpi.mach": "8.0.0"},
"OSBundleRequired": "Root",
}
def exports(binary):
"""The shim's external defined symbols: name -> value."""
out = {}
for line in run(["nm", "-g", "-U", "-arch", "x86_64", binary]).splitlines():
value, _, name = line.split(maxsplit=2)
out[name] = int(value, 16)
return out
def build(out, shim, src_text, sdk):
src = os.path.join(out, "src", shim + ".c")
obj = os.path.join(out, "src", shim + ".o")
kext = os.path.join(out, shim + ".kext")
binary = os.path.join(kext, "Contents", "MacOS", shim)
with open(src, "w") as f:
f.write(src_text)
shutil.rmtree(kext, ignore_errors=True)
os.makedirs(os.path.dirname(binary))
run(["xcrun", "clang", *CFLAGS, "-isysroot", sdk, "-c", src, "-o", obj])
run(["xcrun", "ld", "-arch", "x86_64", "-kext", "-undefined", "dynamic_lookup",
obj, "-o", binary])
with open(os.path.join(kext, "Contents", "Info.plist"), "wb") as f:
plistlib.dump(info_plist(shim), f)
return binary
def main(argv):
ap = argparse.ArgumentParser()
ap.add_argument("consumer")
ap.add_argument("libraries", nargs="+")
ap.add_argument("--out", required=True)
ap.add_argument("--prefix", default="")
a = ap.parse_args(argv[1:])
os.makedirs(os.path.join(a.out, "src"), exist_ok=True)
sdk = run(["xcrun", "--sdk", "macosx", "--show-sdk-path"]).strip()
providers = bridge.analyze(a.consumer, a.libraries)
placeholders, binaries, failed = {}, {}, False
for p in providers:
shim = a.prefix + p.name + "Bridge"
binaries[p.library] = a.prefix + p.name
functions = sorted(p.symbols("function"))
data = sorted(p.symbols("data"))
odd = [d for d in data if not (d.startswith("__ZTV") or d.endswith(METACLASS_DATA))]
if odd:
raise SystemExit(f"{p.name}: data symbols that are neither a vtable, a gMetaClass "
f"nor a metaClass, which a shim has no rule for: {odd}")
sizes = data_sizes(p.sl, set(data))
if any(size <= 0 for size in sizes.values()):
raise SystemExit(f"{p.name}: empty data placeholder")
binary = build(a.out, shim, source(shim, functions, data, sizes), sdk)
got = exports(binary)
want = set(functions) | set(data) | {"_kmod_info"}
if set(got) != want:
print(f"{shim}: exports differ: missing {sorted(want - set(got))[:5]}, "
f"extra {sorted(set(got) - want)[:5]}", file=sys.stderr)
failed = True
placeholders[p.library] = (PREFIX + shim, {n: got[n] for n in functions + data})
vt = [d for d in data if d.startswith("__ZTV")]
print(f"{shim}.kext: {PREFIX + shim} for {p.library}: {len(functions)} functions, "
f"{len(data)} data ({len(vt)} vtables, "
f"{min(max(sizes[v], VTABLE_MIN) for v in vt) if vt else 0}+ bytes of zeroes)")
table = bridge.table(a.consumer, providers, placeholders, binaries)
with open(a.consumer, "rb") as f:
table["consumer_sha256"] = hashlib.sha256(f.read()).hexdigest()
with open(os.path.join(a.out, "fixups.json"), "w") as f:
json.dump(table, f, indent=1)
f.write("\n")
n = sum(len(p.sites) for p in providers)
print(f"fixups: {n} sites into {len(providers)} shims: {a.out}/fixups.json")
if failed:
raise SystemExit("gen-shims: FAILED")
if __name__ == "__main__":
main(sys.argv)