From 243ed69e549b2549d0a2a50f77bfa1fed269e314 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Harabie=C5=84?= Date: Tue, 17 Jan 2023 00:44:08 +0100 Subject: [PATCH] Fix `format_volume` panic in debug build for small FAT12 volumes Backport of 50b8dec36ab664b02d7532422a164e47144eecac --- CHANGELOG.md | 3 ++- src/boot_sector.rs | 9 +++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a63eb4a..78a2b32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,8 @@ Changelog 0.3.6 (not released yet) ------------------------ Bug fixes: -* Create directory entry with `VOLUME_ID` attribute when formatting if volume label was set in `FormatVolumeOptions`. +* Create directory entry with `VOLUME_ID` attribute when formatting if volume label was set in `FormatVolumeOptions` +* Fix `format_volume` function panicking in debug build for FAT12 volumes with size below 1 MB 0.3.5 (2021-01-23) ------------------------ diff --git a/src/boot_sector.rs b/src/boot_sector.rs index 4faf13a..0fd80da 100644 --- a/src/boot_sector.rs +++ b/src/boot_sector.rs @@ -449,8 +449,12 @@ fn determine_bytes_per_cluster(total_bytes: u64, bytes_per_sector: u16, fat_type }, }; const MAX_CLUSTER_SIZE: u32 = 32 * KB as u32; - debug_assert!(bytes_per_cluster.is_power_of_two()); - cmp::min(cmp::max(bytes_per_cluster, bytes_per_sector as u32), MAX_CLUSTER_SIZE) + let bytes_per_cluster_clamped = cmp::min( + cmp::max(bytes_per_cluster, u32::from(bytes_per_sector)), + MAX_CLUSTER_SIZE, + ); + debug_assert!(bytes_per_cluster_clamped.is_power_of_two()); + bytes_per_cluster_clamped } fn determine_sectors_per_fat( @@ -727,6 +731,7 @@ mod tests { #[test] fn test_determine_bytes_per_cluster_fat12() { + assert_eq!(determine_bytes_per_cluster(128 * KB, 512, Some(FatType::Fat12)), 512); assert_eq!(determine_bytes_per_cluster(1 * MB + 0, 512, Some(FatType::Fat12)), 512); assert_eq!(determine_bytes_per_cluster(1 * MB + 1, 512, Some(FatType::Fat12)), 1024); assert_eq!(determine_bytes_per_cluster(1 * MB, 4096, Some(FatType::Fat12)), 4096);