Skip to main content

little_fs/
file_system.rs

1use core::ptr::null_mut;
2
3use super::{Configuration, Directory, convert_result, littlefs};
4use crate::{
5    File,
6    attributes::{self, InternalAttributes},
7    configuration::{self},
8    constants,
9};
10use alloc::{boxed::Box, ffi::CString};
11use file_system::{
12    AttributeFlags, AttributeOperations, Attributes, BaseOperations, Context, DirectBlockDevice,
13    DirectoryOperations, Entry, FileOperations, FileSystemOperations, Flags, IoErrorKind, Kind,
14    MountOperations, Path, Position, Result, Size, mount::MutexMountWrapper,
15};
16use synchronization::{Arc, blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
17
18// Duplicate contexts share a stable handle rather than copying native C caches.
19type SharedContext<T> = Arc<Mutex<CriticalSectionRawMutex, Box<T>>>;
20
21/// Mount and format options for [`FileSystem`].
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub struct Options {
24    /// Size of the read and program caches in bytes.
25    pub cache_size: usize,
26    /// Number of erase cycles before LittleFS evicts a metadata block for wear
27    /// levelling, or `None` for the LittleFS default (`-1`, wear levelling
28    /// disabled).
29    ///
30    /// LittleFS recommends values in the range `100`–`1000`. Flash-backed
31    /// devices should set this (for example, `Some(500)`), while RAM or
32    /// host-file storage can leave it unset.
33    pub block_cycles: Option<u16>,
34}
35
36impl Options {
37    /// Creates options with `cache_size` and `block_cycles` unset (`None`).
38    pub const fn new(cache_size: usize) -> Self {
39        Self {
40            cache_size,
41            block_cycles: None,
42        }
43    }
44
45    /// Sets the read and program cache size in bytes.
46    pub const fn set_cache_size(mut self, cache_size: usize) -> Self {
47        self.cache_size = cache_size;
48        self
49    }
50
51    /// Sets the metadata block wear-levelling cycle count.
52    pub const fn set_block_cycles(mut self, block_cycles: u16) -> Self {
53        self.block_cycles = Some(block_cycles);
54        self
55    }
56}
57
58pub struct FileSystem {
59    file_system: MutexMountWrapper<CriticalSectionRawMutex, MountedFileSystem>,
60}
61
62struct MountedFileSystem {
63    native: littlefs::lfs_t,
64    recovery_required: bool,
65}
66
67impl MountedFileSystem {
68    fn recover(&mut self) -> Result<()> {
69        if !self.recovery_required {
70            return Ok(());
71        }
72        if !self.native.mlist.is_null() {
73            return Err(IoErrorKind::InputOutput);
74        }
75
76        // Mount reads the committed move state from disk. Keep the old mount
77        // blocked if recovery fails, so the next operation can try again.
78        let mut recovered = littlefs::lfs_t::default();
79        unsafe {
80            convert_result(littlefs::lfs_mount(&mut recovered, self.native.cfg))?;
81            littlefs::lfs_unmount(&mut self.native);
82        }
83        self.native = recovered;
84        self.recovery_required = false;
85        Ok(())
86    }
87}
88
89impl FileSystem {
90    fn build_configuration(
91        device: &'static dyn DirectBlockDevice,
92        options: Options,
93    ) -> Result<littlefs::lfs_config> {
94        let block_size = device
95            .get_block_size()
96            .map_err(|_| IoErrorKind::InputOutput)?;
97        // LittleFS counts blocks in a 32-bit field. Reject a device with more
98        // blocks than it can address instead of truncating the count.
99        let block_count = u32::try_from(
100            device
101                .get_block_count()
102                .map_err(|_| IoErrorKind::InputOutput)?,
103        )
104        .map_err(|_| IoErrorKind::InvalidArgument)?;
105
106        let mut configuration = Configuration::new(
107            device,
108            block_size,
109            block_count,
110            options.cache_size,
111            options.cache_size,
112        )
113        .ok_or(IoErrorKind::InvalidArgument)?;
114
115        if let Some(block_cycles) = options.block_cycles {
116            configuration = configuration.set_block_cycles(block_cycles);
117        }
118
119        configuration
120            .try_into()
121            .map_err(|_| IoErrorKind::InvalidArgument)
122    }
123
124    pub fn new_format(device: &'static dyn DirectBlockDevice, options: Options) -> Result<Self> {
125        Self::format(device, options)?;
126
127        Self::new(device, options)
128    }
129
130    pub fn get_or_format(device: &'static dyn DirectBlockDevice, options: Options) -> Result<Self> {
131        match Self::new(device, options) {
132            Ok(file_system) => Ok(file_system),
133            Err(_) => {
134                device.set_position(0, &Position::Start(0))?;
135
136                Self::format(device, options)?;
137
138                Self::new(device, options)
139            }
140        }
141    }
142
143    pub fn new(device: &'static dyn DirectBlockDevice, options: Options) -> Result<Self> {
144        let configuration = Self::build_configuration(device, options)?;
145
146        let configuration = Box::new(configuration);
147
148        let mut file_system = littlefs::lfs_t::default();
149
150        unsafe {
151            convert_result(littlefs::lfs_mount(
152                &mut file_system,
153                Box::leak(configuration),
154            ))?;
155
156            let result = convert_result(littlefs::lfs_getattr(
157                &mut file_system,
158                c"/".as_ptr(),
159                InternalAttributes::IDENTIFIER,
160                null_mut(),
161                0,
162            ));
163
164            if let Err(IoErrorKind::MissingAttribute) = result {
165                // Set root attributes if not present
166                let mut internal_attributes = InternalAttributes::new();
167                internal_attributes.kind = Kind::Directory;
168
169                convert_result(littlefs::lfs_setattr(
170                    &mut file_system,
171                    c"/".as_ptr(),
172                    InternalAttributes::IDENTIFIER,
173                    &internal_attributes as *const _ as *const _,
174                    size_of::<InternalAttributes>() as u32,
175                ))?;
176            } else {
177                result?;
178            }
179        }
180
181        Ok(Self {
182            file_system: MutexMountWrapper::new_mounted(MountedFileSystem {
183                native: file_system,
184                recovery_required: false,
185            }),
186        })
187    }
188
189    pub fn format(device: &'static dyn DirectBlockDevice, options: Options) -> Result<()> {
190        let configuration = Self::build_configuration(device, options)?;
191
192        let mut file_system = littlefs::lfs_t::default();
193
194        convert_result(unsafe { littlefs::lfs_format(&mut file_system, &configuration) })?;
195
196        Ok(())
197    }
198
199    pub fn operation<T>(
200        &self,
201        operation: impl FnOnce(&mut littlefs::lfs_t) -> Result<T>,
202    ) -> Result<T> {
203        self.operation_with_mount(|mount| operation(&mut mount.native))
204    }
205
206    fn operation_with_mount<T>(
207        &self,
208        operation: impl FnOnce(&mut MountedFileSystem) -> Result<T>,
209    ) -> Result<T> {
210        let mut mount = self.file_system.try_get()?;
211        mount.recover()?;
212        let result = operation(&mut mount);
213        Self::drop_read_cache_on_error(&mut mount.native, &result);
214        result
215    }
216
217    fn drop_read_cache_on_error<T>(file_system: &mut littlefs::lfs_t, result: &Result<T>) {
218        // A failed device read can leave stale bytes under the failed block's
219        // cache key. Invalidate the cache before another operation uses it.
220        if matches!(
221            result,
222            Err(IoErrorKind::InputOutput | IoErrorKind::CorruptData)
223        ) {
224            attributes::drop_read_cache(file_system);
225        }
226    }
227
228    pub fn operation_with_context<I: 'static, T>(
229        &self,
230        context: &mut Context,
231        operation: impl FnOnce(&mut littlefs::lfs_t, &mut I) -> Result<T>,
232    ) -> Result<T> {
233        self.operation(|file_system| {
234            let file = context
235                .get_private_data_of_type::<SharedContext<I>>()
236                .ok_or(IoErrorKind::InvalidArgument)?;
237            let mut file = file.try_lock().map_err(|_| IoErrorKind::WouldBlock)?;
238            operation(file_system, &mut file)
239        })
240    }
241}
242
243unsafe impl Send for FileSystem {}
244unsafe impl Sync for FileSystem {}
245
246impl MountOperations for FileSystem {
247    /// Without open handles, sync the backing device, then `lfs_unmount` and
248    /// release the configuration; a failed sync leaves the filesystem mounted.
249    /// With open handles (a forced detach), only stop serving: their caches
250    /// stay allocated and their unsynchronized data is not committed.
251    fn unmount(&self) -> Result<()> {
252        let mut mount = self.file_system.try_get()?;
253        let file_system = &mut mount.native;
254        if file_system.mlist.is_null() {
255            // Directory updates are committed immediately; `lfs_unmount` only
256            // frees caches, so the backing device is synced explicitly first.
257            if unsafe { super::callbacks::flush_callback(file_system.cfg) } != 0 {
258                return Err(IoErrorKind::InputOutput);
259            }
260            convert_result(unsafe { littlefs::lfs_unmount(file_system) })?;
261            let mut configuration =
262                unsafe { Box::from_raw(file_system.cfg as *mut littlefs::lfs_config) };
263            unsafe {
264                configuration::Context::take_from_configuration(&mut *configuration);
265            }
266        }
267        drop(mount);
268        self.file_system.unmount()
269    }
270}
271
272impl FileSystemOperations for FileSystem {
273    fn supports_confined_namespace(&self) -> bool {
274        true
275    }
276
277    fn writable_attributes(&self) -> file_system::AttributeFlags {
278        InternalAttributes::PERSISTED_ATTRIBUTE_FLAGS
279    }
280
281    fn persistent_attributes(&self) -> file_system::AttributeFlags {
282        InternalAttributes::PERSISTED_ATTRIBUTE_FLAGS
283    }
284
285    fn rename(&self, source: &Path, destination: &Path) -> Result<()> {
286        self.operation_with_mount(|mount| {
287            let file_system = &mut mount.native;
288            let source = CString::new(source.as_str()).map_err(|_| IoErrorKind::InvalidArgument)?;
289
290            let destination =
291                CString::new(destination.as_str()).map_err(|_| IoErrorKind::InvalidArgument)?;
292
293            if source != destination {
294                let mut probe = littlefs::lfs_file_t::default();
295                let opened = unsafe {
296                    littlefs::lfs_file_open(
297                        file_system,
298                        &mut probe,
299                        source.as_ptr(),
300                        constants::OPEN_READ_ONLY,
301                    )
302                };
303                if opened >= 0 {
304                    let busy = crate::open_metadata::has_other_open(file_system, &probe);
305                    convert_result(unsafe { littlefs::lfs_file_close(file_system, &mut probe) })?;
306                    if busy {
307                        return Err(IoErrorKind::ResourceBusy);
308                    }
309                } else if opened != littlefs::lfs_error_LFS_ERR_ISDIR {
310                    convert_result(opened)?;
311                }
312            }
313
314            let result = convert_result(unsafe {
315                littlefs::lfs_rename(file_system, source.as_ptr(), destination.as_ptr())
316            });
317            if matches!(
318                result,
319                Err(IoErrorKind::InputOutput | IoErrorKind::CorruptData | IoErrorKind::NoSpace)
320            ) {
321                // A failed commit may already be on disk. Before any further
322                // operation, reload the move state. See littlefs-project/littlefs#1229.
323                mount.recovery_required = true;
324            }
325            result.map(|_| ())
326        })
327    }
328
329    fn remove(&self, path: &Path) -> Result<()> {
330        let path = CString::new(path.as_str()).map_err(|_| IoErrorKind::InvalidArgument)?;
331
332        self.operation(|file_system| {
333            convert_result(unsafe { littlefs::lfs_remove(file_system, path.as_ptr()) })?;
334
335            Ok(())
336        })
337    }
338
339    fn create_directory(&self, path: &Path, attributes: &Attributes) -> Result<()> {
340        self.operation(|file_system| {
341            Directory::create(file_system, path, attributes)?;
342
343            Ok(())
344        })
345    }
346
347    fn lookup_directory(&self, context: &mut Context, path: &Path) -> Result<()> {
348        self.operation(|file_system| {
349            let directory = Directory::lookup(file_system, path)?;
350            context.set_private_data(Box::new(Arc::new(
351                Mutex::<CriticalSectionRawMutex, _>::new(directory),
352            )));
353            Ok(())
354        })
355    }
356
357    fn lookup_file(&self, context: &mut Context, path: &Path, flags: Flags) -> Result<()> {
358        self.operation(|file_system| {
359            let file = File::lookup(file_system, path, flags)?;
360            context.set_private_data(Box::new(Arc::new(
361                Mutex::<CriticalSectionRawMutex, _>::new(file),
362            )));
363            Ok(())
364        })
365    }
366
367    fn create_file(&self, path: &Path, attributes: &Attributes) -> Result<()> {
368        self.operation(|file_system| File::create(file_system, path, attributes))
369    }
370
371    fn get_attributes(&self, path: &Path, attributes: &mut Attributes) -> Result<()> {
372        let requested = attributes.get_mask();
373        if requested.is_empty() {
374            return Ok(());
375        }
376
377        self.operation(|file_system| {
378            let path = CString::new(path.as_str()).map_err(|_| IoErrorKind::InvalidArgument)?;
379
380            let mut internal_attributes = InternalAttributes::new();
381
382            let result = unsafe {
383                littlefs::lfs_getattr(
384                    file_system,
385                    path.as_ptr(),
386                    InternalAttributes::IDENTIFIER,
387                    &mut internal_attributes as *mut _ as *mut _,
388                    size_of::<InternalAttributes>() as u32,
389                )
390            };
391            match convert_result(result) {
392                Ok(_) => {
393                    internal_attributes.update_attributes(attributes)?;
394
395                    if requested.contains(AttributeFlags::Size)
396                        && matches!(internal_attributes.kind, Kind::File | Kind::SymbolicLink)
397                    {
398                        let mut info = littlefs::lfs_info::default();
399
400                        convert_result(unsafe {
401                            littlefs::lfs_stat(file_system, path.as_ptr(), &mut info)
402                        })?;
403
404                        *attributes = attributes.clone().set_size(info.size as Size);
405                    }
406                }
407                // A power loss during creation can leave an entry without
408                // attributes. The name still exists: report the fields
409                // `lfs_stat` can provide (kind, size, inode 0) so it can be
410                // inspected and removed. Owner, permissions and times stay
411                // unavailable: requests for them fail closed with
412                // `MissingAttribute` instead of reporting root with no rights.
413                Err(IoErrorKind::MissingAttribute) => {
414                    const STAT_FIELDS: AttributeFlags = AttributeFlags::Kind
415                        .union(AttributeFlags::Inode)
416                        .union(AttributeFlags::Size);
417                    // Only requests fully answerable from `lfs_stat` fall back;
418                    // anything asking for stored metadata (owner, permissions,
419                    // times) still fails closed with `MissingAttribute`.
420                    if !requested.difference(STAT_FIELDS).is_empty() {
421                        return Err(IoErrorKind::MissingAttribute);
422                    }
423                    let stat_only = requested;
424                    let mut info = littlefs::lfs_info::default();
425                    convert_result(unsafe {
426                        littlefs::lfs_stat(file_system, path.as_ptr(), &mut info)
427                    })?;
428                    *attributes = attributes.clone().set_mask(stat_only);
429                    if stat_only.contains(AttributeFlags::Kind) {
430                        let kind = if info.type_ == constants::TYPE_DIRECTORY {
431                            Kind::Directory
432                        } else {
433                            Kind::File
434                        };
435                        *attributes = attributes.clone().set_kind(kind);
436                    }
437                    if stat_only.contains(AttributeFlags::Inode) {
438                        *attributes = attributes.clone().set_inode(0);
439                    }
440                    if stat_only.contains(AttributeFlags::Size)
441                        && info.type_ == constants::TYPE_REGULAR
442                    {
443                        *attributes = attributes.clone().set_size(info.size as Size);
444                    }
445                }
446                Err(error) => return Err(error),
447            }
448
449            Ok(())
450        })
451    }
452
453    fn set_attributes(&self, path: &Path, attributes: &Attributes) -> Result<()> {
454        let mask = attributes.get_mask();
455        if mask.is_empty() {
456            return Ok(());
457        }
458        InternalAttributes::validate_attribute_mask(mask)?;
459
460        self.operation(|file_system| {
461            let path = CString::new(path.as_str()).map_err(|_| IoErrorKind::InvalidArgument)?;
462
463            let mut internal_attributes = InternalAttributes::new();
464
465            if mask != InternalAttributes::PERSISTED_ATTRIBUTE_FLAGS {
466                convert_result(unsafe {
467                    littlefs::lfs_getattr(
468                        file_system,
469                        path.as_ptr(),
470                        InternalAttributes::IDENTIFIER,
471                        &mut internal_attributes as *mut _ as *mut _,
472                        size_of::<InternalAttributes>() as u32,
473                    )
474                })?;
475            }
476
477            internal_attributes.update_with_attributes(attributes)?;
478
479            // Pin a native identity through the metadata commit (which may
480            // relocate directory blocks). The probe has no configured attrs.
481            let mut probe = littlefs::lfs_file_t::default();
482            let opened = unsafe {
483                littlefs::lfs_file_open(
484                    file_system,
485                    &mut probe,
486                    path.as_ptr(),
487                    constants::OPEN_READ_ONLY,
488                )
489            };
490            if opened < 0 && opened != littlefs::lfs_error_LFS_ERR_ISDIR {
491                convert_result(opened)?;
492            }
493            let result = convert_result(unsafe {
494                littlefs::lfs_setattr(
495                    file_system,
496                    path.as_ptr(),
497                    InternalAttributes::IDENTIFIER,
498                    &internal_attributes as *const _ as *const _,
499                    size_of::<InternalAttributes>() as u32,
500                )
501            });
502            if opened >= 0 {
503                if result.is_ok() {
504                    crate::open_metadata::synchronize(file_system, &probe, &internal_attributes);
505                }
506                let close =
507                    convert_result(unsafe { littlefs::lfs_file_close(file_system, &mut probe) });
508                result?;
509                close?;
510            } else {
511                result?;
512            }
513            Ok(())
514        })
515    }
516}
517
518impl AttributeOperations for FileSystem {
519    fn get_attributes(&self, context: &mut Context, attributes: &mut Attributes) -> Result<()> {
520        if attributes.get_mask().is_empty() {
521            return Ok(());
522        }
523
524        if let Some(file) = context.get_private_data_of_type::<SharedContext<File>>() {
525            self.operation(|file_system| {
526                file.try_lock()
527                    .map_err(|_| IoErrorKind::WouldBlock)?
528                    .get_attributes(file_system, attributes)
529            })
530        } else if let Some(directory) =
531            context.get_private_data_of_type::<SharedContext<Directory>>()
532        {
533            directory
534                .try_lock()
535                .map_err(|_| IoErrorKind::WouldBlock)?
536                .get_attributes(attributes)
537        } else {
538            Err(IoErrorKind::InvalidArgument)
539        }
540    }
541
542    fn set_attributes(&self, context: &mut Context, attributes: &Attributes) -> Result<()> {
543        let mask = attributes.get_mask();
544        if mask.is_empty() {
545            return Ok(());
546        }
547
548        if let Some(file) = context.get_private_data_of_type::<SharedContext<File>>() {
549            self.operation(|file_system| {
550                file.try_lock()
551                    .map_err(|_| IoErrorKind::WouldBlock)?
552                    .set_attributes(file_system, attributes)
553            })
554        } else if let Some(directory) =
555            context.get_private_data_of_type::<SharedContext<Directory>>()
556        {
557            directory
558                .try_lock()
559                .map_err(|_| IoErrorKind::WouldBlock)?
560                .set_attributes(attributes)
561        } else {
562            Err(IoErrorKind::InvalidArgument)
563        }
564    }
565}
566
567impl BaseOperations for FileSystem {
568    fn read(
569        &self,
570        context: &mut Context,
571        _cx: &mut core::task::Context<'_>,
572        buffer: &mut [u8],
573        absolute_position: Size,
574    ) -> core::task::Poll<Result<usize>> {
575        file_system::ready(|| {
576            self.operation_with_context(context, |file_system, file: &mut File| {
577                file.read(file_system, buffer, absolute_position)
578            })
579        })
580    }
581
582    fn write(
583        &self,
584        context: &mut Context,
585        _cx: &mut core::task::Context<'_>,
586        buffer: &[u8],
587        absolute_position: Size,
588    ) -> core::task::Poll<Result<usize>> {
589        file_system::ready(|| {
590            self.operation_with_context(context, |file_system, file: &mut File| {
591                file.write(file_system, buffer, absolute_position)
592            })
593        })
594    }
595
596    fn set_position(
597        &self,
598        context: &mut Context,
599        current_position: Size,
600        position: &Position,
601    ) -> Result<Size> {
602        self.operation_with_context(context, |file_system, file: &mut File| {
603            file.set_position(file_system, current_position, position)
604        })
605    }
606
607    fn flush(
608        &self,
609        context: &mut Context,
610        _cx: &mut core::task::Context<'_>,
611    ) -> core::task::Poll<Result<()>> {
612        file_system::ready(|| {
613            self.operation_with_context(context, |file_system, file: &mut File| {
614                file.flush(file_system)
615            })
616        })
617    }
618
619    fn clone_context(&self, context: &Context) -> Result<Context> {
620        if let Some(file) = context.get_private_data_of_type::<SharedContext<File>>() {
621            Ok(Context::new(Some(file.clone())))
622        } else if let Some(directory) =
623            context.get_private_data_of_type::<SharedContext<Directory>>()
624        {
625            Ok(Context::new(Some(directory.clone())))
626        } else {
627            Err(IoErrorKind::InvalidArgument)
628        }
629    }
630
631    fn close(&self, context: &mut Context) -> Result<()> {
632        let mut mount = self.file_system.try_get()?;
633        let file = context
634            .get_private_data_of_type::<SharedContext<File>>()
635            .ok_or(IoErrorKind::InvalidArgument)?;
636        let mut result = Ok(());
637        if Arc::strong_count(file) == 1 {
638            let mut file = file.try_lock().map_err(|_| IoErrorKind::WouldBlock)?;
639            result = if mount.recovery_required {
640                file.close_without_sync(&mut mount.native)
641            } else {
642                file.close(&mut mount.native)
643            };
644            Self::drop_read_cache_on_error(&mut mount.native, &result);
645        }
646        context.take_private_data_of_type::<SharedContext<File>>();
647        result
648    }
649}
650
651impl FileOperations for FileSystem {}
652
653impl DirectoryOperations for FileSystem {
654    fn read(&self, context: &mut Context) -> Result<Option<Entry>> {
655        self.operation_with_context(context, |file_system, directory: &mut Directory| {
656            directory.read(file_system)
657        })
658    }
659
660    fn get_position(&self, context: &mut file_system::Context) -> Result<Size> {
661        self.operation_with_context(context, |file_system, directory: &mut Directory| {
662            directory.get_position(file_system)
663        })
664    }
665
666    fn set_position(&self, context: &mut Context, position: Size) -> Result<()> {
667        self.operation_with_context(context, |file_system, directory: &mut Directory| {
668            directory.set_position(file_system, position)
669        })
670    }
671
672    fn rewind(&self, context: &mut Context) -> Result<()> {
673        self.operation_with_context(context, |file_system, directory: &mut Directory| {
674            directory.rewind(file_system)
675        })
676    }
677
678    fn close(&self, context: &mut Context) -> Result<()> {
679        let mut mount = self.file_system.try_get()?;
680        let directory = context
681            .get_private_data_of_type::<SharedContext<Directory>>()
682            .ok_or(IoErrorKind::InvalidArgument)?;
683        if Arc::strong_count(directory) == 1 {
684            directory
685                .try_lock()
686                .map_err(|_| IoErrorKind::WouldBlock)?
687                .close(&mut mount.native)?;
688        }
689        context.take_private_data_of_type::<SharedContext<Directory>>();
690
691        Ok(())
692    }
693}
694
695impl Drop for FileSystem {
696    fn drop(&mut self) {
697        if let Ok(mut mount) = self.file_system.try_get() {
698            let file_system = &mut mount.native;
699            unsafe {
700                littlefs::lfs_unmount(file_system);
701
702                let mut configuration = Box::from_raw(file_system.cfg as *mut littlefs::lfs_config);
703                configuration::Context::take_from_configuration(&mut *configuration);
704            }
705        }
706    }
707}
708
709/// Mount an existing Xila disk without ever formatting it. Validate partition
710/// extents before overlap arithmetic, including malicious overflowing entries.
711pub fn mount_disk<D: DirectBlockDevice>(
712    device: &'static D,
713    options: Options,
714) -> Result<FileSystem> {
715    use file_system::{
716        XILA_DISK_SIGNATURE,
717        mbr::{Mbr, PartitionKind, create_partition_device},
718    };
719    let mbr = Mbr::read_from_device(device).map_err(|_| IoErrorKind::CorruptData)?;
720    let count = device.get_block_count()?;
721    for entry in mbr.partitions.iter().filter(|entry| entry.is_valid()) {
722        if entry.start_block == 0 || entry.start_block as u64 + entry.block_count as u64 > count {
723            return Err(IoErrorKind::CorruptData);
724        }
725    }
726    mbr.validate().map_err(|_| IoErrorKind::CorruptData)?;
727    if mbr.get_disk_signature() != XILA_DISK_SIGNATURE {
728        return Err(IoErrorKind::CorruptData);
729    }
730    let entry = mbr
731        .partitions
732        .iter()
733        .find(|entry| entry.is_valid() && entry.kind == PartitionKind::Xila)
734        .ok_or(IoErrorKind::CorruptData)?;
735    let partition = create_partition_device(device, entry).map_err(|_| IoErrorKind::CorruptData)?;
736    FileSystem::new(Box::leak(Box::new(partition)), options)
737}
738
739#[cfg(test)]
740mod tests {
741    extern crate std;
742
743    use file_system::{
744        AttributeFlags, MemoryDevice, PartitionDevice,
745        file_system::tests::{FileSystemTestCapabilities, implement_file_system_tests},
746    };
747
748    use super::*;
749
750    const CACHE_SIZE: usize = 256;
751
752    testing_support::instantiate_global_allocator!();
753
754    fn initialize() -> FileSystem {
755        if !log::is_initialized() {
756            let _ = log::initialize(&testing_support::Logger);
757        }
758
759        let device = Box::leak(Box::new(MemoryDevice::<512>::new(2048 * 512)));
760
761        let options = Options::new(CACHE_SIZE);
762        FileSystem::format(device, options).unwrap();
763
764        FileSystem::new(device, options).unwrap()
765    }
766
767    implement_file_system_tests!(
768        initialize(),
769        FileSystemTestCapabilities {
770            readable: AttributeFlags::all().difference(AttributeFlags::Links),
771            writable: AttributeFlags::all()
772                .difference(AttributeFlags::Size | AttributeFlags::Links),
773        }
774    );
775
776    #[test]
777    fn littlefs_unsupported_attribute_masks_are_rejected_without_mutation() {
778        let fs = initialize();
779        let file = Path::new("/unsupported-attributes.txt");
780        FileSystemOperations::create_file(&fs, file, &Attributes::new()).unwrap();
781
782        let original_permissions = file_system::Permissions::ALL_READ_WRITE;
783        FileSystemOperations::set_attributes(
784            &fs,
785            file,
786            &Attributes::new().set_permissions(original_permissions),
787        )
788        .unwrap();
789
790        for mask in [AttributeFlags::Size, AttributeFlags::Links] {
791            let unsupported = Attributes::new().set_size(12).set_links(2).set_mask(mask);
792            assert_eq!(
793                FileSystemOperations::set_attributes(&fs, file, &unsupported),
794                Err(IoErrorKind::Unsupported)
795            );
796        }
797
798        let mixed = Attributes::new()
799            .set_permissions(file_system::Permissions::NONE)
800            .set_size(12)
801            .set_mask(AttributeFlags::Permissions | AttributeFlags::Size);
802        assert_eq!(
803            FileSystemOperations::set_attributes(&fs, file, &mixed),
804            Err(IoErrorKind::Unsupported)
805        );
806
807        let mut actual = Attributes::new().set_mask(AttributeFlags::Permissions);
808        FileSystemOperations::get_attributes(&fs, file, &mut actual).unwrap();
809        assert_eq!(actual.get_permissions(), Some(&original_permissions));
810
811        let mut file_context = Context::new_empty();
812        fs.lookup_file(
813            &mut file_context,
814            file,
815            file_system::AccessFlags::Read.into(),
816        )
817        .unwrap();
818        let mut file_attributes = Attributes::new()
819            .set_mask(AttributeFlags::Kind | AttributeFlags::Size | AttributeFlags::Links);
820        AttributeOperations::get_attributes(&fs, &mut file_context, &mut file_attributes).unwrap();
821        assert_eq!(
822            file_attributes.get_mask(),
823            AttributeFlags::Kind | AttributeFlags::Size
824        );
825        assert_eq!(file_attributes.get_kind(), Some(&Kind::File));
826        assert_eq!(file_attributes.get_size(), Some(&0));
827        assert_eq!(
828            AttributeOperations::set_attributes(
829                &fs,
830                &mut file_context,
831                &Attributes::new().set_size(8),
832            ),
833            Err(IoErrorKind::Unsupported)
834        );
835        BaseOperations::close(&fs, &mut file_context).unwrap();
836
837        let directory = Path::new("/unsupported-attributes-dir");
838        FileSystemOperations::create_directory(&fs, directory, &Attributes::new()).unwrap();
839        let mut path_directory_attributes = Attributes::new()
840            .set_mask(AttributeFlags::Kind | AttributeFlags::Size | AttributeFlags::Links);
841        FileSystemOperations::get_attributes(&fs, directory, &mut path_directory_attributes)
842            .unwrap();
843        assert_eq!(path_directory_attributes.get_mask(), AttributeFlags::Kind);
844
845        let mut directory_context = Context::new_empty();
846        fs.lookup_directory(&mut directory_context, directory)
847            .unwrap();
848        let mut directory_attributes = Attributes::new()
849            .set_mask(AttributeFlags::Kind | AttributeFlags::Size | AttributeFlags::Links);
850        AttributeOperations::get_attributes(&fs, &mut directory_context, &mut directory_attributes)
851            .unwrap();
852        assert_eq!(directory_attributes.get_mask(), AttributeFlags::Kind);
853        assert_eq!(directory_attributes.get_kind(), Some(&Kind::Directory));
854        assert_eq!(
855            AttributeOperations::set_attributes(
856                &fs,
857                &mut directory_context,
858                &Attributes::new().set_mask(AttributeFlags::Kind),
859            ),
860            Err(IoErrorKind::Unsupported)
861        );
862        AttributeOperations::set_attributes(&fs, &mut directory_context, &Attributes::new())
863            .unwrap();
864        DirectoryOperations::close(&fs, &mut directory_context).unwrap();
865
866        assert_eq!(
867            FileSystemOperations::set_attributes(
868                &fs,
869                Path::new("/missing-attributes.txt"),
870                &Attributes::new().set_permissions(file_system::Permissions::NONE),
871            ),
872            Err(IoErrorKind::NotFound)
873        );
874    }
875
876    #[test]
877    fn littlefs_rejects_unsupported_attribute_all_mask_without_mutation() {
878        let fs = initialize();
879        let file = Path::new("/all-attributes.txt");
880        FileSystemOperations::create_file(&fs, file, &Attributes::new()).unwrap();
881        let original = file_system::Permissions::ALL_READ_WRITE;
882        FileSystemOperations::set_attributes(
883            &fs,
884            file,
885            &Attributes::new().set_permissions(original),
886        )
887        .unwrap();
888
889        let unsupported = Attributes::new()
890            .set_permissions(file_system::Permissions::NONE)
891            .set_inode(999)
892            .set_mask(AttributeFlags::all());
893        assert_eq!(
894            FileSystemOperations::set_attributes(&fs, file, &unsupported),
895            Err(IoErrorKind::Unsupported)
896        );
897
898        let mut after_rejection = Attributes::new().set_mask(AttributeFlags::Permissions);
899        FileSystemOperations::get_attributes(&fs, file, &mut after_rejection).unwrap();
900        assert_eq!(after_rejection.get_permissions(), Some(&original));
901    }
902
903    #[test]
904    fn path_ownership_updates_every_open_cache_and_survives_close() {
905        let fs = initialize();
906        let path = Path::new("/owners");
907        FileSystemOperations::create_file(&fs, path, &Attributes::new()).unwrap();
908        let mut first = Context::new_empty();
909        let mut second = Context::new_empty();
910        for context in [&mut first, &mut second] {
911            fs.lookup_file(context, path, file_system::AccessFlags::READ_WRITE.into())
912                .unwrap();
913        }
914        let owner = users::UserIdentifier::new(123);
915        FileSystemOperations::set_attributes(&fs, path, &Attributes::new().set_user(owner))
916            .unwrap();
917        for context in [&mut first, &mut second] {
918            let mut attributes = Attributes::new().set_mask(AttributeFlags::User);
919            AttributeOperations::get_attributes(&fs, context, &mut attributes).unwrap();
920            assert_eq!(attributes.get_user(), Some(&owner));
921            BaseOperations::close(&fs, context).unwrap();
922        }
923        let mut attributes = Attributes::new().set_mask(AttributeFlags::User);
924        FileSystemOperations::get_attributes(&fs, path, &mut attributes).unwrap();
925        assert_eq!(attributes.get_user(), Some(&owner));
926    }
927
928    #[test]
929    fn ownership_cache_sync_uses_object_identity_after_rename_and_unlink() {
930        let fs = initialize();
931        let original = Path::new("/old");
932        let moved = Path::new("/moved");
933        FileSystemOperations::create_file(&fs, original, &Attributes::new()).unwrap();
934        let mut open = Context::new_empty();
935        fs.lookup_file(
936            &mut open,
937            original,
938            file_system::AccessFlags::READ_WRITE.into(),
939        )
940        .unwrap();
941        // LittleFS detaches live source handles on rename. Reject this
942        // unsupported case instead of silently changing their object identity.
943        assert_eq!(
944            FileSystemOperations::rename(&fs, original, moved),
945            Err(IoErrorKind::ResourceBusy)
946        );
947        BaseOperations::close(&fs, &mut open).unwrap();
948        FileSystemOperations::rename(&fs, original, moved).unwrap();
949        fs.lookup_file(
950            &mut open,
951            moved,
952            file_system::AccessFlags::READ_WRITE.into(),
953        )
954        .unwrap();
955        FileSystemOperations::create_file(&fs, original, &Attributes::new()).unwrap();
956        let owner = users::UserIdentifier::new(123);
957        FileSystemOperations::set_attributes(&fs, moved, &Attributes::new().set_user(owner))
958            .unwrap();
959        FileSystemOperations::set_attributes(
960            &fs,
961            original,
962            &Attributes::new().set_user(users::UserIdentifier::new(456)),
963        )
964        .unwrap();
965        let mut attributes = Attributes::new().set_mask(AttributeFlags::User);
966        AttributeOperations::get_attributes(&fs, &mut open, &mut attributes).unwrap();
967        assert_eq!(attributes.get_user(), Some(&owner));
968        FileSystemOperations::remove(&fs, moved).unwrap();
969        FileSystemOperations::create_file(&fs, moved, &Attributes::new()).unwrap();
970        FileSystemOperations::set_attributes(
971            &fs,
972            moved,
973            &Attributes::new().set_user(users::UserIdentifier::new(789)),
974        )
975        .unwrap();
976        AttributeOperations::get_attributes(&fs, &mut open, &mut attributes).unwrap();
977        assert_eq!(attributes.get_user(), Some(&owner));
978        BaseOperations::close(&fs, &mut open).unwrap();
979    }
980
981    #[test]
982    fn handle_chmod_after_flush_is_persisted_and_visible_to_other_handles() {
983        let fs = initialize();
984        let path = Path::new("/chmod");
985        FileSystemOperations::create_file(&fs, path, &Attributes::new()).unwrap();
986        let mut first = Context::new_empty();
987        let mut second = Context::new_empty();
988        for context in [&mut first, &mut second] {
989            fs.lookup_file(context, path, file_system::AccessFlags::READ_WRITE.into())
990                .unwrap();
991        }
992        BaseOperations::flush_sync(&fs, &mut first).unwrap();
993        let permissions = file_system::Permissions::USER_READ_WRITE;
994        AttributeOperations::set_attributes(
995            &fs,
996            &mut first,
997            &Attributes::new().set_permissions(permissions),
998        )
999        .unwrap();
1000        let mut attributes = Attributes::new().set_mask(AttributeFlags::Permissions);
1001        AttributeOperations::get_attributes(&fs, &mut second, &mut attributes).unwrap();
1002        assert_eq!(attributes.get_permissions(), Some(&permissions));
1003        BaseOperations::close(&fs, &mut second).unwrap();
1004        BaseOperations::close(&fs, &mut first).unwrap();
1005        FileSystemOperations::get_attributes(&fs, path, &mut attributes).unwrap();
1006        assert_eq!(attributes.get_permissions(), Some(&permissions));
1007    }
1008
1009    #[test]
1010    fn stale_handle_chmod_cannot_overwrite_another_opens_data() {
1011        let fs = initialize();
1012        let path = Path::new("/stale-chmod");
1013        FileSystemOperations::create_file(&fs, path, &Attributes::new()).unwrap();
1014        let mut writer = Context::new_empty();
1015        let mut stale = Context::new_empty();
1016        for context in [&mut writer, &mut stale] {
1017            fs.lookup_file(context, path, file_system::AccessFlags::READ_WRITE.into())
1018                .unwrap();
1019        }
1020        BaseOperations::flush_sync(&fs, &mut stale).unwrap();
1021        BaseOperations::write_sync(&fs, &mut writer, b"payload", 0).unwrap();
1022        BaseOperations::flush_sync(&fs, &mut writer).unwrap();
1023        assert_eq!(
1024            AttributeOperations::set_attributes(
1025                &fs,
1026                &mut stale,
1027                &Attributes::new().set_permissions(file_system::Permissions::ALL_FULL)
1028            ),
1029            Err(IoErrorKind::ResourceBusy)
1030        );
1031        BaseOperations::close(&fs, &mut stale).unwrap();
1032        BaseOperations::close(&fs, &mut writer).unwrap();
1033        let mut check = Context::new_empty();
1034        fs.lookup_file(&mut check, path, file_system::AccessFlags::Read.into())
1035            .unwrap();
1036        let mut bytes = [0; 7];
1037        assert_eq!(
1038            BaseOperations::read_sync(&fs, &mut check, &mut bytes, 0).unwrap(),
1039            7
1040        );
1041        assert_eq!(&bytes, b"payload");
1042        BaseOperations::close(&fs, &mut check).unwrap();
1043    }
1044
1045    #[test]
1046    fn filesystem_contents_survive_unmount_and_remount() {
1047        let device = Box::leak(Box::new(MemoryDevice::<512>::new(2048 * 512)));
1048        let options = Options::new(CACHE_SIZE);
1049        FileSystem::format(device, options).unwrap();
1050
1051        let file_system = FileSystem::new(device, options).unwrap();
1052        let directory = Path::new("/persistent");
1053        let file = Path::new("/persistent/data");
1054        FileSystemOperations::create_directory(&file_system, directory, &Attributes::new())
1055            .unwrap();
1056        FileSystemOperations::create_file(&file_system, file, &Attributes::new()).unwrap();
1057
1058        let mut context = Context::new_empty();
1059        file_system
1060            .lookup_file(&mut context, file, file_system::AccessFlags::Write.into())
1061            .unwrap();
1062        let expected = b"littlefs remount";
1063        assert_eq!(
1064            file_system.write_sync(&mut context, expected, 0).unwrap(),
1065            expected.len()
1066        );
1067        BaseOperations::close(&file_system, &mut context).unwrap();
1068
1069        drop(file_system);
1070
1071        let file_system = FileSystem::new(device, options).unwrap();
1072        let mut context = Context::new_empty();
1073        file_system
1074            .lookup_file(&mut context, file, file_system::AccessFlags::Read.into())
1075            .unwrap();
1076        let mut actual = [0; 16];
1077        assert_eq!(
1078            BaseOperations::read_sync(&file_system, &mut context, &mut actual, 0).unwrap(),
1079            expected.len()
1080        );
1081        assert_eq!(&actual, expected);
1082        BaseOperations::close(&file_system, &mut context).unwrap();
1083    }
1084
1085    #[test]
1086    fn special_permission_bits_survive_unmount_and_remount() {
1087        let device = Box::leak(Box::new(MemoryDevice::<512>::new(2048 * 512)));
1088        FileSystem::format(device, Options::new(CACHE_SIZE)).unwrap();
1089
1090        let file_system = FileSystem::new(device, Options::new(CACHE_SIZE)).unwrap();
1091        let directory = Path::new("/shared");
1092        FileSystemOperations::create_directory(&file_system, directory, &Attributes::new())
1093            .unwrap();
1094        FileSystemOperations::set_attributes(
1095            &file_system,
1096            directory,
1097            &Attributes::new().set_permissions(file_system::Permissions::SHARED_DIRECTORY),
1098        )
1099        .unwrap();
1100        MountOperations::unmount(&file_system).unwrap();
1101        drop(file_system);
1102
1103        let file_system = FileSystem::new(device, Options::new(CACHE_SIZE)).unwrap();
1104        let mut attributes = Attributes::new().set_mask(AttributeFlags::Permissions);
1105        FileSystemOperations::get_attributes(&file_system, directory, &mut attributes).unwrap();
1106        assert_eq!(
1107            attributes.get_permissions(),
1108            Some(&file_system::Permissions::SHARED_DIRECTORY)
1109        );
1110        assert_eq!(
1111            attributes.get_permissions().unwrap().get_special(),
1112            file_system::Special::STICKY
1113        );
1114    }
1115
1116    #[test]
1117    fn options_block_cycles_reaches_c_configuration() {
1118        let device = Box::leak(Box::new(MemoryDevice::<512>::new(2048 * 512)));
1119        let options = Options::new(CACHE_SIZE).set_block_cycles(500);
1120        let file_system = FileSystem::new_format(device, options).unwrap();
1121
1122        let block_cycles = file_system
1123            .operation(|native| Ok(unsafe { (*native.cfg).block_cycles }))
1124            .unwrap();
1125        assert_eq!(block_cycles, 500);
1126    }
1127
1128    #[test]
1129    fn options_none_block_cycles_maps_to_minus_one() {
1130        let device = Box::leak(Box::new(MemoryDevice::<512>::new(2048 * 512)));
1131        let options = Options::new(CACHE_SIZE);
1132        assert_eq!(options.block_cycles, None);
1133        let file_system = FileSystem::new_format(device, options).unwrap();
1134
1135        let block_cycles = file_system
1136            .operation(|native| Ok(unsafe { (*native.cfg).block_cycles }))
1137            .unwrap();
1138        assert_eq!(block_cycles, -1);
1139    }
1140
1141    #[test]
1142    fn block_counts_above_32_bits_are_rejected() {
1143        let base = MemoryDevice::<512>::new_static(512 * 128);
1144        // A partition can claim more blocks than LittleFS can address without
1145        // backing them with storage.
1146        let device: &'static dyn DirectBlockDevice = Box::leak(Box::new(PartitionDevice::new(
1147            base,
1148            0,
1149            (1u64 << 32) + 16,
1150            512,
1151        )));
1152        let options = Options::new(CACHE_SIZE);
1153
1154        assert_eq!(
1155            FileSystem::new(device, options).err(),
1156            Some(IoErrorKind::InvalidArgument)
1157        );
1158        assert_eq!(
1159            FileSystem::format(device, options).err(),
1160            Some(IoErrorKind::InvalidArgument)
1161        );
1162        assert_eq!(
1163            FileSystem::new_format(device, options).err(),
1164            Some(IoErrorKind::InvalidArgument)
1165        );
1166    }
1167
1168    fn find_entry(fs: &FileSystem, directory_path: &Path, name: &str) -> Entry {
1169        let mut directory = Context::new_empty();
1170        fs.lookup_directory(&mut directory, directory_path).unwrap();
1171        let mut found = None;
1172        while let Some(entry) = DirectoryOperations::read(fs, &mut directory).unwrap() {
1173            if entry.name == name {
1174                found = Some(entry);
1175                break;
1176            }
1177        }
1178        DirectoryOperations::close(fs, &mut directory).unwrap();
1179        found.unwrap_or_else(|| panic!("entry {name:?} not found in {directory_path:?}"))
1180    }
1181
1182    #[test]
1183    fn directory_listing_reports_file_inode_and_modification_time() {
1184        let fs = initialize();
1185        let path = Path::new("/note.txt");
1186        FileSystemOperations::create_file(&fs, path, &Attributes::new()).unwrap();
1187
1188        let payload = b"hello littlefs";
1189        let mut file = Context::new_empty();
1190        fs.lookup_file(&mut file, path, file_system::AccessFlags::Write.into())
1191            .unwrap();
1192        assert_eq!(
1193            BaseOperations::write_sync(&fs, &mut file, payload, 0).unwrap(),
1194            payload.len()
1195        );
1196        BaseOperations::flush_sync(&fs, &mut file).unwrap();
1197        BaseOperations::close(&fs, &mut file).unwrap();
1198
1199        let initial_mtime = file_system::Time::new(1_700_000_100);
1200        FileSystemOperations::set_attributes(
1201            &fs,
1202            path,
1203            &Attributes::new()
1204                .set_inode(42)
1205                .set_modification(initial_mtime),
1206        )
1207        .unwrap();
1208
1209        let entry = find_entry(&fs, Path::ROOT, "note.txt");
1210        assert_eq!(entry.inode, 42);
1211        assert_eq!(entry.kind, Kind::File);
1212        assert_eq!(entry.size, payload.len() as Size);
1213        assert_eq!(entry.modification, initial_mtime);
1214
1215        let updated_mtime = file_system::Time::new(1_700_000_500);
1216        FileSystemOperations::set_attributes(
1217            &fs,
1218            path,
1219            &Attributes::new().set_modification(updated_mtime),
1220        )
1221        .unwrap();
1222
1223        let updated = find_entry(&fs, Path::ROOT, "note.txt");
1224        assert_eq!(updated.inode, 42);
1225        assert_eq!(updated.kind, Kind::File);
1226        assert_eq!(updated.size, payload.len() as Size);
1227        assert_eq!(updated.modification, updated_mtime);
1228    }
1229
1230    #[test]
1231    fn directory_listing_reports_subdirectory_inode_and_modification_time() {
1232        let fs = initialize();
1233        let root_mtime = file_system::Time::new(1_700_000_000);
1234        FileSystemOperations::set_attributes(
1235            &fs,
1236            Path::ROOT,
1237            &Attributes::new().set_inode(1).set_modification(root_mtime),
1238        )
1239        .unwrap();
1240
1241        let subdir = Path::new("/folder");
1242        FileSystemOperations::create_directory(&fs, subdir, &Attributes::new()).unwrap();
1243
1244        let initial_mtime = file_system::Time::new(1_700_000_200);
1245        FileSystemOperations::set_attributes(
1246            &fs,
1247            subdir,
1248            &Attributes::new()
1249                .set_inode(77)
1250                .set_modification(initial_mtime),
1251        )
1252        .unwrap();
1253
1254        let entry = find_entry(&fs, Path::ROOT, "folder");
1255        assert_eq!(entry.inode, 77);
1256        assert_eq!(entry.kind, Kind::Directory);
1257        assert_eq!(entry.modification, initial_mtime);
1258
1259        let updated_mtime = file_system::Time::new(1_700_000_900);
1260        FileSystemOperations::set_attributes(
1261            &fs,
1262            subdir,
1263            &Attributes::new().set_modification(updated_mtime),
1264        )
1265        .unwrap();
1266
1267        let updated = find_entry(&fs, Path::ROOT, "folder");
1268        assert_eq!(updated.inode, 77);
1269        assert_eq!(updated.kind, Kind::Directory);
1270        assert_eq!(updated.modification, updated_mtime);
1271
1272        let dot = find_entry(&fs, subdir, ".");
1273        assert_eq!(dot.inode, 77);
1274        assert_eq!(dot.kind, Kind::Directory);
1275        assert_eq!(dot.modification, updated_mtime);
1276
1277        let dot_dot = find_entry(&fs, subdir, "..");
1278        assert_eq!(dot_dot.inode, 1);
1279        assert_eq!(dot_dot.kind, Kind::Directory);
1280        assert_eq!(dot_dot.modification, root_mtime);
1281    }
1282
1283    #[test]
1284    fn directory_listing_falls_back_to_zero_when_attributes_are_missing() {
1285        let fs = initialize();
1286        fs.operation(|native| {
1287            let mut raw_file = littlefs::lfs_file_t::default();
1288            unsafe {
1289                convert_result(littlefs::lfs_file_open(
1290                    native,
1291                    &mut raw_file,
1292                    c"/external-file".as_ptr(),
1293                    constants::OPEN_CREATE | constants::OPEN_WRITE_ONLY,
1294                ))?;
1295                convert_result(littlefs::lfs_file_close(native, &mut raw_file))?;
1296                convert_result(littlefs::lfs_mkdir(native, c"/external-dir".as_ptr()))?;
1297            }
1298            Ok(())
1299        })
1300        .unwrap();
1301
1302        let file_entry = find_entry(&fs, Path::ROOT, "external-file");
1303        assert_eq!(file_entry.inode, 0);
1304        assert_eq!(file_entry.kind, Kind::File);
1305        assert_eq!(file_entry.modification, file_system::Time::new(0));
1306
1307        let dir_entry = find_entry(&fs, Path::ROOT, "external-dir");
1308        assert_eq!(dir_entry.inode, 0);
1309        assert_eq!(dir_entry.kind, Kind::Directory);
1310        assert_eq!(dir_entry.modification, file_system::Time::new(0));
1311    }
1312}
1313
1314#[cfg(test)]
1315mod symlink_tests {
1316    use super::*;
1317    use file_system::{AccessFlags, DirectoryOperations, Path};
1318
1319    const CACHE_SIZE: usize = 256;
1320
1321    #[test]
1322    fn persisted_link_kind_size_and_directory_entry_survive_remount() {
1323        let device = file_system::MemoryDevice::<512>::new_static(2048 * 512);
1324        let options = Options::new(CACHE_SIZE);
1325        FileSystem::format(device, options).unwrap();
1326        let filesystem = FileSystem::new(device, options).unwrap();
1327        let link = Path::from_str("/link");
1328        FileSystemOperations::create_file(&filesystem, link, &Attributes::new()).unwrap();
1329
1330        let target = b"../data/target";
1331        let mut context = Context::new_empty();
1332        FileSystemOperations::lookup_file(
1333            &filesystem,
1334            &mut context,
1335            link,
1336            Flags::from(AccessFlags::Write),
1337        )
1338        .unwrap();
1339        assert_eq!(
1340            BaseOperations::write_sync(&filesystem, &mut context, target, 0).unwrap(),
1341            target.len()
1342        );
1343        AttributeOperations::set_attributes(
1344            &filesystem,
1345            &mut context,
1346            &Attributes::new().set_kind(Kind::SymbolicLink),
1347        )
1348        .unwrap();
1349        BaseOperations::flush_sync(&filesystem, &mut context).unwrap();
1350        BaseOperations::close(&filesystem, &mut context).unwrap();
1351
1352        let mut attributes =
1353            Attributes::new().set_mask(AttributeFlags::Kind | AttributeFlags::Size);
1354        FileSystemOperations::get_attributes(&filesystem, link, &mut attributes).unwrap();
1355        assert_eq!(attributes.get_kind(), Some(&Kind::SymbolicLink));
1356        assert_eq!(attributes.get_size(), Some(&(target.len() as Size)));
1357
1358        let mut directory = Context::new_empty();
1359        filesystem
1360            .lookup_directory(&mut directory, Path::ROOT)
1361            .unwrap();
1362        let mut found = None;
1363        while let Some(entry) = DirectoryOperations::read(&filesystem, &mut directory).unwrap() {
1364            if entry.name == "link" {
1365                found = Some(entry);
1366                break;
1367            }
1368        }
1369        let found = found.unwrap();
1370        assert_eq!(found.kind, Kind::SymbolicLink);
1371        assert_eq!(found.size, target.len() as Size);
1372        DirectoryOperations::close(&filesystem, &mut directory).unwrap();
1373
1374        MountOperations::unmount(&filesystem).unwrap();
1375        drop(filesystem);
1376        let filesystem = FileSystem::new(device, options).unwrap();
1377        let mut attributes =
1378            Attributes::new().set_mask(AttributeFlags::Kind | AttributeFlags::Size);
1379        FileSystemOperations::get_attributes(&filesystem, link, &mut attributes).unwrap();
1380        assert_eq!(attributes.get_kind(), Some(&Kind::SymbolicLink));
1381        assert_eq!(attributes.get_size(), Some(&(target.len() as Size)));
1382    }
1383}