Skip to content

Commit

Permalink
utils: introduce mechanism to generate Merkle tree for verity
Browse files Browse the repository at this point in the history
Introduce mechanism to generate Merkle tree for verity.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
  • Loading branch information
jiangliu committed Mar 28, 2023
1 parent 59690f7 commit c978f39
Show file tree
Hide file tree
Showing 3 changed files with 464 additions and 0 deletions.
22 changes: 22 additions & 0 deletions utils/src/filemap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,28 @@ impl FileMapState {
Ok(unsafe { std::slice::from_raw_parts(start as *const T, count) })
}

/// Get a mutable slice of 'T' at 'offset' with 'count' entries.
pub fn get_slice_mut<T>(&mut self, offset: usize, count: usize) -> Result<&mut [T]> {
let start = self.base.wrapping_add(offset);
if count.checked_mul(size_of::<T>()).is_none() {
bail_einval!("count 0x{count:x} to validate_slice() is too big");
}
let size = count * size_of::<T>();
if size.checked_add(start as usize).is_none() {
bail_einval!(
"invalid parameter to validate_slice(), offset 0x{offset:x}, count 0x{count:x}"
);
}
let end = start.wrapping_add(size);
if start > end || start < self.base || end < self.base || end > self.end {
bail_einval!(
"invalid range in validate_slice, base 0x{:p}, start 0x{start:p}, end 0x{end:p}",
self.base
);
}
Ok(unsafe { std::slice::from_raw_parts_mut(start as *mut T, count) })
}

/// Check whether the range [offset, offset + size) is valid and return the start address.
pub fn validate_range(&self, offset: usize, size: usize) -> Result<*const u8> {
let start = self.base.wrapping_add(offset);
Expand Down
8 changes: 8 additions & 0 deletions utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ pub mod mpmc;
pub mod reader;
pub mod trace;
pub mod types;
pub mod verity;

/// Round up and divide the value `n` by `d`.
pub fn div_round_up(n: u64, d: u64) -> u64 {
Expand All @@ -48,6 +49,13 @@ pub fn round_up(n: u64, d: u64) -> u64 {
(n + d - 1) / d * d
}

/// Round up the value `n` to by `d`.
pub fn round_up_usize(n: usize, d: usize) -> usize {
debug_assert!(d != 0);
debug_assert!(d.is_power_of_two());
(n + d - 1) / d * d
}

/// Overflow can fail this rounder if the base value is large enough with 4095 added.
pub fn try_round_up_4k<U: TryFrom<u64>, T: Into<u64>>(x: T) -> Option<U> {
let t = 4095u64;
Expand Down
Loading

0 comments on commit c978f39

Please sign in to comment.