xref: /DragonOS/kernel/src/filesystem/vfs/syscall.rs (revision 9993c0fc61e9603f631bd6748ff0b4fecb7bd483)
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 r = file.lock_no_preempt().inode().ioctl(cmd, data);
301         return r;
302     }
303 
304     /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。
305     ///
306     /// @param fd 文件描述符编号
307     /// @param buf 输出缓冲区
308     ///
309     /// @return Ok(usize) 成功读取的数据的字节数
310     /// @return Err(SystemError) 读取失败,返回posix错误码
311     pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
312         let binding = ProcessManager::current_pcb().fd_table();
313         let fd_table_guard = binding.read();
314 
315         let file = fd_table_guard.get_file_by_fd(fd);
316         if file.is_none() {
317             return Err(SystemError::EBADF);
318         }
319         // drop guard 以避免无法调度的问题
320         drop(fd_table_guard);
321         let file = file.unwrap();
322 
323         return file.lock_no_preempt().read(buf.len(), buf);
324     }
325 
326     /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。
327     ///
328     /// @param fd 文件描述符编号
329     /// @param buf 输入缓冲区
330     ///
331     /// @return Ok(usize) 成功写入的数据的字节数
332     /// @return Err(SystemError) 写入失败,返回posix错误码
333     pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> {
334         let binding = ProcessManager::current_pcb().fd_table();
335         let fd_table_guard = binding.read();
336 
337         let file = fd_table_guard
338             .get_file_by_fd(fd)
339             .ok_or(SystemError::EBADF)?;
340 
341         // drop guard 以避免无法调度的问题
342         drop(fd_table_guard);
343         return file.lock_no_preempt().write(buf.len(), buf);
344     }
345 
346     /// @brief 调整文件操作指针的位置
347     ///
348     /// @param fd 文件描述符编号
349     /// @param seek 调整的方式
350     ///
351     /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量
352     /// @return Err(SystemError) 调整失败,返回posix错误码
353     pub fn lseek(fd: i32, seek: SeekFrom) -> Result<usize, SystemError> {
354         let binding = ProcessManager::current_pcb().fd_table();
355         let fd_table_guard = binding.read();
356         let file = fd_table_guard
357             .get_file_by_fd(fd)
358             .ok_or(SystemError::EBADF)?;
359 
360         // drop guard 以避免无法调度的问题
361         drop(fd_table_guard);
362         return file.lock_no_preempt().lseek(seek);
363     }
364 
365     /// # sys_pread64 系统调用的实际执行函数
366     ///
367     /// ## 参数
368     /// - `fd`: 文件描述符
369     /// - `buf`: 读出缓冲区
370     /// - `len`: 要读取的字节数
371     /// - `offset`: 文件偏移量
372     pub fn pread(fd: i32, buf: &mut [u8], len: usize, offset: usize) -> Result<usize, SystemError> {
373         let binding = ProcessManager::current_pcb().fd_table();
374         let fd_table_guard = binding.read();
375 
376         let file = fd_table_guard.get_file_by_fd(fd);
377         if file.is_none() {
378             return Err(SystemError::EBADF);
379         }
380         // drop guard 以避免无法调度的问题
381         drop(fd_table_guard);
382         let file = file.unwrap();
383 
384         return file.lock_no_preempt().pread(offset, len, buf);
385     }
386 
387     /// # sys_pwrite64 系统调用的实际执行函数
388     ///
389     /// ## 参数
390     /// - `fd`: 文件描述符
391     /// - `buf`: 写入缓冲区
392     /// - `len`: 要写入的字节数
393     /// - `offset`: 文件偏移量
394     pub fn pwrite(fd: i32, buf: &[u8], len: usize, offset: usize) -> Result<usize, SystemError> {
395         let binding = ProcessManager::current_pcb().fd_table();
396         let fd_table_guard = binding.read();
397 
398         let file = fd_table_guard.get_file_by_fd(fd);
399         if file.is_none() {
400             return Err(SystemError::EBADF);
401         }
402         // drop guard 以避免无法调度的问题
403         drop(fd_table_guard);
404         let file = file.unwrap();
405 
406         return file.lock_no_preempt().pwrite(offset, len, buf);
407     }
408 
409     /// @brief 切换工作目录
410     ///
411     /// @param dest_path 目标路径
412     ///
413     /// @return   返回码  描述
414     ///      0       |          成功
415     ///
416     ///   EACCESS    |        权限不足
417     ///
418     ///    ELOOP     | 解析path时遇到路径循环
419     ///
420     /// ENAMETOOLONG |       路径名过长
421     ///
422     ///    ENOENT    |  目标文件或目录不存在
423     ///
424     ///    ENODIR    |  检索期间发现非目录项
425     ///
426     ///    ENOMEM    |      系统内存不足
427     ///
428     ///    EFAULT    |       错误的地址
429     ///
430     /// ENAMETOOLONG |        路径过长
431     pub fn chdir(dest_path: &str) -> Result<usize, SystemError> {
432         let proc = ProcessManager::current_pcb();
433         // Copy path to kernel space to avoid some security issues
434         let path = dest_path.to_string();
435         let mut new_path = String::from("");
436         if path.len() > 0 {
437             let cwd = match path.as_bytes()[0] {
438                 b'/' => String::from("/"),
439                 _ => proc.basic().cwd(),
440             };
441             let mut cwd_vec: Vec<_> = cwd.split("/").filter(|&x| x != "").collect();
442             let path_split = path.split("/").filter(|&x| x != "");
443             for seg in path_split {
444                 if seg == ".." {
445                     cwd_vec.pop();
446                 } else if seg == "." {
447                     // 当前目录
448                 } else {
449                     cwd_vec.push(seg);
450                 }
451             }
452             //proc.basic().set_path(String::from(""));
453             for seg in cwd_vec {
454                 new_path.push_str("/");
455                 new_path.push_str(seg);
456             }
457             if new_path == "" {
458                 new_path = String::from("/");
459             }
460         }
461         let inode =
462             match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) {
463                 Err(e) => {
464                     kerror!("Change Directory Failed, Error = {:?}", e);
465                     return Err(SystemError::ENOENT);
466                 }
467                 Ok(i) => i,
468             };
469         let metadata = inode.metadata()?;
470         if metadata.file_type == FileType::Dir {
471             proc.basic_mut().set_cwd(String::from(new_path));
472             return Ok(0);
473         } else {
474             return Err(SystemError::ENOTDIR);
475         }
476     }
477 
478     /// @brief 获取当前进程的工作目录路径
479     ///
480     /// @param buf 指向缓冲区的指针
481     /// @param size 缓冲区的大小
482     ///
483     /// @return 成功,返回的指针指向包含工作目录路径的字符串
484     /// @return 错误,没有足够的空间
485     pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> {
486         let proc = ProcessManager::current_pcb();
487         let cwd = proc.basic().cwd();
488 
489         let cwd_bytes = cwd.as_bytes();
490         let cwd_len = cwd_bytes.len();
491         if cwd_len + 1 > buf.len() {
492             return Err(SystemError::ENOMEM);
493         }
494         buf[..cwd_len].copy_from_slice(cwd_bytes);
495         buf[cwd_len] = 0;
496 
497         return Ok(VirtAddr::new(buf.as_ptr() as usize));
498     }
499 
500     /// @brief 获取目录中的数据
501     ///
502     /// TODO: 这个函数的语义与Linux不一致,需要修改!!!
503     ///
504     /// @param fd 文件描述符号
505     /// @param buf 输出缓冲区
506     ///
507     /// @return 成功返回读取的字节数,失败返回错误码
508     pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
509         let dirent =
510             unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?;
511 
512         if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD {
513             return Err(SystemError::EBADF);
514         }
515 
516         // 获取fd
517         let binding = ProcessManager::current_pcb().fd_table();
518         let fd_table_guard = binding.read();
519         let file = fd_table_guard
520             .get_file_by_fd(fd)
521             .ok_or(SystemError::EBADF)?;
522 
523         // drop guard 以避免无法调度的问题
524         drop(fd_table_guard);
525 
526         let res = file.lock_no_preempt().readdir(dirent).map(|x| x as usize);
527 
528         return res;
529     }
530 
531     /// @brief 创建文件夹
532     ///
533     /// @param path(r8) 路径 / mode(r9) 模式
534     ///
535     /// @return uint64_t 负数错误码 / 0表示成功
536     pub fn mkdir(path: &str, mode: usize) -> Result<usize, SystemError> {
537         return do_mkdir(path, FileMode::from_bits_truncate(mode as u32)).map(|x| x as usize);
538     }
539 
540     /// **删除文件夹、取消文件的链接、删除文件的系统调用**
541     ///
542     /// ## 参数
543     ///
544     /// - `dirfd`:文件夹的文件描述符.目前暂未实现
545     /// - `pathname`:文件夹的路径
546     /// - `flags`:标志位
547     ///
548     ///
549     pub fn unlinkat(dirfd: i32, pathname: &str, flags: u32) -> Result<usize, SystemError> {
550         let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?;
551 
552         if flags.contains(AtFlags::AT_REMOVEDIR) {
553             // kdebug!("rmdir");
554             match do_remove_dir(dirfd, &pathname) {
555                 Err(err) => {
556                     kerror!("Failed to Remove Directory, Error Code = {:?}", err);
557                     return Err(err);
558                 }
559                 Ok(_) => {
560                     return Ok(0);
561                 }
562             }
563         }
564 
565         match do_unlink_at(dirfd, &pathname) {
566             Err(err) => {
567                 kerror!("Failed to Remove Directory, Error Code = {:?}", err);
568                 return Err(err);
569             }
570             Ok(_) => {
571                 return Ok(0);
572             }
573         }
574     }
575 
576     pub fn unlink(pathname: *const u8) -> Result<usize, SystemError> {
577         if pathname.is_null() {
578             return Err(SystemError::EFAULT);
579         }
580         let ureader = UserBufferReader::new(pathname, MAX_PATHLEN, true)?;
581 
582         let buf: &[u8] = ureader.buffer(0).unwrap();
583 
584         let pathname: &CStr = CStr::from_bytes_until_nul(buf).map_err(|_| SystemError::EINVAL)?;
585 
586         let pathname: &str = pathname.to_str().map_err(|_| SystemError::EINVAL)?;
587         if pathname.len() >= MAX_PATHLEN {
588             return Err(SystemError::ENAMETOOLONG);
589         }
590         let pathname = pathname.trim();
591 
592         return do_unlink_at(AtFlags::AT_FDCWD.bits(), pathname).map(|v| v as usize);
593     }
594 
595     /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd
596     pub fn dup(oldfd: i32) -> Result<usize, SystemError> {
597         let binding = ProcessManager::current_pcb().fd_table();
598         let mut fd_table_guard = binding.write();
599 
600         let old_file = fd_table_guard
601             .get_file_by_fd(oldfd)
602             .ok_or(SystemError::EBADF)?;
603 
604         let new_file = old_file
605             .lock_no_preempt()
606             .try_clone()
607             .ok_or(SystemError::EBADF)?;
608         // 申请文件描述符,并把文件对象存入其中
609         let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize);
610         return res;
611     }
612 
613     /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体,
614     /// 并返回新复制的文件结构体对应的fd.
615     /// 如果新fd已经打开,则会先关闭新fd.
616     ///
617     /// ## 参数
618     ///
619     /// - `oldfd`:旧文件描述符
620     /// - `newfd`:新文件描述符
621     ///
622     /// ## 返回值
623     ///
624     /// - 成功:新文件描述符
625     /// - 失败:错误码
626     pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> {
627         let binding = ProcessManager::current_pcb().fd_table();
628         let mut fd_table_guard = binding.write();
629         return Self::do_dup2(oldfd, newfd, &mut fd_table_guard);
630     }
631 
632     fn do_dup2(
633         oldfd: i32,
634         newfd: i32,
635         fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
636     ) -> Result<usize, SystemError> {
637         // 确认oldfd, newid是否有效
638         if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) {
639             return Err(SystemError::EBADF);
640         }
641 
642         if oldfd == newfd {
643             // 若oldfd与newfd相等
644             return Ok(newfd as usize);
645         }
646         let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some();
647         if new_exists {
648             // close newfd
649             if let Err(_) = fd_table_guard.drop_fd(newfd) {
650                 // An I/O error occurred while attempting to close fildes2.
651                 return Err(SystemError::EIO);
652             }
653         }
654 
655         let old_file = fd_table_guard
656             .get_file_by_fd(oldfd)
657             .ok_or(SystemError::EBADF)?;
658         let new_file = old_file
659             .lock_no_preempt()
660             .try_clone()
661             .ok_or(SystemError::EBADF)?;
662         // 申请文件描述符,并把文件对象存入其中
663         let res = fd_table_guard
664             .alloc_fd(new_file, Some(newfd))
665             .map(|x| x as usize);
666         return res;
667     }
668 
669     /// # fcntl
670     ///
671     /// ## 参数
672     ///
673     /// - `fd`:文件描述符
674     /// - `cmd`:命令
675     /// - `arg`:参数
676     pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> {
677         match cmd {
678             FcntlCommand::DupFd => {
679                 if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD {
680                     return Err(SystemError::EBADF);
681                 }
682                 let arg = arg as usize;
683                 for i in arg..FileDescriptorVec::PROCESS_MAX_FD {
684                     let binding = ProcessManager::current_pcb().fd_table();
685                     let mut fd_table_guard = binding.write();
686                     if fd_table_guard.get_file_by_fd(fd).is_none() {
687                         return Self::do_dup2(fd, i as i32, &mut fd_table_guard);
688                     }
689                 }
690                 return Err(SystemError::EMFILE);
691             }
692             FcntlCommand::GetFd => {
693                 // Get file descriptor flags.
694                 let binding = ProcessManager::current_pcb().fd_table();
695                 let fd_table_guard = binding.read();
696                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
697                     // drop guard 以避免无法调度的问题
698                     drop(fd_table_guard);
699 
700                     if file.lock().close_on_exec() {
701                         return Ok(FD_CLOEXEC as usize);
702                     }
703                 }
704                 return Err(SystemError::EBADF);
705             }
706             FcntlCommand::SetFd => {
707                 // Set file descriptor flags.
708                 let binding = ProcessManager::current_pcb().fd_table();
709                 let fd_table_guard = binding.write();
710 
711                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
712                     // drop guard 以避免无法调度的问题
713                     drop(fd_table_guard);
714                     let arg = arg as u32;
715                     if arg & FD_CLOEXEC != 0 {
716                         file.lock().set_close_on_exec(true);
717                     } else {
718                         file.lock().set_close_on_exec(false);
719                     }
720                     return Ok(0);
721                 }
722                 return Err(SystemError::EBADF);
723             }
724 
725             FcntlCommand::GetFlags => {
726                 // Get file status flags.
727                 let binding = ProcessManager::current_pcb().fd_table();
728                 let fd_table_guard = binding.read();
729 
730                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
731                     // drop guard 以避免无法调度的问题
732                     drop(fd_table_guard);
733                     return Ok(file.lock_no_preempt().mode().bits() as usize);
734                 }
735 
736                 return Err(SystemError::EBADF);
737             }
738             FcntlCommand::SetFlags => {
739                 // Set file status flags.
740                 let binding = ProcessManager::current_pcb().fd_table();
741                 let fd_table_guard = binding.write();
742 
743                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
744                     let arg = arg as u32;
745                     let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?;
746                     // drop guard 以避免无法调度的问题
747                     drop(fd_table_guard);
748                     file.lock_no_preempt().set_mode(mode)?;
749                     return Ok(0);
750                 }
751 
752                 return Err(SystemError::EBADF);
753             }
754             _ => {
755                 // TODO: unimplemented
756                 // 未实现的命令,返回0,不报错。
757 
758                 // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
759                 return Ok(0);
760             }
761         }
762     }
763 
764     /// # ftruncate
765     ///
766     /// ## 描述
767     ///
768     /// 改变文件大小.
769     /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充.
770     /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小.
771     ///
772     /// ## 参数
773     ///
774     /// - `fd`:文件描述符
775     /// - `len`:文件大小
776     ///
777     /// ## 返回值
778     ///
779     /// 如果成功,返回0,否则返回错误码.
780     pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> {
781         let binding = ProcessManager::current_pcb().fd_table();
782         let fd_table_guard = binding.read();
783 
784         if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
785             // drop guard 以避免无法调度的问题
786             drop(fd_table_guard);
787             let r = file.lock_no_preempt().ftruncate(len).map(|_| 0);
788             return r;
789         }
790 
791         return Err(SystemError::EBADF);
792     }
793 
794     fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> {
795         let binding = ProcessManager::current_pcb().fd_table();
796         let fd_table_guard = binding.read();
797         let file = fd_table_guard
798             .get_file_by_fd(fd)
799             .ok_or(SystemError::EBADF)?;
800         // drop guard 以避免无法调度的问题
801         drop(fd_table_guard);
802 
803         let mut kstat = PosixKstat::new();
804         // 获取文件信息
805         let metadata = file.lock().metadata()?;
806         kstat.size = metadata.size as i64;
807         kstat.dev_id = metadata.dev_id as u64;
808         kstat.inode = metadata.inode_id.into() as u64;
809         kstat.blcok_size = metadata.blk_size as i64;
810         kstat.blocks = metadata.blocks as u64;
811 
812         kstat.atime.tv_sec = metadata.atime.tv_sec;
813         kstat.atime.tv_nsec = metadata.atime.tv_nsec;
814         kstat.mtime.tv_sec = metadata.mtime.tv_sec;
815         kstat.mtime.tv_nsec = metadata.mtime.tv_nsec;
816         kstat.ctime.tv_sec = metadata.ctime.tv_sec;
817         kstat.ctime.tv_nsec = metadata.ctime.tv_nsec;
818 
819         kstat.nlink = metadata.nlinks as u64;
820         kstat.uid = metadata.uid as i32;
821         kstat.gid = metadata.gid as i32;
822         kstat.rdev = metadata.raw_dev.data() as i64;
823         kstat.mode = metadata.mode;
824         match file.lock().file_type() {
825             FileType::File => kstat.mode.insert(ModeType::S_IFREG),
826             FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR),
827             FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK),
828             FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR),
829             FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK),
830             FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK),
831             FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO),
832             FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR),
833             FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR),
834         }
835 
836         return Ok(kstat);
837     }
838 
839     pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
840         let kstat = Self::do_fstat(fd)?;
841         if usr_kstat.is_null() {
842             return Err(SystemError::EFAULT);
843         }
844         unsafe {
845             *usr_kstat = kstat;
846         }
847         return Ok(0);
848     }
849 
850     pub fn stat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
851         let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), true)?;
852         let r = Self::fstat(fd as i32, user_kstat);
853         Self::close(fd).ok();
854         return r;
855     }
856 
857     pub fn lstat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
858         let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), false)?;
859         let r = Self::fstat(fd as i32, user_kstat);
860         Self::close(fd).ok();
861         return r;
862     }
863 
864     pub fn mknod(
865         path_ptr: *const i8,
866         mode: ModeType,
867         dev_t: DeviceNumber,
868     ) -> Result<usize, SystemError> {
869         // 安全检验
870         let len = unsafe { CStr::from_ptr(path_ptr).to_bytes().len() };
871         let user_buffer = UserBufferReader::new(path_ptr, len, true)?;
872         let buf = user_buffer.read_from_user::<u8>(0)?;
873         let path = core::str::from_utf8(buf).map_err(|_| SystemError::EINVAL)?;
874 
875         // 文件名过长
876         if path.len() > MAX_PATHLEN as usize {
877             return Err(SystemError::ENAMETOOLONG);
878         }
879 
880         let inode: Result<Arc<dyn IndexNode>, SystemError> =
881             ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
882 
883         if inode.is_ok() {
884             return Err(SystemError::EEXIST);
885         }
886 
887         let (filename, parent_path) = rsplit_path(path);
888 
889         // 查找父目录
890         let parent_inode: Arc<dyn IndexNode> = ROOT_INODE()
891             .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
892         // 创建nod
893         parent_inode.mknod(filename, mode, dev_t)?;
894 
895         return Ok(0);
896     }
897 
898     pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
899         // IoVecs会进行用户态检验
900         let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?;
901 
902         let data = iovecs.gather();
903 
904         Self::write(fd, &data)
905     }
906 
907     pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
908         // IoVecs会进行用户态检验
909         let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?;
910 
911         let mut data = Vec::new();
912         data.resize(iovecs.0.iter().map(|x| x.len()).sum(), 0);
913 
914         let len = Self::read(fd, &mut data)?;
915 
916         iovecs.scatter(&data[..len]);
917 
918         return Ok(len);
919     }
920 
921     pub fn readlink_at(
922         dirfd: i32,
923         path: *const u8,
924         user_buf: *mut u8,
925         buf_size: usize,
926     ) -> Result<usize, SystemError> {
927         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
928         let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?;
929 
930         if path.len() == 0 {
931             return Err(SystemError::EINVAL);
932         }
933 
934         let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, &path)?;
935 
936         let inode = inode.lookup(path.as_str())?;
937         if inode.metadata()?.file_type != FileType::SymLink {
938             return Err(SystemError::EINVAL);
939         }
940 
941         let ubuf = user_buf.buffer::<u8>(0).unwrap();
942 
943         let mut file = File::new(inode, FileMode::O_RDONLY)?;
944 
945         let len = file.read(buf_size, ubuf)?;
946 
947         return Ok(len);
948     }
949 
950     pub fn readlink(
951         path: *const u8,
952         user_buf: *mut u8,
953         buf_size: usize,
954     ) -> Result<usize, SystemError> {
955         return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size);
956     }
957 
958     pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
959         return do_faccessat(
960             AtFlags::AT_FDCWD.bits(),
961             pathname,
962             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
963             0,
964         );
965     }
966 
967     pub fn faccessat2(
968         dirfd: i32,
969         pathname: *const u8,
970         mode: u32,
971         flags: u32,
972     ) -> Result<usize, SystemError> {
973         return do_faccessat(
974             dirfd,
975             pathname,
976             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
977             flags,
978         );
979     }
980 
981     pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
982         return do_fchmodat(
983             AtFlags::AT_FDCWD.bits(),
984             pathname,
985             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
986         );
987     }
988 
989     pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
990         return do_fchmodat(
991             dirfd,
992             pathname,
993             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
994         );
995     }
996 
997     pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> {
998         let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
999         let binding = ProcessManager::current_pcb().fd_table();
1000         let fd_table_guard = binding.read();
1001         let _file = fd_table_guard
1002             .get_file_by_fd(fd)
1003             .ok_or(SystemError::EBADF)?;
1004 
1005         // fchmod没完全实现,因此不修改文件的权限
1006         // todo: 实现fchmod
1007         kwarn!("fchmod not fully implemented");
1008         return Ok(0);
1009     }
1010 }
1011 
1012 #[repr(C)]
1013 #[derive(Debug, Clone, Copy)]
1014 pub struct IoVec {
1015     /// 缓冲区的起始地址
1016     pub iov_base: *mut u8,
1017     /// 缓冲区的长度
1018     pub iov_len: usize,
1019 }
1020 
1021 /// 用于存储多个来自用户空间的IoVec
1022 ///
1023 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。
1024 /// TODO:支持分散读写
1025 #[derive(Debug)]
1026 pub struct IoVecs(Vec<&'static mut [u8]>);
1027 
1028 impl IoVecs {
1029     /// 从用户空间的IoVec中构造IoVecs
1030     ///
1031     /// @param iov 用户空间的IoVec
1032     /// @param iovcnt 用户空间的IoVec的数量
1033     /// @param readv 是否为readv系统调用
1034     ///
1035     /// @return 构造成功返回IoVecs,否则返回错误码
1036     pub unsafe fn from_user(
1037         iov: *const IoVec,
1038         iovcnt: usize,
1039         _readv: bool,
1040     ) -> Result<Self, SystemError> {
1041         // 检查iov指针所在空间是否合法
1042         verify_area(
1043             VirtAddr::new(iov as usize),
1044             iovcnt * core::mem::size_of::<IoVec>(),
1045         )
1046         .map_err(|_| SystemError::EFAULT)?;
1047 
1048         // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放)
1049         let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt);
1050 
1051         let mut slices: Vec<&mut [u8]> = vec![];
1052         slices.reserve(iovs.len());
1053 
1054         for iov in iovs.iter() {
1055             if iov.iov_len == 0 {
1056                 continue;
1057             }
1058 
1059             verify_area(
1060                 VirtAddr::new(iov.iov_base as usize),
1061                 iovcnt * core::mem::size_of::<IoVec>(),
1062             )
1063             .map_err(|_| SystemError::EFAULT)?;
1064 
1065             slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len));
1066         }
1067 
1068         return Ok(Self(slices));
1069     }
1070 
1071     /// @brief 将IoVecs中的数据聚合到一个缓冲区中
1072     ///
1073     /// @return 返回聚合后的缓冲区
1074     pub fn gather(&self) -> Vec<u8> {
1075         let mut buf = Vec::new();
1076         for slice in self.0.iter() {
1077             buf.extend_from_slice(slice);
1078         }
1079         return buf;
1080     }
1081 
1082     /// @brief 将给定的数据分散写入到IoVecs中
1083     pub fn scatter(&mut self, data: &[u8]) {
1084         let mut data: &[u8] = data;
1085         for slice in self.0.iter_mut() {
1086             let len = core::cmp::min(slice.len(), data.len());
1087             if len == 0 {
1088                 continue;
1089             }
1090 
1091             slice[..len].copy_from_slice(&data[..len]);
1092             data = &data[len..];
1093         }
1094     }
1095 
1096     /// @brief 创建与IoVecs等长的缓冲区
1097     ///
1098     /// @param set_len 是否设置返回的Vec的len。
1099     /// 如果为true,则返回的Vec的len为所有IoVec的长度之和;
1100     /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和.
1101     ///
1102     /// @return 返回创建的缓冲区
1103     pub fn new_buf(&self, set_len: bool) -> Vec<u8> {
1104         let total_len: usize = self.0.iter().map(|slice| slice.len()).sum();
1105         let mut buf: Vec<u8> = Vec::with_capacity(total_len);
1106 
1107         if set_len {
1108             buf.resize(total_len, 0);
1109         }
1110         return buf;
1111     }
1112 }
1113