refactor(core/rtl): add rust bindings for ts_t
What changed, and why it matters
This commit is a code cleanup that adds Rust-language bindings for an existing internal error/status type used inside the Trezor firmware. It does not change how user funds or secrets are handled. The main observable effect is that Rust code can now check and report low-level device errors more cleanly, and one screen callback now handles errors more carefully instead of crashing. There is no direct security fix here, but it improves future error-handling hygiene.
Treat as routine refactoring with minor defensive hardening. No urgent action required. Reviewers may want to verify that the new `Error::from_i32` fallback to `EINVAL` for unknown codes does not mask novel error conditions, and that `ts_string` returns a valid static C string for every enum value.
Security signals we found
Adds structured error propagation for low-level status codes (ts_t) into Rust
Replaces silent/ignored FFI return values with explicit `is_ok()` checks in haptic driver
Replaces `unwrap()` panics in a UI callback with `unwrap!` macro that raises a MicroPython exception instead of crashing
Adds `OSError` exception variant backed by `RtlError`, enabling safer reporting of RTL errors to Python
No changelog entry; commit is framed as refactor, not a security fix
Evidence from the diff
The patch refactors the ts_t status-code type so it is exposed to Rust via bindgen. It introduces an rtl::error::Error enum mapped to the C error constants, adds TStatus::ok()/map_err() helpers, blocks ts_t from the trezorhal bindings to avoid duplicate definitions, and wires OSError into the MicroPython exception machinery. A few call sites (haptic.rs, firmware_micropython.rs) are updated to check results instead of ignoring them or unwrapping blindly. The THP logging change merely removes a debug-format error from a log line. The commit is tagged [no changelog] and contains no explicit security claim.
Changed components
core/embed/rtl (Rust runtime library bindings)core/embed/rust/trezorhal FFI bindingscore/embed/rust/micropython error/exception handlingcore/embed/rust/trezorhal/haptic drivercore/embed/rust/ui/api/firmware_micropython UI callbackcore/embed/rust/thp pairing loggingInspect captured patch +154 / −28
### core/embed/Cargo.lock
@@ -719,6 +719,9 @@ dependencies = [
"cty",
"hex",
"models",
+ "num-derive",
+ "num-traits",
+ "ufmt",
"xbuild",
]
### core/embed/rtl/Cargo.toml
@@ -13,6 +13,9 @@ xbuild.workspace = true
[dependencies]
cty.workspace = true
models.workspace = true
+num-derive.workspace = true
+num-traits.workspace = true
+ufmt.workspace = true
[features]
### core/embed/rtl/build.rs
@@ -58,6 +58,11 @@ fn add_rust_bindings(builder: bindgen::Builder) -> Result<bindgen::Builder> {
.header("inc/rtl/sysexit.h")
.allowlist_function("system_exit")
.allowlist_function("system_exit_error_ex")
- .allowlist_function("system_exit_fatal_ex");
+ .allowlist_function("system_exit_fatal_ex")
+ .header("inc/rtl/error_handling.h")
+ .allowlist_type("ts_t")
+ .must_use_type("ts_t")
+ .prepend_enum_name(false)
+ .allowlist_function("ts_string");
Ok(builder)
}
### core/embed/rtl/error_handling.c
@@ -59,6 +59,8 @@ const char *ts_string(ts_t status) {
return "ENOINIT";
} else if (ts_eq(status, TS_ENOEN)) {
return "ENOEN";
+ } else if (ts_eq(status, TS_ENOSTATE)) {
+ return "ENOSTATE";
} else {
return "?ERROR";
}
### core/embed/rtl/inc/rtl/error_handling.h
@@ -20,6 +20,7 @@
#pragma once
#include <errno.h>
+#include <stdint.h>
#include "sysexit.h"
@@ -28,31 +29,50 @@
#define __FILE_NAME__ __FILE__
#endif
+// Error codes (do not use directly, use the TS_* macros instead)
+typedef enum : int32_t {
+ TS_CODE_OK = 0,
+ TS_CODE_EINVAL = EINVAL,
+ TS_CODE_ENOMEM = ENOMEM,
+ TS_CODE_ENOENT = ENOENT,
+ TS_CODE_EBUSY = EBUSY,
+ TS_CODE_ETIMEDOUT = ETIMEDOUT,
+ TS_CODE_EIO = EIO,
+ TS_CODE_EBADMSG = EBADMSG,
+ TS_CODE_EACCES = EACCES,
+ TS_CODE_EEXIST = EEXIST,
+
+ // Trezor-specific error codes
+ TS_CODE_ENOINIT = 2000,
+ TS_CODE_ENOEN = 2001,
+ TS_CODE_ENOSTATE = 2002,
+
+} ts_error_code_t;
+
/** Status code type */
typedef struct {
// Do not access this field directly,
// use `ts_ok()` and `ts_error()` macros.
- int code;
+ ts_error_code_t code;
} ts_t;
/** OK status code (signalling success or no error) */
#define TS_OK ts_make(0)
-#define TS_EINVAL ts_make(EINVAL)
-#define TS_ENOMEM ts_make(ENOMEM)
-#define TS_ENOENT ts_make(ENOENT)
-#define TS_EBUSY ts_make(EBUSY)
-#define TS_ETIMEDOUT ts_make(ETIMEDOUT)
-#define TS_EIO ts_make(EIO)
-#define TS_EBADMSG ts_make(EBADMSG)
-#define TS_EACCES ts_make(EACCES)
-#define TS_EEXIST ts_make(EEXIST)
-
-/** List of Trezor-specific error codes with offset from 2000 to avoid mixing
- * with standard errno codes */
-#define TS_ENOINIT ts_make(2000) /* Not initialized */
-#define TS_ENOEN ts_make(2001) /* Not enabled */
-#define TS_ENOSTATE ts_make(2002) /* Wrong state */
+#define TS_EINVAL ts_make(TS_CODE_EINVAL)
+#define TS_ENOMEM ts_make(TS_CODE_ENOMEM)
+#define TS_ENOENT ts_make(TS_CODE_ENOENT)
+#define TS_EBUSY ts_make(TS_CODE_EBUSY)
+#define TS_ETIMEDOUT ts_make(TS_CODE_ETIMEDOUT)
+#define TS_EIO ts_make(TS_CODE_EIO)
+#define TS_EBADMSG ts_make(TS_CODE_EBADMSG)
+#define TS_EACCES ts_make(TS_CODE_EACCES)
+#define TS_EEXIST ts_make(TS_CODE_EEXIST)
+
+// Trezor-specific error codes
+#define TS_ENOINIT ts_make(TS_CODE_ENOINIT) /* Not initialized */
+#define TS_ENOEN ts_make(TS_CODE_ENOEN) /* Not enabled */
+#define TS_ENOSTATE ts_make(TS_CODE_ENOSTATE) /* Wrong state */
/**
* Extracts the code integer value from status structure.
### core/embed/rtl/src/error.rs
@@ -1,3 +1,82 @@
+use core::ffi::CStr;
+
+pub use ffi::ts_t;
+use num_derive::FromPrimitive;
+use num_traits::FromPrimitive;
+
+use super::ffi;
+
+pub type TStatus = ts_t;
+
+impl TStatus {
+ const fn code(&self) -> i32 {
+ self.code
+ }
+
+ pub const fn is_ok(&self) -> bool {
+ self.code() == ffi::TS_CODE_OK
+ }
+
+ pub fn ok(&self) -> Result<(), Error> {
+ if self.is_ok() {
+ return Ok(());
+ }
+ match Error::from_i32(self.code()) {
+ Some(e) => Err(e),
+ None => Err(Error::EINVAL),
+ }
+ }
+
+ pub fn map_err<E>(&self, func: impl FnOnce(Error) -> E) -> Result<(), E> {
+ self.ok().map_err(func)
+ }
+
+ pub const fn from_error(e: Error) -> Self {
+ Self { code: e as i32 }
+ }
+}
+
+// Must be kept in sync with the values in error_handling.h.
+#[derive(Copy, Clone, FromPrimitive, ufmt::derive::uDebug)]
+#[repr(i32)]
+pub enum Error {
+ // Standard errno
+ EINVAL = ffi::TS_CODE_EINVAL,
+ ENOMEM = ffi::TS_CODE_ENOMEM,
+ ENOENT = ffi::TS_CODE_ENOENT,
+ EBUSY = ffi::TS_CODE_EBUSY,
+ ETIMEDOUT = ffi::TS_CODE_ETIMEDOUT,
+ EIO = ffi::TS_CODE_EIO,
+ EBADMSG = ffi::TS_CODE_EBADMSG,
+ EACCES = ffi::TS_CODE_EACCES,
+ EEXIST = ffi::TS_CODE_EEXIST,
+ // Trezor-specific
+ ENOINIT = ffi::TS_CODE_ENOINIT,
+ ENOEN = ffi::TS_CODE_ENOEN,
+ ENOSTATE = ffi::TS_CODE_ENOSTATE,
+}
+
+impl Error {
+ pub fn to_str(self) -> &'static str {
+ let ts = TStatus::from_error(self);
+ // SAFETY: ffi
+ let cstr = unsafe { CStr::from_ptr(ffi::ts_string(ts)) };
+ cstr.to_str().unwrap_or("?ERROR")
+ }
+}
+
+impl From<Error> for i32 {
+ fn from(e: Error) -> Self {
+ e as i32
+ }
+}
+
+impl core::fmt::Debug for Error {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.write_str(self.to_str())
+ }
+}
+
pub trait UnwrapOrFatalError<T> {
fn unwrap_or_fatal_error(self, msg: &str, file: &str, line: u32) -> T;
}
### core/embed/rtl/src/ffi.rs
@@ -1 +1,4 @@
+#![allow(non_camel_case_types)]
+#![allow(non_upper_case_globals)]
+
include!(concat!(env!("OUT_DIR"), "/rtl.rs"));
### core/embed/rust/build.rs
@@ -160,6 +160,8 @@ fn generate_trezorhal_bindings(lib: &mut CLibrary) -> Result<()> {
lib.add_rust_bindings_ex("trezorhal", |builder| {
Ok(builder
.header("trezorhal.h")
+ // needs to be imported from rtl::error instead
+ .blocklist_type("ts_t")
// model
.allowlist_var("MODEL_INTERNAL_NAME")
.allowlist_var("MODEL_FULL_NAME")
### core/embed/rust/src/micropython/error.rs
@@ -2,12 +2,14 @@ use core::convert::{Infallible, TryInto};
use core::ffi::CStr;
use core::num::TryFromIntError;
+use rtl::error::Error as RtlError;
+
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)]
+#[cfg_attr(test, derive(Debug))]
pub enum Error {
TypeError,
OutOfRange,
@@ -21,6 +23,7 @@ pub enum Error {
ValueErrorParam(&'static CStr, Obj),
RuntimeError(&'static CStr),
NotImplementedError,
+ OSError(RtlError),
Exception(Exception),
}
@@ -46,6 +49,7 @@ impl Error {
Error::EOFError => Exception::new(builtin::EOFError, &[]),
Error::RuntimeError(msg) => Exception::new_with_arg(builtin::RuntimeError, msg),
Error::NotImplementedError => Exception::new(builtin::NotImplementedError, &[]),
+ Error::OSError(e) => Exception::new_with_arg(builtin::OSError, e.to_str()),
Error::Exception(exception) => exception,
}
}
### core/embed/rust/src/micropython/exception.rs
@@ -111,6 +111,7 @@ pub mod builtin {
wrap_builtin!(MemoryError, mp_type_MemoryError);
wrap_builtin!(NotImplementedError, mp_type_NotImplementedError);
wrap_builtin!(OverflowError, mp_type_OverflowError);
+ wrap_builtin!(OSError, mp_type_OSError);
wrap_builtin!(RuntimeError, mp_type_RuntimeError);
wrap_builtin!(TypeError, mp_type_TypeError);
wrap_builtin!(ValueError, mp_type_ValueError);
### core/embed/rust/src/thp/mod.rs
@@ -840,12 +840,8 @@ impl CredentialVerifier for TrezorCredentialVerifier {
log::debug!("[{:04x}] Result: {}", self.channel_id, ps as u8);
ps
}
- Err(e) => {
- log::error!(
- "[{:04x}] Credential verification error: {:?}",
- self.channel_id,
- e
- );
+ Err(_) => {
+ log::error!("[{:04x}] Credential verification error", self.channel_id);
PairingState::Unpaired
}
}
### core/embed/rust/src/trezorhal/ffi.rs
@@ -7,5 +7,8 @@
#![allow(clippy::transmute_int_to_bool)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::cast_lossless)]
+#![allow(unused_imports)]
+
+use rtl::error::ts_t;
include!(concat!(env!("OUT_DIR"), "/trezorhal.rs"));
### core/embed/rust/src/trezorhal/haptic.rs
@@ -9,12 +9,16 @@ pub enum HapticEffect {
pub fn play(effect: HapticEffect) {
unsafe {
- ffi::haptic_play(effect as _);
+ if !ffi::haptic_play(effect as _).is_ok() {
+ log::error!("haptic_play failed");
+ }
}
}
pub fn play_custom(amplitude_pct: i8, duration_ms: u16) {
unsafe {
- ffi::haptic_play_custom(amplitude_pct, duration_ms);
+ if !ffi::haptic_play_custom(amplitude_pct, duration_ms).is_ok() {
+ log::error!("haptic_play_custom failed");
+ }
}
}
### core/embed/rust/src/ui/api/firmware_micropython.rs
@@ -665,8 +665,9 @@ extern "C" fn new_request_number(n_args: usize, args: *const Obj, kwargs: *mut M
let more_info_cb = more_info_callback.map(|callback| {
move |n: u32| {
- let text = callback.call_with_n_args(&[n.try_into().unwrap()]).unwrap();
- TString::try_from(text).unwrap()
+ let n = unwrap!(Obj::try_from(n));
+ let text = unwrap!(callback.call_with_n_args(&[n]));
+ unwrap!(TString::try_from(text))
}
});
Why this scored 17/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.