xref: /DragonOS/kernel/src/filesystem/vfs/syscall.rs (revision 52bcb59e9286def2b66d766f6bf6f46745795ec8)
1 use core::ffi::CStr;
2 
3 use alloc::{
4     string::{String, ToString},
5     sync::Arc,
6     vec::Vec,
7 };
8 use system_error::SystemError;
9 
10 use crate::{
11     driver::base::{block::SeekFrom, device::device_number::DeviceNumber},
12     filesystem::vfs::file::FileDescriptorVec,
13     kerror,
14     libs::rwlock::RwLockWriteGuard,
15     mm::{verify_area, VirtAddr},
16     process::ProcessManager,
17     syscall::{
18         user_access::{check_and_clone_cstr, UserBufferReader, UserBufferWriter},
19         Syscall,
20     },
21     time::TimeSpec,
22 };
23 
24 use super::{
25     core::{do_mkdir, 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},
29     utils::{rsplit_path, user_path_at},
30     Dirent, FileType, IndexNode, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES,
31 };
32 // use crate::kdebug;
33 
34 pub const SEEK_SET: u32 = 0;
35 pub const SEEK_CUR: u32 = 1;
36 pub const SEEK_END: u32 = 2;
37 pub const SEEK_MAX: u32 = 3;
38 
39 bitflags! {
40     /// 文件类型和权限
41     #[repr(C)]
42     pub struct ModeType: u32 {
43         /// 掩码
44         const S_IFMT = 0o0_170_000;
45         /// 文件类型
46         const S_IFSOCK = 0o140000;
47         const S_IFLNK = 0o120000;
48         const S_IFREG = 0o100000;
49         const S_IFBLK = 0o060000;
50         const S_IFDIR = 0o040000;
51         const S_IFCHR = 0o020000;
52         const S_IFIFO = 0o010000;
53 
54         const S_ISUID = 0o004000;
55         const S_ISGID = 0o002000;
56         const S_ISVTX = 0o001000;
57         /// 文件用户权限
58         const S_IRWXU = 0o0700;
59         const S_IRUSR = 0o0400;
60         const S_IWUSR = 0o0200;
61         const S_IXUSR = 0o0100;
62         /// 文件组权限
63         const S_IRWXG = 0o0070;
64         const S_IRGRP = 0o0040;
65         const S_IWGRP = 0o0020;
66         const S_IXGRP = 0o0010;
67         /// 文件其他用户权限
68         const S_IRWXO = 0o0007;
69         const S_IROTH = 0o0004;
70         const S_IWOTH = 0o0002;
71         const S_IXOTH = 0o0001;
72 
73         /// 0o777
74         const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits;
75         /// 0o7777
76         const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits;
77         /// 0o444
78         const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits;
79         /// 0o222
80         const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits;
81         /// 0o111
82         const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits;
83 
84 
85     }
86 }
87 
88 #[repr(C)]
89 /// # 文件信息结构体
90 pub struct PosixKstat {
91     /// 硬件设备ID
92     dev_id: u64,
93     /// inode号
94     inode: u64,
95     /// 硬链接数
96     nlink: u64,
97     /// 文件权限
98     mode: ModeType,
99     /// 所有者用户ID
100     uid: i32,
101     /// 所有者组ID
102     gid: i32,
103     /// 设备ID
104     rdev: i64,
105     /// 文件大小
106     size: i64,
107     /// 文件系统块大小
108     blcok_size: i64,
109     /// 分配的512B块数
110     blocks: u64,
111     /// 最后访问时间
112     atime: TimeSpec,
113     /// 最后修改时间
114     mtime: TimeSpec,
115     /// 最后状态变化时间
116     ctime: TimeSpec,
117     /// 用于填充结构体大小的空白数据
118     pub _pad: [i8; 24],
119 }
120 impl PosixKstat {
121     fn new() -> Self {
122         Self {
123             inode: 0,
124             dev_id: 0,
125             mode: ModeType { bits: 0 },
126             nlink: 0,
127             uid: 0,
128             gid: 0,
129             rdev: 0,
130             size: 0,
131             atime: TimeSpec {
132                 tv_sec: 0,
133                 tv_nsec: 0,
134             },
135             mtime: TimeSpec {
136                 tv_sec: 0,
137                 tv_nsec: 0,
138             },
139             ctime: TimeSpec {
140                 tv_sec: 0,
141                 tv_nsec: 0,
142             },
143             blcok_size: 0,
144             blocks: 0,
145             _pad: Default::default(),
146         }
147     }
148 }
149 
150 ///
151 ///  Arguments for how openat2(2) should open the target path. If only @flags and
152 ///  @mode are non-zero, then openat2(2) operates very similarly to openat(2).
153 ///
154 ///  However, unlike openat(2), unknown or invalid bits in @flags result in
155 ///  -EINVAL rather than being silently ignored. @mode must be zero unless one of
156 ///  {O_CREAT, O_TMPFILE} are set.
157 ///
158 /// ## 成员变量
159 ///
160 /// - flags: O_* flags.
161 /// - mode: O_CREAT/O_TMPFILE file mode.
162 /// - resolve: RESOLVE_* flags.
163 #[derive(Debug, Clone, Copy)]
164 #[repr(C)]
165 pub struct PosixOpenHow {
166     pub flags: u64,
167     pub mode: u64,
168     pub resolve: u64,
169 }
170 
171 impl PosixOpenHow {
172     #[allow(dead_code)]
173     pub fn new(flags: u64, mode: u64, resolve: u64) -> Self {
174         Self {
175             flags,
176             mode,
177             resolve,
178         }
179     }
180 }
181 
182 #[derive(Debug, Clone, Copy)]
183 pub struct OpenHow {
184     pub o_flags: FileMode,
185     pub mode: ModeType,
186     pub resolve: OpenHowResolve,
187 }
188 
189 impl OpenHow {
190     pub fn new(mut o_flags: FileMode, mut mode: ModeType, resolve: OpenHowResolve) -> Self {
191         if !o_flags.contains(FileMode::O_CREAT) {
192             mode = ModeType::empty();
193         }
194 
195         if o_flags.contains(FileMode::O_PATH) {
196             o_flags = o_flags.intersection(FileMode::O_PATH_FLAGS);
197         }
198 
199         Self {
200             o_flags,
201             mode,
202             resolve,
203         }
204     }
205 }
206 
207 impl From<PosixOpenHow> for OpenHow {
208     fn from(posix_open_how: PosixOpenHow) -> Self {
209         let o_flags = FileMode::from_bits_truncate(posix_open_how.flags as u32);
210         let mode = ModeType::from_bits_truncate(posix_open_how.mode as u32);
211         let resolve = OpenHowResolve::from_bits_truncate(posix_open_how.resolve as u64);
212         return Self::new(o_flags, mode, resolve);
213     }
214 }
215 
216 bitflags! {
217     pub struct OpenHowResolve: u64{
218         /// Block mount-point crossings
219         ///     (including bind-mounts).
220         const RESOLVE_NO_XDEV = 0x01;
221 
222         /// Block traversal through procfs-style
223         ///     "magic-links"
224         const RESOLVE_NO_MAGICLINKS = 0x02;
225 
226         /// Block traversal through all symlinks
227         ///     (implies OEXT_NO_MAGICLINKS)
228         const RESOLVE_NO_SYMLINKS = 0x04;
229         /// Block "lexical" trickery like
230         ///     "..", symlinks, and absolute
231         const RESOLVE_BENEATH = 0x08;
232         /// Make all jumps to "/" and ".."
233         ///     be scoped inside the dirfd
234         ///     (similar to chroot(2)).
235         const RESOLVE_IN_ROOT = 0x10;
236         // Only complete if resolution can be
237         // 			completed through cached lookup. May
238         // 			return -EAGAIN if that's not
239         // 			possible.
240         const RESOLVE_CACHED = 0x20;
241     }
242 }
243 impl Syscall {
244     /// @brief 为当前进程打开一个文件
245     ///
246     /// @param path 文件路径
247     /// @param o_flags 打开文件的标志位
248     ///
249     /// @return 文件描述符编号,或者是错误码
250     pub fn open(
251         path: &str,
252         flags: FileMode,
253         mode: ModeType,
254         follow_symlink: bool,
255     ) -> Result<usize, SystemError> {
256         return do_sys_open(AtFlags::AT_FDCWD.bits(), path, flags, mode, follow_symlink);
257     }
258 
259     pub fn openat(
260         dirfd: i32,
261         path: &str,
262         o_flags: FileMode,
263         mode: ModeType,
264         follow_symlink: bool,
265     ) -> Result<usize, SystemError> {
266         return do_sys_open(dirfd, path, o_flags, mode, follow_symlink);
267     }
268 
269     /// @brief 关闭文件
270     ///
271     /// @param fd 文件描述符编号
272     ///
273     /// @return 成功返回0,失败返回错误码
274     pub fn close(fd: usize) -> Result<usize, SystemError> {
275         let binding = ProcessManager::current_pcb().fd_table();
276         let mut fd_table_guard = binding.write();
277 
278         let res = fd_table_guard.drop_fd(fd as i32).map(|_| 0);
279 
280         return res;
281     }
282 
283     /// @brief 发送命令到文件描述符对应的设备,
284     ///
285     /// @param fd 文件描述符编号
286     /// @param cmd 设备相关的请求类型
287     ///
288     /// @return Ok(usize) 成功返回0
289     /// @return Err(SystemError) 读取失败,返回posix错误码
290     pub fn ioctl(fd: usize, cmd: u32, data: usize) -> Result<usize, SystemError> {
291         let binding = ProcessManager::current_pcb().fd_table();
292         let fd_table_guard = binding.read();
293 
294         let file = fd_table_guard
295             .get_file_by_fd(fd as i32)
296             .ok_or(SystemError::EBADF)?;
297 
298         // drop guard 以避免无法调度的问题
299         drop(fd_table_guard);
300         let file = file.lock_no_preempt();
301         let r = file.inode().ioctl(cmd, data, &file.private_data);
302         return r;
303     }
304 
305     /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。
306     ///
307     /// @param fd 文件描述符编号
308     /// @param buf 输出缓冲区
309     ///
310     /// @return Ok(usize) 成功读取的数据的字节数
311     /// @return Err(SystemError) 读取失败,返回posix错误码
312     pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
313         let binding = ProcessManager::current_pcb().fd_table();
314         let fd_table_guard = binding.read();
315 
316         let file = fd_table_guard.get_file_by_fd(fd);
317         if file.is_none() {
318             return Err(SystemError::EBADF);
319         }
320         // drop guard 以避免无法调度的问题
321         drop(fd_table_guard);
322         let file = file.unwrap();
323 
324         return file.lock_no_preempt().read(buf.len(), buf);
325     }
326 
327     /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。
328     ///
329     /// @param fd 文件描述符编号
330     /// @param buf 输入缓冲区
331     ///
332     /// @return Ok(usize) 成功写入的数据的字节数
333     /// @return Err(SystemError) 写入失败,返回posix错误码
334     pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> {
335         let binding = ProcessManager::current_pcb().fd_table();
336         let fd_table_guard = binding.read();
337 
338         let file = fd_table_guard
339             .get_file_by_fd(fd)
340             .ok_or(SystemError::EBADF)?;
341 
342         // drop guard 以避免无法调度的问题
343         drop(fd_table_guard);
344         return file.lock_no_preempt().write(buf.len(), buf);
345     }
346 
347     /// @brief 调整文件操作指针的位置
348     ///
349     /// @param fd 文件描述符编号
350     /// @param seek 调整的方式
351     ///
352     /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量
353     /// @return Err(SystemError) 调整失败,返回posix错误码
354     pub fn lseek(fd: i32, seek: SeekFrom) -> Result<usize, SystemError> {
355         let binding = ProcessManager::current_pcb().fd_table();
356         let fd_table_guard = binding.read();
357         let file = fd_table_guard
358             .get_file_by_fd(fd)
359             .ok_or(SystemError::EBADF)?;
360 
361         // drop guard 以避免无法调度的问题
362         drop(fd_table_guard);
363         return file.lock_no_preempt().lseek(seek);
364     }
365 
366     /// # sys_pread64 系统调用的实际执行函数
367     ///
368     /// ## 参数
369     /// - `fd`: 文件描述符
370     /// - `buf`: 读出缓冲区
371     /// - `len`: 要读取的字节数
372     /// - `offset`: 文件偏移量
373     pub fn pread(fd: i32, buf: &mut [u8], len: usize, offset: usize) -> Result<usize, SystemError> {
374         let binding = ProcessManager::current_pcb().fd_table();
375         let fd_table_guard = binding.read();
376 
377         let file = fd_table_guard.get_file_by_fd(fd);
378         if file.is_none() {
379             return Err(SystemError::EBADF);
380         }
381         // drop guard 以避免无法调度的问题
382         drop(fd_table_guard);
383         let file = file.unwrap();
384 
385         return file.lock_no_preempt().pread(offset, len, buf);
386     }
387 
388     /// # sys_pwrite64 系统调用的实际执行函数
389     ///
390     /// ## 参数
391     /// - `fd`: 文件描述符
392     /// - `buf`: 写入缓冲区
393     /// - `len`: 要写入的字节数
394     /// - `offset`: 文件偏移量
395     pub fn pwrite(fd: i32, buf: &[u8], len: usize, offset: usize) -> Result<usize, SystemError> {
396         let binding = ProcessManager::current_pcb().fd_table();
397         let fd_table_guard = binding.read();
398 
399         let file = fd_table_guard.get_file_by_fd(fd);
400         if file.is_none() {
401             return Err(SystemError::EBADF);
402         }
403         // drop guard 以避免无法调度的问题
404         drop(fd_table_guard);
405         let file = file.unwrap();
406 
407         return file.lock_no_preempt().pwrite(offset, len, buf);
408     }
409 
410     /// @brief 切换工作目录
411     ///
412     /// @param dest_path 目标路径
413     ///
414     /// @return   返回码  描述
415     ///      0       |          成功
416     ///
417     ///   EACCESS    |        权限不足
418     ///
419     ///    ELOOP     | 解析path时遇到路径循环
420     ///
421     /// ENAMETOOLONG |       路径名过长
422     ///
423     ///    ENOENT    |  目标文件或目录不存在
424     ///
425     ///    ENODIR    |  检索期间发现非目录项
426     ///
427     ///    ENOMEM    |      系统内存不足
428     ///
429     ///    EFAULT    |       错误的地址
430     ///
431     /// ENAMETOOLONG |        路径过长
432     pub fn chdir(dest_path: &str) -> Result<usize, SystemError> {
433         let proc = ProcessManager::current_pcb();
434         // Copy path to kernel space to avoid some security issues
435         let path = dest_path.to_string();
436         let mut new_path = String::from("");
437         if path.len() > 0 {
438             let cwd = match path.as_bytes()[0] {
439                 b'/' => String::from("/"),
440                 _ => proc.basic().cwd(),
441             };
442             let mut cwd_vec: Vec<_> = cwd.split("/").filter(|&x| x != "").collect();
443             let path_split = path.split("/").filter(|&x| x != "");
444             for seg in path_split {
445                 if seg == ".." {
446                     cwd_vec.pop();
447                 } else if seg == "." {
448                     // 当前目录
449                 } else {
450                     cwd_vec.push(seg);
451                 }
452             }
453             //proc.basic().set_path(String::from(""));
454             for seg in cwd_vec {
455                 new_path.push_str("/");
456                 new_path.push_str(seg);
457             }
458             if new_path == "" {
459                 new_path = String::from("/");
460             }
461         }
462         let inode =
463             match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) {
464                 Err(e) => {
465                     kerror!("Change Directory Failed, Error = {:?}", e);
466                     return Err(SystemError::ENOENT);
467                 }
468                 Ok(i) => i,
469             };
470         let metadata = inode.metadata()?;
471         if metadata.file_type == FileType::Dir {
472             proc.basic_mut().set_cwd(String::from(new_path));
473             return Ok(0);
474         } else {
475             return Err(SystemError::ENOTDIR);
476         }
477     }
478 
479     /// @brief 获取当前进程的工作目录路径
480     ///
481     /// @param buf 指向缓冲区的指针
482     /// @param size 缓冲区的大小
483     ///
484     /// @return 成功,返回的指针指向包含工作目录路径的字符串
485     /// @return 错误,没有足够的空间
486     pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> {
487         let proc = ProcessManager::current_pcb();
488         let cwd = proc.basic().cwd();
489 
490         let cwd_bytes = cwd.as_bytes();
491         let cwd_len = cwd_bytes.len();
492         if cwd_len + 1 > buf.len() {
493             return Err(SystemError::ENOMEM);
494         }
495         buf[..cwd_len].copy_from_slice(cwd_bytes);
496         buf[cwd_len] = 0;
497 
498         return Ok(VirtAddr::new(buf.as_ptr() as usize));
499     }
500 
501     /// @brief 获取目录中的数据
502     ///
503     /// TODO: 这个函数的语义与Linux不一致,需要修改!!!
504     ///
505     /// @param fd 文件描述符号
506     /// @param buf 输出缓冲区
507     ///
508     /// @return 成功返回读取的字节数,失败返回错误码
509     pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
510         let dirent =
511             unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?;
512 
513         if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD {
514             return Err(SystemError::EBADF);
515         }
516 
517         // 获取fd
518         let binding = ProcessManager::current_pcb().fd_table();
519         let fd_table_guard = binding.read();
520         let file = fd_table_guard
521             .get_file_by_fd(fd)
522             .ok_or(SystemError::EBADF)?;
523 
524         // drop guard 以避免无法调度的问题
525         drop(fd_table_guard);
526 
527         let res = file.lock_no_preempt().readdir(dirent).map(|x| x as usize);
528 
529         return res;
530     }
531 
532     /// @brief 创建文件夹
533     ///
534     /// @param path(r8) 路径 / mode(r9) 模式
535     ///
536     /// @return uint64_t 负数错误码 / 0表示成功
537     pub fn mkdir(path: &str, mode: usize) -> Result<usize, SystemError> {
538         return do_mkdir(path, FileMode::from_bits_truncate(mode as u32)).map(|x| x as usize);
539     }
540 
541     /// **删除文件夹、取消文件的链接、删除文件的系统调用**
542     ///
543     /// ## 参数
544     ///
545     /// - `dirfd`:文件夹的文件描述符.目前暂未实现
546     /// - `pathname`:文件夹的路径
547     /// - `flags`:标志位
548     ///
549     ///
550     pub fn unlinkat(dirfd: i32, pathname: &str, flags: u32) -> Result<usize, SystemError> {
551         let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?;
552 
553         if flags.contains(AtFlags::AT_REMOVEDIR) {
554             // kdebug!("rmdir");
555             match do_remove_dir(dirfd, &pathname) {
556                 Err(err) => {
557                     kerror!("Failed to Remove Directory, Error Code = {:?}", err);
558                     return Err(err);
559                 }
560                 Ok(_) => {
561                     return Ok(0);
562                 }
563             }
564         }
565 
566         match do_unlink_at(dirfd, &pathname) {
567             Err(err) => {
568                 kerror!("Failed to Remove Directory, Error Code = {:?}", err);
569                 return Err(err);
570             }
571             Ok(_) => {
572                 return Ok(0);
573             }
574         }
575     }
576 
577     pub fn rmdir(pathname: *const u8) -> Result<usize, SystemError> {
578         let pathname: String = check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?;
579         if pathname.len() >= MAX_PATHLEN {
580             return Err(SystemError::ENAMETOOLONG);
581         }
582         let pathname = pathname.as_str().trim();
583         return do_remove_dir(AtFlags::AT_FDCWD.bits(), pathname).map(|v| v as usize);
584     }
585 
586     pub fn unlink(pathname: *const u8) -> Result<usize, SystemError> {
587         if pathname.is_null() {
588             return Err(SystemError::EFAULT);
589         }
590         let ureader = UserBufferReader::new(pathname, MAX_PATHLEN, true)?;
591 
592         let buf: &[u8] = ureader.buffer(0).unwrap();
593 
594         let pathname: &CStr = CStr::from_bytes_until_nul(buf).map_err(|_| SystemError::EINVAL)?;
595 
596         let pathname: &str = pathname.to_str().map_err(|_| SystemError::EINVAL)?;
597         if pathname.len() >= MAX_PATHLEN {
598             return Err(SystemError::ENAMETOOLONG);
599         }
600         let pathname = pathname.trim();
601 
602         return do_unlink_at(AtFlags::AT_FDCWD.bits(), pathname).map(|v| v as usize);
603     }
604 
605     /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd
606     pub fn dup(oldfd: i32) -> Result<usize, SystemError> {
607         let binding = ProcessManager::current_pcb().fd_table();
608         let mut fd_table_guard = binding.write();
609 
610         let old_file = fd_table_guard
611             .get_file_by_fd(oldfd)
612             .ok_or(SystemError::EBADF)?;
613 
614         let new_file = old_file
615             .lock_no_preempt()
616             .try_clone()
617             .ok_or(SystemError::EBADF)?;
618         // 申请文件描述符,并把文件对象存入其中
619         let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize);
620         return res;
621     }
622 
623     /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体,
624     /// 并返回新复制的文件结构体对应的fd.
625     /// 如果新fd已经打开,则会先关闭新fd.
626     ///
627     /// ## 参数
628     ///
629     /// - `oldfd`:旧文件描述符
630     /// - `newfd`:新文件描述符
631     ///
632     /// ## 返回值
633     ///
634     /// - 成功:新文件描述符
635     /// - 失败:错误码
636     pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> {
637         let binding = ProcessManager::current_pcb().fd_table();
638         let mut fd_table_guard = binding.write();
639         return Self::do_dup2(oldfd, newfd, &mut fd_table_guard);
640     }
641 
642     fn do_dup2(
643         oldfd: i32,
644         newfd: i32,
645         fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
646     ) -> Result<usize, SystemError> {
647         // 确认oldfd, newid是否有效
648         if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) {
649             return Err(SystemError::EBADF);
650         }
651 
652         if oldfd == newfd {
653             // 若oldfd与newfd相等
654             return Ok(newfd as usize);
655         }
656         let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some();
657         if new_exists {
658             // close newfd
659             if let Err(_) = fd_table_guard.drop_fd(newfd) {
660                 // An I/O error occurred while attempting to close fildes2.
661                 return Err(SystemError::EIO);
662             }
663         }
664 
665         let old_file = fd_table_guard
666             .get_file_by_fd(oldfd)
667             .ok_or(SystemError::EBADF)?;
668         let new_file = old_file
669             .lock_no_preempt()
670             .try_clone()
671             .ok_or(SystemError::EBADF)?;
672         // 申请文件描述符,并把文件对象存入其中
673         let res = fd_table_guard
674             .alloc_fd(new_file, Some(newfd))
675             .map(|x| x as usize);
676         return res;
677     }
678 
679     /// # fcntl
680     ///
681     /// ## 参数
682     ///
683     /// - `fd`:文件描述符
684     /// - `cmd`:命令
685     /// - `arg`:参数
686     pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> {
687         match cmd {
688             FcntlCommand::DupFd => {
689                 if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD {
690                     return Err(SystemError::EBADF);
691                 }
692                 let arg = arg as usize;
693                 for i in arg..FileDescriptorVec::PROCESS_MAX_FD {
694                     let binding = ProcessManager::current_pcb().fd_table();
695                     let mut fd_table_guard = binding.write();
696                     if fd_table_guard.get_file_by_fd(i as i32).is_none() {
697                         return Self::do_dup2(fd, i as i32, &mut fd_table_guard);
698                     }
699                 }
700                 return Err(SystemError::EMFILE);
701             }
702             FcntlCommand::GetFd => {
703                 // Get file descriptor flags.
704                 let binding = ProcessManager::current_pcb().fd_table();
705                 let fd_table_guard = binding.read();
706                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
707                     // drop guard 以避免无法调度的问题
708                     drop(fd_table_guard);
709 
710                     if file.lock().close_on_exec() {
711                         return Ok(FD_CLOEXEC as usize);
712                     }
713                 }
714                 return Err(SystemError::EBADF);
715             }
716             FcntlCommand::SetFd => {
717                 // Set file descriptor flags.
718                 let binding = ProcessManager::current_pcb().fd_table();
719                 let fd_table_guard = binding.write();
720 
721                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
722                     // drop guard 以避免无法调度的问题
723                     drop(fd_table_guard);
724                     let arg = arg as u32;
725                     if arg & FD_CLOEXEC != 0 {
726                         file.lock().set_close_on_exec(true);
727                     } else {
728                         file.lock().set_close_on_exec(false);
729                     }
730                     return Ok(0);
731                 }
732                 return Err(SystemError::EBADF);
733             }
734 
735             FcntlCommand::GetFlags => {
736                 // Get file status flags.
737                 let binding = ProcessManager::current_pcb().fd_table();
738                 let fd_table_guard = binding.read();
739 
740                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
741                     // drop guard 以避免无法调度的问题
742                     drop(fd_table_guard);
743                     return Ok(file.lock_no_preempt().mode().bits() as usize);
744                 }
745 
746                 return Err(SystemError::EBADF);
747             }
748             FcntlCommand::SetFlags => {
749                 // Set file status flags.
750                 let binding = ProcessManager::current_pcb().fd_table();
751                 let fd_table_guard = binding.write();
752 
753                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
754                     let arg = arg as u32;
755                     let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?;
756                     // drop guard 以避免无法调度的问题
757                     drop(fd_table_guard);
758                     file.lock_no_preempt().set_mode(mode)?;
759                     return Ok(0);
760                 }
761 
762                 return Err(SystemError::EBADF);
763             }
764             _ => {
765                 // TODO: unimplemented
766                 // 未实现的命令,返回0,不报错。
767 
768                 // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
769                 return Ok(0);
770             }
771         }
772     }
773 
774     /// # ftruncate
775     ///
776     /// ## 描述
777     ///
778     /// 改变文件大小.
779     /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充.
780     /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小.
781     ///
782     /// ## 参数
783     ///
784     /// - `fd`:文件描述符
785     /// - `len`:文件大小
786     ///
787     /// ## 返回值
788     ///
789     /// 如果成功,返回0,否则返回错误码.
790     pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> {
791         let binding = ProcessManager::current_pcb().fd_table();
792         let fd_table_guard = binding.read();
793 
794         if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
795             // drop guard 以避免无法调度的问题
796             drop(fd_table_guard);
797             let r = file.lock_no_preempt().ftruncate(len).map(|_| 0);
798             return r;
799         }
800 
801         return Err(SystemError::EBADF);
802     }
803 
804     fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> {
805         let binding = ProcessManager::current_pcb().fd_table();
806         let fd_table_guard = binding.read();
807         let file = fd_table_guard
808             .get_file_by_fd(fd)
809             .ok_or(SystemError::EBADF)?;
810         // drop guard 以避免无法调度的问题
811         drop(fd_table_guard);
812 
813         let mut kstat = PosixKstat::new();
814         // 获取文件信息
815         let metadata = file.lock().metadata()?;
816         kstat.size = metadata.size as i64;
817         kstat.dev_id = metadata.dev_id as u64;
818         kstat.inode = metadata.inode_id.into() as u64;
819         kstat.blcok_size = metadata.blk_size as i64;
820         kstat.blocks = metadata.blocks as u64;
821 
822         kstat.atime.tv_sec = metadata.atime.tv_sec;
823         kstat.atime.tv_nsec = metadata.atime.tv_nsec;
824         kstat.mtime.tv_sec = metadata.mtime.tv_sec;
825         kstat.mtime.tv_nsec = metadata.mtime.tv_nsec;
826         kstat.ctime.tv_sec = metadata.ctime.tv_sec;
827         kstat.ctime.tv_nsec = metadata.ctime.tv_nsec;
828 
829         kstat.nlink = metadata.nlinks as u64;
830         kstat.uid = metadata.uid as i32;
831         kstat.gid = metadata.gid as i32;
832         kstat.rdev = metadata.raw_dev.data() as i64;
833         kstat.mode = metadata.mode;
834         match file.lock().file_type() {
835             FileType::File => kstat.mode.insert(ModeType::S_IFREG),
836             FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR),
837             FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK),
838             FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR),
839             FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK),
840             FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK),
841             FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO),
842             FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR),
843             FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR),
844         }
845 
846         return Ok(kstat);
847     }
848 
849     pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
850         let kstat = Self::do_fstat(fd)?;
851         if usr_kstat.is_null() {
852             return Err(SystemError::EFAULT);
853         }
854         unsafe {
855             *usr_kstat = kstat;
856         }
857         return Ok(0);
858     }
859 
860     pub fn stat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
861         let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), true)?;
862         let r = Self::fstat(fd as i32, user_kstat);
863         Self::close(fd).ok();
864         return r;
865     }
866 
867     pub fn lstat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
868         let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), false)?;
869         let r = Self::fstat(fd as i32, user_kstat);
870         Self::close(fd).ok();
871         return r;
872     }
873 
874     pub fn mknod(
875         path_ptr: *const i8,
876         mode: ModeType,
877         dev_t: DeviceNumber,
878     ) -> Result<usize, SystemError> {
879         // 安全检验
880         let len = unsafe { CStr::from_ptr(path_ptr).to_bytes().len() };
881         let user_buffer = UserBufferReader::new(path_ptr, len, true)?;
882         let buf = user_buffer.read_from_user::<u8>(0)?;
883         let path = core::str::from_utf8(buf).map_err(|_| SystemError::EINVAL)?;
884 
885         // 文件名过长
886         if path.len() > MAX_PATHLEN as usize {
887             return Err(SystemError::ENAMETOOLONG);
888         }
889 
890         let inode: Result<Arc<dyn IndexNode>, SystemError> =
891             ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
892 
893         if inode.is_ok() {
894             return Err(SystemError::EEXIST);
895         }
896 
897         let (filename, parent_path) = rsplit_path(path);
898 
899         // 查找父目录
900         let parent_inode: Arc<dyn IndexNode> = ROOT_INODE()
901             .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
902         // 创建nod
903         parent_inode.mknod(filename, mode, dev_t)?;
904 
905         return Ok(0);
906     }
907 
908     pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
909         // IoVecs会进行用户态检验
910         let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?;
911 
912         let data = iovecs.gather();
913 
914         Self::write(fd, &data)
915     }
916 
917     pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
918         // IoVecs会进行用户态检验
919         let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?;
920 
921         let mut data = Vec::new();
922         data.resize(iovecs.0.iter().map(|x| x.len()).sum(), 0);
923 
924         let len = Self::read(fd, &mut data)?;
925 
926         iovecs.scatter(&data[..len]);
927 
928         return Ok(len);
929     }
930 
931     pub fn readlink_at(
932         dirfd: i32,
933         path: *const u8,
934         user_buf: *mut u8,
935         buf_size: usize,
936     ) -> Result<usize, SystemError> {
937         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
938         let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?;
939 
940         if path.len() == 0 {
941             return Err(SystemError::EINVAL);
942         }
943 
944         let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, &path)?;
945 
946         let inode = inode.lookup(path.as_str())?;
947         if inode.metadata()?.file_type != FileType::SymLink {
948             return Err(SystemError::EINVAL);
949         }
950 
951         let ubuf = user_buf.buffer::<u8>(0).unwrap();
952 
953         let mut file = File::new(inode, FileMode::O_RDONLY)?;
954 
955         let len = file.read(buf_size, ubuf)?;
956 
957         return Ok(len);
958     }
959 
960     pub fn readlink(
961         path: *const u8,
962         user_buf: *mut u8,
963         buf_size: usize,
964     ) -> Result<usize, SystemError> {
965         return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size);
966     }
967 
968     pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
969         return do_faccessat(
970             AtFlags::AT_FDCWD.bits(),
971             pathname,
972             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
973             0,
974         );
975     }
976 
977     pub fn faccessat2(
978         dirfd: i32,
979         pathname: *const u8,
980         mode: u32,
981         flags: u32,
982     ) -> Result<usize, SystemError> {
983         return do_faccessat(
984             dirfd,
985             pathname,
986             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
987             flags,
988         );
989     }
990 
991     pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
992         return do_fchmodat(
993             AtFlags::AT_FDCWD.bits(),
994             pathname,
995             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
996         );
997     }
998 
999     pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1000         return do_fchmodat(
1001             dirfd,
1002             pathname,
1003             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1004         );
1005     }
1006 
1007     pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> {
1008         let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
1009         let binding = ProcessManager::current_pcb().fd_table();
1010         let fd_table_guard = binding.read();
1011         let _file = fd_table_guard
1012             .get_file_by_fd(fd)
1013             .ok_or(SystemError::EBADF)?;
1014 
1015         // fchmod没完全实现,因此不修改文件的权限
1016         // todo: 实现fchmod
1017         kwarn!("fchmod not fully implemented");
1018         return Ok(0);
1019     }
1020 }
1021 
1022 #[repr(C)]
1023 #[derive(Debug, Clone, Copy)]
1024 pub struct IoVec {
1025     /// 缓冲区的起始地址
1026     pub iov_base: *mut u8,
1027     /// 缓冲区的长度
1028     pub iov_len: usize,
1029 }
1030 
1031 /// 用于存储多个来自用户空间的IoVec
1032 ///
1033 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。
1034 /// TODO:支持分散读写
1035 #[derive(Debug)]
1036 pub struct IoVecs(Vec<&'static mut [u8]>);
1037 
1038 impl IoVecs {
1039     /// 从用户空间的IoVec中构造IoVecs
1040     ///
1041     /// @param iov 用户空间的IoVec
1042     /// @param iovcnt 用户空间的IoVec的数量
1043     /// @param readv 是否为readv系统调用
1044     ///
1045     /// @return 构造成功返回IoVecs,否则返回错误码
1046     pub unsafe fn from_user(
1047         iov: *const IoVec,
1048         iovcnt: usize,
1049         _readv: bool,
1050     ) -> Result<Self, SystemError> {
1051         // 检查iov指针所在空间是否合法
1052         verify_area(
1053             VirtAddr::new(iov as usize),
1054             iovcnt * core::mem::size_of::<IoVec>(),
1055         )
1056         .map_err(|_| SystemError::EFAULT)?;
1057 
1058         // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放)
1059         let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt);
1060 
1061         let mut slices: Vec<&mut [u8]> = vec![];
1062         slices.reserve(iovs.len());
1063 
1064         for iov in iovs.iter() {
1065             if iov.iov_len == 0 {
1066                 continue;
1067             }
1068 
1069             verify_area(
1070                 VirtAddr::new(iov.iov_base as usize),
1071                 iovcnt * core::mem::size_of::<IoVec>(),
1072             )
1073             .map_err(|_| SystemError::EFAULT)?;
1074 
1075             slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len));
1076         }
1077 
1078         return Ok(Self(slices));
1079     }
1080 
1081     /// @brief 将IoVecs中的数据聚合到一个缓冲区中
1082     ///
1083     /// @return 返回聚合后的缓冲区
1084     pub fn gather(&self) -> Vec<u8> {
1085         let mut buf = Vec::new();
1086         for slice in self.0.iter() {
1087             buf.extend_from_slice(slice);
1088         }
1089         return buf;
1090     }
1091 
1092     /// @brief 将给定的数据分散写入到IoVecs中
1093     pub fn scatter(&mut self, data: &[u8]) {
1094         let mut data: &[u8] = data;
1095         for slice in self.0.iter_mut() {
1096             let len = core::cmp::min(slice.len(), data.len());
1097             if len == 0 {
1098                 continue;
1099             }
1100 
1101             slice[..len].copy_from_slice(&data[..len]);
1102             data = &data[len..];
1103         }
1104     }
1105 
1106     /// @brief 创建与IoVecs等长的缓冲区
1107     ///
1108     /// @param set_len 是否设置返回的Vec的len。
1109     /// 如果为true,则返回的Vec的len为所有IoVec的长度之和;
1110     /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和.
1111     ///
1112     /// @return 返回创建的缓冲区
1113     pub fn new_buf(&self, set_len: bool) -> Vec<u8> {
1114         let total_len: usize = self.0.iter().map(|slice| slice.len()).sum();
1115         let mut buf: Vec<u8> = Vec::with_capacity(total_len);
1116 
1117         if set_len {
1118             buf.resize(total_len, 0);
1119         }
1120         return buf;
1121     }
1122 }
1123