Files

137 lines
5.8 KiB
Python

#!/usr/bin/env python3
"""Build a separate Reims OpenCore image with FileVault input support."""
import argparse
import hashlib
import json
from pathlib import Path
import plistlib
import struct
import subprocess
from tempfile import TemporaryDirectory
from uuid import UUID
from zipfile import ZipFile
from pyfatfs.PyFatFS import PyFatFS
OPENCORE_SHA256 = "2011e8b7216ecb2645d97ea710df965947edd406846e92050b9bc4190be6d27b"
ESP_TYPE = UUID("c12a7328-f81f-11d2-ba4b-00a0c93ec93b").bytes_le
OPENCORE_TREE = "X64/EFI/OC"
CONFIG = "EFI/OC/config.plist"
def run(*command, capture=False):
return subprocess.run(command, check=True, timeout=60, stdout=subprocess.PIPE if capture else None).stdout
def esp_offset(image):
with image.open("rb") as disk:
disk.seek(512)
header = disk.read(512)
table, count, entry_size = struct.unpack_from("<QII", header, 72)
if header[:8] != b"EFI PART" or not 0 < count <= 128 or entry_size != 128:
raise ValueError("unexpected OpenCore GPT layout")
disk.seek(table * 512)
for _ in range(count):
entry = disk.read(entry_size)
if entry[:16] == ESP_TYPE:
return struct.unpack_from("<Q", entry, 32)[0] * 512
raise ValueError("OpenCore EFI system partition not found")
def build_tablet(args, temporary):
edk = args.edk2 / "MdePkg/Include"
oc = args.opencore_source / "Include"
source = Path(__file__).with_name("ReimsTablet.c")
obj = temporary / "ReimsTablet.obj"
driver = temporary / "ReimsTablet.efi"
run(
args.clang, "--target=x86_64-pc-windows-msvc", "-std=c17", "-ffreestanding",
"-fshort-wchar", "-mno-red-zone", "-fno-stack-protector", "-O2",
"-I", edk, "-I", edk / "X64", "-I", oc, "-I", oc / "Apple", "-I", oc / "Generic",
"-c", source, "-o", obj,
)
run(args.lld_link, "/subsystem:efi_boot_service_driver", "/entry:DriverEntry",
"/nodefaultlib", f"/out:{driver}", obj)
return driver.read_bytes()
def add_driver(volume, drivers, name, binary):
path = f"EFI/OC/Drivers/{name}"
entry = next((item for item in drivers if item["Path"].casefold() == name.casefold()), None)
if entry is None:
drivers.append(dict(Arguments="", Comment="", Enabled=True, HideVerbose=False,
LoadEarly=False, Path=name))
else:
entry["Enabled"] = True
if volume.exists(path):
if volume.readbytes(path) == binary:
return
volume.remove(path)
volume.writebytes(path, binary)
def build_image(args, temporary):
image = temporary / "opencore.raw"
output = temporary / "opencore.qcow2"
info = json.loads(run(args.qemu_img, "info", "--output=json", "-f", "qcow2", args.image,
capture=True))
if info["virtual-size"] != 128 << 20 or "backing-filename" in info:
raise ValueError("expected a standalone 128 MiB reims-util OpenCore QCOW2 image")
with args.opencore_zip.open("rb") as archive:
if hashlib.file_digest(archive, "sha256").hexdigest() != OPENCORE_SHA256:
raise ValueError("expected the pinned OpenCore 1.0.8 release ZIP")
run(args.qemu_img, "convert", "-f", "qcow2", "-O", "raw", args.image, image)
with ZipFile(args.opencore_zip) as release:
with PyFatFS(str(image), offset=esp_offset(image)) as volume:
if volume.readbytes("EFI/OC/OpenCore.efi") != release.read(f"{OPENCORE_TREE}/OpenCore.efi"):
raise ValueError("input image must use the OpenCore 1.0.8 release")
original = volume.readbytes(CONFIG)
config = plistlib.loads(original)
uefi = config["UEFI"]
add_driver(volume, uefi["Drivers"], "ReimsTablet.efi", build_tablet(args, temporary))
add_driver(volume, uefi["Drivers"], "OpenUsbKbDxe.efi",
release.read(f"{OPENCORE_TREE}/Drivers/OpenUsbKbDxe.efi"))
uefi["Input"]["KeySupport"] = False
updated = plistlib.dumps(config, sort_keys=False)
if updated != original:
volume.remove(CONFIG)
volume.writebytes(CONFIG, updated)
(temporary / "config.plist").write_bytes(volume.readbytes(CONFIG))
validator = temporary / "ocvalidate.exe"
validator.write_bytes(release.read("Utilities/ocvalidate/ocvalidate.exe"))
run(validator, temporary / "config.plist")
run(args.qemu_img, "convert", "-f", "raw", "-O", "qcow2", image, output)
run(args.qemu_img, "check", output)
output.rename(args.output) # On Windows this refuses to replace an existing file.
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--image", type=Path, required=True, help="existing, stopped VM's opencore.qcow2")
parser.add_argument("--output", type=Path, required=True, help="new QCOW2 path")
parser.add_argument("--qemu-img", required=True, help="qemu-img.exe from the portable runtime")
parser.add_argument("--opencore-zip", type=Path, required=True, help="OpenCore 1.0.8 release ZIP")
parser.add_argument("--opencore-source", type=Path, required=True, help="OpenCorePkg 1.0.8 checkout")
parser.add_argument("--edk2", type=Path, required=True, help="edk2-stable202608 checkout")
parser.add_argument("--clang", default="clang", help="clang executable")
parser.add_argument("--lld-link", default="lld-link", help="lld-link executable")
args = parser.parse_args()
args.output = args.output.resolve()
if args.output.exists():
parser.error("output already exists")
try:
with TemporaryDirectory(prefix="reims-filevault-", dir=args.output.parent) as temporary:
build_image(args, Path(temporary))
except (OSError, ValueError, subprocess.SubprocessError) as exc:
parser.exit(1, f"{exc}\n")
print(args.output)
if __name__ == "__main__":
main()