Skip to main content

hyperlight_common/
mem.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
17pub const PAGE_SHIFT: u64 = 12;
18pub const PAGE_SIZE: u64 = 1 << 12;
19pub const PAGE_SIZE_USIZE: usize = 1 << 12;
20
21/// A memory region in the guest address space
22#[derive(Debug, Clone, Copy)]
23#[repr(C)]
24pub struct GuestMemoryRegion {
25    /// The size of the memory region
26    pub size: u64,
27    /// The address of the memory region
28    pub ptr: u64,
29}
30
31/// Maximum length of a file mapping label (excluding null terminator).
32pub const FILE_MAPPING_LABEL_MAX_LEN: usize = 63;
33
34/// Maximum number of file mappings that can be registered in the PEB.
35///
36/// Space for this many [`FileMappingInfo`] entries is statically
37/// reserved immediately after the [`HyperlightPEB`] struct within the
38/// same memory region. The reservation happens at layout time
39/// (see `SandboxMemoryLayout::new`) so the guest heap never overlaps
40/// the array, regardless of how many entries are actually used.
41pub const MAX_FILE_MAPPINGS: usize = 32;
42
43/// Describes a single file mapping in the guest address space.
44///
45/// Stored in the PEB's file mappings array so the guest can discover
46/// which files have been mapped, at what address, and with what label.
47#[derive(Debug, Clone, Copy)]
48#[repr(C)]
49pub struct FileMappingInfo {
50    /// The guest address where the file is mapped.
51    pub guest_addr: u64,
52    /// The page-aligned size of the mapping in bytes.
53    pub size: u64,
54    /// Null-terminated C-style label (max 63 chars + null).
55    pub label: [u8; FILE_MAPPING_LABEL_MAX_LEN + 1],
56}
57
58impl Default for FileMappingInfo {
59    fn default() -> Self {
60        Self {
61            guest_addr: 0,
62            size: 0,
63            label: [0u8; FILE_MAPPING_LABEL_MAX_LEN + 1],
64        }
65    }
66}
67
68#[derive(Debug, Clone, Copy)]
69#[repr(C)]
70pub struct HyperlightPEB {
71    pub input_stack: GuestMemoryRegion,
72    pub output_stack: GuestMemoryRegion,
73    pub init_data: GuestMemoryRegion,
74    pub guest_heap: GuestMemoryRegion,
75    /// File mappings array descriptor.
76    /// **Note:** `size` holds the **entry count** (number of valid
77    /// [`FileMappingInfo`] entries), NOT a byte size. `ptr` holds the
78    /// guest address of the preallocated array (immediately after the
79    /// PEB struct).
80    pub file_mappings: GuestMemoryRegion,
81}