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