xref: /DragonOS/kernel/src/filesystem/vfs/syscall.rs (revision 4256da7fb6ad25a3caab6f656607aaf047cb6446)
1 use core::ffi::c_void;
2 use core::mem::size_of;
3 
4 use alloc::string::ToString;
5 use alloc::{string::String, sync::Arc, vec::Vec};
6 use system_error::SystemError;
7 
8 use crate::producefs;
9 use crate::{
10     driver::base::{block::SeekFrom, device::device_number::DeviceNumber},
11     filesystem::vfs::{core as Vcore, file::FileDescriptorVec},
12     kerror,
13     libs::rwlock::RwLockWriteGuard,
14     mm::{verify_area, VirtAddr},
15     process::ProcessManager,
16     syscall::{
17         user_access::{self, check_and_clone_cstr, UserBufferWriter},
18         Syscall,
19     },
20     time::TimeSpec,
21 };
22 
23 use super::{
24     core::{do_mkdir, do_remove_dir, do_unlink_at},
25     fcntl::{AtFlags, FcntlCommand, FD_CLOEXEC},
26     file::{File, FileMode},
27     open::{do_faccessat, do_fchmodat, do_sys_open},
28     utils::{rsplit_path, user_path_at},
29     Dirent, FileType, IndexNode, FSMAKER, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES,
30 };
31 // use crate::kdebug;
32 
33 pub const SEEK_SET: u32 = 0;
34 pub const SEEK_CUR: u32 = 1;
35 pub const SEEK_END: u32 = 2;
36 pub const SEEK_MAX: u32 = 3;
37 
38 bitflags! {
39     /// 文件类型和权限
40     #[repr(C)]
41     pub struct ModeType: u32 {
42         /// 掩码
43         const S_IFMT = 0o0_170_000;
44         /// 文件类型
45         const S_IFSOCK = 0o140000;
46         const S_IFLNK = 0o120000;
47         const S_IFREG = 0o100000;
48         const S_IFBLK = 0o060000;
49         const S_IFDIR = 0o040000;
50         const S_IFCHR = 0o020000;
51         const S_IFIFO = 0o010000;
52 
53         const S_ISUID = 0o004000;
54         const S_ISGID = 0o002000;
55         const S_ISVTX = 0o001000;
56         /// 文件用户权限
57         const S_IRWXU = 0o0700;
58         const S_IRUSR = 0o0400;
59         const S_IWUSR = 0o0200;
60         const S_IXUSR = 0o0100;
61         /// 文件组权限
62         const S_IRWXG = 0o0070;
63         const S_IRGRP = 0o0040;
64         const S_IWGRP = 0o0020;
65         const S_IXGRP = 0o0010;
66         /// 文件其他用户权限
67         const S_IRWXO = 0o0007;
68         const S_IROTH = 0o0004;
69         const S_IWOTH = 0o0002;
70         const S_IXOTH = 0o0001;
71 
72         /// 0o777
73         const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits;
74         /// 0o7777
75         const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits;
76         /// 0o444
77         const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits;
78         /// 0o222
79         const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits;
80         /// 0o111
81         const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits;
82 
83 
84     }
85 }
86 
87 #[repr(C)]
88 #[derive(Clone, Copy)]
89 /// # 文件信息结构体
90 pub struct PosixKstat {
91     /// 硬件设备ID
92     dev_id: u64,
93     /// inode号
94     inode: u64,
95     /// 硬链接数
96     nlink: u64,
97     /// 文件权限
98     mode: ModeType,
99     /// 所有者用户ID
100     uid: i32,
101     /// 所有者组ID
102     gid: i32,
103     /// 设备ID
104     rdev: i64,
105     /// 文件大小
106     size: i64,
107     /// 文件系统块大小
108     blcok_size: i64,
109     /// 分配的512B块数
110     blocks: u64,
111     /// 最后访问时间
112     atime: TimeSpec,
113     /// 最后修改时间
114     mtime: TimeSpec,
115     /// 最后状态变化时间
116     ctime: TimeSpec,
117     /// 用于填充结构体大小的空白数据
118     pub _pad: [i8; 24],
119 }
120 impl PosixKstat {
121     fn new() -> Self {
122         Self {
123             inode: 0,
124             dev_id: 0,
125             mode: ModeType { bits: 0 },
126             nlink: 0,
127             uid: 0,
128             gid: 0,
129             rdev: 0,
130             size: 0,
131             atime: TimeSpec {
132                 tv_sec: 0,
133                 tv_nsec: 0,
134             },
135             mtime: TimeSpec {
136                 tv_sec: 0,
137                 tv_nsec: 0,
138             },
139             ctime: TimeSpec {
140                 tv_sec: 0,
141                 tv_nsec: 0,
142             },
143             blcok_size: 0,
144             blocks: 0,
145             _pad: Default::default(),
146         }
147     }
148 }
149 
150 #[repr(C)]
151 #[derive(Clone, Copy)]
152 /// # 文件信息结构体X
153 pub struct PosixStatx {
154     /* 0x00 */
155     stx_mask: PosixStatxMask,
156     /// 文件系统块大小
157     stx_blksize: u32,
158     /// Flags conveying information about the file [uncond]
159     stx_attributes: StxAttributes,
160     /* 0x10 */
161     /// 硬链接数
162     stx_nlink: u32,
163     /// 所有者用户ID
164     stx_uid: u32,
165     /// 所有者组ID
166     stx_gid: u32,
167     /// 文件权限
168     stx_mode: ModeType,
169 
170     /* 0x20 */
171     /// inode号
172     stx_inode: u64,
173     /// 文件大小
174     stx_size: i64,
175     /// 分配的512B块数
176     stx_blocks: u64,
177     /// Mask to show what's supported in stx_attributes
178     stx_attributes_mask: StxAttributes,
179 
180     /* 0x40 */
181     /// 最后访问时间
182     stx_atime: TimeSpec,
183     /// 文件创建时间
184     stx_btime: TimeSpec,
185     /// 最后状态变化时间
186     stx_ctime: TimeSpec,
187     /// 最后修改时间
188     stx_mtime: TimeSpec,
189 
190     /* 0x80 */
191     /// 主设备ID
192     stx_rdev_major: u32,
193     /// 次设备ID
194     stx_rdev_minor: u32,
195     /// 主硬件设备ID
196     stx_dev_major: u32,
197     /// 次硬件设备ID
198     stx_dev_minor: u32,
199 
200     /* 0x90 */
201     stx_mnt_id: u64,
202     stx_dio_mem_align: u32,
203     stx_dio_offset_align: u32,
204 }
205 impl PosixStatx {
206     fn new() -> Self {
207         Self {
208             stx_mask: PosixStatxMask::STATX_BASIC_STATS,
209             stx_blksize: 0,
210             stx_attributes: StxAttributes::STATX_ATTR_APPEND,
211             stx_nlink: 0,
212             stx_uid: 0,
213             stx_gid: 0,
214             stx_mode: ModeType { bits: 0 },
215             stx_inode: 0,
216             stx_size: 0,
217             stx_blocks: 0,
218             stx_attributes_mask: StxAttributes::STATX_ATTR_APPEND,
219             stx_atime: TimeSpec {
220                 tv_sec: 0,
221                 tv_nsec: 0,
222             },
223             stx_btime: TimeSpec {
224                 tv_sec: 0,
225                 tv_nsec: 0,
226             },
227             stx_ctime: TimeSpec {
228                 tv_sec: 0,
229                 tv_nsec: 0,
230             },
231             stx_mtime: TimeSpec {
232                 tv_sec: 0,
233                 tv_nsec: 0,
234             },
235             stx_rdev_major: 0,
236             stx_rdev_minor: 0,
237             stx_dev_major: 0,
238             stx_dev_minor: 0,
239             stx_mnt_id: 0,
240             stx_dio_mem_align: 0,
241             stx_dio_offset_align: 0,
242         }
243     }
244 }
245 
246 bitflags! {
247     pub struct PosixStatxMask: u32{
248         ///  Want stx_mode & S_IFMT
249         const STATX_TYPE = 0x00000001;
250 
251         /// Want stx_mode & ~S_IFMT
252         const STATX_MODE = 0x00000002;
253 
254         /// Want stx_nlink
255         const STATX_NLINK = 0x00000004;
256 
257         /// Want stx_uid
258         const STATX_UID = 0x00000008;
259 
260         /// Want stx_gid
261         const STATX_GID = 0x00000010;
262 
263         /// Want stx_atime
264         const STATX_ATIME = 0x00000020;
265 
266         /// Want stx_mtime
267         const STATX_MTIME = 0x00000040;
268 
269         /// Want stx_ctime
270         const STATX_CTIME = 0x00000080;
271 
272         /// Want stx_ino
273         const STATX_INO = 0x00000100;
274 
275         /// Want stx_size
276         const STATX_SIZE = 0x00000200;
277 
278         /// Want stx_blocks
279         const STATX_BLOCKS = 0x00000400;
280 
281         /// [All of the above]
282         const STATX_BASIC_STATS = 0x000007ff;
283 
284         /// Want stx_btime
285         const STATX_BTIME = 0x00000800;
286 
287         /// The same as STATX_BASIC_STATS | STATX_BTIME.
288         /// It is deprecated and should not be used.
289         const STATX_ALL = 0x00000fff;
290 
291         /// Want stx_mnt_id (since Linux 5.8)
292         const STATX_MNT_ID = 0x00001000;
293 
294         /// Want stx_dio_mem_align and stx_dio_offset_align
295         /// (since Linux 6.1; support varies by filesystem)
296         const STATX_DIOALIGN = 0x00002000;
297 
298         /// Reserved for future struct statx expansion
299         const STATX_RESERVED = 0x80000000;
300     }
301 }
302 
303 bitflags! {
304     pub struct StxAttributes: u64 {
305         /// 文件被文件系统压缩
306         const STATX_ATTR_COMPRESSED = 0x00000004;
307         /// 文件被标记为不可修改
308         const STATX_ATTR_IMMUTABLE = 0x00000010;
309         /// 文件是只追加写入的
310         const STATX_ATTR_APPEND = 0x00000020;
311         /// 文件不会被备份
312         const STATX_ATTR_NODUMP = 0x00000040;
313         /// 文件需要密钥才能在文件系统中解密
314         const STATX_ATTR_ENCRYPTED = 0x00000800;
315         /// 目录是自动挂载触发器
316         const STATX_ATTR_AUTOMOUNT = 0x00001000;
317         /// 目录是挂载点的根目录
318         const STATX_ATTR_MOUNT_ROOT = 0x00002000;
319         /// 文件受到 Verity 保护
320         const STATX_ATTR_VERITY = 0x00100000;
321         /// 文件当前处于 DAX 状态 CPU直接访问
322         const STATX_ATTR_DAX = 0x00200000;
323     }
324 }
325 
326 ///
327 ///  Arguments for how openat2(2) should open the target path. If only @flags and
328 ///  @mode are non-zero, then openat2(2) operates very similarly to openat(2).
329 ///
330 ///  However, unlike openat(2), unknown or invalid bits in @flags result in
331 ///  -EINVAL rather than being silently ignored. @mode must be zero unless one of
332 ///  {O_CREAT, O_TMPFILE} are set.
333 ///
334 /// ## 成员变量
335 ///
336 /// - flags: O_* flags.
337 /// - mode: O_CREAT/O_TMPFILE file mode.
338 /// - resolve: RESOLVE_* flags.
339 #[derive(Debug, Clone, Copy)]
340 #[repr(C)]
341 pub struct PosixOpenHow {
342     pub flags: u64,
343     pub mode: u64,
344     pub resolve: u64,
345 }
346 
347 impl PosixOpenHow {
348     #[allow(dead_code)]
349     pub fn new(flags: u64, mode: u64, resolve: u64) -> Self {
350         Self {
351             flags,
352             mode,
353             resolve,
354         }
355     }
356 }
357 
358 #[derive(Debug, Clone, Copy)]
359 pub struct OpenHow {
360     pub o_flags: FileMode,
361     pub mode: ModeType,
362     pub resolve: OpenHowResolve,
363 }
364 
365 impl OpenHow {
366     pub fn new(mut o_flags: FileMode, mut mode: ModeType, resolve: OpenHowResolve) -> Self {
367         if !o_flags.contains(FileMode::O_CREAT) {
368             mode = ModeType::empty();
369         }
370 
371         if o_flags.contains(FileMode::O_PATH) {
372             o_flags = o_flags.intersection(FileMode::O_PATH_FLAGS);
373         }
374 
375         Self {
376             o_flags,
377             mode,
378             resolve,
379         }
380     }
381 }
382 
383 impl From<PosixOpenHow> for OpenHow {
384     fn from(posix_open_how: PosixOpenHow) -> Self {
385         let o_flags = FileMode::from_bits_truncate(posix_open_how.flags as u32);
386         let mode = ModeType::from_bits_truncate(posix_open_how.mode as u32);
387         let resolve = OpenHowResolve::from_bits_truncate(posix_open_how.resolve);
388         return Self::new(o_flags, mode, resolve);
389     }
390 }
391 
392 bitflags! {
393     pub struct OpenHowResolve: u64{
394         /// Block mount-point crossings
395         ///     (including bind-mounts).
396         const RESOLVE_NO_XDEV = 0x01;
397 
398         /// Block traversal through procfs-style
399         ///     "magic-links"
400         const RESOLVE_NO_MAGICLINKS = 0x02;
401 
402         /// Block traversal through all symlinks
403         ///     (implies OEXT_NO_MAGICLINKS)
404         const RESOLVE_NO_SYMLINKS = 0x04;
405         /// Block "lexical" trickery like
406         ///     "..", symlinks, and absolute
407         const RESOLVE_BENEATH = 0x08;
408         /// Make all jumps to "/" and ".."
409         ///     be scoped inside the dirfd
410         ///     (similar to chroot(2)).
411         const RESOLVE_IN_ROOT = 0x10;
412         // Only complete if resolution can be
413         // 			completed through cached lookup. May
414         // 			return -EAGAIN if that's not
415         // 			possible.
416         const RESOLVE_CACHED = 0x20;
417     }
418 }
419 impl Syscall {
420     /// @brief 为当前进程打开一个文件
421     ///
422     /// @param path 文件路径
423     /// @param o_flags 打开文件的标志位
424     ///
425     /// @return 文件描述符编号,或者是错误码
426     pub fn open(
427         path: *const u8,
428         o_flags: u32,
429         mode: u32,
430         follow_symlink: bool,
431     ) -> Result<usize, SystemError> {
432         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
433         let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?;
434         let mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
435         return do_sys_open(
436             AtFlags::AT_FDCWD.bits(),
437             &path,
438             open_flags,
439             mode,
440             follow_symlink,
441         );
442     }
443 
444     pub fn openat(
445         dirfd: i32,
446         path: *const u8,
447         o_flags: u32,
448         mode: u32,
449         follow_symlink: bool,
450     ) -> Result<usize, SystemError> {
451         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
452         let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?;
453         let mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
454         return do_sys_open(dirfd, &path, open_flags, mode, follow_symlink);
455     }
456 
457     /// @brief 关闭文件
458     ///
459     /// @param fd 文件描述符编号
460     ///
461     /// @return 成功返回0,失败返回错误码
462     pub fn close(fd: usize) -> Result<usize, SystemError> {
463         let binding = ProcessManager::current_pcb().fd_table();
464         let mut fd_table_guard = binding.write();
465 
466         fd_table_guard.drop_fd(fd as i32).map(|_| 0)
467     }
468 
469     /// @brief 发送命令到文件描述符对应的设备,
470     ///
471     /// @param fd 文件描述符编号
472     /// @param cmd 设备相关的请求类型
473     ///
474     /// @return Ok(usize) 成功返回0
475     /// @return Err(SystemError) 读取失败,返回posix错误码
476     pub fn ioctl(fd: usize, cmd: u32, data: usize) -> Result<usize, SystemError> {
477         let binding = ProcessManager::current_pcb().fd_table();
478         let fd_table_guard = binding.read();
479 
480         let file = fd_table_guard
481             .get_file_by_fd(fd as i32)
482             .ok_or(SystemError::EBADF)?;
483 
484         // drop guard 以避免无法调度的问题
485         drop(fd_table_guard);
486         let file = file.lock_no_preempt();
487         let r = file.inode().ioctl(cmd, data, &file.private_data);
488         return r;
489     }
490 
491     /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。
492     ///
493     /// @param fd 文件描述符编号
494     /// @param buf 输出缓冲区
495     ///
496     /// @return Ok(usize) 成功读取的数据的字节数
497     /// @return Err(SystemError) 读取失败,返回posix错误码
498     pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
499         let binding = ProcessManager::current_pcb().fd_table();
500         let fd_table_guard = binding.read();
501 
502         let file = fd_table_guard.get_file_by_fd(fd);
503         if file.is_none() {
504             return Err(SystemError::EBADF);
505         }
506         // drop guard 以避免无法调度的问题
507         drop(fd_table_guard);
508         let file = file.unwrap();
509 
510         return file.lock_no_preempt().read(buf.len(), buf);
511     }
512 
513     /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。
514     ///
515     /// @param fd 文件描述符编号
516     /// @param buf 输入缓冲区
517     ///
518     /// @return Ok(usize) 成功写入的数据的字节数
519     /// @return Err(SystemError) 写入失败,返回posix错误码
520     pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> {
521         let binding = ProcessManager::current_pcb().fd_table();
522         let fd_table_guard = binding.read();
523 
524         let file = fd_table_guard
525             .get_file_by_fd(fd)
526             .ok_or(SystemError::EBADF)?;
527 
528         // drop guard 以避免无法调度的问题
529         drop(fd_table_guard);
530         return file.lock_no_preempt().write(buf.len(), buf);
531     }
532 
533     /// @brief 调整文件操作指针的位置
534     ///
535     /// @param fd 文件描述符编号
536     /// @param seek 调整的方式
537     ///
538     /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量
539     /// @return Err(SystemError) 调整失败,返回posix错误码
540     pub fn lseek(fd: i32, offset: i64, seek: u32) -> Result<usize, SystemError> {
541         let seek = match seek {
542             SEEK_SET => Ok(SeekFrom::SeekSet(offset)),
543             SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)),
544             SEEK_END => Ok(SeekFrom::SeekEnd(offset)),
545             SEEK_MAX => Ok(SeekFrom::SeekEnd(0)),
546             _ => Err(SystemError::EINVAL),
547         }?;
548 
549         let binding = ProcessManager::current_pcb().fd_table();
550         let fd_table_guard = binding.read();
551         let file = fd_table_guard
552             .get_file_by_fd(fd)
553             .ok_or(SystemError::EBADF)?;
554 
555         // drop guard 以避免无法调度的问题
556         drop(fd_table_guard);
557         return file.lock_no_preempt().lseek(seek);
558     }
559 
560     /// # sys_pread64 系统调用的实际执行函数
561     ///
562     /// ## 参数
563     /// - `fd`: 文件描述符
564     /// - `buf`: 读出缓冲区
565     /// - `len`: 要读取的字节数
566     /// - `offset`: 文件偏移量
567     pub fn pread(fd: i32, buf: &mut [u8], len: usize, offset: usize) -> Result<usize, SystemError> {
568         let binding = ProcessManager::current_pcb().fd_table();
569         let fd_table_guard = binding.read();
570 
571         let file = fd_table_guard.get_file_by_fd(fd);
572         if file.is_none() {
573             return Err(SystemError::EBADF);
574         }
575         // drop guard 以避免无法调度的问题
576         drop(fd_table_guard);
577         let file = file.unwrap();
578 
579         return file.lock_no_preempt().pread(offset, len, buf);
580     }
581 
582     /// # sys_pwrite64 系统调用的实际执行函数
583     ///
584     /// ## 参数
585     /// - `fd`: 文件描述符
586     /// - `buf`: 写入缓冲区
587     /// - `len`: 要写入的字节数
588     /// - `offset`: 文件偏移量
589     pub fn pwrite(fd: i32, buf: &[u8], len: usize, offset: usize) -> Result<usize, SystemError> {
590         let binding = ProcessManager::current_pcb().fd_table();
591         let fd_table_guard = binding.read();
592 
593         let file = fd_table_guard.get_file_by_fd(fd);
594         if file.is_none() {
595             return Err(SystemError::EBADF);
596         }
597         // drop guard 以避免无法调度的问题
598         drop(fd_table_guard);
599         let file = file.unwrap();
600 
601         return file.lock_no_preempt().pwrite(offset, len, buf);
602     }
603 
604     /// @brief 切换工作目录
605     ///
606     /// @param dest_path 目标路径
607     ///
608     /// @return   返回码  描述
609     ///      0       |          成功
610     ///
611     ///   EACCESS    |        权限不足
612     ///
613     ///    ELOOP     | 解析path时遇到路径循环
614     ///
615     /// ENAMETOOLONG |       路径名过长
616     ///
617     ///    ENOENT    |  目标文件或目录不存在
618     ///
619     ///    ENODIR    |  检索期间发现非目录项
620     ///
621     ///    ENOMEM    |      系统内存不足
622     ///
623     ///    EFAULT    |       错误的地址
624     ///
625     /// ENAMETOOLONG |        路径过长
626     pub fn chdir(path: *const u8) -> Result<usize, SystemError> {
627         if path.is_null() {
628             return Err(SystemError::EFAULT);
629         }
630 
631         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
632         let proc = ProcessManager::current_pcb();
633         // Copy path to kernel space to avoid some security issues
634         let mut new_path = String::from("");
635         if !path.is_empty() {
636             let cwd = match path.as_bytes()[0] {
637                 b'/' => String::from("/"),
638                 _ => proc.basic().cwd(),
639             };
640             let mut cwd_vec: Vec<_> = cwd.split('/').filter(|&x| !x.is_empty()).collect();
641             let path_split = path.split('/').filter(|&x| !x.is_empty());
642             for seg in path_split {
643                 if seg == ".." {
644                     cwd_vec.pop();
645                 } else if seg == "." {
646                     // 当前目录
647                 } else {
648                     cwd_vec.push(seg);
649                 }
650             }
651             //proc.basic().set_path(String::from(""));
652             for seg in cwd_vec {
653                 new_path.push('/');
654                 new_path.push_str(seg);
655             }
656             if new_path.is_empty() {
657                 new_path = String::from("/");
658             }
659         }
660         let inode =
661             match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) {
662                 Err(_) => {
663                     return Err(SystemError::ENOENT);
664                 }
665                 Ok(i) => i,
666             };
667         let metadata = inode.metadata()?;
668         if metadata.file_type == FileType::Dir {
669             proc.basic_mut().set_cwd(new_path);
670             return Ok(0);
671         } else {
672             return Err(SystemError::ENOTDIR);
673         }
674     }
675 
676     /// @brief 获取当前进程的工作目录路径
677     ///
678     /// @param buf 指向缓冲区的指针
679     /// @param size 缓冲区的大小
680     ///
681     /// @return 成功,返回的指针指向包含工作目录路径的字符串
682     /// @return 错误,没有足够的空间
683     pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> {
684         let proc = ProcessManager::current_pcb();
685         let cwd = proc.basic().cwd();
686 
687         let cwd_bytes = cwd.as_bytes();
688         let cwd_len = cwd_bytes.len();
689         if cwd_len + 1 > buf.len() {
690             return Err(SystemError::ENOMEM);
691         }
692         buf[..cwd_len].copy_from_slice(cwd_bytes);
693         buf[cwd_len] = 0;
694 
695         return Ok(VirtAddr::new(buf.as_ptr() as usize));
696     }
697 
698     /// @brief 获取目录中的数据
699     ///
700     /// TODO: 这个函数的语义与Linux不一致,需要修改!!!
701     ///
702     /// @param fd 文件描述符号
703     /// @param buf 输出缓冲区
704     ///
705     /// @return 成功返回读取的字节数,失败返回错误码
706     pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
707         let dirent =
708             unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?;
709 
710         if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD {
711             return Err(SystemError::EBADF);
712         }
713 
714         // 获取fd
715         let binding = ProcessManager::current_pcb().fd_table();
716         let fd_table_guard = binding.read();
717         let file = fd_table_guard
718             .get_file_by_fd(fd)
719             .ok_or(SystemError::EBADF)?;
720 
721         // drop guard 以避免无法调度的问题
722         drop(fd_table_guard);
723 
724         let res = file.lock_no_preempt().readdir(dirent).map(|x| x as usize);
725 
726         return res;
727     }
728 
729     /// @brief 创建文件夹
730     ///
731     /// @param path(r8) 路径 / mode(r9) 模式
732     ///
733     /// @return uint64_t 负数错误码 / 0表示成功
734     pub fn mkdir(path: *const u8, mode: usize) -> Result<usize, SystemError> {
735         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
736         return do_mkdir(&path, FileMode::from_bits_truncate(mode as u32)).map(|x| x as usize);
737     }
738 
739     /// **创建硬连接的系统调用**
740     ///
741     /// ## 参数
742     ///
743     /// - 'oldfd': 用于解析源文件路径的文件描述符
744     /// - 'old': 源文件路径
745     /// - 'newfd': 用于解析新文件路径的文件描述符
746     /// - 'new': 新文件将创建的路径
747     /// - 'flags': 标志位,仅以位或方式包含AT_EMPTY_PATH和AT_SYMLINK_FOLLOW
748     ///
749     ///
750     pub fn do_linkat(
751         oldfd: i32,
752         old: &str,
753         newfd: i32,
754         new: &str,
755         flags: AtFlags,
756     ) -> Result<usize, SystemError> {
757         // flag包含其他未规定值时返回EINVAL
758         if !(AtFlags::AT_EMPTY_PATH | AtFlags::AT_SYMLINK_FOLLOW).contains(flags) {
759             return Err(SystemError::EINVAL);
760         }
761         // TODO AT_EMPTY_PATH标志启用时,进行调用者CAP_DAC_READ_SEARCH或相似的检查
762         let symlink_times = if flags.contains(AtFlags::AT_SYMLINK_FOLLOW) {
763             0_usize
764         } else {
765             VFS_MAX_FOLLOW_SYMLINK_TIMES
766         };
767         let pcb = ProcessManager::current_pcb();
768 
769         // 得到源路径的inode
770         let old_inode: Arc<dyn IndexNode> = if old.is_empty() {
771             if flags.contains(AtFlags::AT_EMPTY_PATH) {
772                 // 在AT_EMPTY_PATH启用时,old可以为空,old_inode实际为oldfd所指文件,但该文件不能为目录。
773                 let binding = pcb.fd_table();
774                 let fd_table_guard = binding.read();
775                 let file = fd_table_guard
776                     .get_file_by_fd(oldfd)
777                     .ok_or(SystemError::EBADF)?;
778                 let old_inode = file.lock().inode();
779                 old_inode
780             } else {
781                 return Err(SystemError::ENONET);
782             }
783         } else {
784             let (old_begin_inode, old_remain_path) = user_path_at(&pcb, oldfd, old)?;
785             old_begin_inode.lookup_follow_symlink(&old_remain_path, symlink_times)?
786         };
787 
788         // old_inode为目录时返回EPERM
789         if old_inode.metadata().unwrap().file_type == FileType::Dir {
790             return Err(SystemError::EPERM);
791         }
792 
793         // 得到新创建节点的父节点
794         let (new_begin_inode, new_remain_path) = user_path_at(&pcb, newfd, new)?;
795         let (new_name, new_parent_path) = rsplit_path(&new_remain_path);
796         let new_parent =
797             new_begin_inode.lookup_follow_symlink(new_parent_path.unwrap_or("/"), symlink_times)?;
798 
799         // 被调用者利用downcast_ref判断两inode是否为同一文件系统
800         return new_parent.link(new_name, &old_inode).map(|_| 0);
801     }
802 
803     pub fn link(old: *const u8, new: *const u8) -> Result<usize, SystemError> {
804         let get_path = |cstr: *const u8| -> Result<String, SystemError> {
805             let res = check_and_clone_cstr(cstr, Some(MAX_PATHLEN))?;
806             if res.len() >= MAX_PATHLEN {
807                 return Err(SystemError::ENAMETOOLONG);
808             }
809             if res.is_empty() {
810                 return Err(SystemError::ENOENT);
811             }
812             Ok(res)
813         };
814         let old = get_path(old)?;
815         let new = get_path(new)?;
816         return Self::do_linkat(
817             AtFlags::AT_FDCWD.bits(),
818             &old,
819             AtFlags::AT_FDCWD.bits(),
820             &new,
821             AtFlags::empty(),
822         );
823     }
824 
825     pub fn linkat(
826         oldfd: i32,
827         old: *const u8,
828         newfd: i32,
829         new: *const u8,
830         flags: i32,
831     ) -> Result<usize, SystemError> {
832         let old = check_and_clone_cstr(old, Some(MAX_PATHLEN))?;
833         let new = check_and_clone_cstr(new, Some(MAX_PATHLEN))?;
834         if old.len() >= MAX_PATHLEN || new.len() >= MAX_PATHLEN {
835             return Err(SystemError::ENAMETOOLONG);
836         }
837         // old 根据flags & AtFlags::AT_EMPTY_PATH判空
838         if new.is_empty() {
839             return Err(SystemError::ENOENT);
840         }
841         let flags = AtFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
842         Self::do_linkat(oldfd, &old, newfd, &new, flags)
843     }
844 
845     /// **删除文件夹、取消文件的链接、删除文件的系统调用**
846     ///
847     /// ## 参数
848     ///
849     /// - `dirfd`:文件夹的文件描述符.目前暂未实现
850     /// - `pathname`:文件夹的路径
851     /// - `flags`:标志位
852     ///
853     ///
854     pub fn unlinkat(dirfd: i32, path: *const u8, flags: u32) -> Result<usize, SystemError> {
855         let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?;
856 
857         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
858 
859         if flags.contains(AtFlags::AT_REMOVEDIR) {
860             // kdebug!("rmdir");
861             match do_remove_dir(dirfd, &path) {
862                 Err(err) => {
863                     return Err(err);
864                 }
865                 Ok(_) => {
866                     return Ok(0);
867                 }
868             }
869         }
870 
871         match do_unlink_at(dirfd, &path) {
872             Err(err) => {
873                 return Err(err);
874             }
875             Ok(_) => {
876                 return Ok(0);
877             }
878         }
879     }
880 
881     pub fn rmdir(path: *const u8) -> Result<usize, SystemError> {
882         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
883         return do_remove_dir(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
884     }
885 
886     pub fn unlink(path: *const u8) -> Result<usize, SystemError> {
887         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
888         return do_unlink_at(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
889     }
890 
891     /// # 修改文件名
892     ///
893     ///
894     /// ## 参数
895     ///
896     /// - oldfd: 源文件描述符
897     /// - filename_from: 源文件路径
898     /// - newfd: 目标文件描述符
899     /// - filename_to: 目标文件路径
900     /// - flags: 标志位
901     ///
902     ///
903     /// ## 返回值
904     /// - Ok(返回值类型): 返回值的说明
905     /// - Err(错误值类型): 错误的说明
906     ///
907     pub fn do_renameat2(
908         oldfd: i32,
909         filename_from: *const u8,
910         newfd: i32,
911         filename_to: *const u8,
912         _flags: u32,
913     ) -> Result<usize, SystemError> {
914         let filename_from = check_and_clone_cstr(filename_from, Some(MAX_PATHLEN)).unwrap();
915         let filename_to = check_and_clone_cstr(filename_to, Some(MAX_PATHLEN)).unwrap();
916         // 文件名过长
917         if filename_from.len() > MAX_PATHLEN || filename_to.len() > MAX_PATHLEN {
918             return Err(SystemError::ENAMETOOLONG);
919         }
920 
921         //获取pcb,文件节点
922         let pcb = ProcessManager::current_pcb();
923         let (_old_inode_begin, old_remain_path) = user_path_at(&pcb, oldfd, &filename_from)?;
924         let (_new_inode_begin, new_remain_path) = user_path_at(&pcb, newfd, &filename_to)?;
925         //获取父目录
926         let (old_filename, old_parent_path) = rsplit_path(&old_remain_path);
927         let old_parent_inode = ROOT_INODE()
928             .lookup_follow_symlink(old_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
929         let (new_filename, new_parent_path) = rsplit_path(&new_remain_path);
930         let new_parent_inode = ROOT_INODE()
931             .lookup_follow_symlink(new_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
932         old_parent_inode.move_to(old_filename, &new_parent_inode, new_filename)?;
933         return Ok(0);
934     }
935 
936     /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd
937     pub fn dup(oldfd: i32) -> Result<usize, SystemError> {
938         let binding = ProcessManager::current_pcb().fd_table();
939         let mut fd_table_guard = binding.write();
940 
941         let old_file = fd_table_guard
942             .get_file_by_fd(oldfd)
943             .ok_or(SystemError::EBADF)?;
944 
945         let new_file = old_file
946             .lock_no_preempt()
947             .try_clone()
948             .ok_or(SystemError::EBADF)?;
949         // 申请文件描述符,并把文件对象存入其中
950         let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize);
951         return res;
952     }
953 
954     /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体,
955     /// 并返回新复制的文件结构体对应的fd.
956     /// 如果新fd已经打开,则会先关闭新fd.
957     ///
958     /// ## 参数
959     ///
960     /// - `oldfd`:旧文件描述符
961     /// - `newfd`:新文件描述符
962     ///
963     /// ## 返回值
964     ///
965     /// - 成功:新文件描述符
966     /// - 失败:错误码
967     pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> {
968         let binding = ProcessManager::current_pcb().fd_table();
969         let mut fd_table_guard = binding.write();
970         return Self::do_dup2(oldfd, newfd, &mut fd_table_guard);
971     }
972 
973     fn do_dup2(
974         oldfd: i32,
975         newfd: i32,
976         fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
977     ) -> Result<usize, SystemError> {
978         // 确认oldfd, newid是否有效
979         if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) {
980             return Err(SystemError::EBADF);
981         }
982 
983         if oldfd == newfd {
984             // 若oldfd与newfd相等
985             return Ok(newfd as usize);
986         }
987         let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some();
988         if new_exists {
989             // close newfd
990             if fd_table_guard.drop_fd(newfd).is_err() {
991                 // An I/O error occurred while attempting to close fildes2.
992                 return Err(SystemError::EIO);
993             }
994         }
995 
996         let old_file = fd_table_guard
997             .get_file_by_fd(oldfd)
998             .ok_or(SystemError::EBADF)?;
999         let new_file = old_file
1000             .lock_no_preempt()
1001             .try_clone()
1002             .ok_or(SystemError::EBADF)?;
1003         // 申请文件描述符,并把文件对象存入其中
1004         let res = fd_table_guard
1005             .alloc_fd(new_file, Some(newfd))
1006             .map(|x| x as usize);
1007         return res;
1008     }
1009 
1010     /// # fcntl
1011     ///
1012     /// ## 参数
1013     ///
1014     /// - `fd`:文件描述符
1015     /// - `cmd`:命令
1016     /// - `arg`:参数
1017     pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> {
1018         match cmd {
1019             FcntlCommand::DupFd => {
1020                 if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD {
1021                     return Err(SystemError::EBADF);
1022                 }
1023                 let arg = arg as usize;
1024                 for i in arg..FileDescriptorVec::PROCESS_MAX_FD {
1025                     let binding = ProcessManager::current_pcb().fd_table();
1026                     let mut fd_table_guard = binding.write();
1027                     if fd_table_guard.get_file_by_fd(i as i32).is_none() {
1028                         return Self::do_dup2(fd, i as i32, &mut fd_table_guard);
1029                     }
1030                 }
1031                 return Err(SystemError::EMFILE);
1032             }
1033             FcntlCommand::GetFd => {
1034                 // Get file descriptor flags.
1035                 let binding = ProcessManager::current_pcb().fd_table();
1036                 let fd_table_guard = binding.read();
1037                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1038                     // drop guard 以避免无法调度的问题
1039                     drop(fd_table_guard);
1040 
1041                     if file.lock().close_on_exec() {
1042                         return Ok(FD_CLOEXEC as usize);
1043                     }
1044                 }
1045                 return Err(SystemError::EBADF);
1046             }
1047             FcntlCommand::SetFd => {
1048                 // Set file descriptor flags.
1049                 let binding = ProcessManager::current_pcb().fd_table();
1050                 let fd_table_guard = binding.write();
1051 
1052                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1053                     // drop guard 以避免无法调度的问题
1054                     drop(fd_table_guard);
1055                     let arg = arg as u32;
1056                     if arg & FD_CLOEXEC != 0 {
1057                         file.lock().set_close_on_exec(true);
1058                     } else {
1059                         file.lock().set_close_on_exec(false);
1060                     }
1061                     return Ok(0);
1062                 }
1063                 return Err(SystemError::EBADF);
1064             }
1065 
1066             FcntlCommand::GetFlags => {
1067                 // Get file status flags.
1068                 let binding = ProcessManager::current_pcb().fd_table();
1069                 let fd_table_guard = binding.read();
1070 
1071                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1072                     // drop guard 以避免无法调度的问题
1073                     drop(fd_table_guard);
1074                     return Ok(file.lock_no_preempt().mode().bits() as usize);
1075                 }
1076 
1077                 return Err(SystemError::EBADF);
1078             }
1079             FcntlCommand::SetFlags => {
1080                 // Set file status flags.
1081                 let binding = ProcessManager::current_pcb().fd_table();
1082                 let fd_table_guard = binding.write();
1083 
1084                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1085                     let arg = arg as u32;
1086                     let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?;
1087                     // drop guard 以避免无法调度的问题
1088                     drop(fd_table_guard);
1089                     file.lock_no_preempt().set_mode(mode)?;
1090                     return Ok(0);
1091                 }
1092 
1093                 return Err(SystemError::EBADF);
1094             }
1095             _ => {
1096                 // TODO: unimplemented
1097                 // 未实现的命令,返回0,不报错。
1098 
1099                 // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
1100                 return Ok(0);
1101             }
1102         }
1103     }
1104 
1105     /// # ftruncate
1106     ///
1107     /// ## 描述
1108     ///
1109     /// 改变文件大小.
1110     /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充.
1111     /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小.
1112     ///
1113     /// ## 参数
1114     ///
1115     /// - `fd`:文件描述符
1116     /// - `len`:文件大小
1117     ///
1118     /// ## 返回值
1119     ///
1120     /// 如果成功,返回0,否则返回错误码.
1121     pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> {
1122         let binding = ProcessManager::current_pcb().fd_table();
1123         let fd_table_guard = binding.read();
1124 
1125         if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1126             // drop guard 以避免无法调度的问题
1127             drop(fd_table_guard);
1128             let r = file.lock_no_preempt().ftruncate(len).map(|_| 0);
1129             return r;
1130         }
1131 
1132         return Err(SystemError::EBADF);
1133     }
1134 
1135     fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> {
1136         let binding = ProcessManager::current_pcb().fd_table();
1137         let fd_table_guard = binding.read();
1138         let file = fd_table_guard
1139             .get_file_by_fd(fd)
1140             .ok_or(SystemError::EBADF)?;
1141         // drop guard 以避免无法调度的问题
1142         drop(fd_table_guard);
1143 
1144         let mut kstat = PosixKstat::new();
1145         // 获取文件信息
1146         let metadata = file.lock().metadata()?;
1147         kstat.size = metadata.size;
1148         kstat.dev_id = metadata.dev_id as u64;
1149         kstat.inode = metadata.inode_id.into() as u64;
1150         kstat.blcok_size = metadata.blk_size as i64;
1151         kstat.blocks = metadata.blocks as u64;
1152 
1153         kstat.atime.tv_sec = metadata.atime.tv_sec;
1154         kstat.atime.tv_nsec = metadata.atime.tv_nsec;
1155         kstat.mtime.tv_sec = metadata.mtime.tv_sec;
1156         kstat.mtime.tv_nsec = metadata.mtime.tv_nsec;
1157         kstat.ctime.tv_sec = metadata.ctime.tv_sec;
1158         kstat.ctime.tv_nsec = metadata.ctime.tv_nsec;
1159 
1160         kstat.nlink = metadata.nlinks as u64;
1161         kstat.uid = metadata.uid as i32;
1162         kstat.gid = metadata.gid as i32;
1163         kstat.rdev = metadata.raw_dev.data() as i64;
1164         kstat.mode = metadata.mode;
1165         match file.lock().file_type() {
1166             FileType::File => kstat.mode.insert(ModeType::S_IFREG),
1167             FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR),
1168             FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK),
1169             FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR),
1170             FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK),
1171             FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK),
1172             FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO),
1173             FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR),
1174             FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR),
1175         }
1176 
1177         return Ok(kstat);
1178     }
1179 
1180     pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
1181         let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixKstat>(), true)?;
1182         let kstat = Self::do_fstat(fd)?;
1183 
1184         writer.copy_one_to_user(&kstat, 0)?;
1185         return Ok(0);
1186     }
1187 
1188     pub fn stat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
1189         let fd = Self::open(
1190             path,
1191             FileMode::O_RDONLY.bits(),
1192             ModeType::empty().bits(),
1193             true,
1194         )?;
1195         let r = Self::fstat(fd as i32, user_kstat);
1196         Self::close(fd).ok();
1197         return r;
1198     }
1199 
1200     pub fn lstat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
1201         let fd = Self::open(
1202             path,
1203             FileMode::O_RDONLY.bits(),
1204             ModeType::empty().bits(),
1205             false,
1206         )?;
1207         let r = Self::fstat(fd as i32, user_kstat);
1208         Self::close(fd).ok();
1209         return r;
1210     }
1211 
1212     pub fn do_statx(
1213         fd: i32,
1214         path: *const u8,
1215         flags: u32,
1216         mask: u32,
1217         usr_kstat: *mut PosixStatx,
1218     ) -> Result<usize, SystemError> {
1219         if usr_kstat.is_null() {
1220             return Err(SystemError::EFAULT);
1221         }
1222 
1223         let mask = PosixStatxMask::from_bits_truncate(mask);
1224 
1225         if mask.contains(PosixStatxMask::STATX_RESERVED) {
1226             return Err(SystemError::ENAVAIL);
1227         }
1228 
1229         let flags = FileMode::from_bits_truncate(flags);
1230         let ofd = Self::open(path, flags.bits(), ModeType::empty().bits, true)?;
1231 
1232         let binding = ProcessManager::current_pcb().fd_table();
1233         let fd_table_guard = binding.read();
1234         let file = fd_table_guard
1235             .get_file_by_fd(ofd as i32)
1236             .ok_or(SystemError::EBADF)?;
1237         // drop guard 以避免无法调度的问题
1238         drop(fd_table_guard);
1239         let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixStatx>(), true)?;
1240         let mut tmp: PosixStatx = PosixStatx::new();
1241         // 获取文件信息
1242         let metadata = file.lock().metadata()?;
1243 
1244         tmp.stx_mask |= PosixStatxMask::STATX_BASIC_STATS;
1245         tmp.stx_blksize = metadata.blk_size as u32;
1246         if mask.contains(PosixStatxMask::STATX_MODE) || mask.contains(PosixStatxMask::STATX_TYPE) {
1247             tmp.stx_mode = metadata.mode;
1248         }
1249         if mask.contains(PosixStatxMask::STATX_NLINK) {
1250             tmp.stx_nlink = metadata.nlinks as u32;
1251         }
1252         if mask.contains(PosixStatxMask::STATX_UID) {
1253             tmp.stx_uid = metadata.uid as u32;
1254         }
1255         if mask.contains(PosixStatxMask::STATX_GID) {
1256             tmp.stx_gid = metadata.gid as u32;
1257         }
1258         if mask.contains(PosixStatxMask::STATX_ATIME) {
1259             tmp.stx_atime.tv_sec = metadata.atime.tv_sec;
1260             tmp.stx_atime.tv_nsec = metadata.atime.tv_nsec;
1261         }
1262         if mask.contains(PosixStatxMask::STATX_MTIME) {
1263             tmp.stx_mtime.tv_sec = metadata.ctime.tv_sec;
1264             tmp.stx_mtime.tv_nsec = metadata.ctime.tv_nsec;
1265         }
1266         if mask.contains(PosixStatxMask::STATX_CTIME) {
1267             // ctime是文件上次修改状态的时间
1268             tmp.stx_ctime.tv_sec = metadata.mtime.tv_sec;
1269             tmp.stx_ctime.tv_nsec = metadata.mtime.tv_nsec;
1270         }
1271         if mask.contains(PosixStatxMask::STATX_INO) {
1272             tmp.stx_inode = metadata.inode_id.into() as u64;
1273         }
1274         if mask.contains(PosixStatxMask::STATX_SIZE) {
1275             tmp.stx_size = metadata.size;
1276         }
1277         if mask.contains(PosixStatxMask::STATX_BLOCKS) {
1278             tmp.stx_blocks = metadata.blocks as u64;
1279         }
1280 
1281         if mask.contains(PosixStatxMask::STATX_BTIME) {
1282             // btime是文件创建时间
1283             tmp.stx_btime.tv_sec = metadata.ctime.tv_sec;
1284             tmp.stx_btime.tv_nsec = metadata.ctime.tv_nsec;
1285         }
1286         if mask.contains(PosixStatxMask::STATX_ALL) {
1287             tmp.stx_attributes = StxAttributes::STATX_ATTR_APPEND;
1288             tmp.stx_attributes_mask |=
1289                 StxAttributes::STATX_ATTR_AUTOMOUNT | StxAttributes::STATX_ATTR_DAX;
1290             tmp.stx_dev_major = metadata.dev_id as u32;
1291             tmp.stx_dev_minor = metadata.dev_id as u32; //
1292             tmp.stx_rdev_major = metadata.raw_dev.data();
1293             tmp.stx_rdev_minor = metadata.raw_dev.data();
1294         }
1295         if mask.contains(PosixStatxMask::STATX_MNT_ID) {
1296             tmp.stx_mnt_id = 0;
1297         }
1298         if mask.contains(PosixStatxMask::STATX_DIOALIGN) {
1299             tmp.stx_dio_mem_align = 0;
1300             tmp.stx_dio_offset_align = 0;
1301         }
1302 
1303         match file.lock().file_type() {
1304             FileType::File => tmp.stx_mode.insert(ModeType::S_IFREG),
1305             FileType::Dir => tmp.stx_mode.insert(ModeType::S_IFDIR),
1306             FileType::BlockDevice => tmp.stx_mode.insert(ModeType::S_IFBLK),
1307             FileType::CharDevice => tmp.stx_mode.insert(ModeType::S_IFCHR),
1308             FileType::SymLink => tmp.stx_mode.insert(ModeType::S_IFLNK),
1309             FileType::Socket => tmp.stx_mode.insert(ModeType::S_IFSOCK),
1310             FileType::Pipe => tmp.stx_mode.insert(ModeType::S_IFIFO),
1311             FileType::KvmDevice => tmp.stx_mode.insert(ModeType::S_IFCHR),
1312             FileType::FramebufferDevice => tmp.stx_mode.insert(ModeType::S_IFCHR),
1313         }
1314 
1315         writer.copy_one_to_user(&tmp, 0)?;
1316         Self::close(fd as usize).ok();
1317         return Ok(0);
1318     }
1319 
1320     pub fn mknod(
1321         path: *const u8,
1322         mode: ModeType,
1323         dev_t: DeviceNumber,
1324     ) -> Result<usize, SystemError> {
1325         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
1326         let path = path.as_str().trim();
1327 
1328         let inode: Result<Arc<dyn IndexNode>, SystemError> =
1329             ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
1330 
1331         if inode.is_ok() {
1332             return Err(SystemError::EEXIST);
1333         }
1334 
1335         let (filename, parent_path) = rsplit_path(path);
1336 
1337         // 查找父目录
1338         let parent_inode: Arc<dyn IndexNode> = ROOT_INODE()
1339             .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
1340         // 创建nod
1341         parent_inode.mknod(filename, mode, dev_t)?;
1342 
1343         return Ok(0);
1344     }
1345 
1346     pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
1347         // IoVecs会进行用户态检验
1348         let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?;
1349 
1350         let data = iovecs.gather();
1351 
1352         Self::write(fd, &data)
1353     }
1354 
1355     pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
1356         // IoVecs会进行用户态检验
1357         let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?;
1358 
1359         let mut data = vec![0; iovecs.0.iter().map(|x| x.len()).sum()];
1360 
1361         let len = Self::read(fd, &mut data)?;
1362 
1363         iovecs.scatter(&data[..len]);
1364 
1365         return Ok(len);
1366     }
1367 
1368     pub fn readlink_at(
1369         dirfd: i32,
1370         path: *const u8,
1371         user_buf: *mut u8,
1372         buf_size: usize,
1373     ) -> Result<usize, SystemError> {
1374         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
1375         let path = path.as_str().trim();
1376         let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?;
1377 
1378         let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path)?;
1379 
1380         let inode = inode.lookup(path.as_str())?;
1381         if inode.metadata()?.file_type != FileType::SymLink {
1382             return Err(SystemError::EINVAL);
1383         }
1384 
1385         let ubuf = user_buf.buffer::<u8>(0).unwrap();
1386 
1387         let mut file = File::new(inode, FileMode::O_RDONLY)?;
1388 
1389         let len = file.read(buf_size, ubuf)?;
1390 
1391         return Ok(len);
1392     }
1393 
1394     pub fn readlink(
1395         path: *const u8,
1396         user_buf: *mut u8,
1397         buf_size: usize,
1398     ) -> Result<usize, SystemError> {
1399         return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size);
1400     }
1401 
1402     pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1403         return do_faccessat(
1404             AtFlags::AT_FDCWD.bits(),
1405             pathname,
1406             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1407             0,
1408         );
1409     }
1410 
1411     pub fn faccessat2(
1412         dirfd: i32,
1413         pathname: *const u8,
1414         mode: u32,
1415         flags: u32,
1416     ) -> Result<usize, SystemError> {
1417         return do_faccessat(
1418             dirfd,
1419             pathname,
1420             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1421             flags,
1422         );
1423     }
1424 
1425     pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1426         return do_fchmodat(
1427             AtFlags::AT_FDCWD.bits(),
1428             pathname,
1429             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1430         );
1431     }
1432 
1433     pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1434         return do_fchmodat(
1435             dirfd,
1436             pathname,
1437             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1438         );
1439     }
1440 
1441     pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> {
1442         let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
1443         let binding = ProcessManager::current_pcb().fd_table();
1444         let fd_table_guard = binding.read();
1445         let _file = fd_table_guard
1446             .get_file_by_fd(fd)
1447             .ok_or(SystemError::EBADF)?;
1448 
1449         // fchmod没完全实现,因此不修改文件的权限
1450         // todo: 实现fchmod
1451         kwarn!("fchmod not fully implemented");
1452         return Ok(0);
1453     }
1454     /// #挂载文件系统
1455     ///
1456     /// 用于挂载文件系统,目前仅支持ramfs挂载
1457     ///
1458     /// ## 参数:
1459     ///
1460     /// - source       挂载设备(暂时不支持)
1461     /// - target       挂载目录
1462     /// - filesystemtype   文件系统
1463     /// - mountflags     挂载选项(暂未实现)
1464     /// - data        带数据挂载
1465     ///
1466     /// ## 返回值
1467     /// - Ok(0): 挂载成功
1468     /// - Err(SystemError) :挂载过程中出错
1469     pub fn mount(
1470         _source: *const u8,
1471         target: *const u8,
1472         filesystemtype: *const u8,
1473         _mountflags: usize,
1474         _data: *const c_void,
1475     ) -> Result<usize, SystemError> {
1476         let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?;
1477 
1478         let filesystemtype = user_access::check_and_clone_cstr(filesystemtype, Some(MAX_PATHLEN))?;
1479 
1480         let filesystemtype = producefs!(FSMAKER, filesystemtype)?;
1481 
1482         return Vcore::do_mount(filesystemtype, target.to_string().as_str());
1483     }
1484 
1485     // 想法:可以在VFS中实现一个文件系统分发器,流程如下:
1486     // 1. 接受从上方传来的文件类型字符串
1487     // 2. 将传入值与启动时准备好的字符串数组逐个比较(probe)
1488     // 3. 直接在函数内调用构造方法并直接返回文件系统对象
1489 }
1490 
1491 #[repr(C)]
1492 #[derive(Debug, Clone, Copy)]
1493 pub struct IoVec {
1494     /// 缓冲区的起始地址
1495     pub iov_base: *mut u8,
1496     /// 缓冲区的长度
1497     pub iov_len: usize,
1498 }
1499 
1500 /// 用于存储多个来自用户空间的IoVec
1501 ///
1502 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。
1503 /// TODO:支持分散读写
1504 #[derive(Debug)]
1505 pub struct IoVecs(Vec<&'static mut [u8]>);
1506 
1507 impl IoVecs {
1508     /// 从用户空间的IoVec中构造IoVecs
1509     ///
1510     /// @param iov 用户空间的IoVec
1511     /// @param iovcnt 用户空间的IoVec的数量
1512     /// @param readv 是否为readv系统调用
1513     ///
1514     /// @return 构造成功返回IoVecs,否则返回错误码
1515     pub unsafe fn from_user(
1516         iov: *const IoVec,
1517         iovcnt: usize,
1518         _readv: bool,
1519     ) -> Result<Self, SystemError> {
1520         // 检查iov指针所在空间是否合法
1521         verify_area(
1522             VirtAddr::new(iov as usize),
1523             iovcnt * core::mem::size_of::<IoVec>(),
1524         )
1525         .map_err(|_| SystemError::EFAULT)?;
1526 
1527         // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放)
1528         let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt);
1529 
1530         let mut slices: Vec<&mut [u8]> = vec![];
1531         slices.reserve(iovs.len());
1532 
1533         for iov in iovs.iter() {
1534             if iov.iov_len == 0 {
1535                 continue;
1536             }
1537 
1538             verify_area(
1539                 VirtAddr::new(iov.iov_base as usize),
1540                 iovcnt * core::mem::size_of::<IoVec>(),
1541             )
1542             .map_err(|_| SystemError::EFAULT)?;
1543 
1544             slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len));
1545         }
1546 
1547         return Ok(Self(slices));
1548     }
1549 
1550     /// @brief 将IoVecs中的数据聚合到一个缓冲区中
1551     ///
1552     /// @return 返回聚合后的缓冲区
1553     pub fn gather(&self) -> Vec<u8> {
1554         let mut buf = Vec::new();
1555         for slice in self.0.iter() {
1556             buf.extend_from_slice(slice);
1557         }
1558         return buf;
1559     }
1560 
1561     /// @brief 将给定的数据分散写入到IoVecs中
1562     pub fn scatter(&mut self, data: &[u8]) {
1563         let mut data: &[u8] = data;
1564         for slice in self.0.iter_mut() {
1565             let len = core::cmp::min(slice.len(), data.len());
1566             if len == 0 {
1567                 continue;
1568             }
1569 
1570             slice[..len].copy_from_slice(&data[..len]);
1571             data = &data[len..];
1572         }
1573     }
1574 
1575     /// @brief 创建与IoVecs等长的缓冲区
1576     ///
1577     /// @param set_len 是否设置返回的Vec的len。
1578     /// 如果为true,则返回的Vec的len为所有IoVec的长度之和;
1579     /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和.
1580     ///
1581     /// @return 返回创建的缓冲区
1582     pub fn new_buf(&self, set_len: bool) -> Vec<u8> {
1583         let total_len: usize = self.0.iter().map(|slice| slice.len()).sum();
1584         let mut buf: Vec<u8> = Vec::with_capacity(total_len);
1585 
1586         if set_len {
1587             buf.resize(total_len, 0);
1588         }
1589         return buf;
1590     }
1591 }
1592