Skip to main content

hyperlight_guest_bin/
host_comm.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025 The Hyperlight Authors.
3
4use alloc::string::ToString;
5use alloc::vec::Vec;
6
7use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCall;
8use hyperlight_common::flatbuffer_wrappers::function_types::{
9    ParameterValue, ReturnType, ReturnValue,
10};
11use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode;
12use hyperlight_common::flatbuffer_wrappers::util::get_flatbuffer_result;
13use hyperlight_common::func::{ParameterTuple, SupportedReturnType};
14use hyperlight_guest::error::{HyperlightGuestError, Result};
15
16use crate::GUEST_HANDLE;
17
18pub fn call_host_function<T>(
19    function_name: &str,
20    parameters: Option<Vec<ParameterValue>>,
21    return_type: ReturnType,
22) -> Result<T>
23where
24    T: TryFrom<ReturnValue>,
25{
26    let handle = unsafe { GUEST_HANDLE };
27    handle.call_host_function::<T>(function_name, parameters, return_type)
28}
29
30pub fn call_host<T>(function_name: impl AsRef<str>, args: impl ParameterTuple) -> Result<T>
31where
32    T: SupportedReturnType + TryFrom<ReturnValue>,
33{
34    call_host_function::<T>(function_name.as_ref(), Some(args.into_value()), T::TYPE)
35}
36
37pub fn call_host_function_without_returning_result(
38    function_name: &str,
39    parameters: Option<Vec<ParameterValue>>,
40    return_type: ReturnType,
41) -> Result<()> {
42    let handle = unsafe { GUEST_HANDLE };
43    handle.call_host_function_without_returning_result(function_name, parameters, return_type)
44}
45
46pub fn get_host_return_value_raw() -> Result<ReturnValue> {
47    let handle = unsafe { GUEST_HANDLE };
48    handle.get_host_return_raw()
49}
50
51pub fn get_host_return_value<T: TryFrom<ReturnValue>>() -> Result<T> {
52    let handle = unsafe { GUEST_HANDLE };
53    handle.get_host_return_value::<T>()
54}
55
56pub fn read_n_bytes_from_user_memory(num: u64) -> Result<Vec<u8>> {
57    let handle = unsafe { GUEST_HANDLE };
58    handle.read_n_bytes_from_user_memory(num)
59}
60
61/// Print a message using the host's print function.
62///
63/// This function requires memory to be setup to be used. In particular, the
64/// existence of the input and output memory regions.
65pub fn print_output_with_host_print(function_call: FunctionCall) -> Result<Vec<u8>> {
66    let handle = unsafe { GUEST_HANDLE };
67    if let ParameterValue::String(message) = function_call.parameters.unwrap().remove(0) {
68        let res = handle.call_host_function::<i32>(
69            "HostPrint",
70            Some(Vec::from(&[ParameterValue::String(message)])),
71            ReturnType::Int,
72        )?;
73
74        Ok(get_flatbuffer_result(res))
75    } else {
76        Err(HyperlightGuestError::new(
77            ErrorCode::GuestError,
78            "Wrong Parameters passed to print_output_with_host_print".to_string(),
79        ))
80    }
81}