xref: /DragonOS/user/apps/test-symlink/src/main.rs (revision fae6e9ade46a52976ad5d099643d51cc20876448)
1 extern crate libc;
2 use core::ffi::{c_char, c_void};
3 use libc::{mount, umount};
4 use nix::errno::Errno;
5 use std::fs;
6 use std::os::unix::fs::symlink;
7 use std::path::Path;
8 
9 fn main() {
10     mount_test_ramfs();
11 
12     let target = "/mnt/myramfs/target_file.txt";
13     let symlink_path = "/mnt/myramfs/another/symlink_file.txt";
14     let dir = "/mnt/myramfs/another";
15 
16     fs::write(target, "This is the content of the target file.")
17         .expect("Failed to create target file");
18     fs::create_dir(dir).expect("Failed to create target dir");
19 
20     assert!(Path::new(target).exists(), "Target file was not created");
21     assert!(Path::new(dir).exists(), "Target dir was not created");
22 
23     symlink(target, symlink_path).expect("Failed to create symlink");
24 
25     assert!(Path::new(symlink_path).exists(), "Symlink was not created");
26 
27     let symlink_content = fs::read_link(symlink_path).expect("Failed to read symlink");
28     assert_eq!(
29         symlink_content.display().to_string(),
30         target,
31         "Symlink points to the wrong target"
32     );
33 
34     fs::remove_file(symlink_path).expect("Failed to remove symlink");
35     fs::remove_file(target).expect("Failed to remove target file");
36     fs::remove_dir(dir).expect("Failed to remove test_dir");
37 
38     assert!(!Path::new(symlink_path).exists(), "Symlink was not deleted");
39     assert!(!Path::new(target).exists(), "Target file was not deleted");
40     assert!(!Path::new(dir).exists(), "Directory was not deleted");
41 
42     umount_test_ramfs();
43 
44     println!("All tests passed!");
45 }
46 
47 fn mount_test_ramfs() {
48     let path = Path::new("mnt/myramfs");
49     let dir = fs::create_dir_all(path);
50     assert!(dir.is_ok(), "mkdir /mnt/myramfs failed");
51 
52     let source = b"\0".as_ptr() as *const c_char;
53     let target = b"/mnt/myramfs\0".as_ptr() as *const c_char;
54     let fstype = b"ramfs\0".as_ptr() as *const c_char;
55     // let flags = MS_BIND;
56     let flags = 0;
57     let data = std::ptr::null() as *const c_void;
58     let result = unsafe { mount(source, target, fstype, flags, data) };
59 
60     assert_eq!(
61         result,
62         0,
63         "Mount myramfs failed, errno: {}",
64         Errno::last().desc()
65     );
66     println!("Mount myramfs success!");
67 }
68 
69 fn umount_test_ramfs() {
70     let path = b"/mnt/myramfs\0".as_ptr() as *const c_char;
71     let result = unsafe { umount(path) };
72     if result != 0 {
73         let err = Errno::last();
74         println!("Errno: {}", err);
75         println!("Infomation: {}", err.desc());
76     }
77     assert_eq!(result, 0, "Umount myramfs failed");
78 }
79