xref: /DragonOS/kernel/src/filesystem/vfs/syscall.rs (revision 338f6903262c5031abad3c8e361813355a27fcdb)
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 unlink(pathname: *const u8) -> Result<usize, SystemError> {
578         if pathname.is_null() {
579             return Err(SystemError::EFAULT);
580         }
581         let ureader = UserBufferReader::new(pathname, MAX_PATHLEN, true)?;
582 
583         let buf: &[u8] = ureader.buffer(0).unwrap();
584 
585         let pathname: &CStr = CStr::from_bytes_until_nul(buf).map_err(|_| SystemError::EINVAL)?;
586 
587         let pathname: &str = pathname.to_str().map_err(|_| SystemError::EINVAL)?;
588         if pathname.len() >= MAX_PATHLEN {
589             return Err(SystemError::ENAMETOOLONG);
590         }
591         let pathname = pathname.trim();
592 
593         return do_unlink_at(AtFlags::AT_FDCWD.bits(), pathname).map(|v| v as usize);
594     }
595 
596     /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd
597     pub fn dup(oldfd: i32) -> Result<usize, SystemError> {
598         let binding = ProcessManager::current_pcb().fd_table();
599         let mut fd_table_guard = binding.write();
600 
601         let old_file = fd_table_guard
602             .get_file_by_fd(oldfd)
603             .ok_or(SystemError::EBADF)?;
604 
605         let new_file = old_file
606             .lock_no_preempt()
607             .try_clone()
608             .ok_or(SystemError::EBADF)?;
609         // 申请文件描述符,并把文件对象存入其中
610         let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize);
611         return res;
612     }
613 
614     /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体,
615     /// 并返回新复制的文件结构体对应的fd.
616     /// 如果新fd已经打开,则会先关闭新fd.
617     ///
618     /// ## 参数
619     ///
620     /// - `oldfd`:旧文件描述符
621     /// - `newfd`:新文件描述符
622     ///
623     /// ## 返回值
624     ///
625     /// - 成功:新文件描述符
626     /// - 失败:错误码
627     pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> {
628         let binding = ProcessManager::current_pcb().fd_table();
629         let mut fd_table_guard = binding.write();
630         return Self::do_dup2(oldfd, newfd, &mut fd_table_guard);
631     }
632 
633     fn do_dup2(
634         oldfd: i32,
635         newfd: i32,
636         fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
637     ) -> Result<usize, SystemError> {
638         // 确认oldfd, newid是否有效
639         if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) {
640             return Err(SystemError::EBADF);
641         }
642 
643         if oldfd == newfd {
644             // 若oldfd与newfd相等
645             return Ok(newfd as usize);
646         }
647         let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some();
648         if new_exists {
649             // close newfd
650             if let Err(_) = fd_table_guard.drop_fd(newfd) {
651                 // An I/O error occurred while attempting to close fildes2.
652                 return Err(SystemError::EIO);
653             }
654         }
655 
656         let old_file = fd_table_guard
657             .get_file_by_fd(oldfd)
658             .ok_or(SystemError::EBADF)?;
659         let new_file = old_file
660             .lock_no_preempt()
661             .try_clone()
662             .ok_or(SystemError::EBADF)?;
663         // 申请文件描述符,并把文件对象存入其中
664         let res = fd_table_guard
665             .alloc_fd(new_file, Some(newfd))
666             .map(|x| x as usize);
667         return res;
668     }
669 
670     /// # fcntl
671     ///
672     /// ## 参数
673     ///
674     /// - `fd`:文件描述符
675     /// - `cmd`:命令
676     /// - `arg`:参数
677     pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> {
678         match cmd {
679             FcntlCommand::DupFd => {
680                 if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD {
681                     return Err(SystemError::EBADF);
682                 }
683                 let arg = arg as usize;
684                 for i in arg..FileDescriptorVec::PROCESS_MAX_FD {
685                     let binding = ProcessManager::current_pcb().fd_table();
686                     let mut fd_table_guard = binding.write();
687                     if fd_table_guard.get_file_by_fd(i as i32).is_none() {
688                         return Self::do_dup2(fd, i as i32, &mut fd_table_guard);
689                     }
690                 }
691                 return Err(SystemError::EMFILE);
692             }
693             FcntlCommand::GetFd => {
694                 // Get file descriptor flags.
695                 let binding = ProcessManager::current_pcb().fd_table();
696                 let fd_table_guard = binding.read();
697                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
698                     // drop guard 以避免无法调度的问题
699                     drop(fd_table_guard);
700 
701                     if file.lock().close_on_exec() {
702                         return Ok(FD_CLOEXEC as usize);
703                     }
704                 }
705                 return Err(SystemError::EBADF);
706             }
707             FcntlCommand::SetFd => {
708                 // Set file descriptor flags.
709                 let binding = ProcessManager::current_pcb().fd_table();
710                 let fd_table_guard = binding.write();
711 
712                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
713                     // drop guard 以避免无法调度的问题
714                     drop(fd_table_guard);
715                     let arg = arg as u32;
716                     if arg & FD_CLOEXEC != 0 {
717                         file.lock().set_close_on_exec(true);
718                     } else {
719                         file.lock().set_close_on_exec(false);
720                     }
721                     return Ok(0);
722                 }
723                 return Err(SystemError::EBADF);
724             }
725 
726             FcntlCommand::GetFlags => {
727                 // Get file status flags.
728                 let binding = ProcessManager::current_pcb().fd_table();
729                 let fd_table_guard = binding.read();
730 
731                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
732                     // drop guard 以避免无法调度的问题
733                     drop(fd_table_guard);
734                     return Ok(file.lock_no_preempt().mode().bits() as usize);
735                 }
736 
737                 return Err(SystemError::EBADF);
738             }
739             FcntlCommand::SetFlags => {
740                 // Set file status flags.
741                 let binding = ProcessManager::current_pcb().fd_table();
742                 let fd_table_guard = binding.write();
743 
744                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
745                     let arg = arg as u32;
746                     let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?;
747                     // drop guard 以避免无法调度的问题
748                     drop(fd_table_guard);
749                     file.lock_no_preempt().set_mode(mode)?;
750                     return Ok(0);
751                 }
752 
753                 return Err(SystemError::EBADF);
754             }
755             _ => {
756                 // TODO: unimplemented
757                 // 未实现的命令,返回0,不报错。
758 
759                 // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
760                 return Ok(0);
761             }
762         }
763     }
764 
765     /// # ftruncate
766     ///
767     /// ## 描述
768     ///
769     /// 改变文件大小.
770     /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充.
771     /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小.
772     ///
773     /// ## 参数
774     ///
775     /// - `fd`:文件描述符
776     /// - `len`:文件大小
777     ///
778     /// ## 返回值
779     ///
780     /// 如果成功,返回0,否则返回错误码.
781     pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> {
782         let binding = ProcessManager::current_pcb().fd_table();
783         let fd_table_guard = binding.read();
784 
785         if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
786             // drop guard 以避免无法调度的问题
787             drop(fd_table_guard);
788             let r = file.lock_no_preempt().ftruncate(len).map(|_| 0);
789             return r;
790         }
791 
792         return Err(SystemError::EBADF);
793     }
794 
795     fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> {
796         let binding = ProcessManager::current_pcb().fd_table();
797         let fd_table_guard = binding.read();
798         let file = fd_table_guard
799             .get_file_by_fd(fd)
800             .ok_or(SystemError::EBADF)?;
801         // drop guard 以避免无法调度的问题
802         drop(fd_table_guard);
803 
804         let mut kstat = PosixKstat::new();
805         // 获取文件信息
806         let metadata = file.lock().metadata()?;
807         kstat.size = metadata.size as i64;
808         kstat.dev_id = metadata.dev_id as u64;
809         kstat.inode = metadata.inode_id.into() as u64;
810         kstat.blcok_size = metadata.blk_size as i64;
811         kstat.blocks = metadata.blocks as u64;
812 
813         kstat.atime.tv_sec = metadata.atime.tv_sec;
814         kstat.atime.tv_nsec = metadata.atime.tv_nsec;
815         kstat.mtime.tv_sec = metadata.mtime.tv_sec;
816         kstat.mtime.tv_nsec = metadata.mtime.tv_nsec;
817         kstat.ctime.tv_sec = metadata.ctime.tv_sec;
818         kstat.ctime.tv_nsec = metadata.ctime.tv_nsec;
819 
820         kstat.nlink = metadata.nlinks as u64;
821         kstat.uid = metadata.uid as i32;
822         kstat.gid = metadata.gid as i32;
823         kstat.rdev = metadata.raw_dev.data() as i64;
824         kstat.mode = metadata.mode;
825         match file.lock().file_type() {
826             FileType::File => kstat.mode.insert(ModeType::S_IFREG),
827             FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR),
828             FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK),
829             FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR),
830             FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK),
831             FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK),
832             FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO),
833             FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR),
834             FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR),
835         }
836 
837         return Ok(kstat);
838     }
839 
840     pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
841         let kstat = Self::do_fstat(fd)?;
842         if usr_kstat.is_null() {
843             return Err(SystemError::EFAULT);
844         }
845         unsafe {
846             *usr_kstat = kstat;
847         }
848         return Ok(0);
849     }
850 
851     pub fn stat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
852         let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), true)?;
853         let r = Self::fstat(fd as i32, user_kstat);
854         Self::close(fd).ok();
855         return r;
856     }
857 
858     pub fn lstat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
859         let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), false)?;
860         let r = Self::fstat(fd as i32, user_kstat);
861         Self::close(fd).ok();
862         return r;
863     }
864 
865     pub fn mknod(
866         path_ptr: *const i8,
867         mode: ModeType,
868         dev_t: DeviceNumber,
869     ) -> Result<usize, SystemError> {
870         // 安全检验
871         let len = unsafe { CStr::from_ptr(path_ptr).to_bytes().len() };
872         let user_buffer = UserBufferReader::new(path_ptr, len, true)?;
873         let buf = user_buffer.read_from_user::<u8>(0)?;
874         let path = core::str::from_utf8(buf).map_err(|_| SystemError::EINVAL)?;
875 
876         // 文件名过长
877         if path.len() > MAX_PATHLEN as usize {
878             return Err(SystemError::ENAMETOOLONG);
879         }
880 
881         let inode: Result<Arc<dyn IndexNode>, SystemError> =
882             ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
883 
884         if inode.is_ok() {
885             return Err(SystemError::EEXIST);
886         }
887 
888         let (filename, parent_path) = rsplit_path(path);
889 
890         // 查找父目录
891         let parent_inode: Arc<dyn IndexNode> = ROOT_INODE()
892             .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
893         // 创建nod
894         parent_inode.mknod(filename, mode, dev_t)?;
895 
896         return Ok(0);
897     }
898 
899     pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
900         // IoVecs会进行用户态检验
901         let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?;
902 
903         let data = iovecs.gather();
904 
905         Self::write(fd, &data)
906     }
907 
908     pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
909         // IoVecs会进行用户态检验
910         let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?;
911 
912         let mut data = Vec::new();
913         data.resize(iovecs.0.iter().map(|x| x.len()).sum(), 0);
914 
915         let len = Self::read(fd, &mut data)?;
916 
917         iovecs.scatter(&data[..len]);
918 
919         return Ok(len);
920     }
921 
922     pub fn readlink_at(
923         dirfd: i32,
924         path: *const u8,
925         user_buf: *mut u8,
926         buf_size: usize,
927     ) -> Result<usize, SystemError> {
928         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
929         let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?;
930 
931         if path.len() == 0 {
932             return Err(SystemError::EINVAL);
933         }
934 
935         let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, &path)?;
936 
937         let inode = inode.lookup(path.as_str())?;
938         if inode.metadata()?.file_type != FileType::SymLink {
939             return Err(SystemError::EINVAL);
940         }
941 
942         let ubuf = user_buf.buffer::<u8>(0).unwrap();
943 
944         let mut file = File::new(inode, FileMode::O_RDONLY)?;
945 
946         let len = file.read(buf_size, ubuf)?;
947 
948         return Ok(len);
949     }
950 
951     pub fn readlink(
952         path: *const u8,
953         user_buf: *mut u8,
954         buf_size: usize,
955     ) -> Result<usize, SystemError> {
956         return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size);
957     }
958 
959     pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
960         return do_faccessat(
961             AtFlags::AT_FDCWD.bits(),
962             pathname,
963             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
964             0,
965         );
966     }
967 
968     pub fn faccessat2(
969         dirfd: i32,
970         pathname: *const u8,
971         mode: u32,
972         flags: u32,
973     ) -> Result<usize, SystemError> {
974         return do_faccessat(
975             dirfd,
976             pathname,
977             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
978             flags,
979         );
980     }
981 
982     pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
983         return do_fchmodat(
984             AtFlags::AT_FDCWD.bits(),
985             pathname,
986             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
987         );
988     }
989 
990     pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
991         return do_fchmodat(
992             dirfd,
993             pathname,
994             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
995         );
996     }
997 
998     pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> {
999         let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
1000         let binding = ProcessManager::current_pcb().fd_table();
1001         let fd_table_guard = binding.read();
1002         let _file = fd_table_guard
1003             .get_file_by_fd(fd)
1004             .ok_or(SystemError::EBADF)?;
1005 
1006         // fchmod没完全实现,因此不修改文件的权限
1007         // todo: 实现fchmod
1008         kwarn!("fchmod not fully implemented");
1009         return Ok(0);
1010     }
1011 }
1012 
1013 #[repr(C)]
1014 #[derive(Debug, Clone, Copy)]
1015 pub struct IoVec {
1016     /// 缓冲区的起始地址
1017     pub iov_base: *mut u8,
1018     /// 缓冲区的长度
1019     pub iov_len: usize,
1020 }
1021 
1022 /// 用于存储多个来自用户空间的IoVec
1023 ///
1024 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。
1025 /// TODO:支持分散读写
1026 #[derive(Debug)]
1027 pub struct IoVecs(Vec<&'static mut [u8]>);
1028 
1029 impl IoVecs {
1030     /// 从用户空间的IoVec中构造IoVecs
1031     ///
1032     /// @param iov 用户空间的IoVec
1033     /// @param iovcnt 用户空间的IoVec的数量
1034     /// @param readv 是否为readv系统调用
1035     ///
1036     /// @return 构造成功返回IoVecs,否则返回错误码
1037     pub unsafe fn from_user(
1038         iov: *const IoVec,
1039         iovcnt: usize,
1040         _readv: bool,
1041     ) -> Result<Self, SystemError> {
1042         // 检查iov指针所在空间是否合法
1043         verify_area(
1044             VirtAddr::new(iov as usize),
1045             iovcnt * core::mem::size_of::<IoVec>(),
1046         )
1047         .map_err(|_| SystemError::EFAULT)?;
1048 
1049         // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放)
1050         let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt);
1051 
1052         let mut slices: Vec<&mut [u8]> = vec![];
1053         slices.reserve(iovs.len());
1054 
1055         for iov in iovs.iter() {
1056             if iov.iov_len == 0 {
1057                 continue;
1058             }
1059 
1060             verify_area(
1061                 VirtAddr::new(iov.iov_base as usize),
1062                 iovcnt * core::mem::size_of::<IoVec>(),
1063             )
1064             .map_err(|_| SystemError::EFAULT)?;
1065 
1066             slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len));
1067         }
1068 
1069         return Ok(Self(slices));
1070     }
1071 
1072     /// @brief 将IoVecs中的数据聚合到一个缓冲区中
1073     ///
1074     /// @return 返回聚合后的缓冲区
1075     pub fn gather(&self) -> Vec<u8> {
1076         let mut buf = Vec::new();
1077         for slice in self.0.iter() {
1078             buf.extend_from_slice(slice);
1079         }
1080         return buf;
1081     }
1082 
1083     /// @brief 将给定的数据分散写入到IoVecs中
1084     pub fn scatter(&mut self, data: &[u8]) {
1085         let mut data: &[u8] = data;
1086         for slice in self.0.iter_mut() {
1087             let len = core::cmp::min(slice.len(), data.len());
1088             if len == 0 {
1089                 continue;
1090             }
1091 
1092             slice[..len].copy_from_slice(&data[..len]);
1093             data = &data[len..];
1094         }
1095     }
1096 
1097     /// @brief 创建与IoVecs等长的缓冲区
1098     ///
1099     /// @param set_len 是否设置返回的Vec的len。
1100     /// 如果为true,则返回的Vec的len为所有IoVec的长度之和;
1101     /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和.
1102     ///
1103     /// @return 返回创建的缓冲区
1104     pub fn new_buf(&self, set_len: bool) -> Vec<u8> {
1105         let total_len: usize = self.0.iter().map(|slice| slice.len()).sum();
1106         let mut buf: Vec<u8> = Vec::with_capacity(total_len);
1107 
1108         if set_len {
1109             buf.resize(total_len, 0);
1110         }
1111         return buf;
1112     }
1113 }
1114