Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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. ##
Expand Down
16 changes: 16 additions & 0 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions src/lib/vmm/intel/vmx.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
119 changes: 119 additions & 0 deletions test/ept_mmio.py
Original file line number Diff line number Diff line change
@@ -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('<IiiIIIII', data)
if magic != 0xfeedfacf or cpu != 0x1000007:
raise RuntimeError('Expected an x86_64 Mach-O object')
offset = 32
for _ in range(commands):
command, size = struct.unpack_from('<II', data, offset)
if command == 0x19:
sections = struct.unpack_from('<I', data, offset + 64)[0]
for section in range(sections):
at = offset + 72 + 80 * section
if data[at:at + 16].rstrip(b'\0') == b'__text':
length, position = struct.unpack_from('<QI', data, at + 40)
relocations = struct.unpack_from('<I', data, at + 60)[0]
if length != 65536 or relocations:
raise RuntimeError('ROM must be 64 KiB and relocation-free')
destination.write_bytes(data[position:position + length])
return
offset += size
raise RuntimeError('No ROM text section found')


def run_case(binary, rom, library, length, output):
master, slave = pty.openpty()
console = bytearray()
done = threading.Event()

def read_console():
while not done.is_set():
if select.select([master], [], [], 0.1)[0]:
try:
chunk = os.read(master, 65536)
except OSError:
return
if not chunk:
return
console.extend(chunk)

reader = threading.Thread(target=read_console)
env = dict(os.environ)
env.pop('DYLD_INSERT_LIBRARIES', None)
env.pop('HYPERKIT_TEST_EPT_LENGTH', None)
if length is not None:
env['DYLD_INSERT_LIBRARIES'] = str(library)
env['HYPERKIT_TEST_EPT_LENGTH'] = str(length)
args = [str(binary), '-A', '-m', '16M', '-c', '1',
'-s', '0:0,hostbridge', '-s', '31,lpc', '-l', 'com1,stdio',
'-f', 'bootrom,' + str(rom)]
process = subprocess.Popen(args, env=env, stdin=slave, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
reader.start()
timed_out = False
try:
try:
log, _ = process.communicate(timeout=10)
except subprocess.TimeoutExpired:
timed_out = True
process.kill()
log, _ = process.communicate()
finally:
os.close(slave)
reader.join(timeout=1)
done.set()
reader.join()
os.close(master)
name = 'native' if length is None else str(length)
(output / ('length-' + name + '.log')).write_bytes(log)
(output / ('length-' + name + '.serial')).write_bytes(console)
injected = log.count(b'EPT_TEST_LENGTH=')
passed = (not timed_out and process.returncode == 0 and
b'EPT_MMIO_PASS' in console and b'EPT_MMIO_FAIL' not in console and
(length is None or injected >= 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())
88 changes: 88 additions & 0 deletions test/ept_mmio_guest.S
Original file line number Diff line number Diff line change
@@ -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
54 changes: 54 additions & 0 deletions test/ept_stale_length.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/* SPDX-License-Identifier: BSD-2-Clause */

/* Supply defined test values for an architecturally undefined MMIO length. */
#include <Hypervisor/hv.h>
#include <Hypervisor/hv_vmx.h>
#include <Hypervisor/hv_arch_vmx.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

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
};