xref: /DragonOS/kernel/src/filesystem/vfs/syscall.rs (revision 607783d7414735d1dc54afb0c7346ed8e13303a2)
1 use alloc::{boxed::Box, sync::Arc, vec::Vec};
2 
3 use crate::{
4     arch::asm::current::current_pcb,
5     filesystem::vfs::file::FileDescriptorVec,
6     filesystem::vfs::io::SeekFrom,
7     include::bindings::bindings::{verify_area, AT_REMOVEDIR, PAGE_4K_SIZE, PROC_MAX_FD_NUM},
8     kerror,
9     syscall::{Syscall, SystemError},
10     time::TimeSpec,
11 };
12 
13 use super::{
14     core::{do_mkdir, do_remove_dir, do_unlink_at},
15     fcntl::{FcntlCommand, FD_CLOEXEC},
16     file::{File, FileMode},
17     utils::rsplit_path,
18     Dirent, FileType, IndexNode, ROOT_INODE,
19 };
20 
21 pub const SEEK_SET: u32 = 0;
22 pub const SEEK_CUR: u32 = 1;
23 pub const SEEK_END: u32 = 2;
24 pub const SEEK_MAX: u32 = 3;
25 
26 bitflags! {
27     /// 文件类型和权限
28     pub struct ModeType: u32 {
29         /// 掩码
30         const S_IFMT = 0o0_170_000;
31         /// 文件类型
32         const S_IFSOCK = 0o140000;
33         const S_IFLNK = 0o120000;
34         const S_IFREG = 0o100000;
35         const S_IFBLK = 0o060000;
36         const S_IFDIR = 0o040000;
37         const S_IFCHR = 0o020000;
38         const S_IFIFO = 0o010000;
39 
40         const S_ISUID = 0o004000;
41         const S_ISGID = 0o002000;
42         const S_ISVTX = 0o001000;
43         /// 文件用户权限
44         const S_IRWXU = 0o0700;
45         const S_IRUSR = 0o0400;
46         const S_IWUSR = 0o0200;
47         const S_IXUSR = 0o0100;
48         /// 文件组权限
49         const S_IRWXG = 0o0070;
50         const S_IRGRP = 0o0040;
51         const S_IWGRP = 0o0020;
52         const S_IXGRP = 0o0010;
53         /// 文件其他用户权限
54         const S_IRWXO = 0o0007;
55         const S_IROTH = 0o0004;
56         const S_IWOTH = 0o0002;
57         const S_IXOTH = 0o0001;
58     }
59 }
60 
61 #[repr(C)]
62 /// # 文件信息结构体
63 pub struct PosixKstat {
64     /// 硬件设备ID
65     dev_id: u64,
66     /// inode号
67     inode: u64,
68     /// 硬链接数
69     nlink: u64,
70     /// 文件权限
71     mode: ModeType,
72     /// 所有者用户ID
73     uid: i32,
74     /// 所有者组ID
75     gid: i32,
76     /// 设备ID
77     rdev: i64,
78     /// 文件大小
79     size: i64,
80     /// 文件系统块大小
81     blcok_size: i64,
82     /// 分配的512B块数
83     blocks: u64,
84     /// 最后访问时间
85     atime: TimeSpec,
86     /// 最后修改时间
87     mtime: TimeSpec,
88     /// 最后状态变化时间
89     ctime: TimeSpec,
90     /// 用于填充结构体大小的空白数据
91     pub _pad: [i8; 24],
92 }
93 impl PosixKstat {
94     fn new() -> Self {
95         Self {
96             inode: 0,
97             dev_id: 0,
98             mode: ModeType { bits: 0 },
99             nlink: 0,
100             uid: 0,
101             gid: 0,
102             rdev: 0,
103             size: 0,
104             atime: TimeSpec {
105                 tv_sec: 0,
106                 tv_nsec: 0,
107             },
108             mtime: TimeSpec {
109                 tv_sec: 0,
110                 tv_nsec: 0,
111             },
112             ctime: TimeSpec {
113                 tv_sec: 0,
114                 tv_nsec: 0,
115             },
116             blcok_size: 0,
117             blocks: 0,
118             _pad: Default::default(),
119         }
120     }
121 }
122 impl Syscall {
123     /// @brief 为当前进程打开一个文件
124     ///
125     /// @param path 文件路径
126     /// @param o_flags 打开文件的标志位
127     ///
128     /// @return 文件描述符编号,或者是错误码
129     pub fn open(path: &str, mode: FileMode) -> Result<usize, SystemError> {
130         // kdebug!("open: path: {}, mode: {:?}", path, mode);
131         // 文件名过长
132         if path.len() > PAGE_4K_SIZE as usize {
133             return Err(SystemError::ENAMETOOLONG);
134         }
135 
136         let inode: Result<Arc<dyn IndexNode>, SystemError> = ROOT_INODE().lookup(path);
137 
138         let inode: Arc<dyn IndexNode> = if inode.is_err() {
139             let errno = inode.unwrap_err();
140             // 文件不存在,且需要创建
141             if mode.contains(FileMode::O_CREAT)
142                 && !mode.contains(FileMode::O_DIRECTORY)
143                 && errno == SystemError::ENOENT
144             {
145                 let (filename, parent_path) = rsplit_path(path);
146                 // 查找父目录
147                 let parent_inode: Arc<dyn IndexNode> =
148                     ROOT_INODE().lookup(parent_path.unwrap_or("/"))?;
149                 // 创建文件
150                 let inode: Arc<dyn IndexNode> =
151                     parent_inode.create(filename, FileType::File, 0o777)?;
152                 inode
153             } else {
154                 // 不需要创建文件,因此返回错误码
155                 return Err(errno);
156             }
157         } else {
158             inode.unwrap()
159         };
160 
161         let file_type: FileType = inode.metadata()?.file_type;
162         // 如果要打开的是文件夹,而目标不是文件夹
163         if mode.contains(FileMode::O_DIRECTORY) && file_type != FileType::Dir {
164             return Err(SystemError::ENOTDIR);
165         }
166 
167         // 如果O_TRUNC,并且,打开模式包含O_RDWR或O_WRONLY,清空文件
168         if mode.contains(FileMode::O_TRUNC)
169             && (mode.contains(FileMode::O_RDWR) || mode.contains(FileMode::O_WRONLY))
170             && file_type == FileType::File
171         {
172             inode.truncate(0)?;
173         }
174 
175         // 创建文件对象
176         let mut file: File = File::new(inode, mode)?;
177 
178         // 打开模式为“追加”
179         if mode.contains(FileMode::O_APPEND) {
180             file.lseek(SeekFrom::SeekEnd(0))?;
181         }
182 
183         // 把文件对象存入pcb
184         let r = current_pcb().alloc_fd(file, None).map(|fd| fd as usize);
185         // kdebug!("open: fd: {:?}", r);
186         return r;
187     }
188 
189     /// @brief 关闭文件
190     ///
191     /// @param fd 文件描述符编号
192     ///
193     /// @return 成功返回0,失败返回错误码
194     pub fn close(fd: usize) -> Result<usize, SystemError> {
195         // kdebug!("syscall::close: fd: {}", fd);
196         return current_pcb().drop_fd(fd as i32).map(|_| 0);
197     }
198 
199     /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。
200     ///
201     /// @param fd 文件描述符编号
202     /// @param buf 输出缓冲区。
203     ///
204     /// @return Ok(usize) 成功读取的数据的字节数
205     /// @return Err(SystemError) 读取失败,返回posix错误码
206     pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
207         // kdebug!("syscall::read: fd: {}, len={}", fd, buf.len());
208         let file: Option<&mut File> = current_pcb().get_file_mut_by_fd(fd);
209         if file.is_none() {
210             return Err(SystemError::EBADF);
211         }
212         let file: &mut File = file.unwrap();
213 
214         return file.read(buf.len(), buf);
215     }
216 
217     /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。
218     ///
219     /// @param fd 文件描述符编号
220     /// @param buf 输入缓冲区。
221     ///
222     /// @return Ok(usize) 成功写入的数据的字节数
223     /// @return Err(SystemError) 写入失败,返回posix错误码
224     pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> {
225         // kdebug!("syscall::write: fd: {}, len={}", fd, buf.len());
226         let file: Option<&mut File> = current_pcb().get_file_mut_by_fd(fd);
227         if file.is_none() {
228             return Err(SystemError::EBADF);
229         }
230         let file: &mut File = file.unwrap();
231 
232         return file.write(buf.len(), buf);
233     }
234 
235     /// @brief 调整文件操作指针的位置
236     ///
237     /// @param fd 文件描述符编号
238     /// @param seek 调整的方式
239     ///
240     /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量
241     /// @return Err(SystemError) 调整失败,返回posix错误码
242     pub fn lseek(fd: i32, seek: SeekFrom) -> Result<usize, SystemError> {
243         // kdebug!("syscall::lseek: fd: {}, seek={:?}", fd, seek);
244         let file: Option<&mut File> = current_pcb().get_file_mut_by_fd(fd);
245         if file.is_none() {
246             return Err(SystemError::EBADF);
247         }
248         let file: &mut File = file.unwrap();
249         return file.lseek(seek);
250     }
251 
252     /// @brief 切换工作目录
253     ///
254     /// @param dest_path 目标路径
255     ///
256     /// @return   返回码  描述
257     ///      0       |          成功
258     ///
259     ///   EACCESS    |        权限不足
260     ///
261     ///    ELOOP     | 解析path时遇到路径循环
262     ///
263     /// ENAMETOOLONG |       路径名过长
264     ///
265     ///    ENOENT    |  目标文件或目录不存在
266     ///
267     ///    ENODIR    |  检索期间发现非目录项
268     ///
269     ///    ENOMEM    |      系统内存不足
270     ///
271     ///    EFAULT    |       错误的地址
272     ///
273     /// ENAMETOOLONG |        路径过长
274     pub fn chdir(dest_path: &str) -> Result<usize, SystemError> {
275         // Copy path to kernel space to avoid some security issues
276         let path: Box<&str> = Box::new(dest_path);
277         let inode = match ROOT_INODE().lookup(&path) {
278             Err(e) => {
279                 kerror!("Change Directory Failed, Error = {:?}", e);
280                 return Err(SystemError::ENOENT);
281             }
282             Ok(i) => i,
283         };
284 
285         match inode.metadata() {
286             Err(e) => {
287                 kerror!("INode Get MetaData Failed, Error = {:?}", e);
288                 return Err(SystemError::ENOENT);
289             }
290             Ok(i) => {
291                 if let FileType::Dir = i.file_type {
292                     return Ok(0);
293                 } else {
294                     return Err(SystemError::ENOTDIR);
295                 }
296             }
297         }
298     }
299 
300     /// @brief 获取目录中的数据
301     ///
302     /// TODO: 这个函数的语义与Linux不一致,需要修改!!!
303     ///
304     /// @param fd 文件描述符号
305     /// @param buf 输出缓冲区
306     ///
307     /// @return 成功返回读取的字节数,失败返回错误码
308     pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
309         let dirent =
310             unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?;
311 
312         if fd < 0 || fd as u32 > PROC_MAX_FD_NUM {
313             return Err(SystemError::EBADF);
314         }
315 
316         // 获取fd
317         let file: &mut File = match current_pcb().get_file_mut_by_fd(fd) {
318             None => {
319                 return Err(SystemError::EBADF);
320             }
321             Some(file) => file,
322         };
323         // kdebug!("file={file:?}");
324 
325         return file.readdir(dirent).map(|x| x as usize);
326     }
327 
328     /// @brief 创建文件夹
329     ///
330     /// @param path(r8) 路径 / mode(r9) 模式
331     ///
332     /// @return uint64_t 负数错误码 / 0表示成功
333     pub fn mkdir(path: &str, mode: usize) -> Result<usize, SystemError> {
334         return do_mkdir(path, FileMode::from_bits_truncate(mode as u32)).map(|x| x as usize);
335     }
336 
337     /// **删除文件夹、取消文件的链接、删除文件的系统调用**
338     ///
339     /// ## 参数
340     ///
341     /// - `dirfd`:文件夹的文件描述符.目前暂未实现
342     /// - `pathname`:文件夹的路径
343     /// - `flags`:标志位
344     ///
345     ///
346     pub fn unlinkat(_dirfd: i32, pathname: &str, flags: u32) -> Result<usize, SystemError> {
347         // kdebug!("sys_unlink_at={path:?}");
348         if (flags & (!AT_REMOVEDIR)) != 0 {
349             return Err(SystemError::EINVAL);
350         }
351 
352         if (flags & AT_REMOVEDIR) > 0 {
353             // kdebug!("rmdir");
354             match do_remove_dir(&pathname) {
355                 Err(err) => {
356                     kerror!("Failed to Remove Directory, Error Code = {:?}", err);
357                     return Err(err);
358                 }
359                 Ok(_) => {
360                     return Ok(0);
361                 }
362             }
363         }
364 
365         match do_unlink_at(&pathname, FileMode::from_bits_truncate(flags as u32)) {
366             Err(err) => {
367                 kerror!("Failed to Remove Directory, Error Code = {:?}", err);
368                 return Err(err);
369             }
370             Ok(_) => {
371                 return Ok(0);
372             }
373         }
374     }
375 
376     /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd
377     pub fn dup(oldfd: i32) -> Result<usize, SystemError> {
378         if let Some(fds) = FileDescriptorVec::from_pcb(current_pcb()) {
379             // 获得当前文件描述符数组
380             // 确认oldfd是否有效
381             if FileDescriptorVec::validate_fd(oldfd) {
382                 if let Some(file) = &fds.fds[oldfd as usize] {
383                     // 尝试获取对应的文件结构体
384                     let file_cp: Box<File> = file.try_clone().ok_or(SystemError::EBADF)?;
385 
386                     // 申请文件描述符,并把文件对象存入其中
387                     let res = current_pcb().alloc_fd(*file_cp, None).map(|x| x as usize);
388                     return res;
389                 }
390                 // oldfd对应的文件不存在
391                 return Err(SystemError::EBADF);
392             }
393             return Err(SystemError::EBADF);
394         } else {
395             return Err(SystemError::EMFILE);
396         }
397     }
398 
399     /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体,
400     /// 并返回新复制的文件结构体对应的fd.
401     /// 如果新fd已经打开,则会先关闭新fd.
402     ///
403     /// ## 参数
404     ///
405     /// - `oldfd`:旧文件描述符
406     /// - `newfd`:新文件描述符
407     ///
408     /// ## 返回值
409     ///
410     /// - 成功:新文件描述符
411     /// - 失败:错误码
412     pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> {
413         if let Some(fds) = FileDescriptorVec::from_pcb(current_pcb()) {
414             // 获得当前文件描述符数组
415             if FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd) {
416                 //确认oldfd, newid是否有效
417                 if oldfd == newfd {
418                     // 若oldfd与newfd相等
419                     return Ok(newfd as usize);
420                 }
421 
422                 if let Some(file) = &fds.fds[oldfd as usize] {
423                     if fds.fds[newfd as usize].is_some() {
424                         // close newfd
425                         if let Err(_) = current_pcb().drop_fd(newfd) {
426                             // An I/O error occurred while attempting to close fildes2.
427                             return Err(SystemError::EIO);
428                         }
429                     }
430 
431                     // 尝试获取对应的文件结构体
432                     let file_cp = file.try_clone();
433                     if file_cp.is_none() {
434                         return Err(SystemError::EBADF);
435                     }
436                     // 申请文件描述符,并把文件对象存入其中
437                     let res = current_pcb()
438                         .alloc_fd(*file_cp.unwrap(), Some(newfd))
439                         .map(|x| x as usize);
440 
441                     return res;
442                 }
443                 return Err(SystemError::EBADF);
444             } else {
445                 return Err(SystemError::EBADF);
446             }
447         }
448         // 从pcb获取文件描述符数组失败
449         return Err(SystemError::EMFILE);
450     }
451 
452     /// # fcntl
453     ///
454     /// ## 参数
455     ///
456     /// - `fd`:文件描述符
457     /// - `cmd`:命令
458     /// - `arg`:参数
459     pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> {
460         match cmd {
461             FcntlCommand::DupFd => {
462                 if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD {
463                     return Err(SystemError::EBADF);
464                 }
465                 let arg = arg as usize;
466                 for i in arg..FileDescriptorVec::PROCESS_MAX_FD {
467                     if let Some(fds) = FileDescriptorVec::from_pcb(current_pcb()) {
468                         if fds.fds[i as usize].is_none() {
469                             return Self::dup2(fd, i as i32);
470                         }
471                     }
472                 }
473                 return Err(SystemError::EMFILE);
474             }
475             FcntlCommand::GetFd => {
476                 // Get file descriptor flags.
477 
478                 if let Some(fds) = FileDescriptorVec::from_pcb(current_pcb()) {
479                     if FileDescriptorVec::validate_fd(fd) {
480                         if let Some(file) = &fds.fds[fd as usize] {
481                             if file.close_on_exec() {
482                                 return Ok(FD_CLOEXEC as usize);
483                             }
484                         }
485                         return Err(SystemError::EBADF);
486                     }
487                 }
488                 return Err(SystemError::EBADF);
489             }
490             FcntlCommand::SetFd => {
491                 // Set file descriptor flags.
492                 if let Some(fds) = FileDescriptorVec::from_pcb(current_pcb()) {
493                     if FileDescriptorVec::validate_fd(fd) {
494                         if let Some(file) = &mut fds.fds[fd as usize] {
495                             let arg = arg as u32;
496                             if arg & FD_CLOEXEC != 0 {
497                                 file.set_close_on_exec(true);
498                             } else {
499                                 file.set_close_on_exec(false);
500                             }
501                             return Ok(0);
502                         }
503                         return Err(SystemError::EBADF);
504                     }
505                 }
506                 return Err(SystemError::EBADF);
507             }
508 
509             FcntlCommand::GetFlags => {
510                 // Get file status flags.
511                 if let Some(fds) = FileDescriptorVec::from_pcb(current_pcb()) {
512                     if FileDescriptorVec::validate_fd(fd) {
513                         if let Some(file) = &fds.fds[fd as usize] {
514                             return Ok(file.mode().bits() as usize);
515                         }
516                         return Err(SystemError::EBADF);
517                     }
518                 }
519                 return Err(SystemError::EBADF);
520             }
521             FcntlCommand::SetFlags => {
522                 // Set file status flags.
523                 if let Some(fds) = FileDescriptorVec::from_pcb(current_pcb()) {
524                     if FileDescriptorVec::validate_fd(fd) {
525                         if let Some(file) = &mut fds.fds[fd as usize] {
526                             let arg = arg as u32;
527                             let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?;
528                             file.set_mode(mode)?;
529                             return Ok(0);
530                         }
531                         return Err(SystemError::EBADF);
532                     }
533                 }
534                 return Err(SystemError::EBADF);
535             }
536             _ => {
537                 // TODO: unimplemented
538                 // 未实现的命令,返回0,不报错。
539 
540                 // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
541                 return Ok(0);
542             }
543         }
544     }
545 
546     /// # ftruncate
547     ///
548     /// ## 描述
549     ///
550     /// 改变文件大小.
551     /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充.
552     /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小.
553     ///
554     /// ## 参数
555     ///
556     /// - `fd`:文件描述符
557     /// - `len`:文件大小
558     ///
559     /// ## 返回值
560     ///
561     /// 如果成功,返回0,否则返回错误码.
562     pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> {
563         if let Some(fds) = FileDescriptorVec::from_pcb(current_pcb()) {
564             if FileDescriptorVec::validate_fd(fd) {
565                 if let Some(file) = &mut fds.fds[fd as usize] {
566                     let r = file.ftruncate(len).map(|_| 0);
567                     return r;
568                 }
569                 return Err(SystemError::EBADF);
570             }
571         }
572         return Err(SystemError::EBADF);
573     }
574     fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> {
575         let cur = current_pcb();
576         match cur.get_file_ref_by_fd(fd) {
577             Some(file) => {
578                 let mut kstat = PosixKstat::new();
579                 // 获取文件信息
580                 match file.metadata() {
581                     Ok(metadata) => {
582                         kstat.size = metadata.size as i64;
583                         kstat.dev_id = metadata.dev_id as u64;
584                         kstat.inode = metadata.inode_id as u64;
585                         kstat.blcok_size = metadata.blk_size as i64;
586                         kstat.blocks = metadata.blocks as u64;
587 
588                         kstat.atime.tv_sec = metadata.atime.tv_sec;
589                         kstat.atime.tv_nsec = metadata.atime.tv_nsec;
590                         kstat.mtime.tv_sec = metadata.mtime.tv_sec;
591                         kstat.mtime.tv_nsec = metadata.mtime.tv_nsec;
592                         kstat.ctime.tv_sec = metadata.ctime.tv_sec;
593                         kstat.ctime.tv_nsec = metadata.ctime.tv_nsec;
594 
595                         kstat.nlink = metadata.nlinks as u64;
596                         kstat.uid = metadata.uid as i32;
597                         kstat.gid = metadata.gid as i32;
598                         kstat.rdev = metadata.raw_dev as i64;
599                         kstat.mode.bits = metadata.mode;
600                         match file.file_type() {
601                             FileType::File => kstat.mode.insert(ModeType::S_IFMT),
602                             FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR),
603                             FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK),
604                             FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR),
605                             FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK),
606                             FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK),
607                             FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO),
608                         }
609                     }
610                     Err(e) => return Err(e),
611                 }
612 
613                 return Ok(kstat);
614             }
615             None => {
616                 return Err(SystemError::EINVAL);
617             }
618         }
619     }
620     pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
621         match Self::do_fstat(fd) {
622             Ok(kstat) => {
623                 if usr_kstat.is_null() {
624                     return Err(SystemError::EFAULT);
625                 }
626                 unsafe {
627                     *usr_kstat = kstat;
628                 }
629                 return Ok(0);
630             }
631             Err(e) => return Err(e),
632         }
633     }
634 }
635 
636 #[repr(C)]
637 #[derive(Debug, Clone, Copy)]
638 pub struct IoVec {
639     /// 缓冲区的起始地址
640     pub iov_base: *mut u8,
641     /// 缓冲区的长度
642     pub iov_len: usize,
643 }
644 
645 /// 用于存储多个来自用户空间的IoVec
646 ///
647 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。
648 /// TODO:支持分散读写
649 #[derive(Debug)]
650 pub struct IoVecs(Vec<&'static mut [u8]>);
651 
652 impl IoVecs {
653     /// 从用户空间的IoVec中构造IoVecs
654     ///
655     /// @param iov 用户空间的IoVec
656     /// @param iovcnt 用户空间的IoVec的数量
657     /// @param readv 是否为readv系统调用
658     ///
659     /// @return 构造成功返回IoVecs,否则返回错误码
660     pub unsafe fn from_user(
661         iov: *const IoVec,
662         iovcnt: usize,
663         _readv: bool,
664     ) -> Result<Self, SystemError> {
665         // 检查iov指针所在空间是否合法
666         if !verify_area(
667             iov as usize as u64,
668             (iovcnt * core::mem::size_of::<IoVec>()) as u64,
669         ) {
670             return Err(SystemError::EFAULT);
671         }
672 
673         // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放)
674         let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt);
675 
676         let mut slices: Vec<&mut [u8]> = vec![];
677         slices.reserve(iovs.len());
678 
679         for iov in iovs.iter() {
680             if iov.iov_len == 0 {
681                 continue;
682             }
683 
684             if !verify_area(iov.iov_base as usize as u64, iov.iov_len as u64) {
685                 return Err(SystemError::EFAULT);
686             }
687 
688             slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len));
689         }
690 
691         return Ok(Self(slices));
692     }
693 
694     /// @brief 将IoVecs中的数据聚合到一个缓冲区中
695     ///
696     /// @return 返回聚合后的缓冲区
697     pub fn gather(&self) -> Vec<u8> {
698         let mut buf = Vec::new();
699         for slice in self.0.iter() {
700             buf.extend_from_slice(slice);
701         }
702         return buf;
703     }
704 
705     /// @brief 将给定的数据分散写入到IoVecs中
706     pub fn scatter(&mut self, data: &[u8]) {
707         let mut data: &[u8] = data;
708         for slice in self.0.iter_mut() {
709             let len = core::cmp::min(slice.len(), data.len());
710             if len == 0 {
711                 continue;
712             }
713 
714             slice[..len].copy_from_slice(&data[..len]);
715             data = &data[len..];
716         }
717     }
718 
719     /// @brief 创建与IoVecs等长的缓冲区
720     ///
721     /// @param set_len 是否设置返回的Vec的len。
722     /// 如果为true,则返回的Vec的len为所有IoVec的长度之和;
723     /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和.
724     ///
725     /// @return 返回创建的缓冲区
726     pub fn new_buf(&self, set_len: bool) -> Vec<u8> {
727         let total_len: usize = self.0.iter().map(|slice| slice.len()).sum();
728         let mut buf: Vec<u8> = Vec::with_capacity(total_len);
729 
730         if set_len {
731             unsafe {
732                 buf.set_len(total_len);
733             }
734         }
735         return buf;
736     }
737 }
738