fix(opencore): support FileVault mouse and keypad input
This commit is contained in:
1 parent
5c71ac8482
commit
5e67d50012
3 files changed
+362
No files matched your search
@@ -0,0 +1,31 @@
|
||||
# FileVault 开机输入
|
||||
|
||||
在 Windows x64 上,带 FileVault 的 Intel macOS 虚拟机会先进入由 OpenCore 支持的开机解锁界面。此处的输入由固件处理。脚本为使用 OpenCore 1.0.8 的 Reims x86-64 虚拟机生成一份新的启动镜像。应用仍使用原有的 QEMU USB 平板和键盘。
|
||||
|
||||
- 鼠标按虚拟平板的绝对坐标定位,可移动光标并点击。
|
||||
- 小键盘数字在 FileVault 解锁时可直接输入。使用 OpenCore 的 `OpenUsbKbDxe.efi` 并关闭通用 `KeySupport`,避免两个键盘驱动同时处理输入。
|
||||
|
||||
## 生成和使用
|
||||
|
||||
使用 Windows 上的 Python 3.11 或更新版本、Clang、`lld-link` 和便携运行时的 `qemu-img.exe`。将虚拟机正常关机。以下示例从本仓库根目录运行,`$vmDir` 是虚拟机目录,`$runtimeDir` 是便携运行时目录,`$depsDir` 是存放依赖的目录。
|
||||
|
||||
```powershell
|
||||
python -m pip install pyfatfs==1.1.0
|
||||
git clone --depth 1 --branch 1.0.8 https://github.com/acidanthera/OpenCorePkg.git "$depsDir\OpenCorePkg"
|
||||
git clone --depth 1 --filter=blob:none --sparse --branch edk2-stable202608 https://github.com/tianocore/edk2.git "$depsDir\edk2"
|
||||
git -C "$depsDir\edk2" sparse-checkout set MdePkg/Include
|
||||
```
|
||||
|
||||
`$openCoreZip` 指向缓存中的 `OpenCore-1.0.8-RELEASE.zip`,也可以从 [OpenCore 1.0.8 发布页](https://github.com/acidanthera/OpenCorePkg/releases/tag/1.0.8)下载。以下命令保留原镜像并校验新镜像。
|
||||
|
||||
```powershell
|
||||
python scripts/filevault-input/build-image.py --image "$vmDir\opencore.qcow2" --output "$vmDir\opencore-filevault.qcow2" --qemu-img "$runtimeDir\qemu\bin\qemu-img.exe" --opencore-zip $openCoreZip --opencore-source "$depsDir\OpenCorePkg" --edk2 "$depsDir\edk2"
|
||||
```
|
||||
|
||||
停机时用新镜像替换启动镜像并保留回退文件。确保备份名尚未使用。
|
||||
|
||||
```powershell
|
||||
[IO.File]::Replace("$vmDir\opencore-filevault.qcow2", "$vmDir\opencore.qcow2", "$vmDir\opencore-before-filevault.qcow2")
|
||||
```
|
||||
|
||||
要回退,在停机后将备份恢复为 `opencore.qcow2`。使用应用的「重建 OpenCore」后,需要对重建后的镜像重新运行此脚本。
|
||||
@@ -0,0 +1,195 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
#include <Uefi.h>
|
||||
#include <Protocol/GraphicsOutput.h>
|
||||
#include <Protocol/SimplePointer.h>
|
||||
#include <Protocol/UsbIo.h>
|
||||
#include <Apple/Guid/AppleVariable.h>
|
||||
#include <Apple/Protocol/AppleEvent.h>
|
||||
|
||||
// QEMU's full- and high-speed usb-tablet descriptors use the same input endpoint.
|
||||
#define TABLET_ENDPOINT (USB_ENDPOINT_DIR_IN | 1)
|
||||
#define TABLET_PACKET_SIZE 8
|
||||
#define TABLET_MAX 32767
|
||||
#define REPORT_COUNT 32
|
||||
|
||||
typedef struct {
|
||||
UINT16 X;
|
||||
UINT16 Y;
|
||||
UINT8 Buttons;
|
||||
} TABLET_REPORT;
|
||||
|
||||
STATIC EFI_SYSTEM_TABLE *System;
|
||||
STATIC EFI_GUID UsbIoGuid = EFI_USB_IO_PROTOCOL_GUID;
|
||||
STATIC EFI_GUID GraphicsGuid = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
|
||||
STATIC EFI_GUID EventGuid = APPLE_EVENT_PROTOCOL_GUID;
|
||||
STATIC EFI_GUID PointerGuid = EFI_SIMPLE_POINTER_PROTOCOL_GUID;
|
||||
STATIC EFI_GUID AppleVendorGuid = APPLE_VENDOR_VARIABLE_GUID;
|
||||
STATIC EFI_USB_IO_PROTOCOL *Tablet;
|
||||
STATIC TABLET_REPORT Reports[REPORT_COUNT];
|
||||
STATIC UINTN Head, Tail;
|
||||
|
||||
STATIC EFI_STATUS EFIAPI TabletInput(VOID *Data, UINTN Length, VOID *Context,
|
||||
UINT32 Status) {
|
||||
if (Status != EFI_USB_NOERROR || Length < 5) {
|
||||
return EFI_DEVICE_ERROR;
|
||||
}
|
||||
UINTN Next = (Head + 1) % REPORT_COUNT;
|
||||
if (Next == Tail) {
|
||||
Tail = (Tail + 1) % REPORT_COUNT;
|
||||
}
|
||||
CONST UINT8 *Bytes = Data;
|
||||
Reports[Head].X = (UINT16)((UINT16)Bytes[1] | ((UINT16)Bytes[2] << 8));
|
||||
Reports[Head].Y = (UINT16)((UINT16)Bytes[3] | ((UINT16)Bytes[4] << 8));
|
||||
Reports[Head].Buttons = Bytes[0];
|
||||
Head = Next;
|
||||
return EFI_SUCCESS;
|
||||
}
|
||||
|
||||
STATIC BOOLEAN Attach(EFI_USB_IO_PROTOCOL *Usb) {
|
||||
EFI_USB_DEVICE_DESCRIPTOR Device;
|
||||
EFI_USB_INTERFACE_DESCRIPTOR Interface;
|
||||
if (EFI_ERROR(Usb->UsbGetDeviceDescriptor(Usb, &Device)) ||
|
||||
Device.IdVendor != 0x0627 || Device.IdProduct != 0x0001 ||
|
||||
EFI_ERROR(Usb->UsbGetInterfaceDescriptor(Usb, &Interface)) ||
|
||||
Interface.InterfaceClass != 3 || Interface.InterfaceSubClass != 0 ||
|
||||
Interface.InterfaceProtocol != 0) {
|
||||
return FALSE;
|
||||
}
|
||||
if (EFI_ERROR(Usb->UsbAsyncInterruptTransfer(
|
||||
Usb, TABLET_ENDPOINT, TRUE, 10, TABLET_PACKET_SIZE, TabletInput, NULL))) {
|
||||
return FALSE;
|
||||
}
|
||||
Tablet = Usb;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
STATIC VOID EFIAPI FindTablet(EFI_EVENT Event, VOID *Context) {
|
||||
EFI_BOOT_SERVICES *Boot = System->BootServices;
|
||||
EFI_HANDLE *Handles;
|
||||
UINTN Count;
|
||||
if (EFI_ERROR(Boot->LocateHandleBuffer(
|
||||
ByProtocol, &UsbIoGuid, NULL, &Count, &Handles))) {
|
||||
return;
|
||||
}
|
||||
for (UINTN Index = 0; Index < Count; ++Index) {
|
||||
EFI_USB_IO_PROTOCOL *Usb;
|
||||
if (!EFI_ERROR(Boot->HandleProtocol(Handles[Index], &UsbIoGuid,
|
||||
(VOID **)&Usb)) &&
|
||||
Attach(Usb)) {
|
||||
Boot->CloseEvent(Event);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Boot->FreePool(Handles);
|
||||
}
|
||||
|
||||
STATIC VOID EFIAPI StopTablet(EFI_EVENT Event, VOID *Context) {
|
||||
if (Tablet != NULL) {
|
||||
Tablet->UsbAsyncInterruptTransfer(
|
||||
Tablet, TABLET_ENDPOINT, FALSE, 0, 0, NULL, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
STATIC EFI_STATUS EFIAPI Reset(EFI_SIMPLE_POINTER_PROTOCOL *This,
|
||||
BOOLEAN Extended) {
|
||||
Head = Tail = 0;
|
||||
return EFI_SUCCESS;
|
||||
}
|
||||
|
||||
STATIC VOID EFIAPI WaitForInput(EFI_EVENT Event, VOID *Context) {
|
||||
if (Head != Tail) {
|
||||
System->BootServices->SignalEvent(Event);
|
||||
}
|
||||
}
|
||||
|
||||
STATIC INT32 TabletPixel(UINT16 Position, UINT32 Extent) {
|
||||
UINT32 Coordinate = Position < TABLET_MAX ? Position : TABLET_MAX;
|
||||
return (INT32)((Coordinate * (Extent - 1) + TABLET_MAX / 2) / TABLET_MAX);
|
||||
}
|
||||
|
||||
STATIC EFI_STATUS EFIAPI ReadPointer(EFI_SIMPLE_POINTER_PROTOCOL *This,
|
||||
EFI_SIMPLE_POINTER_STATE *State) {
|
||||
if (Head == Tail) {
|
||||
return EFI_NOT_READY;
|
||||
}
|
||||
EFI_BOOT_SERVICES *Boot = System->BootServices;
|
||||
APPLE_EVENT_PROTOCOL *AppleEvent;
|
||||
EFI_GRAPHICS_OUTPUT_PROTOCOL *Graphics;
|
||||
if (EFI_ERROR(Boot->LocateProtocol(&EventGuid, NULL, (VOID **)&AppleEvent)) ||
|
||||
EFI_ERROR(Boot->HandleProtocol(System->ConsoleOutHandle, &GraphicsGuid,
|
||||
(VOID **)&Graphics))) {
|
||||
return EFI_NOT_READY;
|
||||
}
|
||||
EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Mode = Graphics->Mode->Info;
|
||||
TABLET_REPORT Report = Reports[Tail];
|
||||
Tail = (Tail + 1) % REPORT_COUNT;
|
||||
DIMENSION Position = {
|
||||
TabletPixel(Report.X, Mode->HorizontalResolution),
|
||||
TabletPixel(Report.Y, Mode->VerticalResolution)
|
||||
};
|
||||
|
||||
// OpenCore's Simple Pointer adapter emits a motion event only for changed
|
||||
// coordinates. Anchor one UI-scaled pixel-step away from the exact target
|
||||
// and return the compensating unit step. Button events use the final target.
|
||||
UINT8 Scale = 1;
|
||||
UINTN Size = sizeof(Scale);
|
||||
if (EFI_ERROR(System->RuntimeServices->GetVariable(
|
||||
APPLE_UI_SCALE_VARIABLE_NAME, &AppleVendorGuid, NULL, &Size, &Scale)) ||
|
||||
Scale != 2) {
|
||||
Scale = 1;
|
||||
}
|
||||
INT32 Step = Position.Horizontal >= Scale ? 1 : -1;
|
||||
Position.Horizontal -= Step * Scale;
|
||||
EFI_STATUS Status = AppleEvent->SetCursorPosition(&Position);
|
||||
if (EFI_ERROR(Status)) {
|
||||
return Status;
|
||||
}
|
||||
|
||||
State->RelativeMovementX = Step;
|
||||
State->RelativeMovementY = 0;
|
||||
State->RelativeMovementZ = 0;
|
||||
State->LeftButton = (Report.Buttons & 1) != 0;
|
||||
State->RightButton = (Report.Buttons & 2) != 0;
|
||||
return EFI_SUCCESS;
|
||||
}
|
||||
|
||||
STATIC EFI_SIMPLE_POINTER_MODE PointerMode = { 1, 1, 1, TRUE, TRUE };
|
||||
STATIC EFI_SIMPLE_POINTER_PROTOCOL Pointer = {
|
||||
Reset, ReadPointer, NULL, &PointerMode
|
||||
};
|
||||
|
||||
EFI_STATUS EFIAPI DriverEntry(EFI_HANDLE Image, EFI_SYSTEM_TABLE *Table) {
|
||||
System = Table;
|
||||
EFI_BOOT_SERVICES *Boot = Table->BootServices;
|
||||
EFI_STATUS Status = Boot->CreateEvent(EVT_NOTIFY_WAIT, TPL_NOTIFY,
|
||||
WaitForInput, NULL, &Pointer.WaitForInput);
|
||||
if (EFI_ERROR(Status)) {
|
||||
return Status;
|
||||
}
|
||||
EFI_EVENT AttachTimer;
|
||||
Status = Boot->CreateEvent(EVT_TIMER | EVT_NOTIFY_SIGNAL, TPL_CALLBACK,
|
||||
FindTablet, NULL, &AttachTimer);
|
||||
if (EFI_ERROR(Status)) {
|
||||
goto CloseInput;
|
||||
}
|
||||
EFI_EVENT ExitEvent;
|
||||
Status = Boot->CreateEvent(EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY,
|
||||
StopTablet, NULL, &ExitEvent);
|
||||
if (EFI_ERROR(Status)) {
|
||||
goto CloseTimer;
|
||||
}
|
||||
EFI_HANDLE Handle = NULL;
|
||||
Status = Boot->InstallProtocolInterface(&Handle, &PointerGuid,
|
||||
EFI_NATIVE_INTERFACE, &Pointer);
|
||||
if (!EFI_ERROR(Status)) {
|
||||
Boot->SetTimer(AttachTimer, TimerPeriodic, 1000000);
|
||||
return EFI_SUCCESS;
|
||||
}
|
||||
Boot->CloseEvent(ExitEvent);
|
||||
CloseTimer:
|
||||
Boot->CloseEvent(AttachTimer);
|
||||
CloseInput:
|
||||
Boot->CloseEvent(Pointer.WaitForInput);
|
||||
return Status;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
#!/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()
|
||||
Reference in new issue
Block a user