Skip to main content

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