hyperlight_host/lib.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025 The Hyperlight Authors.
3#![warn(dead_code, missing_docs, unused_mut)]
4//! Hyperlight host runtime for executing guest code in lightweight virtual machines.
5//!
6//! This crate provides the host-side runtime for Hyperlight, enabling safe execution
7//! of untrusted guest code within micro virtual machines with minimal overhead.
8//! The runtime manages sandbox creation, guest function calls, memory isolation,
9//! and host-guest communication.
10//!
11//! The primary entry point is [`SandboxBuilder`], which produces a
12//! [`Sandbox`] for executing guest functions.
13//!
14//! ## Guest Requirements
15//!
16//! Hyperlight requires specially compiled guest binaries and cannot run regular
17//! container images or executables. Guests must be built using either the Rust
18//! API ([`hyperlight_guest`] with optional use of [`hyperlight_guest_bin`]),
19//! or with the C API (`hyperlight_guest_capi`).
20//!
21//! [`hyperlight_guest`]: https://docs.rs/hyperlight_guest
22//! [`hyperlight_guest_bin`]: https://docs.rs/hyperlight_guest_bin
23//!
24
25#![cfg_attr(not(any(test, debug_assertions)), warn(clippy::panic))]
26#![cfg_attr(not(any(test, debug_assertions)), warn(clippy::expect_used))]
27#![cfg_attr(not(any(test, debug_assertions)), warn(clippy::unwrap_used))]
28
29#[cfg(feature = "build-metadata")]
30use std::sync::Once;
31
32#[cfg(feature = "build-metadata")]
33/// The `built` crate is used to generate a `built.rs` file that contains
34/// information about the build environment. This information is used to
35/// populate the `built_info` module, which is re-exported here.
36pub(crate) mod built_info {
37 include!(concat!(env!("OUT_DIR"), "/built.rs"));
38}
39/// Dealing with errors, including errors across VM boundaries
40pub mod error;
41/// Wrappers for host and guest functions.
42pub mod func;
43/// Wrappers for hypervisor implementations
44pub mod hypervisor;
45/// Functionality to establish and manage an individual sandbox's
46/// memory.
47///
48/// - Virtual Address
49///
50/// 0x0000 PML4
51/// 0x1000 PDPT
52/// 0x2000 PD
53/// 0x3000 The guest PE code (When the code has been loaded using LoadLibrary to debug the guest this will not be
54/// present and code length will be zero;
55///
56/// - The pointer passed to the Entrypoint in the Guest application is the size of page table + size of code,
57/// at this address structs below are laid out in this order
58pub mod mem;
59/// Metric definitions and helpers
60pub mod metrics;
61/// The main sandbox implementations. Do not use this module directly in code
62/// outside this file. Types from this module needed for public consumption are
63/// re-exported below.
64pub mod sandbox;
65/// Signal handling for Linux
66#[cfg(target_os = "linux")]
67pub(crate) mod signal_handlers;
68/// Utilities for testing including interacting with `simpleguest` testing guest binary
69#[cfg(test)]
70pub(crate) mod testing;
71
72/// The re-export for the `HyperlightError` type
73pub use error::HyperlightError;
74/// The re-export for the `is_hypervisor_present` type
75pub use hypervisor::virtual_machine::is_hypervisor_present;
76/// Deprecated name for [`Sandbox`].
77#[allow(deprecated)]
78pub use sandbox::MultiUseSandbox;
79/// A sandbox that can call be used to make multiple calls to guest functions,
80/// and otherwise reused multiple times
81pub use sandbox::Sandbox;
82/// The lifecycle state of a [`Sandbox`].
83pub use sandbox::SandboxStatus;
84/// The re-export for the `UninitializedSandbox` type
85pub use sandbox::UninitializedSandbox;
86/// The re-export for the `SandboxBuilder` type
87pub use sandbox::builder::SandboxBuilder;
88/// A collection of host functions that can be supplied to a sandbox
89/// constructor (e.g. [`Sandbox::from_snapshot`]).
90pub use sandbox::host_funcs::HostFunctions;
91/// The re-export for the `GuestBinary` type
92pub use sandbox::uninitialized::GuestBinary;
93
94/// Unstable, internal API surface exposed solely for Hyperlight's own
95/// integration tests. Not part of the public API: anything here may
96/// change or disappear without notice. Do not depend on it.
97#[doc(hidden)]
98pub mod __private {
99 /// Short golden-tag token for the host CPU vendor, or `None` if the
100 /// goldens do not cover it. See the snapshot golden tests.
101 pub fn host_cpu_vendor_golden_tag() -> Option<&'static str> {
102 crate::sandbox::snapshot::host_cpu_vendor_golden_tag()
103 }
104}
105
106/// The universal `Result` type used throughout the Hyperlight codebase.
107pub type Result<T> = core::result::Result<T, error::HyperlightError>;
108
109/// Logs an error then returns with it, more or less equivalent to the bail! macro in anyhow
110/// but for HyperlightError instead of anyhow::Error
111#[macro_export]
112macro_rules! log_then_return {
113 ($msg:literal $(,)?) => {{
114 let __args = std::format_args!($msg);
115 let __err_msg = match __args.as_str() {
116 Some(msg) => String::from(msg),
117 None => std::format!($msg),
118 };
119 let __err = $crate::HyperlightError::Error(__err_msg);
120 tracing::error!("{}", __err);
121 return Err(__err);
122 }};
123 ($err:expr $(,)?) => {
124 tracing::error!("{}", $err);
125 return Err($err);
126 };
127 ($err:stmt $(,)?) => {
128 tracing::error!("{}", $err);
129 return Err($err);
130 };
131 ($fmtstr:expr, $($arg:tt)*) => {
132 let __err_msg = std::format!($fmtstr, $($arg)*);
133 let __err = $crate::error::HyperlightError::Error(__err_msg);
134 tracing::error!("{}", __err);
135 return Err(__err);
136 };
137}
138
139/// Same as tracing::debug!, but will additionally print to stdout if the print_debug feature is enabled
140#[macro_export]
141macro_rules! debug {
142 ($($arg:tt)+) =>
143 {
144 #[cfg(print_debug)]
145 println!($($arg)+);
146 tracing::debug!($($arg)+);
147 }
148}
149
150// LOG_ONCE is used to log information about the crate version once
151#[cfg(feature = "build-metadata")]
152static LOG_ONCE: Once = Once::new();
153
154#[cfg(feature = "build-metadata")]
155pub(crate) fn log_build_details() {
156 use tracing::info;
157 LOG_ONCE.call_once(|| {
158 info!("Package name: {}", built_info::PKG_NAME);
159 info!("Package version: {}", built_info::PKG_VERSION);
160 info!("Package features: {:?}", built_info::FEATURES);
161 info!("Target triple: {}", built_info::TARGET);
162 info!("Optimization level: {}", built_info::OPT_LEVEL);
163 info!("Profile: {}", built_info::PROFILE);
164 info!("Debug: {}", built_info::DEBUG);
165 info!("Rustc: {}", built_info::RUSTC);
166 info!("Built at: {}", built_info::BUILT_TIME_UTC);
167 match built_info::CI_PLATFORM.unwrap_or("") {
168 "" => info!("Not built on a CI platform"),
169 other => info!("Built on : {}", other),
170 }
171 match built_info::GIT_COMMIT_HASH.unwrap_or("") {
172 "" => info!("No git commit hash found"),
173 other => info!("Git commit hash: {}", other),
174 }
175
176 let git = match built_info::GIT_HEAD_REF.unwrap_or("") {
177 "" => {
178 info!("No git head ref found");
179 false
180 }
181 other => {
182 info!("Git head ref: {}", other);
183 true
184 }
185 };
186 match built_info::GIT_VERSION.unwrap_or("") {
187 "" => info!("No git version found"),
188 other => info!("Git version: {}", other),
189 }
190 match built_info::GIT_DIRTY.unwrap_or(false) {
191 true => info!("Repo had uncommitted changes"),
192 false => {
193 if git {
194 info!("Repo had no uncommitted changes")
195 } else {
196 info!("No git repo found")
197 }
198 }
199 }
200 });
201}