1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/*
Copyright (c) 2016 Saurav Sachidanand
			  2021 Stefan Lankes

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/*!
This is a Rust library that taps into functionality that enables
hardware-accelerated execution of virtual machines on OS X.

It binds to the `Hypervisor` framework on OS X, and exposes a safe Rust
interface through the `xhypervisor` module, and an unsafe foreign function
interface through the `xhypervisor::ffi` module.

To use this library, you need

* OS X Yosemite (10.10), or newer

* an Intel processor with the VT-x feature set that includes Extended Page
Tables (EPT) and Unrestricted Mode. To verify this, run and expect the following
in your Terminal:

  ```shell
  $ sysctl kern.hv_support
  kern.hv_support: 1
  ```
!*/

extern crate core;
extern crate libc;
extern crate thiserror;

#[cfg(target_arch = "aarch64")]
#[allow(non_camel_case_types)]
pub mod aarch64;
#[cfg(target_arch = "x86_64")]
#[allow(non_camel_case_types)]
pub mod x86_64;

use core::fmt;
use thiserror::Error;

#[cfg(target_arch = "x86_64")]
use self::x86_64::ffi::*;
#[cfg(target_arch = "aarch64")]
use aarch64::ffi::*;
#[cfg(target_arch = "aarch64")]
pub use aarch64::*;
#[cfg(target_arch = "x86_64")]
pub use x86_64::*;

/// Error returned after every call
#[derive(Error, Debug)]
pub enum Error {
	#[error("success")]
	Success,
	#[error("error")]
	Error,
	#[error("busy")]
	Busy,
	#[error("bad argument")]
	BadArg,
	#[error("no resource")]
	NoRes,
	#[error("no device")]
	NoDev,
	#[error("unsupported")]
	Unsupp,
}

// Returns an Error for a hv_return_t
fn match_error_code(code: hv_return_t) -> Result<(), Error> {
	match code {
		HV_SUCCESS => Ok(()),
		HV_BUSY => Err(Error::Busy),
		HV_BAD_ARGUMENT => Err(Error::BadArg),
		HV_NO_RESOURCES => Err(Error::NoRes),
		HV_NO_DEVICE => Err(Error::NoDev),
		HV_UNSUPPORTED => Err(Error::Unsupp),
		_ => Err(Error::Error),
	}
}

/// Destroys the VM instance associated with the current Mach task
pub fn destroy_vm() -> Result<(), Error> {
	match_error_code(unsafe { hv_vm_destroy() })
}

/// Guest physical memory region permissions
#[derive(Debug)]
pub enum MemPerm {
	/// Read
	Read,
	/// Write (implies read)
	Write,
	/// Execute
	Exec,
	/// Execute and write (implies read)
	ExecAndWrite,
	/// Execute and read
	ExecAndRead,
}

#[allow(non_snake_case)]
#[inline(always)]
fn match_MemPerm(mem_perm: MemPerm) -> u64 {
	match mem_perm {
		MemPerm::Read => HV_MEMORY_READ,
		MemPerm::Write => HV_MEMORY_WRITE | HV_MEMORY_READ,
		MemPerm::Exec => HV_MEMORY_EXEC,
		MemPerm::ExecAndWrite => HV_MEMORY_EXEC | HV_MEMORY_WRITE | HV_MEMORY_READ,
		MemPerm::ExecAndRead => HV_MEMORY_EXEC | HV_MEMORY_READ,
	}
}

impl VirtualCpu {
	/// Destroys the VirtualCpu instance associated with the current thread
	pub fn destroy(&self) -> Result<(), Error> {
		match_error_code(unsafe { hv_vcpu_destroy(self.get_id()) })
	}

	/// Executes the VirtualCpu
	pub fn run(&self) -> Result<(), Error> {
		match_error_code(unsafe { hv_vcpu_run(self.get_id()) })
	}
}

impl fmt::Debug for VirtualCpu {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		write!(f, "VirtualCpu ID: {}", (*self).get_id())
	}
}