repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/macros/alloc.rs
src/macros/alloc.rs
#![macro_use] /// Defines the default heap size of the current project /// /// Must only be called once in a project /// /// # Arguments /// /// * `size`: The size passed to the user-configurable heap-initialization function. /// /// # Examples /// /// ``` /// alloc_set_default_heap_size!(0x13F00); /// ``` #[macro_export] macro_rules! alloc_set_default_heap_size { ($val:expr) => { #[unsafe(no_mangle)] #[used] #[unsafe(export_name = "__nx_mem_alloc_default_heap_size")] pub static DEFAULT_HEAP_SIZE: usize = $val; }; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/macros/result.rs
src/macros/result.rs
#![macro_use] /// Creates a result definition /// /// # Examples /// /// ``` /// // Defines "ResultDemo" result definition /// result_define!(Demo: 345, 6789); /// /// // Creates a "ResultCode" of value "2345-6789" /// let rc = ResultDemo::make(); /// ``` #[macro_export] macro_rules! result_define { ( $(#[$meta:meta])* $name:ident: $module:expr, $description:expr ) => { paste::paste! { #[allow(missing_docs)] $(#[$meta])* pub struct [<Result $name>]; impl $crate::result::ResultBase for [<Result $name>] { fn get_module() -> u32 { $module } fn get_description() -> u32 { $description } } } }; } /// Creates a group of result definitions (all under the same module) /// /// # Examples /// /// ``` /// // Defines "ResultDemo1" and "ResultDemo2" /// result_define_group!(345 => { /// Demo1: 12, /// Demo2: 15 /// }); /// /// // Creates a "ResultCode" of value "2345-0012" /// let rc1 = ResultDemo1::make(); /// // Creates a "ResultCode" of value "2345-0015" /// let rc2 = ResultDemo2::make(); /// ``` #[macro_export] macro_rules! result_define_group { ($module:expr => { $( $name:ident: $description:expr ),* }) => { $( $crate::result_define!($name: $module, $description); )* }; } /// Creates a group of result definitions (all under the same module and submodule) /// /// # Examples /// /// ``` /// // Defines "ResultDemo1" and "ResultDemo2" /// result_define_subgroup!(345, 6000 => { /// Demo1: 12, /// Demo2: 15 /// }); /// /// // Creates a "ResultCode" of value "2345-6012" /// let rc1 = ResultDemo1::make(); /// // Creates a "ResultCode" of value "2345-6015" /// let rc2 = ResultDemo2::make(); /// ``` #[macro_export] macro_rules! result_define_subgroup { ( $module:expr, $submodule:expr => { $( $name:ident: $description:expr ),* } ) => { $crate::result_define_group!($module => { $( $name: $submodule + $description ),* }); }; } /// Returns a given result if the given condition is true /// /// # Examples /// /// ``` /// fn demo() -> Result<()> { /// let cond: bool = (...); /// /// // Specifying result definition types /// result_return_if!(cond, ResultTest); /// /// // Giving raw values /// result_return_if!(cond, 0xBABE); /// /// Ok(()) /// } /// ``` #[macro_export] macro_rules! result_return_if { ($cond_expr:expr, $res:ty) => { let cond = $cond_expr; if cond { return <$res>::make_err(); } }; ($cond_expr:expr, $res:literal) => { let cond = $cond_expr; if cond { return $crate::result::ResultCode::new_err($res); } }; } /// Returns a given result unless the given condition is true /// /// # Examples /// /// ``` /// fn demo() -> Result<()> { /// let cond: bool = (...); /// /// // Specifying result definition types /// result_return_unless!(cond, ResultTest); /// /// // Giving raw values /// result_return_unless!(cond, 0xBABE); /// /// Ok(()) /// } /// ``` #[macro_export] macro_rules! result_return_unless { ($cond_expr:expr, $res:ty) => { $crate::result_return_if!(!$cond_expr, $res); }; ($cond_expr:expr, $res:literal) => { $crate::result_return_if!(!$cond_expr, $res); }; } /// Wraps and returns a given result if it's not successful /// /// # Examples /// /// ``` /// fn demo() -> Result<()> { /// // Won't do anything /// result_try!(ResultCode::new(0)); /// result_try!(ResultSuccess::make()); /// /// // Will exit with the given results /// result_try!(ResultCode::new(0xCAFE)); /// result_try!(ResultDemo::make()); /// /// Ok(()) /// } /// ``` #[macro_export] macro_rules! result_try { ($rc_expr:expr) => { let rc = $rc_expr; if rc.is_failure() { return Err(rc); } }; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/macros/util.rs
src/macros/util.rs
#![macro_use] /// Aligns a value up based on the provided alignment which should be a power of two. /// /// # Arguments /// /// * `val`: Expression that should resolve to an unsigned primitive integer type /// * `alignement`: Alignement value, that should resolve to the same type as `val` /// /// # Examples /// /// ``` /// let new_buffer_with_aligned_size = nx::mem::alloc::Buffer::new(size_of::<u128>(), max_object_count); /// ``` #[macro_export] macro_rules! align_up { ($val:expr, $alignment:expr ) => {{ debug_assert!( ($alignment).is_power_of_two(), "Alignment value must be a power of two" ); let align_mask = ($alignment) - 1; (($val) + align_mask) & !align_mask }}; } /// Checks if the provided value is aligned to the provided alignment /// /// # Arguments /// /// * `val`: Expression that should resolve to an unsigned primitive integer type /// * `alignment`: Alignement value, that should resolve to the same type as `val` /// /// # Examples /// /// ``` /// debug_assert!(is_aligned!(buffer.ptr, align_of::<T>())); /// ``` #[macro_export] macro_rules! is_aligned { ($val:expr, $alignment:expr ) => {{ debug_assert!( ($alignment).is_power_of_two(), "Alignment value must be a power of two" ); let align_mask = ($alignment) - 1; ($val) & align_mask == 0 }}; } /// Gets a value corresponding to the given bit /// /// # Arguments /// /// * `val`: Bit index /// /// # Examples /// /// ``` /// assert_eq!(bit!(0), 0b1); /// assert_eq!(bit!(1), 0b10); /// assert_eq!(bit!(5), 0b100000); /// ``` #[macro_export] macro_rules! bit { ($val:expr) => { (1 << $val) }; } /// Defines a type meant to serve as a bitflag set with enum-like API /// /// # Examples /// /// ``` /// define_bit_set! { /// Test (u32) { /// A = bit!(1), /// B = bit!(2) /// } /// } /// ``` #[macro_export] macro_rules! define_bit_set { ( $(#[$a_meta:meta])* $name:ident ($base:ty) { $( $(#[$b_meta:meta])* $entry_name:ident = $entry_value:expr ),* } ) => { $(#[$a_meta])* #[derive($crate::ipc::sf::Request, $crate::ipc::sf::Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct $name($base); #[allow(non_snake_case)] impl $name { #[doc = concat!("Creates a `", stringify!($name), "` from the underlying base type `", stringify!($base), "`")] pub const fn from(val: $base) -> Self { Self(val) } #[doc = concat!("Checks if the provided `", stringify!($name), "` has all of the set bits in `other` are set in `self`")] pub const fn contains(self, other: Self) -> bool { (self.0 & other.0) == other.0 } #[doc = concat!("Checks if the provided ", stringify!($name), " has any common bits with `other`")] pub const fn intersects(self, other: Self) -> bool { (self.0 & other.0) != 0 } /// Returns the value as the underlying type pub const fn get(self) -> $base { self.0 } $( #[doc = concat!("Returns a `", stringify!($name), "` where only the bit for `", stringify!($entry_name), "` is set")] $(#[$b_meta])* pub const fn $entry_name() -> Self { Self($entry_value) } )* } impl core::ops::BitOr for $name { type Output = Self; #[inline] fn bitor(self, other: Self) -> Self { Self(self.0 | other.0) } } impl core::ops::BitAnd for $name { type Output = Self; #[inline] fn bitand(self, other: Self) -> Self { Self(self.0 & other.0) } } impl core::ops::BitOrAssign for $name { #[inline] fn bitor_assign(&mut self, other: Self) { self.0 |= other.0 } } impl core::ops::BitAndAssign for $name { #[inline] fn bitand_assign(&mut self, other: Self) { self.0 &= other.0 } } impl core::ops::Not for $name { type Output = Self; #[inline] fn not(self) -> Self { Self(!self.0) } } }; } /// Constructs a `define_bit_set` type value from various flags /// /// # Examples /// /// ``` /// define_bit_set! { /// Test (u32) { /// A = bit!(1), /// B = bit!(2) /// } /// } /// /// // The equivalent to what would be "A | B" /// let test_ab = bit_group! { Test [A, B] }; /// ``` #[macro_export] macro_rules! bit_group { ($base:ty [ $( $val:ident ),* ]) => { <$base>::from( $( <$base>::$val().get() )|* ) }; } /// Writes bits into a given value /// /// # Arguments /// /// * `start`: The start bit index (inclusive) /// * `end`: The end bit index (inclusive) /// * `value`: The value to write into /// * `data`: The value to set /// /// # Examples /// /// ``` /// let value = 0u8; /// write_bits!(0, 3, value, 0b0110); /// write_bits!(4, 7, value, 0b1001); /// assert_eq!(value, 0b10010110); /// ``` #[macro_export] macro_rules! write_bits { ($start:expr, $end:expr, $value:expr, $data:expr) => { $value = ($value & (!(((1 << ($end - $start + 1)) - 1) << $start))) | ($data << $start); }; } /// Reads bits from a given value /// /// # Arguments /// /// * `start`: The start bit index (inclusive) /// * `end`: The end bit index (inclusive) /// * `value`: The value /// /// # Examples /// /// ``` /// let value = 0b11110000u8; /// assert_eq!(read_bits!(value, 0, 3), 0b0000); /// assert_eq!(read_bits!(value, 4, 7), 0b1111); /// ``` #[macro_export] macro_rules! read_bits { ($start:expr, $end:expr, $value:expr) => { ($value & (((1 << ($end - $start + 1)) - 1) << $start)) >> $start }; } /// Gets the current function name /// /// # Examples /// /// ``` /// fn test() { /// assert_eq!(cur_fn_name!(), "test"); /// } /// ``` #[macro_export] macro_rules! cur_fn_name { () => {{ fn dummy_fn() {} const DUMMY_FN_EXTRA_SIZE: usize = "::dummy_fn".len(); fn type_name_of<T>(_: T) -> &'static str { core::any::type_name::<T>() } let name = type_name_of(dummy_fn); &name[..name.len() - DUMMY_FN_EXTRA_SIZE] }}; } // CFI directives cannot be used if neither debuginfo nor panic=unwind is enabled. // We don't have an easy way to check the former, so just check based on panic strategy. #[cfg(panic = "abort")] macro_rules! maybe_cfi { ($x: literal) => { "" }; } #[cfg(panic = "unwind")] macro_rules! maybe_cfi { ($x: literal) => { $x }; } pub(crate) use maybe_cfi;
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/macros/diag.rs
src/macros/diag.rs
#![macro_use] #[macro_export] macro_rules! diag_assert { ($desired_abort_level:expr, $cond_expr:expr) => {{ let cond = $cond_expr; if !cond { $crate::diag::abort::abort( $desired_abort_level, $crate::diag::rc::ResultAssertionFailed::make(), ); } }}; } // TODO: switch to a log system without having to reopen loggers for every log? global logger object(s) like N's log observers? #[macro_export] macro_rules! diag_log { ($logger:ty { $severity:expr, $verbosity:expr } => $msg:literal) => {{ let metadata = $crate::diag::log::LogMetadata::new($severity, $verbosity, alloc::string::String::from($msg), file!(), $crate::cur_fn_name!(), line!()); $crate::diag::log::log_with::<$logger>(&metadata); }}; ($logger:ty { $severity:expr, $verbosity:expr } => $msg:expr) => {{ let metadata = $crate::diag::log::LogMetadata::new($severity, $verbosity, $msg, file!(), $crate::cur_fn_name!(), line!()); $crate::diag::log::log_with::<$logger>(&metadata); }}; ($logger:ty { $severity:expr, $verbosity:expr } => $fmt:literal, $( $params:expr ),*) => {{ let msg = format!($fmt, $( $params, )*); let metadata = $crate::diag::log::LogMetadata::new($severity, $verbosity, msg, file!(), $crate::cur_fn_name!(), line!()); $crate::diag::log::log_with::<$logger>(&metadata); }}; } #[macro_export] macro_rules! diag_log_assert { ($logger:ty, $desired_abort_level:expr => $cond_expr:expr) => {{ let cond = $cond_expr; if cond { $crate::diag_log!($logger { $crate::diag::log::LogSeverity::Info, true } => "Assertion succeeded: '{}'", stringify!($cond_expr)); } else { $crate::diag_log!($logger { $crate::diag::log::LogSeverity::Fatal, true } => "Assertion failed: '{}' - proceeding to abort through {:?}...", stringify!($cond_expr), $desired_abort_level); $crate::diag::abort::abort($desired_abort_level, $crate::diag::rc::ResultAssertionFailed::make()); } }}; } #[macro_export] macro_rules! diag_result_code_log_assert { ($logger:ty, $desired_abort_level:expr => $rc_expr:expr) => {{ let rc = $rc_expr; if rc.is_success() { $crate::diag_log!($logger { $crate::diag::log::LogSeverity::Info, true } => "Result assertion succeeded: '{}'", stringify!($rc_expr)); } else { $crate::diag_log!($logger { $crate::diag::log::LogSeverity::Fatal, true } => "Result assertion failed: '{0}' was {1} ({1:?}) - proceeding to abort through {2:?}...", stringify!($rc_expr), rc, $desired_abort_level); $crate::diag::abort::abort($desired_abort_level, rc); } }}; } #[macro_export] macro_rules! diag_result_log_assert { ($logger:ty, $desired_abort_level:expr => $rc_expr:expr) => {{ let ret_rc = $rc_expr; match ret_rc { Ok(t) => { $crate::diag_log!($logger { $crate::diag::log::LogSeverity::Info, true } => "Result assertion succeeded: '{}'\n", stringify!($rc_expr)); t }, Err(rc) => { $crate::diag_log!($logger { $crate::diag::log::LogSeverity::Fatal, true } => "Result assertion failed: '{0}' was {1} ({1:?}) - proceeding to abort through {2:?}...", stringify!($rc_expr), rc, $desired_abort_level); $crate::diag::abort::abort($desired_abort_level, rc); } } }}; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/macros/rrt0.rs
src/macros/rrt0.rs
#![macro_use] /// Defines the (runtime) module name of the current project /// /// Must only be called once in a project /// /// # Arguments /// /// * `name`: The module name /// /// # Examples /// /// ``` /// rrt0_define_module_name!("custom-mod-name"); /// ``` #[macro_export] macro_rules! rrt0_define_module_name { ($name:expr) => { #[unsafe(no_mangle)] #[used] #[unsafe(link_section = ".module_name")] #[unsafe(export_name = "__nx_rrt0_module_name")] static G_MODULE_NAME: $crate::rrt0::ModulePath = $crate::rrt0::ModulePath::new($name); }; } /// Defines the (runtime) module name of the current project as the package name /// /// Must only be called once in a project /// /// # Examples /// /// ``` /// rrt0_define_default_module_name!(); /// ``` #[macro_export] macro_rules! rrt0_define_default_module_name { () => { rrt0_define_module_name!(env!("CARGO_PKG_NAME")); }; } /// Defines a default heap initialization function for NROs (homebrew loaded apps) #[macro_export] macro_rules! rrt0_initialize_heap { () => { #[unsafe(no_mangle)] #[inline(always)] pub fn initialize_heap(heap: $crate::util::PointerAndSize) -> $crate::util::PointerAndSize { $crate::mem::alloc::configure_heap(heap) } }; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/macros/ipc.rs
src/macros/ipc.rs
#![macro_use] pub mod client; pub mod sf;
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/macros/ipc/sf.rs
src/macros/ipc/sf.rs
#![macro_use] /// Defines a trait meant to be used for IPC interfaces /// /// # Examples /// /// ``` /// use nx::version::{Version, VersionInterval}; /// /// // Define commands with their request ID, allowed version interval and in/out parameters /// ipc_sf_define_interface_trait! { /// trait ExampleInterface { /// command_1 [1, VersionInterval::all()]: (in_32: u32) => (out_16: u16); /// #[ipc_rid(20)] #[version(VersionInterval::all())] fn command_2(&self, in_8: u8); /// } /// } /// /// // You can impl "IExampleInterface" to create a custom object implementing the commands /// ``` #[macro_export] macro_rules! ipc_sf_define_interface_trait { ( trait $intf:ident { $( $name:ident [$rq_id:expr, $ver_intv:expr $(, $noalias:tt)?]: ( $( $in_param_name:ident: $in_param_type:ty ),* ) => ( $( $client_out_param_name:ident: $client_out_param_type:ty ),* ) ( $( $server_out_param_name:ident: $server_out_param_type:ty ),* ) );* $(;)* // Note: trick to allow last trailing ';' for proper styling } ) => { paste::paste! { /// The IPC server trait for the [`<I $intf Server>`] trait. All methods are provided and overriding the implementations is not recommended. pub trait [<I $intf Client>]: $crate::ipc::client::IClientObject + Sync { $( #[allow(unused_parens)] #[allow(clippy::too_many_arguments)] #[allow(missing_docs)] fn $name(& $($noalias)? self, $( $in_param_name: $in_param_type ),* ) -> $crate::result::Result<( $( $client_out_param_type ),* )> { let mut ctx = $crate::ipc::CommandContext::new_client(self.get_session().object_info); let mut walker = $crate::ipc::DataWalker::new(core::ptr::null_mut()); $( $crate::ipc::client::RequestCommandParameter::before_request_write(&$in_param_name, &mut walker, &mut ctx)?; )* ctx.in_params.data_size = walker.get_offset() as u32; match self.get_session().object_info.protocol { $crate::ipc::CommandProtocol::Cmif => $crate::ipc::cmif::client::write_request_command_on_msg_buffer(&mut ctx, Some($rq_id), $crate::ipc::cmif::DomainCommandType::SendMessage), $crate::ipc::CommandProtocol::Tipc => $crate::ipc::tipc::client::write_request_command_on_msg_buffer(&mut ctx, $rq_id) }; walker.reset_with(ctx.in_params.data_offset); $( $crate::ipc::client::RequestCommandParameter::before_send_sync_request(&$in_param_name, &mut walker, &mut ctx)?; )* $crate::svc::send_sync_request(self.get_session().object_info.handle)?; match self.get_session().object_info.protocol { $crate::ipc::CommandProtocol::Cmif => $crate::ipc::cmif::client::read_request_command_response_from_msg_buffer(&mut ctx)?, $crate::ipc::CommandProtocol::Tipc => $crate::ipc::tipc::client::read_request_command_response_from_msg_buffer(&mut ctx)? }; walker.reset_with(ctx.out_params.data_offset); $( let $client_out_param_name = <$client_out_param_type as $crate::ipc::client::ResponseCommandParameter<_>>::after_response_read(&mut walker, &mut ctx)?; )* Ok(( $( $client_out_param_name as _ ),* )) } )* } /// The IPC server trait for the [`<I $intf Server>`] trait. The methods not provided must all be implemented, but overriding the IPC wrappers is not recommended. pub trait [<I $intf Server>]: $crate::ipc::server::ISessionObject + Sync { $( #[allow(unused_parens)] #[allow(clippy::too_many_arguments)] #[allow(missing_docs)] fn $name(&mut self, $( $in_param_name: $in_param_type ),* ) -> $crate::result::Result<( $( $server_out_param_type ),* )>; #[allow(unused_assignments)] #[allow(unused_parens)] #[allow(unused_mut)] #[doc(hidden)] fn [<sf_server_impl_ $name>](&mut self, protocol: $crate::ipc::CommandProtocol, mut ctx: &mut $crate::ipc::server::ServerContext) -> $crate::result::Result<()> { use $crate::result::ResultBase; ctx.raw_data_walker = $crate::ipc::DataWalker::new(ctx.ctx.in_params.data_offset); $( let $in_param_name = <$in_param_type as $crate::ipc::server::RequestCommandParameter<_>>::after_request_read(&mut ctx)?; )* let ( $( $server_out_param_name ),* ) = self.$name( $( $in_param_name ),* )?; ctx.raw_data_walker = $crate::ipc::DataWalker::new(core::ptr::null_mut()); $( let [<$server_out_param_name _carry_state>] = $crate::ipc::server::ResponseCommandParameter::before_response_write(&$server_out_param_name, &mut ctx)?; )* ctx.ctx.out_params.data_size = ctx.raw_data_walker.get_offset() as u32; match protocol { $crate::ipc::CommandProtocol::Cmif => { $crate::ipc::cmif::server::write_request_command_response_on_msg_buffer(&mut ctx.ctx, $crate::result::ResultSuccess::make(), $crate::ipc::cmif::CommandType::Request); }, $crate::ipc::CommandProtocol::Tipc => { $crate::ipc::tipc::server::write_request_command_response_on_msg_buffer(&mut ctx.ctx, $crate::result::ResultSuccess::make(), 16); // TODO: is this command type actually read/used/relevant? } }; ctx.raw_data_walker = $crate::ipc::DataWalker::new(ctx.ctx.out_params.data_offset); $( $crate::ipc::server::ResponseCommandParameter::after_response_write($server_out_param_name, [<$server_out_param_name _carry_state>], &mut ctx)?; )* Ok(()) } )* /// The dynamic dispatch function that calls into the IPC server functions. This should only be called from the [`$crate::ipc::server::ServerManager`] and not from client code. /// Examples for implementing [`ISessionObject`][`$crate::ipc::server::ISessionObject`] or [`IMitmServerOject`][`$crate::ipc::server::IMitmServerObject`] can be found in the [`nx`] crate. fn try_handle_request_by_id(&mut self, req_id: u32, protocol: $crate::ipc::CommandProtocol, ctx: &mut $crate::ipc::server::ServerContext) -> Option<$crate::result::Result<()>> { let version = $crate::version::get_version(); match req_id { $( $rq_id if $ver_intv.contains(version) => { Some(self.[<sf_server_impl_ $name>](protocol, ctx)) } ),* _ => None } } } } }; } #[macro_export] macro_rules! session_type { ($t:ty) => { paste::paste! { impl [<I $t Server>] + 'static } }; } /// Identical to [`ipc_sf_define_interface_trait`] but for "Control" IPC interfaces (inner trait functionality differs) /// /// This shouldn't really be used unless you really know what you're doing #[macro_export] macro_rules! ipc_sf_define_control_interface_trait { ( trait $intf:ident { $( $name:ident [$rq_id:expr, $ver_intv:expr]: ( $( $in_param_name:ident: $in_param_type:ty ),* ) => ( $( $out_param_name:ident: $out_param_type:ty ),* ) );* $(;)* // Same as above } ) => { paste::paste! { pub trait $intf { $( #[allow(unused_parens)] fn $name(&mut self, $( $in_param_name: $in_param_type ),* ) -> $crate::result::Result<( $( $out_param_type ),* )>; #[allow(unused_assignments)] #[allow(unused_parens)] #[doc(hidden)] fn [<_sf_server_impl_ $name>](&mut self, _protocol: $crate::ipc::CommandProtocol, mut ctx: &mut $crate::ipc::server::ServerContext) -> $crate::result::Result<()> { // TODO: tipc support, for now force cmif $crate::result_return_if!(ctx.ctx.object_info.uses_tipc_protocol(), $crate::ipc::rc::ResultInvalidProtocol); ctx.raw_data_walker = $crate::ipc::DataWalker::new(ctx.ctx.in_params.data_offset); $( let $in_param_name = <$in_param_type as $crate::ipc::server::RequestCommandParameter<_>>::after_request_read(&mut ctx)?; )* let ( $( $out_param_name ),* ) = self.$name( $( $in_param_name ),* )?; ctx.raw_data_walker = $crate::ipc::DataWalker::new(core::ptr::null_mut()); $( let [<$out_param_name _carry_state>] = $crate::ipc::server::ResponseCommandParameter::before_response_write(&$out_param_name, &mut ctx)?; )* ctx.ctx.out_params.data_size = ctx.raw_data_walker.get_offset() as u32; $crate::ipc::cmif::server::write_control_command_response_on_msg_buffer(&mut ctx.ctx, $crate::result::ResultSuccess::make(), $crate::ipc::cmif::CommandType::Control); ctx.raw_data_walker = $crate::ipc::DataWalker::new(ctx.ctx.out_params.data_offset); $( $crate::ipc::server::ResponseCommandParameter::after_response_write($out_param_name, [<$out_param_name _carry_state>], &mut ctx)?; )* Ok(()) } )* fn try_handle_request_by_id(&mut self, rq_id: u32, protocol: $crate::ipc::CommandProtocol, ctx: &mut $crate::ipc::server::ServerContext) -> Option<$crate::result::Result<()>> { match rq_id { $( $rq_id if $ver_intv.contains($crate::version::get_version()) => { Some(self.[<_sf_server_impl_ $name>](protocol, ctx)) } ),* _ => None } } } } }; } #[macro_export] macro_rules! server_mark_request_command_parameters_types_as_copy { ($($t:ty),*) => { $( impl $crate::ipc::server::RequestCommandParameter<'_,$t> for $t { fn after_request_read(ctx: &mut $crate::ipc::server::ServerContext) -> $crate::result::Result<Self> { Ok(ctx.raw_data_walker.advance_get()) } } impl $crate::ipc::server::ResponseCommandParameter for $t { type CarryState = (); fn before_response_write(_raw: &Self, ctx: &mut $crate::ipc::server::ServerContext) -> $crate::result::Result<()> { ctx.raw_data_walker.advance::<Self>(); Ok(()) } fn after_response_write(raw: Self, _carry_state: (), ctx: &mut $crate::ipc::server::ServerContext) -> $crate::result::Result<()> { ctx.raw_data_walker.advance_set(raw); Ok(()) } } )* }; } #[macro_export] macro_rules! api_mark_request_command_parameters_types_as_copy { ($($t:ty),*) => { $( server_mark_request_command_parameters_types_as_copy!($t); client_mark_request_command_parameters_types_as_copy!($t); )* }; } api_mark_request_command_parameters_types_as_copy!( bool, u8, i8, u16, i16, u32, i32, u64, i64, usize, isize, u128, i128, f32, f64 ); impl<T: Copy, const N: usize> crate::ipc::server::RequestCommandParameter<'_, [T; N]> for [T; N] { fn after_request_read( ctx: &mut crate::ipc::server::ServerContext, ) -> crate::result::Result<Self> { Ok(ctx.raw_data_walker.advance_get()) } } impl<T: Copy, const N: usize> crate::ipc::server::ResponseCommandParameter for [T; N] { type CarryState = (); fn before_response_write( _raw: &Self, ctx: &mut crate::ipc::server::ServerContext, ) -> crate::result::Result<()> { ctx.raw_data_walker.advance::<Self>(); Ok(()) } fn after_response_write( raw: Self, _carry_state: (), ctx: &mut crate::ipc::server::ServerContext, ) -> crate::result::Result<()> { ctx.raw_data_walker.advance_set(raw); Ok(()) } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/macros/ipc/client.rs
src/macros/ipc/client.rs
#![macro_use] /// Simplifies the creation of a (client-side IPC) type implementing an IPC interface (and implementing the trait) /// /// # Examples /// /// ``` /// /// // This already creates the client-IPC type and implements IObject and the SF trait below /// ipc_sf_define_default_client_for_interface!(ExampleInterface); /// /// ipc_sf_define_interface_trait! { /// trait ExampleInterface { /// command_1 [1, VersionInterval::all()]: (in_32: u32) => (out_16: u16); /// #[ipc_rid(20)] #[version(VersionInterval::all())] fn command_2(&self, in_8: u8); /// } /// } /// ``` #[macro_export] macro_rules! ipc_sf_define_default_client_for_interface { ($t:ident) => { paste::paste! { #[doc = concat!("The default client for the `", stringify!($t), "` trait. All implementors of the trait need to read their session in accordance with this Types IPC Parameter traits.")] pub struct $t { #[doc(hidden)] pub (crate) session: $crate::ipc::sf::Session } impl $crate::ipc::client::IClientObject for $t { fn new(session: $crate::ipc::sf::Session) -> Self { Self { session } } fn get_session(&self) -> & $crate::ipc::sf::Session { &self.session } fn get_session_mut(&mut self) -> &mut $crate::ipc::sf::Session { &mut self.session } } unsafe impl ::core::marker::Sync for $t {} unsafe impl ::core::marker::Send for $t {} impl $crate::ipc::client::RequestCommandParameter for $t { fn before_request_write(session: &Self, _walker: &mut $crate::ipc::DataWalker, ctx: &mut $crate::ipc::CommandContext) -> $crate::result::Result<()> { ctx.in_params.add_object(session.session.object_info) } fn before_send_sync_request(_session: &Self, _walker: &mut $crate::ipc::DataWalker, _ctx: &mut $crate::ipc::CommandContext) -> $crate::result::Result<()> { Ok(()) } } impl $crate::ipc::client::ResponseCommandParameter<$t> for $t { fn after_response_read(_walker: &mut $crate::ipc::DataWalker, ctx: &mut $crate::ipc::CommandContext) -> $crate::result::Result<Self> { let object_info = ctx.pop_object()?; Ok(Self { session: $crate::ipc::sf::Session::from(object_info)}) } } impl $crate::ipc::server::RequestCommandParameter<'_, $t> for $t { fn after_request_read(_ctx: &mut $crate::ipc::server::ServerContext) -> $crate::result::Result<Self> { use $crate::result::ResultBase; // TODO: determine if we need to do this, since this is a server side operation of a client object? // probably needs to be supported right? $crate::ipc::sf::hipc::rc::ResultUnsupportedOperation::make_err() } } impl $crate::ipc::server::ResponseCommandParameter for $t { type CarryState = (); fn before_response_write(_session: &Self, _ctx: &mut $crate::ipc::server::ServerContext) -> $crate::result::Result<()> { use $crate::result::ResultBase; // TODO: determine if we need to do this, since this is a server side operation of a client object? // probably needs to be supported right? $crate::ipc::sf::hipc::rc::ResultUnsupportedOperation::make_err() } fn after_response_write(_session: Self, _carry_state: (), _ctx: &mut $crate::ipc::server::ServerContext) -> $crate::result::Result<()> { use $crate::result::ResultBase; // TODO: determine if we need to do this, since this is a server side operation of a client object? // probably needs to be supported right? $crate::ipc::sf::hipc::rc::ResultUnsupportedOperation::make_err() } } impl [<I $t Client>] for $t {} } } } /// Simplifies the creation of a (client-side IPC) type implementing an IPC interface, without implementing the trait or IPC serialization /// /// # Examples /// /// ``` /// // Let's suppose a "IExampleInterface" IPC interface trait exists /// /// // This already creates the client-IPC type and impls IObject /// ipc_client_define_client_default!(ExampleInterface); /// /// impl IExampleInterface for ExampleInterface { /// (...) /// } /// ``` #[macro_export] macro_rules! ipc_client_define_client_default { ($t:ident) => { #[doc = concat!("Default client object for the `", stringify!($t), "` service")] #[allow(missing_docs)] pub struct $t { pub(crate) session: $crate::ipc::sf::Session, } impl $crate::ipc::client::IClientObject for $t { fn new(session: $crate::ipc::sf::Session) -> Self { Self { session } } fn get_session(&self) -> &$crate::ipc::sf::Session { &self.session } fn get_session_mut(&mut self) -> &mut $crate::ipc::sf::Session { &mut self.session } } unsafe impl Sync for $t {} unsafe impl Send for $t {} }; } /// Sends an IPC "Request" command /// /// # Examples /// /// ``` /// use nx::ipc::sf::Session; /// /// fn demo(session: Session) -> $crate::result::Result<()> { /// let in_32: u32 = 69; /// let in_16: u16 = 420; /// /// // Calls command with request ID 123 and with an input-u32 and an input-u16 expecting an output-u64, Will yield a Result<u64> /// let _out = ipc_client_send_request_command!([session.object_info; 123] (in_32, in_16) => (out: u64))?; /// /// Ok(()) /// } /// ``` #[macro_export] macro_rules! ipc_client_send_request_command { ([$obj_info:expr; $rq_id:expr] ( $( $in_param:expr ),* ) => ( $( $out_param:ident: $out_param_type:ty ),* )) => {{ let mut ctx = $crate::ipc::CommandContext::new_client($obj_info); let mut walker = $crate::ipc::DataWalker::new(core::ptr::null_mut()); $( $crate::ipc::client::RequestCommandParameter::before_request_write(&$in_param, &mut walker, &mut ctx)?; )* ctx.in_params.data_size = walker.get_offset() as u32; match $obj_info.protocol { $crate::ipc::CommandProtocol::Cmif => $crate::ipc::cmif::client::write_request_command_on_msg_buffer(&mut ctx, Some($rq_id), $crate::ipc::cmif::DomainCommandType::SendMessage), $crate::ipc::CommandProtocol::Tipc => $crate::ipc::tipc::client::write_request_command_on_msg_buffer(&mut ctx, $rq_id) }; walker.reset_with(ctx.in_params.data_offset); $( $crate::ipc::client::RequestCommandParameter::before_send_sync_request(&$in_param, &mut walker, &mut ctx)?; )* $crate::svc::send_sync_request($obj_info.handle)?; match $obj_info.protocol { $crate::ipc::CommandProtocol::Cmif => $crate::ipc::cmif::client::read_request_command_response_from_msg_buffer(&mut ctx)?, $crate::ipc::CommandProtocol::Tipc => $crate::ipc::tipc::client::read_request_command_response_from_msg_buffer(&mut ctx)? }; walker.reset_with(ctx.out_params.data_offset); $( let $out_param = <$out_param_type as $crate::ipc::client::ResponseCommandParameter<_>>::after_response_read(&mut walker, &mut ctx)?; )* Ok(( $( $out_param as _ ),* )) }}; } /// Identical to [`ipc_client_send_request_command`] but for a "Control" command /// /// See <https://switchbrew.org/wiki/IPC_Marshalling#Control> #[macro_export] macro_rules! ipc_client_send_control_command { ([$obj_info:expr; $rq_id:expr] ( $( $in_param:expr ),* ) => ( $( $out_param:ident: $out_param_type:ty ),* )) => {{ $crate::result_return_if!($obj_info.uses_tipc_protocol(), $crate::ipc::rc::ResultInvalidProtocol); let mut ctx = $crate::ipc::CommandContext::new_client($obj_info); let mut walker = $crate::ipc::DataWalker::new(core::ptr::null_mut()); $( $crate::ipc::client::RequestCommandParameter::before_request_write(&$in_param, &mut walker, &mut ctx)?; )* ctx.in_params.data_size = walker.get_offset() as u32; $crate::ipc::cmif::client::write_control_command_on_msg_buffer(&mut ctx, $rq_id); walker.reset_with(ctx.in_params.data_offset); $( $crate::ipc::client::RequestCommandParameter::before_send_sync_request(&$in_param, &mut walker, &mut ctx)?; )* $crate::svc::send_sync_request($obj_info.handle)?; $crate::ipc::cmif::client::read_control_command_response_from_msg_buffer(&mut ctx)?; walker.reset_with(ctx.out_params.data_offset); $( let $out_param = <$out_param_type as $crate::ipc::client::ResponseCommandParameter<_>>::after_response_read(&mut walker, &mut ctx)?; )* Ok(( $( $out_param as _ ),* )) }}; } #[macro_export] macro_rules! client_mark_request_command_parameters_types_as_copy { ($($t:ty),*) => { $( //const_assert!($t::is_pod()); impl $crate::ipc::client::RequestCommandParameter for $t { fn before_request_write(_raw: &Self, walker: &mut $crate::ipc::DataWalker, _ctx: &mut $crate::ipc::CommandContext) -> $crate::result::Result<()> { walker.advance::<Self>(); Ok(()) } fn before_send_sync_request(raw: &Self, walker: &mut $crate::ipc::DataWalker, _ctx: &mut $crate::ipc::CommandContext) -> $crate::result::Result<()> { walker.advance_set(*raw); Ok(()) } } impl $crate::ipc::client::ResponseCommandParameter<$t> for $t { fn after_response_read(walker: &mut $crate::ipc::DataWalker, _ctx: &mut $crate::ipc::CommandContext) -> $crate::result::Result<Self> { Ok(walker.advance_get()) } })* }; } impl<T: Copy, const N: usize> crate::ipc::client::RequestCommandParameter for [T; N] { fn before_request_write( _raw: &Self, walker: &mut crate::ipc::DataWalker, _ctx: &mut crate::ipc::CommandContext, ) -> crate::result::Result<()> { walker.advance::<Self>(); Ok(()) } fn before_send_sync_request( raw: &Self, walker: &mut crate::ipc::DataWalker, _ctx: &mut crate::ipc::CommandContext, ) -> crate::result::Result<()> { walker.advance_set(*raw); Ok(()) } } impl<T: Copy, const N: usize> crate::ipc::client::ResponseCommandParameter<[T; N]> for [T; N] { fn after_response_read( walker: &mut crate::ipc::DataWalker, _ctx: &mut crate::ipc::CommandContext, ) -> crate::result::Result<Self> { Ok(walker.advance_get()) } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/gpu/surface.rs
src/gpu/surface.rs
//! Surface (gfx wrapper) implementation use ::alloc::string::String; use ::alloc::sync::Arc; use service::vi::{IManagerDisplayClient, ISystemDisplayClient}; use super::*; use crate::gpu::binder; use crate::gpu::ioctl; use crate::ipc::sf; use crate::mem::alloc; use crate::service::dispdrv; use crate::svc; use crate::wait; use core::mem as cmem; const MAX_BUFFERS: usize = 8; /// Configures the scaling mode for managed layers pub enum ScaleMode { // Don't scale the layer None, // Native framebuffer/canvas will be scaled and stretched to fit the provided layer size FitToLayer { width: u32, height: u32 }, // Native framebuffer/canvas will be scaled to fit the provided layer height, but aspect ratio will be respected PreseveAspect { height: u32 }, } #[derive(Debug, Clone, Default)] pub enum DisplayName { #[default] Default, Special(String), } impl From<DisplayName> for vi::DisplayName { fn from(var: DisplayName) -> vi::DisplayName { match var { DisplayName::Default => vi::DisplayName::from_str("Default"), DisplayName::Special(special) => vi::DisplayName::from_string(&special), } } } /// Represents a wrapper around layer manipulation pub struct Surface { binder: binder::Binder, gpu_ctx: Arc<RwLock<super::Context>>, buffer_data: alloc::Buffer<u8>, slot_has_requested: [bool; MAX_BUFFERS], graphic_buf: GraphicBuffer, display_id: vi::DisplayId, layer_id: vi::LayerId, vsync_event_handle: svc::Handle, buffer_event_handle: svc::Handle, managed: bool, } #[allow(clippy::too_many_arguments)] impl Surface { /// Create a new stray layer covering the full screen (modeled as a 1280x720 pixel surface) /// /// # Arguments: /// * gpu_ctx: a handle to a gpu shared context we can use to control the propeties of our layer. /// * display_name: a name for the spawned layer /// * buffer_count: the number of buffers to use. using a value of 0 will error, and a value of 1 will hang at runtime as you cannot dequeue the active buffer. /// * block_config: configuration value for the GPU buffer tiling height. Applications with row based rendering should set a low value and applications that draw mainly in blocks (e.g. image decoding or text) should set medium or higher values. /// * color_format: The color format set on the layer /// * pixel_format: The pixel format for the buffer. Must match the color format to run without graphical issues. pub fn new_stray( gpu_ctx: Arc<RwLock<Context>>, display_name: DisplayName, buffer_count: u32, block_config: BlockLinearHeights, color_fmt: ColorFormat, pixel_fmt: PixelFormat, ) -> Result<Self> { let mut gpu_guard = gpu_ctx.write(); let display_id = gpu_guard .application_display_service .open_display(display_name.into())?; let (binder_handle, layer_id) = { let mut native_window = parcel::ParcelPayload::new(); let (layer_id, _) = gpu_guard.application_display_service.create_stray_layer( vi::LayerFlags::Default(), display_id, sf::Buffer::from_other_mut_var(&mut native_window), )?; let mut parcel = parcel::Parcel::new(); parcel.load_from(native_window); let binder_handle = parcel .read::<parcel::ParcelData>() .expect("ParcelData should always be readable if create_stray_layer succeeds.") .handle; (binder_handle, layer_id) }; drop(gpu_guard); Self::new_from_parts( binder_handle, gpu_ctx, buffer_count, display_id, layer_id, SCREEN_WIDTH, SCREEN_HEIGHT, block_config, color_fmt, pixel_fmt, false, ) } /// Create a new stray layer covering the full screen (modeled as a 1280x720 pixel surface) /// /// # Arguments: /// * gpu_ctx: a handle to a gpu shared context we can use to control the propeties of our layer. /// * display_name: a name for the spawned layer /// * aruid: the applet resource user ID for the running app (usually 0, but can be retrieved by initializing the applet module). /// * layer_flags: the `vi` service flags to set for the layer (usually 0). /// * x: the offset of the layer from the left edge of the screen. /// * y: the offset of the layer from the top edge of the screen. /// * width: width of the canvas. /// * height: height of the canvas. /// * buffer_count: the number of buffers to use. using a value of 0 will error, and a value of 1 will hang at runtime as you cannot dequeue the active buffer. /// * block_config: configuration value for the GPU buffer tiling height. Applications with row based rendering should set a low value and applications that draw mainly in blocks (e.g. image decoding or text) should set medium or higher values. /// * color_format: The color format set on the layer /// * pixel_format: The pixel format for the buffer. Must match the color format to run without graphical issues. /// * scaling: The configuration for mapping the framebuffer/canvas onto the spawned layer which may be a larger/smaller size. pub fn new_managed( gpu_ctx: Arc<RwLock<Context>>, display_name: DisplayName, aruid: applet::AppletResourceUserId, layer_flags: vi::LayerFlags, x: f32, y: f32, z: LayerZ, framebuffer_width: u32, framebuffer_height: u32, buffer_count: u32, block_config: BlockLinearHeights, color_fmt: ColorFormat, pixel_fmt: PixelFormat, scaling: ScaleMode, ) -> Result<Self> { let mut gpu_guard = gpu_ctx.write(); let display_name_v = display_name.into(); let display_id = gpu_guard .application_display_service .open_display(display_name_v)?; let mut system_display_service = gpu_guard .application_display_service .get_system_display_service()?; let mut manager_display_service = gpu_guard .application_display_service .get_manager_display_service()?; let mut native_window = parcel::ParcelPayload::new(); let layer_id = manager_display_service.create_managed_layer(layer_flags, display_id, aruid.aruid)?; gpu_guard.application_display_service.open_layer( display_name_v, layer_id, aruid, sf::Buffer::from_other_mut_var(&mut native_window), )?; let binder_handle = match try { let mut binder_parcel = parcel::Parcel::new(); binder_parcel.load_from(native_window); let binder_handle = binder_parcel.read::<parcel::ParcelData>()?.handle; match scaling { ScaleMode::None => { gpu_guard .application_display_service .set_scaling_mode(vi::ScalingMode::None, layer_id)?; system_display_service.set_layer_size( layer_id, framebuffer_width as u64, framebuffer_height as u64, )?; } ScaleMode::FitToLayer { width, height } => { gpu_guard .application_display_service .set_scaling_mode(vi::ScalingMode::FitToLayer, layer_id)?; system_display_service.set_layer_size(layer_id, width as u64, height as u64)?; } ScaleMode::PreseveAspect { height } => { gpu_guard .application_display_service .set_scaling_mode(vi::ScalingMode::PreserveAspectRatio, layer_id)?; system_display_service.set_layer_size( layer_id, (framebuffer_width as f32 * (height as f32) / (framebuffer_height as f32)) as u64, height as u64, )?; } } system_display_service.set_layer_position(x, y, layer_id)?; let z_value = match z { LayerZ::Max => system_display_service.get_z_order_count_max(display_id)?, LayerZ::Min => system_display_service.get_z_order_count_min(display_id)?, LayerZ::Value(z_val) => z_val, }; system_display_service.set_layer_z(layer_id, z_value)?; binder_handle } { Err(e) => { manager_display_service.destroy_managed_layer(layer_id)?; return Err(e); } Ok(handle) => handle, }; drop(gpu_guard); Self::new_from_parts( binder_handle, gpu_ctx, buffer_count, display_id, layer_id, framebuffer_width, framebuffer_height, block_config, color_fmt, pixel_fmt, true, ) } /// Creates a new [`Surface`] /// /// This is not meant to really be used manually, see [`Context`][`super::Context`] pub fn new_from_parts( binder_handle: dispdrv::BinderHandle, gpu_ctx: Arc<RwLock<Context>>, buffer_count: u32, display_id: vi::DisplayId, layer_id: vi::LayerId, width: u32, height: u32, block_height_config: BlockLinearHeights, color_fmt: ColorFormat, pixel_fmt: PixelFormat, managed: bool, ) -> Result<Self> { let mut binder = binder::Binder::new(binder_handle, gpu_ctx.read().hos_binder_driver.clone())?; binder.increase_refcounts()?; let _ = binder.connect(ConnectionApi::Cpu, false)?; let vsync_event_handle = gpu_ctx .read() .application_display_service .get_display_vsync_event(display_id)?; let buffer_event_handle = binder.get_native_handle(dispdrv::NativeHandleType::BufferEvent)?; let mut surface = Self { binder, gpu_ctx, buffer_data: alloc::Buffer::empty(), slot_has_requested: [false; MAX_BUFFERS], graphic_buf: Default::default(), display_id, layer_id, vsync_event_handle: vsync_event_handle.handle, buffer_event_handle: buffer_event_handle.handle, managed, }; // Initialization { let pitch = align_up!(width * color_fmt.bytes_per_pixel(), 64u32); let stride = pitch / color_fmt.bytes_per_pixel(); let aligned_height = align_up!(height, block_height_config.block_height_bytes()); let single_buffer_size = align_up!( pitch as usize * aligned_height as usize, alloc::PAGE_ALIGNMENT ); let total_framebuffer_size = buffer_count as usize * single_buffer_size; surface.buffer_data = alloc::Buffer::new(alloc::PAGE_ALIGNMENT, total_framebuffer_size)?; let mut ioctl_create = ioctl::NvMapCreate { size: total_framebuffer_size as u32, ..Default::default() }; surface.do_ioctl(&mut ioctl_create)?; let mut ioctl_getid = ioctl::NvMapGetId { handle: ioctl_create.handle, ..Default::default() }; surface.do_ioctl(&mut ioctl_getid)?; let mut ioctl_alloc = ioctl::NvMapAlloc { handle: ioctl_create.handle, heap_mask: 0, flags: ioctl::AllocFlags::ReadOnly, align: alloc::PAGE_ALIGNMENT as u32, kind: Kind::Pitch, address: surface.buffer_data.ptr.expose_provenance(), ..Default::default() }; surface.do_ioctl(&mut ioctl_alloc)?; unsafe { nx::arm::cache_flush(surface.buffer_data.ptr, total_framebuffer_size); svc::set_memory_attribute(surface.buffer_data.ptr, total_framebuffer_size, true)?; } let usage = GraphicsAllocatorUsage::HardwareComposer() | GraphicsAllocatorUsage::HardwareRender() | GraphicsAllocatorUsage::HardwareTexture(); surface.graphic_buf.header.magic = GraphicBufferHeader::MAGIC; surface.graphic_buf.header.width = width; surface.graphic_buf.header.height = height; surface.graphic_buf.header.stride = stride; surface.graphic_buf.header.pixel_format = pixel_fmt; surface.graphic_buf.header.gfx_alloc_usage = usage; surface.graphic_buf.header.pid = 42; surface.graphic_buf.header.buffer_size = ((cmem::size_of::<GraphicBuffer>() - cmem::size_of::<GraphicBufferHeader>()) / cmem::size_of::<u32>()) as u32; surface.graphic_buf.unknown = -1; surface.graphic_buf.map_id = ioctl_getid.id; surface.graphic_buf.magic = GraphicBuffer::MAGIC; surface.graphic_buf.pid = 42; surface.graphic_buf.gfx_alloc_usage = usage; surface.graphic_buf.pixel_format = pixel_fmt; surface.graphic_buf.external_pixel_format = pixel_fmt; surface.graphic_buf.stride = stride; surface.graphic_buf.full_size = single_buffer_size as u32; surface.graphic_buf.plane_count = 1; surface.graphic_buf.unk2 = 0; surface.graphic_buf.planes[0].width = width; surface.graphic_buf.planes[0].height = height; surface.graphic_buf.planes[0].color_format = color_fmt; surface.graphic_buf.planes[0].layout = Layout::BlockLinear; surface.graphic_buf.planes[0].pitch = pitch; surface.graphic_buf.planes[0].map_handle = ioctl_create.handle; surface.graphic_buf.planes[0].kind = Kind::Generic_16BX2; surface.graphic_buf.planes[0].block_height_log2 = block_height_config; surface.graphic_buf.planes[0].display_scan_format = DisplayScanFormat::Progressive; surface.graphic_buf.planes[0].size = single_buffer_size; for i in 0..buffer_count { let mut graphic_buf_copy = surface.graphic_buf; graphic_buf_copy.planes[0].offset = i * graphic_buf_copy.full_size; surface .binder .set_preallocated_buffer(i as i32, graphic_buf_copy)?; } } Ok(surface) } fn do_ioctl<I: ioctl::Ioctl>(&mut self, i: &mut I) -> Result<()> { let gpu_guard = self.gpu_ctx.read(); let fd = match I::get_fd() { ioctl::IoctlFd::NvHost => gpu_guard.nvhost_fd, ioctl::IoctlFd::NvMap => gpu_guard.nvmap_fd, ioctl::IoctlFd::NvHostCtrl => gpu_guard.nvhostctrl_fd, }; let err = gpu_guard .nvdrv_service .ioctl(fd, I::get_id(), sf::Buffer::from_other_mut_var(i))?; super::convert_nv_error_code(err) } pub fn get_block_linear_config(&self) -> BlockLinearHeights { self.graphic_buf.planes[0].block_height_log2 } /// Dequeues a buffer, returning the buffer address, its size, its slot, whether it has fences, and those mentioned fences /// /// # Arguments /// /// * `is_async`: Whether to dequeue asynchronously pub fn dequeue_buffer( &mut self, is_async: bool, ) -> Result<(*mut u8, usize, i32, bool, MultiFence)> { let slot: i32; let has_fences: bool; let fences: MultiFence; if is_async { self.wait_buffer_event(-1)?; loop { match self.binder.dequeue_buffer( true, self.width(), self.height(), false, self.graphic_buf.gfx_alloc_usage, ) { Ok((_slot, _has_fences, _fences)) => { slot = _slot; has_fences = _has_fences; fences = _fences; break; } Err(rc) => { if binder::rc::ResultErrorCodeWouldBlock::matches(rc) { continue; } return Err(rc); } }; } } else { let (_slot, _has_fences, _fences) = self.binder.dequeue_buffer( false, self.width(), self.height(), false, self.graphic_buf.gfx_alloc_usage, )?; slot = _slot; has_fences = _has_fences; fences = _fences; } if !self.slot_has_requested[slot as usize] { self.binder.request_buffer(slot)?; self.slot_has_requested[slot as usize] = true; } let buf = unsafe { self.buffer_data .ptr .add(slot as usize * self.graphic_buf.full_size as usize) }; Ok(( buf, self.graphic_buf.full_size as usize, slot, has_fences, fences, )) } /// Queues a buffer /// /// # Arguments /// /// * `slot`: The buffer slot /// * `fences`: The buffer fences pub fn queue_buffer(&mut self, slot: i32, fences: MultiFence) -> Result<()> { let qbi = QueueBufferInput { swap_interval: 1, fences, ..Default::default() }; nx::arm::cache_flush( unsafe { self.buffer_data .ptr .add(self.graphic_buf.full_size as usize * slot as usize) }, self.graphic_buf.full_size as usize, ); self.binder.queue_buffer(slot, qbi)?; Ok(()) } /// Waits for the given fences /// /// # Arguments /// /// * `fences`: The fences /// * `timeout`: The wait timeout pub fn wait_fences(&mut self, fences: MultiFence, timeout: i32) -> Result<()> { for fence in fences.fences[..fences.fence_count as usize].iter().cloned() { let mut ioctl_syncptwait = ioctl::NvHostCtrlSyncptWait { fence, timeout }; if self.do_ioctl(&mut ioctl_syncptwait).is_err() { // Don't error, but stop waiting for fences break; } } Ok(()) } /// Sets whether the surface (its layer) is visible /// /// # Arguments /// /// * `visible`: Whether its visible pub fn set_visible(&mut self, visible: bool) -> Result<()> { self.gpu_ctx .read() .application_display_service .get_system_display_service()? .set_layer_visibility(visible, self.layer_id) } /// Adds a layer visibility stack /// /// The Management display server maintains a stack of visible layers. This allows us to order our layer relative to other elements (e.g. visible or invisible to screenshots/recordings) /// /// # Atguments /// /// * `stack_type_id`: the type of layer to add to the visibility stack pub fn push_layer_stack(&mut self, stack_type_id: vi::LayerStackId) -> Result<()> { self.gpu_ctx .read() .application_display_service .get_manager_display_service()? .add_to_layer_stack(stack_type_id, self.layer_id) } /// Waits for the buffer event /// /// # Arguments /// /// * `timeout`: The wait timeout pub fn wait_buffer_event(&self, timeout: i64) -> Result<()> { wait::wait_handles(&[self.buffer_event_handle], timeout)?; svc::reset_signal(self.buffer_event_handle) } /// Waits for the vsync event /// /// # Arguments /// /// * `timeout`: The wait timeout pub fn wait_vsync_event(&self, timeout: i64) -> Result<()> { wait::wait_handles(&[self.vsync_event_handle], timeout)?; svc::reset_signal(self.vsync_event_handle) } /// Gets the surface width #[inline] pub const fn width(&self) -> u32 { self.graphic_buf.header.width } /// Gets the surface height #[inline] pub const fn height(&self) -> u32 { self.graphic_buf.header.height } /// Gets the surface pitch (in bytes) #[inline] pub const fn pitch(&self) -> u32 { self.graphic_buf.planes[0].pitch } /// Gets the surface [`ColorFormat`] #[inline] pub const fn color_format(&self) -> ColorFormat { self.graphic_buf.planes[0].color_format } /// Computes and gets the surface stride (distance between adjacent rows in pixels, incliuding padding). pub const fn stride(&self) -> u32 { self.pitch() / self.color_format().bytes_per_pixel() } #[inline] pub const fn single_buffer_size(&self) -> u32 { self.graphic_buf.full_size } } impl Drop for Surface { /// Destroys the surface, closing everything it internally opened #[allow(unused_must_use)] // we can't return from Drop, so just ignore result codes fn drop(&mut self) { self.binder .disconnect(ConnectionApi::Cpu, DisconnectMode::AllLocal); self.binder.decrease_refcounts(); let mut ioctl_free = ioctl::NvMapFree { handle: self.graphic_buf.planes[0].map_handle, ..Default::default() }; let _ = self.do_ioctl(&mut ioctl_free); unsafe { svc::set_memory_attribute(self.buffer_data.ptr, self.buffer_data.layout.size(), false) }; let mut gpu_guard = self.gpu_ctx.write(); let _layer_close_result = if self.managed { gpu_guard.application_display_service.get_manager_display_service().expect("We successfully created a managed layer, we should always then be able to recall the manager service").destroy_managed_layer(self.layer_id) } else { gpu_guard .application_display_service .destroy_stray_layer(self.layer_id) }; gpu_guard .application_display_service .close_display(self.display_id); svc::close_handle(self.buffer_event_handle); svc::close_handle(self.vsync_event_handle); } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/gpu/canvas.rs
src/gpu/canvas.rs
use core::marker::PhantomData; use core::ops::Mul; use alloc::sync::Arc; use bitfield_struct::bitfield; //use num_traits::float::Float; use sealed::CanvasColorFormat; use crate::arm; use crate::mem::alloc::Buffer; use crate::result::Result; use crate::sync::RwLock; use crate::{ipc::sf::AppletResourceUserId, service::vi::LayerFlags}; use super::surface::{ScaleMode, Surface}; use super::{BlockLinearHeights, ColorFormat, Context, LayerZ, MultiFence, PixelFormat}; #[cfg(feature = "truetype")] pub type Font<'a> = ab_glyph::FontRef<'a>; #[derive(Debug, Clone, Copy, Default)] pub enum AlphaBlend { None, #[default] Source, Destination, } /// RGBA (4444) Pixel/Color Representation #[bitfield(u16, order = Lsb)] pub struct RGBA4 { /// Alpha channel #[bits(4)] pub b: u8, /// Blue channel #[bits(4)] pub a: u8, /// Green channel #[bits(4)] pub r: u8, /// Red channel #[bits(4)] pub g: u8, } impl RGBA4 { /// Takes in standard 8-bit colors and scales them down to fit the range of 4-bit channels (via 4-bit right shift) #[inline] pub fn new_scaled(r: u8, g: u8, b: u8, a: u8) -> Self { Self::new() .with_r(r >> 4) .with_g(g >> 4) .with_b(b >> 4) .with_a(a >> 4) } #[inline] fn blend_channel(channel: u8, other: u8, alpha: u8) -> u8 { (channel * alpha + other * (15 - alpha)) >> 4 } } impl sealed::CanvasColorFormat for RGBA4 { type RawType = u16; const COLOR_FORMAT: ColorFormat = ColorFormat::A4B4G4R4; const PIXEL_FORMAT: PixelFormat = PixelFormat::RGBA_4444; fn new() -> Self { Self::new() } /// Takes in standard 8-bit colors and scales them down to fit the range of 4-bit channels (via 4-bit right shift) #[inline] fn new_scaled(r: u8, g: u8, b: u8, a: u8) -> Self { Self::new_scaled(r, g, b, a) } fn to_raw(self) -> Self::RawType { self.0.to_be() } fn from_raw(raw: Self::RawType) -> Self { Self::from_bits(raw) } fn blend_with(self, other: Self, blend_mode: AlphaBlend) -> Self { match blend_mode { AlphaBlend::None => self, AlphaBlend::Source => self .with_r(Self::blend_channel(self.r(), other.r(), self.a())) .with_g(Self::blend_channel(self.g(), other.g(), self.a())) .with_b(Self::blend_channel(self.b(), other.b(), self.a())) .with_a(other.a()), AlphaBlend::Destination => self .with_r(Self::blend_channel(self.r(), other.r(), self.a())) .with_g(Self::blend_channel(self.g(), other.g(), self.a())) .with_b(Self::blend_channel(self.b(), other.b(), self.a())) .with_a((self.a() + other.a()).min(0xF)), } } fn scale_alpha(self, alpha: f32) -> Self { let new_alpha = alpha * self.a() as f32; self.with_a(new_alpha as u8) } } /// RGBA (8888) Pixel/Color Representation /// /// We are using the bitfields crate here just for consistency with RGBA4444. /// The bit range checks should be optimized out in release mode. #[bitfield(u32, order = Lsb)] pub struct RGBA8 { /// Alpha channel #[bits(8)] pub a: u8, /// Blue channel #[bits(8)] pub b: u8, /// Green channel #[bits(8)] pub g: u8, /// Red channel #[bits(8)] pub r: u8, } impl RGBA8 { pub fn new_scaled(r: u8, g: u8, b: u8, a: u8) -> Self { Self::new().with_r(r).with_g(g).with_b(b).with_a(a) } fn blend_channel(channel: u8, other: u8, alpha: u8) -> u8 { ((u16::from(channel).mul(alpha as u16) + u16::from(other).mul(u8::MAX as u16 - alpha as u16)) / 0xff) as u8 } } impl sealed::CanvasColorFormat for RGBA8 { type RawType = u32; const COLOR_FORMAT: ColorFormat = ColorFormat::R8G8B8A8; const PIXEL_FORMAT: PixelFormat = PixelFormat::RGBA_8888; fn new() -> Self { Self::new() } fn to_raw(self) -> Self::RawType { self.0 } fn from_raw(raw: Self::RawType) -> Self { Self::from_bits(raw) } fn new_scaled(r: u8, g: u8, b: u8, a: u8) -> Self { Self::new_scaled(r, g, b, a) } fn blend_with(self, other: Self, blend_mode: AlphaBlend) -> Self { match blend_mode { AlphaBlend::None => self, AlphaBlend::Source => self .with_r(Self::blend_channel(self.r(), other.r(), self.a())) .with_g(Self::blend_channel(self.g(), other.g(), self.a())) .with_b(Self::blend_channel(self.b(), other.b(), self.a())) .with_a(other.a()), AlphaBlend::Destination => self .with_r(Self::blend_channel(self.r(), other.r(), self.a())) .with_g(Self::blend_channel(self.g(), other.g(), self.a())) .with_b(Self::blend_channel(self.b(), other.b(), self.a())) .with_a(self.a().saturating_add(other.a())), } } fn scale_alpha(self, alpha: f32) -> Self { let new_alpha = alpha * self.a() as f32; self.with_a(new_alpha as u8) } } pub(crate) mod sealed { use super::{AlphaBlend, ColorFormat, PixelFormat}; pub trait CanvasColorFormat: Copy + Default + 'static { /// The raw type that will be written into the backing buffer; type RawType: num_traits::PrimInt + 'static; /// The native color format used const COLOR_FORMAT: ColorFormat; /// The native pixel format const PIXEL_FORMAT: PixelFormat; /// The size of the raw pixel in bytes (must be the same size as the RawType) const BYTES_PER_PIXEL: u32 = Self::COLOR_FORMAT.bytes_per_pixel(); /// Create a new default instance of the type fn new() -> Self; /// Create an instance of the type scaled from standard 888 color values fn new_scaled(r: u8, g: u8, b: u8, a: u8) -> Self; /// Transmute from the raw backing type fn from_raw(raw: Self::RawType) -> Self; /// Transmute to the raw backing type fn to_raw(self) -> Self::RawType; /// Alpha blend the pixels together fn blend_with(self, other: Self, blend: AlphaBlend) -> Self; /// Scale the color's alpha channel /// /// `alpha` must be between 0 and 1, or the implementation should panic. fn scale_alpha(self, alpha: f32) -> Self; } } pub struct CanvasManager<ColorFormat: sealed::CanvasColorFormat> { pub surface: super::surface::Surface, _color_fmt: PhantomData<ColorFormat>, } #[allow(clippy::too_many_arguments)] impl<ColorFormat: sealed::CanvasColorFormat> CanvasManager<ColorFormat> { /// Computes the heap memory required to contain all the frame buffers for the provided parameters. pub const fn total_heap_required( width: u32, height: u32, block_height_config: BlockLinearHeights, buffer_count: u32, ) -> usize { let pitch = align_up!(width * ColorFormat::COLOR_FORMAT.bytes_per_pixel(), 64u32); let aligned_height = align_up!(height, block_height_config.block_height_bytes()); let single_buffer_size: usize = align_up!( pitch as usize * aligned_height as usize, crate::mem::alloc::PAGE_ALIGNMENT ); buffer_count as usize * single_buffer_size } /// Creates a new stray layer (application/applet window) that can be drawn on for UI elements pub fn new_managed( gpu_ctx: Arc<RwLock<Context>>, surface_name: super::surface::DisplayName, x: u32, y: u32, z: LayerZ, width: u32, height: u32, aruid: AppletResourceUserId, layer_flags: LayerFlags, buffer_count: u32, block_height: BlockLinearHeights, scaling: ScaleMode, ) -> Result<Self> { let raw_surface = Surface::new_managed( gpu_ctx, surface_name, aruid, layer_flags, x as f32, y as f32, z, width, height, buffer_count, block_height, ColorFormat::COLOR_FORMAT, ColorFormat::PIXEL_FORMAT, scaling, )?; Ok(Self { surface: raw_surface, _color_fmt: PhantomData, }) } /// Creates a new managed layer (application/applet window) that can be drawn on overlay elements. /// /// These layers exist on top of stray layers and application/applet UIs, and can be Z-order vertically layered over each other. /// The GPU provides the alpha blending for all layers based on the committed frame. #[inline(always)] pub fn new_stray( gpu_ctx: Arc<RwLock<Context>>, surface_name: super::surface::DisplayName, buffer_count: u32, block_height: BlockLinearHeights, ) -> Result<Self> { let raw_surface = Surface::new_stray( gpu_ctx, surface_name, buffer_count, block_height, ColorFormat::COLOR_FORMAT, ColorFormat::PIXEL_FORMAT, )?; Ok(Self { surface: raw_surface, _color_fmt: PhantomData, }) } /// Wait for a vsync event to ensure that the previously submitted frame has been fully rendered to the display. #[inline(always)] pub fn wait_vsync_event(&self, timeout: Option<i64>) -> Result<()> { self.surface.wait_vsync_event(timeout.unwrap_or(-1)) } /// Check out a canvas/framebuffer to draw a new frame. /// /// This frame is buffered to a linear buffer before being swizzled /// into the backing buffer during frame-commit. This provides better performance for line-based renderers /// as writes will be sequential in memory. There are cache misses during commit, but that is still better performance /// than mapped page churn for GPU-mapped memory. #[inline(always)] pub fn render<T>( &mut self, clear_color: Option<ColorFormat>, runner: impl Fn(&mut BufferedCanvas<'_, ColorFormat>) -> Result<T>, ) -> Result<T> { let (buffer, buffer_length, slot, _fence_present, fences) = self.surface.dequeue_buffer(false)?; let mut canvas = BufferedCanvas { slot, // This transmute is OK as we're only implementing this for types that are secretly just primitive ints linear_buf: Buffer::new( size_of::<u128>(), // we do this as the gob conversion is done in blocks of 8 bytes, casting each block to `*mut u128` buffer_length, )?, base_pointer: buffer as usize, fences, buffer_size: buffer_length, manager: self, }; if let Some(background_color) = clear_color { canvas.clear(background_color); } runner(&mut canvas) } /// Renders a pre-prepared buffer of pixels (represented by their color values) directly to the screen. /// /// A maximum of `(width * height)` pixels are read from the input buffer line-by-line to the screen. Extra /// pixels are discarded, and no error is returned for partial refreshes. pub fn render_prepared_buffer(&mut self, pixels: &[ColorFormat]) -> Result<()> { let height = self.surface.height() as usize; let width = self.surface.width() as usize; let (buffer, buffer_length, slot, _fence_present, fences) = self.surface.dequeue_buffer(false)?; let mut canvas = UnbufferedCanvas { slot, base_pointer: buffer as usize, fences, buffer_size: buffer_length, manager: self, }; for (index, pixel) in pixels.iter().cloned().take(height * width).enumerate() { canvas.draw_single( (index % width) as i32, (index / width) as i32, pixel, AlphaBlend::None, ); } Ok(()) } /// Check out a canvas/framebuffer to draw a new frame, without a linear buffer. /// /// This can be used in memory constrained environments such as sysmodules, but also provides slightly better performance /// for frames that draw in block rather than scan-lines (e.g. JPEG decoding). #[inline(always)] pub fn render_unbuffered<T>( &mut self, clear_color: Option<ColorFormat>, runner: impl Fn(&mut UnbufferedCanvas<'_, ColorFormat>) -> Result<T>, ) -> Result<T> { let (buffer, buffer_length, slot, _fence_present, fences) = self.surface.dequeue_buffer(false)?; let mut canvas = UnbufferedCanvas { slot, base_pointer: buffer as usize, fences, buffer_size: buffer_length, manager: self, }; if let Some(background_color) = clear_color { canvas.clear(background_color); } runner(&mut canvas) } } #[allow(clippy::too_many_arguments)] pub trait Canvas { type ColorFormat: sealed::CanvasColorFormat; /// Draw a single pixel to the canvas /// /// out-of-bounds co-ordinates should be ignored by the implementation. fn draw_single(&mut self, x: i32, y: i32, color: Self::ColorFormat, blend: AlphaBlend); fn height(&self) -> u32; fn width(&self) -> u32; fn clear(&mut self, color: Self::ColorFormat) { for y in 0..self.height() as i32 { for x in 0..self.width() as i32 { self.draw_single(x, y, color, AlphaBlend::None); } } } /// Draw a single-color rectangle to the canvas /// /// out-of-bounds co-ordinates should be ignored by the implementation. fn draw_rect( &mut self, x: i32, y: i32, width: u32, height: u32, color: Self::ColorFormat, blend: AlphaBlend, ) { let s_width = self.width() as i32; let s_height = self.height() as i32; let x0 = x.clamp(0, s_width); let x1 = x.saturating_add_unsigned(width).clamp(0, s_width); let y0 = y.clamp(0, s_height); let y1 = y.saturating_add_unsigned(height).clamp(0, s_height); for y in y0..y1 { for x in x0..x1 { self.draw_single(x, y, color, blend); } } } /// Draw a straight line from the start co-ordinates to the end co-ordinates /// /// Start/end co-ordinates may be outside the screen, but out-of-bounds pixel co-ordinates should be ignored by the implementation. fn draw_line( &mut self, start: (i32, i32), end: (i32, i32), width: u32, color: Self::ColorFormat, blend: AlphaBlend, ) { for (x, y) in line_drawing::Bresenham::new(start, end) { // TODO - fix this stupid algorithm self.draw_circle_filled(x, y, width, color, blend) } } /// Draw an empty circle from the centre co-ordinates and radius. /// /// The shape does not need to be fully in-bounds, but out-of-bounds pixel co-ordinates should be ignored by the implementation. fn draw_circle( &mut self, x: i32, y: i32, r: u32, line_width: u32, color: Self::ColorFormat, blend: AlphaBlend, ) { for (x, y) in line_drawing::BresenhamCircle::new(x, y, r as i32) { // TODO - fix this stupid algorithm self.draw_circle_filled(x, y, line_width, color, blend); } } /// Draw an filled circle from the centre co-ordinates and radius. /// /// The shape does not need to be fully in-bounds, but out-of-bounds pixel co-ordinates should be ignored by the implementation. fn draw_circle_filled( &mut self, cx: i32, cy: i32, r: u32, color: Self::ColorFormat, blend: AlphaBlend, ) { for row in cy.saturating_sub(r as i32)..cy.saturating_add(r as i32) { if (0..self.height() as i32).contains(&row) { // Find the width of the row to draw using a rearranged pythagoras's theorem. // Uses i64s internally as it should all be in registers (no extra memory use) // and the squaring of an i32 should never overflow an i64 let x_width = ((r as i64).pow(2) - ((row - cy) as i64).pow(2)).isqrt() as i32; for column in cx.saturating_sub(x_width)..cx.saturating_add(x_width) { if (0..self.width() as i32).contains(&column) { self.draw_single(column, row, color, blend); } } } } } /// Draw text in a true-type font to the canvas. /// /// The text does not need to be fully in-bounds, but out-of-bounds pixel co-ordinates should be ignored by the implementation. #[cfg(feature = "truetype")] fn draw_font_text( &mut self, font: &Font, text: impl AsRef<str>, color: Self::ColorFormat, size: f32, x: i32, y: i32, blend: AlphaBlend, ) { use ab_glyph::{Font, Glyph, Point, ScaleFont}; use alloc::vec::Vec; let text = text.as_ref(); let position: Point = (x as f32, y as f32).into(); let scale = font.pt_to_px_scale(size).unwrap(); let font = font.as_scaled(scale); let v_advance = font.height() + font.line_gap(); let mut caret = position + ab_glyph::point(0.0, font.ascent()); let mut last_glyph: Option<Glyph> = None; let mut target: Vec<Glyph> = Vec::new(); for c in text.chars() { if c.is_control() { if c == '\n' { caret = ab_glyph::point(position.x, caret.y + v_advance); last_glyph = None; } continue; } let mut glyph = font.scaled_glyph(c); if let Some(previous) = last_glyph.take() { caret.x += font.kern(previous.id, glyph.id); } glyph.position = caret; last_glyph = Some(glyph.clone()); caret.x += font.h_advance(glyph.id); if !c.is_whitespace() && caret.x > position.x + self.width() as f32 { caret = ab_glyph::point(position.x, caret.y + v_advance); glyph.position = caret; last_glyph = None; } target.push(glyph); } for glyph in target { if let Some(outline) = font.outline_glyph(glyph) { let bounds = outline.px_bounds(); outline.draw(|d_x, d_y, c| { if c > 0.2 { // we don't want to cover subpixel issues, so we're just not going to color the pixel unless it's >20% covered. let pix_color = color.scale_alpha(c); self.draw_single( bounds.min.x as i32 + d_x as i32, bounds.min.y as i32 + d_y as i32, pix_color, blend, ); } }); } } } /// Draw text in a 8x8 monospace font to the canvas. /// /// The text does not need to be fully in-bounds, but out-of-bounds pixel co-ordinates should be ignored by the implementation. #[cfg(feature = "fonts")] #[inline(always)] fn draw_ascii_bitmap_text( &mut self, text: impl AsRef<str>, color: Self::ColorFormat, scale: u32, x: i32, y: i32, blend: AlphaBlend, ) { self.draw_bitmap_text(text, &font8x8::BASIC_FONTS, color, scale, x, y, blend); } /// Draw text to the canvas, with a unicode font from the [`font8x8`] crate. /// /// The text does not need to be fully in-bounds, but out-of-bounds pixel co-ordinates should be ignored by the implementation. #[cfg(feature = "fonts")] fn draw_bitmap_text( &mut self, text: impl AsRef<str>, character_set: &font8x8::unicode::BasicFonts, color: Self::ColorFormat, scale: u32, x: i32, y: i32, blend: AlphaBlend, ) { use font8x8::UnicodeFonts; let text = text.as_ref(); let mut tmp_x = x; let mut tmp_y = y; for c in text.chars() { match c { '\r' => { // carriage return moves the caret to the start of the line tmp_x = x; } '\n' => { // new line uses unix convention, advancing the line and moving the caret to the start of the line tmp_y = tmp_y.saturating_add_unsigned(8 * scale); tmp_x = x; } _ => { if let Some(glyph) = character_set.get(c) { let char_tmp_x = tmp_x; let char_tmp_y = tmp_y; for gx in glyph.into_iter() { for bit in 0..8 { match gx & (1 << bit) { 0 => {} _ => { self.draw_rect(tmp_x, tmp_y, scale, scale, color, blend); } } tmp_x += scale as i32; } tmp_y += scale as i32; tmp_x = char_tmp_x; } tmp_x = tmp_x.saturating_add_unsigned(8 * scale); tmp_y = char_tmp_y; } } } } } } pub struct BufferedCanvas<'fb, ColorFormat: sealed::CanvasColorFormat> { slot: i32, linear_buf: Buffer<u8>, base_pointer: usize, buffer_size: usize, fences: MultiFence, manager: &'fb mut CanvasManager<ColorFormat>, } impl<ColorFormat: sealed::CanvasColorFormat> BufferedCanvas<'_, ColorFormat> { /// Write from the pixel buffer to the backing framebuffer in a memory efficient way for GPU page boundaries. fn convert_buffers(&mut self) { let block_config: BlockLinearHeights = self.manager.surface.get_block_linear_config(); let block_height_gobs = block_config.block_height(); let block_height_px = block_config.block_height_bytes(); let mut out_buf = self.base_pointer as *mut u8; let in_buf = self.linear_buf.ptr as *const u8; let pitch = self.manager.surface.pitch(); let height = self.manager.surface.height(); let width_blocks = pitch >> 6; let height_blocks = align_up!(self.height(), block_config.block_height()) / block_config.block_height(); for block_y in 0..height_blocks { for block_x in 0..width_blocks { for gob_y in 0..block_height_gobs { unsafe { let x = block_x * 64; let y = block_y * block_height_px + gob_y * 8; if y < height { let in_gob_buf = in_buf.add((y * pitch + x) as usize); Self::convert_buffers_gob_impl(out_buf, in_gob_buf, pitch); } out_buf = out_buf.add(512); } } } } } /// Converts a pointer to a linear block to Generic16Bx2 sector ordering. fn convert_buffers_gob_impl(out_gob_buf: *mut u8, in_gob_buf: *const u8, stride: u32) { unsafe { let mut out_gob_buf_128 = out_gob_buf as *mut u128; for i in 0..32 { let y = ((i >> 1) & 0x6) | (i & 0x1); let x = ((i << 3) & 0x10) | ((i << 1) & 0x20); let in_gob_buf_128 = in_gob_buf.offset((y * stride + x) as isize) as *const u128; core::ptr::copy(in_gob_buf_128, out_gob_buf_128, 1); out_gob_buf_128 = out_gob_buf_128.add(1); } } } } impl<ColorFormat: CanvasColorFormat> Canvas for BufferedCanvas<'_, ColorFormat> { type ColorFormat = ColorFormat; fn clear(&mut self, color: Self::ColorFormat) { let raw_color: <ColorFormat as CanvasColorFormat>::RawType = color.to_raw(); let raw_buffer: &mut [<ColorFormat as CanvasColorFormat>::RawType] = unsafe { core::slice::from_raw_parts_mut( self.linear_buf.ptr as *mut <ColorFormat as CanvasColorFormat>::RawType, self.linear_buf.layout.size() / <ColorFormat as CanvasColorFormat>::BYTES_PER_PIXEL as usize, ) }; for pixel_slot in raw_buffer.iter_mut() { *pixel_slot = raw_color; } } fn height(&self) -> u32 { self.manager.surface.height() } fn width(&self) -> u32 { self.manager.surface.width() } fn draw_single(&mut self, x: i32, y: i32, color: ColorFormat, blend: AlphaBlend) { if !(0..self.manager.surface.width() as i32).contains(&x) || !(0..self.manager.surface.height() as i32).contains(&y) { return; } let pixel_offset = (self.manager.surface.pitch() * y as u32 + x as u32 * ColorFormat::COLOR_FORMAT.bytes_per_pixel()) as usize; debug_assert!( pixel_offset < self.buffer_size, "in-bounds pixels should never lead to out-of bounds reads/writes" ); let out_color = color.blend_with( ColorFormat::from_raw(unsafe { core::ptr::read(self.linear_buf.ptr.add(pixel_offset) as *mut ColorFormat::RawType) }), blend, ); // SAFETY - we know get_unchecked access below is OK as we have checked the dimensions unsafe { core::ptr::write( self.linear_buf.ptr.add(pixel_offset) as *mut ColorFormat::RawType, out_color.to_raw(), ) }; } } impl<ColorFormat: CanvasColorFormat> Drop for BufferedCanvas<'_, ColorFormat> { fn drop(&mut self) { self.convert_buffers(); arm::cache_flush(self.base_pointer as *mut u8, self.buffer_size); let _ = self.manager.surface.queue_buffer(self.slot, self.fences); let _ = self.manager.surface.wait_buffer_event(-1); } } /// A Canvas where draws are directly written to the backing framebuffer memory. /// /// Users of this object are expected to write to the screen efficiently to manage memory controller pressure, /// or to accept lower performance for lower memory usage. pub struct UnbufferedCanvas<'fb, ColorFormat: sealed::CanvasColorFormat> { slot: i32, base_pointer: usize, buffer_size: usize, fences: MultiFence, manager: &'fb mut CanvasManager<ColorFormat>, } impl<ColorFormat: sealed::CanvasColorFormat> UnbufferedCanvas<'_, ColorFormat> { /// Gets a mutable reference to the raw framebuffer pub fn raw_buffer(&mut self) -> &mut [ColorFormat::RawType] { unsafe { core::slice::from_raw_parts_mut( core::ptr::with_exposed_provenance_mut(self.base_pointer), self.buffer_size / core::mem::size_of::<ColorFormat::RawType>(), ) } } pub fn draw_single(&mut self, x: i32, y: i32, color: ColorFormat, blend: AlphaBlend) { if !(0..self.manager.surface.width() as i32).contains(&x) || !(0..self.manager.surface.height() as i32).contains(&y) { return; } let pixel_offset = self.xy_to_gob_pixel_offset(x as u32, y as u32); debug_assert!( pixel_offset * (ColorFormat::COLOR_FORMAT.bytes_per_pixel() as usize) < self.buffer_size, "pixel offset is outside the buffer" ); let pixel_pointer = unsafe { (self.base_pointer as *mut ColorFormat::RawType).add(pixel_offset) }; // SAFETY: These reads/writes as: // 1 - we allocated it when creating the surface so the base pointer is not null and pixel-aligned // 2 - we only allow 2-byte and 4-byte color formats, so we will never have a pixel that spans the // over the edge of a bit-swizzling boundary of the block linear format's GOBs. unsafe { let old_pixel = core::ptr::read(pixel_pointer); core::ptr::write( pixel_pointer, color .blend_with(ColorFormat::from_raw(old_pixel), blend) .to_raw(), ); } } /// Calculate the actual offset of the pixel in the swizzled framebuffer from the x/y co-ordinates. fn xy_to_gob_pixel_offset(&self, x: u32, y: u32) -> usize { let block_config = self.manager.surface.get_block_linear_config(); let block_height = block_config.block_height(); let mut gob_offset = (y / (8 * block_height)) * 512 * block_height * (self.manager.surface.pitch() / 64) + (x * ColorFormat::COLOR_FORMAT.bytes_per_pixel() / 64) * 512 * block_height + (y % (8 * block_height) / 8) * 512; // Figure 46 in the TRM is in pixel space, even though each GOB in a block is sequential in memory. // This means that each 64bytes of a row (y1 == y2) are separated by `64 x 8 x block_height` bytes, // so the `x` value in figure 47 will be (x * bytes_per_pixel)%64, and `y` will be (y%8) let x = (x * ColorFormat::COLOR_FORMAT.bytes_per_pixel()) % 64; let y = y % 8; gob_offset += ((x % 64) / 32) * 256 + ((y % 8) / 2) * 64 + ((x % 32) / 16) * 32 + (y % 2) * 16 + (x % 16); (gob_offset / ColorFormat::COLOR_FORMAT.bytes_per_pixel()) as usize } } impl<ColorFormat: sealed::CanvasColorFormat> Canvas for UnbufferedCanvas<'_, ColorFormat> { type ColorFormat = ColorFormat; fn draw_single(&mut self, x: i32, y: i32, color: Self::ColorFormat, blend: AlphaBlend) { self.draw_single(x, y, color, blend); } fn clear(&mut self, color: Self::ColorFormat) { let raw_color: <ColorFormat as CanvasColorFormat>::RawType = color.to_raw(); let raw_buffer: &mut [<ColorFormat as CanvasColorFormat>::RawType] = unsafe { core::slice::from_raw_parts_mut( self.base_pointer as *mut <ColorFormat as CanvasColorFormat>::RawType, (self.manager.surface.single_buffer_size() / <ColorFormat as CanvasColorFormat>::BYTES_PER_PIXEL) as usize, ) }; let _: () = raw_buffer .iter_mut() .map(|pixel_slot| *pixel_slot = raw_color) .collect(); } fn width(&self) -> u32 { self.manager.surface.width() } fn height(&self) -> u32 { self.manager.surface.height() } } impl<ColorFormat: CanvasColorFormat> Drop for UnbufferedCanvas<'_, ColorFormat> { fn drop(&mut self) { arm::cache_flush(self.base_pointer as *mut u8, self.buffer_size); let _ = self.manager.surface.queue_buffer(self.slot, self.fences); let _ = self.manager.surface.wait_buffer_event(-1); } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/gpu/ioctl.rs
src/gpu/ioctl.rs
//! `ioctl` command definitions and support use super::*; use crate::service::nv; /// Represents one of the available fds /// /// Note that only the ones used so far in this library are present #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum IoctlFd { /// The ioctl fd for "/dev/nvhost-as-gpu" NvHost, /// The ioctl fd for "/dev/nvmap" NvMap, /// The ioctl fd for "/dev/nvhost-ctrl" NvHostCtrl, } /// Represents a type trait defining an `ioctl` command pub trait Ioctl { /// Gets the [`IoctlId`][`nv::IoctlId`] of this command fn get_id() -> nv::IoctlId; /// Gets the [`IoctlFd`] of this command fn get_fd() -> IoctlFd; } /// Represents the `Create` command for [`NvMap`][`IoctlFd::NvMap`] fd /// /// See <https://switchbrew.org/wiki/NV_services#NVMAP_IOC_CREATE> #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct NvMapCreate { /// The input map size pub size: u32, /// The output handle pub handle: u32, } impl Ioctl for NvMapCreate { fn get_id() -> nv::IoctlId { nv::IoctlId::NvMapCreate } fn get_fd() -> IoctlFd { IoctlFd::NvMap } } /// Represents the `FromId` command for [`NvMap`][`IoctlFd::NvMap`] fd /// /// See <https://switchbrew.org/wiki/NV_services#NVMAP_IOC_FROM_ID> #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct NvMapFromId { /// The input ID pub id: u32, /// The output handle pub handle: u32, } impl Ioctl for NvMapFromId { fn get_id() -> nv::IoctlId { nv::IoctlId::NvMapFromId } fn get_fd() -> IoctlFd { IoctlFd::NvMap } } /// Represents flags used in [`NvMapAlloc`] commands #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u32)] pub enum AllocFlags { /// The Nv driver server can only read the mapped data #[default] ReadOnly = 0, /// The Nv driver server can both read and write to the mapped data area ReadWrite = 1, } /// Represents the `Alloc` command for [`NvMap`][`IoctlFd::NvMap`] fd /// /// See <https://switchbrew.org/wiki/NV_services#NVMAP_IOC_ALLOC> #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct NvMapAlloc { /// The input handle pub handle: u32, /// The input heap mask pub heap_mask: u32, /// The input [`AllocFlags`] pub flags: AllocFlags, /// The input align pub align: u32, /// The input [`Kind`] pub kind: Kind, /// Padding pub pad: [u8; 4], /// The input address pub address: usize, } impl Ioctl for NvMapAlloc { fn get_id() -> nv::IoctlId { nv::IoctlId::NvMapAlloc } fn get_fd() -> IoctlFd { IoctlFd::NvMap } } /// Represents the `GetId` command for [`NvMap`][`IoctlFd::NvMap`] fd /// /// See <https://switchbrew.org/wiki/NV_services#NVMAP_IOC_GET_ID> #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct NvMapGetId { /// The output ID pub id: u32, /// The input handle pub handle: u32, } impl Ioctl for NvMapGetId { fn get_id() -> nv::IoctlId { nv::IoctlId::NvMapGetId } fn get_fd() -> IoctlFd { IoctlFd::NvMap } } /// Represents the `Free` command for [`NvMap`][`IoctlFd::NvMap`] fd /// /// See <https://switchbrew.org/wiki/NV_services#NVMAP_IOC_FREE> #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct NvMapFree { /// The input handle pub handle: u32, /// padding to guarantee 8-byte offset for address pub _pad: u32, /// address of the buffer pub address: usize, /// size of the buffer pub size: u32, /// flags for the opened handle (1 if requested as uncached) pub flags: u32, } impl Ioctl for NvMapFree { fn get_id() -> nv::IoctlId { nv::IoctlId::NvMapFree } fn get_fd() -> IoctlFd { IoctlFd::NvMap } } /// Represents the `SyncptWait` command for [`NvHostCtrl`][`IoctlFd::NvHostCtrl`] fd /// /// See <https://switchbrew.org/wiki/NV_services#NVHOST_IOCTL_CTRL_SYNCPT_WAIT> #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct NvHostCtrlSyncptWait { /// The input [`Fence`] pub fence: Fence, /// The input timeout pub timeout: i32, } impl Ioctl for NvHostCtrlSyncptWait { fn get_id() -> nv::IoctlId { nv::IoctlId::NvHostCtrlSyncptWait } fn get_fd() -> IoctlFd { IoctlFd::NvHostCtrl } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/gpu/rc.rs
src/gpu/rc.rs
//! GPU-specific result definitions use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 500; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { NvErrorCodeInvalid: 1, NvErrorCodeNotImplemented: 2, NvErrorCodeNotSupported: 3, NvErrorCodeNotInitialized: 4, NvErrorCodeInvalidParameter: 5, NvErrorCodeTimeOut: 6, NvErrorCodeInsufficientMemory: 7, NvErrorCodeReadOnlyAttribute: 8, NvErrorCodeInvalidState: 9, NvErrorCodeInvalidAddress: 10, NvErrorCodeInvalidSize: 11, NvErrorCodeInvalidValue: 12, NvErrorCodeAlreadyAllocated: 13, NvErrorCodeBusy: 14, NvErrorCodeResourceError: 15, NvErrorCodeCountMismatch: 16, NvErrorCodeSharedMemoryTooSmall: 17, NvErrorCodeFileOperationFailed: 18, NvErrorCodeIoctlFailed: 19 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/gpu/parcel.rs
src/gpu/parcel.rs
//! Parcel support and utils use alloc::vec::Vec; use crate::result::*; use crate::service::dispdrv::BinderHandle; use crate::util; use core::ptr; pub mod rc; /// Represents a parcel header layout #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct ParcelHeader { /// The payload size pub payload_size: u32, /// The payload offset pub payload_offset: u32, /// The object list size pub objects_size: u32, /// The object list offset pub objects_offset: u32, } impl ParcelHeader { /// Creates a new, empty [`ParcelHeader`] #[inline] pub const fn new() -> Self { Self { payload_size: 0, payload_offset: 0, objects_size: 0, objects_offset: 0, } } } const PAYLOAD_SIZE: usize = 0x200; /// Represents a parcel payload layout /// /// Note that a parcel payload length is variable, but we use a maximum size for this type #[derive(Copy, Clone)] #[repr(C)] pub struct ParcelPayload { /// The header pub header: ParcelHeader, /// The actual payload pub payload: [u8; PAYLOAD_SIZE], } impl ParcelPayload { /// Creates a new, empty [`ParcelPayload`] #[inline] pub const fn new() -> Self { Self { header: ParcelHeader::new(), payload: [0; PAYLOAD_SIZE], } } } impl Default for ParcelPayload { fn default() -> Self { Self::new() } } /// Carrier for the layer's parameters. Used to receive the layer's binder handle. #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct ParcelData { /// The parcel type, usually `0x2` pub parcel_type: u32, /// Unknown, maybe the process ID pub unk_maybe_pid: u32, /// Binder handle pub handle: BinderHandle, /// Unknown, usually zeros pub unk_zero: [u8; 0xC], /// NUL-terminated string containing `"dispdrv\0"` pub dispdrv_str: util::ArrayString<0x8>, /// Unknown, usually zeros pub unk_zero_2: [u8; 8], } /// Represents a wrapper for simple parcel reading/writing pub struct Parcel { payload: ParcelPayload, read_offset: usize, write_offset: usize, } impl Parcel { /// Creates a new [`Parcel`] #[inline] pub const fn new() -> Self { Self { payload: ParcelPayload::new(), read_offset: 0, write_offset: 0, } } /// Reads raw, unaligned data /// /// # Arguments /// /// * `out_data`: Out data buffer /// * `data_size`: Out data size /// /// # Safety /// /// The caller is responsible for providing a pointer valid to write `out_size` bytes pub unsafe fn read_raw_unaligned(&mut self, out_data: *mut u8, data_size: usize) -> Result<()> { result_return_if!( (self.read_offset + data_size) > PAYLOAD_SIZE, rc::ResultNotEnoughReadSpace ); unsafe { ptr::copy( self.payload.payload.as_mut_ptr().add(self.read_offset), out_data, data_size, ); } self.read_offset += data_size; Ok(()) } /// Reads raw (aligned) data /// /// This essentially aligns up the read size to a 4-byte align /// /// # Arguments /// /// * `out_data`: Out data buffer /// * `data_size`: Out data size /// /// # Safety /// /// The caller is responsible for providing a pointer valid to write `out_size` bytes #[inline] pub unsafe fn read_raw(&mut self, out_data: *mut u8, data_size: usize) -> Result<()> { unsafe { self.read_raw_unaligned(out_data, data_size) }?; self.read_offset += (align_up!(data_size, 4usize) - data_size); Ok(()) } /// Writes raw, unaligned data /// /// # Arguments /// /// * `data`: In data buffer /// * `data_size`: In data size /// /// # Safety /// /// The caller is responsible for providing a pointer valid to read `out_size` bytes pub unsafe fn write_raw_unaligned(&mut self, data: *const u8, data_size: usize) -> Result<()> { result_return_if!( (self.write_offset + data_size) > PAYLOAD_SIZE, rc::ResultNotEnoughWriteSpace ); unsafe { ptr::copy( data, self.payload.payload.as_mut_ptr().add(self.write_offset), data_size, ); } self.write_offset += data_size; Ok(()) } /// Reserves a certain (aligned) size at the payload, to be written later (returning the corresponding buffer) /// /// # Arguments /// /// * `data_size`: Out data size pub fn write_reserve_raw(&mut self, data_size: usize) -> Result<*mut u8> { let actual_size = align_up!(data_size, 4usize); result_return_if!( (self.write_offset + actual_size) > PAYLOAD_SIZE, rc::ResultNotEnoughWriteSpace ); let buf = unsafe { self.payload.payload.as_mut_ptr().add(self.write_offset) }; self.write_offset += actual_size; Ok(buf) } /// Writes raw (aligned) data /// /// This essentially aligns up the write size to a 4-byte alignment in the buffer /// /// # Arguments /// /// * `data`: In data buffer /// * `data_size`: In data size /// /// # Safety /// /// The caller must provide a pointer valid for reading `data_size` bytes #[inline] pub unsafe fn write_raw(&mut self, data: *const u8, data_size: usize) -> Result<()> { unsafe { self.write_raw_unaligned(data, data_size) }?; self.write_offset += (align_up!(data_size, 4usize) - data_size); Ok(()) } /// Writes an unaligned value /// /// # Arguments /// /// * `t`: The value #[inline] pub fn write_unaligned<T>(&mut self, t: T) -> Result<()> { unsafe { self.write_raw_unaligned((&raw const t).cast(), size_of::<T>()) } } /// Writes a value (aligned) /// /// # Arguments /// /// * `t`: The value #[inline] pub fn write<T: Copy>(&mut self, t: T) -> Result<()> { unsafe { self.write_raw((&raw const t).cast(), size_of::<T>()) } } /// Reads an unaligned value pub fn read_unaligned<T>(&mut self) -> Result<T> { unsafe { let mut t: T = core::mem::zeroed(); self.read_raw_unaligned((&raw mut t).cast(), size_of::<T>())?; Ok(t) } } /// Reads a value (aligned to a 4-byte word) pub fn read<T: Copy>(&mut self) -> Result<T> { unsafe { let mut t: T = core::mem::zeroed(); self.read_raw((&raw mut t).cast(), size_of::<T>())?; Ok(t) } } /// Writes a string /// /// Note that strings are internally (de)serialized as NUL-terminated UTF-16 /// /// # Arguments /// /// * `string`: The string to write pub fn write_str(&mut self, string: &str) -> Result<()> { let encoded: Vec<u16> = string.encode_utf16().collect(); let len = encoded.len(); self.write(len as u32)?; let str_write_buf = self.write_reserve_raw((len + 1) * 2)? as *mut u16; unsafe { core::ptr::copy(encoded.as_ptr(), str_write_buf, encoded.len()) }; Ok(()) } /// Writes an interface token /// /// # Arguments /// /// * `token`: The interface token name pub fn write_interface_token(&mut self, token: &str) -> Result<()> { let value: u32 = 0x100; self.write(value)?; self.write_str(token) } /// Reads raw sized data /// /// For sized data, the data is preceded by its size /// /// # Arguments /// /// * `out_data`: Out data buffer /// * `out_size`: The maximum size in bytes that can be read into `out_data` /// /// # Safety /// /// The caller is responsible for providing a pointer valid to read `out_size` bytes pub unsafe fn read_sized_raw(&mut self, out_data: *mut u8, out_size: usize) -> Result<usize> { let len = self.read::<i32>()? as usize; result_return_unless!(len <= out_size, rc::ResultReadSizeMismatch); let fd_count = self.read::<i32>()?; result_return_unless!(fd_count == 0, rc::ResultFdsNotSupported); unsafe { self.read_raw(out_data, len)?; } Ok(len) } /// Reads a value as sized data /// /// This verifies that the read data is at least big enough to contain the value type, returning [`ResultReadSizeMismatch`][`rc::ResultReadSizeMismatch`] otherwise pub fn read_sized<T: Default + Copy>(&mut self) -> Result<T> { let mut t: T = Default::default(); let _len = unsafe { self.read_sized_raw((&raw mut t).cast(), size_of::<T>())? }; Ok(t) } /// Writes raw sized data /// /// # Arguments /// /// * `data`: In data buffer /// * `data size`: In data size /// /// # Safety /// /// The caller must provide a pointer valid for reading `data_size` bytes pub unsafe fn write_sized_raw(&mut self, data: *const u8, data_size: usize) -> Result<()> { let len = data_size as i32; self.write(len)?; let fd_count: i32 = 0; self.write(fd_count)?; unsafe { self.write_raw(data, data_size)? }; Ok(()) } /// Writes a value as sized data /// /// # Arguments /// /// * `t`: The value to write #[inline] pub fn write_sized<T: Copy>(&mut self, t: T) -> Result<()> { unsafe { self.write_sized_raw((&raw const t).cast(), size_of::<T>()) } } /// Loads an external payload in this [`Parcel`] /// /// # Arguments /// /// * `payload`: The payload pub fn load_from(&mut self, payload: ParcelPayload) { self.payload = payload; self.read_offset = 0; self.write_offset = payload.header.payload_size as usize; } /// Finishes writing and produces the payload /// /// Essentially populates the payload header and returns the current payload, along with its size pub fn end_write(&mut self) -> Result<(ParcelPayload, usize)> { self.payload.header.payload_size = self.write_offset as u32; self.payload.header.payload_offset = size_of::<ParcelHeader>() as u32; let payload_len = self.payload.header.payload_offset + self.payload.header.payload_size; self.payload.header.objects_offset = payload_len; self.payload.header.objects_size = 0; Ok((self.payload, payload_len as usize)) } } impl Default for Parcel { fn default() -> Self { Self::new() } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/gpu/binder.rs
src/gpu/binder.rs
//! Binder support and utils use super::*; use crate::gpu::parcel; use crate::ipc::sf; use crate::service::dispdrv; pub mod rc; /// Represents the interface token used for parcel transactions pub const INTERFACE_TOKEN: &str = "android.gui.IGraphicBufferProducer"; /// Represents binder error code values. /// See: 🤷 TODO: Find where these values come from. They're different than libnx. #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(i32)] #[allow(missing_docs)] pub enum ErrorCode { #[default] Success = 0, PermissionDenied = -1, NameNotFound = -2, WouldBlock = -11, NoMemory = -12, AlreadyExists = -17, NoInit = -19, BadValue = -22, DeadObject = -32, InvalidOperation = -38, NotEnoughData = -61, UnknownTransaction = -74, BadIndex = -75, TimeOut = -110, FdsNotAllowed = -2147483641, FailedTransaction = -2147483646, BadType = -2147483647, } /// Converts [`ErrorCode`]s to result values #[allow(unreachable_patterns)] pub fn convert_nv_error_code(err: ErrorCode) -> Result<()> { match err { ErrorCode::Success => Ok(()), ErrorCode::PermissionDenied => rc::ResultErrorCodePermissionDenied::make_err(), ErrorCode::NameNotFound => rc::ResultErrorCodeNameNotFound::make_err(), ErrorCode::WouldBlock => rc::ResultErrorCodeWouldBlock::make_err(), ErrorCode::NoMemory => rc::ResultErrorCodeNoMemory::make_err(), ErrorCode::AlreadyExists => rc::ResultErrorCodeAlreadyExists::make_err(), ErrorCode::NoInit => rc::ResultErrorCodeNoInit::make_err(), ErrorCode::BadValue => rc::ResultErrorCodeBadValue::make_err(), ErrorCode::DeadObject => rc::ResultErrorCodeDeadObject::make_err(), ErrorCode::InvalidOperation => rc::ResultErrorCodeInvalidOperation::make_err(), ErrorCode::NotEnoughData => rc::ResultErrorCodeNotEnoughData::make_err(), ErrorCode::UnknownTransaction => rc::ResultErrorCodeUnknownTransaction::make_err(), ErrorCode::BadIndex => rc::ResultErrorCodeBadIndex::make_err(), ErrorCode::TimeOut => rc::ResultErrorCodeTimeOut::make_err(), ErrorCode::FdsNotAllowed => rc::ResultErrorCodeFdsNotAllowed::make_err(), ErrorCode::FailedTransaction => rc::ResultErrorCodeFailedTransaction::make_err(), ErrorCode::BadType => rc::ResultErrorCodeBadType::make_err(), _ => rc::ResultErrorCodeInvalid::make_err(), } } /// Represents a binder object, wrapping transaction functionality pub struct Binder { handle: dispdrv::BinderHandle, hos_binder_driver: Arc<dyn dispdrv::IHOSBinderDriverClient>, } impl Binder { /// Creates a new [`Binder`] /// /// # Arguments /// /// * `handle`: Binder handle to use /// * `hos_binder_driver`: [`IHOSBinderDriver`][`dispdrv::IHOSBinderDriverClient`] object #[inline] pub const fn new( handle: dispdrv::BinderHandle, hos_binder_driver: Arc<dyn dispdrv::IHOSBinderDriverClient>, ) -> Result<Self> { Ok(Self { handle, hos_binder_driver, }) } fn transact_parcel_begin(&self, parcel: &mut parcel::Parcel) -> Result<()> { parcel.write_interface_token(INTERFACE_TOKEN) } fn transact_parcel_check_err(&mut self, parcel: &mut parcel::Parcel) -> Result<()> { let err: ErrorCode = parcel.read()?; convert_nv_error_code(err)?; Ok(()) } fn transact_parcel_impl( &mut self, transaction_id: dispdrv::ParcelTransactionId, payload: parcel::ParcelPayload, ) -> Result<parcel::Parcel> { let mut response_payload = parcel::ParcelPayload::new(); self.hos_binder_driver.transact_parcel( self.handle, transaction_id, 0, sf::Buffer::from_other_var(&payload), sf::Buffer::from_other_mut_var(&mut response_payload), )?; let mut parcel = parcel::Parcel::new(); parcel.load_from(response_payload); Ok(parcel) } fn transact_parcel( &mut self, transaction_id: dispdrv::ParcelTransactionId, parcel: &mut parcel::Parcel, ) -> Result<parcel::Parcel> { let (payload, _payload_size) = parcel.end_write()?; self.transact_parcel_impl(transaction_id, payload) } /// Gets this [`Binder`]'s handle #[inline] pub fn get_handle(&self) -> dispdrv::BinderHandle { self.handle } /// Gets this [`Binder`]'s underlying [`IHOSBinderDriverClient`][`dispdrv::IHOSBinderDriverClient`] object pub fn get_hos_binder_driver(&self) -> Arc<dyn dispdrv::IHOSBinderDriverClient> { self.hos_binder_driver.clone() } /// Increases the [`Binder`]'s reference counts pub fn increase_refcounts(&mut self) -> Result<()> { self.hos_binder_driver .adjust_refcount(self.handle, 1, dispdrv::RefcountType::Weak)?; self.hos_binder_driver .adjust_refcount(self.handle, 1, dispdrv::RefcountType::Strong) } /// Decreases the [`Binder`]'s reference counts pub fn decrease_refcounts(&mut self) -> Result<()> { self.hos_binder_driver .adjust_refcount(self.handle, -1, dispdrv::RefcountType::Weak)?; self.hos_binder_driver .adjust_refcount(self.handle, -1, dispdrv::RefcountType::Strong) } /// Performs a connection /// /// # Arguments /// /// * `api`: The connection API to use /// * `producer_controlled_by_app`: Whether the producer is controlled by the process itself pub fn connect( &mut self, api: ConnectionApi, producer_controlled_by_app: bool, ) -> Result<QueueBufferOutput> { let mut parcel = parcel::Parcel::new(); self.transact_parcel_begin(&mut parcel)?; let producer_listener: u32 = 0; parcel.write(producer_listener)?; parcel.write(api)?; parcel.write(producer_controlled_by_app as u32)?; let mut response_parcel = self.transact_parcel(dispdrv::ParcelTransactionId::Connect, &mut parcel)?; let qbo: QueueBufferOutput = response_parcel.read()?; self.transact_parcel_check_err(&mut response_parcel)?; Ok(qbo) } /// Performs a disconnection /// /// # Arguments /// /// * `api`: The connection API /// * `mode`: The disconnection mode pub fn disconnect(&mut self, api: ConnectionApi, mode: DisconnectMode) -> Result<()> { let mut parcel = parcel::Parcel::new(); self.transact_parcel_begin(&mut parcel)?; parcel.write(api)?; parcel.write(mode)?; let mut response_parcel = self.transact_parcel(dispdrv::ParcelTransactionId::Disconnect, &mut parcel)?; self.transact_parcel_check_err(&mut response_parcel)?; Ok(()) } /// Sets a preallocated buffer /// /// # Arguments /// /// * `slot`: The buffer slot /// * `buf`: The buffer pub fn set_preallocated_buffer(&mut self, slot: i32, buf: GraphicBuffer) -> Result<()> { let mut parcel = parcel::Parcel::new(); self.transact_parcel_begin(&mut parcel)?; parcel.write(slot)?; let has_input = true; parcel.write(has_input as u32)?; if has_input { parcel.write_sized(buf)?; } self.transact_parcel( dispdrv::ParcelTransactionId::SetPreallocatedBuffer, &mut parcel, )?; Ok(()) } /// Requests a buffer at a given slot /// /// This also returns whether the buffer is non-null /// /// # Arguments /// /// * `slot`: The slot pub fn request_buffer(&mut self, slot: i32) -> Result<(bool, GraphicBuffer)> { let mut parcel = parcel::Parcel::new(); self.transact_parcel_begin(&mut parcel)?; parcel.write(slot)?; let mut response_parcel = self.transact_parcel(dispdrv::ParcelTransactionId::RequestBuffer, &mut parcel)?; let non_null_v: u32 = response_parcel.read()?; let non_null = non_null_v != 0; let mut gfx_buf: GraphicBuffer = Default::default(); if non_null { gfx_buf = response_parcel.read_sized()?; } self.transact_parcel_check_err(&mut response_parcel)?; Ok((non_null, gfx_buf)) } /// Dequeues a buffer /// /// # Arguments /// /// * `is_async`: Whether the dequeue is asynchronous /// * `width`: The width /// * `height`: The height /// * `get_frame_timestamps`: Whether to get frame timestamps /// * `usage`: [`GraphicsAllocatorUsage`] value pub fn dequeue_buffer( &mut self, is_async: bool, width: u32, height: u32, get_frame_timestamps: bool, usage: GraphicsAllocatorUsage, ) -> Result<(i32, bool, MultiFence)> { let mut parcel = parcel::Parcel::new(); self.transact_parcel_begin(&mut parcel)?; parcel.write(is_async as u32)?; parcel.write(width)?; parcel.write(height)?; parcel.write(get_frame_timestamps as u32)?; parcel.write(usage)?; let mut response_parcel = self.transact_parcel(dispdrv::ParcelTransactionId::DequeueBuffer, &mut parcel)?; let slot: i32 = response_parcel.read()?; let has_fences_v: u32 = response_parcel.read()?; let has_fences = has_fences_v != 0; let mut fences: MultiFence = Default::default(); if has_fences { fences = response_parcel.read_sized()?; } self.transact_parcel_check_err(&mut response_parcel)?; Ok((slot, has_fences, fences)) } /// Queues a buffer /// /// # Arguments /// /// * `slot`: The slot /// * `qbi`: The input layout pub fn queue_buffer(&mut self, slot: i32, qbi: QueueBufferInput) -> Result<QueueBufferOutput> { let mut parcel = parcel::Parcel::new(); self.transact_parcel_begin(&mut parcel)?; parcel.write(slot)?; parcel.write_sized(qbi)?; let mut response_parcel = self.transact_parcel(dispdrv::ParcelTransactionId::QueueBuffer, &mut parcel)?; let qbo = response_parcel.read()?; self.transact_parcel_check_err(&mut response_parcel)?; Ok(qbo) } /// Gets a native handle of the underlying [`IHOSBinderDriver`][`dispdrv::IHOSBinderDriverClient`] object /// /// # Arguments /// /// * `handle_type`: The [`NativeHandleType`][`dispdrv::NativeHandleType`] value pub fn get_native_handle( &mut self, handle_type: dispdrv::NativeHandleType, ) -> Result<sf::CopyHandle> { self.hos_binder_driver .get_native_handle(self.handle, handle_type) } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/gpu/binder/rc.rs
src/gpu/binder/rc.rs
//! Binder-specific result definitions use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 1100; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { ErrorCodeInvalid: 1, ErrorCodePermissionDenied: 2, ErrorCodeNameNotFound: 3, ErrorCodeWouldBlock: 4, ErrorCodeNoMemory: 5, ErrorCodeAlreadyExists: 6, ErrorCodeNoInit: 7, ErrorCodeBadValue: 8, ErrorCodeDeadObject: 9, ErrorCodeInvalidOperation: 10, ErrorCodeNotEnoughData: 11, ErrorCodeUnknownTransaction: 12, ErrorCodeBadIndex: 13, ErrorCodeTimeOut: 14, ErrorCodeFdsNotAllowed: 15, ErrorCodeFailedTransaction: 16, ErrorCodeBadType: 17 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/gpu/parcel/rc.rs
src/gpu/parcel/rc.rs
//! Parcel-specific result definitions use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 1200; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { NotEnoughReadSpace: 1, NotEnoughWriteSpace: 2, FdsNotSupported: 3, ReadSizeMismatch: 4 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf.rs
src/ipc/sf.rs
use core::{marker::PhantomData, mem::MaybeUninit}; use super::*; use alloc::{ string::{String, ToString}, vec::Vec, }; pub use nx_derive::{Request, Response, ipc_trait}; use zeroize::Zeroize; pub struct Buffer< 'borrow, const IN: bool, const OUT: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, T, > { buf: *mut T, count: usize, _lifetime: PhantomData<&'borrow ()>, } impl< 'borrow, const IN: bool, const OUT: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, > Buffer< 'borrow, IN, OUT, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, u8, > { pub const fn from_other_mut_var<'a: 'borrow, U>(var: &'a mut U) -> Self { unsafe { Self::from_ptr::<'a>(var as *const U as *const u8, size_of::<U>()) } } } impl< 'borrow, const IN: bool, const OUT: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, T, > Buffer< 'borrow, IN, OUT, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T, > { // TODO: ensure that sizeof(T) is a multiple of size /// Creates a `Buffer` from raw parts /// /// # Safety /// /// It is the caller's responsibility to ensure the lifetime of the buffer does not exceed the /// inner data. pub const unsafe fn new<'a: 'borrow>(addr: *mut u8, size: usize) -> Self { Self { buf: addr as *mut T, count: size / core::mem::size_of::<T>(), _lifetime: PhantomData, } } /// Creates a `Buffer` from a raw pointer /// /// # Safety /// /// It is the caller's responsibility to ensure the lifetime of the buffer does not exceed the /// inner data. pub const unsafe fn from_ptr<'a: 'borrow>(buf: *const T, count: usize) -> Self { Self { buf: buf as *mut T, count, _lifetime: PhantomData, } } /// Creates a `Buffer` from a raw pointer /// /// # Safety /// /// It is the caller's responsibility to ensure the lifetime of the buffer does not exceed the /// inner data. pub const unsafe fn from_mut_ptr<'a: 'borrow>(buf: *mut T, count: usize) -> Self { Self { buf, count, _lifetime: PhantomData, } } /// Converts a Buffer from one flag set to another /// /// # Arguments: /// /// * `other`: The other buffer to clone /// /// # Safety /// /// Since this clones the raw pointer, this can be used to get 2 mutable references to the same data. /// The caller _MUST_ ensure that only one the passed `other` buffer or the produced buffer is ever /// read/written while the other is alive. pub const unsafe fn from_other< 'other: 'borrow, const IN2: bool, const OUT2: bool, const MAP_ALIAS2: bool, const POINTER2: bool, const FIXED_SIZE2: bool, const AUTO_SELECT2: bool, const ALLOW_NON_SECURE2: bool, const ALLOW_NON_DEVICE2: bool, U, >( other: &'other Buffer< IN2, OUT2, MAP_ALIAS2, POINTER2, FIXED_SIZE2, AUTO_SELECT2, ALLOW_NON_SECURE2, ALLOW_NON_DEVICE2, U, >, ) -> Self { unsafe { Self::new(other.get_address(), other.get_size()) } } pub const fn get_address(&self) -> *mut u8 { self.buf.cast() } pub const fn get_size(&self) -> usize { self.count * core::mem::size_of::<T>() } pub const fn get_count(&self) -> usize { self.count } pub fn get_mut_var(&mut self) -> &mut T { unsafe { self.buf.as_mut().unwrap() } } pub fn set_var(&mut self, t: T) { unsafe { *self.buf.as_mut().unwrap() = t; } } pub fn get_maybe_unaligned(&self) -> Vec<T> { assert!(!self.buf.is_null()); let mut out = Vec::with_capacity(self.count); for index in 0..self.count { // SAFETY: we have already asserted on non-null `self.buf` out.push(unsafe { core::ptr::read_unaligned(self.buf.add(index)) }); } out } } impl< 'borrow, const IN: bool, const OUT: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, T, > Buffer< 'borrow, IN, OUT, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T, > { pub const fn from_mut_var(var: &'borrow mut T) -> Self { unsafe { Self::from_mut_ptr::<'borrow>(var as *mut T, 1) } } pub const fn from_mut_array(arr: &'borrow mut [T]) -> Self { unsafe { Self::from_mut_ptr(arr.as_mut_ptr(), arr.len()) } } } impl< 'borrow, const OUT: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, T, > Buffer< 'borrow, true, OUT, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T, > { pub fn get_var(&self) -> Result<&T> { unsafe { self.buf .as_ref() .ok_or(rc::ResultInvalidBufferPointer::make()) } } pub fn as_slice(&self) -> Result<&[T]> { result_return_unless!( self.buf.is_aligned() && !self.buf.is_null(), rc::ResultInvalidBufferPointer ); Ok(unsafe { core::slice::from_raw_parts(self.buf, self.count) }) } } impl< 'borrow, const IN: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, > Buffer< 'borrow, IN, false, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, u8, > { pub const fn from_other_var<'a: 'borrow, U>(var: &'a U) -> Self { unsafe { Self::from_ptr::<'a>(var as *const U as *const _, size_of::<U>()) } } } impl< 'borrow, const IN: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, T, > Buffer< 'borrow, IN, false, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T, > { pub const fn from_var(var: &'borrow T) -> Self { unsafe { Self::from_ptr(var as *const T, 1) } } pub const fn from_array(arr: &'borrow [T]) -> Self { unsafe { Self::from_ptr(arr.as_ptr(), arr.len()) } } } impl< const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, T, > Buffer< '_, true, true, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T, > { pub fn as_slice_mut(&mut self) -> Result<&mut [T]> { result_return_unless!( self.buf.is_aligned() && !self.buf.is_null(), rc::ResultInvalidBufferPointer ); Ok(unsafe { core::slice::from_raw_parts_mut(self.buf, self.count) }) } } impl< const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, T, > Buffer< '_, false, true, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T, > { /// If the input buffer is not marked as "IN" then there isn't an API contract that it will be readable/initialized. /// As such, we should consider all "OUT + !IN" buffers as uninitialized until written by the server function. pub fn as_maybeuninit_mut(&mut self) -> Result<&mut [MaybeUninit<T>]> { result_return_unless!( self.buf.is_aligned() && !self.buf.is_null(), rc::ResultInvalidBufferPointer ); Ok(unsafe { core::slice::from_raw_parts_mut(self.buf.cast(), self.count) }) } } impl< const OUT: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, > Buffer< '_, true, OUT, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, u8, > { pub fn get_string(&self) -> String { String::from_utf8_lossy(unsafe { core::slice::from_raw_parts_mut(self.buf, self.count) }) .to_string() } } impl< const IN: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, > Buffer< '_, IN, true, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, u8, > { pub fn set_string(&mut self, string: String) { unsafe { // First memset to zero so that it will be a valid nul-terminated string core::slice::from_raw_parts_mut(self.buf, self.count).zeroize(); core::ptr::copy( string.as_ptr(), self.buf, core::cmp::min(self.count - 1, string.len()), ); } } } pub type InMapAliasBuffer<'borrow, T> = Buffer<'borrow, true, false, true, false, false, false, false, false, T>; pub type OutMapAliasBuffer<'borrow, T> = Buffer<'borrow, false, true, true, false, false, false, false, false, T>; pub type InNonSecureMapAliasBuffer<'borrow, T> = Buffer<'borrow, true, false, true, false, false, false, true, false, T>; pub type OutNonSecureMapAliasBuffer<'borrow, T> = Buffer<'borrow, false, true, true, false, false, false, true, false, T>; pub type InAutoSelectBuffer<'borrow, T> = Buffer<'borrow, true, false, false, false, false, true, false, false, T>; pub type OutAutoSelectBuffer<'borrow, T> = Buffer<'borrow, false, true, false, false, false, true, false, false, T>; pub type InOutAutoSelectBuffer<'borrow, T> = Buffer<'borrow, true, true, false, false, false, true, false, false, T>; pub type InPointerBuffer<'borrow, T> = Buffer<'borrow, true, false, false, true, false, false, false, false, T>; pub type OutPointerBuffer<'borrow, T> = Buffer<'borrow, false, true, false, true, false, false, false, false, T>; pub type InFixedPointerBuffer<'borrow, T> = Buffer<'borrow, true, false, false, true, true, false, false, false, T>; pub type OutFixedPointerBuffer<'borrow, T> = Buffer<'borrow, false, true, false, true, true, false, false, false, T>; #[derive(Clone)] pub struct Handle<const MOVE: bool> { pub handle: svc::Handle, } impl<const MOVE: bool> Handle<MOVE> { pub const fn from(handle: svc::Handle) -> Self { Self { handle } } } pub type CopyHandle = Handle<false>; pub type MoveHandle = Handle<true>; #[derive(Clone, Default)] pub struct ProcessId { pub process_id: u64, } impl ProcessId { pub const fn from(process_id: u64) -> Self { Self { process_id } } pub const fn new() -> Self { Self { process_id: 0 } } } /// AppletResourceUserIds are restricted to the values of zero, or the process' PID. /// When they are sent over an IPC interface, they also trigger the sending of a PID descriptor in the HIPC request, /// so there is an additional field for the PID. This field is filled in by the kernel during a request, and is read /// out of the headers in the same way as the `ProcessId`[`ProcessId`] above. /// /// This allows the crate to just send the `AppletResourceUserId` object when the IPC interface is expecting this value /// and the `send_pid` flag. This also allows us to have a `ProcessId` type that creates it's own pid placeholder in CMIF /// IPC requests. #[derive(Clone, Default)] pub struct AppletResourceUserId { pub process_id: u64, pub aruid: u64, } impl AppletResourceUserId { pub const fn from(process_id: u64, aruid: u64) -> Self { Self { process_id, aruid } } #[cfg(feature = "applet")] pub fn from_global() -> Self { Self { process_id: 0, aruid: crate::applet::GLOBAL_ARUID.load(core::sync::atomic::Ordering::SeqCst), } } pub const fn new(aruid: u64) -> Self { Self { process_id: 0, aruid, } } } // This is used, for instance, with u8-sized enums which are sent/received as u32s in commands #[derive(Copy, Clone)] #[repr(C)] pub union EnumAsPrimitiveType<E: Copy + Clone, T: Copy + Clone> { val: T, enum_val: E, } impl<E: Copy + Clone, T: Copy + Clone> EnumAsPrimitiveType<E, T> { pub fn from(enum_val: E) -> Self { Self { enum_val } } pub fn from_val(val: T) -> Self { Self { val } } pub fn get(&self) -> E { unsafe { self.enum_val } } pub fn set(&mut self, enum_val: E) { self.enum_val = enum_val; } pub fn get_value(&self) -> T { unsafe { self.val } } pub fn set_value(&mut self, val: T) { self.val = val; } } impl<E: Copy + Clone, T: Copy + Clone> server::RequestCommandParameter<'_, EnumAsPrimitiveType<E, T>> for EnumAsPrimitiveType<E, T> { fn after_request_read(ctx: &mut server::ServerContext) -> Result<Self> { Ok(ctx.raw_data_walker.advance_get()) } } impl<E: Copy + Clone, T: Copy + Clone> server::ResponseCommandParameter for EnumAsPrimitiveType<E, T> { type CarryState = (); fn before_response_write(_raw: &Self, ctx: &mut server::ServerContext) -> Result<()> { ctx.raw_data_walker.advance::<Self>(); Ok(()) } fn after_response_write( raw: Self, _carry_state: (), ctx: &mut server::ServerContext, ) -> Result<()> { ctx.raw_data_walker.advance_set(raw); Ok(()) } } impl client::RequestCommandParameter for core::time::Duration { fn before_request_write( _var: &Self, walker: &mut DataWalker, _ctx: &mut CommandContext, ) -> Result<()> { walker.advance::<u64>(); walker.advance::<u64>(); Ok(()) } fn before_send_sync_request( var: &Self, walker: &mut DataWalker, _ctx: &mut CommandContext, ) -> Result<()> { walker.advance_set(var.as_secs()); walker.advance_set(var.subsec_nanos() as u64); Ok(()) } } impl server::RequestCommandParameter<'_, core::time::Duration> for core::time::Duration { fn after_request_read(ctx: &mut server::ServerContext<'_>) -> Result<core::time::Duration> { let seconds: u64 = ctx.raw_data_walker.advance_get(); let nanos: u64 = ctx.raw_data_walker.advance_get(); Ok(core::time::Duration::new(seconds, nanos as u32)) } } impl<E: Copy + Clone, T: Copy + Clone> client::RequestCommandParameter for EnumAsPrimitiveType<E, T> { fn before_request_write( _raw: &Self, walker: &mut crate::ipc::DataWalker, _ctx: &mut crate::ipc::CommandContext, ) -> crate::result::Result<()> { walker.advance::<Self>(); Ok(()) } fn before_send_sync_request( raw: &Self, walker: &mut crate::ipc::DataWalker, _ctx: &mut crate::ipc::CommandContext, ) -> crate::result::Result<()> { walker.advance_set(*raw); Ok(()) } } impl<E: Copy + Clone, T: Copy + Clone> client::ResponseCommandParameter<EnumAsPrimitiveType<E, T>> for EnumAsPrimitiveType<E, T> { fn after_response_read( walker: &mut crate::ipc::DataWalker, _ctx: &mut crate::ipc::CommandContext, ) -> crate::result::Result<Self> { Ok(walker.advance_get()) } } #[derive(Default)] pub struct Session { pub object_info: ObjectInfo, } impl Session { pub const fn new() -> Self { Self { object_info: ObjectInfo::new(), } } pub const fn from(object_info: ObjectInfo) -> Self { Self { object_info } } pub const fn from_handle(handle: svc::Handle) -> Self { Self::from(ObjectInfo::from_handle(handle)) } pub fn convert_to_domain(&mut self) -> Result<()> { self.object_info.domain_object_id = self.object_info.convert_current_object_to_domain()?; Ok(()) } pub fn get_info(&mut self) -> &mut ObjectInfo { &mut self.object_info } pub fn set_info(&mut self, info: ObjectInfo) { self.object_info = info; } pub fn close(&mut self) { if self.object_info.is_valid() { if self.object_info.is_domain() { let mut ctx = CommandContext::new_client(self.object_info); cmif::client::write_request_command_on_msg_buffer( &mut ctx, None, cmif::DomainCommandType::Close, ); let _ = svc::send_sync_request(self.object_info.handle); } else if self.object_info.owns_handle { let mut ctx = CommandContext::new_client(self.object_info); match self.object_info.protocol { CommandProtocol::Cmif => { cmif::client::write_close_command_on_msg_buffer(&mut ctx) } CommandProtocol::Tipc => { tipc::client::write_close_command_on_msg_buffer(&mut ctx) } }; let _ = svc::send_sync_request(self.object_info.handle); } if self.object_info.owns_handle { let _ = svc::close_handle(self.object_info.handle); } self.object_info = ObjectInfo::new(); } } } impl Drop for Session { fn drop(&mut self) { self.close(); } } pub mod sm; pub mod psm; pub mod audio; pub mod applet; pub mod lm; pub mod fatal; pub mod dispdrv; pub mod fsp; pub mod hid; pub mod nv; pub mod vi; pub mod hipc; pub mod psc; pub mod pm; pub mod nfp; pub mod mii; pub mod set; pub mod spl; pub mod usb; pub mod ldr; pub mod ncm; pub mod lr; pub mod bsd;
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/client.rs
src/ipc/client.rs
use sf::hipc; use super::*; pub trait RequestCommandParameter { fn before_request_write( var: &Self, walker: &mut DataWalker, ctx: &mut CommandContext, ) -> Result<()>; fn before_send_sync_request( var: &Self, walker: &mut DataWalker, ctx: &mut CommandContext, ) -> Result<()>; } pub trait ResponseCommandParameter<O> { fn after_response_read(walker: &mut DataWalker, ctx: &mut CommandContext) -> Result<O>; } impl< const IN: bool, const OUT: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, T, > RequestCommandParameter for sf::Buffer< '_, IN, OUT, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T, > { fn before_request_write( buffer: &Self, _walker: &mut DataWalker, ctx: &mut CommandContext, ) -> Result<()> { ctx.add_buffer(buffer) } fn before_send_sync_request( _buffer: &Self, _walker: &mut DataWalker, _ctx: &mut CommandContext, ) -> Result<()> { Ok(()) } } //impl<const A: BufferAttribute, T> !ResponseCommandParameter<sf::Buffer<A, T>> for sf::Buffer<A, T> {} impl<const MOVE: bool> RequestCommandParameter for sf::Handle<MOVE> { fn before_request_write( handle: &Self, _walker: &mut DataWalker, ctx: &mut CommandContext, ) -> Result<()> { ctx.in_params.add_handle(handle.clone()) } fn before_send_sync_request( _handle: &Self, _walker: &mut DataWalker, _ctx: &mut CommandContext, ) -> Result<()> { Ok(()) } } impl<const MOVE: bool> ResponseCommandParameter<sf::Handle<MOVE>> for sf::Handle<MOVE> { fn after_response_read(_walker: &mut DataWalker, ctx: &mut CommandContext) -> Result<Self> { ctx.out_params.pop_handle() } } impl RequestCommandParameter for sf::ProcessId { fn before_request_write( _process_id: &Self, walker: &mut DataWalker, ctx: &mut CommandContext, ) -> Result<()> { // signal to the kernel that we need a PID injected into the request ctx.in_params.send_process_id = true; if ctx.object_info.uses_cmif_protocol() { // TIPC doesn't set this placeholder space for process IDs walker.advance::<u64>(); } Ok(()) } fn before_send_sync_request( process_id: &Self, walker: &mut DataWalker, ctx: &mut CommandContext, ) -> Result<()> { // Same as above if ctx.object_info.uses_cmif_protocol() { walker.advance_set(process_id.process_id); } Ok(()) } } //impl !ResponseCommandParameter<sf::ProcessId> for sf::ProcessId {} impl RequestCommandParameter for sf::AppletResourceUserId { fn before_request_write( _aruid: &Self, walker: &mut DataWalker, ctx: &mut CommandContext, ) -> Result<()> { result_return_unless!( ctx.object_info.uses_cmif_protocol(), hipc::rc::ResultUnsupportedOperation ); // signal to the kernel that we need a PID injected into the request ctx.in_params.send_process_id = true; walker.advance::<u64>(); Ok(()) } fn before_send_sync_request( aruid: &Self, walker: &mut DataWalker, ctx: &mut CommandContext, ) -> Result<()> { result_return_unless!( ctx.object_info.uses_cmif_protocol(), hipc::rc::ResultUnsupportedOperation ); // write the aruid into the slot walker.advance_set(aruid.aruid); Ok(()) } } //impl !ResponseCommandParameter<sf::AppletResourceUserId> for sf::AppletResourceUserId {} pub trait IClientObject { fn new(session: sf::Session) -> Self where Self: Sized; fn get_session(&self) -> &sf::Session; fn get_session_mut(&mut self) -> &mut sf::Session; fn get_info(&self) -> ObjectInfo { self.get_session().object_info } /// # Safety /// /// The `ObjectInfo` being passed in must be for the same implementation of `IClientObject`, /// or the object will cease to function after this call. unsafe fn set_info(&mut self, info: ObjectInfo) { self.get_session_mut().set_info(info); } fn convert_to_domain(&mut self) -> Result<()> { self.get_session_mut().convert_to_domain() } fn query_own_pointer_buffer_size(&self) -> Result<u16> { self.get_info().query_pointer_buffer_size() } fn close_session(&mut self) { self.get_session_mut().close() } fn is_valid(&self) -> bool { self.get_info().is_valid() } fn is_domain(&self) -> bool { self.get_info().is_domain() } fn clone(&self) -> Result<Self> where Self: Sized, { let handle = self.get_info().clone_current_object()?; Ok(Self::new(sf::Session { object_info: ObjectInfo { handle: handle.handle, ..self.get_info() }, })) } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/rc.rs
src/ipc/rc.rs
use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 600; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { CopyHandlesFull: 1, MoveHandlesFull: 2, DomainObjectsFull: 3, InvalidDomainObject: 4, PointerSizesFull: 5, SendStaticsFull: 6, ReceiveStaticsFull: 7, SendBuffersFull: 8, ReceiveBuffersFull: 9, ExchangeBuffersFull: 10, InvalidSendStaticCount: 11, InvalidReceiveStaticCount: 12, InvalidSendBufferCount: 13, InvalidReceiveBufferCount: 14, InvalidExchangeBufferCount: 15, InvalidBufferAttributes: 16, InvalidProtocol: 17, InvalidBufferPointer: 18 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/cmif.rs
src/ipc/cmif.rs
use super::*; pub mod rc; pub type DomainObjectId = u32; #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum ControlRequestId { ConvertCurrentObjectToDomain = 0, CopyFromCurrentDomain = 1, CloneCurrentObject = 2, QueryPointerBufferSize = 3, CloneCurrentObjectEx = 4, } pub const IN_DATA_HEADER_MAGIC: u32 = u32::from_le_bytes(*b"SFCI"); pub const OUT_DATA_HEADER_MAGIC: u32 = u32::from_le_bytes(*b"SFCO"); #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum DomainCommandType { #[default] Invalid = 0, SendMessage = 1, Close = 2, } #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct DomainInDataHeader { pub command_type: DomainCommandType, pub object_count: u8, pub data_size: u16, pub domain_object_id: DomainObjectId, pub pad: u32, pub token: u32, } impl DomainInDataHeader { pub const fn empty() -> Self { Self { command_type: DomainCommandType::Invalid, object_count: 0, data_size: 0, domain_object_id: 0, pad: 0, token: 0, } } pub const fn new( command_type: DomainCommandType, object_count: u8, data_size: u16, domain_object_id: DomainObjectId, token: u32, ) -> Self { Self { command_type, object_count, data_size, domain_object_id, pad: 0, token, } } } #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct DomainOutDataHeader { pub out_object_count: u32, pub pad: [u32; 3], } impl DomainOutDataHeader { pub const fn empty() -> Self { Self { out_object_count: 0, pad: [0; 3], } } pub const fn new(out_object_count: u32) -> Self { let mut header = Self::empty(); header.out_object_count = out_object_count; header } } #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u16)] pub enum CommandType { #[default] Invalid = 0, LegacyRequest = 1, Close = 2, LegacyControl = 3, Request = 4, Control = 5, RequestWithContext = 6, ControlWithContext = 7, } pub fn convert_command_type(command_type: u32) -> CommandType { match command_type { 1 => CommandType::LegacyRequest, 2 => CommandType::Close, 3 => CommandType::LegacyControl, 4 => CommandType::Request, 5 => CommandType::Control, 6 => CommandType::RequestWithContext, 7 => CommandType::ControlWithContext, _ => CommandType::Invalid, } } #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct DataHeader { pub magic: u32, pub version: u32, pub value: u32, pub token: u32, } impl DataHeader { pub const fn empty() -> Self { Self { magic: 0, version: 0, value: 0, token: 0, } } pub const fn new(magic: u32, version: u32, value: u32, token: u32) -> Self { Self { magic, version, value, token, } } } pub mod client; pub mod server;
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/server.rs
src/ipc/server.rs
use super::*; use crate::sync::Mutex; use crate::wait; use alloc::rc::Rc; use alloc::vec::Vec; use sf::hipc::IHipcManager; use sf::hipc::IMitmQueryServiceServer; /// This flags, but is actually necessary #[allow(unused_imports)] use sf::sm::IUserInterfaceClient; #[cfg(feature = "services")] use crate::service; #[cfg(not(feature = "services"))] use crate::ipc::sf::sm; #[cfg(feature = "services")] use crate::service::sm; pub mod rc; // TODO: TIPC support, implement remaining control commands const MAX_COUNT: usize = wait::MAX_OBJECT_COUNT as usize; pub struct ServerContext<'ctx> { pub ctx: &'ctx mut CommandContext, pub raw_data_walker: DataWalker, pub domain_table: Option<Rc<Mutex<DomainTable>>>, pub new_sessions: &'ctx mut Vec<ServerHolder>, } impl<'ctx> ServerContext<'ctx> { pub const fn new( ctx: &'ctx mut CommandContext, raw_data_walker: DataWalker, domain_table: Option<Rc<Mutex<DomainTable>>>, new_sessions: &'ctx mut Vec<ServerHolder>, ) -> Self { Self { ctx, raw_data_walker, domain_table, new_sessions, } } } pub trait RequestCommandParameter<'ctx, O> { fn after_request_read(ctx: &mut ServerContext<'ctx>) -> Result<O>; } pub trait ResponseCommandParameter { type CarryState: 'static; fn before_response_write(var: &Self, ctx: &mut ServerContext) -> Result<Self::CarryState>; fn after_response_write( var: Self, carry_state: Self::CarryState, ctx: &mut ServerContext, ) -> Result<()>; } impl< 'buf, 'ctx: 'buf, const IN: bool, const OUT: bool, const MAP_ALIAS: bool, const POINTER: bool, const FIXED_SIZE: bool, const AUTO_SELECT: bool, const ALLOW_NON_SECURE: bool, const ALLOW_NON_DEVICE: bool, T, > RequestCommandParameter< 'ctx, sf::Buffer< 'buf, IN, OUT, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T, >, > for sf::Buffer< 'buf, IN, OUT, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T, > { fn after_request_read(ctx: &mut ServerContext<'ctx>) -> Result<Self> { let (addr, size) = ctx.ctx.pop_buffer::<IN, OUT, MAP_ALIAS, POINTER, FIXED_SIZE, AUTO_SELECT, ALLOW_NON_SECURE, ALLOW_NON_DEVICE, T>(&mut ctx.raw_data_walker)?; if OUT && POINTER { // For Out(Fixed)Pointer buffers, we need to send them back as InPointer // Note: since buffers can't be out params in this command param system, we need to send them back this way // SAFETY - This should be safe as we're only copying the buffer back into the context and not duplicating access to the buffer. // If we ever actually access that cloned buffer, it's instant UB let in_ptr_buf = unsafe { sf::InPointerBuffer::<u8>::new(addr, size) }; ctx.ctx.add_buffer(&in_ptr_buf)?; } Ok(unsafe { sf::Buffer::new(addr, size) }) } } //impl<const A: BufferAttribute, T> !ResponseCommandParameter for sf::Buffer<A, T> {} impl<const MOVE: bool> RequestCommandParameter<'_, sf::Handle<MOVE>> for sf::Handle<MOVE> { fn after_request_read(ctx: &mut ServerContext) -> Result<Self> { ctx.ctx.in_params.pop_handle::<MOVE>() } } impl<const MOVE: bool> ResponseCommandParameter for sf::Handle<MOVE> { type CarryState = (); fn before_response_write(handle: &Self, ctx: &mut ServerContext) -> Result<()> { ctx.ctx.out_params.push_handle(handle.clone()) } fn after_response_write( _handle: Self, _carry_state: (), _ctx: &mut ServerContext, ) -> Result<()> { Ok(()) } } impl RequestCommandParameter<'_, sf::ProcessId> for sf::ProcessId { fn after_request_read(ctx: &mut ServerContext) -> Result<Self> { if ctx.ctx.in_params.send_process_id { if ctx.ctx.object_info.uses_cmif_protocol() { let _ = ctx.raw_data_walker.advance_get::<u64>(); } Ok(sf::ProcessId::from(ctx.ctx.in_params.process_id)) } else { sf::hipc::rc::ResultUnsupportedOperation::make_err() } } } //impl !ResponseCommandParameter for sf::ProcessId {} impl RequestCommandParameter<'_, sf::AppletResourceUserId> for sf::AppletResourceUserId { fn after_request_read(ctx: &mut ServerContext) -> Result<Self> { result_return_unless!( ctx.ctx.object_info.uses_cmif_protocol(), sf::hipc::rc::ResultUnsupportedOperation ); if ctx.ctx.in_params.send_process_id { Ok(sf::AppletResourceUserId::from( ctx.ctx.in_params.process_id, ctx.raw_data_walker.advance_get::<u64>(), )) } else { sf::hipc::rc::ResultUnsupportedOperation::make_err() } } } //impl !ResponseCommandParameter for sf::AppletResourceUserId {} impl<S: ISessionObject + 'static> ResponseCommandParameter for S { type CarryState = u32; fn before_response_write(_session: &Self, ctx: &mut ServerContext) -> Result<u32> { if ctx.ctx.object_info.is_domain() { let domain_object_id = ctx .domain_table .as_mut() .ok_or(rc::ResultDomainNotFound::make())? .lock() .allocate_id()?; ctx.ctx.out_params.push_domain_object(domain_object_id)?; Ok(domain_object_id) } else { let (server_handle, client_handle) = svc::create_session(false, 0)?; ctx.ctx .out_params .push_handle(sf::MoveHandle::from(client_handle))?; Ok(server_handle) } } fn after_response_write( session: Self, carry_state: u32, ctx: &mut ServerContext, ) -> Result<()> { if ctx.ctx.object_info.is_domain() { ctx.domain_table .as_mut() .ok_or(rc::ResultDomainNotFound::make())? .lock() .domains .push(ServerHolder::new_domain_session( 0, carry_state, Rc::new(Mutex::new(session)), )) } else { ctx.new_sessions.push(ServerHolder::new_session( carry_state, Rc::new(Mutex::new(session)), )); } Ok(()) } } pub trait ISessionObject { fn try_handle_request_by_id( &mut self, req_id: u32, protocol: CommandProtocol, server_ctx: &mut ServerContext, ) -> Option<Result<()>>; } pub trait IServerObject: ISessionObject { fn new() -> Self where Self: Sized; } pub trait IMitmServerObject: ISessionObject { fn new(info: sm::mitm::MitmProcessInfo) -> Self where Self: Sized; } pub type NewServerFn = fn() -> Rc<Mutex<dyn ISessionObject>>; fn create_server_object_impl<S: IServerObject + 'static>() -> Rc<Mutex<dyn ISessionObject>> { Rc::new(Mutex::new(S::new())) } pub type NewMitmServerFn = fn(sm::mitm::MitmProcessInfo) -> Rc<Mutex<dyn ISessionObject>>; fn create_mitm_server_object_impl<S: IMitmServerObject + 'static>( info: sm::mitm::MitmProcessInfo, ) -> Rc<Mutex<dyn ISessionObject>> { Rc::new(Mutex::new(S::new(info))) } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum WaitHandleType { Server, Session, } #[derive(Default)] pub struct DomainTable { pub table: Vec<cmif::DomainObjectId>, pub domains: Vec<ServerHolder>, } impl DomainTable { pub fn new() -> Self { Self { table: Vec::new(), domains: Vec::new(), } } pub fn allocate_id(&mut self) -> Result<cmif::DomainObjectId> { let mut current_id: cmif::DomainObjectId = 1; loop { // Note: fix potential infinite loops here? if !self.table.contains(&current_id) { self.table.push(current_id); return Ok(current_id); } current_id += 1; } } pub fn allocate_specific_id( &mut self, specific_domain_object_id: cmif::DomainObjectId, ) -> Result<cmif::DomainObjectId> { if !self.table.contains(&specific_domain_object_id) { self.table.push(specific_domain_object_id); return Ok(specific_domain_object_id); } rc::ResultObjectIdAlreadyAllocated::make_err() } pub fn find_domain( &mut self, id: cmif::DomainObjectId, ) -> Result<Rc<Mutex<dyn ISessionObject>>> { for holder in &self.domains { if holder.info.domain_object_id == id { return holder .server .clone() .ok_or(rc::ResultDomainNotFound::make()); } } rc::ResultDomainNotFound::make_err() } pub fn deallocate_domain(&mut self, domain_object_id: cmif::DomainObjectId) { self.table.retain(|&id| id != domain_object_id); self.domains .retain(|holder| holder.info.domain_object_id != domain_object_id); } } pub struct ServerHolder { pub server: Option<Rc<Mutex<dyn ISessionObject>>>, pub info: ObjectInfo, pub new_server_fn: Option<NewServerFn>, pub new_mitm_server_fn: Option<NewMitmServerFn>, pub handle_type: WaitHandleType, pub mitm_forward_info: ObjectInfo, pub is_mitm_service: bool, pub service_name: sm::ServiceName, pub domain_table: Option<Rc<Mutex<DomainTable>>>, } impl ServerHolder { pub fn new_session(handle: svc::Handle, object: Rc<Mutex<dyn ISessionObject>>) -> Self { Self { server: Some(object), info: ObjectInfo::from_handle(handle), new_server_fn: None, new_mitm_server_fn: None, handle_type: WaitHandleType::Session, mitm_forward_info: ObjectInfo::new(), is_mitm_service: false, service_name: sm::ServiceName::empty(), domain_table: None, } } pub fn new_domain_session( handle: svc::Handle, domain_object_id: cmif::DomainObjectId, object: Rc<Mutex<dyn ISessionObject>>, ) -> Self { Self { server: Some(object), info: ObjectInfo::from_domain_object_id(handle, domain_object_id), new_server_fn: None, new_mitm_server_fn: None, handle_type: WaitHandleType::Session, mitm_forward_info: ObjectInfo::new(), is_mitm_service: false, service_name: sm::ServiceName::empty(), domain_table: None, } } pub fn new_server<S: IServerObject + 'static>( handle: svc::Handle, service_name: sm::ServiceName, ) -> Self { Self { server: None, info: ObjectInfo::from_handle(handle), new_server_fn: Some(create_server_object_impl::<S>), new_mitm_server_fn: None, handle_type: WaitHandleType::Server, mitm_forward_info: ObjectInfo::new(), is_mitm_service: false, service_name, domain_table: None, } } pub fn new_mitm_server<S: IMitmServerObject + 'static>( handle: svc::Handle, service_name: sm::ServiceName, ) -> Self { Self { server: None, info: ObjectInfo::from_handle(handle), new_server_fn: None, new_mitm_server_fn: Some(create_mitm_server_object_impl::<S>), handle_type: WaitHandleType::Server, mitm_forward_info: ObjectInfo::new(), is_mitm_service: true, service_name, domain_table: None, } } pub fn make_new_session(&self, handle: svc::Handle) -> Result<Self> { let new_fn = self.get_new_server_fn()?; Ok(Self { server: Some((new_fn)()), info: ObjectInfo::from_handle(handle), new_server_fn: self.new_server_fn, new_mitm_server_fn: self.new_mitm_server_fn, handle_type: WaitHandleType::Session, mitm_forward_info: ObjectInfo::new(), is_mitm_service: self.is_mitm_service, service_name: sm::ServiceName::empty(), domain_table: None, }) } pub fn make_new_mitm_session( &self, handle: svc::Handle, forward_handle: svc::Handle, info: sm::mitm::MitmProcessInfo, service_name: sm::ServiceName, ) -> Result<Self> { let new_mitm_fn = self.get_new_mitm_server_fn()?; Ok(Self { server: Some((new_mitm_fn)(info)), info: ObjectInfo::from_handle(handle), new_server_fn: self.new_server_fn, new_mitm_server_fn: self.new_mitm_server_fn, handle_type: WaitHandleType::Session, mitm_forward_info: ObjectInfo::from_handle(forward_handle), is_mitm_service: self.is_mitm_service, service_name, domain_table: None, }) } pub fn clone_self(&self, handle: svc::Handle, forward_handle: svc::Handle) -> Result<Self> { let mut object_info = self.info; object_info.handle = handle; let mut mitm_fwd_info = self.mitm_forward_info; mitm_fwd_info.handle = forward_handle; Ok(Self { server: self.server.clone(), info: object_info, new_server_fn: self.new_server_fn, new_mitm_server_fn: self.new_mitm_server_fn, handle_type: WaitHandleType::Session, mitm_forward_info: mitm_fwd_info, is_mitm_service: forward_handle != svc::INVALID_HANDLE, service_name: sm::ServiceName::empty(), domain_table: self.domain_table.clone(), }) } pub fn get_new_server_fn(&self) -> Result<NewServerFn> { match self.new_server_fn { Some(new_server_fn) => Ok(new_server_fn), None => sf::hipc::rc::ResultSessionClosed::make_err(), } } pub fn get_new_mitm_server_fn(&self) -> Result<NewMitmServerFn> { match self.new_mitm_server_fn { Some(new_mitm_server_fn) => Ok(new_mitm_server_fn), None => sf::hipc::rc::ResultSessionClosed::make_err(), } } pub fn convert_to_domain(&mut self) -> Result<cmif::DomainObjectId> { // Check that we're not already a domain result_return_if!(self.info.is_domain(), rc::ResultAlreadyDomain); // Since we're a base domain object now, create a domain table let dom_table = Rc::new(Mutex::new(DomainTable::new())); self.domain_table = Some(dom_table.clone()); let domain_object_id = match self.is_mitm_service { true => { let forward_object_id = self.mitm_forward_info.convert_current_object_to_domain()?; self.mitm_forward_info.domain_object_id = forward_object_id; dom_table.lock().allocate_specific_id(forward_object_id)? } false => dom_table.lock().allocate_id()?, }; self.info.domain_object_id = domain_object_id; Ok(domain_object_id) } pub fn close(&mut self) -> Result<()> { if !self.service_name.is_empty() { #[cfg(feature = "services")] { if self.handle_type == WaitHandleType::Server { let sm = service::new_named_port_object::<sm::UserInterface>()?; if self.is_mitm_service { debug_assert!( self.info.owns_handle, "MitM server objects should always own their handles." ); sm.atmosphere_uninstall_mitm(self.service_name)?; } else { sm.unregister_service(self.service_name)?; } sm.detach_client(sf::ProcessId::new())?; } } } // Forward info may be valid despite having an empty service name (like a cloned session) if self.is_mitm_service { sf::Session::from(self.mitm_forward_info).close(); } // Don't close our session like a normal one (like the forward session below) as we allocated the object IDs ourselves, the only thing we do have to close is the handle if self.info.owns_handle { svc::close_handle(self.info.handle)?; } Ok(()) } } impl Drop for ServerHolder { fn drop(&mut self) { self.close().unwrap(); } } pub struct HipcManager<'a> { server_holder: &'a mut ServerHolder, pointer_buf_size: usize, pub cloned_object_server_handle: svc::Handle, pub cloned_object_forward_handle: svc::Handle, } impl<'a> HipcManager<'a> { pub fn new(server_holder: &'a mut ServerHolder, pointer_buf_size: usize) -> Self { Self { server_holder, pointer_buf_size, cloned_object_server_handle: svc::INVALID_HANDLE, cloned_object_forward_handle: svc::INVALID_HANDLE, } } pub fn has_cloned_object(&self) -> bool { self.cloned_object_server_handle != 0 } pub fn clone_object(&self) -> Result<ServerHolder> { self.server_holder.clone_self( self.cloned_object_server_handle, self.cloned_object_forward_handle, ) } } impl IHipcManager for HipcManager<'_> { fn convert_current_object_to_domain(&mut self) -> Result<cmif::DomainObjectId> { self.server_holder.convert_to_domain() } fn copy_from_current_domain( &mut self, _domain_object_id: cmif::DomainObjectId, ) -> Result<sf::MoveHandle> { // TODO crate::rc::ResultNotImplemented::make_err() } fn clone_current_object(&mut self) -> Result<sf::MoveHandle> { let (server_handle, client_handle) = svc::create_session(false, 0)?; let mut forward_handle: svc::Handle = 0; if self.server_holder.is_mitm_service { let fwd_handle = self .server_holder .mitm_forward_info .clone_current_object()?; forward_handle = fwd_handle.handle; } self.cloned_object_server_handle = server_handle; self.cloned_object_forward_handle = forward_handle; Ok(sf::Handle::from(client_handle)) } fn query_pointer_buffer_size(&mut self) -> Result<u16> { Ok(self.pointer_buf_size as u16) } fn clone_current_object_ex(&mut self, _tag: u32) -> Result<sf::MoveHandle> { // The tag value is unused anyways :P self.clone_current_object() } } impl ISessionObject for HipcManager<'_> { fn try_handle_request_by_id( &mut self, req_id: u32, protocol: CommandProtocol, server_ctx: &mut ServerContext, ) -> Option<Result<()>> { <Self as IHipcManager>::try_handle_request_by_id(self, req_id, protocol, server_ctx) } } pub struct MitmQueryService<S: IMitmService> { _phantom: core::marker::PhantomData<S>, } /// This is safe as we're only calling associated functions and not trait methods. unsafe impl<S: IMitmService> Sync for MitmQueryService<S> {} impl<S: IMitmService> MitmQueryService<S> { pub fn new() -> Self { Self { _phantom: core::marker::PhantomData, } } } impl<S: IMitmService> Default for MitmQueryService<S> { fn default() -> Self { Self::new() } } impl<S: IMitmService> IMitmQueryServiceServer for MitmQueryService<S> { fn should_mitm(&mut self, info: sm::mitm::MitmProcessInfo) -> Result<bool> { Ok(S::should_mitm(info)) } } impl<S: IMitmService> ISessionObject for MitmQueryService<S> { fn try_handle_request_by_id( &mut self, req_id: u32, protocol: CommandProtocol, server_ctx: &mut ServerContext, ) -> Option<Result<()>> { <Self as IMitmQueryServiceServer>::try_handle_request_by_id( self, req_id, protocol, server_ctx, ) } } pub trait INamedPort: IServerObject { fn get_port_name() -> &'static core::ffi::CStr; fn get_max_sesssions() -> i32; } pub trait IService: IServerObject { fn get_name() -> sm::ServiceName; fn get_max_sesssions() -> i32; } pub trait IMitmService: IMitmServerObject { fn get_name() -> sm::ServiceName; fn should_mitm(info: sm::mitm::MitmProcessInfo) -> bool; } // TODO: use const generics to reduce memory usage, like libstratosphere does? pub struct ServerManager<const P: usize> { server_holders: Vec<ServerHolder>, wait_handles: [svc::Handle; MAX_COUNT], pointer_buffer: [u8; P], } impl<const P: usize> ServerManager<P> { pub fn new() -> Result<Self> { Ok(Self { server_holders: Vec::new(), wait_handles: [0; MAX_COUNT], pointer_buffer: [0; P], }) } #[inline(always)] fn prepare_wait_handles(&mut self) -> &[svc::Handle] { let mut handles_index: usize = 0; for server_holder in &mut self.server_holders { let server_info = server_holder.info; if server_info.handle != svc::INVALID_HANDLE { self.wait_handles[handles_index] = server_info.handle; handles_index += 1; } } &self.wait_handles[..handles_index] } #[inline(always)] fn handle_request_command( &mut self, ctx: &mut CommandContext, rq_id: u32, command_type: cmif::CommandType, domain_command_type: cmif::DomainCommandType, ipc_buf_backup: &[u8], domain_table: Option<Rc<Mutex<DomainTable>>>, ) -> Result<()> { let is_domain = ctx.object_info.is_domain(); let domain_table_clone = domain_table.clone(); let do_handle_request = || -> Result<()> { let mut new_sessions: Vec<ServerHolder> = Vec::new(); for server_holder in &mut self.server_holders { let server_info = server_holder.info; if server_info.handle == ctx.object_info.handle { let send_to_forward_handle = || -> Result<()> { let ipc_buf = get_msg_buffer(); unsafe { core::ptr::copy(ipc_buf_backup.as_ptr(), ipc_buf, ipc_buf_backup.len()); } // Let the original service take care of the command for us. svc::send_sync_request(server_holder.mitm_forward_info.handle) }; let target_server = match is_domain { true => match ctx.object_info.owns_handle { true => server_holder .server .clone() .ok_or(rc::ResultSignaledServerNotFound::make())?, false => domain_table .ok_or(rc::ResultDomainNotFound::make())? .lock() .find_domain(ctx.object_info.domain_object_id)?, }, false => server_holder .server .clone() .ok_or(rc::ResultSignaledServerNotFound::make())?, }; // Nothing done on success here, as if the command succeeds it will automatically respond by itself. let mut command_found = false; { let protocol = ctx.object_info.protocol; let mut server_ctx = ServerContext::new( ctx, DataWalker::empty(), domain_table_clone.clone(), &mut new_sessions, ); if let Some(result) = target_server.lock().try_handle_request_by_id( rq_id, protocol, &mut server_ctx, ) { command_found = true; if let Err(rc) = result { if server_holder.is_mitm_service && sm::mitm::rc::ResultShouldForwardToSession::matches(rc) { if let Err(rc) = send_to_forward_handle() { cmif::server::write_request_command_response_on_msg_buffer( ctx, rc, command_type, ); } } else { cmif::server::write_request_command_response_on_msg_buffer( ctx, rc, command_type, ); } } } } if !command_found { if server_holder.is_mitm_service { if let Err(rc) = send_to_forward_handle() { cmif::server::write_request_command_response_on_msg_buffer( ctx, rc, command_type, ); } } else { cmif::server::write_request_command_response_on_msg_buffer( ctx, cmif::rc::ResultInvalidCommandRequestId::make(), command_type, ); } } break; } } self.server_holders.append(&mut new_sessions); Ok(()) }; match domain_command_type { cmif::DomainCommandType::Invalid => { // Invalid command type might mean that the session isn't a domain :P match is_domain { false => do_handle_request()?, true => return rc::ResultInvalidDomainCommandType::make_err(), }; } cmif::DomainCommandType::SendMessage => do_handle_request()?, cmif::DomainCommandType::Close => { if !ctx.object_info.owns_handle { domain_table_clone .ok_or(rc::ResultDomainNotFound::make())? .lock() .deallocate_domain(ctx.object_info.domain_object_id); } else { // TODO: Abort? Error? } } } Ok(()) } #[inline(always)] fn handle_control_command( &mut self, ctx: &mut CommandContext, rq_id: u32, command_type: cmif::CommandType, ) -> Result<()> { // Control commands only exist in CMIF... result_return_unless!( ctx.object_info.uses_cmif_protocol(), super::rc::ResultInvalidProtocol ); for server_holder in &mut self.server_holders { let server_info = server_holder.info; if server_info.handle == ctx.object_info.handle { let mut hipc_manager = HipcManager::new(server_holder, P); // Nothing done on success here, as if the command succeeds it will automatically respond by itself. let mut command_found = false; { let mut unused_new_sessions: Vec<ServerHolder> = Vec::new(); let mut server_ctx = ServerContext::new( ctx, DataWalker::empty(), None, &mut unused_new_sessions, ); if let Some(result) = <HipcManager as ISessionObject>::try_handle_request_by_id( &mut hipc_manager, rq_id, CommandProtocol::Cmif, &mut server_ctx, ) { command_found = true; if let Err(rc) = result { cmif::server::write_control_command_response_on_msg_buffer( ctx, rc, command_type, ); } } } if !command_found { cmif::server::write_control_command_response_on_msg_buffer( ctx, cmif::rc::ResultInvalidCommandRequestId::make(), command_type, ); } if hipc_manager.has_cloned_object() { let cloned_holder = hipc_manager.clone_object()?; self.server_holders.push(cloned_holder); } break; } } Ok(()) } fn process_signaled_handle(&mut self, handle: svc::Handle) -> Result<()> { let mut server_found = false; let mut index: usize = 0; let mut should_close_session = false; let mut new_sessions: Vec<ServerHolder> = Vec::new(); let mut ctx = CommandContext::empty(); let mut command_type = cmif::CommandType::Invalid; let mut domain_cmd_type = cmif::DomainCommandType::Invalid; let mut rq_id: u32 = 0; let mut ipc_buf_backup: [u8; 0x100] = [0; 0x100]; let mut domain_table: Option<Rc<Mutex<DomainTable>>> = None; for server_holder in &mut self.server_holders { let server_info = server_holder.info; if server_info.handle == handle { server_found = true; match server_holder.handle_type { WaitHandleType::Session => { if P > 0 { // Send our pointer buffer as a C descriptor for kernel - why are Pointer buffers so fucking weird? let mut tmp_ctx = CommandContext::new_client(server_info); tmp_ctx.add_receive_static(ReceiveStaticDescriptor::new( self.pointer_buffer.as_ptr(), P, ))?; cmif::client::write_command_on_msg_buffer( &mut tmp_ctx, cmif::CommandType::Invalid, 0, ); } if let Err(rc) = unsafe { svc::reply_and_receive(&handle, 1, 0, -1) } { if svc::rc::ResultSessionClosed::matches(rc) { should_close_session = true; break; } else { return Err(rc); } }; unsafe { core::ptr::copy( get_msg_buffer(), ipc_buf_backup.as_mut_ptr(), ipc_buf_backup.len(), ) }; ctx = CommandContext::new_server( server_info, self.pointer_buffer.as_mut_ptr(), ); command_type = cmif::server::read_command_from_msg_buffer(&mut ctx);
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
true
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/tipc.rs
src/ipc/tipc.rs
//! TIPC ("tiny IPC") protocol support use super::*; /// Represents special TIPC command types /// /// Note that regular/"Request" commands use `16 + <request-id>` as their command type #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum CommandType { Invalid = 0, CloseSession = 15, } pub mod client; pub mod server;
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/hipc.rs
src/ipc/sf/hipc.rs
use crate::ipc::sf; use crate::ipc::sf::sm; use crate::result::*; use crate::version; pub mod rc; // Interfaces related to core serverside IPC (for control requests and MitM support) ipc_sf_define_control_interface_trait! { trait IHipcManager { convert_current_object_to_domain [0, version::VersionInterval::all()]: () => (domain_object_id: u32); copy_from_current_domain [1, version::VersionInterval::all()]: (domain_object_id: u32) => (handle: sf::MoveHandle); clone_current_object [2, version::VersionInterval::all()]: () => (cloned_handle: sf::MoveHandle); query_pointer_buffer_size [3, version::VersionInterval::all()]: () => (pointer_buffer_size: u16); clone_current_object_ex [4, version::VersionInterval::all()]: (tag: u32) => (cloned_handle: sf::MoveHandle); } } #[nx_derive::ipc_trait] #[default_client] pub trait MitmQueryService { #[ipc_rid(65000)] fn should_mitm(&self, info: sm::mitm::MitmProcessInfo) -> bool; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/applet.rs
src/ipc/sf/applet.rs
use crate::ipc::sf; use crate::result::*; use crate::svc::Handle; use crate::version; pub use super::AppletResourceUserId; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone)] #[repr(C)] pub struct AppletAttribute { flag: u8, reserved: [u8; 0x7F], } impl AppletAttribute { pub const fn zero() -> Self { Self { flag: 0, reserved: [0u8; 0x7F], } } } impl Default for AppletAttribute { fn default() -> Self { Self::zero() } } const_assert!(core::mem::size_of::<AppletAttribute>() == 0x80); #[derive(Request, Response, Copy, Clone)] #[repr(C)] pub struct AppletProcessLaunchReason { flag: u8, _zero: [u8; 2], _zero2: u8, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum ScreenShotPermission { Inherit, Enable, Disable, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum AppletId { None = 0x00, Application = 0x01, OverlayApplet = 0x02, SystemAppletMenu = 0x03, SystemApplication = 0x04, LibraryAppletAuth = 0x0A, LibraryAppletCabinet = 0x0B, LibraryAppletController = 0x0C, LibraryAppletDataErase = 0x0D, LibraryAppletError = 0x0E, LibraryAppletNetConnect = 0x0F, LibraryAppletPlayerSelect = 0x10, LibraryAppletSwkbd = 0x11, LibraryAppletMiiEdit = 0x12, LibAppletWeb = 0x13, LibAppletShop = 0x14, LibraryAppletPhotoViewer = 0x15, LibraryAppletSet = 0x16, LibraryAppletOfflineWeb = 0x17, LibraryAppletLoginShare = 0x18, LibraryAppletWifiWebAuth = 0x19, LibraryAppletMyPage = 0x1A, LibraryAppletGift = 0x1B, LibraryAppletUserMigration = 0x1C, LibraryAppletPreomiaSys = 0x1D, LibraryAppletStory = 0x1E, LibraryAppletPreomiaUsr = 0x1F, LibraryAppletPreomiaUsrDummy = 0x20, LibraryAppletSample = 0x21, DevlopmentTool = 0x3E8, CombinationLA = 0x3F1, AeSystemApplet = 0x3F2, AeOverlayApplet = 0x3F3, AeStarter = 0x3F4, AeLibraryAppletAlone = 0x3F5, AeLibraryApplet1 = 0x3F6, AeLibraryApplet2 = 0x3F7, AeLibraryApplet3 = 0x3F8, AeLibraryApplet4 = 0x3F9, AppletISA = 0x3FA, AppletIOA = 0x3FB, AppletISTA = 0x3FC, AppletILA1 = 0x3FD, AppletILA2 = 0x3FE, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub enum OperationMode { Handheld = 0, Console = 1, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub enum PerformanceMode { Invalid = -1, Normal = 0, Boost = 1, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub enum LibraryAppletMode { AllForeground, Background, NoUi, BackgroundIndirectDisplay, AllForegroundInitiallyHidden, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub enum AppletMessage { /// The applet received an exit request ExitRequest = 4, /// The FocusState of the applet changed FocusStateChanged = 15, /// The applet was resumed Resume = 16, /// The OperationMode of the applet changed OperationModeChanged = 30, /// The PerformanceMode of the applet changed PerformanceMode = 31, /// The applet was requested to display DisplayRequested = 51, /// Capture button was pressed (short) CaptureButtonPressedShort = 90, /// A screenshot was taken ScreenShotTaken = 92, /// A screen recoding was saved RecordingSaved = 93, } #[nx_derive::ipc_trait] #[default_client] pub trait StorageAccessor { #[ipc_rid(0)] fn get_size(&self) -> usize; #[ipc_rid(10)] fn write(&self, offset: usize, buf: sf::InAutoSelectBuffer<'_, u8>); #[ipc_rid(11)] fn read(&self, offset: usize, buf: sf::OutAutoSelectBuffer<'_, u8>); } #[nx_derive::ipc_trait] #[default_client] pub trait Storage { #[ipc_rid(0)] fn open(&self) -> StorageAccessor; } #[nx_derive::ipc_trait] #[default_client] pub trait LibraryAppletAccessor { #[ipc_rid(0)] fn get_applet_state_changed_event(&mut self) -> sf::CopyHandle; #[ipc_rid(10)] fn start(&mut self); #[ipc_rid(100)] fn push_in_data(&mut self, storage: Storage); #[ipc_rid(101)] fn pop_out_data(&mut self) -> Storage; } #[nx_derive::ipc_trait] #[default_client] pub trait LibraryAppletCreator { #[ipc_rid(0)] #[return_session] fn create_library_applet( &self, applet_id: AppletId, applet_mode: LibraryAppletMode, ) -> LibraryAppletAccessor; #[ipc_rid(10)] fn create_storage(&self, size: usize) -> Storage; } #[nx_derive::ipc_trait] #[default_client] pub trait WindowController { #[ipc_rid(1)] fn get_applet_resource_user_id(&self) -> u64; #[ipc_rid(10)] fn acquire_foreground_rights(&self); } #[nx_derive::ipc_trait] #[default_client] pub trait SelfController { #[ipc_rid(10)] fn set_screenshot_permission(&self, permission: ScreenShotPermission); #[ipc_rid(40)] fn create_managed_display_layer(&self) -> u64; } #[nx_derive::ipc_trait] #[default_client] pub trait AudioController { #[ipc_rid(0)] fn set_expected_master_volume(&self, main_applet_level: f32, library_applet_level: f32); #[ipc_rid(1)] fn get_main_applet_volume(&self) -> f32; #[ipc_rid(2)] fn get_library_applet_volume(&self) -> f32; #[ipc_rid(3)] fn change_main_applet_volume(&self, main_applet_level: f32, unknown: u64); #[ipc_rid(4)] fn set_transparent_volume_rate(&self, rate: f32); } #[nx_derive::ipc_trait] #[default_client] pub trait DisplayController { #[ipc_rid(3)] fn update_caller_applet_capture_image(&self); } #[nx_derive::ipc_trait] #[default_client] pub trait ProcessWindingController { #[ipc_rid(0)] fn get_launch_reason(&self) -> AppletProcessLaunchReason; } #[nx_derive::ipc_trait] #[default_client] pub trait CommonStateGetter { #[ipc_rid(0)] fn get_event_handle(&self) -> Handle; #[ipc_rid(1)] fn receive_message(&self) -> AppletMessage; } #[nx_derive::ipc_trait] #[default_client] pub trait LibraryAppletProxy { #[ipc_rid(0)] #[return_session] fn get_common_state_getter(&self) -> CommonStateGetter; #[ipc_rid(1)] #[return_session] fn get_self_controller(&self) -> SelfController; #[ipc_rid(2)] #[return_session] fn get_window_controller(&self) -> WindowController; #[ipc_rid(3)] #[return_session] fn get_audio_controller(&self) -> AudioController; #[ipc_rid(4)] #[return_session] fn get_display_controller(&self) -> DisplayController; #[ipc_rid(10)] #[return_session] fn get_process_winding_controller(&self) -> ProcessWindingController; #[ipc_rid(11)] #[return_session] fn get_library_applet_creator(&self) -> LibraryAppletCreator; } #[nx_derive::ipc_trait] #[default_client] pub trait ApplicationProxy { #[ipc_rid(0)] #[return_session] fn get_common_state_getter(&self) -> CommonStateGetter; #[ipc_rid(1)] #[return_session] fn get_self_controller(&self) -> SelfController; #[ipc_rid(2)] #[return_session] fn get_window_controller(&self) -> WindowController; #[ipc_rid(3)] #[return_session] fn get_audio_controller(&self) -> AudioController; #[ipc_rid(4)] #[return_session] fn get_display_controller(&self) -> DisplayController; #[ipc_rid(10)] #[return_session] fn get_process_winding_controller(&self) -> ProcessWindingController; #[ipc_rid(11)] #[return_session] fn get_library_applet_creator(&self) -> LibraryAppletCreator; } #[nx_derive::ipc_trait] #[default_client] pub trait SystemAppletProxy { #[ipc_rid(0)] #[return_session] fn get_common_state_getter(&self) -> CommonStateGetter; #[ipc_rid(1)] #[return_session] fn get_self_controller(&self) -> SelfController; #[ipc_rid(2)] #[return_session] fn get_window_controller(&self) -> WindowController; #[ipc_rid(3)] #[return_session] fn get_audio_controller(&self) -> AudioController; #[ipc_rid(4)] #[return_session] fn get_display_controller(&self) -> DisplayController; #[ipc_rid(10)] #[return_session] fn get_process_winding_controller(&self) -> ProcessWindingController; #[ipc_rid(11)] #[return_session] fn get_library_applet_creator(&self) -> LibraryAppletCreator; } #[nx_derive::ipc_trait] #[default_client] pub trait OverlayAppletProxy { #[ipc_rid(0)] #[return_session] fn get_common_state_getter(&self) -> CommonStateGetter; #[ipc_rid(1)] #[return_session] fn get_self_controller(&self) -> SelfController; #[ipc_rid(2)] #[return_session] fn get_window_controller(&self) -> WindowController; #[ipc_rid(3)] #[return_session] fn get_audio_controller(&self) -> AudioController; #[ipc_rid(4)] #[return_session] fn get_display_controller(&self) -> DisplayController; #[ipc_rid(10)] #[return_session] fn get_process_winding_controller(&self) -> ProcessWindingController; #[ipc_rid(11)] #[return_session] fn get_library_applet_creator(&self) -> LibraryAppletCreator; } #[nx_derive::ipc_trait] #[default_client] pub trait SystemApplicationProxy { #[ipc_rid(0)] #[return_session] fn get_common_state_getter(&self) -> CommonStateGetter; #[ipc_rid(1)] #[return_session] fn get_self_controller(&self) -> SelfController; #[ipc_rid(2)] #[return_session] fn get_window_controller(&self) -> WindowController; #[ipc_rid(3)] #[return_session] fn get_audio_controller(&self) -> AudioController; #[ipc_rid(4)] #[return_session] fn get_display_controller(&self) -> DisplayController; #[ipc_rid(10)] #[return_session] fn get_process_winding_controller(&self) -> ProcessWindingController; #[ipc_rid(11)] #[return_session] fn get_library_applet_creator(&self) -> LibraryAppletCreator; } #[nx_derive::ipc_trait] pub trait AllSystemAppletProxies { #[ipc_rid(0)] #[return_session] fn open_application_proxy( &self, process_id: sf::ProcessId, self_process_handle: sf::CopyHandle, ) -> ApplicationProxy; #[ipc_rid(100)] #[return_session] fn open_system_applet_proxy( &self, process_id: sf::ProcessId, self_process_handle: sf::CopyHandle, ) -> SystemAppletProxy; #[ipc_rid(200)] #[return_session] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn open_library_applet_proxy_old( &self, process_id: sf::ProcessId, self_process_handle: sf::CopyHandle, ) -> LibraryAppletProxy; #[ipc_rid(201)] #[return_session] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn open_library_applet_proxy( &self, process_id: sf::ProcessId, self_process_handle: sf::CopyHandle, applet_attribute: sf::InMapAliasBuffer<'_, AppletAttribute>, ) -> LibraryAppletProxy; #[ipc_rid(300)] #[return_session] fn open_overlay_applet_proxy( &self, process_id: sf::ProcessId, self_process_handle: sf::CopyHandle, ) -> OverlayAppletProxy; #[ipc_rid(350)] #[return_session] fn open_system_application_proxy( &self, process_id: sf::ProcessId, self_process_handle: sf::CopyHandle, ) -> SystemApplicationProxy; } pub trait ProxyCommon { fn get_common_state_getter(&self) -> Result<CommonStateGetter>; fn get_self_controller(&self) -> Result<SelfController>; fn get_window_controller(&self) -> Result<WindowController>; fn get_audio_controller(&self) -> Result<AudioController>; fn get_display_controller(&self) -> Result<DisplayController>; fn get_process_winding_controller(&self) -> Result<ProcessWindingController>; fn get_library_applet_creator(&self) -> Result<LibraryAppletCreator>; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/sm.rs
src/ipc/sf/sm.rs
use crate::ipc::sf; use crate::util; use crate::version; pub mod mitm; pub mod rc; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, Eq)] #[repr(C)] pub union ServiceName { pub value: u64, pub name: [u8; 8], } const_assert!(core::mem::size_of::<ServiceName>() == 0x8); impl ServiceName { pub const fn from(value: u64) -> Self { Self { value } } pub const fn new(name: &str) -> Self { let mut raw_name: [u8; 8] = [0; 8]; let name_bytes = name.as_bytes(); let copy_len = util::const_usize_min(8, name_bytes.len()); unsafe { core::ptr::copy_nonoverlapping(name_bytes.as_ptr(), raw_name.as_mut_ptr(), copy_len) } Self { name: raw_name } } pub const fn empty() -> Self { Self::from(0) } pub const fn is_empty(&self) -> bool { unsafe { self.value == 0 } } } impl PartialEq for ServiceName { fn eq(&self, other: &Self) -> bool { unsafe { self.value == other.value } } } impl core::fmt::Debug for ServiceName { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { unsafe { self.name.fmt(f) } } } #[nx_derive::ipc_trait] #[default_client] pub trait UserInterface { #[ipc_rid(0)] fn register_client(&self, process_id: sf::ProcessId); #[ipc_rid(1)] fn get_service_handle(&self, name: ServiceName) -> sf::MoveHandle; #[ipc_rid(2)] fn register_service( &self, name: ServiceName, is_light: bool, max_sessions: i32, ) -> sf::MoveHandle; #[ipc_rid(3)] fn unregister_service(&self, name: ServiceName); #[ipc_rid(4)] #[version(version::VersionInterval::from(version::Version::new(11, 0, 0)))] fn detach_client(&self, process_id: sf::ProcessId); #[ipc_rid(65000)] fn atmosphere_install_mitm(&self, name: ServiceName) -> (sf::MoveHandle, sf::MoveHandle); #[ipc_rid(65001)] fn atmosphere_uninstall_mitm(&self, name: ServiceName); #[ipc_rid(65003)] fn atmosphere_acknowledge_mitm_session( &self, name: ServiceName, ) -> (mitm::MitmProcessInfo, sf::MoveHandle); #[ipc_rid(65004)] fn atmosphere_has_mitm(&self, name: ServiceName) -> bool; #[ipc_rid(65005)] fn atmosphere_wait_mitm(&self, name: ServiceName); #[ipc_rid(65006)] fn atmosphere_declare_future_mitm(&self, name: ServiceName); #[ipc_rid(65007)] fn atmosphere_clear_future_mitm(&self, name: ServiceName); #[ipc_rid(65100)] fn atmosphere_has_service(&self, name: ServiceName) -> bool; #[ipc_rid(65101)] fn atmosphere_wait_service(&self, name: ServiceName); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/spl.rs
src/ipc/sf/spl.rs
use crate::ipc::sf; #[nx_derive::ipc_trait] pub trait Random { #[ipc_rid(0)] fn generate_random_bytes(&self, out_buf: sf::OutMapAliasBuffer<'_, u8>); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/dispdrv.rs
src/ipc/sf/dispdrv.rs
use crate::ipc::sf; use crate::version; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum RefcountType { Weak, Strong, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum ParcelTransactionId { RequestBuffer = 1, SetBufferCount = 2, DequeueBuffer = 3, DetachBuffer = 4, DetachNextBuffer = 5, AttachBuffer = 6, QueueBuffer = 7, CancelBuffer = 8, Query = 9, Connect = 10, Disconnect = 11, SetSidebandStream = 12, AllocateBuffers = 13, SetPreallocatedBuffer = 14, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum NativeHandleType { BufferEvent = 0xF, } pub type BinderHandle = i32; #[nx_derive::ipc_trait] #[default_client] pub trait HOSBinderDriver { #[ipc_rid(0)] fn transact_parcel( &self, binder_handle: BinderHandle, transaction_id: ParcelTransactionId, flags: u32, in_parcel: sf::InMapAliasBuffer<'_, u8>, out_parcel: sf::OutMapAliasBuffer<'_, u8>, ); #[ipc_rid(1)] fn adjust_refcount( &self, binder_handle: BinderHandle, add_value: i32, refcount_type: RefcountType, ); #[ipc_rid(2)] fn get_native_handle( &self, binder_handle: BinderHandle, handle_type: NativeHandleType, ) -> sf::CopyHandle; #[ipc_rid(3)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn transact_parcel_auto( &self, binder_handle: BinderHandle, transaction_id: ParcelTransactionId, flags: u32, in_parcel: sf::InAutoSelectBuffer<'_, u8>, out_parcel: sf::OutAutoSelectBuffer<'_, u8>, ); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/psm.rs
src/ipc/sf/psm.rs
#[nx_derive::ipc_trait] pub trait Psm { #[ipc_rid(0)] fn get_battery_charge_percentage(&self) -> u32; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/hid.rs
src/ipc/sf/hid.rs
use crate::ipc::sf; use crate::result::*; use crate::version; use super::CopyHandle; use super::applet::AppletResourceUserId; pub mod shmem; use enum_iterator::{All, Sequence}; use nx_derive::{Request, Response}; define_bit_set! { DebugPadAttribute (u32) { IsConnected = bit!(0) } } define_bit_set! { DebugPadButton (u32) { A = bit!(0), B = bit!(1), X = bit!(2), Y = bit!(3), L = bit!(4), R = bit!(5), ZL = bit!(6), ZR = bit!(7), Start = bit!(8), Select = bit!(9), Left = bit!(10), Up = bit!(11), Right = bit!(12), Down = bit!(13) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct AnalogStickState { pub x: i32, pub y: i32, } define_bit_set! { TouchAttribute (u32) { None = 0, Start = bit!(0), End = bit!(1) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct TouchState { pub delta_time: u64, pub attributes: TouchAttribute, pub finger_id: u32, pub x: u32, pub y: u32, pub diameter_x: u32, pub diameter_y: u32, pub rotation_angle: u32, pub reserved: [u8; 4], } define_bit_set! { MouseAttribute (u32) { Transferable = bit!(0), IsConnected = bit!(1) } } define_bit_set! { MouseButton (u32) { Left = bit!(0), Right = bit!(1), Middle = bit!(2), Forward = bit!(3), Back = bit!(4) } } define_bit_set! { KeyboardModifier (u64) { Control = bit!(0), Shift = bit!(1), LeftAlt = bit!(2), RightAlt = bit!(3), Gui = bit!(4), CapsLock = bit!(8), ScrollLock = bit!(9), NumLock = bit!(10), Katakana = bit!(11), Hiragana = bit!(12) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct KeyboardKeyStates { pub key_bitfield: [u8; 0x20], } impl KeyboardKeyStates { /// Check if a particular key is depressed #[inline] pub fn is_down(&self, key: KeyboardKey) -> bool { let key_offset = key.bit_offset(); (self.key_bitfield[key_offset >> 3] >> (key_offset & 7)) & 1 == 1 } /// Check if a particular key is not depressed #[inline(always)] pub fn is_up(&self, key: KeyboardKey) -> bool { !self.is_down(key) } } pub struct KeyboardKeyDownIter(KeyboardKeyStates, All<KeyboardKey>); impl Iterator for KeyboardKeyDownIter { type Item = KeyboardKey; fn next(&mut self) -> Option<Self::Item> { loop { let key = self.1.next()?; let key_offset = key.bit_offset(); if (self.0.key_bitfield[key_offset >> 3] >> (key_offset & 0b111)) & 1 == 1 { return Some(key); } } } } impl IntoIterator for KeyboardKeyStates { type Item = KeyboardKey; type IntoIter = KeyboardKeyDownIter; fn into_iter(self) -> Self::IntoIter { KeyboardKeyDownIter(self, enum_iterator::all::<Self::Item>()) } } #[derive(Debug, Clone, Copy, Sequence)] pub enum KeyboardKey { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, D1, D2, D3, D4, D5, D6, D7, D8, D9, D0, Return, Escape, Backspace, Tab, Space, Minus, Plus, OpenBracket, CloseBracket, Pipe, Tilde, Semicolon, Quote, Backquote, Comma, Period, Slash, CapsLock, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, PrintScreen, ScrollLock, Pause, Insert, Home, PageUp, Delete, End, PageDown, RightArrow, LeftArrow, DownArrow, UpArrow, NumLock, NumPadDivide, NumPadMultiply, NumPadSubtract, NumPadAdd, NumPadEnter, NumPad1, NumPad2, NumPad3, NumPad4, NumPad5, NumPad6, NumPad7, NumPad8, NumPad9, NumPad0, NumPadDot, Backslash, Application, Power, NumPadEquals, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, NumPadComma, Ro, KatakanaHiragana, Yen, Henkan, Muhenkan, NumPadCommaPc98, HangulEnglish, Hanja, Katakana, Hiragana, ZenkakuHankaku, LeftControl, LeftShift, LeftAlt, LeftGui, RightControl, RightShift, RightAlt, RightGui, } impl KeyboardKey { fn bit_offset(&self) -> usize { match *self { KeyboardKey::A => 4, KeyboardKey::B => 5, KeyboardKey::C => 6, KeyboardKey::D => 7, KeyboardKey::E => 8, KeyboardKey::F => 9, KeyboardKey::G => 10, KeyboardKey::H => 11, KeyboardKey::I => 12, KeyboardKey::J => 13, KeyboardKey::K => 14, KeyboardKey::L => 15, KeyboardKey::M => 16, KeyboardKey::N => 17, KeyboardKey::O => 18, KeyboardKey::P => 19, KeyboardKey::Q => 20, KeyboardKey::R => 21, KeyboardKey::S => 22, KeyboardKey::T => 23, KeyboardKey::U => 24, KeyboardKey::V => 25, KeyboardKey::W => 26, KeyboardKey::X => 27, KeyboardKey::Y => 28, KeyboardKey::Z => 29, KeyboardKey::D1 => 30, KeyboardKey::D2 => 31, KeyboardKey::D3 => 32, KeyboardKey::D4 => 33, KeyboardKey::D5 => 34, KeyboardKey::D6 => 35, KeyboardKey::D7 => 36, KeyboardKey::D8 => 37, KeyboardKey::D9 => 38, KeyboardKey::D0 => 39, KeyboardKey::Return => 40, KeyboardKey::Escape => 41, KeyboardKey::Backspace => 42, KeyboardKey::Tab => 43, KeyboardKey::Space => 44, KeyboardKey::Minus => 45, KeyboardKey::Plus => 46, KeyboardKey::OpenBracket => 47, KeyboardKey::CloseBracket => 48, KeyboardKey::Pipe => 49, KeyboardKey::Tilde => 50, KeyboardKey::Semicolon => 51, KeyboardKey::Quote => 52, KeyboardKey::Backquote => 53, KeyboardKey::Comma => 54, KeyboardKey::Period => 55, KeyboardKey::Slash => 56, KeyboardKey::CapsLock => 57, KeyboardKey::F1 => 58, KeyboardKey::F2 => 59, KeyboardKey::F3 => 60, KeyboardKey::F4 => 61, KeyboardKey::F5 => 62, KeyboardKey::F6 => 63, KeyboardKey::F7 => 64, KeyboardKey::F8 => 65, KeyboardKey::F9 => 66, KeyboardKey::F10 => 67, KeyboardKey::F11 => 68, KeyboardKey::F12 => 69, KeyboardKey::PrintScreen => 70, KeyboardKey::ScrollLock => 71, KeyboardKey::Pause => 72, KeyboardKey::Insert => 73, KeyboardKey::Home => 74, KeyboardKey::PageUp => 75, KeyboardKey::Delete => 76, KeyboardKey::End => 77, KeyboardKey::PageDown => 78, KeyboardKey::RightArrow => 79, KeyboardKey::LeftArrow => 80, KeyboardKey::DownArrow => 81, KeyboardKey::UpArrow => 82, KeyboardKey::NumLock => 83, KeyboardKey::NumPadDivide => 84, KeyboardKey::NumPadMultiply => 85, KeyboardKey::NumPadSubtract => 86, KeyboardKey::NumPadAdd => 87, KeyboardKey::NumPadEnter => 88, KeyboardKey::NumPad1 => 89, KeyboardKey::NumPad2 => 90, KeyboardKey::NumPad3 => 91, KeyboardKey::NumPad4 => 92, KeyboardKey::NumPad5 => 93, KeyboardKey::NumPad6 => 94, KeyboardKey::NumPad7 => 95, KeyboardKey::NumPad8 => 96, KeyboardKey::NumPad9 => 97, KeyboardKey::NumPad0 => 98, KeyboardKey::NumPadDot => 99, KeyboardKey::Backslash => 100, KeyboardKey::Application => 101, KeyboardKey::Power => 102, KeyboardKey::NumPadEquals => 103, KeyboardKey::F13 => 104, KeyboardKey::F14 => 105, KeyboardKey::F15 => 106, KeyboardKey::F16 => 107, KeyboardKey::F17 => 108, KeyboardKey::F18 => 109, KeyboardKey::F19 => 110, KeyboardKey::F20 => 111, KeyboardKey::F21 => 112, KeyboardKey::F22 => 113, KeyboardKey::F23 => 114, KeyboardKey::F24 => 115, KeyboardKey::NumPadComma => 133, KeyboardKey::Ro => 135, KeyboardKey::KatakanaHiragana => 136, KeyboardKey::Yen => 137, KeyboardKey::Henkan => 138, KeyboardKey::Muhenkan => 139, KeyboardKey::NumPadCommaPc98 => 140, KeyboardKey::HangulEnglish => 144, KeyboardKey::Hanja => 145, KeyboardKey::Katakana => 146, KeyboardKey::Hiragana => 147, KeyboardKey::ZenkakuHankaku => 148, KeyboardKey::LeftControl => 224, KeyboardKey::LeftShift => 225, KeyboardKey::LeftAlt => 226, KeyboardKey::LeftGui => 227, KeyboardKey::RightControl => 228, KeyboardKey::RightShift => 229, KeyboardKey::RightAlt => 230, KeyboardKey::RightGui => 231, } } pub fn get_ansi(&self) -> Option<&'static str> { match *self { Self::A => Some("a"), Self::B => Some("b"), Self::C => Some("c"), Self::D => Some("d"), Self::E => Some("e"), Self::F => Some("f"), Self::G => Some("g"), Self::H => Some("h"), Self::I => Some("i"), Self::J => Some("j"), Self::K => Some("k"), Self::L => Some("l"), Self::M => Some("m"), Self::N => Some("n"), Self::O => Some("o"), Self::P => Some("p"), Self::Q => Some("q"), Self::R => Some("r"), Self::S => Some("s"), Self::T => Some("t"), Self::U => Some("u"), Self::V => Some("v"), Self::W => Some("w"), Self::X => Some("x"), Self::Y => Some("y"), Self::Z => Some("z"), Self::Return => Some("\r\n"), Self::Backquote => Some("`"), Self::Backslash => Some("\\"), Self::Comma => Some(","), Self::CloseBracket => Some(")"), Self::OpenBracket => Some("("), Self::DownArrow => Some("\x1b[(224;80)"), Self::UpArrow => Some("\x1b[(224;72)"), Self::Minus => Some("-"), Self::Plus => Some("+"), Self::LeftArrow => Some("\x1B[(224;75)"), Self::RightArrow => Some("\x1B[(224;77)"), Self::F1 => Some("\x1b[0;59"), Self::F2 => Some("\x1b[0;60"), Self::F3 => Some("\x1b[0;61"), Self::F4 => Some("\x1b[0;62"), Self::F5 => Some("\x1b[0;63"), Self::F6 => Some("\x1b[0;64"), Self::F7 => Some("\x1b[0;65"), Self::F8 => Some("\x1b[0;66"), Self::F9 => Some("\x1b[0;67"), Self::F10 => Some("\x1b[0;68"), Self::F11 => Some("\x1b[0;133"), Self::F12 => Some("\x1b[0;134"), Self::Home => Some("\x1b[(224;71)"), Self::End => Some("\x1b[(224;79)"), // TODO: More - https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797 _ => None, } } } define_bit_set! { BasicXpadAttribute (u32) { // TODO: are these known at all? } } define_bit_set! { BasicXpadButton (u32) { // TODO: are these known at all? } } define_bit_set! { DigitizerAttribute (u32) { // TODO: are these known at all? } } define_bit_set! { DigitizerButton (u32) { // TODO: are these known at all? } } define_bit_set! { HomeButton (u32) { // TODO: are these known at all? } } define_bit_set! { SleepButton (u32) { // TODO: are these known at all? } } define_bit_set! { CaptureButton (u32) { // TODO: are these known at all? } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct InputSourceState { pub timestamp: u64, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum UniquePadType { Embedded = 0, FullKeyController = 1, RightController = 2, LeftController = 3, DebugPadController = 4, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum UniquePadInterface { Embedded = 0, Rail = 1, Bluetooth = 2, Usb = 3, } pub type UniquePadSerialNumber = [u8; 0x10]; define_bit_set! { AnalogStickCalibrationFlags (u32) { // TODO: are these known at all? } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum AnalogStickManualCalibrationStage { ReleaseFromRight = 0, ReleaseFromBottom = 1, ReleaseFromLeft = 2, ReleaseFromTop = 3, Rotate = 4, Update = 5, Completed = 6, Clear = 7, ClearCompleted = 8, } define_bit_set! { SixAxisSensorUserCalibrationFlags (u32) { // TODO: are these known at all? } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum SixAxisSensorUserCalibrationStage { Measuring = 0, Update = 1, Completed = 2, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum GestureType { Idle = 0, Complete = 1, Cancel = 2, Touch = 3, Press = 4, Tap = 5, Pan = 6, Swipe = 7, Pinch = 8, Rotate = 9, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum GestureDirection { None = 0, Left = 1, Up = 2, Right = 3, Down = 4, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct GesturePoint { pub x: u32, pub y: u32, } define_bit_set! { GestureAttribute (u32) { IsNewTouch = bit!(4), IsDoubleTap = bit!(8) } } define_bit_set! { NpadStyleTag (u32) { FullKey = bit!(0), // Pro controller Handheld = bit!(1), // Joy-Con controller in handheld mode JoyDual = bit!(2), // Joy-Con controller in dual mode JoyLeft = bit!(3), // Joy-Con left controller in single mode JoyRight = bit!(4), // Joy-Con right controller in single mode Gc = bit!(5), // GameCube controller Palma = bit!(6), // Poké Ball Plus controller Lark = bit!(7), // NES/Famicom controller HandheldLark = bit!(8), // NES/Famicom controller (handheld) Lucia = bit!(9), // SNES controller Lagon = bit!(10), // N64 controller Lager = bit!(11), // Sega Genesis controller SystemExt = bit!(29), // Generic external controller System = bit!(30) // Generic controller } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(i64)] pub enum NpadJoyDeviceType { Left = 0, Right = 1, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum NpadIdType { No1 = 0, // Players 1-8 No2 = 1, No3 = 2, No4 = 3, No5 = 4, No6 = 5, No7 = 6, No8 = 7, Other = 0x10, Handheld = 0x20, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum NpadJoyAssignmentMode { Dual = 0, Single = 1, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum ColorAttribute { Ok = 0, ReadError = 1, NoController = 2, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadControllerColor { pub main: u32, pub sub: u32, } define_bit_set! { NpadButton (u64) { A = bit!(0), B = bit!(1), X = bit!(2), Y = bit!(3), StickL = bit!(4), StickR = bit!(5), L = bit!(6), R = bit!(7), ZL = bit!(8), ZR = bit!(9), Plus = bit!(10), Minus = bit!(11), Left = bit!(12), Up = bit!(13), Right = bit!(14), Down = bit!(15), StickLLeft = bit!(16), StickLUp = bit!(17), StickLRight = bit!(18), StickLDown = bit!(19), StickRLeft = bit!(20), StickRUp = bit!(21), StickRRight = bit!(22), StickRDown = bit!(23), LeftSL = bit!(24), LeftSR = bit!(25), RightSL = bit!(26), RightSR = bit!(27), Palma = bit!(28), Verification = bit!(29), HandheldLeftB = bit!(30), LagonCLeft = bit!(31), LagonCUp = bit!(32), LagonCRight = bit!(33), LagonCDown = bit!(34) } } define_bit_set! { NpadAttribute (u32) { IsConnected = bit!(0), IsWired = bit!(1), IsLeftConnected = bit!(2), IsLeftWired = bit!(3), IsRightConnected = bit!(4), IsRightWired = bit!(5) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct DirectionState { pub xx: u32, pub xy: u32, pub xz: u32, pub yx: u32, pub yy: u32, pub yz: u32, pub zx: u32, pub zy: u32, pub zz: u32, } define_bit_set! { SixAxisSensorAttribute (u32) { IsConnected = bit!(0), IsInterpolated = bit!(1) } } define_bit_set! { DeviceType (u32) { FullKey = bit!(0), DebugPad = bit!(1), HandheldLeft = bit!(2), HandheldRight = bit!(3), JoyLeft = bit!(4), JoyRight = bit!(5), Palma = bit!(6), LarkHvcLeft = bit!(7), LarkHvcRight = bit!(8), LarkNesLeft = bit!(9), LarkNesRight = bit!(10), HandheldLarkHvcLeft = bit!(11), HandheldLarkHvcRight = bit!(12), HandheldLarkNesLeft = bit!(13), HandheldLarkNesRight = bit!(14), Lucia = bit!(15), Lagon = bit!(16), Lager = bit!(17), System = bit!(31) } } define_bit_set! { NpadSystemProperties (u64) { IsChargingJoyDual = bit!(0), IsChargingJoyLeft = bit!(1), IsChargingJoyRight = bit!(2), IsPoweredJoyDual = bit!(3), IsPoweredJoyLeft = bit!(4), IsPoweredJoyRight = bit!(5), IsUnsuportedButtonPressedOnNpadSystem = bit!(9), IsUnsuportedButtonPressedOnNpadSystemExt = bit!(10), IsAbxyButtonOriented = bit!(11), IsSlSrButtonOriented = bit!(12), IsPlusAvailable = bit!(13), IsMinusAvailable = bit!(14), IsDirectionalButtonsAvailable = bit!(15) } } define_bit_set! { NpadSystemButtonProperties (u32) { IsUnintendedHomeButtonInputProtectionEnabled = bit!(0) } } pub type NpadBatteryLevel = u32; define_bit_set! { AppletFooterUiAttribute (u32) { // TODO: are these known at all? } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum AppletFooterUiType { None = 0, HandheldNone = 1, HandheldJoyConLeftOnly = 2, HandheldJoyConRightOnly = 3, HandheldJoyConLeftJoyConRight = 4, JoyDual = 5, JoyDualLeftOnly = 6, JoyDualRightOnly = 7, JoyLeftHorizontal = 8, JoyLeftVertical = 9, JoyRightHorizontal = 10, JoyRightVertical = 11, SwitchProController = 12, CompatibleProController = 13, CompatibleJoyCon = 14, LarkHvc1 = 15, LarkHvc2 = 16, LarkNesLeft = 17, LarkNesRight = 18, Lucia = 19, Verification = 20, Lagon = 21, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum NpadLarkType { Invalid = 0, H1 = 1, H2 = 2, NL = 3, NR = 4, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum NpadLuciaType { Invalid = 0, J = 1, E = 2, U = 3, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum NpadLagerType { Invalid = 0, J = 1, E = 2, U = 3, } define_bit_set! { SixAxisSensorProperties (u8) { IsSixAxisSensorDeviceNewlyAssigned = bit!(0), IsFirmwareUpdateAvailableForSixAxisSensor = bit!(1) } } define_bit_set! { LockKeyFlags (u32) { NumLockOn = bit!(0), NumLockOff = bit!(1), NumLockToggle = bit!(2), CapsLockOn = bit!(3), CapsLockOff = bit!(4), CapsLockToggle = bit!(5), ScrollLockOn = bit!(6), ScrollLockOff = bit!(7), ScrollLockToggle = bit!(8) } } #[nx_derive::ipc_trait] #[default_client] pub trait AppletResource { #[ipc_rid(0)] fn get_shared_memory_handle(&mut self) -> sf::CopyHandle; } #[nx_derive::ipc_trait] pub trait Hid { #[ipc_rid(0)] #[return_session] fn create_applet_resource(&mut self, aruid: AppletResourceUserId) -> AppletResource; #[ipc_rid(100)] fn set_supported_npad_style_set( &mut self, npad_style_tag: NpadStyleTag, aruid: AppletResourceUserId, ); #[ipc_rid(101)] fn get_supported_npad_style_set(&self, aruid: AppletResourceUserId) -> NpadStyleTag; #[ipc_rid(102)] fn set_supported_npad_id_type( &mut self, aruid: AppletResourceUserId, npad_ids: sf::InPointerBuffer<'_, NpadIdType>, ); #[ipc_rid(103)] fn activate_npad(&mut self, aruid: AppletResourceUserId); #[ipc_rid(104)] fn deactivate_npad(&mut self, aruid: AppletResourceUserId); #[ipc_rid(109)] fn activate_npad_with_revision(&mut self, revision: i32, aruid: AppletResourceUserId); #[ipc_rid(123)] fn set_npad_joy_assignment_mode_single( &mut self, npad_id: NpadIdType, aruid: AppletResourceUserId, joy_type: NpadJoyDeviceType, ); #[ipc_rid(124)] fn set_npad_joy_assignment_mode_dual( &mut self, npad_id: NpadIdType, aruid: AppletResourceUserId, ); } #[nx_derive::ipc_trait] pub trait HidSys { #[ipc_rid(31)] fn send_keyboard_lock_key_event(&self, flags: LockKeyFlags); #[ipc_rid(101)] fn acquire_home_button_event_handle(&self, aruid: AppletResourceUserId) -> CopyHandle; #[ipc_rid(111)] fn activate_home_button(&self, aruid: AppletResourceUserId); #[ipc_rid(121)] fn acquire_sleep_button_event_handle(&self, aruid: AppletResourceUserId) -> CopyHandle; #[ipc_rid(131)] fn activate_sleep_button(&self, aruid: AppletResourceUserId); #[ipc_rid(141)] fn acquire_capture_button_event_handle(&self, aruid: AppletResourceUserId) -> CopyHandle; #[ipc_rid(151)] fn activate_capture_button(&self, aruid: AppletResourceUserId); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/nfp.rs
src/ipc/sf/nfp.rs
use crate::ipc::sf; use crate::ipc::sf::applet; use crate::ipc::sf::hid; use crate::ipc::sf::mii; use crate::util; use crate::version; use super::ncm; use nx_derive::{Request, Response}; pub mod rc; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct McuVersionData { pub version: u64, pub reserved: [u8; 0x18], } const_assert!(core::mem::size_of::<McuVersionData>() == 0x20); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct DeviceHandle { pub id: u32, pub reserved: [u8; 4], } const_assert!(core::mem::size_of::<DeviceHandle>() == 0x8); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum State { NonInitialized = 0, Initialized = 1, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum DeviceState { Initialized = 0, SearchingForTag = 1, TagFound = 2, TagRemoved = 3, TagMounted = 4, Unavailable = 5, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum ModelType { Amiibo = 0, } define_bit_set! { MountTarget (u32) { Rom = bit!(0), Ram = bit!(1) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct Date { pub year: u16, pub month: u8, pub day: u8, } const_assert!(core::mem::size_of::<Date>() == 0x4); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct TagId { pub uuid: [u8; 10], pub uuid_length: u8, pub reserved_1: [u8; 0x15], } const_assert!(core::mem::size_of::<TagId>() == 0x20); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct TagInfo { pub uid: TagId, pub protocol: u32, pub tag_type: u32, pub reserved_2: [u8; 0x30], } const_assert!(core::mem::size_of::<TagInfo>() == 0x58); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct RegisterInfo { pub mii_charinfo: mii::CharInfo, pub first_write_date: Date, pub name: util::ArrayString<41>, pub font_region: u8, pub reserved: [u8; 0x7A], } const_assert!(core::mem::size_of::<RegisterInfo>() == 0x100); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct CommonInfo { pub last_write_date: Date, pub write_counter: u16, pub version: u8, pub pad: u8, pub application_area_size: u32, pub reserved: [u8; 0x34], } const_assert!(core::mem::size_of::<CommonInfo>() == 0x40); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct ModelInfo { pub character_id: [u8; 3], pub series_id: u8, pub numbering_id: u16, pub nfp_type: u8, pub reserved: [u8; 0x39], } const_assert!(core::mem::size_of::<ModelInfo>() == 0x40); pub type AccessId = u32; define_bit_set! { AdminInfoFlags (u8) { // Note: plain amiibo flags shifted 4 bits (original bits 0-3 are discarded) IsInitialized = bit!(0), HasApplicationArea = bit!(1) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum ApplicationAreaVersion { // Note: unofficial name #[default] Default = 0, NintendoWiiU = 1, Nintendo3DS = 2, NintendoSwitch = 3, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct AdminInfo { pub app_id: ncm::ProgramId, pub access_id: AccessId, pub terminal_id_crc32_change_counter: u16, pub flags: AdminInfoFlags, pub unk: u8, pub app_area_version: ApplicationAreaVersion, pub pad: [u8; 0x7], pub reserved: [u8; 0x28], } const_assert!(core::mem::size_of::<AdminInfo>() == 0x40); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct RegisterInfoPrivate { pub mii_store_data: mii::StoreData, pub first_write_date: Date, pub name: util::ArrayString<41>, pub font_region: u8, pub reserved: [u8; 0x8E], } const_assert!(core::mem::size_of::<RegisterInfoPrivate>() == 0x100); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NfpData { pub header_magic: u8, pub reserved: u8, pub header_write_counter: u16, pub terminal_id_crc32: u32, pub reserved_2: [u8; 0x38], pub common_info: CommonInfo, pub mii_v3: mii::Ver3StoreData, pub pad: [u8; 2], pub mii_crc16: u16, pub mii_store_data_extension: mii::NfpStoreDataExtension, pub first_write_date: Date, pub name: util::ArrayWideString<11>, pub font_region: u8, pub unk_1: u8, pub mii_crc32: u32, pub unk_2: [u8; 0x14], pub reserved_3: [u8; 100], pub modified_app_id: u64, pub access_id: AccessId, pub terminal_id_crc32_change_counter: u16, pub flags: AdminInfoFlags, pub unk_3: u8, pub app_id_byte: u8, pub reserved_4: [u8; 0x2E], pub app_area: [u8; 0xD8], } const_assert!(core::mem::size_of::<NfpData>() == 0x298); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum BreakType { // Note: unofficial names FlushOnly = 0, BreakDataHash = 1, BreakHeaderMagic = 2, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum WriteType { Unk0 = 0, Unk1 = 1, } #[nx_derive::ipc_trait] #[default_client] pub trait User { #[ipc_rid(0)] fn initialize( &self, aruid: applet::AppletResourceUserId, process_id: sf::ProcessId, mcu_data: sf::InMapAliasBuffer<'_, McuVersionData>, ); #[ipc_rid(1)] fn finalize(&self); #[ipc_rid(2)] fn list_devices(&self, out_devices: sf::OutPointerBuffer<'_, DeviceHandle>) -> u32; #[ipc_rid(3)] fn start_detection(&self, device_handle: DeviceHandle); #[ipc_rid(4)] fn stop_detection(&self, device_handle: DeviceHandle); #[ipc_rid(5)] fn mount(&self, device_handle: DeviceHandle, model_type: ModelType, mount_target: MountTarget); #[ipc_rid(6)] fn unmount(&self, device_handle: DeviceHandle); #[ipc_rid(7)] fn open_application_area(&self, device_handle: DeviceHandle, access_id: AccessId); #[ipc_rid(8)] fn get_application_area( &self, device_handle: DeviceHandle, out_data: sf::OutMapAliasBuffer<'_, u8>, ) -> u32; #[ipc_rid(9)] fn set_application_area(&self, device_handle: DeviceHandle, data: sf::InMapAliasBuffer<'_, u8>); #[ipc_rid(10)] fn flush(&self, device_handle: DeviceHandle); #[ipc_rid(11)] fn restore(&self, device_handle: DeviceHandle); #[ipc_rid(12)] fn create_application_area( &self, device_handle: DeviceHandle, access_id: AccessId, data: sf::InMapAliasBuffer<'_, u8>, ); #[ipc_rid(13)] fn get_tag_info( &self, device_handle: DeviceHandle, out_tag_info: sf::OutFixedPointerBuffer<'_, TagInfo>, ); #[ipc_rid(14)] fn get_register_info( &self, device_handle: DeviceHandle, out_register_info: sf::OutFixedPointerBuffer<'_, RegisterInfo>, ); #[ipc_rid(15)] fn get_common_info( &self, device_handle: DeviceHandle, out_common_info: sf::OutFixedPointerBuffer<'_, CommonInfo>, ); #[ipc_rid(16)] fn get_model_info( &self, device_handle: DeviceHandle, out_model_info: sf::OutFixedPointerBuffer<'_, ModelInfo>, ); #[ipc_rid(17)] fn attach_activate_event(&self, device_handle: DeviceHandle) -> sf::CopyHandle; #[ipc_rid(18)] fn attach_deactivate_event(&self, device_handle: DeviceHandle) -> sf::CopyHandle; #[ipc_rid(19)] fn get_state(&self) -> State; #[ipc_rid(20)] fn get_device_state(&self, device_handle: DeviceHandle) -> DeviceState; #[ipc_rid(21)] fn get_npad_id(&self, device_handle: DeviceHandle) -> hid::NpadIdType; #[ipc_rid(22)] fn get_application_area_size(&self, device_handle: DeviceHandle) -> u32; #[ipc_rid(23)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn attach_availability_change_event(&self) -> sf::CopyHandle; #[ipc_rid(24)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn recreate_application_area( &self, device_handle: DeviceHandle, access_id: AccessId, data: sf::InMapAliasBuffer<'_, u8>, ); } #[nx_derive::ipc_trait] pub trait UserManager { #[ipc_rid(0)] #[return_session] fn create_user_interface(&self) -> User; } #[nx_derive::ipc_trait] #[default_client] pub trait System { #[ipc_rid(0)] fn initialize( &self, aruid: applet::AppletResourceUserId, process_id: sf::ProcessId, mcu_data: sf::InMapAliasBuffer<'_, McuVersionData>, ); #[ipc_rid(1)] fn finalize(&self); #[ipc_rid(2)] fn list_devices(&self, out_devices: sf::OutPointerBuffer<'_, DeviceHandle>) -> u32; #[ipc_rid(3)] fn start_detection(&self, device_handle: DeviceHandle); #[ipc_rid(4)] fn stop_detection(&self, device_handle: DeviceHandle); #[ipc_rid(5)] fn mount(&self, device_handle: DeviceHandle, model_type: ModelType, mount_target: MountTarget); #[ipc_rid(6)] fn unmount(&self, device_handle: DeviceHandle); #[ipc_rid(10)] fn flush(&self, device_handle: DeviceHandle); #[ipc_rid(11)] fn restore(&self, device_handle: DeviceHandle); #[ipc_rid(13)] fn get_tag_info( &self, device_handle: DeviceHandle, out_tag_info: sf::OutFixedPointerBuffer<'_, TagInfo>, ); #[ipc_rid(14)] fn get_register_info( &self, device_handle: DeviceHandle, out_register_info: sf::OutFixedPointerBuffer<'_, RegisterInfo>, ); #[ipc_rid(15)] fn get_common_info( &self, device_handle: DeviceHandle, out_common_info: sf::OutFixedPointerBuffer<'_, CommonInfo>, ); #[ipc_rid(16)] fn get_model_info( &self, device_handle: DeviceHandle, out_model_info: sf::OutFixedPointerBuffer<'_, ModelInfo>, ); #[ipc_rid(17)] fn attach_activate_event(&self, device_handle: DeviceHandle) -> sf::CopyHandle; #[ipc_rid(18)] fn attach_deactivate_event(&self, device_handle: DeviceHandle) -> sf::CopyHandle; #[ipc_rid(19)] fn get_state(&self) -> State; #[ipc_rid(20)] fn get_device_state(&self, device_handle: DeviceHandle) -> DeviceState; #[ipc_rid(21)] fn get_npad_id(&self, device_handle: DeviceHandle) -> hid::NpadIdType; #[ipc_rid(23)] fn attach_availability_change_event(&self) -> sf::CopyHandle; #[ipc_rid(100)] fn format(&self, device_handle: DeviceHandle); #[ipc_rid(101)] fn get_admin_info( &self, device_handle: DeviceHandle, out_admin_info: sf::OutFixedPointerBuffer<'_, AdminInfo>, ); #[ipc_rid(102)] fn get_register_info_private( &self, device_handle: DeviceHandle, out_register_info_private: sf::OutFixedPointerBuffer<'_, RegisterInfoPrivate>, ); #[ipc_rid(103)] fn set_register_info_private( &self, device_handle: DeviceHandle, register_info_private: sf::InFixedPointerBuffer<'_, RegisterInfoPrivate>, ); #[ipc_rid(104)] fn delete_register_info(&self, device_handle: DeviceHandle); #[ipc_rid(105)] fn delete_application_area(&self, device_handle: DeviceHandle); #[ipc_rid(106)] fn exists_application_area(&self, device_handle: DeviceHandle) -> bool; } #[nx_derive::ipc_trait] pub trait SystemManager { #[ipc_rid(0)] #[return_session] fn create_system_interface(&self) -> System; } #[nx_derive::ipc_trait] #[default_client] pub trait Debug { #[ipc_rid(0)] fn initialize( &self, aruid: applet::AppletResourceUserId, process_id: sf::ProcessId, mcu_data: sf::InMapAliasBuffer<'_, McuVersionData>, ); #[ipc_rid(1)] fn finalize(&self); #[ipc_rid(2)] fn list_devices(&self, out_devices: sf::OutPointerBuffer<'_, DeviceHandle>) -> u32; #[ipc_rid(3)] fn start_detection(&self, device_handle: DeviceHandle); #[ipc_rid(4)] fn stop_detection(&self, device_handle: DeviceHandle); #[ipc_rid(5)] fn mount(&self, device_handle: DeviceHandle, model_type: ModelType, mount_target: MountTarget); #[ipc_rid(6)] fn unmount(&self, device_handle: DeviceHandle); #[ipc_rid(7)] fn open_application_area(&self, device_handle: DeviceHandle, access_id: AccessId); #[ipc_rid(8)] fn get_application_area( &self, device_handle: DeviceHandle, out_data: sf::OutMapAliasBuffer<'_, u8>, ) -> u32; #[ipc_rid(9)] fn set_application_area(&self, device_handle: DeviceHandle, data: sf::InMapAliasBuffer<'_, u8>); #[ipc_rid(10)] fn flush(&self, device_handle: DeviceHandle); #[ipc_rid(11)] fn restore(&self, device_handle: DeviceHandle); #[ipc_rid(12)] fn create_application_area( &self, device_handle: DeviceHandle, access_id: AccessId, data: sf::InMapAliasBuffer<'_, u8>, ); #[ipc_rid(13)] fn get_tag_info( &self, device_handle: DeviceHandle, out_tag_info: sf::OutFixedPointerBuffer<'_, TagInfo>, ); #[ipc_rid(14)] fn get_register_info( &self, device_handle: DeviceHandle, out_register_info: sf::OutFixedPointerBuffer<'_, RegisterInfo>, ); #[ipc_rid(15)] fn get_common_info( &self, device_handle: DeviceHandle, out_common_info: sf::OutFixedPointerBuffer<'_, CommonInfo>, ); #[ipc_rid(16)] fn get_model_info( &self, device_handle: DeviceHandle, out_model_info: sf::OutFixedPointerBuffer<'_, ModelInfo>, ); #[ipc_rid(17)] fn attach_activate_event(&self, device_handle: DeviceHandle) -> sf::CopyHandle; #[ipc_rid(18)] fn attach_deactivate_event(&self, device_handle: DeviceHandle) -> sf::CopyHandle; #[ipc_rid(19)] fn get_state(&self) -> State; #[ipc_rid(20)] fn get_device_state(&self, device_handle: DeviceHandle) -> DeviceState; #[ipc_rid(21)] fn get_npad_id(&self, device_handle: DeviceHandle) -> hid::NpadIdType; #[ipc_rid(22)] fn get_application_area_size(&self, device_handle: DeviceHandle) -> u32; #[ipc_rid(23)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn attach_availability_change_event(&self) -> sf::CopyHandle; #[ipc_rid(24)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn recreate_application_area( &self, device_handle: DeviceHandle, access_id: AccessId, data: sf::InMapAliasBuffer<'_, u8>, ); #[ipc_rid(100)] fn format(&self, device_handle: DeviceHandle); #[ipc_rid(101)] fn get_admin_info( &self, device_handle: DeviceHandle, out_admin_info: sf::OutFixedPointerBuffer<'_, AdminInfo>, ); #[ipc_rid(102)] fn get_register_info_private( &self, device_handle: DeviceHandle, out_register_info_private: sf::OutFixedPointerBuffer<'_, RegisterInfoPrivate>, ); #[ipc_rid(103)] fn set_register_info_private( &self, device_handle: DeviceHandle, register_info_private: sf::InFixedPointerBuffer<'_, RegisterInfoPrivate>, ); #[ipc_rid(104)] fn delete_register_info(&self, device_handle: DeviceHandle); #[ipc_rid(105)] fn delete_application_area(&self, device_handle: DeviceHandle); #[ipc_rid(106)] fn exists_application_area(&self, device_handle: DeviceHandle) -> bool; #[ipc_rid(200)] fn get_all( &self, device_handle: DeviceHandle, out_data: sf::OutFixedPointerBuffer<'_, NfpData>, ); #[ipc_rid(201)] fn set_all(&self, device_handle: DeviceHandle, data: sf::InFixedPointerBuffer<'_, NfpData>); #[ipc_rid(202)] fn flush_debug(&self, device_handle: DeviceHandle); #[ipc_rid(203)] fn break_tag(&self, device_handle: DeviceHandle, break_type: BreakType); #[ipc_rid(204)] fn read_backup_data( &self, device_handle: DeviceHandle, out_buf: sf::OutMapAliasBuffer<'_, u8>, ) -> u32; #[ipc_rid(205)] fn write_backup_data(&self, device_handle: DeviceHandle, buf: sf::InMapAliasBuffer<'_, u8>); #[ipc_rid(206)] fn write_ntf( &self, device_handle: DeviceHandle, write_type: WriteType, buf: sf::InMapAliasBuffer<'_, u8>, ); } #[nx_derive::ipc_trait] pub trait DebugManager { #[ipc_rid(0)] #[return_session] fn create_debug_interface(&self) -> Debug; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/lr.rs
src/ipc/sf/lr.rs
use super::ncm; use crate::ipc::sf; use crate::version; #[nx_derive::ipc_trait] #[default_client] pub trait LocationResolver { #[ipc_rid(1)] fn redirect_program_path( &self, program_id: ncm::ProgramId, path_buf: sf::InPointerBuffer<'_, u8>, ); } #[nx_derive::ipc_trait] #[default_client] pub trait RegisteredLocationResolver { #[ipc_rid(1)] #[version(version::VersionInterval::to(version::Version::new(8, 1, 1)))] fn register_program_path_deprecated( &self, program_id: ncm::ProgramId, path_buf: sf::InPointerBuffer<'_, u8>, ); #[ipc_rid(1)] #[version(version::VersionInterval::from(version::Version::new(9, 0, 0)))] fn register_program_path( &self, program_id: ncm::ProgramId, owner_id: ncm::ProgramId, path_buf: sf::InPointerBuffer<'_, u8>, ); #[ipc_rid(3)] #[version(version::VersionInterval::to(version::Version::new(8, 1, 1)))] fn redirect_program_path_deprecated( &self, program_id: ncm::ProgramId, path_buf: sf::InPointerBuffer<'_, u8>, ); #[ipc_rid(3)] #[version(version::VersionInterval::from(version::Version::new(9, 0, 0)))] fn redirect_program_path( &self, program_id: ncm::ProgramId, owner_id: ncm::ProgramId, path_buf: sf::InPointerBuffer<'_, u8>, ); } #[nx_derive::ipc_trait] pub trait LocationResolverManager { #[ipc_rid(0)] #[return_session] fn open_location_resolver(&self, storage_id: ncm::StorageId) -> LocationResolver; #[ipc_rid(1)] #[return_session] fn open_registered_location_resolver(&self) -> RegisteredLocationResolver; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/ncm.rs
src/ipc/sf/ncm.rs
use crate::ipc::sf; use crate::util::ArrayString; use crate::version; use core::fmt::{Debug, Display, Formatter, Result as FmtResult}; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] #[repr(C)] pub struct ProgramId(pub u64); impl Display for ProgramId { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { write!(f, "{:#018X}", self.0) } } impl Debug for ProgramId { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { write!(f, "{:#018X}", self.0) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] #[repr(C)] pub struct ApplicationId(pub u64); impl Display for ApplicationId { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { write!(f, "{:#018X}", self.0) } } impl Debug for ApplicationId { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { write!(f, "{:#018X}", self.0) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum StorageId { #[default] None = 0, Host = 1, GameCard = 2, BuiltInSystem = 3, BuiltInUser = 4, SdCard = 5, Any = 6, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum ContentMetaType { #[default] Unknown = 0x0, SystemProgram = 0x1, SystemData = 0x2, SystemUpdate = 0x3, BootImagePackage = 0x4, BootImagePackageSafe = 0x5, Application = 0x80, Patch = 0x81, AddOnContent = 0x82, Delta = 0x83, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum ContentType { #[default] Meta = 0, Program = 1, Data = 2, Control = 3, HtmlDocument = 4, LegalInformation = 5, DeltaFragment = 6, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum ContentInstallType { #[default] Full = 0x0, FragmentOnly = 0x1, Unknown = 0x7, } pub type ContentPath = ArrayString<0x301>; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct ContentMetaKey { pub program_id: ProgramId, pub version: u32, pub meta_type: ContentMetaType, pub install_type: ContentInstallType, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct ApplicationContentMetaKey { pub key: ContentMetaKey, pub app_id: ApplicationId, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct ContentId { pub id: [u8; 0x10], } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct LegacyContentInfo { pub hash: [u8; 0x20], pub id: ContentId, pub size: [u8; 0x6], pub cnt_type: ContentType, pub id_offset: u8, } const_assert!(core::mem::size_of::<LegacyContentInfo>() == 0x38); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct ContentInfo { pub hash: [u8; 0x20], pub id: ContentId, pub size: [u8; 0x5], pub attrs: u8, pub cnt_type: ContentType, pub id_offset: u8, } const_assert!(core::mem::size_of::<ContentInfo>() == 0x38); #[derive(Request, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct ContentMetaInfo { pub program_id: ProgramId, pub version: u32, pub meta_type: ContentMetaType, pub attrs: u8, pub pad: [u8; 2], } #[nx_derive::ipc_trait] #[default_client] pub trait ContentMetaDatabase { #[ipc_rid(0)] fn set(&self, meta_key: ContentMetaKey, in_rec_buf: sf::InMapAliasBuffer<'_, u8>); #[ipc_rid(1)] fn get(&self, meta_key: ContentMetaKey, out_rec_buf: sf::OutMapAliasBuffer<'_, u8>) -> usize; #[ipc_rid(2)] fn remove(&self, meta_key: ContentMetaKey); #[ipc_rid(3)] fn get_content_id_by_type(&self, meta_key: ContentMetaKey, cnt_type: ContentType) -> ContentId; #[ipc_rid(4)] fn list_content_info( &self, out_rec_buf: sf::OutMapAliasBuffer<'_, ContentInfo>, meta_key: ContentMetaKey, offset: u32, ) -> u32; #[ipc_rid(5)] fn list( &self, out_meta_keys: sf::OutMapAliasBuffer<'_, ContentMetaKey>, meta_type: ContentMetaType, program_id: ProgramId, program_id_min: ProgramId, program_id_max: ProgramId, install_type: ContentInstallType, ) -> (u32, u32); #[ipc_rid(6)] fn get_latest_content_meta_key(&self, program_id: ProgramId) -> ContentMetaKey; #[ipc_rid(7)] fn list_application( &self, out_app_meta_keys: sf::OutMapAliasBuffer<'_, ApplicationContentMetaKey>, meta_type: ContentMetaType, ) -> (u32, u32); #[ipc_rid(8)] fn has(&self, meta_key: ContentMetaKey) -> bool; #[ipc_rid(9)] fn has_all(&self, meta_keys_buf: sf::InMapAliasBuffer<'_, ContentMetaKey>) -> bool; #[ipc_rid(10)] fn get_size(&self, meta_key: ContentMetaKey) -> usize; #[ipc_rid(11)] fn get_required_system_version(&self, meta_key: ContentMetaKey) -> u32; #[ipc_rid(12)] fn get_patch_content_meta_id(&self, meta_key: ContentMetaKey) -> ProgramId; #[ipc_rid(13)] fn disable_forcibly(&self); #[ipc_rid(14)] fn lookup_orphan_content( &self, content_ids_buf: sf::InMapAliasBuffer<'_, ContentId>, out_orphaned_buf: sf::OutMapAliasBuffer<'_, bool>, ); #[ipc_rid(15)] fn commit(&self); #[ipc_rid(16)] fn has_content(&self, meta_key: ContentMetaKey, id: ContentId) -> bool; #[ipc_rid(17)] fn list_content_meta_info( &self, out_meta_infos: sf::OutMapAliasBuffer<'_, ContentMetaInfo>, meta_key: ContentMetaKey, offset: u32, ) -> u32; #[ipc_rid(18)] fn get_attributes(&self, meta_key: ContentMetaKey) -> u8; #[ipc_rid(19)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn get_required_application_version(&self, meta_key: ContentMetaKey) -> u32; #[ipc_rid(20)] #[version(version::VersionInterval::from(version::Version::new(5, 0, 0)))] fn get_content_id_by_type_and_offset( &self, meta_key: ContentMetaKey, cnt_type: ContentType, id_offset: u8, ) -> ContentId; #[ipc_rid(21)] #[version(version::VersionInterval::from(version::Version::new(10, 0, 0)))] fn get_count(&self) -> u32; #[ipc_rid(22)] #[version(version::VersionInterval::from(version::Version::new(10, 0, 0)))] fn get_owner_application_id(&self, meta_key: ContentMetaKey) -> ApplicationId; } #[nx_derive::ipc_trait] pub trait ContentManager { #[ipc_rid(0)] #[return_session] fn open_content_meta_database(&self, storage_id: StorageId) -> ContentMetaDatabase; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/bsd.rs
src/ipc/sf/bsd.rs
use nx_derive::{Request, Response}; use crate::ipc::sf::{ CopyHandle, InAutoSelectBuffer, InOutAutoSelectBuffer, OutAutoSelectBuffer, OutMapAliasBuffer, ProcessId, }; use crate::result::Result; use crate::version::{self, Version, VersionInterval}; use core::net::Ipv4Addr; use core::str::FromStr; use core::time::Duration as TimeSpec; pub mod rc; pub const SOL_SOCKET: i32 = 0xffff; #[derive(Copy, Clone, Debug, Request, Response)] #[repr(C)] pub struct LibraryVersion(u32); macro_rules! version_in { ($version:ident, $from:expr, $to:expr) => { VersionInterval::from_to( Version::new($from.0, $from.1, $from.2), Version::new($to.0, $to.1, $to.2), ) .contains($version) }; } impl LibraryVersion { fn new() -> Self { let version = version::get_version(); if version_in!(version, (1, 0, 0), (2, 3, 0)) { Self(1) } else if version_in!(version, (3, 0, 0), (3, 0, 2)) { Self(2) } else if version_in!(version, (4, 0, 0), (4, 1, 0)) { Self(3) } else if version_in!(version, (5, 0, 0), (5, 1, 0)) { Self(4) } else if version_in!(version, (6, 0, 0), (7, 0, 1)) { Self(5) } else if version_in!(version, (8, 0, 0), (8, 1, 1)) { Self(6) } else if version_in!(version, (9, 0, 0), (12, 1, 0)) { Self(7) } else if version_in!(version, (13, 0, 0), (15, 0, 1)) { Self(8) } else if version_in!(version, (16, 0, 0), (18, 1, 0)) { Self(9) } else /*if version >= Version::new(19,0, 0)*/ { Self(10) } } } impl Default for LibraryVersion { fn default() -> Self { Self::new() } } #[derive(Copy, Clone, Debug, Request, Response)] pub struct BsdServiceConfig { /// Observed 1 on 2.0 LibAppletWeb, 2 on 3.0. pub version: LibraryVersion, /// Size of the TCP transfer (send) buffer (initial or fixed). pub tcp_tx_buf_size: u32, /// Size of the TCP receive buffer (initial or fixed). pub tcp_rx_buf_size: u32, /// Maximum size of the TCP transfer (send) buffer. If it is 0, the size of the buffer is fixed to its initial value. pub tcp_tx_buf_max_size: u32, /// Maximum size of the TCP receive buffer. If it is 0, the size of the buffer is fixed to its initial value. pub tcp_rx_buf_max_size: u32, /// Size of the UDP transfer (send) buffer (typically 0x2400 bytes). pub udp_tx_buf_size: u32, /// Size of the UDP receive buffer (typically 0xA500 bytes). pub udp_rx_buf_size: u32, /// Number of buffers for each socket (standard values range from 1 to 8). pub sb_efficiency: u32, } impl Default for BsdServiceConfig { fn default() -> Self { Self { version: Default::default(), tcp_tx_buf_size: 0x8000, tcp_rx_buf_size: 0x10000, tcp_tx_buf_max_size: 0x40000, tcp_rx_buf_max_size: 0x40000, udp_tx_buf_size: 0x2400, udp_rx_buf_size: 0xA500, sb_efficiency: 4, } } } impl BsdServiceConfig { pub fn min_transfer_mem_size(self) -> usize { let tx_max_size = if self.tcp_tx_buf_max_size != 0 { self.tcp_tx_buf_max_size } else { self.tcp_tx_buf_size }; let rx_max_size = if self.tcp_rx_buf_max_size != 0 { self.tcp_rx_buf_max_size } else { self.tcp_rx_buf_size }; let sum = tx_max_size + rx_max_size + self.udp_tx_buf_size + self.udp_rx_buf_size; self.sb_efficiency as usize * align_up!(sum as usize, 0x1000usize) } } pub type Fqdn = crate::util::ArrayString<0x100>; //#[derive(Copy, Clone, Debug)] pub enum BsdResult<T> { Ok(i32, T), Err(i32), } impl<T: super::client::ResponseCommandParameter<T>> super::client::ResponseCommandParameter<BsdResult<T>> for BsdResult<T> { fn after_response_read( walker: &mut crate::ipc::DataWalker, ctx: &mut crate::ipc::CommandContext, ) -> Result<BsdResult<T>> { let ret: i32 = walker.advance_get(); let errno: i32 = walker.advance_get(); if ret < 0 { Ok(Self::Err(errno)) } else { Ok(Self::Ok( ret, <T as super::client::ResponseCommandParameter<T>>::after_response_read( walker, ctx, )?, )) } } } impl super::client::ResponseCommandParameter<BsdResult<()>> for BsdResult<()> { fn after_response_read( walker: &mut crate::ipc::DataWalker, _ctx: &mut crate::ipc::CommandContext, ) -> Result<BsdResult<()>> { let ret: i32 = walker.advance_get(); let errno: i32 = walker.advance_get(); if ret < 0 { Ok(Self::Err(errno)) } else { Ok(Self::Ok(ret, ())) } } } impl<T: for<'a> super::server::RequestCommandParameter<'a, T>> super::server::ResponseCommandParameter for BsdResult<T> { type CarryState = (); fn before_response_write( var: &Self, ctx: &mut crate::ipc::server::ServerContext, ) -> Result<Self::CarryState> { match var { Self::Ok(_ret, _okval) => { ctx.raw_data_walker.advance::<i32>(); ctx.raw_data_walker.advance::<i32>(); ctx.raw_data_walker.advance::<T>(); } Self::Err(_errval) => { ctx.raw_data_walker.advance::<i32>(); ctx.raw_data_walker.advance::<i32>(); } } Ok(()) } fn after_response_write( var: Self, _carry_state: Self::CarryState, ctx: &mut crate::ipc::server::ServerContext, ) -> Result<()> { match var { Self::Ok(ret, okval) => { ctx.raw_data_walker.advance_set(ret); ctx.raw_data_walker.advance_set(0i32); ctx.raw_data_walker.advance_set(okval); } Self::Err(errval) => { ctx.raw_data_walker.advance_set(-1i32); ctx.raw_data_walker.advance_set(errval); } } Ok(()) } } impl super::server::ResponseCommandParameter for BsdResult<()> { type CarryState = (); fn before_response_write( var: &Self, ctx: &mut crate::ipc::server::ServerContext, ) -> Result<Self::CarryState> { match var { Self::Ok(_, _) => { ctx.raw_data_walker.advance::<i32>(); ctx.raw_data_walker.advance::<i32>(); } Self::Err(_) => { ctx.raw_data_walker.advance::<i32>(); ctx.raw_data_walker.advance::<i32>(); } } Ok(()) } fn after_response_write( var: Self, _carry_state: Self::CarryState, ctx: &mut crate::ipc::server::ServerContext, ) -> Result<()> { match var { Self::Ok(ret, ()) => { ctx.raw_data_walker.advance_set(ret); ctx.raw_data_walker.advance_set(0i32); } Self::Err(errval) => { ctx.raw_data_walker.advance_set(-1i32); ctx.raw_data_walker.advance_set(errval); } } Ok(()) } } /* impl BsdResult { pub fn to_result(self) -> Result<i32> { if self.0 < 0 { Err(ResultCode::new(self.1 as u32)) } else { Ok(self.0) } } //fn convert_errno(_errno: i32) {} }*/ #[derive(Copy, Clone, Default, Request, Response)] #[repr(C)] pub struct SocketAddrRepr { /// The actual size in bytes of the Socket. /// /// This gets sent over BSD API where the size of the socket is at least the size of `Self` here /// but it could be longer (e.g. IPV6 addresses don't fit). len: u8, /// The address family family: SocketDomain, // TCP/UDP port pub port: u16, // IPv4 Address pub addr: [u8; 4], /// The min size we are working with for the true types. The real size is based on `self.actual_length` and `self.family`. pub(crate) _zero: [u8; 8], } const_assert!(core::mem::size_of::<SocketAddrRepr>() == 16); impl core::fmt::Debug for SocketAddrRepr { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("SocketAddrRepr") .field("family", &self.family) .field("address", &self.addr) .field("port", &u16::from_be(self.port)) .finish_non_exhaustive() } } impl FromStr for SocketAddrRepr { type Err = core::net::AddrParseError; fn from_str(s: &str) -> core::result::Result<Self, Self::Err> { let ipv4_addr = Ipv4Addr::from_str(s)?; Ok(SocketAddrRepr::from(ipv4_addr)) } } impl From<core::net::Ipv4Addr> for SocketAddrRepr { fn from(value: core::net::Ipv4Addr) -> Self { Self { len: 6, family: SocketDomain::INet, port: 0, addr: value.octets(), _zero: [0; 8], } } } impl From<(core::net::Ipv4Addr, u16)> for SocketAddrRepr { fn from(value: (core::net::Ipv4Addr, u16)) -> Self { Self { len: 6, family: SocketDomain::INet, port: value.1.to_be(), addr: value.0.octets(), _zero: [0; 8], } } } #[derive(Copy, Clone, Debug, Default, Request, Response, PartialEq, Eq, PartialOrd, Ord)] #[repr(C)] pub struct BsdDuration { seconds: u64, microseconds: u64, } impl From<BsdDuration> for TimeSpec { fn from(value: BsdDuration) -> Self { TimeSpec::from_secs(value.seconds) + TimeSpec::from_micros(value.microseconds) } } impl From<TimeSpec> for BsdDuration { fn from(timeout: TimeSpec) -> Self { Self { seconds: timeout.as_secs(), microseconds: timeout.subsec_micros() as u64, } } } impl From<Option<TimeSpec>> for BsdDuration { fn from(timeout: Option<TimeSpec>) -> Self { match timeout { None | Some(TimeSpec::ZERO) => { // match libstd behaviour on unix Self { seconds: 0, microseconds: 1, } } Some(timeout) => timeout.into(), } } } #[derive(Copy, Clone, Debug, Request, Response)] #[repr(C)] /// This is newly added but immediately deprecated. /// See `ISocketClient::select` for details. pub struct BsdTimeout { timeout: BsdDuration, no_timeout: bool, } impl BsdTimeout { pub const fn new() -> Self { Self { timeout: BsdDuration { seconds: 0, microseconds: 0, }, no_timeout: true, } } pub const fn timeout(timeout: TimeSpec) -> Self { Self { timeout: BsdDuration { seconds: timeout.as_secs(), microseconds: timeout.subsec_micros() as u64, }, no_timeout: false, } } } impl Default for BsdTimeout { fn default() -> Self { Self::new() } } impl From<Option<core::time::Duration>> for BsdTimeout { fn from(value: Option<core::time::Duration>) -> Self { if let Some(duration) = value { Self { timeout: BsdDuration { seconds: duration.as_secs(), microseconds: duration.subsec_micros() as u64, }, no_timeout: false, } } else { Self { no_timeout: true, timeout: Default::default(), } } } } /// Shutdown mode for TCP streams #[derive(Copy, Clone, Debug, Request, Response)] #[repr(C)] pub enum ShutdownMode { /// Disable reads Receive = 0, /// Disable writes Send = 1, /// Disable both directions Bidirectional = 2, } /// `get/set_sock_opt` options for level `IpProto::IP` #[derive(Copy, Clone, Debug, Request, Response)] #[repr(C)] pub enum IpOptions { /// buf/ip_opts; set/get IP options Options = 1, /// int; header is included with data HeaderIncluded = 2, /// int; IP type of service and preced. TypeOfService = 3, /// int; IP time to live TimeToLive = 4, /// bool; receive all IP opts w/dgram RecvOptions = 5, /// bool; receive IP opts for response RecvReturnOptions = 6, /// bool; receive IP dst addr w/dgram ReceiveDestinationOptions = 7, /// ip_opts; set/get IP options ReturnOptions = 8, /// struct in_addr *or* struct ip_mreqn; MulticastInterface = 9, /// u_char; set/get IP multicast ttl MulticastTimeToLive = 10, /// u_char; set/get IP multicast loopback MulticastLoopback = 11, /// ip_mreq; add an IP group membership MulticastAddMembership = 12, /// ip_mreq; drop an IP group membership MulticastDropMembership = 13, /// set/get IP mcast virt. iface MulticastVirtualInterface = 14, /// enable RSVP in kernel EnableRSVP = 15, /// disable RSVP in kernel DisableRSVP = 16, /// set RSVP per-vif socket EnablePerInterfaceRSVP = 17, /// unset RSVP per-vif socket DisablePerInterfaceRSVP = 18, /// int; range to choose for unspec port PortRange = 19, /// bool; receive reception if w/dgram RecvInterface = 20, /// int; set/get security policy IpsecPolicy = 21, /// bool: send all-ones broadcast AllOnesBroadcast = 23, /// bool: allow bind to any address AllowBindAny = 24, /// bool: allow multiple listeners on a tuple AllowBindMulti = 25, /// int; set RSS listen bucket ResetListenBucket = 26, /// bool: receive IP dst addr/port w/dgram OriginalDestinationAddress = 27, } /// `get/set_sock_opt` options for level `SOL_SOCKET` #[derive(Copy, Clone, Debug, Request, Response)] #[repr(C)] pub enum SocketOptions { /// turn on debugging info recording Debug = 0x0001, /// socket has had listen() AcceptConn = 0x0002, /// allow local address reuse ReuseAddr = 0x0004, /// keep connections alive KeepAlive = 0x0008, /// just use interface addresses DontRoute = 0x0010, /// permit sending of broadcast msgs Broadcast = 0x0020, /// bypass hardware when possible UseLoopbackK = 0x0040, /// linger on close if data present Linger = 0x0080, /// leave received OOB data in line OOBInline = 0x0100, /// allow local address & port reuse ReusePort = 0x0200, /// timestamp received dgram traffic Timestamp = 0x0400, /// no SIGPIPE from EPIPE NoSigPipe = 0x0800, /// there is an accept filter AcceptFilter = 0x1000, /// timestamp received dgram traffic BInTime = 0x2000, /// socket cannot be offloaded NoOffload = 0x4000, /// disable direct data placement NoDdp = 0x8000, // Other options not generally kept in so_options /// send buffer size SendBufferSize = 0x1001, /// receive buffer size ReceiveBufferSize = 0x1002, /// send low-water mark SendLowWaterMark = 0x1003, /// receive low-water mark ReceiveLowWaterMark = 0x1004, /// send timeout SendTimeout = 0x1005, /// receive timeout ReceiveTimeout = 0x1006, /// get error status and clear Error = 0x1007, /// get socket type Type = 0x1008, /// socket's MAC label Label = 0x1009, /// socket's peer's MAC label PeerLabel = 0x1010, /// socket's backlog limit ListenQueueLimit = 0x1011, /// socket's complete queue length ListenQueueLength = 0x1012, /// socket's incomplete queue length ListenIncompleteQueueLength = 0x1013, /// use this FIB to route SetFIB = 0x1014, /// user cookie (dummynet etc.) UserCookie = 0x1015, /// get socket protocol (Linux name) Protocol = 0x1016, /// clock type used for SO_TIMESTAMP TimestampClock = 0x1017, /// socket's max TX pacing rate (Linux name) MaxPacingRate = 0x1018, } #[derive(Clone, Copy, Debug, Request, Response)] #[repr(C)] pub enum TcpOptions { /// don't delay send to coalesce packets NoDelay = 1, /// set maximum segment size MaxSegmentSize = 2, /// don't push last block of write NoPush = 4, /// don't use TCP options NoOptions = 8, /// use MD5 digests (RFC2385) MD5Signature = 16, /// retrieve tcp_info structure Info = 32, /// get/set congestion control algorithm Congestion = 64, /// get/set cc algorithm specific options CCAlgorithmOptions = 65, /// N, time to establish connection KeepInit = 128, /// L,N,X start keeplives after this period KeepIdle = 256, /// L,N interval between keepalives KeepInterval = 512, /// L,N number of keepalives before close KeepCount = 1024, /// enable TFO / was created via TFO FastOpen = 1025, /// number of output packets to keep PCapOut = 2048, /// number of input packets to keep PCapIn = 4096, /// Set the tcp function pointers to the specified stack FunctionBlock = 8192, } #[derive(Copy, Clone, Debug, Default, Request, Response)] #[repr(C)] pub struct Linger { pub on_off: u32, pub linger_time: u32, } #[derive(Copy, Clone, Debug, Request, Response)] #[repr(C)] pub struct IpMulticastRequest { pub multicast_addr: Ipv4Addr, pub interface_addr: Ipv4Addr, } impl Linger { pub fn as_duration(self) -> Option<TimeSpec> { if self.on_off == 0 { None } else { Some(TimeSpec::from_secs(self.linger_time as _)) } } } impl From<Linger> for Option<TimeSpec> { fn from(value: Linger) -> Self { match value.as_duration() { None | Some(TimeSpec::ZERO) => None, Some(time) => Some(time), } } } impl From<TimeSpec> for Linger { fn from(value: TimeSpec) -> Self { Self { on_off: (value == TimeSpec::ZERO) as u32, linger_time: value.as_secs() as u32, } } } impl From<Option<TimeSpec>> for Linger { fn from(value: Option<TimeSpec>) -> Self { value.unwrap_or(TimeSpec::ZERO).into() } } #[derive(Copy, Clone, Debug, Request, Response)] #[repr(C)] pub enum FcntlCmd { /// Duplicate file descriptor DupFd = 0, /// Get file descriptor flags (close on exec) GetFd = 1, /// Set file descriptor flags (close on exec) SetFd = 2, /// Get file flags GetFl = 3, /// Set file flags SetFl = 4, /// Get owner - for ASYNC GetOwn = 5, /// Set owner - for ASYNC SetOwn = 6, /// Get record-locking information GetLk = 7, /// Set or Clear a record-lock (Non-Blocking) SetLk = 8, /// Set or Clear a record-lock (Blocking) SetLkW = 9, /// Test a remote lock to see if it is blocked RGetLk = 10, /// Set or unlock a remote lock RsetLk = 11, /// Convert a fhandle to an open fd Cnvt = 12, /// Set or Clear remote record-lock(Blocking) RsetLkW = 13, /// As F_DUPFD, but set close-on-exec flag DupFdCloexec = 14, } pub type FdSet = [u64; 1024 / (8 * core::mem::size_of::<u64>())]; #[derive(Copy, Clone, Debug, Default, Request, Response)] #[repr(C)] pub struct PollFd { pub fd: i32, pub events: PollFlags, pub revents: PollFlags, } define_bit_set! { PollFlags (u16) { /// any readable data available PollIn = 0x0001, /// OOB/Urgent readable data PollPri = 0x0002, /// file descriptor is writeable PollOut = 0x0004, /// non-OOB/URG data available PollRDNorm = 0x0040, /// OOB/Urgent readable data PollRDBand = 0x0080, /// OOB/Urgent data can be written PollWRBand = 0x0100, /// like PollIN, except ignore EOF PollInIgnoreEof = 0x2000, /// some poll error occurred PollError = 0x0008, /// file descriptor was "hung up" PollHangup = 0x0010, /// requested events "invalid" PollInvalid = 0x0020 } } /// Valid socket domains to request from the bsd service #[derive(Copy, Clone, Debug, Default, Request, Response)] #[repr(u8)] pub enum SocketDomain { // IPV4 #[default] INet = 2, ///Internal Routing Protocol Route = 17, // IPV6 //INet6 = 28, - not supported? } /// Valid socket types to create from the bsd service. #[derive(Copy, Clone, Debug, Request, Response)] #[repr(C)] pub enum SocketType { Stream = 1, DataGram = 2, Raw = 3, SequencePacket = 5, } /// Valid Levels for `get/set_sock_opt` #[derive(Copy, Clone, Debug, Request, Response)] #[repr(C)] pub enum IpProto { IP = 0, ICMP = 1, TCP = 6, UDP = 17, Socket = 0xffff, } define_bit_set! { /// Represents the valid flags when receiving data from a network socket. ReadFlags (u32) { None = 0, /// process out-of-band data Oob = 0x00000001, /// peek at incoming message Peek = 0x00000002, /// data discarded before delivery Trunc = 0x00000010, /// control data lost before delivery CTrunc = 0x00000020, /// wait for full request or error WaitAll = 0x00000040, /// this message should be nonblocking DontWait = 0x00000080, /// make received fds close-on-exec CMsg_CloExec = 0x00040000, /// do not block after receiving the first message (only for `recv_mmsg()`) WaitForOne = 0x00080000 } } define_bit_set! { SendFlags (u32) { None = 0, /// process out-of-band data Oob = 0x00001, /// bypass routing, use direct interface DontRoute = 0x00004, /// data completes record Eor = 0x00008, /// do not block DontWait = 0x00080, /// data completes transaction Eof = 0x00100, /// do not generate SIGPIPE on EOF NoSignal = 0x20000 } } #[nx_derive::ipc_trait] pub trait Bsd { #[ipc_rid(0)] fn register_client( &mut self, library_config: BsdServiceConfig, pid: ProcessId, transfer_mem_size: usize, tmem_handle: CopyHandle, ) -> u64; #[ipc_rid(1)] fn start_monitoring(&mut self, pid: ProcessId) -> (); #[ipc_rid(2)] /// See [read(2)](https://man.openbsd.org/read.2) fn socket( &self, domain: SocketDomain, sock_type: SocketType, protocol: IpProto, ) -> BsdResult<()>; #[ipc_rid(3)] fn socket_exempt( &self, domain: SocketDomain, sock_type: SocketType, protocol: IpProto, ) -> BsdResult<()>; #[ipc_rid(4)] fn open(&self, path_cstr: InAutoSelectBuffer<u8>, flags: i32) -> BsdResult<()>; #[ipc_rid(5)] fn select( &self, fd_count: u32, read_fds: InOutAutoSelectBuffer<FdSet>, write_fds: InOutAutoSelectBuffer<FdSet>, except_fds: InOutAutoSelectBuffer<FdSet>, timeout: BsdTimeout, ) -> BsdResult<()>; #[ipc_rid(6)] fn poll(&self, fds: InOutAutoSelectBuffer<PollFd>, timeout: i32) -> BsdResult<()>; #[ipc_rid(7)] fn sysctl( &self, name: InAutoSelectBuffer<u32>, newp: InAutoSelectBuffer<u8>, oldp: OutAutoSelectBuffer<u8>, ) -> BsdResult<u32>; #[ipc_rid(8)] fn recv( &self, sockfd: i32, flags: ReadFlags, out_buffer: OutAutoSelectBuffer<u8>, ) -> BsdResult<()>; #[ipc_rid(9)] fn recv_from( &self, sockfd: i32, flags: ReadFlags, out_buffer: OutAutoSelectBuffer<u8>, from_addrs: OutAutoSelectBuffer<SocketAddrRepr>, ) -> BsdResult<()>; #[ipc_rid(10)] fn send(&self, sockfd: i32, flags: SendFlags, buffer: InAutoSelectBuffer<u8>) -> BsdResult<()>; #[ipc_rid(11)] fn send_to( &self, sockfd: i32, flags: SendFlags, buffer: InAutoSelectBuffer<u8>, to_addrs: InAutoSelectBuffer<SocketAddrRepr>, ) -> BsdResult<()>; #[ipc_rid(12)] fn accept(&self, sockfd: i32, addrs: OutAutoSelectBuffer<SocketAddrRepr>) -> BsdResult<u32>; #[ipc_rid(13)] fn bind(&self, sockfd: i32, addrs: InAutoSelectBuffer<SocketAddrRepr>) -> BsdResult<()>; #[ipc_rid(14)] fn connect(&self, sockfd: i32, addrs: InAutoSelectBuffer<SocketAddrRepr>) -> BsdResult<()>; #[ipc_rid(15)] fn get_peer_name( &self, sockfd: i32, addrs: OutAutoSelectBuffer<SocketAddrRepr>, ) -> BsdResult<u32>; #[ipc_rid(16)] fn get_socket_name( &self, sockfd: i32, addrs: OutAutoSelectBuffer<SocketAddrRepr>, ) -> BsdResult<u32>; #[ipc_rid(17)] fn get_sock_opt( &self, sockfd: i32, level: i32, optname: i32, out_opt_buffer: OutAutoSelectBuffer<u8>, ) -> BsdResult<u32>; #[ipc_rid(18)] fn listen(&self, sockfd: i32, backlog: i32) -> BsdResult<()>; #[ipc_rid(20)] fn fcntl(&self, sockfd: i32, cmd: FcntlCmd, flags: i32) -> BsdResult<()>; #[ipc_rid(21)] fn set_sock_opt( &self, sockfd: i32, level: i32, optname: i32, opt_buffer: InAutoSelectBuffer<u8>, ) -> BsdResult<()>; #[ipc_rid(22)] fn shutdown(&self, sockfd: i32, how: ShutdownMode) -> BsdResult<()>; #[ipc_rid(23)] fn shutdown_all(&self, how: ShutdownMode) -> BsdResult<()>; #[ipc_rid(24)] fn write(&self, sockfd: i32, data: InAutoSelectBuffer<u8>) -> BsdResult<()>; #[ipc_rid(25)] fn read(&self, sockfd: i32, buffer: OutAutoSelectBuffer<u8>) -> BsdResult<()>; #[ipc_rid(26)] fn close(&self, sockfd: i32) -> BsdResult<()>; #[ipc_rid(27)] fn dup_fd(&self, fd: i32, zero: u64) -> BsdResult<()>; #[ipc_rid(29)] #[version(VersionInterval::from(Version::new(7, 0, 0)))] fn recv_mmesg( &self, fd: i32, buffer: OutMapAliasBuffer<u8>, vlen: i32, flags: ReadFlags, timeout: TimeSpec, ) -> BsdResult<()>; #[ipc_rid(30)] #[version(VersionInterval::from(Version::new(7, 0, 0)))] fn send_mmesg( &self, fd: i32, buffer: OutMapAliasBuffer<u8>, vlen: i32, flags: SendFlags, ) -> BsdResult<()>; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/psc.rs
src/ipc/sf/psc.rs
use crate::ipc::sf; use crate::version; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum ModuleId { Lm = 0x29, // TODO: more } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum State { FullAwake = 0, MinimumAwake = 1, SleepReady = 2, EssentialServicesSleepReady = 3, EssentialServicesAwake = 4, ShutdownReady = 5, Invalid = 6, } #[nx_derive::ipc_trait] #[default_client] pub trait PmModule { #[ipc_rid(0)] fn initialize( &self, id: ModuleId, dependencies: sf::InMapAliasBuffer<'_, ModuleId>, ) -> sf::CopyHandle; #[ipc_rid(1)] fn get_request(&self) -> (State, u32); #[ipc_rid(2)] fn acknowledge(&self); #[ipc_rid(3)] fn finalize(&self); #[ipc_rid(4)] #[version(version::VersionInterval::from(version::Version::new(5, 1, 0)))] fn acknowledge_ex(&self, state: State); } #[nx_derive::ipc_trait] pub trait Pm { #[ipc_rid(0)] #[return_session] fn get_pm_module(&self) -> PmModule; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/pm.rs
src/ipc/sf/pm.rs
use crate::version; use super::ncm; #[nx_derive::ipc_trait] pub trait InformationInterface { #[ipc_rid(0)] fn get_program_id(&self, process_id: u64) -> ncm::ProgramId; } #[nx_derive::ipc_trait] pub trait DebugMonitorInterface { #[ipc_rid(5)] #[version(version::VersionInterval::to(version::Version::new(4, 1, 0)))] fn get_application_process_id_deprecated(&self) -> u64; #[ipc_rid(4)] #[version(version::VersionInterval::from(version::Version::new(5, 0, 0)))] fn get_application_process_id(&self) -> u64; #[ipc_rid(7)] #[version(version::VersionInterval::from(version::Version::new(14, 0, 0)))] fn get_program_id(&self, raw_process_id: u64) -> ncm::ProgramId; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/ldr.rs
src/ipc/sf/ldr.rs
use crate::ipc::sf; use crate::version; use super::ncm; #[nx_derive::ipc_trait] pub trait ShellInterface { #[ipc_rid(0)] #[version(version::VersionInterval::to(version::Version::new(10, 2, 0)))] fn set_program_argument_deprecated( &self, program_id: ncm::ProgramId, args_size: u32, args_buf: sf::InPointerBuffer<'_, u8>, ); #[ipc_rid(0)] #[version(version::VersionInterval::from(version::Version::new(11, 0, 0)))] fn set_program_argument( &self, program_id: ncm::ProgramId, args_buf: sf::InPointerBuffer<'_, u8>, ); #[ipc_rid(1)] fn flush_arguments(&self); #[ipc_rid(65000)] fn atmosphere_register_external_code(&self, program_id: ncm::ProgramId) -> sf::MoveHandle; #[ipc_rid(65001)] fn atmosphere_unregister_external_code(&self, program_id: ncm::ProgramId); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/mii.rs
src/ipc/sf/mii.rs
use crate::ipc::sf; use crate::result::*; use crate::util; #[cfg(feature = "services")] use crate::service; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum Age { Young, Normal, Old, #[default] All, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum Gender { Male, Female, #[default] All, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum FaceColor { Black, White, Asian, #[default] All, } define_bit_set! { SourceFlag (u32) { Database = bit!(0), Default = bit!(1) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u32)] pub enum SpecialKeyCode { #[default] Normal = 0, Special = 0xA523B78F, } pub type CreateId = util::Uuid; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum HairType { #[default] NormalLong, NormalShort, NormalMedium, NormalExtraLong, NormalLongBottom, NormalTwoPeaks, PartingLong, FrontLock, PartingShort, PartingExtraLongCurved, PartingExtraLong, PartingMiddleLong, PartingSquared, PartingLongBottom, PeaksTop, PeaksSquared, PartingPeaks, PeaksLongBottom, Peaks, PeaksRounded, PeaksSide, PeaksMedium, PeaksLong, PeaksRoundedLong, PartingFrontPeaks, PartingLongFront, PartingLongRounded, PartingFrontPeaksLong, PartingExtraLongRounded, LongRounded, NormalUnknown1, NormalUnknown2, NormalUnknown3, NormalUnknown4, NormalUnknown5, NormalUnknown6, DreadLocks, PlatedMats, Caps, Afro, PlatedMatsLong, Beanie, Short, ShortTopLongSide, ShortUnknown1, ShortUnknown2, MilitaryParting, Military, ShortUnknown3, ShortUnknown4, ShortUnknown5, ShortUnknown6, NoneTop, None, LongUnknown1, LongUnknown2, LongUnknown3, LongUnknown4, LongUnknown5, LongUnknown6, LongUnknown7, LongUnknown8, LongUnknown9, LongUnknown10, LongUnknown11, LongUnknown12, LongUnknown13, LongUnknown14, LongUnknown15, LongUnknown16, LongUnknown17, LongUnknown18, LongUnknown19, LongUnknown20, LongUnknown21, LongUnknown22, LongUnknown23, LongUnknown24, LongUnknown25, LongUnknown26, LongUnknown27, LongUnknown28, LongUnknown29, LongUnknown30, LongUnknown31, LongUnknown32, LongUnknown33, LongUnknown34, LongUnknown35, LongUnknown36, LongUnknown37, LongUnknown38, LongUnknown39, LongUnknown40, LongUnknown41, LongUnknown42, LongUnknown43, LongUnknown44, LongUnknown45, LongUnknown46, LongUnknown47, LongUnknown48, LongUnknown49, LongUnknown50, LongUnknown51, LongUnknown52, LongUnknown53, LongUnknown54, LongUnknown55, LongUnknown56, LongUnknown57, LongUnknown58, LongUnknown59, LongUnknown60, LongUnknown61, LongUnknown62, LongUnknown63, LongUnknown64, LongUnknown65, LongUnknown66, TwoMediumFrontStrandsOneLongBackPonyTail, TwoFrontStrandsLongBackPonyTail, PartingFrontTwoLongBackPonyTails, TwoFrontStrandsOneLongBackPonyTail, LongBackPonyTail, LongFrontTwoLongBackPonyTails, StrandsTwoShortSidedPonyTails, TwoMediumSidedPonyTails, ShortFrontTwoBackPonyTails, TwoShortSidedPonyTails, TwoLongSidedPonyTails, LongFrontTwoBackPonyTails, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum MoleType { #[default] None, OneDot, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum HairFlip { #[default] Left, Right, } pub type CommonColor = u8; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum EyeType { #[default] Normal, NormalLash, WhiteLash, WhiteNoBottom, OvalAngledWhite, AngryWhite, DotLashType1, Line, DotLine, OvalWhite, RoundedWhite, NormalShadow, CircleWhite, Circle, CircleWhiteStroke, NormalOvalNoBottom, NormalOvalLarge, NormalRoundedNoBottom, SmallLash, Small, TwoSmall, NormalLongLash, WhiteTwoLashes, WhiteThreeLashes, DotAngry, DotAngled, Oval, SmallWhite, WhiteAngledNoBottom, WhiteAngledNoLeft, SmallWhiteTwoLashes, LeafWhiteLash, WhiteLargeNoBottom, Dot, DotLashType2, DotThreeLashes, WhiteOvalTop, WhiteOvalBottom, WhiteOvalBottomFlat, WhiteOvalTwoLashes, WhiteOvalThreeLashes, WhiteOvalNoBottomTwoLashes, DotWhite, WhiteOvalTopFlat, WhiteThinLeaf, StarThreeLashes, LineTwoLashes, CrowsFeet, WhiteNoBottomFlat, WhiteNoBottomRounded, WhiteSmallBottomLine, WhiteNoBottomLash, WhiteNoPartialBottomLash, WhiteOvalBottomLine, WhiteNoBottomLashTopLine, WhiteNoPartialBottomTwoLashes, NormalTopLine, WhiteOvalLash, RoundTired, WhiteLarge, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum MouthType { #[default] Neutral, NeutralLips, Smile, SmileStroke, SmileTeeth, LipsSmall, LipsLarge, Wave, WaveAngrySmall, NeutralStrokeLarge, TeethSurprised, LipsExtraLarge, LipsUp, NeutralDown, Surprised, TeethMiddle, NeutralStroke, LipsExtraSmall, Malicious, LipsDual, NeutralComma, NeutralUp, TeethLarge, WaveAngry, LipsSexy, SmileInverted, LipsSexyOutline, SmileRounded, LipsTeeth, NeutralOpen, TeethRounded, WaveAngrySmallInverted, NeutralCommaInverted, TeethFull, SmileDownLine, Kiss, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum FontRegion { #[default] Standard, China, Korea, Taiwan, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum FacelineType { #[default] Sharp, Rounded, SharpRounded, SharpRoundedSmall, Large, LargeRounded, SharpSmall, Flat, Bump, Angular, FlatRounded, AngularSmall, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum FacelineColor { #[default] Beige, WarmBeige, Natural, Honey, Chestnut, Porcelain, Ivory, WarmIvory, Almond, Espresso, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum FacelineWrinkle { #[default] None, TearTroughs, FacialPain, Cheeks, Folds, UnderTheEyes, SplitChin, Chin, BrowDroop, MouthFrown, CrowsFeet, FoldsCrowsFrown, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum FacelineMake { #[default] None, CheekPorcelain, CheekNatural, EyeShadowBlue, CheekBlushPorcelain, CheekBlushNatural, CheekPorcelainEyeShadowBlue, CheekPorcelainEyeShadowNatural, CheekBlushPorcelainEyeShadowEspresso, Freckles, LionsManeBeard, StubbleBeard, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum EyebrowType { #[default] FlatAngledLarge, LowArchRoundedThin, SoftAngledLarge, MediumArchRoundedThin, RoundedMedium, LowArchMedium, RoundedThin, UpThin, MediumArchRoundedMedium, RoundedLarge, UpLarge, FlatAngledLargeInverted, MediumArchFlat, AngledThin, HorizontalLarge, HighArchFlat, Flat, MediumArchLarge, LowArchThin, RoundedThinInverted, HighArchLarge, Hairy, Dotted, None, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum NoseType { #[default] Normal, Rounded, Dot, Arrow, Roman, Triangle, Button, RoundedInverted, Potato, Grecian, Snub, Aquiline, ArrowLeft, RoundedLarge, Hooked, Fat, Droopy, ArrowLarge, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum BeardType { #[default] None, Goatee, GoateeLong, LionsManeLong, LionsMane, Full, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum MustacheType { #[default] None, Walrus, Pencil, Horseshoe, Normal, Toothbrush, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum GlassType { #[default] None, Oval, Wayfarer, Rectangle, TopRimless, Rounded, Oversized, CatEye, Square, BottomRimless, SemiOpaqueRounded, SemiOpaqueCatEye, SemiOpaqueOval, SemiOpaqueRectangle, SemiOpaqueAviator, OpaqueRounded, OpaqueCatEye, OpaqueOval, OpaqueRectangle, OpaqueAviator, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct CharInfo { pub id: CreateId, pub name: util::ArrayWideString<11>, pub font_region: FontRegion, pub favorite_color: u8, pub gender: Gender, pub height: u8, pub build: u8, pub type_val: u8, pub region_move: u8, pub faceline_type: FacelineType, pub faceline_color: FacelineColor, pub faceline_wrinkle: FacelineWrinkle, pub faceline_make: FacelineMake, pub hair_type: HairType, pub hair_color: CommonColor, pub hair_flip: HairFlip, pub eye_type: EyeType, pub eye_color: CommonColor, pub eye_scale: u8, pub eye_aspect: u8, pub eye_rotate: u8, pub eye_x: u8, pub eye_y: u8, pub eyebrow_type: EyebrowType, pub eyebrow_color: CommonColor, pub eyebrow_scale: u8, pub eyebrow_aspect: u8, pub eyebrow_rotate: u8, pub eyebrow_x: u8, pub eyebrow_y: u8, pub nose_type: NoseType, pub nose_scale: u8, pub nose_y: u8, pub mouth_type: MouthType, pub mouth_color: CommonColor, pub mouth_scale: u8, pub mouth_aspect: u8, pub mouth_y: u8, pub beard_color: CommonColor, pub beard_type: BeardType, pub mustache_type: MustacheType, pub mustache_scale: u8, pub mustache_y: u8, pub glass_type: GlassType, pub glass_color: CommonColor, pub glass_scale: u8, pub glass_y: u8, pub mole_type: MoleType, pub mole_scale: u8, pub mole_x: u8, pub mole_y: u8, pub reserved: u8, } const_assert!(core::mem::size_of::<CharInfo>() == 0x58); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum CoreDataElement { HairType, Height, MoleType, Build, HairFlip, HairColor, Type, EyeColor, Gender, EyebrowColor, MouthColor, BeardColor, GlassColor, EyeType, RegionMove, MouthType, FontRegion, EyeY, GlassScale, EyebrowType, MustacheType, NoseType, BeardType, NoseY, MouthAspect, MouthY, EyebrowAspect, MustacheY, EyeRotate, GlassY, EyeAspect, MoleX, EyeScale, MoleY, GlassType, FavoriteColor, FacelineType, FacelineColor, FacelineWrinkle, FacelineMake, EyeX, EyebrowScale, EyebrowRotate, EyebrowX, EyebrowY, NoseScale, MouthScale, MustacheScale, MoleScale, } #[derive(Request, Response, Copy, Clone)] #[repr(C)] pub struct CoreDataElementInfo { pub byte_offset: u32, pub bit_offset: u32, pub bit_width: u32, pub min_value: u32, pub max_value: u32, pub unk: u32, } pub const fn get_element_info(elm: CoreDataElement) -> CoreDataElementInfo { match elm { CoreDataElement::HairType => CoreDataElementInfo { byte_offset: 0x0, bit_offset: 0, bit_width: 8, min_value: 0, max_value: 0x83, unk: 1, }, CoreDataElement::Height => CoreDataElementInfo { byte_offset: 0x1, bit_offset: 0, bit_width: 7, min_value: 0, max_value: 0x7F, unk: 0, }, CoreDataElement::MoleType => CoreDataElementInfo { byte_offset: 0x1, bit_offset: 7, bit_width: 1, min_value: 0, max_value: 0x1, unk: 0, }, CoreDataElement::Build => CoreDataElementInfo { byte_offset: 0x2, bit_offset: 0, bit_width: 7, min_value: 0, max_value: 0x7F, unk: 0, }, CoreDataElement::HairFlip => CoreDataElementInfo { byte_offset: 0x2, bit_offset: 7, bit_width: 1, min_value: 0, max_value: 0x1, unk: 0, }, CoreDataElement::HairColor => CoreDataElementInfo { byte_offset: 0x3, bit_offset: 0, bit_width: 7, min_value: 0, max_value: 0x63, unk: 1, }, CoreDataElement::Type => CoreDataElementInfo { byte_offset: 0x3, bit_offset: 7, bit_width: 1, min_value: 0, max_value: 0x1, unk: 0, }, CoreDataElement::EyeColor => CoreDataElementInfo { byte_offset: 0x4, bit_offset: 0, bit_width: 7, min_value: 0, max_value: 0x63, unk: 1, }, CoreDataElement::Gender => CoreDataElementInfo { byte_offset: 0x4, bit_offset: 7, bit_width: 1, min_value: 0, max_value: 0x1, unk: 0, }, CoreDataElement::EyebrowColor => CoreDataElementInfo { byte_offset: 0x5, bit_offset: 0, bit_width: 7, min_value: 0, max_value: 0x63, unk: 1, }, CoreDataElement::MouthColor => CoreDataElementInfo { byte_offset: 0x6, bit_offset: 0, bit_width: 7, min_value: 0, max_value: 0x63, unk: 1, }, CoreDataElement::BeardColor => CoreDataElementInfo { byte_offset: 0x7, bit_offset: 0, bit_width: 7, min_value: 0, max_value: 0x63, unk: 1, }, CoreDataElement::GlassColor => CoreDataElementInfo { byte_offset: 0x8, bit_offset: 0, bit_width: 7, min_value: 0, max_value: 0x63, unk: 1, }, CoreDataElement::EyeType => CoreDataElementInfo { byte_offset: 0x9, bit_offset: 0, bit_width: 6, min_value: 0, max_value: 0x3B, unk: 1, }, CoreDataElement::RegionMove => CoreDataElementInfo { byte_offset: 0x9, bit_offset: 6, bit_width: 2, min_value: 0, max_value: 0x3, unk: 0, }, CoreDataElement::MouthType => CoreDataElementInfo { byte_offset: 0xA, bit_offset: 0, bit_width: 6, min_value: 0, max_value: 0x23, unk: 1, }, CoreDataElement::FontRegion => CoreDataElementInfo { byte_offset: 0xA, bit_offset: 6, bit_width: 2, min_value: 0, max_value: 0x3, unk: 0, }, CoreDataElement::EyeY => CoreDataElementInfo { byte_offset: 0xB, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x12, unk: 1, }, CoreDataElement::GlassScale => CoreDataElementInfo { byte_offset: 0xB, bit_offset: 5, bit_width: 3, min_value: 0, max_value: 0x7, unk: 0, }, CoreDataElement::EyebrowType => CoreDataElementInfo { byte_offset: 0xC, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x17, unk: 1, }, CoreDataElement::MustacheType => CoreDataElementInfo { byte_offset: 0xC, bit_offset: 5, bit_width: 3, min_value: 0, max_value: 0x5, unk: 1, }, CoreDataElement::NoseType => CoreDataElementInfo { byte_offset: 0xD, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x11, unk: 1, }, CoreDataElement::BeardType => CoreDataElementInfo { byte_offset: 0xD, bit_offset: 5, bit_width: 3, min_value: 0, max_value: 0x5, unk: 1, }, CoreDataElement::NoseY => CoreDataElementInfo { byte_offset: 0xE, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x12, unk: 1, }, CoreDataElement::MouthAspect => CoreDataElementInfo { byte_offset: 0xE, bit_offset: 5, bit_width: 3, min_value: 0, max_value: 0x6, unk: 1, }, CoreDataElement::MouthY => CoreDataElementInfo { byte_offset: 0xF, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x12, unk: 1, }, CoreDataElement::EyebrowAspect => CoreDataElementInfo { byte_offset: 0xF, bit_offset: 5, bit_width: 3, min_value: 0, max_value: 0x6, unk: 1, }, CoreDataElement::MustacheY => CoreDataElementInfo { byte_offset: 0x10, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x10, unk: 1, }, CoreDataElement::EyeRotate => CoreDataElementInfo { byte_offset: 0x10, bit_offset: 5, bit_width: 3, min_value: 0, max_value: 0x7, unk: 0, }, CoreDataElement::GlassY => CoreDataElementInfo { byte_offset: 0x11, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x14, unk: 1, }, CoreDataElement::EyeAspect => CoreDataElementInfo { byte_offset: 0x11, bit_offset: 5, bit_width: 3, min_value: 0, max_value: 0x6, unk: 1, }, CoreDataElement::MoleX => CoreDataElementInfo { byte_offset: 0x12, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x10, unk: 1, }, CoreDataElement::EyeScale => CoreDataElementInfo { byte_offset: 0x12, bit_offset: 5, bit_width: 3, min_value: 0, max_value: 0x7, unk: 0, }, CoreDataElement::MoleY => CoreDataElementInfo { byte_offset: 0x13, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x1E, unk: 1, }, CoreDataElement::GlassType => CoreDataElementInfo { byte_offset: 0x14, bit_offset: 0, bit_width: 5, min_value: 0, max_value: 0x13, unk: 1, }, CoreDataElement::FavoriteColor => CoreDataElementInfo { byte_offset: 0x15, bit_offset: 0, bit_width: 4, min_value: 0, max_value: 0xB, unk: 1, }, CoreDataElement::FacelineType => CoreDataElementInfo { byte_offset: 0x15, bit_offset: 4, bit_width: 4, min_value: 0, max_value: 0xB, unk: 1, }, CoreDataElement::FacelineColor => CoreDataElementInfo { byte_offset: 0x16, bit_offset: 0, bit_width: 4, min_value: 0, max_value: 0x9, unk: 1, }, CoreDataElement::FacelineWrinkle => CoreDataElementInfo { byte_offset: 0x16, bit_offset: 4, bit_width: 4, min_value: 0, max_value: 0xB, unk: 1, }, CoreDataElement::FacelineMake => CoreDataElementInfo { byte_offset: 0x17, bit_offset: 0, bit_width: 4, min_value: 0, max_value: 0xB, unk: 1, }, CoreDataElement::EyeX => CoreDataElementInfo { byte_offset: 0x17, bit_offset: 4, bit_width: 4, min_value: 0, max_value: 0xC, unk: 1, }, CoreDataElement::EyebrowScale => CoreDataElementInfo { byte_offset: 0x18, bit_offset: 0, bit_width: 4, min_value: 0, max_value: 0x8, unk: 1, }, CoreDataElement::EyebrowRotate => CoreDataElementInfo { byte_offset: 0x18, bit_offset: 4, bit_width: 4, min_value: 0, max_value: 0xB, unk: 1, }, CoreDataElement::EyebrowX => CoreDataElementInfo { byte_offset: 0x19, bit_offset: 0, bit_width: 4, min_value: 0, max_value: 0xC, unk: 1, }, CoreDataElement::EyebrowY => CoreDataElementInfo { byte_offset: 0x19, bit_offset: 4, bit_width: 4, min_value: 0x3, max_value: 0x12, unk: 0, }, CoreDataElement::NoseScale => CoreDataElementInfo { byte_offset: 0x1A, bit_offset: 0, bit_width: 4, min_value: 0, max_value: 0x8, unk: 1, }, CoreDataElement::MouthScale => CoreDataElementInfo { byte_offset: 0x1A, bit_offset: 4, bit_width: 4, min_value: 0, max_value: 0x8, unk: 1, }, CoreDataElement::MustacheScale => CoreDataElementInfo { byte_offset: 0x1B, bit_offset: 0, bit_width: 4, min_value: 0, max_value: 0x8, unk: 1, }, CoreDataElement::MoleScale => CoreDataElementInfo { byte_offset: 0x1B, bit_offset: 4, bit_width: 4, min_value: 0, max_value: 0x8, unk: 1, }, } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct CoreData { pub data: [u8; 0x1C], pub name: util::ArrayWideString<10>, } const_assert!(core::mem::size_of::<CoreData>() == 0x30); impl CoreData { #[inline] fn get_value(&self, info: CoreDataElementInfo) -> u32 { ((self.data[info.byte_offset as usize] as u32 >> info.bit_offset) & !(u32::MAX << info.bit_width)) + info.min_value } #[inline] fn set_value(&mut self, info: CoreDataElementInfo, val: u32) { let new_val = (self.data[info.byte_offset as usize] as u32 & !(!(u32::MAX << info.bit_width) << info.bit_offset) | (((val - info.min_value) & !(u32::MAX << info.bit_width)) << info.bit_offset)) as u8; self.data[info.byte_offset as usize] = new_val; } // TODO: order these? #[inline] pub fn get_hair_type(&self) -> HairType { unsafe { core::mem::transmute(self.get_value(get_element_info(CoreDataElement::HairType)) as u8) } } #[inline] pub fn set_hair_type(&mut self, hair_type: HairType) { self.set_value( get_element_info(CoreDataElement::HairType), hair_type as u32, ) } #[inline] pub fn get_height(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::Height)) as u8 } #[inline] pub fn set_height(&mut self, height: u8) { self.set_value(get_element_info(CoreDataElement::Height), height as u32) } #[inline] pub fn get_mole_type(&self) -> MoleType { unsafe { core::mem::transmute(self.get_value(get_element_info(CoreDataElement::MoleType)) as u8) } } #[inline] pub fn set_mole_type(&mut self, mole_type: MoleType) { self.set_value( get_element_info(CoreDataElement::MoleType), mole_type as u32, ) } #[inline] pub fn get_build(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::Build)) as u8 } #[inline] pub fn set_build(&mut self, build: u8) { self.set_value(get_element_info(CoreDataElement::Build), build as u32) } #[inline] pub fn get_hair_flip(&self) -> HairFlip { unsafe { core::mem::transmute(self.get_value(get_element_info(CoreDataElement::HairFlip)) as u8) } } #[inline] pub fn set_hair_flip(&mut self, hair_flip: HairFlip) { self.set_value( get_element_info(CoreDataElement::HairFlip), hair_flip as u32, ) } #[inline] pub fn get_hair_color(&self) -> CommonColor { self.get_value(get_element_info(CoreDataElement::HairColor)) as u8 } #[inline] pub fn set_hair_color(&mut self, color: CommonColor) { self.set_value(get_element_info(CoreDataElement::HairColor), color as u32) } #[inline] pub fn get_type(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::Type)) as u8 } #[inline] pub fn set_type(&mut self, type_val: u8) { self.set_value(get_element_info(CoreDataElement::Type), type_val as u32) } #[inline] pub fn get_eye_color(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::EyeColor)) as u8 } #[inline] pub fn set_eye_color(&mut self, color: u8) { self.set_value(get_element_info(CoreDataElement::EyeColor), color as u32) } #[inline] pub fn get_gender(&self) -> Gender { unsafe { core::mem::transmute(self.get_value(get_element_info(CoreDataElement::Gender)) as u8) } } #[inline] pub fn set_gender(&mut self, gender: Gender) { self.set_value(get_element_info(CoreDataElement::Gender), gender as u32) } #[inline] pub fn get_eyebrow_color(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::EyebrowColor)) as u8 } #[inline] pub fn set_eyebrow_color(&mut self, color: u8) { self.set_value( get_element_info(CoreDataElement::EyebrowColor), color as u32, ) } #[inline] pub fn get_mouth_color(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::MouthColor)) as u8 } #[inline] pub fn set_mouth_color(&mut self, color: u8) { self.set_value(get_element_info(CoreDataElement::MouthColor), color as u32) } #[inline] pub fn get_beard_color(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::BeardColor)) as u8 } #[inline] pub fn set_beard_color(&mut self, color: u8) { self.set_value(get_element_info(CoreDataElement::BeardColor), color as u32) } #[inline] pub fn get_glass_color(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::GlassColor)) as u8 } #[inline] pub fn set_glass_color(&mut self, color: u8) { self.set_value(get_element_info(CoreDataElement::GlassColor), color as u32) } #[inline] pub fn get_eye_type(&self) -> EyeType { unsafe { core::mem::transmute(self.get_value(get_element_info(CoreDataElement::EyeType)) as u8) } } #[inline] pub fn set_eye_type(&mut self, eye_type: EyeType) { self.set_value(get_element_info(CoreDataElement::EyeType), eye_type as u32) } #[inline] pub fn get_region_move(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::RegionMove)) as u8 } #[inline] pub fn set_region_move(&mut self, region_move: u8) { self.set_value( get_element_info(CoreDataElement::RegionMove), region_move as u32, ) } #[inline] pub fn get_mouth_type(&self) -> MouthType { unsafe { core::mem::transmute(self.get_value(get_element_info(CoreDataElement::MouthType)) as u8) } } #[inline] pub fn set_mouth_type(&mut self, mouth_type: MouthType) { self.set_value( get_element_info(CoreDataElement::MouthType), mouth_type as u32, ) } #[inline] pub fn get_font_region(&self) -> FontRegion { unsafe { core::mem::transmute( self.get_value(get_element_info(CoreDataElement::FontRegion)) as u8, ) } } #[inline] pub fn set_font_region(&mut self, font_region: FontRegion) { self.set_value( get_element_info(CoreDataElement::FontRegion), font_region as u32, ) } #[inline] pub fn get_eye_y(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::EyeY)) as u8 } #[inline] pub fn set_eye_y(&mut self, y: u8) { self.set_value(get_element_info(CoreDataElement::EyeY), y as u32) } #[inline] pub fn get_glass_scale(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::GlassScale)) as u8 } #[inline] pub fn set_glass_scale(&mut self, scale: u8) { self.set_value(get_element_info(CoreDataElement::GlassScale), scale as u32) } #[inline] pub fn get_eyebrow_type(&self) -> EyebrowType { unsafe { core::mem::transmute( self.get_value(get_element_info(CoreDataElement::EyebrowType)) as u8, ) } } #[inline] pub fn set_eyebrow_type(&mut self, eyebrow_type: EyebrowType) { self.set_value( get_element_info(CoreDataElement::EyebrowType), eyebrow_type as u32, ) } #[inline] pub fn get_mustache_type(&self) -> MustacheType { unsafe { core::mem::transmute( self.get_value(get_element_info(CoreDataElement::MustacheType)) as u8, ) } } #[inline] pub fn set_mustache_type(&mut self, mustache_type: MustacheType) { self.set_value( get_element_info(CoreDataElement::MustacheType), mustache_type as u32, ) } #[inline] pub fn get_nose_type(&self) -> NoseType { unsafe { core::mem::transmute(self.get_value(get_element_info(CoreDataElement::NoseType)) as u8) } } #[inline] pub fn set_nose_type(&mut self, nose_type: NoseType) { self.set_value( get_element_info(CoreDataElement::NoseType), nose_type as u32, ) } #[inline] pub fn get_beard_type(&self) -> BeardType { unsafe { core::mem::transmute(self.get_value(get_element_info(CoreDataElement::BeardType)) as u8) } } #[inline] pub fn set_beard_type(&mut self, beard_type: BeardType) { self.set_value( get_element_info(CoreDataElement::BeardType), beard_type as u32, ) } #[inline] pub fn get_nose_y(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::NoseY)) as u8 } #[inline] pub fn set_nose_y(&mut self, y: u8) { self.set_value(get_element_info(CoreDataElement::NoseY), y as u32) } #[inline] pub fn get_mouth_aspect(&self) -> u8 { self.get_value(get_element_info(CoreDataElement::MouthAspect)) as u8 } #[inline] pub fn set_mouth_aspect(&mut self, aspect: u8) { self.set_value( get_element_info(CoreDataElement::MouthAspect), aspect as u32,
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
true
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/usb.rs
src/ipc/sf/usb.rs
pub mod hs; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum DescriptorType { Device = 0x1, Config = 0x2, String = 0x3, Interface = 0x4, EndPoint = 0x5, Bos = 0xF, DeviceCapability = 0x10, Hid = 0x21, Report = 0x22, Physical = 0x23, Hub = 0x29, SuperSpeedHub = 0x2A, SsEndPointCompanion = 0x30, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum ClassCode { #[default] PerInterface = 0x0, Audio = 0x1, Comm = 0x2, Hid = 0x3, Physical = 0x5, Printer = 0x7, Image = 0x6, MassStorage = 0x8, Hub = 0x9, Data = 0xA, SmartCard = 0xB, ContentSecurity = 0xD, Video = 0xE, PersonalHealthcare = 0xF, DiagnosticDevice = 0xDC, Wireless = 0xE0, Application = 0xFE, VendorSpec = 0xFF, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct InterfaceDescriptor { length: u8, descriptor_type: DescriptorType, interface_number: u8, alternate_setting: u8, endpoint_count: u8, interface_class: ClassCode, interface_subclass: u8, interface_protocol: u8, interface: u8, } const_assert!(core::mem::size_of::<InterfaceDescriptor>() == 0x9); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C, packed)] pub struct EndPointDescriptor { length: u8, descriptor_type: DescriptorType, endpoint_access: u8, attributes: u8, max_packet_size: u16, interval: u8, } const_assert!(core::mem::size_of::<EndPointDescriptor>() == 0x7); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct SsEndPointCompanionDescriptor { length: u8, descriptor_type: DescriptorType, max_burst: u8, attributes: u8, bytes_per_interval: u16, } const_assert!(core::mem::size_of::<SsEndPointCompanionDescriptor>() == 0x6); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct DeviceDescriptor { length: u8, descriptor_type: DescriptorType, usb_bcd: u16, device_class: ClassCode, device_subclass: u8, device_protocol: u8, max_packet_size_0: u8, vendor_id: u16, product_id: u16, device_bcd: u8, manufacturer: u8, product: u8, serial_number: u8, configuration_count: u8, } const_assert!(core::mem::size_of::<DeviceDescriptor>() == 0x12); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C, packed)] pub struct ConfigDescriptor { length: u8, descriptor_type: DescriptorType, total_length: u16, interface_count: u8, configuration_value: u8, configuration: u8, attributes: u8, max_power: u8, } const_assert!(core::mem::size_of::<ConfigDescriptor>() == 0x9);
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/audio.rs
src/ipc/sf/audio.rs
use crate::util::ArrayString; use nx_derive::{Request, Response}; use crate::ipc::sf::{ self, AppletResourceUserId, CopyHandle, InAutoSelectBuffer, InMapAliasBuffer, OutAutoSelectBuffer, OutMapAliasBuffer, }; use crate::version; pub mod rc; pub type AudioInterfaceName = ArrayString<0x100>; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct AudioRequestParameters { pub sample_rate: u32, pub channel_count: u16, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct AudioResponseParameters { pub sample_rate: u32, pub channel_count: u32, pub sample_format: PcmFormat, pub state: u32, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct AudioBuffer { pub _unused_ptr: usize, pub sample_buffer: *mut u8, pub buffer_capacity: usize, pub data_size: usize, pub _data_offset: usize, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum PcmFormat { Invalid = 0, Int8 = 1, Int16 = 2, Int24 = 3, Int32 = 4, Float = 5, Adpcm = 6, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum AudioState { Started = 0, Stopped = 1, } #[nx_derive::ipc_trait] pub trait AudioOutManager { #[ipc_rid(0)] fn list_audio_outs(&self, names: OutMapAliasBuffer<AudioInterfaceName>) -> u32; #[ipc_rid(1)] #[return_session] fn open_audio_out( &self, in_name: InMapAliasBuffer<AudioInterfaceName>, out_name: OutMapAliasBuffer<AudioInterfaceName>, params: AudioRequestParameters, aruid: AppletResourceUserId, process_handle: sf::CopyHandle, ) -> (AudioOut, AudioResponseParameters); #[ipc_rid(2)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn list_audio_outs_auto(&self, names: OutAutoSelectBuffer<AudioInterfaceName>) -> u32; #[ipc_rid(3)] #[return_session] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn open_audio_out_auto( &self, in_name: InAutoSelectBuffer<AudioInterfaceName>, out_name: OutMapAliasBuffer<AudioInterfaceName>, params: AudioRequestParameters, aruid: AppletResourceUserId, process_handle: sf::CopyHandle, ) -> (AudioOut, AudioResponseParameters); } #[nx_derive::ipc_trait] pub trait AudioInManager { #[ipc_rid(0)] fn list(&self, names: OutMapAliasBuffer<AudioInterfaceName>) -> u32; #[ipc_rid(1)] #[return_session] fn open( &self, in_name: InMapAliasBuffer<AudioInterfaceName>, out_name: OutMapAliasBuffer<AudioInterfaceName>, params: AudioRequestParameters, aruid: AppletResourceUserId, process_handle: sf::CopyHandle, ) -> (AudioIn, AudioResponseParameters); #[ipc_rid(2)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn list_auto(&self, names: OutAutoSelectBuffer<AudioInterfaceName>) -> u32; #[ipc_rid(3)] #[return_session] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn open_auto( &self, in_name: InAutoSelectBuffer<AudioInterfaceName>, out_name: OutMapAliasBuffer<AudioInterfaceName>, params: AudioRequestParameters, aruid: AppletResourceUserId, process_handle: sf::CopyHandle, ) -> (AudioIn, AudioResponseParameters); #[ipc_rid(4)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn list_filtered(&self, names: OutAutoSelectBuffer<AudioInterfaceName>) -> u32; #[ipc_rid(5)] #[return_session] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn open_with_protocol( &self, in_name: InMapAliasBuffer<AudioInterfaceName>, out_name: OutMapAliasBuffer<AudioInterfaceName>, params: AudioRequestParameters, aruid: AppletResourceUserId, process_handle: sf::CopyHandle, protocol: u64, ) -> (AudioIn, AudioResponseParameters); } #[nx_derive::ipc_trait] #[default_client] pub trait AudioOut { #[ipc_rid(0)] fn get_state(&self) -> AudioState; #[ipc_rid(1)] fn start(&self); #[ipc_rid(2)] fn stop(&self); #[ipc_rid(3)] /// # Safety /// /// The `buffer_ptr` parameter must be a pointer to the `buffer` [`AudioBuffer`] unsafe fn append_buffer(&self, buffer: InMapAliasBuffer<AudioBuffer>, buffer_ptr: usize); #[ipc_rid(4)] fn register_buffer_event(&self) -> CopyHandle; #[ipc_rid(5)] fn get_released_buffers(&self, buffers: OutMapAliasBuffer<*mut AudioBuffer>) -> u32; #[ipc_rid(6)] fn contains_buffer(&self, buffer_ptr: usize) -> bool; #[ipc_rid(7)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] /// # Safety /// /// The `buffer_ptr` parameter must be a pointer to the `buffer` [`AudioBuffer`]. unsafe fn append_buffer_auto(&self, buffer: InAutoSelectBuffer<AudioBuffer>, buffer_ptr: usize); #[ipc_rid(8)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn get_released_buffers_auto(&self, buffers: OutAutoSelectBuffer<AudioBuffer>) -> u32; #[ipc_rid(9)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn get_buffer_count(&self) -> u32; #[ipc_rid(10)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn get_played_sample_count(&self) -> u64; #[ipc_rid(11)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn flush_buffers(&self) -> bool; #[ipc_rid(12)] #[version(version::VersionInterval::from(version::Version::new(6, 0, 0)))] fn set_volume(&self, volume: f32); #[ipc_rid(13)] #[version(version::VersionInterval::from(version::Version::new(6, 0, 0)))] fn get_volume(&self) -> u32; } #[nx_derive::ipc_trait] #[default_client] pub trait AudioIn { #[ipc_rid(0)] fn get_state(&self) -> AudioState; #[ipc_rid(1)] fn start(&self); #[ipc_rid(2)] fn stop(&self); #[ipc_rid(3)] /// # Safety /// /// The `buffer_ptr` parameter must be a pointer to the `buffer` [`AudioBuffer`] unsafe fn append_buffer(&self, buffer: InMapAliasBuffer<AudioBuffer>, buffer_ptr: usize); #[ipc_rid(4)] fn register_buffer_event(&self) -> CopyHandle; #[ipc_rid(5)] fn get_released_buffers(&self, buffers: OutMapAliasBuffer<*mut AudioBuffer>) -> u32; #[ipc_rid(6)] fn contains_buffer(&self, buffer_ptr: usize) -> bool; #[ipc_rid(8)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] /// # Safety /// /// The `buffer_ptr` parameter must be a pointer to the `buffer` [`AudioBuffer`] unsafe fn append_buffer_auto(&self, buffer: InAutoSelectBuffer<AudioBuffer>, buffer_ptr: usize); #[ipc_rid(9)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn get_released_buffers_auto(&self, buffers: OutAutoSelectBuffer<*mut AudioBuffer>) -> u32; #[ipc_rid(11)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn get_buffer_count(&self) -> u32; #[ipc_rid(12)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn set_device_gain(&mut self, gain: f32); #[ipc_rid(13)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn get_device_gain(&self) -> f32; #[ipc_rid(14)] #[version(version::VersionInterval::from(version::Version::new(6, 0, 0)))] fn flush_buffers(&self) -> bool; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/lm.rs
src/ipc/sf/lm.rs
use crate::ipc::sf; use crate::version; define_bit_set! { LogDestination (u32) { Tma = bit!(0), Uart = bit!(1), UartSleeping = bit!(2), All = 0xFFFF } } #[nx_derive::ipc_trait] #[default_client] pub trait Logger { #[ipc_rid(0)] fn log(&self, log_buf: sf::InAutoSelectBuffer<'_, u8>); #[ipc_rid(1)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn set_destination(&mut self, log_destination: LogDestination); } #[nx_derive::ipc_trait] pub trait Logging { #[ipc_rid(0)] #[return_session] fn open_logger(&mut self, process_id: sf::ProcessId) -> Logger; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/nv.rs
src/ipc/sf/nv.rs
use crate::ipc::sf; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u32)] pub enum ErrorCode { #[default] Success = 0, NotImplemented = 1, NotSupported = 2, NotInitialized = 3, InvalidParameter = 4, TimeOut = 5, InsufficientMemory = 6, ReadOnlyAttribute = 7, InvalidState = 8, InvalidAddress = 9, InvalidSize = 10, InvalidValue = 11, AlreadyAllocated = 13, Busy = 14, ResourceError = 15, CountMismatch = 16, SharedMemoryTooSmall = 0x1000, FileOperationFailed = 0x30003, IoctlFailed = 0x3000F, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum IoctlId { NvMapCreate = 0xC0080101, NvMapFromId = 0xC0080103, NvMapAlloc = 0xC0200104, NvMapFree = 0xC0180105, NvMapParam = 0xC00C0109, NvMapGetId = 0xC008010E, NvHostCtrlSyncptWait = 0xC00C0016, } pub type Fd = u32; #[nx_derive::ipc_trait] pub trait NvDrv { #[ipc_rid(0)] fn open(&self, path: sf::InMapAliasBuffer<'_, u8>) -> (Fd, ErrorCode); #[ipc_rid(1)] fn ioctl(&self, fd: Fd, id: IoctlId, in_buf: sf::InOutAutoSelectBuffer<'_, u8>) -> ErrorCode; #[ipc_rid(2)] fn close(&self, fd: Fd) -> ErrorCode; #[ipc_rid(3)] fn initialize( &self, transfer_mem_size: u32, self_process_handle: sf::CopyHandle, transfer_mem_handle: sf::CopyHandle, ) -> ErrorCode; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/fatal.rs
src/ipc/sf/fatal.rs
use crate::ipc::sf; use crate::result::*; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum FatalPolicy { ErrorReportAndErrorScreen, ErrorReport, ErrorScreen, } #[nx_derive::ipc_trait] pub trait Fatal { #[ipc_rid(1)] fn throw_fatal_with_policy( &self, rc: ResultCode, policy: FatalPolicy, process_id: sf::ProcessId, ); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/set.rs
src/ipc/sf/set.rs
use crate::ipc::sf; use crate::ipc::sf::mii; use crate::util; use crate::version; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct FirmwareVersion { pub major: u8, pub minor: u8, pub micro: u8, pub pad_1: u8, pub revision_major: u8, pub revision_minor: u8, pub pad_2: u8, pub pad_3: u8, pub platform: util::ArrayString<0x20>, pub version_hash: util::ArrayString<0x40>, pub display_version: util::ArrayString<0x18>, pub display_title: util::ArrayString<0x80>, } const_assert!(core::mem::size_of::<FirmwareVersion>() == 0x100); #[nx_derive::ipc_trait] pub trait SystemSettings { #[ipc_rid(3)] fn get_firmware_version(&self, out_version: sf::OutFixedPointerBuffer<'_, FirmwareVersion>); #[ipc_rid(4)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn get_firmware_version_2(&self, out_version: sf::OutFixedPointerBuffer<'_, FirmwareVersion>); #[ipc_rid(90)] fn get_mii_author_id(&self) -> mii::CreateId; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/fsp.rs
src/ipc/sf/fsp.rs
use crate::ipc::sf; use crate::util; use crate::version; pub mod rc; use nx_derive::{Request, Response}; define_bit_set! { FileOpenMode (u32) { None = 0, Read = bit!(0), Write = bit!(1), Append = bit!(2) } } define_bit_set! { DirectoryOpenMode (u32) { ReadDirectories = bit!(0), ReadFiles = bit!(1), NoFileSizes = bit!(31) } } define_bit_set! { FileAttribute (u32) { None = 0, ConcatenationFile = bit!(0) } } define_bit_set! { FileReadOption (u32) { None = 0 } } define_bit_set! { FileWriteOption (u32) { None = 0, Flush = bit!(0) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum DirectoryEntryType { #[default] Directory = 0, File = 1, } pub type Path = util::ArrayString<0x301>; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct DirectoryEntry { pub name: Path, pub attr: u8, pub pad: [u8; 2], pub entry_type: DirectoryEntryType, pub pad_2: [u8; 3], pub file_size: usize, } const_assert!(core::mem::size_of::<DirectoryEntry>() == 0x310); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct FileTimeStampRaw { pub create: i64, pub modify: i64, pub access: i64, pub is_local_time: bool, pub pad: [u8; 7], } const_assert!(core::mem::size_of::<FileTimeStampRaw>() == 0x20); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum QueryId { SetConcatenationFileAttribute = 0, UpdateMac = 1, IsSignedSystemPartitionOnSdCardValid = 2, QueryUnpreparedFileInformation = 3, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct FileQueryRangeInfo { pub aes_ctr_key_type: u32, pub speed_emulation_type: u32, pub reserved_1: [u8; 0x20], pub reserved_2: [u8; 0x18], } const_assert!(core::mem::size_of::<FileQueryRangeInfo>() == 0x40); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum OperationId { FillZero = 0, DestroySignature = 1, Invalidate = 2, QueryRange = 3, QueryUnpreparedRange = 4, QueryLazyLoadCompletionRate = 5, SetLazyLoadPriority = 6, ReadLazyLoadFileForciblyForDebug = 10001, } #[nx_derive::ipc_trait] #[default_client] pub trait File { #[ipc_rid(0)] fn read( &mut self, option: FileReadOption, offset: usize, size: usize, out_buf: sf::OutNonSecureMapAliasBuffer<'_, u8>, ) -> usize; #[ipc_rid(1)] fn write( &mut self, option: FileWriteOption, offset: usize, size: usize, buf: sf::InNonSecureMapAliasBuffer<'_, u8>, ); #[ipc_rid(2)] fn flush(&self); #[ipc_rid(3)] fn set_size(&mut self, size: usize); #[ipc_rid(4)] fn get_size(&mut self) -> usize; #[ipc_rid(5)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn operate_range( &mut self, operation_id: OperationId, offset: usize, size: usize, ) -> FileQueryRangeInfo; #[ipc_rid(6)] #[version(version::VersionInterval::from(version::Version::new(12, 0, 0)))] fn operate_range_with_buffer( &mut self, operation_id: OperationId, offset: usize, size: usize, in_buf: sf::InNonSecureMapAliasBuffer<'_, u8>, out_buf: sf::OutNonSecureMapAliasBuffer<'_, u8>, ); } #[nx_derive::ipc_trait] #[default_client] pub trait Directory { #[ipc_rid(0)] fn read(&self, out_entries: sf::OutMapAliasBuffer<'_, DirectoryEntry>) -> u64; #[ipc_rid(1)] fn get_entry_count(&self) -> u64; } #[nx_derive::ipc_trait] #[default_client] pub trait FileSystem { #[ipc_rid(0)] fn create_file( &self, attribute: FileAttribute, size: usize, path_buf: sf::InFixedPointerBuffer<'_, Path>, ); #[ipc_rid(1)] fn delete_file(&self, path_buf: sf::InFixedPointerBuffer<'_, Path>); #[ipc_rid(2)] fn create_directory(&self, path_buf: sf::InFixedPointerBuffer<'_, Path>); #[ipc_rid(3)] fn delete_directory(&self, path_buf: sf::InFixedPointerBuffer<'_, Path>); #[ipc_rid(4)] fn delete_directory_recursively(&self, path_buf: sf::InFixedPointerBuffer<'_, Path>); #[ipc_rid(5)] fn rename_file( &self, old_path_buf: sf::InFixedPointerBuffer<'_, Path>, new_path_buf: sf::InFixedPointerBuffer<'_, Path>, ); #[ipc_rid(6)] fn rename_directory( &self, old_path_buf: sf::InFixedPointerBuffer<'_, Path>, new_path_buf: sf::InFixedPointerBuffer<'_, Path>, ); #[ipc_rid(7)] fn get_entry_type(&self, path_buf: sf::InFixedPointerBuffer<'_, Path>) -> DirectoryEntryType; #[ipc_rid(8)] #[return_session] fn open_file(&self, mode: FileOpenMode, path_buf: sf::InFixedPointerBuffer<'_, Path>) -> File; #[ipc_rid(9)] #[return_session] fn open_directory( &self, mode: DirectoryOpenMode, path_buf: sf::InFixedPointerBuffer<'_, Path>, ) -> Directory; #[ipc_rid(10)] fn commit(&self); #[ipc_rid(11)] fn get_free_space_size(&self, path_buf: sf::InFixedPointerBuffer<'_, Path>) -> usize; #[ipc_rid(12)] fn get_total_space_size(&self, path_buf: sf::InFixedPointerBuffer<'_, Path>) -> usize; #[ipc_rid(13)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn clean_directory_recursively(&self, path_buf: sf::InFixedPointerBuffer<'_, Path>); #[ipc_rid(14)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn get_file_time_stamp_raw( &self, path_buf: sf::InFixedPointerBuffer<'_, Path>, ) -> FileTimeStampRaw; #[ipc_rid(15)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn query_entry( &self, path_buf: sf::InFixedPointerBuffer<'_, Path>, query_id: QueryId, in_buf: sf::InNonSecureMapAliasBuffer<'_, u8>, out_buf: sf::OutNonSecureMapAliasBuffer<'_, u8>, ); } #[nx_derive::ipc_trait] #[default_client] pub trait FileSystemProxy { #[ipc_rid(1)] fn set_current_process(&self, process_id: sf::ProcessId); #[ipc_rid(18)] #[return_session] fn open_sd_card_filesystem(&self) -> FileSystem; #[ipc_rid(1006)] fn output_access_log_to_sd_card(&self, log_buf: sf::InMapAliasBuffer<'_, u8>); } pub mod srv;
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/vi.rs
src/ipc/sf/vi.rs
use crate::ipc::sf; use crate::util; use sf::dispdrv::{HOSBinderDriver, IHOSBinderDriverServer}; use sf::applet::AppletResourceUserId; use nx_derive::{Request, Response}; pub type DisplayName = util::ArrayString<0x40>; define_bit_set! { LayerFlags (u32) { None = 0, Default = bit!(0) } } /// Tells the display service how to scale spawned layers. #[derive(Request, Response, Copy, Clone, Debug, Default)] #[repr(u64)] pub enum ScalingMode { None = 0, #[default] FitToLayer = 2, PreserveAspectRatio = 4, } pub type DisplayId = u64; pub type LayerId = u64; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u32)] pub enum DisplayServiceMode { User = 0, Privileged = 1, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(u32)] pub enum LayerStackId { #[default] Default, Lcd, Screenshot, Recording, LastFrame, Arbitrary, ApplicationForDebug, Null, } #[nx_derive::ipc_trait] #[default_client] pub trait ManagerDisplay { #[ipc_rid(2010)] fn create_managed_layer( &mut self, flags: LayerFlags, display_id: DisplayId, raw_aruid: u64, ) -> LayerId; #[ipc_rid(2011)] fn destroy_managed_layer(&self, id: LayerId); #[ipc_rid(6000)] fn add_to_layer_stack(&self, stack: LayerStackId, layer: LayerId); } #[nx_derive::ipc_trait] #[default_client] pub trait SystemDisplay { #[ipc_rid(1200)] fn get_z_order_count_min(&self, display_id: DisplayId) -> i64; #[ipc_rid(1202)] fn get_z_order_count_max(&self, display_id: DisplayId) -> i64; #[ipc_rid(2201)] fn set_layer_position(&mut self, x: f32, y: f32, id: LayerId); #[ipc_rid(2203)] fn set_layer_size(&mut self, id: LayerId, width: u64, height: u64); #[ipc_rid(2205)] fn set_layer_z(&mut self, id: LayerId, z: i64); #[ipc_rid(2207)] fn set_layer_visibility(&mut self, visible: bool, id: LayerId); } #[nx_derive::ipc_trait] #[default_client] pub trait ApplicationDisplay { #[ipc_rid(100)] #[return_session] fn get_relay_service(&self) -> HOSBinderDriver; #[ipc_rid(101)] #[return_session] fn get_system_display_service(&self) -> SystemDisplay; #[ipc_rid(102)] #[return_session] fn get_manager_display_service(&self) -> ManagerDisplay; #[ipc_rid(1010)] fn open_display(&mut self, name: DisplayName) -> DisplayId; #[ipc_rid(1020)] fn close_display(&mut self, id: DisplayId); #[ipc_rid(2020)] fn open_layer( &mut self, name: DisplayName, id: LayerId, aruid: AppletResourceUserId, out_native_window: sf::OutMapAliasBuffer<'_, u8>, ) -> usize; #[ipc_rid(2021)] fn destroy_managed_layer(&mut self, id: LayerId); #[ipc_rid(2030)] fn create_stray_layer( &mut self, flags: LayerFlags, display_id: DisplayId, out_native_window: sf::OutMapAliasBuffer<'_, u8>, ) -> (LayerId, usize); #[ipc_rid(2031)] fn destroy_stray_layer(&mut self, id: LayerId); #[ipc_rid(2101)] fn set_scaling_mode(&mut self, scaling_mode: ScalingMode, layer_id: LayerId); #[ipc_rid(5202)] fn get_display_vsync_event(&self, id: DisplayId) -> sf::CopyHandle; } #[nx_derive::ipc_trait] pub trait ApplicationDisplayRoot { #[ipc_rid(0)] #[return_session] fn get_display_service(&self, mode: DisplayServiceMode) -> ApplicationDisplay; } #[nx_derive::ipc_trait] pub trait SystemDisplayRoot { #[ipc_rid(1)] #[return_session] fn get_display_service(&self, mode: DisplayServiceMode) -> ApplicationDisplay; } #[nx_derive::ipc_trait] pub trait ManagerDisplayRoot { #[ipc_rid(2)] #[return_session] fn get_display_service(&self, mode: DisplayServiceMode) -> ApplicationDisplay; }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/usb/hs.rs
src/ipc/sf/usb/hs.rs
use crate::ipc::sf; use crate::version; use crate::{result::*, util}; use nx_derive::{Request, Response}; define_bit_set! { DeviceFilterFlags (u16) { IdVendor = bit!(0), IdProduct = bit!(1), DeviceMin = bit!(2), DeviceMax = bit!(3), DeviceClass = bit!(4), DeviceSubClass = bit!(5), DeviceProtocol = bit!(6), InterfaceClass = bit!(7), InterfaceSubClass = bit!(8), InterfaceProtocol = bit!(9) } } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct DeviceFilter { pub flags: DeviceFilterFlags, pub vendor_id: u16, pub product_id: u16, pub device_min_bcd: u16, pub device_max_bcd: u16, pub device_class: super::ClassCode, pub device_subclass: u8, pub device_protocol: u8, pub interface_class: super::ClassCode, pub interface_subclass: u8, pub interface_protocol: u8, } const_assert!(core::mem::size_of::<DeviceFilter>() == 0x10); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum InterfaceAvailableEventId { Unk0 = 0, Unk1 = 1, Unk2 = 2, } #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C, packed)] pub struct InterfaceProfile { pub id: u32, pub device_id: u32, pub unk: [u8; 0x4], pub interface_descriptor: super::InterfaceDescriptor, pub pad_1: [u8; 0x7], pub output_endpoint_descriptors: [super::EndPointDescriptor; 15], pub pad_2: [u8; 0x7], pub input_endpoint_descriptors: [super::EndPointDescriptor; 15], pub pad_3: [u8; 0x6], pub output_ss_endpoint_companion_descriptors: [super::SsEndPointCompanionDescriptor; 15], pub pad_4: [u8; 0x6], pub input_ss_endpoint_companion_descriptors: [super::SsEndPointCompanionDescriptor; 15], pub pad_5: [u8; 0x3], } const_assert!(core::mem::size_of::<InterfaceProfile>() == 0x1B8); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct InterfaceInfo { pub unk_str: util::ArrayString<0x40>, pub bus_id: u32, pub device_id: u32, pub device_descriptor: super::DeviceDescriptor, pub config_descriptor: super::ConfigDescriptor, pub pad: [u8; 0x5], pub unk_maybe_timestamp: u64, } const_assert!(core::mem::size_of::<InterfaceInfo>() == 0x70); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct InterfaceQueryOutput { pub profile: InterfaceProfile, pub info: InterfaceInfo, } const_assert!(core::mem::size_of::<InterfaceQueryOutput>() == 0x228); #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct XferReport { pub xfer_id: u32, pub result: ResultCode, pub requested_size: u32, pub transferred_size: u32, pub unk: [u8; 8], } const_assert!(core::mem::size_of::<XferReport>() == 0x18); #[nx_derive::ipc_trait] #[default_client] pub trait ClientEpSession { #[ipc_rid(0)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn submit_out_request(&self, size: u32, unk: u32, buf: sf::InMapAliasBuffer<'_, u8>) -> u32; #[ipc_rid(0)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn re_open(&self); #[ipc_rid(1)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn submit_in_request(&self, size: u32, unk: u32, out_buf: sf::OutMapAliasBuffer<'_, u8>) -> u32; #[ipc_rid(1)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn close(&self); #[ipc_rid(2)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn reset(&self); #[ipc_rid(2)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn get_completion_event(&self) -> sf::CopyHandle; #[ipc_rid(3)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn close_deprecated(&self); #[ipc_rid(3)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn populate_ring(&self); #[ipc_rid(4)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn post_buffer_async(&self, size: u32, buf_addr: u64, unk: u64) -> u32; #[ipc_rid(5)] #[version(version::VersionInterval::from_to( version::Version::new(2, 0, 0), version::Version::new(2, 3, 0) ))] fn get_xfer_report_deprecated( &self, count: u32, out_reports_buf: sf::OutMapAliasBuffer<'_, XferReport>, ) -> u32; #[ipc_rid(5)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn get_xfer_report( &self, count: u32, out_reports_buf: sf::OutAutoSelectBuffer<'_, XferReport>, ) -> u32; #[ipc_rid(6)] #[version(version::VersionInterval::from_to( version::Version::new(2, 0, 0), version::Version::new(2, 3, 0) ))] fn batch_buffer_async_deprecated( &self, urb_count: u32, unk_1: u32, unk_2: u32, buf_addr: u64, unk_3: u64, urb_sizes_buf: sf::InMapAliasBuffer<'_, u32>, ) -> u32; #[ipc_rid(6)] #[version(version::VersionInterval::from(version::Version::new(3, 0, 0)))] fn batch_buffer_async( &self, urb_count: u32, unk_1: u32, unk_2: u32, buf_addr: u64, unk_3: u64, urb_sizes_buf: sf::InAutoSelectBuffer<'_, u32>, ) -> u32; #[ipc_rid(7)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn create_smmu_space(&self, unk: [u8; 0x10]); #[ipc_rid(8)] #[version(version::VersionInterval::from(version::Version::new(4, 0, 0)))] fn share_report_ring(&self, unk: [u8; 0x4], unk_handle: sf::CopyHandle); } #[nx_derive::ipc_trait] #[default_client] pub trait ClientIfSession { #[ipc_rid(0)] fn get_state_change_event(&self) -> sf::CopyHandle; #[ipc_rid(1)] fn set_interface(&self, unk: u8, profile_buf: sf::InMapAliasBuffer<'_, InterfaceProfile>); #[ipc_rid(2)] fn get_interface(&self, out_profile_buf: sf::OutMapAliasBuffer<'_, InterfaceProfile>); #[ipc_rid(3)] fn get_alternate_interface( &self, unk: u8, out_profile_buf: sf::OutMapAliasBuffer<'_, InterfaceProfile>, ); #[ipc_rid(5)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn get_current_frame_deprecated(&self) -> u32; #[ipc_rid(4)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn get_current_frame(&self) -> u32; #[ipc_rid(5)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn ctrl_xfer_async( &self, request_type: u8, request: u8, val: u16, idx: u16, length: u16, buf_addr: u64, ); #[ipc_rid(6)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn submit_control_in_request( &self, request: u8, request_type: u8, val: u16, idx: u16, length: u16, timeout_ms: u32, out_buf: sf::OutMapAliasBuffer<'_, u8>, ) -> u32; #[ipc_rid(6)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn get_ctrl_xfer_completion_event(&self) -> sf::CopyHandle; #[ipc_rid(7)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn submit_control_out_request( &self, request: u8, request_type: u8, val: u16, idx: u16, length: u16, timeout_ms: u32, buf: sf::InMapAliasBuffer<'_, u8>, ) -> u32; #[ipc_rid(7)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn get_ctrl_xfer_report(&self, out_report_buf: sf::OutMapAliasBuffer<'_, XferReport>); #[ipc_rid(8)] fn reset_device(&self, unk: u32); #[ipc_rid(4)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn open_usb_ep_deprecated( &self, max_urb_count: u16, ep_type: u32, ep_number: u32, ep_direction: u32, max_xfer_size: u32, ) -> (super::EndPointDescriptor, ClientEpSession); #[ipc_rid(9)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn open_usb_ep( &self, max_urb_count: u16, ep_type: u32, ep_number: u32, ep_direction: u32, max_xfer_size: u32, ) -> (super::EndPointDescriptor, ClientEpSession); } #[nx_derive::ipc_trait] pub trait ClientRootSession { #[ipc_rid(0)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn bind_client_process(&self, self_process_handle: sf::CopyHandle); #[ipc_rid(0)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn query_all_interfaces_deprecated( &self, filter: DeviceFilter, out_intfs: sf::OutMapAliasBuffer<'_, InterfaceQueryOutput>, ) -> u32; #[ipc_rid(1)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn query_all_interfaces( &self, filter: DeviceFilter, out_intfs: sf::OutMapAliasBuffer<'_, InterfaceQueryOutput>, ) -> u32; #[ipc_rid(1)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn query_available_interfaces_deprecated( &self, filter: DeviceFilter, out_intfs: sf::OutMapAliasBuffer<'_, InterfaceQueryOutput>, ) -> u32; #[ipc_rid(2)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn query_available_interfaces( &self, filter: DeviceFilter, out_intfs: sf::OutMapAliasBuffer<'_, InterfaceQueryOutput>, ) -> u32; #[ipc_rid(2)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn query_acquired_interfaces_deprecated( &self, out_intfs: sf::OutMapAliasBuffer<'_, InterfaceQueryOutput>, ) -> u32; #[ipc_rid(3)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn query_acquired_interfaces( &self, out_intfs: sf::OutMapAliasBuffer<'_, InterfaceQueryOutput>, ) -> u32; #[ipc_rid(3)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn create_interface_available_event_deprecated( &self, event_id: InterfaceAvailableEventId, filter: DeviceFilter, ) -> sf::CopyHandle; #[ipc_rid(4)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn create_interface_available_event( &self, event_id: InterfaceAvailableEventId, filter: DeviceFilter, ) -> sf::CopyHandle; #[ipc_rid(4)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn destroy_interface_available_event_deprecated(&self, event_id: InterfaceAvailableEventId); #[ipc_rid(5)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn destroy_interface_available_event(&self, event_id: InterfaceAvailableEventId); #[ipc_rid(5)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn get_interface_state_change_event_deprecated(&self) -> sf::CopyHandle; #[ipc_rid(6)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn get_interface_state_change_event(&self) -> sf::CopyHandle; #[ipc_rid(6)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn acquire_usb_if_deprecated( &self, id: u32, out_profile_buf: sf::OutMapAliasBuffer<'_, InterfaceProfile>, ) -> ClientIfSession; #[ipc_rid(7)] #[version(version::VersionInterval::from(version::Version::new(2, 0, 0)))] fn acquire_usb_if( &self, id: u32, out_info_buf: sf::OutMapAliasBuffer<'_, InterfaceInfo>, out_profile_buf: sf::OutMapAliasBuffer<'_, InterfaceProfile>, ) -> ClientIfSession; #[ipc_rid(7)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn get_descriptor_string( &self, unk_1: u8, unk_2: bool, unk_maybe_id: u32, out_desc_buf: sf::OutMapAliasBuffer<'_, u8>, ) -> u32; #[ipc_rid(8)] #[version(version::VersionInterval::to(version::Version::new(1, 0, 0)))] fn reset_device(&self, unk: u32); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/hid/shmem.rs
src/ipc/sf/hid/shmem.rs
use core::fmt::Debug; use core::mem::MaybeUninit; use core::sync::atomic::Ordering; use core::sync::atomic::{AtomicU64, AtomicUsize}; use crate::svc::rc::ResultInvalidAddress; use super::*; pub const SHMEM_SIZE: usize = 0x40000; #[repr(C)] pub struct RingLifo<T: Copy + Clone + Debug, const S: usize> { pub vptr: u64, pub buf_count: AtomicUsize, pub tail: AtomicUsize, pub count: AtomicUsize, pub items: [AtomicSample<T>; S], } impl<T: Copy + Clone + Debug, const S: usize> core::fmt::Debug for RingLifo<T, S> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("RingLifo") .field("vptr", &self.vptr) .field("buf_count", &self.buf_count) .field("tail", &self.tail) .field("count", &self.count) .field("items", &self.items) .finish() } } // Copy bound it important as we (and libnx) rely on the data being trivially copy-able to memcopy the data out. #[derive(Debug)] #[repr(C)] pub struct AtomicSample<T: Copy + Clone + Debug> { pub sampling_size: AtomicU64, pub storage: T, } impl<T: Copy + Debug, const S: usize> RingLifo<T, S> { pub fn get_tail_item(&self) -> T { let mut out_value: MaybeUninit<T> = MaybeUninit::uninit(); loop { let tail_index = self.tail.load(Ordering::Acquire); let sampling_value_before = self.items[tail_index].sampling_size.load(Ordering::Acquire); // We read through a volatile pointer since it basically an uncached memcpy for our purposes. // The read is safe, as it is being constructed from a valid reference. unsafe { out_value.as_mut_ptr().write(core::ptr::read_volatile( &raw const self.items[tail_index].storage, )) }; if sampling_value_before == self.items[tail_index].sampling_size.load(Ordering::Acquire) { // the value hasn't been updated while we were reading it (split read) break; } } // we have successfully initialized the value slot, so we can unwrap it into the real type unsafe { out_value.assume_init() } } } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct DebugPadState { pub sampling_number: u64, pub attrs: DebugPadAttribute, pub buttons: DebugPadButton, pub analog_stick_r: AnalogStickState, pub analog_stick_l: AnalogStickState, } #[derive(Debug)] #[repr(C)] pub struct DebugPadSharedMemoryFormat { pub lifo: RingLifo<DebugPadState, 17>, pub pad: [u8; 0x138], } const_assert!(core::mem::size_of::<DebugPadSharedMemoryFormat>() == 0x400); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct TouchScreenState { pub sampling_number: u64, pub count: u32, pub reserved: [u8; 4], pub touches: [TouchState; 16], } #[derive(Debug)] #[repr(C)] pub struct TouchScreenSharedMemoryFormat { pub lifo: RingLifo<TouchScreenState, 17>, pub pad: [u8; 0x3C8], } const_assert!(core::mem::size_of::<TouchScreenSharedMemoryFormat>() == 0x3000); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct MouseState { pub sampling_number: u64, pub x: u32, pub y: u32, pub delta_x: u32, pub delta_y: u32, pub wheel_delta_x: u32, pub wheel_delta_y: u32, pub buttons: MouseButton, pub attributes: MouseAttribute, } #[derive(Debug)] #[repr(C)] pub struct MouseSharedMemoryFormat { pub lifo: RingLifo<MouseState, 17>, pub pad: [u8; 0xB0], } const_assert!(core::mem::size_of::<MouseSharedMemoryFormat>() == 0x400); #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct KeyboardState { pub sampling_number: u64, pub modifiers: KeyboardModifier, pub keys: KeyboardKeyStates, } #[derive(Debug)] #[repr(C)] pub struct KeyboardSharedMemoryFormat { pub lifo: RingLifo<KeyboardState, 17>, pub pad: [u8; 0x28], } const_assert!(core::mem::size_of::<KeyboardSharedMemoryFormat>() == 0x400); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct BasicXpadState { pub sampling_number: u64, pub attributes: BasicXpadAttribute, pub buttons: BasicXpadButton, pub analog_stick_l: AnalogStickState, pub analog_stick_r: AnalogStickState, } #[derive(Debug)] #[repr(C)] pub struct BasicXpadSharedMemoryEntry { pub lifo: RingLifo<BasicXpadState, 17>, pub pad: [u8; 0x138], } #[derive(Debug)] #[repr(C)] pub struct BasicXpadSharedMemoryFormat { pub entries: [BasicXpadSharedMemoryEntry; 4], } const_assert!(core::mem::size_of::<BasicXpadSharedMemoryFormat>() == 0x1000); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct DigitizerState { pub sampling_number: u64, pub unk_1: [u32; 2], pub attributes: DigitizerAttribute, pub buttons: DigitizerButton, pub unk_2: [u32; 16], } #[derive(Debug)] #[repr(C)] pub struct DigitizerSharedMemoryFormat { pub lifo: RingLifo<DigitizerState, 17>, pub pad: [u8; 0x980], } const_assert!(core::mem::size_of::<DigitizerSharedMemoryFormat>() == 0x1000); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct HomeButtonState { pub sampling_number: u64, pub buttons: HomeButton, } #[derive(Debug)] #[repr(C)] pub struct HomeButtonSharedMemoryFormat { pub lifo: RingLifo<HomeButtonState, 17>, pub pad: [u8; 0x48], } const_assert!(core::mem::size_of::<HomeButtonSharedMemoryFormat>() == 0x200); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct SleepButtonState { pub sampling_number: u64, pub buttons: SleepButton, } #[derive(Debug)] #[repr(C)] pub struct SleepButtonSharedMemoryFormat { pub lifo: RingLifo<SleepButtonState, 17>, pub pad: [u8; 0x48], } const_assert!(core::mem::size_of::<SleepButtonSharedMemoryFormat>() == 0x200); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct CaptureButtonState { pub sampling_number: u64, pub buttons: CaptureButton, } #[derive(Debug)] #[repr(C)] pub struct CaptureButtonSharedMemoryFormat { pub lifo: RingLifo<CaptureButtonState, 17>, pub pad: [u8; 0x48], } const_assert!(core::mem::size_of::<CaptureButtonSharedMemoryFormat>() == 0x200); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct InputDetectorState { pub source_state: InputSourceState, pub sampling_number: u64, } #[derive(Debug)] #[repr(C)] pub struct InputDetectorSharedMemoryEntry { pub lifo: RingLifo<InputDetectorState, 2>, pub pad: [u8; 0x30], } #[derive(Debug)] #[repr(C)] pub struct InputDetectorSharedMemoryFormat { pub entries: [InputDetectorSharedMemoryEntry; 16], } const_assert!(core::mem::size_of::<InputDetectorSharedMemoryFormat>() == 0x800); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct UniquePadConfig { pub pad_type: UniquePadType, pub interface: UniquePadInterface, pub serial_number: UniquePadSerialNumber, pub controller_number: u32, pub is_active: bool, pub reserved: [u8; 3], pub sampling_number: u64, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct AnalogStickCalibrationStateImpl { pub state: AnalogStickState, pub flags: AnalogStickCalibrationFlags, pub stage: AnalogStickManualCalibrationStage, pub sampling_number: u64, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct SixAxisSensorUserCalibrationState { pub flags: SixAxisSensorUserCalibrationFlags, pub reserved: [u8; 4], pub stage: SixAxisSensorUserCalibrationStage, pub sampling_number: u64, } #[derive(Debug)] #[repr(C)] pub struct UniquePadSharedMemoryEntry { pub config_lifo: RingLifo<UniquePadConfig, 2>, pub analog_stick_calibration_state_impls: [RingLifo<AnalogStickCalibrationStateImpl, 2>; 2], pub six_axis_sensor_user_calibration_state: RingLifo<SixAxisSensorUserCalibrationState, 2>, pub unique_pad_config_mutex: [u8; 0x40], pub pad: [u8; 0x220], } #[derive(Debug)] #[repr(C)] pub struct UniquePadSharedMemoryFormat { pub entries: [UniquePadSharedMemoryEntry; 16], } const_assert!(core::mem::size_of::<UniquePadSharedMemoryFormat>() == 0x4000); #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadFullKeyColorState { pub attribute: ColorAttribute, pub color: NpadControllerColor, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadJoyColorState { pub attribute: ColorAttribute, pub left_joy_color: NpadControllerColor, pub right_joy_color: NpadControllerColor, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadFullKeyState { pub sampling_number: u64, pub buttons: NpadButton, pub analog_stick_l: AnalogStickState, pub analog_stick_r: AnalogStickState, pub attributes: NpadAttribute, pub reserved: [u8; 4], } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadHandheldState { pub sampling_number: u64, pub buttons: NpadButton, pub analog_stick_l: AnalogStickState, pub analog_stick_r: AnalogStickState, pub attributes: NpadAttribute, pub reserved: [u8; 4], } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadJoyDualState { pub sampling_number: u64, pub buttons: NpadButton, pub analog_stick_l: AnalogStickState, pub analog_stick_r: AnalogStickState, pub attributes: NpadAttribute, pub reserved: [u8; 4], } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadJoyLeftState { pub sampling_number: u64, pub buttons: NpadButton, pub analog_stick_l: AnalogStickState, pub analog_stick_r: AnalogStickState, pub attributes: NpadAttribute, pub reserved: [u8; 4], } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadJoyRightState { pub sampling_number: u64, pub buttons: NpadButton, pub analog_stick_l: AnalogStickState, pub analog_stick_r: AnalogStickState, pub attributes: NpadAttribute, pub reserved: [u8; 4], } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadSystemState { pub sampling_number: u64, pub buttons: NpadButton, pub analog_stick_l: AnalogStickState, pub analog_stick_r: AnalogStickState, pub attributes: NpadAttribute, pub reserved: [u8; 4], } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadPalmaState { pub sampling_number: u64, pub buttons: NpadButton, pub analog_stick_l: AnalogStickState, pub analog_stick_r: AnalogStickState, pub attributes: NpadAttribute, pub reserved: [u8; 4], } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadSystemExtState { pub sampling_number: u64, pub buttons: NpadButton, pub analog_stick_l: AnalogStickState, pub analog_stick_r: AnalogStickState, pub attributes: NpadAttribute, pub reserved: [u8; 4], } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct SixAxisSensorState { pub delta_time: u64, pub sampling_number: u64, pub acceleration_x: u32, pub acceleration_y: u32, pub acceleration_z: u32, pub angular_velocity_x: u32, pub angular_velocity_y: u32, pub angular_velocity_z: u32, pub angle_x: u32, pub angle_y: u32, pub angle_z: u32, pub direction: DirectionState, pub attributes: SixAxisSensorAttribute, pub reserved: [u8; 4], } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NfcXcdDeviceHandleStateImpl { pub handle: u64, // TODO: xcd::DeviceHandle pub is_available: bool, pub is_activated: bool, pub reserved: [u8; 6], pub sampling_number: u64, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub struct NpadGcTriggerState { pub sampling_number: u64, pub trigger_l: u32, pub trigger_r: u32, } // V1: 1.0.0-3.0.2 // V2: 4.0.0-8.1.0 // V3: 9.0.0-12.1.0 // V4: 13.0.0- #[derive(Debug)] pub enum SharedMemoryFormat { V1(&'static SharedMemoryFormatV1), V2(&'static SharedMemoryFormatV2), V3(&'static SharedMemoryFormatV3), V4(&'static SharedMemoryFormatV4), V5(&'static SharedMemoryFormatV5), V6(&'static SharedMemoryFormatV6), } impl SharedMemoryFormat { /// Constructs an enum to get the controller parameters from the shared memory map. /// /// # Args /// * ptr - a const pointer to the controller's shared memory /// /// # Safety /// /// It is the caller's responsibility to make sure the returned struct does not outlive the shared memory mapping. pub unsafe fn from_shmem_ptr(ptr: *const u8) -> Result<Self> { let firmware_version = version::get_version(); // Safety - The calls to `cast()` should be safe as we only access it though the checked `as_ref()` calls, // and the pointer->reference preconditions are checked above. unsafe { if SharedMemoryFormatV1::VERSION_INTERVAL.contains(firmware_version) { Ok(Self::V1( ptr.cast::<SharedMemoryFormatV1>() .as_ref() .ok_or(ResultInvalidAddress::make())?, )) } else if SharedMemoryFormatV2::VERSION_INTERVAL.contains(firmware_version) { Ok(Self::V2( ptr.cast::<SharedMemoryFormatV2>() .as_ref() .ok_or(ResultInvalidAddress::make())?, )) } else if SharedMemoryFormatV3::VERSION_INTERVAL.contains(firmware_version) { Ok(Self::V3( ptr.cast::<SharedMemoryFormatV3>() .as_ref() .ok_or(ResultInvalidAddress::make())?, )) } else if SharedMemoryFormatV4::VERSION_INTERVAL.contains(firmware_version) { Ok(Self::V4( ptr.cast::<SharedMemoryFormatV4>() .as_ref() .ok_or(ResultInvalidAddress::make())?, )) } else if SharedMemoryFormatV5::VERSION_INTERVAL.contains(firmware_version) { Ok(Self::V5( ptr.cast::<SharedMemoryFormatV5>() .as_ref() .ok_or(ResultInvalidAddress::make())?, )) } else if SharedMemoryFormatV6::VERSION_INTERVAL.contains(firmware_version) { Ok(Self::V6( ptr.cast::<SharedMemoryFormatV6>() .as_ref() .ok_or(ResultInvalidAddress::make())?, )) } else { unreachable!( "We should never have this happen as all versions should be covered by the above matching" ) } } } pub fn as_ptr(&self) -> *const u8 { match *self { Self::V1(r) => r as *const SharedMemoryFormatV1 as *const _, Self::V2(r) => r as *const SharedMemoryFormatV2 as *const _, Self::V3(r) => r as *const SharedMemoryFormatV3 as *const _, Self::V4(r) => r as *const SharedMemoryFormatV4 as *const _, Self::V5(r) => r as *const SharedMemoryFormatV5 as *const _, Self::V6(r) => r as *const SharedMemoryFormatV6 as *const _, } } } #[derive(Debug)] #[repr(C)] pub struct NpadSharedMemoryEntryV1 { pub style_tag: NpadStyleTag, pub joy_assignment_mode: NpadJoyAssignmentMode, pub full_key_color: NpadFullKeyColorState, pub joy_color: NpadJoyColorState, pub full_key_lifo: RingLifo<NpadFullKeyState, 17>, pub handheld_lifo: RingLifo<NpadHandheldState, 17>, pub joy_dual_lifo: RingLifo<NpadJoyDualState, 17>, pub joy_left_lifo: RingLifo<NpadJoyLeftState, 17>, pub joy_right_lifo: RingLifo<NpadJoyRightState, 17>, pub system_lifo: RingLifo<NpadSystemState, 17>, pub system_ext_lifo: RingLifo<NpadSystemExtState, 17>, pub full_key_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub handheld_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_dual_left_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_dual_right_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_left_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_right_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub device_type: DeviceType, pub reserved: [u8; 4], pub system_properties: NpadSystemProperties, pub system_button_properties: NpadSystemButtonProperties, pub battery_level_joy_dual: NpadBatteryLevel, pub battery_level_joy_left: NpadBatteryLevel, pub battery_level_joy_right: NpadBatteryLevel, pub nfc_xcd_device_handle_lifo: RingLifo<NfcXcdDeviceHandleStateImpl, 2>, pub mutex: [u8; 0x40], pub gc_trigger_lifo: RingLifo<NpadGcTriggerState, 17>, pub lark_type_l_and_main: NpadLarkType, pub lark_type_r: NpadLarkType, pub lucia_type: NpadLuciaType, pub lager_type: NpadLagerType, pub pad: [u8; 0xBF0], } const_assert!(core::mem::size_of::<NpadSharedMemoryEntryV1>() == 0x5000); #[derive(Debug)] #[repr(C)] pub struct NpadSharedMemoryEntryV2 { pub style_tag: NpadStyleTag, pub joy_assignment_mode: NpadJoyAssignmentMode, pub full_key_color: NpadFullKeyColorState, pub joy_color: NpadJoyColorState, pub full_key_lifo: RingLifo<NpadFullKeyState, 17>, pub handheld_lifo: RingLifo<NpadHandheldState, 17>, pub joy_dual_lifo: RingLifo<NpadJoyDualState, 17>, pub joy_left_lifo: RingLifo<NpadJoyLeftState, 17>, pub joy_right_lifo: RingLifo<NpadJoyRightState, 17>, pub palma_lifo: RingLifo<NpadPalmaState, 17>, pub system_ext_lifo: RingLifo<NpadSystemExtState, 17>, pub full_key_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub handheld_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_dual_left_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_dual_right_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_left_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_right_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub device_type: DeviceType, pub reserved: [u8; 4], pub system_properties: NpadSystemProperties, pub system_button_properties: NpadSystemButtonProperties, pub battery_level_joy_dual: NpadBatteryLevel, pub battery_level_joy_left: NpadBatteryLevel, pub battery_level_joy_right: NpadBatteryLevel, pub nfc_xcd_device_handle_lifo: RingLifo<NfcXcdDeviceHandleStateImpl, 2>, pub mutex: [u8; 0x40], pub gc_trigger_lifo: RingLifo<NpadGcTriggerState, 17>, pub lark_type_l_and_main: NpadLarkType, pub lark_type_r: NpadLarkType, pub lucia_type: NpadLuciaType, pub lager_type: NpadLagerType, pub pad: [u8; 0xBF0], } const_assert!(core::mem::size_of::<NpadSharedMemoryEntryV2>() == 0x5000); #[derive(Debug)] #[repr(C)] pub struct NpadSharedMemoryEntryV3 { pub style_tag: NpadStyleTag, pub joy_assignment_mode: NpadJoyAssignmentMode, pub full_key_color: NpadFullKeyColorState, pub joy_color: NpadJoyColorState, pub full_key_lifo: RingLifo<NpadFullKeyState, 17>, pub handheld_lifo: RingLifo<NpadHandheldState, 17>, pub joy_dual_lifo: RingLifo<NpadJoyDualState, 17>, pub joy_left_lifo: RingLifo<NpadJoyLeftState, 17>, pub joy_right_lifo: RingLifo<NpadJoyRightState, 17>, pub palma_lifo: RingLifo<NpadPalmaState, 17>, pub system_ext_lifo: RingLifo<NpadSystemExtState, 17>, pub full_key_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub handheld_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_dual_left_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_dual_right_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_left_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_right_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub device_type: DeviceType, pub reserved: [u8; 4], pub system_properties: NpadSystemProperties, pub system_button_properties: NpadSystemButtonProperties, pub battery_level_joy_dual: NpadBatteryLevel, pub battery_level_joy_left: NpadBatteryLevel, pub battery_level_joy_right: NpadBatteryLevel, pub applet_footer_ui_attributes: AppletFooterUiAttribute, pub applet_footer_ui_type: AppletFooterUiType, pub reserved_2: [u8; 0x7B], pub gc_trigger_lifo: RingLifo<NpadGcTriggerState, 17>, pub lark_type_l_and_main: NpadLarkType, pub lark_type_r: NpadLarkType, pub lucia_type: NpadLuciaType, pub lager_type: NpadLagerType, pub pad: [u8; 0xC10], } const_assert!(core::mem::size_of::<NpadSharedMemoryEntryV3>() == 0x5000); #[derive(Debug)] #[repr(C)] pub struct NpadSharedMemoryEntryV4 { pub style_tag: NpadStyleTag, pub joy_assignment_mode: NpadJoyAssignmentMode, pub full_key_color: NpadFullKeyColorState, pub joy_color: NpadJoyColorState, pub full_key_lifo: RingLifo<NpadFullKeyState, 17>, pub handheld_lifo: RingLifo<NpadHandheldState, 17>, pub joy_dual_lifo: RingLifo<NpadJoyDualState, 17>, pub joy_left_lifo: RingLifo<NpadJoyLeftState, 17>, pub joy_right_lifo: RingLifo<NpadJoyRightState, 17>, pub palma_lifo: RingLifo<NpadPalmaState, 17>, pub system_ext_lifo: RingLifo<NpadSystemExtState, 17>, pub full_key_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub handheld_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_dual_left_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_dual_right_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_left_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub joy_right_six_axis_sensor_lifo: RingLifo<SixAxisSensorState, 17>, pub device_type: DeviceType, pub reserved: [u8; 4], pub system_properties: NpadSystemProperties, pub system_button_properties: NpadSystemButtonProperties, pub battery_level_joy_dual: NpadBatteryLevel, pub battery_level_joy_left: NpadBatteryLevel, pub battery_level_joy_right: NpadBatteryLevel, pub applet_footer_ui_attributes: AppletFooterUiAttribute, pub applet_footer_ui_type: AppletFooterUiType, pub reserved_2: [u8; 0x7B], pub gc_trigger_lifo: RingLifo<NpadGcTriggerState, 17>, pub lark_type_l_and_main: NpadLarkType, pub lark_type_r: NpadLarkType, pub lucia_type: NpadLuciaType, pub lager_type: NpadLagerType, pub six_axis_sensor_properties: [SixAxisSensorProperties; 6], pub pad: [u8; 0xC08], } const_assert!(core::mem::size_of::<NpadSharedMemoryEntryV4>() == 0x5000); #[derive(Debug)] #[repr(C)] pub struct NpadSharedMemoryFormatV1 { pub entries: [NpadSharedMemoryEntryV1; 10], } #[derive(Debug)] #[repr(C)] pub struct NpadSharedMemoryFormatV2 { pub entries: [NpadSharedMemoryEntryV2; 10], } #[derive(Debug)] #[repr(C)] pub struct NpadSharedMemoryFormatV3 { pub entries: [NpadSharedMemoryEntryV3; 10], } #[derive(Debug)] #[repr(C)] pub struct NpadSharedMemoryFormatV4 { pub entries: [NpadSharedMemoryEntryV4; 10], } #[derive(Copy, Clone, PartialEq, Debug)] #[repr(C)] pub struct GestureDummyState { pub sampling_number: u64, pub context_number: u8, pub gesture_type: GestureType, pub direction: GestureDirection, pub x: u32, pub y: u32, pub delta_x: u32, pub delta_y: u32, pub velocity_x: f32, pub velocity_y: f32, pub attributes: GestureAttribute, pub scale: u32, pub rotation_angle: u32, pub point_count: u32, pub points: [GesturePoint; 4], } #[derive(Debug)] #[repr(C)] pub struct GestureSharedMemoryFormat { pub lifo: RingLifo<GestureDummyState, 17>, pub pad: [u8; 0xF8], } const_assert!(core::mem::size_of::<GestureSharedMemoryFormat>() == 0x800); #[derive(Debug)] #[repr(C)] pub struct ConsoleSixAxisSensorSharedMemoryFormat { pub sampling_number: AtomicU64, pub is_seven_six_axis_sensor_at_rest: bool, pub pad: [u8; 3], pub verticalization_error: f32, pub gyro_bias: [f32; 3], pub pad2: [u8; 4], } const_assert!(core::mem::size_of::<ConsoleSixAxisSensorSharedMemoryFormat>() == 0x20); // V1: 1.0.0-3.0.2 // V2: 4.0.0-4.1.0 // V3: 5.0.0-8.1.0/8.1.1 // V4: 9.0.0-9.2.0 // V5: 10.0.0-12.1.0 // V6: 13.0.0- #[derive(Debug)] #[repr(C)] pub struct SharedMemoryFormatV1 { pub debug_pad: DebugPadSharedMemoryFormat, pub touch_screen: TouchScreenSharedMemoryFormat, pub mouse: MouseSharedMemoryFormat, pub keyboard: KeyboardSharedMemoryFormat, pub basic_xpad: BasicXpadSharedMemoryFormat, pub home_button: HomeButtonSharedMemoryFormat, pub sleep_button: SleepButtonSharedMemoryFormat, pub capture_button: CaptureButtonSharedMemoryFormat, pub input_detector: InputDetectorSharedMemoryFormat, pub unique_pad: UniquePadSharedMemoryFormat, pub npad: NpadSharedMemoryFormatV1, pub gesture: GestureSharedMemoryFormat, } const_assert!(align_of::<SharedMemoryFormatV1>() <= 8); impl SharedMemoryFormatV1 { pub const VERSION_INTERVAL: version::VersionInterval = version::VersionInterval::from_to( version::Version::new(1, 0, 0), version::Version::new(3, 0, 2), ); } #[derive(Debug)] #[repr(C)] pub struct SharedMemoryFormatV2 { pub debug_pad: DebugPadSharedMemoryFormat, pub touch_screen: TouchScreenSharedMemoryFormat, pub mouse: MouseSharedMemoryFormat, pub keyboard: KeyboardSharedMemoryFormat, pub basic_xpad: BasicXpadSharedMemoryFormat, pub home_button: HomeButtonSharedMemoryFormat, pub sleep_button: SleepButtonSharedMemoryFormat, pub capture_button: CaptureButtonSharedMemoryFormat, pub input_detector: InputDetectorSharedMemoryFormat, pub unique_pad: UniquePadSharedMemoryFormat, pub npad: NpadSharedMemoryFormatV2, pub gesture: GestureSharedMemoryFormat, } const_assert!(align_of::<SharedMemoryFormatV2>() <= 8); impl SharedMemoryFormatV2 { pub const VERSION_INTERVAL: version::VersionInterval = version::VersionInterval::from_to( version::Version::new(4, 0, 0), version::Version::new(4, 1, 0), ); } #[derive(Debug)] #[repr(C)] pub struct SharedMemoryFormatV3 { pub debug_pad: DebugPadSharedMemoryFormat, pub touch_screen: TouchScreenSharedMemoryFormat, pub mouse: MouseSharedMemoryFormat, pub keyboard: KeyboardSharedMemoryFormat, pub basic_xpad: BasicXpadSharedMemoryFormat, pub home_button: HomeButtonSharedMemoryFormat, pub sleep_button: SleepButtonSharedMemoryFormat, pub capture_button: CaptureButtonSharedMemoryFormat, pub input_detector: InputDetectorSharedMemoryFormat, pub pad: [u8; 0x4000], pub npad: NpadSharedMemoryFormatV2, pub gesture: GestureSharedMemoryFormat, pub console_six_axis_sensor: ConsoleSixAxisSensorSharedMemoryFormat, } const_assert!(align_of::<SharedMemoryFormatV3>() <= 8); impl SharedMemoryFormatV3 { pub const VERSION_INTERVAL: version::VersionInterval = version::VersionInterval::from_to( version::Version::new(5, 0, 0), version::Version::new(8, 1, 1), ); } #[derive(Debug)] #[repr(C)] pub struct SharedMemoryFormatV4 { pub debug_pad: DebugPadSharedMemoryFormat, pub touch_screen: TouchScreenSharedMemoryFormat, pub mouse: MouseSharedMemoryFormat, pub keyboard: KeyboardSharedMemoryFormat, pub basic_xpad: BasicXpadSharedMemoryFormat, pub home_button: HomeButtonSharedMemoryFormat, pub sleep_button: SleepButtonSharedMemoryFormat, pub capture_button: CaptureButtonSharedMemoryFormat, pub input_detector: InputDetectorSharedMemoryFormat, pub pad: [u8; 0x4000], pub npad: NpadSharedMemoryFormatV3, pub gesture: GestureSharedMemoryFormat, pub console_six_axis_sensor: ConsoleSixAxisSensorSharedMemoryFormat, } const_assert!(align_of::<SharedMemoryFormatV4>() <= 8); impl SharedMemoryFormatV4 { pub const VERSION_INTERVAL: version::VersionInterval = version::VersionInterval::from_to( version::Version::new(9, 0, 0), version::Version::new(9, 2, 0), ); } #[derive(Debug)] #[repr(C)] pub struct SharedMemoryFormatV5 { pub debug_pad: DebugPadSharedMemoryFormat, pub touch_screen: TouchScreenSharedMemoryFormat, pub mouse: MouseSharedMemoryFormat, pub keyboard: KeyboardSharedMemoryFormat, pub digitizer: DigitizerSharedMemoryFormat, pub home_button: HomeButtonSharedMemoryFormat, pub sleep_button: SleepButtonSharedMemoryFormat, pub capture_button: CaptureButtonSharedMemoryFormat, pub input_detector: InputDetectorSharedMemoryFormat, pub pad: [u8; 0x4000], pub npad: NpadSharedMemoryFormatV3, pub gesture: GestureSharedMemoryFormat, pub console_six_axis_sensor: ConsoleSixAxisSensorSharedMemoryFormat, } const_assert!(align_of::<SharedMemoryFormatV5>() <= 8); impl SharedMemoryFormatV5 { pub const VERSION_INTERVAL: version::VersionInterval = version::VersionInterval::from_to( version::Version::new(10, 0, 0), version::Version::new(12, 1, 0), ); } #[derive(Debug)] #[repr(C)] pub struct SharedMemoryFormatV6 { pub debug_pad: DebugPadSharedMemoryFormat, pub touch_screen: TouchScreenSharedMemoryFormat, pub mouse: MouseSharedMemoryFormat, pub keyboard: KeyboardSharedMemoryFormat, pub digitizer: DigitizerSharedMemoryFormat, pub home_button: HomeButtonSharedMemoryFormat, pub sleep_button: SleepButtonSharedMemoryFormat, pub capture_button: CaptureButtonSharedMemoryFormat, pub input_detector: InputDetectorSharedMemoryFormat, pub pad: [u8; 0x4000], pub npad: NpadSharedMemoryFormatV4, pub gesture: GestureSharedMemoryFormat, pub console_six_axis_sensor: ConsoleSixAxisSensorSharedMemoryFormat, } const_assert!(align_of::<SharedMemoryFormatV6>() <= 8); impl SharedMemoryFormatV6 { pub const VERSION_INTERVAL: version::VersionInterval = version::VersionInterval::from(version::Version::new(13, 0, 0)); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/audio/rc.rs
src/ipc/sf/audio/rc.rs
pub const RESULT_MODULE: u32 = 153; result_define_group!(RESULT_MODULE => { });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/hipc/rc.rs
src/ipc/sf/hipc/rc.rs
pub const RESULT_MODULE: u32 = 11; result_define_group!(RESULT_MODULE => { UnsupportedOperation: 1, SessionClosed: 301 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/bsd/rc.rs
src/ipc/sf/bsd/rc.rs
pub const RESULT_MODULE: u32 = 17; result_define_group!(RESULT_MODULE => { NotInitialized: 1, InvalidSocketString: 2, InvalidSockAddr:3, InvalidTimeout: 4 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/fsp/rc.rs
src/ipc/sf/fsp/rc.rs
pub const RESULT_MODULE: u32 = 2; result_define_group!(RESULT_MODULE => { PathNotFound: 1, PathAlreadyExists: 2 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/fsp/srv.rs
src/ipc/sf/fsp/srv.rs
use crate::ipc::sf; use super::FileSystem; #[nx_derive::ipc_trait] pub trait FileSystemProxy { #[ipc_rid(1)] fn set_current_process(&self, process_id: sf::ProcessId); #[ipc_rid(18)] fn open_sd_card_filesystem(&self) -> FileSystem; #[ipc_rid(1006)] fn output_access_log_to_sd_card(&self, log_buf: sf::InMapAliasBuffer<'_, u8>); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/nfp/rc.rs
src/ipc/sf/nfp/rc.rs
pub const RESULT_MODULE: u32 = 115; result_define_group!(RESULT_MODULE => { DeviceNotFound: 64, NeedRestart: 96, AreaNeedsToBeCreated: 128, AccessIdMismatch: 152, AreaAlreadyCreated: 168 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/sm/mitm.rs
src/ipc/sf/sm/mitm.rs
use crate::ipc::sf::{hid, ncm}; use nx_derive::{Request, Response}; #[derive(Request, Response, Copy, Clone, PartialEq, Eq, Debug, Default)] #[repr(C)] pub struct MitmProcessInfo { pub process_id: u64, pub program_id: ncm::ProgramId, pub npad_buttons: hid::NpadButton, pub override_flags: u64, } pub mod rc;
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/sm/rc.rs
src/ipc/sf/sm/rc.rs
pub const RESULT_MODULE: u32 = 21; result_define_group!(RESULT_MODULE => { NotInitialized: 2 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/sf/sm/mitm/rc.rs
src/ipc/sf/sm/mitm/rc.rs
use crate::ipc::sf::sm::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 1000; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { ShouldForwardToSession: 0 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/cmif/client.rs
src/ipc/cmif/client.rs
use super::*; use core::mem as cmem; #[inline(always)] pub fn write_command_on_msg_buffer( ctx: &mut CommandContext, command_type: CommandType, data_size: u32, ) { unsafe { let mut ipc_buf = get_msg_buffer(); let has_special_header = ctx.in_params.send_process_id || !ctx.in_params.copy_handles.is_empty() || !ctx.in_params.move_handles.is_empty(); let data_word_count = data_size.div_ceil(4); let command_header = ipc_buf as *mut CommandHeader; *command_header = CommandHeader::new( command_type as u32, ctx.send_statics.len() as u32, ctx.send_buffers.len() as u32, ctx.receive_buffers.len() as u32, ctx.exchange_buffers.len() as u32, data_word_count, ctx.receive_statics.len() as u32, has_special_header, ); ipc_buf = command_header.offset(1) as *mut u8; if has_special_header { let special_header = ipc_buf as *mut CommandSpecialHeader; *special_header = CommandSpecialHeader::new( ctx.in_params.send_process_id, ctx.in_params.copy_handles.len() as u32, ctx.in_params.move_handles.len() as u32, ); ipc_buf = special_header.offset(1) as *mut u8; if ctx.in_params.send_process_id { ipc_buf = ipc_buf.add(cmem::size_of::<u64>()); } ipc_buf = write_array_to_buffer( ipc_buf, ctx.in_params.copy_handles.len() as u32, &ctx.in_params.copy_handles, ); ipc_buf = write_array_to_buffer( ipc_buf, ctx.in_params.move_handles.len() as u32, &ctx.in_params.move_handles, ); } ipc_buf = write_array_to_buffer(ipc_buf, ctx.send_statics.len() as u32, &ctx.send_statics); ipc_buf = write_array_to_buffer(ipc_buf, ctx.send_buffers.len() as u32, &ctx.send_buffers); ipc_buf = write_array_to_buffer( ipc_buf, ctx.receive_buffers.len() as u32, &ctx.receive_buffers, ); ipc_buf = write_array_to_buffer( ipc_buf, ctx.exchange_buffers.len() as u32, &ctx.exchange_buffers, ); ctx.in_params.data_words_offset = ipc_buf; ipc_buf = ipc_buf.add(cmem::size_of::<u32>() * data_word_count as usize); write_array_to_buffer( ipc_buf, ctx.receive_statics.len() as u32, &ctx.receive_statics, ); } } #[inline(always)] pub fn read_command_response_from_msg_buffer(ctx: &mut CommandContext) { unsafe { let mut ipc_buf = get_msg_buffer(); let command_header = ipc_buf as *mut CommandHeader; ipc_buf = command_header.offset(1) as *mut u8; let mut copy_handle_count: u32 = 0; let mut move_handle_count: u32 = 0; if (*command_header).get_has_special_header() { let special_header = ipc_buf as *mut CommandSpecialHeader; copy_handle_count = (*special_header).get_copy_handle_count(); move_handle_count = (*special_header).get_move_handle_count(); ipc_buf = special_header.offset(1) as *mut u8; if (*special_header).get_send_process_id() { ctx.out_params.process_id = *(ipc_buf as *mut u64); ipc_buf = ipc_buf.add(cmem::size_of::<u64>()); } } ipc_buf = read_array_from_buffer(ipc_buf, copy_handle_count, &mut ctx.out_params.copy_handles); ipc_buf = read_array_from_buffer(ipc_buf, move_handle_count, &mut ctx.out_params.move_handles); ipc_buf = ipc_buf.add( cmem::size_of::<SendStaticDescriptor>() * (*command_header).get_send_static_count() as usize, ); ctx.out_params.data_words_offset = ipc_buf; } } #[inline(always)] pub fn write_request_command_on_msg_buffer( ctx: &mut CommandContext, request_id: Option<u32>, domain_command_type: DomainCommandType, ) { unsafe { let ipc_buf = get_msg_buffer(); let has_data_header = request_id.is_some(); let mut data_size = DATA_PADDING + ctx.in_params.data_size; if has_data_header { data_size += cmem::size_of::<DataHeader>() as u32; } if ctx.object_info.is_domain() { data_size += (cmem::size_of::<DomainInDataHeader>() + cmem::size_of::<DomainObjectId>() * ctx.in_params.objects.len()) as u32; } data_size = (data_size + 1) & !1; let out_pointer_sizes_offset = data_size; data_size += (cmem::size_of::<u16>() * ctx.in_params.out_pointer_sizes.len()) as u32; write_command_on_msg_buffer(ctx, CommandType::Request, data_size); let mut data_offset = get_aligned_data_offset(ctx.in_params.data_words_offset, ipc_buf); let out_pointer_sizes = ctx .in_params .data_words_offset .offset(out_pointer_sizes_offset as isize); write_array_to_buffer( out_pointer_sizes, ctx.in_params.out_pointer_sizes.len() as u32, &ctx.in_params.out_pointer_sizes, ); let mut data_header = data_offset as *mut DataHeader; if ctx.object_info.is_domain() { let domain_header = data_offset as *mut DomainInDataHeader; let left_data_size = cmem::size_of::<DataHeader>() as u32 + ctx.in_params.data_size; *domain_header = DomainInDataHeader::new( domain_command_type, ctx.in_params.objects.len() as u8, left_data_size as u16, ctx.object_info.domain_object_id, 0, ); data_offset = data_offset.add(cmem::size_of::<DomainInDataHeader>()); let objects_offset = data_offset.offset(left_data_size as isize); write_array_to_buffer( objects_offset, ctx.in_params.objects.len() as u32, &ctx.in_params.objects, ); data_header = data_offset as *mut DataHeader; } if has_data_header { *data_header = DataHeader::new(IN_DATA_HEADER_MAGIC, 0, request_id.unwrap(), 0); data_offset = data_offset.add(cmem::size_of::<DataHeader>()); } ctx.in_params.data_offset = data_offset; } } #[inline(always)] pub fn read_request_command_response_from_msg_buffer(ctx: &mut CommandContext) -> Result<()> { unsafe { let ipc_buf = get_msg_buffer(); read_command_response_from_msg_buffer(ctx); let mut data_offset = get_aligned_data_offset(ctx.out_params.data_words_offset, ipc_buf); let mut data_header = data_offset as *mut DataHeader; if ctx.object_info.is_domain() { let domain_header = data_offset as *mut DomainOutDataHeader; data_offset = data_offset.add(cmem::size_of::<DomainOutDataHeader>()); let objects_offset = data_offset.add(cmem::size_of::<DataHeader>() + ctx.out_params.data_size as usize); let object_count = (*domain_header).out_object_count; read_array_from_buffer(objects_offset, object_count, &mut ctx.out_params.objects); data_header = data_offset as *mut DataHeader; } data_offset = data_offset.add(cmem::size_of::<DataHeader>()); result_return_unless!( (*data_header).magic == OUT_DATA_HEADER_MAGIC, super::rc::ResultInvalidOutputHeader ); result_try!(ResultCode::new((*data_header).value)); ctx.out_params.data_offset = data_offset; Ok(()) } } #[inline(always)] pub fn write_control_command_on_msg_buffer(ctx: &mut CommandContext, request_id: ControlRequestId) { unsafe { let ipc_buf = get_msg_buffer(); let data_size = DATA_PADDING + cmem::size_of::<DataHeader>() as u32 + ctx.in_params.data_size; write_command_on_msg_buffer(ctx, CommandType::Control, data_size); let mut data_offset = get_aligned_data_offset(ctx.in_params.data_words_offset, ipc_buf); let data_header = data_offset as *mut DataHeader; *data_header = DataHeader::new(IN_DATA_HEADER_MAGIC, 0, request_id as u32, 0); data_offset = data_offset.add(cmem::size_of::<DataHeader>()); ctx.in_params.data_offset = data_offset; } } #[inline(always)] pub fn read_control_command_response_from_msg_buffer(ctx: &mut CommandContext) -> Result<()> { unsafe { let ipc_buf = get_msg_buffer(); read_command_response_from_msg_buffer(ctx); let mut data_offset = get_aligned_data_offset(ctx.out_params.data_words_offset, ipc_buf); let data_header = data_offset as *mut DataHeader; data_offset = data_offset.add(cmem::size_of::<DataHeader>()); result_return_unless!( (*data_header).magic == OUT_DATA_HEADER_MAGIC, super::rc::ResultInvalidOutputHeader ); result_try!(ResultCode::new((*data_header).value)); ctx.out_params.data_offset = data_offset; Ok(()) } } #[inline(always)] pub fn write_close_command_on_msg_buffer(ctx: &mut CommandContext) { write_command_on_msg_buffer(ctx, CommandType::Close, 0); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/cmif/rc.rs
src/ipc/cmif/rc.rs
pub const RESULT_MODULE: u32 = 10; result_define_group!(RESULT_MODULE => { InvalidHeaderSize: 202, InvalidInputHeader: 211, InvalidOutputHeader: 212, InvalidCommandRequestId: 221, InvalidInObjectCount: 235, InvalidOutObjectCount: 236 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/cmif/server.rs
src/ipc/cmif/server.rs
use super::*; use core::mem as cmem; #[inline(always)] pub fn read_command_from_msg_buffer(ctx: &mut CommandContext) -> CommandType { unsafe { let mut ipc_buf = get_msg_buffer(); let command_header = ipc_buf as *mut CommandHeader; ipc_buf = command_header.offset(1) as *mut u8; let command_type = (*command_header).get_command_type(); let data_size = (*command_header).get_data_word_count() * cmem::size_of::<u32>() as u32; ctx.in_params.data_size = data_size; if (*command_header).get_has_special_header() { let special_header = ipc_buf as *mut CommandSpecialHeader; ipc_buf = special_header.offset(1) as *mut u8; ctx.in_params.send_process_id = (*special_header).get_send_process_id(); if ctx.in_params.send_process_id { let process_id_ptr = ipc_buf as *mut u64; ctx.in_params.process_id = *process_id_ptr; ipc_buf = process_id_ptr.offset(1) as *mut u8; } let copy_handle_count = (*special_header).get_copy_handle_count(); ipc_buf = read_array_from_buffer(ipc_buf, copy_handle_count, &mut ctx.in_params.copy_handles); let move_handle_count = (*special_header).get_move_handle_count(); ipc_buf = read_array_from_buffer(ipc_buf, move_handle_count, &mut ctx.in_params.move_handles); } let send_static_count = (*command_header).get_send_static_count(); ipc_buf = read_array_from_buffer(ipc_buf, send_static_count, &mut ctx.send_statics); let send_buffer_count = (*command_header).get_send_buffer_count(); ipc_buf = read_array_from_buffer(ipc_buf, send_buffer_count, &mut ctx.send_buffers); let receive_buffer_count = (*command_header).get_receive_buffer_count(); ipc_buf = read_array_from_buffer(ipc_buf, receive_buffer_count, &mut ctx.receive_buffers); let exchange_buffer_count = (*command_header).get_exchange_buffer_count(); ipc_buf = read_array_from_buffer(ipc_buf, exchange_buffer_count, &mut ctx.exchange_buffers); ctx.in_params.data_words_offset = ipc_buf; ipc_buf = ipc_buf.offset(data_size as isize); let receive_static_count = (*command_header).get_receive_static_count(); read_array_from_buffer(ipc_buf, receive_static_count, &mut ctx.receive_statics); convert_command_type(command_type) } } #[inline(always)] pub fn write_command_response_on_msg_buffer( ctx: &mut CommandContext, command_type: CommandType, data_size: u32, ) { unsafe { let mut ipc_buf = get_msg_buffer(); let command_header = ipc_buf as *mut CommandHeader; ipc_buf = command_header.offset(1) as *mut u8; let data_word_count = data_size.div_ceil(4); let has_special_header = ctx.out_params.send_process_id || !ctx.out_params.copy_handles.is_empty() || !ctx.out_params.move_handles.is_empty(); *command_header = CommandHeader::new( command_type as u32, ctx.send_statics.len() as u32, ctx.send_buffers.len() as u32, ctx.receive_buffers.len() as u32, ctx.exchange_buffers.len() as u32, data_word_count, ctx.receive_statics.len() as u32, has_special_header, ); if has_special_header { let special_header = ipc_buf as *mut CommandSpecialHeader; ipc_buf = special_header.offset(1) as *mut u8; *special_header = CommandSpecialHeader::new( ctx.out_params.send_process_id, ctx.out_params.copy_handles.len() as u32, ctx.out_params.move_handles.len() as u32, ); if ctx.out_params.send_process_id { ipc_buf = ipc_buf.add(cmem::size_of::<u64>()); } ipc_buf = write_array_to_buffer( ipc_buf, ctx.out_params.copy_handles.len() as u32, &ctx.out_params.copy_handles, ); ipc_buf = write_array_to_buffer( ipc_buf, ctx.out_params.move_handles.len() as u32, &ctx.out_params.move_handles, ); } ipc_buf = write_array_to_buffer(ipc_buf, ctx.send_statics.len() as u32, &ctx.send_statics); ipc_buf = write_array_to_buffer(ipc_buf, ctx.send_buffers.len() as u32, &ctx.send_buffers); ipc_buf = write_array_to_buffer( ipc_buf, ctx.receive_buffers.len() as u32, &ctx.receive_buffers, ); ipc_buf = write_array_to_buffer( ipc_buf, ctx.exchange_buffers.len() as u32, &ctx.exchange_buffers, ); ctx.out_params.data_words_offset = ipc_buf; ipc_buf = ipc_buf.offset((data_word_count * cmem::size_of::<u32>() as u32) as isize); write_array_to_buffer( ipc_buf, ctx.receive_statics.len() as u32, &ctx.receive_statics, ); } } #[inline(always)] pub fn read_request_command_from_msg_buffer( ctx: &mut CommandContext, ) -> Result<(u32, DomainCommandType, DomainObjectId)> { unsafe { let mut domain_command_type = DomainCommandType::Invalid; let mut domain_object_id: DomainObjectId = 0; let ipc_buf = get_msg_buffer(); let mut data_ptr = get_aligned_data_offset(ctx.in_params.data_words_offset, ipc_buf); let mut data_header = data_ptr as *mut DataHeader; if ctx.object_info.is_domain() { let domain_header = data_ptr as *mut DomainInDataHeader; data_ptr = domain_header.offset(1) as *mut u8; ctx.in_params.data_size -= cmem::size_of::<DomainInDataHeader>() as u32; domain_command_type = (*domain_header).command_type; let object_count = (*domain_header).object_count; domain_object_id = (*domain_header).domain_object_id; let objects_offset = data_ptr.offset((*domain_header).data_size as isize); read_array_from_buffer( objects_offset, object_count as u32, &mut ctx.in_params.objects, ); data_header = data_ptr as *mut DataHeader; } let mut rq_id: u32 = 0; if ctx.in_params.data_size >= DATA_PADDING { ctx.in_params.data_size -= DATA_PADDING; if ctx.in_params.data_size >= cmem::size_of::<DataHeader>() as u32 { result_return_unless!( (*data_header).magic == IN_DATA_HEADER_MAGIC, super::rc::ResultInvalidInputHeader ); rq_id = (*data_header).value; data_ptr = data_header.offset(1) as *mut u8; ctx.in_params.data_size -= cmem::size_of::<DataHeader>() as u32; } } ctx.in_params.data_offset = data_ptr; Ok((rq_id, domain_command_type, domain_object_id)) } } #[inline(always)] pub fn write_request_command_response_on_msg_buffer( ctx: &mut CommandContext, result: ResultCode, request_type: CommandType, ) { unsafe { let ipc_buf = get_msg_buffer(); let mut data_size = DATA_PADDING + cmem::size_of::<DataHeader>() as u32 + ctx.out_params.data_size; if ctx.object_info.is_domain() { data_size += (cmem::size_of::<DomainOutDataHeader>() + cmem::size_of::<DomainObjectId>() * ctx.out_params.objects.len()) as u32; } data_size = (data_size + 1) & !1; write_command_response_on_msg_buffer(ctx, request_type, data_size); let mut data_offset = get_aligned_data_offset(ctx.out_params.data_words_offset, ipc_buf); let mut data_header = data_offset as *mut DataHeader; if ctx.object_info.is_domain() { let domain_header = data_offset as *mut DomainOutDataHeader; data_offset = domain_header.offset(1) as *mut u8; *domain_header = DomainOutDataHeader::new(ctx.out_params.objects.len() as u32); let objects_offset = data_offset.add(cmem::size_of::<DataHeader>() + ctx.out_params.data_size as usize); write_array_to_buffer( objects_offset, ctx.out_params.objects.len() as u32, &ctx.out_params.objects, ); data_header = data_offset as *mut DataHeader; } data_offset = data_header.offset(1) as *mut u8; let version: u32 = match request_type { CommandType::RequestWithContext => 1, _ => 0, }; *data_header = DataHeader::new(OUT_DATA_HEADER_MAGIC, version, result.get_value(), 0); ctx.out_params.data_offset = data_offset; } } #[inline(always)] pub fn read_control_command_from_msg_buffer(ctx: &mut CommandContext) -> Result<ControlRequestId> { unsafe { let ipc_buf = get_msg_buffer(); let mut data_offset = get_aligned_data_offset(ctx.in_params.data_words_offset, ipc_buf); let data_header = data_offset as *mut DataHeader; data_offset = data_header.offset(1) as *mut u8; result_return_unless!( (*data_header).magic == IN_DATA_HEADER_MAGIC, super::rc::ResultInvalidInputHeader ); let control_rq_id = (*data_header).value; ctx.in_params.data_offset = data_offset; ctx.in_params.data_size -= DATA_PADDING + cmem::size_of::<DataHeader>() as u32; Ok(cmem::transmute::<u32, ControlRequestId>(control_rq_id)) } } #[inline(always)] pub fn write_control_command_response_on_msg_buffer( ctx: &mut CommandContext, result: ResultCode, control_type: CommandType, ) { unsafe { let ipc_buf = get_msg_buffer(); let mut data_size = DATA_PADDING + cmem::size_of::<DataHeader>() as u32 + ctx.out_params.data_size; data_size = (data_size + 1) & !1; write_command_response_on_msg_buffer(ctx, control_type, data_size); let mut data_offset = get_aligned_data_offset(ctx.out_params.data_words_offset, ipc_buf); let data_header = data_offset as *mut DataHeader; data_offset = data_header.offset(1) as *mut u8; let version: u32 = match control_type { CommandType::ControlWithContext => 1, _ => 0, }; *data_header = DataHeader::new(OUT_DATA_HEADER_MAGIC, version, result.get_value(), 0); ctx.out_params.data_offset = data_offset; } } #[inline(always)] pub fn write_close_command_response_on_msg_buffer(ctx: &mut CommandContext) { write_command_response_on_msg_buffer(ctx, CommandType::Close, 0); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/server/rc.rs
src/ipc/server/rc.rs
use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 1300; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { ObjectIdAlreadyAllocated: 1, DomainNotFound: 2, InvalidCommandType: 3, InvalidDomainCommandType: 4, SignaledServerNotFound: 5, AlreadyDomain: 6 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/tipc/client.rs
src/ipc/tipc/client.rs
use super::*; use core::mem as cmem; #[inline(always)] pub fn write_command_on_msg_buffer(ctx: &mut CommandContext, command_type: u32, data_size: u32) { unsafe { // TODO: in move handles are allowed? let mut ipc_buf = get_msg_buffer(); let has_special_header = ctx.in_params.send_process_id || !ctx.in_params.copy_handles.is_empty() || !ctx.in_params.move_handles.is_empty(); let data_word_count = data_size.div_ceil(4); let command_header = ipc_buf as *mut CommandHeader; *command_header = CommandHeader::new( command_type, 0, ctx.send_buffers.len() as u32, ctx.receive_buffers.len() as u32, ctx.exchange_buffers.len() as u32, data_word_count, 0, has_special_header, ); ipc_buf = command_header.offset(1) as *mut u8; if has_special_header { let special_header = ipc_buf as *mut CommandSpecialHeader; *special_header = CommandSpecialHeader::new( ctx.in_params.send_process_id, ctx.in_params.copy_handles.len() as u32, ctx.in_params.move_handles.len() as u32, ); ipc_buf = special_header.offset(1) as *mut u8; if ctx.in_params.send_process_id { ipc_buf = ipc_buf.add(cmem::size_of::<u64>()); } ipc_buf = write_array_to_buffer( ipc_buf, ctx.in_params.copy_handles.len() as u32, &ctx.in_params.copy_handles, ); ipc_buf = write_array_to_buffer( ipc_buf, ctx.in_params.move_handles.len() as u32, &ctx.in_params.move_handles, ); } ipc_buf = write_array_to_buffer(ipc_buf, ctx.send_buffers.len() as u32, &ctx.send_buffers); ipc_buf = write_array_to_buffer( ipc_buf, ctx.receive_buffers.len() as u32, &ctx.receive_buffers, ); ipc_buf = write_array_to_buffer( ipc_buf, ctx.exchange_buffers.len() as u32, &ctx.exchange_buffers, ); ctx.in_params.data_words_offset = ipc_buf; } } #[inline(always)] pub fn read_command_response_from_msg_buffer(ctx: &mut CommandContext) { unsafe { let mut ipc_buf = get_msg_buffer(); let command_header = ipc_buf as *mut CommandHeader; ipc_buf = command_header.offset(1) as *mut u8; let mut copy_handle_count: u32 = 0; let mut move_handle_count: u32 = 0; if (*command_header).get_has_special_header() { let special_header = ipc_buf as *mut CommandSpecialHeader; copy_handle_count = (*special_header).get_copy_handle_count(); move_handle_count = (*special_header).get_move_handle_count(); ipc_buf = special_header.offset(1) as *mut u8; if (*special_header).get_send_process_id() { ctx.out_params.process_id = *(ipc_buf as *mut u64); ipc_buf = ipc_buf.add(cmem::size_of::<u64>()); } } ipc_buf = read_array_from_buffer(ipc_buf, copy_handle_count, &mut ctx.out_params.copy_handles); ipc_buf = read_array_from_buffer(ipc_buf, move_handle_count, &mut ctx.out_params.move_handles); ctx.out_params.data_words_offset = ipc_buf; } } #[inline(always)] pub fn write_request_command_on_msg_buffer(ctx: &mut CommandContext, request_id: u32) { // TIPC directly sends the request ID here, without wasting data words let command_type = request_id + 16; write_command_on_msg_buffer(ctx, command_type, ctx.in_params.data_size); ctx.in_params.data_offset = ctx.in_params.data_words_offset; } #[inline(always)] pub fn read_request_command_response_from_msg_buffer(ctx: &mut CommandContext) -> Result<()> { unsafe { read_command_response_from_msg_buffer(ctx); let data_offset = ctx.out_params.data_words_offset; let rc_ref = data_offset as *mut ResultCode; result_try!(*rc_ref); ctx.out_params.data_offset = rc_ref.offset(1) as *mut u8; Ok(()) } } #[inline(always)] pub fn write_close_command_on_msg_buffer(ctx: &mut CommandContext) { write_command_on_msg_buffer(ctx, CommandType::CloseSession as u32, 0); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/ipc/tipc/server.rs
src/ipc/tipc/server.rs
use super::*; use core::mem as cmem; #[inline(always)] pub fn read_command_from_msg_buffer(ctx: &mut CommandContext) -> u32 { unsafe { let mut ipc_buf = get_msg_buffer(); let command_header = ipc_buf as *mut CommandHeader; ipc_buf = command_header.offset(1) as *mut u8; let command_type = (*command_header).get_command_type(); let data_size = (*command_header).get_data_word_count() * cmem::size_of::<u32>() as u32; ctx.in_params.data_size = data_size; if (*command_header).get_has_special_header() { let special_header = ipc_buf as *mut CommandSpecialHeader; ipc_buf = special_header.offset(1) as *mut u8; ctx.in_params.send_process_id = (*special_header).get_send_process_id(); if ctx.in_params.send_process_id { let process_id_ptr = ipc_buf as *mut u64; ctx.in_params.process_id = *process_id_ptr; ipc_buf = process_id_ptr.offset(1) as *mut u8; } let copy_handle_count = (*special_header).get_copy_handle_count(); ipc_buf = read_array_from_buffer(ipc_buf, copy_handle_count, &mut ctx.in_params.copy_handles); let move_handle_count = (*special_header).get_move_handle_count(); ipc_buf = read_array_from_buffer(ipc_buf, move_handle_count, &mut ctx.in_params.move_handles); } let send_buffer_count = (*command_header).get_send_buffer_count(); ipc_buf = read_array_from_buffer(ipc_buf, send_buffer_count, &mut ctx.send_buffers); let receive_buffer_count = (*command_header).get_receive_buffer_count(); ipc_buf = read_array_from_buffer(ipc_buf, receive_buffer_count, &mut ctx.receive_buffers); let exchange_buffer_count = (*command_header).get_exchange_buffer_count(); ipc_buf = read_array_from_buffer(ipc_buf, exchange_buffer_count, &mut ctx.exchange_buffers); ctx.in_params.data_words_offset = ipc_buf; command_type } } #[inline(always)] pub fn write_command_response_on_msg_buffer( ctx: &mut CommandContext, command_type: u32, data_size: u32, ) { unsafe { let mut ipc_buf = get_msg_buffer(); let command_header = ipc_buf as *mut CommandHeader; ipc_buf = command_header.offset(1) as *mut u8; let data_word_count = data_size.div_ceil(4); let has_special_header = ctx.out_params.send_process_id || !ctx.out_params.copy_handles.is_empty() || !ctx.out_params.move_handles.is_empty(); *command_header = CommandHeader::new( command_type, 0, ctx.send_buffers.len() as u32, ctx.receive_buffers.len() as u32, ctx.exchange_buffers.len() as u32, data_word_count, 0, has_special_header, ); if has_special_header { let special_header = ipc_buf as *mut CommandSpecialHeader; ipc_buf = special_header.offset(1) as *mut u8; *special_header = CommandSpecialHeader::new( ctx.out_params.send_process_id, ctx.out_params.copy_handles.len() as u32, ctx.out_params.move_handles.len() as u32, ); if ctx.out_params.send_process_id { ipc_buf = ipc_buf.add(cmem::size_of::<u64>()); } ipc_buf = write_array_to_buffer( ipc_buf, ctx.out_params.copy_handles.len() as u32, &ctx.out_params.copy_handles, ); ipc_buf = write_array_to_buffer( ipc_buf, ctx.out_params.move_handles.len() as u32, &ctx.out_params.move_handles, ); } ipc_buf = write_array_to_buffer(ipc_buf, ctx.send_buffers.len() as u32, &ctx.send_buffers); ipc_buf = write_array_to_buffer( ipc_buf, ctx.receive_buffers.len() as u32, &ctx.receive_buffers, ); ipc_buf = write_array_to_buffer( ipc_buf, ctx.exchange_buffers.len() as u32, &ctx.exchange_buffers, ); ctx.out_params.data_words_offset = ipc_buf; } } #[inline(always)] pub fn read_request_command_from_msg_buffer(ctx: &mut CommandContext) -> Result<()> { let ipc_buf = get_msg_buffer(); let data_offset = get_aligned_data_offset(ctx.in_params.data_words_offset, ipc_buf); ctx.in_params.data_offset = data_offset; Ok(()) } #[inline(always)] pub fn write_request_command_response_on_msg_buffer( ctx: &mut CommandContext, result: ResultCode, request_type: u32, ) { unsafe { let ipc_buf = get_msg_buffer(); let data_size = cmem::size_of::<ResultCode>() as u32 + ctx.out_params.data_size; // data_size = (data_size + 1) & !1; write_command_response_on_msg_buffer(ctx, request_type, data_size); let data_offset = get_aligned_data_offset(ctx.out_params.data_words_offset, ipc_buf); let rc_ref = data_offset as *mut ResultCode; *rc_ref = result; ctx.out_params.data_offset = rc_ref.offset(1) as *mut u8; } } #[inline(always)] pub fn write_close_command_response_on_msg_buffer(ctx: &mut CommandContext) { write_command_response_on_msg_buffer(ctx, CommandType::CloseSession as u32, 0); }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/thread/scoped.rs
src/thread/scoped.rs
use super::{Builder, JoinInner, Result, Thread}; use ::alloc::sync::Arc; use core::fmt; use core::marker::PhantomData; use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; /// A scope to spawn scoped threads in. /// /// See [`scope`] for details. pub struct Scope<'scope, 'env: 'scope> { data: Arc<ScopeData>, /// Invariance over 'scope, to make sure 'scope cannot shrink, /// which is necessary for soundness. /// /// Without invariance, this would compile fine but be unsound: /// /// ```compile_fail,E0373 /// std::thread::scope(|s| { /// s.spawn(|| { /// let a = String::from("abcd"); /// s.spawn(|| println!("{a:?}")); // might run after `a` is dropped /// }); /// }); /// ``` scope: PhantomData<&'scope mut &'scope ()>, env: PhantomData<&'env mut &'env ()>, } /// An owned permission to join on a scoped thread (block on its termination). /// /// See [`Scope::spawn`] for details. pub struct ScopedJoinHandle<'scope, T>(JoinInner<'scope, T>); pub(super) struct ScopeData { num_running_threads: AtomicUsize, a_thread_panicked: AtomicBool, //main_thread: Thread, } impl ScopeData { pub(super) fn increment_num_running_threads(&self) { // We check for 'overflow' with usize::MAX / 2, to make sure there's no // chance it overflows to 0, which would result in unsoundness. if self.num_running_threads.fetch_add(1, Ordering::Relaxed) > usize::MAX / 2 { // This can only reasonably happen by mem::forget()'ing a lot of ScopedJoinHandles. self.overflow(); } } #[cold] fn overflow(&self) { self.decrement_num_running_threads(false); panic!("too many running threads in thread scope"); } pub(super) fn decrement_num_running_threads(&self, panic: bool) { if panic { self.a_thread_panicked.store(true, Ordering::Relaxed); } } } /// Create a scope for spawning scoped threads. /// /// The function passed to `scope` will be provided a [`Scope`] object, /// through which scoped threads can be [spawned][`Scope::spawn`]. /// /// Unlike non-scoped threads, scoped threads can borrow non-`'static` data, /// as the scope guarantees all threads will be joined at the end of the scope. /// /// All threads spawned within the scope that haven't been manually joined /// will be automatically joined before this function returns. /// /// # Panics /// /// If any of the automatically joined threads panicked, this function will panic. /// /// If you want to handle panics from spawned threads, /// [`join`][ScopedJoinHandle::join] them before the end of the scope. /// /// # Example /// /// ``` /// use std::thread; /// /// let mut a = vec![1, 2, 3]; /// let mut x = 0; /// /// thread::scope(|s| { /// s.spawn(|| { /// println!("hello from the first scoped thread"); /// // We can borrow `a` here. /// dbg!(&a); /// }); /// s.spawn(|| { /// println!("hello from the second scoped thread"); /// // We can even mutably borrow `x` here, /// // because no other threads are using it. /// x += a[0] + a[2]; /// }); /// println!("hello from the main thread"); /// }); /// /// // After the scope, we can modify and access our variables again: /// a.push(4); /// assert_eq!(x, a.len()); /// ``` /// /// # Lifetimes /// /// Scoped threads involve two lifetimes: `'scope` and `'env`. /// /// The `'scope` lifetime represents the lifetime of the scope itself. /// That is: the time during which new scoped threads may be spawned, /// and also the time during which they might still be running. /// Once this lifetime ends, all scoped threads are joined. /// This lifetime starts within the `scope` function, before `f` (the argument to `scope`) starts. /// It ends after `f` returns and all scoped threads have been joined, but before `scope` returns. /// /// The `'env` lifetime represents the lifetime of whatever is borrowed by the scoped threads. /// This lifetime must outlast the call to `scope`, and thus cannot be smaller than `'scope`. /// It can be as small as the call to `scope`, meaning that anything that outlives this call, /// such as local variables defined right before the scope, can be borrowed by the scoped threads. /// /// The `'env: 'scope` bound is part of the definition of the `Scope` type. #[track_caller] pub fn scope<'env, F, T>(f: F) -> T where F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T, { // We put the `ScopeData` into an `Arc` so that other threads can finish their // `decrement_num_running_threads` even after this function returns. let scope = Scope { data: Arc::new(ScopeData { num_running_threads: AtomicUsize::new(0), //main_thread: current(), a_thread_panicked: AtomicBool::new(false), }), env: PhantomData, scope: PhantomData, }; // Run `f`, the scoped function. let result = unwinding::panic::catch_unwind(core::panic::AssertUnwindSafe(|| f(&scope))); // Wait until all the threads are finished. This should always happen first try as we can only drop a thread handle when the thread has finished. // TODO: we can possibly detect panics if the num_running_threads > 0 - as this should never happen in our model. while scope.data.num_running_threads.load(Ordering::Acquire) != 0 { let _ = super::r#yield(super::YieldType::ToAnyThread); } // Throw any panic from `f`, or the return value of `f` if no thread panicked. match result { Err(e) => { unwinding::panic::begin_panic(e); unreachable!() } Ok(_) if scope.data.a_thread_panicked.load(Ordering::Relaxed) => { panic!("a scoped thread panicked") } Ok(result) => result, } } impl<'scope> Scope<'scope, '_> { /// Spawns a new thread within a scope, returning a [`ScopedJoinHandle`] for it. /// /// Unlike non-scoped threads, threads spawned with this function may /// borrow non-`'static` data from the outside the scope. See [`scope`] for /// details. /// /// The join handle provides a [`join`] method that can be used to join the spawned /// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing /// the panic payload. /// /// If the join handle is dropped, the spawned thread will implicitly joined at the /// end of the scope. In that case, if the spawned thread panics, [`scope`] will /// panic after all threads are joined. /// /// This call will create a thread using default parameters of [`Builder`]. /// If you want to specify the stack size or the name of the thread, use /// [`Builder::spawn_scoped`] instead. /// /// # Panics /// /// Panics if the OS fails to create a thread; use [`Builder::spawn_scoped`] /// to recover from such errors. /// /// [`join`]: ScopedJoinHandle::join pub fn spawn<F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T> where F: FnOnce() -> T + Send + 'scope + 'static, T: Send + 'scope + 'static, { Builder::new() .spawn_scoped(self, f) .expect("failed to spawn thread") } } impl Builder { /// Spawns a new scoped thread using the settings set through this `Builder`. /// /// Unlike [`Scope::spawn`], this method yields a [`Result`] to /// capture any failure to create the thread at the OS level. /// /// [`Result`]: crate::result::Result /// /// # Panics /// /// Panics if a thread name was set and it contained null bytes. /// /// # Example /// /// ``` /// use std::thread; /// /// let mut a = vec![1, 2, 3]; /// let mut x = 0; /// /// thread::scope(|s| { /// thread::Builder::new() /// .name("first".to_string()) /// .spawn_scoped(s, || /// { /// println!("hello from the {:?} scoped thread", thread::current().name()); /// // We can borrow `a` here. /// dbg!(&a); /// }) /// .unwrap(); /// thread::Builder::new() /// .name("second".to_string()) /// .spawn_scoped(s, || /// { /// println!("hello from the {:?} scoped thread", thread::current().name()); /// // We can even mutably borrow `x` here, /// // because no other threads are using it. /// x += a[0] + a[2]; /// }) /// .unwrap(); /// println!("hello from the main thread"); /// }); /// /// // After the scope, we can modify and access our variables again: /// a.push(4); /// assert_eq!(x, a.len()); /// ``` pub fn spawn_scoped<'scope, 'env, F, T>( self, scope: &'scope Scope<'scope, 'env>, f: F, ) -> crate::result::Result<ScopedJoinHandle<'scope, T>> where F: FnOnce() -> T + Send + 'scope + 'static, T: Send + 'scope + 'static, { Ok(ScopedJoinHandle(unsafe { self.spawn_unchecked_(f, Some(scope.data.clone())) }?)) } } impl<T> ScopedJoinHandle<'_, T> { /// Extracts a handle to the underlying thread. /// /// # Examples /// /// ``` /// use std::thread; /// /// thread::scope(|s| { /// let t = s.spawn(|| { /// println!("hello"); /// }); /// println!("thread id: {:?}", t.thread().id()); /// }); /// ``` #[must_use] pub fn thread(&self) -> &Thread { &self.0.thread } /// Waits for the associated thread to finish. /// /// This function will return immediately if the associated thread has already finished. /// /// In terms of [atomic memory orderings], the completion of the associated /// thread synchronizes with this function returning. /// In other words, all operations performed by that thread /// [happen before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) /// all operations that happen after `join` returns. /// /// If the associated thread panics, [`Err`] is returned with the panic payload. /// /// [atomic memory orderings]: core::sync::atomic /// /// # Examples /// /// ``` /// use std::thread; /// /// thread::scope(|s| { /// let t = s.spawn(|| { /// panic!("oh no"); /// }); /// assert!(t.join().is_err()); /// }); /// ``` pub fn join(mut self) -> Result<T> { self.0.join() } /// Checks if the associated thread has finished running its main function. /// /// `is_finished` supports implementing a non-blocking join operation, by checking /// `is_finished`, and calling `join` if it returns `true`. This function does not block. To /// block while waiting on the thread to finish, use [`join`][Self::join]. /// /// This might return `true` for a brief moment after the thread's main /// function has returned, but before the thread itself has stopped running. /// However, once this returns `true`, [`join`][Self::join] can be expected /// to return quickly, without blocking for any significant amount of time. pub fn is_finished(&self) -> bool { Arc::strong_count(&self.0.packet) == 1 } } impl fmt::Debug for Scope<'_, '_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Scope") .field( "num_running_threads", &self.data.num_running_threads.load(Ordering::Relaxed), ) .field( "a_thread_panicked", &self.data.a_thread_panicked.load(Ordering::Relaxed), ) //.field("main_thread", &self.data.main_thread) .finish_non_exhaustive() } } impl<T> fmt::Debug for ScopedJoinHandle<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ScopedJoinHandle").finish_non_exhaustive() } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/thread/rc.rs
src/thread/rc.rs
//! Thread-specific result definitions use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 900; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { InvalidStack: 1, InvalidState: 2, InvalidPriority: 112 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/diag/log.rs
src/diag/log.rs
//! Logging support and utils use crate::thread; use alloc::{ffi::CString, string::String}; /// Represents the logging severity pub type LogSeverity = logpacket::detail::LogSeverity; /// Represents the metadata used on a logging context pub struct LogMetadata { /// The log severity pub severity: LogSeverity, /// Whether the log is verbose pub verbosity: bool, /// The log message pub msg: String, /// The source file name pub file_name: &'static str, /// The source function name pub fn_name: &'static str, /// The source line number pub line_number: u32, } impl LogMetadata { /// Creates a new [`LogMetadata`] /// /// # Arguments /// /// * `severity`: The log severity /// * `verbosity`: Whether the log is verbose /// * `msg`: The log message /// * `file_name`: The source file name /// * `fn_name`: The source function name /// * `line_number`: The source line number #[inline] pub const fn new( severity: LogSeverity, verbosity: bool, msg: String, file_name: &'static str, fn_name: &'static str, line_number: u32, ) -> Self { Self { severity, verbosity, msg, file_name, fn_name, line_number, } } } /// Represents a logging object pub trait Logger { /// Creates a new logging object fn new() -> Self; /// Logs with the given metadata /// /// # Arguments /// /// * `metadata`: The metadata to log fn log(&mut self, metadata: &LogMetadata); } /// Wrapper for logging a single log /// /// Essentially creates a [`Logger`] and logs with it /// /// # Arguments /// /// * `metadata`: The metadata to log pub fn log_with<L: Logger>(metadata: &LogMetadata) { let mut logger = L::new(); logger.log(metadata); } fn format_plain_string_log_impl(metadata: &LogMetadata, log_type: &str) -> CString { let severity_str = match metadata.severity { LogSeverity::Trace => "Trace", LogSeverity::Info => "Info", LogSeverity::Warn => "Warn", LogSeverity::Error => "Error", LogSeverity::Fatal => "Fatal", }; let thread_name = unsafe { thread::current() .as_ref() .unwrap() .name .get_str() .unwrap_or("<unknown>") }; // SAFETY - This is find as we are only writing ascii string generated in this function, an the thread_name with is read through // a conversion from a CStr, and a log message that has been escaped of null bytes. unsafe { CString::from_vec_unchecked( format!( "[ {} (severity: {}, verbosity: {}) from {} in thread {}, at {}:{} ] {}\0", log_type, severity_str, metadata.verbosity, metadata.fn_name, thread_name, metadata.file_name, metadata.line_number, metadata.msg.replace('\0', "\\0") ) .into_bytes(), ) } } pub mod svc; #[cfg(feature = "services")] pub mod fs; #[cfg(feature = "services")] pub mod lm;
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/diag/rc.rs
src/diag/rc.rs
//! Diagnostics-related result definitions use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 400; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { AssertionFailed: 1 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/diag/abort.rs
src/diag/abort.rs
//! Aborting implementation use crate::mem::alloc; use crate::result::*; use crate::rrt0; use crate::svc; #[cfg(feature = "services")] use crate::ipc::sf; #[cfg(feature = "services")] use crate::service; #[cfg(feature = "services")] use crate::service::fatal; define_bit_set! { /// Represents a system to abort, plus optional flags they have AbortLevel (u32) { NeedsHeapAllocation = bit!(31), FatalThrow = bit!(0) | Self::NeedsHeapAllocation().get(), Panic = bit!(2) | Self::NeedsHeapAllocation().get(), ProcessExit = bit!(3), SvcBreak = bit!(4) } } impl AbortLevel { // When the desired level can't be processed (for instance, a panic due to errors allocating memory since it cannot allocate anymore) the next one is attempted, and so on // The last level, breaking via SVC, is guaranteed to work properly const LEVEL_ORDER: &'static [AbortLevel] = &[ AbortLevel::FatalThrow(), AbortLevel::Panic(), AbortLevel::ProcessExit(), AbortLevel::SvcBreak(), ]; /// Gets the next [`AbortLevel`] /// /// The abort level order is the following: `FatalThrow`, `Panic`, `ProcessExit`, `SvcBreak` #[inline] pub fn get_next_level(self) -> Option<Self> { for i in 0..Self::LEVEL_ORDER.len() { if Self::LEVEL_ORDER[i] == self { let next_i = i + 1; if next_i < Self::LEVEL_ORDER.len() { return Some(Self::LEVEL_ORDER[next_i]); } } } None } } fn do_abort(level: AbortLevel, rc: ResultCode) { if level.contains(AbortLevel::NeedsHeapAllocation()) && !alloc::is_enabled() { // Prevent abort methods which will allocate from running if we cannot allocate, to avoid infinite alloc-error recursions return; } if level == AbortLevel::FatalThrow() { #[cfg(feature = "services")] { use crate::service::fatal::{FatalService, IFatalClient}; if let Ok(fatal) = service::new_service_object::<FatalService>() { let _ = fatal.throw_fatal_with_policy( rc, fatal::FatalPolicy::ErrorScreen, sf::ProcessId::new(), ); } } } else if level == AbortLevel::Panic() { panic!("{rc:?}"); } else if level == AbortLevel::ProcessExit() { rrt0::exit(rc); } else if level == AbortLevel::SvcBreak() { let rc = rc.get_value(); let _ = unsafe { svc::r#break( svc::BreakReason::Panic, core::slice::from_raw_parts(&raw const rc as *const u8, 4), ) }; } // return so we can try the next level. } /// Attempts to abort at the specified [`AbortLevel`] /// /// Note that a certain [`AbortLevel`] may not work/be available (heap allocation is not available and that level requires allocations, etc.) /// /// Therefore, this function will try with the next levels in order if the desired one fails (see [`get_next_level`][`AbortLevel::get_next_level`]) /// /// Also note that a success [`ResultCode`] may result in UB for certain [`AbortLevel`]s /// /// This function never returns since the last possible [`AbortLevel`] is guaranteed to succeed /// /// # Arguments /// /// * `desired_level`: Desired [`AbortLevel`] /// * `rc`: [`ResultCode`] to abort with pub fn abort(desired_level: AbortLevel, rc: ResultCode) -> ! { let mut current_level = desired_level; loop { do_abort(current_level, rc); if let Some(next_level) = current_level.get_next_level() { current_level = next_level; } else { // This should never happen, since the last level is guaranteed to work unreachable!(); } } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/diag/log/fs.rs
src/diag/log/fs.rs
//! `FsAccessLog` logger implementation use super::*; use crate::ipc::sf; use crate::result::*; use crate::service; use crate::service::fsp::srv::{self, IFileSystemProxyClient}; /// Represents a logger though `FsAccessLog`s (see [`output_access_log_to_sd_card`][`srv::FileSystemProxyService::output_access_log_to_sd_card`]) pub struct FsAccessLogLogger { service: Result<srv::FileSystemProxyService>, } impl Logger for FsAccessLogLogger { fn new() -> Self { Self { service: service::new_service_object(), } } fn log(&mut self, metadata: &LogMetadata) { let msg = format_plain_string_log_impl(metadata, "FsAccessLog"); if let Ok(ref mut fspsrv) = self.service { let _ = fspsrv.output_access_log_to_sd_card(sf::Buffer::from_array(msg.as_bytes())); } } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/diag/log/svc.rs
src/diag/log/svc.rs
//! SVC-output logger implementation use super::*; use crate::svc; /// Represents a logger through [`output_debug_string`][`svc::output_debug_string`] pub struct SvcOutputLogger; impl Logger for SvcOutputLogger { fn new() -> Self { Self {} } #[allow(unused_must_use)] fn log(&mut self, metadata: &LogMetadata) { let msg = format_plain_string_log_impl(metadata, "SvcOutputLog"); unsafe { svc::output_debug_string(msg.as_c_str()) }; } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/diag/log/lm.rs
src/diag/log/lm.rs
//! `LogManager` logger implementation use alloc::string::ToString; use super::*; use crate::ipc::sf; use crate::rrt0; use crate::service; use crate::service::lm::{self, ILoggerClient, ILoggingClient, LoggingService}; use crate::svc; /// Represents a logger through [`LogService`][`lm::LoggingService`] services pub struct LmLogger { logger: Option<lm::Logger>, } impl Logger for LmLogger { fn new() -> Self { Self { logger: service::new_service_object::<LoggingService>() .map(|mut log_srv| log_srv.open_logger(sf::ProcessId::new()).ok()) .ok() .flatten(), } } fn log(&mut self, metadata: &LogMetadata) { if let Some(logger_obj) = self.logger.as_mut() { let mut log_packet = logpacket::LogPacket::new(); if let Ok(process_id) = svc::get_process_id(svc::CURRENT_PROCESS_PSEUDO_HANDLE) { log_packet.set_process_id(process_id); } let cur_thread = unsafe { thread::current().as_ref().unwrap() }; if let Ok(thread_id) = cur_thread.id() { log_packet.set_thread_id(thread_id); } log_packet.set_file_name(String::from(metadata.file_name)); log_packet.set_function_name(String::from(metadata.fn_name)); log_packet.set_line_number(metadata.line_number); let mod_name = rrt0::get_module_name() .get_name() .get_string() .unwrap_or("aarch64-switch-rs (invalid module name)".to_string()); log_packet.set_module_name(mod_name); log_packet.set_text_log(metadata.msg.clone()); let thread_name = cur_thread .name .get_str() .unwrap_or("aarch64-switch-rs (invalid thread name)"); log_packet.set_thread_name(String::from(thread_name)); for packet in log_packet.encode_packet() { let _ = logger_obj.log(sf::Buffer::from_array(&packet)); } } } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/svc/asm.rs
src/svc/asm.rs
use core::arch::naked_asm as nasm; use crate::result::ResultCode; use crate::svc::{CreateProcessInfo, DebugThreadParam, SystemInfoParam}; use crate::{arm, svc::PhysicalMemoryInfo}; use super::{ BreakReason, CodeMapOperation, DebugEvent, Handle, InfoId, LastThreadContext, LimitableResource, MemoryAttribute, MemoryInfo, MemoryPermission, PageInfo, SchedulerState, }; #[unsafe(naked)] pub unsafe extern "C" fn set_heap_size(out_address: *mut *mut u8, size: usize) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x1", "ldr x2, [sp], #16", "str x1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn set_memory_permission( address: *const u8, size: usize, value: MemoryPermission, ) -> ResultCode { nasm!("svc 0x2", "ret") } #[unsafe(naked)] pub unsafe extern "C" fn set_memory_attribute( address: *const u8, size: usize, mask: u32, value: MemoryAttribute, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x3", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn map_memory( address: *const u8, source_address: *mut u8, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x4", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn unmap_memory( address: *const u8, source_address: *mut u8, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x5", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn query_memory( out_info: *mut MemoryInfo, out_page_info: *mut PageInfo, address: *const u8, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x1, [sp, #-16]!", "svc 0x6", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn exit_process() -> ! { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x7", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_thread( handle: *mut Handle, entry: unsafe extern "C" fn(*mut u8) -> !, entry_arg: *const u8, stack_top: *const u8, priority: i32, processor_id: i32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x8", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn start_thread(handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x9", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn exit_thread() -> ! { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0xA", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn sleep_thread(timeout: i64) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0xB", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_thread_priority(out_priority: *mut i32, handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0xC", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn set_thread_priority(handle: Handle, priority: i32) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0xD", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_thread_core_mask( core_mask: *mut i32, core_affinity: *mut u64, handle: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "stp x0, x1, [sp, #-16]!", "svc 0xE", "ldp x3, x4, [sp], #16", "str w1, [x3]", "str x2, [x4]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn set_thread_core_mask( handle: Handle, preferred_core: i32, affinity_mask: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0xF", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_current_processor_number() -> u32 { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x10", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn signal_event(handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x11", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn clear_event(handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x12", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn map_shared_memory( handle: Handle, address: *const u8, size: usize, permission: MemoryPermission, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x13", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn unmap_shared_memory( handle: Handle, address: *const u8, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x14", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_transfer_memory( out_handle: *mut Handle, address: *const u8, size: usize, permissions: MemoryPermission, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x15", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn close_handle(handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x16", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn reset_signal(handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x17", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn wait_synchronization( out_index: *mut i32, handles: *const Handle, handle_count: u32, timeout: i64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x18", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn cancel_synchronization(handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x19", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn arbitrate_lock( thread_handle: Handle, tag_location: *const u8, tag: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x1A", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn arbitrate_unlock(tag_location: *const u8) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x1B", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn wait_process_wide_key_atomic( wait_location: *const u8, tag_location: *const u8, desired_tag: u32, timeout: i64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x1C", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn signal_process_wide_key( tag_location: *const u8, desired_tag: i32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x1D", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_system_tick() -> u64 { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x1E", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn connect_to_named_port( out_handle: *mut Handle, name: *const u8, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x1F", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn send_sync_request_light(handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x20", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn send_sync_request(handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x21", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn send_sync_request_with_user_data( buffer: *mut u8, size: usize, session: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x22", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn send_async_request_with_user_data( handle: *mut Handle, buffer: *mut u8, size: usize, session: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x23", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_process_id( out_process_id: *mut u64, process_handle: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x24", "ldr x2, [sp], #16", "str x1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_thread_id(out_thread_id: *mut u64, handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x25", "ldr x2, [sp], #16", "str x1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn r#break(reason: BreakReason, arg: *const u8, size: usize) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x26", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn output_debug_string(msg: *const u8, len: usize) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x27", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn return_from_exception(res: ResultCode) -> ! { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x28", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_info( out_info: *mut u64, id: InfoId, handle: Handle, sub_id: u64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x29", "ldr x2, [sp], #16", "str x1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn flush_entire_data_cache() -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x2A", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn flush_data_cache(address: *const u8, len: usize) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x2B", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn map_physical_memory(address: *const u8, len: usize) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x2C", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn unmap_physical_memory(address: *const u8, len: usize) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x2D", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_debug_future_thread_info( out_context: *mut LastThreadContext, out_thread_id: *mut u64, debug_proc_handle: Handle, ns: i64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "stp x0, x1, [sp, #-16]!", "svc 0x2E", "ldp x6, x7, [sp], #16", "stp x1, x2, [x6]", "stp x3, x4, [x6, #16]", "str x5, [x7]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_last_thread_info( out_context: *mut LastThreadContext, out_tls_address: *mut u64, out_flags: *mut u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "stp x1, x2, [sp, #-16]!", "str x0, [sp, #-16]!", "svc 0x2F", "ldr x7, [sp], #16", "stp x1, x2, [x7]", "stp x3, x4, [x7, #16]", "ldp x1, x2, [sp], #16", "str x5, [x1]", "str w6, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_resource_limit_limit_value( out_val: *mut i64, resource_limit_handle: Handle, limit_kind: LimitableResource, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x30", "ldr x2, [sp], #16", "str x1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_resource_limit_current_value( out_val: *mut i64, resource_limit_handle: Handle, limit_kind: LimitableResource, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x31", "ldr x2, [sp], #16", "str x1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn set_thread_activity( thread_handle: Handle, thread_state: SchedulerState, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x32", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_thread_context3( out_context: *mut arm::ThreadContext, thread_handle: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x32", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn wait_for_address( address: *const u8, arbitration_type: u32, value: u32, timeout: i64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x34", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn signal_to_address( address: *const u8, signal: u32, value: u32, signal_count: i32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x35", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn synchronize_preemption_states() -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x36", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_resource_limit_peak_value( out_value: *mut i64, resource_limit_handle: Handle, limit_kind: LimitableResource, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x37", "ldr x2, [sp], #16", "str x1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_io_pool(pool_type: u32) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x39", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_io_region( io_region_handle: *mut Handle, io_pool_handle: Handle, physical_addres: *mut u8, size: usize, permissions: MemoryPermission, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x3A", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn kernel_debug( debug_type: u32, debug_arg0: u64, debug_arg1: u64, debug_arg2: u64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x3C", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn change_kernel_trace_state(tracing_state: u32) { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x3D", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_session( out_server_handle: *mut Handle, out_client_handle: *mut Handle, is_light: bool, unk_name: u64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "stp x0, x1, [sp, #-16]!", "svc 0x40", "ldp x3, x4, [sp], #16", "str w1, [x3]", "str w2, [x4]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn accept_session( out_session_handle: *mut Handle, handle: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x41", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn reply_and_receive_light(handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x42", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn reply_and_receive( out_index: *mut i32, handles: *const Handle, handle_count: u32, reply_target: Handle, timeout: i64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x43", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn reply_and_receive_with_user_buffer( out_index: *mut i32, user_buffer: *mut u8, buffer_size: usize, handles: *const Handle, handle_count: u32, reply_target: Handle, timeout: i64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x44", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_event( out_server_handle: *mut Handle, out_client_handle: *mut Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "stp x0, x1, [sp, #-16]!", "svc 0x45", "ldp x3, x4, [sp], #16", "str w1, [x3]", "str w2, [x4]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn map_io_region( io_region_handle: Handle, address: *mut u8, size: usize, permissions: MemoryPermission, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x46", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn unmap_io_region( io_region_handle: Handle, address: *mut u8, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x47", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn map_physical_memory_unsafe(address: *mut u8, size: usize) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x48", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn unmap_physical_memory_unsafe(address: *mut u8, size: usize) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x49", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn set_unsafe_limit(size: usize) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x4A", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_code_memory( code_memory_handle: *mut Handle, source_address: *mut u8, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x4B", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn control_code_memory( code_memory_handle: Handle, operation_type: CodeMapOperation, destination_address: *mut u8, size: usize, permission: MemoryPermission, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x4C", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn sleep_system() -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x4D", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn read_write_register( mmio_val: u32, register_addres: usize, read_write_mask: u32, in_val: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x4E", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn set_process_activity( process: Handle, paused: SchedulerState, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x4F", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_shared_memory( shmem_handle: *mut Handle, size: usize, local_permission: MemoryPermission, other_permission: MemoryPermission, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x50", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn map_transfer_memory( tmem_handle: Handle, address: *mut u8, size: usize, permissions: MemoryPermission, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x51", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn unmap_transfer_memory( tmem_handle: Handle, address: *mut u8, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x52", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_interrupt_event( int_handle: *mut Handle, irq_number: u64, flags: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x53", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn query_physical_address( mem_info: PhysicalMemoryInfo, virtual_address: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x54", "ldr x4, [sp], #16", "stp x1, x2, [x4]", "str x3, [x4, #16]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn query_io_mapping( virtual_address: *mut usize, virtual_size: *mut usize, physical_address: usize, physical_size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "stp x0, x1, [sp, #-16]!", "svc 0x55", "ldp x3, x4, [sp], #16", "str x1, [x3]", "str x2, [x4]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn legacy_query_io_mapping( virtual_address: *mut usize, physical_address: usize, physical_size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x55", "ldr x2, [sp], #16", "str x1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn create_device_address_space( device_handle: *mut Handle, device_address: usize, device_mem_size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x56", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn attach_device_address_space( device: usize, device_handle: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x57", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn detach_device_address_space( device: usize, device_handle: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x58", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn map_device_address_space_by_force( handle: Handle, process_handle: Handle, map_addresss: usize, device_mem_size: usize, device_address: usize, options: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x59", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn map_device_address_space_aligned( handle: Handle, process_handle: Handle, map_addresss: usize, device_mem_size: usize, device_address: usize, options: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x5A", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn map_device_address_space( mapped_address_size: *mut usize, handle: Handle, process_handle: Handle, map_addresss: usize, device_mem_size: usize, device_address: usize, options: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x5B", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn unmap_device_address_space( handle: Handle, process_handle: Handle, map_addresss: usize, device_mem_size: usize, device_address: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x5C", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn invalidate_process_data_cache( proc_handle: Handle, address: *const u8, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x5D", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn store_process_data_cache( proc_handle: Handle, address: *const u8, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x5E", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn flush_process_data_cache( proc_handle: Handle, address: *const u8, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x5F", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn debug_active_process( out_handle: *mut Handle, process_id: u64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x60", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn break_debug_process(debug_handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x61", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn terminate_debug_process(debug_handle: Handle) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x62", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_debug_event( out_debug_event: *mut DebugEvent, debug_handle: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x63", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn continue_debug_event( debug_handle: Handle, flags: u32, thread_ids: *const u64, thread_id_count: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x64", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_process_list( out_count: *mut u32, out_process_ids: *mut u64, process_id_count: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x65", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_thread_list( out_count: *mut u32, out_thread_ids: *mut u64, thread_id_count: u32, debug_handle: Handle, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x0, [sp, #-16]!", "svc 0x66", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn get_debug_thread_context( thread_context: *mut arm::ThreadContext, // *mut arm::ThreadContext debug_handle: Handle, thread_id: u64, register_group: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x67", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn set_debug_thread_context( debug_handle: Handle, thread_id: u64, thread_context: *const arm::ThreadContext, register_group: u32, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x68", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn query_debug_process_memory( out_info: *mut MemoryInfo, out_page_info: *mut PageInfo, debug_handle: Handle, address: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "str x1, [sp, #-16]!", "svc 0x69", "ldr x2, [sp], #16", "str w1, [x2]", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn read_debug_process_memory( buffer: *mut u8, debug_handle: Handle, address: usize, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x6A", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn write_debug_process_memory( debug_handle: Handle, buffer: *const u8, address: usize, size: usize, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x6B", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)] pub unsafe extern "C" fn set_hardware_break_point( which: u32, flags: u64, value: u64, ) -> ResultCode { nasm!( maybe_cfi!(".cfi_startproc"), "svc 0x6C", "ret", maybe_cfi!(".cfi_endproc") ); } #[unsafe(naked)]
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
true
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/svc/rc.rs
src/svc/rc.rs
//! Official SVC-related result definitions pub const RESULT_MODULE: u32 = 1; result_define_group!(RESULT_MODULE => { InvalidSize: 101, InvalidAddress: 102, InvalidCurrentMemory: 106, InvalidHandle: 114, TimedOut: 117, Cancelled: 118, SessionClosed: 123, NotHandled: 124, Debug: 128 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/input/rc.rs
src/input/rc.rs
//! Input-related result definitions use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 800; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { InvalidControllerId: 1, InvalidTouchIndex: 2 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/elf/mod0.rs
src/elf/mod0.rs
//! MOD0 format utils /// Represents the `MOD0` start layout, which are the first 8 bytes of the binary in memory. /// These are usually right before the actual header in official binaries, but they don't have /// to be and we store it (the actual header) in `.rodata`. #[derive(Copy, Clone)] #[repr(C)] pub struct ModuleStart { /// Reserved pub reserved: u32, /// The magic offset pub magic_offset: u32, } /// Represents the `MOD0` header structure. /// Although we know from the official linker script that all the offsets will be positive, /// the offsets have been made signed so that consumers can bring their own linker scripts /// (e.g. emuiibo) and we won't break functionality if they reorder sections. /// /// All members have been made private as this should only ever be instantiated using /// [`Header::from_text_start_addr`], with data populated by the linker. #[derive(Copy, Clone)] #[repr(C)] pub struct Header { /// The magic, whose expected value is [`MAGIC`][`Header::MAGIC`] magic: u32, /// The dynamic offset dynamic: i32, /// The BSS start offset bss_start: i32, /// The BSS end offset bss_end: i32, /// The eh_frame_hdr start offset eh_frame_hdr_start: i32, /// The eh_frame_hdr end offset eh_frame_hdr_end: i32, /// The offset to runtime-generated module object module_object: i32, } impl Header { /// The header magic value (`MOD0`) pub const MAGIC: u32 = u32::from_le_bytes(*b"MOD0"); /// Gets the header embedded at the slot `.text.jmp+4`. /// Since this is a hard requirement of the switch runtime, /// an invalid MOD0 header offset or invalid header magic value panics. /// Panics if the `text_base` pointer is invalid, the derived `MOD0` /// pointer is invalid, or if the derived `MOD0` header magic value is incorrect. /// /// # Arguments: /// /// * `text_base`: The start of the `.text.jmp` section. #[inline] #[allow(clippy::not_unsafe_ptr_arg_deref)] // We are checking the validity of the pointer, so this is handled by pub fn from_text_start_addr(text_base: *mut u8) -> &'static mut Self { let mod0_ref = unsafe { let module_start = (text_base as *const ModuleStart) .as_ref() .expect("Invalid base `.text` pointer. Address is null or improperly aligned"); // Get the MOD0 offset that is written at the slot `.text.jmp+4` let mod0_offset = module_start.magic_offset as usize; // The mod0_ptr is written into `.rodata`, at the offset `mod0_offset` from the start of `.test.jmp` let mod0_ptr = text_base.add(mod0_offset) as *mut Header; mod0_ptr.as_mut().expect( "Failed to get reference to MOD0 header. Address is null or improperly aligned.", ) }; assert!(mod0_ref.magic == Header::MAGIC, "Invalid MOD0 magic value."); mod0_ref } /// Gets the start address for the `.dynamic` section pub fn get_dyn_start(&self) -> *const super::Dyn { // This could cause panics on access if the pointer is incorrectly aligned but that is not a // UB issue here - unaligned raw pointers are allowed. unsafe { (self as *const Self as *const u8).offset(self.dynamic as isize) as *const super::Dyn } } /// Gets the start address for the `eh_frame_hdr` section. /// /// # Safety /// /// The reference `&self` must be the copy in `.rodata` created by the linker. #[inline] pub fn get_eh_frame_header_start(&self) -> *const u8 { // SAFETY: Safe as we are just computing a new pointer, not dereferencing. unsafe { (self as *const Self as *const u8).offset(self.eh_frame_hdr_start as isize) } } /// Zeroes the bss section from a base code address. We have to take an `&mut self` here as computing. /// /// # Safety /// /// The reference `&mut self` must be the copy in `.rodata` created by the linker. Additionally, /// The reference to self should have been created using a mutable pointer, to prevent a shared->mut conversion /// which would be immediate UB (as documented in the struct docstring). #[inline] pub unsafe fn zero_bss_section(&mut self) { use zeroize::Zeroize; debug_assert!( self.bss_end >= self.bss_start, "Invalid offset range for BSS region. End address is before start address." ); unsafe { let module_addr = (&raw mut *self).cast::<u8>(); let bss_start = module_addr.offset(self.bss_start as isize); let bss_len = (self.bss_end - self.bss_start) as usize; // Use the zeroize library to get bss zeroing with the guarantee that it won'get get elided. core::slice::from_raw_parts_mut(bss_start, bss_len).zeroize(); } // With a SeqCst fence, we ensure that the bss section is zeroed before we return. // The call to this function now can not be reordered either. core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/elf/rc.rs
src/elf/rc.rs
//! ELF-related result definitions use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 100; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { RelaSizeMismatch: 1, InvalidModuleMagic: 2, DuplicatedDtEntry: 3, MissingDtEntry: 4 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/mem/alloc.rs
src/mem/alloc.rs
//! Allocator implementation and definitions use crate::result::*; use crate::svc; use crate::util::PointerAndSize; use core::mem; use core::mem::ManuallyDrop; use core::ops::Index; use core::ops::IndexMut; use core::ptr; use core::ptr::NonNull; use ::alloc::alloc::{AllocError, Allocator, Global, Layout}; pub const PAGE_ALIGNMENT: usize = 0x1000; pub mod rc; impl From<AllocError> for ResultCode { fn from(_value: AllocError) -> Self { ResultCode::new(rc::ResultOutOfMemory::get_value()) } } #[linkage = "weak"] #[unsafe(export_name = "__nx_mem_alloc_default_heap_size")] pub static DEFAULT_HEAP_SIZE: usize = 0; /// Default implementation #[linkage = "weak"] #[unsafe(export_name = "__nx_mem_alloc_configure_heap")] pub fn configure_heap(heap_override: PointerAndSize) -> PointerAndSize { if heap_override.is_valid() { heap_override } else { let heap_size = match heap_override.size { 0 => { let mem_available = svc::get_info( svc::InfoId::TotalMemorySize, svc::CURRENT_PROCESS_PSEUDO_HANDLE, 0, ) .unwrap(); let mem_used = svc::get_info( svc::InfoId::UsedMemorySize, svc::CURRENT_PROCESS_PSEUDO_HANDLE, 0, ) .unwrap(); if mem_available > mem_used + 0x200000 { ((mem_available - mem_used - 0x200000) & !0x1FFFFF) as usize } else { (0x2000000 * 16) as usize } } non_zero => non_zero, }; let heap_addr = svc::set_heap_size(heap_size).unwrap(); debug_assert!( !heap_addr.is_null(), "Received null heap address after requesting from the kernel" ); let (heap_metadata, _) = svc::query_memory(heap_addr).unwrap(); if !heap_metadata .permission .contains(svc::MemoryPermission::Read() | svc::MemoryPermission::Write()) { unsafe { svc::set_memory_permission( heap_addr, heap_size, svc::MemoryPermission::Read() | svc::MemoryPermission::Write(), ) .unwrap(); } } PointerAndSize::new(heap_addr, heap_size) } } // TODO: be able to change the global allocator? /// Represents a heap allocator for this library /// # Safety /// /// As with the regular Allocator trait, the `delete` function can only be called on pointers produced by the same implementation's `new` pub unsafe trait AllocatorEx: Allocator { /// Allocates a new heap value #[allow(clippy::new_ret_no_self)] #[allow(clippy::wrong_self_convention)] fn new<T>(&self) -> Result<NonNull<T>> { let layout = Layout::new::<T>(); match self.allocate(layout) { Ok(allocation) => Ok(allocation.cast()), Err(_) => rc::ResultOutOfMemory::make_err(), } } /// Releases a heap value /// /// The value must have been created using [`AllocatorEx::new`] /// /// # Arguments /// /// * `t`: Heap value address fn delete<T>(&self, t: *mut T) { let layout = Layout::new::<T>(); unsafe { self.deallocate(NonNull::new_unchecked(t.cast()), layout) }; } } unsafe impl AllocatorEx for Global {} #[global_allocator] static GLOBAL_ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty(); /// Initializes the global allocator with the given address and size. /// Returns a bool to indicate if the memory was consumed by the allocator /// /// # Arguments /// /// * `heap`: The heap address and size pub fn initialize(heap: PointerAndSize) -> bool { unsafe { GLOBAL_ALLOCATOR.lock().init(heap.address, heap.size) }; false } /// Gets whether heap allocations are enabled /// /// The library may internally disable them in exceptional cases: for instance, to avoid exception handlers to allocate heap memory if the exception cause is actually an OOM situation pub fn is_enabled() -> bool { let alloc_guard = GLOBAL_ALLOCATOR.lock(); alloc_guard.size() != 0 } /// Represents a wrapped and manually managed heap value /// /// Note that a [`Buffer`] is able to hold both a single value or an array of values of the provided type pub struct Buffer<T, A: Allocator = Global> { /// The actual heap value pub(crate) ptr: *mut T, /// The memory's layout pub(crate) layout: Layout, /// The allocator used to request the buffer pub(crate) allocator: A, } impl<T> Buffer<T> { /// Creates a new [`Buffer`] using the global allocator /// /// # Arguments /// /// * `align`: The align to use /// * `count`: The count of values to allocate pub fn new(align: usize, count: usize) -> Result<Self> { let layout = Layout::from_size_align(count * mem::size_of::<T>(), align) .map_err(|_| ResultCode::new(rc::ResultLayoutError::get_value()))?; let allocator = Global; let ptr = allocator.allocate(layout)?.as_ptr().cast(); Ok(Self { ptr, layout, allocator, }) } /// Creates a new, invalid [`Buffer`] #[inline] pub const fn empty() -> Self { Self { ptr: ptr::null_mut(), layout: Layout::new::<u8>(), // Dummy value allocator: Global, } } } impl<T, A: Allocator> Buffer<T, A> { /// Creates a new [`Buffer`] using a given allocator /// /// # Arguments /// /// * `align`: The align to use /// * `count`: The count of values to allocate /// * `allocator`: The allocator to use pub fn new_in(align: usize, count: usize, allocator: A) -> Result<Self> { let layout = Layout::from_size_align(count * mem::size_of::<T>(), align) .map_err(|_| ResultCode::new(rc::ResultLayoutError::get_value()))?; let ptr = allocator.allocate(layout)?.as_ptr().cast(); Ok(Self { ptr, layout, allocator, }) } /// Gets whether this [`Buffer`] is valid #[inline] pub fn is_valid(&self) -> bool { !self.ptr.is_null() } pub fn into_raw(value: Self) -> *mut [T] { let no_drop = ManuallyDrop::new(value); core::ptr::slice_from_raw_parts_mut( no_drop.ptr, no_drop.layout.size() / mem::size_of::<T>(), ) } /// Releases the [`Buffer`] /// /// The [`Buffer`] becomes invalid after this /// /// # Safety /// /// The buffer must never be read after this, as the internal buffer pointer is wiped. The buffer must also be for pub unsafe fn release(&mut self) { if self.is_valid() { unsafe { self.allocator .deallocate(NonNull::new_unchecked(self.ptr.cast()), self.layout); } self.ptr = core::ptr::null_mut(); } } } impl<T> Index<usize> for Buffer<T> { type Output = T; fn index(&self, index: usize) -> &Self::Output { assert!(self.is_valid(), "Indexing into invalid buffer"); assert!( index <= (self.layout.size() / size_of::<T>()), "Index out of bounds." ); // SAFETY - we check that this pointer is valid via the two asserts above unsafe { self.ptr.add(index).as_ref().unwrap_unchecked() } } } impl<T> IndexMut<usize> for Buffer<T> { fn index_mut(&mut self, index: usize) -> &mut T { assert!(self.is_valid(), "Indexing into invalid buffer"); assert!( index <= (self.layout.size() / size_of::<T>()), "Index out of bounds." ); // SAFETY - we check that this pointer is valid via the two asserts above unsafe { self.ptr.add(index).as_mut().unwrap_unchecked() } } } impl<T, A: Allocator> Drop for Buffer<T, A> { fn drop(&mut self) { if self.is_valid() { unsafe { self.allocator .deallocate(NonNull::new_unchecked(self.ptr.cast()), self.layout); } } } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/mem/alloc/rc.rs
src/mem/alloc/rc.rs
//! Allocation-specific result definitions use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 1000; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { OutOfMemory: 1, LayoutError: 2 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/fs/nca.rs
src/fs/nca.rs
// TODO: NCA filesystem/file/dir
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/fs/pfs0.rs
src/fs/pfs0.rs
// TODO: PFS0 filesystem/file/dir
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/fs/subdir.rs
src/fs/subdir.rs
//! Helper object types for treating FS subdirectories as IPC filesystems use crate::fs; use crate::result::*; use alloc::string::ToString; use alloc::{boxed::Box, string::String}; // TODO: subdir FS object, non-IPC version? /// Represents an [`FileSystem`][`fs::FileSystem`] object wrapping around a FS subdirectory path pub struct SubDir<FS: fs::FileSystem> { fs: FS, base: String, } impl<FS: fs::FileSystem> SubDir<FS> { /// Creates a new [`SubDir`] from a [`FileSystem`][`fs::FileSystem`] instance. /// /// # Arguments /// /// * `sub_dir`: The subdirectory path to wrap #[inline] pub fn new(fs: FS, dir: impl AsRef<str>) -> Result<Self> { Ok(Self { fs, base: dir.as_ref().to_string(), }) } fn make_path(&self, path: &str) -> String { let mut out = self.base.clone(); out.push_str(path); out } } impl<FS: fs::FileSystem> fs::FileSystem for SubDir<FS> { fn commit(&self) -> Result<()> { self.fs.commit() } fn create_directory(&self, path: &str) -> Result<()> { self.fs.create_directory(self.make_path(path).as_str()) } fn create_file(&self, path: &str, attribute: fs::FileAttribute, size: usize) -> Result<()> { self.fs .create_file(self.make_path(path).as_str(), attribute, size) } fn get_entry_type(&self, path: &str) -> Result<fs::DirectoryEntryType> { self.fs.get_entry_type(self.make_path(path).as_str()) } fn get_file_time_stamp_raw(&self, path: &str) -> Result<fs::FileTimeStampRaw> { self.fs .get_file_time_stamp_raw(self.make_path(path).as_str()) } fn get_free_space_size(&self, path: &str) -> Result<usize> { // we don't need to make a new path here, as the path is guaranteed to be in the same volume self.fs.get_free_space_size(path) } fn get_total_space_size(&self, path: &str) -> Result<usize> { // we don't need to make a new path here, as the path is guaranteed to be in the same volume self.fs.get_total_space_size(path) } fn open_directory( &self, path: &str, mode: fs::DirectoryOpenMode, ) -> Result<Box<dyn fs::Directory>> { self.fs.open_directory(self.make_path(path).as_str(), mode) } fn open_file(&self, path: &str, mode: fs::FileOpenMode) -> Result<Box<dyn super::File>> { self.fs.open_file(self.make_path(path).as_str(), mode) } fn query_entry( &self, path: &str, query_id: fs::QueryId, in_buf: &[u8], out_buf: &mut [u8], ) -> Result<()> { self.fs .query_entry(self.make_path(path).as_str(), query_id, in_buf, out_buf) } fn remove_children_all(&self, path: &str) -> Result<()> { self.fs.remove_children_all(self.make_path(path).as_str()) } fn remove_dir(&self, path: &str) -> Result<()> { self.fs.remove_dir(self.make_path(path).as_str()) } fn remove_dir_all(&self, path: &str) -> Result<()> { self.fs.remove_dir_all(self.make_path(path).as_str()) } fn remove_file(&self, path: &str) -> Result<()> { self.fs.remove_file(self.make_path(path).as_str()) } fn rename_directory(&self, old_path: &str, new_path: &str) -> Result<()> { self.fs.rename_directory( self.make_path(old_path).as_str(), self.make_path(new_path).as_str(), ) } fn rename_file(&self, old_path: &str, new_path: &str) -> Result<()> { self.fs.rename_file( self.make_path(old_path).as_str(), self.make_path(new_path).as_str(), ) } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/fs/rc.rs
src/fs/rc.rs
//! FS-related result definitions use crate::rc; /// Result Submodule ID for the parent module pub const RESULT_SUBMODULE: u32 = 700; result_define_subgroup!(rc::RESULT_MODULE, RESULT_SUBMODULE => { DeviceNotFound: 1, InvalidPath: 2, NotInSameFileSystem: 3 });
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/sync/sys.rs
src/sync/sys.rs
//use core::arch::asm; use crate::thread; pub mod futex; pub mod mutex; pub mod rwlock; #[inline(always)] fn get_current_thread_handle() -> u32 { unsafe { (*thread::get_thread_local_region()).nx_thread_vars.handle } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/sync/sys/rwlock.rs
src/sync/sys/rwlock.rs
use core::sync::atomic::Ordering::*; use super::futex::Futex; // We're just going to steal the Rust stdlib implementation since it's a compatible license (MIT-apache dual license). pub struct RwLock { state: Futex, writer_notifier: Futex, } const READ_LOCKED: u32 = 1; const MASK: u32 = (1 << 30) - 1; const WRITE_LOCKED: u32 = MASK; const DOWNGRADE: u32 = READ_LOCKED.wrapping_sub(WRITE_LOCKED); // READ_LOCKED - WRITE_LOCKED const MAX_READERS: u32 = MASK - 1; const READERS_WAITING: u32 = 1 << 30; const WRITERS_WAITING: u32 = 1 << 31; #[inline] fn is_unlocked(state: u32) -> bool { state & MASK == 0 } #[inline] fn is_write_locked(state: u32) -> bool { state & MASK == WRITE_LOCKED } #[inline] fn has_readers_waiting(state: u32) -> bool { state & READERS_WAITING != 0 } #[inline] fn has_writers_waiting(state: u32) -> bool { state & WRITERS_WAITING != 0 } impl RwLock { pub const fn new() -> Self { Self { state: Futex::new(), writer_notifier: Futex::new(), } } #[inline] pub fn try_read(&self) -> bool { self.state .0 .fetch_update(Acquire, Relaxed, |s| { is_read_lockable(s).then(|| s + READ_LOCKED) }) .is_ok() } #[inline] pub fn read(&self) { let state = self.state.0.load(Relaxed); if !is_read_lockable(state) || self .state .0 .compare_exchange_weak(state, state + READ_LOCKED, Acquire, Relaxed) .is_err() { self.read_contended(); } } /// # Safety /// /// The `RwLock` must be read-locked (N readers) in order to call this. #[inline] pub unsafe fn read_unlock(&self) { let state = self.state.0.fetch_sub(READ_LOCKED, Release) - READ_LOCKED; // It's impossible for a reader to be waiting on a read-locked RwLock, // except if there is also a writer waiting. debug_assert!(!has_readers_waiting(state) || has_writers_waiting(state)); // Wake up a writer if we were the last reader and there's a writer waiting. if is_unlocked(state) && has_writers_waiting(state) { self.wake_writer_or_readers(state); } } #[cold] fn read_contended(&self) { let mut has_slept = false; let mut state = self.state.0.load(Relaxed); loop { // If we have just been woken up, first check for a `downgrade` call. // Otherwise, if we can read-lock it, lock it. if (has_slept && is_read_lockable_after_wakeup(state)) || is_read_lockable(state) { match self.state.0.compare_exchange_weak( state, state + READ_LOCKED, Acquire, Relaxed, ) { Ok(_) => return, // Locked! Err(s) => { state = s; continue; } } } // Check for overflow. assert!( !has_reached_max_readers(state), "too many active read locks on RwLock" ); // Make sure the readers waiting bit is set before we go to sleep. if !has_readers_waiting(state) && let Err(s) = self.state .0 .compare_exchange(state, state | READERS_WAITING, Relaxed, Relaxed) { state = s; continue; } // Wait for the state to change. self.state.wait(state | READERS_WAITING, -1); has_slept = true; // Read again after waking up. state = self.state.0.load(Relaxed); } } fn wake_writer(&self) { self.writer_notifier.0.fetch_add(1, Release); self.writer_notifier.signal_one() } #[inline] pub fn try_write(&self) -> bool { self.state .0 .fetch_update(Acquire, Relaxed, |s| { is_unlocked(s).then(|| s + WRITE_LOCKED) }) .is_ok() } #[inline] pub fn write(&self) { if self .state .0 .compare_exchange_weak(0, WRITE_LOCKED, Acquire, Relaxed) .is_err() { self.write_contended(); } } /// # Safety /// /// The `RwLock` must be write-locked (single writer) in order to call this. #[inline] pub unsafe fn write_unlock(&self) { let state = self.state.0.fetch_sub(WRITE_LOCKED, Release) - WRITE_LOCKED; debug_assert!(is_unlocked(state)); if has_writers_waiting(state) || has_readers_waiting(state) { self.wake_writer_or_readers(state); } } /// # Safety /// /// The `RwLock` must be write-locked (single writer) in order to call this. #[inline] pub unsafe fn downgrade(&self) { // Removes all write bits and adds a single read bit. let state = self.state.0.fetch_add(DOWNGRADE, Release); debug_assert!( is_write_locked(state), "RwLock must be write locked to call `downgrade`" ); if has_readers_waiting(state) { // Since we had the exclusive lock, nobody else can unset this bit. self.state.0.fetch_sub(READERS_WAITING, Relaxed); self.state.signal_all(); } } #[cold] fn write_contended(&self) { let mut state = self.state.0.load(Relaxed); let mut other_writers_waiting = 0; loop { // If it's unlocked, we try to lock it. if is_unlocked(state) { match self.state.0.compare_exchange_weak( state, state | WRITE_LOCKED | other_writers_waiting, Acquire, Relaxed, ) { Ok(_) => return, // Locked! Err(s) => { state = s; continue; } } } // Set the waiting bit indicating that we're waiting on it. if !has_writers_waiting(state) && let Err(s) = self.state .0 .compare_exchange(state, state | WRITERS_WAITING, Relaxed, Relaxed) { state = s; continue; } // Other writers might be waiting now too, so we should make sure // we keep that bit on once we manage lock it. other_writers_waiting = WRITERS_WAITING; // Examine the notification counter before we check if `state` has changed, // to make sure we don't miss any notifications. let seq = self.writer_notifier.0.load(Acquire); // Don't go to sleep if the lock has become available, // or if the writers waiting bit is no longer set. state = self.state.0.load(Relaxed); if is_unlocked(state) || !has_writers_waiting(state) { continue; } // Wait for the state to change. self.writer_notifier.wait(seq, -1); // Read again after waking up. state = self.state.0.load(Relaxed); } } /// Wakes up waiting threads after unlocking. /// /// If both are waiting, this will wake up only one writer, but will fall /// back to waking up readers if there was no writer to wake up. #[cold] fn wake_writer_or_readers(&self, mut state: u32) { assert!(is_unlocked(state)); // The readers waiting bit might be turned on at any point now, // since readers will block when there's anything waiting. // Writers will just lock the lock though, regardless of the waiting bits, // so we don't have to worry about the writer waiting bit. // // If the lock gets locked in the meantime, we don't have to do // anything, because then the thread that locked the lock will take // care of waking up waiters when it unlocks. // If only writers are waiting, wake one of them up. if state == WRITERS_WAITING { match self.state.0.compare_exchange(state, 0, Relaxed, Relaxed) { Ok(_) => { self.wake_writer(); return; } Err(s) => { // Maybe some readers are now waiting too. So, continue to the next `if`. state = s; } } } // If both writers and readers are waiting, leave the readers waiting // and only wake up one writer. if state == READERS_WAITING + WRITERS_WAITING { if self .state .0 .compare_exchange(state, READERS_WAITING, Relaxed, Relaxed) .is_err() { // The lock got locked. Not our problem anymore. return; } self.wake_writer(); // No writers were actually blocked on futex_wait, so we continue // to wake up readers instead, since we can't be sure if we notified a writer. state = READERS_WAITING; } // If readers are waiting, wake them all up. if state == READERS_WAITING && self .state .0 .compare_exchange(state, 0, Relaxed, Relaxed) .is_ok() { self.state.signal_all(); } } } #[inline] fn is_read_lockable(state: u32) -> bool { // This also returns false if the counter could overflow if we tried to read lock it. // // We don't allow read-locking if there's readers waiting, even if the lock is unlocked // and there's no writers waiting. The only situation when this happens is after unlocking, // at which point the unlocking thread might be waking up writers, which have priority over readers. // The unlocking thread will clear the readers waiting bit and wake up readers, if necessary. state & MASK < MAX_READERS && !has_readers_waiting(state) && !has_writers_waiting(state) } #[inline] fn is_read_lockable_after_wakeup(state: u32) -> bool { // We make a special case for checking if we can read-lock _after_ a reader thread that went to // sleep has been woken up by a call to `downgrade`. // // `downgrade` will wake up all readers and place the lock in read mode. Thus, there should be // no readers waiting and the lock should be read-locked (not write-locked or unlocked). // // Note that we do not check if any writers are waiting. This is because a call to `downgrade` // implies that the caller wants other readers to read the value protected by the lock. If we // did not allow readers to acquire the lock before writers after a `downgrade`, then only the // original writer would be able to read the value, thus defeating the purpose of `downgrade`. state & MASK < MAX_READERS && !has_readers_waiting(state) && !is_write_locked(state) && !is_unlocked(state) } #[inline] fn has_reached_max_readers(state: u32) -> bool { state & MASK == MAX_READERS } impl Default for RwLock { fn default() -> Self { Self::new() } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/sync/sys/futex.rs
src/sync/sys/futex.rs
use core::{ ptr, sync::atomic::{AtomicU32, Ordering}, }; use crate::{ result::ResultBase, svc::{self, rc::ResultTimedOut}, }; #[repr(transparent)] pub struct Futex(pub(super) AtomicU32); impl Futex { pub const fn new() -> Self { Self(AtomicU32::new(0)) } pub fn wait(&self, expected: u32, timeout: i64) -> bool { // No need to wait if the value already changed. if self.0.load(Ordering::Relaxed) != expected { return true; } match unsafe { svc::wait_for_address( ptr::from_ref(self).cast(), svc::ArbitrationType::WaitIfEqual, expected, timeout, ) } { Ok(_) => true, Err(rc) if ResultTimedOut::matches(rc) => false, Err(rc) => { panic!( "Error waiting for valid pointer at {:#X}, err : {}-{}", ptr::from_ref(self).addr(), rc.get_module(), rc.get_value() ); } } } #[inline(always)] pub fn signal_one(&self) { self.signal_n(1); } #[inline(always)] pub fn signal_all(&self) { self.signal_n(-1); } pub fn signal_n(&self, count: i32) { if let Err(rc) = unsafe { svc::signal_to_address( ptr::from_ref(self).cast(), svc::SignalType::Signal, 0, count, ) } { panic!( "Error signaling for valid pointer at {:#X}, err : {}-{}", ptr::from_ref(self).addr(), rc.get_module(), rc.get_value() ) } } } impl Default for Futex { fn default() -> Self { Self::new() } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/src/sync/sys/mutex.rs
src/sync/sys/mutex.rs
use core::sync::atomic::AtomicU32; use core::sync::atomic::Ordering::*; //use super::*; use crate::diag::abort; use crate::svc; use super::get_current_thread_handle; const WAIT_MASK: u32 = 0x40_00_00_00; pub struct Mutex { owner_thread_handle: AtomicU32, } impl Mutex { #[inline] pub const fn new() -> Self { Self { owner_thread_handle: AtomicU32::new(svc::INVALID_HANDLE), } } #[inline] pub fn is_locked(&self) -> bool { (self.owner_thread_handle.load(Relaxed) & !WAIT_MASK) != svc::INVALID_HANDLE } #[inline] pub fn try_lock(&self) -> bool { self.owner_thread_handle .compare_exchange( svc::INVALID_HANDLE, get_current_thread_handle(), Acquire, Relaxed, ) .is_ok() } #[inline] pub fn lock(&self) { let current_thread = get_current_thread_handle(); let _current_val = self.owner_thread_handle.load(Relaxed); if let Err(state) = self.owner_thread_handle.compare_exchange( svc::INVALID_HANDLE, current_thread, Acquire, Relaxed, ) { self.lock_contended(state, current_thread); } } #[cold] fn lock_contended(&self, mut state: u32, current_thread: u32) { loop { // If the state isn't marked as contended yet, mark it if state & WAIT_MASK == 0 { // check if we have just caught an unlocked mutex while setting the wait flag // this should only happen when an uncontended mutex unlocks, so we can just try to // lock without worrying about the kernel giving it to a waiter if self.owner_thread_handle.fetch_or(WAIT_MASK, Acquire) == svc::INVALID_HANDLE { // we have found an unlocked mutex by chance, try to lock it match self.owner_thread_handle.compare_exchange( svc::INVALID_HANDLE | WAIT_MASK, current_thread, Acquire, Relaxed, ) { Ok(_) => { // we locked by replacing our written wait mask with the new handle value return; } Err(s) => { state = s; } } } // we didn't luck into a lock, and the value is not flagged for aribitration. // we can wait for the kernel to hand us the value if let Err(rc) = unsafe { svc::arbitrate_lock( state & !WAIT_MASK, &self.owner_thread_handle as *const _ as _, current_thread, ) } { abort::abort(abort::AbortLevel::Panic(), rc); } // we should have the value here, but libnx and nnSdk check state = self.owner_thread_handle.load(Acquire); if state & !WAIT_MASK == current_thread { return; } } } } /// # Safety /// /// This can only be called on a mutex that has been locked by the owner/borrower as it will directly overwrite /// the value without checking if it was already #[inline] pub unsafe fn unlock(&self) { let state = self.owner_thread_handle.swap(svc::INVALID_HANDLE, Acquire); //debug_assert!(state & !WAIT_MASK == 0, "Tried to unlock and unlocked mutex"); // we're actually not going to check the assert below, as we want to support having a Mutex that is Sync, // and/or a MutexGuard that is Sync/Send // assert_eq!(current_thread, state & !WAIT_MASK, "We are unlocking a mutex that isn't owned by the current thread"); if state & WAIT_MASK != 0 && let Err(rc) = unsafe { svc::arbitrate_unlock(&self.owner_thread_handle as *const _ as _) } { abort::abort(abort::AbortLevel::Panic(), rc); } } } impl Default for Mutex { fn default() -> Self { Self::new() } } #[allow(clippy::declare_interior_mutable_const)] unsafe impl lock_api::RawMutex for Mutex { // mark that a mutex guard can be Send type GuardMarker = lock_api::GuardSend; // const initializer for the Mutex const INIT: Self = Self::new(); fn is_locked(&self) -> bool { self.is_locked() } fn lock(&self) { self.lock() } fn try_lock(&self) -> bool { self.try_lock() } unsafe fn unlock(&self) { unsafe { self.unlock() } } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/nx-derive/src/lib.rs
nx-derive/src/lib.rs
use proc_macro::TokenStream; use quote::quote; use syn::{DeriveInput, parse_macro_input}; mod ipc_traits; /// This creates the required trait implementations for the type to be used as an IPC request parameter. /// As the type is directly copied into the buffer from an &Self, this will only work on `Copy` types. #[proc_macro_derive(Request)] pub fn derive_request(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident; TokenStream::from(quote!( impl ::nx::ipc::client::RequestCommandParameter for #name { fn before_request_write(_raw: &Self, walker: &mut ::nx::ipc::DataWalker, ctx: &mut ::nx::ipc::CommandContext) -> ::nx::result::Result<()> { walker.advance::<Self>(); Ok(()) } fn before_send_sync_request(raw: &Self, walker: &mut ::nx::ipc::DataWalker, ctx: &mut ::nx::ipc::CommandContext) -> ::nx::result::Result<()> { walker.advance_set(*raw); Ok(()) } } impl ::nx::ipc::server::RequestCommandParameter<'_, #name> for #name { fn after_request_read(ctx: &mut ::nx::ipc::server::ServerContext<'_>) -> ::nx::result::Result<Self> { Ok(ctx.raw_data_walker.advance_get()) } } )) } /// This creates the required trait implementations for the type to be used as an IPC response parameter. /// As the type is directly copied into the buffer from an &Self, this will only work on `Copy` types. #[proc_macro_derive(Response)] pub fn derive_response(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident; let item_generics = &input.generics; TokenStream::from(quote!( impl #item_generics ::nx::ipc::client::ResponseCommandParameter<#name> for #name { fn after_response_read(walker: &mut ::nx::ipc::DataWalker, ctx: &mut ::nx::ipc::CommandContext) -> ::nx::result::Result<Self> { Ok(walker.advance_get()) } } impl #item_generics ::nx::ipc::server::ResponseCommandParameter for #name { type CarryState = (); fn before_response_write(_raw: &Self, ctx: &mut ::nx::ipc::server::ServerContext) -> ::nx::result::Result<Self::CarryState> { ctx.raw_data_walker.advance::<Self>(); Ok(()) } fn after_response_write(raw: Self, _carry_state: Self::CarryState, ctx: &mut ::nx::ipc::server::ServerContext) -> ::nx::result::Result<()> { ctx.raw_data_walker.advance_set(raw); Ok(()) } } )) } #[proc_macro_attribute] pub fn ipc_trait(args: TokenStream, ipc_trait: TokenStream) -> TokenStream { match ipc_traits::ipc_trait(args.into(), ipc_trait.into()) { Ok(ts) => ts.into(), Err(e) => e.into_compile_error().into(), } }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
aarch64-switch-rs/nx
https://github.com/aarch64-switch-rs/nx/blob/b365c1baa4c4472fe604f4ab9646440d23c3bd9c/nx-derive/src/ipc_traits.rs
nx-derive/src/ipc_traits.rs
use std::str::FromStr; use proc_macro2::{Ident, Span, TokenStream}; use quote::{format_ident, quote}; use syn::{ AngleBracketedGenericArguments, AttrStyle, FnArg, GenericArgument, Path, PathSegment, ReturnType, TraitItem, TraitItemFn, Type, TypePath, punctuated::Punctuated, spanned::Spanned, token::{Gt, Lt, Mut, PathSep}, }; pub fn ipc_trait(_args: TokenStream, ipc_trait: TokenStream) -> syn::Result<TokenStream> { let input: syn::ItemTrait = syn::parse2::<syn::ItemTrait>(ipc_trait)?; let name = input.ident; let vis = input.vis; let client_trait = format_ident!("I{}Client", name); let server_trait = format_ident!("I{}Server", name); let build_default_client = input.attrs.iter().any(|attr| { if let syn::Attribute { meta: syn::Meta::Path(p), .. } = attr { p.is_ident("default_client") } else { false } }); let default_client: TokenStream = if build_default_client { quote! { #[doc = concat!("The default client for the `", stringify!(#name), "` trait. All implementors of the trait need to read their session in accordance with this Types IPC Parameter traits.")] pub struct #name { #[doc(hidden)] pub (crate) session: ::nx::ipc::sf::Session } impl ::nx::ipc::client::IClientObject for #name { fn new(session: ::nx::ipc::sf::Session) -> Self { Self { session } } fn get_session(&self) -> & ::nx::ipc::sf::Session { &self.session } fn get_session_mut(&mut self) -> &mut ::nx::ipc::sf::Session { &mut self.session } } unsafe impl ::core::marker::Sync for #name {} unsafe impl ::core::marker::Send for #name {} impl ::nx::ipc::client::RequestCommandParameter for #name { fn before_request_write(session: &Self, _walker: &mut ::nx::ipc::DataWalker, ctx: &mut ::nx::ipc::CommandContext) -> ::nx::result::Result<()> { ctx.in_params.add_object(session.session.object_info) } fn before_send_sync_request(_session: &Self, _walker: &mut ::nx::ipc::DataWalker, _ctx: &mut ::nx::ipc::CommandContext) -> ::nx::result::Result<()> { Ok(()) } } impl ::nx::ipc::client::ResponseCommandParameter<#name> for #name { fn after_response_read(_walker: &mut ::nx::ipc::DataWalker, ctx: &mut ::nx::ipc::CommandContext) -> ::nx::result::Result<Self> { let object_info = ctx.pop_object()?; Ok(Self { session: ::nx::ipc::sf::Session::from(object_info)}) } } impl ::nx::ipc::server::RequestCommandParameter<'_, #name> for #name { fn after_request_read(_ctx: &mut ::nx::ipc::server::ServerContext) -> ::nx::result::Result<Self> { use ::nx::result::ResultBase; // TODO: determine if we need to do this, since this is a server side operation of a client object? // probably needs to be supported right? ::nx::ipc::sf::hipc::rc::ResultUnsupportedOperation::make_err() } } impl ::nx::ipc::server::ResponseCommandParameter for #name { type CarryState = (); fn before_response_write(_session: &Self, _ctx: &mut ::nx::ipc::server::ServerContext) -> ::nx::result::Result<()> { use ::nx::result::ResultBase; // TODO: determine if we need to do this, since this is a server side operation of a client object? // probably needs to be supported right? ::nx::ipc::sf::hipc::rc::ResultUnsupportedOperation::make_err() } fn after_response_write(_session: Self, _carry_state: (), _ctx: &mut ::nx::ipc::server::ServerContext) -> ::nx::result::Result<()> { use ::nx::result::ResultBase; // TODO: determine if we need to do this, since this is a server side operation of a client object? // probably needs to be supported right? ::nx::ipc::sf::hipc::rc::ResultUnsupportedOperation::make_err() } } impl #client_trait for #name {} } } else { quote! {} }; for item in input.items.iter() { if !matches!(item, TraitItem::Fn(_)) { return Err(stringify_error( item.span(), "Only function items are supported for ipc_trait derivations", )); } } let mut client_fns = vec![]; let mut server_fns = vec![]; let mut handle_request_matches = vec![]; let mut item_iter = input.items.iter(); while let Some(TraitItem::Fn(fn_item)) = item_iter.next() { if fn_item.default.is_some() { return Err(stringify_error( fn_item.span(), "No default implementations are supported for ipc_trait derivations", )); } let fn_name = fn_item.sig.ident.clone(); let mut ipc_rid: Option<u32> = None; let mut version_req = None; let mut return_type_is_session = false; let mut return_wrap_result = true; let mut doc_comments: Vec<syn::Attribute> = vec![]; for attr in fn_item.attrs.iter() { if let syn::Attribute { style: AttrStyle::Outer, meta: syn::Meta::List(syn::MetaList { path, delimiter: _, tokens, }), .. } = attr { if path.is_ident("ipc_rid") { ipc_rid = Some(syn::parse2::<syn::LitInt>(tokens.clone())?.base10_parse()?); } else if path.is_ident("version") { version_req = Some(syn::parse2::<syn::Expr>(tokens.clone())?); } else { return Err(stringify_error( fn_item.span(), "Only the `ipc_rid`, `version`, `no_wrap_return`, and `return_session` attrs are supported on ipc trait functions (plus doc comments)", )); } } else if let syn::Attribute { meta: syn::Meta::Path(p), .. } = attr { if p.is_ident("return_session") { return_type_is_session = true; } else if p.is_ident("no_wrap_return") { return_wrap_result = false } else { return Err(stringify_error( fn_item.span(), "Only the `ipc_rid`, `version` `no_wrap_return`, and `return_session` attrs are supported on ipc trait functions (plus doc comments)", )); } } else if let syn::Attribute { style: AttrStyle::Outer, meta: syn::Meta::NameValue(syn::MetaNameValue { path, .. }), .. } = attr && path.is_ident("doc") { doc_comments.push(attr.clone()); } else { return Err(stringify_error( fn_item.span(), "Only the `ipc_rid`, `version` `no_wrap_return`, and `return_session` attrs are supported on ipc trait functions (plus doc comments)", )); } } if ipc_rid.is_none() { return Err(stringify_error( fn_item.span(), "IPC member functions must have an assigned request id", )); } let ipc_rid = ipc_rid.unwrap(); let version_req = version_req .unwrap_or(syn::parse2(quote! {::nx::version::VersionInterval::all()}).unwrap()); // fix up the return types of the client functions to return nx::result::Result let mut client_fn = fn_item.clone(); client_fn.attrs = doc_comments.clone(); let mut client_in_param_names = vec![]; let mut server_in_param_names = vec![]; let mut in_param_types = vec![]; client_fn .sig .inputs .iter() .skip(1) .try_for_each(|fn_args| { let arg_span = fn_args.span(); let arg_pat = match fn_args { FnArg::Typed(pat) => pat, _ => { return Err(stringify_error( arg_span, "We should only have non-receiver arguments after skipping the first arg.", )); } }; let arg_name = match *arg_pat.pat.clone() { syn::Pat::Ident(pat_ident) => pat_ident.ident, _ => { return Err(stringify_error( arg_span, "Only basic ident names are supported.", )); } }; client_in_param_names.push(arg_pat.pat.clone()); server_in_param_names.push(format_ident!("in_param_{}", arg_name)); in_param_types.push(arg_pat.ty.clone()); Ok(()) })?; let mut out_param_names = vec![]; let mut out_param_types = vec![]; if return_wrap_result { match client_fn.sig.output.clone() { ReturnType::Default => {} ReturnType::Type(_, ty) => match *ty { Type::Tuple(tuple) => { let types: Vec<Type> = (0..) .map_while(|off| tuple.elems.get(off).cloned()) .collect(); let _: () = types .into_iter() .enumerate() .map(|(off, t)| { out_param_names.push(format_ident!("out_param_{}", off)); out_param_types.push(t); }) .collect(); } Type::Paren(ty_pat) => { out_param_names.push(format_ident!("out_param_0")); out_param_types.push((*ty_pat.elem).clone()); } Type::Path(ty_path) => { out_param_names.push(format_ident!("out_param_0")); out_param_types.push(Type::Path(ty_path)); } _ => { return Err(stringify_error( client_fn.sig.output.span(), "Only tuple types, paren-wrapped types, or paths are supported for return types", )); } }, } } client_fn.default = Some(syn::parse2(quote! { { let mut ctx = ::nx::ipc::CommandContext::new_client(self.get_session().object_info); let mut walker = ::nx::ipc::DataWalker::new(core::ptr::null_mut()); #(::nx::ipc::client::RequestCommandParameter::before_request_write(&#client_in_param_names, &mut walker, &mut ctx)?;)* ctx.in_params.data_size = walker.get_offset() as u32; match self.get_session().object_info.protocol { ::nx::ipc::CommandProtocol::Cmif => ::nx::ipc::cmif::client::write_request_command_on_msg_buffer(&mut ctx, Some(#ipc_rid), ::nx::ipc::cmif::DomainCommandType::SendMessage), ::nx::ipc::CommandProtocol::Tipc => ::nx::ipc::tipc::client::write_request_command_on_msg_buffer(&mut ctx, #ipc_rid) }; walker.reset_with(ctx.in_params.data_offset); #( ::nx::ipc::client::RequestCommandParameter::before_send_sync_request(&#client_in_param_names, &mut walker, &mut ctx)?; )* ::nx::svc::send_sync_request(self.get_session().object_info.handle)?; match self.get_session().object_info.protocol { ::nx::ipc::CommandProtocol::Cmif => ::nx::ipc::cmif::client::read_request_command_response_from_msg_buffer(&mut ctx)?, ::nx::ipc::CommandProtocol::Tipc => ::nx::ipc::tipc::client::read_request_command_response_from_msg_buffer(&mut ctx)? }; walker.reset_with(ctx.out_params.data_offset); #( let #out_param_names = <#out_param_types as ::nx::ipc::client::ResponseCommandParameter<_>>::after_response_read(&mut walker, &mut ctx)?; )* Ok(( #(#out_param_names as _),* )) } })?); client_fn.semi_token = None; let output_span = client_fn.sig.output.span(); match &mut client_fn.sig.output { ReturnType::Default => { client_fn.sig.output = syn::parse2::<ReturnType>( FromStr::from_str(" -> ::nx::result::Result<()>").unwrap(), ) .unwrap() } ReturnType::Type(_, ty) => { let mut wrapped_result_generic = Punctuated::new(); wrapped_result_generic.push(GenericArgument::Type(*ty.clone())); let mut result_path = Punctuated::new(); result_path.push(PathSegment { ident: Ident::new_raw("nx", output_span), arguments: syn::PathArguments::None, }); result_path.push(PathSegment { ident: Ident::new_raw("result", output_span), arguments: syn::PathArguments::None, }); result_path.push(PathSegment { ident: Ident::new_raw("Result", output_span), arguments: syn::PathArguments::AngleBracketed(AngleBracketedGenericArguments { colon2_token: None, lt_token: Lt::default(), args: wrapped_result_generic, gt_token: Gt::default(), }), }); *ty = Box::new(Type::Path(TypePath { qself: None, path: Path { leading_colon: Some(PathSep::default()), segments: result_path, }, })); } }; client_fns.push(client_fn); // fix the return type for the server function types if let mut server_fn = fn_item.clone(); server_fn.attrs = doc_comments; if let Some(FnArg::Receiver(r)) = server_fn.sig.inputs.iter_mut().next() { // all server functions are considered &mut borrowing r.mutability = Some(Mut::default()); r.ty = Box::new(syn::parse2(quote! {&mut Self}).unwrap()); } else { return Err(stringify_error( server_fn.span(), "IPC traits with associated functions is not supported.", )); } if return_type_is_session { if let ReturnType::Type(_, bty) = &mut server_fn.sig.output { match *bty.clone() { Type::Path(ty) => { if ty.path.segments.len() != 1 { return Err(stringify_error( server_fn.sig.output.span(), "Output type be a raw type name (the base name of the traits) the return type is marked as a session type", )); } let out_type_ident = format!( "impl I{}Server + 'static", ty.path.segments.last().unwrap().ident ); *bty = Box::new(syn::parse2::<Type>(FromStr::from_str( out_type_ident.as_str(), )?)?); } Type::Tuple(mut tup_ty) => { if let Some(first_mut_ref) = tup_ty.elems.first_mut() { if let Type::Path(ty) = first_mut_ref.clone() { if ty.path.segments.len() != 1 { return Err(stringify_error( server_fn.sig.output.span(), "Output type be a raw type name (the base name of the traits) the return type is marked as a session type", )); } *first_mut_ref = syn::parse2(FromStr::from_str( format!( "impl I{}Server + 'static", ty.path.segments.last().unwrap().ident ) .as_str(), )?)?; } else { return Err(stringify_error( server_fn.sig.output.span(), "The first element of a tuple return type must be a bare type name when returning a session type", )); } *bty = Box::new(Type::Tuple(tup_ty)); } else { return Err(stringify_error( server_fn.sig.output.span(), "Tuple type outputs must have at least 2 elements when specifying a session type. If one element is being returned, omit the braces to return the bare type.", )); } } _ => { return Err(stringify_error( server_fn.sig.output.span(), "Output type be a raw type name (the base name of the traits) or a tuple with the base name as the first element, if the return type is marked as a session type", )); } } } } // now that the return type for server functions has been fixed, we can apply the same T -> Result<T> from the client functions match &mut server_fn.sig.output { ReturnType::Default => { server_fn.sig.output = syn::parse2::<ReturnType>( FromStr::from_str(" -> ::nx::result::Result<()>").unwrap(), ) .unwrap() } ReturnType::Type(_, ty) => { let mut wrapped_result_generic = Punctuated::new(); wrapped_result_generic.push(GenericArgument::Type(*ty.clone())); let mut result_path = Punctuated::new(); result_path.push(PathSegment { ident: Ident::new_raw("nx", Span::call_site()), arguments: syn::PathArguments::None, }); result_path.push(PathSegment { ident: Ident::new_raw("result", Span::call_site()), arguments: syn::PathArguments::None, }); result_path.push(PathSegment { ident: Ident::new_raw("Result", Span::call_site()), arguments: syn::PathArguments::AngleBracketed(AngleBracketedGenericArguments { colon2_token: None, lt_token: Lt::default(), args: wrapped_result_generic, gt_token: Gt::default(), }), }); *ty = Box::new(Type::Path(TypePath { qself: None, path: Path { leading_colon: Some(PathSep::default()), segments: result_path, }, })); } }; server_fns.push(server_fn); let server_impl_fn_name = format_ident!("sf_server_impl_{}", fn_name); let carry_state_names: Vec<Ident> = out_param_names .iter() .map(|ident| format_ident!("{}_carry_state", ident)) .collect(); let server_internal_fn: TraitItemFn = syn::parse2(quote! { #[allow(unused_assignments)] #[allow(unused_parens)] #[allow(unused_mut)] #[doc(hidden)] fn #server_impl_fn_name(&mut self, protocol: ::nx::ipc::CommandProtocol, mut ctx: &mut ::nx::ipc::server::ServerContext) -> ::nx::result::Result<()> { use ::nx::result::ResultBase; ctx.raw_data_walker = ::nx::ipc::DataWalker::new(ctx.ctx.in_params.data_offset); #( let #server_in_param_names = <#in_param_types as ::nx::ipc::server::RequestCommandParameter<_>>::after_request_read(&mut ctx)?; )* let ( #( #out_param_names ),* ) = unsafe {self.#fn_name( #( #server_in_param_names ),* )? }; ctx.raw_data_walker = ::nx::ipc::DataWalker::new(core::ptr::null_mut()); #( let #carry_state_names = ::nx::ipc::server::ResponseCommandParameter::before_response_write(&#out_param_names, &mut ctx)?; )* ctx.ctx.out_params.data_size = ctx.raw_data_walker.get_offset() as u32; match protocol { ::nx::ipc::CommandProtocol::Cmif => { ::nx::ipc::cmif::server::write_request_command_response_on_msg_buffer(&mut ctx.ctx, ::nx::result::ResultSuccess::make(), ::nx::ipc::cmif::CommandType::Request); }, ::nx::ipc::CommandProtocol::Tipc => { ::nx::ipc::tipc::server::write_request_command_response_on_msg_buffer(&mut ctx.ctx, ::nx::result::ResultSuccess::make(), 16); // TODO: is this command type actually read/used/relevant? } }; ctx.raw_data_walker = ::nx::ipc::DataWalker::new(ctx.ctx.out_params.data_offset); #( ::nx::ipc::server::ResponseCommandParameter::after_response_write(#out_param_names, #carry_state_names, &mut ctx)?; )* Ok(()) } })?; server_fns.push(server_internal_fn); handle_request_matches.push(quote! { #ipc_rid if (#version_req).contains(version) => { Some(self.#server_impl_fn_name(protocol, ctx)) } }); } Ok(quote! { #default_client #vis trait #client_trait: ::nx::ipc::client::IClientObject + Sync { #( #[allow(unused_parens)] #[allow(clippy::too_many_arguments)] #[allow(missing_docs)] #client_fns )* } #vis trait #server_trait: ::nx::ipc::server::ISessionObject + Sync { #( #[allow(unused_parens)] #[allow(clippy::too_many_arguments)] #[allow(missing_docs)] #server_fns )* /// The dynamic dispatch function that calls into the IPC server functions. This should only be called from the [`ServerManager`][`::nx::ipc::server::ServerManager`] and not from client code. /// /// Examples for implementing [`ISessionObject`][`::nx::ipc::server::ISessionObject`] or [`IMitmServerOject`][`::nx::ipc::server::IMitmServerObject`] can be found in the [examples](https://github.com/aarch64-switch-rs/examples/) crate. fn try_handle_request_by_id(&mut self, req_id: u32, protocol: ::nx::ipc::CommandProtocol, ctx: &mut ::nx::ipc::server::ServerContext) -> Option<::nx::result::Result<()>> { let version = ::nx::version::get_version(); match req_id { #( #handle_request_matches ),* _ => None } } } }) } fn stringify_error(span: proc_macro2::Span, msg: impl std::fmt::Display) -> syn::Error { syn::Error::new(span, msg) }
rust
MIT
b365c1baa4c4472fe604f4ab9646440d23c3bd9c
2026-01-04T20:16:15.900894Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/config.rs
src/config.rs
use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use crate::theme::ThemeName; #[derive(Debug, Deserialize, Serialize)] pub struct Config { #[serde(default)] pub keybindings: KeyBindings, #[serde(default)] pub theme: ThemeName, } #[derive(Debug, Deserialize, Serialize)] pub struct KeyBindings { #[serde(default = "default_quit")] pub quit: char, #[serde(default = "default_open")] pub open: char, #[serde(default = "default_open_new_tab")] pub open_new_tab: char, #[serde(default = "default_refresh")] pub refresh: char, #[serde(default = "default_latest")] pub latest: char, #[serde(default = "default_scroll_up")] pub scroll_up: char, #[serde(default = "default_scroll_down")] pub scroll_down: char, #[serde(default = "default_scroll_bottom")] pub scroll_bottom: char, } fn default_quit() -> char { 'q' } fn default_open() -> char { 'o' } fn default_open_new_tab() -> char { 'O' } fn default_refresh() -> char { 'r' } fn default_latest() -> char { 'l' } fn default_scroll_up() -> char { 'k' } fn default_scroll_down() -> char { 'j' } fn default_scroll_bottom() -> char { 'G' } impl Default for KeyBindings { fn default() -> Self { Self { quit: default_quit(), open: default_open(), open_new_tab: default_open_new_tab(), refresh: default_refresh(), latest: default_latest(), scroll_up: default_scroll_up(), scroll_down: default_scroll_down(), scroll_bottom: default_scroll_bottom(), } } } impl Default for Config { fn default() -> Self { Self { keybindings: KeyBindings::default(), theme: ThemeName::default(), } } } pub fn load_config() -> Result<Config> { let config_path = get_config_path()?; if !config_path.exists() { return Ok(Config::default()); } let content = std::fs::read_to_string(&config_path) .context("Failed to read config file")?; let config: Config = toml::from_str(&content) .context("Failed to parse config file")?; Ok(config) } fn get_config_path() -> Result<PathBuf> { // Try ~/.bbcli first if let Some(home) = dirs::home_dir() { let bbcli_path = home.join(".bbcli"); if bbcli_path.exists() { return Ok(bbcli_path); } } // Try ~/.config/bbcli if let Some(config_dir) = dirs::config_dir() { let bbcli_config = config_dir.join("bbcli"); return Ok(bbcli_config); } // Fallback to home directory dirs::home_dir() .map(|h| h.join(".bbcli")) .context("Could not determine config path") }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/app.rs
src/app.rs
use crate::feeds::{Feed, get_default_feed}; use crate::theme::Theme; use std::time::{Instant, Duration}; use std::collections::HashMap; #[derive(Debug, Clone, PartialEq)] pub enum AppMode { Normal, FeedMenu, Preview, Help, } #[derive(Debug, Clone, PartialEq)] pub enum SortOrder { Default, // RSS feed order (as received) DateNewest, // Newest first DateOldest, // Oldest first } impl SortOrder { pub fn next(&self) -> Self { match self { SortOrder::Default => SortOrder::DateNewest, SortOrder::DateNewest => SortOrder::DateOldest, SortOrder::DateOldest => SortOrder::Default, } } pub fn name(&self) -> &str { match self { SortOrder::Default => "Default", SortOrder::DateNewest => "Newest First", SortOrder::DateOldest => "Oldest First", } } } #[derive(Debug, Clone, PartialEq)] pub enum ImageProtocol { Auto, // Automatically detect best protocol Halfblocks, // Unicode half blocks (widely compatible) Sixel, // High quality Sixel graphics Kitty, // Kitty graphics protocol (high quality, modern terminals) } impl ImageProtocol { pub fn next(&self) -> Self { match self { ImageProtocol::Auto => ImageProtocol::Halfblocks, ImageProtocol::Halfblocks => ImageProtocol::Sixel, ImageProtocol::Sixel => ImageProtocol::Kitty, ImageProtocol::Kitty => ImageProtocol::Auto, } } pub fn name(&self) -> &str { match self { ImageProtocol::Auto => "Auto", ImageProtocol::Halfblocks => "Halfblocks", ImageProtocol::Sixel => "Sixel", ImageProtocol::Kitty => "Kitty", } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct NewsStory { pub title: String, pub description: String, pub link: String, pub pub_date: String, pub category: String, pub image_url: Option<String>, } pub struct App { pub stories: Vec<NewsStory>, pub ticker_stories: Vec<NewsStory>, // Always contains Top Stories for ticker pub selected: usize, pub should_quit: bool, pub is_loading: bool, pub is_refreshing: bool, // Track if currently refreshing data pub is_offline: bool, // Track offline mode pub error_message: Option<String>, pub ticker_index: usize, pub ticker_counter: u32, pub mode: AppMode, pub current_feed: Feed, pub feed_menu_selected: usize, pub show_preview: bool, pub humanize_dates: bool, pub image_protocol: ImageProtocol, pub theme: Theme, // Current theme pub show_full_article: bool, // Toggle between preview and full article view pub article_scroll_offset: usize, // Scroll position in article view pub is_fetching_article: bool, // Loading state for article fetching pub sort_order: SortOrder, // Current sort order pub last_refresh_time: Instant, // Track last refresh for auto-refresh article_cache: HashMap<String, String>, // Cache fetched articles by URL last_opened_index: Option<usize>, // Track last opened article index to prevent repeated opens last_open_time: Option<Instant>, // Track last open time for cooldown last_selection_change_time: Instant, // Track when selection last changed scroll_count: u32, // Count rapid scroll events (for storm detection) last_scroll_time: Instant, // Track last scroll event time scroll_pause_until: Option<Instant>, // When to resume scrolling after storm } impl App { pub fn new(theme: Theme) -> Self { Self { stories: Vec::new(), ticker_stories: Vec::new(), selected: 0, should_quit: false, is_loading: true, is_refreshing: false, // Not refreshing initially is_offline: false, // Start in online mode error_message: None, ticker_index: 0, ticker_counter: 0, mode: AppMode::Normal, current_feed: get_default_feed(), feed_menu_selected: 0, show_preview: false, humanize_dates: true, // Default to humanized dates image_protocol: ImageProtocol::Auto, // Auto-detect best protocol theme, // Theme from config show_full_article: false, // Start in preview mode article_scroll_offset: 0, // Start at top of article is_fetching_article: false, // Not fetching initially sort_order: SortOrder::Default, // Default RSS order last_refresh_time: Instant::now(), // Initialize to now article_cache: HashMap::new(), // Empty cache last_opened_index: None, // No article opened yet last_open_time: None, // No article opened yet last_selection_change_time: Instant::now(), // Initialize to now scroll_count: 0, // No scrolls yet last_scroll_time: Instant::now(), // Initialize to now scroll_pause_until: None, // Not paused } } // Scroll storm detection: prevents catastrophic event buffering in Ghostty // Returns true if scrolling should be allowed, false if paused fn check_scroll_storm(&mut self) -> bool { // Only enable storm detection when preview is OPEN // (When preview is closed, scroll keys work normally without blocking) if !self.show_preview { return true; // Preview closed, allow all scrolling } // Check if currently paused if let Some(pause_until) = self.scroll_pause_until { if Instant::now() < pause_until { return false; // Still paused, ignore scroll } else { // Pause expired, resume scrolling self.scroll_pause_until = None; self.scroll_count = 0; } } // Check if this is part of a scroll storm let now = Instant::now(); let time_since_last_scroll = now.duration_since(self.last_scroll_time).as_secs_f32(); if time_since_last_scroll > 0.5 { // Been a while since last scroll, reset counter self.scroll_count = 0; } // Increment scroll count self.scroll_count += 1; self.last_scroll_time = now; // Check if storm detected (more than 10 scrolls in 0.5 seconds) if self.scroll_count > 10 && time_since_last_scroll < 0.5 { // SCROLL STORM DETECTED! Pause scrolling for 1 second self.scroll_pause_until = Some(now + std::time::Duration::from_secs(1)); self.scroll_count = 0; return false; // Ignore this scroll } true // Allow scroll } pub fn next(&mut self) { // Check for scroll storm - pause scrolling if detected if !self.check_scroll_storm() { return; // Scroll storm detected, ignoring this scroll event } if !self.stories.is_empty() { self.selected = (self.selected + 1).min(self.stories.len() - 1); // Clear last opened index when selection changes - allows opening new article self.last_opened_index = None; // Record when selection changed - prevents immediate opens self.last_selection_change_time = Instant::now(); } } pub fn previous(&mut self) { // Check for scroll storm - pause scrolling if detected if !self.check_scroll_storm() { return; // Scroll storm detected, ignoring this scroll event } if self.selected > 0 { self.selected -= 1; // Clear last opened index when selection changes - allows opening new article self.last_opened_index = None; // Record when selection changed - prevents immediate opens self.last_selection_change_time = Instant::now(); } } pub fn scroll_to_bottom(&mut self) { // Check for scroll storm - pause scrolling if detected if !self.check_scroll_storm() { return; // Scroll storm detected, ignoring this scroll event } if !self.stories.is_empty() { self.selected = self.stories.len() - 1; // Clear last opened index when selection changes - allows opening new article self.last_opened_index = None; // Record when selection changed - prevents immediate opens self.last_selection_change_time = Instant::now(); } } pub fn scroll_to_top(&mut self) { // Check for scroll storm - pause scrolling if detected if !self.check_scroll_storm() { return; // Scroll storm detected, ignoring this scroll event } self.selected = 0; // Clear last opened index when selection changes - allows opening new article self.last_opened_index = None; // Record when selection changed - prevents immediate opens self.last_selection_change_time = Instant::now(); } pub fn open_selected(&mut self) -> anyhow::Result<()> { // AGGRESSIVE PROTECTION against Ghostty event buffering catastrophe: // 1. SELECTION STABILITY: Prevent opening if selection changed recently // (Requires 3 seconds on same article before opening) if self.last_selection_change_time.elapsed().as_secs_f32() < 3.0 { return Ok(()); // Selection changed too recently, ignore } // 2. TIME-BASED: Prevent opening ANY article within 5 seconds of last open // (Prevents rapid-fire opens even when scrolling to different articles) if let Some(last_time) = self.last_open_time { if last_time.elapsed().as_secs_f32() < 5.0 { return Ok(()); // Still in cooldown, ignore } } // 3. INDEX-BASED: Prevent opening same article multiple times // (Additional protection against repeated opens) if let Some(last_idx) = self.last_opened_index { if last_idx == self.selected { return Ok(()); // Same article, ignore } } // All checks passed, open the article if let Some(story) = self.stories.get(self.selected) { webbrowser::open(&story.link)?; self.last_opened_index = Some(self.selected); self.last_open_time = Some(Instant::now()); } Ok(()) } pub fn open_selected_new_tab(&mut self) -> anyhow::Result<()> { // Most browsers will open in a new tab by default self.open_selected() } pub fn quit(&mut self) { self.should_quit = true; } pub fn update_stories(&mut self, stories: Vec<NewsStory>) { self.stories = stories; self.is_loading = false; self.is_refreshing = false; // Check selection bounds before sorting if self.selected >= self.stories.len() && !self.stories.is_empty() { self.selected = self.stories.len() - 1; } // Re-apply current sort order after updating stories // Note: apply_sort() resets selection to 0, which is intentional for sorted views if self.sort_order != crate::app::SortOrder::Default { self.apply_sort(); } } pub fn update_ticker_stories(&mut self, stories: Vec<NewsStory>) { self.ticker_stories = stories; self.is_refreshing = false; } pub fn set_error(&mut self, error: String) { self.error_message = Some(error); self.is_loading = false; self.is_refreshing = false; } pub fn clear_error(&mut self) { self.error_message = None; } pub fn tick(&mut self) -> bool { self.ticker_counter += 1; // Rotate ticker every 100 ticks (approximately 10 seconds at 100ms polling) if self.ticker_counter >= 100 { self.ticker_counter = 0; self.rotate_ticker(); } // Return true every 10 ticks (approximately 1 second) to trigger clock update self.ticker_counter % 10 == 0 } fn rotate_ticker(&mut self) { if self.ticker_stories.is_empty() { self.ticker_index = 0; return; } let max_ticker_items = 5.min(self.ticker_stories.len()); self.ticker_index = (self.ticker_index + 1) % max_ticker_items; } pub fn toggle_feed_menu(&mut self) { self.mode = if self.mode == AppMode::FeedMenu { AppMode::Normal } else { AppMode::FeedMenu }; } pub fn toggle_preview(&mut self) { self.show_preview = !self.show_preview; } pub fn toggle_date_format(&mut self) { self.humanize_dates = !self.humanize_dates; } pub fn cycle_image_protocol(&mut self) { self.image_protocol = self.image_protocol.next(); } pub fn feed_menu_next(&mut self, feed_count: usize) { if feed_count > 0 { self.feed_menu_selected = (self.feed_menu_selected + 1).min(feed_count - 1); } } pub fn feed_menu_previous(&mut self) { if self.feed_menu_selected > 0 { self.feed_menu_selected -= 1; } } pub fn select_feed(&mut self, feed: Feed) { self.current_feed = feed; self.mode = AppMode::Normal; self.is_loading = true; self.selected = 0; } // Article viewing methods pub fn fetch_and_show_article(&mut self) { if let Some(story) = self.stories.get(self.selected) { let url = &story.link; // Check cache first if !self.article_cache.contains_key(url) { // Not in cache, fetch it self.is_fetching_article = true; use crate::article_fetcher::fetch_article_content; match fetch_article_content(url) { Ok(content) => { self.article_cache.insert(url.clone(), content); self.is_fetching_article = false; self.show_full_article = true; self.article_scroll_offset = 0; } Err(e) => { self.is_fetching_article = false; self.set_error(format!("Failed to fetch article: {}", e)); } } } else { // Already cached, show it self.show_full_article = true; self.article_scroll_offset = 0; } } } pub fn toggle_article_view(&mut self) { if self.show_full_article { // Return to preview self.show_full_article = false; self.article_scroll_offset = 0; } } pub fn scroll_article_up(&mut self) { if self.article_scroll_offset > 0 { self.article_scroll_offset = self.article_scroll_offset.saturating_sub(1); } } pub fn scroll_article_down(&mut self) { // Scroll down (limit will be checked during rendering) self.article_scroll_offset += 1; } pub fn get_current_article_text(&self) -> Option<&String> { if let Some(story) = self.stories.get(self.selected) { self.article_cache.get(&story.link) } else { None } } pub fn toggle_help_menu(&mut self) { self.mode = if self.mode == AppMode::Help { AppMode::Normal } else { AppMode::Help }; } pub fn cycle_theme(&mut self) { self.theme = match self.theme.name.as_str() { "Light" => Theme::dark(), "Dark" => Theme::light(), _ => Theme::light(), }; } pub fn cycle_sort_order(&mut self) { self.sort_order = self.sort_order.next(); self.apply_sort(); } fn apply_sort(&mut self) { match self.sort_order { SortOrder::Default => { // Keep original RSS order - do nothing or reload } SortOrder::DateNewest => { // Sort by date, newest first self.stories.sort_by(|a, b| b.pub_date.cmp(&a.pub_date)); } SortOrder::DateOldest => { // Sort by date, oldest first self.stories.sort_by(|a, b| a.pub_date.cmp(&b.pub_date)); } } // Reset selection to top after sorting self.selected = 0; } pub fn check_auto_refresh(&self) -> bool { // Auto-refresh every 5 minutes (300 seconds) const AUTO_REFRESH_INTERVAL: Duration = Duration::from_secs(300); self.last_refresh_time.elapsed() >= AUTO_REFRESH_INTERVAL } pub fn mark_refreshed(&mut self) { self.last_refresh_time = Instant::now(); } // Jump to the current ticker article // Returns true if feed needs to change (trigger FeedChanged action) pub fn jump_to_ticker_article(&mut self) -> bool { // Check if ticker has any stories if self.ticker_stories.is_empty() || self.ticker_index >= self.ticker_stories.len() { return false; } // Get the current ticker story let ticker_story = &self.ticker_stories[self.ticker_index]; let ticker_url = &ticker_story.link; // Check if we're already on Top Stories feed let top_stories_feed = crate::feeds::get_default_feed(); let need_feed_change = self.current_feed.url != top_stories_feed.url; if need_feed_change { // Switch to Top Stories feed self.current_feed = top_stories_feed; self.is_loading = true; self.selected = 0; return true; // Signal that feed needs to be fetched } else { // Already on Top Stories, just find and select the ticker article if let Some(index) = self.stories.iter().position(|s| s.link == *ticker_url) { self.selected = index; // Clear last opened to allow opening this article self.last_opened_index = None; self.last_selection_change_time = Instant::now(); } else { // Story not found, select first story self.selected = 0; } return false; } } }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/lib.rs
src/lib.rs
pub mod app; pub mod api; pub mod article_fetcher; pub mod cache; pub mod cli; pub mod config; pub mod date_utils; pub mod events; pub mod feeds; pub mod image_cache; pub mod theme; pub mod ui;
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/theme.rs
src/theme.rs
use ratatui::style::Color; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum ThemeName { Light, Dark, } impl Default for ThemeName { fn default() -> Self { ThemeName::Light } } #[derive(Debug, Clone)] pub struct Theme { pub name: String, pub bg_primary: Color, // Main background pub bg_secondary: Color, // Alternate background (for list items) pub bg_accent: Color, // Header/footer background pub fg_primary: Color, // Main text pub fg_secondary: Color, // Secondary/muted text pub accent: Color, // BBC red / selection color pub accent_fg: Color, // Text color on accent background } impl Theme { pub fn light() -> Self { Self { name: "Light".to_string(), bg_primary: Color::Rgb(255, 254, 252), // Off-white bg_secondary: Color::Rgb(255, 254, 252), // Same as primary bg_accent: Color::Rgb(230, 230, 227), // Light gray for footer fg_primary: Color::Rgb(0, 0, 0), // Black text fg_secondary: Color::Rgb(148, 148, 148), // Gray text accent: Color::Rgb(234, 68, 57), // BBC red accent_fg: Color::Rgb(255, 255, 255), // White on red } } pub fn dark() -> Self { Self { name: "Dark".to_string(), bg_primary: Color::Rgb(0, 0, 0), // Pure black bg_secondary: Color::Rgb(20, 20, 20), // Slightly lighter black bg_accent: Color::Rgb(40, 40, 40), // Dark gray for footer fg_primary: Color::Rgb(255, 255, 255), // White text fg_secondary: Color::Rgb(150, 150, 150), // Light gray text accent: Color::Rgb(234, 68, 57), // BBC red (same) accent_fg: Color::Rgb(255, 255, 255), // White on red (same) } } pub fn from_name(name: &ThemeName) -> Self { match name { ThemeName::Light => Self::light(), ThemeName::Dark => Self::dark(), } } }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/feeds.rs
src/feeds.rs
#[derive(Debug, Clone)] pub struct Feed { pub name: String, pub url: String, } impl Feed { pub fn new(name: &str, url: &str) -> Self { Self { name: name.to_string(), url: url.to_string(), } } } pub fn get_all_feeds() -> Vec<Feed> { vec![ Feed::new("Top Stories", "https://feeds.bbci.co.uk/news/rss.xml"), Feed::new("World", "https://feeds.bbci.co.uk/news/world/rss.xml"), Feed::new("UK", "https://feeds.bbci.co.uk/news/uk/rss.xml"), Feed::new("Business", "https://feeds.bbci.co.uk/news/business/rss.xml"), Feed::new("Politics", "https://feeds.bbci.co.uk/news/politics/rss.xml"), Feed::new("Health", "https://feeds.bbci.co.uk/news/health/rss.xml"), Feed::new("Education & Family", "https://feeds.bbci.co.uk/news/education/rss.xml"), Feed::new("Science & Environment", "https://feeds.bbci.co.uk/news/science_and_environment/rss.xml"), Feed::new("Technology", "https://feeds.bbci.co.uk/news/technology/rss.xml"), Feed::new("Entertainment & Arts", "https://feeds.bbci.co.uk/news/entertainment_and_arts/rss.xml"), Feed::new("England", "https://feeds.bbci.co.uk/news/england/rss.xml"), Feed::new("Northern Ireland", "https://feeds.bbci.co.uk/news/northern_ireland/rss.xml"), Feed::new("Scotland", "https://feeds.bbci.co.uk/news/scotland/rss.xml"), Feed::new("Wales", "https://feeds.bbci.co.uk/news/wales/rss.xml"), Feed::new("Africa", "https://feeds.bbci.co.uk/news/world/africa/rss.xml"), Feed::new("Asia", "https://feeds.bbci.co.uk/news/world/asia/rss.xml"), Feed::new("Europe", "https://feeds.bbci.co.uk/news/world/europe/rss.xml"), Feed::new("Latin America", "https://feeds.bbci.co.uk/news/world/latin_america/rss.xml"), Feed::new("Middle East", "https://feeds.bbci.co.uk/news/world/middle_east/rss.xml"), Feed::new("US & Canada", "https://feeds.bbci.co.uk/news/world/us_and_canada/rss.xml"), ] } pub fn get_default_feed() -> Feed { Feed::new("Top Stories", "https://feeds.bbci.co.uk/news/rss.xml") } pub fn get_feed_by_name(name: &str) -> anyhow::Result<Feed> { let name_lower = name.to_lowercase(); let feeds = get_all_feeds(); // Try exact match first (case-insensitive) for feed in &feeds { if feed.name.to_lowercase() == name_lower { return Ok(feed.clone()); } } // Try partial match (shortcuts) for feed in &feeds { if feed.name.to_lowercase().contains(&name_lower) { return Ok(feed.clone()); } } // Try common shortcuts let feed = match name_lower.as_str() { "tech" => Feed::new("Technology", "https://feeds.bbci.co.uk/news/technology/rss.xml"), "biz" | "business" => Feed::new("Business", "https://feeds.bbci.co.uk/news/business/rss.xml"), "pol" | "politics" => Feed::new("Politics", "https://feeds.bbci.co.uk/news/politics/rss.xml"), "sci" | "science" => Feed::new("Science & Environment", "https://feeds.bbci.co.uk/news/science_and_environment/rss.xml"), "entertainment" | "ent" => Feed::new("Entertainment & Arts", "https://feeds.bbci.co.uk/news/entertainment_and_arts/rss.xml"), "edu" | "education" => Feed::new("Education & Family", "https://feeds.bbci.co.uk/news/education/rss.xml"), _ => anyhow::bail!("Unknown feed: '{}'. Use 'world', 'uk', 'business', 'technology', etc.", name), }; Ok(feed) }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/cli.rs
src/cli.rs
use clap::{Parser, Subcommand}; use anyhow::Result; use crate::{api, article_fetcher, date_utils, feeds}; #[derive(Parser)] #[command(name = "bbcli")] #[command(about = "Browse BBC News like a hacker", long_about = None)] #[command(version)] pub struct Cli { #[command(subcommand)] pub command: Option<Commands>, /// Specify feed name (e.g., world, technology, business) #[arg(short, long, global = true)] pub feed: Option<String>, } #[derive(Subcommand)] pub enum Commands { /// List headlines from feed List, /// Open article in browser by index Open { /// Article index (1-based) index: usize, }, /// Show article in terminal Show { /// Article index (1-based) index: usize, }, } pub fn run_cli(cli: Cli) -> Result<()> { // Get feed URL let feed = if let Some(feed_name) = &cli.feed { feeds::get_feed_by_name(feed_name)? } else { feeds::get_default_feed() }; match cli.command { Some(Commands::List) => list_headlines(&feed), Some(Commands::Open { index }) => open_article(&feed, index), Some(Commands::Show { index }) => show_article(&feed, index), None => { // No subcommand provided, default to listing list_headlines(&feed) } } } fn list_headlines(feed: &feeds::Feed) -> Result<()> { let stories = api::fetch_stories(&feed.url)?; if stories.is_empty() { println!("No stories available."); return Ok(()); } println!("# {}\n", feed.name); for (i, story) in stories.iter().enumerate() { let humanized_date = date_utils::humanize_time(&story.pub_date); println!("{}. {} ({})", i + 1, story.title, humanized_date); } Ok(()) } fn open_article(feed: &feeds::Feed, index: usize) -> Result<()> { let stories = api::fetch_stories(&feed.url)?; if index == 0 || index > stories.len() { anyhow::bail!("Invalid article index: {}. Available: 1-{}", index, stories.len()); } let story = &stories[index - 1]; println!("Opening: {}", story.title); webbrowser::open(&story.link)?; println!("Launched in browser."); Ok(()) } fn show_article(feed: &feeds::Feed, index: usize) -> Result<()> { let stories = api::fetch_stories(&feed.url)?; if index == 0 || index > stories.len() { anyhow::bail!("Invalid article index: {}. Available: 1-{}", index, stories.len()); } let story = &stories[index - 1]; // Fetch full article content let article_text = article_fetcher::fetch_article_content(&story.link)?; // Print to terminal println!("{}", article_text); Ok(()) }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/article_fetcher.rs
src/article_fetcher.rs
use anyhow::Result; use reqwest::blocking::Client; use dom_smoothie::Readability; use html2text::from_read; use std::time::Duration; use crate::cache::Cache; pub fn fetch_article_content(url: &str) -> Result<String> { let cache = Cache::new().ok(); // Try to load from cache first if let Some(ref cache) = cache { if let Some(cached_content) = cache.load_article(url) { return Ok(cached_content); } } // Try to fetch from network let content_result = fetch_article_from_network(url); match content_result { Ok(content) => { // Save to cache on successful fetch if let Some(ref cache) = cache { let _ = cache.save_article(url, &content); } Ok(content) } Err(e) => { // Network failed, try to load from cache (even if expired) if let Some(ref cache) = cache { if let Some(cached_content) = cache.load_article_offline(url) { return Ok(cached_content); } } Err(e) } } } fn fetch_article_from_network(url: &str) -> Result<String> { // Fetch HTML content let client = Client::builder() .timeout(Duration::from_secs(10)) .build()?; let response = client.get(url).send()?; let html = response.text()?; // Extract article using dom_smoothie let mut readability = Readability::new(html, None, None)?; let article = readability.parse()?; // Get the cleaned HTML content as a string let cleaned_html = article.content.to_string(); // Convert cleaned HTML to plain text // Use large width to avoid hard-wrapping - let the UI handle text wrapping let text = from_read(cleaned_html.as_bytes(), 1000); // Create formatted article with title let title = article.title; let formatted = format!( "{}\n{}\n\n{}", title, "=".repeat(title.len()), text.trim() ); Ok(formatted) }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/api.rs
src/api.rs
use anyhow::{Context, Result}; use quick_xml::events::Event; use quick_xml::Reader; use std::time::Duration; use crate::app::NewsStory; use crate::cache::Cache; fn create_http_client() -> Result<reqwest::blocking::Client> { reqwest::blocking::Client::builder() .user_agent("Mozilla/5.0 (Linux; Android 10; SM-A307G) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36") .timeout(Duration::from_secs(10)) .build() .context("Failed to create HTTP client") } pub fn fetch_stories(feed_url: &str) -> Result<Vec<NewsStory>> { fetch_stories_with_cache(feed_url, false) } pub fn fetch_stories_with_cache(feed_url: &str, force_offline: bool) -> Result<Vec<NewsStory>> { let cache = Cache::new().ok(); // Try to load from cache first (if not expired) if let Some(ref cache) = cache { if let Some(cached_stories) = cache.load_feed(feed_url) { return Ok(cached_stories); } } // Try to fetch from network let stories_result = if !force_offline { fetch_from_network(feed_url) } else { Err(anyhow::anyhow!("Offline mode - skipping network fetch")) }; match stories_result { Ok(stories) => { // Save to cache on successful fetch if let Some(ref cache) = cache { let _ = cache.save_feed(feed_url, &stories); } Ok(stories) } Err(e) => { // Network failed, try to load from cache (even if expired) if let Some(ref cache) = cache { if let Some(cached_stories) = cache.load_feed_offline(feed_url) { return Ok(cached_stories); } } Err(e) } } } fn fetch_from_network(feed_url: &str) -> Result<Vec<NewsStory>> { let client = create_http_client()?; let response = client .get(feed_url) .send() .context("Failed to fetch BBC RSS feed")? .text() .context("Failed to read response text")?; parse_rss(&response) } fn parse_rss(xml_content: &str) -> Result<Vec<NewsStory>> { let mut reader = Reader::from_str(xml_content); reader.config_mut().trim_text(true); let mut stories = Vec::new(); let mut buf = Vec::new(); let mut in_item = false; let mut current_story = NewsStory { title: String::new(), description: String::new(), link: String::new(), pub_date: String::new(), category: String::new(), image_url: None, }; let mut current_tag = String::new(); loop { match reader.read_event_into(&mut buf) { Ok(Event::Start(e)) => { let tag_name = String::from_utf8_lossy(e.name().as_ref()).to_string(); if tag_name == "item" { in_item = true; current_story = NewsStory { title: String::new(), description: String::new(), link: String::new(), pub_date: String::new(), category: String::from("News"), image_url: None, }; } else if in_item { // Handle media:thumbnail tag to extract image URL if tag_name == "media:thumbnail" || tag_name == "media:content" { // Extract url attribute if let Some(url_attr) = e.attributes() .filter_map(|a| a.ok()) .find(|attr| { let key = String::from_utf8_lossy(attr.key.as_ref()); key == "url" }) { if let Ok(url_value) = url_attr.unescape_value() { current_story.image_url = Some(url_value.to_string()); } } } current_tag = tag_name; } } Ok(Event::Text(e)) => { if in_item { let text = e.unescape().unwrap_or_default().to_string(); match current_tag.as_str() { "title" => current_story.title = text, "description" => current_story.description = text, "link" => current_story.link = text, "pubDate" => current_story.pub_date = format_date(&text), "category" => current_story.category = text, _ => {} } } } Ok(Event::CData(e)) => { if in_item { let text = String::from_utf8_lossy(&e.into_inner()).to_string(); match current_tag.as_str() { "title" => current_story.title = text, "description" => current_story.description = text, "link" => current_story.link = text, "pubDate" => current_story.pub_date = format_date(&text), "category" => current_story.category = text, _ => {} } } } Ok(Event::Empty(e)) => { // Handle self-closing tags like <media:thumbnail ... /> let tag_name = String::from_utf8_lossy(e.name().as_ref()).to_string(); if in_item && (tag_name == "media:thumbnail" || tag_name == "media:content") { // Extract url attribute if let Some(url_attr) = e.attributes() .filter_map(|a| a.ok()) .find(|attr| { let key = String::from_utf8_lossy(attr.key.as_ref()); key == "url" }) { if let Ok(url_value) = url_attr.unescape_value() { current_story.image_url = Some(url_value.to_string()); } } } } Ok(Event::End(e)) => { let tag_name = String::from_utf8_lossy(e.name().as_ref()).to_string(); if tag_name == "item" { in_item = false; if !current_story.title.is_empty() { stories.push(current_story.clone()); } } else if in_item { current_tag.clear(); } } Ok(Event::Eof) => break, Err(e) => return Err(anyhow::anyhow!("Error parsing XML at position {}: {:?}", reader.buffer_position(), e)), _ => {} } buf.clear(); } Ok(stories.into_iter().take(30).collect()) } fn format_date(date_str: &str) -> String { use chrono::DateTime; // BBC RSS dates are in RFC 2822 format (e.g., "Wed, 03 Feb 2015 15:58:15 GMT") // Convert to "YYYY-MM-DD HH:MM:SS" format if let Ok(dt) = DateTime::parse_from_rfc2822(date_str) { dt.format("%Y-%m-%d %H:%M:%S").to_string() } else { date_str.to_string() } }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/image_cache.rs
src/image_cache.rs
use image::{DynamicImage, ImageReader, Rgba, RgbaImage}; use std::collections::HashMap; use std::io::Cursor; use std::sync::{Arc, Mutex}; /// Simple in-memory image cache pub struct ImageCache { cache: HashMap<String, DynamicImage>, max_size: usize, } impl ImageCache { pub fn new() -> Self { Self { cache: HashMap::new(), max_size: 50, // Keep up to 50 images in cache } } /// Get image from cache or download it pub fn get_or_load(&mut self, url: &str) -> DynamicImage { // Check cache first if let Some(img) = self.cache.get(url) { return img.clone(); } // Try to download match Self::download_image(url) { Ok(img) => { // Add to cache (simple, no LRU for now) if self.cache.len() >= self.max_size { // Clear cache if too large (simple strategy) self.cache.clear(); } self.cache.insert(url.to_string(), img.clone()); img } Err(_) => { // Return BBC logo placeholder on error Self::create_bbc_logo() } } } /// Download image from URL fn download_image(url: &str) -> anyhow::Result<DynamicImage> { // Use BBC-compatible user agent and timeout let client = reqwest::blocking::Client::builder() .user_agent("Mozilla/5.0 (Linux; Android 10; SM-A307G) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36") .timeout(std::time::Duration::from_secs(15)) .build()?; let response = client.get(url).send()?; let bytes = response.bytes()?; let img = ImageReader::new(Cursor::new(bytes)) .with_guessed_format()? .decode()?; Ok(img) } /// Create BBC logo placeholder (red rectangle with white BBC text effect) pub fn create_bbc_logo() -> DynamicImage { let width = 240; let height = 135; let mut img = RgbaImage::new(width, height); // BBC red background let bbc_red = Rgba([234, 68, 57, 255]); // Fill with red for pixel in img.pixels_mut() { *pixel = bbc_red; } // Create simple BBC text pattern (simplified blocks) // This creates a minimalist "BBC" appearance let white = Rgba([255, 255, 255, 255]); // Draw simplified "BBC" blocks in center let center_x = width / 2; let center_y = height / 2; let block_width = 15; let block_height = 30; let spacing = 5; // B (left) let x1 = center_x - block_width * 2 - spacing * 2; draw_rect(&mut img, x1, center_y - block_height / 2, block_width, block_height, white); // B (middle) let x2 = center_x - block_width - spacing; draw_rect(&mut img, x2, center_y - block_height / 2, block_width, block_height, white); // C (right) let x3 = center_x + spacing; draw_rect(&mut img, x3, center_y - block_height / 2, block_width, block_height, white); DynamicImage::ImageRgba8(img) } /// Clear the cache pub fn clear(&mut self) { self.cache.clear(); } } // Helper to draw a rectangle fn draw_rect(img: &mut RgbaImage, x: u32, y: u32, width: u32, height: u32, color: Rgba<u8>) { for dy in 0..height { for dx in 0..width { let px = x + dx; let py = y + dy; if px < img.width() && py < img.height() { img.put_pixel(px, py, color); } } } } // Global cache instance using lazy_static lazy_static::lazy_static! { pub static ref GLOBAL_IMAGE_CACHE: Arc<Mutex<ImageCache>> = Arc::new(Mutex::new(ImageCache::new())); } /// Get image from global cache pub fn get_image(url: Option<&str>) -> DynamicImage { match url { Some(url_str) => { let mut cache = GLOBAL_IMAGE_CACHE.lock().unwrap(); cache.get_or_load(url_str) } None => { ImageCache::create_bbc_logo() } } }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/ui.rs
src/ui.rs
use ratatui::{ layout::{Alignment, Constraint, Direction, Layout, Rect}, style::{Color, Modifier, Style}, text::{Line, Span}, widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Clear}, Frame, }; use ratatui_image::{picker::Picker, StatefulImage}; use crate::app::{App, AppMode, ImageProtocol}; use crate::date_utils::humanize_time; use crate::feeds::get_all_feeds; use crate::image_cache::get_image; use ratatui_image::picker::ProtocolType; pub fn render(f: &mut Frame, app: &App) { let main_chunks = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(3), // Header Constraint::Min(0), // Main content Constraint::Length(1), // Footer (no border) ]) .split(f.area()); render_header(f, main_chunks[0], app); // Full article view takes over the entire content area (full width) if app.show_full_article { render_full_article(f, main_chunks[1], app); } else if app.show_preview { // Split main content area if preview is enabled (but not full article) let content_chunks = Layout::default() .direction(Direction::Horizontal) .constraints([ Constraint::Percentage(80), // Story list Constraint::Percentage(20), // Preview ]) .split(main_chunks[1]); render_stories(f, content_chunks[0], app); render_preview(f, content_chunks[1], app); } else { render_stories(f, main_chunks[1], app); } render_footer(f, main_chunks[2], app); // Render feed menu overlay if in feed menu mode if app.mode == AppMode::FeedMenu { render_feed_menu(f, app); } // Render help menu overlay if in help mode if app.mode == AppMode::Help { render_help_menu(f, app); } } fn render_header(f: &mut Frame, area: Rect, app: &App) { let last_updated = if !app.stories.is_empty() { let date_str = app.stories.first().map(|s| s.pub_date.as_str()).unwrap_or(""); let formatted_date = if app.humanize_dates { humanize_time(date_str) } else { date_str.to_string() }; format!("Last updated: {} | {}", formatted_date, app.current_feed.name) } else { format!("Last updated: -- | {}", app.current_feed.name) }; // Add offline indicator if in offline mode let title_text = if app.is_offline { "BBC | NEWS [OFFLINE]" } else { "BBC | NEWS" }; let header_text = vec![ Line::from( Span::styled( title_text, Style::default().fg(app.theme.accent_fg).add_modifier(Modifier::BOLD) ) ), Line::from( Span::styled( last_updated, Style::default().fg(app.theme.accent_fg) ) ), ]; let header = Paragraph::new(header_text) .alignment(Alignment::Center) .block(Block::default() .borders(Borders::NONE) .style(Style::default().bg(app.theme.accent))); f.render_widget(header, area); } fn render_stories(f: &mut Frame, area: Rect, app: &App) { if app.is_loading { let loading = Paragraph::new("Loading BBC News...") .style(Style::default().fg(app.theme.fg_primary).bg(app.theme.bg_primary)) .alignment(Alignment::Center); f.render_widget(loading, area); return; } // Show error message if present if let Some(ref error_msg) = app.error_message { let error_text = vec![ Line::from(Span::styled("Error fetching BBC News:", Style::default().fg(Color::Red).bg(app.theme.bg_primary).add_modifier(Modifier::BOLD))), Line::from(""), Line::from(Span::styled(error_msg, Style::default().fg(app.theme.fg_primary).bg(app.theme.bg_primary))), Line::from(""), Line::from(Span::styled("Press 'r' to retry", Style::default().fg(app.theme.fg_secondary).bg(app.theme.bg_primary))), ]; let error = Paragraph::new(error_text) .style(Style::default().bg(app.theme.bg_primary)) .alignment(Alignment::Center); f.render_widget(error, area); return; } if app.stories.is_empty() { let empty = Paragraph::new("No stories available. Press 'r' to refresh.") .style(Style::default().fg(Color::Red).bg(app.theme.bg_primary)) .alignment(Alignment::Center); f.render_widget(empty, area); return; } let items: Vec<ListItem> = app .stories .iter() .enumerate() .map(|(i, story)| { let is_selected = i == app.selected; let number = i + 1; let title_text = format!("{}. {}", number, story.title); // Pad title to full width for full-width background, truncate if too long let width = area.width as usize; let padded_title = if title_text.len() < width { format!("{}{}", title_text, " ".repeat(width - title_text.len())) } else { // Truncate and add ellipsis let max_len = width.saturating_sub(3); if max_len > 0 { let truncated = title_text.chars().take(max_len).collect::<String>(); format!("{}...", truncated) } else { title_text.chars().take(width).collect::<String>() } }; let title_line = if is_selected { // Selected: white text on accent (BBC red) background (full width) Line::styled( padded_title, Style::default() .fg(app.theme.accent_fg) .bg(app.theme.accent) .add_modifier(Modifier::BOLD) ) } else { // Normal: primary text on primary background Line::styled( padded_title, Style::default() .fg(app.theme.fg_primary) .bg(app.theme.bg_primary) .add_modifier(Modifier::BOLD) ) }; // Metadata line (indented with 3 spaces) - always gray background let formatted_date = if app.humanize_dates { humanize_time(&story.pub_date) } else { story.pub_date.clone() }; let meta_text = format!(" Last updated: {} | {}", formatted_date, app.current_feed.name); let padded_meta = if meta_text.len() < width { format!("{}{}", meta_text, " ".repeat(width - meta_text.len())) } else { // Truncate and add ellipsis let max_len = width.saturating_sub(3); if max_len > 0 { let truncated = meta_text.chars().take(max_len).collect::<String>(); format!("{}...", truncated) } else { meta_text.chars().take(width).collect::<String>() } }; let meta_line = Line::styled( padded_meta, Style::default() .fg(app.theme.fg_secondary) .bg(app.theme.bg_primary) ); ListItem::new(vec![title_line, meta_line]) }) .collect(); let list = List::new(items) .block(Block::default() .borders(Borders::NONE) .style(Style::default().bg(app.theme.bg_primary))); // Create state for scrolling let mut state = ListState::default(); state.select(Some(app.selected)); f.render_stateful_widget(list, area, &mut state); } fn render_footer(f: &mut Frame, area: Rect, app: &App) { use chrono::Local; // Split footer into left and right sections let footer_chunks = Layout::default() .direction(Direction::Horizontal) .constraints([ Constraint::Min(0), // Left: status/ticker Constraint::Length(8), // Right: time (HH:MM:SS) ]) .split(area); // Left side: show refresh status or ticker/keybindings let footer_text = if app.is_refreshing { String::from("Refreshing News...") } else if !app.ticker_stories.is_empty() { let max_ticker_items = 8.min(app.ticker_stories.len()); if app.ticker_index < app.ticker_stories.len() { let story = &app.ticker_stories[app.ticker_index]; format!("[LATEST] {} ({}/{})", story.title, app.ticker_index + 1, max_ticker_items) } else { format!("q: quit | o: open | Tab: preview | f: feeds | s: sort ({}) | t: dates | p: protocol ({}) | r: refresh", app.sort_order.name(), app.image_protocol.name()) } } else { // Show default keybindings help when no ticker stories format!("q: quit | o: open | Tab: preview | f: feeds | s: sort ({}) | t: dates | p: protocol ({}) | r: refresh", app.sort_order.name(), app.image_protocol.name()) }; let footer_left = Paragraph::new(footer_text) .style(Style::default().fg(app.theme.fg_primary).bg(app.theme.bg_accent)) .alignment(Alignment::Left); // Right side: current time with seconds let current_time = Local::now().format("%H:%M:%S").to_string(); let footer_right = Paragraph::new(current_time) .style(Style::default().fg(app.theme.fg_primary).bg(app.theme.bg_accent)) .alignment(Alignment::Right); f.render_widget(footer_left, footer_chunks[0]); f.render_widget(footer_right, footer_chunks[1]); } fn render_full_article(f: &mut Frame, area: Rect, app: &App) { if let Some(_story) = app.stories.get(app.selected) { let article_block = Block::default() .title("Article View (Enter/Tab/Esc to close)") .borders(Borders::ALL) .border_style(Style::default().fg(app.theme.accent)) .style(Style::default().bg(app.theme.bg_primary)); // Get inner area (within borders) let inner_area = article_block.inner(area); f.render_widget(article_block, area); if let Some(article_text) = app.get_current_article_text() { // Create paragraph with full text and let ratatui handle wrapping let article_paragraph = Paragraph::new(article_text.as_str()) .wrap(ratatui::widgets::Wrap { trim: true }) .alignment(Alignment::Left) .style(Style::default().fg(app.theme.fg_primary).bg(app.theme.bg_primary)) .scroll((app.article_scroll_offset as u16, 0)); f.render_widget(article_paragraph, inner_area); } else { // No article content cached - show error message let error_msg = Paragraph::new("No article content available.\nPress Tab or Esc to return to preview.") .style(Style::default().fg(Color::Red).bg(app.theme.bg_primary)) .alignment(Alignment::Center) .wrap(ratatui::widgets::Wrap { trim: true }); f.render_widget(error_msg, inner_area); } } } fn render_preview(f: &mut Frame, area: Rect, app: &App) { if let Some(story) = app.stories.get(app.selected) { // Choose title based on loading state let title = if app.is_fetching_article { "Loading Article..." } else { "Preview (Tab/Enter for article)" }; let preview_block = Block::default() .title(title) .borders(Borders::ALL) .border_style(Style::default().fg(app.theme.accent)) .style(Style::default().bg(app.theme.bg_primary)); // Get inner area (within borders) let inner_area = preview_block.inner(area); f.render_widget(preview_block, area); // LOADING STATE: Show loading message if app.is_fetching_article { let loading_msg = Paragraph::new("Fetching article...\nThis may take a few seconds.") .style(Style::default().fg(app.theme.fg_secondary).bg(app.theme.bg_primary)) .alignment(Alignment::Center) .wrap(ratatui::widgets::Wrap { trim: true }); f.render_widget(loading_msg, inner_area); return; } // Check if area is too small for preview let min_width = 20; let min_height = 6; if area.width < min_width || area.height < min_height { // Too small - show message instead let msg = Paragraph::new("Terminal too small for preview") .style(Style::default().fg(app.theme.fg_secondary).bg(app.theme.bg_primary)) .alignment(Alignment::Center) .wrap(ratatui::widgets::Wrap { trim: true }); f.render_widget(msg, inner_area); return; } // Split into image area and text area let chunks = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Percentage(40), // Image area Constraint::Percentage(60), // Text area ]) .split(inner_area); // Render image let img = get_image(story.image_url.as_deref()); // Get image area for rendering let image_area = chunks[0]; // Create picker and configure protocol let mut picker = Picker::new((8, 12)); // Set protocol based on user preference match app.image_protocol { ImageProtocol::Auto => { picker.guess_protocol(); }, ImageProtocol::Halfblocks => { picker.protocol_type = ProtocolType::Halfblocks; }, ImageProtocol::Sixel => { picker.protocol_type = ProtocolType::Sixel; }, ImageProtocol::Kitty => { picker.protocol_type = ProtocolType::Kitty; }, } // Calculate target pixel dimensions based on widget area and font size // This ensures the image fits within the allocated space while maintaining aspect ratio let font_size = picker.font_size; let target_width = (image_area.width as u32 * font_size.0 as u32) as u32; let target_height = (image_area.height as u32 * font_size.1 as u32) as u32; // Resize image to fit within the widget area while maintaining aspect ratio let resized_img = img.resize(target_width, target_height, image::imageops::FilterType::Triangle); // Create protocol from resized image let mut dyn_img = picker.new_resize_protocol(resized_img); let image_widget = StatefulImage::new(None); f.render_stateful_widget(image_widget, image_area, &mut dyn_img); // Create text content let mut preview_lines = vec![ Line::from(Span::styled( &story.title, Style::default() .fg(app.theme.fg_primary) .add_modifier(Modifier::BOLD) )), Line::from(""), ]; // Add description if !story.description.is_empty() { preview_lines.push(Line::from(Span::styled( &story.description, Style::default().fg(app.theme.fg_primary) ))); preview_lines.push(Line::from("")); } // Add metadata let formatted_date = if app.humanize_dates { humanize_time(&story.pub_date) } else { story.pub_date.clone() }; preview_lines.push(Line::from(Span::styled( format!("Published: {}", formatted_date), Style::default().fg(app.theme.fg_secondary) ))); preview_lines.push(Line::from(Span::styled( format!("Feed: {}", app.current_feed.name), Style::default().fg(app.theme.fg_secondary) ))); let preview_text = Paragraph::new(preview_lines) .wrap(ratatui::widgets::Wrap { trim: true }) .alignment(Alignment::Left) .style(Style::default().bg(app.theme.bg_primary)); f.render_widget(preview_text, chunks[1]); } } fn render_feed_menu(f: &mut Frame, app: &App) { let feeds = get_all_feeds(); // Create centered popup let area = f.area(); let popup_width = 60.min(area.width - 4); let popup_height = (feeds.len() as u16 + 4).min(area.height - 4); let popup_area = Rect { x: (area.width.saturating_sub(popup_width)) / 2, y: (area.height.saturating_sub(popup_height)) / 2, width: popup_width, height: popup_height, }; // Clear the area f.render_widget(Clear, popup_area); // Create feed items let items: Vec<ListItem> = feeds .iter() .enumerate() .map(|(i, feed)| { let is_selected = i == app.feed_menu_selected; let is_current = feed.name == app.current_feed.name; let indicator = if is_current { "✓ " } else { " " }; let text = format!("{}{}", indicator, feed.name); let style = if is_selected { Style::default() .fg(app.theme.accent_fg) .bg(app.theme.accent) .add_modifier(Modifier::BOLD) } else { Style::default() .fg(app.theme.fg_primary) .bg(app.theme.bg_primary) }; ListItem::new(Line::styled(text, style)) }) .collect(); let list = List::new(items) .block(Block::default() .title("Select Feed (f/Esc to close, Enter to select)") .borders(Borders::ALL) .border_style(Style::default().fg(app.theme.accent)) .style(Style::default().bg(app.theme.bg_primary))); let mut state = ListState::default(); state.select(Some(app.feed_menu_selected)); f.render_stateful_widget(list, popup_area, &mut state); } fn render_help_menu(f: &mut Frame, app: &App) { // Create centered popup let area = f.area(); let popup_width = 70.min(area.width - 4); let popup_height = 22.min(area.height - 4); // Enough for all help items + padding let popup_area = Rect { x: (area.width.saturating_sub(popup_width)) / 2, y: (area.height.saturating_sub(popup_height)) / 2, width: popup_width, height: popup_height, }; // Clear the area f.render_widget(Clear, popup_area); // Create help content let help_text = vec![ Line::from(Span::styled( "Navigation", Style::default().fg(app.theme.accent).add_modifier(Modifier::BOLD) )), Line::from(Span::styled( " j / ↓ Scroll down", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " k / ↑ Scroll up", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " G Jump to bottom", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " l Jump to top", Style::default().fg(app.theme.fg_primary) )), Line::from(""), Line::from(Span::styled( "Actions", Style::default().fg(app.theme.accent).add_modifier(Modifier::BOLD) )), Line::from(Span::styled( " o Open article in browser", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " O Open in new tab", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " Space Jump to ticker article", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " r Refresh news feed", Style::default().fg(app.theme.fg_primary) )), Line::from(""), Line::from(Span::styled( "Views", Style::default().fg(app.theme.accent).add_modifier(Modifier::BOLD) )), Line::from(Span::styled( " Tab Toggle preview pane", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " a / Enter Open article view", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " f Open feed selector", Style::default().fg(app.theme.fg_primary) )), Line::from(""), Line::from(Span::styled( "Settings", Style::default().fg(app.theme.accent).add_modifier(Modifier::BOLD) )), Line::from(Span::styled( " s Cycle sort order", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " t Toggle date format", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " T Cycle theme (light/dark)", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " p Cycle image protocol", Style::default().fg(app.theme.fg_primary) )), Line::from(""), Line::from(Span::styled( "Other", Style::default().fg(app.theme.accent).add_modifier(Modifier::BOLD) )), Line::from(Span::styled( " q / Esc Quit", Style::default().fg(app.theme.fg_primary) )), Line::from(Span::styled( " ? Toggle this help menu", Style::default().fg(app.theme.fg_primary) )), ]; let help_paragraph = Paragraph::new(help_text) .block(Block::default() .title("Help (? or Esc to close)") .borders(Borders::ALL) .border_style(Style::default().fg(app.theme.accent)) .style(Style::default().bg(app.theme.bg_primary))) .alignment(Alignment::Left); f.render_widget(help_paragraph, popup_area); }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/main.rs
src/main.rs
use bbc_news_cli::{app, api, cli, config, events, theme, ui}; use anyhow::Result; use clap::Parser; use crossterm::{ execute, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, }; use ratatui::{backend::CrosstermBackend, Terminal}; use std::io; use app::App; fn main() -> Result<()> { // Parse CLI arguments let cli_args = cli::Cli::parse(); // If any subcommand is provided, run CLI mode if cli_args.command.is_some() || cli_args.feed.is_some() { return cli::run_cli(cli_args); } // Otherwise, launch TUI run_tui() } fn run_tui() -> Result<()> { // Load configuration let config = config::load_config().unwrap_or_default(); // Get theme from config let theme = theme::Theme::from_name(&config.theme); // Setup terminal enable_raw_mode()?; let mut stdout = io::stdout(); execute!(stdout, EnterAlternateScreen)?; let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; // Create app state with theme let mut app = App::new(theme); // Fetch initial data (both ticker and main feed) if let Err(e) = fetch_ticker_data(&mut app) { app.set_error(format!("{:#}", e)); } if let Err(e) = fetch_data(&mut app) { app.set_error(format!("{:#}", e)); } // Run the app let result = run_app(&mut terminal, &mut app, &config); // Restore terminal disable_raw_mode()?; execute!(terminal.backend_mut(), LeaveAlternateScreen)?; terminal.show_cursor()?; if let Err(err) = result { eprintln!("Error: {}", err); } Ok(()) } fn run_app( terminal: &mut Terminal<CrosstermBackend<io::Stdout>>, app: &mut App, config: &config::Config, ) -> Result<()> { // Initial draw terminal.draw(|f| ui::render(f, app))?; loop { // Track state before event handling to detect changes let prev_selected = app.selected; let prev_mode = app.mode.clone(); let prev_preview = app.show_preview; let prev_protocol = app.image_protocol.clone(); let prev_ticker_index = app.ticker_index; let prev_loading = app.is_loading; let prev_refreshing = app.is_refreshing; let prev_humanize_dates = app.humanize_dates; let prev_feed_menu_selected = app.feed_menu_selected; let prev_show_full_article = app.show_full_article; let prev_article_scroll = app.article_scroll_offset; let prev_is_fetching_article = app.is_fetching_article; let prev_sort_order = app.sort_order.clone(); let prev_offline = app.is_offline; // Check for auto-refresh (every 5 minutes) let mut action = events::handle_events(app, config)?; if app.check_auto_refresh() && matches!(action, events::AppAction::None) { action = events::AppAction::Refresh; } match action { events::AppAction::Refresh => { // Keep stories visible during refresh (no loading placeholder) app.is_refreshing = true; app.clear_error(); // Redraw to show "Refreshing News..." message terminal.draw(|f| ui::render(f, app))?; // Refresh both ticker and current feed if let Err(e) = fetch_ticker_data(app) { app.set_error(format!("{:#}", e)); } if let Err(e) = fetch_data(app) { app.set_error(format!("{:#}", e)); } app.mark_refreshed(); } events::AppAction::FeedChanged => { app.is_loading = true; app.is_refreshing = true; app.clear_error(); // Redraw to show "Refreshing News..." message terminal.draw(|f| ui::render(f, app))?; // Only fetch new feed, keep ticker as-is if let Err(e) = fetch_data(app) { app.set_error(format!("{:#}", e)); } } events::AppAction::Resize => { // No special handling needed, redraw will be triggered below } events::AppAction::None => {} } // Update ticker rotation and check if clock should update let clock_tick = app.tick(); // Only redraw if something actually changed let should_redraw = prev_selected != app.selected || prev_mode != app.mode || prev_preview != app.show_preview || prev_protocol != app.image_protocol || prev_ticker_index != app.ticker_index || prev_loading != app.is_loading || prev_refreshing != app.is_refreshing || prev_humanize_dates != app.humanize_dates || prev_feed_menu_selected != app.feed_menu_selected || prev_show_full_article != app.show_full_article || prev_article_scroll != app.article_scroll_offset || prev_is_fetching_article != app.is_fetching_article || prev_sort_order != app.sort_order || prev_offline != app.is_offline || clock_tick // Redraw when clock ticks (approximately every second) || matches!(action, events::AppAction::Refresh | events::AppAction::FeedChanged | events::AppAction::Resize); if should_redraw { terminal.draw(|f| ui::render(f, app))?; } if app.should_quit { break; } } Ok(()) } fn fetch_data(app: &mut App) -> Result<()> { // Fetch stories from current feed with cache support let feed_url = &app.current_feed.url; // First try network fetch directly match api::fetch_stories(feed_url) { Ok(stories) => { // Network is available app.is_offline = false; app.update_stories(stories); Ok(()) } Err(e) => { // Network failed, try to use cache let cache = bbc_news_cli::cache::Cache::new().ok(); if let Some(ref cache) = cache { if let Some(cached_stories) = cache.load_feed_offline(feed_url) { // We have cached data - we're offline app.is_offline = true; app.update_stories(cached_stories); return Ok(()); } } // No cache available either Err(e) } } } fn fetch_ticker_data(app: &mut App) -> Result<()> { // Always fetch Top Stories for ticker const TOP_STORIES_URL: &str = "https://feeds.bbci.co.uk/news/rss.xml"; // Try network first, fall back to cache if offline match api::fetch_stories(TOP_STORIES_URL) { Ok(ticker_stories) => { app.update_ticker_stories(ticker_stories); Ok(()) } Err(e) => { // Network failed, try to use cache let cache = bbc_news_cli::cache::Cache::new().ok(); if let Some(ref cache) = cache { if let Some(cached_stories) = cache.load_feed_offline(TOP_STORIES_URL) { app.update_ticker_stories(cached_stories); return Ok(()); } } // No cache available either Err(e) } } }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/events.rs
src/events.rs
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind}; use std::time::Duration; use crate::app::{App, AppMode}; use crate::config::Config; use crate::feeds::get_all_feeds; pub enum AppAction { None, Refresh, FeedChanged, Resize, } pub fn handle_events(app: &mut App, config: &Config) -> anyhow::Result<AppAction> { if event::poll(Duration::from_millis(100))? { match event::read()? { Event::Key(key) if key.kind == KeyEventKind::Press => { return handle_key_event(app, key, config); } Event::Resize(_, _) => { return Ok(AppAction::Resize); } _ => {} } } Ok(AppAction::None) } fn handle_key_event(app: &mut App, key: KeyEvent, config: &Config) -> anyhow::Result<AppAction> { let kb = &config.keybindings; // Handle help menu mode separately if app.mode == AppMode::Help { match key.code { KeyCode::Char('?') | KeyCode::Esc => app.toggle_help_menu(), _ => {} } return Ok(AppAction::None); } // Handle feed menu mode separately if app.mode == AppMode::FeedMenu { match key.code { KeyCode::Char('j') | KeyCode::Down => { let feeds = get_all_feeds(); app.feed_menu_next(feeds.len()); } KeyCode::Char('k') | KeyCode::Up => app.feed_menu_previous(), KeyCode::Enter => { let feeds = get_all_feeds(); if let Some(feed) = feeds.get(app.feed_menu_selected) { app.select_feed(feed.clone()); return Ok(AppAction::FeedChanged); } } KeyCode::Char('f') | KeyCode::Esc => app.toggle_feed_menu(), _ => {} } return Ok(AppAction::None); } // ARTICLE VIEW MODE: Handle scrolling within article if app.show_full_article { match key.code { KeyCode::Up | KeyCode::Char('k') => app.scroll_article_up(), KeyCode::Down | KeyCode::Char('j') => app.scroll_article_down(), KeyCode::Char(c) if c == kb.open => app.open_selected()?, KeyCode::Enter | KeyCode::Tab | KeyCode::Esc => app.toggle_article_view(), _ => {} } return Ok(AppAction::None); } // PREVIEW PANE PROTECTION: Block scrolling keys when preview is open // This prevents Ghostty event buffering catastrophe (scroll storm detection is backup) if app.show_preview && !app.show_full_article { let is_scroll_key = matches!( key.code, KeyCode::Down | KeyCode::Up ) || matches!( key.code, KeyCode::Char(c) if c == kb.scroll_down || c == kb.scroll_up || c == kb.scroll_bottom || c == kb.latest ); if is_scroll_key { // Drain all buffered scroll events to prevent delay when Tab is pressed // This prevents 5+ second delays when keys were held down while event::poll(Duration::ZERO)? { if let Event::Key(next_key) = event::read()? { if next_key.kind == KeyEventKind::Press { // Check if this is also a scroll key let is_next_scroll = matches!( next_key.code, KeyCode::Down | KeyCode::Up ) || matches!( next_key.code, KeyCode::Char(c) if c == kb.scroll_down || c == kb.scroll_up || c == kb.scroll_bottom || c == kb.latest ); if !is_next_scroll { // Found a non-scroll key (like Tab!), process it immediately return handle_key_event(app, next_key, config); } // Otherwise it's another scroll key, discard and continue draining } } } // All buffered scroll events drained, return return Ok(AppAction::None); } } // Normal mode key handling match key.code { KeyCode::Char(c) if c == kb.quit => app.quit(), KeyCode::Char(c) if c == kb.scroll_down => app.next(), KeyCode::Char(c) if c == kb.scroll_up => app.previous(), KeyCode::Char(c) if c == kb.scroll_bottom => app.scroll_to_bottom(), KeyCode::Char(c) if c == kb.open => app.open_selected()?, KeyCode::Char(c) if c == kb.open_new_tab => app.open_selected_new_tab()?, KeyCode::Char(c) if c == kb.latest => app.scroll_to_top(), KeyCode::Char(c) if c == kb.refresh => return Ok(AppAction::Refresh), KeyCode::Char('f') => app.toggle_feed_menu(), KeyCode::Char('s') => app.cycle_sort_order(), KeyCode::Char('t') => app.toggle_date_format(), KeyCode::Char('T') => app.cycle_theme(), KeyCode::Char('p') => app.cycle_image_protocol(), KeyCode::Char('?') => app.toggle_help_menu(), KeyCode::Char('a') => app.fetch_and_show_article(), KeyCode::Char(' ') => { // Jump to current ticker article if app.jump_to_ticker_article() { return Ok(AppAction::FeedChanged); } } KeyCode::Tab => app.toggle_preview(), KeyCode::Enter => app.fetch_and_show_article(), // Also support arrow keys KeyCode::Down => app.next(), KeyCode::Up => app.previous(), KeyCode::Esc => app.quit(), _ => {} } Ok(AppAction::None) }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/cache.rs
src/cache.rs
use anyhow::Result; use serde::{Deserialize, Serialize}; use std::fs; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; use crate::app::NewsStory; const CACHE_EXPIRY_SECS: u64 = 900; // 15 minutes #[derive(Serialize, Deserialize)] struct CachedFeed { stories: Vec<NewsStory>, timestamp: u64, feed_url: String, } #[derive(Serialize, Deserialize)] struct CachedArticle { content: String, timestamp: u64, url: String, } pub struct Cache { cache_dir: PathBuf, } impl Cache { pub fn new() -> Result<Self> { // Use ~/.bbcli/cache for consistency with config location let home = dirs::home_dir() .ok_or_else(|| anyhow::anyhow!("Could not determine home directory"))?; let cache_dir = home.join(".bbcli").join("cache"); // Create cache directory if it doesn't exist fs::create_dir_all(&cache_dir)?; Ok(Cache { cache_dir }) } /// Get current Unix timestamp fn current_timestamp() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs() } /// Get cache file path for a feed fn feed_cache_path(&self, feed_url: &str) -> PathBuf { let hash = Self::hash_string(feed_url); self.cache_dir.join(format!("feed_{}.bin", hash)) } /// Get cache file path for an article fn article_cache_path(&self, article_url: &str) -> PathBuf { let hash = Self::hash_string(article_url); self.cache_dir.join(format!("article_{}.bin", hash)) } /// Simple hash function for URLs fn hash_string(s: &str) -> String { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; let mut hasher = DefaultHasher::new(); s.hash(&mut hasher); format!("{:x}", hasher.finish()) } /// Save feed to cache pub fn save_feed(&self, feed_url: &str, stories: &[NewsStory]) -> Result<()> { let cached_feed = CachedFeed { stories: stories.to_vec(), timestamp: Self::current_timestamp(), feed_url: feed_url.to_string(), }; let path = self.feed_cache_path(feed_url); let encoded = bincode::serialize(&cached_feed)?; fs::write(path, encoded)?; Ok(()) } /// Load feed from cache if not expired pub fn load_feed(&self, feed_url: &str) -> Option<Vec<NewsStory>> { let path = self.feed_cache_path(feed_url); if !path.exists() { return None; } let data = fs::read(&path).ok()?; let cached_feed: CachedFeed = bincode::deserialize(&data).ok()?; // Check if cache is expired let age = Self::current_timestamp() - cached_feed.timestamp; if age > CACHE_EXPIRY_SECS { return None; } Some(cached_feed.stories) } /// Load feed from cache regardless of expiry (for offline mode) pub fn load_feed_offline(&self, feed_url: &str) -> Option<Vec<NewsStory>> { let path = self.feed_cache_path(feed_url); if !path.exists() { return None; } let data = fs::read(&path).ok()?; let cached_feed: CachedFeed = bincode::deserialize(&data).ok()?; Some(cached_feed.stories) } /// Save article content to cache pub fn save_article(&self, article_url: &str, content: &str) -> Result<()> { let cached_article = CachedArticle { content: content.to_string(), timestamp: Self::current_timestamp(), url: article_url.to_string(), }; let path = self.article_cache_path(article_url); let encoded = bincode::serialize(&cached_article)?; fs::write(path, encoded)?; Ok(()) } /// Load article from cache if not expired pub fn load_article(&self, article_url: &str) -> Option<String> { let path = self.article_cache_path(article_url); if !path.exists() { return None; } let data = fs::read(&path).ok()?; let cached_article: CachedArticle = bincode::deserialize(&data).ok()?; // Check if cache is expired (articles cache for longer - 1 hour) let age = Self::current_timestamp() - cached_article.timestamp; if age > 3600 { return None; } Some(cached_article.content) } /// Load article from cache regardless of expiry (for offline mode) pub fn load_article_offline(&self, article_url: &str) -> Option<String> { let path = self.article_cache_path(article_url); if !path.exists() { return None; } let data = fs::read(&path).ok()?; let cached_article: CachedArticle = bincode::deserialize(&data).ok()?; Some(cached_article.content) } /// Get cache age in seconds for a feed pub fn get_feed_age(&self, feed_url: &str) -> Option<u64> { let path = self.feed_cache_path(feed_url); if !path.exists() { return None; } let data = fs::read(&path).ok()?; let cached_feed: CachedFeed = bincode::deserialize(&data).ok()?; Some(Self::current_timestamp() - cached_feed.timestamp) } /// Clear all cache pub fn clear_all(&self) -> Result<()> { if self.cache_dir.exists() { fs::remove_dir_all(&self.cache_dir)?; fs::create_dir_all(&self.cache_dir)?; } Ok(()) } }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false