Skip to content

Commit

Permalink
Merge pull request #15 from dadada/fix-panic-when-read-from-empty-file
Browse files Browse the repository at this point in the history
fix panic on empty read from file
  • Loading branch information
wucke13 authored Dec 9, 2022
2 parents 2f69d2b + 24e28b3 commit d3d68cf
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 15 deletions.
19 changes: 9 additions & 10 deletions core/src/file.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
//! Implementation of in-memory files
use std::io::{Read, Seek, SeekFrom, Write};
use std::marker::PhantomData;
use std::mem::size_of;
use std::os::unix::prelude::{AsRawFd, IntoRawFd, RawFd};
use std::os::unix::prelude::{AsRawFd, FileExt, IntoRawFd, RawFd};

use anyhow::{anyhow, Result};
use memfd::{FileSeal, Memfd, MemfdOptions};
Expand Down Expand Up @@ -79,21 +78,21 @@ impl<T: Send + Clone + Sized> TempFile<T> {
// TODO: Use an approach without unsafe
let bytes =
unsafe { std::slice::from_raw_parts(value as *const T as *const u8, size_of::<T>()) };
let mut file = self.get_memfd()?.into_file();
file.seek(SeekFrom::Start(0)).typ(SystemError::Panic)?;
file.write_all(bytes)
let file = self.get_memfd()?.into_file();
file.write_all_at(bytes, 0)
.map_err(anyhow::Error::from)
.typ(SystemError::Panic)
}

/// Returns all of the TempFile's data
pub fn read(&self) -> TypedResult<T> {
let mut buf = Vec::with_capacity(size_of::<T>());
let mut file = self.get_memfd()?.into_file();
file.seek(SeekFrom::Start(0)).typ(SystemError::Panic)?;
file.read_to_end(buf.as_mut()).typ(SystemError::Panic)?;
let mut buf = vec![0u8; size_of::<T>()];
let buf = buf.as_mut_slice();
let file = self.get_memfd()?.into_file();
file.read_at(buf, 0).typ(SystemError::Panic)?;
// TODO: Use an approach without unsafe
Ok(unsafe { buf.as_slice().align_to::<T>().1[0].clone() })
let aligned = unsafe { buf.align_to::<T>() };
Ok(aligned.1[0].clone())
}

/// Returns a mutable memory map from a TempFile
Expand Down
11 changes: 6 additions & 5 deletions partition/src/apex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,12 @@ impl ApexSamplingPortP4 for ApexLinuxPartition {
sampling_port_id: SamplingPortId,
message: &mut [ApexByte],
) -> Result<(Validity, MessageSize), ErrorReturnCode> {
if let Some((port, val)) = SAMPLING_PORTS
.read()
.unwrap()
.get(sampling_port_id as usize - 1)
{
let read = if let Ok(read) = SAMPLING_PORTS.read() {
read
} else {
return Err(ErrorReturnCode::NotAvailable);
};
if let Some((port, val)) = read.get(sampling_port_id as usize - 1) {
if let Some(port) = CONSTANTS.sampling.get(*port) {
if message.is_empty() {
return Err(ErrorReturnCode::InvalidParam);
Expand Down

0 comments on commit d3d68cf

Please sign in to comment.