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