Skip to content

Commit

Permalink
WIP - do alignment check before reading u16 data
Browse files Browse the repository at this point in the history
  • Loading branch information
grdddj committed Nov 21, 2023
1 parent ff2aa20 commit 83805e5
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions core/embed/rust/src/ui/translations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,27 +238,35 @@ fn get_translation_by_index(index: usize) -> Option<&'static str> {
str::from_utf8(data).ok()
}

/// Given blob data returns a list of (u16, u16) values.
fn read_u16_pairs_list(bytes: &'static [u8]) -> &'static [(u16, u16)] {
let len = bytes.len() / core::mem::size_of::<(u16, u16)>();
let item_size = core::mem::size_of::<(u16, u16)>();

if bytes.len() % item_size != 0 {
return &[];
}

let len = bytes.len() / item_size;
let ptr = bytes.as_ptr() as *const (u16, u16);

// SAFETY: The following conditions must hold:
// - `bytes` must be correctly aligned for `(u16, u16)` tuples.
// - `bytes` must be of a length that is a multiple of the size of `(u16, u16)`.
// - The lifetime `'static` ensures the reference is valid for the duration of
// the program.
// SAFETY:
// - `bytes` must be correctly aligned for `(u16, u16)` tuples - checked above.
unsafe { core::slice::from_raw_parts(ptr, len) }
}

/// Given blob data returns a list of u16 values.
fn read_u16_list(bytes: &'static [u8]) -> &'static [u16] {
let len = bytes.len() / core::mem::size_of::<u16>();
let item_size = core::mem::size_of::<u16>();

if bytes.len() % item_size != 0 {
return &[];
}

let len = bytes.len() / item_size;
let ptr = bytes.as_ptr() as *const u16;

// SAFETY: The following conditions must hold:
// - `bytes` must be correctly aligned for `u16.
// - `bytes` must be of a length that is a multiple of the size of `u16.
// - The lifetime `'static` ensures the reference is valid for the duration of
// the program.
// SAFETY:
// - `bytes` must be correctly aligned for `u16 - checked above.
unsafe { core::slice::from_raw_parts(ptr, len) }
}

Expand Down

0 comments on commit 83805e5

Please sign in to comment.