Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d69ec2c353 | ||
|
|
263148e1fe | ||
|
|
8a09a1f02f | ||
|
|
c2443b576e | ||
|
|
fba39e78f6 |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
target/
|
||||
/runs/
|
||||
Generated
+193
@@ -0,0 +1,193 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85c097ce94629611e0a15ef1078a2fe2ce3b4a0f4b44708e85eeb09dd5f188eb"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c7a9e344b352bef7873e51ff425c2f90d5aa2a252db2b84289c93ff30beb3d7"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0571a23d2188b4aae7adc1df454cc81d6232cf37674fa717ac119f6c74d0dc1"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76a5cf9d05ffa9c878c447b33b069605e890ebcd36d2761f86367873c2ecaa7f"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c2d00c1b2d84cef823d89d4da02ad8ff1e76c969e029da990b40f16dc834221"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.105"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902"
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"strsim",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f7f11958434c85b6efac08f8299dc08bd263184ce080232e2168940cda4368e"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "reims-openvmm-x86"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.101.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.101.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "reims-openvmm-x86"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.85"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
@@ -1,2 +1,31 @@
|
||||
# -Name-reims-openvmm-x86-Description-OpenVMM-backend-for-Intel-macOS-guests-on-Windows-x86-64-.Name
|
||||
@{Name=reims-openvmm-x86; Description=OpenVMM backend for Intel macOS guests on Windows x86-64}.Description
|
||||
# Reims OpenVMM x86 boot probe
|
||||
|
||||
This Windows x64 probe starts OpenVMM through WHP, boots a supplied UEFI disk,
|
||||
and records the COM1 output. It includes:
|
||||
|
||||
- `oc-shim`: UEFI pre-OpenCore shim (`reims-oc-shim.efi`) installed at `\EFI\BOOT\BOOTX64.EFI` to supply a valid ESP `BlockIo`+`FilePath` device path for in-memory `gBS->LoadImage` calls so `SecurityStubDxe` accepts `OpenRuntime.efi` under OpenVMM/Patina DXE Core.
|
||||
- `nvram-probe`: UEFI Runtime Services & disk probe (`reims-nvram-probe.efi`) verifying `gRT->GetTime`, `gRT->SetVariable` / `GetVariable` persistence (`NV|BS|RT`) across cold OpenVMM restarts with `--vmgs`, read-only NVMe disk sector verification, and clean `ResetSystem(SHUTDOWN)`.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Windows x64 with Windows Hypervisor Platform already enabled.
|
||||
- OpenVMM x86_64 binary (`6575a1e6a854ec4193c90c4f416419b6e55bdce5` or `codex/reims-openvmm`).
|
||||
- `MSVM.fd` from the x64 Microsoft `mu_msvm` firmware package (`963a3c9fed47e227a6aeb7aac3e9e4ff3b9ebde0`).
|
||||
- Rust and Cargo (`x86_64-unknown-uefi` target for building `oc-shim` and `nvram-probe`).
|
||||
|
||||
## Build UEFI Shims & Host Harness
|
||||
|
||||
```powershell
|
||||
cargo build --locked --release
|
||||
cargo +1.99.1 build --manifest-path oc-shim/Cargo.toml --target x86_64-unknown-uefi --release
|
||||
cargo +1.99.1 build --manifest-path nvram-probe/Cargo.toml --target x86_64-unknown-uefi --release
|
||||
```
|
||||
|
||||
## Verified Bringup Stages
|
||||
|
||||
1. **OpenCore 1.0.8 DEBUG + `OpenRuntime.efi`**:
|
||||
- Placing `reims-oc-shim.efi` at `\EFI\BOOT\BOOTX64.EFI` and chaining `\EFI\OC\OpenCore.efi` resolves the `SecurityStubDxe` `File == NULL` `EFI_INVALID_PARAMETER` rejection for memory-loaded `OpenRuntime.efi`.
|
||||
- Serial log reaches `OCABC: Got rendezvous with OpenRuntime r12`, `OCABC: MAT support is 1`, `OC: Driver OpenRuntime.efi at 0 is successfully loaded!`, and `OpenCore Boot Menu (DBG-108-2026-09-27)`.
|
||||
2. **UEFI Runtime Services + `--vmgs` Persistence + NVMe Readback**:
|
||||
- First boot with `--vmgs file:<path>;create=VMGS_DEFAULT,fmt-on-fail` writes `ReimsNvramProbe` (`NV|BS|RT`), reads attached read-only NVMe GPT sectors (`REIMS_DISK_CHECK|time_ok=true|disks=2|sector_tag_ok=true`), and cleanly shuts down (`rc=0`).
|
||||
- Second cold boot with `--vmgs file:<path>` reads back matching variable bytes/attributes (`REIMS_RT_VERIFY=OK`) and OpenCore + `OpenRuntime.efi` initializes cleanly alongside the persisted VMGS.
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Build an EFI marker app and place it on a disposable FAT16 ESP disk image."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
SECTOR = 512
|
||||
PARTITION_START = 2048
|
||||
PARTITION_SECTORS = 32768
|
||||
FAT_SECTORS = 128
|
||||
ROOT_ENTRIES = 512
|
||||
|
||||
|
||||
def make_disk(efi_name, program):
|
||||
image = bytearray((PARTITION_START + PARTITION_SECTORS) * SECTOR)
|
||||
struct.pack_into("<B3sB3sII", image, 446, 0, b"\xfe\xff\xff", 0xEF,
|
||||
b"\xfe\xff\xff", PARTITION_START, PARTITION_SECTORS)
|
||||
image[510:512] = b"\x55\xaa"
|
||||
|
||||
volume = memoryview(image)[PARTITION_START * SECTOR:]
|
||||
volume[:11] = b"\xeb\x3c\x90MSDOS5.0"
|
||||
struct.pack_into("<HBHBHHBHHHII", volume, 11, SECTOR, 1, 1, 2, ROOT_ENTRIES,
|
||||
PARTITION_SECTORS, 0xF8, FAT_SECTORS, 63, 255, PARTITION_START, 0)
|
||||
struct.pack_into("<BBBI11s8s", volume, 36, 0x80, 0, 0x29, 0x5245494D,
|
||||
b"REIMS EFI ", b"FAT16 ")
|
||||
volume[510:512] = b"\x55\xaa"
|
||||
|
||||
fat = bytearray(FAT_SECTORS * SECTOR)
|
||||
struct.pack_into("<HHHH", fat, 0, 0xFFF8, 0xFFFF, 0xFFFF, 0xFFFF)
|
||||
cluster_count = (len(program) + SECTOR - 1) // SECTOR
|
||||
for cluster in range(4, 4 + cluster_count):
|
||||
following = cluster + 1 if cluster < 3 + cluster_count else 0xFFFF
|
||||
struct.pack_into("<H", fat, cluster * 2, following)
|
||||
|
||||
first_fat = SECTOR
|
||||
second_fat = first_fat + len(fat)
|
||||
root = second_fat + len(fat)
|
||||
data = root + ROOT_ENTRIES * 32
|
||||
volume[first_fat:second_fat] = fat
|
||||
volume[second_fat:root] = fat
|
||||
|
||||
def entry(directory, index, name, attributes, cluster, size=0):
|
||||
struct.pack_into("<11sB14xHI", volume, directory + index * 32,
|
||||
name, attributes, cluster, size)
|
||||
|
||||
entry(root, 0, b"EFI ", 0x10, 2)
|
||||
entry(data, 0, b". ", 0x10, 2)
|
||||
entry(data, 1, b".. ", 0x10, 0)
|
||||
entry(data, 2, b"BOOT ", 0x10, 3)
|
||||
entry(data + SECTOR, 0, b". ", 0x10, 3)
|
||||
entry(data + SECTOR, 1, b".. ", 0x10, 2)
|
||||
entry(data + SECTOR, 2, efi_name, 0x20, 4, len(program))
|
||||
volume[data + 2 * SECTOR:data + 2 * SECTOR + len(program)] = program
|
||||
return image
|
||||
|
||||
|
||||
def find_compiler(arch):
|
||||
installer = Path(os.environ["ProgramFiles(x86)"]) / "Microsoft Visual Studio" / "Installer"
|
||||
result = subprocess.check_output([
|
||||
installer / "vswhere.exe", "-products", "*", "-latest", "-find",
|
||||
f"VC\\Tools\\MSVC\\**\\bin\\Hostx64\\{arch}\\cl.exe",
|
||||
], text=True).strip()
|
||||
if not result:
|
||||
raise RuntimeError(f"Visual Studio has no {arch} C compiler")
|
||||
return Path(result.splitlines()[0])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("output", type=Path)
|
||||
parser.add_argument("--arch", choices=("x64", "arm64"), default="x64")
|
||||
parser.add_argument("--compiler", type=Path)
|
||||
args = parser.parse_args()
|
||||
compiler = args.compiler or find_compiler(args.arch)
|
||||
source = Path(__file__).with_name("marker.c").resolve()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
work = Path(temp)
|
||||
subprocess.run([compiler, "/nologo", "/c", "/GS-", "/Zl", "/WX", "/W4",
|
||||
"/Fomarker.obj", source], check=True, cwd=work)
|
||||
subprocess.run([compiler.with_name("link.exe"), "/nologo", "/nodefaultlib",
|
||||
"/subsystem:efi_application", "/entry:efi_main", "/machine:" + args.arch,
|
||||
"/out:marker.efi", "marker.obj"], check=True, cwd=work)
|
||||
program = (work / "marker.efi").read_bytes()
|
||||
|
||||
efi_name = b"BOOTX64 EFI" if args.arch == "x64" else b"BOOTAA64EFI"
|
||||
with args.output.open("xb") as disk:
|
||||
disk.write(make_disk(efi_name, program))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,28 @@
|
||||
/* Minimal UEFI application for exercising firmware and serial I/O. */
|
||||
typedef unsigned long long EfiStatus;
|
||||
typedef struct TextOutput TextOutput;
|
||||
|
||||
struct TextOutput {
|
||||
void *reset;
|
||||
EfiStatus (*write)(TextOutput *, const unsigned short *);
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
unsigned char table_header[24];
|
||||
void *firmware_vendor;
|
||||
unsigned int firmware_revision;
|
||||
void *console_in_handle;
|
||||
void *console_in;
|
||||
void *console_out_handle;
|
||||
TextOutput *console_out;
|
||||
} EfiSystemTable;
|
||||
|
||||
EfiStatus efi_main(void *image, EfiSystemTable *system) {
|
||||
(void)image;
|
||||
#ifdef _M_ARM64
|
||||
static const unsigned short marker[] = L"REIMS_OPENVMM_ARM64_EFI_OK\r\n";
|
||||
#else
|
||||
static const unsigned short marker[] = L"REIMS_OPENVMM_X64_EFI_OK\r\n";
|
||||
#endif
|
||||
return system->console_out->write(system->console_out, marker);
|
||||
}
|
||||
Generated
+153
@@ -0,0 +1,153 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ptr_meta"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "743da816b98c921cdbe8628ef7381b76f25ecf4da599fc80aca90eae7ef70cc0"
|
||||
dependencies = [
|
||||
"ptr_meta_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ptr_meta_derive"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c8d9ca532f185d5d4db7a7c9d51420b452168ea1c2b913953281bd6fe1fcbd0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "reims-nvram-probe"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"uefi",
|
||||
"uefi-raw",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ucs2"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df79298e11f316400c57ec268f3c2c29ac3c4d4777687955cd3d4f3a35ce7eba"
|
||||
dependencies = [
|
||||
"bit_field",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uefi"
|
||||
version = "0.35.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7569ceafb898907ff764629bac90ac24ba4203c38c33ef79ee88c74aa35b11"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"ptr_meta",
|
||||
"ucs2",
|
||||
"uefi-macros",
|
||||
"uefi-raw",
|
||||
"uguid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uefi-macros"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3dad47b3af8f99116c0f6d4d669c439487d9aaf1c8d9480d686cda6f3a8aa23"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uefi-raw"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cad96b8baaf1615d3fdd0f03d04a0b487d857c1b51b19dcbfe05e2e3c447b78"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"uguid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uguid"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab14ea9660d240e7865ce9d54ecdbd1cd9fa5802ae6f4512f093c7907e921533"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "reims-nvram-probe"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
uefi = { version = "0.35", features = ["panic_handler"] }
|
||||
uefi-raw = "0.11"
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
@@ -0,0 +1,122 @@
|
||||
#![no_main]
|
||||
#![no_std]
|
||||
|
||||
use core::fmt::Write;
|
||||
use uefi::proto::media::block::BlockIO;
|
||||
use uefi::runtime::{self, ResetType, VariableAttributes, VariableVendor};
|
||||
use uefi::{Guid, Status, boot, cstr16, entry, system};
|
||||
|
||||
const REIMS_TEST_VENDOR: VariableVendor = VariableVendor(Guid::from_bytes([
|
||||
0x10, 0x2e, 0x3a, 0x8b, 0x4d, 0x7c, 0x1a, 0x4f, 0x9a, 0x12, 0x10, 0x20, 0x30, 0x40, 0x50,
|
||||
0x60,
|
||||
]));
|
||||
const MAGIC_VALUE: &[u8] = b"REIMS_NVRAM_PERSIST_V1";
|
||||
|
||||
struct ConsoleOut;
|
||||
impl Write for ConsoleOut {
|
||||
fn write_str(&mut self, s: &str) -> core::fmt::Result {
|
||||
let mut buf = [0u16; 128];
|
||||
let mut i = 0;
|
||||
for b in s.bytes() {
|
||||
if i + 2 >= buf.len() {
|
||||
buf[i] = 0;
|
||||
let _ = system::with_stdout(|out| {
|
||||
out.output_string(unsafe { uefi::CStr16::from_u16_with_nul_unchecked(&buf[..=i]) })
|
||||
});
|
||||
i = 0;
|
||||
}
|
||||
if b == b'\n' {
|
||||
buf[i] = b'\r' as u16;
|
||||
i += 1;
|
||||
}
|
||||
buf[i] = b as u16;
|
||||
i += 1;
|
||||
}
|
||||
if i > 0 {
|
||||
buf[i] = 0;
|
||||
let _ = system::with_stdout(|out| {
|
||||
out.output_string(unsafe { uefi::CStr16::from_u16_with_nul_unchecked(&buf[..=i]) })
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[entry]
|
||||
fn main() -> Status {
|
||||
let mut con = ConsoleOut;
|
||||
let _ = writeln!(con, "REIMS_NVRAM_PROBE_START");
|
||||
|
||||
let time_ok = runtime::get_time().is_ok();
|
||||
let mut block_hits = 0usize;
|
||||
let mut sector_tag_ok = false;
|
||||
|
||||
if let Ok(handles) = boot::locate_handle_buffer(boot::SearchType::ByProtocol(&<BlockIO as uefi::Identify>::GUID)) {
|
||||
for &h in handles.iter() {
|
||||
if let Ok(bio) = boot::open_protocol_exclusive::<BlockIO>(h) {
|
||||
let media = bio.media();
|
||||
let bsz = media.block_size() as usize;
|
||||
if !media.is_logical_partition() && bsz == 512 && media.last_block() >= 2048 {
|
||||
let mut buf = [0u8; 512];
|
||||
if bio.read_blocks(media.media_id(), 0, &mut buf).is_ok() {
|
||||
block_hits += 1;
|
||||
// Check MBR signature 0x55AA and GPT header signature at LBA 1
|
||||
if buf[510] == 0x55 && buf[511] == 0xAA {
|
||||
let mut lba1 = [0u8; 512];
|
||||
if bio.read_blocks(media.media_id(), 1, &mut lba1).is_ok()
|
||||
&& &lba1[0..8] == b"EFI PART"
|
||||
{
|
||||
let mut lba2048 = [0u8; 512];
|
||||
if bio.read_blocks(media.media_id(), 2048, &mut lba2048).is_ok()
|
||||
&& lba2048.starts_with(b"REIMS-SECTOR-00-TEST-PATTERN")
|
||||
{
|
||||
sector_tag_ok = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = writeln!(
|
||||
con,
|
||||
"REIMS_DISK_CHECK|time_ok={}|disks={}|sector_tag_ok={}",
|
||||
time_ok, block_hits, sector_tag_ok
|
||||
);
|
||||
|
||||
let name = cstr16!("ReimsNvramProbe");
|
||||
let mut buf = [0u8; 64];
|
||||
match runtime::get_variable(name, &REIMS_TEST_VENDOR, &mut buf) {
|
||||
Ok((bytes, attrs)) => {
|
||||
let expected = VariableAttributes::NON_VOLATILE
|
||||
| VariableAttributes::BOOTSERVICE_ACCESS
|
||||
| VariableAttributes::RUNTIME_ACCESS;
|
||||
if bytes == MAGIC_VALUE && attrs == expected {
|
||||
let _ = writeln!(con, "REIMS_RT_VERIFY=OK");
|
||||
} else {
|
||||
let _ = writeln!(con, "REIMS_RT_VERIFY=MISMATCH|len={}|attrs={:?}", bytes.len(), attrs);
|
||||
}
|
||||
}
|
||||
Err(err) if err.status() == Status::NOT_FOUND => {
|
||||
let attrs = VariableAttributes::NON_VOLATILE
|
||||
| VariableAttributes::BOOTSERVICE_ACCESS
|
||||
| VariableAttributes::RUNTIME_ACCESS;
|
||||
match runtime::set_variable(name, &REIMS_TEST_VENDOR, attrs, MAGIC_VALUE) {
|
||||
Ok(()) => {
|
||||
let _ = writeln!(con, "REIMS_RT_WRITE=OK");
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = writeln!(con, "REIMS_RT_WRITE=ERR:{:?}", e.status());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
let _ = writeln!(con, "REIMS_RT_VERIFY=ERR:{:?}", err.status());
|
||||
}
|
||||
}
|
||||
|
||||
let _ = writeln!(con, "REIMS_NVRAM_PROBE_DONE");
|
||||
runtime::reset(ResetType::SHUTDOWN, Status::SUCCESS, None);
|
||||
}
|
||||
Generated
+153
@@ -0,0 +1,153 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ptr_meta"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "743da816b98c921cdbe8628ef7381b76f25ecf4da599fc80aca90eae7ef70cc0"
|
||||
dependencies = [
|
||||
"ptr_meta_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ptr_meta_derive"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c8d9ca532f185d5d4db7a7c9d51420b452168ea1c2b913953281bd6fe1fcbd0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "reims-oc-shim"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"uefi",
|
||||
"uefi-raw",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ucs2"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df79298e11f316400c57ec268f3c2c29ac3c4d4777687955cd3d4f3a35ce7eba"
|
||||
dependencies = [
|
||||
"bit_field",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uefi"
|
||||
version = "0.35.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7569ceafb898907ff764629bac90ac24ba4203c38c33ef79ee88c74aa35b11"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"ptr_meta",
|
||||
"ucs2",
|
||||
"uefi-macros",
|
||||
"uefi-raw",
|
||||
"uguid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uefi-macros"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3dad47b3af8f99116c0f6d4d669c439487d9aaf1c8d9480d686cda6f3a8aa23"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uefi-raw"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cad96b8baaf1615d3fdd0f03d04a0b487d857c1b51b19dcbfe05e2e3c447b78"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"uguid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uguid"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab14ea9660d240e7865ce9d54ecdbd1cd9fa5802ae6f4512f093c7907e921533"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "reims-oc-shim"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
uefi = { version = "0.35", features = ["panic_handler"] }
|
||||
uefi-raw = "0.11"
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
@@ -0,0 +1,850 @@
|
||||
#![no_main]
|
||||
#![no_std]
|
||||
|
||||
use core::arch::asm;
|
||||
use core::ffi::c_void;
|
||||
use core::ptr;
|
||||
use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
|
||||
use uefi::proto::loaded_image::LoadedImage;
|
||||
use uefi::{Status, boot, cstr16, entry, system};
|
||||
use uefi_raw::Handle as RawHandle;
|
||||
use uefi_raw::protocol::device_path::{DevicePathProtocol, DeviceSubType, DeviceType};
|
||||
use uefi_raw::protocol::loaded_image::LoadedImageProtocol;
|
||||
use uefi_raw::table::boot::{BootServices, MemoryDescriptor, MemoryType};
|
||||
use uefi_raw::table::system::SystemTable;
|
||||
use uefi_raw::{Boolean, Char16};
|
||||
|
||||
type LoadImageFn = unsafe extern "efiapi" fn(
|
||||
boot_policy: Boolean,
|
||||
parent_image_handle: RawHandle,
|
||||
device_path: *const DevicePathProtocol,
|
||||
source_buffer: *const u8,
|
||||
source_size: usize,
|
||||
image_handle: *mut RawHandle,
|
||||
) -> Status;
|
||||
|
||||
type StartImageFn = unsafe extern "efiapi" fn(
|
||||
image_handle: RawHandle,
|
||||
exit_data_size: *mut usize,
|
||||
exit_data: *mut *mut Char16,
|
||||
) -> Status;
|
||||
|
||||
type ImageEntryFn =
|
||||
unsafe extern "efiapi" fn(image_handle: RawHandle, system_table: *mut c_void) -> Status;
|
||||
|
||||
static ORIG_BS: AtomicPtr<BootServices> = AtomicPtr::new(ptr::null_mut());
|
||||
static ORIG_GST: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
|
||||
static ORIG_LOAD_IMAGE: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
|
||||
static ORIG_START_IMAGE: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
|
||||
static SYNTH_MEM_DP: AtomicPtr<DevicePathProtocol> = AtomicPtr::new(ptr::null_mut());
|
||||
|
||||
type GetMemoryMapFn = unsafe extern "efiapi" fn(
|
||||
memory_map_size: *mut usize,
|
||||
memory_map: *mut MemoryDescriptor,
|
||||
map_key: *mut usize,
|
||||
descriptor_size: *mut usize,
|
||||
descriptor_version: *mut u32,
|
||||
) -> Status;
|
||||
|
||||
static ORIG_GET_MMAP: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
|
||||
static ORIG_BOOT_GET_MMAP: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
|
||||
static GET_MMAP_CALLS: AtomicUsize = AtomicUsize::new(0);
|
||||
static mut MMAP_LOG_BUF: [u8; 65536] = [0; 65536];
|
||||
static mut MMAP_PTS: [u64; 512] = [0; 512];
|
||||
static mut MMAP_CLEAN: [MemoryDescriptor; 256] = [MemoryDescriptor {
|
||||
ty: MemoryType::RESERVED,
|
||||
phys_start: 0,
|
||||
virt_start: 0,
|
||||
page_count: 0,
|
||||
att: uefi_raw::table::boot::MemoryAttribute::empty(),
|
||||
}; 256];
|
||||
|
||||
static SAVED_ENTRY_VA: AtomicUsize = AtomicUsize::new(0);
|
||||
static SAVED_LI_ST: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
|
||||
static mut SAVED_ENTRY_BYTES: [u8; 14] = [0; 14];
|
||||
|
||||
#[inline(always)]
|
||||
unsafe fn com1_write_byte(b: u8) {
|
||||
unsafe {
|
||||
loop {
|
||||
let lsr: u8;
|
||||
asm!("in al, dx", in("dx") 0x3FDu16, out("al") lsr, options(nomem, nostack));
|
||||
if (lsr & 0x20) != 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
asm!("out dx, al", in("dx") 0x3F8u16, in("al") b, options(nomem, nostack));
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn com1_str(s: &str) {
|
||||
for &b in s.as_bytes() {
|
||||
unsafe { com1_write_byte(b) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn com1_hex(mut v: u64) {
|
||||
unsafe { com1_str("0x") };
|
||||
if v == 0 {
|
||||
unsafe { com1_write_byte(b'0') };
|
||||
return;
|
||||
}
|
||||
let mut buf = [0u8; 16];
|
||||
let mut n = 0usize;
|
||||
while v != 0 {
|
||||
let d = (v & 0xf) as u8;
|
||||
buf[n] = if d < 10 { b'0' + d } else { b'a' + (d - 10) };
|
||||
n += 1;
|
||||
v >>= 4;
|
||||
}
|
||||
while n > 0 {
|
||||
n -= 1;
|
||||
unsafe { com1_write_byte(buf[n]) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn write_code_bytes(dst: *mut u8, bytes: &[u8]) {
|
||||
unsafe {
|
||||
let rflags: u64;
|
||||
let cr0: u64;
|
||||
asm!(
|
||||
"pushfq",
|
||||
"pop {rflags}",
|
||||
"cli",
|
||||
"mov {cr0}, cr0",
|
||||
rflags = out(reg) rflags,
|
||||
cr0 = out(reg) cr0,
|
||||
);
|
||||
let wp_cleared = cr0 & !(1u64 << 16);
|
||||
asm!("mov cr0, {val}", val = in(reg) wp_cleared, options(nostack));
|
||||
ptr::copy_nonoverlapping(bytes.as_ptr(), dst, bytes.len());
|
||||
asm!("mov cr0, {val}", val = in(reg) cr0, options(nostack));
|
||||
if (rflags & (1u64 << 9)) != 0 {
|
||||
asm!("sti", options(nomem, nostack));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn pe32plus_entry_va(image_base: *const u8, image_size: u64) -> Option<usize> {
|
||||
if image_base.is_null() || image_size < 0x100 {
|
||||
return None;
|
||||
}
|
||||
unsafe {
|
||||
let dos_sig = ptr::read_unaligned(image_base.cast::<u16>());
|
||||
if dos_sig != 0x5A4D {
|
||||
return None;
|
||||
}
|
||||
let lfanew = ptr::read_unaligned(image_base.add(0x3C).cast::<u32>()) as u64;
|
||||
if lfanew + 0x40 > image_size {
|
||||
return None;
|
||||
}
|
||||
let nt = image_base.add(lfanew as usize);
|
||||
let pe_sig = ptr::read_unaligned(nt.cast::<u32>());
|
||||
if pe_sig != 0x0000_4550 {
|
||||
return None;
|
||||
}
|
||||
let magic = ptr::read_unaligned(nt.add(0x18).cast::<u16>());
|
||||
if magic != 0x020B {
|
||||
return None;
|
||||
}
|
||||
let entry_rva = ptr::read_unaligned(nt.add(0x28).cast::<u32>()) as u64;
|
||||
if entry_rva == 0 || entry_rva + 14 > image_size {
|
||||
return None;
|
||||
}
|
||||
Some((image_base as usize) + (entry_rva as usize))
|
||||
}
|
||||
}
|
||||
|
||||
fn desc_priority(d: &MemoryDescriptor) -> u8 {
|
||||
if d.att
|
||||
.contains(uefi_raw::table::boot::MemoryAttribute::RUNTIME)
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
match d.ty {
|
||||
MemoryType::CONVENTIONAL => 1,
|
||||
MemoryType::LOADER_CODE
|
||||
| MemoryType::LOADER_DATA
|
||||
| MemoryType::BOOT_SERVICES_CODE
|
||||
| MemoryType::BOOT_SERVICES_DATA => 2,
|
||||
_ => 3,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn normalize_memory_map(
|
||||
capacity: usize,
|
||||
memory_map_size: *mut usize,
|
||||
memory_map: *mut MemoryDescriptor,
|
||||
desc_size: usize,
|
||||
) -> Status {
|
||||
let raw_bytes = memory_map as *mut u8;
|
||||
if raw_bytes.is_null() || desc_size < core::mem::size_of::<MemoryDescriptor>() {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
let cur_size = unsafe { *memory_map_size };
|
||||
let count = cur_size / desc_size;
|
||||
if count <= 1 || count > 256 {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
let mut need_fix = false;
|
||||
let mut prev_start = 0u64;
|
||||
let mut prev_end = 0u64;
|
||||
for i in 0..count {
|
||||
let d = unsafe { &*(raw_bytes.add(i * desc_size).cast::<MemoryDescriptor>()) };
|
||||
let start = d.phys_start;
|
||||
let end = start.saturating_add(d.page_count.saturating_mul(4096));
|
||||
if i > 0 && (start < prev_start || start < prev_end) {
|
||||
need_fix = true;
|
||||
break;
|
||||
}
|
||||
prev_start = start;
|
||||
prev_end = end;
|
||||
}
|
||||
if !need_fix {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
let pts = ptr::addr_of_mut!(MMAP_PTS) as *mut u64;
|
||||
let mut n_pts = 0usize;
|
||||
for i in 0..count {
|
||||
let d = unsafe { &*(raw_bytes.add(i * desc_size).cast::<MemoryDescriptor>()) };
|
||||
if d.page_count == 0 {
|
||||
continue;
|
||||
}
|
||||
let s = d.phys_start;
|
||||
let e = s.saturating_add(d.page_count.saturating_mul(4096));
|
||||
if n_pts + 2 > 512 {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
unsafe {
|
||||
*pts.add(n_pts) = s;
|
||||
*pts.add(n_pts + 1) = e;
|
||||
}
|
||||
n_pts += 2;
|
||||
}
|
||||
if n_pts < 2 {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
|
||||
// Insertion sort boundaries.
|
||||
for i in 1..n_pts {
|
||||
let key = unsafe { *pts.add(i) };
|
||||
let mut j = i;
|
||||
while j > 0 && unsafe { *pts.add(j - 1) } > key {
|
||||
unsafe { *pts.add(j) = *pts.add(j - 1) };
|
||||
j -= 1;
|
||||
}
|
||||
unsafe { *pts.add(j) = key };
|
||||
}
|
||||
|
||||
// Deduplicate sorted boundaries in-place.
|
||||
let mut u_pts = 1usize;
|
||||
for i in 1..n_pts {
|
||||
let v = unsafe { *pts.add(i) };
|
||||
if v != unsafe { *pts.add(u_pts - 1) } {
|
||||
unsafe { *pts.add(u_pts) = v };
|
||||
u_pts += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let clean = ptr::addr_of_mut!(MMAP_CLEAN) as *mut MemoryDescriptor;
|
||||
let mut out_count = 0usize;
|
||||
for k in 0..(u_pts - 1) {
|
||||
let s = unsafe { *pts.add(k) };
|
||||
let e = unsafe { *pts.add(k + 1) };
|
||||
if e <= s {
|
||||
continue;
|
||||
}
|
||||
let mut best: Option<&MemoryDescriptor> = None;
|
||||
let mut best_prio = 0u8;
|
||||
for i in 0..count {
|
||||
let d = unsafe { &*(raw_bytes.add(i * desc_size).cast::<MemoryDescriptor>()) };
|
||||
if d.page_count == 0 {
|
||||
continue;
|
||||
}
|
||||
let ds = d.phys_start;
|
||||
let de = ds.saturating_add(d.page_count.saturating_mul(4096));
|
||||
if ds <= s && e <= de {
|
||||
let p = desc_priority(d);
|
||||
if best.is_none() || p > best_prio || (p == best_prio && d.ty.0 < best.unwrap().ty.0)
|
||||
{
|
||||
best = Some(d);
|
||||
best_prio = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(winner) = best else {
|
||||
continue;
|
||||
};
|
||||
let pages = (e - s) / 4096;
|
||||
if out_count > 0 {
|
||||
let prev = unsafe { &mut *clean.add(out_count - 1) };
|
||||
let prev_end = prev.phys_start.saturating_add(prev.page_count.saturating_mul(4096));
|
||||
if prev_end == s && prev.ty == winner.ty && prev.att == winner.att {
|
||||
prev.page_count += pages;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if out_count >= 256 {
|
||||
return Status::SUCCESS;
|
||||
}
|
||||
let virt = if winner.virt_start == 0 {
|
||||
0
|
||||
} else {
|
||||
winner.virt_start.wrapping_add(s - winner.phys_start)
|
||||
};
|
||||
unsafe {
|
||||
*clean.add(out_count) = MemoryDescriptor {
|
||||
ty: winner.ty,
|
||||
phys_start: s,
|
||||
virt_start: virt,
|
||||
page_count: pages,
|
||||
att: winner.att,
|
||||
};
|
||||
}
|
||||
out_count += 1;
|
||||
}
|
||||
|
||||
let needed = out_count * desc_size;
|
||||
if needed > capacity {
|
||||
unsafe { *memory_map_size = (out_count + 8) * desc_size };
|
||||
return Status::BUFFER_TOO_SMALL;
|
||||
}
|
||||
for i in 0..out_count {
|
||||
let dst = unsafe { raw_bytes.add(i * desc_size) };
|
||||
unsafe {
|
||||
ptr::write_bytes(dst, 0, desc_size);
|
||||
ptr::write(dst.cast::<MemoryDescriptor>(), *clean.add(i));
|
||||
}
|
||||
}
|
||||
unsafe { *memory_map_size = needed };
|
||||
Status::SUCCESS
|
||||
}
|
||||
|
||||
unsafe fn call_and_normalize_get_memory_map(
|
||||
orig_ptr: *mut c_void,
|
||||
memory_map_size: *mut usize,
|
||||
memory_map: *mut MemoryDescriptor,
|
||||
map_key: *mut usize,
|
||||
descriptor_size: *mut usize,
|
||||
descriptor_version: *mut u32,
|
||||
) -> Status {
|
||||
if orig_ptr.is_null() {
|
||||
return Status::LOAD_ERROR;
|
||||
}
|
||||
let capacity = if !memory_map_size.is_null() {
|
||||
unsafe { *memory_map_size }
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let orig: GetMemoryMapFn = unsafe { core::mem::transmute(orig_ptr) };
|
||||
let st = unsafe {
|
||||
orig(
|
||||
memory_map_size,
|
||||
memory_map,
|
||||
map_key,
|
||||
descriptor_size,
|
||||
descriptor_version,
|
||||
)
|
||||
};
|
||||
if st == Status::BUFFER_TOO_SMALL {
|
||||
if !memory_map_size.is_null() && !descriptor_size.is_null() && unsafe { *descriptor_size } > 0
|
||||
{
|
||||
unsafe { *memory_map_size += 8 * *descriptor_size };
|
||||
}
|
||||
return Status::BUFFER_TOO_SMALL;
|
||||
}
|
||||
if st != Status::SUCCESS || memory_map_size.is_null() || descriptor_size.is_null() {
|
||||
return st;
|
||||
}
|
||||
let dsz = unsafe { *descriptor_size };
|
||||
let norm_st = unsafe { normalize_memory_map(capacity, memory_map_size, memory_map, dsz) };
|
||||
if norm_st == Status::BUFFER_TOO_SMALL {
|
||||
return Status::BUFFER_TOO_SMALL;
|
||||
}
|
||||
Status::SUCCESS
|
||||
}
|
||||
|
||||
unsafe extern "efiapi" fn hooked_get_memory_map(
|
||||
memory_map_size: *mut usize,
|
||||
memory_map: *mut MemoryDescriptor,
|
||||
map_key: *mut usize,
|
||||
descriptor_size: *mut usize,
|
||||
descriptor_version: *mut u32,
|
||||
) -> Status {
|
||||
GET_MMAP_CALLS.fetch_add(1, Ordering::Relaxed);
|
||||
unsafe {
|
||||
call_and_normalize_get_memory_map(
|
||||
ORIG_GET_MMAP.load(Ordering::Acquire),
|
||||
memory_map_size,
|
||||
memory_map,
|
||||
map_key,
|
||||
descriptor_size,
|
||||
descriptor_version,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "efiapi" fn hooked_boot_get_memory_map(
|
||||
memory_map_size: *mut usize,
|
||||
memory_map: *mut MemoryDescriptor,
|
||||
map_key: *mut usize,
|
||||
descriptor_size: *mut usize,
|
||||
descriptor_version: *mut u32,
|
||||
) -> Status {
|
||||
unsafe {
|
||||
call_and_normalize_get_memory_map(
|
||||
ORIG_BOOT_GET_MMAP.load(Ordering::Acquire),
|
||||
memory_map_size,
|
||||
memory_map,
|
||||
map_key,
|
||||
descriptor_size,
|
||||
descriptor_version,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn log_boot_memory_map(bs: &BootServices, tag: &str) {
|
||||
let mut map_size = size_of_static_mmap_buf();
|
||||
let mut map_key: usize = 0;
|
||||
let mut desc_size: usize = 0;
|
||||
let mut desc_ver: u32 = 0;
|
||||
let buf = ptr::addr_of_mut!(MMAP_LOG_BUF).cast::<u8>();
|
||||
let st = unsafe {
|
||||
(bs.get_memory_map)(
|
||||
&mut map_size,
|
||||
buf.cast::<MemoryDescriptor>(),
|
||||
&mut map_key,
|
||||
&mut desc_size,
|
||||
&mut desc_ver,
|
||||
)
|
||||
};
|
||||
unsafe {
|
||||
com1_str("REIMS_MMAP_HDR ");
|
||||
com1_str(tag);
|
||||
com1_str(" st=");
|
||||
com1_hex(st.0 as u64);
|
||||
com1_str(" size=");
|
||||
com1_hex(map_size as u64);
|
||||
com1_str(" dsz=");
|
||||
com1_hex(desc_size as u64);
|
||||
com1_str("\r\n");
|
||||
}
|
||||
if st != Status::SUCCESS || desc_size < core::mem::size_of::<MemoryDescriptor>() {
|
||||
return;
|
||||
}
|
||||
let count = map_size / desc_size;
|
||||
let mut prev_start = 0u64;
|
||||
let mut prev_end = 0u64;
|
||||
let mut unsorted = 0u64;
|
||||
let mut overlaps = 0u64;
|
||||
for idx in 0..count {
|
||||
let d = unsafe { &*(buf.add(idx * desc_size).cast::<MemoryDescriptor>()) };
|
||||
let start = d.phys_start;
|
||||
let end = start.saturating_add(d.page_count.saturating_mul(4096));
|
||||
if idx > 0 {
|
||||
if start < prev_start {
|
||||
unsorted += 1;
|
||||
}
|
||||
if start < prev_end {
|
||||
overlaps += 1;
|
||||
}
|
||||
}
|
||||
prev_start = start;
|
||||
prev_end = end;
|
||||
}
|
||||
unsafe {
|
||||
com1_str("REIMS_MMAP_SUMMARY ");
|
||||
com1_str(tag);
|
||||
com1_str(" count=");
|
||||
com1_hex(count as u64);
|
||||
com1_str(" unsorted=");
|
||||
com1_hex(unsorted);
|
||||
com1_str(" overlaps=");
|
||||
com1_hex(overlaps);
|
||||
com1_str("\r\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn size_of_static_mmap_buf() -> usize {
|
||||
65536
|
||||
}
|
||||
|
||||
unsafe extern "efiapi" fn boot_entry_shim(
|
||||
image_handle: RawHandle,
|
||||
passed_st: *mut c_void,
|
||||
) -> Status {
|
||||
let entry_va = SAVED_ENTRY_VA.load(Ordering::Acquire);
|
||||
let override_st = SAVED_LI_ST.load(Ordering::Acquire);
|
||||
unsafe {
|
||||
com1_str("REIMS_BOOT_SHIM passed_st=");
|
||||
com1_hex(passed_st as u64);
|
||||
com1_str(" override_st=");
|
||||
com1_hex(override_st as u64);
|
||||
com1_str("\r\n");
|
||||
|
||||
if !override_st.is_null() {
|
||||
let st_ref = &*(override_st as *const SystemTable);
|
||||
if !st_ref.boot_services.is_null() {
|
||||
let bs = &mut *st_ref.boot_services;
|
||||
ORIG_BS.store(st_ref.boot_services, Ordering::Release);
|
||||
if (bs.get_memory_map as usize) != (hooked_get_memory_map as *const () as usize)
|
||||
&& (bs.get_memory_map as usize)
|
||||
!= (hooked_boot_get_memory_map as *const () as usize)
|
||||
{
|
||||
ORIG_BOOT_GET_MMAP.store(bs.get_memory_map as *mut c_void, Ordering::Release);
|
||||
bs.get_memory_map = hooked_boot_get_memory_map;
|
||||
}
|
||||
bs.header.crc = 0;
|
||||
let mut crc = 0u32;
|
||||
let _ = (bs.calculate_crc32)(
|
||||
(bs as *const BootServices).cast(),
|
||||
bs.header.size as usize,
|
||||
&mut crc,
|
||||
);
|
||||
bs.header.crc = crc;
|
||||
log_boot_memory_map(bs, "ENTRY");
|
||||
}
|
||||
}
|
||||
|
||||
let saved_ptr = ptr::addr_of!(SAVED_ENTRY_BYTES) as *const [u8; 14];
|
||||
write_code_bytes(entry_va as *mut u8, &*saved_ptr);
|
||||
let orig_entry: ImageEntryFn = core::mem::transmute(entry_va);
|
||||
orig_entry(image_handle, override_st)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn log_runtime_descriptors(bs: &BootServices, orig_gst: u64, orig_grt: u64) {
|
||||
let mut map_size: usize = 0;
|
||||
let mut map_key: usize = 0;
|
||||
let mut desc_size: usize = 0;
|
||||
let mut desc_ver: u32 = 0;
|
||||
let st = unsafe {
|
||||
(bs.get_memory_map)(
|
||||
&mut map_size,
|
||||
ptr::null_mut(),
|
||||
&mut map_key,
|
||||
&mut desc_size,
|
||||
&mut desc_ver,
|
||||
)
|
||||
};
|
||||
if st != Status::BUFFER_TOO_SMALL || desc_size == 0 {
|
||||
return;
|
||||
}
|
||||
let alloc_size = map_size + desc_size * 8;
|
||||
let mut buf: *mut u8 = ptr::null_mut();
|
||||
let ast = unsafe { (bs.allocate_pool)(MemoryType::BOOT_SERVICES_DATA, alloc_size, &mut buf) };
|
||||
if ast != Status::SUCCESS || buf.is_null() {
|
||||
return;
|
||||
}
|
||||
map_size = alloc_size;
|
||||
let gm_st = unsafe {
|
||||
(bs.get_memory_map)(
|
||||
&mut map_size,
|
||||
buf.cast::<MemoryDescriptor>(),
|
||||
&mut map_key,
|
||||
&mut desc_size,
|
||||
&mut desc_ver,
|
||||
)
|
||||
};
|
||||
if gm_st == Status::SUCCESS {
|
||||
let mut off = 0usize;
|
||||
while off + core::mem::size_of::<MemoryDescriptor>() <= map_size {
|
||||
let d = unsafe { &*(buf.add(off).cast::<MemoryDescriptor>()) };
|
||||
let start = d.phys_start;
|
||||
let end = start.saturating_add(d.page_count.saturating_mul(4096));
|
||||
if (orig_gst >= start && orig_gst < end) || (orig_grt >= start && orig_grt < end) {
|
||||
unsafe {
|
||||
com1_str("REIMS_SHIM_RT_DESC type=");
|
||||
com1_hex(d.ty.0 as u64);
|
||||
com1_str(" start=");
|
||||
com1_hex(start);
|
||||
com1_str(" end=");
|
||||
com1_hex(end);
|
||||
com1_str(" attr=");
|
||||
com1_hex(d.att.bits());
|
||||
com1_str("\r\n");
|
||||
}
|
||||
}
|
||||
off += desc_size;
|
||||
}
|
||||
}
|
||||
let _ = unsafe { (bs.free_pool)(buf) };
|
||||
}
|
||||
|
||||
unsafe extern "efiapi" fn hooked_start_image(
|
||||
image_handle: RawHandle,
|
||||
exit_data_size: *mut usize,
|
||||
exit_data: *mut *mut Char16,
|
||||
) -> Status {
|
||||
let orig_ptr = ORIG_START_IMAGE.load(Ordering::Acquire);
|
||||
if orig_ptr.is_null() {
|
||||
return Status::LOAD_ERROR;
|
||||
}
|
||||
let bs_ptr = ORIG_BS.load(Ordering::Acquire);
|
||||
let orig_gst = ORIG_GST.load(Ordering::Acquire);
|
||||
if !bs_ptr.is_null() && !image_handle.is_null() {
|
||||
let mut li_iface: *mut c_void = ptr::null_mut();
|
||||
let st = unsafe {
|
||||
((*bs_ptr).handle_protocol)(
|
||||
image_handle,
|
||||
&LoadedImageProtocol::GUID,
|
||||
&mut li_iface,
|
||||
)
|
||||
};
|
||||
if st == Status::SUCCESS && !li_iface.is_null() {
|
||||
let li = unsafe { &*(li_iface as *const LoadedImageProtocol) };
|
||||
let li_st = li.system_table as *mut c_void;
|
||||
if !li_st.is_null() && li_st != orig_gst {
|
||||
if let Some(entry_va) =
|
||||
unsafe { pe32plus_entry_va(li.image_base.cast::<u8>(), li.image_size) }
|
||||
{
|
||||
let mut orig_bytes = [0u8; 14];
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(entry_va as *const u8, orig_bytes.as_mut_ptr(), 14);
|
||||
ptr::copy_nonoverlapping(
|
||||
orig_bytes.as_ptr(),
|
||||
ptr::addr_of_mut!(SAVED_ENTRY_BYTES) as *mut u8,
|
||||
14,
|
||||
);
|
||||
}
|
||||
SAVED_ENTRY_VA.store(entry_va, Ordering::Release);
|
||||
SAVED_LI_ST.store(li_st, Ordering::Release);
|
||||
|
||||
let mut trampoline = [0u8; 14];
|
||||
trampoline[0] = 0xFF;
|
||||
trampoline[1] = 0x25;
|
||||
let target = (boot_entry_shim as *const () as usize as u64).to_le_bytes();
|
||||
trampoline[6..14].copy_from_slice(&target);
|
||||
unsafe {
|
||||
write_code_bytes(entry_va as *mut u8, &trampoline);
|
||||
com1_str("REIMS_START_SHIM entry=");
|
||||
com1_hex(entry_va as u64);
|
||||
com1_str(" li_st=");
|
||||
com1_hex(li_st as u64);
|
||||
com1_str(" orig_gst=");
|
||||
com1_hex(orig_gst as u64);
|
||||
com1_str("\r\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let orig: StartImageFn = unsafe { core::mem::transmute(orig_ptr) };
|
||||
unsafe { orig(image_handle, exit_data_size, exit_data) }
|
||||
}
|
||||
|
||||
const MEM_BUFFER_PATH_U16: &[u16] = &[
|
||||
b'\\' as u16, b'E' as u16, b'F' as u16, b'I' as u16, b'\\' as u16, b'O' as u16, b'C' as u16,
|
||||
b'\\' as u16, b'D' as u16, b'r' as u16, b'i' as u16, b'v' as u16, b'e' as u16, b'r' as u16,
|
||||
b's' as u16, b'\\' as u16, b'M' as u16, b'e' as u16, b'm' as u16, b'B' as u16, b'u' as u16,
|
||||
b'f' as u16, b'f' as u16, b'e' as u16, b'r' as u16, b'.' as u16, b'e' as u16, b'f' as u16,
|
||||
b'i' as u16, 0,
|
||||
];
|
||||
|
||||
const OPENCORE_PATH_U16: &[u16] = &[
|
||||
b'\\' as u16, b'E' as u16, b'F' as u16, b'I' as u16, b'\\' as u16, b'O' as u16, b'C' as u16,
|
||||
b'\\' as u16, b'O' as u16, b'p' as u16, b'e' as u16, b'n' as u16, b'C' as u16, b'o' as u16,
|
||||
b'r' as u16, b'e' as u16, b'.' as u16, b'e' as u16, b'f' as u16, b'i' as u16, 0,
|
||||
];
|
||||
|
||||
unsafe extern "efiapi" fn hooked_load_image(
|
||||
boot_policy: Boolean,
|
||||
parent_image_handle: RawHandle,
|
||||
device_path: *const DevicePathProtocol,
|
||||
source_buffer: *const u8,
|
||||
source_size: usize,
|
||||
image_handle: *mut RawHandle,
|
||||
) -> Status {
|
||||
let orig_ptr = ORIG_LOAD_IMAGE.load(Ordering::Acquire);
|
||||
if orig_ptr.is_null() {
|
||||
return Status::LOAD_ERROR;
|
||||
}
|
||||
let orig: LoadImageFn = unsafe { core::mem::transmute(orig_ptr) };
|
||||
let effective_dp = if device_path.is_null() && !source_buffer.is_null() && source_size > 0 {
|
||||
let synth = SYNTH_MEM_DP.load(Ordering::Acquire);
|
||||
if synth.is_null() { device_path } else { synth }
|
||||
} else {
|
||||
device_path
|
||||
};
|
||||
unsafe {
|
||||
orig(
|
||||
boot_policy,
|
||||
parent_image_handle,
|
||||
effective_dp,
|
||||
source_buffer,
|
||||
source_size,
|
||||
image_handle,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn device_path_prefix_len(dp: *const DevicePathProtocol) -> Option<usize> {
|
||||
if dp.is_null() {
|
||||
return None;
|
||||
}
|
||||
let mut offset = 0usize;
|
||||
loop {
|
||||
if offset > 4096 {
|
||||
return None;
|
||||
}
|
||||
let node = unsafe { &*((dp as *const u8).add(offset) as *const DevicePathProtocol) };
|
||||
let node_len = node.length() as usize;
|
||||
if node_len < 4 {
|
||||
return None;
|
||||
}
|
||||
if node.major_type == DeviceType::END && node.sub_type == DeviceSubType(0xFF) {
|
||||
return Some(offset);
|
||||
}
|
||||
offset += node_len;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn build_file_device_path(
|
||||
bs: &BootServices,
|
||||
parent_dp: *const DevicePathProtocol,
|
||||
prefix_len: usize,
|
||||
file_path_u16: &[u16],
|
||||
) -> Option<*mut DevicePathProtocol> {
|
||||
let file_node_len = 4 + file_path_u16.len() * 2;
|
||||
let total_len = prefix_len + file_node_len + 4;
|
||||
let mut buf: *mut u8 = ptr::null_mut();
|
||||
let st = unsafe { (bs.allocate_pool)(MemoryType::BOOT_SERVICES_DATA, total_len, &mut buf) };
|
||||
if st != Status::SUCCESS || buf.is_null() {
|
||||
return None;
|
||||
}
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(parent_dp as *const u8, buf, prefix_len);
|
||||
let fnode = buf.add(prefix_len);
|
||||
*fnode.add(0) = 0x04; // MEDIA_DEVICE_PATH
|
||||
*fnode.add(1) = 0x04; // MEDIA_FILEPATH_DP
|
||||
let fl_bytes = (file_node_len as u16).to_le_bytes();
|
||||
*fnode.add(2) = fl_bytes[0];
|
||||
*fnode.add(3) = fl_bytes[1];
|
||||
for (i, &ch) in file_path_u16.iter().enumerate() {
|
||||
let le = ch.to_le_bytes();
|
||||
*fnode.add(4 + i * 2) = le[0];
|
||||
*fnode.add(4 + i * 2 + 1) = le[1];
|
||||
}
|
||||
let end = buf.add(prefix_len + file_node_len);
|
||||
*end.add(0) = 0x7F;
|
||||
*end.add(1) = 0xFF;
|
||||
*end.add(2) = 0x04;
|
||||
*end.add(3) = 0x00;
|
||||
}
|
||||
Some(buf.cast())
|
||||
}
|
||||
|
||||
#[entry]
|
||||
fn main() -> Status {
|
||||
let _ = system::with_stdout(|out| out.output_string(cstr16!("REIMS_OC_SHIM_START\r\n")));
|
||||
|
||||
let Some(st_ptr) = uefi::table::system_table_raw() else {
|
||||
return Status::LOAD_ERROR;
|
||||
};
|
||||
let bs_ptr = unsafe { st_ptr.as_ref().boot_services };
|
||||
if bs_ptr.is_null() {
|
||||
return Status::LOAD_ERROR;
|
||||
}
|
||||
let bs = unsafe { &mut *bs_ptr };
|
||||
let self_handle = boot::image_handle();
|
||||
|
||||
let device_handle = {
|
||||
let Ok(li) = (unsafe {
|
||||
boot::open_protocol::<LoadedImage>(
|
||||
boot::OpenProtocolParams {
|
||||
handle: self_handle,
|
||||
agent: self_handle,
|
||||
controller: None,
|
||||
},
|
||||
boot::OpenProtocolAttributes::GetProtocol,
|
||||
)
|
||||
}) else {
|
||||
return Status::LOAD_ERROR;
|
||||
};
|
||||
match li.device() {
|
||||
Some(h) => h,
|
||||
None => return Status::DEVICE_ERROR,
|
||||
}
|
||||
};
|
||||
|
||||
let mut dp_iface: *mut c_void = ptr::null_mut();
|
||||
let dp_st = unsafe {
|
||||
(bs.handle_protocol)(
|
||||
device_handle.as_ptr(),
|
||||
&DevicePathProtocol::GUID,
|
||||
&mut dp_iface,
|
||||
)
|
||||
};
|
||||
if dp_st != Status::SUCCESS || dp_iface.is_null() {
|
||||
return dp_st;
|
||||
}
|
||||
let parent_dp = dp_iface as *const DevicePathProtocol;
|
||||
let Some(prefix_len) = (unsafe { device_path_prefix_len(parent_dp) }) else {
|
||||
return Status::DEVICE_ERROR;
|
||||
};
|
||||
|
||||
let Some(synth_dp) = (unsafe { build_file_device_path(bs, parent_dp, prefix_len, MEM_BUFFER_PATH_U16) }) else {
|
||||
return Status::OUT_OF_RESOURCES;
|
||||
};
|
||||
let Some(oc_dp) = (unsafe { build_file_device_path(bs, parent_dp, prefix_len, OPENCORE_PATH_U16) }) else {
|
||||
return Status::OUT_OF_RESOURCES;
|
||||
};
|
||||
|
||||
let orig_gst = st_ptr.as_ptr() as *mut c_void;
|
||||
let orig_grt = unsafe { st_ptr.as_ref().runtime_services as *mut c_void };
|
||||
ORIG_BS.store(bs_ptr, Ordering::Release);
|
||||
ORIG_GST.store(orig_gst, Ordering::Release);
|
||||
unsafe {
|
||||
com1_str("REIMS_SHIM_TABLES gst=");
|
||||
com1_hex(orig_gst as u64);
|
||||
com1_str(" grt=");
|
||||
com1_hex(orig_grt as u64);
|
||||
com1_str("\r\n");
|
||||
log_runtime_descriptors(bs, orig_gst as u64, orig_grt as u64);
|
||||
}
|
||||
|
||||
SYNTH_MEM_DP.store(synth_dp, Ordering::Release);
|
||||
ORIG_GET_MMAP.store(bs.get_memory_map as *mut c_void, Ordering::Release);
|
||||
ORIG_LOAD_IMAGE.store(bs.load_image as *mut c_void, Ordering::Release);
|
||||
ORIG_START_IMAGE.store(bs.start_image as *mut c_void, Ordering::Release);
|
||||
bs.get_memory_map = hooked_get_memory_map;
|
||||
bs.load_image = hooked_load_image;
|
||||
bs.start_image = hooked_start_image;
|
||||
bs.header.crc = 0;
|
||||
let mut crc = 0u32;
|
||||
let _ = unsafe {
|
||||
(bs.calculate_crc32)(
|
||||
(bs as *const BootServices).cast(),
|
||||
bs.header.size as usize,
|
||||
&mut crc,
|
||||
)
|
||||
};
|
||||
bs.header.crc = crc;
|
||||
|
||||
let orig_fn: LoadImageFn = unsafe { core::mem::transmute(ORIG_LOAD_IMAGE.load(Ordering::Acquire)) };
|
||||
let mut oc_handle: RawHandle = ptr::null_mut();
|
||||
let load_st = unsafe {
|
||||
orig_fn(
|
||||
Boolean::FALSE,
|
||||
self_handle.as_ptr(),
|
||||
oc_dp,
|
||||
ptr::null(),
|
||||
0,
|
||||
&mut oc_handle,
|
||||
)
|
||||
};
|
||||
if load_st != Status::SUCCESS || oc_handle.is_null() {
|
||||
let _ = system::with_stdout(|out| out.output_string(cstr16!("REIMS_OC_SHIM_LOAD_FAIL\r\n")));
|
||||
return load_st;
|
||||
}
|
||||
|
||||
let _ = system::with_stdout(|out| out.output_string(cstr16!("REIMS_OC_SHIM_LAUNCH_OC\r\n")));
|
||||
let mut exit_size: usize = 0;
|
||||
let mut exit_data: *mut Char16 = ptr::null_mut();
|
||||
let orig_start: StartImageFn =
|
||||
unsafe { core::mem::transmute(ORIG_START_IMAGE.load(Ordering::Acquire)) };
|
||||
unsafe { orig_start(oc_handle, &mut exit_size, &mut exit_data) }
|
||||
}
|
||||
@@ -0,0 +1,965 @@
|
||||
import hashlib
|
||||
import http.server
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
WORK = Path(os.environ.get("REIMS_OPENVMM_WORK", r"D:\ReimsOpenvmmWork"))
|
||||
RUN_DIR = WORK / "runs" / "gate2b-intel"
|
||||
BIN_DIR = WORK / "bin"
|
||||
BASE_SYS = WORK / "disks" / "intel-base.raw"
|
||||
OC_SHIM = WORK / "disks" / "opencore-shim.raw"
|
||||
RGFX_EFI = BIN_DIR / "ReimsGraphics.efi"
|
||||
RGFX_ROM = BIN_DIR / "ReimsGraphics.rom"
|
||||
|
||||
HID_USAGE = {
|
||||
**{chr(ord("a") + i): (0x04 + i, False) for i in range(26)},
|
||||
**{chr(ord("A") + i): (0x04 + i, True) for i in range(26)},
|
||||
"1": (0x1E, False), "!": (0x1E, True),
|
||||
"2": (0x1F, False), "@": (0x1F, True),
|
||||
"3": (0x20, False), "#": (0x20, True),
|
||||
"4": (0x21, False), "$": (0x21, True),
|
||||
"5": (0x22, False), "%": (0x22, True),
|
||||
"6": (0x23, False), "^": (0x23, True),
|
||||
"7": (0x24, False), "&": (0x24, True),
|
||||
"8": (0x25, False), "*": (0x25, True),
|
||||
"9": (0x26, False), "(": (0x26, True),
|
||||
"0": (0x27, False), ")": (0x27, True),
|
||||
"\n": (0x28, False), "\r": (0x28, False),
|
||||
" ": (0x2C, False),
|
||||
"-": (0x2D, False), "_": (0x2D, True),
|
||||
"=": (0x2E, False), "+": (0x2E, True),
|
||||
"[": (0x2F, False), "{": (0x2F, True),
|
||||
"]": (0x30, False), "}": (0x30, True),
|
||||
"\\": (0x31, False), "|": (0x31, True),
|
||||
";": (0x33, False), ":": (0x33, True),
|
||||
"'": (0x34, False), '"': (0x34, True),
|
||||
"`": (0x35, False), "~": (0x35, True),
|
||||
",": (0x36, False), "<": (0x36, True),
|
||||
".": (0x37, False), ">": (0x37, True),
|
||||
"/": (0x38, False), "?": (0x38, True),
|
||||
}
|
||||
MOD_LCTRL = 0xE0
|
||||
MOD_LSHIFT = 0xE1
|
||||
MOD_LGUI = 0xE3 # Cmd on macOS
|
||||
|
||||
|
||||
def ensure_no_running_vmm():
|
||||
for exe in ("openvmm.exe", "qemu-system-x86_64.exe", "qemu-system-aarch64.exe"):
|
||||
r = subprocess.run(["tasklist", "/FI", f"IMAGENAME eq {exe}", "/NH"], capture_output=True, text=True)
|
||||
if exe.lower() in r.stdout.lower():
|
||||
raise RuntimeError(f"Stale VM process running: {exe}\n{r.stdout}")
|
||||
|
||||
|
||||
def find_fat_part_offset(data: bytearray) -> int:
|
||||
if data[512:520] == b"EFI PART":
|
||||
part_lba = struct.unpack("<Q", data[512 + 72 : 512 + 80])[0]
|
||||
n_entries = struct.unpack("<I", data[512 + 80 : 512 + 84])[0]
|
||||
esz = struct.unpack("<I", data[512 + 84 : 512 + 88])[0]
|
||||
for i in range(n_entries):
|
||||
off = part_lba * 512 + i * esz
|
||||
if data[off : off + 16] != b"\x00" * 16:
|
||||
s_lba = struct.unpack("<Q", data[off + 32 : off + 40])[0]
|
||||
return s_lba * 512
|
||||
raise RuntimeError("GPT partition not found")
|
||||
|
||||
|
||||
def inject_reims_gop_and_patch_oc(oc_img: Path, gop_efi: Path):
|
||||
efi_bytes = gop_efi.read_bytes()
|
||||
data = bytearray(oc_img.read_bytes())
|
||||
part_off = find_fat_part_offset(data)
|
||||
|
||||
bps = struct.unpack("<H", data[part_off + 11 : part_off + 13])[0]
|
||||
spc = data[part_off + 13]
|
||||
rsvd = struct.unpack("<H", data[part_off + 14 : part_off + 16])[0]
|
||||
nfats = data[part_off + 16]
|
||||
fatz32 = struct.unpack("<I", data[part_off + 36 : part_off + 40])[0]
|
||||
root_cl = struct.unpack("<I", data[part_off + 44 : part_off + 48])[0]
|
||||
assert data[part_off + 82 : part_off + 90] == b"FAT32 "
|
||||
|
||||
cluster_size = bps * spc
|
||||
fat_offs = [part_off + (rsvd + i * fatz32) * bps for i in range(nfats)]
|
||||
data_off = part_off + (rsvd + nfats * fatz32) * bps
|
||||
max_clusters = (len(data) - data_off) // cluster_size + 2
|
||||
|
||||
def get_fat(cl: int) -> int:
|
||||
o = fat_offs[0] + cl * 4
|
||||
return struct.unpack("<I", data[o : o + 4])[0] & 0x0FFF_FFFF
|
||||
|
||||
def set_fat(cl: int, val: int) -> None:
|
||||
for fo in fat_offs:
|
||||
o = fo + cl * 4
|
||||
cur = struct.unpack("<I", data[o : o + 4])[0]
|
||||
nxt = (cur & 0xF000_0000) | (val & 0x0FFF_FFFF)
|
||||
data[o : o + 4] = struct.pack("<I", nxt)
|
||||
|
||||
def cl_off(cl: int) -> int:
|
||||
return data_off + (cl - 2) * cluster_size
|
||||
|
||||
def read_chain(start_cl: int) -> list[int]:
|
||||
out = []
|
||||
cl = start_cl
|
||||
while 2 <= cl < 0x0FFF_FFF8:
|
||||
out.append(cl)
|
||||
cl = get_fat(cl)
|
||||
return out
|
||||
|
||||
def find_entry_with_prev(dir_cl: int, target83: bytes):
|
||||
slots = []
|
||||
for cl in read_chain(dir_cl):
|
||||
base = cl_off(cl)
|
||||
for idx in range(cluster_size // 32):
|
||||
off = base + idx * 32
|
||||
slots.append(off)
|
||||
e = data[off : off + 32]
|
||||
if e[0] == 0:
|
||||
return None
|
||||
if e[0] == 0xE5 or (e[11] & 0x0F) == 0x0F:
|
||||
continue
|
||||
if e[:11] == target83:
|
||||
hi = struct.unpack("<H", e[20:22])[0]
|
||||
lo = struct.unpack("<H", e[26:28])[0]
|
||||
sz = struct.unpack("<I", e[28:32])[0]
|
||||
prev_off = slots[-2] if len(slots) >= 2 else None
|
||||
return off, prev_off, (hi << 16) | lo, sz
|
||||
return None
|
||||
|
||||
efi_dir = find_entry_with_prev(root_cl, b"EFI ")
|
||||
oc_dir = find_entry_with_prev(efi_dir[2], b"OC ")
|
||||
drv_dir = find_entry_with_prev(oc_dir[2], b"Drivers ")
|
||||
if drv_dir is None:
|
||||
drv_dir = find_entry_with_prev(oc_dir[2], b"DRIVERS ")
|
||||
audio = find_entry_with_prev(drv_dir[2], b"AUDIODXEEFI")
|
||||
assert audio is not None, "AUDIODXEEFI entry not found in EFI/OC/Drivers"
|
||||
entry_off, prev_off, old_cl, old_sz = audio
|
||||
|
||||
# Delete preceding LFN slot(s) of AudioDxe.efi if present
|
||||
if prev_off is not None and (data[prev_off + 11] & 0x0F) == 0x0F:
|
||||
data[prev_off] = 0xE5
|
||||
|
||||
for cl in read_chain(old_cl):
|
||||
set_fat(cl, 0)
|
||||
|
||||
needed = max(1, math.ceil(len(efi_bytes) / cluster_size))
|
||||
new_chain = []
|
||||
for cl in range(2, max_clusters):
|
||||
if get_fat(cl) == 0:
|
||||
new_chain.append(cl)
|
||||
if len(new_chain) == needed:
|
||||
break
|
||||
assert len(new_chain) == needed, "FAT32 out of clusters"
|
||||
|
||||
for i, cl in enumerate(new_chain):
|
||||
set_fat(cl, new_chain[i + 1] if i + 1 < len(new_chain) else 0x0FFF_FFF8)
|
||||
chunk = efi_bytes[i * cluster_size : (i + 1) * cluster_size]
|
||||
data[cl_off(cl) : cl_off(cl) + cluster_size] = chunk + b"\x00" * (cluster_size - len(chunk))
|
||||
|
||||
first_cl = new_chain[0]
|
||||
short83 = b"REIMSGOPEFI"
|
||||
assert len(short83) == 11
|
||||
data[entry_off : entry_off + 11] = short83
|
||||
data[entry_off + 11] = 0x20 # archive attribute
|
||||
data[entry_off + 20 : entry_off + 22] = struct.pack("<H", (first_cl >> 16) & 0xFFFF)
|
||||
data[entry_off + 26 : entry_off + 28] = struct.pack("<H", first_cl & 0xFFFF)
|
||||
data[entry_off + 28 : entry_off + 32] = struct.pack("<I", len(efi_bytes))
|
||||
|
||||
# Readback verify FAT chain
|
||||
rb = bytearray()
|
||||
for cl in read_chain(first_cl):
|
||||
rb.extend(data[cl_off(cl) : cl_off(cl) + cluster_size])
|
||||
assert bytes(rb[: len(efi_bytes)]) == efi_bytes
|
||||
print(f"Injected EFI/OC/Drivers/ReimsGop.efi ({len(efi_bytes)} B, sha256={hashlib.sha256(efi_bytes).hexdigest()[:16]}...)")
|
||||
|
||||
# Replace AudioDxe.efi -> ReimsGop.efi in config.plist (same 12-char length!)
|
||||
old_drv = b"<string>AudioDxe.efi</string>"
|
||||
new_drv = b"<string>ReimsGop.efi</string>"
|
||||
assert len(old_drv) == len(new_drv)
|
||||
cnt = data.count(old_drv)
|
||||
assert cnt == 1, f"Expected 1 occurrence of AudioDxe.efi in config.plist, found {cnt}"
|
||||
data = bytearray(bytes(data).replace(old_drv, new_drv, 1))
|
||||
|
||||
# Apply Booter Quirks for MSVM.fd
|
||||
booter_pos = data.find(b"<key>Booter</key>")
|
||||
q_start = data.find(b"<key>Quirks</key>", booter_pos)
|
||||
d_start = data.find(b"<dict>", q_start)
|
||||
d_end = data.find(b"</dict>", d_start) + len(b"</dict>")
|
||||
old_block = bytes(data[q_start:d_end])
|
||||
pl_chunk = b'<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>' + old_block + b"</dict></plist>"
|
||||
q = plistlib.loads(pl_chunk)["Quirks"]
|
||||
q["EnableWriteUnprotector"] = True
|
||||
q["RebuildAppleMemoryMap"] = True
|
||||
q["SyncRuntimePermissions"] = True
|
||||
q["SetupVirtualMap"] = False
|
||||
q["DevirtualiseMmio"] = False
|
||||
q["AvoidRuntimeDefrag"] = True
|
||||
q["ProtectUefiServices"] = False
|
||||
qlines = ["<key>Quirks</key>", "\t\t<dict>"]
|
||||
for k, v in q.items():
|
||||
qlines.append(
|
||||
f"\t\t\t<key>{k}</key><{'true' if v else 'false'}/>"
|
||||
if isinstance(v, bool)
|
||||
else f"\t\t\t<key>{k}</key><integer>{v}</integer>"
|
||||
)
|
||||
qlines.append("\t\t</dict>")
|
||||
new_block = "\n".join(qlines).encode("utf-8")
|
||||
new_block = new_block + b" " * (len(old_block) - len(new_block))
|
||||
data[q_start:d_end] = new_block
|
||||
|
||||
tgt_key = data.find(b"<key>Target</key>")
|
||||
i0 = data.find(b"<integer>", tgt_key)
|
||||
i1 = data.find(b"</integer>", i0)
|
||||
data[i0 + 9 : i1] = b"75"
|
||||
|
||||
ba_key = b"<key>boot-args</key>"
|
||||
bi = data.find(ba_key)
|
||||
s0 = data.find(b"<string>", bi)
|
||||
s1 = data.find(b"</string>", s0) + len(b"</string>")
|
||||
old_ba = data[s0 + 8 : s1 - 9].decode("utf-8", "replace")
|
||||
if "-s" in old_ba.split():
|
||||
toks = [t for t in old_ba.split() if t != "-s"]
|
||||
new_inner = " ".join(toks).encode("utf-8")
|
||||
pad = len(data[s0 + 8 : s1 - 9]) - len(new_inner)
|
||||
assert pad >= 0
|
||||
data[s0 + 8 : s1 - 9] = new_inner + b" " * pad
|
||||
oc_img.write_bytes(data)
|
||||
|
||||
|
||||
def bmp_stats(path: Path) -> dict:
|
||||
raw = path.read_bytes()
|
||||
assert raw[:2] == b"BM", f"Not BMP: {path}"
|
||||
data_off = struct.unpack_from("<I", raw, 10)[0]
|
||||
w, h = struct.unpack_from("<ii", raw, 18)
|
||||
bpp = struct.unpack_from("<H", raw, 28)[0]
|
||||
aw, ah = abs(w), abs(h)
|
||||
row_stride = ((aw * (bpp // 8) + 3) // 4) * 4
|
||||
total = 0
|
||||
nonblack = 0
|
||||
buckets = set()
|
||||
# Sample step across rows & cols so 1920x1080 stays fast
|
||||
step_y = max(1, ah // 180)
|
||||
step_x = max(1, aw // 240)
|
||||
bypp = bpp // 8
|
||||
for y in range(0, ah, step_y):
|
||||
row_start = data_off + y * row_stride
|
||||
for x in range(0, aw, step_x):
|
||||
p = row_start + x * bypp
|
||||
b, g, r = raw[p], raw[p + 1], raw[p + 2]
|
||||
total += 1
|
||||
if r > 12 or g > 12 or b > 12:
|
||||
nonblack += 1
|
||||
buckets.add((r >> 4, g >> 4, b >> 4))
|
||||
return {
|
||||
"width": aw,
|
||||
"height": ah,
|
||||
"bpp": bpp,
|
||||
"bytes": len(raw),
|
||||
"sha": hashlib.sha256(raw).hexdigest()[:16],
|
||||
"nonblack_pct": round(100.0 * nonblack / max(1, total), 2),
|
||||
"color_buckets": len(buckets),
|
||||
}
|
||||
|
||||
|
||||
def ctl_cmd(ctl_port: int, line: str) -> str:
|
||||
with socket.create_connection(("127.0.0.1", ctl_port), timeout=10.0) as cs:
|
||||
cs.sendall((line + "\n").encode("utf-8"))
|
||||
return cs.recv(4096).decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def is_pinyin_pill(path: Path) -> bool:
|
||||
raw = path.read_bytes()
|
||||
off = struct.unpack_from("<I", raw, 10)[0]
|
||||
w, h = struct.unpack_from("<ii", raw, 18)
|
||||
aw, ah = abs(w), abs(h)
|
||||
if aw != 1024 or ah != 576:
|
||||
return False
|
||||
rs = ((aw * 3 + 3) // 4) * 4
|
||||
col_ok = []
|
||||
for x in range(660, 830):
|
||||
cnt = 0
|
||||
for y in range(6, 24):
|
||||
ry = y if h < 0 else (ah - 1 - y)
|
||||
i = off + ry * rs + x * 3
|
||||
if raw[i] > 200 and raw[i + 1] > 200 and raw[i + 2] > 200:
|
||||
cnt += 1
|
||||
col_ok.append(1 if cnt >= 9 else 0)
|
||||
best = max(sum(col_ok[i : i + 24]) for i in range(len(col_ok) - 24))
|
||||
return best >= 10
|
||||
|
||||
|
||||
def ensure_abc_input(ctl_port: int, probe_path: Path):
|
||||
ctl_cmd(ctl_port, f"screenshot {probe_path}")
|
||||
before = is_pinyin_pill(probe_path)
|
||||
if not before:
|
||||
print(f"[IME] is_pinyin_pill False (already ABC, no Ctrl+Space) ({probe_path.name})", flush=True)
|
||||
return
|
||||
for attempt in range(3):
|
||||
hid_tap(ctl_port, 0x2C, hold_s=0.14, post_s=3.0, mods=[MOD_LCTRL])
|
||||
ctl_cmd(ctl_port, f"screenshot {probe_path}")
|
||||
after = is_pinyin_pill(probe_path)
|
||||
print(f"[IME] attempt {attempt+1}: is_pinyin_pill {before} -> {after} ({probe_path.name})", flush=True)
|
||||
if not after:
|
||||
return
|
||||
before = after
|
||||
|
||||
|
||||
def abs_click(ctl_port: int, x: int, y: int, post_s: float = 0.5):
|
||||
ctl_cmd(ctl_port, f"abs {x} {y} 0")
|
||||
time.sleep(0.15)
|
||||
ctl_cmd(ctl_port, f"abs {x} {y} 1")
|
||||
time.sleep(0.10)
|
||||
ctl_cmd(ctl_port, f"abs {x} {y} 0")
|
||||
if post_s > 0:
|
||||
time.sleep(post_s)
|
||||
|
||||
|
||||
def hid_tap(ctl_port: int, usage: int, hold_s: float = 0.08, post_s: float = 0.08, mods: list[int] = ()):
|
||||
for m in mods:
|
||||
ctl_cmd(ctl_port, f"hid {m} 1")
|
||||
time.sleep(0.03)
|
||||
ctl_cmd(ctl_port, f"hid {usage} 1")
|
||||
time.sleep(hold_s)
|
||||
ctl_cmd(ctl_port, f"hid {usage} 0")
|
||||
for m in reversed(mods):
|
||||
time.sleep(0.03)
|
||||
ctl_cmd(ctl_port, f"hid {m} 0")
|
||||
time.sleep(post_s)
|
||||
|
||||
|
||||
def hid_type(ctl_port: int, text: str, hold_s: float = 0.05, gap_s: float = 0.06):
|
||||
for ch in text:
|
||||
usage, shift = HID_USAGE[ch]
|
||||
mods = (MOD_LSHIFT,) if shift else ()
|
||||
hid_tap(ctl_port, usage, hold_s=hold_s, post_s=gap_s, mods=mods)
|
||||
|
||||
|
||||
def get_applesmc_osk() -> str:
|
||||
osk = os.environ.get("REIMS_SMC_OSK", "").strip()
|
||||
if not osk:
|
||||
raise RuntimeError("Set REIMS_SMC_OSK in environment before running Gate 2B")
|
||||
return osk
|
||||
|
||||
|
||||
def get_guest_password() -> str:
|
||||
return os.environ.get("REIMS_GUEST_PASSWORD", "testpass")
|
||||
|
||||
|
||||
def get_guest_mac() -> str:
|
||||
return os.environ.get("REIMS_VM_MAC", "52-54-00-12-34-56")
|
||||
|
||||
|
||||
|
||||
def build_guest_script(http_port: int, do_full_checks: bool) -> str:
|
||||
if not do_full_checks:
|
||||
tpl = r"""#!/bin/bash
|
||||
set -e
|
||||
JXA_RES=$(osascript -l JavaScript -e '
|
||||
ObjC.import("Metal");
|
||||
var dev = $.MTLCreateSystemDefaultDevice();
|
||||
dev ? ObjC.unwrap(dev.name) : "NIL";
|
||||
')
|
||||
PS_RES=$(ps aux | grep -E "Finder\.app|WindowServer" | grep -v grep)
|
||||
export G2B_METAL="$JXA_RES"
|
||||
export G2B_SW="$(sw_vers | tr '\n' '|')"
|
||||
export G2B_PS="$PS_RES"
|
||||
osascript -l JavaScript -e '
|
||||
ObjC.import("Foundation");
|
||||
var env = $.NSProcessInfo.processInfo.environment;
|
||||
var val = function(k) { return ObjC.unwrap(env.objectForKey(k)) || ""; };
|
||||
var obj = {phase: "cold_reboot_check", metal_device: val("G2B_METAL"), sw_vers: val("G2B_SW"), ps: val("G2B_PS")};
|
||||
$.NSString.stringWithString(JSON.stringify(obj)).writeToFileAtomicallyEncodingError("/tmp/g2b_reboot.json", true, 4, Ref());
|
||||
' >/dev/null
|
||||
curl -s -X POST -H "Content-Type: application/json" --data-binary @/tmp/g2b_reboot.json "http://10.0.2.2:__HTTP_PORT__/report" >/dev/null
|
||||
defaults write com.apple.loginwindow TALLogoutSavesState -bool false || true
|
||||
/bin/sync
|
||||
echo __GUEST_PW__ | sudo -S /sbin/shutdown -h now
|
||||
"""
|
||||
return tpl.replace("__HTTP_PORT__", str(http_port)).replace("__GUEST_PW__", get_guest_password())
|
||||
|
||||
tpl = r"""#!/bin/bash
|
||||
exec > /tmp/gate2b_guest.log 2>&1
|
||||
SWV=$(sw_vers | tr '\n' '|')
|
||||
UNAME=$(uname -a)
|
||||
NCPU=$(sysctl -n hw.ncpu)
|
||||
PS_GUI=$(ps aux | grep -E 'Finder\.app|WindowServer' | grep -v grep)
|
||||
DISP=$(system_profiler SPDisplaysDataType 2>&1)
|
||||
KEXTS=$(kextstat | grep -iE 'reims|graft|rgfx')
|
||||
IOREG=$(ioreg -l | grep -iE 'ReimsGraphics|Rgfx' | head -n 40)
|
||||
|
||||
METAL_RES=$(osascript -l JavaScript -e '
|
||||
ObjC.import("Foundation");
|
||||
ObjC.import("Metal");
|
||||
var dev = $.MTLCreateSystemDefaultDevice();
|
||||
if (!dev || dev.isNil()) throw new Error("NO_METAL_DEVICE");
|
||||
var q = dev.newCommandQueue;
|
||||
var sz881 = $.NSData.alloc.initWithBase64EncodedStringOptions("CAAAAAAAAAAIAAAAAAAAAAEAAAAAAAAA", 0);
|
||||
function dispatch8x8(enc) {
|
||||
var sel = "dispatchThreadgroups:threadsPerThreadgroup:";
|
||||
var sig = enc.methodSignatureForSelector(sel);
|
||||
var inv = $.NSInvocation.invocationWithMethodSignature(sig);
|
||||
inv.setTarget(enc);
|
||||
inv.setSelector(sel);
|
||||
inv["setArgument:atIndex:"](sz881.bytes, 2);
|
||||
inv["setArgument:atIndex:"](sz881.bytes, 3);
|
||||
inv.invoke;
|
||||
}
|
||||
var msl = [
|
||||
"#include <metal_stdlib>",
|
||||
"using namespace metal;",
|
||||
"kernel void fill(device uint* buf [[buffer(0)]], texture2d<float, access::write> tex [[texture(0)]], uint2 gid [[thread_position_in_grid]]) {",
|
||||
" if (gid.x == 0 && gid.y == 0) { buf[0] = 0xCAFEBABEu; buf[1] = 0x13572468u; buf[2] = 0xDEADBEEFu; buf[3] = 0x99887766u; }",
|
||||
" if (gid.x < 32 && gid.y < 32) { tex.write(float4(float(gid.x)/31.0f, float(gid.y)/31.0f, 0.5f, 1.0f), gid); }",
|
||||
"}",
|
||||
"kernel void readback(device const uint* privBuf [[buffer(0)]], device uint* outBuf [[buffer(1)]], texture2d<float, access::read> privTex [[texture(0)]], device uint* outPx [[buffer(2)]], uint2 gid [[thread_position_in_grid]]) {",
|
||||
" if (gid.x == 0 && gid.y == 0) { for (uint i=0;i<4;i++) outBuf[i]=privBuf[i]; }",
|
||||
" if (gid.x == 10 && gid.y == 20) { float4 p = privTex.read(gid); outPx[0] = (uint(p.r*255.0f+0.5f)<<16)|(uint(p.g*255.0f+0.5f)<<8)|uint(p.b*255.0f+0.5f); }",
|
||||
"}"
|
||||
].join("\n");
|
||||
var err = Ref();
|
||||
var lib = dev.newLibraryWithSourceOptionsError(msl, $.MTLCompileOptions.alloc.init, err);
|
||||
if (!lib || lib.isNil()) throw new Error("LIB_FAIL");
|
||||
var p1 = dev.newComputePipelineStateWithFunctionError(lib.newFunctionWithName("fill"), err);
|
||||
var p2 = dev.newComputePipelineStateWithFunctionError(lib.newFunctionWithName("readback"), err);
|
||||
var privBuf = dev.newBufferWithLengthOptions(256, 2 << 4);
|
||||
var outBuf = dev.newBufferWithLengthOptions(256, 0);
|
||||
var outPx = dev.newBufferWithLengthOptions(64, 0);
|
||||
var td = $.MTLTextureDescriptor.texture2DDescriptorWithPixelFormatWidthHeightMipmapped(70, 32, 32, false);
|
||||
td.storageMode = 2; td.usage = 3;
|
||||
var privTex = dev.newTextureWithDescriptor(td);
|
||||
var cb1 = q.commandBuffer;
|
||||
var e1 = cb1.computeCommandEncoder;
|
||||
e1.setComputePipelineState(p1); e1["setBuffer:offset:atIndex:"](privBuf, 0, 0); e1["setTexture:atIndex:"](privTex, 0);
|
||||
dispatch8x8(e1);
|
||||
e1.endEncoding; cb1.commit; cb1.waitUntilCompleted;
|
||||
var cb2 = q.commandBuffer;
|
||||
var e2 = cb2.computeCommandEncoder;
|
||||
e2.setComputePipelineState(p2); e2["setBuffer:offset:atIndex:"](privBuf, 0, 0); e2["setBuffer:offset:atIndex:"](outBuf, 0, 1); e2["setTexture:atIndex:"](privTex, 0); e2["setBuffer:offset:atIndex:"](outPx, 0, 2);
|
||||
dispatch8x8(e2);
|
||||
e2.endEncoding; cb2.commit; cb2.waitUntilCompleted;
|
||||
var d1 = $.NSData.dataWithBytesLength(outBuf.contents, 16);
|
||||
d1.writeToFileAtomically("/tmp/m_buf.bin", true);
|
||||
var d2 = $.NSData.dataWithBytesLength(outPx.contents, 4);
|
||||
d2.writeToFileAtomically("/tmp/m_px.bin", true);
|
||||
JSON.stringify({name: ObjC.unwrap(dev.name), regId: Number(dev.registryID)});
|
||||
' 2>&1)
|
||||
BUF_HEX=$(od -An -tx4 /tmp/m_buf.bin 2>/dev/null | xargs)
|
||||
PX_HEX=$(od -An -tx4 /tmp/m_px.bin 2>/dev/null | xargs)
|
||||
|
||||
INIT_DIM=$(osascript -l JavaScript -e '
|
||||
ObjC.import("CoreGraphics");
|
||||
var did = $.CGMainDisplayID();
|
||||
Number($.CGDisplayPixelsWide(did)) + "x" + Number($.CGDisplayPixelsHigh(did));
|
||||
' 2>&1)
|
||||
|
||||
curl -s -X POST -d "$INIT_DIM" "http://10.0.2.2:__HTTP_PORT__/before_resize" >/dev/null
|
||||
|
||||
RES_SWITCH=$(INIT_DIM="$INIT_DIM" osascript -l JavaScript -e '
|
||||
ObjC.import("Foundation");
|
||||
ObjC.import("CoreGraphics");
|
||||
var initDim = ObjC.unwrap($.NSProcessInfo.processInfo.environment.objectForKey("INIT_DIM")) || "";
|
||||
var did = $.CGMainDisplayID();
|
||||
var w1 = Number($.CGDisplayPixelsWide(did));
|
||||
var h1 = Number($.CGDisplayPixelsHigh(did));
|
||||
for (var i = 0; i < 40; i++) {
|
||||
if (w1 + "x" + h1 !== initDim) break;
|
||||
$.NSThread.sleepForTimeInterval(0.5);
|
||||
w1 = Number($.CGDisplayPixelsWide(did));
|
||||
h1 = Number($.CGDisplayPixelsHigh(did));
|
||||
}
|
||||
"BEFORE=" + initDim + " AFTER=" + w1 + "x" + h1;
|
||||
' 2>&1)
|
||||
|
||||
curl -s -X POST "http://10.0.2.2:__HTTP_PORT__/res_switched" >/dev/null
|
||||
sleep 2
|
||||
|
||||
export G2B_SW="$SWV"
|
||||
export G2B_UNAME="$UNAME"
|
||||
export G2B_NCPU="$NCPU"
|
||||
export G2B_PS="$PS_GUI"
|
||||
export G2B_DISP="$DISP"
|
||||
export G2B_KEXTS="$KEXTS"
|
||||
export G2B_IOREG="$IOREG"
|
||||
export G2B_METAL="$METAL_RES"
|
||||
export G2B_BUF="$BUF_HEX"
|
||||
export G2B_PX="$PX_HEX"
|
||||
export G2B_RES="$RES_SWITCH"
|
||||
|
||||
osascript -l JavaScript -e '
|
||||
ObjC.import("Foundation");
|
||||
var env = $.NSProcessInfo.processInfo.environment;
|
||||
var val = function(k) { return ObjC.unwrap(env.objectForKey(k)) || ""; };
|
||||
var payload = {
|
||||
phase: "boot1_checks",
|
||||
sw_vers: val("G2B_SW"),
|
||||
uname: val("G2B_UNAME"),
|
||||
ncpu: val("G2B_NCPU"),
|
||||
ps_gui: val("G2B_PS"),
|
||||
displays: val("G2B_DISP"),
|
||||
kexts: val("G2B_KEXTS"),
|
||||
ioreg: val("G2B_IOREG"),
|
||||
metal_res: val("G2B_METAL"),
|
||||
buf_hex: val("G2B_BUF"),
|
||||
px_hex: val("G2B_PX"),
|
||||
res_switch: val("G2B_RES")
|
||||
};
|
||||
$.NSString.stringWithString(JSON.stringify(payload)).writeToFileAtomicallyEncodingError("/tmp/g2b_report.json", true, 4, Ref());
|
||||
' >/dev/null
|
||||
curl -s -X POST -H "Content-Type: application/json" --data-binary @/tmp/g2b_report.json "http://10.0.2.2:__HTTP_PORT__/report" >/dev/null
|
||||
|
||||
curl -s "http://10.0.2.2:__HTTP_PORT__/shutdown_wait" >/dev/null
|
||||
defaults write com.apple.loginwindow TALLogoutSavesState -bool false || true
|
||||
/bin/sync
|
||||
echo __GUEST_PW__ | sudo -S /sbin/shutdown -h now
|
||||
"""
|
||||
return tpl.replace("__HTTP_PORT__", str(http_port)).replace("__GUEST_PW__", get_guest_password())
|
||||
|
||||
|
||||
def run_boot(boot_label: str, oc_img: Path, osk: str, create_disk: bool, do_full_checks: bool):
|
||||
with socket.socket() as s1, socket.socket() as s2, socket.socket() as s3:
|
||||
s1.bind(("127.0.0.1", 0))
|
||||
s2.bind(("127.0.0.1", 0))
|
||||
s3.bind(("127.0.0.1", 0))
|
||||
com1_port = s1.getsockname()[1]
|
||||
ctl_port = s2.getsockname()[1]
|
||||
http_port = s3.getsockname()[1]
|
||||
|
||||
state = {
|
||||
"reports": [],
|
||||
"script_fetched_ev": threading.Event(),
|
||||
"before_resize_ev": threading.Event(),
|
||||
"res_switched_ev": threading.Event(),
|
||||
"report_ev": threading.Event(),
|
||||
"allow_shutdown": threading.Event(),
|
||||
}
|
||||
if not do_full_checks:
|
||||
state["allow_shutdown"].set()
|
||||
|
||||
script_body = build_guest_script(http_port, do_full_checks)
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/run.sh":
|
||||
state["script_fetched_ev"].set()
|
||||
b = script_body.encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain")
|
||||
self.send_header("Content-Length", str(len(b)))
|
||||
self.end_headers()
|
||||
self.wfile.write(b)
|
||||
elif self.path == "/shutdown_wait":
|
||||
state["allow_shutdown"].wait(timeout=30)
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.write(b"OK\n")
|
||||
else:
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def do_POST(self):
|
||||
ln = int(self.headers.get("Content-Length", "0"))
|
||||
raw = self.rfile.read(ln)
|
||||
if self.path == "/before_resize":
|
||||
state["before_resize_ev"].set()
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.write(b"OK")
|
||||
elif self.path == "/res_switched":
|
||||
state["res_switched_ev"].set()
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.write(b"OK")
|
||||
elif self.path == "/report":
|
||||
state["reports"].append(json.loads(raw.decode("utf-8", "replace")))
|
||||
state["report_ev"].set()
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.write(b"OK")
|
||||
else:
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", http_port), Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
|
||||
env = {
|
||||
**os.environ,
|
||||
"REIMS_SMC_OSK": osk,
|
||||
"REIMS_VGPU_LOG": "info",
|
||||
"OPENVMM_LOG": "info,usb_xhci=debug",
|
||||
"RUST_LOG": "info,usb_xhci=debug,reims_vgpu=info,reims_vgpu_graphics=info,reims_vgpu_vulkan=info",
|
||||
"MESA_VK_DEVICE_SELECT": "10de:2231",
|
||||
"VK_LOADER_DEVICE_SELECT": "10de:2231",
|
||||
}
|
||||
env.pop("REIMS_VGPU_WINDOW", None)
|
||||
|
||||
vmgs_spec = "file:nvram.vmgs;create=VMGS_DEFAULT,fmt-on-fail" if create_disk else "file:nvram.vmgs"
|
||||
disk_spec = f"sqldiff:sys-diff.sqlite;create:file:{BASE_SYS},on=sys" if create_disk else f"sqldiff:sys-diff.sqlite:file:{BASE_SYS},on=sys"
|
||||
|
||||
cmd = [
|
||||
str(BIN_DIR / "openvmm.exe"),
|
||||
"--single-process",
|
||||
"--hypervisor", "whp",
|
||||
"--memory", "8G",
|
||||
"--processors", "4",
|
||||
"--smt", "off",
|
||||
"--vps-per-socket", "4",
|
||||
"--macos-x64-compat",
|
||||
"--applesmc",
|
||||
"--uefi", f"firmware={BIN_DIR / 'MSVM.fd'},console=com1,disable_frontpage,default_boot_always_attempt",
|
||||
"--com1", f"listen=tcp:127.0.0.1:{com1_port}",
|
||||
"--vmgs", vmgs_spec,
|
||||
"--pcie-ecam-below-4gb",
|
||||
"--pcie-root-complex", "rc0,low_mmio=2688M,high_mmio=4G",
|
||||
"--pcie-root-port", "rc0:gpu",
|
||||
"--reims-vgpu", f"port=gpu,window=1920x1080,rom={RGFX_ROM}",
|
||||
"--pcie-root-port", "rc0:xhci",
|
||||
"--usb-xhci", "xhci",
|
||||
"--usb-device", "mock-hid",
|
||||
"--reims-input-listen", f"127.0.0.1:{ctl_port}",
|
||||
"--pcie-root-port", "rc0:oc",
|
||||
"--nvme-pci", "id=oc,pcie_port=oc,serial=REIMSOC0",
|
||||
"--disk", f"file:{oc_img},on=oc",
|
||||
"--pcie-root-port", "rc0:sys",
|
||||
"--nvme-pci", "id=sys,pcie_port=sys,serial=reims-ctl",
|
||||
"--disk", disk_spec,
|
||||
"--pcie-root-port", "rc0:net",
|
||||
"--virtio-net", f"pcie_port=net:mac={get_guest_mac()}:consomme:slirp,hostfwd=tcp:127.0.0.1:22229-:22",
|
||||
"--guest-shutdown-action", "exit",
|
||||
"--guest-crash-action", "exit:2",
|
||||
]
|
||||
|
||||
com1_log = RUN_DIR / f"{boot_label}_com1.log"
|
||||
stderr_log = RUN_DIR / f"{boot_label}_stderr.log"
|
||||
stdout_f = open(RUN_DIR / f"{boot_label}_stdout.log", "wb")
|
||||
stderr_f = open(stderr_log, "wb")
|
||||
proc = subprocess.Popen(cmd, cwd=RUN_DIR, env=env, stdin=subprocess.PIPE, stdout=stdout_f, stderr=stderr_f)
|
||||
|
||||
buf_lock = threading.Lock()
|
||||
buf = bytearray()
|
||||
sock_holder = [None]
|
||||
stop = [False]
|
||||
|
||||
def reader():
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline and not stop[0] and proc.poll() is None:
|
||||
try:
|
||||
sock = socket.create_connection(("127.0.0.1", com1_port), timeout=1.0)
|
||||
sock.settimeout(0.5)
|
||||
sock_holder[0] = sock
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.05)
|
||||
sock = sock_holder[0]
|
||||
if not sock:
|
||||
return
|
||||
with open(com1_log, "wb") as lf:
|
||||
while not stop[0]:
|
||||
try:
|
||||
data = sock.recv(4096)
|
||||
if not data:
|
||||
break
|
||||
lf.write(data)
|
||||
lf.flush()
|
||||
with buf_lock:
|
||||
buf.extend(data)
|
||||
except TimeoutError:
|
||||
continue
|
||||
except OSError:
|
||||
break
|
||||
|
||||
t = threading.Thread(target=reader, daemon=True)
|
||||
t.start()
|
||||
|
||||
t0 = time.monotonic()
|
||||
menu_picked = False
|
||||
booting_at = None
|
||||
fv_unlocked = False
|
||||
fv_retry_at = 0.0
|
||||
saw_splash = False
|
||||
desktop_at = None
|
||||
shots = {}
|
||||
t_res_switch = None
|
||||
|
||||
try:
|
||||
# Phase A: OpenCore -> FileVault UI -> XNU -> Finder Desktop
|
||||
while time.monotonic() - t0 < 480:
|
||||
if proc.poll() is not None:
|
||||
raise RuntimeError(f"[{boot_label}] openvmm exited early rc={proc.returncode}")
|
||||
with buf_lock:
|
||||
txt = buf.decode("utf-8", "replace")
|
||||
err_txt = stderr_log.read_text("utf-8", "ignore") if stderr_log.exists() else ""
|
||||
|
||||
if not menu_picked and "Choose the Operating System:" in txt and sock_holder[0]:
|
||||
time.sleep(0.3)
|
||||
# Pick first Macintosh HD entry (0 or 1 depending on config)
|
||||
sock_holder[0].sendall(b"1\r")
|
||||
menu_picked = True
|
||||
print(f"[{boot_label} +{time.monotonic()-t0:.1f}s] Selected OC entry", flush=True)
|
||||
|
||||
if booting_at is None and "Should boot from " in txt:
|
||||
booting_at = time.monotonic()
|
||||
assert "Err(0x3) <- EB.G.OBG" not in txt, "Unexpected GOP error EB.G.OBG!"
|
||||
print(f"[{boot_label} +{time.monotonic()-t0:.1f}s] Launching Macintosh HD (GOP check passed!)", flush=True)
|
||||
|
||||
# Poll FileVault UI after Should boot from ...
|
||||
if booting_at is not None and not fv_unlocked and "EXITBS:END" not in txt:
|
||||
probe = RUN_DIR / f"{boot_label}_fv_probe.bmp"
|
||||
try:
|
||||
resp = ctl_cmd(ctl_port, f"screenshot {probe}")
|
||||
if resp.startswith("ok") and probe.exists():
|
||||
st = bmp_stats(probe)
|
||||
print(f"[{boot_label} +{time.monotonic()-t0:.1f}s] FV probe: {st}", flush=True)
|
||||
if st["nonblack_pct"] >= 35.0 and st["color_buckets"] >= 20:
|
||||
shutil.copy2(probe, RUN_DIR / f"{boot_label}_01_filevault.bmp")
|
||||
shots["filevault"] = st
|
||||
print(f"[{boot_label} +{time.monotonic()-t0:.1f}s] FileVault UI visible: {st}", flush=True)
|
||||
time.sleep(1.5)
|
||||
if "EXITBS:END" not in txt and sock_holder[0]:
|
||||
print(f"[{boot_label} +{time.monotonic()-t0:.1f}s] Sending FileVault unlock over COM1 SimpleTextIn", flush=True)
|
||||
for ch in (get_guest_password() + "\r").encode("utf-8"):
|
||||
sock_holder[0].sendall(bytes([ch]))
|
||||
time.sleep(0.08)
|
||||
fv_unlocked = True
|
||||
fv_retry_at = time.monotonic() + 12.0
|
||||
print(f"[{boot_label} +{time.monotonic()-t0:.1f}s] FileVault unlock submitted", flush=True)
|
||||
except OSError as e:
|
||||
print(f"[{boot_label}] CTL probe wait: {e}", flush=True)
|
||||
elif fv_unlocked and "EXITBS:END" not in txt and sock_holder[0] and time.monotonic() >= fv_retry_at:
|
||||
fv_retry_at = time.monotonic() + 12.0
|
||||
print(f"[{boot_label} +{time.monotonic()-t0:.1f}s] Retrying FileVault unlock over COM1 SimpleTextIn", flush=True)
|
||||
for ch in (get_guest_password() + "\r").encode("utf-8"):
|
||||
sock_holder[0].sendall(bytes([ch]))
|
||||
time.sleep(0.08)
|
||||
|
||||
if "the display shows IOSurface" in err_txt and "EXITBS:END" in txt:
|
||||
probe = RUN_DIR / f"{boot_label}_desk_probe.bmp"
|
||||
try:
|
||||
resp = ctl_cmd(ctl_port, f"screenshot {probe}")
|
||||
if resp.startswith("ok") and probe.exists():
|
||||
st = bmp_stats(probe)
|
||||
finder_ok = "from Finder[" in txt
|
||||
ime_ok = ("from TextInputMenuAgent[" in txt) or ((time.monotonic() - t0) > 155)
|
||||
hid_cnt = txt.count("AppleUserUSBHostHIDDevice:")
|
||||
xhci_ready = (
|
||||
"CONFIG_EP slot_id=0x1" in err_txt
|
||||
and "CONFIG_EP slot_id=0x2" in err_txt
|
||||
and "req_type=0x21 req=0x9" in err_txt
|
||||
)
|
||||
hid_ok = (hid_cnt >= 2) or xhci_ready
|
||||
print(f"[{boot_label} +{time.monotonic()-t0:.1f}s] IOSurface shot: {st} finder={finder_ok} ime={ime_ok} hid={hid_cnt} xhci={xhci_ready}", flush=True)
|
||||
if st["nonblack_pct"] < 15.0:
|
||||
saw_splash = True
|
||||
if (
|
||||
(saw_splash or (time.monotonic() - t0 > 95))
|
||||
and finder_ok
|
||||
and ime_ok
|
||||
and hid_ok
|
||||
and st["nonblack_pct"] >= 45.0
|
||||
and st["color_buckets"] >= 50
|
||||
):
|
||||
print(f"[{boot_label} +{time.monotonic()-t0:.1f}s] Finder, IME & HID ready! Settling 12s...", flush=True)
|
||||
time.sleep(12.0)
|
||||
desktop_at = time.monotonic() - t0
|
||||
desk_path = RUN_DIR / f"{boot_label}_02_desktop.bmp"
|
||||
ctl_cmd(ctl_port, f"screenshot {desk_path}")
|
||||
shots["desktop"] = bmp_stats(desk_path)
|
||||
print(f"[{boot_label}] Saved 02_desktop: {shots['desktop']}", flush=True)
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(3.5)
|
||||
|
||||
assert desktop_at is not None, f"[{boot_label}] Timed out waiting for Finder desktop"
|
||||
|
||||
def wait_terminal(timeout_s: float = 30.0) -> bool:
|
||||
deadline = time.monotonic() + timeout_s
|
||||
while time.monotonic() < deadline:
|
||||
with buf_lock:
|
||||
cur_t = buf.decode("utf-8", "replace")
|
||||
if "from Terminal[" in cur_t:
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
# Phase B: Quit App Store, hover & open Finder via Dock twice (15s wait), deterministically ensure ABC input,
|
||||
# and launch Terminal.app via Cmd+Shift+G (with "/" root scan settle + lowercase path).
|
||||
def open_terminal_via_finder(tag: str):
|
||||
hid_tap(ctl_port, 0x29, hold_s=0.08, post_s=0.6) # Esc any open sheet/menu
|
||||
hid_tap(ctl_port, HID_USAGE["g"][0], hold_s=0.14, post_s=4.0, mods=[MOD_LGUI, MOD_LSHIFT])
|
||||
ensure_abc_input(ctl_port, RUN_DIR / f"{boot_label}_{tag}_ime.bmp")
|
||||
hid_tap(ctl_port, HID_USAGE["a"][0], hold_s=0.10, post_s=0.4, mods=[MOD_LGUI])
|
||||
hid_tap(ctl_port, 0x2A, hold_s=0.08, post_s=0.5) # Backspace
|
||||
hid_type(ctl_port, "/", hold_s=0.06, gap_s=1.0)
|
||||
hid_type(ctl_port, "system/applications/utilities/terminal.app", hold_s=0.06, gap_s=0.09)
|
||||
time.sleep(2.0)
|
||||
ctl_cmd(ctl_port, f"screenshot {RUN_DIR / f'{boot_label}_{tag}_go.bmp'}")
|
||||
hid_tap(ctl_port, 0x28, hold_s=0.12, post_s=2.5)
|
||||
hid_tap(ctl_port, 0x28, hold_s=0.12, post_s=2.5)
|
||||
hid_tap(ctl_port, HID_USAGE["o"][0], hold_s=0.14, post_s=2.0, mods=[MOD_LGUI])
|
||||
|
||||
print(f"[{boot_label}] Quitting App Store (Cmd+Q) and clicking Finder Dock (1888, 30886)...", flush=True)
|
||||
hid_tap(ctl_port, HID_USAGE["q"][0], hold_s=0.14, post_s=3.0, mods=[MOD_LGUI])
|
||||
ctl_cmd(ctl_port, "abs 1888 30886 0")
|
||||
time.sleep(0.8)
|
||||
abs_click(ctl_port, 1888, 30886, post_s=3.0)
|
||||
abs_click(ctl_port, 1888, 30886, post_s=15.0)
|
||||
|
||||
open_terminal_via_finder("m1")
|
||||
|
||||
if not wait_terminal(90.0):
|
||||
print(f"[{boot_label}] Terminal client not seen after 90s; retrying Finder focus -> Cmd+Shift+G...", flush=True)
|
||||
abs_click(ctl_port, 1888, 30886, post_s=3.0)
|
||||
open_terminal_via_finder("m2")
|
||||
assert wait_terminal(90.0), f"[{boot_label}] Terminal never launched (no from Terminal[ in com1.log)"
|
||||
|
||||
print(f"[{boot_label}] Terminal launched (seen in com1.log)! Waiting 12s for window & shell prompt...", flush=True)
|
||||
time.sleep(12.0)
|
||||
hid_tap(ctl_port, HID_USAGE["n"][0], hold_s=0.12, post_s=3.0, mods=[MOD_LGUI])
|
||||
term_bmp = RUN_DIR / f"{boot_label}_02b_terminal.bmp"
|
||||
ctl_cmd(ctl_port, f"screenshot {term_bmp}")
|
||||
shots["terminal"] = bmp_stats(term_bmp)
|
||||
|
||||
ensure_abc_input(ctl_port, RUN_DIR / f"{boot_label}_m1_pre_curl.bmp")
|
||||
cmd_str = f"curl -s http://10.0.2.2:{http_port}/run.sh | bash\n"
|
||||
hid_type(ctl_port, cmd_str, hold_s=0.04, gap_s=0.05)
|
||||
print(f"[{boot_label}] Sent guest command via HID: {cmd_str.strip()}", flush=True)
|
||||
|
||||
if not state["script_fetched_ev"].wait(timeout=18.0):
|
||||
print(f"[{boot_label}] Retry 1: Click Terminal Dock icon (27040, 30886) + Cmd+N + ensure ABC + retype curl...", flush=True)
|
||||
ctl_cmd(ctl_port, "abs 27040 30886 0")
|
||||
time.sleep(0.5)
|
||||
abs_click(ctl_port, 27040, 30886, post_s=2.5)
|
||||
abs_click(ctl_port, 27040, 30886, post_s=2.5)
|
||||
hid_tap(ctl_port, HID_USAGE["n"][0], hold_s=0.12, post_s=3.0, mods=[MOD_LGUI])
|
||||
ensure_abc_input(ctl_port, RUN_DIR / f"{boot_label}_m2_retry1.bmp")
|
||||
hid_type(ctl_port, cmd_str, hold_s=0.04, gap_s=0.05)
|
||||
if not state["script_fetched_ev"].wait(timeout=20.0):
|
||||
ctl_cmd(ctl_port, f"screenshot {RUN_DIR / f'{boot_label}_m2_failed_final.bmp'}")
|
||||
raise AssertionError(f"[{boot_label}] Guest never fetched /run.sh after Terminal launch")
|
||||
|
||||
print(f"[{boot_label}] Guest fetched /run.sh!", flush=True)
|
||||
ctl_cmd(ctl_port, f"screenshot {RUN_DIR / f'{boot_label}_02c_curl.bmp'}")
|
||||
|
||||
if do_full_checks:
|
||||
assert state["before_resize_ev"].wait(timeout=60), "Timed out waiting for before_resize notification"
|
||||
resize_info = ctl_cmd(ctl_port, "resize 800 600")
|
||||
assert resize_info.startswith("ok"), f"CTL resize failed: {resize_info}"
|
||||
print(f"[{boot_label}] Resized Reims vGPU window via CTL: {resize_info}", flush=True)
|
||||
assert state["res_switched_ev"].wait(timeout=30), "Timed out waiting for resolution switch notification"
|
||||
time.sleep(1.5)
|
||||
st_str = ctl_cmd(ctl_port, "status")
|
||||
res_bmp = RUN_DIR / f"{boot_label}_03_res_switched.bmp"
|
||||
ctl_cmd(ctl_port, f"screenshot {res_bmp}")
|
||||
shots["res_switched"] = bmp_stats(res_bmp)
|
||||
print(f"[{boot_label}] After resolution switch: status={st_str} shot={shots['res_switched']}", flush=True)
|
||||
cnt_str = ctl_cmd(ctl_port, "counts")
|
||||
print(f"[{boot_label}] CTL counts={cnt_str}", flush=True)
|
||||
assert state["report_ev"].wait(timeout=60), "Timed out waiting for Boot 1 guest report"
|
||||
state["allow_shutdown"].set()
|
||||
else:
|
||||
assert state["report_ev"].wait(timeout=90), "Timed out waiting for Cold Reboot guest report"
|
||||
|
||||
# Wait for clean VM shutdown (rc=0)
|
||||
rc = proc.wait(timeout=90)
|
||||
print(f"[{boot_label}] openvmm exited cleanly with rc={rc} in {time.monotonic()-t0:.1f}s!", flush=True)
|
||||
assert rc == 0, f"[{boot_label}] Expected rc=0 clean shutdown, got {rc}"
|
||||
|
||||
st_pre = ctl_cmd(ctl_port, "status") if False else None
|
||||
return {
|
||||
"rc": rc,
|
||||
"desktop_sec": round(desktop_at, 2),
|
||||
"total_sec": round(time.monotonic() - t0, 2),
|
||||
"shots": shots,
|
||||
"report": state["reports"][-1],
|
||||
}
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
stop[0] = True
|
||||
if sock_holder[0]:
|
||||
try:
|
||||
sock_holder[0].close()
|
||||
except OSError:
|
||||
pass
|
||||
t.join(timeout=2)
|
||||
stdout_f.close()
|
||||
stderr_f.close()
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
ensure_no_running_vmm()
|
||||
if RUN_DIR.exists():
|
||||
shutil.rmtree(RUN_DIR)
|
||||
RUN_DIR.mkdir(parents=True)
|
||||
|
||||
oc_gpu = RUN_DIR / "opencore-gpu.raw"
|
||||
shutil.copy2(OC_SHIM, oc_gpu)
|
||||
inject_reims_gop_and_patch_oc(oc_gpu, RGFX_EFI)
|
||||
osk = get_applesmc_osk()
|
||||
|
||||
print("=== GATE 2B BOOT 1 (Initial Desktop + Metal + Shared Pages + Input + Res Switch + Shutdown) ===", flush=True)
|
||||
b1 = run_boot("boot1", oc_gpu, osk, create_disk=True, do_full_checks=True)
|
||||
print("BOOT 1 SUMMARY:", json.dumps(b1, indent=2), flush=True)
|
||||
|
||||
time.sleep(2.0)
|
||||
print("=== GATE 2B BOOT 2 (Cold Reboot on persistent sys-diff.sqlite + nvram.vmgs) ===", flush=True)
|
||||
b2 = run_boot("boot2", oc_gpu, osk, create_disk=False, do_full_checks=False)
|
||||
print("BOOT 2 SUMMARY:", json.dumps(b2, indent=2), flush=True)
|
||||
|
||||
# Check stderr host logs
|
||||
b1_err = (RUN_DIR / "boot1_stderr.log").read_text("utf-8", "ignore")
|
||||
b2_err = (RUN_DIR / "boot2_stderr.log").read_text("utf-8", "ignore")
|
||||
for label, txt in (("boot1_stderr", b1_err), ("boot2_stderr", b2_err)):
|
||||
print(f"=== {label} key lines ===")
|
||||
for line in txt.splitlines():
|
||||
if any(k in line for k in ("NVIDIA", "IOSurface", "shared section", "degradation", "not-mapped", "mapped", "WARN", "ERROR")):
|
||||
print(" ", line)
|
||||
|
||||
r1 = b1["report"]
|
||||
r2 = b2["report"]
|
||||
assert "A5000" in r1["metal_res"], f"Unexpected Boot 1 Metal GPU: {r1}"
|
||||
assert r1["buf_hex"] == "cafebabe 13572468 deadbeef 99887766", f"Bad Boot 1 Metal compute readback: {r1}"
|
||||
assert r1["px_hex"] in ("0052a47f", "0054a47f"), f"Bad Boot 1 Metal texture readback: {r1}"
|
||||
assert "BEFORE=1024x576 AFTER=800x600" in r1["res_switch"], f"Unexpected Boot 1 res_switch: {r1['res_switch']}"
|
||||
assert b1["shots"]["res_switched"]["width"] == 800 and b1["shots"]["res_switched"]["height"] == 600, f"Resolution switch screenshot not 800x600: {b1['shots']}"
|
||||
assert 'window "Reims vGPU" open' in b1_err, "Reims vGPU SDL3 window did not open"
|
||||
assert "NVIDIA RTX A5000" in b1_err, "NVIDIA RTX A5000 not reported in host stderr"
|
||||
ip_matches = list(re.finditer(
|
||||
r"IOSurface pages in place:\s*(\d+)\s+views made.*?;\s*(\d+)\s+pages blocks' views made.*?;\s*(\d+)\s+named by their runs;\s*refused:\s*(\d+)\s+for bad runs,\s*(\d+)\s+not mapped",
|
||||
b1_err,
|
||||
))
|
||||
assert ip_matches, "Missing IOSurface pages in place log in boot1_stderr.log"
|
||||
m_ip = ip_matches[-1]
|
||||
assert (int(m_ip.group(1)) + int(m_ip.group(2))) > 0 and int(m_ip.group(3)) > 0, f"Bad IOSurface shared pages metric: {m_ip.group(0)}"
|
||||
assert int(m_ip.group(4)) == 0 and int(m_ip.group(5)) == 0, f"Expected 0 refused/not-mapped: {m_ip.group(0)}"
|
||||
assert "A5000" in r2["metal_device"], f"Unexpected Boot 2 Metal GPU: {r2}"
|
||||
assert "Finder.app" in r2["ps"] and "WindowServer" in r2["ps"], f"Boot 2 missing Finder/WindowServer: {r2}"
|
||||
|
||||
result = {"boot1": b1, "boot2": b2, "in_place_line": m_ip.group(0), "GATE2B_INTEL_PASSED": True}
|
||||
(RUN_DIR / "gate2b_result.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
|
||||
print("GATE2B_INTEL_PASSED=True", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
use std::fs::{self, File};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use clap::Parser;
|
||||
|
||||
mod probe;
|
||||
|
||||
const OPENVMM_COMMIT: &str = "6575a1e6a854ec4193c90c4f416419b6e55bdce5";
|
||||
const OPENVMM_TARGET: &str = "x86_64-pc-windows-msvc";
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(about = "Probe an x64 UEFI boot under OpenVMM on Windows")]
|
||||
struct Args {
|
||||
/// OpenVMM executable built from the pinned upstream revision.
|
||||
#[arg(long)]
|
||||
openvmm: PathBuf,
|
||||
/// x64 MSVM UEFI firmware from the pinned OpenVMM build.
|
||||
#[arg(long)]
|
||||
firmware: PathBuf,
|
||||
/// Read-only whole-disk image containing an x64 UEFI system partition.
|
||||
#[arg(long)]
|
||||
boot_disk: PathBuf,
|
||||
/// Optional read-only guest disk attached behind the same controller.
|
||||
#[arg(long)]
|
||||
guest_disk: Option<PathBuf>,
|
||||
/// New directory for serial output, OpenVMM output, and build identity.
|
||||
#[arg(long)]
|
||||
output_dir: PathBuf,
|
||||
/// Exact text to locate in the VM's serial byte stream.
|
||||
#[arg(long, value_parser = parse_marker)]
|
||||
marker: String,
|
||||
/// End the probe after this many seconds if the marker is absent.
|
||||
#[arg(long, default_value_t = 60, value_parser = clap::value_parser!(u64).range(1..=900))]
|
||||
timeout_secs: u64,
|
||||
/// Number of virtual processors.
|
||||
#[arg(long, default_value_t = 2, value_parser = clap::value_parser!(u32).range(1..=32))]
|
||||
processors: u32,
|
||||
/// Guest RAM in MiB.
|
||||
#[arg(long, default_value_t = 2048, value_parser = clap::value_parser!(u32).range(256..=32768))]
|
||||
memory_mib: u32,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
ensure!(
|
||||
cfg!(all(target_os = "windows", target_arch = "x86_64")),
|
||||
"this probe requires a native Windows x64 host"
|
||||
);
|
||||
|
||||
let openvmm = input_file(&args.openvmm)?;
|
||||
let firmware = input_file(&args.firmware)?;
|
||||
let boot_disk = input_file(&args.boot_disk)?;
|
||||
let guest_disk = args.guest_disk.as_deref().map(input_file).transpose()?;
|
||||
|
||||
// Validate each path before starting OpenVMM. Its compound CLI arguments
|
||||
// use commas and semicolons as delimiters even with shell quoting.
|
||||
let firmware = openvmm_path(&firmware)?;
|
||||
let boot_disk = openvmm_path(&boot_disk)?;
|
||||
let guest_disk = guest_disk.as_deref().map(openvmm_path).transpose()?;
|
||||
|
||||
fs::create_dir(&args.output_dir)
|
||||
.with_context(|| format!("create new log directory {}", args.output_dir.display()))?;
|
||||
let serial = args.output_dir.join("serial.log");
|
||||
let identity = args.output_dir.join("openvmm-version.txt");
|
||||
let identity_error = args.output_dir.join("openvmm-version.stderr.log");
|
||||
let stdout = args.output_dir.join("openvmm.stdout.log");
|
||||
let stderr = args.output_dir.join("openvmm.stderr.log");
|
||||
|
||||
verify_openvmm(&openvmm, &identity, &identity_error)
|
||||
.with_context(|| format!("see build identity in {}", args.output_dir.display()))?;
|
||||
let mut command = Command::new(openvmm);
|
||||
command
|
||||
.args(["--single-process", "--hypervisor", "whp", "--uefi"])
|
||||
.arg(format!(
|
||||
"firmware={firmware},console=com1,default_boot_always_attempt,disable_frontpage"
|
||||
))
|
||||
.arg("--com1")
|
||||
.arg(format!("file={}", openvmm_path(&serial)?))
|
||||
.args(["--vmbus-scsi", "id=boot", "--disk"])
|
||||
.arg(format!("file:{boot_disk},ro,on=boot,lun=0"))
|
||||
.args(["--guest-shutdown-action", "exit"])
|
||||
.arg("--processors")
|
||||
.arg(args.processors.to_string())
|
||||
.arg("--memory")
|
||||
.arg(format!("{}M", args.memory_mib));
|
||||
if let Some(disk) = guest_disk {
|
||||
command
|
||||
.arg("--disk")
|
||||
.arg(format!("file:{disk},ro,on=boot,lun=1"));
|
||||
}
|
||||
|
||||
let mut child = probe::ChildProcess::spawn(&mut command, &stdout, &stderr)?;
|
||||
let elapsed = probe::wait_for_marker(
|
||||
&mut child,
|
||||
&serial,
|
||||
args.marker.as_bytes(),
|
||||
Duration::from_secs(args.timeout_secs),
|
||||
)
|
||||
.with_context(|| format!("see probe logs in {}", args.output_dir.display()))?;
|
||||
child.stop()?;
|
||||
println!(
|
||||
"Observed {:?} after {:.2?} in {}",
|
||||
args.marker,
|
||||
elapsed,
|
||||
serial.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn input_file(path: &Path) -> Result<PathBuf> {
|
||||
ensure!(
|
||||
path.metadata()
|
||||
.is_ok_and(|meta| meta.is_file() && meta.len() > 0),
|
||||
"expected a non-empty file at {}",
|
||||
path.display()
|
||||
);
|
||||
std::path::absolute(path).with_context(|| format!("resolve path {}", path.display()))
|
||||
}
|
||||
|
||||
fn openvmm_path(path: &Path) -> Result<&str> {
|
||||
let value = path
|
||||
.to_str()
|
||||
.with_context(|| format!("OpenVMM CLI requires a Unicode path: {}", path.display()))?;
|
||||
ensure!(
|
||||
!value.contains([',', ';', '\r', '\n']),
|
||||
"path contains an OpenVMM argument delimiter: {}",
|
||||
path.display()
|
||||
);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn parse_marker(value: &str) -> Result<String> {
|
||||
ensure!(
|
||||
!value.is_empty() && value.len() <= 1024,
|
||||
"marker must have 1 to 1024 bytes"
|
||||
);
|
||||
Ok(value.to_owned())
|
||||
}
|
||||
|
||||
fn verify_openvmm(executable: &Path, output: &Path, stderr: &Path) -> Result<()> {
|
||||
let mut command = Command::new(executable);
|
||||
command.arg("--version");
|
||||
let mut process = probe::ChildProcess::spawn(&mut command, output, stderr)?;
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
if let Some(status) = process.try_wait()? {
|
||||
ensure!(status.success(), "OpenVMM --version returned {status}");
|
||||
break;
|
||||
}
|
||||
if started.elapsed() >= Duration::from_secs(10) {
|
||||
bail!("OpenVMM --version timed out");
|
||||
}
|
||||
std::thread::sleep(probe::POLL_INTERVAL);
|
||||
}
|
||||
let mut version = String::new();
|
||||
File::open(output)?
|
||||
.take(16 * 1024)
|
||||
.read_to_string(&mut version)?;
|
||||
verify_identity(&version)
|
||||
}
|
||||
|
||||
fn verify_identity(version: &str) -> Result<()> {
|
||||
let field = |key| {
|
||||
version
|
||||
.lines()
|
||||
.find_map(|line| line.split_once(':').filter(|(name, _)| *name == key))
|
||||
.map(|(_, value)| value.trim())
|
||||
};
|
||||
ensure!(
|
||||
field("commit") == Some(OPENVMM_COMMIT) && field("target") == Some(OPENVMM_TARGET),
|
||||
"expected OpenVMM commit {OPENVMM_COMMIT} and target {OPENVMM_TARGET}"
|
||||
);
|
||||
ensure!(
|
||||
version
|
||||
.lines()
|
||||
.next()
|
||||
.is_some_and(|line| !line.trim().ends_with(".dirty")),
|
||||
"OpenVMM was built from a dirty checkout"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn verifies_build_identity() -> Result<()> {
|
||||
let fields =
|
||||
format!("\nversion: 0.1.0\ncommit: {OPENVMM_COMMIT}\ntarget: {OPENVMM_TARGET}");
|
||||
verify_identity(&format!("0.1.0+g6575a1e{fields}"))?;
|
||||
assert!(verify_identity(&format!("0.1.0+g6575a1e.dirty{fields}")).is_err());
|
||||
assert!(verify_identity(&fields.replace(OPENVMM_COMMIT, "abcdef")).is_err());
|
||||
assert!(
|
||||
verify_identity(&fields.replace(OPENVMM_TARGET, "aarch64-pc-windows-msvc")).is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_delimiters_but_accepts_spaces() -> Result<()> {
|
||||
assert_eq!(openvmm_path(Path::new("lab disk.img"))?, "lab disk.img");
|
||||
assert!(openvmm_path(Path::new("lab,ro.img")).is_err());
|
||||
assert!(openvmm_path(Path::new("lab;direct.img")).is_err());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{ErrorKind, Read};
|
||||
use std::path::Path;
|
||||
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
||||
pub(crate) const POLL_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
pub(crate) struct ChildProcess(Child);
|
||||
|
||||
impl ChildProcess {
|
||||
pub(crate) fn spawn(command: &mut Command, stdout: &Path, stderr: &Path) -> Result<Self> {
|
||||
let new_log = |path: &Path| {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
.with_context(|| format!("create log {}", path.display()))
|
||||
};
|
||||
// Keep the REPL input pipe open. EOF tells OpenVMM to stop the VM.
|
||||
command
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(new_log(stdout)?)
|
||||
.stderr(new_log(stderr)?)
|
||||
.spawn()
|
||||
.map(Self)
|
||||
.context("start OpenVMM")
|
||||
}
|
||||
|
||||
pub(crate) fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
|
||||
self.0.try_wait().context("poll OpenVMM")
|
||||
}
|
||||
|
||||
pub(crate) fn stop(&mut self) -> Result<()> {
|
||||
if self.try_wait()?.is_none() {
|
||||
if let Err(error) = self.0.kill() {
|
||||
if self.try_wait()?.is_none() {
|
||||
return Err(error).context("stop OpenVMM");
|
||||
}
|
||||
}
|
||||
self.0.wait().context("reap OpenVMM")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ChildProcess {
|
||||
fn drop(&mut self) {
|
||||
if let Err(error) = self.stop() {
|
||||
eprintln!("OpenVMM cleanup failed: {error:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn wait_for_marker(
|
||||
child: &mut ChildProcess,
|
||||
serial: &Path,
|
||||
marker: &[u8],
|
||||
timeout: Duration,
|
||||
) -> Result<Duration> {
|
||||
let started = Instant::now();
|
||||
let deadline = started + timeout;
|
||||
let mut log = None;
|
||||
let mut scanner = MarkerScanner::new(marker);
|
||||
let mut bytes = [0; 8192];
|
||||
|
||||
loop {
|
||||
let status = child.try_wait()?;
|
||||
if log.is_none() {
|
||||
match File::open(serial) {
|
||||
Ok(file) => log = Some(file),
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => (),
|
||||
Err(error) => return Err(error).context("open guest serial log"),
|
||||
}
|
||||
}
|
||||
// Check the child's state first. If it exited, the bytes read below
|
||||
// include any marker it wrote immediately before shutting down.
|
||||
if let Some(file) = &mut log {
|
||||
loop {
|
||||
let read = file.read(&mut bytes).context("read guest serial log")?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
if scanner.scan(&bytes[..read]) {
|
||||
return Ok(started.elapsed());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(status) = status {
|
||||
bail!("OpenVMM exited with {status} before the serial marker appeared");
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
bail!("serial marker did not appear within {}s", timeout.as_secs());
|
||||
}
|
||||
std::thread::sleep(remaining.min(POLL_INTERVAL));
|
||||
}
|
||||
}
|
||||
|
||||
struct MarkerScanner<'a> {
|
||||
marker: &'a [u8],
|
||||
previous: Vec<u8>,
|
||||
}
|
||||
|
||||
impl<'a> MarkerScanner<'a> {
|
||||
fn new(marker: &'a [u8]) -> Self {
|
||||
Self {
|
||||
marker,
|
||||
previous: Vec::with_capacity(marker.len() - 1 + 8192),
|
||||
}
|
||||
}
|
||||
|
||||
fn scan(&mut self, bytes: &[u8]) -> bool {
|
||||
self.previous.extend_from_slice(bytes);
|
||||
if self
|
||||
.previous
|
||||
.windows(self.marker.len())
|
||||
.any(|candidate| candidate == self.marker)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let keep = self.previous.len().min(self.marker.len() - 1);
|
||||
let tail = self.previous.len() - keep;
|
||||
self.previous.copy_within(tail.., 0);
|
||||
self.previous.truncate(keep);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recognizes_marker_split_across_reads() {
|
||||
let mut scanner = MarkerScanner::new(b"BOOT MARKER");
|
||||
assert!(!scanner.scan(b"\xff\nBO"));
|
||||
assert!(!scanner.scan(b"OT MAR"));
|
||||
assert!(scanner.scan(b"KER\r\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_single_byte_marker() {
|
||||
let mut scanner = MarkerScanner::new(b"!");
|
||||
assert!(!scanner.scan(b"partial"));
|
||||
assert!(scanner.scan(b"done!"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user