1use alloc::{boxed::Box, vec, vec::Vec};
2use core::task::{Context as TaskContext, Poll};
3use file_system::{
4 AttributeFlags, AttributeOperations, Attributes, BaseOperations, Context, DirectoryOperations,
5 FileOperations, FileSystemOperations, Flags, IoErrorKind, Kind, MountOperations, Path,
6 Permissions, Position, Result, Size, mount::MutexMountWrapper,
7};
8use synchronization::{Arc, blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
9
10use crate::{
11 attributes::{NodeAttributes, SUPPORTED_ATTRIBUTE_FLAGS},
12 directory::Directory,
13 node::{Node, ROOT_NODE_INDEX},
14};
15
16type SharedContext<T> = Arc<Mutex<CriticalSectionRawMutex, Box<T>>>;
17
18enum TargetPath<'a> {
19 Root,
20 ExistingComponent(usize),
21 Child {
22 parent_index: usize,
23 name: &'a str,
24 trailing_slash: bool,
25 },
26}
27
28pub(crate) struct State {
29 nodes: Vec<Option<Node>>,
30 next_generation: u32,
31}
32
33impl State {
34 pub(crate) fn new() -> Self {
35 let root = Node::new(
36 Box::from(""),
37 ROOT_NODE_INDEX as u32,
38 1,
39 Kind::Directory,
40 Permissions::DIRECTORY_DEFAULT,
41 );
42 Self {
43 nodes: vec![Some(root)],
44 next_generation: 2,
45 }
46 }
47
48 pub(crate) fn slot_count(&self) -> usize {
49 self.nodes.len()
50 }
51
52 pub(crate) fn get_node(&self, index: usize) -> Result<&Node> {
53 self.nodes
54 .get(index)
55 .and_then(|slot| slot.as_ref())
56 .ok_or(IoErrorKind::NotFound)
57 }
58
59 pub(crate) fn get_node_mutable(&mut self, index: usize) -> Result<&mut Node> {
60 self.nodes
61 .get_mut(index)
62 .and_then(|slot| slot.as_mut())
63 .ok_or(IoErrorKind::NotFound)
64 }
65
66 pub(crate) fn get_node_with_generation(&self, index: usize, generation: u32) -> Result<&Node> {
67 let node = self.get_node(index)?;
68 if node.generation != generation {
69 return Err(IoErrorKind::NotFound);
70 }
71 Ok(node)
72 }
73
74 pub(crate) fn get_node_with_generation_mutable(
75 &mut self,
76 index: usize,
77 generation: u32,
78 ) -> Result<&mut Node> {
79 let node = self.get_node_mutable(index)?;
80 if node.generation != generation {
81 return Err(IoErrorKind::NotFound);
82 }
83 Ok(node)
84 }
85
86 pub(crate) fn next_child(
87 &self,
88 parent_index: u32,
89 start_slot: usize,
90 ) -> Option<(usize, &Node)> {
91 let start = start_slot.max(ROOT_NODE_INDEX + 1);
92 self.nodes
93 .iter()
94 .enumerate()
95 .skip(start)
96 .find_map(|(slot_index, slot)| {
97 slot.as_ref()
98 .filter(|node| node.parent == parent_index)
99 .map(|node| (slot_index, node))
100 })
101 }
102
103 fn find_child(&self, parent_index: u32, name: &str) -> Option<usize> {
104 self.nodes
105 .iter()
106 .enumerate()
107 .skip(ROOT_NODE_INDEX + 1)
108 .find_map(|(slot_index, slot)| {
109 slot.as_ref()
110 .filter(|node| node.parent == parent_index && node.name.as_ref() == name)
111 .map(|_| slot_index)
112 })
113 }
114
115 fn has_children(&self, parent_index: u32) -> bool {
116 self.next_child(parent_index, ROOT_NODE_INDEX + 1).is_some()
117 }
118
119 fn is_ancestor(&self, candidate_ancestor: usize, start_index: usize) -> bool {
120 let mut current = start_index;
121 loop {
122 if current == candidate_ancestor {
123 return true;
124 }
125 if current == ROOT_NODE_INDEX {
126 return false;
127 }
128 match self.nodes.get(current).and_then(|slot| slot.as_ref()) {
129 Some(node) => current = node.parent as usize,
130 None => return false,
131 }
132 }
133 }
134
135 fn allocate_generation(&mut self) -> u32 {
136 let generation = self.next_generation;
137 self.next_generation = self.next_generation.wrapping_add(1).max(1);
138 generation
139 }
140
141 fn insert_node(
142 &mut self,
143 parent_index: usize,
144 name: &str,
145 kind: Kind,
146 attributes: &Attributes,
147 ) -> Result<usize> {
148 let generation = self.allocate_generation();
149 let permissions = if kind == Kind::Directory {
150 Permissions::DIRECTORY_DEFAULT
151 } else {
152 Permissions::NONE
153 };
154 let mut node_attributes = NodeAttributes::new(kind, permissions);
155 node_attributes.apply_from(attributes)?;
156 let node = Node::with_attributes(
157 Box::from(name),
158 parent_index as u32,
159 generation,
160 node_attributes,
161 );
162
163 if let Some(free_index) = self
164 .nodes
165 .iter()
166 .enumerate()
167 .skip(ROOT_NODE_INDEX + 1)
168 .find_map(|(index, slot)| slot.is_none().then_some(index))
169 {
170 self.nodes[free_index] = Some(node);
171 return Ok(free_index);
172 }
173
174 if self.nodes.len() >= u32::MAX as usize {
175 return Err(IoErrorKind::NoSpace);
176 }
177
178 let new_index = self.nodes.len();
179 self.nodes.push(Some(node));
180 Ok(new_index)
181 }
182
183 fn remove_slot(&mut self, index: usize) {
184 if index > ROOT_NODE_INDEX && index < self.nodes.len() {
185 self.nodes[index] = None;
186 while self.nodes.len() > ROOT_NODE_INDEX + 1
187 && self.nodes.last().is_some_and(Option::is_none)
188 {
189 self.nodes.pop();
190 }
191 }
192 }
193
194 fn validate_path_string(path: &Path) -> Result<&str> {
195 let path_string = path.as_str();
198 if path_string.contains('\0') {
199 return Err(IoErrorKind::InvalidArgument);
200 }
201 Ok(path_string)
202 }
203
204 fn resolve_segments(&self, path_string: &str) -> Result<usize> {
205 let mut current = ROOT_NODE_INDEX;
206
207 for segment in path_string.split('/') {
208 if segment.is_empty() {
209 continue;
210 }
211 if !self.get_node(current)?.is_directory() {
212 return Err(IoErrorKind::NotADirectory);
213 }
214 match segment {
215 "." => {}
216 ".." => {
217 current = self.get_node(current)?.parent as usize;
218 }
219 name => {
220 current = self
221 .find_child(current as u32, name)
222 .ok_or(IoErrorKind::NotFound)?;
223 }
224 }
225 }
226
227 Ok(current)
228 }
229
230 fn resolve_existing_path(&self, path: &Path) -> Result<usize> {
231 let path_string = Self::validate_path_string(path)?;
232 let trailing_slash = path_string.len() > 1 && path_string.ends_with('/');
233 let node_index = self.resolve_segments(path_string)?;
234
235 if trailing_slash && !self.get_node(node_index)?.is_directory() {
236 return Err(IoErrorKind::NotADirectory);
237 }
238
239 Ok(node_index)
240 }
241
242 fn resolve_target_path<'a>(&self, path: &'a Path) -> Result<TargetPath<'a>> {
243 let path_string = Self::validate_path_string(path)?;
244 let trailing_slash = path_string.len() > 1 && path_string.ends_with('/');
245 let trimmed = path_string.trim_end_matches('/');
246
247 if trimmed.is_empty() {
248 return Ok(TargetPath::Root);
249 }
250
251 let (parent_string, name) = match trimmed.rfind('/') {
252 Some(separator_index) => (&trimmed[..separator_index], &trimmed[separator_index + 1..]),
253 None => ("", trimmed),
254 };
255
256 if name == "." || name == ".." {
257 let existing = self.resolve_segments(trimmed)?;
258 if trailing_slash && !self.get_node(existing)?.is_directory() {
259 return Err(IoErrorKind::NotADirectory);
260 }
261 return Ok(TargetPath::ExistingComponent(existing));
262 }
263
264 let parent_index = if parent_string.is_empty() {
265 ROOT_NODE_INDEX
266 } else {
267 let index = self.resolve_segments(parent_string)?;
268 if !self.get_node(index)?.is_directory() {
269 return Err(IoErrorKind::NotADirectory);
270 }
271 index
272 };
273
274 Ok(TargetPath::Child {
275 parent_index,
276 name,
277 trailing_slash,
278 })
279 }
280
281 fn create_directory(&mut self, path: &Path, attributes: &Attributes) -> Result<()> {
282 match self.resolve_target_path(path)? {
283 TargetPath::Root | TargetPath::ExistingComponent(_) => Err(IoErrorKind::AlreadyExists),
284 TargetPath::Child {
285 parent_index,
286 name,
287 trailing_slash: _,
288 } => {
289 if self.find_child(parent_index as u32, name).is_some() {
290 return Err(IoErrorKind::AlreadyExists);
291 }
292 self.insert_node(parent_index, name, Kind::Directory, attributes)?;
293 Ok(())
294 }
295 }
296 }
297
298 fn create_file(&mut self, path: &Path, attributes: &Attributes) -> Result<()> {
299 match self.resolve_target_path(path)? {
300 TargetPath::Root => Err(IoErrorKind::IsADirectory),
301 TargetPath::ExistingComponent(existing_index) => {
302 if self.get_node(existing_index)?.is_directory() {
303 Err(IoErrorKind::IsADirectory)
304 } else {
305 Err(IoErrorKind::AlreadyExists)
306 }
307 }
308 TargetPath::Child {
309 parent_index,
310 name,
311 trailing_slash,
312 } => {
313 if let Some(existing_index) = self.find_child(parent_index as u32, name) {
314 if self.get_node(existing_index)?.is_directory() {
315 return Err(IoErrorKind::IsADirectory);
316 }
317 return Err(IoErrorKind::AlreadyExists);
318 }
319 if trailing_slash {
320 return Err(IoErrorKind::InvalidPath);
321 }
322 self.insert_node(parent_index, name, Kind::File, attributes)?;
323 Ok(())
324 }
325 }
326 }
327
328 fn remove(&mut self, path: &Path) -> Result<()> {
329 let node_index = self.resolve_existing_path(path)?;
330 if node_index == ROOT_NODE_INDEX {
331 return Err(IoErrorKind::InvalidArgument);
332 }
333
334 if self.get_node(node_index)?.is_directory() && self.has_children(node_index as u32) {
335 return Err(IoErrorKind::DirectoryNotEmpty);
336 }
337
338 self.remove_slot(node_index);
339 Ok(())
340 }
341
342 fn rename(&mut self, source: &Path, destination: &Path) -> Result<()> {
343 let source_index = self.resolve_existing_path(source)?;
344 if source_index == ROOT_NODE_INDEX {
345 return Err(IoErrorKind::InvalidArgument);
346 }
347
348 let source_is_directory = self.get_node(source_index)?.is_directory();
349
350 match self.resolve_target_path(destination)? {
351 TargetPath::Root => Err(IoErrorKind::InvalidArgument),
352 TargetPath::ExistingComponent(existing_index) => {
353 if existing_index == source_index {
354 Ok(())
355 } else {
356 Err(IoErrorKind::InvalidArgument)
357 }
358 }
359 TargetPath::Child {
360 parent_index,
361 name,
362 trailing_slash,
363 } => {
364 if source_is_directory && self.is_ancestor(source_index, parent_index) {
365 return Err(IoErrorKind::InvalidArgument);
366 }
367
368 if let Some(destination_index) = self.find_child(parent_index as u32, name) {
369 if destination_index == source_index {
370 return Ok(());
371 }
372
373 let destination_is_directory = self.get_node(destination_index)?.is_directory();
374 if source_is_directory && !destination_is_directory {
375 return Err(IoErrorKind::NotADirectory);
376 }
377 if !source_is_directory && destination_is_directory {
378 return Err(IoErrorKind::IsADirectory);
379 }
380 if destination_is_directory && self.has_children(destination_index as u32) {
381 return Err(IoErrorKind::DirectoryNotEmpty);
382 }
383 if trailing_slash && !source_is_directory {
384 return Err(IoErrorKind::NotADirectory);
385 }
386
387 self.remove_slot(destination_index);
388 } else if trailing_slash && !source_is_directory {
389 return Err(IoErrorKind::NotADirectory);
390 }
391
392 let source_node = self.get_node_mutable(source_index)?;
393 source_node.parent = parent_index as u32;
394 if source_node.name.as_ref() != name {
395 source_node.name = Box::from(name);
396 }
397 Ok(())
398 }
399 }
400 }
401
402 fn get_attributes(&self, path: &Path, attributes: &mut Attributes) -> Result<()> {
403 if attributes.get_mask().is_empty() {
404 return Ok(());
405 }
406
407 let node_index = self.resolve_existing_path(path)?;
408 let node = self.get_node(node_index)?;
409 node.to_attributes().read_into(attributes);
410 Ok(())
411 }
412
413 fn set_attributes(&mut self, path: &Path, attributes: &Attributes) -> Result<()> {
414 let mask = attributes.get_mask();
415 if mask.is_empty() {
416 return Ok(());
417 }
418
419 let node_index = self.resolve_existing_path(path)?;
420 let node = self.get_node_mutable(node_index)?;
421 let mut node_attributes: NodeAttributes = node.to_attributes();
422 node_attributes.apply_from(attributes)?;
423 node.set_attributes(&node_attributes);
424 Ok(())
425 }
426}
427
428pub struct FileSystem {
430 state: MutexMountWrapper<CriticalSectionRawMutex, State>,
431}
432
433impl Default for FileSystem {
434 fn default() -> Self {
435 Self::new()
436 }
437}
438
439impl FileSystem {
440 pub fn new() -> Self {
442 Self {
443 state: MutexMountWrapper::new_mounted(State::new()),
444 }
445 }
446
447 fn with_state<T>(&self, operation: impl FnOnce(&mut State) -> Result<T>) -> Result<T> {
448 let mut state = self.state.try_get()?;
449 operation(&mut state)
450 }
451
452 fn with_directory<T>(
453 &self,
454 context: &mut Context,
455 operation: impl FnOnce(&mut State, &mut Directory) -> Result<T>,
456 ) -> Result<T> {
457 let mut state = self.state.try_get()?;
458 let directory = context
459 .get_private_data_of_type::<SharedContext<Directory>>()
460 .ok_or(IoErrorKind::InvalidArgument)?;
461 let mut directory = directory.try_lock().map_err(|_| IoErrorKind::WouldBlock)?;
462 operation(&mut state, &mut directory)
463 }
464}
465
466impl MountOperations for FileSystem {
467 fn mount(&self) -> Result<()> {
468 if self.state.is_mounted()? {
469 return Ok(());
470 }
471 self.state.mount(State::new())
472 }
473
474 fn unmount(&self) -> Result<()> {
475 self.state.unmount()
476 }
477}
478
479impl FileSystemOperations for FileSystem {
480 fn supports_confined_namespace(&self) -> bool {
481 true
482 }
483
484 fn writable_attributes(&self) -> AttributeFlags {
485 SUPPORTED_ATTRIBUTE_FLAGS
486 }
487
488 fn persistent_attributes(&self) -> AttributeFlags {
489 AttributeFlags::empty()
490 }
491
492 fn lookup_directory(&self, context: &mut Context, path: &Path) -> Result<()> {
493 self.with_state(|state| {
494 let node_index = state.resolve_existing_path(path)?;
495 let node = state.get_node(node_index)?;
496 if !node.is_directory() {
497 return Err(IoErrorKind::NotADirectory);
498 }
499
500 let directory = Box::new(Directory::new(node_index, node.generation));
501 context.set_private_data(Box::new(Arc::new(
502 Mutex::<CriticalSectionRawMutex, _>::new(directory),
503 )));
504 Ok(())
505 })
506 }
507
508 fn lookup_file(&self, _context: &mut Context, path: &Path, _flags: Flags) -> Result<()> {
509 self.with_state(|state| {
510 let node_index = state.resolve_existing_path(path)?;
511 if state.get_node(node_index)?.is_directory() {
512 return Err(IoErrorKind::IsADirectory);
513 }
514 Err(IoErrorKind::Unsupported)
515 })
516 }
517
518 fn create_directory(&self, path: &Path, attributes: &Attributes) -> Result<()> {
519 self.with_state(|state| state.create_directory(path, attributes))
520 }
521
522 fn create_file(&self, path: &Path, attributes: &Attributes) -> Result<()> {
523 self.with_state(|state| state.create_file(path, attributes))
524 }
525
526 fn remove(&self, path: &Path) -> Result<()> {
527 self.with_state(|state| state.remove(path))
528 }
529
530 fn rename(&self, source: &Path, destination: &Path) -> Result<()> {
531 self.with_state(|state| state.rename(source, destination))
532 }
533
534 fn get_attributes(&self, path: &Path, attributes: &mut Attributes) -> Result<()> {
535 if attributes.get_mask().is_empty() {
536 return Ok(());
537 }
538 self.with_state(|state| state.get_attributes(path, attributes))
539 }
540
541 fn set_attributes(&self, path: &Path, attributes: &Attributes) -> Result<()> {
542 if attributes.get_mask().is_empty() {
543 return Ok(());
544 }
545 self.with_state(|state| state.set_attributes(path, attributes))
546 }
547}
548
549impl AttributeOperations for FileSystem {
550 fn get_attributes(&self, context: &mut Context, attributes: &mut Attributes) -> Result<()> {
551 if attributes.get_mask().is_empty() {
552 return Ok(());
553 }
554 self.with_directory(context, |state, directory| {
555 directory.get_attributes(state, attributes)
556 })
557 }
558
559 fn set_attributes(&self, context: &mut Context, attributes: &Attributes) -> Result<()> {
560 if attributes.get_mask().is_empty() {
561 return Ok(());
562 }
563 self.with_directory(context, |state, directory| {
564 directory.set_attributes(state, attributes)
565 })
566 }
567}
568
569impl BaseOperations for FileSystem {
570 fn read(
571 &self,
572 _context: &mut Context,
573 _task_context: &mut TaskContext<'_>,
574 _buffer: &mut [u8],
575 _absolute_position: Size,
576 ) -> Poll<Result<usize>> {
577 Poll::Ready(Err(IoErrorKind::Unsupported))
578 }
579
580 fn write(
581 &self,
582 _context: &mut Context,
583 _task_context: &mut TaskContext<'_>,
584 _buffer: &[u8],
585 _absolute_position: Size,
586 ) -> Poll<Result<usize>> {
587 Poll::Ready(Err(IoErrorKind::Unsupported))
588 }
589
590 fn set_position(
591 &self,
592 _context: &mut Context,
593 _current: Size,
594 _position: &Position,
595 ) -> Result<Size> {
596 Err(IoErrorKind::Unsupported)
597 }
598
599 fn flush(
600 &self,
601 _context: &mut Context,
602 _task_context: &mut TaskContext<'_>,
603 ) -> Poll<Result<()>> {
604 Poll::Ready(Err(IoErrorKind::Unsupported))
605 }
606
607 fn open(&self, _context: &mut Context) -> Result<()> {
608 Err(IoErrorKind::Unsupported)
609 }
610
611 fn close(&self, _context: &mut Context) -> Result<()> {
612 Err(IoErrorKind::Unsupported)
613 }
614
615 fn clone_context(&self, context: &Context) -> Result<Context> {
616 if let Some(directory) = context.get_private_data_of_type::<SharedContext<Directory>>() {
617 Ok(Context::new(Some(directory.clone())))
618 } else {
619 Err(IoErrorKind::InvalidArgument)
620 }
621 }
622}
623
624impl FileOperations for FileSystem {}
625
626impl DirectoryOperations for FileSystem {
627 fn read(&self, context: &mut Context) -> Result<Option<file_system::Entry>> {
628 self.with_directory(context, |state, directory| directory.read(state))
629 }
630
631 fn get_position(&self, context: &mut Context) -> Result<Size> {
632 self.with_directory(context, |state, directory| directory.get_position(state))
633 }
634
635 fn set_position(&self, context: &mut Context, position: Size) -> Result<()> {
636 self.with_directory(context, |state, directory| {
637 directory.set_position(state, position)
638 })
639 }
640
641 fn rewind(&self, context: &mut Context) -> Result<()> {
642 self.with_directory(context, |state, directory| directory.rewind(state))
643 }
644
645 fn close(&self, context: &mut Context) -> Result<()> {
646 let _state = self.state.try_get()?;
647 if context
648 .take_private_data_of_type::<SharedContext<Directory>>()
649 .is_none()
650 {
651 return Err(IoErrorKind::InvalidArgument);
652 }
653 Ok(())
654 }
655}
656
657#[cfg(test)]
658mod tests {
659 use super::*;
660 use alloc::{string::String, vec::Vec};
661 use file_system::{
662 AccessFlags,
663 file_system::tests::{
664 FileSystemTestCapabilities, test_attribute_operations_with_capabilities,
665 test_directory_attributes, test_directory_entry_metadata, test_directory_operations,
666 test_directory_position_operations, test_directory_read_operations,
667 test_directory_rewind, test_empty_directory_read, test_error_handling,
668 test_file_creation_edge_cases, test_file_system_consistency, test_invalid_paths,
669 test_long_filenames, test_nested_directories, test_rename_edge_cases,
670 test_root_directory_operations, test_special_characters_in_names,
671 },
672 };
673 use users::{GroupIdentifier, UserIdentifier};
674
675 fn test_attribute_capabilities() -> FileSystemTestCapabilities {
676 FileSystemTestCapabilities {
677 readable: SUPPORTED_ATTRIBUTE_FLAGS | AttributeFlags::Size,
678 writable: SUPPORTED_ATTRIBUTE_FLAGS,
679 }
680 }
681
682 #[test]
683 fn shared_conformance_directory_operations() {
684 let file_system = FileSystem::new();
685 test_directory_operations(&file_system);
686 }
687
688 #[test]
689 fn shared_conformance_nested_directories() {
690 let file_system = FileSystem::new();
691 test_nested_directories(&file_system);
692 }
693
694 #[test]
695 fn shared_conformance_file_creation_edge_cases() {
696 let file_system = FileSystem::new();
697 test_file_creation_edge_cases(&file_system);
698 }
699
700 #[test]
701 fn shared_conformance_rename_edge_cases() {
702 let file_system = FileSystem::new();
703 test_rename_edge_cases(&file_system);
704 }
705
706 #[test]
707 fn shared_conformance_attribute_operations() {
708 let file_system = FileSystem::new();
709 test_attribute_operations_with_capabilities(&file_system, test_attribute_capabilities());
710 }
711
712 #[test]
713 fn shared_conformance_directory_attributes() {
714 let file_system = FileSystem::new();
715 test_directory_attributes(&file_system);
716 }
717
718 #[test]
719 fn shared_conformance_error_handling() {
720 let file_system = FileSystem::new();
721 test_error_handling(&file_system);
722 }
723
724 #[test]
725 fn shared_conformance_invalid_paths() {
726 let file_system = FileSystem::new();
727 test_invalid_paths(&file_system);
728 }
729
730 #[test]
731 fn shared_conformance_file_system_consistency() {
732 let file_system = FileSystem::new();
733 test_file_system_consistency(&file_system);
734 }
735
736 #[test]
737 fn shared_conformance_directory_read_operations() {
738 let file_system = FileSystem::new();
739 test_directory_read_operations(&file_system);
740 }
741
742 #[test]
743 fn shared_conformance_directory_position_operations() {
744 let file_system = FileSystem::new();
745 test_directory_position_operations(&file_system);
746 }
747
748 #[test]
749 fn shared_conformance_directory_rewind() {
750 let file_system = FileSystem::new();
751 test_directory_rewind(&file_system);
752 }
753
754 #[test]
755 fn shared_conformance_empty_directory_read() {
756 let file_system = FileSystem::new();
757 test_empty_directory_read(&file_system);
758 }
759
760 #[test]
761 fn shared_conformance_directory_entry_metadata() {
762 let file_system = FileSystem::new();
763 test_directory_entry_metadata(&file_system);
764 }
765
766 #[test]
767 fn shared_conformance_root_directory_operations() {
768 let file_system = FileSystem::new();
769 test_root_directory_operations(&file_system);
770 }
771
772 #[test]
773 fn shared_conformance_long_filenames() {
774 let file_system = FileSystem::new();
775 test_long_filenames(&file_system);
776 }
777
778 #[test]
779 fn shared_conformance_special_characters_in_names() {
780 let file_system = FileSystem::new();
781 test_special_characters_in_names(&file_system);
782 }
783
784 #[test]
785 fn node_memory_footprint_is_compact() {
786 #[cfg(target_pointer_width = "32")]
787 assert_eq!(core::mem::size_of::<Node>(), 64);
788 #[cfg(target_pointer_width = "64")]
789 assert_eq!(core::mem::size_of::<Node>(), 72);
790
791 assert_eq!(
792 core::mem::size_of::<Option<Node>>(),
793 core::mem::size_of::<Node>()
794 );
795 }
796
797 #[test]
798 fn lookup_file_and_content_operations_return_unsupported_operation() {
799 let file_system = FileSystem::new();
800 let node_path = Path::new("/serial0");
801 file_system
802 .create_file(node_path, &Attributes::new())
803 .unwrap();
804
805 let mut context = Context::new_empty();
806 assert_eq!(
807 file_system.lookup_file(&mut context, node_path, AccessFlags::Read.into()),
808 Err(IoErrorKind::Unsupported)
809 );
810 assert_eq!(
811 file_system.lookup_file(&mut context, Path::ROOT, AccessFlags::Read.into()),
812 Err(IoErrorKind::IsADirectory)
813 );
814 assert_eq!(
815 file_system.lookup_file(
816 &mut context,
817 Path::new("/missing"),
818 AccessFlags::Read.into()
819 ),
820 Err(IoErrorKind::NotFound)
821 );
822
823 let mut buffer = [0u8; 8];
824 assert_eq!(
825 BaseOperations::read_sync(&file_system, &mut context, &mut buffer, 0),
826 Err(IoErrorKind::Unsupported)
827 );
828 assert_eq!(
829 BaseOperations::write_sync(&file_system, &mut context, b"data", 0),
830 Err(IoErrorKind::Unsupported)
831 );
832 assert_eq!(
833 BaseOperations::flush_sync(&file_system, &mut context),
834 Err(IoErrorKind::Unsupported)
835 );
836 assert_eq!(
837 BaseOperations::set_position(&file_system, &mut context, 0, &Position::Start(0)),
838 Err(IoErrorKind::Unsupported)
839 );
840 assert_eq!(
841 BaseOperations::open(&file_system, &mut context),
842 Err(IoErrorKind::Unsupported)
843 );
844 assert_eq!(
845 BaseOperations::close(&file_system, &mut context),
846 Err(IoErrorKind::Unsupported)
847 );
848 }
849
850 #[test]
851 fn device_and_pipe_attributes_round_trip_and_links_remain_unsupported() {
852 let file_system = FileSystem::new();
853 assert_eq!(file_system.writable_attributes(), SUPPORTED_ATTRIBUTE_FLAGS);
854 assert_eq!(file_system.persistent_attributes(), AttributeFlags::empty());
855
856 let node_path = Path::new("/tty0");
857 file_system
858 .create_file(node_path, &Attributes::new())
859 .unwrap();
860
861 let updated = Attributes::new()
862 .set_kind(Kind::CharacterDevice)
863 .set_inode(7)
864 .set_user(UserIdentifier::new(1000))
865 .set_group(GroupIdentifier::new(100))
866 .set_permissions(Permissions::DEVICE_DEFAULT);
867 FileSystemOperations::set_attributes(&file_system, node_path, &updated).unwrap();
868
869 let mut actual = Attributes::new().set_mask(AttributeFlags::all());
870 FileSystemOperations::get_attributes(&file_system, node_path, &mut actual).unwrap();
871 assert_eq!(actual.get_mask(), SUPPORTED_ATTRIBUTE_FLAGS);
872 assert_eq!(actual.get_kind(), Some(&Kind::CharacterDevice));
873 assert_eq!(actual.get_inode(), Some(&7));
874 assert_eq!(actual.get_user(), Some(&UserIdentifier::new(1000)));
875 assert_eq!(actual.get_group(), Some(&GroupIdentifier::new(100)));
876 assert_eq!(actual.get_permissions(), Some(&Permissions::DEVICE_DEFAULT));
877 assert_eq!(actual.get_size(), None);
878 assert_eq!(actual.get_links(), None);
879
880 assert_eq!(
881 file_system.create_symlink(
882 Path::new("/tty0"),
883 Path::new("/tty_link"),
884 &Attributes::new()
885 ),
886 Err(IoErrorKind::Unsupported)
887 );
888 assert_eq!(
889 file_system.link(Path::new("/tty0"), Path::new("/tty_hardlink")),
890 Err(IoErrorKind::Unsupported)
891 );
892 let mut symlink_buffer = [0u8; 16];
893 assert_eq!(
894 file_system.read_symlink(Path::new("/tty_link"), &mut symlink_buffer),
895 Err(IoErrorKind::Unsupported)
896 );
897 }
898
899 #[test]
900 fn rename_and_move_semantics_match_little_fs() {
901 let file_system = FileSystem::new();
902 file_system
903 .create_directory(Path::new("/uart"), &Attributes::new())
904 .unwrap();
905 file_system
906 .create_directory(Path::new("/serial"), &Attributes::new())
907 .unwrap();
908 file_system
909 .create_file(Path::new("/uart/uart0"), &Attributes::new())
910 .unwrap();
911 file_system
912 .create_file(Path::new("/uart/uart1"), &Attributes::new())
913 .unwrap();
914
915 let uart0_attributes = Attributes::new()
916 .set_kind(Kind::CharacterDevice)
917 .set_inode(11);
918 FileSystemOperations::set_attributes(
919 &file_system,
920 Path::new("/uart/uart0"),
921 &uart0_attributes,
922 )
923 .unwrap();
924
925 file_system
927 .rename(Path::new("/uart/uart0"), Path::new("/uart/console"))
928 .unwrap();
929
930 let mut read_back =
931 Attributes::new().set_mask(AttributeFlags::Kind | AttributeFlags::Inode);
932 assert_eq!(
933 FileSystemOperations::get_attributes(
934 &file_system,
935 Path::new("/uart/uart0"),
936 &mut read_back
937 ),
938 Err(IoErrorKind::NotFound)
939 );
940 FileSystemOperations::get_attributes(
941 &file_system,
942 Path::new("/uart/console"),
943 &mut read_back,
944 )
945 .unwrap();
946 assert_eq!(read_back.get_kind(), Some(&Kind::CharacterDevice));
947 assert_eq!(read_back.get_inode(), Some(&11));
948
949 file_system
951 .create_file(Path::new("/serial/console"), &Attributes::new())
952 .unwrap();
953 file_system
954 .rename(Path::new("/uart/console"), Path::new("/serial/console"))
955 .unwrap();
956 FileSystemOperations::get_attributes(
957 &file_system,
958 Path::new("/serial/console"),
959 &mut read_back,
960 )
961 .unwrap();
962 assert_eq!(read_back.get_inode(), Some(&11));
963
964 file_system
966 .create_directory(Path::new("/uart/child"), &Attributes::new())
967 .unwrap();
968 assert_eq!(
969 file_system.rename(Path::new("/uart"), Path::new("/uart/child/nested")),
970 Err(IoErrorKind::InvalidArgument)
971 );
972
973 assert_eq!(
975 file_system.rename(Path::new("/serial/console"), Path::new("/uart")),
976 Err(IoErrorKind::IsADirectory)
977 );
978 assert_eq!(
979 file_system.rename(Path::new("/uart"), Path::new("/serial/console")),
980 Err(IoErrorKind::NotADirectory)
981 );
982 assert_eq!(
983 file_system.rename(Path::new("/serial"), Path::new("/uart")),
984 Err(IoErrorKind::DirectoryNotEmpty)
985 );
986 }
987
988 #[test]
989 fn directory_listing_includes_dot_and_dot_dot_and_attribute_context() {
990 let file_system = FileSystem::new();
991 file_system
992 .create_directory(Path::new("/uart"), &Attributes::new())
993 .unwrap();
994 file_system
995 .create_file(Path::new("/uart/uart0"), &Attributes::new())
996 .unwrap();
997
998 let mut root_context = Context::new_empty();
999 file_system
1000 .lookup_directory(&mut root_context, Path::ROOT)
1001 .unwrap();
1002
1003 let mut root_names = Vec::new();
1004 while let Some(entry) = DirectoryOperations::read(&file_system, &mut root_context).unwrap()
1005 {
1006 root_names.push(entry.name);
1007 }
1008 assert_eq!(
1009 root_names,
1010 Vec::from([String::from("."), String::from(".."), String::from("uart")])
1011 );
1012
1013 let mut directory_attributes = Attributes::new().set_mask(AttributeFlags::Kind);
1014 AttributeOperations::get_attributes(
1015 &file_system,
1016 &mut root_context,
1017 &mut directory_attributes,
1018 )
1019 .unwrap();
1020 assert_eq!(directory_attributes.get_kind(), Some(&Kind::Directory));
1021
1022 let mut cloned_context =
1023 BaseOperations::clone_context(&file_system, &root_context).unwrap();
1024 DirectoryOperations::close(&file_system, &mut root_context).unwrap();
1025 DirectoryOperations::rewind(&file_system, &mut cloned_context).unwrap();
1026 assert_eq!(
1027 DirectoryOperations::read(&file_system, &mut cloned_context)
1028 .unwrap()
1029 .unwrap()
1030 .name,
1031 "."
1032 );
1033 DirectoryOperations::close(&file_system, &mut cloned_context).unwrap();
1034 }
1035
1036 #[test]
1037 fn unmount_clears_state_and_mount_reinitializes() {
1038 let file_system = FileSystem::new();
1039 file_system
1040 .create_file(Path::new("/temporary_node"), &Attributes::new())
1041 .unwrap();
1042
1043 file_system.mount().unwrap();
1044 let mut attributes = Attributes::new().set_mask(AttributeFlags::Kind);
1045 FileSystemOperations::get_attributes(
1046 &file_system,
1047 Path::new("/temporary_node"),
1048 &mut attributes,
1049 )
1050 .unwrap();
1051
1052 file_system.unmount().unwrap();
1053 assert_eq!(
1054 file_system.create_file(Path::new("/after_unmount"), &Attributes::new()),
1055 Err(IoErrorKind::DeviceUnavailable)
1056 );
1057 assert_eq!(file_system.unmount(), Err(IoErrorKind::DeviceUnavailable));
1058
1059 file_system.mount().unwrap();
1060 assert_eq!(
1061 FileSystemOperations::get_attributes(
1062 &file_system,
1063 Path::new("/temporary_node"),
1064 &mut attributes,
1065 ),
1066 Err(IoErrorKind::NotFound)
1067 );
1068 }
1069
1070 #[test]
1071 fn directory_position_and_stale_generation_after_remove() {
1072 let file_system = FileSystem::new();
1073 file_system
1074 .create_directory(Path::new("/devices"), &Attributes::new())
1075 .unwrap();
1076 file_system
1077 .create_file(Path::new("/devices/first"), &Attributes::new())
1078 .unwrap();
1079 file_system
1080 .create_file(Path::new("/devices/second"), &Attributes::new())
1081 .unwrap();
1082
1083 let mut context = Context::new_empty();
1084 file_system
1085 .lookup_directory(&mut context, Path::new("/devices"))
1086 .unwrap();
1087
1088 assert_eq!(
1089 DirectoryOperations::read(&file_system, &mut context)
1090 .unwrap()
1091 .unwrap()
1092 .name,
1093 "."
1094 );
1095 let after_dot = DirectoryOperations::get_position(&file_system, &mut context).unwrap();
1096 assert_eq!(
1097 DirectoryOperations::read(&file_system, &mut context)
1098 .unwrap()
1099 .unwrap()
1100 .name,
1101 ".."
1102 );
1103 assert_eq!(
1104 DirectoryOperations::read(&file_system, &mut context)
1105 .unwrap()
1106 .unwrap()
1107 .name,
1108 "first"
1109 );
1110 file_system.remove(Path::new("/devices/second")).unwrap();
1111 assert_eq!(
1112 DirectoryOperations::read(&file_system, &mut context).unwrap(),
1113 None
1114 );
1115
1116 DirectoryOperations::set_position(&file_system, &mut context, after_dot).unwrap();
1117 assert_eq!(
1118 DirectoryOperations::read(&file_system, &mut context)
1119 .unwrap()
1120 .unwrap()
1121 .name,
1122 ".."
1123 );
1124 DirectoryOperations::close(&file_system, &mut context).unwrap();
1125
1126 assert_eq!(
1128 file_system.remove(Path::new("/devices")),
1129 Err(IoErrorKind::DirectoryNotEmpty)
1130 );
1131
1132 file_system
1134 .create_directory(Path::new("/transient"), &Attributes::new())
1135 .unwrap();
1136 let mut stale_context = Context::new_empty();
1137 file_system
1138 .lookup_directory(&mut stale_context, Path::new("/transient"))
1139 .unwrap();
1140 file_system.remove(Path::new("/transient")).unwrap();
1141 file_system
1142 .create_directory(Path::new("/reused"), &Attributes::new())
1143 .unwrap();
1144 assert_eq!(
1145 DirectoryOperations::read(&file_system, &mut stale_context),
1146 Err(IoErrorKind::NotFound)
1147 );
1148 }
1149
1150 #[test]
1151 fn set_attributes_validates_kind_transitions_and_path_errors() {
1152 let file_system = FileSystem::new();
1153 file_system
1154 .create_directory(Path::new("/folder"), &Attributes::new())
1155 .unwrap();
1156 file_system
1157 .create_file(Path::new("/folder/node"), &Attributes::new())
1158 .unwrap();
1159
1160 let mut attributes = Attributes::new().set_kind(Kind::File);
1161 assert_eq!(
1162 FileSystemOperations::set_attributes(&file_system, Path::new("/folder"), &attributes),
1163 Err(IoErrorKind::IsADirectory)
1164 );
1165
1166 attributes = Attributes::new().set_kind(Kind::Directory);
1167 assert_eq!(
1168 FileSystemOperations::set_attributes(
1169 &file_system,
1170 Path::new("/folder/node"),
1171 &attributes
1172 ),
1173 Err(IoErrorKind::InvalidArgument)
1174 );
1175
1176 attributes = Attributes::new().set_kind(Kind::Pipe).set_inode(5);
1177 FileSystemOperations::set_attributes(&file_system, Path::new("/folder/node"), &attributes)
1178 .unwrap();
1179
1180 let mut read_back =
1181 Attributes::new().set_mask(AttributeFlags::Kind | AttributeFlags::Inode);
1182 FileSystemOperations::get_attributes(
1183 &file_system,
1184 Path::new("/folder/./../folder/node"),
1185 &mut read_back,
1186 )
1187 .unwrap();
1188 assert_eq!(read_back.get_kind(), Some(&Kind::Pipe));
1189 assert_eq!(read_back.get_inode(), Some(&5));
1190
1191 assert_eq!(
1192 FileSystemOperations::get_attributes(
1193 &file_system,
1194 Path::new("/folder/node/"),
1195 &mut read_back,
1196 ),
1197 Err(IoErrorKind::NotADirectory)
1198 );
1199 assert_eq!(
1200 file_system.create_file(Path::new("/missing/node"), &Attributes::new()),
1201 Err(IoErrorKind::NotFound)
1202 );
1203 assert_eq!(
1204 file_system.create_file(Path::new("/folder/node/child"), &Attributes::new()),
1205 Err(IoErrorKind::NotADirectory)
1206 );
1207 assert_eq!(
1209 file_system.create_file(Path::EMPTY, &Attributes::new()),
1210 Err(IoErrorKind::IsADirectory)
1211 );
1212 assert_eq!(
1213 file_system.create_directory(Path::EMPTY, &Attributes::new()),
1214 Err(IoErrorKind::AlreadyExists)
1215 );
1216 assert_eq!(
1217 file_system.create_file(Path::new("/bad\0name"), &Attributes::new()),
1218 Err(IoErrorKind::InvalidArgument)
1219 );
1220 }
1221
1222 #[test]
1223 fn directory_entries_carry_inode_and_modification_time() {
1224 let file_system = FileSystem::new();
1225 let root_mtime = file_system::Time::new(1_700_000_000);
1226 let dir_mtime = file_system::Time::new(1_700_000_100);
1227 let file_mtime = file_system::Time::new(1_700_000_200);
1228
1229 FileSystemOperations::set_attributes(
1230 &file_system,
1231 Path::ROOT,
1232 &Attributes::new().set_inode(1).set_modification(root_mtime),
1233 )
1234 .unwrap();
1235 file_system
1236 .create_directory(Path::new("/dir"), &Attributes::new())
1237 .unwrap();
1238 FileSystemOperations::set_attributes(
1239 &file_system,
1240 Path::new("/dir"),
1241 &Attributes::new().set_inode(2).set_modification(dir_mtime),
1242 )
1243 .unwrap();
1244 file_system
1245 .create_file(Path::new("/dir/item"), &Attributes::new())
1246 .unwrap();
1247 FileSystemOperations::set_attributes(
1248 &file_system,
1249 Path::new("/dir/item"),
1250 &Attributes::new().set_inode(3).set_modification(file_mtime),
1251 )
1252 .unwrap();
1253
1254 let mut context = Context::new_empty();
1255 file_system
1256 .lookup_directory(&mut context, Path::new("/dir"))
1257 .unwrap();
1258 let mut entries = alloc::vec::Vec::new();
1259 while let Some(entry) = DirectoryOperations::read(&file_system, &mut context).unwrap() {
1260 entries.push(entry);
1261 }
1262 DirectoryOperations::close(&file_system, &mut context).unwrap();
1263
1264 let dot = entries.iter().find(|entry| entry.name == ".").unwrap();
1265 assert_eq!(dot.inode, 2);
1266 assert_eq!(dot.modification, dir_mtime);
1267
1268 let dot_dot = entries.iter().find(|entry| entry.name == "..").unwrap();
1269 assert_eq!(dot_dot.inode, 1);
1270 assert_eq!(dot_dot.modification, root_mtime);
1271
1272 let item = entries.iter().find(|entry| entry.name == "item").unwrap();
1273 assert_eq!(item.inode, 3);
1274 assert_eq!(item.modification, file_mtime);
1275 }
1276}