Skip to content

Commit

Permalink
chore(common): Use Box::leak rather than mem::forget (#180)
Browse files Browse the repository at this point in the history
Uses `Box::leak` to ensure that the files that are constructed from raw
file descriptors are kept alive for the static lifetime of the program,
rather than `mem::forget`.
  • Loading branch information
clabby authored May 26, 2024
1 parent 8ea3204 commit 6766a7d
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions crates/common/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ mod native_io {
extern crate std;

use crate::{io::FileDescriptor, traits::BasicKernelInterface};
use alloc::boxed::Box;
use anyhow::{anyhow, Result};
use std::{
fs::File,
Expand All @@ -73,7 +74,10 @@ mod native_io {
impl BasicKernelInterface for NativeIO {
fn write(fd: FileDescriptor, buf: &[u8]) -> Result<usize> {
let raw_fd: usize = fd.into();
let mut file = unsafe { File::from_raw_fd(raw_fd as i32) };
let file = unsafe {
let b = Box::new(File::from_raw_fd(raw_fd as i32));
Box::leak(b)
};
let n = file
.write(buf)
.map_err(|e| anyhow!("Error writing to buffer to file descriptor: {e}"))?;
Expand All @@ -82,21 +86,18 @@ mod native_io {
file.seek(SeekFrom::Current(-(buf.len() as i64)))
.map_err(|e| anyhow!("Failed to reset file cursor to 0: {e}"))?;

// forget the file descriptor so that the `Drop` impl doesn't close it.
std::mem::forget(file);

Ok(n)
}

fn read(fd: FileDescriptor, buf: &mut [u8]) -> Result<usize> {
let raw_fd: usize = fd.into();
let mut file = unsafe { File::from_raw_fd(raw_fd as i32) };
let file = unsafe {
let b = Box::new(File::from_raw_fd(raw_fd as i32));
Box::leak(b)
};
let n =
file.read(buf).map_err(|e| anyhow!("Error reading from file descriptor: {e}"))?;

// forget the file descriptor so that the `Drop` impl doesn't close it.
std::mem::forget(file);

Ok(n)
}

Expand Down

0 comments on commit 6766a7d

Please sign in to comment.