From 83805e57dc90a13ebcfc92072d4267b29feb154a Mon Sep 17 00:00:00 2001 From: grdddj Date: Tue, 21 Nov 2023 12:15:02 +0100 Subject: [PATCH] WIP - do alignment check before reading u16 data --- core/embed/rust/src/ui/translations/mod.rs | 32 ++++++++++++++-------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/core/embed/rust/src/ui/translations/mod.rs b/core/embed/rust/src/ui/translations/mod.rs index a391935cb6e..22599ed27b6 100644 --- a/core/embed/rust/src/ui/translations/mod.rs +++ b/core/embed/rust/src/ui/translations/mod.rs @@ -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::(); + let item_size = core::mem::size_of::(); + + 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) } }