1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-21 05:48:23 +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",
]
[[package]]
name = "cstr_core"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd98742e4fdca832d40cab219dc2e3048de17d873248f83f17df47c1bea70956"
dependencies = [
"cty",
"memchr",
]
[[package]]
name = "cty"
version = "0.2.2"
@ -340,7 +330,6 @@ version = "0.1.0"
dependencies = [
"bindgen",
"cc",
"cstr_core",
"cty",
"easer",
"glob",

View File

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

View File

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

View File

@ -1,5 +1,4 @@
use core::{convert::Infallible, num::TryFromIntError};
use cstr_core::CStr;
use core::{convert::Infallible, ffi::CStr, num::TryFromIntError};
#[cfg(feature = "micropython")]
use {
@ -30,7 +29,7 @@ pub enum Error {
#[macro_export]
macro_rules! value_error {
($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 cstr_core::CStr;
use core::{
convert::{TryFrom, TryInto},
ffi::CStr,
};
use crate::error::Error;
@ -290,7 +291,7 @@ impl TryFrom<&'static CStr> for Obj {
// SAFETY:
// - `CStr` is guaranteed to be null-terminated UTF-8.
// - 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() {
Err(Error::AllocationFailed)
} else {

View File

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

View File

@ -1,23 +1,21 @@
use cstr_core::cstr;
use crate::{error::Error, micropython::qstr::Qstr};
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 {
value_error!("Unknown field type.")
value_error!(c"Unknown field type.")
}
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 {
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 {
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.
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)]
struct OffsetEntry {
@ -145,7 +145,7 @@ impl<'a> Translations<'a> {
let remaining = blob_reader.rest();
if !remaining.iter().all(|&b| b == EMPTY_BYTE) {
// 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();
@ -337,7 +337,7 @@ impl<'a> TranslationsHeader<'a> {
let model = read_fixedsize_str(&mut header_reader, 4)?;
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)?;

View File

@ -15,7 +15,7 @@ pub fn erase() -> Result<(), Error> {
let blob = unwrap!(TRANSLATIONS_ON_FLASH.try_write());
{
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.
@ -33,7 +33,7 @@ pub fn write(data: &[u8], offset: usize) -> Result<(), Error> {
let blob = unwrap!(TRANSLATIONS_ON_FLASH.try_write());
let result = {
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.
@ -42,7 +42,7 @@ pub fn write(data: &[u8], offset: usize) -> Result<(), Error> {
if result {
Ok(())
} 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.
pub fn deinit() -> Result<(), Error> {
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;
Ok(())
@ -116,5 +116,5 @@ pub fn deinit() -> Result<(), Error> {
pub fn get() -> Result<RwLockReadGuard<'static, Option<Translations<'static>>>, Error> {
TRANSLATIONS_ON_FLASH
.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 cstr_core::CStr;
use core::{ffi::CStr, str};
use super::ffi;
@ -26,6 +25,6 @@ pub fn button_sequence_to_word(prefix: u16) -> Option<&'static str> {
} else {
// SAFETY: On success, `button_sequence_to_word` should return a 0-terminated
// 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 {
fn from(err: StorageError) -> Self {
match err {
StorageError::InvalidData => value_error!("Invalid data for storage"),
StorageError::WriteFailed => value_error!("Storage write failed"),
StorageError::ReadFailed => value_error!("Storage read failed"),
StorageError::DeleteFailed => value_error!("Storage delete failed"),
StorageError::InvalidData => value_error!(c"Invalid data for storage"),
StorageError::WriteFailed => value_error!(c"Storage write failed"),
StorageError::ReadFailed => value_error!(c"Storage read failed"),
StorageError::DeleteFailed => value_error!(c"Storage delete failed"),
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 core::cmp::Ordering;
use cstr_core::CStr;
use core::{cmp::Ordering, ffi::CStr};
/// Holds all the possible words with the possibility to interact
/// 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.
// This assumption holds for usage on words of the BIP-39/SLIP-39 wordlists.
unsafe {
let word = CStr::from_ptr(word);
let word = CStr::from_ptr(word as _);
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> {
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;
if zdatalen + TOIF_HEADER_LENGTH != data.len() {
return Err(value_error!("Invalid TOIF length."));
return Err(value_error!(c"Invalid TOIF length."));
}
Ok(Self {
data,

View File

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

View File

@ -9,7 +9,6 @@ use crate::{
},
};
use cstr_core::CStr;
use heapless::String;
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;
}
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() {
Some(core::str::from_utf8_unchecked(bytes))
} else {