1 // Copyright 2017 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #![cfg(any(target_os = "android", target_os = "linux"))]
6 #![cfg(target_arch = "x86_64")]
7
8 use kvm::*;
9 use kvm_sys::kvm_regs;
10 use vm_memory::GuestAddress;
11 use vm_memory::GuestMemory;
12
13 #[test]
test_run()14 fn test_run() {
15 // This example based on https://lwn.net/Articles/658511/
16 let code = [
17 0xba, 0xf8, 0x03, /* mov $0x3f8, %dx */
18 0x00, 0xd8, /* add %bl, %al */
19 0x04, b'0', /* add $'0', %al */
20 0xee, /* out %al, (%dx) */
21 0xb0, b'\n', /* mov $'\n', %al */
22 0xee, /* out %al, (%dx) */
23 0x2e, 0xc6, 0x06, 0xf1, 0x10, 0x13, /* movb $0x13, %cs:0xf1 */
24 0xf4, /* hlt */
25 ];
26
27 let mem_size = 0x1000;
28 let load_addr = GuestAddress(0x1000);
29 let mem = GuestMemory::new(&[(load_addr, mem_size)]).unwrap();
30
31 let kvm = Kvm::new().expect("new kvm failed");
32 let vm = Vm::new(&kvm, mem).expect("new vm failed");
33 let vcpu = Vcpu::new(0, &kvm, &vm).expect("new vcpu failed");
34
35 vm.get_memory()
36 .write_at_addr(&code, load_addr)
37 .expect("Writing code to memory failed.");
38
39 let mut vcpu_sregs = vcpu.get_sregs().expect("get sregs failed");
40 assert_ne!(vcpu_sregs.cs.base, 0);
41 assert_ne!(vcpu_sregs.cs.selector, 0);
42 vcpu_sregs.cs.base = 0;
43 vcpu_sregs.cs.selector = 0;
44 vcpu.set_sregs(&vcpu_sregs).expect("set sregs failed");
45
46 // SAFETY: trivially safe
47 let mut vcpu_regs: kvm_regs = unsafe { std::mem::zeroed() };
48 vcpu_regs.rip = 0x1000;
49 vcpu_regs.rax = 2;
50 vcpu_regs.rbx = 7;
51 vcpu_regs.rflags = 2;
52 vcpu.set_regs(&vcpu_regs).expect("set regs failed");
53
54 let mut out = String::new();
55 let runnable_vcpu = vcpu.to_runnable(None).unwrap();
56 loop {
57 match runnable_vcpu.run().expect("run failed") {
58 VcpuExit::IoOut {
59 port: 0x3f8,
60 size,
61 data,
62 } => {
63 assert_eq!(size, 1);
64 out.push(data[0] as char);
65 }
66 VcpuExit::Hlt => break,
67 r => panic!("unexpected exit reason: {:?}", r),
68 }
69 }
70
71 assert_eq!(out, "9\n");
72 let result: u8 = vm
73 .get_memory()
74 .read_obj_from_addr(load_addr.checked_add(0xf1).unwrap())
75 .expect("Error reading the result.");
76 assert_eq!(result, 0x13);
77 }
78