From: Arthur Chunqi Li Subject: [PATCH 1/2] kvm-unit-tests: Add a func to run instruction in emulator Date: Mon, 10 Jun 2013 21:38:32 +0800 Message-ID: <1370871513-31815-1-git-send-email-yzt356@gmail.com> Cc: gleb@redhat.com, pbonzini@redhat.com, Arthur Chunqi Li To: kvm@vger.kernel.org Return-path: Received: from mail-pb0-f42.google.com ([209.85.160.42]:58975 "EHLO mail-pb0-f42.google.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1752430Ab3FJNi7 (ORCPT ); Mon, 10 Jun 2013 09:38:59 -0400 Received: by mail-pb0-f42.google.com with SMTP id un1so3123978pbc.1 for ; Mon, 10 Jun 2013 06:38:58 -0700 (PDT) Sender: kvm-owner@vger.kernel.org List-ID: Add a function trap_emulator to run an instruction in emulator. Set inregs first (%rax is invalid because it is used as return address), put instruction codec in alt_insn and call func with alt_insn_length. Get results in outregs. Signed-off-by: Arthur Chunqi Li --- x86/emulator.c | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) diff --git a/x86/emulator.c b/x86/emulator.c index 96576e5..a1bd92e 100644 --- a/x86/emulator.c +++ b/x86/emulator.c @@ -11,6 +11,13 @@ int fails, tests; static int exceptions; +struct regs { + u64 rax, rbx, rcx, rdx; + u64 rsi, rdi, rsp, rbp; + u64 rip, rflags; +}; +static struct regs inregs, outregs; + void report(const char *name, int result) { ++tests; @@ -685,6 +692,105 @@ static void test_shld_shrd(u32 *mem) report("shrd (cl)", *mem == ((0x12345678 >> 3) | (5u << 29))); } +static void trap_emulator(uint64_t *mem, uint8_t *insn_page, + uint8_t *alt_insn_page, void *insn_ram, + uint8_t* alt_insn, int alt_insn_length, int reserve_stack) +{ + ulong *cr3 = (ulong *)read_cr3(); + int i; + static struct regs save; + + // Pad with RET instructions + memset(insn_page, 0x90, 4096); + memset(alt_insn_page, 0x90, 4096); + + asm volatile( + "movw $1, %0\n\t" + : : "m"(mem) + : "memory" + ); + // Place a trapping instruction in the page to trigger a VMEXIT + insn_page[0] = 0xc3; // ret + if (!reserve_stack) + { + insn_page[1] = 0x49; // xchg %rsp,%r9 + insn_page[2] = 0x87; + insn_page[3] = 0xe1; + insn_page[4] = 0x49; // xchg %rbp,%r10 + insn_page[5] = 0x87; + insn_page[6] = 0xea; + } + //in (%dx),%al, may change in the future + insn_page[7] = 0xec; + + // Place the instruction we want the hypervisor to see in the alternate page + for (i=7; i