feat(rust/micropython): implement Attribute type
What changed, and why it matters
This commit is a routine internal refactoring of the Trezor firmware's Rust/MicroPython bindings. It introduces a new `Attribute` wrapper type for MicroPython string identifiers (qstrs) and reorganizes how those identifiers are converted between Rust and MicroPython. There is no indication from the commit message or diff that this fixes a security bug, changes user-visible behavior, or addresses any reported vulnerability. It appears to be a code-quality and architecture improvement.
No security action required. Review as normal code-quality/architecture change. If auditing, verify that the new `Attribute` conversions preserve the same qstr numeric values and that `#[repr(transparent)]` guarantees layout compatibility where slices are passed to C.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The change refactors qstr handling in the Rust layer of Trezor firmware. It adds an Attribute newtype over ffi::qstr, defines a QstrValue const trait, moves generated qstr bindings into a new qstr_generated module, and updates call sites (protobuf, translations, UI backlight, exception types, maps, attrtuples) to use Attribute or QstrValue instead of the previous Qstr type directly. It also enables the unstable const_trait_impl feature. The diff shows type-system changes and API cleanups, not memory-safety fixes, bounds checks, or cryptographic changes.
Changed components
core/embed/rust/src/micropython/qstr.rscore/embed/rust/src/micropython/qstr_generated.rscore/embed/rust/src/micropython/typ.rscore/embed/rust/src/micropython/util.rscore/embed/rust/src/micropython/macros.rscore/embed/rust/src/micropython/map.rscore/embed/rust/src/micropython/error.rscore/embed/rust/src/protobuf/decode.rscore/embed/rust/src/protobuf/defs.rscore/embed/rust/src/protobuf/encode.rscore/embed/rust/src/protobuf/error.rscore/embed/rust/src/protobuf/obj.rscore/embed/rust/src/translations/obj.rscore/embed/rust/src/translations/translated_string.rscore/embed/rust/src/ui/backlight.rsInspect captured patch +280 / −100
### core/embed/rust/build.rs
@@ -335,6 +335,7 @@ fn generate_qstr_bindings(lib: &mut CLibrary) -> Result<()> {
lib.add_rust_bindings_ex("qstr", |builder| {
Ok(builder
.header("qstr.h")
+ .allowlist_type("Qstr")
// Build the Qstr enum as a newtype so we can define method on it.
.default_enum_style(bindgen::EnumVariation::NewType {
is_bitfield: false,
### core/embed/rust/src/lib.rs
@@ -8,6 +8,7 @@
// Allowing dead code not to cause a lot of warnings when building for a specific target
// (when building for TR, a lot of code only used in TT would get marked as unused).
#![allow(dead_code)]
+#![feature(const_trait_impl)]
#![feature(custom_test_frameworks)]
#![no_main]
#![reexport_test_harness_main = "test_main"]
### core/embed/rust/src/micropython/error.rs
@@ -4,6 +4,7 @@ use core::num::TryFromIntError;
use super::exception::{builtin, Exception};
use super::obj::Obj;
+use super::qstr::Attribute;
#[allow(clippy::enum_variant_names)] // We mimic the Python exception classnames here.
#[derive(Debug)]
@@ -15,7 +16,7 @@ pub enum Error {
EOFError,
IndexError,
KeyError(Obj),
- AttributeError(Obj),
+ AttributeError(Attribute),
ValueError(&'static CStr),
ValueErrorParam(&'static CStr, Obj),
RuntimeError(&'static CStr),
### core/embed/rust/src/micropython/exception.rs
@@ -3,7 +3,7 @@
use super::ffi;
use super::gc::Gc;
use super::obj::Obj;
-use super::qstr::Qstr;
+use super::qstr::QstrValue;
use super::tuple::Tuple;
use super::typ::{EmptyType, Type};
@@ -44,7 +44,7 @@ unsafe impl Send for ExceptionType {}
impl ExceptionType {
/// Construct a new exception type as a child of an existing exception type.
- pub const fn new(parent: &'static ExceptionType, name: Qstr) -> Self {
+ pub const fn new(parent: &'static ExceptionType, name: impl const QstrValue) -> Self {
Self {
head: unsafe {
// SAFETY: we have four slots so maximum slot_index 4 is valid
### core/embed/rust/src/micropython/macros.rs
@@ -84,7 +84,7 @@ macro_rules! obj_fn_kw {
macro_rules! obj_map {
($($key:expr => $val:expr),*) => ({
$crate::micropython::map::Map::from_fixed_static(const {
- &[ $($crate::micropython::map::Map::at($key, $val),)* ]
+ &[ $($crate::micropython::map::Map::at($crate::micropython::qstr::Attribute::from_qstr_value($key), $val),)* ]
})
});
($($key:expr => $val:expr),* ,) => ({
@@ -124,7 +124,7 @@ macro_rules! obj_type {
) => {{
use $crate::micropython::ffi;
- let name = $name.to_u16();
+ let name = $crate::micropython::qstr::qstr_value_to_u16($name);
#[allow(unused_mut)]
#[allow(unused_assignments)]
@@ -226,15 +226,15 @@ macro_rules! obj_module {
#[allow(unused_unsafe)]
#[allow(unused_doc_comments)]
unsafe {
- use $crate::micropython::{ffi, map::Map};
+ use $crate::micropython::{ffi, map::Map, qstr::Attribute};
static DICT: ffi::mp_obj_dict_t = ffi::mp_obj_dict_t {
base: ffi::mp_obj_base_t {
/// SAFETY: Reasonable to assume the pointer stays valid.
type_: unsafe { &ffi::mp_type_dict },
},
map: Map::from_fixed_static(const {
- &[ $( Map::at($key, $val), )* ]
+ &[ $( Map::at(Attribute::from_qstr_value($key), $val), )* ]
})
};
ffi::mp_obj_module_t {
@@ -263,7 +263,7 @@ macro_rules! attr_tuple {
) => {
attr_tuple! {
@append
- fields: [$($fields,)* $field,],
+ fields: [$($fields,)* Attribute::from_qstr_value($field),],
values: [$($values,)* $val,],
rest: {$($rest)*}
}
@@ -272,9 +272,11 @@ macro_rules! attr_tuple {
fields: [$($fields:expr,)*],
values: [$($values:expr,)*],
rest: {}
- ) => {
- $crate::micropython::util::new_attrtuple(&[$($fields,)*], &[$($values,)*])
- };
+ ) => {{
+ use $crate::micropython::qstr::Attribute;
+ static ATTRIBUTES: &[Attribute] = &[$($fields,)*];
+ $crate::micropython::util::new_attrtuple(ATTRIBUTES, &[$($values,)*])
+ }};
// version without trailing comma
($($key:expr => $val:expr),*) => ({
attr_tuple!(@append fields: [], values: [], rest: { $($key => $val,)* })
### core/embed/rust/src/micropython/map.rs
@@ -6,7 +6,7 @@ use core::{ptr, slice};
use super::error::Error;
use super::ffi;
use super::obj::Obj;
-use super::qstr::Qstr;
+use super::qstr::Attribute;
use super::runtime::catch_exception;
pub type Map = ffi::mp_map_t;
@@ -33,7 +33,7 @@ impl Map {
}
}
- pub const fn at(key: Qstr, value: Obj) -> MapElem {
+ pub const fn at(key: Attribute, value: Obj) -> MapElem {
MapElem {
key: key.to_obj(),
value,
### core/embed/rust/src/micropython/mod.rs
@@ -22,6 +22,8 @@ pub mod tuple;
pub mod typ;
pub mod util;
+mod qstr_generated;
+
pub use error::Error;
pub use obj::Obj;
### core/embed/rust/src/micropython/qstr.rs
@@ -1,62 +1,168 @@
-#![allow(non_camel_case_types)]
-#![allow(non_upper_case_globals)]
-#![allow(dead_code)]
-
use core::convert::TryFrom;
use core::slice;
-use core::str::from_utf8;
-use super::error::Error;
-use super::ffi;
-use super::obj::Obj;
+use super::{ffi, Error, Obj};
-impl Qstr {
- pub const fn to_obj(self) -> Obj {
- // SAFETY:
- // - Micropython compiled with `MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A`.
- //
- // micropython/py/obj.h
- // #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 3) | 2))
- let bits = (self.0 << 3) | 2;
- unsafe { Obj::from_bits(bits) }
+/// Identifier trait for Qstr numeric ids.
+///
+/// Users of the `micropython` module must generate a full set of qstrings used
+/// throughout both MicroPython and their own codebase (via MPy's qstr
+/// collection mechanism), and then implement this trait on type(s) that
+/// represent those qstring identifiers.
+///
+/// One way to do that is use MicroPython's collection script to generate
+/// `qstrdefs.generated.h` and generate a Rust enum from those values.
+///
+/// The [`crate::micropython`] module cannot provide that enum, because its
+/// values depend on the full codebase of the caller's MicroPython project. That
+/// would introduce a circular dependency: you could not build the `micropython`
+/// module without knowing the code which calls it.
+///
+/// Instead, the user code shall implement `QstrValue` on the generated enum (or
+/// whatever other choice of type). The implementation provides two-way
+/// conversion between raw qstr id numbers, and a representation type.
+///
+/// The trait must be `const` in order to be usable when constructing static
+/// objects (module definitions, etc.)
+pub const trait QstrValue: Copy {
+ /// Convert a numeric qstr identifier to a QstrValue object.
+ fn from_u16(val: u16) -> Self;
+
+ /// Get a numeric qstr identifier from a QstrValue object.
+ fn to_u16(self) -> u16;
+
+ /// Convert a QstrValue object to an `Attribute`.
+ fn to_attribute(self) -> Attribute {
+ Attribute(self.to_u16() as _)
+ }
+}
+
+/// Extension trait for QstrValue objects.
+///
+/// Provides a `to_str` method that converts a QstrValue object to a string.
+pub trait QstrExt {
+ /// Return a string corresponding to the qstr value.
+ fn to_str(self) -> &'static str;
+}
+
+impl<T: QstrValue> QstrExt for T {
+ fn to_str(self) -> &'static str {
+ self.to_attribute().to_str()
}
+}
- pub const fn from_obj_bits(bits: cty::uintptr_t) -> Self {
- let bits = (bits >> 3) as u16; // See `Self::to_obj`.
- Self::from_u16(bits)
+/// A reusable `TryFrom<Obj>` implementation for QstrValues.
+///
+/// Place the following next to your `QstrValue` concrete type:
+///
+/// ```rust,ignore
+/// impl TryFrom<Obj> for $your_qstr_value_type {
+/// type Error = Error;
+///
+/// fn try_from(value: Obj) -> Result<Self, Self::Error> {
+/// qstr::try_from_obj(value)
+/// }
+/// }
+/// ```
+pub fn try_from_obj<T: QstrValue>(obj: Obj) -> Result<T, Error> {
+ let attr: Attribute = obj.try_into()?;
+ Ok(T::from_u16(attr.into_raw() as _))
+}
+
+impl<T: QstrValue> From<T> for Obj {
+ fn from(value: T) -> Self {
+ value.to_attribute().to_obj()
+ }
+}
+
+/// MicroPython attribute type.
+///
+/// A value type for arguments, struct fields, function returns, etc.,
+/// representing MicroPython qstrings.
+///
+/// MicroPython itself is somewhat inconsistent in this:
+///
+/// * most of the API surface relies on `Obj`s and does conversions internally
+/// * `Map` elements can have keys of an arbitrary `Obj`, but attribute lookups
+/// only work correctly if the `Obj` is a qstr
+/// * some struct members (`Type::name`) are numeric types (`u16`)
+/// * certain features (`qstr.h`, `attrtuple`) require the use of explicit
+/// `qstr` type
+///
+/// `Attribute` is a newtype wrapper over `qstr`, which is typically a typedef
+/// over `usize` (so we can't put impls directly on `qstr`). It is also
+/// `repr(transparent)`, so `&[Attribute]` is legal where `&[qstr]` is expected
+/// (such as in attrtuples).
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+#[repr(transparent)]
+pub struct Attribute(ffi::qstr);
+
+impl Attribute {
+ /// Lower an `Attribute` into the inner `qstr` value.
+ pub const fn into_raw(self) -> ffi::qstr {
+ self.0
}
- pub const fn to_u16(self) -> u16 {
- // TODO: Change the internal representation of Qstr to u16.
- self.0 as _
+ /// Construct an `Attribute` from the inner `qstr` value.
+ pub const fn from_raw(raw: ffi::qstr) -> Self {
+ Self(raw)
}
+ /// Construct an `Attribute` from a raw qstr id number.
pub const fn from_u16(val: u16) -> Self {
- // TODO: Change the internal representation of Qstr to u16.
Self(val as _)
}
- pub fn as_str(self) -> &'static str {
+ /// Return a string corresponding to the qstr id.
+ pub fn to_str(self) -> &'static str {
let mut len = 0usize;
let slice = unsafe {
// SAFETY: qstr_data should always return a valid string, even for unknown ids.
- let ptr = ffi::qstr_data(self.0 as _, &mut len as *mut _);
+ let ptr = ffi::qstr_data(self.0, &mut len as *mut _);
slice::from_raw_parts(ptr, len)
};
// SAFETY: Qstr pools are either ROM-based or permanently allocated in the GC
// arena. The MicroPython runtime holds the respective head pointers so we don't
// need to care.
- unwrap!(from_utf8(slice))
+ unwrap!(str::from_utf8(slice))
+ }
+
+ /// Convert an `Attribute` to an `Obj`.
+ pub const fn to_obj(self) -> Obj {
+ // SAFETY:
+ // Micropython compiled with `MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A`.
+ //
+ // micropython/py/obj.h
+ // ```c
+ // #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 3) | 2))
+ // ```
+ let bits = (self.0 << 3) | 2;
+ unsafe { Obj::from_bits(bits) }
+ }
+
+ /// Extract the qstr id bits from `Obj`'s bits.
+ ///
+ /// Assumes but does not check that the passed bits represent a `qstr`. If
+ /// they don't, the result is a spurious `Attribute` with unspecified,
+ /// possibly invalid id.
+ const fn from_obj_bits(bits: cty::uintptr_t) -> Self {
+ let bits = (bits >> 3) as u16; // See `Self::to_obj`.
+ Self::from_u16(bits)
+ }
+
+ /// Construct an `Attribute` from a `QstrValue` object.
+ pub const fn from_qstr_value<T: const QstrValue>(value: T) -> Self {
+ Self::from_u16(value.to_u16())
}
}
-impl From<u16> for Qstr {
- fn from(val: u16) -> Self {
- Self::from_u16(val)
+impl From<Attribute> for Obj {
+ fn from(value: Attribute) -> Self {
+ value.to_obj()
}
}
-impl TryFrom<Obj> for Qstr {
+impl TryFrom<Obj> for Attribute {
type Error = Error;
fn try_from(value: Obj) -> Result<Self, Self::Error> {
@@ -68,10 +174,18 @@ impl TryFrom<Obj> for Qstr {
}
}
-impl From<Qstr> for Obj {
- fn from(value: Qstr) -> Self {
- value.to_obj()
- }
+#[inline]
+/// Const helper to convert a `QstrValue` object to a raw qstr id number.
+///
+/// Workaround for Rust's const trait limitations: a const fn is explicitly
+/// valid to call in const contexts, where a method on an `impl QstrValue`
+/// either may not be, or may require horrible typecasting boilerplate (which
+/// itself may be legal but not supported by rustc in const contexts).
+pub const fn qstr_value_to_u16<T: const QstrValue>(value: T) -> u16 {
+ value.to_u16()
}
-include!(concat!(env!("OUT_DIR"), "/qstr.rs"));
+// XXX compatibility re-export
+// The intention here is that after the crate split,
+// `crate::micropython::qstr::Qstr` remains valid
+pub use super::qstr_generated::Qstr;
### core/embed/rust/src/micropython/qstr_generated.rs
@@ -0,0 +1,50 @@
+use super::{qstr, Obj};
+
+#[allow(non_camel_case_types)]
+#[allow(non_upper_case_globals)]
+#[allow(dead_code)]
+mod generated {
+ include!(concat!(env!("OUT_DIR"), "/qstr.rs"));
+}
+pub use generated::Qstr;
+
+// TODO: bindgen generates the Qstr type as usize, but for us it would be enough
+// to have a u16
+
+impl Qstr {
+ pub const fn to_obj(self) -> Obj {
+ <Self as qstr::QstrValue>::to_attribute(self).to_obj()
+ }
+
+ pub const fn from_u16(val: u16) -> Self {
+ Self(val as _)
+ }
+
+ pub const fn to_u16(self) -> u16 {
+ self.0
+ }
+}
+
+impl const qstr::QstrValue for Qstr {
+ fn from_u16(val: u16) -> Self {
+ Self::from_u16(val)
+ }
+
+ fn to_u16(self) -> u16 {
+ self.to_u16()
+ }
+}
+
+impl TryFrom<Obj> for Qstr {
+ type Error = super::Error;
+
+ fn try_from(value: Obj) -> Result<Self, Self::Error> {
+ qstr::try_from_obj(value)
+ }
+}
+
+impl From<qstr::Attribute> for Qstr {
+ fn from(value: qstr::Attribute) -> Self {
+ Self::from_u16(value.into_raw() as u16)
+ }
+}
### core/embed/rust/src/micropython/typ.rs
@@ -2,7 +2,7 @@ use core::ops::Deref;
use super::ffi;
use super::obj::{Obj, ObjBase};
-use super::qstr::Qstr;
+use super::qstr::{Attribute, QstrValue};
pub type Type = ffi::mp_obj_type_t;
@@ -58,7 +58,7 @@ impl EmptyType {
///
/// This is useful as a first item in a `repr(C)` struct
/// extending to a custom number of slots.
- pub const fn new(name: Qstr) -> Self {
+ pub const fn new(name: impl const QstrValue) -> Self {
Self(ffi::mp_obj_empty_type_t {
base: TYPE_BASE.as_base(),
flags: 0,
@@ -118,11 +118,8 @@ impl Type {
unsafe { Obj::from_ptr(self as *const _ as *mut _) }
}
- #[cfg(any(feature = "debug", feature = "dbg_console"))]
pub fn name(&self) -> &'static str {
- use super::qstr::Qstr;
-
- Qstr::from(self.name).as_str()
+ Attribute::from_u16(self.name).to_str()
}
}
### core/embed/rust/src/micropython/util.rs
@@ -6,7 +6,7 @@ use super::error::Error;
use super::iter::IterBuf;
use super::map::{Map, MapElem};
use super::obj::Obj;
-use super::qstr::Qstr;
+use super::qstr::{Attribute, Qstr};
use super::runtime::catch_exception;
use super::{exception, ffi};
@@ -92,7 +92,7 @@ pub unsafe fn try_with_args_and_kwargs_inline(
/// // ...
/// }
/// ```
-pub fn new_attrtuple(field_qstrs: &'static [Qstr], values: &[Obj]) -> Result<Obj, Error> {
+pub fn new_attrtuple(field_qstrs: &'static [Attribute], values: &[Obj]) -> Result<Obj, Error> {
if field_qstrs.len() != values.len() {
return Err(Error::TypeError);
}
@@ -101,8 +101,8 @@ pub fn new_attrtuple(field_qstrs: &'static [Qstr], values: &[Obj]) -> Result<Obj
// pointer in the last tuple item. Hence the requirement that `fields` is
// 'static. See objattrtuple.c:79
// * we cast `field_qstrs` to the required type `qstr`, which is internally
- // usize. (py/qstr.h:48). This is valid for as long as Qstr is
- // repr(transparent) and the only field is a usize. Check generated qstr.rs.
+ // usize. (py/qstr.h:48). This is valid for as long as Attribute is
+ // repr(transparent) over the ffi::qstr type.
// EXCEPTION: Raises if allocation fails, does not return NULL.
catch_exception!(unsafe { ffi::mp_obj_new_attrtuple } => { field_qstrs.as_ptr() as *const _, values.len(), values.as_ptr() })
}
### core/embed/rust/src/protobuf/decode.rs
@@ -111,11 +111,11 @@ impl Decoder {
match msg.field(field_tag) {
Some(field) if field.get_type().primitive_type() != prim_type => {
- return Err(error::invalid_value(field.name.into()));
+ return Err(error::invalid_value(field.name()));
}
Some(field) => {
let field_value = self.decode_field(stream, field, depth)?;
- let field_name = Qstr::from(field.name);
+ let field_name = Qstr::from(field.name());
if field.is_repeated() {
// Repeated field, values are stored in a list. First, look up the list
// object. If it exists, append to it. If it doesn't, create a new list with
@@ -171,7 +171,7 @@ impl Decoder {
let field = msg
.field(field_tag)
.ok_or_else(|| Error::KeyError(field_tag.into()))?;
- let field_name = Qstr::from(field.name);
+ let field_name = Qstr::from(field.name());
if map.contains_key(field_name) {
// Field already has a value assigned, skip it.
match field.get_type().primitive_type() {
@@ -200,14 +200,14 @@ impl Decoder {
/// assigned and all optional missing fields are set to `None`.
fn assign_required_into(&self, msg: &MsgDef, map: &mut Map) -> Result<(), Error> {
for field in msg.fields {
- let field_name = Qstr::from(field.name);
+ let field_name = Qstr::from(field.name());
if map.contains_key(field_name) {
// Field is assigned, skip.
continue;
}
if field.is_required() {
// Required field is missing, abort.
- return Err(error::missing_required_field(field_name));
+ return Err(error::missing_required_field(field.name()));
}
if field.is_repeated() {
// Optional repeated field, set to a new empty list.
@@ -250,15 +250,15 @@ impl Decoder {
let buf_len = num.try_into()?;
let buf = stream.read(buf_len)?;
let unicode =
- str::from_utf8(buf).map_err(|_| error::invalid_value(field.name.into()))?;
+ str::from_utf8(buf).map_err(|_| error::invalid_value(field.name()))?;
unicode.try_into()
}
FieldType::Enum(enum_type) => {
let enum_val = num.try_into()?;
if enum_type.values.contains(&enum_val) {
Ok(enum_val.into())
} else {
- Err(error::invalid_value(field.name.into()))
+ Err(error::invalid_value(field.name()))
}
}
FieldType::Msg(msg_type) => {
### core/embed/rust/src/protobuf/defs.rs
@@ -1,6 +1,7 @@
use core::mem;
use crate::align::include_aligned;
+use crate::micropython::qstr::Attribute;
macro_rules! proto_def_path {
($filename:expr) => {
@@ -40,7 +41,7 @@ pub struct FieldDef {
pub tag: u8,
flags_and_type: u8,
enum_or_msg_offset: u16,
- pub name: u16,
+ name: u16,
}
const STATIC_ASSERT_FIELD_DEF_ALIGNMENT: () = {
@@ -70,25 +71,29 @@ impl FieldDef {
}
}
- pub fn is_required(&self) -> bool {
+ pub const fn is_required(&self) -> bool {
self.flags() & 0b_1000_0000 != 0
}
- pub fn is_repeated(&self) -> bool {
+ pub const fn is_repeated(&self) -> bool {
self.flags() & 0b_0100_0000 != 0
}
- pub fn is_experimental(&self) -> bool {
+ pub const fn is_experimental(&self) -> bool {
self.flags() & 0b_0010_0000 != 0
}
- fn flags(&self) -> u8 {
+ const fn flags(&self) -> u8 {
self.flags_and_type & 0xF0
}
- fn ftype(&self) -> u8 {
+ const fn ftype(&self) -> u8 {
self.flags_and_type & 0x0F
}
+
+ pub const fn name(&self) -> Attribute {
+ Attribute::from_u16(self.name)
+ }
}
pub enum FieldType {
### core/embed/rust/src/protobuf/encode.rs
@@ -6,7 +6,6 @@ use super::zigzag;
use crate::micropython::gc::Gc;
use crate::micropython::iter::IterBuf;
use crate::micropython::list::List;
-use crate::micropython::qstr::Qstr;
use crate::micropython::{buffer, util, Error, Obj};
pub extern "C" fn protobuf_len(obj: Obj) -> Obj {
@@ -48,10 +47,8 @@ impl Encoder {
obj: &MsgObj,
) -> Result<(), Error> {
for field in msg.fields {
- let field_name = Qstr::from(field.name);
-
// Lookup the field by name. If not set or None, skip.
- let field_value = match obj.map().get(field_name) {
+ let field_value = match obj.map().get(field.name()) {
Ok(value) => value,
Err(_) => continue,
};
### core/embed/rust/src/protobuf/error.rs
@@ -1,5 +1,5 @@
use crate::micropython::error::Error;
-use crate::micropython::qstr::Qstr;
+use crate::micropython::qstr::Attribute;
pub const fn experimental_not_enabled() -> Error {
Error::ValueError(c"Experimental features are disabled.")
@@ -9,10 +9,10 @@ pub const fn unknown_field_type() -> Error {
Error::ValueError(c"Unknown field type.")
}
-pub const fn missing_required_field(field: Qstr) -> Error {
+pub const fn missing_required_field(field: Attribute) -> Error {
Error::ValueErrorParam(c"Missing required field.", field.to_obj())
}
-pub const fn invalid_value(field: Qstr) -> Error {
+pub const fn invalid_value(field: Attribute) -> Error {
Error::ValueErrorParam(c"Invalid value for field.", field.to_obj())
}
### core/embed/rust/src/protobuf/obj.rs
@@ -9,7 +9,7 @@ use crate::micropython::macros::{obj_fn_1, obj_fn_2, obj_fn_3, obj_module, obj_t
use crate::micropython::map::Map;
use crate::micropython::module::Module;
use crate::micropython::obj::{Obj, ObjBase};
-use crate::micropython::qstr::Qstr;
+use crate::micropython::qstr::{Attribute, Qstr};
use crate::micropython::typ::{FullType, Type};
use crate::micropython::{ffi, util, Error};
@@ -53,14 +53,14 @@ impl MsgObj {
}
impl MsgObj {
- fn getattr(&self, attr: Qstr) -> Result<Obj, Error> {
+ fn getattr(&self, attr: Attribute) -> Result<Obj, Error> {
if let Ok(obj) = self.map.get(attr) {
// Message field was found, return its value.
return Ok(obj);
}
// Built-in attribute.
- match attr {
+ match attr.into() {
Qstr::MP_QSTR_MESSAGE_WIRE_TYPE => {
// Return the wire ID of this message def, or None if not set.
Ok(self.msg_wire_id.map_or_else(Obj::const_none, Into::into))
@@ -79,11 +79,11 @@ impl MsgObj {
// we're returning a mutable dict.
Ok(Gc::new(Dict::with_map(self.map.try_clone()?))?.into())
}
- _ => Err(Error::AttributeError(attr.into())),
+ _ => Err(Error::AttributeError(attr)),
}
}
- fn setattr(&mut self, attr: Qstr, value: Obj) -> Result<(), Error> {
+ fn setattr(&mut self, attr: Attribute, value: Obj) -> Result<(), Error> {
if value.is_null() {
// Null value means a delattr operation, reject.
return Err(Error::TypeError);
@@ -93,7 +93,7 @@ impl MsgObj {
self.map.set(attr, value)?;
Ok(())
} else {
- Err(Error::AttributeError(attr.into()))
+ Err(Error::AttributeError(attr))
}
}
}
@@ -126,7 +126,7 @@ impl TryFrom<Obj> for Gc<MsgObj> {
unsafe extern "C" fn msg_obj_attr(self_in: Obj, attr: ffi::qstr, dest: *mut Obj) {
let block = || {
let mut this = Gc::<MsgObj>::try_from(self_in)?;
- let attr = Qstr::from_u16(attr as _);
+ let attr = Attribute::from_raw(attr);
unsafe {
if dest.read().is_null() {
@@ -201,15 +201,15 @@ impl TryFrom<Obj> for Gc<MsgDefObj> {
unsafe extern "C" fn msg_def_obj_attr(self_in: Obj, attr: ffi::qstr, dest: *mut Obj) {
let block = || {
let this = Gc::<MsgDefObj>::try_from(self_in)?;
- let attr = Qstr::from_u16(attr as _);
+ let attr = Attribute::from_raw(attr);
let arg = unsafe { dest.read() };
if !arg.is_null() {
// Null destination would mean a `setattr`.
return Err(Error::TypeError);
}
- match attr {
+ match attr.into() {
Qstr::MP_QSTR_MESSAGE_NAME => {
// Return the QSTR name of this message def.
let name = Qstr::from_u16(unwrap!(find_name_by_msg_offset(this.def.offset)));
@@ -234,7 +234,7 @@ unsafe extern "C" fn msg_def_obj_attr(self_in: Obj, attr: ffi::qstr, dest: *mut
}
}
_ => {
- return Err(Error::AttributeError(attr.into()));
+ return Err(Error::AttributeError(attr));
}
}
Ok(())
### core/embed/rust/src/translations/obj.rs
@@ -10,7 +10,7 @@ use crate::micropython::macros::{
use crate::micropython::map::Map;
use crate::micropython::module::Module;
use crate::micropython::obj::Obj;
-use crate::micropython::qstr::Qstr;
+use crate::micropython::qstr::{Attribute, Qstr};
use crate::micropython::simple_type::SimpleTypeObj;
use crate::micropython::typ::FullType;
use crate::micropython::{ffi, util};
@@ -32,13 +32,13 @@ unsafe extern "C" fn tr_attr_fn(_self_in: Obj, attr: ffi::qstr, dest: *mut Obj)
// Null destination would mean a `setattr`.
return Err(Error::TypeError);
}
- let attr = Qstr::from_u16(attr as u16);
- let result = if let Some(translation) = TranslatedString::from_qstr(attr) {
+ let attr = Attribute::from_raw(attr);
+ let result = if let Some(translation) = TranslatedString::from_attribute(attr) {
translation.map_translated(|t| t.try_into())?
// TODO fall back to English (which is static and can be converted
// infallibly) if the allocation fails?
} else {
- return Err(Error::AttributeError(attr.into()));
+ return Err(Error::AttributeError(attr));
};
unsafe { dest.write(result) };
Ok(())
### core/embed/rust/src/translations/translated_string.rs
@@ -1,7 +1,7 @@
use super::blob::{Translations, ENGLISH_CHUNK};
pub use super::generated::translated_string::TranslatedString;
#[cfg(feature = "micropython")]
-use crate::micropython::qstr::Qstr;
+use crate::micropython::qstr::{Attribute, Qstr};
use crate::strutil::TString;
impl TranslatedString {
@@ -16,14 +16,24 @@ impl TranslatedString {
}
#[cfg(feature = "micropython")]
- pub(super) fn from_qstr(qstr: Qstr) -> Option<Self> {
+ fn from_u16_id(id: u16) -> Option<Self> {
// QSTR_MAP must be sorted by its first element
- match Self::QSTR_MAP.binary_search_by(|(key, _)| key.to_u16().cmp(&qstr.to_u16())) {
+ match Self::QSTR_MAP.binary_search_by(|(key, _)| key.to_u16().cmp(&id)) {
Ok(index) => Some(Self::QSTR_MAP[index].1),
Err(_) => None,
}
}
+ #[cfg(feature = "micropython")]
+ pub(super) fn from_qstr(qstr: Qstr) -> Option<Self> {
+ Self::from_u16_id(qstr.to_u16())
+ }
+
+ #[cfg(feature = "micropython")]
+ pub(super) fn from_attribute(attribute: Attribute) -> Option<Self> {
+ Self::from_u16_id(attribute.into_raw() as _)
+ }
+
/// Maps the translated string to a value using a closure.
///
/// # Safety
### core/embed/rust/src/ui/backlight.rs
@@ -1,5 +1,5 @@
use crate::micropython::macros::obj_type;
-use crate::micropython::qstr::Qstr;
+use crate::micropython::qstr::{Attribute, Qstr};
use crate::micropython::simple_type::SimpleTypeObj;
use crate::micropython::typ::FullType;
use crate::micropython::{ffi, util, Error, Obj};
@@ -26,14 +26,14 @@ unsafe extern "C" fn backlight_levels_attr(_self_in: Obj, attr: ffi::qstr, dest:
// Null destination would mean a `setattr`.
return Err(Error::TypeError);
}
- let attr = Qstr::from_u16(attr as _);
- let value = match attr {
+ let attr = Attribute::from_raw(attr);
+ let value = match attr.into() {
Qstr::MP_QSTR_NONE => ModelUI::get_backlight_none(),
Qstr::MP_QSTR_NORMAL => ModelUI::get_backlight_normal(),
Qstr::MP_QSTR_LOW => ModelUI::get_backlight_low(),
Qstr::MP_QSTR_DIM => ModelUI::get_backlight_dim(),
Qstr::MP_QSTR_MAX => ModelUI::get_backlight_max(),
- _ => return Err(Error::AttributeError(attr.into())),
+ _ => return Err(Error::AttributeError(attr)),
};
unsafe { dest.write(value.into()) };
Ok(())Why this scored 12/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.