From ef237e7bf85c9a03bcf5072e43d6814c7830b2df Mon Sep 17 00:00:00 2001 From: Tim Crawford Date: Wed, 13 Nov 2024 07:16:25 -0700 Subject: [PATCH] Remove debug logging Serial debug cannot be used on newer toolchains due to its use of unaligned references. Signed-off-by: Tim Crawford --- src/debug.rs | 55 ------------- src/dump_hii.rs | 207 ------------------------------------------------ src/fde.rs | 77 ++++-------------- src/main.rs | 8 +- src/security.rs | 42 ++-------- src/serial.rs | 125 ----------------------------- 6 files changed, 26 insertions(+), 488 deletions(-) delete mode 100644 src/debug.rs delete mode 100644 src/dump_hii.rs delete mode 100644 src/serial.rs diff --git a/src/debug.rs b/src/debug.rs deleted file mode 100644 index 391ea14..0000000 --- a/src/debug.rs +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-only - -use core::fmt::{self, Write}; -use hwio::{Io, Mmio, Pio}; - -use crate::coreboot::COREBOOT_SERIAL; -use crate::serial::SerialPort; - -pub struct Debug; - -impl Write for Debug { - fn write_str(&mut self, string: &str) -> Result<(), fmt::Error> { - if let Some(ref serial) = *COREBOOT_SERIAL.lock() { - match (serial.kind, serial.regwidth) { - (1, 1) => unsafe { - SerialPort::>::new(serial.baseaddr as u16) - .write(string.as_bytes()); - }, - (2, 4) => unsafe { - SerialPort::>::new(serial.baseaddr as usize) - .write(string.as_bytes()); - }, - _ => (), - } - } else { - let mut port = Pio::::new(0x402); - for b in string.bytes() { - port.write(b); - } - } - - Ok(()) - } -} - -#[cfg(not(feature = "debug"))] -pub fn _debug(_args: fmt::Arguments) {} - -#[cfg(feature = "debug")] -pub fn _debug(args: fmt::Arguments) { - Debug.write_fmt(args).unwrap(); -} - - -#[macro_export] -macro_rules! debug { - ($($arg:tt)*) => ($crate::debug::_debug(format_args!($($arg)*))); -} - -#[macro_export] -macro_rules! debugln { - () => (debug!("\n")); - ($fmt:expr) => (debug!(concat!($fmt, "\n"))); - ($fmt:expr, $($arg:tt)*) => (debug!(concat!($fmt, "\n"), $($arg)*)); -} diff --git a/src/dump_hii.rs b/src/dump_hii.rs deleted file mode 100644 index 0de35f6..0000000 --- a/src/dump_hii.rs +++ /dev/null @@ -1,207 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-only - -use hwio::{Io, Pio}; -use std::{char, mem, ptr, str}; -use std::ops::Try; -use std::proto::Protocol; -use std::prelude::*; -use std::uefi::hii::database::HiiHandle; -use std::uefi::hii::ifr::{IfrOpCode, IfrOpHeader, IfrForm, IfrAction}; -use std::uefi::hii::package::{HiiPackageHeader, HiiPackageKind, HiiPackageListHeader, HiiStringPackageHeader}; -use std::uefi::hii::sibt::{SibtHeader, SibtKind, SibtEnd, SibtSkip2, SibtStringUcs2, SibtStringsUcs2}; - -use crate::hii; - -// The IfrOpCode's we need to handle so far: -// Action -// DefaultStore -// End -// Form -// FormSet -// Guid -// OneOf -// OneOfOption -// Ref -// Subtitle - -fn dump_form(op: &IfrOpHeader) { - debugln!( - " Form: OpCode {:#x} {:?}, Length {}, Scope {}", - op.OpCode as u8, - op.OpCode, - op.Length(), - op.Scope() - ); - - match op.OpCode { - IfrOpCode::Form => { - let form = unsafe { &*(op as *const _ as *const IfrForm) }; - debugln!(" {:?}", form); - }, - IfrOpCode::Action => { - let action = unsafe { &*(op as *const _ as *const IfrAction) }; - debugln!(" {:?}", action); - }, - _ => () - } -} - -fn dump_forms(data: &[u8]) { - let mut i = 0; - while i + mem::size_of::() < data.len() { - let op = unsafe { - & *(data.as_ptr().add(i) as *const IfrOpHeader) - }; - - dump_form(op); - - i += op.Length() as usize; - } -} - -fn dump_strings(strings: &HiiStringPackageHeader) { - debugln!(" {:?}: {:?}", strings, str::from_utf8(strings.Language())); - let info = strings.StringInfo(); - let mut id = 1; - let mut i = 0; - while i < info.len() { - let ptr = unsafe { info.as_ptr().add(i) }; - let header = unsafe { &*(ptr as *const SibtHeader) }; - match header.BlockType { - SibtKind::End => { - let block = unsafe { &*(ptr as *const SibtEnd) }; - debugln!(" {:?}", block); - i += mem::size_of_val(block); - }, - SibtKind::Skip2 => { - let block = unsafe { &*(ptr as *const SibtSkip2) }; - debugln!(" {:?}", block); - id += block.SkipCount(); - i += mem::size_of_val(block); - }, - SibtKind::StringUcs2 => { - let block = unsafe { &*(ptr as *const SibtStringUcs2) }; - debugln!(" {:?}", block); - let text = block.StringText(); - { - // Capacity will be at least text.len() - let mut string = String::with_capacity(text.len()); - for &w in text.iter() { - let c = unsafe { char::from_u32_unchecked(w as u32) }; - string.push(c); - } - debugln!(" {}: \"{}\"", id, string); - } - id += 1; - let text_end = unsafe { text.as_ptr().add(text.len() + 1) }; - i += text_end as usize - ptr as usize - }, - /* TODO, if required - SibtKind::StringsUcs2 => { - let block = unsafe { &*(ptr as *const SibtStringsUcs2) }; - debugln!(" {:?}", block); - if block.StringCount > 0 { - let text = block.StringText(block.StringCount - 1); - let text_end = unsafe { text.as_ptr().add(text.len() + 1) }; - i += text_end as usize - ptr as usize - } else { - i += mem::size_of_val(block); - } - }, - */ - unknown => { - panic!( - "Unimplemented SibtKind {:?}, {:#x}", - unknown, - unknown as u8 - ); - } - } - } -} - -fn dump_package(package: &HiiPackageHeader) { - debugln!( - " Package: Kind {:#x} {:?}, Length {}", - package.Kind() as u8, - package.Kind(), - package.Length() - ); - - match package.Kind() { - HiiPackageKind::Forms => { - dump_forms(package.Data()); - }, - HiiPackageKind::Strings => { - let strings = unsafe { &*(package as *const _ as *const HiiStringPackageHeader) }; - dump_strings(strings); - } - _ => (), - } -} - -fn dump_package_list(package_list: &HiiPackageListHeader) { - debugln!( - "Package List: Guid {}, Length {}", - package_list.PackageListGuid, - package_list.PackageLength - ); - - let data = package_list.Data(); - let mut i = 0; - while i + mem::size_of::() < data.len() { - let package = unsafe { - & *(data.as_ptr().add(i) as *const HiiPackageHeader) - }; - dump_package(package); - i += package.Length() as usize; - } -} - -fn dump_package_lists(data: &[u8]) { - let mut i = 0; - while i + mem::size_of::() < data.len() { - let package_list = unsafe { - & *(data.as_ptr().add(i) as *const HiiPackageListHeader) - }; - dump_package_list(package_list); - i += package_list.PackageLength as usize; - } -} - -pub fn dump_hii() -> Result<()> { - for db in hii::Database::all() { - let mut size = 0; - - match (db.0.ExportPackageLists)( - db.0, - HiiHandle(0), - &mut size, - unsafe { &mut *ptr::null_mut() } - ).into_result() { - Ok(_) => (), - Err(err) if err == Error::BufferTooSmall => (), - Err(err) => return Err(err), - } - - let mut data: Box<[u8]> = vec![0; size].into_boxed_slice(); - (db.0.ExportPackageLists)( - db.0, - HiiHandle(0), - &mut size, - unsafe { &mut *(data.as_mut_ptr() as *mut HiiPackageListHeader) } - )?; - - if size != data.len() { - debugln!("Database: ExportPackageLists size {} does not match {}", size, data.len()); - return Err(Error::BadBufferSize); - } - - dump_package_lists(&data); - } - - //debugln!("Shutdown"); - //Pio::::new(0x604).write(0x2000); - - Ok(()) -} diff --git a/src/fde.rs b/src/fde.rs index 2d97bbf..2483b77 100644 --- a/src/fde.rs +++ b/src/fde.rs @@ -361,11 +361,6 @@ fn wait_for_events(form: &Form) -> Result { #[allow(unused_assignments)] fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { - debugln!(); - debugln!("form_display"); - debugln!("FORM_DISPLAY_ENGINE_FORM {}, {:?}", mem::size_of::
(), span_of!(Form, HotKeyListHead)); - debugln!("BROWSER_HOT_KEY {}, {:?}", mem::size_of::(), span_of!(HotKey, Link)); - let hii_string = <&'static mut HiiStringProtocol>::one()?; let string = |string_id: StringId| -> Result { @@ -404,18 +399,7 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { 'render: loop { let mut hotkey_helps = Vec::new(); for hotkey in form.HotKeyListHead.iter() { - let hotkey_ptr = hotkey as *const _; - debugln!(" hotkey: {:p}, {:x?}", hotkey_ptr, unsafe { - slice::from_raw_parts( - hotkey_ptr as *const u8, - mem::size_of_val(hotkey) - ) - }); - debugln!(" key: {:p}, {:?}", hotkey.KeyData, unsafe { *hotkey.KeyData }); - debugln!(" action: {:#x}", hotkey.Action); - debugln!(" defaultid: {:#x}", hotkey.DefaultId); let hotkey_help = ffi::nstr(hotkey.HelpString); - debugln!(" help: {:p}, {}", hotkey.HelpString, hotkey_help); hotkey_helps.push(hotkey_help); } @@ -424,17 +408,14 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { let mut elements = Vec::new(); for statement in form.StatementListHead.iter() { let statement_ptr = statement as *const _; - debugln!("statement: {:p}", statement_ptr); let mut options = Vec::new(); for option in statement.OptionListHead.iter() { let option_ptr = option as *const _; - debugln!(" option: {:p}", option_ptr); if let Some(op) = option.OptionOpCode() { let value = unsafe { op.Value.to_enum(op.Kind) }; - debugln!(" {:?}: {:?}", op.Option, value); let prompt = ui.font.render(&string(op.Option).unwrap_or_default(), font_size); options.push(ElementOption { option_ptr, @@ -448,7 +429,6 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { let value = unsafe { statement.CurrentValue.Value.to_enum(statement.CurrentValue.Kind) }; - debugln!(" {:?}: {:?}", header, value); let buffer_opt = if statement.CurrentValue.Buffer.is_null() { None } else { @@ -458,7 +438,6 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { statement.CurrentValue.BufferLen as usize ) }; - debugln!(" buffer: {:?}", buffer); // Order list according to buffer if list { let mut offset = 0; @@ -492,10 +471,7 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { IfrTypeValueEnum::U16(u16) => check_option!(u16), IfrTypeValueEnum::U32(u32) => check_option!(u32), IfrTypeValueEnum::U64(u64) => check_option!(u64), - other => { - debugln!("unsupported option in list: {:?}", other); - false - }, + _ => false, }; if matches { if i != j { @@ -510,7 +486,6 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { }; if statement_ptr == form.HighLightedStatement || (selected == !0 && selectable) { selected = elements.len(); - debugln!("selected {}", selected); } elements.push(Element { statement_ptr, @@ -527,10 +502,8 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { }; if let Some(op) = statement.OpCode() { - debugln!(" {:?}", op); macro_rules! cast { ($type:ty) => ({ - debugln!(" casting {} to {}", op.Length(), mem::size_of::<$type>()); op.cast::<$type>() }); } @@ -781,7 +754,6 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { for hotkey in form.HotKeyListHead.iter() { let key_data = unsafe { &*hotkey.KeyData }; if key_data.ScanCode == raw_key.ScanCode && key_data.UnicodeChar == raw_key.UnicodeChar { - debugln!("pressed {}", ffi::nstr(hotkey.HelpString)); user_input.Action = hotkey.Action; user_input.DefaultId = hotkey.DefaultId; break 'render; @@ -790,7 +762,6 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { } let key = Key::from(raw_key); - debugln!("{:?}", key); match key { Key::Enter => { if let Some(element) = elements.get_mut(selected) { @@ -807,26 +778,23 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { } if checkbox { - match element.value { - IfrTypeValueEnum::Bool(b) => { - user_input.SelectedStatement = element.statement_ptr; - unsafe { - ptr::copy( - &(*element.statement_ptr).CurrentValue, - &mut user_input.InputValue, - 1 - ); - } + if let IfrTypeValueEnum::Bool(b) = element.value { + user_input.SelectedStatement = element.statement_ptr; + unsafe { + ptr::copy( + &(*element.statement_ptr).CurrentValue, + &mut user_input.InputValue, + 1 + ); + } - let (kind, value) = unsafe { - IfrTypeValueEnum::Bool(!b).to_union() - }; - user_input.InputValue.Kind = kind; - user_input.InputValue.Value = value; + let (kind, value) = unsafe { + IfrTypeValueEnum::Bool(!b).to_union() + }; + user_input.InputValue.Kind = kind; + user_input.InputValue.Value = value; - break 'render; - }, - other => debugln!("unsupported checkbox value {:?}", other) + break 'render; } } else if element.editable && ! editing { editing = true; @@ -864,9 +832,7 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { IfrTypeValueEnum::U16(u16) => copy_option!(u16), IfrTypeValueEnum::U32(u32) => copy_option!(u32), IfrTypeValueEnum::U64(u64) => copy_option!(u64), - other => { - debugln!("unsupported option in list: {:?}", other); - }, + _ => (), } } if offset < buffer.len() { @@ -874,9 +840,6 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { buffer[i] = 0; } } - debugln!("modified: {:?}", buffer); - } else { - debugln!("list without buffer"); } } else { let (kind, value) = unsafe { element.value.to_union() }; @@ -1020,8 +983,6 @@ fn form_display_inner(form: &Form, user_input: &mut UserInput) -> Result<()> { } } - debugln!("selected: {:p}, action: {:#x}", user_input.SelectedStatement, user_input.Action); - Ok(()) } @@ -1030,11 +991,9 @@ extern "efiapi" fn form_display(form: &Form, user_input: &mut UserInput) -> Stat } extern "efiapi" fn exit_display() { - debugln!("exit_display"); } extern "efiapi" fn confirm_data_change() -> usize { - debugln!("confirm_data_change"); 0 } @@ -1050,8 +1009,6 @@ impl Fde { &mut *(interface as *mut Fde) }; - debugln!("Current FDE: {:#p}", current); - current.FormDisplay = form_display; current.ExitDisplay = exit_display; current.ConfirmDataChange = confirm_data_change; diff --git a/src/main.rs b/src/main.rs index 33f6a5a..7d8d291 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,18 +13,12 @@ use std::prelude::*; use core::ptr; -#[macro_use] -mod debug; - mod coreboot; mod display; mod hii; pub mod image; mod key; mod rng; -mod serial; - -//mod dump_hii; mod fde; mod security; mod ui; @@ -43,7 +37,7 @@ pub extern "C" fn main() -> Status { } if let Err(err) = security::install() { - debugln!("security error: {:?}", err); + println!("security error: {:?}", err); let _ = key::key(true); } diff --git a/src/security.rs b/src/security.rs index e4cc403..be55baa 100644 --- a/src/security.rs +++ b/src/security.rs @@ -69,10 +69,7 @@ fn confirm(display: &mut Display) -> Result<()> { let rng = match Rng::one() { Ok(ok) => ok, - Err(err) => { - debugln!("failed to get random number generator: {:?}", err); - return Err(err); - } + Err(err) => return Err(err), }; // Clear any previous keys @@ -199,7 +196,6 @@ fn confirm(display: &mut Display) -> Result<()> { display.sync(); let k = key(true)?; - debugln!("key: {:?}", k); match k { Key::Backspace => { input.pop(); @@ -247,33 +243,23 @@ fn confirm(display: &mut Display) -> Result<()> { extern "efiapi" fn run() -> bool { let access = match unsafe { AccessLpcDirect::new(UefiTimeout::new(100_000)) } { Ok(ok) => ok, - Err(err) => { - debugln!("failed to access EC: {:?}", err); - return false; - }, + Err(_) => return false, }; let mut ec = match unsafe { Ec::new(access) } { Ok(ok) => ok, - Err(err) => { - debugln!("failed to probe EC: {:?}", err); - return false; - }, + Err(_) => return false, }; let security_state = match unsafe { ec.security_get() } { Ok(ok) => ok, - Err(err) => { - debugln!("failed to get EC security state: {:?}", err); - return false; - } + Err(_) => return false, }; // The EC will already be set to unlocked at this point, so the prompt // must be run even when in the "Unlock" state. This is fine, as the // prompt is for physical presence detection. - debugln!("security state: {:?}", security_state); if security_state == SecurityState::Lock { // Already locked, so do not confirm return false; @@ -293,26 +279,14 @@ extern "efiapi" fn run() -> bool { res }, - Err(err) => { - debugln!("failed to get output: {:?}", err); - Err(err) - } + Err(err) => Err(err), }; match res { - Ok(()) => { - debugln!("confirmed"); - }, - Err(err) => { - debugln!("failed to confirm: {:?}", err); - + Ok(()) => (), + Err(_) => { // Lock on next shutdown, will power on automatically - match unsafe { ec.security_set(SecurityState::PrepareLock) } { - Ok(()) => (), - Err(err) => { - debugln!("failed to prepare to lock EC security state: {:?}", err) - } - } + let _ = unsafe { ec.security_set(SecurityState::PrepareLock) }; // Shutdown (std::system_table().RuntimeServices.ResetSystem)( diff --git a/src/serial.rs b/src/serial.rs deleted file mode 100644 index 92221a1..0000000 --- a/src/serial.rs +++ /dev/null @@ -1,125 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-only - -use core::convert::TryInto; -use hwio::{Io, Pio, Mmio, ReadOnly}; - -bitflags::bitflags! { - /// Interrupt enable flags - struct IntEnFlags: u8 { - const RECEIVED = 1; - const SENT = 1 << 1; - const ERRORED = 1 << 2; - const STATUS_CHANGE = 1 << 3; - // 4 to 7 are unused - } -} - -bitflags::bitflags! { - /// Line status flags - struct LineStsFlags: u8 { - const INPUT_FULL = 1; - // 1 to 4 unknown - const OUTPUT_EMPTY = 1 << 5; - // 6 and 7 unknown - } -} - -#[allow(dead_code)] -#[repr(packed)] -pub struct SerialPort { - /// Data register, read to receive, write to send - data: T, - /// Interrupt enable - int_en: T, - /// FIFO control - fifo_ctrl: T, - /// Line control - line_ctrl: T, - /// Modem control - modem_ctrl: T, - /// Line status - line_sts: ReadOnly, - /// Modem status - modem_sts: ReadOnly, -} - -impl SerialPort> { - pub unsafe fn new(base: u16) -> SerialPort> { - SerialPort { - data: Pio::new(base), - int_en: Pio::new(base + 1), - fifo_ctrl: Pio::new(base + 2), - line_ctrl: Pio::new(base + 3), - modem_ctrl: Pio::new(base + 4), - line_sts: ReadOnly::new(Pio::new(base + 5)), - modem_sts: ReadOnly::new(Pio::new(base + 6)) - } - } -} - -impl SerialPort> { - pub unsafe fn new(base: usize) -> &'static mut SerialPort> { - &mut *(base as *mut Self) - } -} - -#[allow(dead_code)] -impl SerialPort - where T::Value: From + TryInto -{ - #[allow(unaligned_references)] - pub unsafe fn init(&mut self) { - //TODO: Cleanup - self.int_en.write(0x00.into()); - self.line_ctrl.write(0x80.into()); - self.data.write(0x01.into()); - self.int_en.write(0x00.into()); - self.line_ctrl.write(0x03.into()); - self.fifo_ctrl.write(0xC7.into()); - self.modem_ctrl.write(0x0B.into()); - self.int_en.write(0x01.into()); - } - - #[allow(unaligned_references)] - unsafe fn line_sts(&self) -> LineStsFlags { - LineStsFlags::from_bits_truncate( - (self.line_sts.read() & 0xFF.into()).try_into().unwrap_or(0) - ) - } - - #[allow(unaligned_references)] - pub unsafe fn receive(&mut self) -> Option { - if self.line_sts().contains(LineStsFlags::INPUT_FULL) { - Some( - (self.data.read() & 0xFF.into()).try_into().unwrap_or(0) - ) - } else { - None - } - } - - #[allow(unaligned_references)] - pub unsafe fn send(&mut self, data: u8) { - while ! self.line_sts().contains(LineStsFlags::OUTPUT_EMPTY) {} - self.data.write(data.into()); - } - - pub unsafe fn write(&mut self, buf: &[u8]) { - for &b in buf { - match b { - 8 | 0x7F => { - self.send(8); - self.send(b' '); - self.send(8); - }, - b'\n' => { - self.send(b'\r'); - self.send(b'\n'); - }, - _ => { - self.send(b); - } - } - } - } -}