Skip to content

Commit

Permalink
Fix search segfaulting on empty bucket files
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Saveau <[email protected]>
  • Loading branch information
SUPERCILEX committed Jul 1, 2024
1 parent 6e17500 commit 3e31ba1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 24 deletions.
2 changes: 1 addition & 1 deletion client-sdk/src/ring_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ impl EntryReader {
let mut maps = ArrayVec::new_const();
for (i, fd) in buckets.into_iter().enumerate() {
maps.push(
Mmap::new(fd, usize::try_from(lengths[i]).unwrap().max(4096))
Mmap::new(fd, usize::try_from(lengths[i]).unwrap())
.map_io_err(|| "Failed to map memory.")?,
);
}
Expand Down
42 changes: 19 additions & 23 deletions ringboard/src/ring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ impl BucketEntry {
#[derive(Debug)]
pub struct Mmap {
ptr: NonNull<u8>,
len: usize,
requested_len: usize,
backing_len: usize,
}

unsafe impl Send for Mmap {}
Expand All @@ -127,37 +128,25 @@ impl Mmap {
}

pub fn new<Fd: AsFd>(fd: Fd, len: usize) -> rustix::io::Result<Self> {
if len == 0 {
return Ok(Self {
ptr: NonNull::dangling(),
len,
});
}

let backing_len = len.max(4096);
Ok(Self {
ptr: unsafe {
NonNull::new_unchecked(mmap(
ptr::null_mut(),
len,
backing_len,
ProtFlags::READ,
MapFlags::SHARED_VALIDATE,
fd,
0,
)?)
}
.cast(),
len,
requested_len: len,
backing_len,
})
}

pub fn new_anon(len: usize) -> rustix::io::Result<Self> {
if len == 0 {
return Ok(Self {
ptr: NonNull::dangling(),
len,
});
}

Ok(Self {
ptr: unsafe {
NonNull::new_unchecked(mmap_anonymous(
Expand All @@ -168,23 +157,30 @@ impl Mmap {
)?)
}
.cast(),
len,
requested_len: len,
backing_len: len,
})
}

pub fn remap(&mut self, len: usize) -> rustix::io::Result<()> {
if len >= self.requested_len && len <= self.backing_len {
self.requested_len = len;
return Ok(());
}

self.ptr = unsafe {
NonNull::new_unchecked(
mremap(
self.ptr.as_ptr().cast(),
self.len,
self.backing_len,
len,
MremapFlags::MAYMOVE,
)?
.cast(),
)
};
self.len = len;
self.requested_len = len;
self.backing_len = len;
Ok(())
}

Expand All @@ -195,12 +191,12 @@ impl Mmap {

#[must_use]
pub const fn len(&self) -> usize {
self.len
self.requested_len
}

#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
self.requested_len == 0
}
}

Expand All @@ -220,7 +216,7 @@ impl AsRef<[u8]> for Mmap {

impl Drop for Mmap {
fn drop(&mut self) {
let _ = unsafe { munmap(self.ptr.as_ptr().cast(), self.len) };
let _ = unsafe { munmap(self.ptr.as_ptr().cast(), self.backing_len) };
}
}

Expand Down

0 comments on commit 3e31ba1

Please sign in to comment.