From 20a756e1c573134e4d2c912c21d06ff4d0ab49d2 Mon Sep 17 00:00:00 2001 From: MrXhh <2791341417@qq.com> Date: Fri, 13 Nov 2026 16:01:10 +0800 Subject: [PATCH] fix: Avoid stale instruction lengths for EPT MMIO emulation Clear the undefined VM-exit instruction length in the EPT MMIO emulation branch so the existing emulator determines the decoded length and next RIP. Add an IOAPIC regression covering native and injected lengths 0, 1, 2, 6, and 15. All six cases pass with the fix. With an identical separate GS workaround, three minimal Linux boots and three LinuxKit shell/poweroff tests also pass. Bare-metal Intel Mac validation is still unavailable. Signed-off-by: MrXhh <2791341417@qq.com> --- Makefile | 5 +- TESTING.md | 16 ++++++ src/lib/vmm/intel/vmx.c | 6 ++ test/ept_mmio.py | 119 ++++++++++++++++++++++++++++++++++++++++ test/ept_mmio_guest.S | 88 +++++++++++++++++++++++++++++ test/ept_stale_length.c | 54 ++++++++++++++++++ 6 files changed, 287 insertions(+), 1 deletion(-) create mode 100644 test/ept_mmio.py create mode 100644 test/ept_mmio_guest.S create mode 100644 test/ept_stale_length.c diff --git a/Makefile b/Makefile index c7c4d9fc..56db3912 100644 --- a/Makefile +++ b/Makefile @@ -148,7 +148,7 @@ TARGET = build/hyperkit all: $(TARGET) | build -.PHONY: clean all test test-qcow +.PHONY: clean all test test-qcow test-ept-mmio .SUFFIXES: -include $(DEP) @@ -204,6 +204,9 @@ test: $(TARGET) test/vmlinuz test/initrd.gz test-qcow: $(TARGET) test/vmlinuz test/initrd.gz @(cd test && ./retry-infra-failure 5 ./test_linux_qcow.exp) +test-ept-mmio: $(TARGET) + @python3 test/ept_mmio.py $(TARGET) + ## ----------- ## ## Artifacts. ## diff --git a/TESTING.md b/TESTING.md index 2841c4d5..8fe32364 100644 --- a/TESTING.md +++ b/TESTING.md @@ -5,6 +5,22 @@ via github issues/pull requests following https://docs.docker.com/opensource/workflow/advanced-contributing/ +## EPT MMIO instruction length regression + +Run `make HAVE_OCAML_QCOW=NO test-ept-mmio` on an Intel Mac with Python 3 and the existing macOS +build tools. No downloaded kernel, disk image, network service, or OCaml +dependency is needed. The test builds a small reset ROM and uses the real +HyperKit EPT exit, decoder, and IOAPIC device paths. The ROM copies its test +payload to guest RAM so that the instruction emulator can fetch it. + +The guest writes and reads an IOAPIC register using six-byte instructions, +checks the returned value, and powers off. Halt guards detect incorrect RIP +advancement. A test-only interposer supplies VMCS instruction lengths 0, 1, 2, +6, and 15 for these MMIO exits; other exits are unchanged. The native path is +also exercised without the interposer. Each case requires a success marker, +normal poweroff, and, for injected cases, both MMIO exits to have been reached. +The timeout is a failure. Logs and a JSON summary are in `build/ept-mmio`. + ## Expect based test The current integration test uses expect to drive it. Some tips for diagnosing tests for people new to expect. diff --git a/src/lib/vmm/intel/vmx.c b/src/lib/vmm/intel/vmx.c index 595b1d0a..8f90cf11 100644 --- a/src/lib/vmm/intel/vmx.c +++ b/src/lib/vmm/intel/vmx.c @@ -2093,6 +2093,12 @@ vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit) vmexit->u.paging.fault_type = ept_fault_type(qual); vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1); } else if (ept_emulation_fault(qual)) { + /* + * The VM-exit instruction length is not defined for the + * instruction whose memory access caused an EPT violation. + * Let the instruction emulator determine its length. + */ + vmexit->inst_length = 0; vmexit_inst_emul(vmexit, gpa, vmcs_gla(vcpu), vcpu); vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1); } diff --git a/test/ept_mmio.py b/test/ept_mmio.py new file mode 100644 index 00000000..2fb041b2 --- /dev/null +++ b/test/ept_mmio.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Exercise the real EPT decoder and IOAPIC device with stale VMCS lengths.""" +import json +import os +from pathlib import Path +import pty +import resource +import select +import struct +import subprocess +import sys +import threading + + +def extract_rom(obj, destination): + data = obj.read_bytes() + magic, cpu, _, _, commands, _, _, _ = struct.unpack_from('= 2)) + result = {'length': name, 'passed': passed, 'exit': process.returncode, + 'timeout': timed_out, 'injected_mmio_exits': injected} + print(json.dumps(result), flush=True) + if not passed: + print(log.decode(errors='replace')[-1800:], flush=True) + print(console.decode(errors='replace')[-800:], flush=True) + return result + + +def main(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + root = Path(__file__).resolve().parent.parent + binary = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else root / 'build/hyperkit' + output = root / 'build/ept-mmio' + output.mkdir(parents=True, exist_ok=True) + obj = output / 'guest.o' + subprocess.run(['clang', '-arch', 'x86_64', '-c', + str(root / 'test/ept_mmio_guest.S'), '-o', str(obj)], check=True) + rom = output / 'guest.rom' + extract_rom(obj, rom) + library = output / 'stale-length.dylib' + subprocess.run(['clang', '-arch', 'x86_64', '-dynamiclib', '-Wall', '-Wextra', + '-Werror', '-Wno-deprecated-declarations', '-framework', 'Hypervisor', + str(root / 'test/ept_stale_length.c'), '-o', str(library)], check=True) + results = [run_case(binary, rom, library, length, output) + for length in (None, 0, 1, 2, 6, 15)] + (output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + return 0 if all(case['passed'] for case in results) else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/test/ept_mmio_guest.S b/test/ept_mmio_guest.S new file mode 100644 index 00000000..8ee9ebc9 --- /dev/null +++ b/test/ept_mmio_guest.S @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ + +/* A reset ROM with six-byte IOAPIC accesses and no external firmware. */ +.text +.code16 +Lstart: + cli + lgdtl %cs:(Lgdt_pointer - Lstart) + movl %cr0, %eax + orl $1, %eax + movl %eax, %cr0 + ljmpl $8, $(0xffff0000 + Lprotected_mode - Lstart) + +.code32 +Lprotected_mode: + movw $16, %ax + movw %ax, %ds + movw %ax, %es + movw %ax, %ss + movl $0x8000, %esp + /* The emulator fetches instructions from guest RAM, not ROM mappings. */ + movl $(0xffff0000 + Lpayload - Lstart), %esi + movl $0x100000, %edi + movl $(Lpayload_end - Lpayload), %ecx + cld + rep movsb + ljmpl $8, $0x100000 +Lpayload: + movl $0xfec00000, %edi + movl $7, %eax + /* movl %eax, 0(%edi), with a disp32 to require six bytes. */ + .byte 0x89, 0x87 + .long 0 + jmp Lafter_write + /* A stale length of 15 must not accidentally reach the success path. */ + .fill 15, 1, 0xf4 +Lafter_write: + movl $0xdeadbeef, %eax + /* movl 0(%edi), %eax, also using a disp32. */ + .byte 0x8b, 0x87 + .long 0 + jmp Lafter_read + .fill 15, 1, 0xf4 +Lafter_read: + cmpl $7, %eax + jne Lfailed + movl $(0x100000 + Lpassed_message - Lpayload), %esi + jmp Lprint +Lfailed: + movl $(0x100000 + Lfailed_message - Lpayload), %esi +Lprint: + movw $0x3f8, %dx +Lnext_char: + lodsb + testb %al, %al + jz Lpoweroff + outb %al, %dx + jmp Lnext_char +Lpoweroff: + /* HyperKit's PM1 control port: SLP_TYP=S5, SLP_EN=1. */ + movw $0x404, %dx + movw $0x3400, %ax + outw %ax, %dx +Lstopped: + hlt + jmp Lstopped + +Lpassed_message: + .asciz "EPT_MMIO_PASS\n" +Lfailed_message: + .asciz "EPT_MMIO_FAIL\n" +Lpayload_end: + +.p2align 3 +Lgdt: + .quad 0 + .quad 0x00cf9b000000ffff + .quad 0x00cf93000000ffff +Lgdt_end: +Lgdt_pointer: + .word Lgdt_end - Lgdt - 1 + .long 0xffff0000 + Lgdt - Lstart + +.code16 +.org 0xfff0, 0xff + /* A 16-bit near jump wraps IP from 0xfff0 back to offset zero. */ + .byte 0xe9, 0x0d, 0x00 +.org 0x10000, 0xff diff --git a/test/ept_stale_length.c b/test/ept_stale_length.c new file mode 100644 index 00000000..ba1353e0 --- /dev/null +++ b/test/ept_stale_length.c @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ + +/* Supply defined test values for an architecturally undefined MMIO length. */ +#include +#include +#include +#include +#include +#include + +static unsigned int instruction_length; + +static void __attribute__((constructor)) +configure(void) +{ + const char *setting; + char *end; + unsigned long value; + + setting = getenv("HYPERKIT_TEST_EPT_LENGTH"); + if (setting == NULL) + abort(); + value = strtoul(setting, &end, 10); + if (*setting == '\0' || *end != '\0' || value > 15) + abort(); + instruction_length = (unsigned int)value; +} + +static hv_return_t +stale_length(hv_vcpuid_t cpu, uint32_t field, uint64_t *value) +{ + hv_return_t result; + uint64_t reason, gpa; + + result = hv_vmx_vcpu_read_vmcs(cpu, field, value); + if (result == HV_SUCCESS && field == VMCS_RO_VMEXIT_INSTR_LEN && + hv_vmx_vcpu_read_vmcs(cpu, VMCS_RO_EXIT_REASON, &reason) == HV_SUCCESS && + reason == 48 && + hv_vmx_vcpu_read_vmcs(cpu, VMCS_GUEST_PHYSICAL_ADDRESS, &gpa) == HV_SUCCESS && + gpa == 0xfec00000) { + *value = instruction_length; + fprintf(stderr, "EPT_TEST_LENGTH=%u\n", instruction_length); + } + return (result); +} + +__attribute__((used, section("__DATA,__interpose"))) +static const struct { + const void *replacement; + const void *original; +} interpose = { + (const void *)&stale_length, + (const void *)&hv_vmx_vcpu_read_vmcs +};