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
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/disk_selection.rs
crates/ffedit/src/disk_selection.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use anyhow::{anyhow, Error}; use core::fmt; use fluxfox::prelude::*; use std::fmt::Display; /// Track the selection level #[derive(Default, Debug, Copy, Clone, PartialEq, PartialOrd)] pub enum SelectionLevel { #[default] Disk = 0, Head = 1, Cylinder = 2, Sector = 3, } #[derive(Copy, Clone)] pub struct DiskSelection { pub level: SelectionLevel, pub head: Option<u8>, pub cylinder: Option<u16>, pub sector: Option<u8>, } impl Default for DiskSelection { fn default() -> Self { DiskSelection { level: SelectionLevel::Cylinder, head: Some(0), cylinder: Some(0), sector: None, } } } impl Display for DiskSelection { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.level { SelectionLevel::Disk => write!(f, ""), SelectionLevel::Head => write!(f, "[h:{}]", self.head.unwrap_or(0)), SelectionLevel::Cylinder => write!(f, "[h:{} c:{}]", self.head.unwrap_or(0), self.cylinder.unwrap_or(0)), SelectionLevel::Sector => write!( f, "[h:{} c:{} s:{}]", self.head.unwrap_or(0), self.cylinder.unwrap_or(0), self.sector.unwrap_or(0) ), } } } impl DiskSelection { pub(crate) fn level(&self) -> SelectionLevel { self.level } pub(crate) fn into_ch(&self) -> Result<DiskCh, Error> { if self.level < SelectionLevel::Cylinder { return Err(anyhow!("Cylinder not selected")); } let c = self.cylinder.ok_or(anyhow!("No cylinder selected!"))?; let h = self.head.ok_or(anyhow!("No head selected!"))?; Ok(DiskCh::new(c, h)) } pub(crate) fn into_chs(&self) -> Result<DiskChs, Error> { let ch = self.into_ch()?; if self.level < SelectionLevel::Sector { return Err(anyhow!("Sector not selected")); } let s = self.sector.ok_or(anyhow!("No sector selected!"))?; Ok(DiskChs::from((ch, s))) } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/widget.rs
crates/ffedit/src/widget.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::components::metadata_header::MetaDataHeader; use ratatui::widgets::{ScrollbarState, WidgetRef}; pub trait TabSelectableWidget { fn can_select(&self) -> bool; fn select(&mut self); fn deselect(&mut self); } pub trait ScrollableWidget { fn scroll_up(&mut self); fn scroll_down(&mut self); fn page_up(&mut self); fn page_down(&mut self); fn scroll_to_start(&mut self); fn scroll_to_end(&mut self); } pub trait HasMetaDataHeader { fn set_header(&mut self, header: MetaDataHeader); } #[derive(Default)] pub struct WidgetState { pub visible_rows: usize, pub vertical_scroll_state: ScrollbarState, } pub trait FoxWidget: WidgetRef + TabSelectableWidget + ScrollableWidget {}
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/logger.rs
crates/ffedit/src/logger.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::app::AppEvent; use crossbeam_channel::Sender; use log::{Level, Metadata, Record, SetLoggerError}; pub enum LogEntry { Trace(String), Info(String), Debug(String), Warning(String), Error(String), } struct TuiLogger { sender: Sender<AppEvent>, // Add a sender for crossbeam channel. } impl TuiLogger { fn new(sender: Sender<AppEvent>) -> Self { TuiLogger { sender } } } impl log::Log for TuiLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= Level::Debug // Adjust the level as needed } fn log(&self, record: &Record) { let from_ffedit = record.target().starts_with("ffedit"); let message = if from_ffedit { format!("{}", record.args().to_string()) } else { format!("[{}] {}", record.target().to_string(), record.args().to_string()) }; let log = match record.level() { Level::Trace if from_ffedit => LogEntry::Trace(message), Level::Info if from_ffedit => LogEntry::Info(message), Level::Warn => LogEntry::Warning(message), Level::Error => LogEntry::Error(message), Level::Debug if from_ffedit => LogEntry::Debug(message), _ => { // Ignore other log levels from external libraries return; } }; self.sender.send(AppEvent::Log(log)).unwrap(); } fn flush(&self) {} } //static LOGGER: Lazy<TuiLogger> = Lazy::new(TuiLogger::new); pub(crate) fn init_logger(sender: Sender<AppEvent>) -> Result<(), SetLoggerError> { //log::set_logger(&*LOGGER).map(|()| log::set_max_level(log::LevelFilter::Info)) let logger = TuiLogger::new(sender); log::set_boxed_logger(Box::new(logger)) // Set the logger as a boxed trait object. .map(|()| log::set_max_level(log::LevelFilter::Debug)) }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/app_events.rs
crates/ffedit/src/app_events.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::{ app::{App, AppEvent, ApplicationState}, components::history::HistoryEntry, logger::LogEntry, modal::ModalState, util::strip_path, }; impl App { pub(crate) fn handle_app_events(&mut self) { while let Ok(msg) = self.receiver.try_recv() { let mut history = self.history.borrow_mut(); match msg { AppEvent::Log(entry) => match entry { LogEntry::Trace(msg) => { history.push(HistoryEntry::Trace(msg)); } LogEntry::Info(msg) => { history.push(HistoryEntry::Info(msg)); } LogEntry::Debug(msg) => { history.push(HistoryEntry::Debug(msg)); } LogEntry::Warning(msg) => { history.push(HistoryEntry::Warning(msg)); } LogEntry::Error(msg) => { history.push(HistoryEntry::Error(msg)); } }, AppEvent::OpenFileRequest(path) => { self.ctx.load_disk_image(path); } AppEvent::LoadingStatus(progress) => { self.ctx.state = ApplicationState::Modal(ModalState::ProgressBar("Loading Disk Image".to_string(), progress)); } AppEvent::DiskImageLoaded(di, di_name) => { self.ctx.di = Some(di); self.ctx.di_name = Some(strip_path(&di_name)); self.ctx.state = ApplicationState::Normal; // Reset the selection. self.ctx.selection = Default::default(); // Load the data block. match self .ctx .db .borrow_mut() .load(self.ctx.di.as_mut().unwrap(), &self.ctx.selection) { Ok(_) => { history.push(HistoryEntry::CommandResponse(format!( "Loaded disk image: {}", di_name.display() ))); } Err(e) => { history.push(HistoryEntry::Error(format!("Failed to load disk image: {}", e))); } } } AppEvent::DiskImageLoadingFailed(msg) => { self.ctx.state = ApplicationState::Normal; history.push(HistoryEntry::CommandResponse(msg)); } AppEvent::DiskSelectionChanged => { // Depending on selection, we need to read the current track or sector, // and update the data displayed in the data viewer. if let Some(di) = &mut self.ctx.di { _ = self.ctx.db.borrow_mut().load(di, &self.ctx.selection); } } } } } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/app_context.rs
crates/ffedit/src/app_context.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::{ app::{AppEvent, ApplicationState}, components::data_block::DataBlock, disk_selection::DiskSelection, }; use crossbeam_channel::Sender; use fluxfox::DiskImage; use std::{cell::RefCell, path::PathBuf, rc::Rc, sync::Arc}; // Contain mutable data for App // This avoids borrowing issues when passing the mutable context to the command processor pub struct AppContext { pub selection: DiskSelection, pub state: ApplicationState, pub di: Option<DiskImage>, pub di_name: Option<PathBuf>, pub sender: Sender<AppEvent>, pub db: Rc<RefCell<DataBlock>>, } impl AppContext { pub(crate) fn load_disk_image(&mut self, filename: PathBuf) { let outer_sender = self.sender.clone(); let inner_filename = filename.clone(); std::thread::spawn(move || { let inner_sender = outer_sender.clone(); match DiskImage::load_from_file( &inner_filename, None, Some(Arc::new(move |status| match status { fluxfox::LoadingStatus::Progress(progress) => { inner_sender.send(AppEvent::LoadingStatus(progress)).unwrap(); } fluxfox::LoadingStatus::Error => { log::error!("load_disk_image()... Error loading disk image"); inner_sender .send(AppEvent::DiskImageLoadingFailed("Unknown error".to_string())) .unwrap(); } _ => {} })), ) { Ok(di) => { log::debug!("load_disk_image()... Successfully loaded disk image"); outer_sender .send(AppEvent::DiskImageLoaded(di, filename.clone())) .unwrap(); } Err(e) => { log::error!("load_disk_image()... Error loading disk image"); outer_sender .send(AppEvent::DiskImageLoadingFailed(format!("Error: {}", e))) .unwrap(); } } }); } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/util.rs
crates/ffedit/src/util.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use std::path::{Path, PathBuf}; pub(crate) fn strip_path(path: &Path) -> PathBuf { let mut components = path.components().rev(); // Get the last component (file name) let file_name = components.next().expect("Path should have at least one component"); // Try to get the second-to-last component (immediate parent) if let Some(parent) = components.next() { // Reconstruct the path in reverse order PathBuf::from(parent.as_os_str()).join(file_name.as_os_str()) } else { // If no parent is found, fall back to just the file name PathBuf::from(file_name.as_os_str()) } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/layout.rs
crates/ffedit/src/layout.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use ratatui::{layout::Flex, prelude::*}; /// Centers a [`Rect`] within another [`Rect`] using the provided [`Constraint`]s. /// /// # Examples /// /// ```rust /// use ratatui::layout::{Constraint, Rect}; /// /// let area = Rect::new(0, 0, 100, 100); /// let horizontal = Constraint::Percentage(20); /// let vertical = Constraint::Percentage(30); /// /// let centered = center(area, horizontal, vertical); /// ``` #[allow(dead_code)] fn center(area: Rect, horizontal: Constraint, vertical: Constraint) -> Rect { let [area] = Layout::horizontal([horizontal]).flex(Flex::Center).areas(area); let [area] = Layout::vertical([vertical]).flex(Flex::Center).areas(area); area }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/modal.rs
crates/ffedit/src/modal.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ // Modal state for the application pub(crate) enum ModalState { ProgressBar(String, f64), // Title and completion percentage (0.0 to 1.0) } impl ModalState { // Create a new progress bar modal state pub(crate) fn new_progress_bar(title: &str) -> ModalState { ModalState::ProgressBar(title.to_string(), 0.0) } // Update the progress bar completion percentage pub(crate) fn update_progress(&mut self, percentage: f64) { if let ModalState::ProgressBar(_, ref mut p) = self { *p = percentage; } } pub(crate) fn input_enabled(&self) -> bool { match self { ModalState::ProgressBar(_, _) => false, } } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/main.rs
crates/ffedit/src/main.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ // This project is inactive. Disable all lints. #![allow(clippy::all)] mod app; mod app_context; mod app_events; mod cmd_interpreter; mod components; mod disk_selection; mod layout; mod logger; mod modal; mod util; mod widget; use std::{io, path::PathBuf}; use bpaf::{construct, short, OptionParser, Parser}; use crossterm::ExecutableCommand; use app::App; #[allow(dead_code)] #[derive(Debug, Clone)] struct CmdParams { in_filename: Option<PathBuf>, mouse: bool, } /// Set up bpaf argument parsing. fn opts() -> OptionParser<CmdParams> { let in_filename = short('i') .long("in_filename") .help("Filename of image to read") .argument::<PathBuf>("IN_FILE") .optional(); let mouse = short('m').long("switch").help("Enable mouse support").switch(); construct!(CmdParams { in_filename, mouse }).to_options() } fn main() -> io::Result<()> { let opts = opts().run(); let mut terminal = ratatui::init(); if opts.mouse { io::stdout().execute(crossterm::event::EnableMouseCapture).unwrap(); } let mut app = App::new(opts); let app_result = app.run(&mut terminal); ratatui::restore(); app_result }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/components/metadata_header.rs
crates/ffedit/src/components/metadata_header.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use indexmap::IndexMap; use ratatui::{ buffer::Buffer, layout::Rect, prelude::*, style::Style, widgets::{Block, WidgetRef}, }; #[derive(Default)] pub enum MetaDataType { #[default] Track, Sector, } pub enum MetaDataItem { Null, Good(String), Bad(String), } pub struct MetaDataHeader { pub map: IndexMap<String, Vec<MetaDataItem>>, } impl MetaDataHeader { pub fn new(dh_type: MetaDataType) -> MetaDataHeader { match dh_type { MetaDataType::Sector => { let mut map = IndexMap::new(); map.insert("Sector ID".to_string(), Vec::new()); MetaDataHeader { map } } MetaDataType::Track => { let mut map = IndexMap::new(); map.insert("Encoding".to_string(), Vec::new()); map.insert("Bit Length".to_string(), Vec::new()); map.insert("Bitrate".to_string(), Vec::new()); MetaDataHeader { map } } } } pub fn set_key_good(&mut self, key: &str, value: String) { self.map.insert(key.to_string(), vec![MetaDataItem::Good(value)]); } pub fn set_key(&mut self, key: &str, value: MetaDataItem) { self.map.insert(key.to_string(), vec![value]); } pub fn insert_key(&mut self, key: &str, value: MetaDataItem) { self.map.entry(key.to_string()).or_insert_with(Vec::new).push(value); } pub fn rows(&self) -> u16 { self.map.len() as u16 } /// Returns the maximum length of a key name in the metadata header. /// 1 character is included for the colon. pub fn max_key_len(&self) -> usize { self.map.keys().map(|k| k.len() + 1).max().unwrap_or(0) } } impl WidgetRef for MetaDataHeader { fn render_ref(&self, area: Rect, buf: &mut Buffer) { let mut y = area.top(); let style = Style::from((Color::White, Color::DarkGray)); let block = Block::default().style(style); block.render(area, buf); for (key, value) in &self.map { // Set key style to white text on dark blue background let key_style = style; let key_pad = self.max_key_len() - key.len(); let key_str = format!("{}:{:width$}", key, "", width = key_pad); let mut x = area.left() + key_str.len() as u16; buf.set_string(area.left(), y, key_str, key_style); for item in value { match item { MetaDataItem::Null => {} MetaDataItem::Good(s) => { buf.set_string(x, y, s, key_style); x += s.len() as u16; } MetaDataItem::Bad(s) => { buf.set_string(x, y, s, key_style); x += s.len() as u16; } } } y += 1; } } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/components/data_block.rs
crates/ffedit/src/components/data_block.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::disk_selection::{DiskSelection, SelectionLevel}; use crate::{ components::metadata_header::{MetaDataHeader, MetaDataType}, widget::{FoxWidget, ScrollableWidget, TabSelectableWidget, WidgetState}, }; use anyhow::{anyhow, Error}; use fluxfox::prelude::*; use ratatui::{ prelude::*, widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState, WidgetRef}, }; use std::cell::RefCell; #[derive(Clone, Debug)] pub enum DataToken { Padding(u16), HexAddress(u16), DataByte { byte: u8, last: bool, wrapping: bool }, AddressMarker(u8), } #[derive(Default, Copy, Clone, Debug)] pub enum DataBlockType { #[default] Track, Sector, } pub struct DataBlock { pub caption: String, pub block_type: DataBlockType, pub cylinder: u16, pub head: u8, pub sector: Option<u8>, pub columns: usize, pub rows: usize, pub data: Vec<u8>, pub data_context_len: usize, pub formatted_lines: Vec<Vec<DataToken>>, pub visible_rows: usize, pub scroll_offset: usize, pub vertical_scroll_state: ScrollbarState, pub tab_selected: bool, pub data_header: MetaDataHeader, pub ui_state: RefCell<WidgetState>, } impl Default for DataBlock { fn default() -> Self { DataBlock { caption: String::new(), block_type: DataBlockType::Track, cylinder: 0, head: 0, sector: None, columns: 16, rows: 0, data: Vec::new(), data_context_len: 0, formatted_lines: Vec::new(), visible_rows: 0, scroll_offset: 0, vertical_scroll_state: ScrollbarState::default(), tab_selected: false, data_header: MetaDataHeader::new(MetaDataType::Track), ui_state: RefCell::new(WidgetState::default()), } } } impl DataBlock { pub fn load(&mut self, disk: &mut DiskImage, selection: &DiskSelection) -> Result<(), Error> { self.block_type = match selection.level() { SelectionLevel::Cylinder => DataBlockType::Track, SelectionLevel::Sector => DataBlockType::Sector, _ => return Err(anyhow!("Invalid selection level")), }; match self.block_type { DataBlockType::Track => { let ch = selection.into_ch()?; let rtr = disk.read_track(ch, None)?; let ti = disk.track(ch).ok_or(anyhow!("Track not found"))?.info(); log::debug!("load(): read_track() returned {} bytes", rtr.read_buf.len()); if rtr.read_buf.is_empty() { return Err(anyhow!("No data read")); } self.head = ch.h(); self.cylinder = ch.c(); self.sector = None; self.data_header = MetaDataHeader::new(MetaDataType::Track); self.data_header.set_key_good("Encoding", ti.encoding.to_string()); self.data_header.set_key_good("Bit Length", ti.bit_length.to_string()); self.data_header.set_key_good("Bitrate", ti.data_rate.to_string()); self.set_caption(&format!("Track: {}", ch)); self.scroll_offset = 0; log::debug!("first byte of track is {:02X}", rtr.read_buf[0]); self.update_data(rtr.read_buf, rtr.read_len_bytes); } DataBlockType::Sector => { let ch = selection.into_ch()?; let chs = selection.into_chs()?; let rsr = disk.read_sector( ch, DiskChsnQuery::new(chs.c(), chs.h(), chs.s(), None), None, None, RwScope::DataOnly, true, )?; self.head = ch.h(); self.cylinder = ch.c(); self.sector = selection.sector; self.data_header = MetaDataHeader::new(MetaDataType::Sector); self.data_header .set_key_good("Sector ID", rsr.id_chsn.unwrap_or_default().to_string()); self.data_header .set_key_good("Address CRC Valid", (!rsr.address_crc_error).to_string()); self.data_header .set_key_good("Data: CRC Valid", (!rsr.data_crc_error).to_string()); self.set_caption(&format!("Sector: {}", chs)); self.scroll_offset = 0; let read_buf_len = rsr.read_buf.len(); self.update_data(rsr.read_buf, read_buf_len); } } Ok(()) } pub fn set_metadata(&mut self, metadata: MetaDataHeader) { self.data_header = metadata; } //noinspection RsExternalLinter pub fn get_line(&self, index: usize) -> Option<Line> { if index >= self.formatted_lines.len() { return None; } let wrap = match self.block_type { DataBlockType::Track => true, DataBlockType::Sector => false, }; let line_vec = self.formatted_lines.get(index)?; let mut line = Line::default(); let mut byte_count = 0; let mut last_token_wrapped = false; for token in line_vec { match token { DataToken::HexAddress(addr) => { // Use blue style line.spans .push(Span::styled(format!("{:04X}", addr), Style::default().fg(Color::Cyan))); line.spans .push(Span::styled(" |", Style::default().fg(Color::DarkGray))); } DataToken::DataByte { byte, last, wrapping } => { let mut style = Style::default(); style = if *last { style.underlined() } else { style }; style = if *wrapping { style.fg(Color::DarkGray) } else { style }; let mut pad_style = if byte_count == 0 { Style::default() } else { style }; let pad_char = if byte_count > 0 && *wrapping && !last_token_wrapped { pad_style = Style::default(); "|" } else { " " }; line.spans.push(Span::styled(pad_char, pad_style)); line.spans.push(Span::styled(format!("{:02X}", byte), style)); last_token_wrapped = *wrapping; byte_count += 1; } DataToken::Padding(size) => { line.spans .push(Span::styled(" ".repeat((*size + 1) as usize), Style::default())); } DataToken::AddressMarker(byte) => { line.spans.push(Span::styled( format!("{:02X}", byte), Style::default().add_modifier(Modifier::REVERSED), )); } } } // 2nd pass to add DataBytes as ascii representation line.spans .push(Span::styled("| ", Style::default().fg(Color::DarkGray))); for token in line_vec { match token { DataToken::DataByte { byte, .. } => { let ascii_span = if byte.is_ascii_graphic() { Span::styled(format!("{}", *byte as char), Style::default()) } else { Span::styled(".", Style::default().fg(Color::Gray)) }; line.spans.push(ascii_span); } _ => {} } } Some(line) } pub fn set_caption(&mut self, caption: &str) { self.caption = caption.to_string(); } pub fn update_data(&mut self, data: Vec<u8>, data_context_len: usize) { self.data = data; self.data_context_len = data_context_len; self.format(); // Reformat the data when it changes } /// Formats the data into vectors of tokens fn format(&mut self) { let wrap = match self.block_type { DataBlockType::Track => true, DataBlockType::Sector => false, }; self.formatted_lines.clear(); let bytes_per_line = 16; let data_partial_row_len = self.data.len() % bytes_per_line; let dump_partial_row_len = self.data_context_len % bytes_per_line; let data_full_rows = self.data_context_len / bytes_per_line; let data_rows = data_full_rows + if data_partial_row_len > 0 { 1 } else { 0 }; let dump_rows = self.data.len() / bytes_per_line + if dump_partial_row_len > 0 { 1 } else { 0 }; log::debug!( "partial row len: {} last full data row {:04X}", data_partial_row_len, data_full_rows * bytes_per_line ); let mut previous_row = 0; let mut line_iterator = self.data.chunks(bytes_per_line).peekable(); // Format whole lines of data context for (row, chunk) in line_iterator.by_ref().take(data_full_rows).enumerate() { // Format hex address let mut token_vec = Vec::new(); let addr = DataToken::HexAddress((row * bytes_per_line) as u16); token_vec.push(addr); let second_to_last_row = data_partial_row_len > 0 && row == data_full_rows - 1; //let last_row = row == data_even_rows - 1; for (bi, byte) in chunk.iter().enumerate() { // Format data byte let mut mark_last_row = false; if second_to_last_row && bi >= data_partial_row_len { mark_last_row = true; } let data_byte = DataToken::DataByte { byte: *byte, last: mark_last_row, wrapping: false, }; token_vec.push(data_byte); } // if chunk.len() < bytes_per_line { // // Pad the line with spaces // let pad_len = bytes_per_line - chunk.len(); // for _ in 0..pad_len { // token_vec.push(DataToken::Padding(2)); // } // } previous_row = row; self.formatted_lines.push(token_vec); } // Format any remaining partial line of data context if let Some(incomplete_line) = line_iterator.next() { if data_partial_row_len > 0 { let mut token_vec = Vec::new(); let addr = DataToken::HexAddress(((previous_row + 1) * bytes_per_line) as u16); token_vec.push(addr); // Add data bytes for di in 0..data_partial_row_len { token_vec.push(DataToken::DataByte { byte: incomplete_line[di], last: true, wrapping: false, }); } if incomplete_line.len() == bytes_per_line { // Add wrapping bytes to end of line for di in data_partial_row_len..bytes_per_line { if wrap { token_vec.push(DataToken::DataByte { byte: incomplete_line[di], last: false, wrapping: true, }); } else { token_vec.push(DataToken::Padding(2)); } } } self.formatted_lines.push(token_vec); } } // if wrap { // // Draw wrapped full rows // for (wrap_row, chunk) in self.data[wrapping_idx..].chunks(bytes_per_line).enumerate() { // let mut token_vec = Vec::new(); // let addr = DataToken::HexAddress(((last_row + wrap_row + 1) * bytes_per_line) as u16); // // token_vec.push(addr); // for (bi, byte) in chunk.iter().enumerate() { // // Format data byte // let data_byte = DataToken::DataByte { // byte: *byte, // last: false, // wrapping: true, // }; // token_vec.push(data_byte); // } // self.formatted_lines.push(token_vec); // // if wrap_row > 4 { // break; // } // } // } } pub fn required_width(&self) -> u16 { // 4 hex digits + space + pipe + space 7 + // column * (2 hex digits + 1 space) self.columns as u16 * 3 + // space + pipe + space 3 + // column * 1 ASCII char self.columns as u16 } fn render_ref_internal(&self, area: Rect, buf: &mut Buffer) { let mut state = self.ui_state.borrow_mut(); // Render a border around the widget let border_style = if self.tab_selected { Style::default().fg(Color::LightCyan).add_modifier(Modifier::BOLD) } else { Style::default() }; let mut title_line = Line::from(vec![Span::styled("Data Block", Style::default())]); if !self.caption.is_empty() { title_line.push_span(Span::styled(format!(": {}", self.caption), Style::default())); } let block = Block::default() .borders(Borders::ALL) .border_style(border_style) .title(title_line); let inner = block.inner(area); block.render(area, buf); let panel_layout = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Length(self.data_header.rows()), // for metadata header Constraint::Min(1), // for hex display ] .as_ref(), ) .split(inner); // Render the metadata header. self.data_header.render_ref(panel_layout[0], buf); // Calculate the inner area for rendering the hex dump if panel_layout[1].width < self.required_width() || panel_layout[1].height == 0 { return; // Not enough space to render } // Determine the number of visible rows and total rows let total_rows = self.formatted_lines.len(); let visible_rows = panel_layout[1].height as usize; state.visible_rows = visible_rows; // Render the hex dump. let rows_to_render = visible_rows.min(total_rows.saturating_sub(self.scroll_offset)); for i in 0..rows_to_render { let line_index = self.scroll_offset + i; if let Some(line) = self.get_line(line_index) { // Render the line at the appropriate position buf.set_line(panel_layout[1].x, panel_layout[1].y + i as u16, &line, inner.width); } } // let scrollbar_height = (visible_rows as f64 / total_rows as f64 * inner.height as f64).ceil() as u16; // let scrollbar_position = ((self.scroll_offset as f64 / total_rows as f64) // * (inner.height as f64 - scrollbar_height as f64)) // .ceil() as u16; // Update scrollbar content let mut vertical_scroll_state = self .vertical_scroll_state .content_length(total_rows) .position(self.scroll_offset); // Render a scrollbar if needed if total_rows > visible_rows { // Calculate scrollbar size and position // Render a scrollbar using the ScrollBar widget if needed if total_rows > visible_rows { // Create a ScrollBar widget let scrollbar = Scrollbar::default() .orientation(ScrollbarOrientation::VerticalRight) // Vertical on the right side .thumb_symbol("█") .track_style(Style::default().fg(Color::Cyan)) .track_symbol(Some("|")); // Render the scrollbar scrollbar.render(panel_layout[1], buf, &mut vertical_scroll_state); } } } } impl FoxWidget for DataBlock {} impl TabSelectableWidget for DataBlock { fn can_select(&self) -> bool { true } fn select(&mut self) { self.tab_selected = true; } fn deselect(&mut self) { self.tab_selected = false; } } impl ScrollableWidget for DataBlock { fn scroll_up(&mut self) { self.scroll_offset = self.scroll_offset.saturating_sub(1); } fn scroll_down(&mut self) { self.scroll_offset += 1; if self.scroll_offset >= self.formatted_lines.len() { self.scroll_offset = self.formatted_lines.len() - 1; } } fn page_up(&mut self) { let state = self.ui_state.borrow(); self.scroll_offset = self.scroll_offset.saturating_sub(state.visible_rows); } fn page_down(&mut self) { let state = self.ui_state.borrow(); //self.scroll_offset = (self.scroll_offset).min(self.formatted_lines.len() - 1); self.scroll_offset = (self.scroll_offset + state.visible_rows).min(self.formatted_lines.len() - 1); // log::debug!( // "page_down(): scroll_offset: {} visible: {}", // self.scroll_offset, // state.visible_rows // ); } fn scroll_to_start(&mut self) { self.scroll_offset = 0; } fn scroll_to_end(&mut self) { self.scroll_offset = self.formatted_lines.len() - 1; } } impl WidgetRef for &DataBlock { fn render_ref(&self, area: Rect, buf: &mut Buffer) { self.render_ref_internal(area, buf); } } impl WidgetRef for DataBlock { fn render_ref(&self, area: Rect, buf: &mut Buffer) { self.render_ref_internal(area, buf); } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/components/history.rs
crates/ffedit/src/components/history.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::{ logger::LogEntry, widget::{FoxWidget, ScrollableWidget, TabSelectableWidget, WidgetState}, }; use ratatui::{ prelude::*, widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState, WidgetRef}, }; use std::{cell::RefCell, cmp, collections::VecDeque}; // Define an enum for the history entries #[derive(Clone)] pub(crate) enum HistoryEntry { UserCommand(String), CommandResponse(String), Info(String), Trace(String), Debug(String), Warning(String), Error(String), } pub(crate) const MAX_HISTORY: usize = 1000; // Maximum number of history entries pub(crate) struct HistoryWidget { pub(crate) max_len: usize, // Maximum length of the history pub(crate) history: VecDeque<HistoryEntry>, // Store history as Vec<HistoryEntry> pub scroll_offset: usize, pub vertical_scroll_state: ScrollbarState, pub tab_selected: bool, pub ui_state: RefCell<WidgetState>, } impl HistoryWidget { pub fn new(max_len: Option<usize>) -> HistoryWidget { HistoryWidget { max_len: max_len.unwrap_or(MAX_HISTORY), history: VecDeque::with_capacity(max_len.unwrap_or(MAX_HISTORY)), scroll_offset: 0, vertical_scroll_state: ScrollbarState::default(), tab_selected: false, ui_state: RefCell::new(WidgetState::default()), } } pub fn push(&mut self, entry: HistoryEntry) { self.history.push_back(entry); // Push a new entry onto the history if self.history.len() > MAX_HISTORY { _ = self.history.pop_front(); // Remove the oldest entry if the history is too long } self.scroll_to_end(); } pub fn push_user_cmd(&mut self, cmd: &str) { self.push(HistoryEntry::UserCommand(cmd.to_string())); } pub fn push_cmd_response(&mut self, response: &str) { let response_lines = response.split("\n"); for line in response_lines { self.push(HistoryEntry::CommandResponse(line.to_string())); } } pub fn push_log(&mut self, entry: LogEntry) { match entry { LogEntry::Info(msg) => self.push(HistoryEntry::Info(msg)), LogEntry::Trace(msg) => self.push(HistoryEntry::Trace(msg)), LogEntry::Debug(msg) => self.push(HistoryEntry::Debug(msg)), LogEntry::Warning(msg) => self.push(HistoryEntry::Warning(msg)), LogEntry::Error(msg) => self.push(HistoryEntry::Error(msg)), } } fn render_ref_internal(&self, area: Rect, buf: &mut Buffer) { let mut state = self.ui_state.borrow_mut(); // Render a border around the widget let border_style = if self.tab_selected { Style::default().fg(Color::LightCyan).add_modifier(Modifier::BOLD) } else { Style::default() }; // Update scrollbar content let block = Block::default().borders(Borders::ALL).border_style(border_style); let inner = block.inner(area); // Determine the number of visible rows and total rows let total_rows = self.history.len(); let visible_rows = inner.height as usize; state.visible_rows = visible_rows; let scroll_pos = cmp::min(self.scroll_offset, total_rows.saturating_sub(visible_rows)); let title = format!("History [{}/{}]", scroll_pos, self.history.len()); block.title(title).render(area, buf); let mut vertical_scroll_state = self .vertical_scroll_state .content_length(total_rows.saturating_sub(visible_rows)) .viewport_content_length(1) .position(scroll_pos); let visible_history: Vec<Line> = self .history .iter() .skip(scroll_pos) .map(|entry| match entry { HistoryEntry::UserCommand(cmd) => Line::from(Span::styled(format!("> {}", cmd), Style::default())), HistoryEntry::CommandResponse(resp) => { Line::from(Span::styled(resp.clone(), Style::default().fg(Color::Cyan))) } HistoryEntry::Trace(msg) => Line::from(Span::styled(msg.clone(), Style::default().fg(Color::DarkGray))), HistoryEntry::Debug(msg) => Line::from(Span::styled(msg.clone(), Style::default().fg(Color::Green))), HistoryEntry::Info(msg) => Line::from(Span::styled(msg.clone(), Style::default().fg(Color::White))), HistoryEntry::Warning(msg) => Line::from(Span::styled(msg.clone(), Style::default().fg(Color::Yellow))), HistoryEntry::Error(msg) => Line::from(Span::styled(msg.clone(), Style::default().fg(Color::Red))), }) .collect(); let history_paragraph = Paragraph::new(visible_history); history_paragraph.render(inner, buf); // Render a scrollbar if needed if total_rows > visible_rows { // if true { // Calculate scrollbar size and position let scrollbar_height = (visible_rows as f64 / total_rows as f64 * inner.height as f64).ceil() as u16; let scrollbar_position = ((scroll_pos as f64 / total_rows as f64) * (inner.height as f64 - scrollbar_height as f64)) .ceil() as u16; // Render a scrollbar using the ScrollBar widget if needed if total_rows > visible_rows { // Create a ScrollBar widget let scrollbar = Scrollbar::default() .orientation(ScrollbarOrientation::VerticalRight) // Vertical on the right side .thumb_symbol("█") .track_style(Style::default().fg(Color::Cyan)) .track_symbol(Some("|")); // Render the scrollbar scrollbar.render(inner, buf, &mut vertical_scroll_state); } } } } impl FoxWidget for HistoryWidget {} impl ScrollableWidget for HistoryWidget { fn scroll_up(&mut self) { self.scroll_offset = self.scroll_offset.saturating_sub(1); } fn scroll_down(&mut self) { self.scroll_offset += 1; if self.scroll_offset >= self.history.len() { self.scroll_offset = self.history.len() - 1; } } fn page_up(&mut self) { let state = self.ui_state.borrow(); self.scroll_offset = self.scroll_offset.saturating_sub(state.visible_rows); } fn page_down(&mut self) { let state = self.ui_state.borrow(); self.scroll_offset = (self.scroll_offset + state.visible_rows).min(self.history.len() - 1); } fn scroll_to_start(&mut self) { self.scroll_offset = 0; } fn scroll_to_end(&mut self) { self.scroll_offset = self.history.len(); } } impl TabSelectableWidget for HistoryWidget { fn can_select(&self) -> bool { true } fn select(&mut self) { self.tab_selected = true; } fn deselect(&mut self) { self.tab_selected = false; } } impl WidgetRef for &HistoryWidget { fn render_ref(&self, area: Rect, buf: &mut Buffer) { self.render_ref_internal(area, buf); } } impl WidgetRef for HistoryWidget { fn render_ref(&self, area: Rect, buf: &mut Buffer) { self.render_ref_internal(area, buf); } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/components/mod.rs
crates/ffedit/src/components/mod.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ pub mod data_block; pub mod history; pub mod metadata_header;
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/cmd_interpreter/open.rs
crates/ffedit/src/cmd_interpreter/open.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::{ app::{AppContext, AppEvent}, cmd_interpreter::{Command, CommandArgs, CommandResult}, }; use std::path::PathBuf; pub(crate) struct OpenCommand; impl Command for OpenCommand { fn execute(&self, app: &mut AppContext, args: CommandArgs) -> Result<CommandResult, String> { if let Some(argv) = args.argv { if argv.len() != 1 { return Err(format!("Usage: open {}", self.usage())); } let filename = &argv[0]; //app.file_opened = Some(filename.clone()); if let Err(e) = app .sender .send(AppEvent::OpenFileRequest(PathBuf::from(filename.clone()))) { return Err(format!("Internal error: {}", e)); } Ok(CommandResult::Success(format!("Opening file: {}...", filename))) } else { Err(format!("Usage: open {}", self.usage())) } } fn usage(&self) -> String { "<filename>".into() } fn desc(&self) -> String { "Open a disk image file".into() } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/cmd_interpreter/up.rs
crates/ffedit/src/cmd_interpreter/up.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::{ app::{AppContext, AppEvent}, cmd_interpreter::{Command, CommandArgs, CommandResult}, disk_selection::SelectionLevel, }; pub(crate) struct UpCommand; impl Command for UpCommand { fn execute(&self, app: &mut AppContext, _args: CommandArgs) -> Result<CommandResult, String> { let old_selection_level = app.selection.level; app.selection.level = match app.selection.level { SelectionLevel::Sector => { app.selection.sector = None; SelectionLevel::Cylinder } SelectionLevel::Cylinder => { app.selection.cylinder = None; SelectionLevel::Head } SelectionLevel::Head => { app.selection.cylinder = None; app.selection.head = None; SelectionLevel::Disk } _ => { // Can't go up from disk level app.selection.level } }; if old_selection_level != app.selection.level { _ = app.sender.send(AppEvent::DiskSelectionChanged); } Ok(CommandResult::Success(format!( "Moved up selection level. New level: {:?}", app.selection.level ))) } fn usage(&self) -> String { "No arguments".into() } fn desc(&self) -> String { "Go up a selection".into() } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/cmd_interpreter/h.rs
crates/ffedit/src/cmd_interpreter/h.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::{ app::{AppContext, AppEvent}, cmd_interpreter::{Command, CommandArgs, CommandResult}, disk_selection::SelectionLevel, }; pub(crate) struct HeadCommand; impl Command for HeadCommand { fn execute(&self, app: &mut AppContext, args: CommandArgs) -> Result<CommandResult, String> { if let Some(argv) = args.argv { if argv.len() != 1 { return Err(format!("Usage: h {}", self.usage())); } let new_head: u8 = argv[0].parse::<u8>().map_err(|_| "Invalid head number")?; if let Some(di) = &app.di { if new_head >= di.heads() { return Err(format!("Invalid head number: {}", new_head)); } } _ = app.sender.send(AppEvent::DiskSelectionChanged); if app.selection.level < SelectionLevel::Head { app.selection.level = SelectionLevel::Head } app.selection.head = Some(new_head); Ok(CommandResult::Success(format!("Changed head to: {}", new_head))) } else { Err(format!("Usage: h {}", self.usage())) } } fn usage(&self) -> String { "<head #>".into() } fn desc(&self) -> String { "Select a head/side #".into() } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/cmd_interpreter/list.rs
crates/ffedit/src/cmd_interpreter/list.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::{ app::AppContext, cmd_interpreter::{Command, CommandArgs, CommandResult}, disk_selection::SelectionLevel, }; use fluxfox::prelude::*; pub(crate) struct ListCommand; impl Command for ListCommand { fn execute(&self, app: &mut AppContext, _args: CommandArgs) -> Result<CommandResult, String> { let mut result_string = String::new(); if let Some(di) = &app.di { match app.selection.level { SelectionLevel::Sector => Ok(CommandResult::Success("List sectors here".into())), SelectionLevel::Cylinder => { let ch = app .selection .into_ch() .map_err(|_| "Invalid selection level".to_string())?; app.selection.cylinder = None; Ok(CommandResult::Success("List sectors here".into())) } SelectionLevel::Head => { let h = app .selection .head .ok_or_else(|| "Invalid selection level".to_string())?; let track_ct = di.tracks(h); result_string.push_str(&format!("Head {}, {} tracks:\n", h, track_ct)); for i in 0..track_ct { let track = di.track(DiskCh::new(i, h)).unwrap(); result_string.push_str(&format!("{:02} | ", i)); let ti = track.info(); result_string.push_str(&format!( "{:?} encoding, {:6} bits, {:2} sectors, {:?}\n", ti.encoding, ti.bit_length, ti.sector_ct, ti.data_rate )); } Ok(CommandResult::Success(result_string)) } SelectionLevel::Disk => Ok(CommandResult::Success("List tracks for both heads here".into())), } } else { Err("No disk image loaded".into()) } } fn usage(&self) -> String { "No arguments".into() } fn desc(&self) -> String { "List items depending on current selection level".into() } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/cmd_interpreter/c.rs
crates/ffedit/src/cmd_interpreter/c.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::{ app::{AppContext, AppEvent}, cmd_interpreter::{Command, CommandArgs, CommandResult}, disk_selection::SelectionLevel, }; pub(crate) struct CylinderCommand; impl Command for CylinderCommand { fn execute(&self, app: &mut AppContext, args: CommandArgs) -> Result<CommandResult, String> { if let Some(argv) = args.argv { if argv.len() != 1 { return Err(format!("Usage: c {}", self.usage())); } let new_cylinder: u16 = argv[0].parse::<u16>().map_err(|_| "Invalid cylinder number")?; if let Some(di) = &app.di { if new_cylinder >= di.tracks(app.selection.head.unwrap_or(0)) { return Err(format!("Invalid cylinder number: {}", new_cylinder)); } } _ = app.sender.send(AppEvent::DiskSelectionChanged); if app.selection.level < SelectionLevel::Cylinder { app.selection.level = SelectionLevel::Cylinder } app.selection.cylinder = Some(new_cylinder); Ok(CommandResult::Success(format!("Changed cylinder to: {}", new_cylinder))) } else { Err(format!("Usage: c {}", self.usage())) } } fn usage(&self) -> String { "<cylinder #>".into() } fn desc(&self) -> String { "Select a cylinder".into() } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/cmd_interpreter/mod.rs
crates/ffedit/src/cmd_interpreter/mod.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ mod c; mod h; mod list; mod open; mod s; mod up; use crate::app::AppContext; use once_cell::sync::Lazy; use std::collections::HashMap; pub static COMMAND_ALIASES: Lazy<HashMap<String, String>> = Lazy::new(|| { HashMap::from([ ("?".to_string(), "help".to_string()), ("q".to_string(), "quit".to_string()), ("o".to_string(), "open".to_string()), ("..".to_string(), "up".to_string()), ("ls".to_string(), "list".to_string()), ("dir".to_string(), "list".to_string()), ]) }); pub struct CommandArgs { pub command: String, pub argv: Option<Vec<String>>, pub raw_args: Option<String>, } // Trait for commands trait Command { fn execute(&self, app: &mut AppContext, args: CommandArgs) -> Result<CommandResult, String>; fn usage(&self) -> String; fn desc(&self) -> String; } // Command registry for managing and dispatching commands #[derive(Default)] struct CommandRegistry { commands: HashMap<String, Box<dyn Command>>, } impl CommandRegistry { fn new() -> Self { CommandRegistry { commands: HashMap::new(), } } fn register_command(&mut self, name: &str, command: Box<dyn Command>) { self.commands.insert(name.to_string(), command); } fn dispatch(&self, app: &mut AppContext, input: &str) -> Result<CommandResult, String> { let cmd_args = parse_input(input); if let Some(command) = self.commands.get(&cmd_args.command) { command.execute(app, cmd_args) } else { Err(format!("Unknown command: {} [Type ? for help]", &cmd_args.command)) } } fn get_usage(&self) -> String { if self.commands.is_empty() { return "No commands have been registered.".to_string(); } let str = self .commands .iter() .map(|(name, command)| format!("{} - {} - {}", name, command.usage(), command.desc())) .collect::<Vec<_>>() .join("\n"); str } } // Command result for processing commands pub enum CommandResult { Success(String), Error(String), UserExit, // Used to indicate that the user wants to quit the application } pub struct CommandInterpreter { registry: CommandRegistry, } impl Default for CommandInterpreter { fn default() -> Self { let mut i = CommandInterpreter { registry: CommandRegistry::new(), }; i.register_default_commands(); i } } impl CommandInterpreter { pub fn new() -> CommandInterpreter { Default::default() } // Registering commands with the registry fn register_default_commands(&mut self) { self.registry.register_command("open", Box::new(open::OpenCommand)); self.registry.register_command("h", Box::new(h::HeadCommand)); self.registry.register_command("c", Box::new(c::CylinderCommand)); self.registry.register_command("s", Box::new(s::SectorCommand)); self.registry.register_command("up", Box::new(up::UpCommand)); self.registry.register_command("list", Box::new(list::ListCommand)); } // Command processor pub(crate) fn process_command(&self, app: &mut AppContext, command: &str) -> CommandResult { // Resolve command aliases let command_string = command.to_string(); let resolved_command = COMMAND_ALIASES.get(command).unwrap_or(&command_string); if resolved_command == "q" { CommandResult::UserExit } else if resolved_command == "help" { // Return help information by calling get_usage on the registry let help_message = self.registry.get_usage(); CommandResult::Success(help_message) } else { self.registry .dispatch(app, resolved_command) .unwrap_or_else(|e| CommandResult::Error(format!("Error: {}", e))) } } } fn parse_input(input: &str) -> CommandArgs { let parts = split_quoted(input); let command = parts[0].clone(); let argv = if parts.len() > 1 { Some(parts[1..].to_vec()) } else { None }; let raw_args = split_once(input).get(1).map(|s| s.clone()); CommandArgs { command, argv, raw_args, } } fn split(input: &str) -> Vec<String> { input.split_whitespace().map(String::from).collect() } fn split_once(input: &str) -> Vec<String> { let parts = input .splitn(2, char::is_whitespace) .map(String::from) .collect::<Vec<String>>(); parts } fn split_quoted(input: &str) -> Vec<String> { let mut result = Vec::new(); let mut in_quotes = false; let mut current = String::new(); for c in input.chars() { match c { '"' => { in_quotes = !in_quotes; } ' ' | '\t' | '\n' if !in_quotes => { if !current.is_empty() { result.push(current.clone()); current.clear(); } } _ => current.push(c), } } if !current.is_empty() { result.push(current); } result }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/crates/ffedit/src/cmd_interpreter/s.rs
crates/ffedit/src/cmd_interpreter/s.rs
/* ffedit https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::{ app::{AppContext, AppEvent}, cmd_interpreter::{Command, CommandArgs, CommandResult}, disk_selection::SelectionLevel, }; use fluxfox::prelude::*; pub(crate) struct SectorCommand; impl Command for SectorCommand { fn execute(&self, app: &mut AppContext, args: CommandArgs) -> Result<CommandResult, String> { if let Some(argv) = args.argv { if argv.len() != 1 { return Err(format!("Usage: {}", self.usage())); } let new_sector: u8 = argv[0].parse::<u8>().map_err(|_| "Invalid sector number")?; if let Some(di) = &app.di { let track = di .track(DiskCh::new( app.selection.cylinder.unwrap_or(0), app.selection.head.unwrap_or(0), )) .ok_or("Invalid track")?; if !track.has_sector_id(new_sector, None) { return Err(format!("Invalid sector number: {}", new_sector)); } } _ = app.sender.send(AppEvent::DiskSelectionChanged); if app.selection.level < SelectionLevel::Sector { app.selection.level = SelectionLevel::Sector } app.selection.sector = Some(new_sector); Ok(CommandResult::Success(format!("Changed sector to: {}", new_sector))) } else { Err(format!("Usage: c {}", self.usage())) } } fn usage(&self) -> String { "<sector #>".into() } fn desc(&self) -> String { "Select a sector #".into() } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/serde_demo/src/main.rs
examples/serde_demo/src/main.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- examples/async/src/main.rs This is a simple example of how to use FluxFox with the Tokio async runtime. */ use std::path::PathBuf; use bpaf::*; use fluxfox::{io::Cursor, DiskImage}; #[allow(dead_code)] #[derive(Debug, Clone)] struct Opts { debug: bool, deserialize_fn: Option<PathBuf>, serialize_fn: Option<PathBuf>, output_fn: Option<PathBuf>, } /// Set up bpaf argument parsing. fn opts() -> OptionParser<Opts> { let debug = long("debug").help("Print debug messages").switch(); let deserialize_fn = short('d') .long("deserialize") .help("Filename of serialized disk image to deserialize") .argument::<PathBuf>("FILE_TO_DESERIALIZE") .optional(); let serialize_fn = short('s') .long("serialize") .help("Filename of disk image to read and serialize") .argument::<PathBuf>("FILE_TO_SERIALIZE") .optional(); let output_fn = short('o') .long("output") .help("Filename of serialized disk image to output") .argument::<PathBuf>("FILE_TO_OUTPUT") .optional(); construct!(Opts { debug, deserialize_fn, serialize_fn, output_fn, }) .guard( |opts| opts.deserialize_fn.is_some() || opts.serialize_fn.is_some(), "Must specify either serialize or deserialize", ) .guard( |opts| { (opts.serialize_fn.is_some() && opts.deserialize_fn.is_some()) || !(opts.serialize_fn.is_some() && opts.output_fn.is_none()) }, "Must specify output filename for serialization", ) .guard( |opts| !(opts.serialize_fn.is_some() && opts.deserialize_fn.is_some()), "Cannot serialize and deserialize at the same time", ) .to_options() .descr("serde_demo: demonstrate serialization and deserialization of DiskImages") } fn main() { env_logger::init(); // Get the command line options. let opts = opts().run(); if opts.serialize_fn.is_some() { serialize(opts); } else if opts.deserialize_fn.is_some() { deserialize(opts); } } fn serialize(opts: Opts) { let filename = opts.serialize_fn.clone().unwrap(); let file_vec = match std::fs::read(&filename) { Ok(file_vec) => file_vec, Err(e) => { eprintln!("Error reading file: {}", e); std::process::exit(1); } }; let mut reader = Cursor::new(file_vec); let disk_image_type = match DiskImage::detect_format(&mut reader, Some(&filename.clone())) { Ok(disk_image_type) => disk_image_type, Err(e) => { eprintln!("Error detecting disk image type: {}", e); return; } }; println!("Detected disk image type: {}", disk_image_type); let mut disk = match DiskImage::load(&mut reader, Some(&filename.clone()), None, None) { Ok(disk) => disk, Err(e) => { eprintln!("Error loading disk image: {}", e); std::process::exit(1); } }; println!("Disk image info:"); println!("{}", "-".repeat(79)); let _ = disk.dump_info(&mut std::io::stdout()); println!(); println!("Serializing disk image to file: {:?}", opts.output_fn.clone().unwrap()); match bincode::serialize(&disk) { Ok(serialized) => match std::fs::write(opts.output_fn.unwrap(), serialized) { Ok(_) => println!("Serialization successful"), Err(e) => eprintln!("Error writing serialized disk image: {}", e), }, Err(e) => eprintln!("Error serializing disk image: {}", e), } } fn deserialize(opts: Opts) { let serialized = match std::fs::read(opts.deserialize_fn.unwrap()) { Ok(serialized) => serialized, Err(e) => { eprintln!("Error reading serialized disk image: {}", e); std::process::exit(1); } }; let mut disk: DiskImage = match bincode::deserialize(&serialized) { Ok(disk) => { println!("Deserialization successful"); disk } Err(e) => { eprintln!("Error deserializing disk image: {}", e); std::process::exit(1); } }; println!("Deserialized disk image:"); println!("{}", "-".repeat(79)); let _ = disk.dump_info(&mut std::io::stdout()); println!(); }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/fat/src/main.rs
examples/fat/src/main.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- examples/fat/src/main.rs This is a simple example of how to use FluxFox to mount and read a FAT filesystem using a DiskImage and a StandardSectorView. */ use std::path::PathBuf; use bpaf::*; use fluxfox::{ disk_lock::{NonTrackingDiskLock, NullContext}, file_system::fat::fat_fs::FatFileSystem, io::Cursor, prelude::*, }; #[allow(dead_code)] #[derive(Debug, Clone)] struct Out { debug: bool, silent: bool, filename: PathBuf, } /// Set up bpaf argument parsing. fn opts() -> OptionParser<Out> { let debug = short('d').long("debug").help("Print debug messages").switch(); let silent = long("silent") .help("Suppress all output except errors and requested data") .switch(); let filename = short('i') .long("filename") .help("Filename of image to read") .argument::<PathBuf>("FILE"); construct!(Out { debug, silent, filename, }) .to_options() .descr("fat_example: list all files on a disk containing a DOS FAT12 filesystem") } fn main() { env_logger::init(); // Get the command line options. let opts = opts().run(); let mut file_vec = match std::fs::read(opts.filename.clone()) { Ok(file_vec) => file_vec, Err(e) => { eprintln!("Error reading file: {}", e); std::process::exit(1); } }; let mut cursor = Cursor::new(&mut file_vec); let disk_image_type = match DiskImage::detect_format(&mut cursor, Some(&opts.filename)) { Ok(disk_image_type) => disk_image_type, Err(e) => { eprintln!("Error detecting disk image type: {}", e); std::process::exit(1); } }; if !opts.silent { println!("Detected disk image type: {}", disk_image_type); } let disk = match DiskImage::load(&mut cursor, Some(&opts.filename), None, None) { Ok(disk) => disk, Err(e) => { eprintln!("Error loading disk image: {}", e); std::process::exit(1); } }; // Attempt to determine the disk format. Trust the BPB for this purpose. let format = match disk.closest_format(true) { Some(format) => format, None => { eprintln!("Couldn't detect disk format. Disk may not contain a FAT filesystem."); std::process::exit(1); } }; if !opts.silent { println!("Disk format: {:?}", format); } let disk_arc = DiskImage::into_arc(disk); // Mount the filesystem let fs = match FatFileSystem::mount(NonTrackingDiskLock::new(disk_arc.clone()), NullContext::default(), None) { Ok(fs) => fs, Err(e) => { eprintln!("Error mounting filesystem: {}", e); std::process::exit(1); } }; // Create a FileTreeNode from the root directory. if let Some(root) = fs.build_file_tree_from_root() { root.for_each_file(true, &mut |file| { println!("{}", file); }); } // // Get file listing. // let files = fs.list_all_files(); // // for file in files { // println!("{}", file); // } if !opts.silent { println!("Done!"); } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgdump/src/main.rs
examples/imgdump/src/main.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- examples/imgdump/src/main.rs This is a simple example of how to use FluxFox to read a disk image and dump information from it, such a specified sector or track, in hex or binary format. */ use bpaf::*; use fluxfox::prelude::*; use std::{ io::{BufWriter, Cursor, Write}, path::PathBuf, }; #[allow(dead_code)] #[derive(Debug, Clone)] struct Out { debug: bool, filename: PathBuf, cylinder: Option<u16>, phys_cylinder: Option<u16>, head: Option<u8>, phys_head: Option<u8>, sector: Option<u8>, n: Option<u8>, row_size: usize, structure: bool, find: Option<String>, dump_dupe_mark: bool, silent: bool, } /// Set up bpaf argument parsing. fn opts() -> OptionParser<Out> { let debug = short('d').long("debug").help("Print debug messages").switch(); let silent = long("silent") .help("Suppress all output except errors and requested data") .switch(); let filename = short('i') .long("filename") .help("Filename of image to read") .argument::<PathBuf>("FILE"); let dump_dupe_mark = long("dump_dupe_mark").help("Dump Duplication mark if present").switch(); let phys_cylinder = long("phys_c") .help("Physical cylinder") .argument::<u16>("PHYS_CYLINDER") .optional(); let cylinder = short('c') .long("cylinder") .help("Target cylinder") .argument::<u16>("CYLINDER") .optional(); let head = short('h') .long("head") .help("Target head") .argument::<u8>("HEAD") .optional(); let phys_head = long("phys_h") .help("Physical cylinder") .argument::<u8>("PHYS_HEAD") .optional(); let sector = short('s') .long("sector") .help("Target sector") .argument::<u8>("SECTOR") .optional(); let n = short('n') .long("sector_size") .help("Sector size (override)") .argument::<u8>("SIZE") .optional(); let row_size = short('r') .long("row_size") .help("Number of bytes per row") .argument::<usize>("ROWSIZE") .fallback(16); let structure = long("structure") .help("Dump IDAM header and data CRC in addition to data.") .switch(); let find = long("find") .help("String to find") .argument::<String>("FIND_STRING") .optional(); construct!(Out { debug, filename, cylinder, phys_cylinder, head, phys_head, sector, n, row_size, structure, find, dump_dupe_mark, silent }) .to_options() .descr("imginfo: display info about disk image") } fn main() { env_logger::init(); // Get the command line options. let opts = opts().run(); let mut file_vec = match std::fs::read(opts.filename.clone()) { Ok(file_vec) => file_vec, Err(e) => { eprintln!("Error reading file: {}", e); std::process::exit(1); } }; let mut cursor = Cursor::new(&mut file_vec); let disk_image_type = match DiskImage::detect_format(&mut cursor, Some(&opts.filename)) { Ok(disk_image_type) => disk_image_type, Err(e) => { eprintln!("Error detecting disk image type: {}", e); std::process::exit(1); } }; if !opts.silent { println!("Detected disk image type: {}", disk_image_type); } let mut disk = match DiskImage::load(&mut cursor, Some(&opts.filename), None, None) { Ok(disk) => disk, Err(e) => { eprintln!("Error loading disk image: {}", e); std::process::exit(1); } }; let handle = std::io::stdout(); let mut buf = BufWriter::new(handle); if opts.dump_dupe_mark { if let Some((dupe_ch, dupe_chsn)) = disk.find_duplication_mark() { // let rsr = match disk.read_sector(dupe_ch, DiskChs::from(dupe_chsn), None, RwSectorScope::DataOnly, true) { // Ok(rsr) => rsr, // Err(e) => { // eprintln!("Error reading sector: {}", e); // std::process::exit(1); // } // }; let dump_string = match disk.dump_sector_string(dupe_ch, DiskChsnQuery::from(dupe_chsn), None, None) { Ok(dump_string) => dump_string, Err(e) => { eprintln!("Error dumping sector: {}", e); std::process::exit(1); } }; //println!("Duplication mark found at {} with ID {}", dupe_ch, dupe_chsn); println!("{}", dump_string); std::process::exit(0); } else { println!("No duplication mark found."); } } if opts.cylinder.is_none() || opts.head.is_none() { eprintln!("Cylinder and head must be specified."); std::process::exit(1); } // Specify the physical cylinder and head. If these are not explicitly provided, we assume // that the physical cylinder and head are the same as the target cylinder and head. let mut phys_ch = DiskCh::new(opts.cylinder.unwrap(), opts.head.unwrap()); if let Some(phys_cylinder) = opts.phys_cylinder { phys_ch.set_c(phys_cylinder); } if let Some(phys_head) = opts.phys_head { phys_ch.set_h(phys_head); } // If sector was provided, dump the sector. if let Some(sector) = opts.sector { // Dump the specified sector in hex format to stdout. let id_chs = DiskChs::new(opts.cylinder.unwrap(), opts.head.unwrap(), sector); let (scope, calc_crc) = match opts.structure { true => (RwScope::EntireElement, true), false => (RwScope::DataOnly, false), }; let rsr = match disk.read_sector( phys_ch, DiskChsnQuery::new(id_chs.c(), id_chs.h(), id_chs.s(), opts.n), opts.n, None, scope, true, ) { Ok(rsr) => rsr, Err(e) => { eprintln!("Error reading sector: {}", e); std::process::exit(1); } }; _ = writeln!(&mut buf, "Data length: {}", rsr.data_range.len()); let data_slice = &rsr.read_buf[rsr.data_range]; if let Some(find_string) = &opts.find { let find_bytes = find_string.as_bytes(); let mut found = false; for i in 0..data_slice.len() { if data_slice[i..].starts_with(find_bytes) { _ = writeln!(&mut buf, "Found {} at offset {}", find_string, i); found = true; break; } } if !found { _ = writeln!(&mut buf, "Did not find search string."); } } else { println!( "Dumping sector from {} with id {} in hex format, with scope {:?}:", phys_ch, DiskChsn::from((id_chs, opts.n.unwrap_or(2))), scope ); _ = fluxfox::util::dump_slice(data_slice, 0, opts.row_size, 1, &mut buf); // If we requested DataBlock scope, we can independently calculate the CRC, so do that now. if calc_crc { let calculated_crc = fluxfox::util::crc_ibm_3740(&data_slice[0..0x104], None); _ = writeln!(&mut buf, "Calculated CRC: {:04X}", calculated_crc); } } } else { // No sector was provided, dump the whole track. let ch = DiskCh::new(opts.cylinder.unwrap(), opts.head.unwrap()); println!("Dumping track {} in hex format:", ch); let rtr = match disk.read_track(ch, None) { Ok(rtr) => rtr, Err(e) => { eprintln!("Error reading track: {}", e); std::process::exit(1); } }; _ = fluxfox::util::dump_slice(&rtr.read_buf, 0, opts.row_size, 1, &mut buf); } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/async/src/main.rs
examples/async/src/main.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- examples/async/src/main.rs This is a simple example of how to use FluxFox with the Tokio async runtime. */ use std::{ path::PathBuf, sync::{Arc, Mutex}, time::Duration, }; use tokio::{task, time::sleep}; use anyhow::{anyhow, Error}; use bpaf::*; use fluxfox::{ io::{Cursor, ReadSeek, Write}, DiskImage, LoadingStatus, }; #[allow(dead_code)] #[derive(Debug, Clone)] struct Opts { debug: bool, filename: PathBuf, } /// Set up bpaf argument parsing. fn opts() -> OptionParser<Opts> { let debug = short('d').long("debug").help("Print debug messages").switch(); let filename = short('t') .long("filename") .help("Filename of image to read") .argument::<PathBuf>("FILE"); construct!(Opts { debug, filename }) .to_options() .descr("imginfo: display info about disk image") } #[tokio::main] async fn main() { env_logger::init(); // Get the command line options. let opts = opts().run(); let file_vec = match std::fs::read(opts.filename.clone()) { Ok(file_vec) => file_vec, Err(e) => { eprintln!("Error reading file: {}", e); std::process::exit(1); } }; let mut reader = Cursor::new(file_vec); let disk_image_type = match DiskImage::detect_format(&mut reader, Some(&opts.filename)) { Ok(disk_image_type) => disk_image_type, Err(e) => { eprintln!("Error detecting disk image type: {}", e); return; } }; println!("Detected disk image type: {}", disk_image_type); let disk_opt = match load_disk_image(reader, opts).await { Ok(disk) => Some(disk), Err(_) => None, }; if let Some(mut disk) = disk_opt { println!("Disk image info:"); println!("{}", "-".repeat(79)); let _ = disk.dump_info(&mut std::io::stdout()); println!(); } } // Load a disk image from a stream, displaying a progress spinner. async fn load_disk_image<RS: ReadSeek + Send + 'static>(mut reader: RS, opts: Opts) -> Result<DiskImage, Error> { let progress = Arc::new(Mutex::new(0.0)); // Define a callback to update the progress percentage as the disk image loads. let progress_clone = Arc::clone(&progress); let callback: Arc<dyn Fn(LoadingStatus) + Send + Sync> = Arc::new(move |status| match status { LoadingStatus::Progress(p) => { let mut progress = progress_clone.lock().unwrap(); *progress = p * 100.0; } LoadingStatus::Complete => { let mut progress = progress_clone.lock().unwrap(); *progress = 100.0; } _ => {} }); // Spawn a task for loading the disk image let mut load_handle = task::spawn( async move { DiskImage::load_async(&mut reader, Some(&opts.filename), None, Some(callback)).await }, ); // Display spinner with percentage progress let spinner_chars = ['|', '/', '-', '\\']; let mut spinner_idx = 0; loop { tokio::select! { result = &mut load_handle => { // When the loading task completes, handle the result let disk = match result { Ok(Ok(disk)) => disk, Ok(Err(e)) => { eprintln!("Error loading disk image: {:?}", e); return Err(anyhow!(e)); } Err(e) => { eprintln!("Task failed: {:?}", e); return Err(anyhow!(e)); } }; // Break out of the loop with the loaded disk break Ok(disk); } _ = sleep(Duration::from_millis(100)) => { // Update the spinner and display progress let progress = *progress.lock().unwrap(); print!("\rLoading disk image... {} {:.2}%", spinner_chars[spinner_idx], progress); std::io::stdout().flush().unwrap(); spinner_idx = (spinner_idx + 1) % spinner_chars.len(); } } } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgviz/src/config.rs
examples/imgviz/src/config.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use std::{fs, path::Path}; use crate::style::Style; use anyhow::Error; use fluxfox::{track_schema::GenericTrackElement, visualization::prelude::*, FoxHashMap}; use fluxfox_svg::prelude::BlendMode; use serde::Deserialize; // Deserialize colors as either RGBA tuple or u32 #[derive(Debug, Deserialize)] #[serde(untagged)] enum ConfigColor { Rgba(u8, u8, u8, u8), U32(u32), } #[derive(Copy, Clone, Debug, Default, Deserialize)] pub enum ConfigBlendMode { #[default] Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity, } #[cfg(feature = "use_svg")] impl From<ConfigBlendMode> for BlendMode { fn from(value: ConfigBlendMode) -> Self { match value { ConfigBlendMode::Normal => BlendMode::Normal, ConfigBlendMode::Multiply => BlendMode::Multiply, ConfigBlendMode::Screen => BlendMode::Screen, ConfigBlendMode::Overlay => BlendMode::Overlay, ConfigBlendMode::Darken => BlendMode::Darken, ConfigBlendMode::Lighten => BlendMode::Lighten, ConfigBlendMode::ColorDodge => BlendMode::ColorDodge, ConfigBlendMode::ColorBurn => BlendMode::ColorBurn, ConfigBlendMode::HardLight => BlendMode::HardLight, ConfigBlendMode::SoftLight => BlendMode::SoftLight, ConfigBlendMode::Difference => BlendMode::Difference, ConfigBlendMode::Exclusion => BlendMode::Exclusion, ConfigBlendMode::Hue => BlendMode::Hue, ConfigBlendMode::Saturation => BlendMode::Saturation, ConfigBlendMode::Color => BlendMode::Color, ConfigBlendMode::Luminosity => BlendMode::Luminosity, } } } // Optional style fields #[derive(Debug, Deserialize)] struct PartialStyleConfig { fill: Option<ConfigColor>, stroke: Option<ConfigColor>, stroke_width: Option<f32>, } #[derive(Debug, Deserialize)] struct MaskConfigInput { weak: ConfigColor, error: ConfigColor, } pub(crate) struct MaskConfig { pub(crate) weak: VizColor, pub(crate) error: VizColor, } // Complete palette configuration #[derive(Debug, Deserialize)] struct StyleConfigFileInput { track_gap: f32, default_style: PartialStyleConfig, masks: MaskConfigInput, track_style: PartialStyleConfig, element_styles: FoxHashMap<String, PartialStyleConfig>, blend_mode: ConfigBlendMode, } // Translated and merged configuration pub(crate) struct StyleConfig { pub(crate) track_gap: f32, pub(crate) masks: MaskConfig, pub(crate) track_style: Style, pub(crate) element_styles: FoxHashMap<GenericTrackElement, Style>, pub(crate) blend_mode: ConfigBlendMode, } // Conversion for ConfigColor to VizColor impl ConfigColor { fn to_viz_color(&self) -> VizColor { match self { ConfigColor::Rgba(r, g, b, a) => VizColor::from_rgba8(*r, *g, *b, *a), ConfigColor::U32(val) => { let r = ((val >> 24) & 0xFF) as u8; let g = ((val >> 16) & 0xFF) as u8; let b = ((val >> 8) & 0xFF) as u8; let a = (val & 0xFF) as u8; VizColor::from_rgba8(r, g, b, a) } } } } // Merge optional styles with defaults fn merge_style(default: &PartialStyleConfig, custom: &PartialStyleConfig) -> Style { let fill = custom .fill .as_ref() .or(default.fill.as_ref()) .expect("Fill color must be defined") .to_viz_color(); let stroke = custom .stroke .as_ref() .or(default.stroke.as_ref()) .expect("Stroke color must be defined") .to_viz_color(); let stroke_width = custom.stroke_width.unwrap_or(default.stroke_width.unwrap_or(1.0)); Style { fill, stroke, stroke_width, } } pub fn load_style_config(path: impl AsRef<Path>) -> Result<StyleConfig, Error> { let config_str = fs::read_to_string(path)?; let config: StyleConfigFileInput = toml::from_str(&config_str)?; let mut styles = FoxHashMap::new(); for (key, partial_style) in config.element_styles { let element = match key.as_str() { "NullElement" => GenericTrackElement::NullElement, "Marker" => GenericTrackElement::Marker, "SectorHeader" => GenericTrackElement::SectorHeader, "SectorBadHeader" => GenericTrackElement::SectorBadHeader, "SectorData" => GenericTrackElement::SectorData, "SectorDeletedData" => GenericTrackElement::SectorDeletedData, "SectorBadData" => GenericTrackElement::SectorBadData, "SectorBadDeletedData" => GenericTrackElement::SectorBadDeletedData, _ => continue, }; let style = merge_style(&config.default_style, &partial_style); styles.insert(element, style); } let track_style = merge_style(&config.default_style, &config.track_style); Ok(StyleConfig { track_gap: config.track_gap, masks: MaskConfig { weak: config.masks.weak.to_viz_color(), error: config.masks.error.to_viz_color(), }, track_style, element_styles: styles, blend_mode: config.blend_mode, }) }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgviz/src/render_bitmap.rs
examples/imgviz/src/render_bitmap.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- examples/imgviz/src/render.rs Rendering functions for imgviz. */ use fluxfox::{ track_schema::GenericTrackElement, visualization::{ prelude::*, rasterize_track_data, render_track_mask, CommonVizParams, RenderMaskType, RenderRasterizationParams, RenderTrackDataParams, ResolutionType, TurningDirection, }, DiskImage, DiskImageError, MAX_CYLINDER, }; use std::{ cmp::min, collections::HashMap, f32::consts::{PI, TAU}, io::Write, sync::{Arc, Mutex}, thread, time::Instant, }; use fluxfox_tiny_skia::tiny_skia::{ BlendMode, Color, FilterQuality, IntSize, Paint, Pixmap, PixmapPaint, PremultipliedColorU8, Transform, }; use crate::{ args::VizArgs, config::StyleConfig, legend::VizLegend, palette::{default_error_bit_color, default_weak_bit_color}, style::Style, text::{render_text, Justification}, }; use crate::style::style_map_to_skia; use anyhow::{anyhow, bail, Error}; use crossbeam::channel; use fast_image_resize::{images::Image as FirImage, FilterType, PixelType, ResizeAlg, Resizer}; use fluxfox_tiny_skia::{ prelude::SkiaStyle, render_display_list::render_data_display_list, render_elements::{skia_render_data_slice, skia_render_element}, }; use tiny_skia::Stroke; pub struct RenderParams { pub bg_color: Option<VizColor>, pub track_bg_color: Option<Color>, pub render_size: u32, pub supersample: u8, pub side: u32, pub min_radius: f32, pub direction: TurningDirection, pub angle: f32, pub track_limit: usize, pub track_gap: f32, pub decode: bool, pub weak: bool, pub errors: bool, pub weak_color: Option<VizColor>, pub error_color: Option<VizColor>, pub resolution_type: ResolutionType, } #[allow(dead_code)] pub(crate) fn color_to_premultiplied(color: Color) -> PremultipliedColorU8 { PremultipliedColorU8::from_rgba( (color.red() * color.alpha() * 255.0) as u8, (color.green() * color.alpha() * 255.0) as u8, (color.blue() * color.alpha() * 255.0) as u8, (color.alpha() * 255.0) as u8, ) .expect("Failed to create PremultipliedColorU8") } pub struct RasterizationData {} pub fn render_bitmap( disk: DiskImage, starting_head: u32, sides_to_render: u32, opts: &VizArgs, style: &StyleConfig, legend: &mut VizLegend, ) -> Result<(), Error> { let image_size = opts.resolution; // New pool for metadata rendering. Don't bother with quadrants - just render full sides let meta_pixmap_pool = [ Arc::new(Mutex::new(Pixmap::new(opts.resolution, opts.resolution).unwrap())), Arc::new(Mutex::new(Pixmap::new(opts.resolution, opts.resolution).unwrap())), ]; // Vec to receive rendered pixmaps for compositing as they are generated. let mut rendered_pixmaps = Vec::new(); let track_cts = [disk.track_ct(0), disk.track_ct(1)]; let a_disk = disk.into_arc(); for si in 0..sides_to_render { let side = si + starting_head; log::debug!(" >>> Rendering side {} of {}...", side, sides_to_render); let disk = Arc::clone(&a_disk); // Default to clockwise turning, unless --cc flag is passed. let mut direction = if opts.cc { TurningDirection::CounterClockwise } else { TurningDirection::Clockwise }; // Reverse side 1 as long as --dont_reverse flag is not present. if side > 0 && !opts.dont_reverse { direction = direction.opposite(); } log::debug!("Rendering display list at resolution: {}", opts.resolution); let common_params = CommonVizParams { radius: Some(image_size as f32 / 2.0), max_radius_ratio: 1.0, min_radius_ratio: opts.hole_ratio, pos_offset: None, index_angle: direction.adjust_angle(opts.angle), track_limit: Some(track_cts[side as usize]), pin_last_standard_track: true, track_gap: opts.track_gap.unwrap_or(0.0), direction, ..CommonVizParams::default() }; let render_params = RenderTrackDataParams { side: si as u8, decode: opts.decode, sector_mask: true, resolution: Default::default(), slices: opts.data_slices, ..RenderTrackDataParams::default() }; let rasterization_params = RenderRasterizationParams { image_size: VizDimensions::from((image_size, image_size)), supersample: opts.supersample, image_bg_color: opts.img_bg_color, disk_bg_color: opts.track_bg_color, mask_color: None, palette: None, pos_offset: None, }; let weak_color = default_weak_bit_color(); let error_color = default_error_bit_color(); // Render data if data flag was passed. let mut pixmap = if opts.data { // If the rasterize_data flag was set, directly rasterize the data layer, otherwise // we'll vectorize it and rasterize that. match opts.rasterize_data { true => { match rasterize_data_layer( &disk.read().unwrap(), opts, &common_params, &render_params, &rasterization_params, ) { Ok(pixmap) => pixmap, Err(e) => { eprintln!("Error rendering side: {}", e); std::process::exit(1); } } } false => { let mut data_pixmap = Pixmap::new(image_size, image_size).unwrap(); // Vectorize the data layer, then render it let vector_params = RenderVectorizationParams { view_box: VizRect::from((0.0, 0.0, image_size as f32, image_size as f32)), image_bg_color: None, disk_bg_color: None, mask_color: None, pos_offset: None, }; let display_list = match vectorize_disk_data( &disk.read().unwrap(), &common_params, &render_params, &vector_params, ) { Ok(display_list) => display_list, Err(e) => { eprintln!("Error vectorizing disk elements: {}", e); std::process::exit(1); } }; // Disable antialiasing to reduce moiré. For antialiasing, use supersampling. let mut paint = Paint { anti_alias: false, ..Default::default() }; render_data_display_list(&mut data_pixmap, &mut paint, common_params.index_angle, &display_list) .map_err(|s| anyhow!("Error rendering data display list: {}", s))?; data_pixmap } } } else { Pixmap::new(image_size, image_size).unwrap() }; drop(disk); let (sender, receiver) = channel::unbounded::<u8>(); if opts.metadata { log::debug!("Rendering metadata for side {}...", side); let inner_disk = Arc::clone(&a_disk); let inner_pixmap = Arc::clone(&meta_pixmap_pool[side as usize]); let palette = style.element_styles.clone(); let render_debug = opts.debug; let inner_params = common_params.clone(); thread::spawn(move || { let mut metadata_pixmap = inner_pixmap.lock().unwrap(); // We set the angle to 0.0 here, because tiny_skia can rotate the resulting // display list for us. let mut common_params = inner_params.clone(); common_params.index_angle = 0.0; let metadata_params = RenderTrackMetadataParams { quadrant: None, side: side as u8, geometry: Default::default(), winding: Default::default(), draw_empty_tracks: false, draw_sector_lookup: false, }; let metadata_disk = inner_disk.read().unwrap(); let list_start_time = Instant::now(); let display_list = match vectorize_disk_elements(&metadata_disk, &common_params, &metadata_params) { Ok(display_list) => display_list, Err(e) => { eprintln!("Error rendering metadata: {}", e); std::process::exit(1); } }; println!( "visualize_disk_elements() returned a display list of length {} in {:.3}ms", display_list.len(), list_start_time.elapsed().as_secs_f64() * 1000.0 ); // Set the index angle for rasterization. let angle = inner_params.index_angle; let track_style = Style::default(); rasterize_display_list(&mut metadata_pixmap, angle, &track_style, &display_list, &palette); if render_debug { metadata_pixmap.save_png(format!("new_metadata{}.png", side)).unwrap(); } println!("Sending rendered metadata pixmap for side: {} over channel...", side); if let Err(e) = sender.send(side as u8) { eprintln!("Error sending metadata pixmap: {}", e); std::process::exit(1); } }); println!("Waiting for metadata pixmap for side {}...", side); std::io::stdout().flush().unwrap(); for (p, recv_side) in receiver.iter().enumerate() { // let (x, y) = match recv_side { // 0 => (0, 0u32), // 1 => (image_size, 0u32), // _ => panic!("Invalid side"), // }; println!("Received metadata pixmap for side {}...", recv_side); std::io::stdout().flush().unwrap(); let paint = match opts.data { true => PixmapPaint { opacity: 1.0, blend_mode: BlendMode::HardLight, quality: FilterQuality::Nearest, }, false => PixmapPaint::default(), }; pixmap.draw_pixmap( 0, 0, meta_pixmap_pool[recv_side as usize].lock().unwrap().as_ref(), // Convert &Pixmap to PixmapRef &paint, Transform::identity(), None, ); if p == sides_to_render.saturating_sub(1) as usize { break; } } } log::debug!("Adding rendered side {} to vector...", side); rendered_pixmaps.push(pixmap); } if rendered_pixmaps.is_empty() { eprintln!("No sides rendered!"); std::process::exit(1); } //println!("Finished data layer in {:?}", data_render_start_time.elapsed()); let horiz_gap = 0; // Combine both sides into a single image, if we have two sides. let (mut composited_image, composited_width) = if (rendered_pixmaps.len() > 1) || (sides_to_render == 2) { let final_size = ( image_size * sides_to_render + horiz_gap * (sides_to_render - 1), image_size + legend.height().unwrap_or(0) as u32, ); let mut final_image = Pixmap::new(final_size.0, final_size.1).unwrap(); if let Some(color) = opts.img_bg_color { final_image.fill(Color::from(color)); } println!("Compositing sides..."); for (i, pixmap) in rendered_pixmaps.iter().enumerate() { //println!("Compositing pixmap #{}", i); final_image.draw_pixmap( (image_size + horiz_gap) as i32 * i as i32, 0, pixmap.as_ref(), &PixmapPaint::default(), Transform::identity(), None, ); } println!("Saving final image as {}", opts.out_filename.display()); (final_image, final_size.0) } else if let Some(height) = legend.height() { // Just one side, but we have a legend. let final_size = (image_size, image_size + height as u32); let mut final_image = Pixmap::new(final_size.0, final_size.1).unwrap(); if let Some(color) = opts.img_bg_color { final_image.fill(Color::from(color)); } println!("Compositing side..."); final_image.draw_pixmap( 0, 0, rendered_pixmaps.pop().unwrap().as_ref(), &PixmapPaint::default(), Transform::identity(), None, ); println!("Saving final image as {}", opts.out_filename.display()); (final_image, image_size) } else { // Just one side, and no legend. Nothing to composite. println!("Saving final image as {}", opts.out_filename.display()); (rendered_pixmaps.pop().unwrap(), image_size) }; // // Render index hole if requested. // if opts.index_hole { // draw_index_hole( // &mut composited_image, // 0.39, // 2.88, // 10.0, // 1.0, // Color::from_rgba8(255, 255, 255, 255), // TurningDirection::CounterClockwise, // ); // } // Render legend. legend.render(&mut composited_image); // Save image to disk. composited_image.save_png(opts.out_filename.clone())?; Ok(()) } pub fn rasterize_data_layer( disk: &DiskImage, opts: &VizArgs, p: &CommonVizParams, r: &RenderTrackDataParams, rr: &RenderRasterizationParams, ) -> Result<Pixmap, Error> { let mut rr = rr.clone(); let supersample_size = match rr.supersample { 1 => rr.image_size, 2 => rr.image_size.scale(2), 4 => rr.image_size.scale(4), 8 => rr.image_size.scale(8), _ => { bail!("Invalid supersample factor: {}", rr.supersample); } }; let mut data_layer_pixmap = Pixmap::new(supersample_size.x, supersample_size.y).unwrap(); // To implement the disk background color, we first fill the entire image with it. // The areas outside the disk circumference will be set to the img_bg_color during rendering. if let Some(color) = rr.disk_bg_color { data_layer_pixmap.fill(Color::from(color)); } println!("Rendering data layer for side {}...", r.side); let data_render_start_time = Instant::now(); match rasterize_track_data(disk, &mut data_layer_pixmap, p, r, &rr) { Ok(_) => { println!("Rendered data layer in {:?}", data_render_start_time.elapsed()); } Err(e) => { eprintln!("Error rendering tracks: {}", e); std::process::exit(1); } }; // // Render error bits on composited image if requested. // if opts.errors { // let error_render_start_time = Instant::now(); // println!("Rendering error map layer for side {}...", r.side); // match render_track_mask(disk, &mut rendered_image, RenderMaskType::Errors, p, r, &rr) { // Ok(_) => { // println!("Rendered error map layer in {:?}", error_render_start_time.elapsed()); // } // Err(e) => { // eprintln!("Error rendering tracks: {}", e); // std::process::exit(1); // } // }; // } // // // Render weak bits on composited image if requested. // if opts.weak { // rr.mask_color = Some(weak_color); // let weak_render_start_time = Instant::now(); // println!("Rendering weak bits layer for side {}...", r.side); // match render_track_mask(disk, &mut rendered_image, RenderMaskType::WeakBits, p, r, &rr) { // Ok(_) => { // println!("Rendered weak bits layer in {:?}", weak_render_start_time.elapsed()); // } // Err(e) => { // eprintln!("Error rendering tracks: {}", e); // std::process::exit(1); // } // }; // } let resampled_image = match rr.supersample { 1 => data_layer_pixmap, _ => { let resample_start_time = Instant::now(); let src_image = match FirImage::from_slice_u8( data_layer_pixmap.width(), data_layer_pixmap.height(), data_layer_pixmap.data_mut(), PixelType::U8x4, ) { Ok(image) => image, Err(e) => { eprintln!("Error converting image: {}", e); std::process::exit(1); } }; let mut dst_image = FirImage::new(rr.image_size.x, rr.image_size.y, PixelType::U8x4); let mut resizer = Resizer::new(); let resize_opts = fast_image_resize::ResizeOptions::new().resize_alg(ResizeAlg::Convolution(FilterType::CatmullRom)); println!("Resampling output image for side {}...", r.side); match resizer.resize(&src_image, &mut dst_image, &resize_opts) { Ok(_) => { println!( "Resampled image to {} in {:?}", rr.image_size, resample_start_time.elapsed() ); Pixmap::from_vec( dst_image.into_vec(), IntSize::from_wh(rr.image_size.x, rr.image_size.y).unwrap(), ) .unwrap() } Err(e) => { eprintln!("Error resizing image: {}", e); std::process::exit(1); } } } }; Ok(resampled_image) } pub fn rasterize_display_list( pixmap: &mut Pixmap, angle: f32, track_style: &Style, display_list: &VizElementDisplayList, styles: &HashMap<GenericTrackElement, Style>, ) { let mut paint = Paint { blend_mode: BlendMode::SourceOver, anti_alias: true, ..Default::default() }; let mut transform = Transform::identity(); if angle != 0.0 { log::debug!("Rotating tiny_skia Transform by {}", angle); transform = Transform::from_rotate_at( angle.to_degrees(), pixmap.width() as f32 / 2.0, pixmap.height() as f32 / 2.0, ); } let skia_styles = style_map_to_skia(styles); let skia_track_style = SkiaStyle::from(track_style); for element in display_list.iter() { skia_render_element(pixmap, &mut paint, &transform, &skia_track_style, &skia_styles, element); } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgviz/src/legend.rs
examples/imgviz/src/legend.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use crate::text::{calculate_scaled_font_size, measure_text, render_text, Justification}; use rusttype::Font; use tiny_skia::{Color, Pixmap}; pub struct VizLegend { pub title_string: String, pub title_font: Option<Font<'static>>, pub title_font_size: f32, pub title_font_color: Color, pub image_size: u32, pub height: Option<i32>, } impl VizLegend { pub fn new(title: &str, image_size: u32) -> Self { log::debug!("Using title: {}", title); Self { title_string: title.to_string(), title_font: None, title_font_size: 0.0, title_font_color: Color::WHITE, image_size, height: None, } } pub fn set_title_font(&mut self, font: Font<'static>, size: f32) { self.title_font = Some(font); self.title_font_size = size; self.calculate_height(); } fn calculate_height(&mut self) { if let Some(font) = &self.title_font { let font_size = calculate_scaled_font_size(40.0, self.image_size, 1024); let (_, font_h) = measure_text(&font, &self.title_string, font_size); self.height = Some(font_h * 3); // 3 lines of text. Title will be centered within. } } pub fn height(&self) -> Option<i32> { self.height } pub fn render(&mut self, pixmap: &mut Pixmap) { if let Some(title_font) = &self.title_font { let (_, font_h) = measure_text(title_font, &self.title_string, self.title_font_size); let legend_height = self.height.unwrap_or(0); let x = (pixmap.width() / 2) as i32; let y = pixmap.height() as i32 - legend_height - font_h; // Draw text one 'line' up from bottom of image. log::debug!("Rendering text at ({}, {})", x, y); render_text( pixmap, title_font, self.title_font_size, &self.title_string, x, y, Justification::Center, self.title_font_color, ); } } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgviz/src/palette.rs
examples/imgviz/src/palette.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ //! Palette module for defining the palette for imgviz to use. //! Currently, this returns a single default palette, but eventually we should //! be able to load a user-specified palette, probably from a TOML file... use crate::{ config::{ConfigBlendMode, MaskConfig, StyleConfig}, style::Style, }; use fluxfox::{track_schema::GenericTrackElement, visualization::prelude::*, FoxHashMap}; /// Return a default palette for visualization. /// There's no need to modify this - override colors with a style.toml file and use the `--style` /// flag to apply them. pub fn default_palette() -> FoxHashMap<GenericTrackElement, VizColor> { // Defined colors let viz_light_red: VizColor = VizColor::from_rgba8(180, 0, 0, 255); let vis_purple: VizColor = VizColor::from_rgba8(180, 0, 180, 255); let pal_medium_green = VizColor::from_rgba8(0x38, 0xb7, 0x64, 0xff); let pal_dark_green = VizColor::from_rgba8(0x25, 0x71, 0x79, 0xff); let pal_medium_blue = VizColor::from_rgba8(0x3b, 0x5d, 0xc9, 0xff); let pal_light_blue = VizColor::from_rgba8(0x41, 0xa6, 0xf6, 0xff); let pal_orange = VizColor::from_rgba8(0xef, 0x7d, 0x57, 0xff); // Here are some other colors you can use if you want to change the palette //let viz_orange = VizColor::from_rgba8(255, 100, 0, 255); //let viz_cyan = VizColor::from_rgba8(70, 200, 200, 255); //let vis_light_purple = VizColor::from_rgba8(185, 0, 255, 255); //let pal_dark_blue = VizColor::from_rgba8(0x29, 0x36, 0x6f, 0xff); //let pal_dark_purple = VizColor::from_rgba8(0x5d, 0x27, 0x5d, 0xff); //let pal_dark_red = VizColor::from_rgba8(0xb1, 0x3e, 0x53, 0xff); //let pal_weak_bits = VizColor::from_rgba8(70, 200, 200, 255); //let pal_error_bits = VizColor::from_rgba8(255, 0, 0, 255); #[rustfmt::skip] let palette = FoxHashMap::from([ (GenericTrackElement::SectorData, pal_medium_green), (GenericTrackElement::SectorBadData, pal_orange), (GenericTrackElement::SectorDeletedData, pal_dark_green), (GenericTrackElement::SectorBadDeletedData, viz_light_red), (GenericTrackElement::SectorHeader, pal_light_blue), (GenericTrackElement::SectorBadHeader, pal_medium_blue), (GenericTrackElement::Marker, vis_purple), ]); palette } /// Convert a simple color palette to a style map, using default stroke color and stroke width pub fn palette_to_style_config(palette: &FoxHashMap<GenericTrackElement, VizColor>) -> StyleConfig { let mut style_map = FoxHashMap::new(); for (element, color) in palette.iter() { style_map.insert(*element, Style::fill_only(*color)); } StyleConfig { track_gap: 0.0, masks: MaskConfig { weak: default_weak_bit_color(), error: default_error_bit_color(), }, track_style: Style::fill_only(VizColor::from_rgba8(0, 0, 0, 0)), element_styles: style_map, blend_mode: ConfigBlendMode::Multiply, } } /// Return the default style configuration for visualization if a style file is not provided. pub fn default_style_config() -> StyleConfig { let palette = default_palette(); palette_to_style_config(&palette) } /// Return a default color for weak bit visualization. /// There's no need to modify this - override colors with a style.toml file and use the `--style` pub fn default_weak_bit_color() -> VizColor { VizColor::from_rgba8(70, 200, 200, 255) } /// Return a default color for error bit visualization. /// There's no need to modify this - override colors with a style.toml file and use the `--style` pub fn default_error_bit_color() -> VizColor { VizColor::from_rgba8(255, 0, 0, 255) }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgviz/src/args.rs
examples/imgviz/src/args.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- examples/imgviz/src/args.rs Argument parsers for imgviz. */ use std::path::{Path, PathBuf}; use fluxfox::visualization::prelude::*; use bpaf::{construct, long, short, OptionParser, Parser}; use crate::DEFAULT_DATA_SLICES; #[allow(dead_code)] #[derive(Debug, Clone)] pub(crate) struct VizArgs { pub(crate) debug: bool, pub(crate) in_filename: PathBuf, pub(crate) out_filename: PathBuf, pub(crate) style_filename: Option<PathBuf>, pub(crate) resolution: u32, pub(crate) side: Option<u8>, pub(crate) sides: Option<u8>, pub(crate) side_spacing: f32, pub(crate) track_gap: Option<f32>, pub(crate) hole_ratio: f32, pub(crate) angle: f32, pub(crate) data: bool, pub(crate) rasterize_data: bool, pub(crate) data_slices: usize, pub(crate) weak: bool, pub(crate) errors: bool, pub(crate) metadata: bool, pub(crate) index_hole: bool, pub(crate) decode: bool, pub(crate) cc: bool, pub(crate) dont_reverse: bool, pub(crate) supersample: u32, pub(crate) img_bg_color: Option<VizColor>, pub(crate) track_bg_color: Option<VizColor>, pub(crate) title: Option<String>, } /// Set up bpaf argument parsing. pub(crate) fn opts() -> OptionParser<VizArgs> { let debug = short('d').long("debug").help("Enable debug mode").switch(); let in_filename = short('i') .long("in_filename") .help("Filename of disk image to read") .argument::<PathBuf>("IN_FILE"); let out_filename = short('o') .long("out_filename") .help("Filename of image to write") .argument::<PathBuf>("OUT_FILE"); let style_filename = long("style_file") .help("Filename of style definition to use") .argument::<PathBuf>("STYLE_FILE") .optional(); let resolution = short('r') .long("resolution") .help("Size of resulting image, in pixels") .argument::<u32>("SIZE"); let side = short('s') .long("side") .help("Side to render. Omit to render both sides") .argument::<u8>("SIDE") .guard(|side| *side < 2, "Side must be 0 or 1") .optional(); let sides = long("sides") .help("Override number of sides to render. Only useful for rendering single-sided disks as double-wide images.") .argument::<u8>("SIDES") .guard(|sides| *sides > 0 && *sides < 3, "Sides must be 1 or 2") .optional(); let side_spacing = long("side_spacing") .help("Spacing between sides in two-sided images") .argument::<f32>("SIDE_SPACING") .fallback(0.0); let track_gap = long("track_gap") .help("Size of gap between tracks as a ratio of track width") .argument::<f32>("TRACK_GAP") .optional(); let hole_ratio = short('h') .long("hole_ratio") .help("Ratio of inner radius to outer radius") .argument::<f32>("RATIO") .fallback(0.33); let angle = short('a') .long("angle") .help("Angle of rotation") .argument::<f32>("ANGLE") .fallback(0.0); let data = long("data").help("Render data").switch(); let data_slices = long("data_slices") .help("Number of slices to use rendering data") .argument::<usize>("DATA_SLICES") .fallback(DEFAULT_DATA_SLICES); let rasterize_data = long("rasterize_data") .help("Use rasterization method for data rendering.") .switch(); let weak = short('w').long("weak").help("Render weak bits").switch(); let errors = short('e').long("errors").help("Render bitstream errors").switch(); let metadata = long("metadata").help("Render metadata").switch(); let decode = long("decode").help("Decode data").switch(); let index_hole = long("index_hole").help("Render index hole").switch(); let supersample = long("ss") .help("Supersample (2,4,8)") .argument::<u32>("FACTOR") .fallback(1); let cc = long("cc").help("Wrap data counter-clockwise").switch(); let dont_reverse = long("dont_reverse").help("Don't reverse direction of side 1").switch(); let img_bg_color = long("img_bg_color") .help("Specify the image background color as #RRGGBBAA, #RRGGBB, or R,G,B,A") .argument::<String>("IMAGE_BACKGROUND_COLOR") .parse(|input: String| parse_color(&input)) .optional(); let track_bg_color = long("track_bg_color") .help("Specify the track background color as #RRGGBBAA, #RRGGBB, or R,G,B,A") .argument::<String>("TRACK_BACKGROUND_COLOR") .parse(|input: String| parse_color(&input)) .optional(); // Title argument with substitution let title = long("title") .help("Specify the title string, or ${IN_FILE} to use the input filename.") .argument::<String>("TITLE") .optional(); construct!(VizArgs { debug, in_filename, out_filename, style_filename, resolution, side, sides, data_slices, rasterize_data, side_spacing, track_gap, hole_ratio, angle, data, weak, errors, metadata, index_hole, decode, cc, dont_reverse, supersample, img_bg_color, track_bg_color, title, }) .to_options() .descr("imgviz: generate a graphical visualization of a disk image") } /// Perform `${IN_FILE}` substitution for the `title`, using only the filename portion of `in_filename`. pub(crate) fn substitute_title(title: Option<String>, in_filename: &Path) -> Option<String> { // Extract only the filename portion for substitution let in_filename_str = in_filename .file_name() .unwrap_or_default() .to_string_lossy() .into_owned(); let in_dir_str = in_filename .parent() // Get the parent directory .and_then(|parent| parent.file_name()) // Get the last component of the parent .and_then(|name| name.to_str()) // Convert OsStr to &str .map(|name| name.to_string()); // Convert &str to String // Substitute `${IN_FILE}` in `title` if provided; otherwise, return `None` let title = title.map(|t| t.replace("${IN_FILE}", &in_filename_str)); // Substitute `${IN_DIR}` in `title` title.map(|t| t.replace("${IN_DIR}", &in_dir_str.unwrap_or_default())) } /// Parse a color from either a hex string (`#RRGGBBAA` or `#RRGGBB`) or an RGBA string (`R,G,B,A`). pub(crate) fn parse_color(input: &str) -> Result<VizColor, String> { if input.starts_with('#') { // Parse hex color: #RRGGBBAA or #RRGGBB let hex = input.strip_prefix('#').ok_or("Invalid hex color")?; match hex.len() { 6 => { let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| "Invalid hex color")?; let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| "Invalid hex color")?; let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| "Invalid hex color")?; Ok(VizColor::from_rgba8(r, g, b, 255)) } 8 => { let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| "Invalid hex color")?; let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| "Invalid hex color")?; let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| "Invalid hex color")?; let a = u8::from_str_radix(&hex[6..8], 16).map_err(|_| "Invalid hex color")?; Ok(VizColor::from_rgba8(r, g, b, a)) } _ => Err("Hex color must be in the format #RRGGBB or #RRGGBBAA".to_string()), } } else { // Parse RGBA color: R,G,B,A let parts: Vec<&str> = input.split(',').collect(); if parts.len() != 4 { return Err("RGBA color must be in the format R,G,B,A".to_string()); } let r = parts[0].parse::<u8>().map_err(|_| "Invalid RGBA color component")?; let g = parts[1].parse::<u8>().map_err(|_| "Invalid RGBA color component")?; let b = parts[2].parse::<u8>().map_err(|_| "Invalid RGBA color component")?; let a = parts[3].parse::<u8>().map_err(|_| "Invalid RGBA color component")?; Ok(VizColor::from_rgba8(r, g, b, a)) } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgviz/src/text.rs
examples/imgviz/src/text.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- examples/imgviz/src/text.rs Text-handling routines using rusttype. */ use anyhow::Error; use rusttype::{point, Font, Scale}; use tiny_skia::{BlendMode, Color, FilterQuality, Pixmap, PixmapPaint, PremultipliedColorU8, Transform}; /// Enum to specify text justification #[allow(dead_code)] #[derive(Copy, Clone)] pub(crate) enum Justification { Left, Center, Right, } pub(crate) fn calculate_scaled_font_size(base_font_size: f32, resolution: u32, baseline_resolution: u32) -> f32 { // Calculate scaling factors for width and height relative to the baseline resolution let scale = resolution as f32 / baseline_resolution as f32; // Scale the base font size base_font_size * scale } pub(crate) fn create_font(font_data: &[u8]) -> Option<Font<'static>> { let owned_font_data: Vec<u8> = font_data.to_vec(); let from_owned_font: Font<'static> = Font::try_from_vec(owned_font_data)?; Some(from_owned_font) } pub(crate) fn render_text( pixmap: &mut Pixmap, font: &Font, size: f32, text: &str, x: i32, y: i32, justification: Justification, base_color: Color, ) { let scale = Scale::uniform(size); // Set font size // Calculate text width to adjust the starting position based on justification let text_width = measure_text(font, text, size).0; let adjusted_x = match justification { Justification::Left => x, Justification::Center => x - text_width / 2, Justification::Right => x - text_width, }; // Layout the text at origin (0, 0) and draw each glyph at the adjusted position for glyph in font.layout(text, scale, point(0.0, 0.0)) { if let Some(bounding_box) = glyph.pixel_bounding_box() { // Create a pixmap for the glyph let mut glyph_pixmap = Pixmap::new(bounding_box.width() as u32, bounding_box.height() as u32) .expect("Failed to create glyph pixmap"); // Render the glyph into its pixmap glyph.draw(|px, py, alpha| { let alpha = alpha.max(0.0).min(1.0); // Clamp alpha to [0.0, 1.0] let alpha_color = PremultipliedColorU8::from_rgba( (base_color.red() * alpha * 255.0) as u8, (base_color.green() * alpha * 255.0) as u8, (base_color.blue() * alpha * 255.0) as u8, (base_color.alpha() * alpha * 255.0) as u8, ) .expect("Failed to create PremultipliedColorU8"); let pixel_index = ((py * glyph_pixmap.width() + px) * 4) as usize; let data = glyph_pixmap.data_mut(); data[pixel_index] = alpha_color.red(); data[pixel_index + 1] = alpha_color.green(); data[pixel_index + 2] = alpha_color.blue(); data[pixel_index + 3] = alpha_color.alpha(); }); // Draw the glyph onto the main pixmap at the final position pixmap.draw_pixmap( bounding_box.min.x + adjusted_x, bounding_box.min.y + y, glyph_pixmap.as_ref(), &PixmapPaint { opacity: 1.0, blend_mode: BlendMode::SourceOver, quality: FilterQuality::Bilinear, }, Transform::identity(), None, ); } } } /// Calculate the width and height of rendered text based on the font, text, and font size. pub(crate) fn measure_text(font: &Font, text: &str, font_size: f32) -> (i32, i32) { let scale = Scale::uniform(font_size); let mut min_x = 0; let mut min_y = 0; let mut max_x = 0; let mut max_y = 0; for glyph in font.layout(text, scale, point(0.0, 0.0)) { if let Some(bounding_box) = glyph.pixel_bounding_box() { min_x = min_x.min(bounding_box.min.x); max_x = max_x.max(bounding_box.max.x); min_y = min_y.min(bounding_box.min.y); max_y = max_y.max(bounding_box.max.y); } } (max_x - min_x, max_y - min_y) }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgviz/src/style.rs
examples/imgviz/src/style.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ use fluxfox::{track_schema::GenericTrackElement, visualization::prelude::*, FoxHashMap}; use fluxfox_svg::prelude::ElementStyle; use fluxfox_tiny_skia::styles::SkiaStyle; // Style struct for storing visual properties #[derive(Copy, Clone, Debug, Default)] pub struct Style { pub fill: VizColor, pub stroke: VizColor, pub stroke_width: f32, } impl Style { pub fn fill_only(fill: VizColor) -> Style { Style { fill, stroke: VizColor::from_rgba8(0, 0, 0, 0), stroke_width: 0.0, } } } #[cfg(feature = "use_svg")] pub fn style_map_to_fluxfox_svg( style_map: &FoxHashMap<GenericTrackElement, Style>, ) -> FoxHashMap<GenericTrackElement, ElementStyle> { style_map .iter() .map(|(k, v)| { ( k.clone(), ElementStyle { fill: v.fill, stroke: v.stroke, stroke_width: v.stroke_width, }, ) }) .collect() } #[cfg(feature = "use_tiny_skia")] pub fn style_map_to_skia( style_map: &FoxHashMap<GenericTrackElement, Style>, ) -> FoxHashMap<GenericTrackElement, SkiaStyle> { style_map .iter() .map(|(k, v)| { ( k.clone(), SkiaStyle { fill: v.fill, stroke: v.stroke, stroke_width: v.stroke_width, }, ) }) .collect() } #[cfg(feature = "use_tiny_skia")] impl From<Style> for SkiaStyle { fn from(style: Style) -> Self { SkiaStyle { fill: style.fill, stroke: style.stroke, stroke_width: style.stroke_width, } } } #[cfg(feature = "use_tiny_skia")] impl From<&Style> for SkiaStyle { fn from(style: &Style) -> Self { SkiaStyle { fill: style.fill, stroke: style.stroke, stroke_width: style.stroke_width, } } }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgviz/src/main.rs
examples/imgviz/src/main.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- examples/imgviz/src/main.rs This is a simple example of how to use FluxFox to produce a graphical visualization of a disk image. */ mod args; mod config; mod legend; mod palette; mod render_bitmap; mod render_svg; mod style; mod text; use crate::{ args::{opts, substitute_title}, palette::{default_error_bit_color, default_style_config, default_weak_bit_color}, render_bitmap::rasterize_data_layer, text::{calculate_scaled_font_size, create_font, measure_text, render_text, Justification}, }; use rusttype::Font; use std::{ io::{Cursor, Write}, sync::{Arc, Mutex}, thread, time::Instant, }; use crate::legend::VizLegend; use fluxfox::{ visualization::{ prelude::*, CommonVizParams, RenderRasterizationParams, RenderTrackDataParams, RenderTrackMetadataParams, ResolutionType, TurningDirection, }, DiskImage, }; pub const MAX_SLICES: usize = 2880; pub const DEFAULT_DATA_SLICES: usize = 1440; fn main() { env_logger::init(); // Get the command line options. let opts = opts().run(); // Perform argument substitution. let title = substitute_title(opts.title.clone(), &opts.in_filename); // Create a VizLegend. let mut legend = VizLegend::new(&title.unwrap_or("".to_string()), opts.resolution); // Load default title font and add it to the legend. let font_data = include_bytes!("../../../resources/PTN57F.ttf"); let font: Font<'static> = match create_font(font_data) { Some(font) => font, None => { eprintln!("Error loading font."); std::process::exit(1); } }; legend.set_title_font(font, 40.0); // Enforce power of two image size. This isn't strictly required, but it avoids some aliasing // issues when rasterizing. if !is_power_of_two(opts.resolution) { eprintln!("Image size must be a power of two"); return; } // Limit supersampling from 1-8x. match opts.supersample { 1 => opts.resolution, 2 => opts.resolution * 2, 4 => opts.resolution * 4, 8 => opts.resolution * 8, _ => { eprintln!("Supersample must be 2, 4, or 8"); std::process::exit(1); } }; // Read the style configuration file, if specified. let style_config = if let Some(style_filename) = opts.style_filename.clone() { match config::load_style_config(&style_filename) { Ok(style_config) => style_config, Err(e) => { eprintln!("Error loading style configuration: {}", e); std::process::exit(1); } } } else { default_style_config() }; // Read in the entire input file and put it in a Cursor. let mut file_vec = match std::fs::read(opts.in_filename.clone()) { Ok(file_vec) => file_vec, Err(e) => { eprintln!("Error reading file: {}", e); std::process::exit(1); } }; let mut reader = Cursor::new(&mut file_vec); // Detect the image file format, or bail. let disk_image_type = match DiskImage::detect_format(&mut reader, Some(&opts.in_filename)) { Ok(disk_image_type) => disk_image_type, Err(e) => { eprintln!("Error detecting disk image type: {}", e); std::process::exit(1); } }; println!("Reading disk image: {}", opts.in_filename.display()); println!("Detected disk image type: {}", disk_image_type); // Load the disk image or bail. let disk = match DiskImage::load(&mut reader, Some(&opts.in_filename), None, None) { Ok(disk) => disk, Err(e) => { eprintln!("Error loading disk image: {}", e); std::process::exit(1); } }; // let direction = match &opts.cc { // true => RotationDirection::CounterClockwise, // false => RotationDirection::Clockwise, // }; let resolution = ResolutionType::Byte; // Change to Bit if needed let min_radius_fraction = opts.hole_ratio; // Minimum radius as a fraction of the image size // TODO: Make this a command line parameter let render_track_gap = 0.10; // Fraction of the track width to leave transparent as a gap between tracks (0.0-1.0) let sides_to_render: u32; let starting_head: u32; // If the user specifies a side, we assume that only that side will be rendered. // However, the 'sides' parameter can be overridden to 2 to leave a blank space for the missing // empty side. This is useful when rendering slideshows. if let Some(side) = opts.side { log::debug!("Side {} specified.", side); if side >= disk.heads() { eprintln!("Disk image does not have requested side: {}", side); std::process::exit(1); } sides_to_render = opts.sides.unwrap_or(1) as u32; starting_head = side as u32; println!("Visualizing side {}/{}...", starting_head, sides_to_render); } else { // No side was specified. We'll render all sides, starting at side 0. sides_to_render = opts.sides.unwrap_or(disk.heads()) as u32; starting_head = 0; println!("Visualizing {} sides...", sides_to_render); } let image_size = opts.resolution; let track_ct = disk.tracks(0) as usize; log::trace!("Image has {} tracks.", track_ct); // Determine whether our output format is SVG or PNG. Only do so if `use_svg` is enabled. #[cfg(feature = "use_svg")] if let Some(extension) = opts.out_filename.extension() { if extension == "svg" { log::debug!("Rendering SVG..."); match render_svg::render_svg(&disk, starting_head, sides_to_render, &opts, &style_config, &legend) { Ok(_) => { log::debug!("Saved SVG to: {}", opts.out_filename.display()); std::process::exit(0); } Err(e) => { eprintln!("Error rendering SVG: {}", e); std::process::exit(1); } } } } #[cfg(feature = "use_tiny_skia")] if let Some(extension) = opts.out_filename.extension() { if extension == "png" { log::debug!("Rendering bitmap..."); match render_bitmap::render_bitmap(disk, starting_head, sides_to_render, &opts, &style_config, &mut legend) { Ok(_) => { log::debug!("Saved bitmap to: {}", opts.out_filename.display()); std::process::exit(0); } Err(e) => { eprintln!("Error rendering bitmap: {}", e); std::process::exit(1); } } } else { eprintln!("Unknown extension: {}. Did you mean .PNG?", extension.to_string_lossy()); } } } fn is_power_of_two(n: u32) -> bool { n > 0 && (n & (n - 1)) == 0 }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imgviz/src/render_svg.rs
examples/imgviz/src/render_svg.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- */ //! Module to render disk visualization to SVG using the `svg` crate. use crate::{args::VizArgs, config::StyleConfig, style::style_map_to_fluxfox_svg}; use fluxfox::{ visualization::{prelude::*, TurningDirection}, DiskImage, }; use anyhow::{anyhow, Error}; use crate::legend::VizLegend; use fluxfox_svg::prelude::*; pub(crate) fn render_svg( disk: &DiskImage, starting_head: u32, sides_to_render: u32, opts: &VizArgs, style: &StyleConfig, _legend: &VizLegend, ) -> Result<(), Error> { // Render with fluxfox_svg's SvgRenderer let render_timer = std::time::Instant::now(); let mut renderer = SvgRenderer::new() .side_by_side(true, 20.0) .with_radius_ratios(0.55, 0.88) .with_track_gap(opts.track_gap.unwrap_or(style.track_gap)) .with_data_layer(opts.data, Some(opts.data_slices)) .decode_data(opts.decode) .with_metadata_layer(opts.metadata) .with_index_angle(opts.angle) .with_layer_stack(true) .with_side_view_box(VizRect::from(( 0.0, 0.0, opts.resolution as f32, opts.resolution as f32, ))) .with_styles(style_map_to_fluxfox_svg(&style.element_styles)) .with_blend_mode(style.blend_mode.into()) .with_overlay(Overlay::Overlay5_25) .with_initial_turning(if opts.cc { TurningDirection::CounterClockwise } else { TurningDirection::Clockwise }); if sides_to_render == 1 { renderer = renderer.with_side(starting_head as u8); } else { renderer = renderer.side_by_side(true, opts.side_spacing); } let documents = renderer .render(disk) .map_err(|e| anyhow!("Error rendering SVG documents: {}", e))? .create_documents() .map_err(|e| anyhow!("Error rendering SVG documents: {}", e))?; let render_time = render_timer.elapsed(); log::debug!("SVG rendering took {:.3}ms", render_time.as_secs_f64() * 1000.0); if documents.is_empty() { return Err(anyhow!("No SVG documents were created!")); } if documents.len() > 1 { log::warn!("Multiple SVG documents were created, but only the first will be saved."); } println!("Saving SVG to {}...", opts.out_filename.display()); svg::save(&opts.out_filename, &documents[0].document)?; Ok(()) }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
dbalsom/fluxfox
https://github.com/dbalsom/fluxfox/blob/b4c04b51746e5fe7769f49a1b32b8caad426fc81/examples/imginfo/src/main.rs
examples/imginfo/src/main.rs
/* FluxFox https://github.com/dbalsom/fluxfox Copyright 2024-2025 Daniel Balsom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- examples/imginfo/src/main.rs This is a simple example of how to use FluxFox to read a disk image and print out some basic information about it. */ use bpaf::*; use std::io::Cursor; use fluxfox::DiskImage; use std::path::PathBuf; #[allow(dead_code)] #[derive(Debug, Clone)] struct Out { debug: bool, sector_list: bool, filename: PathBuf, } /// Set up bpaf argument parsing. fn opts() -> OptionParser<Out> { let debug = short('d').long("debug").help("Print debug messages").switch(); let sector_list = short('s') .long("sector-list") .help("List all sectors in the image") .switch(); let filename = short('t') .long("filename") .help("Filename of image to read") .argument::<PathBuf>("FILE"); construct!(Out { debug, sector_list, filename }) .to_options() .descr("imginfo: display info about disk image") } fn main() { env_logger::init(); // Get the command line options. let opts = opts().run(); let mut file_vec = match std::fs::read(opts.filename.clone()) { Ok(file_vec) => file_vec, Err(e) => { eprintln!("Error reading file: {}", e); std::process::exit(1); } }; let mut reader = Cursor::new(&mut file_vec); let disk_image_type = match DiskImage::detect_format(&mut reader, Some(&opts.filename)) { Ok(disk_image_type) => disk_image_type, Err(e) => { eprintln!("Error detecting disk image type: {}", e); return; } }; println!("Detected disk image type: {}", disk_image_type); let mut disk = match DiskImage::load(&mut reader, Some(&opts.filename), None, None) { Ok(disk) => disk, Err(e) => { eprintln!("Error loading disk image: {}", e); return; } }; println!("Disk image info:"); println!("{}", "-".repeat(79)); let _ = disk.dump_info(&mut std::io::stdout()); println!(); println!("Disk analysis:"); println!("{}", "-".repeat(79)); let _ = disk.dump_analysis(&mut std::io::stdout()); println!("Image can be represented by the following formats with write support:"); let formats = disk.compatible_formats(true); for format in formats { println!(" {} [{}]", format.0, format.1.join(", ")); } if let Some(bootsector) = disk.boot_sector() { println!("Disk has a boot sector"); if bootsector.has_valid_bpb() { println!("Boot sector with valid BPB detected:"); println!("{}", "-".repeat(79)); let _ = bootsector.dump_bpb(&mut std::io::stdout()); } else { println!("Boot sector has an invalid BPB"); } } println!(); if opts.sector_list { let _ = disk.dump_sector_map(&mut std::io::stdout()); } /* for track in disk.track_pool.iter_mut() { match &mut track.data { TrackData::BitStream { data, .. } => { let elements = System34Parser::scan_track_metadata(data); log::trace!("Found {} elements on track.", elements.len()); } _ => { println!("Track data is not a bitstream. Skipping track element scan."); } } }*/ }
rust
MIT
b4c04b51746e5fe7769f49a1b32b8caad426fc81
2026-01-04T20:24:04.021295Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/scripts/docker/build.rs
scripts/docker/build.rs
#!/usr/bin/env bash set -e ROOT=$(git rev-parse --show-toplevel) sudo docker build $ROOT -t islet
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/scripts/docker/run.rs
scripts/docker/run.rs
#!/usr/bin/env bash set -e ROOT=$(git rev-parse --show-toplevel) sudo docker run -it -v $ROOT:/islet islet:latest
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/config.rs
rmm/src/config.rs
use alloc::vec::Vec; use lazy_static::lazy_static; use spin::mutex::Mutex; pub const NUM_OF_CPU: usize = 8; pub const NUM_OF_CLUSTER: usize = 2; pub const NUM_OF_CPU_PER_CLUSTER: usize = NUM_OF_CPU / NUM_OF_CLUSTER; pub const PAGE_BITS: usize = 12; pub const PAGE_SIZE: usize = 1 << PAGE_BITS; // 4KiB pub const LARGE_PAGE_SIZE: usize = 1024 * 1024 * 2; // 2MiB pub const HUGE_PAGE_SIZE: usize = 1024 * 1024 * 1024; // 1GiB #[cfg(any(feature = "fvp", not(feature = "qemu")))] pub const MAX_DRAM_SIZE: usize = 0xFC00_0000; // 4GB - 64MB #[cfg(feature = "qemu")] pub const MAX_DRAM_SIZE: usize = 0x2_0000_0000; // 8GB pub const RMM_STACK_GUARD_SIZE: usize = crate::granule::GRANULE_SIZE * 1; pub const RMM_STACK_SIZE: usize = 1024 * 1024 - RMM_STACK_GUARD_SIZE; pub const RMM_HEAP_SIZE: usize = 16 * 1024 * 1024; pub const VM_STACK_SIZE: usize = 1 << 15; pub const STACK_ALIGN: usize = 16; pub const SMCCC_1_3_SVE_HINT: usize = 1 << 16; #[derive(Debug, Default)] pub struct PlatformMemoryLayout { pub rmm_base: u64, pub rw_start: u64, pub rw_end: u64, pub stack_base: u64, pub uart_phys: u64, pub el3_shared_buf: u64, } lazy_static! { pub static ref NS_DRAM_REGIONS: Mutex<Vec<core::ops::Range<usize>>> = Mutex::new(Vec::new()); } pub fn is_ns_dram(addr: usize) -> bool { let regions = NS_DRAM_REGIONS.lock(); for range in regions.iter() { if range.contains(&addr) { return true; } } false }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/lib.rs
rmm/src/lib.rs
#![no_std] #![allow(incomplete_features)] #![feature(alloc_error_handler)] #![feature(specialization)] #![warn(rust_2018_idioms)] #[cfg(not(any(test, fuzzing)))] pub mod allocator; pub mod asm; pub mod config; pub(crate) mod cose; pub mod cpu; pub(crate) mod event; pub mod exception; pub mod gic; #[macro_use] pub mod granule; #[macro_use] pub(crate) mod host; pub mod logger; pub mod mm; #[cfg(not(any(test, kani, miri, fuzzing)))] pub mod panic; pub mod pmu; pub mod realm; pub mod rec; pub mod rmi; pub mod rsi; pub mod simd; #[cfg(feature = "stat")] pub mod stat; #[cfg(any(test, miri))] pub(crate) mod test_utils; #[cfg(fuzzing)] pub mod test_utils; #[macro_use] pub mod r#macro; mod measurement; #[cfg(kani)] // we declare monitor as `pub` in model checking, so that // its member can be accessed freely outside the rmm crate pub mod monitor; #[cfg(not(kani))] mod monitor; mod rmm_el3; extern crate alloc; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use crate::config::PlatformMemoryLayout; use crate::exception::vectors; #[cfg(feature = "gst_page_table")] use crate::granule::create_granule_status_table as setup_gst; use crate::mm::translation::{get_page_table, init_page_table}; use crate::monitor::Monitor; use crate::rmm_el3::setup_el3_ifc; use aarch64_cpu::registers::*; use armv9a::{MDCR_EL2, PMCR_EL0}; use core::ptr::addr_of; #[cfg(not(kani))] // model checking harnesses do not use this function, instead // they use their own entry points marked with #[kani::proof] // where slightly adjusted `Monitor` is used /// Starts the RMM on the specified CPU with the given memory layout. /// /// # Safety /// /// The caller must ensure that: /// - The caller must ensure that `cpu_id` corresponds to a valid and initialized CPU. /// - The `layout` must be a valid `PlatformMemoryLayout` appropriate for the platform. /// - Calling this function may alter system-level configurations and should be done with caution. pub unsafe fn start(cpu_id: usize, layout: PlatformMemoryLayout) { let el3_shared_buf = layout.el3_shared_buf; setup_mmu_cfg(layout); info!( "booted on core {:2} with EL{}!", cpu_id, CurrentEL.read(CurrentEL::EL) as u8 ); setup_el2(); #[cfg(feature = "gst_page_table")] setup_gst(); // TODO: call once or with every start? if cpu_id == 0 { setup_el3_ifc(el3_shared_buf); } Monitor::new().run(); } /// # Safety /// /// This function performs several operations that involve writing to system control registers /// at the EL2. /// /// The caller must ensure that: /// - The function is called at EL2 with the required privileges. /// - The `vectors` variable points to a valid exception vector table in memory. /// - The system is in a state where modifying these control registers is safe and will not /// interfere with other critical operations. /// /// Failing to meet these requirements can result in system crashes, security vulnerabilities, /// or other undefined behavior. unsafe fn setup_el2() { HCR_EL2.write( HCR_EL2::FWB::SET + HCR_EL2::TEA::SET + HCR_EL2::TERR::SET + HCR_EL2::TLOR::SET + HCR_EL2::RW::SET + HCR_EL2::TSW::SET + HCR_EL2::TACR::SET + HCR_EL2::TIDCP::SET + HCR_EL2::TSC::SET + HCR_EL2::TID3::SET + HCR_EL2::BSU::InnerShareable + HCR_EL2::FB::SET + HCR_EL2::AMO::SET + HCR_EL2::IMO::SET + HCR_EL2::FMO::SET + HCR_EL2::VM::SET + HCR_EL2::API::SET + HCR_EL2::APK::SET, // HCR_EL2::TWI::SET, ); VBAR_EL2.set(addr_of!(vectors) as u64); SCTLR_EL2 .write(SCTLR_EL2::C::SET + SCTLR_EL2::I::SET + SCTLR_EL2::M::SET + SCTLR_EL2::EOS::SET); CPTR_EL2.write(CPTR_EL2::TAM::SET); ICC_SRE_EL2.write( ICC_SRE_EL2::ENABLE::SET + ICC_SRE_EL2::DIB::SET + ICC_SRE_EL2::DFB::SET + ICC_SRE_EL2::SRE::SET, ); MDCR_EL2.write( MDCR_EL2::MTPME::SET + MDCR_EL2::HCCD::SET + MDCR_EL2::HPMD::SET + MDCR_EL2::TDA::SET + MDCR_EL2::TPM::SET + MDCR_EL2::TPMCR::SET + MDCR_EL2::HPMN.val(PMCR_EL0.read(PMCR_EL0::N)), ); } /// # Safety /// /// This function configures the Memory Management Unit (MMU) at the EL2. /// /// The caller must ensure: /// - The function is called at EL2 with the appropriate privileges. /// - The translation table base address (`ttbl_base`) is valid and correctly initialized. /// - Modifying these registers and executing these assembly instructions will not interfere /// with other critical operations. /// /// Failing to meet these requirements can result in system crashes, memory corruption, security /// vulnerabilities, or other undefined behavior. unsafe fn setup_mmu_cfg(layout: PlatformMemoryLayout) { core::arch::asm!("tlbi alle2is", "dsb ish", "isb",); // /* Set attributes in the right indices of the MAIR. */ let mair_el2 = MAIR_EL2::Attr0_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL2::Attr0_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL2::Attr1_Device::nonGathering_nonReordering_noEarlyWriteAck + MAIR_EL2::Attr2_Device::nonGathering_nonReordering_EarlyWriteAck; /* * The size of the virtual address space is configured as 64 – T0SZ. * In this, 64 – 0x19 gives 39 bits of virtual address space. * This equates to 512GB (2^39), which means that the entire virtual address * space is covered by a single L1 table. * Therefore, our starting level of translation is level 1. */ let tcr_el2 = TCR_EL2::T0SZ.val(0x19) + TCR_EL2::PS::Bits_40 + TCR_EL2::TG0::KiB_4 + TCR_EL2::SH0::Inner + TCR_EL2::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL2::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable; // set the ttbl base address, this is where the memory address translation // table walk starts init_page_table(layout); let ttbl_base = get_page_table(); // Invalidate the local I-cache so that any instructions fetched // speculatively are discarded. MAIR_EL2.write(mair_el2); TCR_EL2.write(tcr_el2); TTBR0_EL2.set(ttbl_base); core::arch::asm!("dsb ish", "isb",); } /// Call `rmm_exit` within `exception/vectors.s` and jumps to EL1. /// /// Currently, this function gets [0usize; 3] as an argument to initialize /// x0, x1 and x2 registers. /// /// When an exception occurs and the flow comes back to EL2 through `rmm_enter`, /// x0, x1 and x2 registers might be changed to contain additional information /// set from `handle_lower_exception`. /// These are the return values of this function. /// The return value encodes: [rmi::RET_XXX, ret_val1, ret_val2] /// In most cases, the function returns [rmi::RET_SUCCESS, _, _] /// pagefault returns [rmi::RET_PAGE_FAULT, faulted address, _] /// /// # Safety /// /// - This function alters the processor's execution level by jumping to EL1; /// the caller must ensure that the system is in a correct state for this transition. #[cfg(not(kani))] pub unsafe fn rmm_exit(args: [usize; 4]) -> [usize; 4] { let mut ret: [usize; 4] = [0usize; 4]; core::arch::asm!( "bl rmm_exit", inlateout("x0") args[0] => ret[0], inlateout("x1") args[1] => ret[1], inlateout("x2") args[2] => ret[2], inlateout("x3") args[3] => ret[3], ); ret } #[cfg(kani)] pub unsafe fn rmm_exit(_args: [usize; 4]) -> [usize; 4] { let ret: [usize; 4] = [0usize; 4]; ret }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/asm.rs
rmm/src/asm.rs
use core::arch::asm; pub const SMC_SUCCESS: usize = 0; #[cfg(any(kani, miri, test, fuzzing))] pub const SMC_ERROR: usize = 1; pub fn smc(cmd: usize, args: &[usize]) -> [usize; 8] { let mut ret: [usize; 8] = [0usize; 8]; let mut padded_args: [usize; 8] = [0usize; 8]; let start = 1; let end = start + args.len(); if end > ret.len() - 1 { // TODO: need a more graceful way to return error value (Result?) error!("{} arguments exceed the current limit of smc call. Please try assigning more registers to smc", args.len()); return ret; } let put = |arr: &mut [usize; 8]| { arr[0] = cmd; arr[start..end].copy_from_slice(args); }; put(&mut ret); put(&mut padded_args); #[cfg(any(kani, miri, test, fuzzing))] if cmd == crate::rmi::gpt::MARK_REALM { use crate::get_granule; use crate::granule::entry::GranuleGpt; let addr = args[0]; let gpt = get_granule!(addr).map(|guard| guard.gpt).unwrap(); if gpt != GranuleGpt::GPT_NS { ret[0] = SMC_ERROR; } else { let _ = get_granule!(addr).map(|mut guard| guard.set_gpt(GranuleGpt::GPT_REALM)); ret[0] = SMC_SUCCESS; } } else if cmd == crate::rmi::gpt::MARK_NONSECURE { use crate::get_granule; use crate::granule::entry::GranuleGpt; let addr = args[0]; let is_valid = get_granule!(addr).map(|guard| guard.is_valid()).unwrap(); assert!(is_valid); let gpt = get_granule!(addr).map(|guard| guard.gpt).unwrap(); if gpt != GranuleGpt::GPT_REALM { ret[0] = SMC_ERROR; } else { let _ = get_granule!(addr).map(|mut guard| guard.set_gpt(GranuleGpt::GPT_NS)); ret[0] = SMC_SUCCESS; } } // TODO: support more number of registers than 8 if needed #[cfg(not(any(kani, miri, test, fuzzing)))] unsafe { asm!( "smc #0x0", inlateout("x0") padded_args[0] => ret[0], inlateout("x1") padded_args[1] => ret[1], inlateout("x2") padded_args[2] => ret[2], inlateout("x3") padded_args[3] => ret[3], inlateout("x4") padded_args[4] => ret[4], inlateout("x5") padded_args[5] => ret[5], inlateout("x6") padded_args[6] => ret[6], inlateout("x7") padded_args[7] => ret[7], ) } ret } #[inline(always)] pub fn dcache_flush(addr: usize, len: usize) { let mut cur_addr = addr; let addr_end = addr + len; unsafe { while cur_addr < addr_end { asm!("dc civac, {}", in(reg) cur_addr); asm!("dsb ish"); asm!("isb"); cur_addr += 64; // the cache line size is 64 } } } #[inline(always)] pub fn isb() { #[cfg(target_arch = "aarch64")] unsafe { core::arch::asm!("isb", options(nomem, nostack)) } #[cfg(not(target_arch = "aarch64"))] unimplemented!() }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/gic.rs
rmm/src/gic.rs
use aarch64_cpu::registers::*; use lazy_static::lazy_static; pub const ICH_HCR_EL2_INIT: u64 = (ICH_HCR_EL2::En.mask << ICH_HCR_EL2::En.shift) + (ICH_HCR_EL2::vSGIEOICount.mask << ICH_HCR_EL2::vSGIEOICount.shift) + (ICH_HCR_EL2::DVIM.mask << ICH_HCR_EL2::DVIM.shift); // Interrupt Controller List Registers (ICH_LR) const ICH_LR_PRIORITY_WIDTH: u64 = 8; pub const ICH_HCR_EL2_NS_MASK: u64 = (ICH_HCR_EL2::UIE.mask << ICH_HCR_EL2::UIE.shift) | (ICH_HCR_EL2::LRENPIE.mask << ICH_HCR_EL2::LRENPIE.shift) | (ICH_HCR_EL2::NPIE.mask << ICH_HCR_EL2::NPIE.shift) | (ICH_HCR_EL2::VGrp1DIE.mask << ICH_HCR_EL2::VGrp1DIE.shift) | (ICH_HCR_EL2::VGrp1EIE.mask << ICH_HCR_EL2::VGrp1EIE.shift) | (ICH_HCR_EL2::VGrp0DIE.mask << ICH_HCR_EL2::VGrp0DIE.shift) | (ICH_HCR_EL2::VGrp0EIE.mask << ICH_HCR_EL2::VGrp0EIE.shift) | (ICH_HCR_EL2::TDIR.mask << ICH_HCR_EL2::TDIR.shift); const ICH_HCR_EL2_EOI_COUNT_WIDTH: usize = 5; pub const ICH_HCR_EL2_EOI_COUNT_MASK: u64 = ((!0u64) >> (64 - ICH_HCR_EL2_EOI_COUNT_WIDTH)) << ICH_HCR_EL2::EOIcount.shift; const MAX_SPI_ID: u64 = 1019; const MIN_EPPI_ID: u64 = 1056; const MAX_EPPI_ID: u64 = 1119; const MIN_ESPI_ID: u64 = 4096; const MAX_ESPI_ID: u64 = 5119; const MIN_LPI_ID: u64 = 8192; #[allow(dead_code)] pub struct GicFeatures { pub nr_lrs: usize, pub nr_aprs: usize, pub pri_res0_mask: u64, pub max_vintid: u64, pub ext_range: bool, } lazy_static! { pub static ref GIC_FEATURES: GicFeatures = { trace!("read gic features"); let nr_lrs = ICH_VTR_EL2.read(ICH_VTR_EL2::ListRegs) as usize; trace!("nr_lrs (LIST) {}", nr_lrs); let id = ICH_VTR_EL2.read(ICH_VTR_EL2::IDbits); let max_vintid = if id == 0 { (1u64 << 16) - 1 } else { (1u64 << 24) - 1 }; trace!("id {} max_vintid {}", id, max_vintid); let pre = ICH_VTR_EL2.read(ICH_VTR_EL2::PREbits) + 1; let nr_aprs = (1 << (pre - 5)) - 1; trace!("pre {}, nr_aprs {}", pre, nr_aprs); let pri = ICH_VTR_EL2.read(ICH_VTR_EL2::PRIbits) + 1; let pri_res0_mask = (1u64 << (ICH_LR_PRIORITY_WIDTH - pri)) - 1; trace!("pri {} pri_res0_mask {}", pri, pri_res0_mask); let ext_range = ICC_CTLR_EL1.read(ICC_CTLR_EL1::ExtRange) != 0; trace!("icc_ctlr ext_range {}", ext_range); GicFeatures { nr_lrs, nr_aprs, pri_res0_mask, max_vintid, ext_range, } }; } pub fn nr_lrs() -> usize { GIC_FEATURES.nr_lrs } pub fn nr_aprs() -> usize { GIC_FEATURES.nr_aprs } pub fn pri_res0_mask() -> u64 { GIC_FEATURES.pri_res0_mask } pub fn set_lr(i: usize, val: u64) { match i { 0 => ICH_LR0_EL2.set(val), 1 => ICH_LR1_EL2.set(val), 2 => ICH_LR2_EL2.set(val), 3 => ICH_LR3_EL2.set(val), 4 => ICH_LR4_EL2.set(val), 5 => ICH_LR5_EL2.set(val), 6 => ICH_LR6_EL2.set(val), 7 => ICH_LR7_EL2.set(val), 8 => ICH_LR8_EL2.set(val), 9 => ICH_LR9_EL2.set(val), 10 => ICH_LR10_EL2.set(val), 11 => ICH_LR11_EL2.set(val), 12 => ICH_LR12_EL2.set(val), 13 => ICH_LR13_EL2.set(val), 14 => ICH_LR14_EL2.set(val), 15 => ICH_LR15_EL2.set(val), _ => {} } } pub fn set_ap0r(i: usize, val: u64) { match i { 0 => ICH_AP0R0_EL2.set(val), 1 => ICH_AP0R1_EL2.set(val), 2 => ICH_AP0R2_EL2.set(val), 3 => ICH_AP0R3_EL2.set(val), _ => {} } } pub fn set_ap1r(i: usize, val: u64) { match i { 0 => ICH_AP1R0_EL2.set(val), 1 => ICH_AP1R1_EL2.set(val), 2 => ICH_AP1R2_EL2.set(val), 3 => ICH_AP1R3_EL2.set(val), _ => {} } } pub fn get_lr(i: usize) -> u64 { match i { 0 => ICH_LR0_EL2.get(), 1 => ICH_LR1_EL2.get(), 2 => ICH_LR2_EL2.get(), 3 => ICH_LR3_EL2.get(), 4 => ICH_LR4_EL2.get(), 5 => ICH_LR5_EL2.get(), 6 => ICH_LR6_EL2.get(), 7 => ICH_LR7_EL2.get(), 8 => ICH_LR8_EL2.get(), 9 => ICH_LR9_EL2.get(), 10 => ICH_LR10_EL2.get(), 11 => ICH_LR11_EL2.get(), 12 => ICH_LR12_EL2.get(), 13 => ICH_LR13_EL2.get(), 14 => ICH_LR14_EL2.get(), 15 => ICH_LR15_EL2.get(), _ => unreachable!(), } } pub fn get_ap0r(i: usize) -> u64 { match i { 0 => ICH_AP0R0_EL2.get(), 1 => ICH_AP0R1_EL2.get(), 2 => ICH_AP0R2_EL2.get(), 3 => ICH_AP0R3_EL2.get(), _ => unreachable!(), } } pub fn get_ap1r(i: usize) -> u64 { match i { 0 => ICH_AP1R0_EL2.get(), 1 => ICH_AP1R1_EL2.get(), 2 => ICH_AP1R2_EL2.get(), 3 => ICH_AP1R3_EL2.get(), _ => unreachable!(), } } pub fn valid_vintid(intid: u64) -> bool { /* Check for INTID [0..1019] and [8192..] */ if intid <= MAX_SPI_ID || (intid >= MIN_LPI_ID && intid <= GIC_FEATURES.max_vintid) { return true; } /* * If extended INTID range sopported, check for * Extended PPI [1056..1119] and Extended SPI [4096..5119] */ if GIC_FEATURES.ext_range { return (intid >= MIN_EPPI_ID && intid <= MAX_EPPI_ID) || (intid >= MIN_ESPI_ID && intid <= MAX_ESPI_ID); } false }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/macro.rs
rmm/src/macro.rs
// TODO: Expands to cover args, ret #[macro_export] macro_rules! define_interface { (command {$($variant:ident = $val:expr),*,}) => { $(pub const $variant: usize = $val;)* pub fn to_str(code: usize) -> alloc::string::String { use alloc::string::ToString; use alloc::format; match code { $($variant => stringify!($variant).to_string()),*, _ => format!("Undefined {}", code) } } }; } #[macro_export] macro_rules! print { ($($arg:tt)*) => { let buffer = alloc::format!($($arg)*); let _ = io::stdout().write_all(buffer.as_bytes()); }; } #[macro_export] macro_rules! println { () => {crate::print!("\n")}; ($fmt:expr) => {crate::print!(concat!($fmt, "\n"))}; ($fmt:expr, $($arg:tt)*) => {crate::print!(concat!($fmt, "\n"), $($arg)*)}; } #[macro_export] macro_rules! eprint { ($fmt:expr) => { let buffer = concat!("\x1b[0;31m", $fmt, "\x1b[0m"); let _ = io::stdout().write_all(buffer.as_bytes()); }; ($fmt:expr, $($arg:tt)*) => {{ let buffer = alloc::format!(concat!("\x1b[0;31m", $fmt, "\x1b[0m"), $($arg)*); let _ = io::stdout().write_all(buffer.as_bytes()); }}; } #[macro_export] macro_rules! eprintln { () => {crate::eprint!("\n")}; ($fmt:expr) => {crate::eprint!(concat!($fmt, "\n"))}; ($fmt:expr, $($arg:tt)*) => {crate::eprint!(concat!($fmt, "\n"), $($arg)*)}; } #[macro_export] macro_rules! const_assert { ($cond:expr) => { // Causes overflow if condition is false let _ = [(); 0 - (!($cond) as usize)]; }; } #[macro_export] macro_rules! const_assert_eq { ($left:expr, $right:expr) => { const _: () = { crate::const_assert!($left == $right); }; }; } #[macro_export] macro_rules! const_assert_size { ($struct:ty, $size:expr) => { crate::const_assert_eq!(core::mem::size_of::<$struct>(), ($size)); }; } #[cfg(test)] mod test { extern crate alloc; use crate::{eprintln, println}; use alloc::boxed::Box; use alloc::string::String; use alloc::vec::Vec; use core::cell::RefCell; use io::{stdout, Write as IoWrite}; use io::{ConsoleWriter, Device, Result, Write}; pub struct MockDevice { buffer: RefCell<Vec<u8>>, ready: bool, } impl MockDevice { pub const fn new() -> Self { MockDevice { buffer: RefCell::new(Vec::new()), ready: false, } } pub fn output(&self) -> String { String::from_utf8(self.buffer.borrow().to_vec()).unwrap() } } impl Device for MockDevice { fn initialize(&mut self) -> Result<()> { self.ready = true; Ok(()) } fn initialized(&self) -> bool { self.ready } } impl Write for MockDevice { fn write_all(&mut self, buf: &[u8]) -> Result<()> { self.buffer.borrow_mut().extend_from_slice(buf); Ok(()) } } impl ConsoleWriter for MockDevice {} #[test] fn println_without_arg() { let mock = Box::new(MockDevice::new()); let mock_ptr = mock.as_ref() as *const MockDevice; stdout().attach(mock).ok().unwrap(); println!(); assert_eq!(unsafe { (*mock_ptr).output() }, "\n"); } #[test] fn println_without_format() { let mock = Box::new(MockDevice::new()); let mock_ptr = mock.as_ref() as *const MockDevice; stdout().attach(mock).ok().unwrap(); println!("hello"); assert_eq!(unsafe { (*mock_ptr).output() }, "hello\n"); } #[test] fn println_with_format() { let mock = Box::new(MockDevice::new()); let mock_ptr = mock.as_ref() as *const MockDevice; stdout().attach(mock).ok().unwrap(); println!("number {}", 1234); assert_eq!(unsafe { (*mock_ptr).output() }, "number 1234\n"); } #[test] fn eprintln_without_arg() { let mock = Box::new(MockDevice::new()); let mock_ptr = mock.as_ref() as *const MockDevice; stdout().attach(mock).ok().unwrap(); eprintln!(); assert_eq!(unsafe { (*mock_ptr).output() }, "\x1b[0;31m\n\x1b[0m"); } #[test] fn eprintln_without_format() { let mock = Box::new(MockDevice::new()); let mock_ptr = mock.as_ref() as *const MockDevice; stdout().attach(mock).ok().unwrap(); eprintln!("hello"); assert_eq!(unsafe { (*mock_ptr).output() }, "\x1b[0;31mhello\n\x1b[0m"); } #[test] fn eprintln_with_format() { let mock = Box::new(MockDevice::new()); let mock_ptr = mock.as_ref() as *const MockDevice; stdout().attach(mock).ok().unwrap(); eprintln!("number {}", 4321); assert_eq!( unsafe { (*mock_ptr).output() }, "\x1b[0;31mnumber 4321\n\x1b[0m" ); } #[test] fn set_of_const_assert() { const_assert!(1 != 2); const_assert!(true); const_assert_eq!(1, 1); const_assert_eq!(false, false); const_assert_size!(u32, 4); const_assert_size!(u64, 8); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/stat.rs
rmm/src/stat.rs
use crate::allocator; use crate::rmi; use crate::rsi; use spin::mutex::Mutex; use crate::alloc::string::ToString; use alloc::string::String; //NOTE: RMI, RSI_CMD_MAX are should be updated whenever there is a new command // which is bigger than the current max value of the commands. // But if RMI, RSI commands are handled by 'Enum', then it can be fixed // by using the max enum value like MAX_KIND const RMI_CMD_MIN: usize = rmi::VERSION; const RMI_CMD_MAX: usize = rmi::RTT_SET_RIPAS; const RMI_CMD_CNT: usize = RMI_CMD_MAX - RMI_CMD_MIN + 1; const RSI_CMD_MIN: usize = rsi::ABI_VERSION; const RSI_CMD_MAX: usize = rsi::HOST_CALL; const RSI_CMD_CNT: usize = RSI_CMD_MAX - RSI_CMD_MIN + 1; const MAX_CMD_CNT: usize = max(RMI_CMD_CNT, RSI_CMD_CNT); const MAX_KIND: usize = Kind::Undefined as usize; const fn max(a: usize, b: usize) -> usize { if a >= b { a } else { b } } lazy_static! { pub static ref STATS: Mutex<Stats> = Mutex::new(Stats::new()); } #[inline(always)] fn is_rmi_cmd(cmd: usize) -> bool { RMI_CMD_MIN <= cmd && cmd <= RMI_CMD_MAX } #[inline(always)] fn is_rsi_cmd(cmd: usize) -> bool { RSI_CMD_MIN <= cmd && cmd <= RSI_CMD_MAX } #[repr(C)] #[derive(Copy, Clone)] pub struct Stats { collected_stat_cnt: u64, list: [Stat; MAX_KIND], } impl Stats { fn new() -> Self { let mut stats = Stats { collected_stat_cnt: 0, list: [Stat::default(); MAX_KIND], }; for i in 0..MAX_KIND { stats.list[i] = Stat::new(Kind::from(i)); } stats } fn get_stat(&mut self, cmd: usize) -> Result<&mut Stat, Error> { let kind = Kind::get_kind(cmd)?; Ok(&mut self.list[kind as usize]) } pub fn measure<F: FnMut()>(&mut self, cmd: usize, mut handler: F) { if let Err(e) = self.start(cmd) { info!("stats.start is failed: {:?} with cmd {:x}", e, cmd); } handler(); if let Err(e) = self.end(cmd) { info!("stats.end is failed: {:?} with cmd {:x}", e, cmd); } } fn start(&mut self, cmd: usize) -> Result<(), Error> { let stat = self.get_stat(cmd)?; trace!("start Stat with command {}", stat.cmd_to_str(cmd)); stat.start(cmd) } fn end(&mut self, cmd: usize) -> Result<(), Error> { let stat = self.get_stat(cmd)?; if stat.overflowed { return Err(Error::IntegerOverflow); } if let Err(Error::IntegerOverflow) = stat.update(cmd) { stat.overflowed = true; return Err(Error::IntegerOverflow); } self.collected_stat_cnt = self.collected_stat_cnt.wrapping_add(1); if self.collected_stat_cnt % 10 == 0 { self.print(); } Ok(()) } fn print(&self) { info!("=============================================== STATS::PRINT() START ============================================="); for i in 0..MAX_KIND { if let Err(e) = self.list[i].print_all() { info!("Failed to print Stats: {:?}", e); } } info!( "TOTAL MemUsed in RMM HEAP: {: >12} byte", allocator::get_used_size() ); info!("=============================================== STATS::PRINT() END ==============================================="); } } #[repr(C)] #[derive(Copy, Clone, Debug, Default)] struct Stat { kind: Kind, overflowed: bool, cur_cmd: Option<usize>, call_cnt: [u64; MAX_CMD_CNT], mem_used_before: Option<i64>, total_mem_used: [i64; MAX_CMD_CNT], } impl Stat { fn new(kind: Kind) -> Self { Stat { kind, ..Default::default() } } fn cmd_to_str(&self, cmd: usize) -> String { match self.kind { Kind::RMI => rmi::to_str(cmd), Kind::RSI => rsi::to_str(cmd), _ => "Undefined".to_string(), } } fn print_mem_stat(&self, idx: usize, cmd: usize, avg_mem_used: i64) { info!( "{:?}::{: <25} TOTAL MemUsed: {: >12} byte, AVG MemUsed: {: >10} byte, CallCnt: {: >8}", self.kind, self.cmd_to_str(cmd), self.total_mem_used[idx], avg_mem_used, self.call_cnt[idx] ); } fn print(&self, cmd: usize) -> Result<(), Error> { let idx = self.get_idx(cmd)?; if self.call_cnt[idx] == 0 { return Ok(()); } if self.total_mem_used[idx] == 0 { self.print_mem_stat(idx, cmd, 0); return Ok(()); } let avg_mem_used = self.total_mem_used[idx].checked_div(self.call_cnt[idx] as i64); if avg_mem_used.is_none() { return Err(Error::IntegerOverflow); } self.print_mem_stat(idx, cmd, avg_mem_used.unwrap()); Ok(()) } fn print_all(&self) -> Result<(), Error> { let cmd_min = match self.kind { Kind::RMI => RMI_CMD_MIN, Kind::RSI => RSI_CMD_MIN, _ => return Ok(()), }; for i in 0..MAX_CMD_CNT { self.print(cmd_min + i)?; } Ok(()) } fn start(&mut self, cmd: usize) -> Result<(), Error> { if self.mem_used_before.is_some() || self.cur_cmd.is_some() { return Err(Error::MismatchedSequence); } self.mem_used_before = Some(allocator::get_used_size() as i64); self.cur_cmd = Some(cmd); Ok(()) } fn get_idx(&self, cmd: usize) -> Result<usize, Error> { let idx = match self.kind { Kind::RMI => cmd.checked_sub(RMI_CMD_MIN), Kind::RSI => cmd.checked_sub(RSI_CMD_MIN), _ => return Err(Error::Unknown), }; if idx.is_none() { error!("get_idx is failed with: {:?}", Error::IntegerOverflow); return Err(Error::IntegerOverflow); } Ok(idx.unwrap()) } fn update(&mut self, cmd: usize) -> Result<(), Error> { if self.mem_used_before.is_none() || self.cur_cmd.is_none() { return Err(Error::MismatchedSequence); } if cmd != self.cur_cmd.unwrap() { return Err(Error::MismatchedCommand); } let idx = self.get_idx(cmd)?; let mem_used_after = allocator::get_used_size() as i64; let mem_used_before = self.mem_used_before.unwrap(); if mem_used_after.checked_sub(mem_used_before).is_none() { error!( "Failed to subtract mem_used_before {:x} from mem_used_after {:x}", mem_used_before, mem_used_after ); return Err(Error::IntegerOverflow); } let cur_mem_used = mem_used_after - mem_used_before; if self.total_mem_used[idx].checked_add(cur_mem_used).is_none() { error!( "Failed to add {:x} to total_mem_used[{}] {:x}", cur_mem_used, idx, self.total_mem_used[idx] ); return Err(Error::IntegerOverflow); } self.total_mem_used[idx] += cur_mem_used; if self.call_cnt[idx].checked_add(1).is_none() { error!( "Failed to add 1 to call_cnt[{}] {:x}", idx, self.call_cnt[idx] ); return Err(Error::IntegerOverflow); } self.call_cnt[idx] += 1; if let Err(e) = self.print(cmd) { error!("error to print Stat {:?}, {}", e, self.cmd_to_str(cmd)); } // clean up after updating self.mem_used_before = None; self.cur_cmd = None; Ok(()) } } #[derive(Copy, Clone, Debug)] pub enum Kind { RMI = 0, RSI = 1, Undefined, } impl Default for Kind { fn default() -> Self { Kind::Undefined } } impl From<usize> for Kind { fn from(num: usize) -> Self { match num { 0 => Kind::RMI, 1 => Kind::RSI, _ => Kind::Undefined, } } } impl Kind { fn get_kind(cmd: usize) -> Result<Self, Error> { if is_rmi_cmd(cmd) { return Ok(Kind::RMI); } else if is_rsi_cmd(cmd) { return Ok(Kind::RSI); } Err(Error::InvalidCommand) } } #[derive(Debug)] pub enum Error { IntegerOverflow = 1, InvalidCommand = 2, MismatchedCommand = 3, MismatchedSequence = 4, Unknown, }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/logger.rs
rmm/src/logger.rs
use io::Write; use log::{Level, LevelFilter, Metadata, Record}; struct SimpleLogger; extern crate alloc; impl log::Log for SimpleLogger { fn enabled(&self, metadata: &Metadata<'_>) -> bool { metadata.level() <= Level::Trace } fn log(&self, record: &Record<'_>) { if self.enabled(record.metadata()) { if record.metadata().level() <= Level::Warn { crate::eprintln!( "[{}]{} -- {}", record.level(), record.target(), record.args() ); } else { crate::println!( "[{}]{} -- {}", record.level(), record.target(), record.args() ); } } } fn flush(&self) {} } static LOGGER: SimpleLogger = SimpleLogger; pub fn register_global_logger(maxlevel: LevelFilter) { log::set_logger(&LOGGER).unwrap(); log::set_max_level(maxlevel); }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/pmu.rs
rmm/src/pmu.rs
use aarch64_cpu::registers::*; use armv9a::regs::pmu::*; use armv9a::PMCR_EL0; pub const MAX_EVCNT: usize = 31; #[allow(non_upper_case_globals)] const FEAT_PMUv3p7: u64 = 7; #[cfg(not(feature = "qemu"))] const PMU_MIN_VER: u64 = FEAT_PMUv3p7; #[cfg(feature = "qemu")] const PMU_MIN_VER: u64 = 5; // FEAT_PMUv3p5 // ID_AA64DFR0_EL1 // HPMN0, bits [63:60] : // Zero PMU event counters for a Guest operating system. const HPMN0_MASK: u64 = 0xF << 60; pub fn pmu_present() -> bool { trace!( "PMUVer: v3p{:?}", ID_AA64DFR0_EL1.read(ID_AA64DFR0_EL1::PMUVer) ); ID_AA64DFR0_EL1.read(ID_AA64DFR0_EL1::PMUVer) >= PMU_MIN_VER } pub fn hpmn0_present() -> bool { trace!( "FEAT_HPMN0: {:?}", (ID_AA64DFR0_EL1.get() & HPMN0_MASK) >> 60 ); ID_AA64DFR0_EL1.get() & HPMN0_MASK != 0 } pub fn pmu_num_ctrs() -> u64 { trace!("PMU # counters: {:?}", PMCR_EL0.read(PMCR_EL0::N)); PMCR_EL0.read(PMCR_EL0::N) } fn store_pmev(n: usize, pmevcntr_el0: &mut [u64; MAX_EVCNT], pmevtyper_el0: &mut [u64; MAX_EVCNT]) { match n { 0 => { pmevcntr_el0[0] = PMEVCNTR0_EL0.get(); pmevtyper_el0[0] = PMEVTYPER0_EL0.get(); } 1 => { pmevcntr_el0[1] = PMEVCNTR1_EL0.get(); pmevtyper_el0[1] = PMEVTYPER1_EL0.get(); } 2 => { pmevcntr_el0[2] = PMEVCNTR2_EL0.get(); pmevtyper_el0[2] = PMEVTYPER2_EL0.get(); } 3 => { pmevcntr_el0[3] = PMEVCNTR3_EL0.get(); pmevtyper_el0[3] = PMEVTYPER3_EL0.get(); } 4 => { pmevcntr_el0[4] = PMEVCNTR4_EL0.get(); pmevtyper_el0[4] = PMEVTYPER4_EL0.get(); } 5 => { pmevcntr_el0[5] = PMEVCNTR5_EL0.get(); pmevtyper_el0[5] = PMEVTYPER5_EL0.get(); } 6 => { pmevcntr_el0[6] = PMEVCNTR6_EL0.get(); pmevtyper_el0[6] = PMEVTYPER6_EL0.get(); } 7 => { pmevcntr_el0[7] = PMEVCNTR7_EL0.get(); pmevtyper_el0[7] = PMEVTYPER7_EL0.get(); } 8 => { pmevcntr_el0[8] = PMEVCNTR8_EL0.get(); pmevtyper_el0[8] = PMEVTYPER8_EL0.get(); } 9 => { pmevcntr_el0[9] = PMEVCNTR9_EL0.get(); pmevtyper_el0[9] = PMEVTYPER9_EL0.get(); } 10 => { pmevcntr_el0[10] = PMEVCNTR10_EL0.get(); pmevtyper_el0[10] = PMEVTYPER10_EL0.get(); } 11 => { pmevcntr_el0[11] = PMEVCNTR11_EL0.get(); pmevtyper_el0[11] = PMEVTYPER11_EL0.get(); } 12 => { pmevcntr_el0[12] = PMEVCNTR12_EL0.get(); pmevtyper_el0[12] = PMEVTYPER12_EL0.get(); } 13 => { pmevcntr_el0[13] = PMEVCNTR13_EL0.get(); pmevtyper_el0[13] = PMEVTYPER13_EL0.get(); } 14 => { pmevcntr_el0[14] = PMEVCNTR14_EL0.get(); pmevtyper_el0[14] = PMEVTYPER14_EL0.get(); } 15 => { pmevcntr_el0[15] = PMEVCNTR15_EL0.get(); pmevtyper_el0[15] = PMEVTYPER15_EL0.get(); } 16 => { pmevcntr_el0[16] = PMEVCNTR16_EL0.get(); pmevtyper_el0[16] = PMEVTYPER16_EL0.get(); } 17 => { pmevcntr_el0[17] = PMEVCNTR17_EL0.get(); pmevtyper_el0[17] = PMEVTYPER17_EL0.get(); } 18 => { pmevcntr_el0[18] = PMEVCNTR18_EL0.get(); pmevtyper_el0[18] = PMEVTYPER18_EL0.get(); } 19 => { pmevcntr_el0[19] = PMEVCNTR19_EL0.get(); pmevtyper_el0[19] = PMEVTYPER19_EL0.get(); } 20 => { pmevcntr_el0[20] = PMEVCNTR20_EL0.get(); pmevtyper_el0[20] = PMEVTYPER20_EL0.get(); } 21 => { pmevcntr_el0[21] = PMEVCNTR21_EL0.get(); pmevtyper_el0[21] = PMEVTYPER21_EL0.get(); } 22 => { pmevcntr_el0[22] = PMEVCNTR22_EL0.get(); pmevtyper_el0[22] = PMEVTYPER22_EL0.get(); } 23 => { pmevcntr_el0[23] = PMEVCNTR23_EL0.get(); pmevtyper_el0[23] = PMEVTYPER23_EL0.get(); } 24 => { pmevcntr_el0[24] = PMEVCNTR24_EL0.get(); pmevtyper_el0[24] = PMEVTYPER24_EL0.get(); } 25 => { pmevcntr_el0[25] = PMEVCNTR25_EL0.get(); pmevtyper_el0[25] = PMEVTYPER25_EL0.get(); } 26 => { pmevcntr_el0[26] = PMEVCNTR26_EL0.get(); pmevtyper_el0[26] = PMEVTYPER26_EL0.get(); } 27 => { pmevcntr_el0[27] = PMEVCNTR27_EL0.get(); pmevtyper_el0[27] = PMEVTYPER27_EL0.get(); } 28 => { pmevcntr_el0[28] = PMEVCNTR28_EL0.get(); pmevtyper_el0[28] = PMEVTYPER28_EL0.get(); } 29 => { pmevcntr_el0[29] = PMEVCNTR29_EL0.get(); pmevtyper_el0[29] = PMEVTYPER29_EL0.get(); } 30 => { pmevcntr_el0[30] = PMEVCNTR30_EL0.get(); pmevtyper_el0[30] = PMEVTYPER30_EL0.get(); } _ => warn!("Invalid PMEV index"), } } fn load_pmev(n: usize, cntr_val: u64, typer_val: u64) { match n { 0 => { PMEVCNTR0_EL0.set(cntr_val); PMEVTYPER0_EL0.set(typer_val); } 1 => { PMEVCNTR1_EL0.set(cntr_val); PMEVTYPER1_EL0.set(typer_val); } 2 => { PMEVCNTR2_EL0.set(cntr_val); PMEVTYPER2_EL0.set(typer_val); } 3 => { PMEVCNTR3_EL0.set(cntr_val); PMEVTYPER3_EL0.set(typer_val); } 4 => { PMEVCNTR4_EL0.set(cntr_val); PMEVTYPER4_EL0.set(typer_val); } 5 => { PMEVCNTR5_EL0.set(cntr_val); PMEVTYPER5_EL0.set(typer_val); } 6 => { PMEVCNTR6_EL0.set(cntr_val); PMEVTYPER6_EL0.set(typer_val); } 7 => { PMEVCNTR7_EL0.set(cntr_val); PMEVTYPER7_EL0.set(typer_val); } 8 => { PMEVCNTR8_EL0.set(cntr_val); PMEVTYPER8_EL0.set(typer_val); } 9 => { PMEVCNTR9_EL0.set(cntr_val); PMEVTYPER9_EL0.set(typer_val); } 10 => { PMEVCNTR10_EL0.set(cntr_val); PMEVTYPER10_EL0.set(typer_val); } 11 => { PMEVCNTR11_EL0.set(cntr_val); PMEVTYPER11_EL0.set(typer_val); } 12 => { PMEVCNTR12_EL0.set(cntr_val); PMEVTYPER12_EL0.set(typer_val); } 13 => { PMEVCNTR13_EL0.set(cntr_val); PMEVTYPER13_EL0.set(typer_val); } 14 => { PMEVCNTR14_EL0.set(cntr_val); PMEVTYPER14_EL0.set(typer_val); } 15 => { PMEVCNTR15_EL0.set(cntr_val); PMEVTYPER15_EL0.set(typer_val); } 16 => { PMEVCNTR16_EL0.set(cntr_val); PMEVTYPER16_EL0.set(typer_val); } 17 => { PMEVCNTR17_EL0.set(cntr_val); PMEVTYPER17_EL0.set(typer_val); } 18 => { PMEVCNTR18_EL0.set(cntr_val); PMEVTYPER18_EL0.set(typer_val); } 19 => { PMEVCNTR19_EL0.set(cntr_val); PMEVTYPER19_EL0.set(typer_val); } 20 => { PMEVCNTR20_EL0.set(cntr_val); PMEVTYPER20_EL0.set(typer_val); } 21 => { PMEVCNTR21_EL0.set(cntr_val); PMEVTYPER21_EL0.set(typer_val); } 22 => { PMEVCNTR22_EL0.set(cntr_val); PMEVTYPER22_EL0.set(typer_val); } 23 => { PMEVCNTR23_EL0.set(cntr_val); PMEVTYPER23_EL0.set(typer_val); } 24 => { PMEVCNTR24_EL0.set(cntr_val); PMEVTYPER24_EL0.set(typer_val); } 25 => { PMEVCNTR25_EL0.set(cntr_val); PMEVTYPER25_EL0.set(typer_val); } 26 => { PMEVCNTR26_EL0.set(cntr_val); PMEVTYPER26_EL0.set(typer_val); } 27 => { PMEVCNTR27_EL0.set(cntr_val); PMEVTYPER27_EL0.set(typer_val); } 28 => { PMEVCNTR28_EL0.set(cntr_val); PMEVTYPER28_EL0.set(typer_val); } 29 => { PMEVCNTR29_EL0.set(cntr_val); PMEVTYPER29_EL0.set(typer_val); } 30 => { PMEVCNTR30_EL0.set(cntr_val); PMEVTYPER30_EL0.set(typer_val); } _ => warn!("Invalid PMEV index"), } } pub fn set_pmev_regs( cnt: usize, pmevcntr_el0: &[u64; MAX_EVCNT], pmevtyper_el0: &[u64; MAX_EVCNT], ) { if cnt > MAX_EVCNT { error!("Index out of bounds"); return; } for i in 0..cnt { load_pmev(i, pmevcntr_el0[i], pmevtyper_el0[i]); } } pub fn get_pmev_regs( cnt: usize, pmevcntr_el0: &mut [u64; MAX_EVCNT], pmevtyper_el0: &mut [u64; MAX_EVCNT], ) { if cnt > MAX_EVCNT { error!("Index out of bounds"); return; } for i in 0..cnt { store_pmev(i, pmevcntr_el0, pmevtyper_el0); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/panic.rs
rmm/src/panic.rs
#[alloc_error_handler] fn alloc_error_handler(_layout: core::alloc::Layout) -> ! { panic!("OOM! memory allocation of {} bytes failed", _layout.size()) } #[panic_handler] pub fn panic_handler(_info: &core::panic::PanicInfo<'_>) -> ! { error!("RMM: {}", _info); halt() } pub fn halt() -> ! { loop {} }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/test_utils.rs
rmm/src/test_utils.rs
use crate::event::Context; use crate::event::Mainloop; use crate::granule::GRANULE_SIZE; use crate::monitor::Monitor; use crate::rmi::realm::Params as RealmParams; use crate::rmi::rec::params::Params as RecParams; use crate::rmi::*; pub use mock::host::{alloc_granule, granule_addr}; use alloc::vec::Vec; pub fn rmi<const COMMAND: usize>(arg: &[usize]) -> Vec<usize> { let monitor = Monitor::new(); let mut ctx = Context::new(COMMAND); ctx.init_arg(&arg); ctx.init_ret(&[0; 8]); let handler = monitor.rmi.on_event.get(&COMMAND).unwrap(); if let Err(code) = handler(&ctx.arg, &mut ctx.ret, &monitor) { ctx.ret[0] = code.into(); } ctx.ret.to_vec() } pub fn extract_bits(value: usize, start: u32, end: u32) -> usize { let num_bits = end - start + 1; let mask = if num_bits == usize::BITS { usize::MAX } else { (1 << num_bits) - 1 }; (value >> start) & mask } pub fn realm_create() -> usize { for mocking_addr in &[alloc_granule(IDX_RD), alloc_granule(IDX_RTT_LEVEL0)] { let ret = rmi::<GRANULE_DELEGATE>(&[*mocking_addr]); assert_eq!(ret[0], SUCCESS); } let (rd, rtt, params_ptr) = ( alloc_granule(IDX_RD), alloc_granule(IDX_RTT_LEVEL0), alloc_granule(IDX_REALM_PARAMS), ); unsafe { let params = &mut *(params_ptr as *mut RealmParams); params.s2sz = 40; params.rtt_num_start = 1; params.rtt_level_start = 0; params.rtt_base = rtt as u64; }; let ret = rmi::<REALM_CREATE>(&[rd, params_ptr]); assert_eq!(ret[0], SUCCESS); rd } pub fn realm_destroy(rd: usize) { let ret = rmi::<REALM_DESTROY>(&[rd]); assert_eq!(ret[0], SUCCESS); for mocking_addr in &[granule_addr(IDX_RD), granule_addr(IDX_RTT_LEVEL0)] { let ret = rmi::<GRANULE_UNDELEGATE>(&[*mocking_addr]); assert_eq!(ret[0], SUCCESS); } } pub fn rec_create(rd: usize, idx_rec: usize, idx_rec_params: usize, idx_rec_aux_start: usize) { let (rec, params_ptr) = (alloc_granule(idx_rec), alloc_granule(idx_rec_params)); let ret = rmi::<GRANULE_DELEGATE>(&[rec]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<REC_AUX_COUNT>(&[rd]); assert_eq!(ret[0], SUCCESS); assert_eq!(ret[1], MAX_REC_AUX_GRANULES); let aux_count = ret[1]; unsafe { let params = &mut *(params_ptr as *mut RecParams); params.pc = 0; params.flags = 1; // RMI_RUNNABLE params.mpidr = (idx_rec % IDX_REC1) as u64; params.num_aux = aux_count as u64; for idx in 0..aux_count { let mocking_addr = alloc_granule(idx + idx_rec_aux_start); let ret = rmi::<GRANULE_DELEGATE>(&[mocking_addr]); assert_eq!(ret[0], SUCCESS); params.aux[idx] = mocking_addr as u64; } } let ret = rmi::<REC_CREATE>(&[rd, rec, params_ptr]); assert_eq!(ret[0], SUCCESS); } pub fn rec_destroy(idx_rec: usize, idx_rec_aux_start: usize) { let rec = granule_addr(idx_rec); let ret = rmi::<REC_DESTROY>(&[rec]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<GRANULE_UNDELEGATE>(&[rec]); assert_eq!(ret[0], SUCCESS); for idx in 0..MAX_REC_AUX_GRANULES { let mocking_addr = granule_addr(idx + idx_rec_aux_start); let ret = rmi::<GRANULE_UNDELEGATE>(&[mocking_addr]); assert_eq!(ret[0], SUCCESS); } } pub fn data_create(rd: usize, ipa: usize, idx_data: usize, idx_src: usize) { const RMI_NO_MEASURE_CONTENT: usize = 0; mock::host::map(rd, ipa); let base = (ipa / L3_SIZE) * L3_SIZE; let top = base + L3_SIZE; let ret = rmi::<RTT_INIT_RIPAS>(&[rd, base, top]); assert_eq!(ret[0], SUCCESS); let data = alloc_granule(idx_data); let ret = rmi::<GRANULE_DELEGATE>(&[data]); assert_eq!(ret[0], SUCCESS); let src = alloc_granule(idx_src); let flags = RMI_NO_MEASURE_CONTENT; let ret = rmi::<DATA_CREATE>(&[rd, data, ipa, src, flags]); assert_eq!(ret[0], SUCCESS); } pub fn align_up(addr: usize) -> usize { let align_mask = GRANULE_SIZE - 1; if addr & align_mask == 0 { addr } else { (addr | align_mask) + 1 } } #[cfg(fuzzing)] pub fn align_up_l2(addr: usize) -> usize { let align_mask = L2_SIZE - 1; if addr & align_mask == 0 { addr } else { (addr | align_mask) + 1 } } pub const IDX_RD: usize = 0; pub const IDX_RTT_LEVEL0: usize = 1; pub const IDX_REALM_PARAMS: usize = 2; pub const IDX_RTT_LEVEL1: usize = 3; pub const IDX_RTT_LEVEL2: usize = 4; pub const IDX_RTT_LEVEL3: usize = 5; pub const IDX_RTT_OTHER: usize = 6; pub const IDX_REC1: usize = 7; pub const IDX_REC2: usize = 8; pub const IDX_REC1_AUX: usize = 9; pub const IDX_REC2_AUX: usize = 25; // 9 + 16 pub const IDX_REC1_PARAMS: usize = 41; // 25 + 16 pub const IDX_REC2_PARAMS: usize = 42; pub const IDX_REC1_RUN: usize = 43; pub const IDX_NS_DESC: usize = 45; pub const IDX_DATA1: usize = 46; pub const IDX_DATA2: usize = 47; pub const IDX_DATA3: usize = 48; pub const IDX_DATA4: usize = 49; pub const IDX_SRC1: usize = 50; pub const IDX_SRC2: usize = 51; #[cfg(fuzzing)] pub const IDX_L2_ALIGNED_DATA: usize = 0; pub const MAP_LEVEL: usize = 3; pub const L3_SIZE: usize = GRANULE_SIZE; pub const L2_SIZE: usize = 512 * L3_SIZE; pub const L1_SIZE: usize = 512 * L2_SIZE; pub const L0_SIZE: usize = 512 * L1_SIZE; pub const IPA_WIDTH: usize = 40; pub const ATTR_NORMAL_WB_WA_RA: usize = 1 << 2; pub const ATTR_STAGE2_AP_RW: usize = 3 << 6; pub const ATTR_INNER_SHARED: usize = 3 << 8; pub const REC_ENTER_EXIT_CMD: usize = 0; /// This function is a temporary workaround to pass the MIRI test due to a memory leak bug /// related to the RMM Page Table. It forces the RMM Page Table to drop at the end of the /// test, preventing the memory leak issue from occurring during MIRI testing. /// /// - Memory Leak in RMM Page Table: During the mapping/unmapping process, the Page Table /// might not deallocate even when there are no entries in Level 1-3 tables. /// /// Note: When testing this function individually, set `TEST_TOTAL` to 1. pub fn miri_teardown() { use core::sync::atomic::AtomicUsize; use core::sync::atomic::Ordering; const TEST_TOTAL: usize = 11; static TEST_COUNT: AtomicUsize = AtomicUsize::new(0); TEST_COUNT.fetch_add(1, Ordering::SeqCst); if TEST_COUNT.load(Ordering::SeqCst) == TEST_TOTAL { crate::mm::translation::drop_page_table(); } } pub mod mock { pub mod host { use super::super::*; use crate::granule::{GRANULE_REGION, GRANULE_SIZE}; use crate::rmi::{RTT_CREATE, RTT_DESTROY, RTT_READ_ENTRY}; pub use alloc_granule as granule_addr; /// This function simulates memory allocation by using a portion of the /// pre-allocated memory within the RMM. /// It mocks the memory allocation provided by host and is designed /// to bypass provenance issues detected by MIRI. pub fn alloc_granule(idx: usize) -> usize { let start = unsafe { GRANULE_REGION.as_ptr() as usize }; let first = crate::test_utils::align_up(start); first + idx * GRANULE_SIZE } /// Mock allocation of granules starting from an L2 aligned address for RTT fold fuzzing. /// The granule region is made big enough to make space for these granules in the /// fuzzing setup. It is also ensured these granules do not collide with the /// regular mock granules. #[cfg(fuzzing)] pub fn alloc_granule_l2_aligned(idx: usize) -> usize { let start = unsafe { GRANULE_REGION.as_ptr() as usize }; let first = crate::test_utils::align_up_l2(start + L2_SIZE); first + idx * GRANULE_SIZE } pub fn map(rd: usize, ipa: usize) { let ret = rmi::<RTT_READ_ENTRY>(&[rd, ipa, MAP_LEVEL]); assert_eq!(ret[0], SUCCESS); let (level, _state, _desc, _ripas) = (ret[1], ret[2], ret[3], ret[4]); let (rtt_l1, rtt_l2, rtt_l3) = ( alloc_granule(IDX_RTT_LEVEL1), alloc_granule(IDX_RTT_LEVEL2), alloc_granule(IDX_RTT_LEVEL3), ); if level < 1 { let ret = rmi::<GRANULE_DELEGATE>(&[rtt_l1]); assert_eq!(ret[0], SUCCESS); let ipa_aligned = (ipa / L0_SIZE) * L0_SIZE; let ret = rmi::<RTT_CREATE>(&[rd, rtt_l1, ipa_aligned, 1]); assert_eq!(ret[0], SUCCESS); } if level < 2 { let ret = rmi::<GRANULE_DELEGATE>(&[rtt_l2]); assert_eq!(ret[0], SUCCESS); let ipa_aligned = (ipa / L1_SIZE) * L1_SIZE; let ret = rmi::<RTT_CREATE>(&[rd, rtt_l2, ipa_aligned, 2]); assert_eq!(ret[0], SUCCESS); } if level < 3 { let ret = rmi::<GRANULE_DELEGATE>(&[rtt_l3]); assert_eq!(ret[0], SUCCESS); let ipa_aligned = (ipa / L2_SIZE) * L2_SIZE; let ret = rmi::<RTT_CREATE>(&[rd, rtt_l3, ipa_aligned, 3]); assert_eq!(ret[0], SUCCESS); } } pub fn unmap(rd: usize, ipa: usize, folded: bool) { if !folded { let ipa_aligned = (ipa / L2_SIZE) * L2_SIZE; let ret = rmi::<RTT_DESTROY>(&[rd, ipa_aligned, 3]); assert_eq!(ret[0], SUCCESS); } let ipa_aligned = (ipa / L1_SIZE) * L1_SIZE; let ret = rmi::<RTT_DESTROY>(&[rd, ipa_aligned, 2]); assert_eq!(ret[0], SUCCESS); let ipa_aligned = (ipa / L0_SIZE) * L0_SIZE; let ret = rmi::<RTT_DESTROY>(&[rd, ipa_aligned, 1]); assert_eq!(ret[0], SUCCESS); for mocking_addr in &[ granule_addr(IDX_RTT_LEVEL1), granule_addr(IDX_RTT_LEVEL2), granule_addr(IDX_RTT_LEVEL3), ] { let ret = rmi::<GRANULE_UNDELEGATE>(&[*mocking_addr]); assert_eq!(ret[0], SUCCESS); } } pub fn realm_setup() -> usize { let rd = realm_create(); rec_create(rd, IDX_REC1, IDX_REC1_PARAMS, IDX_REC1_AUX); rec_create(rd, IDX_REC2, IDX_REC2_PARAMS, IDX_REC2_AUX); let ret = rmi::<REALM_ACTIVATE>(&[rd]); assert_eq!(ret[0], SUCCESS); rd } pub fn realm_unactivated_setup() -> usize { let rd = realm_create(); rec_create(rd, IDX_REC1, IDX_REC1_PARAMS, IDX_REC1_AUX); rec_create(rd, IDX_REC2, IDX_REC2_PARAMS, IDX_REC2_AUX); rd } pub fn realm_teardown(rd: usize) { rec_destroy(IDX_REC1, IDX_REC1_AUX); rec_destroy(IDX_REC2, IDX_REC2_AUX); realm_destroy(rd); } } pub mod realm { use super::super::*; use crate::event::realmexit::RecExitReason; use crate::rec::context::set_reg; use crate::rec::Rec; use crate::rmi::error::Error; use crate::rmi::rec::exit::handle_realm_exit; use crate::rmi::rec::run::Run; use crate::rsi::PSCI_CPU_ON; pub fn setup_psci_complete(rec: &mut Rec<'_>, run: &mut Run) { let reason: u64 = RecExitReason::PSCI.into(); // caller rec.set_psci_pending(true); run.set_exit_reason(reason as u8); run.set_gpr(0, PSCI_CPU_ON as u64).unwrap(); let target_mpidr = IDX_REC2 % IDX_REC1; set_reg(rec, 1, target_mpidr).unwrap(); } pub fn setup_ripas_state(rec: &mut Rec<'_>, run: &mut Run) { let ipa_base: u64 = 0; let ipa_top: u64 = 0x1000; const RSI_RAM: u8 = 1; const RSI_NO_CHANGE_DESTROYED: u64 = 0; run.set_ripas(ipa_base, ipa_top, RSI_RAM); rec.set_ripas(ipa_base, ipa_top, RSI_RAM, RSI_NO_CHANGE_DESTROYED); } pub fn emulate_realm( rmm: &Monitor, rec: &mut Rec<'_>, run: &mut Run, cmd: usize, args: &[usize], ) -> Result<(bool, usize), Error> { const RSI_REASON: usize = 1 << 4; if cmd == REC_ENTER_EXIT_CMD { let realm_exit_res: [usize; 4] = [args[0], args[1], args[2], args[3]]; handle_realm_exit(realm_exit_res, rmm, rec, run) } else { set_reg(rec, 0, cmd)?; for idx in 0..args.len() { set_reg(rec, idx + 1, args[idx])?; } let realm_exit_res = [RSI_REASON, cmd, 0, 0]; handle_realm_exit(realm_exit_res, rmm, rec, run) } } } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/allocator.rs
rmm/src/allocator.rs
use core::mem::MaybeUninit; use core::ptr::addr_of_mut; use linked_list_allocator::LockedHeap; use crate::config::RMM_HEAP_SIZE; static mut HEAP: [MaybeUninit<u8>; RMM_HEAP_SIZE] = [MaybeUninit::uninit(); RMM_HEAP_SIZE]; #[global_allocator] static mut ALLOCATOR: LockedHeap = LockedHeap::empty(); /// Initializes the global allocator with a heap backed by the `HEAP` array. /// /// # Safety /// /// - This function must be called exactly once before any memory allocation occurs. /// Calling it multiple times or after allocations have started can lead to undefined behavior. pub unsafe fn init() { ALLOCATOR.lock().init_from_slice(&mut *addr_of_mut!(HEAP)); } pub fn get_used_size() -> usize { unsafe { ALLOCATOR.lock().used() } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/simd.rs
rmm/src/simd.rs
use aarch64_cpu::registers::ID_AA64PFR0_EL1; use aarch64_cpu::registers::{Readable, Writeable}; use armv9a::regs::{ID_AA64PFR1_SME_EL1, SMCR_EL2, ZCR_EL2}; use core::arch::asm; use lazy_static::lazy_static; // Vector length (VL) = size of a Z-register in bytes // Vector quadwords (VQ) = size of a Z-register in units of 128 bits // Minimum length of a SVE vector: 128 bits const ZCR_EL2_LEN_WIDTH: u64 = 4; const SVE_VQ_ARCH_MAX: u64 = (1 << ZCR_EL2_LEN_WIDTH) - 1; const QUARD_WORD: u64 = 128; // Note: Limit maximun vq to 4 to avoid exceeding a page boundary. // Currunt rmm implmentation maps a physical page to a virtual address // using its physical address (i.e. identical mapping). // Discontiguous Aux granules cannot not be accessed contiguously // in their virtual address. For this reason, limit vq up to 4(~2184 bytes). // Z regs = 16bytes * 32 regs * 4 vq // P regs = 2 bytes * 16 regs * 4 vq // FFR reg = 2 bytes * 4 vq pub const MAX_VQ: u64 = 4; #[derive(Default, Debug)] // SIMD configuration structure pub struct SimdConfig { // SVE enabled flag pub sve_en: bool, // SVE vector length represented in quads pub sve_vq: u64, // SME enabled flag pub sme_en: bool, } lazy_static! { // Global SIMD configuration static ref SIMD_CONFIG: SimdConfig = { // Initalize SVE let mut sve_en: bool = false; let mut sve_vq: u64 = 0; let mut sme_en: bool = false; trace!("Reading simd features"); #[cfg(not(any(test, miri, fuzzing)))] if ID_AA64PFR0_EL1.is_set(ID_AA64PFR0_EL1::SVE) { trace!("SVE is set"); // Get effective vl: (ZCR_EL2:LEN + 1)*128 bits //let _e_vl = ZCR_EL2.read(ZCR_EL2::LEN); // Set to maximum ZCR_EL2.write(ZCR_EL2::LEN.val(SVE_VQ_ARCH_MAX)); // Get vl in bytes let vl_b = unsafe { get_vector_length_bytes() }; sve_vq = ((vl_b << 3)/ QUARD_WORD) - 1; if sve_vq > MAX_VQ { sve_vq = MAX_VQ - 1; } sve_en = true; trace!("sve_vq={:?}", sve_vq); } // init sme #[cfg(not(any(test, miri, fuzzing)))] if ID_AA64PFR1_SME_EL1.is_set(ID_AA64PFR1_SME_EL1::SME) { trace!("SME is set"); // Find the architecturally permitted SVL SMCR_EL2.write(SMCR_EL2::RAZWI.val(SMCR_EL2::RAZWI.mask) + SMCR_EL2::LEN.val(SMCR_EL2::LEN.mask)); let raz = SMCR_EL2.read(SMCR_EL2::RAZWI); let len = SMCR_EL2.read(SMCR_EL2::LEN); let sme_svq_arch_max = (raz << 4) + len; trace!("sme_svq_arch_max={:?}", sme_svq_arch_max); assert!(sme_svq_arch_max <= SVE_VQ_ARCH_MAX); sme_en = true; } SimdConfig { sve_en, sve_vq, sme_en, } }; } /// Get the SVE vector length in bytes using the RDVL instruction #[target_feature(enable = "sve")] unsafe fn get_vector_length_bytes() -> u64 { let vl_b: u64; unsafe { asm!("rdvl {}, #1", out(reg) vl_b); } vl_b } pub fn validate(en: bool, sve_vl: u64) -> bool { if en && !SIMD_CONFIG.sve_en { return false; } if sve_vl > SIMD_CONFIG.sve_vq { return false; } true } pub fn sve_en() -> bool { SIMD_CONFIG.sve_en } pub fn max_sve_vl() -> u64 { SIMD_CONFIG.sve_vq } pub fn sme_en() -> bool { SIMD_CONFIG.sme_en }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/monitor.rs
rmm/src/monitor.rs
use crate::event::{Context, Mainloop, RmiHandle, RsiHandle}; use crate::mm::translation::PageTable; use crate::rec::context::set_reg; use crate::rec::Rec; use crate::rmi; use crate::rmi::rec::run::Run; #[cfg(not(kani))] pub struct Monitor { pub rsi: RsiHandle, pub rmi: RmiHandle, pub page_table: PageTable, mainloop: Mainloop, } #[cfg(kani)] // `rsi` and `page_table` are removed in model checking harnesses // to reduce overall state space pub struct Monitor { pub rmi: RmiHandle, mainloop: Mainloop, } impl Monitor { #[cfg(not(kani))] pub fn new() -> Self { Self { rsi: RsiHandle::new(), rmi: RmiHandle::new(), page_table: PageTable::get_ref(), mainloop: Mainloop::new(), } } #[cfg(kani)] pub fn new() -> Self { Self { rmi: RmiHandle::new(), mainloop: Mainloop::new(), } } #[cfg(not(kani))] fn boot_complete(&self) -> Context { let mut ctx = Context::new(rmi::BOOT_COMPLETE); ctx.init_arg(&[rmi::BOOT_SUCCESS]); self.mainloop.dispatch(ctx) } #[cfg(kani)] // DIFF: `symbolic` parameter is added to pass symbolic input pub fn boot_complete(&mut self, symbolic: [usize; 8]) -> Context { let mut ctx = Context::new(rmi::BOOT_COMPLETE); ctx.init_arg(&[rmi::BOOT_SUCCESS]); self.mainloop.dispatch(ctx, symbolic) } #[cfg(not(kani))] pub fn run(&mut self) { let mut ctx = self.boot_complete(); loop { self.handle_rmi(&mut ctx); ctx = self.mainloop.dispatch(ctx); } } #[cfg(kani)] // DIFF: `symbolic` parameter is added to pass symbolic input // return value is added to track output // infinite loop is removed pub fn run(&mut self, symbolic: [usize; 8]) -> [usize; 5] { let mut ctx = self.boot_complete(symbolic); let mut result = [0; 5]; self.handle_rmi(&mut ctx); ctx = self.mainloop.dispatch(ctx, symbolic); let ret_len = ctx.ret.len(); result[..ret_len].copy_from_slice(&ctx.ret[..]); result } pub fn handle_rmi(&mut self, ctx: &mut Context) { if let Some(handler) = self.rmi.on_event.get(&ctx.cmd) { #[cfg(feature = "stat")] { if ctx.cmd != rmi::REC_ENTER { trace!("let's get STATS.lock() with cmd {}", rmi::to_str(ctx.cmd)); crate::stat::STATS.lock().measure(ctx.cmd, || { if let Err(code) = handler(&ctx.arg[..], &mut ctx.ret[..], self) { ctx.ret[0] = code.into(); } }); } else if let Err(code) = handler(&ctx.arg[..], &mut ctx.ret[..], self) { ctx.ret[0] = code.into(); } } #[cfg(not(feature = "stat"))] { if let Err(code) = handler(&ctx.arg[..], &mut ctx.ret[..], self) { ctx.ret[0] = code.into(); } } trace!( "RMI: {0: <20} {1:X?} > {2:X?}", rmi::to_str(ctx.cmd), &ctx.arg, &ctx.ret ); // SMC calling convention requires x4-x7 to be preserved unless used. // Since the rmmd in EL3 takes care of preserving x5-x7, // we only restore x4. ctx.arg.resize(5, 0); ctx.arg[..ctx.ret.len()].copy_from_slice(&ctx.ret[..]); if ctx.ret.len() < 5 { ctx.arg[4] = ctx.x4 as usize; } #[cfg(kani)] // the below is a proof helper { let ret_len = ctx.ret.len(); #[cfg(any( feature = "mc_rmi_granule_delegate", feature = "mc_rmi_granule_undelegate", feature = "mc_rmi_realm_activate", feature = "mc_rmi_realm_destroy", feature = "mc_rmi_rec_destroy" ))] assert!(ret_len == 1); #[cfg(any(feature = "mc_rmi_rec_aux_count", feature = "mc_rmi_features"))] assert!(ret_len == 2); #[cfg(feature = "mc_rmi_version")] assert!(ret_len == 3); } } else { error!("Not registered event: {:X}", ctx.cmd); ctx.init_arg(&[rmi::RET_FAIL]); } ctx.cmd = rmi::REQ_COMPLETE; } pub fn handle_rsi(&self, ctx: &mut Context, rec: &mut Rec<'_>, run: &mut Run) -> usize { #[cfg(not(kani))] match self.rsi.on_event.get(&ctx.cmd) { Some(handler) => { ctx.do_rsi(|arg, ret| handler(arg, ret, self, rec, run)); } None => { ctx.init_ret(&[RsiHandle::NOT_SUPPORTED]); error!( "Not registered event: {:X} returning {:X}", ctx.cmd, RsiHandle::NOT_SUPPORTED ); // TODO: handle the error properly let _ = set_reg(rec, 0, RsiHandle::NOT_SUPPORTED); return RsiHandle::RET_FAIL; } } RsiHandle::RET_SUCCESS } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/cose.rs
rmm/src/cose.rs
use alloc::{borrow::ToOwned, vec::Vec}; use ciborium::ser; use coset::{iana, AsCborValue, CoseKeyBuilder}; use ecdsa::elliptic_curve::sec1::ToEncodedPoint; // Convert SEC1 encoded EC2 public `key` to COSE/CBOR // Handles only p384 for now, others can be uncommented when needed pub fn ec_public_key_sec1_to_cose(key: &[u8]) -> Vec<u8> { // let p256_sec1_len = 1 + 2 * 32; let p384_sec1_len = 1 + 2 * 48; // let p521_sec1_len = 1 + 2 * 66; let key_cbor_value = match key.len() { // n if n == p256_sec1_len => { // let pk = p256::PublicKey::from_sec1_bytes(key).expect("Failed to load p256 sec1 key"); // let ep = pk.to_encoded_point(false); // let x = ep.x().unwrap().to_owned().to_vec(); // let y = ep.y().unwrap().to_owned().to_vec(); // let key = CoseKeyBuilder::new_ec2_pub_key(iana::EllipticCurve::P_256, x, y).build(); // key.to_cbor_value().expect("Failed to encode p256 as CBOR") // } n if n == p384_sec1_len => { let pk = p384::PublicKey::from_sec1_bytes(key).expect("Failed to load p384 sec1 key"); let ep = pk.to_encoded_point(false); let x = ep.x().unwrap().to_owned().to_vec(); let y = ep.y().unwrap().to_owned().to_vec(); let key = CoseKeyBuilder::new_ec2_pub_key(iana::EllipticCurve::P_384, x, y).build(); key.to_cbor_value().expect("Failed to encode p384 as CBOR") } // n if n == p521_sec1_len => { // let pk = p521::PublicKey::from_sec1_bytes(key).expect("Failed to load p521 sec1 key"); // let ep = pk.to_encoded_point(false); // let x = ep.x().unwrap().to_owned().to_vec(); // let y = ep.y().unwrap().to_owned().to_vec(); // let key = CoseKeyBuilder::new_ec2_pub_key(iana::EllipticCurve::P_521, x, y).build(); // key.to_cbor_value().expect("Failed to encode p521 as CBOR") // } _ => panic!("Wrong sec1 key length"), }; let mut key_cbor_bytes = Vec::new(); ser::into_writer(&key_cbor_value, &mut key_cbor_bytes).expect("Failed to serialize CBOR value"); key_cbor_bytes }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/cpu.rs
rmm/src/cpu.rs
use crate::config::NUM_OF_CPU_PER_CLUSTER; use aarch64_cpu::registers::*; #[no_mangle] pub extern "C" fn get_cpu_id() -> usize { let (cluster, core) = id(); cluster * NUM_OF_CPU_PER_CLUSTER + core } #[cfg(any(feature = "fvp", not(feature = "qemu")))] #[inline(always)] pub fn id() -> (usize, usize) { ( MPIDR_EL1.read(MPIDR_EL1::Aff2) as usize, MPIDR_EL1.read(MPIDR_EL1::Aff1) as usize, ) } #[cfg(feature = "qemu")] #[inline(always)] pub fn id() -> (usize, usize) { ( MPIDR_EL1.read(MPIDR_EL1::Aff1) as usize, MPIDR_EL1.read(MPIDR_EL1::Aff0) as usize, ) }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/host.rs
rmm/src/host.rs
#[cfg(feature = "gst_page_table")] use crate::granule::{is_not_in_realm, GRANULE_SIZE}; #[cfg(not(feature = "gst_page_table"))] use crate::granule::{GranuleState, GRANULE_SIZE}; #[cfg(not(feature = "gst_page_table"))] use crate::{get_granule, get_granule_if}; use safe_abstraction::raw_ptr::{assume_safe, SafetyAssured, SafetyChecked}; use vmsa::guard::Content; pub fn copy_from<T: SafetyChecked + SafetyAssured + Copy>(addr: usize) -> Option<T> { #[cfg(feature = "gst_page_table")] if !is_not_in_realm(addr) { return None; } #[cfg(not(feature = "gst_page_table"))] if get_granule_if!(addr, GranuleState::Undelegated).is_err() { return None; } let ret = assume_safe::<T>(addr).map(|safety_assumed| *safety_assumed); match ret { Ok(obj) => Some(obj), Err(err) => { error!("Failed to convert a raw pointer to the struct. {:?}", err); None } } } pub fn copy_to_obj<T: SafetyChecked + SafetyAssured + Copy>(src: usize, dst: &mut T) -> Option<()> { #[cfg(feature = "gst_page_table")] if !is_not_in_realm(src) { return None; } #[cfg(not(feature = "gst_page_table"))] if get_granule_if!(src, GranuleState::Undelegated).is_err() { return None; } let ret = assume_safe::<T>(src).map(|safety_assumed| *dst = *safety_assumed); match ret { Ok(_) => Some(()), Err(err) => { error!("Failed to convert a raw pointer to the struct. {:?}", err); None } } } pub fn copy_to_ptr<T: SafetyChecked + SafetyAssured + Copy>(src: &T, dst: usize) -> Option<()> { #[cfg(feature = "gst_page_table")] if !is_not_in_realm(dst) { return None; } #[cfg(not(feature = "gst_page_table"))] if get_granule_if!(dst, GranuleState::Undelegated).is_err() { return None; } let ret = assume_safe::<T>(dst).map(|mut safety_assumed| *safety_assumed = *src); match ret { Ok(_) => Some(()), Err(err) => { error!("Failed to convert a raw pointer to the struct. {:?}", err); None } } } /// DataPage is used to convey realm data from host to realm. #[repr(C)] #[derive(Copy, Clone)] pub struct DataPage([u8; GRANULE_SIZE]); impl DataPage { pub fn as_slice(&self) -> &[u8] { self.0.as_slice() } } impl Default for DataPage { fn default() -> Self { Self([0; GRANULE_SIZE]) } } impl Content for DataPage {} impl safe_abstraction::raw_ptr::RawPtr for DataPage {} impl safe_abstraction::raw_ptr::SafetyChecked for DataPage {} impl safe_abstraction::raw_ptr::SafetyAssured for DataPage { fn is_initialized(&self) -> bool { // Given the fact that this memory is initialized by the Host, // it's not possible to unequivocally guarantee // that the values have been initialized from the perspective of the RMM. // However, any values, whether correctly initialized or not, will undergo // verification during the Measurement phase. // Consequently, this function returns `true`. true } fn verify_ownership(&self) -> bool { // This memory has permissions from the Host's perspective, // which inherently implies that exclusive ownership cannot be guaranteed by the RMM alone. // However, since the RMM only performs read operations and any incorrect values will be // verified during the Measurement phase. // Consequently, this function returns `true`. true } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/exception/trap.rs
rmm/src/exception/trap.rs
mod frame; pub mod syndrome; use self::frame::TrapFrame; use self::syndrome::Fault; use self::syndrome::Syndrome; use super::lower::synchronous; use crate::cpu; use crate::event::realmexit::{ExitSyncType, RecExitReason}; use crate::rec::simd; use crate::rec::Rec; use aarch64_cpu::registers::*; #[repr(u16)] #[derive(Debug, Copy, Clone)] pub enum Source { CurrentSPEL0, CurrentSPELx, LowerAArch64, LowerAArch32, } #[repr(u16)] #[derive(Debug, Copy, Clone)] pub enum Kind { Synchronous, Irq, Fiq, SError, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Info { source: Source, kind: Kind, } /// This function is called when an exception occurs from CurrentSPEL0, CurrentSPELx. /// The `info` parameter specifies source (first 16 bits) and kind (following 16 /// bits) of the exception. /// The `esr` has the value of a syndrome register (ESR_ELx) holding the cause /// of the Synchronous and SError exception. /// The `tf` has the TrapFrame of current context. #[no_mangle] #[allow(unused_variables)] pub extern "C" fn handle_exception(info: Info, esr: u32, tf: &mut TrapFrame) { match info.kind { Kind::Synchronous => match Syndrome::from(esr) { Syndrome::Brk(b) => { debug!("brk #{}", b); debug!("{:?}\nESR: {:X}\n{:#X?}", info, esr, tf); tf.elr += 4; //continue } Syndrome::PCAlignmentFault => { debug!("PCAlignmentFault"); } Syndrome::DataAbort(fault) => { let far = FAR_EL2.get(); debug!("Data Abort (higher), far:{:X}", far); match fault { Fault::AddressSize { level } => { debug!("address size, level:{}", level); } Fault::Translation { level } => { debug!("translation, level:{}, esr:{:X}", level, esr); } Fault::AccessFlag { level } => { debug!("access flag, level:{}", level); } Fault::Permission { level } => { debug!("permission, level:{}", level); } Fault::Alignment => { debug!("alignment"); } Fault::TLBConflict => { debug!("tlb conflict"); } Fault::Other(_x) => { debug!("other"); } } } Syndrome::InstructionAbort(v) => { debug!("Instruction Abort (higher)"); } Syndrome::HVC => { debug!("HVC"); } Syndrome::SMC => { debug!("SMC"); } Syndrome::SysRegInst => { debug!("SysRegInst"); } Syndrome::WFX => { debug!("WFX"); } Syndrome::FPU | Syndrome::SVE | Syndrome::SME => { // Islet RMM is not supposed to use simd. debug!("ELR_EL2:{:x}", ELR_EL2.get()); panic!("RMM is using SIMD instruction"); } Syndrome::Other(v) => { debug!("Other"); } undefined => { panic!( "{:?} and esr {:x}, TrapFrame: {:?} on cpu::id {:?}", info, esr, tf, cpu::id() ); } }, _ => { panic!( "Unknown exception! Info={:?}, ESR={:x} on CPU {:?}", info, esr, cpu::id() ); } } } pub const RET_TO_REC: u64 = 0; pub const RET_TO_RMM: u64 = 1; /// This function is called when an exception occurs from LowerAArch64. /// To enter RMM (EL2), return 1. Otherwise, return 0 to go back to EL1. /// The `info` parameter specifies source (first 16 bits) and kind (following 16 /// bits) of the exception. /// The `esr` has the value of a syndrome register (ESR_ELx) holding the cause /// of the Synchronous and SError exception. /// The `rec` has the Rec context. /// The `tf` has the TrapFrame of current context. /// /// Do not write sys_regs of Rec here. (ref. HANDLE_LOWER in vectors.s) #[no_mangle] #[allow(unused_variables)] pub extern "C" fn handle_lower_exception( info: Info, esr: u32, rec: &mut Rec<'_>, tf: &mut TrapFrame, ) -> u64 { match info.kind { // TODO: adjust elr according to the decision that kvm made Kind::Synchronous => match Syndrome::from(esr) { Syndrome::HVC => { debug!("Synchronous: HVC: {:#X}", rec.context.gp_regs[0]); // Inject undefined exception to the realm SPSR_EL1.set(rec.context.spsr_el2); ELR_EL1.set(rec.context.elr_el2); ESR_EL1.write(ESR_EL1::EC::Unknown + ESR_EL1::IL::SET); // Return to realm's exception handler let vbar = rec.context.sys_regs.vbar; const SPSR_EL2_MODE_EL1H_OFFSET: u64 = 0x200; rec.context.elr_el2 = vbar + SPSR_EL2_MODE_EL1H_OFFSET; tf.regs[0] = RecExitReason::Sync(ExitSyncType::Undefined).into(); tf.regs[1] = esr as u64; tf.regs[2] = 0; tf.regs[3] = FAR_EL2.get(); RET_TO_REC } Syndrome::SMC => { tf.regs[0] = RecExitReason::Sync(ExitSyncType::RSI).into(); tf.regs[1] = rec.context.gp_regs[0]; // RSI command advance_pc(rec); RET_TO_RMM } Syndrome::InstructionAbort(_) | Syndrome::DataAbort(_) => { debug!("Synchronous: InstructionAbort | DataAbort"); if let Syndrome::InstructionAbort(_) = Syndrome::from(esr) { tf.regs[0] = RecExitReason::Sync(ExitSyncType::InstAbort).into() } else { tf.regs[0] = RecExitReason::Sync(ExitSyncType::DataAbort).into(); } tf.regs[1] = esr as u64; tf.regs[2] = HPFAR_EL2.get(); tf.regs[3] = FAR_EL2.get(); let fipa = HPFAR_EL2.read(HPFAR_EL2::FIPA) << 8; debug!("fipa: {:X}", fipa); debug!("esr_el2: {:X}", esr); RET_TO_RMM } Syndrome::SysRegInst => { debug!("Synchronous: MRS, MSR System Register Instruction"); let ret = synchronous::sys_reg::handle(rec, esr as u64); advance_pc(rec); if ret == RET_TO_RMM { tf.regs[0] = RecExitReason::Sync(ExitSyncType::Undefined).into(); tf.regs[1] = esr as u64; tf.regs[2] = 0; } ret } Syndrome::WFX => { debug!("Synchronous: WFx"); tf.regs[0] = RecExitReason::Sync(ExitSyncType::WFx).into(); tf.regs[1] = esr as u64; advance_pc(rec); RET_TO_RMM } Syndrome::FPU | Syndrome::SVE | Syndrome::SME => { debug!("Synchronous: SIMD"); let abort: bool = match Syndrome::from(esr) { Syndrome::SVE => !rec.context.simd.cfg.sve_en, // Note: Since only FEAT_SVE is set for Realms and // we are doing lazy restore, being reported as Syndrome::SME // is actually comming from the NW's SME setting. Syndrome::SME => !rec.context.simd.cfg.sve_en, _ => false, }; if abort { // Inject undefined exception to the realm SPSR_EL1.set(rec.context.spsr_el2); ELR_EL1.set(rec.context.elr_el2); ESR_EL1.write(ESR_EL1::EC::Unknown + ESR_EL1::IL::SET); // Return to realm's exception handler let vbar = rec.context.sys_regs.vbar; const SPSR_EL2_MODE_EL1H_OFFSET: u64 = 0x200; rec.context.elr_el2 = vbar + SPSR_EL2_MODE_EL1H_OFFSET; tf.regs[0] = RecExitReason::Sync(ExitSyncType::Undefined).into(); tf.regs[1] = esr as u64; tf.regs[2] = 0; tf.regs[3] = FAR_EL2.get(); debug!("Unsupported feature access. Inject abort"); return RET_TO_REC; } // Note: To avoid being trapped from RMM's access to simd, // setting cptr_el2 should come prior to the context restoration. simd::restore_state_lazy(rec); rec.context.simd.is_used = true; RET_TO_REC } undefined => { debug!("Synchronous: Other"); tf.regs[0] = RecExitReason::Sync(ExitSyncType::Undefined).into(); tf.regs[1] = esr as u64; RET_TO_RMM } }, Kind::Irq => { debug!("IRQ"); tf.regs[0] = RecExitReason::IRQ.into(); // IRQ isn't interpreted with esr. It just hold previsou info. Void them out. tf.regs[1] = 0; RET_TO_RMM } Kind::SError => { debug!("SError"); tf.regs[0] = RecExitReason::SError.into(); tf.regs[1] = esr as u64; RET_TO_RMM } _ => { error!( "Unknown exception! Info={:?}, ESR={:x} on CPU {:?}", info, esr, cpu::id() ); RET_TO_REC } } } #[inline(always)] fn advance_pc(rec: &mut Rec<'_>) { rec.context.elr_el2 += 4; }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/exception/mod.rs
rmm/src/exception/mod.rs
pub mod lower; pub mod trap; core::arch::global_asm!(include_str!("vectors.s")); extern "C" { pub static mut vectors: u64; }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/exception/trap/frame.rs
rmm/src/exception/trap/frame.rs
#[repr(C)] #[derive(Debug, Copy, Clone)] pub struct TrapFrame { pub _res: u64, pub elr: u64, pub spsr: u64, pub regs: [u64; 31], }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/exception/trap/syndrome.rs
rmm/src/exception/trap/syndrome.rs
use aarch64_cpu::registers::*; #[derive(Debug, Copy, Clone)] pub enum Fault { AddressSize { level: u8 }, Translation { level: u8 }, AccessFlag { level: u8 }, Permission { level: u8 }, Alignment, TLBConflict, Other(u8), } const DFSC_MASK: u8 = 0x3f; const ISS_BRK_CMT_MASK: u16 = 0xffff; impl From<u32> for Fault { fn from(origin: u32) -> Self { let level = (origin & 0b11) as u8; let origin = origin as u8; match (origin & DFSC_MASK) >> 2 { 0b0000 => Fault::AddressSize { level }, 0b0001 => Fault::Translation { level }, 0b0010 => Fault::AccessFlag { level }, 0b0011 => Fault::Permission { level }, 0b1000 => Fault::Alignment, 0b1100 => Fault::TLBConflict, _ => Fault::Other(origin & DFSC_MASK), } } } #[derive(Debug, Copy, Clone)] pub enum Syndrome { Unknown, PCAlignmentFault, DataAbort(Fault), InstructionAbort(Fault), SPAlignmentFault, Brk(u16), HVC, SMC, SysRegInst, WFX, FPU, SVE, SME, Other(u32), } impl From<u32> for Syndrome { fn from(origin: u32) -> Self { match (origin >> ESR_EL2::EC.shift) & ESR_EL2::EC.mask as u32 { 0b00_0000 => Syndrome::Unknown, 0b00_0001 => Syndrome::WFX, 0b00_0111 => Syndrome::FPU, 0b01_0010 => Syndrome::HVC, 0b01_0110 => Syndrome::HVC, 0b01_0011 => Syndrome::SMC, 0b01_0111 => Syndrome::SMC, 0b01_1000 => Syndrome::SysRegInst, 0b01_1001 => Syndrome::SVE, 0b01_1101 => Syndrome::SME, 0b10_0000 => { debug!("Instruction Abort from a lower Exception level"); Syndrome::InstructionAbort(Fault::from(origin)) } 0b10_0001 => { debug!("Instruction Abort taken without a change in Exception level"); Syndrome::InstructionAbort(Fault::from(origin)) } 0b10_0010 => Syndrome::PCAlignmentFault, 0b10_0100 => { debug!("Data Abort from a lower Exception level"); Syndrome::DataAbort(Fault::from(origin)) } 0b10_0101 => { debug!("Data Abort without a change in Exception level"); Syndrome::DataAbort(Fault::from(origin)) } 0b10_0110 => Syndrome::SPAlignmentFault, 0b11_1100 => Syndrome::Brk(origin as u16 & ISS_BRK_CMT_MASK), ec => Syndrome::Other(ec), } } } impl Into<u64> for Syndrome { fn into(self) -> u64 { match self { Syndrome::DataAbort(fault) => { let ec: u64 = 0b10_0100 << ESR_EL2::EC.shift; let iss: u64 = fault.into(); ec | iss } _ => { panic!("Not implemented yet!"); } } } } impl Into<u64> for Fault { fn into(self) -> u64 { match self { Fault::Translation { level } => (0b000100 | level) as u64, _ => { panic!("Not implemented yet!"); } } } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/exception/lower/mod.rs
rmm/src/exception/lower/mod.rs
pub mod synchronous;
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/exception/lower/synchronous/mod.rs
rmm/src/exception/lower/synchronous/mod.rs
pub mod sys_reg;
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/exception/lower/synchronous/sys_reg.rs
rmm/src/exception/lower/synchronous/sys_reg.rs
use crate::exception::trap; use crate::rec::Rec; use aarch64_cpu::registers::*; use armv9a::regs::*; fn check_sysreg_id_access(esr: u64) -> bool { let esr = ISS::new(esr); (esr.get_masked(ISS::Op0) | esr.get_masked(ISS::Op1) | esr.get_masked(ISS::CRn)) == ISS::Op0 } fn check_sysreg_icc_access(esr: u64) -> bool { let esr = ISS::new(esr); // direction: 0b0 - write, 0b1 - read let direction = esr.get_masked_value(ISS::Direction); let esr_iss = esr.get_masked(ISS::Op0 | ISS::Op1 | ISS::CRn | ISS::CRm) as u32; // Only writing to the system register is valid. direction == 0 && (esr_iss == ISS_ID_ICC_MASK || esr_iss == ISS_ID_ICC_PMR_EL1) } pub fn handle(rec: &mut Rec<'_>, esr: u64) -> u64 { if check_sysreg_id_access(esr) { handle_sysreg_id(rec, esr); } else if check_sysreg_icc_access(esr) { return trap::RET_TO_RMM; } else { warn!("Unhandled MSR/MRS instruction. ESR_EL2:{:X}", esr); } trap::RET_TO_REC } fn handle_sysreg_id(rec: &mut Rec<'_>, esr: u64) -> u64 { let esr = ISS::new(esr); let il = esr.get_masked_value(ISS::IL); let rt = esr.get_masked_value(ISS::Rt) as usize; // direction: 0b0 - write, 0b1 - read let direction = esr.get_masked_value(ISS::Direction); if il == 0 { error!("Exception taken from 32bit arch. Realm needs to be 64bit(arm64)."); } if direction == 0 { warn!("Unable to write id system reg. Will ignore this request!"); return trap::RET_TO_REC; } if rt == 31 { trace!("handle_sysreg_id(): Rt = xzr"); return trap::RET_TO_REC; } let idreg = esr.get_masked(ISS::Op0 | ISS::Op1 | ISS::CRn | ISS::CRm | ISS::Op2); let mut mask: u64 = match idreg as u32 { ISS_ID_AA64PFR0_EL1 => { (ID_AA64PFR0_EL1::AMU.mask << ID_AA64PFR0_EL1::AMU.shift) + if !rec.context.simd.cfg.sve_en { ID_AA64PFR0_EL1::SVE.mask << ID_AA64PFR0_EL1::SVE.shift } else { 0 } } // Present FEAT_SVE only if Rec is set to use SVE. ISS_ID_AA64ZFR0_EL1 => (!rec.context.simd.cfg.sve_en as u64).wrapping_neg(), ISS_ID_AA64PFR1_EL1 => { (ID_AA64PFR1_SME_EL1::MTE.mask << ID_AA64PFR1_SME_EL1::MTE.shift) + (ID_AA64PFR1_SME_EL1::SME.mask << ID_AA64PFR1_SME_EL1::SME.shift) } ISS_ID_AA64DFR0_EL1 => { (ID_AA64DFR0_EL1::BRBE.mask << ID_AA64DFR0_EL1::BRBE.shift) + (ID_AA64DFR0_EL1::MTPMU.mask << ID_AA64DFR0_EL1::MTPMU.shift) + (ID_AA64DFR0_EL1::TraceBuffer.mask << ID_AA64DFR0_EL1::TraceBuffer.shift) + (ID_AA64DFR0_EL1::TraceFilt.mask << ID_AA64DFR0_EL1::TraceFilt.shift) + (ID_AA64DFR0_EL1::PMSVer.mask << ID_AA64DFR0_EL1::PMSVer.shift) + (ID_AA64DFR0_EL1::CTX_CMPs.mask << ID_AA64DFR0_EL1::CTX_CMPs.shift) + (ID_AA64DFR0_EL1::WRPs.mask << ID_AA64DFR0_EL1::WRPs.shift) + (ID_AA64DFR0_EL1::BRPs.mask << ID_AA64DFR0_EL1::BRPs.shift) + (ID_AA64DFR0_EL1::TraceVer.mask << ID_AA64DFR0_EL1::TraceVer.shift) + (ID_AA64DFR0_EL1::DebugVer.mask << ID_AA64DFR0_EL1::DebugVer.shift) } _ => 0, }; mask = !mask; rec.context.gp_regs[rt] = match idreg as u32 { ISS_ID_AA64PFR0_EL1 => ID_AA64PFR0_EL1.get() & mask, ISS_ID_AA64PFR1_EL1 => ID_AA64PFR1_EL1.get() & mask, ISS_ID_AA64ZFR0_EL1 => ID_AA64ZFR0_EL1.get() & mask, ISS_ID_AA64DFR0_EL1 => { let mut dfr0_set = 0u64; dfr0_set &= 6 << ID_AA64DFR0_EL1::DebugVer.shift; dfr0_set &= 1 << ID_AA64DFR0_EL1::BRPs.shift; dfr0_set &= 1 << ID_AA64DFR0_EL1::WRPs.shift; ID_AA64DFR0_EL1.get() & mask | dfr0_set } ISS_ID_AA64DFR1_EL1 => ID_AA64DFR1_EL1.get() & mask, ISS_ID_AA64AFR0_EL1 => ID_AA64AFR0_EL1.get(), ISS_ID_AA64AFR1_EL1 => ID_AA64AFR1_EL1.get(), ISS_ID_AA64ISAR0_EL1 => ID_AA64ISAR0_EL1.get(), ISS_ID_AA64ISAR1_EL1 => ID_AA64ISAR1_EL1.get(), ISS_ID_AA64MMFR0_EL1 => ID_AA64MMFR0_EL1.get(), ISS_ID_AA64MMFR1_EL1 => ID_AA64MMFR1_EL1.get(), ISS_ID_AA64MMFR2_EL1 => ID_AA64MMFR2_EL1.get(), //0x10211122, _ => 0x0, }; trap::RET_TO_REC }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmm_el3/digest.rs
rmm/src/rmm_el3/digest.rs
use crate::cose; use alloc::vec::Vec; use sha2::{Digest, Sha256, Sha384, Sha512}; /// Supported public dak hash algorithms. #[allow(dead_code)] #[derive(Debug)] enum HashAlgo { Sha256, Sha384, Sha512, } fn calculate_hash(data: Vec<u8>, algo: HashAlgo) -> Vec<u8> { match algo { HashAlgo::Sha256 => { let mut hasher = Sha256::new(); hasher.update(data); hasher.finalize().to_vec() } HashAlgo::Sha384 => { let mut hasher = Sha384::new(); hasher.update(data); hasher.finalize().to_vec() } HashAlgo::Sha512 => { let mut hasher = Sha512::new(); hasher.update(data); hasher.finalize().to_vec() } } } pub(super) fn get_realm_public_key_hash(key: Vec<u8>) -> Vec<u8> { let priv_dak = p384::SecretKey::from_slice(&key).unwrap(); let public_dak = priv_dak.public_key().to_sec1_bytes().to_vec(); let public_dak_cose = cose::ec_public_key_sec1_to_cose(&public_dak); calculate_hash(public_dak_cose, HashAlgo::Sha256) }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmm_el3/manifest.rs
rmm/src/rmm_el3/manifest.rs
use autopadding::*; use safe_abstraction::raw_ptr::assume_safe; use safe_abstraction::raw_ptr::Error; use spinning_top::SpinlockGuard; use super::RMM_SHARED_BUFFER_LOCK; use crate::config; /* * Boot Manifest structure illustration, with two dram banks and * a single console. * * +----------------------------------------+ * | offset | field | comment | * +--------+----------------+--------------+ * | 0 | version | 0x00000003 | * +--------+----------------+--------------+ * | 4 | padding | 0x00000000 | * +--------+----------------+--------------+ * | 8 | plat_data | NULL | * +--------+----------------+--------------+ * | 16 | num_banks | | * +--------+----------------+ | * | 24 | banks | plat_dram | * +--------+----------------+ | * | 32 | checksum | | * +--------+----------------+--------------+ * | 40 | num_consoles | | * +--------+----------------+ | * | 48 | consoles | plat_console | * +--------+----------------+ | * | 56 | checksum | | * +--------+----------------+--------------+ * | 64 | base 0 | | * +--------+----------------+ bank[0] | * | 72 | size 0 | | * +--------+----------------+--------------+ * +--------+----------------+ bank[N] | * +--------+----------------+--------------+ * | X | base | | * +--------+----------------+ | * | X+8 | map_pages | | * +--------+----------------+ | * | X+16 | name | | * +--------+----------------+ consoles[0] | * | X+24 | clk_in_hz | | * +--------+----------------+ | * | X+32 | baud_rate | | * +--------+----------------+ | * | X+40 | flags | | * +--------+----------------+--------------+ * +--------+----------------+ consoles[M] | * +--------+----------------+--------------+ */ // Console info structure /* #[repr(C)] pub struct ConsoleInfo { pub base: u64, // Console base address pub map_pages: u64, // Num of pages to be mapped in RMM for the console MMIO pub name: [u8; 8], // Name of console pub clk_in_hz: u64, // UART clock (in Hz) for the console pub baud_rate: u64, // Baud rate pub flags: u64, // Additional flags RES0 } */ // NS DRAM bank structure #[repr(C)] pub struct DramBank { pub base: u64, // Base address pub size: u64, // Size of bank } // Boot manifest core structure as per v0.3 pad_struct_and_impl_default!( pub struct RmmManifest { 0x0 pub version: u32, // Manifest version 0x8 pub plat_data_ptr: u64, // Manifest platform data 0x10 pub num_banks: u64, // plat_dram.banks 0x18 pub banks_ptr: u64, // plat_dram.banks_ptr 0x20 pub banks_checksum: u64, // plat_dram.bank_checksum 0x28 pub num_consoles: u64, // plat_console.num_consoles 0x30 pub consoles_ptr: u64, // plat_console.consoles 0x38 pub console_checksum: u64, // plat_console.checksum 0x40 => @END, } ); const EL3_IFC_VERSION: u32 = 0x00000003; pub fn load() -> core::result::Result<(), Error> { debug!("Configuring RMM with EL3 manifest"); let guard: SpinlockGuard<'_, _> = RMM_SHARED_BUFFER_LOCK.lock(); let manifest = assume_safe::<RmmManifest>(*guard)?; let struct_size = core::mem::size_of::<DramBank>(); let mut dram_vec = config::NS_DRAM_REGIONS.lock(); debug!("version: {:?}", manifest.version); debug!("num_banks: {:x}", manifest.num_banks); if manifest.version != EL3_IFC_VERSION { panic!( "manifest version {:X} not supported. requires {:X}", manifest.version, EL3_IFC_VERSION ); } let mut bank_ptr = manifest.banks_ptr as usize; let mut max_base = 0; for i in 0..manifest.num_banks { let bank = assume_safe::<DramBank>(bank_ptr)?; debug!( "NS_DRAM[{:?}]: {:X}-{:X} (size:{:X})", i, bank.base, bank.base + bank.size, bank.size ); dram_vec.push(core::ops::Range { start: bank.base as usize, end: (bank.base + bank.size) as usize, }); bank_ptr += struct_size; if bank.base < max_base { panic!("Islet only accepts an ordered bank list"); } max_base = bank.base; } Ok(()) } impl safe_abstraction::raw_ptr::RawPtr for RmmManifest {} impl safe_abstraction::raw_ptr::SafetyChecked for RmmManifest {} impl safe_abstraction::raw_ptr::SafetyAssured for RmmManifest { fn is_initialized(&self) -> bool { true } fn verify_ownership(&self) -> bool { true } } impl safe_abstraction::raw_ptr::RawPtr for DramBank {} impl safe_abstraction::raw_ptr::SafetyChecked for DramBank {} impl safe_abstraction::raw_ptr::SafetyAssured for DramBank { fn is_initialized(&self) -> bool { true } fn verify_ownership(&self) -> bool { true } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmm_el3/iface.rs
rmm/src/rmm_el3/iface.rs
use super::{digest, utils}; use super::{ ATTEST_KEY_CURVE_ECC_SECP384R1, PLAT_TOKEN, REALM_ATTEST_KEY, RMM_SHARED_BUFFER_LOCK, SHA256_DIGEST_SIZE, VHUK_A, VHUK_M, }; use crate::asm::smc; use crate::{config, rmi}; use spinning_top::{Spinlock, SpinlockGuard}; const ID_VHUK_A: usize = 0x1; const ID_VHUK_M: usize = 0x2; #[derive(Debug)] enum RmmEl3IfcError { Unk, BadAddr, BadPas, NoMem, Inval, } impl From<isize> for RmmEl3IfcError { fn from(value: isize) -> Self { match value { -1 => RmmEl3IfcError::Unk, -2 => RmmEl3IfcError::BadAddr, -3 => RmmEl3IfcError::BadPas, -4 => RmmEl3IfcError::NoMem, -5 => RmmEl3IfcError::Inval, _ => panic!("Uknown RMM-EL3 SMC error code"), } } } pub(super) fn get_realm_attest_key() { trace!("RMM_GET_REALM_ATTEST_KEY"); let guard: SpinlockGuard<'_, _> = super::RMM_SHARED_BUFFER_LOCK.lock(); let ret = smc( rmi::RMM_GET_REALM_ATTEST_KEY, &[*guard, config::PAGE_SIZE, ATTEST_KEY_CURVE_ECC_SECP384R1], ); let ret_code = ret[0] as isize; let buflen = ret[1] as usize; debug!( "RMM_GET_REALM_ATTEST_KEY returned with: {}, {}", ret_code, buflen ); if ret_code != 0 { let e: RmmEl3IfcError = ret_code.into(); error!("RMM_GET_REALM_ATTEST_KEY failed with {:?}", e); } let v = utils::va_to_vec(*guard, buflen); utils::set_vector(v, &REALM_ATTEST_KEY); debug!("REALM_ATTEST_KEY: {:02x?}", super::realm_attest_key()); } pub(super) fn get_plat_token() { trace!("RMM_GET_PLAT_TOKEN"); let guard: SpinlockGuard<'_, _> = RMM_SHARED_BUFFER_LOCK.lock(); let dak_priv = utils::get_spinlock(&REALM_ATTEST_KEY); let dak_pub_hash = digest::get_realm_public_key_hash(dak_priv); utils::vec_to_va(&dak_pub_hash, *guard, config::PAGE_SIZE); let ret = smc( rmi::RMM_GET_PLAT_TOKEN, &[*guard, config::PAGE_SIZE, SHA256_DIGEST_SIZE], ); let ret_code = ret[0] as isize; let buflen = ret[1] as usize; debug!("RMM_GET_PLAT_TOKEN returned with: {}, {}", ret_code, buflen); if ret_code != 0 { let e: RmmEl3IfcError = ret_code.into(); error!("RMM_GET_PLAT_TOKEN failed with {:?}", e); } let v = utils::va_to_vec(*guard, buflen); utils::set_vector(v, &PLAT_TOKEN); debug!("PLAT_TOKEN: {:02x?}", super::plat_token()); } pub(super) fn get_vhuks() { trace!("RMM_ISLET_GET_VHUK(A&M)"); let ret_code = get_vhuk(ID_VHUK_A, &VHUK_A); if ret_code != 0 { let e: RmmEl3IfcError = ret_code.into(); error!("RMM_ISLET_GET_VHUK(A) failed with {:?}", e); } debug!("VHUK_A: {:02x?}", super::vhuk_a()); let ret_code = get_vhuk(ID_VHUK_M, &VHUK_M); if ret_code != 0 { let e: RmmEl3IfcError = ret_code.into(); error!("RMM_ISLET_GET_VHUK(M) failed with {:?}", e); } debug!("VHUK_M: {:02x?}", super::vhuk_m()); } fn get_vhuk(id: usize, out: &Spinlock<[u8; 32]>) -> isize { trace!("RMM_ISLET_GET_VHUK"); let ret = smc(rmi::RMM_ISLET_GET_VHUK, &[id]); let ret_code = ret[0] as isize; debug!("RMM_ISLET_GET_VHUK returned with: {}", ret_code); if ret_code != 0 { let e: RmmEl3IfcError = ret_code.into(); error!("RMM_ISLET_GET_VHUK failed with {:?}", e); } utils::set_array(ret, 1..5, out); ret_code }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmm_el3/utils.rs
rmm/src/rmm_el3/utils.rs
use alloc::vec::Vec; use core::{ops::Range, ptr, slice}; use spinning_top::{Spinlock, SpinlockGuard}; pub(super) fn va_to_vec(ptr: usize, len: usize) -> Vec<u8> { let ptr: *const u8 = ptr as *const u8; unsafe { slice::from_raw_parts(ptr, len).to_vec() } } pub(super) fn vec_to_va(vec: &[u8], ptr: usize, len: usize) { // safety check if vec.len() > len { panic!("Vector too long"); } let v_ptr = vec.as_ptr(); let ptr = ptr as *mut u8; unsafe { ptr::copy(v_ptr, ptr, vec.len()); } } pub(super) fn set_vector(src: Vec<u8>, dst: &Spinlock<Vec<u8>>) { let mut guard: SpinlockGuard<'_, _> = dst.lock(); guard.clear(); guard.extend_from_slice(&src); } // it's up to the caller of this function to make sure dst won't go out of bounds pub(super) fn set_array<const N: usize>( smc_ret: [usize; 8], range: Range<usize>, dst: &Spinlock<[u8; N]>, ) { let mut guard: SpinlockGuard<'_, _> = dst.lock(); let len = core::mem::size_of::<usize>(); for (i, reg) in smc_ret[range].iter().enumerate() { guard[i * len..i * len + len].copy_from_slice(reg.to_ne_bytes().as_slice()); } } pub(super) fn get_spinlock<T: Clone>(src: &Spinlock<T>) -> T { let guard: SpinlockGuard<'_, _> = src.lock(); guard.clone() }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmm_el3/mod.rs
rmm/src/rmm_el3/mod.rs
mod digest; mod iface; mod manifest; mod utils; // TODO: This code should be made in an objective manner with some RMM-EL3 // context but to do that we'd need to have a way to pass this context to the // main event loop. For the initial version I've decided to modify the original // code as little as possible. use alloc::vec::Vec; use spinning_top::{Spinlock, SpinlockGuard}; // TODO: move those consts to a more appropriate place const SHA256_DIGEST_SIZE: usize = 32; const ATTEST_KEY_CURVE_ECC_SECP384R1: usize = 0; const VHUK_LENGTH: usize = 32; static RMM_SHARED_BUFFER_LOCK: Spinlock<usize> = Spinlock::new(0); static REALM_ATTEST_KEY: Spinlock<Vec<u8>> = Spinlock::new(Vec::new()); static PLAT_TOKEN: Spinlock<Vec<u8>> = Spinlock::new(Vec::new()); static VHUK_A: Spinlock<[u8; VHUK_LENGTH]> = Spinlock::new([0xAAu8; VHUK_LENGTH]); static VHUK_M: Spinlock<[u8; VHUK_LENGTH]> = Spinlock::new([0x33u8; VHUK_LENGTH]); pub fn setup_el3_ifc(el3_shared_buf: u64) { trace!("Setup EL3 interface"); // In case of warm boot, el3_shared_buf is delivered with 0x0 if el3_shared_buf == 0x0 { warn!("el3_sshared_buf address is 0x0. Won't initialize again."); return; } { // limit the scope of lock to this scope // to avoid spinning forever in the subsequent functions let mut guard: SpinlockGuard<'_, _> = RMM_SHARED_BUFFER_LOCK.lock(); *guard = el3_shared_buf as usize; } let _ = manifest::load(); iface::get_realm_attest_key(); iface::get_plat_token(); iface::get_vhuks(); } // TODO: should those functions fail when respective RMM from TF-A failed? #[allow(dead_code)] pub fn realm_attest_key() -> Vec<u8> { utils::get_spinlock(&REALM_ATTEST_KEY) } #[allow(dead_code)] pub fn plat_token() -> Vec<u8> { utils::get_spinlock(&PLAT_TOKEN) } #[allow(dead_code)] pub fn vhuk_a() -> [u8; VHUK_LENGTH] { utils::get_spinlock(&VHUK_A) } #[allow(dead_code)] pub fn vhuk_m() -> [u8; VHUK_LENGTH] { utils::get_spinlock(&VHUK_M) }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/measurement/error.rs
rmm/src/measurement/error.rs
#[derive(Debug)] pub enum MeasurementError { InvalidHashAlgorithmValue(u8), OutputBufferTooSmall, }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/measurement/mod.rs
rmm/src/measurement/mod.rs
mod ctx; mod error; mod hash; pub use ctx::HashContext; pub use error::MeasurementError; pub use hash::Hashable; pub use hash::Hasher; pub const MEASUREMENTS_SLOT_MAX_SIZE: usize = 512 / 8; pub const MEASUREMENTS_SLOT_NR: usize = 5; pub const MEASUREMENTS_SLOT_RIM: usize = 0; pub const RMI_MEASURE_CONTENT: usize = 1; pub const MEASURE_DESC_TYPE_DATA: u8 = 0; pub const MEASURE_DESC_TYPE_REC: u8 = 1; pub const MEASURE_DESC_TYPE_RIPAS: u8 = 2; #[derive(Copy, Clone, Debug)] pub struct Measurement([u8; MEASUREMENTS_SLOT_MAX_SIZE]); impl Measurement { pub const fn empty() -> Self { Self([0u8; MEASUREMENTS_SLOT_MAX_SIZE]) } pub fn as_slice(&self) -> &[u8] { &self.0 } pub fn as_mut_slice(&mut self) -> &mut [u8] { &mut self.0 } } impl AsMut<[u8]> for Measurement { fn as_mut(&mut self) -> &mut [u8] { self.as_mut_slice() } } impl AsRef<[u8]> for Measurement { fn as_ref(&self) -> &[u8] { self.as_slice() } } impl Default for Measurement { fn default() -> Self { Measurement([0; MEASUREMENTS_SLOT_MAX_SIZE]) } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/measurement/hash.rs
rmm/src/measurement/hash.rs
use alloc::boxed::Box; use sha2::Digest; use sha2::{digest::DynDigest, Sha256, Sha512}; use crate::{ measurement::MeasurementError, rmi::{HASH_ALGO_SHA256, HASH_ALGO_SHA512}, }; pub struct HashWrapper { pub hash_func: Box<dyn DynDigest>, } impl HashWrapper { pub fn hash(&mut self, data: impl AsRef<[u8]>) { self.hash_func.update(data.as_ref()); } pub fn hash_u8(&mut self, data: u8) { self.hash_func.update(data.to_le_bytes().as_slice()); } pub fn hash_u16(&mut self, data: u16) { self.hash_func.update(data.to_le_bytes().as_slice()); } pub fn hash_u32(&mut self, data: u32) { self.hash_func.update(data.to_le_bytes().as_slice()); } pub fn hash_u64(&mut self, data: u64) { self.hash_func.update(data.to_le_bytes().as_slice()); } pub fn hash_usize(&mut self, data: usize) { self.hash_func.update(data.to_le_bytes().as_slice()); } pub fn hash_u64_array(&mut self, array: &[u64]) { for el in array.iter() { self.hash_func.update(el.to_le_bytes().as_slice()); } } fn finish(&mut self, mut out: impl AsMut<[u8]>) -> Result<(), MeasurementError> { self.hash_func .finalize_into_reset(&mut out.as_mut()[0..self.hash_func.output_size()]) .map_err(|_| MeasurementError::OutputBufferTooSmall) } } pub struct Hasher { factory: Box<dyn Fn() -> Box<dyn DynDigest>>, block_size: usize, } impl Hasher { pub fn from_hash_algo(hash_algo: u8) -> Result<Self, MeasurementError> { let factory: Box<dyn Fn() -> Box<dyn DynDigest>> = match hash_algo { HASH_ALGO_SHA256 => Box::new(|| Box::new(Sha256::new())), HASH_ALGO_SHA512 => Box::new(|| Box::new(Sha512::new())), _ => return Err(MeasurementError::InvalidHashAlgorithmValue(hash_algo)), }; let block_size = match hash_algo { HASH_ALGO_SHA256 => <Sha256 as Digest>::output_size(), HASH_ALGO_SHA512 => <Sha512 as Digest>::output_size(), _ => return Err(MeasurementError::InvalidHashAlgorithmValue(hash_algo)), }; Ok(Self { factory, block_size, }) } pub fn hash_fields_into( &self, out: impl AsMut<[u8]>, f: impl Fn(&mut HashWrapper), ) -> Result<(), MeasurementError> { let mut wrapper = HashWrapper { hash_func: (self.factory)(), }; f(&mut wrapper); wrapper.finish(out) } pub fn hash_object_into( &self, obj: &dyn Hashable, mut out: impl AsMut<[u8]>, ) -> Result<(), MeasurementError> { obj.hash(self, out.as_mut()) } pub fn output_size(&self) -> usize { self.block_size } } pub trait Hashable { fn hash(&self, hasher: &Hasher, out: &mut [u8]) -> Result<(), MeasurementError>; }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/measurement/ctx.rs
rmm/src/measurement/ctx.rs
use super::{ Hasher, Measurement, MeasurementError, MEASUREMENTS_SLOT_RIM, MEASURE_DESC_TYPE_DATA, MEASURE_DESC_TYPE_REC, MEASURE_DESC_TYPE_RIPAS, RMI_MEASURE_CONTENT, }; use crate::rmi::rec::params::Params as RecParams; use crate::{host::DataPage, realm::rd::Rd, rmi::realm::params::Params as RealmParams, rsi}; pub struct HashContext<'a> { hasher: Hasher, rd: &'a mut Rd, } impl<'a> HashContext<'a> { pub fn new(rd: &'a mut Rd) -> Result<Self, MeasurementError> { Ok(Self { hasher: Hasher::from_hash_algo(rd.hash_algo())?, rd, }) } pub fn measure_realm_create(&mut self, params: &RealmParams) -> Result<(), rsi::error::Error> { crate::rsi::measurement::extend(self.rd, MEASUREMENTS_SLOT_RIM, |rim| { self.hasher.hash_object_into(params, rim) }) } pub fn extend_measurement( &mut self, buffer: &[u8], index: usize, ) -> Result<(), rsi::error::Error> { crate::rsi::measurement::extend(self.rd, index, |current| { let old_value = *current; self.hasher.hash_fields_into(current, |h| { h.hash(&old_value.as_ref()[0..self.hasher.output_size()]); h.hash(buffer); }) }) } pub fn measure_data_granule( &mut self, data: &DataPage, ipa: usize, flags: usize, ) -> Result<(), rsi::error::Error> { let mut data_measurement = Measurement::empty(); if flags == RMI_MEASURE_CONTENT { self.hasher.hash_fields_into(&mut data_measurement, |h| { h.hash(data.as_slice()); })?; } crate::rsi::measurement::extend(self.rd, MEASUREMENTS_SLOT_RIM, |current| { let oldrim = *current; self.hasher.hash_fields_into(current, |h| { h.hash_u8(MEASURE_DESC_TYPE_DATA); // desc type h.hash([0u8; 7]); // padding h.hash_u64(0x100); // desc struct size h.hash(oldrim); // old RIM value h.hash_usize(ipa); // ipa h.hash_usize(flags); // flags h.hash(data_measurement); // data granule hash h.hash([0u8; 0x100 - 0xa0]); // padding }) }) } pub fn measure_rec_params(&mut self, params: &RecParams) -> Result<(), rsi::error::Error> { let mut params_measurement = Measurement::empty(); self.hasher .hash_object_into(params, &mut params_measurement)?; crate::rsi::measurement::extend(self.rd, MEASUREMENTS_SLOT_RIM, |current| { let oldrim = *current; self.hasher.hash_fields_into(current, |h| { h.hash_u8(MEASURE_DESC_TYPE_REC); // desc type h.hash([0u8; 7]); // padding h.hash_u64(0x100); // desc struct size h.hash(oldrim); // old RIM value h.hash(params_measurement); // REC params hash h.hash([0u8; 0x100 - 0x90]); // padding }) }) } pub fn measure_ripas_granule(&mut self, base: u64, top: u64) -> Result<(), rsi::error::Error> { crate::rsi::measurement::extend(self.rd, MEASUREMENTS_SLOT_RIM, |current| { let oldrim = *current; self.hasher.hash_fields_into(current, |h| { h.hash_u8(MEASURE_DESC_TYPE_RIPAS); // desc type h.hash([0u8; 7]); // padding h.hash_u64(0x100); // desc struct size h.hash(oldrim); // old RIM value h.hash_u64(base); // ipa h.hash_u64(top); // level h.hash([0u8; 0x100 - 0x60]); // padding to 0x100 size }) }) } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/granule/mod.rs
rmm/src/granule/mod.rs
#[cfg(feature = "gst_page_table")] pub mod page_table; #[cfg(feature = "gst_page_table")] pub use page_table::*; #[cfg(not(feature = "gst_page_table"))] pub mod array; #[cfg(not(feature = "gst_page_table"))] pub use array::*;
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/granule/page_table/translation.rs
rmm/src/granule/page_table/translation.rs
use super::entry; use super::{validate_addr, GranuleState, L0Table, L1Table, GRANULE_SIZE}; use crate::config; use crate::const_assert_eq; use alloc::collections::BTreeMap; use core::ptr::addr_of_mut; use vmsa::address::PhysAddr; use vmsa::error::Error; use vmsa::page::{Page, PageSize}; use vmsa::page_table::{DefaultMemAlloc, Level, PageTable, PageTableMethods}; pub const L0_TABLE_ENTRY_SIZE_RANGE: usize = 1024 * 1024 * 4; // 4mb pub const L1_TABLE_ENTRY_SIZE_RANGE: usize = GRANULE_SIZE; const_assert_eq!(L0_TABLE_ENTRY_SIZE_RANGE % L1_TABLE_ENTRY_SIZE_RANGE, 0); type L0PageTable = PageTable<PhysAddr, L0Table, entry::Entry, { <L0Table as Level>::NUM_ENTRIES }>; pub type L1PageTable = PageTable<PhysAddr, L1Table, entry::Entry, { <L1Table as Level>::NUM_ENTRIES }>; pub struct GranuleStatusTable<'a, 'b> { pub root_pgtbl: &'a mut L0PageTable, l1_tables: BTreeMap<usize, &'b mut L1PageTable>, // TODO: replace this BTreeMap with a more efficient structure. // to do so, we need to do refactoring on how we manage entries in PageTable. // e.g., moving storage (`entries: [E; N]`) out of PageTable, and each impl (GST, RMM, RTT) is in charge of handling that. } impl GranuleStatusTable<'_, '_> { pub fn new() -> Self { Self { root_pgtbl: L0PageTable::new_in(&DefaultMemAlloc {}).unwrap(), l1_tables: BTreeMap::new(), } } fn add_l1_table(&mut self, index: usize, addr: usize) { self.l1_tables .insert(index, unsafe { &mut *(addr as *mut L1PageTable) }); } pub fn set_granule(&mut self, addr: usize, state: u64) -> Result<(), Error> { if !validate_addr(addr) { return Err(Error::MmInvalidAddr); } let pa1 = Page::<GranuleSize, PhysAddr>::including_address(PhysAddr::from(addr)); let pa2 = Page::<GranuleSize, PhysAddr>::including_address(PhysAddr::from(addr)); self.root_pgtbl.set_page(pa1, pa2, state) } } #[derive(Clone, Copy)] pub enum GranuleSize {} impl PageSize for GranuleSize { const SIZE: usize = GRANULE_SIZE; const MAP_TABLE_LEVEL: usize = 1; const MAP_EXTRA_FLAG: u64 = GranuleState::Undelegated; } pub static mut GRANULE_STATUS_TABLE: Option<GranuleStatusTable<'_, '_>> = None; pub fn add_l1_table(index: usize, addr: usize) -> Result<usize, Error> { if let Some(gst) = unsafe { &mut *addr_of_mut!(GRANULE_STATUS_TABLE) } { gst.add_l1_table(index, addr); if let Some(t) = gst.l1_tables.get(&index) { Ok(t as *const _ as usize) } else { Err(Error::MmErrorOthers) } } else { Err(Error::MmErrorOthers) } } pub fn get_l1_table_addr(index: usize) -> Result<usize, Error> { if let Some(gst) = unsafe { &mut *addr_of_mut!(GRANULE_STATUS_TABLE) } { if let Some(t) = gst.l1_tables.get_mut(&index) { Ok(*t as *mut _ as usize) } else { Err(Error::MmErrorOthers) } } else { Err(Error::MmErrorOthers) } } pub fn addr_to_idx(phys: usize) -> Result<usize, Error> { if phys % GRANULE_SIZE != 0 { warn!("address need to be aligned 0x{:X}", phys); return Err(Error::MmInvalidAddr); } let mut base_idx = 0; let regions = config::NS_DRAM_REGIONS.lock(); for range in regions.iter() { if range.contains(&phys) { return Ok((phys - range.start) / GRANULE_SIZE + base_idx); } base_idx += (range.end - range.start) / GRANULE_SIZE; } warn!("address is strange 0x{:X}", phys); Err(Error::MmInvalidAddr) }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/granule/page_table/mod.rs
rmm/src/granule/page_table/mod.rs
pub mod entry; pub mod translation; use self::entry::{Entry, Inner}; use self::translation::{ GranuleStatusTable, GRANULE_STATUS_TABLE, L0_TABLE_ENTRY_SIZE_RANGE, L1_TABLE_ENTRY_SIZE_RANGE, }; use crate::config; use crate::rmi::error::Error as RmiError; use core::ptr::addr_of_mut; use vmsa::address::PhysAddr; use vmsa::error::Error; use vmsa::page_table::{HasSubtable, Level}; pub const GRANULE_SIZE: usize = 4096; pub const GRANULE_SHIFT: usize = 12; pub const GRANULE_MASK: usize = !((1 << GRANULE_SHIFT) - 1); /// The Level 0 Table /// Each entry (L1table) covers 4mb. This is a configurable number. pub enum L0Table {} impl Level for L0Table { const THIS_LEVEL: usize = 0; const TABLE_SIZE: usize = Self::NUM_ENTRIES * core::mem::size_of::<Entry>(); const TABLE_ALIGN: usize = 64; const NUM_ENTRIES: usize = L1Table::NUM_ENTRIES; // Note/TODO: why using "L1Table::NUM_ENTRIES"? // currently, PageTable simply assumes that every level table has the same NUM_ENTRIES. // it gets problematic in which for example L0Table has 1000 entries while L1table has 1024 entries. // when trying to access L1table[1010], it causes out-of-bound access because the array is created by the size of 1000. // for a workaround, we need to use the largest NUM_ENTRIES. } impl HasSubtable for L0Table { type NextLevel = L1Table; } /// The Level 1 Table /// Each entry covers PAGE_SIZE (4kb). pub enum L1Table {} impl Level for L1Table { const THIS_LEVEL: usize = 1; const TABLE_SIZE: usize = Self::NUM_ENTRIES * core::mem::size_of::<Entry>(); const TABLE_ALIGN: usize = 64; const NUM_ENTRIES: usize = (L0_TABLE_ENTRY_SIZE_RANGE / L1_TABLE_ENTRY_SIZE_RANGE); } #[derive(Clone, Copy, Debug, PartialEq)] pub struct GranuleState { pub inner: u64, } #[allow(non_upper_case_globals)] impl GranuleState { pub const Undelegated: u64 = 0; pub const Delegated: u64 = 1; pub const RD: u64 = 2; pub const Rec: u64 = 3; pub const RecAux: u64 = 4; pub const Data: u64 = 5; pub const RTT: u64 = 6; pub const Metadata: u64 = 7; pub fn new(state: u64) -> Self { Self { inner: state } } } /// Safety / Usage: "granule transaction" a set of APIs that define how to access "granule" and contents inside it. /// /// - Goal /// - The high-level goal of these APIs is to enforce that read/write from/to "granule" is only allowed after getting a proper granule lock. /// /// - Usage: take the example of REALM_DESTROY. /// (1) `let mut g = get_granule_if!(addr, GranuleStatus::RD);` --> getting a granule while holding a lock. (precisely, it gets EntryGuard<entry::Inner>) /// (2) ... do something under `g` ... /// (3) `set_granule(&mut g, GranuleStatus::Delegated)` --> do a state transition when everything goes ok. /// - this can be seen as a typical transaction that defines a way to access granule. (granule transaction) /// - to open a transaction, you can use either `get_granule` or `get_granule_if` or `set_state_and_get_granule`. /// - to modify a granule and close a transaction, `set_granule` can be used. /// /// - Safety: /// - In the above usage, `set_granule()` takes &entry::Inner as input, which can only be acquired by `get_granule_if!`. /// This means that you can access granule only after `get_granule_if!`, and this is ensured by this API design. /// - TODO(Optional): currently, handling a granule transaction is in charge of developers. /// e.g., (1) they should invoke `set_granule()` at the right moment, (2) `EntryGuard` still lives after `set_granule()`. /// we might be able to free them from it via Rust features. /// - TODO(Must): currently, these APIs do not involve in mapping some address into RMM page table. /// callers must map some physical address, if needed, before/after using these APIs. /// we need to define and use a secure interface to map some address and do set_granule(). /// /// - Note: /// - why is it using macros, not functions? /// writing a function that returns `EntryGuard<>` requires cloning EntryGuard. To get around this, macros are currently used. /// we might be able to figure out a better way to define `get_granule_*!` macros. /// get_granule!(addr: a physical address) /// - when success, returns `EntryGuard<entry::Inner>` allowing an access to "Granule". #[macro_export] macro_rules! get_granule { ($addr:expr) => {{ { use crate::granule::translation::{GranuleSize, GRANULE_STATUS_TABLE}; use crate::granule::validate_addr; use core::ptr::addr_of_mut; use vmsa::address::PhysAddr; use vmsa::error::Error as MmError; use vmsa::page::Page; use vmsa::page_table::{self, PageTableMethods}; if !validate_addr($addr) { Err(MmError::MmInvalidAddr) } else { if let Some(gst) = unsafe { &mut *addr_of_mut!(GRANULE_STATUS_TABLE) } { let pa = Page::<GranuleSize, PhysAddr>::including_address(PhysAddr::from($addr)); match gst .root_pgtbl .entry(pa, 1, false, |e| page_table::Entry::lock(e)) { Ok(guard) => match guard { (Some(g), _level) => Ok(g), _ => Err(MmError::MmNoEntry), }, Err(e) => Err(e), } } else { Err(MmError::MmErrorOthers) } } } }}; } /// get_granule_if!(addr: a physical address, state: a granule state you expect it to be) /// - when success, returns `EntryGuard<entry::Inner>` allowing an access to "Granule". #[macro_export] macro_rules! get_granule_if { ($addr:expr, $state:expr) => {{ get_granule!($addr).and_then(|guard| { if guard.state() != $state { use vmsa::error::Error as MmError; Err(MmError::MmStateError) } else { Ok(guard) } }) }}; } /// set_state_and_get_granule!(addr: a physical address, state: a granule state you want to set) /// - when success, returns `EntryGuard<entry::Inner>` allowing an access to "Granule". #[macro_export] macro_rules! set_state_and_get_granule { ($addr:expr, $state:expr) => {{ { use crate::granule::set_granule_raw; set_granule_raw($addr, $state).and_then(|_| get_granule!($addr)) } }}; } fn make_move_mut_reference<T>(_: T) {} // Notice: do not try to make a cycle in parent-child relationship // e.g., Rd (parent) -> Rec (child) -> Rd (parent) pub fn set_granule_with_parent( parent: Inner, child: &mut Inner, state: u64, ) -> Result<(), RmiError> { let addr = child.addr(); let prev = child.state(); match child.set_state(PhysAddr::from(addr), state) { Ok(_) => { match child.set_parent(parent) { Ok(_) => Ok(()), Err(e) => { // In this case, state has already been changed. // So, we should get its state back for a complete transaction management. to_rmi_result(child.set_state(PhysAddr::from(addr), prev))?; to_rmi_result(Err(e)) } } } Err(e) => to_rmi_result(Err(e)), } } pub fn set_granule(granule: &mut Inner, state: u64) -> Result<(), RmiError> { let addr = granule.addr(); to_rmi_result(granule.set_state(PhysAddr::from(addr), state))?; make_move_mut_reference(granule); Ok(()) } pub fn check_granule_parent(parent: &Inner, child: &Inner) -> Result<(), RmiError> { to_rmi_result(child.check_parent(parent)) } /// This is the only function that doesn't take `Inner` as input, instead it takes a raw address. /// Notice: do not directly call this function outside this file. pub fn set_granule_raw(addr: usize, state: u64) -> Result<(), Error> { if let Some(gst) = unsafe { &mut *addr_of_mut!(GRANULE_STATUS_TABLE) } { gst.set_granule(addr, state) } else { Err(Error::MmErrorOthers) } } pub fn validate_addr(addr: usize) -> bool { if addr % GRANULE_SIZE != 0 { // if the address is out of range. warn!("address need to be aligned 0x{:X}", addr); return false; } if !config::is_ns_dram(addr) { // if the address is out of range. warn!("address is strange 0x{:X}", addr); return false; } true } // TODO: we can use "constructors" for this kind of initialization. (we can define macros for that) pub fn create_granule_status_table() { unsafe { if GRANULE_STATUS_TABLE.is_none() { GRANULE_STATUS_TABLE = Some(GranuleStatusTable::new()); } } } pub fn to_rmi_result(res: Result<(), Error>) -> Result<(), RmiError> { match res { Ok(_) => Ok(()), Err(e) => Err(RmiError::from(e)), } } pub fn is_not_in_realm(addr: usize) -> bool { match get_granule_if!(addr, GranuleState::Undelegated) { Ok(_) | Err(Error::MmNoEntry) => true, _ => false, } } pub fn is_granule_aligned(addr: usize) -> bool { addr % GRANULE_SIZE == 0 } #[cfg(test)] mod test { use crate::granule::translation::{GranuleStatusTable, GRANULE_STATUS_TABLE}; use crate::granule::{set_granule, GranuleState}; use crate::set_state_and_get_granule; use vmsa::error::Error; const TEST_ADDR: usize = 0x880c_0000; const TEST_WRONG_ADDR: usize = 0x7900_0000; fn recreate_granule_status_table() { unsafe { if GRANULE_STATUS_TABLE.is_none() { GRANULE_STATUS_TABLE = Some(GranuleStatusTable::new()); } else { GRANULE_STATUS_TABLE.take(); GRANULE_STATUS_TABLE = Some(GranuleStatusTable::new()); } } } #[test] fn test_add_granule() { recreate_granule_status_table(); let test_fn = |addr: usize| -> Result<(), Error> { let mut granule = set_state_and_get_granule!(addr, GranuleState::Delegated)?; assert!(set_granule(&mut granule, GranuleState::Undelegated).is_ok()); Ok(()) }; assert!(test_fn(TEST_ADDR).is_ok()); } #[test] fn test_find_granule_with_wrong_addr() { recreate_granule_status_table(); let test_fn = |addr: usize| -> Result<(), Error> { let _ = set_state_and_get_granule!(addr, GranuleState::Delegated)?; Ok(()) }; assert!(test_fn(TEST_WRONG_ADDR).is_err()); } #[test] fn test_validate_state() { recreate_granule_status_table(); let test_fn = |addr: usize| -> Result<(), Error> { let mut granule = set_state_and_get_granule!(addr, GranuleState::Delegated)?; assert!(set_granule(&mut granule, GranuleState::RTT).is_ok()); assert!(set_granule(&mut granule, GranuleState::Delegated).is_ok()); assert!(set_granule(&mut granule, GranuleState::Undelegated).is_ok()); Ok(()) }; assert!(test_fn(TEST_ADDR).is_ok()); } #[test] fn test_validate_wrong_state() { recreate_granule_status_table(); let test_fn = |addr: usize| -> Result<(), Error> { let mut granule = set_state_and_get_granule!(addr, GranuleState::Delegated)?; assert!(set_granule(&mut granule, GranuleState::Delegated).is_err()); assert!(set_granule(&mut granule, GranuleState::Undelegated).is_ok()); Ok(()) }; assert!(test_fn(TEST_ADDR).is_ok()); } #[test] fn test_get_granule_state() { recreate_granule_status_table(); let test_fn = |addr: usize| -> Result<(), Error> { let granule = set_state_and_get_granule!(addr, GranuleState::Delegated)?; assert!(granule.state() == GranuleState::Delegated); Ok(()) }; assert!(test_fn(TEST_ADDR).is_ok()); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/granule/page_table/entry.rs
rmm/src/granule/page_table/entry.rs
use vmsa::address::PhysAddr; use vmsa::error::Error; use vmsa::guard::EntryGuard; use vmsa::page_table::{self, Level}; use super::translation::{add_l1_table, addr_to_idx, get_l1_table_addr, L0_TABLE_ENTRY_SIZE_RANGE}; use super::{GranuleState, GRANULE_SIZE}; use spinning_top::Spinlock; extern crate alloc; use alloc::rc::Rc; // Safety: concurrency safety // - For a granule status table that manages granules, it doesn't use a big lock for efficiency. So, we need to associate "lock" with each granule entry. // - For granule entries and a page table for them, removing a table or an entry is not supported on purpose to make things easier for concurrency safety. // - There are two points that requires locking, // - (1) subtable creation: `set_with_page_table_flags_via_alloc()` is in charge of it. In this function, validity_check-memory_alloc-set_state should be done under the lock. // - (2) state change on entry: `set()` should be done under the lock. // - Each entry can be either table (L1 table) or granule. This is determined by `Inner.table`. pub struct Granule { /// granule state state: u64, /// physical address which is aligned with GRANULE_SIZE addr: usize, /// parent that this granule points to /// the only case at this point is "Rd(parent) - Rec(child)" /// Notice: do not put self-reference into this field, which may cause undefined behaviors. parent: Option<Inner>, } impl Granule { fn set_state<F>(&mut self, addr: usize, state: u64, destroy_callback: F) -> Result<(), Error> where F: Fn() -> Result<(), Error>, { // check if this state transition is valid let prev = self.state; let valid = match prev { GranuleState::Undelegated => { state == GranuleState::Delegated || state == GranuleState::Undelegated } GranuleState::Delegated => state != GranuleState::Delegated, _ => state == GranuleState::Delegated, }; if !valid { error!( "Granule state transition failed: prev[{:?}] -> next[{:?}]", prev, state ); return Err(Error::MmStateError); } // check if it needs to be wiped out match state { GranuleState::Delegated => { // transition from something to Delegatated means "destroyed". (e.g., Rd --> Delegated when REALM_DESTROY) // so, it releases its parent and check its refcount to determine whether it's safe to get destroyed. // Note: currently, as we don't map RTT, rule out the case where prev == RTT. if prev != GranuleState::RTT { self.parent.take(); destroy_callback()?; self.zeroize(); } } GranuleState::Undelegated => { if prev == GranuleState::Delegated { self.zeroize(); } } _ => {} } self.addr = addr; self.state = state; Ok(()) } fn set_parent(&mut self, parent: Inner) -> Result<(), Error> { // parent-child state validation check // (Parent, Child): (Rd, Rec) --> only one case at this moment. if self.state() != GranuleState::Rec || parent.granule.state() != GranuleState::RD { return Err(Error::MmWrongParentChild); } self.parent = Some(parent); Ok(()) } fn set_addr(&mut self, addr: usize) { self.addr = addr; } fn addr(&self) -> usize { self.addr } fn state(&self) -> u64 { self.state } #[cfg(not(test))] fn zeroize(&mut self) { let buf = self.addr; unsafe { core::ptr::write_bytes(buf as *mut usize, 0x0, GRANULE_SIZE / 8); } } #[cfg(test)] fn zeroize(&mut self) {} } pub struct Inner { granule: Rc<Granule>, table: bool, valid: bool, } impl Inner { fn new() -> Self { Self { granule: Rc::new(Granule { state: GranuleState::Undelegated, addr: 0, parent: None, }), table: false, valid: false, } } pub fn addr(&self) -> usize { self.granule.addr() } pub fn state(&self) -> u64 { self.granule.state() } pub fn set_state(&mut self, addr: PhysAddr, state: u64) -> Result<(), Error> { let refcount = Rc::strong_count(&self.granule); Rc::get_mut(&mut self.granule).map_or_else( || Err(Error::MmRefcountError), |g| { g.set_state(addr.as_usize(), state, || { if refcount > 1 { // if this is a command to destroy granule (e.g., Rd -> Delegated), // there has to be no one who points to it. // for example, when REALM_DESTROY, it must be guranteed that no RECs point to it. Err(Error::MmIsInUse) } else { Ok(()) } }) }, )?; self.table = false; self.valid = true; Ok(()) } pub fn set_parent(&mut self, parent: Inner) -> Result<(), Error> { Rc::get_mut(&mut self.granule) .map_or_else(|| Err(Error::MmRefcountError), |g| g.set_parent(parent)) } pub fn check_parent(&self, parent: &Inner) -> Result<(), Error> { if let Some(src_parent) = &self.granule.parent { if core::ptr::eq(src_parent, parent) { Ok(()) } else { Err(Error::MmStateError) } } else { Err(Error::MmStateError) } } pub fn num_children(&self) -> usize { Rc::strong_count(&self.granule) - 1 } fn set_state_for_table(&mut self, index: usize, addr: usize) -> Result<(), Error> { match add_l1_table(index, addr) { Ok(addr) => { Rc::get_mut(&mut self.granule).map_or_else( || Err(Error::MmRefcountError), |g| { g.set_addr(addr); Ok(()) }, )?; } Err(e) => { return Err(e); } } self.table = true; self.valid = true; Ok(()) } fn valid(&self) -> bool { self.valid } } impl Clone for Inner { fn clone(&self) -> Inner { Inner { granule: self.granule.clone(), table: self.table, valid: self.valid, } } } pub struct Entry(Spinlock<Inner>); impl page_table::Entry for Entry { type Inner = Inner; fn new() -> Self { Self(Spinlock::new(Inner::new())) } fn is_valid(&self) -> bool { self.0.lock().valid() } fn clear(&mut self) {} fn pte(&self) -> u64 { todo!(); } fn mut_pte(&mut self) -> &mut Self::Inner { self.0.get_mut() } fn address(&self, _level: usize) -> Option<PhysAddr> { Some(PhysAddr::from(self.0.lock().addr())) } fn set(&mut self, addr: PhysAddr, flags: u64) -> Result<(), Error> { self.0.lock().set_state(addr, flags) } fn point_to_subtable(&mut self, index: usize, addr: PhysAddr) -> Result<(), Error> { let mut inner = self.0.lock(); if !inner.valid() { inner.set_state_for_table(index, addr.into()) } else { Ok(()) } } fn index<L: Level>(addr: usize) -> usize { match addr_to_idx(addr) { Ok(idx) => match L::THIS_LEVEL { 0 => (idx * GRANULE_SIZE) / L0_TABLE_ENTRY_SIZE_RANGE, 1 => ((idx * GRANULE_SIZE) % L0_TABLE_ENTRY_SIZE_RANGE) / GRANULE_SIZE, _ => panic!(), }, Err(_) => panic!(), } } fn as_subtable(&self, index: usize, _level: usize) -> Result<usize, Error> { get_l1_table_addr(index) } fn lock(&self) -> Result<Option<EntryGuard<'_, Self::Inner>>, Error> { let inner = self.0.lock(); let addr = inner.addr(); let state = inner.state(); let valid = inner.valid(); if !valid { Err(Error::MmStateError) } else { Ok(Some(EntryGuard::new(inner, addr, state))) } } fn points_to_table_or_page(&self) -> bool { true } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/granule/array/mod.rs
rmm/src/granule/array/mod.rs
pub mod entry; use self::entry::Entry; use self::entry::Granule; use crate::config; use crate::rmi::error::Error; pub const GRANULE_SIZE: usize = 4096; pub const GRANULE_SHIFT: usize = 12; pub const GRANULE_MASK: usize = !((1 << GRANULE_SHIFT) - 1); #[cfg(any(kani, miri, test, fuzzing))] pub const GRANULE_MEM_SIZE: usize = GRANULE_SIZE * GRANULE_STATUS_TABLE_SIZE; #[cfg(any(kani, miri, test, fuzzing))] // We model the Host memory as a pre-allocated memory region which // can avoid a false positive related to invalid memory accesses // in model checking. Also, instead of using the same starting // address (e.g., 0x8000_0000), we use a mock region filled with // non-deterministic contents. It helps to address an issue related // to the backend CBMC's pointer encoding, as 0x8000_0000 cannot be // distinguished from null pointer in CBMC. // // NOTE: In MIRI and test evironments, aligned addresses are used, // so the last region cannot be utilized. pub static mut GRANULE_REGION: [u8; GRANULE_MEM_SIZE] = [0; GRANULE_MEM_SIZE]; #[cfg(not(any(kani, miri, test, fuzzing)))] pub fn validate_addr(addr: usize) -> bool { if addr % GRANULE_SIZE != 0 { // if the address is out of range. warn!("address need to be aligned 0x{:X}", addr); return false; } if !config::is_ns_dram(addr) { // if the address is out of range. warn!("address is strange 0x{:X}", addr); return false; } true } #[cfg(any(kani, miri, test, fuzzing))] // DIFF: check against GRANULE_REGION pub fn validate_addr(addr: usize) -> bool { if addr % GRANULE_SIZE != 0 { // if the address is out of range. warn!("address need to be aligned 0x{:X}", addr); return false; } let g_start = unsafe { GRANULE_REGION.as_ptr() as usize }; let g_end = g_start + GRANULE_MEM_SIZE; addr >= g_start && addr < g_end } #[cfg(not(any(kani, miri, test, fuzzing)))] pub fn granule_addr_to_index(addr: usize) -> usize { let regions = config::NS_DRAM_REGIONS.lock(); let mut base_idx = 0; for range in regions.iter() { if range.contains(&addr) { return (addr - range.start) / GRANULE_SIZE + base_idx; } base_idx += (range.end - range.start) / GRANULE_SIZE; } usize::MAX } #[cfg(any(kani, miri, test, fuzzing))] // DIFF: calculate index using GRANULE_REGION pub fn granule_addr_to_index(addr: usize) -> usize { let g_start = unsafe { GRANULE_REGION.as_ptr() as usize }; let g_end = g_start + GRANULE_MEM_SIZE; if addr >= g_start && addr < g_end { return (addr - g_start) / GRANULE_SIZE; } usize::MAX } pub fn is_granule_aligned(addr: usize) -> bool { addr % GRANULE_SIZE == 0 } #[derive(Clone, Copy, Debug, PartialEq)] pub struct GranuleState { pub inner: u8, } #[allow(non_upper_case_globals)] impl GranuleState { pub const Undelegated: u8 = 0; pub const Delegated: u8 = 1; pub const RD: u8 = 2; pub const Rec: u8 = 3; pub const RecAux: u8 = 4; pub const Data: u8 = 5; pub const RTT: u8 = 6; pub const Metadata: u8 = 7; pub fn new(state: u8) -> Self { Self { inner: state } } } pub fn set_granule(granule: &mut Granule, state: u8) -> Result<(), Error> { granule.set_state(state) } lazy_static! { pub static ref GRANULE_STATUS_TABLE: GranuleStatusTable = GranuleStatusTable::new(); } #[cfg(not(any(kani, miri, test, fuzzing)))] pub const GRANULE_STATUS_TABLE_SIZE: usize = config::MAX_DRAM_SIZE / GRANULE_SIZE; // == RMM_MAX_GRANULES #[cfg(kani)] pub const GRANULE_STATUS_TABLE_SIZE: usize = 6; #[cfg(any(miri, test))] pub const GRANULE_STATUS_TABLE_SIZE: usize = 55; #[cfg(fuzzing)] pub const GRANULE_STATUS_TABLE_SIZE: usize = 2048; pub struct GranuleStatusTable { pub entries: [Entry; GRANULE_STATUS_TABLE_SIZE], } impl GranuleStatusTable { pub fn new() -> Self { Self { entries: core::array::from_fn(|_| Entry::new()), } } #[cfg(kani)] pub fn is_valid(&self) -> bool { self.entries .iter() .fold(true, |acc, x| acc && x.lock().unwrap().is_valid()) } } #[macro_export] macro_rules! get_granule { ($addr:expr) => {{ use crate::granule::array::{GRANULE_STATUS_TABLE, GRANULE_STATUS_TABLE_SIZE}; use crate::granule::{granule_addr_to_index, validate_addr}; use crate::rmi::error::Error; if !validate_addr($addr) { Err(Error::RmiErrorInput) } else { let idx = granule_addr_to_index($addr); if idx >= GRANULE_STATUS_TABLE_SIZE { Err(Error::RmiErrorInput) } else { let gst = &GRANULE_STATUS_TABLE; match gst.entries[idx].lock() { Ok(guard) => Ok(guard), Err(e) => Err(e), } } } }}; } #[macro_export] macro_rules! get_granule_if { ($addr:expr, $state:expr) => {{ get_granule!($addr).and_then(|guard| { if guard.state() != $state { use crate::rmi::error::Error; Err(Error::RmiErrorInput) } else { Ok(guard) } }) }}; } pub fn is_not_in_realm(addr: usize) -> bool { match get_granule_if!(addr, GranuleState::Undelegated) { Ok(_) => true, _ => false, } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/granule/array/entry.rs
rmm/src/granule/array/entry.rs
use crate::config; use crate::granule::array::GRANULE_STATUS_TABLE; use crate::rmi::error::Error; use super::{GranuleState, GRANULE_SIZE}; use core::sync::atomic::{AtomicU8, Ordering}; use safe_abstraction::raw_ptr; use spinning_top::{Spinlock, SpinlockGuard}; use vmsa::guard::Content; // Safety: concurrency safety // - For a granule status table that manages granules, it doesn't use a big lock for efficiency. // So, we need to associate "lock" with each granule entry. #[cfg(not(any(kani, miri, test, fuzzing)))] #[derive(Debug)] pub struct Granule { /// granule state state: u8, /// granule ref count ref_count: AtomicU8, } #[cfg(any(kani, miri, test, fuzzing))] // DIFF: `gpt` ghost field is added to track GPT entry's status pub struct Granule { /// granule state state: u8, /// granule ref count ref_count: AtomicU8, /// granule protection table (ghost field) pub gpt: GranuleGpt, } #[cfg(kani)] #[derive(Copy, Clone, PartialEq, kani::Arbitrary)] pub enum GranuleGpt { GPT_NS, GPT_OTHER, GPT_REALM, } #[cfg(any(miri, test, fuzzing))] #[derive(Copy, Clone, PartialEq)] pub enum GranuleGpt { GPT_NS, GPT_OTHER, GPT_REALM, } impl Granule { #[cfg(not(any(kani, miri, test, fuzzing)))] fn new() -> Self { let state = GranuleState::Undelegated; let ref_count = AtomicU8::new(0); Granule { state, ref_count } } #[cfg(any(kani, miri, test, fuzzing))] // DIFF: `state` and `gpt` are filled with non-deterministic values fn new() -> Self { #[cfg(kani)] { let state = kani::any(); let ref_count = AtomicU8::new(kani::any()); kani::assume(state >= GranuleState::Undelegated && state <= GranuleState::RTT); let gpt = { if state != GranuleState::Undelegated { GranuleGpt::GPT_REALM } else { let gpt = kani::any(); kani::assume(gpt != GranuleGpt::GPT_REALM); gpt } }; Granule { state, ref_count, gpt, } } #[cfg(any(miri, test, fuzzing))] { Self { state: GranuleState::Undelegated, ref_count: AtomicU8::new(0), gpt: GranuleGpt::GPT_NS, } } } pub fn inc_count(&mut self) { let _ = self.ref_count.fetch_add(1, Ordering::SeqCst); } pub fn dec_count(&mut self) { let _ = self.ref_count.fetch_sub(1, Ordering::SeqCst); } pub fn load_count(&self) -> u8 { self.ref_count.load(Ordering::SeqCst) } pub fn num_children(&self) -> usize { self.ref_count.load(Ordering::SeqCst) as usize } #[cfg(any(kani, miri, test, fuzzing))] pub fn set_gpt(&mut self, gpt: GranuleGpt) { self.gpt = gpt; } #[cfg(any(kani, miri, test, fuzzing))] pub fn is_valid(&self) -> bool { self.state >= GranuleState::Undelegated && self.state <= GranuleState::RTT && // XXX: the below condition holds from beta0 to eac4 if self.state != GranuleState::Undelegated { self.gpt == GranuleGpt::GPT_REALM } else { self.gpt != GranuleGpt::GPT_REALM } } pub fn state(&self) -> u8 { self.state } pub fn set_state(&mut self, state: u8) -> Result<(), Error> { let prev = self.state; if (prev == GranuleState::Delegated && state == GranuleState::Undelegated) || (state == GranuleState::Delegated) { self.zeroize(); } self.state = state; Ok(()) } pub fn content_mut<T>(&mut self) -> Result<raw_ptr::SafetyAssumed<T>, Error> where T: Content + raw_ptr::SafetyChecked + raw_ptr::SafetyAssured, { let addr = self.index_to_addr(); Ok(raw_ptr::assume_safe::<T>(addr)?) } pub fn new_uninit_with<T>(&mut self, value: T) -> Result<raw_ptr::SafetyAssumed<T>, Error> where T: Content + raw_ptr::SafetyChecked + raw_ptr::SafetyAssured, { let addr = self.index_to_addr(); Ok(raw_ptr::assume_safe_uninit_with::<T>(addr, value)?) } pub fn content<T>(&self) -> Result<raw_ptr::SafetyAssumed<T>, Error> where T: Content + raw_ptr::SafetyChecked + raw_ptr::SafetyAssured, { let addr = self.index_to_addr(); Ok(raw_ptr::assume_safe::<T>(addr)?) } fn index(&self) -> usize { let entry_size = core::mem::size_of::<Entry>(); let granule_size = core::mem::size_of::<Granule>(); // XXX: is there a clever way of getting the Entry from Granule (e.g., container_of())? // [ Entry ] // [ offset ] [ Granule ] let granule_offset = entry_size - granule_size; let granule_addr = self as *const Granule as usize; let entry_addr = granule_addr - granule_offset; let gst = &GRANULE_STATUS_TABLE; let table_base = gst.entries.as_ptr() as usize; (entry_addr - table_base) / core::mem::size_of::<Entry>() } #[cfg(not(any(kani, miri, test, fuzzing)))] fn index_to_addr(&self) -> usize { let mut idx = self.index(); let regions = config::NS_DRAM_REGIONS.lock(); for range in regions.iter() { let region_max = (range.end - range.start) / GRANULE_SIZE; if idx < region_max { return range.start + (idx * GRANULE_SIZE); } idx -= region_max; } 0 } #[cfg(any(kani, miri, test, fuzzing))] // DIFF: calculate addr using GRANULE_REGION pub fn index_to_addr(&self) -> usize { use crate::granule::{GRANULE_REGION, GRANULE_STATUS_TABLE_SIZE}; let idx = self.index(); assert!(idx < GRANULE_STATUS_TABLE_SIZE); #[cfg(any(miri, test, fuzzing))] return crate::test_utils::align_up(unsafe { GRANULE_REGION.as_ptr() as usize + (idx * GRANULE_SIZE) }); #[cfg(kani)] return unsafe { GRANULE_REGION.as_ptr() as usize + (idx * GRANULE_SIZE) }; } #[cfg(not(any(kani, miri, test, fuzzing)))] fn zeroize(&mut self) { let addr = self.index_to_addr(); // Safety: This operation writes to a Granule outside the RMM Memory region, // thus not violating RMM's Memory Safety. // (ref. RMM Specification A2.2.4 Granule Wiping) unsafe { core::ptr::write_bytes(addr as *mut u8, 0x0, GRANULE_SIZE); } } #[cfg(any(kani, miri, test, fuzzing))] // DIFF: assertion is added to reduce the proof burden // `write_bytes()` uses a small count value fn zeroize(&mut self) { let addr = self.index_to_addr(); let g_start = unsafe { crate::granule::array::GRANULE_REGION.as_ptr() as usize }; let g_end = g_start + crate::granule::array::GRANULE_MEM_SIZE; assert!(addr >= g_start && addr < g_end); unsafe { core::ptr::write_bytes(addr as *mut u8, 0x0, 8); assert!(*(addr as *const u8) == 0); } } } pub struct Entry(Spinlock<Granule>); impl Entry { #[cfg(not(any(kani, miri, test, fuzzing)))] pub fn new() -> Self { Self(Spinlock::new(Granule::new())) } #[cfg(any(kani, miri, test, fuzzing))] // DIFF: assertion is added to reduce the proof burden pub fn new() -> Self { let granule = Granule::new(); assert!(granule.is_valid()); Self(Spinlock::new(granule)) } pub fn lock(&self) -> Result<SpinlockGuard<'_, Granule>, Error> { let granule = self.0.lock(); Ok(granule) } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/mm/page.rs
rmm/src/mm/page.rs
use super::page_table::{attr, entry::PTDesc}; use crate::config::PAGE_SIZE; use armv9a::bits_in_reg; use vmsa::page::PageSize; /// A 4 KiB page mapped in the L3Table. #[derive(Clone, Copy)] pub enum BasePageSize {} impl PageSize for BasePageSize { const SIZE: usize = PAGE_SIZE; const MAP_TABLE_LEVEL: usize = 3; const MAP_EXTRA_FLAG: u64 = bits_in_reg(PTDesc::TYPE, attr::page_type::TABLE_OR_PAGE) | bits_in_reg(PTDesc::SH, attr::shareable::INNER) | bits_in_reg(PTDesc::VALID, 1) | bits_in_reg(PTDesc::AF, 1); }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/mm/translation.rs
rmm/src/mm/translation.rs
use super::page_table::entry::Entry; use super::page_table::{attr, L1Table}; use crate::config::{PlatformMemoryLayout, PAGE_SIZE, RMM_STACK_GUARD_SIZE, RMM_STACK_SIZE}; use crate::mm::page::BasePageSize; use crate::mm::page_table::entry::PTDesc; use vmsa::address::{PhysAddr, VirtAddr}; use vmsa::page::Page; use vmsa::page_table::PageTable as RootPageTable; use vmsa::page_table::{DefaultMemAlloc, Level, PageTableMethods}; use armv9a::bits_in_reg; use core::ffi::c_void; use core::fmt; use lazy_static::lazy_static; use spin::mutex::Mutex; pub struct PageTable { page_table: &'static Mutex<Inner<'static>>, } impl PageTable { pub fn get_ref() -> Self { Self { page_table: &RMM_PAGE_TABLE, } } pub fn map(&self, addr: usize, secure: bool) -> bool { self.page_table.lock().set_pages_for_rmi(addr, secure) } pub fn unmap(&self, addr: usize) -> bool { self.page_table.lock().unset_pages_for_rmi(addr) } } lazy_static! { static ref RMM_PAGE_TABLE: Mutex<Inner<'static>> = Mutex::new(Inner::new()); } pub fn init_page_table(layout: PlatformMemoryLayout) { let mut page_table = RMM_PAGE_TABLE.lock(); page_table.fill(layout); } pub fn get_page_table() -> u64 { RMM_PAGE_TABLE.lock().get_base_address() as u64 } pub fn drop_page_table() { RMM_PAGE_TABLE.lock().root_pgtbl.drop(); } struct Inner<'a> { // We will set the translation granule with 4KB. // To reduce the level of page lookup, initial lookup will start from L1. root_pgtbl: &'a mut RootPageTable<VirtAddr, L1Table, Entry, { <L1Table as Level>::NUM_ENTRIES }>, dirty: bool, } impl Inner<'_> { pub fn new() -> Self { let root_pgtbl = RootPageTable::<VirtAddr, L1Table, Entry, { <L1Table as Level>::NUM_ENTRIES }>::new_in( &DefaultMemAlloc {}, ) .unwrap(); Self { root_pgtbl, dirty: false, } } fn fill(&mut self, layout: PlatformMemoryLayout) { if self.dirty { return; } let ro_flags = bits_in_reg(PTDesc::AP, attr::permission::RO); let rw_flags = bits_in_reg(PTDesc::AP, attr::permission::RW); let rmm_flags = bits_in_reg(PTDesc::INDX, attr::mair_idx::RMM_MEM); let device_flags = bits_in_reg(PTDesc::INDX, attr::mair_idx::DEVICE_MEM); let base_address = layout.rmm_base; let rw_start = layout.rw_start; let ro_size = rw_start - base_address; let rw_size = layout.rw_end - rw_start; let uart_phys = layout.uart_phys; let el3_shared_page = layout.el3_shared_buf; self.set_pages( VirtAddr::from(base_address), PhysAddr::from(base_address), ro_size as usize, ro_flags | rmm_flags, ); self.set_pages( VirtAddr::from(rw_start), PhysAddr::from(rw_start), rw_size as usize, rw_flags | rmm_flags, ); let per_cpu = RMM_STACK_GUARD_SIZE + RMM_STACK_SIZE; for i in 0..crate::config::NUM_OF_CPU { let stack_base = layout.stack_base + (per_cpu * i) as u64; self.set_pages( VirtAddr::from(stack_base), PhysAddr::from(stack_base), RMM_STACK_SIZE, rw_flags | rmm_flags, ); } // UART self.set_pages( VirtAddr::from(uart_phys), PhysAddr::from(uart_phys), PAGE_SIZE, rw_flags | device_flags, ); self.set_pages( VirtAddr::from(el3_shared_page), PhysAddr::from(el3_shared_page), PAGE_SIZE, rw_flags | rmm_flags, ); //TODO Set dirty only if pages are updated, not added self.dirty = true; } fn get_base_address(&self) -> *const c_void { self.root_pgtbl as *const _ as *const c_void } fn set_pages(&mut self, va: VirtAddr, phys: PhysAddr, size: usize, flags: u64) { let virtaddr = Page::<BasePageSize, VirtAddr>::range_with_size(va, size); let phyaddr = Page::<BasePageSize, PhysAddr>::range_with_size(phys, size); if self.root_pgtbl.set_pages(virtaddr, phyaddr, flags).is_err() { warn!("set_pages error"); } } fn unset_page(&mut self, addr: usize) { let va = VirtAddr::from(addr); let page = Page::<BasePageSize, VirtAddr>::including_address(va); self.root_pgtbl.unset_page(page); } fn set_pages_for_rmi(&mut self, addr: usize, secure: bool) -> bool { if addr == 0 { warn!("map address is empty"); return false; } let rw_flags = bits_in_reg(PTDesc::AP, attr::permission::RW); let memattr_flags = bits_in_reg(PTDesc::INDX, attr::mair_idx::RMM_MEM); let sh_flags = bits_in_reg(PTDesc::SH, attr::shareable::INNER); let secure_flags = bits_in_reg(PTDesc::NS, !secure as u64); let xn_flags = bits_in_reg(PTDesc::UXN, 1) | bits_in_reg(PTDesc::PXN, 1); let valid_flags = bits_in_reg(PTDesc::VALID, 1); let va = VirtAddr::from(addr); let phys = PhysAddr::from(addr); self.set_pages( va, phys, PAGE_SIZE, rw_flags | memattr_flags | secure_flags | sh_flags | xn_flags | valid_flags, ); true } fn unset_pages_for_rmi(&mut self, addr: usize) -> bool { if addr == 0 { warn!("map address is empty"); return false; } self.unset_page(addr); true } } impl fmt::Debug for Inner<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct(stringify!(Self)).finish() } } impl Drop for Inner<'_> { fn drop(&mut self) { info!("drop PageTable"); self.root_pgtbl.drop(); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/mm/mod.rs
rmm/src/mm/mod.rs
pub mod page; pub mod page_table; pub mod translation;
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/mm/page_table/attr.rs
rmm/src/mm/page_table/attr.rs
pub mod shareable { pub const NONE: u64 = 0b00; pub const OUTER: u64 = 0b10; pub const INNER: u64 = 0b11; } pub mod permission { pub const RW: u64 = 0b00; pub const RO: u64 = 0b10; } pub mod page_type { pub const BLOCK: u64 = 0b0; pub const TABLE_OR_PAGE: u64 = 0b1; } pub mod mair_idx { pub const RMM_MEM: u64 = 0b0; pub const DEVICE_MEM: u64 = 0b1; pub const RW_DATA: u64 = 0b0; }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/mm/page_table/mod.rs
rmm/src/mm/page_table/mod.rs
pub mod attr; pub mod entry; use self::entry::Entry; use crate::config::PAGE_SIZE; use vmsa::page_table::{HasSubtable, Level}; // Safety/TODO: // - As of now, concurrency safety for RTT and Realm page table is achieved by a big lock. // - If we want to use entry-level locking for a better efficiency, several pieces of codes in this file should be modified accordingly. /// The Level 0 Table pub enum L0Table {} impl Level for L0Table { const THIS_LEVEL: usize = 0; const TABLE_SIZE: usize = PAGE_SIZE; const TABLE_ALIGN: usize = PAGE_SIZE; const NUM_ENTRIES: usize = (Self::TABLE_SIZE / core::mem::size_of::<Entry>()); } impl HasSubtable for L0Table { type NextLevel = L1Table; } /// The Level 1 Table pub enum L1Table {} impl Level for L1Table { const THIS_LEVEL: usize = 1; const TABLE_SIZE: usize = PAGE_SIZE; const TABLE_ALIGN: usize = PAGE_SIZE; const NUM_ENTRIES: usize = (Self::TABLE_SIZE / core::mem::size_of::<Entry>()); } impl HasSubtable for L1Table { type NextLevel = L2Table; } /// The Level 2 Table pub enum L2Table {} impl Level for L2Table { const THIS_LEVEL: usize = 2; const TABLE_SIZE: usize = PAGE_SIZE; const TABLE_ALIGN: usize = PAGE_SIZE; const NUM_ENTRIES: usize = (Self::TABLE_SIZE / core::mem::size_of::<Entry>()); } impl HasSubtable for L2Table { type NextLevel = L3Table; } /// The Level 3 Table (Doesn't have Subtable!) pub enum L3Table {} impl Level for L3Table { const THIS_LEVEL: usize = 3; const TABLE_SIZE: usize = PAGE_SIZE; const TABLE_ALIGN: usize = PAGE_SIZE; const NUM_ENTRIES: usize = (Self::TABLE_SIZE / core::mem::size_of::<Entry>()); }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/mm/page_table/entry.rs
rmm/src/mm/page_table/entry.rs
use super::attr; use attr::mair_idx; use vmsa::address::PhysAddr; use vmsa::error::Error; use vmsa::page_table::{self, Level}; use vmsa::RawGPA; use armv9a::{define_bitfield, define_bits, define_mask}; define_bits!( PTDesc, Reserved[58 - 55], UXN[54 - 54], PXN[53 - 53], ADDR_BLK_L1[47 - 30], // block descriptor; level 1 ADDR_BLK_L2[47 - 21], // block descriptor; level 2 ADDR_TBL_OR_PAGE[47 - 12], // table descriptor(level 0-2) || page descriptor(level3) AF[10 - 10], // access flag SH[9 - 8], // pte_shareable AP[7 - 6], // pte_access_perm NS[5 - 5], // security bit INDX[4 - 2], // the index into the Memory Attribute Indirection Register MAIR_ELn TYPE[1 - 1], VALID[0 - 0] ); #[derive(Clone, Copy)] pub struct Entry(PTDesc); impl page_table::Entry for Entry { type Inner = PTDesc; fn new() -> Self { Self(PTDesc::new(0)) } fn is_valid(&self) -> bool { self.0.get_masked_value(PTDesc::VALID) != 0 } fn clear(&mut self) { self.0 = PTDesc::new(0); } fn pte(&self) -> u64 { self.0.get() } fn mut_pte(&mut self) -> &mut Self::Inner { self.0.get_mut() } fn address(&self, level: usize) -> Option<PhysAddr> { match self.is_valid() { true => match self.0.get_masked_value(PTDesc::TYPE) { attr::page_type::TABLE_OR_PAGE => { Some(PhysAddr::from(self.0.get_masked(PTDesc::ADDR_TBL_OR_PAGE))) } attr::page_type::BLOCK => match level { 1 => Some(PhysAddr::from(self.0.get_masked(PTDesc::ADDR_BLK_L1))), 2 => Some(PhysAddr::from(self.0.get_masked(PTDesc::ADDR_BLK_L2))), _ => None, }, _ => None, }, false => None, } } fn set(&mut self, addr: PhysAddr, flags: u64) -> Result<(), Error> { self.0.set(addr.as_u64() | flags); #[cfg(not(any(miri, test, fuzzing)))] unsafe { core::arch::asm!( "dsb ishst", "dc civac, {}", "dsb ish", "isb", in(reg) &self.0 as *const _ as usize, ); } Ok(()) } fn point_to_subtable(&mut self, _index: usize, addr: PhysAddr) -> Result<(), Error> { let mut flags = PTDesc::new(0); flags .set_masked_value(PTDesc::INDX, mair_idx::RMM_MEM) .set_masked_value(PTDesc::TYPE, attr::page_type::TABLE_OR_PAGE) .set_masked_value(PTDesc::SH, attr::shareable::INNER) .set_bits(PTDesc::AF | PTDesc::VALID); self.set(addr, flags.get()) } fn index<L: Level>(addr: usize) -> usize { match L::THIS_LEVEL { 0 => RawGPA::from(addr).get_masked_value(RawGPA::L0Index) as usize, 1 => RawGPA::from(addr).get_masked_value(RawGPA::L1Index) as usize, 2 => RawGPA::from(addr).get_masked_value(RawGPA::L2Index) as usize, 3 => RawGPA::from(addr).get_masked_value(RawGPA::L3Index) as usize, _ => panic!(), } } fn points_to_table_or_page(&self) -> bool { match self.is_valid() { true => match self.0.get_masked_value(PTDesc::TYPE) { attr::page_type::TABLE_OR_PAGE => true, _ => false, }, false => false, } } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/event/rsihandle.rs
rmm/src/event/rsihandle.rs
extern crate alloc; use crate::rec::Rec; use crate::rmi::rec::run::Run; use crate::rsi; use crate::rsi::psci; use crate::Monitor; // TODO: Change this into rsi::error::Error use crate::rmi::error::Error; use alloc::boxed::Box; use alloc::collections::btree_map::BTreeMap; pub type Handler = Box<dyn Fn(&[usize], &mut [usize], &Monitor, &mut Rec<'_>, &mut Run) -> Result<(), Error>>; pub struct RsiHandle { pub on_event: BTreeMap<usize, Handler>, } impl RsiHandle { pub const RET_SUCCESS: usize = 0x0000; pub const RET_FAIL: usize = 0x0001; pub const NOT_SUPPORTED: usize = !0; pub fn new() -> Self { let mut rsi = Self { on_event: BTreeMap::new(), }; rsi.set_event_handlers(); rsi } fn set_event_handlers(&mut self) { rsi::set_event_handler(self); psci::set_event_handler(self); } pub fn add_event_handler(&mut self, code: usize, handler: Handler) { self.on_event.insert(code, handler); } } unsafe impl Send for RsiHandle {} unsafe impl Sync for RsiHandle {}
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/event/realmexit.rs
rmm/src/event/realmexit.rs
const REC_EXIT_REASON_MASK: usize = 15; // 0b1111 const EXIT_SYNC_TYPE_SHIFT: usize = 4; const EXIT_SYNC_TYPE_MASK: usize = 15 << EXIT_SYNC_TYPE_SHIFT; // 0b1111_0000 /// Handles 'RET_TO_RMM' cases from trap::handle_lower_exception() /// /// It can't cover all of RmiRecExitReason types. /// Because the following types of RmiRecExitReason /// are set to ExitReason using RSI: /// - RMI_EXIT_RIPAS_CHANGE /// - RMI_EXIT_HOST_CALL #[derive(Debug)] #[repr(usize)] pub enum RecExitReason { Sync(ExitSyncType), IRQ = 1, FIQ = 2, PSCI = 3, SError = 4, Undefined = REC_EXIT_REASON_MASK, // fixed, 0b1111 } impl Into<u64> for RecExitReason { fn into(self) -> u64 { match self { RecExitReason::Sync(exit_sync_type) => exit_sync_type.into(), RecExitReason::IRQ => 1, RecExitReason::FIQ => 2, RecExitReason::PSCI => 3, RecExitReason::SError => 4, RecExitReason::Undefined => 7, } } } impl From<usize> for RecExitReason { fn from(num: usize) -> Self { match num & REC_EXIT_REASON_MASK { 0 => RecExitReason::Sync(ExitSyncType::from(num)), 1 => RecExitReason::IRQ, 2 => RecExitReason::FIQ, 3 => RecExitReason::PSCI, 4 => RecExitReason::SError, _ => RecExitReason::Undefined, } } } /// Fault Status Code only for the 'RecExitReason::Sync' /// it's a different from trap::Syndrome #[derive(Debug, PartialEq)] #[repr(usize)] pub enum ExitSyncType { RSI = 1 << EXIT_SYNC_TYPE_SHIFT, DataAbort = 2 << EXIT_SYNC_TYPE_SHIFT, InstAbort = 3 << EXIT_SYNC_TYPE_SHIFT, WFx = 4 << EXIT_SYNC_TYPE_SHIFT, Undefined = EXIT_SYNC_TYPE_MASK, // fixed, 0b1111_0000 } impl Into<u64> for ExitSyncType { fn into(self) -> u64 { self as u64 } } impl From<usize> for ExitSyncType { fn from(num: usize) -> Self { let masked_val = (num & EXIT_SYNC_TYPE_MASK) >> EXIT_SYNC_TYPE_SHIFT; match masked_val { 1 => ExitSyncType::RSI, 2 => ExitSyncType::DataAbort, 3 => ExitSyncType::InstAbort, 4 => ExitSyncType::WFx, _ => ExitSyncType::Undefined, } } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/event/rmihandle.rs
rmm/src/event/rmihandle.rs
extern crate alloc; use crate::rmi; use crate::rmi::error::Error; use crate::Monitor; use alloc::boxed::Box; use alloc::collections::btree_map::BTreeMap; pub type Handler = Box<dyn Fn(&[usize], &mut [usize], &Monitor) -> Result<(), Error>>; pub struct RmiHandle { pub on_event: BTreeMap<usize, Handler>, } impl RmiHandle { pub fn new() -> Self { let mut rmi = Self { on_event: BTreeMap::new(), }; rmi.add_event_handlers(); rmi } #[cfg(not(kani))] pub fn add_event_handlers(&mut self) { rmi::features::set_event_handler(self); rmi::gpt::set_event_handler(self); rmi::realm::set_event_handler(self); rmi::rec::set_event_handler(self); rmi::rtt::set_event_handler(self); rmi::version::set_event_handler(self); } #[cfg(kani)] fn add_event_handlers(&mut self) { #[cfg(feature = "mc_rmi_features")] rmi::features::set_event_handler(self); #[cfg(any( feature = "mc_rmi_granule_delegate", feature = "mc_rmi_granule_undelegate" ))] rmi::gpt::set_event_handler(self); #[cfg(any( feature = "mc_rmi_realm_activate", feature = "mc_rmi_realm_destroy", feature = "mc_rmi_rec_aux_count" ))] rmi::realm::set_event_handler(self); #[cfg(feature = "mc_rmi_rec_destroy")] rmi::rec::set_event_handler(self); #[cfg(feature = "mc_rmi_version")] rmi::version::set_event_handler(self); } pub fn add_event_handler(&mut self, code: usize, handler: Handler) { self.on_event.insert(code, handler); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/event/mainloop.rs
rmm/src/event/mainloop.rs
use super::Context; use crate::asm::smc; use crate::rmi; pub struct Mainloop; impl Mainloop { pub fn new() -> Self { Self } #[cfg(not(kani))] pub fn dispatch(&self, ctx: Context) -> Context { let ret = smc(ctx.cmd(), ctx.arg_slice()); let cmd = ret[0]; rmi::constraint::validate(cmd, &ret[1..]) } #[cfg(kani)] // DIFF: `symbolic` parameter is added to pass symbolic input pub fn dispatch(&self, ctx: Context, symbolic: [usize; 8]) -> Context { let _ret = smc(ctx.cmd(), ctx.arg_slice()); let ret = symbolic; let cmd = ret[0]; rmi::constraint::validate(cmd, &ret[1..]) } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/event/mod.rs
rmm/src/event/mod.rs
pub mod mainloop; pub mod realmexit; pub mod rmihandle; pub mod rsihandle; pub use crate::rmi::error::Error; pub use crate::rsi; pub use mainloop::Mainloop; pub use rmihandle::RmiHandle; pub use rsihandle::RsiHandle; extern crate alloc; use alloc::vec::Vec; #[macro_export] macro_rules! listen { ($eventloop:expr, $code:expr, $handler:expr) => {{ $eventloop.add_event_handler($code.into(), alloc::boxed::Box::new($handler)) }}; } pub type Command = usize; #[derive(Clone)] pub struct Context { pub cmd: Command, pub arg: Vec<usize>, pub ret: Vec<usize>, pub sve_hint: bool, pub x4: u64, } impl Context { pub fn new(cmd: Command) -> Context { Context { cmd, arg: Vec::new(), ret: Vec::new(), sve_hint: false, x4: 0, } } pub fn init_arg(&mut self, arg: &[usize]) { self.arg.clear(); self.arg.extend_from_slice(arg); } pub fn init_ret(&mut self, ret: &[usize]) { self.ret.clear(); self.ret.extend_from_slice(ret); } pub fn resize_ret(&mut self, new_len: usize) { self.ret.clear(); self.ret.resize(new_len, 0); } pub fn arg_slice(&self) -> &[usize] { &self.arg[..] } pub fn ret_slice(&self) -> &[usize] { &self.ret[..] } pub fn cmd(&self) -> Command { self.cmd } pub fn do_rsi<F>(&mut self, mut handler: F) where F: FnMut(&[usize], &mut [usize]) -> Result<(), Error>, { self.ret[0] = rsi::SUCCESS; #[cfg(feature = "stat")] { trace!("let's get STATS.lock() with cmd {}", rsi::to_str(self.cmd)); crate::stat::STATS.lock().measure(self.cmd, || { if let Err(code) = handler(&self.arg[..], &mut self.ret[..]) { error!("rsi handler returns error:{:?}", code); self.ret[0] = code.into(); } }); } #[cfg(not(feature = "stat"))] { if let Err(code) = handler(&self.arg[..], &mut self.ret[..]) { error!("rsi handler returns error:{:?}", code); self.ret[0] = code.into(); } } trace!( "RSI: {0: <20} {1:X?} > {2:X?}", rsi::to_str(self.cmd), &self.arg, &self.ret ); self.arg.clear(); self.arg.extend_from_slice(&self.ret[..]); } } impl Default for Context { fn default() -> Context { Context::new(0) } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/gpt.rs
rmm/src/rmi/gpt.rs
use crate::asm::{smc, SMC_SUCCESS}; use crate::event::RmiHandle; use crate::granule::{set_granule, GranuleState}; use crate::listen; use crate::rmi; use crate::rmi::error::Error; #[cfg(not(feature = "gst_page_table"))] use crate::{get_granule, get_granule_if}; #[cfg(feature = "gst_page_table")] use crate::{get_granule, get_granule_if, set_state_and_get_granule}; #[cfg(feature = "gst_page_table")] use vmsa::error::Error as MmError; extern crate alloc; // defined in trusted-firmware-a/include/services/rmmd_svc.h pub const MARK_REALM: usize = 0xc400_01b0; pub const MARK_NONSECURE: usize = 0xc400_01b1; pub fn set_event_handler(rmi: &mut RmiHandle) { #[cfg(any(not(kani), feature = "mc_rmi_granule_delegate"))] listen!(rmi, rmi::GRANULE_DELEGATE, |arg, _, rmm| { let addr = arg[0]; #[cfg(feature = "gst_page_table")] let mut granule = match get_granule_if!(addr, GranuleState::Undelegated) { Err(MmError::MmNoEntry) => set_state_and_get_granule!(addr, GranuleState::Undelegated), other => other, }?; #[cfg(not(feature = "gst_page_table"))] let mut granule = get_granule_if!(addr, GranuleState::Undelegated)?; // Avoid deadlock in get_granule() in smc() on {miri, test} mode #[cfg(any(miri, test, fuzzing))] core::mem::drop(granule); if smc(MARK_REALM, &[addr])[0] != SMC_SUCCESS { return Err(Error::RmiErrorInput); } #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.map(addr, true); #[cfg(any(miri, test, fuzzing))] let mut granule = get_granule_if!(addr, GranuleState::Undelegated)?; set_granule(&mut granule, GranuleState::Delegated).inspect_err(|_| { #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.unmap(addr); })?; #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.unmap(addr); Ok(()) }); #[cfg(any(not(kani), feature = "mc_rmi_granule_undelegate"))] listen!(rmi, rmi::GRANULE_UNDELEGATE, |arg, _, rmm| { let addr = arg[0]; let mut granule = get_granule_if!(addr, GranuleState::Delegated)?; // Avoid deadlock in get_granule() in smc() on {miri, test} mode #[cfg(any(miri, test, fuzzing))] core::mem::drop(granule); if smc(MARK_NONSECURE, &[addr])[0] != SMC_SUCCESS { panic!( "A delegated granule should only be undelegated on request from RMM. {:X}", addr ); } #[cfg(any(miri, test, fuzzing))] let mut granule = get_granule_if!(addr, GranuleState::Delegated)?; #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.map(addr, false); set_granule(&mut granule, GranuleState::Undelegated).inspect_err(|_| { #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.unmap(addr); })?; #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.unmap(addr); Ok(()) }); } #[cfg(test)] mod test { use crate::rmi::gpt::GranuleState; use crate::rmi::{ERROR_INPUT, GRANULE_DELEGATE, GRANULE_UNDELEGATE, SUCCESS}; use crate::test_utils::*; use crate::{get_granule, get_granule_if}; use alloc::vec; #[test] fn rmi_granule_delegate_positive() { let mocking_addr = mock::host::alloc_granule(IDX_RD); let ret = rmi::<GRANULE_DELEGATE>(&[mocking_addr]); assert_eq!(ret[0], SUCCESS); assert!(get_granule_if!(mocking_addr, GranuleState::Delegated).is_ok()); let ret = rmi::<GRANULE_UNDELEGATE>(&[mocking_addr]); assert_eq!(ret[0], SUCCESS); assert!(get_granule_if!(mocking_addr, GranuleState::Undelegated).is_ok()); miri_teardown(); } // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_granule_delegate /* Check 1 : gran_align; intent id : 0x0 addr : 0x88300001 Check 2 : gran_bound; intent id : 0x1 addr : 0x1C0B0000 Check 3 : gran_bound; intent id : 0x2 addr : 0x1000000001000 Check 4 : gran_state; intent id : 0x3 addr : 0x8830C000 Check 5 : gran_state; intent id : 0x4 addr : 0x88315000 Check 6 : gran_state; intent id : 0x5 addr : 0x88351000 Check 7 : gran_state; intent id : 0x6 addr : 0x88306000 Check 8 : gran_state; intent id : 0x7 addr : 0x88303000 Check 9 : gran_gpt; intent id : 0x8 addr : 0x88357000 Check 10 : gran_gpt; intent id : 0x9 addr : 0x6000000 */ #[test] fn rmi_granule_delegate_negative() { let test_data = vec![ (0x88300001, ERROR_INPUT), (0x1C0B0000, ERROR_INPUT), (0x1000000001000, ERROR_INPUT), // TODO: Cover all test data ]; for (input, output) in test_data { let ret = rmi::<GRANULE_DELEGATE>(&[input]); assert_eq!(output, ret[0]); } } // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_granule_undelegate /* Check 1 : gran_align; intent id : 0x0 addr : 0x88300001 Check 2 : gran_bound; intent id : 0x1 addr : 0x1C0B0000 Check 3 : gran_bound; intent id : 0x2 addr : 0x1000000001000 Check 4 : gran_state; intent id : 0x3 addr : 0x8830C000 Check 5 : gran_state; intent id : 0x4 addr : 0x88315000 Check 6 : gran_state; intent id : 0x5 addr : 0x88351000 Check 7 : gran_state; intent id : 0x6 addr : 0x88306000 Check 8 : gran_state; intent id : 0x7 addr : 0x88303000 */ #[test] fn rmi_granule_undelegate() { let test_data = vec![ (0x88300001, ERROR_INPUT), (0x1C0B0000, ERROR_INPUT), (0x1000000001000, ERROR_INPUT), (0x8830C000, ERROR_INPUT), // TODO: Cover all test data ]; for (input, output) in test_data { let ret = rmi::<GRANULE_UNDELEGATE>(&[input]); assert_eq!(output, ret[0]); } miri_teardown(); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/rtt.rs
rmm/src/rmi/rtt.rs
extern crate alloc; use crate::event::RmiHandle; use crate::granule::{ is_granule_aligned, is_not_in_realm, set_granule, GranuleState, GRANULE_SIZE, }; use crate::host; use crate::host::DataPage; use crate::listen; use crate::measurement::HashContext; use crate::realm::mm::rtt; use crate::realm::mm::rtt::{RTT_MIN_BLOCK_LEVEL, RTT_PAGE_LEVEL}; use crate::realm::mm::stage2_tte::{level_mask, S2TTE}; use crate::realm::rd::{Rd, State}; use crate::rec::Rec; use crate::rmi; use crate::rmi::error::Error; #[cfg(not(feature = "gst_page_table"))] use crate::{get_granule, get_granule_if}; #[cfg(feature = "gst_page_table")] use crate::{get_granule, get_granule_if, set_state_and_get_granule}; fn is_valid_rtt_cmd(rd: &Rd, ipa: usize, level: usize) -> bool { if level > RTT_PAGE_LEVEL { return false; } if ipa >= rd.ipa_size() { return false; } let mask = level_mask(level).unwrap_or(0); if ipa & mask as usize != ipa { return false; } true } pub fn set_event_handler(rmi: &mut RmiHandle) { listen!(rmi, rmi::RTT_CREATE, |arg, _ret, rmm| { let rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let rtt_addr = arg[1]; let rd = rd_granule.content::<Rd>()?; let ipa = arg[2]; let level = arg[3]; let min_level = rd.s2_starting_level() as usize + 1; if (level < min_level) || (level > RTT_PAGE_LEVEL) || !is_valid_rtt_cmd(&rd, ipa, level - 1) { return Err(Error::RmiErrorInput); } if rtt_addr == arg[0] { return Err(Error::RmiErrorInput); } let mut rtt_granule = get_granule_if!(rtt_addr, GranuleState::Delegated)?; // The below is added to avoid a fault regarding the RTT entry // during the `create_pgtbl_at()` in `rtt::create()`. #[cfg(not(kani))] rmm.page_table.map(rtt_addr, true); rtt::create(&rd, rtt_addr, ipa, level)?; set_granule(&mut rtt_granule, GranuleState::RTT)?; Ok(()) }); listen!(rmi, rmi::RTT_DESTROY, |arg, ret, _rmm| { let rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; let ipa = arg[1]; let level = arg[2]; let min_level = rd.s2_starting_level() as usize + 1; if (level < min_level) || (level > RTT_PAGE_LEVEL) || !is_valid_rtt_cmd(&rd, ipa, level - 1) { return Err(Error::RmiErrorInput); } let (ipa, walk_top) = rtt::destroy(&rd, ipa, level, |t| { ret[2] = t; })?; ret[1] = ipa; ret[2] = walk_top; Ok(()) }); listen!(rmi, rmi::RTT_INIT_RIPAS, |arg, ret, _rmm| { let mut rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let mut rd = rd_granule.content_mut::<Rd>()?; let base = arg[1]; let top = arg[2]; if rd.state() != State::New { return Err(Error::RmiErrorRealm(0)); } if top <= base { return Err(Error::RmiErrorInput); } if !is_valid_rtt_cmd(&rd, base, RTT_PAGE_LEVEL) || !is_valid_rtt_cmd(&rd, top, RTT_PAGE_LEVEL) || !rd.addr_in_par(base) || !rd.addr_in_par(top - GRANULE_SIZE) { return Err(Error::RmiErrorInput); } let out_top = rtt::init_ripas(&mut rd, base, top)?; ret[1] = out_top; //This is walk_top Ok(()) }); listen!(rmi, rmi::RTT_SET_RIPAS, |arg, ret, _rmm| { let base = arg[2]; let top = arg[3]; if arg[0] == arg[1] { warn!("Granules of RD and REC shouldn't be identical"); return Err(Error::RmiErrorInput); } let rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; let mut rec_granule = get_granule_if!(arg[1], GranuleState::Rec)?; let mut rec = rec_granule.content_mut::<Rec<'_>>()?; if rec.realmid()? != rd.id() { warn!("RD:{:X} doesn't own REC:{:X}", arg[0], arg[1]); return Err(Error::RmiErrorRec); } if rec.ripas_addr() != base as u64 || rec.ripas_end() < top as u64 { return Err(Error::RmiErrorInput); } if !is_granule_aligned(base) || !is_granule_aligned(top) || !rd.addr_in_par(base) || top.checked_sub(GRANULE_SIZE).is_none() || !rd.addr_in_par(top - GRANULE_SIZE) { return Err(Error::RmiErrorInput); } let out_top = rtt::set_ripas(&rd, base, top, rec.ripas_state(), rec.ripas_flags())?; ret[1] = out_top; rec.set_ripas_addr(out_top as u64); Ok(()) }); listen!(rmi, rmi::RTT_READ_ENTRY, |arg, ret, _rmm| { let rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; let ipa = arg[1]; let level = arg[2]; if !is_valid_rtt_cmd(&rd, ipa, level) { return Err(Error::RmiErrorInput); } let res = rtt::read_entry(&rd, ipa, level)?; ret[1..5].copy_from_slice(&res[0..4]); Ok(()) }); listen!(rmi, rmi::DATA_CREATE, |arg, _ret, rmm| { // target_pa: location where realm data is created. let rd = arg[0]; let target_pa = arg[1]; let ipa = arg[2]; let src_pa = arg[3]; let flags = arg[4]; if target_pa == rd || target_pa == src_pa || rd == src_pa { return Err(Error::RmiErrorInput); } // rd granule lock let mut rd_granule = get_granule_if!(rd, GranuleState::RD)?; let mut rd = rd_granule.content_mut::<Rd>()?; // Make sure DATA_CREATE is only processed // when the realm is in its New state. if !rd.at_state(State::New) { return Err(Error::RmiErrorRealm(0)); } validate_ipa(&rd, ipa)?; if !is_not_in_realm(src_pa) { return Err(Error::RmiErrorInput); }; // data granule lock for the target page let mut target_page_granule = get_granule_if!(target_pa, GranuleState::Delegated)?; let mut target_page = target_page_granule.content_mut::<DataPage>()?; #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.map(target_pa, true); // copy src to target #[cfg(not(kani))] rmm.page_table.map(src_pa, false); host::copy_to_obj::<DataPage>(src_pa, &mut target_page).ok_or(Error::RmiErrorInput)?; #[cfg(not(kani))] rmm.page_table.unmap(src_pa); // map ipa to taget_pa in S2 table rtt::data_create(&rd, ipa, target_pa, false)?; #[cfg(not(kani))] // `rsi` is currently not reachable in model checking harnesses HashContext::new(&mut rd)?.measure_data_granule(&target_page, ipa, flags)?; set_granule(&mut target_page_granule, GranuleState::Data)?; Ok(()) }); listen!(rmi, rmi::DATA_CREATE_UNKNOWN, |arg, _ret, rmm| { // rd granule lock let rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; // target_phys: location where realm data is created. let target_pa = arg[1]; let ipa = arg[2]; if target_pa == arg[0] { return Err(Error::RmiErrorInput); } validate_ipa(&rd, ipa)?; // 0. Make sure granule state can make a transition to DATA // data granule lock for the target page let mut target_page_granule = get_granule_if!(target_pa, GranuleState::Delegated)?; #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.map(target_pa, true); // 1. map ipa to target_pa in S2 table rtt::data_create(&rd, ipa, target_pa, true)?; // TODO: 2. perform measure // L0czek - not needed here see: tf-rmm/runtime/rmi/rtt.c:883 set_granule(&mut target_page_granule, GranuleState::Data)?; Ok(()) }); listen!(rmi, rmi::DATA_DESTROY, |arg, ret, _rmm| { // rd granule lock let rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; let ipa = arg[1]; if !rd.addr_in_par(ipa) || !is_valid_rtt_cmd(&rd, ipa, RTT_PAGE_LEVEL) { return Err(Error::RmiErrorInput); } let (pa, top) = rtt::data_destroy(&rd, ipa, |t| { ret[2] = t; })?; // data granule lock and change state #[cfg(feature = "gst_page_table")] set_state_and_get_granule!(pa, GranuleState::Delegated)?; #[cfg(not(feature = "gst_page_table"))] { let mut granule = get_granule!(pa)?; set_granule(&mut granule, GranuleState::Delegated)?; } ret[1] = pa; ret[2] = top; Ok(()) }); // Map an unprotected IPA to a non-secure PA. listen!(rmi, rmi::RTT_MAP_UNPROTECTED, |arg, _ret, _rmm| { let ipa = arg[1]; let level = arg[2]; let host_s2tte = arg[3]; let s2tte = S2TTE::from(host_s2tte); if !s2tte.is_host_ns_valid(level) { return Err(Error::RmiErrorInput); } // rd granule lock let rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; if (level < rd.s2_starting_level() as usize) || (level < RTT_MIN_BLOCK_LEVEL) || (level > RTT_PAGE_LEVEL) || !is_valid_rtt_cmd(&rd, ipa, level) { return Err(Error::RmiErrorInput); } rtt::map_unprotected(&rd, ipa, level, host_s2tte)?; Ok(()) }); // Unmap a non-secure PA at an unprotected IPA listen!(rmi, rmi::RTT_UNMAP_UNPROTECTED, |arg, ret, _rmm| { let rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; let ipa = arg[1]; let level = arg[2]; if (level < rd.s2_starting_level() as usize) || (level < RTT_MIN_BLOCK_LEVEL) || (level > RTT_PAGE_LEVEL) || !is_valid_rtt_cmd(&rd, ipa, level) { return Err(Error::RmiErrorInput); } let top = rtt::unmap_unprotected(&rd, ipa, level, |t| { ret[1] = t; })?; ret[1] = top; Ok(()) }); // Destroy a homogeneous RTT and map as a bigger block at its parent RTT listen!(rmi, rmi::RTT_FOLD, |arg, ret, _rmm| { let rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; let ipa = arg[1]; let level = arg[2]; let min_level = rd.s2_starting_level() as usize + 1; if (level < min_level) || (level > RTT_PAGE_LEVEL) || !is_valid_rtt_cmd(&rd, ipa, level - 1) { return Err(Error::RmiErrorInput); } let rtt = rtt::fold(&rd, ipa, level)?; ret[1] = rtt; Ok(()) }); } pub fn validate_ipa(rd: &Rd, ipa: usize) -> Result<(), Error> { if !is_granule_aligned(ipa) { error!("ipa: {:x} is not aligned with {:x}", ipa, GRANULE_SIZE); return Err(Error::RmiErrorInput); } if !rd.addr_in_par(ipa) { error!( "ipa: {:x} is not in protected ipa range {:x}", ipa, rd.par_size() ); return Err(Error::RmiErrorInput); } if !is_valid_rtt_cmd(rd, ipa, RTT_PAGE_LEVEL) { return Err(Error::RmiErrorInput); } Ok(()) } #[cfg(test)] mod test { use crate::granule::GRANULE_SIZE; use crate::realm::rd::{Rd, State}; use crate::rmi::*; use crate::test_utils::{mock, *}; use alloc::vec; // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_rtt_create // Covered RMIs: RTT_CREATE, RTT_DESTROY, RTT_READ_ENTRY #[test] fn rmi_rtt_create_positive() { let rd = realm_create(); let (rtt1, rtt2, rtt3, rtt4) = ( mock::host::alloc_granule(IDX_RTT_LEVEL1), mock::host::alloc_granule(IDX_RTT_LEVEL2), mock::host::alloc_granule(IDX_RTT_LEVEL3), mock::host::alloc_granule(IDX_RTT_OTHER), ); for rtt in &[rtt1, rtt2, rtt3, rtt4] { let ret = rmi::<GRANULE_DELEGATE>(&[*rtt]); assert_eq!(ret[0], SUCCESS); } let test_data = vec![ (rtt1, 0x0, 0x1), (rtt2, 0x0, 0x2), (rtt3, 0x0, 0x3), (rtt4, 0x40000000, 0x2), ]; unsafe { let rd_obj = &*(rd as *const Rd); assert!(rd_obj.at_state(State::New)); }; for (rtt, ipa, level) in &test_data { let ret = rmi::<RTT_CREATE>(&[rd, *rtt, *ipa, *level]); assert_eq!(ret[0], SUCCESS); } let (rtt4_ipa, rtt4_level) = (test_data[3].1, test_data[3].2); let ret = rmi::<RTT_READ_ENTRY>(&[rd, rtt4_ipa, rtt4_level - 1]); assert_eq!(ret[0], SUCCESS); let (state, desc) = (ret[2], ret[3]); const RMI_TABLE: usize = 2; assert_eq!(state, RMI_TABLE); assert_eq!(desc, rtt4); for (_, ipa, level) in test_data.iter().rev() { let ret = rmi::<RTT_DESTROY>(&[rd, *ipa, *level]); assert_eq!(ret[0], SUCCESS); } for rtt in &[rtt1, rtt2, rtt3, rtt4] { let ret = rmi::<GRANULE_UNDELEGATE>(&[*rtt]); assert_eq!(ret[0], SUCCESS); } realm_destroy(rd); miri_teardown(); } // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_rtt_init_ripas // Covered RMIs: RTT_INIT_RIPAS, RTT_READ_ENTRY #[test] fn rmi_rtt_init_ripas_positive() { let rd = realm_create(); let ipa = 0; mock::host::map(rd, ipa); let base = (ipa / L3_SIZE) * L3_SIZE; let top = base + L3_SIZE; let ret = rmi::<RTT_INIT_RIPAS>(&[rd, base, top]); assert_eq!(ret[0], SUCCESS); assert_eq!(ret[1], top); let ret = rmi::<RTT_READ_ENTRY>(&[rd, ipa, MAP_LEVEL]); assert_eq!(ret[0], SUCCESS); let (level, ripas) = (ret[1], ret[4]); const RMI_RAM: usize = 1; assert_eq!(level, MAP_LEVEL); assert_eq!(ripas, RMI_RAM); mock::host::unmap(rd, ipa, false); realm_destroy(rd); miri_teardown(); } // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_rtt_map_unprotected // Covered RMIs: RTT_MAP_UNPROTECTED, RTT_UNMAP_UNPROTECTED #[test] fn rmi_rtt_map_unprotected_positive() { let rd = realm_create(); const IPA_ADDR_UNPROTECTED_UNASSIGNED: usize = (1 << (IPA_WIDTH - 1)) + L3_SIZE; mock::host::map(rd, IPA_ADDR_UNPROTECTED_UNASSIGNED); let ipa = IPA_ADDR_UNPROTECTED_UNASSIGNED; let level = MAP_LEVEL; let ns = mock::host::alloc_granule(IDX_NS_DESC); let desc = ns | ATTR_NORMAL_WB_WA_RA | ATTR_STAGE2_AP_RW; let ret = rmi::<RTT_MAP_UNPROTECTED>(&[rd, ipa, level, desc]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<RTT_READ_ENTRY>(&[rd, ipa, level]); assert_eq!(ret[0], SUCCESS); let (_level, state, out_desc, _ripas) = (ret[1], ret[2], ret[3], ret[4]); const RMI_ASSIGNED: usize = 1; assert_eq!(state, RMI_ASSIGNED); assert_eq!(out_desc, desc); let ret = rmi::<RTT_UNMAP_UNPROTECTED>(&[rd, ipa, level]); assert_eq!(ret[0], SUCCESS); mock::host::unmap(rd, ipa, false); realm_destroy(rd); miri_teardown(); } // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_data_destroy // Covered RMIs: DATA_CREATE, DATA_CREATE_UNKNOWN, DATA_DESTROY #[test] fn rmi_data_create_positive() { let rd = realm_create(); const IPA_ADDR_ASSIGNED: usize = GRANULE_SIZE; const IPA_ADDR_DATA: usize = GRANULE_SIZE * 3; const IPA_ADDR_PROTECTED_ASSIGNED_EMPTY: usize = GRANULE_SIZE * 4; const RMI_UNASSIGNED: usize = 0; const RMI_DESTROYED: usize = 2; const RMI_EMPTY: usize = 0; data_create(rd, IPA_ADDR_ASSIGNED, IDX_DATA1, IDX_SRC1); data_create(rd, IPA_ADDR_DATA, IDX_DATA2, IDX_SRC2); let ipa = IPA_ADDR_ASSIGNED; let ret = rmi::<DATA_DESTROY>(&[rd, ipa]); assert_eq!(ret[0], SUCCESS); let (data, top) = (ret[1], ret[2]); assert_eq!(data, granule_addr(IDX_DATA1)); assert_eq!(top, IPA_ADDR_DATA); // Check for RIPAS and HIPAS from RIPAS = RAM let ret = rmi::<RTT_READ_ENTRY>(&[rd, ipa, MAP_LEVEL]); assert_eq!(ret[0], SUCCESS); let (_level, state, _desc, ripas) = (ret[1], ret[2], ret[3], ret[4]); assert_eq!(state, RMI_UNASSIGNED); assert_eq!(ripas, RMI_DESTROYED); // Check for RIPAS transition from ASSIGNED,DESTROYED let data = mock::host::alloc_granule(IDX_DATA3); let ret = rmi::<GRANULE_DELEGATE>(&[data]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<DATA_CREATE_UNKNOWN>(&[rd, data, ipa]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<DATA_DESTROY>(&[rd, ipa]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<RTT_READ_ENTRY>(&[rd, ipa, MAP_LEVEL]); assert_eq!(ret[0], SUCCESS); let (_level, state, _desc, ripas) = (ret[1], ret[2], ret[3], ret[4]); assert_eq!(state, RMI_UNASSIGNED); assert_eq!(ripas, RMI_DESTROYED); // Check for RIPAS and HIPAS from RIPAS = EMPTY let ipa = IPA_ADDR_PROTECTED_ASSIGNED_EMPTY; let ret = rmi::<RTT_READ_ENTRY>(&[rd, ipa, MAP_LEVEL]); assert_eq!(ret[0], SUCCESS); mock::host::map(rd, ipa); let data = mock::host::alloc_granule(IDX_DATA4); let ret = rmi::<GRANULE_DELEGATE>(&[data]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<DATA_CREATE_UNKNOWN>(&[rd, data, ipa]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<RTT_READ_ENTRY>(&[rd, ipa, MAP_LEVEL]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<DATA_DESTROY>(&[rd, ipa]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<RTT_READ_ENTRY>(&[rd, ipa, MAP_LEVEL]); assert_eq!(ret[0], SUCCESS); let (_level, state, _desc, ripas) = (ret[1], ret[2], ret[3], ret[4]); assert_eq!(state, RMI_UNASSIGNED); assert_eq!(ripas, RMI_EMPTY); let ret = rmi::<DATA_DESTROY>(&[rd, IPA_ADDR_DATA]); assert_eq!(ret[0], SUCCESS); // Cleanup mock::host::unmap(rd, ipa, false); for idx in IDX_DATA1..IDX_DATA4 + 1 { let ret = rmi::<GRANULE_UNDELEGATE>(&[granule_addr(idx)]); assert_eq!(ret[0], SUCCESS); } realm_destroy(rd); miri_teardown(); } // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_rtt_fold // Covered RMIs: RTT_FOLD #[test] fn rmi_rtt_fold_positive() { let rd = realm_create(); const IPA_HOMOGENEOUS_RTT: usize = 0; let ipa = IPA_HOMOGENEOUS_RTT; mock::host::map(rd, ipa); let base = ipa; let top = ipa + L2_SIZE; let ret = rmi::<RTT_INIT_RIPAS>(&[rd, base, top]); assert_eq!(ret[0], SUCCESS); // Save Parent rtte.addr for comparision let ret = rmi::<RTT_READ_ENTRY>(&[rd, base, MAP_LEVEL - 1]); let (_level, _state, parent_desc, _ripas) = (ret[1], ret[2], ret[3], ret[4]); assert_eq!(ret[0], SUCCESS); // Save fold.addr, fold.ripas for Positive Observability let ret = rmi::<RTT_READ_ENTRY>(&[rd, base, MAP_LEVEL]); let (_level, fold_state, fold_desc, fold_ripas) = (ret[1], ret[2], ret[3], ret[4]); assert_eq!(ret[0], SUCCESS); let ret = rmi::<RTT_FOLD>(&[rd, base, MAP_LEVEL]); assert_eq!(ret[0], SUCCESS); let out_rtt = ret[1]; assert_eq!(out_rtt, parent_desc); // Compare rtte_addr, rtte_ripas in folded RTTE let ret = rmi::<RTT_READ_ENTRY>(&[rd, base, MAP_LEVEL - 1]); assert_eq!(ret[0], SUCCESS); // Compare HIPAS, RIPAS and addr of parent RTTE to its child RTTE let (_level, state, desc, ripas) = (ret[1], ret[2], ret[3], ret[4]); assert_eq!(fold_state, state); assert_eq!(fold_desc, desc); assert_eq!(fold_ripas, ripas); mock::host::unmap(rd, ipa, true); realm_destroy(rd); miri_teardown(); } // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_rtt_set_ripas // Covered RMIs: RTT_SET_RIPAS #[test] fn rmi_rtt_set_ripas_positive() { use crate::rmi::rec::run::Run; use crate::rsi::PSCI_CPU_ON; let rd = mock::host::realm_setup(); let (rec1, run1) = (granule_addr(IDX_REC1), granule_addr(IDX_REC1_RUN)); let ret = rmi::<REC_ENTER>(&[rec1, run1]); assert_eq!(ret[0], SUCCESS); let ipa = 0; mock::host::map(rd, ipa); unsafe { let run = &*(run1 as *const Run); let (base, top) = run.ripas(); let ret = rmi::<RTT_SET_RIPAS>(&[rd, rec1, base as usize, top as usize]); assert_eq!(ret[0], SUCCESS); } mock::host::unmap(rd, ipa, false); mock::host::realm_teardown(rd); miri_teardown(); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/version.rs
rmm/src/rmi/version.rs
use crate::event::RmiHandle; use crate::listen; use crate::rmi::{self, error::Error}; extern crate alloc; pub fn decode_version(version: usize) -> (usize, usize) { let major = (version & 0x7fff0000) >> 16; let minor = version & 0xffff; (major, minor) } fn encode_version() -> usize { (rmi::ABI_MAJOR_VERSION << 16) | rmi::ABI_MINOR_VERSION } pub fn set_event_handler(rmi: &mut RmiHandle) { listen!(rmi, rmi::VERSION, |arg, ret, _| { let req = arg[0]; let lower = encode_version(); let higher = lower; ret[1] = lower; ret[2] = higher; let (req_major, req_minor) = decode_version(req); if req_major != rmi::ABI_MAJOR_VERSION || req_minor != rmi::ABI_MINOR_VERSION { warn!( "Wrong unsupported version requested ({}, {})", req_major, req_minor ); return Err(Error::RmiErrorInput); } trace!("RMI_ABI_VERSION: {:#X?} {:#X?}", lower, higher); Ok(()) }); } #[cfg(test)] mod test { use super::encode_version; use crate::rmi::{ABI_MAJOR_VERSION, ABI_MINOR_VERSION, SUCCESS, VERSION}; use crate::test_utils::*; // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_rmi_version_host #[test] fn rmi_version() { let ret = rmi::<VERSION>(&[encode_version()]); assert_eq!(ret[0], SUCCESS); // Must Be Zero fields assert_eq!(extract_bits(ret[1], 31, 63), 0); assert_eq!(extract_bits(ret[2], 31, 63), 0); // Version Check assert_eq!(extract_bits(ret[1], 0, 15), ABI_MINOR_VERSION); assert_eq!(extract_bits(ret[1], 16, 30), ABI_MAJOR_VERSION); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/error.rs
rmm/src/rmi/error.rs
use crate::{measurement::MeasurementError, rsi}; use safe_abstraction::raw_ptr; // B3.4.1 RmiCommandReturnCode type // Default index is 0 #[derive(Debug)] pub enum Error { RmiErrorInput, RmiErrorRealm(usize), RmiErrorRec, RmiErrorRtt(usize), RmiErrorInUse, RmiErrorCount, //// The below are our-defined errors not in TF-RMM RmiErrorOthers(InternalError), } #[derive(Debug)] pub enum InternalError { NotExistRealm, MeasurementError, InvalidMeasurementIndex, } impl From<Error> for usize { fn from(err: Error) -> Self { match err { Error::RmiErrorInput => 1, Error::RmiErrorRealm(index) => 2 | (index << 8), Error::RmiErrorRec => 3, Error::RmiErrorRtt(level) => 4 | (level << 8), Error::RmiErrorInUse => 5, Error::RmiErrorCount => 6, Error::RmiErrorOthers(_) => 7, } } } impl From<vmsa::error::Error> for Error { fn from(_e: vmsa::error::Error) -> Self { //error!("MmError occured: {}", <Error as Into<usize>>::into(e)); Error::RmiErrorInput } } impl From<MeasurementError> for Error { fn from(_value: MeasurementError) -> Self { Error::RmiErrorOthers(InternalError::MeasurementError) } } impl From<rsi::error::Error> for Error { fn from(value: rsi::error::Error) -> Self { match value { rsi::error::Error::RealmDoesNotExists => { Self::RmiErrorOthers(InternalError::NotExistRealm) } _ => Self::RmiErrorOthers(InternalError::InvalidMeasurementIndex), } } } impl From<raw_ptr::Error> for Error { fn from(error: raw_ptr::Error) -> Self { error!("Failed to convert a raw pointer to the struct. {:?}", error); Error::RmiErrorInput } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/mod.rs
rmm/src/rmi/mod.rs
pub mod constraint; pub mod error; pub mod features; pub mod gpt; pub mod metadata; pub mod realm; pub mod rec; pub mod rtt; pub mod version; use crate::define_interface; define_interface! { command { VERSION = 0xc400_0150, GRANULE_DELEGATE = 0xc400_0151, GRANULE_UNDELEGATE = 0xc400_0152, DATA_CREATE = 0xc400_0153, DATA_CREATE_UNKNOWN = 0xc400_0154, DATA_DESTROY = 0xc400_0155, REALM_ACTIVATE = 0xc400_0157, REALM_CREATE = 0xc400_0158, REALM_DESTROY = 0xc400_0159, REC_CREATE = 0xc400_015a, REC_DESTROY = 0xc400_015b, REC_ENTER = 0xc400_015c, RTT_CREATE = 0xc400_015d, RTT_DESTROY = 0xc400_015e, RTT_MAP_UNPROTECTED = 0xc400_015f, RTT_UNMAP_UNPROTECTED = 0xc400_0162, RTT_READ_ENTRY = 0xc400_0161, PSCI_COMPLETE = 0xc400_0164, FEATURES = 0xc400_0165, RTT_FOLD = 0xc400_0166, REC_AUX_COUNT = 0xc400_0167, RTT_INIT_RIPAS = 0xc400_0168, RTT_SET_RIPAS = 0xc400_0169, // vendor calls ISLET_REALM_SET_METADATA = 0xc700_0150, } } pub const REQ_COMPLETE: usize = 0xc400_018f; pub const RMM_GET_REALM_ATTEST_KEY: usize = 0xC400_01B2; pub const RMM_GET_PLAT_TOKEN: usize = 0xC400_01B3; pub const RMM_ISLET_GET_VHUK: usize = 0xC700_01B0; pub const BOOT_COMPLETE: usize = 0xC400_01CF; pub const BOOT_SUCCESS: usize = 0x0; pub const NOT_SUPPORTED_YET: usize = 0xFFFF_EEEE; pub const ABI_MAJOR_VERSION: usize = 1; pub const ABI_MINOR_VERSION: usize = 0; pub const HASH_ALGO_SHA256: u8 = 0; pub const HASH_ALGO_SHA512: u8 = 1; pub const RET_FAIL: usize = 0x100; pub const RET_EXCEPTION_IRQ: usize = 0x0; pub const RET_EXCEPTION_SERROR: usize = 0x1; pub const RET_EXCEPTION_TRAP: usize = 0x2; pub const RET_EXCEPTION_IL: usize = 0x3; pub const SUCCESS: usize = 0; pub const ERROR_INPUT: usize = 1; pub const ERROR_REC: usize = 3; pub const SUCCESS_REC_ENTER: usize = 4; pub const PMU_OVERFLOW_NOT_ACTIVE: u8 = 0; pub const PMU_OVERFLOW_ACTIVE: u8 = 1; // RmiRttEntryState represents the state of an RTTE pub mod rtt_entry_state { pub const RMI_UNASSIGNED: usize = 0; pub const RMI_ASSIGNED: usize = 1; pub const RMI_TABLE: usize = 2; } pub const MAX_REC_AUX_GRANULES: usize = 16; pub const EXIT_SYNC: u8 = 0; pub const EXIT_IRQ: u8 = 1; pub const EXIT_FIQ: u8 = 2; pub const EXIT_PSCI: u8 = 3; pub const EXIT_RIPAS_CHANGE: u8 = 4; pub const EXIT_HOST_CALL: u8 = 5; pub const EXIT_SERROR: u8 = 6;
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/features.rs
rmm/src/rmi/features.rs
use crate::event::RmiHandle; use crate::gic; use crate::listen; use crate::pmu; use crate::rec; use crate::rmi; use crate::simd; use armv9a::{define_bitfield, define_bits, define_mask}; extern crate alloc; define_bits!( FeatureReg0, MAX_RECS_ORDER[41 - 38], GICV3_NUM_LRS[37 - 34], HASH_SHA_512[33 - 33], HASH_SHA_256[32 - 32], PMU_NUM_CTRS[31 - 27], PMU_EN[26 - 26], NUM_WPS[25 - 20], NUM_BPS[19 - 14], SVE_VL[13 - 10], SVE_EN[9 - 9], LPA2[8 - 8], S2SZ[7 - 0] ); const S2SZ_VALUE: u64 = 48; pub const LPA2_VALUE: u64 = 0; const HASH_SHA_256_VALUE: u64 = SUPPORTED; const HASH_SHA_512_VALUE: u64 = SUPPORTED; pub const NOT_SUPPORTED: u64 = 0; pub const SUPPORTED: u64 = 1; const FEATURE_REGISTER_0_INDEX: usize = 0; pub fn set_event_handler(rmi: &mut RmiHandle) { listen!(rmi, rmi::FEATURES, |arg, ret, _| { if arg[0] != FEATURE_REGISTER_0_INDEX { ret[1] = 0; return Ok(()); } let mut feat_reg0 = FeatureReg0::new(0); feat_reg0 .set_masked_value(FeatureReg0::S2SZ, S2SZ_VALUE) .set_masked_value(FeatureReg0::LPA2, LPA2_VALUE) .set_masked_value(FeatureReg0::HASH_SHA_256, HASH_SHA_256_VALUE) .set_masked_value(FeatureReg0::HASH_SHA_512, HASH_SHA_512_VALUE) .set_masked_value(FeatureReg0::MAX_RECS_ORDER, rec::max_recs_order() as u64); #[cfg(not(any(miri, test, fuzzing)))] feat_reg0 .set_masked_value( FeatureReg0::SVE_EN, if simd::sve_en() { SUPPORTED } else { NOT_SUPPORTED }, ) .set_masked_value(FeatureReg0::SVE_VL, simd::max_sve_vl()) .set_masked_value( FeatureReg0::PMU_EN, if pmu::pmu_present() { SUPPORTED } else { NOT_SUPPORTED }, ) .set_masked_value(FeatureReg0::PMU_NUM_CTRS, pmu::pmu_num_ctrs()) .set_masked_value(FeatureReg0::GICV3_NUM_LRS, gic::nr_lrs() as u64); #[cfg(any(miri, test, fuzzing))] feat_reg0 .set_masked_value(FeatureReg0::SVE_EN, NOT_SUPPORTED) .set_masked_value(FeatureReg0::SVE_VL, 0) .set_masked_value(FeatureReg0::GICV3_NUM_LRS, 0); ret[1] = feat_reg0.get() as usize; debug!("rmi::FEATURES ret:{:X}", feat_reg0.get()); Ok(()) }); } //TODO: locate validate() in armv9a to check against AA64MMFR_EL1 register pub fn validate(s2sz: usize) -> bool { const MIN_IPA_SIZE: usize = 32; if !(MIN_IPA_SIZE..=S2SZ_VALUE as usize).contains(&s2sz) { return false; } true } #[cfg(test)] mod test { use crate::rmi::{FEATURES, SUCCESS}; use crate::test_utils::*; // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_rmi_features_host #[test] fn rmi_features() { let ret = rmi::<FEATURES>(&[0]); assert_eq!(ret[0], SUCCESS); assert_eq!(extract_bits(ret[1], 42, 63), 0); let ret = rmi::<FEATURES>(&[1]); assert_eq!(ret[0], SUCCESS); assert_eq!(ret[1], 0); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/constraint.rs
rmm/src/rmi/constraint.rs
use crate::config::SMCCC_1_3_SVE_HINT; use crate::event::{Command, Context}; use crate::rmi; #[allow(dead_code)] #[derive(Default, Copy, Clone)] pub struct Constraint { pub cmd: Command, pub arg_num: usize, // number of args including fid pub ret_num: usize, // TODO: add validate function for each RMI command (validate type or value inside registers) } impl Constraint { pub fn new(cmd: Command, arg_num: usize, ret_num: usize) -> Constraint { Constraint { cmd, arg_num, ret_num, } } } fn pick(cmd: Command) -> Option<Constraint> { let constraint = match cmd { rmi::VERSION => Constraint::new(rmi::VERSION, 2, 3), rmi::GRANULE_DELEGATE => Constraint::new(rmi::GRANULE_DELEGATE, 2, 1), rmi::GRANULE_UNDELEGATE => Constraint::new(rmi::GRANULE_UNDELEGATE, 2, 1), rmi::DATA_CREATE => Constraint::new(rmi::DATA_CREATE, 6, 1), rmi::DATA_CREATE_UNKNOWN => Constraint::new(rmi::DATA_CREATE_UNKNOWN, 4, 1), rmi::DATA_DESTROY => Constraint::new(rmi::DATA_DESTROY, 3, 3), rmi::REALM_ACTIVATE => Constraint::new(rmi::REALM_ACTIVATE, 2, 1), // NOTE: REALM_CREATE has 3 of arg_num and 1 of ret_num according to the specification, // but we're using one more return value for our own purpose. rmi::REALM_CREATE => Constraint::new(rmi::REALM_CREATE, 3, 2), rmi::REALM_DESTROY => Constraint::new(rmi::REALM_DESTROY, 2, 1), // NOTE: REC_CREATE has 4 of arg_num and 1 of ret_num according to the specification, // but we're using one more return value for our own purpose. rmi::REC_CREATE => Constraint::new(rmi::REC_CREATE, 4, 2), rmi::REC_DESTROY => Constraint::new(rmi::REC_DESTROY, 2, 1), rmi::REC_ENTER => Constraint::new(rmi::REC_ENTER, 3, 1), rmi::RTT_MAP_UNPROTECTED => Constraint::new(rmi::RTT_MAP_UNPROTECTED, 5, 1), rmi::RTT_UNMAP_UNPROTECTED => Constraint::new(rmi::RTT_UNMAP_UNPROTECTED, 4, 2), rmi::RTT_READ_ENTRY => Constraint::new(rmi::RTT_READ_ENTRY, 4, 5), rmi::FEATURES => Constraint::new(rmi::FEATURES, 2, 2), rmi::REC_AUX_COUNT => Constraint::new(rmi::REC_AUX_COUNT, 2, 2), rmi::RTT_CREATE => Constraint::new(rmi::RTT_CREATE, 5, 1), rmi::RTT_DESTROY => Constraint::new(rmi::RTT_DESTROY, 4, 3), rmi::RTT_INIT_RIPAS => Constraint::new(rmi::RTT_INIT_RIPAS, 4, 2), rmi::RTT_SET_RIPAS => Constraint::new(rmi::RTT_SET_RIPAS, 5, 2), rmi::RTT_FOLD => Constraint::new(rmi::RTT_FOLD, 4, 2), // XXX: REQ_COMPLETE do not exist in the spec rmi::REQ_COMPLETE => Constraint::new(rmi::REQ_COMPLETE, 4, 2), rmi::PSCI_COMPLETE => Constraint::new(rmi::PSCI_COMPLETE, 4, 1), rmi::ISLET_REALM_SET_METADATA => Constraint::new(rmi::ISLET_REALM_SET_METADATA, 4, 1), _ => return None, }; Some(constraint) } pub fn validate(cmd: Command, arg: &[usize]) -> Context { let fid = cmd & !SMCCC_1_3_SVE_HINT; if let Some(c) = pick(fid) { let mut ctx = Context::new(fid); // SMC calling convention requires x4-x7 to be preserved unless used. // Since the rmmd in EL3 takes care of preserving x5-x7, // we only store x4. ctx.x4 = arg[3] as u64; ctx.init_arg(&arg[..(c.arg_num - 1)]); ctx.resize_ret(c.ret_num); if cmd & SMCCC_1_3_SVE_HINT != 0 { ctx.sve_hint = true; } ctx } else { error!("Coudlnt find constraint for command: {:X}", cmd); Context::new(rmi::NOT_SUPPORTED_YET) } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/metadata.rs
rmm/src/rmi/metadata.rs
use core::ffi::CStr; use p384::{ ecdsa::{signature::Verifier, Signature, VerifyingKey}, elliptic_curve::generic_array::GenericArray, EncodedPoint, }; use super::{HASH_ALGO_SHA256, HASH_ALGO_SHA512}; use crate::granule::GRANULE_SIZE; use crate::measurement::{Measurement, MEASUREMENTS_SLOT_MAX_SIZE}; use crate::rmi::error::Error; const FMT_VERSION: usize = 1; pub const REALM_ID_SIZE: usize = 128; pub const P384_PUBLIC_KEY_SIZE: usize = 96; const P384_SIGNATURE_SIZE: usize = P384_PUBLIC_KEY_SIZE; #[allow(dead_code)] const P385_SIGNATURE_POINT_SIZE: usize = P384_SIGNATURE_SIZE / 2; #[allow(dead_code)] const SHA_384_HASH_SIZE: usize = 48; const METADATA_HASH_SHA_256: usize = 0x01; const METADATA_HASH_SHA_512: usize = 0x02; const REALM_METADATA_HEADER_SIZE: usize = 0x150; #[allow(dead_code)] const REALM_METADATA_SIGNED_SIZE: usize = 0x1B0; const REALM_METADATA_UNUSED_SIZE: usize = 0xE50; #[derive(Debug, Clone, Copy)] #[repr(C)] pub struct IsletRealmMetadata { fmt_version: usize, realm_id: [u8; REALM_ID_SIZE], rim: [u8; MEASUREMENTS_SLOT_MAX_SIZE], hash_algo: usize, svn: usize, version_major: usize, version_minor: usize, version_patch: usize, public_key: [u8; P384_PUBLIC_KEY_SIZE], signature: [u8; P384_SIGNATURE_SIZE], _unused: [u8; REALM_METADATA_UNUSED_SIZE], } const _: () = assert!(core::mem::size_of::<IsletRealmMetadata>() == GRANULE_SIZE); const _: () = assert!(core::mem::size_of::<IsletRealmMetadata>() >= REALM_METADATA_SIGNED_SIZE); const _: () = assert!(core::mem::offset_of!(IsletRealmMetadata, fmt_version) == 0x00); const _: () = assert!(core::mem::offset_of!(IsletRealmMetadata, realm_id) == 0x08); const _: () = assert!(core::mem::offset_of!(IsletRealmMetadata, rim) == 0x88); const _: () = assert!(core::mem::offset_of!(IsletRealmMetadata, hash_algo) == 0xc8); const _: () = assert!(core::mem::offset_of!(IsletRealmMetadata, svn) == 0xd0); const _: () = assert!(core::mem::offset_of!(IsletRealmMetadata, version_major) == 0xd8); const _: () = assert!(core::mem::offset_of!(IsletRealmMetadata, version_minor) == 0xe0); const _: () = assert!(core::mem::offset_of!(IsletRealmMetadata, version_patch) == 0xe8); const _: () = assert!(core::mem::offset_of!(IsletRealmMetadata, public_key) == 0xf0); impl IsletRealmMetadata { fn realm_id_as_str(&self) -> Option<&str> { let Ok(cstr) = CStr::from_bytes_until_nul(&self.realm_id) else { return None; }; let Ok(s) = cstr.to_str() else { return None; }; Some(s) } pub fn dump(&self) { debug!("fmt_version: {:#010x}", self.fmt_version); debug!( "realm_id: {}", self.realm_id_as_str().unwrap_or("INVALID REALM ID") ); debug!("rim: {}", hex::encode(self.rim)); debug!("hash_algo: {:#010x}", self.hash_algo); debug!("svn: {:#010x}", self.svn); debug!("version_major: {:#010x}", self.version_major); debug!("version_minor: {:#010x}", self.version_minor); debug!("version_patch: {:#010x}", self.version_patch); debug!("public_key: {}", hex::encode(self.public_key)); debug!("signature: {}", hex::encode(self.signature)); } fn verifying_key(&self) -> core::result::Result<VerifyingKey, Error> { let point = EncodedPoint::from_untagged_bytes(GenericArray::from_slice(&self.public_key)); VerifyingKey::from_encoded_point(&point).or(Err(Error::RmiErrorInput)) } fn signature(&self) -> core::result::Result<Signature, Error> { Signature::from_slice(&self.signature).or(Err(Error::RmiErrorInput)) } fn header_as_u8_slice(&self) -> &[u8] { let slice = unsafe { core::slice::from_raw_parts( (self as *const Self) as *const u8, core::mem::size_of::<Self>(), ) }; &slice[..REALM_METADATA_HEADER_SIZE] } pub fn verify_signature(&self) -> core::result::Result<(), Error> { let verifying_key = self.verifying_key()?; let signature = self.signature()?; let data = self.header_as_u8_slice(); verifying_key .verify(data, &signature) .or(Err(Error::RmiErrorInput)) } pub fn validate(&self) -> core::result::Result<(), Error> { if self.fmt_version != FMT_VERSION { error!( "Metadata format version {} is not supported!", self.fmt_version ); Err(Error::RmiErrorInput)? } if self.svn == 0 { error!("SVN number should be greater than zero"); Err(Error::RmiErrorInput)? } if ![METADATA_HASH_SHA_256, METADATA_HASH_SHA_512].contains(&self.hash_algo) { error!("Hash algorithm is invalid {}", self.hash_algo); Err(Error::RmiErrorInput)? } let is_printable_ascii = |&c| c >= b' ' && c <= b'~'; if !self .realm_id .iter() .take_while(|&c| *c != b'\0') .all(is_printable_ascii) { error!("Realm id is invalid"); Err(Error::RmiErrorInput)? } Ok(()) } pub fn equal_rd_rim(&self, rim: &Measurement) -> bool { rim.as_slice() == self.rim } pub fn equal_rd_hash_algo(&self, hash_algo: u8) -> bool { let converted_algo = match hash_algo { HASH_ALGO_SHA256 => METADATA_HASH_SHA_256, HASH_ALGO_SHA512 => METADATA_HASH_SHA_512, _ => unreachable!(), }; converted_algo == self.hash_algo } // for sealing key derivation pub fn svn(&self) -> usize { self.svn } pub fn public_key(&self) -> &[u8; P384_PUBLIC_KEY_SIZE] { &self.public_key } pub fn realm_id(&self) -> &[u8; REALM_ID_SIZE] { &self.realm_id } } // This should work but I don't like this traits impl vmsa::guard::Content for IsletRealmMetadata {} impl safe_abstraction::raw_ptr::RawPtr for IsletRealmMetadata {} impl safe_abstraction::raw_ptr::SafetyChecked for IsletRealmMetadata {} impl safe_abstraction::raw_ptr::SafetyAssured for IsletRealmMetadata { fn is_initialized(&self) -> bool { true } fn verify_ownership(&self) -> bool { true } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/realm/params.rs
rmm/src/rmi/realm/params.rs
use crate::const_assert_eq; use crate::granule::{GRANULE_SHIFT, GRANULE_SIZE}; use crate::measurement::Hashable; use crate::pmu; use crate::realm::mm::rtt::{RTT_PAGE_LEVEL, RTT_STRIDE}; use crate::rmi::error::Error; use crate::rmi::features; use crate::rmi::{HASH_ALGO_SHA256, HASH_ALGO_SHA512}; use crate::simd; use armv9a::{define_bitfield, define_bits, define_mask}; use autopadding::*; define_bits!( RmiRealmFlags, Lpa2[0 - 0], Sve[1 - 1], Pmu[2 - 2], Reserved[63 - 3] ); pad_struct_and_impl_default!( pub struct Params { 0x0 pub flags: u64, 0x8 pub s2sz: u8, 0x10 pub sve_vl: u8, 0x18 pub num_bps: u8, 0x20 pub num_wps: u8, 0x28 pub pmu_num_ctrs: u8, 0x30 pub hash_algo: u8, 0x400 pub rpv: [u8; 64], 0x800 pub vmid: u16, 0x808 pub rtt_base: u64, 0x810 pub rtt_level_start: i64, 0x818 pub rtt_num_start: u32, 0x1000 => @END, } ); const_assert_eq!(core::mem::size_of::<Params>(), GRANULE_SIZE); const SUPPORTED: u64 = 1; impl core::fmt::Debug for Params { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("Params") .field( "flags", &format_args!( "lpa2: {:?} sve: {:?} pmu: {:?}", RmiRealmFlags::new(self.flags).get_masked_value(RmiRealmFlags::Lpa2), RmiRealmFlags::new(self.flags).get_masked_value(RmiRealmFlags::Sve), RmiRealmFlags::new(self.flags).get_masked_value(RmiRealmFlags::Pmu) ), ) .field("s2sz", &self.s2sz) .field("sve_vl", &self.sve_vl) .field("num_bps", &self.num_bps) .field("num_wps", &self.num_wps) .field("pmu_num_ctrs", &self.pmu_num_ctrs) .field("hash_algo", &self.hash_algo) .field("rpv", &self.rpv) .field("vmid", &self.vmid) .field("rtt_base", &format_args!("{:#X}", &self.rtt_base)) .field("rtt_level_start", &self.rtt_level_start) .field("rtt_num_start", &self.rtt_num_start) .finish() } } impl Hashable for Params { fn hash( &self, hasher: &crate::measurement::Hasher, out: &mut [u8], ) -> Result<(), crate::measurement::MeasurementError> { hasher.hash_fields_into(out, |alg| { alg.hash_u64(self.flags); alg.hash(self._padflags); alg.hash_u8(self.s2sz); alg.hash(self._pads2sz); alg.hash_u8(self.sve_vl); alg.hash(self._padsve_vl); alg.hash_u8(self.num_bps); alg.hash(self._padnum_bps); alg.hash_u8(self.num_wps); alg.hash(self._padnum_wps); alg.hash_u8(self.pmu_num_ctrs); alg.hash(self._padpmu_num_ctrs); alg.hash_u8(self.hash_algo); alg.hash(self._padhash_algo); alg.hash([0u8; 64]); // rpv is not used alg.hash(self._padrpv); alg.hash_u16(0); // vmid is not used alg.hash(self._padvmid); alg.hash_u64(0); // rtt_base is not used alg.hash(self._padrtt_base); alg.hash_u64(0); // rtt_level_start is not used alg.hash(self._padrtt_level_start); alg.hash_u32(0); // rtt_num_start is not used alg.hash(self._padrtt_num_start); }) } } impl Params { pub fn ipa_bits(&self) -> usize { self.s2sz as usize } pub fn sve_en(&self) -> bool { let flags = RmiRealmFlags::new(self.flags); flags.get_masked_value(RmiRealmFlags::Sve) == SUPPORTED } pub fn pmu_en(&self) -> bool { let flags = RmiRealmFlags::new(self.flags); flags.get_masked_value(RmiRealmFlags::Pmu) == SUPPORTED } pub fn verify_compliance(&self, rd: usize) -> Result<(), Error> { trace!("{:?}", self); if self.rtt_base as usize == rd { return Err(Error::RmiErrorInput); } if self.rtt_base as usize % GRANULE_SIZE != 0 { return Err(Error::RmiErrorInput); } if !features::validate(self.s2sz as usize) { return Err(Error::RmiErrorInput); } // Check misconfigurations between IPA size and SL let ipa_bits = self.ipa_bits(); let rtt_slvl = self.rtt_level_start as usize; let level = RTT_PAGE_LEVEL .checked_sub(rtt_slvl) .ok_or(Error::RmiErrorInput)?; let min_ipa_bits = level * RTT_STRIDE + GRANULE_SHIFT + 1; let max_ipa_bits = min_ipa_bits + (RTT_STRIDE - 1) + 4; let sl_ipa_bits = (level * RTT_STRIDE) + GRANULE_SHIFT + RTT_STRIDE; if (ipa_bits < min_ipa_bits) || (ipa_bits > max_ipa_bits) { return Err(Error::RmiErrorInput); } let s2_num_root_rtts = { if sl_ipa_bits >= ipa_bits { 1 } else { 1 << (ipa_bits - sl_ipa_bits) } }; if s2_num_root_rtts != self.rtt_num_start { return Err(Error::RmiErrorInput); } // TODO: We don't support pmu, lpa2 let flags = RmiRealmFlags::new(self.flags); if flags.get_masked_value(RmiRealmFlags::Lpa2) != features::LPA2_VALUE { return Err(Error::RmiErrorInput); } if !simd::validate(self.sve_en(), self.sve_vl as u64) { return Err(Error::RmiErrorInput); } if self.pmu_en() && (!pmu::pmu_present() || self.pmu_num_ctrs > pmu::pmu_num_ctrs() as u8 || (self.pmu_num_ctrs == 0 && !pmu::hpmn0_present())) { return Err(Error::RmiErrorInput); } match self.hash_algo { HASH_ALGO_SHA256 | HASH_ALGO_SHA512 => Ok(()), _ => Err(Error::RmiErrorInput), } } } impl safe_abstraction::raw_ptr::RawPtr for Params {} impl safe_abstraction::raw_ptr::SafetyChecked for Params {} impl safe_abstraction::raw_ptr::SafetyAssured for Params { fn is_initialized(&self) -> bool { // Given the fact that this memory is initialized by the Host, // it's not possible to unequivocally guarantee // that the values have been initialized from the perspective of the RMM. // However, any values, whether correctly initialized or not, will undergo // verification during the Measurement phase. // Consequently, this function returns `true`. true } fn verify_ownership(&self) -> bool { // This memory has permissions from the Host's perspective, // which inherently implies that exclusive ownership cannot be guaranteed by the RMM alone. // However, since the RMM only performs read operations and any incorrect values will be // verified during the Measurement phase. // Consequently, this function returns `true`. true } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/realm/mod.rs
rmm/src/rmi/realm/mod.rs
pub mod params; pub use self::params::Params; use super::error::Error; use crate::event::RmiHandle; use crate::granule::GRANULE_SIZE; use crate::granule::{set_granule, GranuleState}; use crate::host; use crate::listen; use crate::measurement::{HashContext, MEASUREMENTS_SLOT_RIM}; use crate::realm::mm::stage2_translation::Stage2Translation; use crate::realm::mm::IPATranslation; use crate::realm::rd::State; use crate::realm::rd::{insert_rtt, Rd}; use crate::realm::registry::{remove, VMID_SET}; use crate::rmi::{self, metadata::IsletRealmMetadata}; use crate::{get_granule, get_granule_if}; use alloc::boxed::Box; use alloc::sync::Arc; use spin::mutex::Mutex; extern crate alloc; pub fn set_event_handler(rmi: &mut RmiHandle) { #[cfg(any(not(kani), feature = "mc_rmi_realm_activate"))] listen!(rmi, rmi::REALM_ACTIVATE, |arg, _, _| { let rd = arg[0]; let mut rd_granule = get_granule_if!(rd, GranuleState::RD)?; let mut rd = rd_granule.content_mut::<Rd>()?; if let Some(meta) = rd.metadata() { debug!("Realm metadata is in use!"); let metadata_granule = get_granule_if!(meta, GranuleState::Metadata)?; let metadata_obj = metadata_granule.content::<IsletRealmMetadata>()?; if !metadata_obj.equal_rd_rim(&rd.measurements[MEASUREMENTS_SLOT_RIM]) { error!("Calculated rim and those read from metadata are not the same!"); return Err(Error::RmiErrorRealm(0)); } if !metadata_obj.equal_rd_hash_algo(rd.hash_algo()) { error!("Provided measurement hash algorithm and metadata hash algorithm are different!"); return Err(Error::RmiErrorRealm(0)); } } if !rd.at_state(State::New) { return Err(Error::RmiErrorRealm(0)); } rd.set_state(State::Active); Ok(()) }); #[cfg(not(kani))] listen!(rmi, rmi::REALM_CREATE, |arg, _, rmm| { let rd = arg[0]; let params_ptr = arg[1]; if rd == params_ptr { return Err(Error::RmiErrorInput); } let mut rd_granule = get_granule_if!(rd, GranuleState::Delegated)?; let mut rd_obj = rd_granule.content_mut::<Rd>()?; #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.map(rd, true); rmm.page_table.map(params_ptr, false); let params = host::copy_from::<Params>(params_ptr).ok_or(Error::RmiErrorInput)?; rmm.page_table.unmap(params_ptr); params.verify_compliance(rd)?; for i in 0..params.rtt_num_start as usize { let rtt = params.rtt_base as usize + i * GRANULE_SIZE; let _ = get_granule_if!(rtt, GranuleState::Delegated)?; // The below is added to avoid a fault regarding the RTT entry // during the below stage 2 page table creation rmm.page_table.map(rtt, true); } // revisit rmi.create_realm() (is it necessary?) create_realm(params.vmid as usize).map(|_| { let s2 = Box::new(Stage2Translation::new( params.rtt_base as usize, params.rtt_level_start as usize, params.rtt_num_start as usize, )) as Box<dyn IPATranslation>; insert_rtt(params.vmid as usize, Arc::new(Mutex::new(s2))); rd_obj.init( params.vmid, params.rtt_base as usize, params.rtt_num_start as usize, params.ipa_bits(), params.rtt_level_start as isize, params.rpv, params.sve_en(), params.sve_vl as u64, params.pmu_en(), params.pmu_num_ctrs as usize, ) })?; let rtt_base = rd_obj.rtt_base(); rd_obj.set_hash_algo(params.hash_algo); #[cfg(not(kani))] // `rsi` is currently not reachable in model checking harnesses HashContext::new(&mut rd_obj)?.measure_realm_create(&params)?; let mut epilogue = move || { for i in 0..params.rtt_num_start as usize { let rtt = rtt_base + i * GRANULE_SIZE; let mut rtt_granule = get_granule_if!(rtt, GranuleState::Delegated)?; set_granule(&mut rtt_granule, GranuleState::RTT)?; } set_granule(&mut rd_granule, GranuleState::RD) }; epilogue().inspect_err(|_| { #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.unmap(rd); remove(params.vmid as usize).expect("Realm should be created before."); }) }); #[cfg(any(not(kani), feature = "mc_rmi_rec_aux_count"))] listen!(rmi, rmi::REC_AUX_COUNT, |arg, ret, _| { let _ = get_granule_if!(arg[0], GranuleState::RD)?; ret[1] = rmi::MAX_REC_AUX_GRANULES; Ok(()) }); #[cfg(any(not(kani), feature = "mc_rmi_realm_destroy"))] listen!(rmi, rmi::REALM_DESTROY, |arg, _ret, rmm| { // get the lock for Rd let mut rd_granule = get_granule_if!(arg[0], GranuleState::RD)?; if rd_granule.num_children() > 0 { return Err(Error::RmiErrorRealm(0)); } let mut rd = rd_granule.content::<Rd>()?; let vmid = rd.id(); let rtt_base = rd.rtt_base(); if let Some(meta) = rd.metadata() { let mut meta_granule = get_granule_if!(meta, GranuleState::Metadata)?; set_granule(&mut meta_granule, GranuleState::Delegated)?; rd.set_metadata(None); rmm.page_table.unmap(meta); } #[cfg(kani)] // XXX: the below can be guaranteed by Rd's invariants kani::assume(crate::granule::validate_addr(rtt_base)); #[cfg(not(feature = "gst_page_table"))] { #[cfg(not(kani))] for i in 0..rd.rtt_num_start() { let rtt = rtt_base + i * GRANULE_SIZE; let rtt_granule = get_granule!(rtt)?; if rtt_granule.num_children() > 0 { return Err(Error::RmiErrorRealm(0)); } } #[cfg(kani)] { // XXX: we remove the loop and consider only the first iteration // to reduce the overall verification time let rtt_granule = get_granule!(rtt_base)?; if rtt_granule.num_children() > 0 { return Err(Error::RmiErrorRealm(0)); } } } #[cfg(not(kani))] for i in 0..rd.rtt_num_start() { let rtt = rtt_base + i * GRANULE_SIZE; let mut rtt_granule = get_granule!(rtt)?; set_granule(&mut rtt_granule, GranuleState::Delegated)?; } #[cfg(kani)] { // XXX: we remove the loop and consider only the first iteration // to reduce the overall verification time let mut rtt_granule = get_granule!(rtt_base)?; set_granule(&mut rtt_granule, GranuleState::Delegated)?; } // change state when everything goes fine. set_granule(&mut rd_granule, GranuleState::Delegated)?; #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.unmap(arg[0]); // TODO: remove the below after modeling `VmidIsFree()` #[cfg(not(kani))] remove(vmid)?; Ok(()) }); // ISLET_REALM_SET_METADATA is a vendor specific RMI for provisioning the realm metadata to the Realm // Input registers // x0: function id (0xC7000150) // x1: rd - a physicall address of the RD for the target Realm // x2: mdg - a physicall address of the delegated granule used for storage of the metadata // x3: meta_ptr - a physicall address of the host provided (NS) metadata granule listen!(rmi, rmi::ISLET_REALM_SET_METADATA, |arg, _ret, rmm| { let rd_addr = arg[0]; let mdg_addr = arg[1]; let meta_ptr = arg[2]; rmm.page_table.map(meta_ptr, false); let realm_metadata: Box<IsletRealmMetadata> = Box::new(host::copy_from(meta_ptr).ok_or(Error::RmiErrorInput)?); rmm.page_table.unmap(meta_ptr); realm_metadata.dump(); if let Err(e) = realm_metadata.verify_signature() { error!("Verification of realm metadata signature has failed"); Err(e)?; } if let Err(e) = realm_metadata.validate() { error!("The content of realm metadata is not valid"); Err(e)?; } let mut rd_granule = get_granule_if!(rd_addr, GranuleState::RD)?; let mut rd = rd_granule.content_mut::<Rd>()?; if !rd.at_state(State::New) { error!("Metadata can only be set for new realms"); Err(Error::RmiErrorRealm(0))?; } if rd.metadata().is_some() { error!("Metadata is already set"); Err(Error::RmiErrorRealm(0))?; } rmm.page_table.map(mdg_addr, true); let mut metadata_granule = get_granule_if!(mdg_addr, GranuleState::Delegated)?; let mut metadata_obj = metadata_granule.content_mut::<IsletRealmMetadata>()?; *metadata_obj = *realm_metadata.clone(); set_granule(&mut metadata_granule, GranuleState::Metadata)?; rd.set_metadata(Some(mdg_addr)); Ok(()) }); } fn create_realm(vmid: usize) -> Result<(), Error> { let mut vmid_set = VMID_SET.lock(); if vmid_set.contains(&vmid) { return Err(Error::RmiErrorInput); } else { vmid_set.insert(vmid); }; Ok(()) } #[cfg(test)] mod test { use crate::realm::rd::{Rd, State}; use crate::rmi::{ERROR_INPUT, REALM_ACTIVATE, REALM_CREATE, SUCCESS}; use crate::test_utils::*; use alloc::vec; #[test] fn rmi_realm_create_positive() { let rd = realm_create(); let ret = rmi::<REALM_ACTIVATE>(&[rd]); assert_eq!(ret[0], SUCCESS); unsafe { let rd_obj = &*(rd as *const Rd); assert!(rd_obj.at_state(State::Active)); }; realm_destroy(rd); miri_teardown(); } // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_realm_create /* Check 1 : params_align; rd : 0x88300000 params_ptr : 0x88303001 ret : 1 Check 2 : params_bound; rd : 0x88300000 params_ptr : 0x1C0B0000 ret : 1 Check 3 : params_bound; rd : 0x88300000 params_ptr : 0x1000000001000 ret : 1 Check 4 : params_pas; rd : 0x88300000 params_ptr : 0x88309000 ret : 1 Check 5 : params_pas; rd : 0x88300000 params_ptr : 0x6000000 ret : 1 Check 6 : params_valid; rd : 0x88300000 params_ptr : 0x8830C000 ret : 1 Check 7 : params_valid; rd : 0x88300000 params_ptr : 0x8830F000 ret : 1 Check 8 : params_supp Skipping Test case Check 9 : params_supp; rd : 0x88300000 params_ptr : 0x88315000 ret : 1 Check 10 : params_supp; rd : 0x88300000 params_ptr : 0x88318000 ret : 1 Check 11 : params_supp; rd : 0x88300000 params_ptr : 0x8831B000 ret : 1 Check 12 : params_supp; rd : 0x88300000 params_ptr : 0x8831E000 ret : 1 Check 13 : params_supp; rd : 0x88300000 params_ptr : 0x88321000 ret : 1 Check 14 : alias; rd : 0x88306000 params_ptr : 0x88303000 ret : 1 Check 15 : rd_align; rd : 0x88300001 params_ptr : 0x88303000 ret : 1 Check 16 : rd_bound; rd : 0x1C0B0000 params_ptr : 0x88303000 ret : 1 Check 17 : rd_bound; rd : 0x1000000001000 params_ptr : 0x88303000 ret : 1 Check 18 : rd_state; rd : 0x88324000 params_ptr : 0x88303000 ret : 1 Check 19 : rd_state; rd : 0x88327000 params_ptr : 0x88303000 ret : 1 Check 20 : rd_state; rd : 0x88336000 params_ptr : 0x88303000 ret : 1 Check 21 : rd_state; rd : 0x8832A000 params_ptr : 0x88303000 ret : 1 Check 22 : rd_state; rd : 0x88372000 params_ptr : 0x88303000 ret : 1 Check 23 : rtt_align; rd : 0x88300000 params_ptr : 0x88378000 ret : 1 Check 24 : rtt_num_level; rd : 0x88300000 params_ptr : 0x8837B000 ret : 1 Check 25 : rtt_state; rd : 0x88300000 params_ptr : 0x8837E000 ret : 1 Check 26 : vmid_valid Couldn't create VMID Invalid sequence Skipping Test case Check 27 : vmid_valid; rd : 0x88300000 params_ptr : 0x88387000 ret : 1 */ #[test] fn rmi_realm_create_negative() { let test_data = vec![ // TODO: Cover all test data ((0x88300000 as usize, 0x88303001 as usize), ERROR_INPUT), ]; // main test for (input, output) in test_data { let ret = rmi::<REALM_CREATE>(&[input.0, input.1, 0]); assert_eq!(output, ret[0]); } } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/rec/vtcr.rs
rmm/src/rmi/rec/vtcr.rs
use crate::realm::rd::Rd; use crate::rec::Rec; use crate::rmi::error::Error; use aarch64_cpu::registers::*; fn is_feat_vmid16_present() -> bool { #[cfg(not(any(miri, test)))] let ret = ID_AA64MMFR1_EL1.read(ID_AA64MMFR1_EL1::VMIDBits) == ID_AA64MMFR1_EL1::VMIDBits::Bits16.into(); #[cfg(any(miri, test))] let ret = true; ret } pub fn prepare_vtcr(rd: &Rd) -> Result<u64, Error> { let s2_starting_level = rd.s2_starting_level(); let ipa_bits = rd.ipa_bits(); // sl0 consists of 2 bits (2^2 == 4) if !(s2_starting_level >= 0 && s2_starting_level <= 3) { return Err(Error::RmiErrorInput); } // t0sz consists of 6 bits (2^6 == 64) if !(ipa_bits > 0 && ipa_bits <= 64) { return Err(Error::RmiErrorInput); } let mut vtcr_val = VTCR_EL2::PS::PA_40B_1TB + VTCR_EL2::TG0::Granule4KB + VTCR_EL2::SH0::Inner + VTCR_EL2::ORGN0::NormalWBRAWA + VTCR_EL2::IRGN0::NormalWBRAWA + VTCR_EL2::NSA::NonSecurePASpace + VTCR_EL2::RES1.val(1); //XXX: not sure why RES1 is in default set in tf-rmm if is_feat_vmid16_present() { vtcr_val += VTCR_EL2::VS::Bits16; } let sl0_array = [ VTCR_EL2::SL0::Granule4KBLevel0, VTCR_EL2::SL0::Granule4KBLevel1, VTCR_EL2::SL0::Granule4KBLevel2, VTCR_EL2::SL0::Granule4KBLevel3, ]; let sl0_val = sl0_array[s2_starting_level as usize]; let t0sz_val = (64 - ipa_bits) as u64; vtcr_val += sl0_val + VTCR_EL2::T0SZ.val(t0sz_val); Ok(vtcr_val.into()) } pub fn activate_stage2_mmu(rec: &Rec<'_>) { VTCR_EL2.set(rec.vtcr()); }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/rec/handlers.rs
rmm/src/rmi/rec/handlers.rs
use super::mpidr::MPIDR; use super::params::Params; use super::run::{EntryFlag, Run}; use super::vtcr::{activate_stage2_mmu, prepare_vtcr}; use crate::event::RmiHandle; #[cfg(feature = "gst_page_table")] use crate::granule::{set_granule, set_granule_with_parent, GranuleState}; #[cfg(not(feature = "gst_page_table"))] use crate::granule::{set_granule, GranuleState}; use crate::host; use crate::listen; use crate::measurement::HashContext; use crate::realm::rd::{Rd, State}; use crate::rec::context::{set_reg, RegOffset}; use crate::rec::State as RecState; use crate::rec::{max_recs_order, Rec, RmmRecEmulatableAbort::NotEmulatableAbort}; use crate::rmi; use crate::rmi::error::Error; use crate::rsi::do_host_call; use crate::rsi::psci::complete_psci; use crate::{get_granule, get_granule_if}; use aarch64_cpu::registers::*; use armv9a::bits_in_reg; extern crate alloc; fn prepare_args(rd: &mut Rd, mpidr: u64) -> Result<(usize, u64, u64), Error> { let page_table = rd.s2_table().lock().get_base_address() as u64; let vttbr = bits_in_reg( VTTBR_EL2::VMID.mask << VTTBR_EL2::VMID.shift, rd.id() as u64, ) | bits_in_reg( VTTBR_EL2::BADDR.mask << VTTBR_EL2::BADDR.shift, page_table >> 1, ); let vmpidr = mpidr | (MPIDR_EL1::RES1.mask << MPIDR_EL1::RES1.shift); let vcpuid = rd.vcpu_index; rd.vcpu_index += 1; Ok((vcpuid, vttbr, vmpidr)) } pub fn set_event_handler(rmi: &mut RmiHandle) { #[cfg(not(kani))] listen!(rmi, rmi::REC_CREATE, |arg, ret, rmm| { let rd = arg[0]; let rec = arg[1]; let params_ptr = arg[2]; let owner = rd; if rec == rd { return Err(Error::RmiErrorInput); } rmm.page_table.map(params_ptr, false); let params = host::copy_from::<Params>(params_ptr).ok_or(Error::RmiErrorInput)?; rmm.page_table.unmap(params_ptr); params.verify_compliance(rec, rd, params_ptr)?; let rec_index = MPIDR::from(params.mpidr).index(); let mut rd_granule = get_granule_if!(rd, GranuleState::RD)?; let mut rd = rd_granule.content_mut::<Rd>()?; if !rd.at_state(State::New) { return Err(Error::RmiErrorRealm(0)); } if rd.num_recs() == (1 << max_recs_order()) - 1 { return Err(Error::RmiErrorRealm(0)); } if rec_index != rd.rec_index() { return Err(Error::RmiErrorInput); } // set Rec_state and grab the lock for Rec granule let mut rec_granule = get_granule_if!(rec, GranuleState::Delegated)?; #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.map(rec, true); let mut rec = rec_granule.new_uninit_with::<Rec<'_>>(Rec::new())?; match prepare_args(&mut rd, params.mpidr) { Ok((vcpuid, vttbr, vmpidr)) => { ret[1] = vcpuid; // Transit granule status of param.aux to RecAux from Delegated // before access within rec.init(). for i in 0..rmi::MAX_REC_AUX_GRANULES { let aux = params.aux[i] as usize; rmm.page_table.map(aux, true); let mut aux_granule = get_granule_if!(aux, GranuleState::Delegated)?; set_granule(&mut aux_granule, GranuleState::RecAux)?; } rec.init(owner, vcpuid, params.flags, params.aux, vttbr, vmpidr)?; } Err(_) => return Err(Error::RmiErrorInput), } for (idx, gpr) in params.gprs.iter().enumerate() { if set_reg(&mut rec, idx, *gpr as usize).is_err() { return Err(Error::RmiErrorInput); } } if set_reg(&mut rec, RegOffset::PC, params.pc as usize).is_err() { return Err(Error::RmiErrorInput); } rec.set_vtcr(prepare_vtcr(&rd)?); rd.inc_recs(); #[cfg(not(kani))] // `rsi` is currently not reachable in model checking harnesses HashContext::new(&mut rd)?.measure_rec_params(&params)?; #[cfg(not(feature = "gst_page_table"))] rd_granule.inc_count(); #[cfg(feature = "gst_page_table")] return set_granule_with_parent(rd_granule.clone(), &mut rec_granule, GranuleState::Rec); #[cfg(not(feature = "gst_page_table"))] return set_granule(&mut rec_granule, GranuleState::Rec); }); #[cfg(any(not(kani), feature = "mc_rmi_rec_destroy"))] listen!(rmi, rmi::REC_DESTROY, |arg, _ret, rmm| { let mut rec_granule = get_granule_if!(arg[0], GranuleState::Rec)?; let rec = rec_granule.content::<Rec<'_>>()?; if rec.get_state() == RecState::Running { return Err(Error::RmiErrorRec); } #[cfg(not(kani))] for i in 0..rmi::MAX_REC_AUX_GRANULES { let rec_aux = rec.aux(i) as usize; let mut rec_aux_granule = get_granule_if!(rec_aux, GranuleState::RecAux)?; set_granule(&mut rec_aux_granule, GranuleState::Delegated)?; rmm.page_table.unmap(rec_aux); } #[cfg(kani)] { // XXX: we check only the first aux to reduce the overall // verification time let rec_aux = rec.aux(0) as usize; // XXX: the below can be guaranteed by Rec's invariants instead kani::assume(crate::granule::validate_addr(rec_aux)); let mut rec_aux_granule = get_granule!(rec_aux)?; set_granule(&mut rec_aux_granule, GranuleState::Delegated)?; } let rd = rec.owner()?; #[cfg(kani)] { // XXX: the below can be guaranteed by Rec's invariants instead kani::assume(crate::granule::validate_addr(rd)); let rd_granule = get_granule!(rd)?; kani::assume(rd_granule.state() == GranuleState::RD); } let mut rd_granule = get_granule_if!(rd, GranuleState::RD)?; #[cfg(not(feature = "gst_page_table"))] rd_granule.dec_count(); let mut rd = rd_granule.content::<Rd>()?; rd.dec_recs(); set_granule(&mut rec_granule, GranuleState::Delegated).inspect_err(|_| { #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.unmap(arg[0]); })?; #[cfg(not(kani))] // `page_table` is currently not reachable in model checking harnesses rmm.page_table.unmap(arg[0]); Ok(()) }); #[cfg(not(kani))] listen!(rmi, rmi::REC_ENTER, |arg, ret, rmm| { let run_pa = arg[1]; // grab the lock for Rec let mut rec_granule = get_granule_if!(arg[0], GranuleState::Rec)?; let mut rec = rec_granule.content_mut::<Rec<'_>>()?; // read Run rmm.page_table.map(run_pa, false); let mut run = host::copy_from::<Run>(run_pa).ok_or(Error::RmiErrorInput)?; rmm.page_table.unmap(run_pa); run.verify_compliance()?; trace!("{:?}", run); let rd_granule = get_granule_if!(rec.owner()?, GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; match rd.state() { State::Active => {} State::New => { return Err(Error::RmiErrorRealm(0)); } State::SystemOff => { return Err(Error::RmiErrorRealm(1)); } _ => { panic!("Unexpected realm state"); } } // XXX: we explicitly release Rd's lock here to avoid a deadlock core::mem::drop(rd_granule); // runnable oder is lower if !rec.runnable() { return Err(Error::RmiErrorRec); } if let RecState::Running = rec.get_state() { error!("Rec is already running: {:?}", *rec); return Err(Error::RmiErrorRec); } if rec.psci_pending() { return Err(Error::RmiErrorRec); } #[cfg(not(any(miri, test, fuzzing)))] if !crate::rec::gic::validate_state(&run) { return Err(Error::RmiErrorRec); } if rec.host_call_pending() { // The below should be called without holding rd's lock do_host_call(arg, ret, rmm, &mut rec, &mut run)?; } #[cfg(not(any(miri, test, fuzzing)))] crate::rec::gic::receive_state_from_host(&mut rec, &run)?; crate::rec::mmio::emulate_mmio(&mut rec, &run)?; crate::rec::sea::host_sea_inject(&mut rec, &run)?; crate::rsi::ripas::complete_ripas(&mut rec, &run)?; let wfx_flag = run.entry_flags(); #[cfg(not(any(miri, test, fuzzing)))] { let hcr_el2 = HCR_EL2.get(); let mut wfx = 0; let wfx_mask = !(3 << 13); if wfx_flag.get_masked(EntryFlag::TRAP_WFI) != 0 { wfx |= 1 << 13; } if wfx_flag.get_masked(EntryFlag::TRAP_WFE) != 0 { wfx |= 1 << 14; } HCR_EL2.set((hcr_el2 & wfx_mask) | wfx); } #[cfg(not(any(miri, test, fuzzing)))] activate_stage2_mmu(&rec); crate::rec::save_host_state(&rec); let mut ret_ns; loop { ret_ns = true; run.set_imm(0); rec.set_state(RecState::Running); #[cfg(not(any(miri, test, fuzzing)))] { use crate::rmi::rec::exit::handle_realm_exit; let rd_granule = get_granule_if!(rec.owner()?, GranuleState::RD)?; let rd = rd_granule.content::<Rd>()?; rec.set_emulatable_abort(NotEmulatableAbort); crate::rec::run_prepare(&rd, rec.vcpuid(), &mut rec, 0)?; // XXX: we explicitly release Rd's lock here, because RSI calls // would acquire the same lock again (deadlock). core::mem::drop(rd_granule); match crate::rec::run() { Ok(realm_exit_res) => { (ret_ns, ret[0]) = handle_realm_exit(realm_exit_res, rmm, &mut rec, &mut run)? } Err(_) => ret[0] = rmi::ERROR_REC, } } #[cfg(any(miri, test))] { use crate::test_utils::mock; mock::realm::setup_psci_complete(&mut rec, &mut run); mock::realm::setup_ripas_state(&mut rec, &mut run); } #[cfg(fuzzing)] { use crate::test_utils::mock; // In fuzzing contexts, unused register x3 denotes either RSI command or // pseudo RSI command, REC_ENTER_EXIT_CMD for simulating realm exit conditions. // Unused registers x4 and above serve as arguments for the RSI command. if arg.len() >= 3 { let cmd = arg[2]; let args = &arg[3..]; rec.set_emulatable_abort(NotEmulatableAbort); (_, ret[0]) = mock::realm::emulate_realm(rmm, &mut rec, &mut run, cmd, args)?; } } rec.set_state(RecState::Ready); if ret_ns { break; } } #[cfg(not(any(miri, test, fuzzing)))] crate::rec::gic::send_state_to_host(&rec, &mut run)?; crate::rec::timer::send_state_to_host(&rec, &mut run)?; crate::rec::pmu::send_state_to_host(&rec, &mut run)?; crate::rec::restore_host_state(&rec); // NOTICE: do not modify `run` after copy_to_ptr(). it won't have any effect. rmm.page_table.map(run_pa, false); let ret = host::copy_to_ptr::<Run>(&run, run_pa).ok_or(Error::RmiErrorInput); rmm.page_table.unmap(run_pa); ret }); #[cfg(not(kani))] listen!(rmi, rmi::PSCI_COMPLETE, |arg, _ret, _rmm| { let caller_pa = arg[0]; let target_pa = arg[1]; if caller_pa == target_pa { return Err(Error::RmiErrorInput); } let mut caller_granule = get_granule_if!(caller_pa, GranuleState::Rec)?; let mut caller = caller_granule.content_mut::<Rec<'_>>()?; let mut target_granule = get_granule_if!(target_pa, GranuleState::Rec)?; let mut target = target_granule.content_mut::<Rec<'_>>()?; let status = arg[2]; if !caller.psci_pending() { return Err(Error::RmiErrorInput); } if caller.realmid()? != target.realmid()? { return Err(Error::RmiErrorInput); } complete_psci(&mut caller, &mut target, status) }); } #[cfg(test)] mod test { use crate::event::realmexit::RecExitReason; use crate::rmi::rec::run::Run; use crate::rmi::*; use crate::rsi::PSCI_CPU_ON; use crate::test_utils::*; // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_rec_create // Covered RMIs: REC_CREATE, REC_DESTROY, REC_AUX_COUNT // Related Spec: D1.2.4 REC creation flow #[test] fn rmi_rec_create_positive() { let rd = realm_create(); rec_create(rd, IDX_REC1, IDX_REC1_PARAMS, IDX_REC1_AUX); rec_destroy(IDX_REC1, IDX_REC1_AUX); realm_destroy(rd); miri_teardown(); } // Source: https://github.com/ARM-software/cca-rmm-acs // Test Case: cmd_psci_complete // Covered RMIs: REC_ENTER, PSCI_COMPLETE #[test] fn rmi_rec_enter_positive() { let rd = mock::host::realm_setup(); let (rec1, run1) = (granule_addr(IDX_REC1), granule_addr(IDX_REC1_RUN)); let ret = rmi::<REC_ENTER>(&[rec1, run1]); assert_eq!(ret[0], SUCCESS); unsafe { let run = &*(run1 as *const Run); let reason: u64 = RecExitReason::PSCI.into(); assert_eq!(run.exit_reason(), reason as u8); assert_eq!(run.gpr(0).unwrap(), PSCI_CPU_ON as u64); } let rec2 = granule_addr(IDX_REC2); const PSCI_E_SUCCESS: usize = 0; let ret = rmi::<PSCI_COMPLETE>(&[rec1, rec2, PSCI_E_SUCCESS]); assert_eq!(ret[0], SUCCESS); mock::host::realm_teardown(rd); miri_teardown(); } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/rec/params.rs
rmm/src/rmi/rec/params.rs
use super::mpidr; use crate::const_assert_eq; use crate::granule::{GranuleState, GRANULE_SIZE}; use crate::measurement::Hashable; use crate::rmi; use crate::rmi::error::Error; use crate::{get_granule, get_granule_if}; use autopadding::*; pub const NR_AUX: usize = 16; pub const NR_GPRS: usize = 8; pad_struct_and_impl_default!( pub struct Params { 0x0 pub flags: u64, 0x100 pub mpidr: u64, 0x200 pub pc: u64, 0x300 pub gprs: [u64; NR_GPRS], 0x800 pub num_aux: u64, 0x808 pub aux: [u64; NR_AUX], 0x1000 => @END, } ); const_assert_eq!(core::mem::size_of::<Params>(), GRANULE_SIZE); impl Params { pub fn verify_compliance(&self, rec: usize, rd: usize, params_ptr: usize) -> Result<(), Error> { // Currently, we use rmi::MAX_REC_AUX_GRANULES for RecAuxCount(rd) if !mpidr::validate(self.mpidr) || self.num_aux as usize != rmi::MAX_REC_AUX_GRANULES { return Err(Error::RmiErrorInput); } let mut aux = self.aux; aux.sort(); for idx in 0..self.num_aux as usize { let addr = aux[idx] as usize; if addr == rec || addr == rd || addr == params_ptr { return Err(Error::RmiErrorInput); } if idx != 0 && aux[idx - 1] == aux[idx] { return Err(Error::RmiErrorInput); } let _aux_granule = get_granule_if!(addr, GranuleState::Delegated)?; } Ok(()) } } impl core::fmt::Debug for Params { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("Params") .field("flags", &format_args!("{:#X}", &self.flags)) .field("mpidr", &format_args!("{:#X}", &self.mpidr)) .field("pc", &format_args!("{:#X}", &self.pc)) .field("gprs", &format_args!("{:#X?}", &self.gprs)) .field("num_aux", &self.num_aux) .field("aux", &self.aux) .finish() } } impl safe_abstraction::raw_ptr::RawPtr for Params {} impl safe_abstraction::raw_ptr::SafetyChecked for Params {} impl safe_abstraction::raw_ptr::SafetyAssured for Params { fn is_initialized(&self) -> bool { // Given the fact that this memory is initialized by the Host, // it's not possible to unequivocally guarantee // that the values have been initialized from the perspective of the RMM. // However, any values, whether correctly initialized or not, will undergo // verification during the Measurement phase. // Consequently, this function returns `true`. true } fn verify_ownership(&self) -> bool { // This memory has permissions from the Host's perspective, // which inherently implies that exclusive ownership cannot be guaranteed by the RMM alone. // However, since the RMM only performs read operations and any incorrect values will be // verified during the Measurement phase. // Consequently, this function returns `true`. true } } impl Hashable for Params { fn hash( &self, hasher: &crate::measurement::Hasher, out: &mut [u8], ) -> Result<(), crate::measurement::MeasurementError> { hasher.hash_fields_into(out, |h| { h.hash_u64(self.flags); h.hash(self._padflags); h.hash_u64(0); // mpidr not used h.hash(self._padmpidr); h.hash_u64(self.pc); h.hash(self._padpc); h.hash_u64_array(self.gprs.as_slice()); h.hash(self._padgprs); h.hash_u64(0); // num_aux not used h.hash_u64_array([0u64; 16].as_slice()); // aux is not used h.hash(self._padaux); }) } }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/rec/mpidr.rs
rmm/src/rmi/rec/mpidr.rs
use armv9a::{define_bitfield, define_bits, define_mask}; // B3.4.16 RmiRecMpidr type define_bits!( MPIDR, AFF3[31 - 24], AFF2[23 - 16], AFF1[15 - 8], AFF0[3 - 0] ); impl From<u64> for MPIDR { fn from(val: u64) -> Self { Self(val) } } impl MPIDR { // B2.30 RecIndex function pub fn index(&self) -> usize { let aff0 = self.get_masked_value(MPIDR::AFF0) as usize; let aff1 = self.get_masked_value(MPIDR::AFF1) as usize; let aff2 = self.get_masked_value(MPIDR::AFF2) as usize; let aff3 = self.get_masked_value(MPIDR::AFF3) as usize; aff0 + (16 * aff1) + (16 * 256 * aff2) + (16 * 256 * 256 * aff3) } } pub fn validate(mpidr: u64) -> bool { let must_be_zero = !(MPIDR::AFF0 | MPIDR::AFF1 | MPIDR::AFF2 | MPIDR::AFF3); mpidr & must_be_zero == 0 }
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false
islet-project/islet
https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/rmm/src/rmi/rec/mod.rs
rmm/src/rmi/rec/mod.rs
pub mod exit; pub mod handlers; pub mod mpidr; pub mod params; pub mod run; pub mod vtcr; pub use self::handlers::set_event_handler;
rust
Apache-2.0
5f541377a34c5daaf01aa148e406370e304fb661
2026-01-04T20:21:26.369655Z
false