Skip to content

Commit 23058ec

Browse files
committed
Remove and prevent use of unwrap in hyperlight_host
Signed-off-by: Simon Davies <[email protected]>
1 parent d047d51 commit 23058ec

File tree

13 files changed

+73
-42
lines changed

13 files changed

+73
-42
lines changed

src/hyperlight_host/src/hypervisor/hypervisor_handler.rs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,11 @@ impl HypervisorHandler {
246246
#[cfg(target_os = "windows")]
247247
let in_process = sandbox_memory_manager.is_in_process();
248248

249-
*self.execution_variables.shm.try_lock().unwrap() = Some(sandbox_memory_manager);
249+
*self
250+
.execution_variables
251+
.shm
252+
.try_lock()
253+
.map_err(|e| new_error!("Failed to lock shm: {}", e))? = Some(sandbox_memory_manager);
250254

251255
// Other than running initialization and code execution, the handler thread also handles
252256
// cancellation. When we need to cancel the execution there are 2 possible cases
@@ -299,13 +303,13 @@ impl HypervisorHandler {
299303
HypervisorHandlerAction::Initialise => {
300304
{
301305
hv = Some(set_up_hypervisor_partition(
302-
execution_variables.shm.try_lock().unwrap().deref_mut().as_mut().unwrap(),
306+
execution_variables.shm.try_lock().map_err(|e| new_error!("Failed to lock shm: {}", e))?.deref_mut().as_mut().ok_or_else(|| new_error!("shm not set"))?,
303307
configuration.outb_handler.clone(),
304308
#[cfg(gdb)]
305309
&debug_info,
306310
)?);
307311
}
308-
let hv = hv.as_mut().unwrap();
312+
let hv = hv.as_mut().ok_or_else(|| new_error!("Hypervisor not set"))?;
309313

310314
#[cfg(target_os = "windows")]
311315
if !in_process {
@@ -386,7 +390,7 @@ impl HypervisorHandler {
386390
}
387391
}
388392
HypervisorHandlerAction::DispatchCallFromHost(function_name) => {
389-
let hv = hv.as_mut().unwrap();
393+
let hv = hv.as_mut().ok_or_else(|| new_error!("Hypervisor not initialized"))?;
390394

391395
// Lock to indicate an action is being performed in the hypervisor
392396
execution_variables.running.store(true, Ordering::SeqCst);
@@ -647,6 +651,8 @@ impl HypervisorHandler {
647651
// If the thread has finished, we try to join it and return the error if it has one
648652
let res = handle.join();
649653
if res.as_ref().is_ok_and(|inner_res| inner_res.is_err()) {
654+
#[allow(clippy::unwrap_used)]
655+
// We know that the thread has finished and that the inner result is an error, so we can safely unwrap the result and the contained err
650656
return Err(res.unwrap().unwrap_err());
651657
}
652658
Err(HyperlightError::HypervisorHandlerMessageReceiveTimedout())
@@ -757,7 +763,7 @@ impl HypervisorHandler {
757763
if thread_id == u64::MAX {
758764
log_then_return!("Failed to get thread id to signal thread");
759765
}
760-
let mut count: i32 = 0;
766+
let mut count: u128 = 0;
761767
// We need to send the signal multiple times in case the thread was between checking if it
762768
// should be cancelled and entering the run loop
763769

@@ -771,7 +777,7 @@ impl HypervisorHandler {
771777
while !self.execution_variables.run_cancelled.load() {
772778
count += 1;
773779

774-
if count > number_of_iterations.try_into().unwrap() {
780+
if count > number_of_iterations {
775781
break;
776782
}
777783

@@ -797,7 +803,8 @@ impl HypervisorHandler {
797803
// partition handle only set when running in-hypervisor (not in-process)
798804
unsafe {
799805
WHvCancelRunVirtualProcessor(
800-
self.execution_variables.get_partition_handle()?.unwrap(), // safe unwrap
806+
#[allow(clippy::unwrap_used)]
807+
self.execution_variables.get_partition_handle()?.unwrap(), // safe unwrap as we checked is some
801808
0,
802809
0,
803810
)

src/hyperlight_host/src/hypervisor/surrogate_process_manager.rs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -267,14 +267,26 @@ impl Drop for SurrogateProcessManager {
267267
lazy_static::lazy_static! {
268268
// see the large comment inside `SurrogateProcessManager` describing
269269
// our reasoning behind using `lazy_static`.
270-
static ref SURROGATE_PROCESSES_MANAGER: SurrogateProcessManager =
271-
SurrogateProcessManager::new().unwrap();
270+
static ref SURROGATE_PROCESSES_MANAGER: std::result::Result<SurrogateProcessManager, &'static str> =
271+
match SurrogateProcessManager::new() {
272+
Ok(manager) => Ok(manager),
273+
Err(e) => {
274+
error!("Failed to create SurrogateProcessManager: {:?}", e);
275+
Err("Failed to create SurrogateProcessManager")
276+
}
277+
};
272278
}
273279

274280
/// Gets the singleton SurrogateProcessManager. This should be called when a new HyperV on Windows Driver is created.
275281
#[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")]
276282
pub(crate) fn get_surrogate_process_manager() -> Result<&'static SurrogateProcessManager> {
277-
Ok(&SURROGATE_PROCESSES_MANAGER)
283+
match &*SURROGATE_PROCESSES_MANAGER {
284+
Ok(manager) => Ok(manager),
285+
Err(e) => {
286+
error!("Failed to get SurrogateProcessManager: {:?}", e);
287+
Err(new_error!("Failed to get SurrogateProcessManager {}", e))
288+
}
289+
}
278290
}
279291

280292
// Creates a job object that will terminate all the surrogate processes when the struct instance is dropped.

src/hyperlight_host/src/hypervisor/windows_hypervisor_platform.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ pub unsafe fn try_load_whv_map_gpa_range2() -> Result<WHvMapGpaRange2Func> {
165165
return Err(new_error!("{}", e));
166166
}
167167

168+
#[allow(clippy::unwrap_used)]
169+
// We know this will succeed because we just checked for an error above
168170
let library = library.unwrap();
169171

170172
let address = unsafe { GetProcAddress(library, s!("WHvMapGpaRange2")) };

src/hyperlight_host/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ limitations under the License.
1919

2020
#![cfg_attr(not(any(test, debug_assertions)), warn(clippy::panic))]
2121
#![cfg_attr(not(any(test, debug_assertions)), warn(clippy::expect_used))]
22+
#![cfg_attr(not(any(test, debug_assertions)), warn(clippy::unwrap_used))]
2223

2324
use std::sync::Once;
2425

src/hyperlight_host/src/mem/elf.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,20 +52,22 @@ impl ElfInfo {
5252
self.entry
5353
}
5454
pub(crate) fn get_base_va(&self) -> u64 {
55+
#[allow(clippy::unwrap_used)] // guaranteed not to panic because of the check in new()
5556
let min_phdr = self
5657
.phdrs
5758
.iter()
5859
.find(|phdr| phdr.p_type == PT_LOAD)
59-
.unwrap(); // guaranteed not to panic because of the check in new()
60+
.unwrap();
6061
min_phdr.p_vaddr
6162
}
6263
pub(crate) fn get_va_size(&self) -> usize {
64+
#[allow(clippy::unwrap_used)] // guaranteed not to panic because of the check in new()
6365
let max_phdr = self
6466
.phdrs
6567
.iter()
6668
.rev()
6769
.find(|phdr| phdr.p_type == PT_LOAD)
68-
.unwrap(); // guaranteed not to panic because of the check in new()
70+
.unwrap();
6971
(max_phdr.p_vaddr + max_phdr.p_memsz - self.get_base_va()) as usize
7072
}
7173
pub(crate) fn load_at(&self, load_addr: usize, target: &mut [u8]) -> Result<()> {

src/hyperlight_host/src/mem/loaded_lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ impl LoadedLib {
5454
// arc reference is dropped, but before the destructor is executed. This however
5555
// is ok, as it means that the old library is not going to be used anymore and
5656
// we can use it instead.
57-
let mut lock = LOADED_LIB.lock().unwrap();
57+
let mut lock = LOADED_LIB.lock()?;
5858
if lock.upgrade().is_some() {
5959
// An owning copy of the loaded library still exists somewhere,
6060
// we can't load a new library yet

src/hyperlight_host/src/mem/memory_region.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,8 @@ impl MemoryRegionVecBuilder {
202202
return guest_end - self.guest_base_phys_addr;
203203
}
204204

205+
#[allow(clippy::unwrap_used)]
206+
// we know this is safe because we check if the regions are empty above
205207
let last_region = self.regions.last().unwrap();
206208
let new_region = MemoryRegion {
207209
guest_region: last_region.guest_region.end..last_region.guest_region.end + size,

src/hyperlight_host/src/mem/mgr.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@ where
300300
if last.is_none() {
301301
log_then_return!(NoMemorySnapshot);
302302
}
303+
#[allow(clippy::unwrap_used)] // We know that last is not None because we checked it above
303304
let snapshot = last.unwrap();
304305
snapshot.restore_from_snapshot(&mut self.shared_mem)
305306
}

src/hyperlight_host/src/mem/pe/base_relocations.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ impl<'a> Iterator for BaseRelocations<'a> {
9191
let word = u16::from_le_bytes(block);
9292

9393
// Shift the word over so that we are only reading a number from the first (most significant) 4 bits
94+
#[allow(clippy::unwrap_used)] // this is safe as we are only reading 4 bits from a u16
9495
let typ = u8::try_from(word >> 12).unwrap();
9596

9697
// Set the first 4 bits to 0 so that we only use the lower 12 bits for the location of the RVA in the PE file

src/hyperlight_host/src/mem/shared_mem.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -885,7 +885,7 @@ impl HostSharedMemory {
885885
buffer_size: usize,
886886
data: &[u8],
887887
) -> Result<()> {
888-
let stack_pointer_rel = self.read::<u64>(buffer_start_offset).unwrap() as usize;
888+
let stack_pointer_rel = self.read::<u64>(buffer_start_offset)? as usize;
889889
let buffer_size_u64: u64 = buffer_size.try_into()?;
890890

891891
if stack_pointer_rel > buffer_size || stack_pointer_rel < 8 {
@@ -953,7 +953,7 @@ impl HostSharedMemory {
953953

954954
// go back 8 bytes to get offset to element on top of stack
955955
let last_element_offset_rel: usize =
956-
self.read::<u64>(last_element_offset_abs - 8).unwrap() as usize;
956+
self.read::<u64>(last_element_offset_abs - 8)? as usize;
957957

958958
// make it absolute
959959
let last_element_offset_abs = last_element_offset_rel + buffer_start_offset;

0 commit comments

Comments
 (0)