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