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/// Signal handling for Linux
80#[cfg(target_os = "linux")]
81pub(crate) mod signal_handlers;
82/// Utilities for testing including interacting with `simpleguest` testing guest binary
83#[cfg(test)]
84pub(crate) mod testing;
85
86/// The re-export for the `HyperlightError` type
87pub use error::HyperlightError;
88/// A sandbox that can call be used to make multiple calls to guest functions,
89/// and otherwise reused multiple times
90pub use sandbox::MultiUseSandbox;
91/// The re-export for the `UninitializedSandbox` type
92pub use sandbox::UninitializedSandbox;
93/// The re-export for the `is_hypervisor_present` type
94pub use sandbox::is_hypervisor_present;
95/// The re-export for the `GuestBinary` type
96pub use sandbox::uninitialized::GuestBinary;
97
98/// The universal `Result` type used throughout the Hyperlight codebase.
99pub type Result<T> = core::result::Result<T, error::HyperlightError>;
100
101/// Logs an error then returns with it, more or less equivalent to the bail! macro in anyhow
102/// but for HyperlightError instead of anyhow::Error
103#[macro_export]
104macro_rules! log_then_return {
105    ($msg:literal $(,)?) => {{
106        let __args = std::format_args!($msg);
107        let __err_msg = match __args.as_str() {
108            Some(msg) => String::from(msg),
109            None => std::format!($msg),
110        };
111        let __err = $crate::HyperlightError::Error(__err_msg);
112        log::error!("{}", __err);
113        return Err(__err);
114    }};
115    ($err:expr $(,)?) => {
116        log::error!("{}", $err);
117        return Err($err);
118    };
119    ($err:stmt $(,)?) => {
120        log::error!("{}", $err);
121        return Err($err);
122    };
123    ($fmtstr:expr, $($arg:tt)*) => {
124           let __err_msg = std::format!($fmtstr, $($arg)*);
125           let __err = $crate::error::HyperlightError::Error(__err_msg);
126           log::error!("{}", __err);
127           return Err(__err);
128    };
129}
130
131/// Same as log::debug!, but will additionally print to stdout if the print_debug feature is enabled
132#[macro_export]
133macro_rules! debug {
134    ($($arg:tt)+) =>
135    {
136        #[cfg(print_debug)]
137        println!($($arg)+);
138        log::debug!($($arg)+);
139    }
140}
141
142// LOG_ONCE is used to log information about the crate version once
143#[cfg(feature = "build-metadata")]
144static LOG_ONCE: Once = Once::new();
145
146#[cfg(feature = "build-metadata")]
147pub(crate) fn log_build_details() {
148    use log::info;
149    LOG_ONCE.call_once(|| {
150        info!("Package name: {}", built_info::PKG_NAME);
151        info!("Package version: {}", built_info::PKG_VERSION);
152        info!("Package features: {:?}", built_info::FEATURES);
153        info!("Target triple: {}", built_info::TARGET);
154        info!("Optimization level: {}", built_info::OPT_LEVEL);
155        info!("Profile: {}", built_info::PROFILE);
156        info!("Debug: {}", built_info::DEBUG);
157        info!("Rustc: {}", built_info::RUSTC);
158        info!("Built at: {}", built_info::BUILT_TIME_UTC);
159        match built_info::CI_PLATFORM.unwrap_or("") {
160            "" => info!("Not built on  a CI platform"),
161            other => info!("Built on : {}", other),
162        }
163        match built_info::GIT_COMMIT_HASH.unwrap_or("") {
164            "" => info!("No git commit hash found"),
165            other => info!("Git commit hash: {}", other),
166        }
167
168        let git = match built_info::GIT_HEAD_REF.unwrap_or("") {
169            "" => {
170                info!("No git head ref found");
171                false
172            }
173            other => {
174                info!("Git head ref: {}", other);
175                true
176            }
177        };
178        match built_info::GIT_VERSION.unwrap_or("") {
179            "" => info!("No git version found"),
180            other => info!("Git version: {}", other),
181        }
182        match built_info::GIT_DIRTY.unwrap_or(false) {
183            true => info!("Repo had uncommitted changes"),
184            false => {
185                if git {
186                    info!("Repo had no uncommitted changes")
187                } else {
188                    info!("No git repo found")
189                }
190            }
191        }
192    });
193}