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