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