diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dad703ac..a0fe2a6b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -145,6 +145,14 @@ jobs: cargo build -p framework_tool cargo build -p framework_tool --release --features nvidia,smartmontools + # The lints and test jobs only run on Linux, so they never see the + # cfg(windows) code. Lint and test it here instead. + - name: Run cargo clippy (Windows) + run: cargo clippy -p framework_lib -p framework_tool --all-targets -- -D warnings + + - name: Run cargo test (Windows) + run: cargo test -p framework_lib + - name: Check if Windows tool can start run: target/release/framework_tool.exe --help diff --git a/EXAMPLES.md b/EXAMPLES.md index 759c9f99..131aa1bf 100644 --- a/EXAMPLES.md +++ b/EXAMPLES.md @@ -118,7 +118,7 @@ Options: --hash Hash a file of arbitrary data --driver - Select which driver is used. By default portio is used [possible values: portio, cros-ec, windows] + Select which driver is used to talk to the EC. Defaults to the first available one [possible values: portio, cros-ec] --pd-addrs Specify I2C addresses of the PD chips (Advanced) --pd-ports diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 53c3da14..4737adc4 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -2140,11 +2140,19 @@ impl CrosEc { } } +/// Drivers that can be built for the current platform +/// +/// Only gated by OS, not by architecture, so that there's always at least one +/// variant. Whether the driver is actually usable on this machine is decided by +/// `available_drivers`. #[cfg_attr(not(feature = "uefi"), derive(clap::ValueEnum))] #[derive(Clone, Debug, Copy, PartialEq)] pub enum CrosEcDriverType { + #[cfg(not(windows))] Portio, + #[cfg(target_os = "linux")] CrosEc, + #[cfg(windows)] Windows, } @@ -2173,6 +2181,9 @@ impl CrosEcDriver for CrosEc { } // TODO: Change this function to return EcResult instead and print the error only in UI code + // The catch-all arm is unreachable unless a variant is built without its driver, + // which only happens for Portio on non-x86_64 + #[allow(unreachable_patterns)] print_err(match self.driver { #[cfg(all(not(windows), target_arch = "x86_64"))] Some(CrosEcDriverType::Portio) => portio::read_memory(offset, length), @@ -2204,6 +2215,7 @@ impl CrosEcDriver for CrosEc { ))); } + #[allow(unreachable_patterns)] match self.driver { #[cfg(all(not(windows), target_arch = "x86_64"))] Some(CrosEcDriverType::Portio) => portio::send_command(command, command_version, data), diff --git a/framework_lib/src/chromium_ec/windows.rs b/framework_lib/src/chromium_ec/windows.rs index 050d734d..877a5692 100644 --- a/framework_lib/src/chromium_ec/windows.rs +++ b/framework_lib/src/chromium_ec/windows.rs @@ -88,6 +88,14 @@ pub fn read_memory(offset: u16, length: u16) -> EcResult> { if !init() { return Err(EcError::DeviceError("Failed to initialize".to_string())); } + // The driver rejects reads that end at the last byte of the memory map, + // so it can only read up to EC_MEMMAP_SIZE - 1 bytes + if offset as u32 + length as u32 >= EC_MEMMAP_SIZE as u32 { + return Err(EcError::DeviceError(format!( + "Windows driver requires offset + length < {:#X} (offset={:#X}, length={:#X})", + EC_MEMMAP_SIZE, offset, length + ))); + } let mut rm = CrosEcReadMem { offset: offset as u32, bytes: length as u32, @@ -97,7 +105,7 @@ pub fn read_memory(offset: u16, length: u16) -> EcResult> { let const_ptr = &mut rm as *const _ as *const ::core::ffi::c_void; let mut_ptr = &mut rm as *mut _ as *mut ::core::ffi::c_void; let ptr_size = std::mem::size_of::() as u32; - let retb: u32 = 0; + let mut returned: u32 = 0; unsafe { let device = DEVICE.lock().unwrap(); let device = if let Some(device) = *device { @@ -112,10 +120,10 @@ pub fn read_memory(offset: u16, length: u16) -> EcResult> { ptr_size, Some(mut_ptr), ptr_size, - Some(retb as *mut u32), + Some(&mut returned), None, ) - .unwrap(); + .map_err(|err| EcError::DeviceError(format!("IOCTL_CROSEC_RDMEM failed with {:?}", err)))?; } let output = &rm.buffer[..(length as usize)]; Ok(output.to_vec()) @@ -157,10 +165,10 @@ pub fn send_command(command: u16, command_version: u8, data: &[u8]) -> EcResult< cmd_len.try_into().unwrap(), Some(mut_ptr), out_len.try_into().unwrap(), - Some(&mut returned as *mut u32), + Some(&mut returned), None, ) - .unwrap(); + .map_err(|err| EcError::DeviceError(format!("IOCTL_CROSEC_XCMD failed with {:?}", err)))?; } match FromPrimitive::from_u32(cmd.result) { diff --git a/framework_lib/src/commandline/clap_std.rs b/framework_lib/src/commandline/clap_std.rs index 323f3f37..e0636e13 100644 --- a/framework_lib/src/commandline/clap_std.rs +++ b/framework_lib/src/commandline/clap_std.rs @@ -361,7 +361,7 @@ struct ClapCli { #[arg(long)] hash: Option, - /// Select which driver is used. By default portio is used + /// Select which driver is used to talk to the EC. Defaults to the first available one #[clap(value_enum)] #[arg(long)] driver: Option, diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index f23d5e9e..95c45a8c 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -541,16 +541,36 @@ fn active_mode(mode: &FwMode, reference: FwMode) -> &'static str { } } +/// Whether this system can have the ILI touchscreen and stylus +/// +/// So far only the Framework Laptop 12 has them. Other systems may have a +/// Himax touchscreen, which is handled separately. +#[cfg(feature = "hidapi")] +fn has_ili_touchscreen() -> bool { + smbios::get_platform().and_then(Platform::which_family) == Some(PlatformFamily::Framework12) +} + +/// How often to ask the stylus for its battery level before giving up +/// +/// The stylus only answers while it's awake, so a few tries are needed. But it +/// has to be bounded, otherwise this never returns when no stylus is around. +#[cfg(feature = "hidapi")] +const STYLUS_BATTERY_TRIES: u32 = 50; + #[cfg(feature = "hidapi")] fn print_stylus_battery_level() { - loop { + if !has_ili_touchscreen() { + error!("This system has no stylus"); + return; + } + for _ in 0..STYLUS_BATTERY_TRIES { if let Some(level) = touchscreen::get_battery_level() { println!("Stylus Battery Strength: {}%", level); return; - } else { - debug!("Stylus Battery Strength: Unknown"); } + debug!("Stylus Battery Strength: Unknown"); } + println!("Stylus Battery Strength: Unknown"); } fn print_versions(ec: &CrosEc) { @@ -860,13 +880,12 @@ fn print_versions(ec: &CrosEc) { let _ignore_err = print_touchpad_fw_ver(); #[cfg(feature = "hidapi")] - { + if has_ili_touchscreen() { + // Also prints the Himax touchscreen version + let _ignore_err = touchscreen::print_fw_ver(); + } else { + // Laptop 13 can have a Himax touchscreen let _ignore_err = touchscreen::print_himax_fw_ver(); - if smbios::get_platform().and_then(Platform::which_family) - == Some(PlatformFamily::Framework12) - { - let _ignore_err = touchscreen::print_fw_ver(); - } } #[cfg(feature = "hidapi")] print_dp_hdmi_details(false); @@ -1464,12 +1483,34 @@ fn flash_ec(ec: &CrosEc, ec_bin_path: &str, flash_type: EcFlashType, dry_run: bo } fn dump_ec_flash(ec: &CrosEc, dump_path: &str) { - let flash_bin = ec.get_entire_ec_flash().unwrap(); + // Create the file before the slow flash read, so a bad path is reported + // right away instead of after dumping all of it + #[cfg(not(feature = "uefi"))] + let mut file = match fs::File::create(dump_path) { + Ok(file) => file, + Err(err) => { + error!("Failed to create {}: {}", dump_path, err); + return; + } + }; + + let flash_bin = match ec.get_entire_ec_flash() { + Ok(flash_bin) => flash_bin, + Err(err) => { + error!("Failed to read EC flash: {:?}", err); + // Don't leave an empty file behind that looks like a dump + #[cfg(not(feature = "uefi"))] + { + drop(file); + let _ = fs::remove_file(dump_path); + } + return; + } + }; #[cfg(not(feature = "uefi"))] - { - let mut file = fs::File::create(dump_path).unwrap(); - file.write_all(&flash_bin).unwrap(); + if let Err(err) = file.write_all(&flash_bin) { + error!("Failed to write {}: {}", dump_path, err); } #[cfg(feature = "uefi")] { @@ -1864,7 +1905,9 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { ec.set_tablet_mode(mode); } else if let Some(_enable) = &args.touchscreen_enable { #[cfg(feature = "hidapi")] - if touchscreen::enable_touch(*_enable).is_none() { + if !has_ili_touchscreen() { + error!("This system has no touchscreen"); + } else if touchscreen::enable_touch(*_enable).is_none() { error!("Failed to enable/disable touch"); } } else if let Some(_intensity) = &args.haptic_intensity { diff --git a/framework_lib/src/power.rs b/framework_lib/src/power.rs index cbb0382b..073812bc 100644 --- a/framework_lib/src/power.rs +++ b/framework_lib/src/power.rs @@ -883,7 +883,11 @@ pub fn check_update_ready(power_info: &PowerInfo) -> bool { Some(battery) if power_info.ac_present && battery.charge_percentage > 20 => true, Some(battery) => { println!("Please plug in AC. If the battery is connected, charge it to at least 20% before proceeding."); - println!("Current charge is: {}%", battery.charge_percentage); + if battery.last_full_charge_capacity == 0 { + println!("Current charge is: Unknown (LFCC is 0)"); + } else { + println!("Current charge is: {}%", battery.charge_percentage); + } false } } diff --git a/framework_lib/src/touchscreen_win.rs b/framework_lib/src/touchscreen_win.rs index f5fd42a0..c7d47888 100644 --- a/framework_lib/src/touchscreen_win.rs +++ b/framework_lib/src/touchscreen_win.rs @@ -1,5 +1,4 @@ use hidapi::HidApi; -use std::path::Path; use crate::touchscreen::{TouchScreen, ILI_PID, ILI_VID}; #[allow(unused_imports)] @@ -19,10 +18,21 @@ use windows::{ const REPORT_ID_FIRMWARE: u8 = 0x27; const REPORT_ID_USI_VER: u8 = 0x28; +/// Size of the HID reports this device uses +const REPORT_LEN: usize = 0x40; + pub struct NativeWinTouchScreen { handle: HANDLE, } +impl Drop for NativeWinTouchScreen { + fn drop(&mut self) { + unsafe { + let _ = CloseHandle(self.handle); + } + } +} + impl TouchScreen for NativeWinTouchScreen { fn open_device(target_up: u16, skip: u8) -> Option { debug!( @@ -63,11 +73,17 @@ impl TouchScreen for NativeWinTouchScreen { // TODO: Enumerate with windows // Should enumerate and find the right one // See: https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/finding-and-opening-a-hid-collection - let path = dev_info.path().to_str().unwrap(); + let path = match dev_info.path().to_str() { + Ok(path) => path, + Err(err) => { + error!("Device path is not valid UTF-8: {:?}", err); + return None; + } + }; let res = unsafe { CreateFileW( - &HSTRING::from(Path::new(path)), + &HSTRING::from(path), FILE_GENERIC_WRITE.0 | FILE_GENERIC_READ.0, FILE_SHARE_READ | FILE_SHARE_WRITE, None, @@ -101,66 +117,95 @@ impl TouchScreen for NativeWinTouchScreen { fn send_message(&self, message_id: u8, read_len: usize, data: Vec) -> Option> { let report_id = 0x03; let data_len = data.len(); - let mut msg = [0u8; 0x40]; let msg_len = 3 + data_len; + // Microsoft docs says that the first byte of the message has to be the report ID. + // This is normal with HID implementations. + // But it seems on Windows (at least for this device's firmware) we have to set the + // length as one more than the report is long. + // Otherwise no data is returned in the read call later. + // Make the buffer that one byte longer rather than having the driver read past its end. + let mut msg = [0u8; REPORT_LEN + 1]; + if 5 + data_len > REPORT_LEN { + error!("Message data of {} B doesn't fit into a report", data_len); + return None; + } + if msg_len + read_len > REPORT_LEN { + error!("Response of {} B doesn't fit into a report", read_len); + return None; + } msg[0] = report_id; msg[1] = 0xA3; msg[2] = data_len as u8; msg[3] = read_len as u8; msg[4] = message_id; - for (i, b) in data.into_iter().enumerate() { - msg[5 + i] = b; - } + msg[5..5 + data_len].copy_from_slice(&data); - let mut buf = [0u8; 0x40]; + let mut buf = [0u8; REPORT_LEN]; buf[0] = report_id; + let mut bytes_read = 0; unsafe { debug!(" HidD_SetOutputReport {:X?}", msg); - let success = HidD_SetOutputReport( - self.handle, - // Microsoft docs says that the first byte of the message has to be the report ID. - // This is normal with HID implementations. - // But it seems on Windows (at least for this device's firmware) we have to set the - // length as one more than the buffer is long. - // Otherwise no data is returned in the read call later. - msg.as_mut_ptr() as _, - msg.len() as u32 + 1, - ); + let success = + HidD_SetOutputReport(self.handle, msg.as_mut_ptr() as _, msg.len() as u32); debug!(" Success: {}", success); + if !success { + error!("Failed to send report to touchscreen"); + return None; + } if read_len == 0 { return Some(vec![]); } - let mut bytes_read = 0; debug!(" ReadFile"); // HidD_GetFeature doesn't work, have to use ReadFile // Microsoft does recommend that // https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/obtaining-hid-reports - let res = ReadFile(self.handle, Some(&mut buf), Some(&mut bytes_read), None); - debug!(" Success: {:?}, Bytes: {}", res, bytes_read); + if let Err(err) = ReadFile(self.handle, Some(&mut buf), Some(&mut bytes_read), None) { + error!("Failed to read from touchscreen: {:?}", err); + return None; + } + debug!(" Bytes: {}", bytes_read); debug!(" Read buf: {:X?}", buf); - debug!(" Read msg: {:X?}", msg); + } + + // Without this the zero-initialized buffer would be returned as if the + // device had answered + if (bytes_read as usize) < msg_len + read_len { + error!( + "Touchscreen only returned {} B, expected at least {} B", + bytes_read, + msg_len + read_len + ); + return None; } Some(buf[msg_len..msg_len + read_len].to_vec()) } fn get_stylus_fw(&self) -> Option<()> { - let mut msg = [0u8; 0x40]; + let mut msg = [0u8; REPORT_LEN]; msg[0] = REPORT_ID_FIRMWARE; unsafe { let success = HidD_GetFeature(self.handle, msg.as_mut_ptr() as _, msg.len() as u32); debug!(" Success: {}", success); + if !success { + error!("Failed to get stylus firmware report"); + return None; + } } println!("Stylus firmware: {:X?}", msg); - let mut msg = [0u8; 0x40]; + let mut msg = [0u8; REPORT_LEN]; msg[0] = REPORT_ID_USI_VER; unsafe { let success = HidD_GetFeature(self.handle, msg.as_mut_ptr() as _, msg.len() as u32); debug!(" Success: {}", success); + if !success { + error!("Failed to get USI version report"); + return None; + } } println!("USI Version: {:X?}", msg); diff --git a/framework_tool/completions/bash/framework_tool b/framework_tool/completions/bash/framework_tool index 9806ab61..b53cd9a2 100755 --- a/framework_tool/completions/bash/framework_tool +++ b/framework_tool/completions/bash/framework_tool @@ -206,7 +206,7 @@ _framework_tool() { return 0 ;; --driver) - COMPREPLY=($(compgen -W "portio cros-ec windows" -- "${cur}")) + COMPREPLY=($(compgen -W "portio cros-ec" -- "${cur}")) return 0 ;; --pd-addrs) diff --git a/framework_tool/completions/fish/framework_tool.fish b/framework_tool/completions/fish/framework_tool.fish index 129cead3..4143ebac 100644 --- a/framework_tool/completions/fish/framework_tool.fish +++ b/framework_tool/completions/fish/framework_tool.fish @@ -72,9 +72,8 @@ cancel-jump\t'' disable-jump\t''" complete -c framework_tool -l ec-hib-delay -d 'Get or set EC hibernate delay (S5 to G3)' -r complete -c framework_tool -l hash -d 'Hash a file of arbitrary data' -r -F -complete -c framework_tool -l driver -d 'Select which driver is used. By default portio is used' -r -f -a "portio\t'' -cros-ec\t'' -windows\t''" +complete -c framework_tool -l driver -d 'Select which driver is used to talk to the EC. Defaults to the first available one' -r -f -a "portio\t'' +cros-ec\t''" complete -c framework_tool -l pd-addrs -d 'Specify I2C addresses of the PD chips (Advanced)' -r complete -c framework_tool -l pd-ports -d 'Specify I2C ports of the PD chips (Advanced)' -r complete -c framework_tool -l flash-gpu-descriptor-file -d 'File to write to the gpu EEPROM' -r -F diff --git a/framework_tool/completions/zsh/_framework_tool b/framework_tool/completions/zsh/_framework_tool index c820518b..2c204bb6 100644 --- a/framework_tool/completions/zsh/_framework_tool +++ b/framework_tool/completions/zsh/_framework_tool @@ -59,7 +59,7 @@ _framework_tool() { '--reboot-ec=[Control EC RO/RW jump]:REBOOT_EC:(reboot jump-ro jump-rw cancel-jump disable-jump)' \ '--ec-hib-delay=[Get or set EC hibernate delay (S5 to G3)]::EC_HIB_DELAY:_default' \ '--hash=[Hash a file of arbitrary data]:HASH:_files' \ -'--driver=[Select which driver is used. By default portio is used]:DRIVER:(portio cros-ec windows)' \ +'--driver=[Select which driver is used to talk to the EC. Defaults to the first available one]:DRIVER:(portio cros-ec)' \ '*--pd-addrs=[Specify I2C addresses of the PD chips (Advanced)]:PD_ADDRS:_default:PD_ADDRS:_default:PD_ADDRS:_default' \ '*--pd-ports=[Specify I2C ports of the PD chips (Advanced)]:PD_PORTS:_default:PD_PORTS:_default:PD_PORTS:_default' \ '--flash-gpu-descriptor-file=[File to write to the gpu EEPROM]:FLASH_GPU_DESCRIPTOR_FILE:_files' \ diff --git a/framework_tool/framework_tool.1 b/framework_tool/framework_tool.1 index 8e3f6ceb..13fc6cfc 100644 --- a/framework_tool/framework_tool.1 +++ b/framework_tool/framework_tool.1 @@ -397,7 +397,7 @@ Show saved EC panic info Hash a file of arbitrary data .TP \fB\-\-driver\fR \fI\fR -Select which driver is used. By default portio is used +Select which driver is used to talk to the EC. Defaults to the first available one .br .br @@ -407,8 +407,6 @@ Select which driver is used. By default portio is used portio .IP \(bu 2 cros\-ec -.IP \(bu 2 -windows .RE .TP \fB\-\-pd\-addrs\fR \fI...\fR