1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-21 13:58:08 +00:00

chore(core/rust): drop cstr_core dependency

now that we have c"..." literals in Rust
This commit is contained in:
matejcik 2024-06-05 12:58:33 +02:00 committed by matejcik
parent ce2436245d
commit 567de6579e
16 changed files with 39 additions and 60 deletions

View File

@ -78,16 +78,6 @@ dependencies = [
"libloading", "libloading",
] ]
[[package]]
name = "cstr_core"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd98742e4fdca832d40cab219dc2e3048de17d873248f83f17df47c1bea70956"
dependencies = [
"cty",
"memchr",
]
[[package]] [[package]]
name = "cty" name = "cty"
version = "0.2.2" version = "0.2.2"
@ -340,7 +330,6 @@ version = "0.1.0"
dependencies = [ dependencies = [
"bindgen", "bindgen",
"cc", "cc",
"cstr_core",
"cty", "cty",
"easer", "easer",
"glob", "glob",

View File

@ -112,11 +112,6 @@ features = ["libm"]
[dependencies.num-derive] [dependencies.num-derive]
version = "0.3.3" version = "0.3.3"
[dependencies.cstr_core]
version = "0.2.6"
default-features = false
features = ["nightly"]
[dependencies.static-alloc] [dependencies.static-alloc]
version = "0.2.4" version = "0.2.4"

View File

@ -16,9 +16,9 @@ pub enum Error {
impl From<Error> for crate::error::Error { impl From<Error> for crate::error::Error {
fn from(e: Error) -> Self { fn from(e: Error) -> Self {
match e { match e {
Error::SignatureVerificationFailed => value_error!("Signature verification failed"), Error::SignatureVerificationFailed => value_error!(c"Signature verification failed"),
Error::InvalidEncoding => value_error!("Invalid key or signature encoding"), Error::InvalidEncoding => value_error!(c"Invalid key or signature encoding"),
Error::InvalidParams => value_error!("Invalid cryptographic parameters"), Error::InvalidParams => value_error!(c"Invalid cryptographic parameters"),
} }
} }
} }

View File

@ -1,5 +1,4 @@
use core::{convert::Infallible, num::TryFromIntError}; use core::{convert::Infallible, ffi::CStr, num::TryFromIntError};
use cstr_core::CStr;
#[cfg(feature = "micropython")] #[cfg(feature = "micropython")]
use { use {
@ -30,7 +29,7 @@ pub enum Error {
#[macro_export] #[macro_export]
macro_rules! value_error { macro_rules! value_error {
($msg:expr) => { ($msg:expr) => {
$crate::error::Error::ValueError(cstr_core::cstr!($msg)) $crate::error::Error::ValueError($msg)
}; };
} }

View File

@ -1,6 +1,7 @@
use core::convert::{TryFrom, TryInto}; use core::{
convert::{TryFrom, TryInto},
use cstr_core::CStr; ffi::CStr,
};
use crate::error::Error; use crate::error::Error;
@ -290,7 +291,7 @@ impl TryFrom<&'static CStr> for Obj {
// SAFETY: // SAFETY:
// - `CStr` is guaranteed to be null-terminated UTF-8. // - `CStr` is guaranteed to be null-terminated UTF-8.
// - the argument is static so it will remain valid for the lifetime of result. // - the argument is static so it will remain valid for the lifetime of result.
let obj = unsafe { ffi::trezor_obj_str_from_rom_text(val.as_ptr()) }; let obj = unsafe { ffi::trezor_obj_str_from_rom_text(val.as_ptr() as _) };
if obj.is_null() { if obj.is_null() {
Err(Error::AllocationFailed) Err(Error::AllocationFailed)
} else { } else {

View File

@ -133,7 +133,7 @@ where
let vec: Vec<T, N> = iter_into_vec(iterable)?; let vec: Vec<T, N> = iter_into_vec(iterable)?;
// Returns error if array.len() != N // Returns error if array.len() != N
vec.into_array() vec.into_array()
.map_err(|_| value_error!("Invalid iterable length")) .map_err(|_| value_error!(c"Invalid iterable length"))
} }
pub fn iter_into_vec<T, E, const N: usize>(iterable: Obj) -> Result<Vec<T, N>, Error> pub fn iter_into_vec<T, E, const N: usize>(iterable: Obj) -> Result<Vec<T, N>, Error>
@ -144,7 +144,7 @@ where
let mut vec = Vec::<T, N>::new(); let mut vec = Vec::<T, N>::new();
for item in IterBuf::new().try_iterate(iterable)? { for item in IterBuf::new().try_iterate(iterable)? {
vec.push(item.try_into()?) vec.push(item.try_into()?)
.map_err(|_| value_error!("Invalid iterable length"))?; .map_err(|_| value_error!(c"Invalid iterable length"))?;
} }
Ok(vec) Ok(vec)
} }

View File

@ -1,23 +1,21 @@
use cstr_core::cstr;
use crate::{error::Error, micropython::qstr::Qstr}; use crate::{error::Error, micropython::qstr::Qstr};
pub const fn experimental_not_enabled() -> Error { pub const fn experimental_not_enabled() -> Error {
value_error!("Experimental features are disabled.") value_error!(c"Experimental features are disabled.")
} }
pub const fn unknown_field_type() -> Error { pub const fn unknown_field_type() -> Error {
value_error!("Unknown field type.") value_error!(c"Unknown field type.")
} }
pub fn missing_required_field(field: Qstr) -> Error { pub fn missing_required_field(field: Qstr) -> Error {
Error::ValueErrorParam(cstr!("Missing required field."), field.into()) Error::ValueErrorParam(c"Missing required field.", field.into())
} }
pub fn invalid_value(field: Qstr) -> Error { pub fn invalid_value(field: Qstr) -> Error {
Error::ValueErrorParam(cstr!("Invalid value for field."), field.into()) Error::ValueErrorParam(c"Invalid value for field.", field.into())
} }
pub const fn end_of_buffer() -> Error { pub const fn end_of_buffer() -> Error {
value_error!("End of buffer.") value_error!(c"End of buffer.")
} }

View File

@ -19,7 +19,7 @@ const SIGNATURE_THRESHOLD: u8 = 2;
// should be max 1. // should be max 1.
const MAX_TABLE_PADDING: usize = 3; const MAX_TABLE_PADDING: usize = 3;
const INVALID_TRANSLATIONS_BLOB: Error = value_error!("Invalid translations blob"); const INVALID_TRANSLATIONS_BLOB: Error = value_error!(c"Invalid translations blob");
#[repr(packed)] #[repr(packed)]
struct OffsetEntry { struct OffsetEntry {
@ -145,7 +145,7 @@ impl<'a> Translations<'a> {
let remaining = blob_reader.rest(); let remaining = blob_reader.rest();
if !remaining.iter().all(|&b| b == EMPTY_BYTE) { if !remaining.iter().all(|&b| b == EMPTY_BYTE) {
// TODO optimize to quadwords? // TODO optimize to quadwords?
return Err(value_error!("Trailing data in translations blob")); return Err(value_error!(c"Trailing data in translations blob"));
} }
let payload_bytes = payload_reader.rest(); let payload_bytes = payload_reader.rest();
@ -337,7 +337,7 @@ impl<'a> TranslationsHeader<'a> {
let model = read_fixedsize_str(&mut header_reader, 4)?; let model = read_fixedsize_str(&mut header_reader, 4)?;
if model != crate::trezorhal::model::INTERNAL_NAME { if model != crate::trezorhal::model::INTERNAL_NAME {
return Err(value_error!("Wrong Trezor model")); return Err(value_error!(c"Wrong Trezor model"));
} }
let version_bytes = header_reader.read(4)?; let version_bytes = header_reader.read(4)?;

View File

@ -15,7 +15,7 @@ pub fn erase() -> Result<(), Error> {
let blob = unwrap!(TRANSLATIONS_ON_FLASH.try_write()); let blob = unwrap!(TRANSLATIONS_ON_FLASH.try_write());
{ {
if blob.is_some() { if blob.is_some() {
return Err(value_error!("Translations blob already set")); return Err(value_error!(c"Translations blob already set"));
} }
// SAFETY: The blob is not set, so there are no references to it. // SAFETY: The blob is not set, so there are no references to it.
@ -33,7 +33,7 @@ pub fn write(data: &[u8], offset: usize) -> Result<(), Error> {
let blob = unwrap!(TRANSLATIONS_ON_FLASH.try_write()); let blob = unwrap!(TRANSLATIONS_ON_FLASH.try_write());
let result = { let result = {
if blob.is_some() { if blob.is_some() {
return Err(value_error!("Translations blob already set")); return Err(value_error!(c"Translations blob already set"));
} }
// SAFETY: The blob is not set, so there are no references to it. // SAFETY: The blob is not set, so there are no references to it.
@ -42,7 +42,7 @@ pub fn write(data: &[u8], offset: usize) -> Result<(), Error> {
if result { if result {
Ok(()) Ok(())
} else { } else {
Err(value_error!("Failed to write translations blob")) Err(value_error!(c"Failed to write translations blob"))
} }
} }
@ -92,7 +92,7 @@ pub fn init() {
/// If the blob is locked by a reader, `deinit()` will return an error. /// If the blob is locked by a reader, `deinit()` will return an error.
pub fn deinit() -> Result<(), Error> { pub fn deinit() -> Result<(), Error> {
let Some(mut blob) = TRANSLATIONS_ON_FLASH.try_write() else { let Some(mut blob) = TRANSLATIONS_ON_FLASH.try_write() else {
return Err(value_error!("Translations are in use.")); return Err(value_error!(c"Translations are in use."));
}; };
*blob = None; *blob = None;
Ok(()) Ok(())
@ -116,5 +116,5 @@ pub fn deinit() -> Result<(), Error> {
pub fn get() -> Result<RwLockReadGuard<'static, Option<Translations<'static>>>, Error> { pub fn get() -> Result<RwLockReadGuard<'static, Option<Translations<'static>>>, Error> {
TRANSLATIONS_ON_FLASH TRANSLATIONS_ON_FLASH
.try_read() .try_read()
.ok_or_else(|| value_error!("Translations are in use.")) .ok_or(value_error!(c"Translations are in use."))
} }

View File

@ -1,5 +1,4 @@
use core::str; use core::{ffi::CStr, str};
use cstr_core::CStr;
use super::ffi; use super::ffi;
@ -26,6 +25,6 @@ pub fn button_sequence_to_word(prefix: u16) -> Option<&'static str> {
} else { } else {
// SAFETY: On success, `button_sequence_to_word` should return a 0-terminated // SAFETY: On success, `button_sequence_to_word` should return a 0-terminated
// UTF-8 string with static lifetime. // UTF-8 string with static lifetime.
Some(unsafe { str::from_utf8_unchecked(CStr::from_ptr(word).to_bytes()) }) Some(unsafe { str::from_utf8_unchecked(CStr::from_ptr(word as _).to_bytes()) })
} }
} }

View File

@ -80,12 +80,12 @@ pub enum StorageError {
impl From<StorageError> for Error { impl From<StorageError> for Error {
fn from(err: StorageError) -> Self { fn from(err: StorageError) -> Self {
match err { match err {
StorageError::InvalidData => value_error!("Invalid data for storage"), StorageError::InvalidData => value_error!(c"Invalid data for storage"),
StorageError::WriteFailed => value_error!("Storage write failed"), StorageError::WriteFailed => value_error!(c"Storage write failed"),
StorageError::ReadFailed => value_error!("Storage read failed"), StorageError::ReadFailed => value_error!(c"Storage read failed"),
StorageError::DeleteFailed => value_error!("Storage delete failed"), StorageError::DeleteFailed => value_error!(c"Storage delete failed"),
StorageError::CounterFailed => { StorageError::CounterFailed => {
value_error!("Retrieving counter value failed") value_error!(c"Retrieving counter value failed")
} }
} }
} }

View File

@ -1,6 +1,5 @@
use super::ffi; use super::ffi;
use core::cmp::Ordering; use core::{cmp::Ordering, ffi::CStr};
use cstr_core::CStr;
/// Holds all the possible words with the possibility to interact /// Holds all the possible words with the possibility to interact
/// with the "list" - filtering it further, getting their count, etc. /// with the "list" - filtering it further, getting their count, etc.
@ -102,7 +101,7 @@ unsafe fn from_utf8_unchecked<'a>(word: *const cty::c_char) -> &'a str {
// SAFETY: caller must pass a valid 0-terminated UTF-8 string. // SAFETY: caller must pass a valid 0-terminated UTF-8 string.
// This assumption holds for usage on words of the BIP-39/SLIP-39 wordlists. // This assumption holds for usage on words of the BIP-39/SLIP-39 wordlists.
unsafe { unsafe {
let word = CStr::from_ptr(word); let word = CStr::from_ptr(word as _);
core::str::from_utf8_unchecked(word.to_bytes()) core::str::from_utf8_unchecked(word.to_bytes())
} }
} }

View File

@ -208,11 +208,11 @@ impl<'i> Toif<'i> {
pub const fn new(data: &'i [u8]) -> Result<Self, Error> { pub const fn new(data: &'i [u8]) -> Result<Self, Error> {
if data.len() < TOIF_HEADER_LENGTH || data[0] != b'T' || data[1] != b'O' || data[2] != b'I' if data.len() < TOIF_HEADER_LENGTH || data[0] != b'T' || data[1] != b'O' || data[2] != b'I'
{ {
return Err(value_error!("Invalid TOIF header.")); return Err(value_error!(c"Invalid TOIF header."));
} }
let zdatalen = u32::from_le_bytes([data[8], data[9], data[10], data[11]]) as usize; let zdatalen = u32::from_le_bytes([data[8], data[9], data[10], data[11]]) as usize;
if zdatalen + TOIF_HEADER_LENGTH != data.len() { if zdatalen + TOIF_HEADER_LENGTH != data.len() {
return Err(value_error!("Invalid TOIF length.")); return Err(value_error!(c"Invalid TOIF length."));
} }
Ok(Self { Ok(Self {
data, data,

View File

@ -526,7 +526,7 @@ extern "C" fn new_confirm_homescreen(n_args: usize, args: *const Obj, kwargs: *m
)) ))
} else { } else {
if !check_homescreen_format(jpeg) { if !check_homescreen_format(jpeg) {
return Err(value_error!("Invalid image.")); return Err(value_error!(c"Invalid image."));
}; };
LayoutObj::new(SwipeUpScreen::new( LayoutObj::new(SwipeUpScreen::new(

View File

@ -602,7 +602,7 @@ extern "C" fn new_confirm_homescreen(n_args: usize, args: *const Obj, kwargs: *m
} }
if !check_homescreen_format(jpeg, false) { if !check_homescreen_format(jpeg, false) {
return Err(value_error!("Invalid image.")); return Err(value_error!(c"Invalid image."));
}; };
let buttons = Button::cancel_confirm_text(None, Some(TR::buttons__change.into())); let buttons = Button::cancel_confirm_text(None, Some(TR::buttons__change.into()));

View File

@ -9,7 +9,6 @@ use crate::{
}, },
}; };
use cstr_core::CStr;
use heapless::String; use heapless::String;
use super::display::Font; use super::display::Font;
@ -40,7 +39,7 @@ pub unsafe fn from_c_str<'a>(c_str: *const cty::c_char) -> Option<&'a str> {
return None; return None;
} }
unsafe { unsafe {
let bytes = CStr::from_ptr(c_str).to_bytes(); let bytes = core::ffi::CStr::from_ptr(c_str as _).to_bytes();
if bytes.is_ascii() { if bytes.is_ascii() {
Some(core::str::from_utf8_unchecked(bytes)) Some(core::str::from_utf8_unchecked(bytes))
} else { } else {