From 63d01e9d8eb6f3ccb6a96b7c577834276cf51add Mon Sep 17 00:00:00 2001 From: salmonik Date: Sat, 1 Aug 2026 03:44:57 +0200 Subject: Clean up warnings, fix FAT32 multi-cluster dirs, prep for edition 2024 Warning cleanup (cargo check + clippy now 0 across the workspace): - Migrate all 21 static_mut_refs sites to &raw mut accessors (fat, gop, ps2, vt, ahci, interrupts, memory) so edition 2024 won't deny them - panic = "abort" profiles: bare cargo check/build now works without nightly/-Zbuild-std - Wire TICKS in the timer ISR (it was never incremented, so the vt scroll batching trigger was dead code) - Clippy: efi_main becomes unsafe extern "efiapi" with a # Safety doc, KeyBuf::new uses inline-const array repeat (no interior-mutable const), editor main loop is a while-let, PIT control byte regrouped - [workspace.lints.clippy] allows result_unit_err + needless_range_loop (deliberate kernel style); large_enum_variant allowed on LineInput - Drop now-stale static_mut_refs allow from the rsdos bin FAT32 correctness fixes (both pre-existing, exposed by the SFN fix): - Unique 8.3 short names: to_8_3() never disambiguated collisions, so files sharing a long-name prefix got identical SFNs and fsck reported duplicate directory entries. Add dir_short_names() + unique_short_name() (~N tails, Windows-style) and force LFN when the SFN changes. - Multi-cluster directories: scan_dir/dir_short_names stopped at the first 0x00 slot, hiding every entry written into a chained cluster (writes failed with 'cannot write', duplicate SFNs accumulated); add_dir_entry now packs the cluster (0xE5 deleted-markers) before extending so other FAT readers (mtools, Windows) see the continuation too. Other: delete dead fields (Disk.fis, Volume.fat_count), drop timer_irq/ keyboard_irq/rendered, refresh_and_exit is a documented unsafe fn, CONTEXT .md corrected (stable toolchain, IRQ input, 4-crate layout), .gitignore excludes .pi-subagents artifacts. Validated: cargo check/clippy/fmt clean, make test-disk PASS on fresh and reused images (incl. two directory-chain extensions and ~10 SFN tails), editor round-trip smoke test PASS. --- rsnix/src/fat.rs | 130 ++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 105 insertions(+), 25 deletions(-) (limited to 'rsnix/src/fat.rs') diff --git a/rsnix/src/fat.rs b/rsnix/src/fat.rs index 52aa641..13d19df 100644 --- a/rsnix/src/fat.rs +++ b/rsnix/src/fat.rs @@ -38,7 +38,6 @@ struct Volume { uid: String, // unique mount name: "LABEL-XXXXXXXX" sectors_per_cluster: u8, reserved: u16, - fat_count: u8, fat_size: u32, // sectors per FAT root_cluster: u32, first_data: u32, // LBA of cluster 2 @@ -50,28 +49,36 @@ struct Volume { static mut VOLS: Vec = Vec::new(); static mut ACTIVE_VOL: usize = 0; +/// Raw-pointer accessors for the volume statics. The kernel is +/// single-threaded, so `&'static` refs are sound; the `addr_of_mut!` +/// round-trip keeps `static_mut_refs` (warn today, deny in edition +/// 2024) quiet. +fn vols() -> &'static mut Vec { + unsafe { &mut *core::ptr::addr_of_mut!(VOLS) } +} + +fn active_vol() -> &'static mut usize { + unsafe { &mut *core::ptr::addr_of_mut!(ACTIVE_VOL) } +} + pub fn volume_count() -> usize { - unsafe { VOLS.len() } + vols().len() } /// Unique mount name of volume `vol` ("RSDOS-5BD1E55F"). pub fn uid(vol: usize) -> &'static str { - unsafe { VOLS.get(vol) } - .map(|v| v.uid.as_str()) - .unwrap_or("") + vols().get(vol).map(|v| v.uid.as_str()).unwrap_or("") } pub fn root_cluster(vol: usize) -> u32 { - unsafe { VOLS.get(vol) } - .map(|v| v.root_cluster) - .unwrap_or(0) + vols().get(vol).map(|v| v.root_cluster).unwrap_or(0) } /// Point all FAT operations at volume `vol`; also selects the backing /// AHCI disk. Called by every public entry point (single-threaded /// kernel, so a process-wide "current volume" is fine). fn select_vol(vol: usize) -> Result<(), ()> { - let disk = unsafe { VOLS.get(vol) }.map(|v| v.disk).ok_or(())?; + let disk = vols().get(vol).map(|v| v.disk).ok_or(())?; unsafe { ACTIVE_VOL = vol; } @@ -97,7 +104,7 @@ fn write_sector(lba: u64, data: &[u8; SECTOR]) -> Result<(), ()> { // --- cluster math ---------------------------------------------------------- fn v() -> &'static mut Volume { - unsafe { VOLS.get_mut(ACTIVE_VOL) }.unwrap() + vols().get_mut(*active_vol()).unwrap() } fn spc() -> usize { @@ -351,13 +358,13 @@ fn scan_dir(dir_cluster: u32) -> Result, ()> { return Err(()); // loop protection on a corrupt chain } read_cluster(c, &mut buf)?; - let mut done = false; for (i, e) in buf.chunks_exact(32).enumerate() { match e[0] { - 0x00 => { - done = true; - break; - } + // 0x00 ends the entries in THIS cluster, not the whole + // directory: a dir that spills into a second cluster keeps + // its 0x00 marker in the first cluster, so we must keep + // walking the chain to see the rest. + 0x00 => break, 0xE5 => lfn.clear(), // deleted entry; drop any partial LFN _ => { let attr = e[11]; @@ -415,9 +422,6 @@ fn scan_dir(dir_cluster: u32) -> Result, ()> { } } } - if done { - break; - } cur = next_cluster(c).ok(); } Ok(items) @@ -729,10 +733,77 @@ fn to_8_3(name: &str) -> Option<([u8; 11], bool)> { Some((sfn, needs)) } +/// Collect the raw short names already present in a directory. +fn dir_short_names(parent: u32) -> Result, ()> { + let cs = cluster_size(); + let mut buf = vec![0u8; cs]; + let mut out = Vec::new(); + let mut cur: Option = Some(parent); + let mut guard = 0; + while let Some(c) = cur { + guard += 1; + if guard > 1_000_000 { + return Err(()); // loop protection on a corrupt chain + } + read_cluster(c, &mut buf)?; + for e in buf.chunks_exact(32) { + match e[0] { + // Same rule as scan_dir: 0x00 ends this cluster's entries + // but the directory may continue in the next cluster. + 0x00 => break, + 0xE5 => {} + _ => { + if e[11] != 0x0F { + let mut sfn = [0u8; 11]; + sfn.copy_from_slice(&e[0..11]); + out.push(sfn); + } + } + } + } + cur = next_cluster(c).ok(); + } + Ok(out) +} + +/// Make `base` unique within a directory: on collision, append a numeric +/// ~N tail (DISK-TE~1, DISK-TE~2, …) — the standard FAT short-name +/// disambiguation that fsck and other OSes expect. Without it, two files +/// whose long names share an 8.3 prefix would get the same short name and +/// fsck reports them as duplicate directory entries. +fn unique_short_name(base: &[u8; 11], used: &[[u8; 11]]) -> [u8; 11] { + if !used.contains(base) { + return *base; + } + let mut name_len = 0; + while name_len < 8 && base[name_len] != b' ' { + name_len += 1; + } + for n in 1..=999u32 { + let tail = alloc::format!("~{}", n); + let tb = tail.as_bytes(); + let keep = name_len.saturating_sub(tb.len()); + let mut cand = [b' '; 11]; + cand[..keep].copy_from_slice(&base[..keep]); + cand[keep..keep + tb.len()].copy_from_slice(tb); + cand[8..11].copy_from_slice(&base[8..11]); + if !used.contains(&cand) { + return cand; + } + } + *base // pathological; keep the colliding name +} + /// Write the LFN entries (if any) + SFN entry for `name` into the parent /// directory, extending its chain with a fresh zeroed cluster if needed. fn add_dir_entry(parent: u32, name: &str, is_dir: bool, cluster: u32) -> Result<(), ()> { - let (sfn, needs_lfn) = to_8_3(name).ok_or(())?; + let (base_sfn, mut needs_lfn) = to_8_3(name).ok_or(())?; + // Short names must be unique within the directory; a plain truncation + // collides when two long names share an 8.3 prefix. + let sfn = unique_short_name(&base_sfn, &dir_short_names(parent)?); + if sfn != base_sfn { + needs_lfn = true; // keep the original name via an LFN entry + } let lfn_chars: Vec = name.encode_utf16().collect(); let groups = if needs_lfn { lfn_chars.len().div_ceil(13) @@ -810,6 +881,18 @@ fn add_dir_entry(parent: u32, name: &str, is_dir: bool, cluster: u32) -> Result< write_cluster(c, &buf)?; return Ok(()); } + // Chain full: pack this cluster before extending. A mid-chain + // 0x00 would look like the end of the directory to other FAT + // readers (Windows, mtools stop at the first 0x00), hiding every + // entry written into the new cluster. Marking the free slots as + // 0xE5 (deleted) keeps them skippable while the chain walk finds + // the continuation. + for i in 0..slots { + if buf[i * 32] == 0x00 { + buf[i * 32] = 0xE5; + } + } + write_cluster(c, &buf)?; // Chain full: extend with a fresh zeroed cluster and retry. match next_cluster(c) { Ok(n) => cur = Some(n), @@ -910,10 +993,8 @@ pub fn init() -> bool { match try_mount(d) { Some(volume) => { let uid = volume.uid.clone(); - let vol = unsafe { - VOLS.push(volume); - VOLS.len() - 1 - }; + vols().push(volume); + let vol = vols().len() - 1; // Re-sync the FSInfo free-cluster count (may be stale // from earlier sessions). if select_vol(vol).is_ok() { @@ -1026,7 +1107,7 @@ fn try_mount(d: usize) -> Option { let mut uid = alloc::format!("{}-{:08X}", label, serial); let mut n = 2u32; loop { - let taken = unsafe { VOLS.iter() }.any(|v| v.uid == uid); + let taken = vols().iter().any(|v| v.uid == uid); if !taken { break; } @@ -1038,7 +1119,6 @@ fn try_mount(d: usize) -> Option { uid, sectors_per_cluster: spc, reserved, - fat_count, fat_size, root_cluster, first_data, -- cgit v1.2.3