Skip to main content

exfat_slim/
file_system.rs

1use aligned::Aligned;
2
3#[cfg(feature = "alloc")]
4use alloc::{string::String, vec::Vec};
5
6use super::{
7    BlockDevice,
8    allocation::{AllocationBitmap, Allocator, SearchPolicy, StoredChain},
9    bisync,
10    boot_sector::BootSector,
11    directory::{DirectoryIterator, ExactNameFilter, directory_list, get_leaf_file_entry},
12    directory_entry::{
13        AllocationBitmapDirEntry, DirSetWriter, DirectoryEntryChain, EntryType, FileAttributes,
14        FileDirEntry, FileNameDirEntry, GeneralSecondaryFlags, Location, RAW_ENTRY_LEN,
15        RawDirEntry, StreamExtensionDirEntry, UpcaseTableDirEntry, VolumeLabelDirEntry,
16        is_end_of_directory,
17    },
18    error::ExFatError,
19    fat::Fat,
20    file::{
21        File, FileDetails, FileDirty, NO_CLUSTER_ID, OpenOptions, Touched, TouchedKind,
22        TouchedSector,
23    },
24    slot_cache::SlotCache,
25    upcase_table::UpcaseTable,
26    utils::{Utf16Chunks, calc_dir_entry_set_len, encode_utf16_upcase_and_hash, split_path},
27};
28use crate::timestamp::{EncodedTimestamp, Timestamp};
29
30pub type ExFatResult<T, D, const SIZE: usize> =
31    core::result::Result<T, ExFatError<<D as BlockDevice<SIZE>>::Error>>;
32
33#[cfg_attr(feature = "defmt", derive(defmt::Format))]
34#[derive(Debug, Clone)]
35pub(crate) struct FileSystemDetails {
36    /// volume-relative sector offset of the cluster heap
37    pub cluster_heap_offset: u32,
38
39    /// volume-relative sector offset of the first FAT
40    pub fat_offset: u32,
41
42    /// number of sectors per cluster (64 is normal for an SD card of 8GB - that equates to 32KB per cluster)
43    pub sectors_per_cluster: u32,
44
45    /// number of bytes in a cluster
46    pub cluster_length: u32,
47
48    /// number of clusters in the cluster heap
49    pub cluster_count: u32,
50
51    /// first cluster of root directory
52    pub first_cluster_of_root_dir: u32,
53}
54
55impl FileSystemDetails {
56    pub(crate) const fn empty() -> Self {
57        Self {
58            cluster_heap_offset: 0,
59            fat_offset: 0,
60            sectors_per_cluster: 64,
61            cluster_length: 32768,
62            cluster_count: 0,
63            first_cluster_of_root_dir: 0,
64        }
65    }
66
67    pub(crate) fn new(boot_sector: &BootSector) -> Self {
68        let cluster_length = boot_sector.bytes_per_sector as u32 * boot_sector.sectors_per_cluster;
69        Self {
70            cluster_heap_offset: boot_sector.cluster_heap_offset,
71            sectors_per_cluster: boot_sector.sectors_per_cluster,
72            cluster_length,
73            cluster_count: boot_sector.cluster_count,
74            fat_offset: boot_sector.fat_offset,
75            first_cluster_of_root_dir: boot_sector.first_cluster_of_root_dir,
76        }
77    }
78
79    pub(crate) fn get_heap_sector_id<D, const SIZE: usize>(
80        &self,
81        cluster_id: u32,
82    ) -> ExFatResult<u32, D, SIZE>
83    where
84        D: BlockDevice<SIZE>,
85    {
86        if cluster_id < 2 {
87            return Err(ExFatError::InvalidClusterId(cluster_id));
88        }
89
90        let sector_id = self.cluster_heap_offset + (cluster_id - 2) * self.sectors_per_cluster;
91        Ok(sector_id)
92    }
93}
94
95#[cfg_attr(feature = "defmt", derive(defmt::Format))]
96#[derive(Debug)]
97pub struct FileSystem<D, const SIZE: usize, const N: usize>
98where
99    D: BlockDevice<SIZE>,
100{
101    pub(crate) dev: D,
102    pub(crate) is_mounted: bool,
103    pub(crate) fs: FileSystemDetails,
104    pub(crate) upcase_table: UpcaseTable,
105    pub(crate) allocator: Allocator<D, SIZE, N>,
106    pub(crate) fat: Fat<D, SIZE, N>,
107    pub(crate) data_blocks: SlotCache<D, SIZE, N>,
108    pub(crate) time_provider: Option<fn() -> Timestamp>,
109}
110
111pub(crate) struct FileSystemMetadata<const SIZE: usize> {
112    details: FileSystemDetails,
113    upcase_table: UpcaseTable,
114    alloc_bitmap: AllocationBitmap<SIZE>,
115}
116
117impl<D, const SIZE: usize, const N: usize> FileSystem<D, SIZE, N>
118where
119    D: BlockDevice<SIZE>,
120{
121    pub fn new(io: D) -> Self {
122        let fs = FileSystemDetails::empty();
123        let upcase_table = UpcaseTable::empty();
124        let fat = Fat::new();
125        let allocator = Allocator::new();
126        let data_blocks: SlotCache<D, SIZE, N> = SlotCache::new();
127
128        Self {
129            dev: io,
130            fs,
131            upcase_table,
132            is_mounted: false,
133            fat,
134            allocator,
135            data_blocks,
136            time_provider: None,
137        }
138    }
139
140    pub fn into_inner(self) -> D {
141        self.dev
142    }
143
144    /// Sets the time provider for file and directory timestamps
145    pub fn set_time_provider(&mut self, time_provider: fn() -> Timestamp) {
146        self.time_provider = Some(time_provider)
147    }
148
149    pub(crate) fn get_current_timestamp(&self) -> EncodedTimestamp {
150        match self.time_provider.as_ref() {
151            Some(get_timestamp) => {
152                let timestamp = get_timestamp();
153                timestamp.encode()
154            }
155            None => EncodedTimestamp::default(),
156        }
157    }
158
159    /// Calling this is optional as the file system will be automatically mounted upon first use if it is not already mounted
160    /// Reads the boot sector using the block device and initializes the file system returning an instance of it
161    #[bisync]
162    pub async fn mount(&mut self) -> ExFatResult<(), D, SIZE> {
163        if self.is_mounted {
164            return Ok(());
165        }
166
167        let FileSystemMetadata {
168            details,
169            upcase_table,
170            alloc_bitmap,
171        } = read_file_system_metadata(&mut self.dev).await?;
172        self.fat.start_of_fat_sector = Some(details.fat_offset);
173        self.allocator.bitmap.cluster_count = details.cluster_count;
174        self.fs = details;
175        self.allocator.bitmap.first_sector = self
176            .fs
177            .get_heap_sector_id::<D, SIZE>(alloc_bitmap.first_cluster)?;
178        self.allocator.bitmap.num_sectors = alloc_bitmap.num_sectors;
179
180        self.upcase_table = upcase_table;
181        self.is_mounted = true;
182        Ok(())
183    }
184
185    #[bisync]
186    pub async fn open(&mut self, path: &str, options: OpenOptions) -> ExFatResult<File, D, SIZE> {
187        self.mount().await?;
188
189        // attempt to get the file details
190        let file_details = self
191            .find_file_or_directory(path, Some(FileAttributes::Archive))
192            .await;
193
194        // get file details or create if required
195        let file_details = match file_details {
196            Ok(mut file_details) => {
197                if options.create_new {
198                    return Err(ExFatError::AlreadyExists);
199                }
200
201                if options.truncate {
202                    self.truncate_file(&mut file_details, 0).await?;
203                }
204
205                file_details
206            }
207            Err(ExFatError::FileNotFound) => {
208                if options.create || options.create_new {
209                    self.create_file(path).await?
210                } else {
211                    return Err(ExFatError::FileNotFound);
212                }
213            }
214            Err(e) => return Err(e),
215        };
216
217        let chain = self.get_stored_chain(&file_details).await?;
218        let cluster_id = if options.append {
219            match &chain {
220                StoredChain::Empty => file_details.first_cluster,
221                StoredChain::Contiguous {
222                    first,
223                    cluster_count,
224                } => first + cluster_count - 1,
225                StoredChain::Fat {
226                    first: _first,
227                    last,
228                    cluster_count: _cluster_count,
229                } => *last,
230            }
231        } else {
232            file_details.first_cluster
233        };
234
235        Ok(File::new(
236            &file_details,
237            cluster_id,
238            self.fs.cluster_length,
239            options,
240            chain,
241        ))
242    }
243
244    /// Returns true if the file or directory exists
245    ///
246    /// Symbolic link following is not supported
247    #[bisync]
248    pub async fn exists(&mut self, path: &str) -> ExFatResult<bool, D, SIZE> {
249        self.mount().await?;
250
251        match self.find_file_or_directory(path, None).await {
252            Ok(_file) => Ok(true),
253            Err(ExFatError::FileNotFound) => Ok(false),
254            Err(ExFatError::DirectoryNotFound) => Ok(false),
255            Err(e) => Err(e),
256        }
257    }
258
259    /// Reads the entire contents of the file into a byte vector
260    ///
261    /// Supports nested paths
262    #[cfg(feature = "alloc")]
263    #[bisync]
264    pub async fn read(&mut self, path: &str) -> ExFatResult<Vec<u8>, D, SIZE> {
265        self.mount().await?;
266        let options = OpenOptions::new().read(true);
267        let mut file = self.open(path, options).await?;
268        let mut buf = Vec::new();
269        file.read_to_end(self, &mut buf).await?;
270        file.close(self).await?;
271        Ok(buf)
272    }
273
274    /// Reads the entire contents of the file into a string
275    ///
276    /// Supports nested paths
277    #[cfg(feature = "alloc")]
278    #[bisync]
279    pub async fn read_to_string(&mut self, path: &str) -> ExFatResult<String, D, SIZE> {
280        self.mount().await?;
281        let options = OpenOptions::new().read(true);
282        let mut file = self.open(path, options).await?;
283        let s = file.read_to_string(self).await?;
284        file.close(self).await?;
285        Ok(s)
286    }
287
288    /// Returns an iterator over the entries in a directory
289    ///
290    /// Supports nested paths
291    #[bisync]
292    pub async fn read_dir(&mut self, path: &str) -> ExFatResult<DirectoryIterator<SIZE>, D, SIZE> {
293        self.mount().await?;
294        directory_list(self, path).await
295    }
296
297    /// Deletes a file
298    ///
299    /// Returns an error if the file does not exist or something else failed
300    #[bisync]
301    pub async fn remove_file(&mut self, path: &str) -> ExFatResult<(), D, SIZE> {
302        self.mount().await?;
303        let file_details = self
304            .find_file_inner(path, Some(FileAttributes::Archive))
305            .await?;
306        self.delete_inner(&file_details).await?;
307        Ok(())
308    }
309
310    /// Creates a directory recursively
311    ///
312    /// The dir path can be nested
313    #[bisync]
314    pub async fn create_directory(&mut self, path: &str) -> ExFatResult<(), D, SIZE> {
315        self.mount().await?;
316        let mut touched = FileDirty::new();
317
318        // find directory or recursively create it if it does not already exist
319        let _cluster_id = self.get_or_create_directory(&mut touched, path).await?;
320
321        touched.flush(self).await?;
322        Ok(())
323    }
324
325    /// Copies a file from one file to another
326    ///
327    /// If directories in the to_path do not exist they will be created
328    /// File attributes will also be copied but timestamps will be new
329    #[bisync]
330    pub async fn copy(&mut self, from_path: &str, to_path: &str) -> ExFatResult<(), D, SIZE> {
331        self.mount().await?;
332        if from_path == to_path {
333            return Err(ExFatError::InvalidFileName {
334                reason: "cannot copy file to the same exact location",
335            });
336        }
337        let options = OpenOptions::new().read(true);
338        let mut file = self.open(from_path, options).await?;
339        file.copy_to(self, to_path).await?;
340        file.close(self).await?;
341        Ok(())
342    }
343
344    /// Rename a file or folder (also know as `move`)
345    ///
346    /// The from_path is the old file or directory path (including all sub directories)
347    /// The to_path is the new file or directory path (including all sub directories)
348    /// If the file or directory changes parent directories then this is considered to be a file move, otherwise a rename
349    /// If the to_path contains directories that don't yet exist they will be created.
350    #[bisync]
351    pub async fn rename(&mut self, from_path: &str, to_path: &str) -> ExFatResult<(), D, SIZE> {
352        self.mount().await?;
353
354        // in exFAT a directory cannot have a directory and file with the same name in it so no need to filter here
355        let file_details = self.find_file_inner(from_path, None).await?;
356
357        // don't allow moving to a file that already exists
358        if self.find_file_inner(to_path, None).await.is_ok() {
359            return Err(ExFatError::AlreadyExists);
360        }
361
362        let mut touched = FileDirty::new();
363        let (dir_path, file_or_dir_name) = split_path(to_path);
364
365        // find directory or recursively create it if it does not already exist
366        let directory_cluster_id = self.get_or_create_directory(&mut touched, dir_path).await?;
367
368        // create a new dir entry and point it at the same file or directory as the old one
369        self.create_file_dir_entry_at(
370            &mut touched,
371            file_or_dir_name,
372            directory_cluster_id,
373            file_details.first_cluster,
374            file_details.attributes,
375            file_details.flags,
376            file_details.valid_data_length,
377            file_details.data_length,
378        )
379        .await?;
380
381        // remove the old dir entry
382        let num_entries = file_details.secondary_count as usize + 1;
383        self.mark_directory_entry_set_unused(&mut touched, file_details.location, num_entries)
384            .await?;
385
386        touched.flush(self).await?;
387
388        Ok(())
389    }
390
391    /// Removes an empty directory
392    ///
393    /// Will return an error if the directory does not exist or is not empty
394    #[bisync]
395    pub async fn remove_dir(&mut self, path: &str) -> ExFatResult<(), D, SIZE> {
396        self.mount().await?;
397        let file_details = self
398            .find_file_inner(path, Some(FileAttributes::Directory))
399            .await?;
400        self.delete_inner(&file_details).await?;
401        Ok(())
402    }
403
404    /// Writes the entire contents to a file.
405    ///
406    /// The file will be overwritten if it already exists.
407    /// This function will create any directories in the path that do not already exist.
408    /// Relative paths are not supported.
409    #[bisync]
410    pub async fn write(
411        &mut self,
412        path: &str,
413        contents: impl AsRef<[u8]>,
414    ) -> ExFatResult<(), D, SIZE> {
415        self.mount().await?;
416        let options = OpenOptions::new().create(true).truncate(true).write(true);
417        let mut file = self.open(path, options).await?;
418        file.write(self, contents.as_ref()).await?;
419        file.close(self).await?;
420        Ok(())
421    }
422
423    #[bisync]
424    pub(crate) async fn get_stored_chain(
425        &mut self,
426        file_details: &FileDetails,
427    ) -> ExFatResult<StoredChain, D, SIZE> {
428        let no_fat_chain = file_details
429            .flags
430            .contains(GeneralSecondaryFlags::NoFatChain);
431        let cluster_count = file_details
432            .data_length
433            .div_ceil(self.fs.cluster_length as u64) as u32;
434        let is_empty = file_details.first_cluster == NO_CLUSTER_ID || cluster_count == 0;
435
436        let chain = if is_empty {
437            StoredChain::Empty
438        } else if no_fat_chain {
439            StoredChain::Contiguous {
440                first: file_details.first_cluster,
441                cluster_count,
442            }
443        } else {
444            let last = self
445                .get_cluster_id_at(file_details.data_length, file_details)
446                .await?;
447            StoredChain::Fat {
448                first: file_details.first_cluster,
449                last,
450                cluster_count,
451            }
452        };
453
454        Ok(chain)
455    }
456
457    #[bisync]
458    pub(crate) async fn find_file_or_directory(
459        &mut self,
460        path: &str,
461        file_attributes: Option<FileAttributes>,
462    ) -> ExFatResult<FileDetails, D, SIZE> {
463        let file_details = self.find_file_inner(path, file_attributes).await?;
464        Ok(file_details)
465    }
466
467    // TODO: figure out visibility (pub or private)
468    #[bisync]
469    pub(crate) async fn find_file_inner(
470        &mut self,
471        path: &str,
472        file_attributes: Option<FileAttributes>,
473    ) -> ExFatResult<FileDetails, D, SIZE> {
474        match get_leaf_file_entry(self, path, file_attributes).await? {
475            Some(file_details) => Ok(file_details),
476            None => Err(ExFatError::FileNotFound),
477        }
478    }
479
480    /// Sets a file to length specified and allocates or frees up all the clusters linked to the file
481    /// If length is set to zero then only the first cluster in the file will be allocated.
482    #[bisync]
483    pub(crate) async fn truncate_file(
484        &mut self,
485        file_details: &mut FileDetails,
486        length: u64,
487    ) -> ExFatResult<(), D, SIZE> {
488        // TODO: support length greater than 0 for preallocated files
489        if length > 0 {
490            unimplemented!("length greater than 0 not yet supported")
491        }
492        let mut touched = FileDirty::new();
493
494        // capture the original chain before changes
495        let stored_chain = self.get_stored_chain(file_details).await?;
496
497        file_details.data_length = length;
498        file_details.valid_data_length = file_details.valid_data_length.min(length);
499        file_details.first_cluster = NO_CLUSTER_ID;
500
501        let mut chain = DirectoryEntryChain::new_from_file_details(file_details, &self.fs);
502        let mut count = 0;
503        let mut dir_set_writer = DirSetWriter::new(file_details.location);
504        let mut file_dir: Option<RawDirEntry> = None;
505
506        while let Some((dir_entry, _location)) = chain.next(self).await? {
507            match count {
508                0 => {
509                    // file dir
510                    dir_set_writer.add_no_write::<SIZE>(dir_entry, true);
511                    let mut raw = [0u8; RAW_ENTRY_LEN];
512                    raw.copy_from_slice(dir_entry);
513                    file_dir = Some(raw);
514                }
515                1 => {
516                    // stream ext
517                    let mut stream_ext: StreamExtensionDirEntry = dir_entry.into();
518                    stream_ext.data_length = file_details.data_length;
519                    stream_ext.valid_data_length = file_details.valid_data_length;
520                    stream_ext.first_cluster = file_details.first_cluster;
521                    dir_set_writer
522                        .add(self, &mut touched, &stream_ext.serialize(), false)
523                        .await?;
524                }
525                _ => {
526                    // file name
527                    dir_set_writer.add_no_write::<SIZE>(dir_entry, false);
528                }
529            }
530
531            count += 1;
532        }
533
534        if let Some(file_dir) = file_dir {
535            dir_set_writer.finish(self, &mut touched, &file_dir).await?;
536        }
537
538        // set file length to 0
539        file_details.data_length = length;
540        file_details.valid_data_length = file_details.valid_data_length.min(length);
541
542        // mark all clusters as free - use the originally captured chain from the beginning
543        self.allocator
544            .free(&mut self.dev, &mut touched, &mut self.fat, &stored_chain)
545            .await?;
546
547        touched.flush(self).await?;
548
549        Ok(())
550    }
551
552    #[bisync]
553    pub(crate) async fn create_file(&mut self, path: &str) -> ExFatResult<FileDetails, D, SIZE> {
554        let (dir_path, file_or_dir_name) = split_path(path);
555        let mut touched = FileDirty::new();
556
557        // find directory or recursively create it if it does not already exist
558        let directory_cluster_id = self.get_or_create_directory(&mut touched, dir_path).await?;
559        let flags = GeneralSecondaryFlags::AllocationPossible | GeneralSecondaryFlags::NoFatChain;
560
561        let attributes = FileAttributes::Archive;
562        let first_cluster = NO_CLUSTER_ID; // sentinel value for no allocation
563        let file_details = self
564            .create_file_dir_entry_at(
565                &mut touched,
566                file_or_dir_name,
567                directory_cluster_id,
568                first_cluster,
569                attributes,
570                flags,
571                0,
572                0,
573            )
574            .await?;
575
576        touched.flush(self).await?;
577
578        Ok(file_details)
579    }
580
581    #[bisync]
582    async fn zero_cluster(
583        &mut self,
584        touched: &mut impl Touched,
585        cluster_id: u32,
586    ) -> ExFatResult<(), D, SIZE> {
587        let first_sector = self.fs.get_heap_sector_id::<D, SIZE>(cluster_id)?;
588        for sector_id in first_sector..first_sector + self.fs.sectors_per_cluster {
589            let slot = self.data_blocks.read_mut(sector_id, &mut self.dev).await?;
590            slot.as_mut_slice().fill(0);
591            touched.insert(TouchedSector::new(TouchedKind::Dir, sector_id));
592        }
593
594        Ok(())
595    }
596
597    #[bisync]
598    pub(crate) async fn get_or_create_directory(
599        &mut self,
600        touched: &mut impl Touched,
601        path: &str,
602    ) -> ExFatResult<u32, D, SIZE> {
603        let mut names = path_to_iter(path).peekable();
604        let mut cluster_id = self.fs.first_cluster_of_root_dir;
605
606        while let Some(dir_name) = names.next() {
607            let is_last = names.peek().is_none();
608
609            let filter = ExactNameFilter::new(
610                dir_name,
611                &self.upcase_table,
612                Some(FileAttributes::Directory),
613            )
614            .map_err(|e| ExFatError::InvalidFileName { reason: e })?;
615            let mut entries = DirectoryEntryChain::new(cluster_id, &self.fs);
616            let file_details = entries.next_file_entry(self, &filter, None).await?;
617
618            match file_details {
619                Some((file_details, _)) => {
620                    // directory already exists
621                    cluster_id = file_details.first_cluster;
622                }
623                None => {
624                    // directory does not exist, create it
625                    let run = self
626                        .allocator
627                        .find_free_clusters(&mut self.dev, None, 1, SearchPolicy::LongestRun)
628                        .await?;
629                    self.allocator
630                        .mark_allocated(&mut self.dev, touched, &run, true)
631                        .await?;
632
633                    // it is important to zero the data in a cluster that you want to use for a directory because
634                    // garbage data can be confused with an end-of-directory marker which causes problems
635                    self.zero_cluster(touched, run.first_cluster).await?;
636
637                    self.create_file_dir_entry_at(
638                        touched,
639                        dir_name,
640                        cluster_id,
641                        run.first_cluster,
642                        FileAttributes::Directory,
643                        GeneralSecondaryFlags::AllocationPossible
644                            | GeneralSecondaryFlags::NoFatChain,
645                        self.fs.cluster_length as u64,
646                        self.fs.cluster_length as u64,
647                    )
648                    .await?;
649
650                    cluster_id = run.first_cluster;
651                }
652            }
653
654            if is_last {
655                return Ok(cluster_id);
656            }
657        }
658
659        // return the root directory cluster
660        Ok(cluster_id)
661    }
662
663    // assume that the file dir entry does NOT already exist
664    // TODO: this is a fairly dangerous assumption, try to enforce it without redundant checks
665    // assume that name is valid
666    #[allow(clippy::too_many_arguments)]
667    #[bisync]
668    pub(crate) async fn create_file_dir_entry_at(
669        &mut self,
670        touched: &mut impl Touched,
671        name: &str,
672        directory_cluster_id: u32,
673        first_cluster: u32, // the directory or file that this entry points to
674        file_attributes: FileAttributes,
675        stream_ext_flags: GeneralSecondaryFlags,
676        valid_data_length: u64,
677        data_length: u64,
678    ) -> ExFatResult<FileDetails, D, SIZE> {
679        let (name_hash, file_name_char_count) =
680            encode_utf16_upcase_and_hash(name, &self.upcase_table)
681                .map_err(|e| ExFatError::InvalidFileName { reason: e })?;
682        let dir_entry_set_len = calc_dir_entry_set_len(file_name_char_count);
683        let location = self
684            .find_empty_dir_entry_set(directory_cluster_id, dir_entry_set_len)
685            .await?;
686        let location_copy = location;
687        let secondary_count = dir_entry_set_len as u8 - 1;
688
689        let mut dir_set_writer = DirSetWriter::new(location);
690        let timestamp = self.get_current_timestamp();
691
692        // write file directory entry set
693        let file = FileDirEntry {
694            secondary_count,
695            set_checksum: 0,
696            file_attributes,
697            create_timestamp: timestamp.packed,
698            last_modified_timestamp: timestamp.packed,
699            last_accessed_timestamp: timestamp.packed,
700            create_10ms_increment: timestamp.increment_10ms,
701            last_modified_10ms_increment: timestamp.increment_10ms,
702            create_utc_offset: timestamp.utc_offset,
703            last_modified_utc_offset: timestamp.utc_offset,
704            last_accessed_utc_offset: timestamp.utc_offset,
705        };
706        let file_dir = file.serialize();
707        dir_set_writer.add(self, touched, &file_dir, true).await?;
708
709        // write stream extension directory entry
710        let stream_ext = StreamExtensionDirEntry {
711            general_secondary_flags: stream_ext_flags,
712            name_length: file_name_char_count as u8,
713            name_hash,
714            valid_data_length,
715            first_cluster,
716            data_length,
717        };
718        dir_set_writer
719            .add(self, touched, &stream_ext.serialize(), false)
720            .await?;
721
722        // write file name directory entries chunked by 15 characters
723        let mut chunk_iter = Utf16Chunks::new(name);
724        loop {
725            let mut file_name = FileNameDirEntry {
726                general_secondary_flags: GeneralSecondaryFlags::empty(),
727                file_name: [0u16; 15],
728            };
729            if let Some(_len) = chunk_iter.next_chunk(&mut file_name.file_name) {
730                dir_set_writer
731                    .add(self, touched, &file_name.serialize(), false)
732                    .await?;
733            } else {
734                break;
735            }
736        }
737
738        dir_set_writer.finish(self, touched, &file_dir).await?;
739
740        let file_details = FileDetails {
741            attributes: file_attributes,
742            data_length,
743            valid_data_length,
744            first_cluster,
745            flags: stream_ext_flags,
746            location: location_copy,
747            secondary_count,
748            accessed: timestamp,
749            modified: timestamp,
750            created: timestamp,
751        };
752
753        Ok(file_details)
754    }
755
756    // do not make this public as it should only be used by the unmount mechanic
757    // since the file_system does not currently keep track of open files it cannot close them on flush.
758    // all public functions on the file_system like `write`` flush file system metadata anyway
759    #[bisync]
760    async fn flush(&mut self) -> ExFatResult<(), D, SIZE> {
761        self.fat.flush(&mut self.dev).await?;
762        self.allocator.flush(&mut self.dev).await?;
763        self.data_blocks.flush(&mut self.dev).await?;
764        Ok(())
765    }
766
767    /// unmounts the file system and returns the device back to the user.
768    /// IMPORTANT: it is up to the caller to ensure that all open files have been closed.
769    /// it is not necessary to unmount the file system for consistency for example if you need to reboot
770    /// However, a reboot SHOULD close all open files beforehand
771    #[bisync]
772    pub async fn unmount(mut self) -> D {
773        // as a defense in depth precaution we flush all the caches before unmounting
774        // however, this should not be necessary if the user closed all the files
775        // data may still be lost despite the flush below if files are not closed so don't rely on it.
776        if self.flush().await.is_err() {
777            crate::warn!("unmount: flushing leftover dirty sectors failed - possible data loss");
778        }
779
780        self.dev
781    }
782
783    #[bisync]
784    async fn mark_directory_entry_set_unused(
785        &mut self,
786        touched: &mut impl Touched,
787        location: Location,
788        num_entries: usize,
789    ) -> ExFatResult<(), D, SIZE> {
790        let mut sector_id = location.sector_id;
791        let mut offset = location.dir_entry_offset;
792        let entries_per_sector = SIZE / RAW_ENTRY_LEN;
793
794        for _ in 0..num_entries {
795            if offset == entries_per_sector {
796                // this assumes the set does not cross a cluster boundary (sectors within a cluster are contiguous)
797                // TODO: fix this when this crate adds the ability to create multi cluster directories
798                sector_id += 1;
799                offset = 0;
800            }
801
802            let slot = self.data_blocks.read_mut(sector_id, &mut self.dev).await?;
803            slot.as_mut_slice()[offset * RAW_ENTRY_LEN] &= 0x7F;
804            touched.insert(TouchedSector::new(TouchedKind::Dir, sector_id));
805
806            offset += 1;
807        }
808
809        Ok(())
810    }
811
812    #[bisync]
813    async fn get_cluster_id_at(
814        &mut self,
815        cursor: u64,
816        file_details: &FileDetails,
817    ) -> ExFatResult<u32, D, SIZE> {
818        if cursor == 0 {
819            return Ok(file_details.first_cluster);
820        }
821
822        let num_clusters = ((cursor - 1) / self.fs.cluster_length as u64) as u32;
823
824        if file_details
825            .flags
826            .contains(GeneralSecondaryFlags::NoFatChain)
827        {
828            Ok(file_details.first_cluster + num_clusters)
829        } else {
830            let mut cluster_id = file_details.first_cluster;
831            for _i in 0..num_clusters {
832                if let Some(x) = self
833                    .fat
834                    .next_cluster_in_fat_chain(cluster_id, &mut self.dev)
835                    .await?
836                {
837                    cluster_id = x;
838                } else {
839                    return Err(ExFatError::EndOfFatChain);
840                }
841            }
842            Ok(cluster_id)
843        }
844    }
845
846    #[bisync]
847    async fn confirm_has_no_children(
848        &mut self,
849        file_details: &FileDetails,
850    ) -> ExFatResult<(), D, SIZE> {
851        if file_details.attributes.contains(FileAttributes::Directory) {
852            let mut reader = DirectoryEntryChain::new(file_details.first_cluster, &self.fs);
853
854            while let Some((dir_entry, _location)) = reader.next(self).await? {
855                let entry_type_val = dir_entry[0];
856                match EntryType::from(entry_type_val) {
857                    EntryType::EndOfDirectory if is_end_of_directory(dir_entry) => break,
858                    EntryType::EndOfDirectory | EntryType::Unused(_) => continue,
859                    _ => return Err(ExFatError::DirectoryNotEmpty),
860                }
861            }
862        }
863
864        Ok(())
865    }
866
867    // the only difference between deleting a file and a directory is that we must
868    // first check tha the directory is empty.
869    #[bisync]
870    async fn delete_inner(&mut self, file_details: &FileDetails) -> ExFatResult<(), D, SIZE> {
871        self.confirm_has_no_children(file_details).await?;
872        let mut touched = FileDirty::new();
873
874        // TODO: if this is no-fat-chain then don't use the FAT
875        let chain = self.get_stored_chain(file_details).await?;
876        self.allocator
877            .free(&mut self.dev, &mut touched, &mut self.fat, &chain)
878            .await?;
879
880        let num_entries = file_details.secondary_count as usize + 1;
881        self.mark_directory_entry_set_unused(&mut touched, file_details.location, num_entries)
882            .await?;
883
884        touched.flush(self).await?;
885
886        Ok(())
887    }
888
889    #[bisync]
890    async fn find_empty_dir_entry_set(
891        &mut self,
892        cluster_id: u32,
893        dir_entry_set_len: usize,
894    ) -> ExFatResult<Location, D, SIZE> {
895        let mut entries = DirectoryEntryChain::new(cluster_id, &self.fs);
896        let mut counter = 0;
897        let mut start = None;
898        while let Some((entry, location)) = entries.next(self).await? {
899            let entry_type_val = entry[0];
900            match EntryType::from(entry_type_val) {
901                EntryType::EndOfDirectory | EntryType::Unused(_) => {
902                    if start.is_none() {
903                        start = Some(location)
904                    }
905                    counter += 1;
906
907                    if counter == dir_entry_set_len {
908                        break;
909                    }
910                }
911
912                _entry_type => {
913                    // slot taken, reset search run
914                    counter = 0;
915                    start = None
916                }
917            }
918        }
919
920        match start {
921            Some(location) => Ok(location),
922            None => Err(ExFatError::DirectoryFull),
923        }
924    }
925}
926
927fn path_to_iter(path: &str) -> impl Iterator<Item = &str> {
928    path.split(['/', '\\'])
929        .filter(|part| !part.is_empty())
930        .map(|c| c.trim())
931}
932
933#[bisync]
934async fn read_boot_sector<D, const SIZE: usize>(
935    io: &mut D,
936    sector_id: u32,
937) -> ExFatResult<BootSector, D, SIZE>
938where
939    D: BlockDevice<SIZE>,
940{
941    let mut data = [Aligned([0u8; SIZE])];
942    io.read(sector_id, &mut data)
943        .await
944        .map_err(ExFatError::Io)?;
945    let boot_sector: BootSector = (&data[0]).try_into()?;
946    // TODO: run checks
947    Ok(boot_sector)
948}
949
950#[bisync]
951pub(crate) async fn read_file_system_metadata<D, const SIZE: usize>(
952    io: &mut D,
953) -> ExFatResult<FileSystemMetadata<SIZE>, D, SIZE>
954where
955    D: BlockDevice<SIZE>,
956{
957    // the boot sector is always at sector_id 0 and everything is relative from there
958    // you need to offset the sector_id in your block device if there is a master boot record before this
959    let boot_sector = read_boot_sector(io, 0).await?;
960
961    let details = FileSystemDetails::new(&boot_sector);
962
963    let cluster_id = details.first_cluster_of_root_dir;
964    let sector_id = details.get_heap_sector_id::<D, SIZE>(cluster_id)?;
965    let mut data = [Aligned([0u8; SIZE])];
966    io.read(sector_id, &mut data)
967        .await
968        .map_err(ExFatError::Io)?;
969
970    let mut allocation_bitmap_dir_entry: Option<AllocationBitmapDirEntry> = None;
971    let mut volume_label: Option<VolumeLabelDirEntry> = None;
972    let mut upcase_table_dir_entry: Option<UpcaseTableDirEntry> = None;
973
974    let (chunks, _remainder) = data[0].as_chunks::<RAW_ENTRY_LEN>();
975
976    for chunk in chunks {
977        let entry_type_val = chunk[0];
978        match EntryType::from(entry_type_val) {
979            EntryType::AllocationBitmap => {
980                let entry: AllocationBitmapDirEntry = chunk.into();
981                allocation_bitmap_dir_entry = Some(entry);
982            }
983            EntryType::VolumeLabel => {
984                let entry: VolumeLabelDirEntry = chunk.try_into()?;
985                volume_label = Some(entry);
986            }
987            EntryType::UpcaseTable => {
988                let entry: UpcaseTableDirEntry = chunk.into();
989                upcase_table_dir_entry = Some(entry);
990            }
991            EntryType::EndOfDirectory if is_end_of_directory(chunk) => {
992                break;
993            }
994            _ => {} // ignore
995        }
996
997        if allocation_bitmap_dir_entry.is_some()
998            && upcase_table_dir_entry.is_some()
999            && volume_label.is_some()
1000        {
1001            break;
1002        }
1003    }
1004
1005    let upcase_table_dir_entry = match upcase_table_dir_entry {
1006        Some(entry) => entry,
1007        None => {
1008            return Err(ExFatError::InvalidFileSystem {
1009                reason: "no upcase table found in root dir",
1010            });
1011        }
1012    };
1013
1014    if volume_label.is_none() {
1015        return Err(ExFatError::InvalidFileSystem {
1016            reason: "no volume label found in root dir",
1017        });
1018    }
1019
1020    let allocation_bitmap_dir_entry = match allocation_bitmap_dir_entry {
1021        Some(entry) => entry,
1022        None => {
1023            return Err(ExFatError::InvalidFileSystem {
1024                reason: "no allocation bitmap found in root dir",
1025            });
1026        }
1027    };
1028
1029    let mut upcase_table = UpcaseTable::default();
1030    upcase_table
1031        .load(&upcase_table_dir_entry, &details, io)
1032        .await?;
1033
1034    let alloc_bitmap = AllocationBitmap::new(&allocation_bitmap_dir_entry);
1035    Ok(FileSystemMetadata {
1036        details,
1037        upcase_table,
1038        alloc_bitmap,
1039    })
1040}
1041
1042#[allow(unused)]
1043#[cfg(test)]
1044mod tests {
1045    use crate::{
1046        blocking::{directory::MAX_NAME_LEN, file_system},
1047        test_utils::{BLOCK_SIZE, DummyBlockDevice, empty_fs, list_names},
1048    };
1049
1050    use super::super::only_sync;
1051    use super::*;
1052    use aligned::Aligned;
1053    use alloc::{vec, vec::Vec};
1054
1055    #[only_sync]
1056    #[test]
1057    fn check_for_entry_type_mapping_errors() {
1058        // test every byte combination
1059        for b in 0..=u8::MAX {
1060            assert_eq!(EntryType::from(b).serialize(), b, "byte {b:#04x}");
1061        }
1062
1063        // test boundary conditions
1064        assert!(matches!(EntryType::from(0x05), EntryType::Unused(0x05)));
1065        assert!(matches!(EntryType::from(0x00), EntryType::EndOfDirectory));
1066        assert!(matches!(EntryType::from(0x85), EntryType::FileAndDirectory));
1067    }
1068
1069    // this ensures that deleting a directory entry does not make the dir entry scanner stop scanning
1070    // this would be the case if we simply write zeros (which would be interpreted as an end of directory marker)
1071    #[only_sync]
1072    #[test]
1073    fn removing_file_keeps_later_dir_entries_visible() {
1074        let mut fs = empty_fs();
1075        let create = OpenOptions::new().create(true).write(true);
1076        for name in ["a.txt", "b.txt", "c.txt"] {
1077            fs.open(name, create).unwrap().close(&mut fs).unwrap();
1078        }
1079
1080        // remove the first file in the dir
1081        fs.remove_file("a.txt").unwrap();
1082
1083        // check that b.txt and c.txt are still discoverable
1084        assert_eq!(list_names(&mut fs, ""), ["b.txt", "c.txt"]);
1085
1086        let root = &fs.dev.blocks[0];
1087        assert_eq!([root[0], root[32], root[64]], [0x05, 0x40, 0x41]);
1088        assert_eq!(&root[66..70], &[b'a', 0, b'.', 0], "payload untouched");
1089    }
1090
1091    #[only_sync]
1092    #[test]
1093    fn deleted_slot_is_reused_by_next_create() {
1094        let mut fs = empty_fs();
1095        let create = OpenOptions::new().create(true).write(true);
1096        for name in ["a.txt", "b.txt"] {
1097            fs.open(name, create).unwrap().close(&mut fs).unwrap();
1098        }
1099        fs.remove_file("a.txt").unwrap();
1100        fs.open("d.txt", create).unwrap().close(&mut fs).unwrap();
1101
1102        // if d.txt wasn't created in a.txt's place this wouldn't be a valid FileDirectoryEntryType
1103        assert_eq!(fs.dev.blocks[0][0], 0x85);
1104        assert_eq!(list_names(&mut fs, ""), ["d.txt", "b.txt"]);
1105    }
1106
1107    #[only_sync]
1108    #[test]
1109    fn can_remove_dir_after_contents_deleted() {
1110        let mut fs = empty_fs();
1111        fs.create_directory("my_dir").unwrap();
1112        let create = OpenOptions::new().create(true).write(true);
1113        fs.open("my_dir/a.txt", create)
1114            .unwrap()
1115            .close(&mut fs)
1116            .unwrap();
1117
1118        // attempt to delete a dir that is not empty should fail
1119        assert!(matches!(
1120            fs.remove_dir("my_dir"),
1121            Err(ExFatError::DirectoryNotEmpty)
1122        ));
1123
1124        // attempt to delete an empty dir should not fail and actually delete the directory
1125        fs.remove_file("my_dir/a.txt").unwrap();
1126        fs.remove_dir("my_dir").unwrap();
1127        assert!(!fs.exists("my_dir").unwrap());
1128    }
1129
1130    #[only_sync]
1131    #[test]
1132    fn renaming_a_file_keeps_later_entries_visible() {
1133        let mut fs = empty_fs();
1134        let create = OpenOptions::new().create(true).write(true);
1135        for name in ["a.txt", "b.txt", "c.txt"] {
1136            fs.open(name, create).unwrap().close(&mut fs).unwrap();
1137        }
1138
1139        fs.rename("a.txt", "z.txt").unwrap();
1140
1141        assert_eq!(list_names(&mut fs, ""), ["b.txt", "c.txt", "z.txt"]);
1142    }
1143
1144    #[only_sync]
1145    #[test]
1146    fn open_file_creates_empty_file() {
1147        let mut io = DummyBlockDevice::new(4);
1148        let mut fs = FileSystem::<_, _, 4>::new(io);
1149        fs.is_mounted = true;
1150        fs.fs.first_cluster_of_root_dir = 2;
1151        fs.upcase_table = UpcaseTable::default();
1152        let options = OpenOptions::new().create(true).write(true);
1153
1154        let file = fs.open("hello.txt", options).unwrap();
1155
1156        let dir_entries = &fs.dev.blocks[0][..32 * 3];
1157        #[rustfmt::skip]
1158        assert_eq!(
1159            dir_entries,
1160            &[
1161                133, 2, 114, 4, 32, 0, 0, 0, 0, 0, 33, 0, 0, 0, 33, 0, 0, 0, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1162                192, 3, 0, 9, 70, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
1163                193, 0, 104, 0, 101, 0, 108, 0, 108, 0, 111, 0, 46, 0, 116, 0, 120, 0, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1164            ]
1165        );
1166    }
1167
1168    #[only_sync]
1169    #[test]
1170    fn write_text_to_file() {
1171        // arrange
1172        let mut io = DummyBlockDevice::new(128); // 2 clusters
1173        io.blocks[1][0] = 1; // mark the first cluster (cluster 2) as allocated
1174        let mut fs = FileSystem::<_, _, 4>::new(io);
1175        fs.is_mounted = true;
1176        fs.fs.first_cluster_of_root_dir = 2;
1177        fs.upcase_table = UpcaseTable::default();
1178        fs.allocator.bitmap.first_sector = 1;
1179        fs.allocator.bitmap.num_sectors = 1;
1180        fs.allocator.bitmap.cluster_count = 2;
1181        let options = OpenOptions::new().create(true).write(true);
1182
1183        // act
1184        let mut file = fs.open("hello.txt", options).unwrap();
1185        file.write(&mut fs, b"world").unwrap();
1186        file.close(&mut fs).unwrap();
1187
1188        // check first 8 bits of the alloc bitmap
1189        // it was 0b0000_0001 before the file was allocated
1190        let alloc_bitmap = fs.dev.blocks[1][0];
1191        assert_eq!(alloc_bitmap, 0b0000_0011);
1192
1193        // check the first 3 directory entried of the root directory
1194        let dir_entries = &fs.dev.blocks[0][..32 * 3];
1195        #[rustfmt::skip]
1196        assert_eq!(
1197            dir_entries,
1198            &[
1199                133, 2, 84, 24, 32, 0, 0, 0, 0, 0, 33, 0, 0, 0, 33, 0, 0, 0, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1200                192, 3, 0, 9, 70, 48, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0,
1201                193, 0, 104, 0, 101, 0, 108, 0, 108, 0, 111, 0, 46, 0, 116, 0, 120, 0, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1202            ]
1203        );
1204
1205        // check the first sector of cluster 3
1206        // there are 64 sectors in a cluster here and clusters start at 2
1207        let data = &fs.dev.blocks[64][..5];
1208        assert_eq!(data, b"world");
1209    }
1210
1211    // only to be used with the removed_file_stays_removed_after_remount test
1212    #[only_sync]
1213    fn remount(io: DummyBlockDevice) -> FileSystem<DummyBlockDevice, BLOCK_SIZE, 4> {
1214        let mut fs = FileSystem::<_, _, 4>::new(io);
1215        fs.is_mounted = true;
1216        fs.fs.first_cluster_of_root_dir = 2;
1217        fs.upcase_table = UpcaseTable::default();
1218        fs.allocator.bitmap.first_sector = 1;
1219        fs.allocator.bitmap.cluster_count = 8;
1220        fs.allocator.bitmap.num_sectors = 1;
1221        fs
1222    }
1223
1224    // this ensures that the cache is cleared between remounts
1225    #[only_sync]
1226    #[test]
1227    fn removed_file_stays_removed_after_remount() {
1228        let mut fs = empty_fs();
1229        let options = OpenOptions::new().create(true).write(true);
1230        let mut file = fs.open("hello.txt", options).unwrap();
1231        file.write(&mut fs, b"foo").unwrap();
1232        file.close(&mut fs).unwrap();
1233
1234        let io = fs.unmount();
1235        let mut fs = remount(io);
1236        assert!(
1237            fs.exists("hello.txt").unwrap(),
1238            "created file lost by remount"
1239        );
1240
1241        fs.remove_file("hello.txt").unwrap();
1242        let io = fs.unmount();
1243        let mut fs = remount(io);
1244        assert!(
1245            !fs.exists("hello.txt").unwrap(),
1246            "deleted file survived remount indicating that cache was not cleared"
1247        );
1248    }
1249}