unc_vm_vm/instance/allocator.rs
1use super::{Instance, InstanceRef};
2use crate::vmcontext::{VMMemoryDefinition, VMTableDefinition};
3use crate::VMOffsets;
4use std::alloc::{self, Layout};
5use std::convert::TryFrom;
6use std::mem;
7use std::ptr::{self, NonNull};
8use unc_vm_types::entity::EntityRef;
9use unc_vm_types::{LocalMemoryIndex, LocalTableIndex};
10
11/// This is an intermediate type that manages the raw allocation and
12/// metadata when creating an [`Instance`].
13///
14/// This type will free the allocated memory if it's dropped before
15/// being used.
16///
17/// It is important to remind that [`Instance`] is dynamically-sized
18/// based on `VMOffsets`: The `Instance.vmctx` field represents a
19/// dynamically-sized array that extends beyond the nominal end of the
20/// type. So in order to create an instance of it, we must:
21///
22/// 1. Define the correct layout for `Instance` (size and alignment),
23/// 2. Allocate it properly.
24///
25/// The [`InstanceAllocator::instance_layout`] computes the correct
26/// layout to represent the wanted [`Instance`].
27///
28/// Then we use this layout to allocate an empty `Instance` properly.
29pub struct InstanceAllocator {
30 /// The buffer that will contain the [`Instance`] and dynamic fields.
31 instance_ptr: NonNull<Instance>,
32
33 /// The layout of the `instance_ptr` buffer.
34 instance_layout: Layout,
35
36 /// Information about the offsets into the `instance_ptr` buffer for
37 /// the dynamic fields.
38 offsets: VMOffsets,
39
40 /// Whether or not this type has transferred ownership of the
41 /// `instance_ptr` buffer. If it has not when being dropped,
42 /// the buffer should be freed.
43 consumed: bool,
44}
45
46impl Drop for InstanceAllocator {
47 fn drop(&mut self) {
48 if !self.consumed {
49 // If `consumed` has not been set, then we still have ownership
50 // over the buffer and must free it.
51 let instance_ptr = self.instance_ptr.as_ptr();
52
53 unsafe {
54 std::alloc::dealloc(instance_ptr as *mut u8, self.instance_layout);
55 }
56 }
57 }
58}
59
60impl InstanceAllocator {
61 /// Allocates instance data for use with [`InstanceHandle::new`].
62 ///
63 /// Returns a wrapper type around the allocation and 2 vectors of
64 /// pointers into the allocated buffer. These lists of pointers
65 /// correspond to the location in memory for the local memories and
66 /// tables respectively. These pointers should be written to before
67 /// calling [`InstanceHandle::new`].
68 ///
69 /// [`InstanceHandle::new`]: super::InstanceHandle::new
70 pub fn new(
71 offsets: VMOffsets,
72 ) -> (Self, Vec<NonNull<VMMemoryDefinition>>, Vec<NonNull<VMTableDefinition>>) {
73 let instance_layout = Self::instance_layout(&offsets);
74
75 #[allow(clippy::cast_ptr_alignment)]
76 let instance_ptr = unsafe { alloc::alloc(instance_layout) as *mut Instance };
77
78 let instance_ptr = if let Some(ptr) = NonNull::new(instance_ptr) {
79 ptr
80 } else {
81 alloc::handle_alloc_error(instance_layout);
82 };
83
84 let allocator = Self { instance_ptr, instance_layout, offsets, consumed: false };
85
86 // # Safety
87 // Both of these calls are safe because we allocate the pointer
88 // above with the same `offsets` that these functions use.
89 // Thus there will be enough valid memory for both of them.
90 let memories = unsafe { allocator.memory_definition_locations() };
91 let tables = unsafe { allocator.table_definition_locations() };
92
93 (allocator, memories, tables)
94 }
95
96 /// Calculate the appropriate layout for the [`Instance`].
97 fn instance_layout(offsets: &VMOffsets) -> Layout {
98 let vmctx_size = usize::try_from(offsets.size_of_vmctx())
99 .expect("Failed to convert the size of `vmctx` to a `usize`");
100
101 let instance_vmctx_layout =
102 Layout::array::<u8>(vmctx_size).expect("Failed to create a layout for `VMContext`");
103
104 let (instance_layout, _offset) = Layout::new::<Instance>()
105 .extend(instance_vmctx_layout)
106 .expect("Failed to extend to `Instance` layout to include `VMContext`");
107
108 instance_layout.pad_to_align()
109 }
110
111 /// Get the locations of where the local [`VMMemoryDefinition`]s should be stored.
112 ///
113 /// This function lets us create `Memory` objects on the host with backing
114 /// memory in the VM.
115 ///
116 /// # Safety
117 ///
118 /// - `Self.instance_ptr` must point to enough memory that all of
119 /// the offsets in `Self.offsets` point to valid locations in
120 /// memory, i.e. `Self.instance_ptr` must have been allocated by
121 /// `Self::new`.
122 unsafe fn memory_definition_locations(&self) -> Vec<NonNull<VMMemoryDefinition>> {
123 let num_memories = self.offsets.num_local_memories();
124 let num_memories = usize::try_from(num_memories).unwrap();
125 let mut out = Vec::with_capacity(num_memories);
126
127 // We need to do some pointer arithmetic now. The unit is `u8`.
128 let ptr = self.instance_ptr.cast::<u8>().as_ptr();
129 let base_ptr = ptr.add(mem::size_of::<Instance>());
130
131 for i in 0..num_memories {
132 let mem_offset = self.offsets.vmctx_vmmemory_definition(LocalMemoryIndex::new(i));
133 let mem_offset = usize::try_from(mem_offset).unwrap();
134
135 let new_ptr = NonNull::new_unchecked(base_ptr.add(mem_offset));
136
137 out.push(new_ptr.cast());
138 }
139
140 out
141 }
142
143 /// Get the locations of where the [`VMTableDefinition`]s should be stored.
144 ///
145 /// This function lets us create [`Table`] objects on the host with backing
146 /// memory in the VM.
147 ///
148 /// # Safety
149 ///
150 /// - `Self.instance_ptr` must point to enough memory that all of
151 /// the offsets in `Self.offsets` point to valid locations in
152 /// memory, i.e. `Self.instance_ptr` must have been allocated by
153 /// `Self::new`.
154 unsafe fn table_definition_locations(&self) -> Vec<NonNull<VMTableDefinition>> {
155 let num_tables = self.offsets.num_local_tables();
156 let num_tables = usize::try_from(num_tables).unwrap();
157 let mut out = Vec::with_capacity(num_tables);
158
159 // We need to do some pointer arithmetic now. The unit is `u8`.
160 let ptr = self.instance_ptr.cast::<u8>().as_ptr();
161 let base_ptr = ptr.add(std::mem::size_of::<Instance>());
162
163 for i in 0..num_tables {
164 let table_offset = self.offsets.vmctx_vmtable_definition(LocalTableIndex::new(i));
165 let table_offset = usize::try_from(table_offset).unwrap();
166
167 let new_ptr = NonNull::new_unchecked(base_ptr.add(table_offset));
168
169 out.push(new_ptr.cast());
170 }
171 out
172 }
173
174 /// Finish preparing by writing the [`Instance`] into memory, and
175 /// consume this `InstanceAllocator`.
176 pub(crate) fn write_instance(mut self, instance: Instance) -> InstanceRef {
177 // Prevent the old state's drop logic from being called as we
178 // transition into the new state.
179 self.consumed = true;
180
181 unsafe {
182 // `instance` is moved at `Self.instance_ptr`. This
183 // pointer has been allocated by `Self::allocate_instance`
184 // (so by `InstanceRef::allocate_instance`).
185 ptr::write(self.instance_ptr.as_ptr(), instance);
186 // Now `instance_ptr` is correctly initialized!
187 }
188 let instance = self.instance_ptr;
189 let instance_layout = self.instance_layout;
190
191 // This is correct because of the invariants of `Self` and
192 // because we write `Instance` to the pointer in this function.
193 unsafe { InstanceRef::new(instance, instance_layout) }
194 }
195}