1 use core::{ 2 ffi::{c_char, c_int, c_void, CStr}, 3 sync::atomic::{AtomicBool, Ordering}, 4 }; 5 6 use crate::{ 7 arch::syscall::nr::*, 8 libs::{futex::constant::FutexFlag, rand::GRandFlags}, 9 process::{ 10 fork::KernelCloneArgs, 11 resource::{RLimit64, RUsage}, 12 }, 13 }; 14 15 use num_traits::{FromPrimitive, ToPrimitive}; 16 17 use crate::{ 18 arch::{cpu::cpu_reset, interrupt::TrapFrame, MMArch}, 19 driver::base::block::SeekFrom, 20 filesystem::vfs::{ 21 fcntl::FcntlCommand, 22 file::FileMode, 23 syscall::{ModeType, PosixKstat, SEEK_CUR, SEEK_END, SEEK_MAX, SEEK_SET}, 24 MAX_PATHLEN, 25 }, 26 include::bindings::bindings::{PAGE_2M_SIZE, PAGE_4K_SIZE}, 27 kinfo, 28 libs::align::page_align_up, 29 mm::{verify_area, MemoryManagementArch, VirtAddr}, 30 net::syscall::SockAddr, 31 process::{fork::CloneFlags, Pid}, 32 time::{ 33 syscall::{PosixTimeZone, PosixTimeval}, 34 TimeSpec, 35 }, 36 }; 37 38 use self::{ 39 misc::SysInfo, 40 user_access::{UserBufferReader, UserBufferWriter}, 41 }; 42 43 pub mod misc; 44 pub mod user_access; 45 46 #[repr(i32)] 47 #[derive(Debug, FromPrimitive, ToPrimitive, PartialEq, Eq, Clone)] 48 #[allow(dead_code, non_camel_case_types)] 49 pub enum SystemError { 50 /// 操作不被允许 Operation not permitted. 51 EPERM = 1, 52 /// 没有指定的文件或目录 No such file or directory. 53 ENOENT = 2, 54 /// 没有这样的进程 No such process. 55 ESRCH = 3, 56 /// 被中断的函数 Interrupted function. 57 EINTR = 4, 58 /// I/O错误 I/O error. 59 EIO = 5, 60 /// 没有这样的设备或地址 No such device or address. 61 ENXIO = 6, 62 /// 参数列表过长,或者在输出buffer中缺少空间 或者参数比系统内建的最大值要大 Argument list too long. 63 E2BIG = 7, 64 /// 可执行文件格式错误 Executable file format error 65 ENOEXEC = 8, 66 /// 错误的文件描述符 Bad file descriptor. 67 EBADF = 9, 68 /// 没有子进程 No child processes. 69 ECHILD = 10, 70 /// 资源不可用,请重试。 Resource unavailable, try again.(may be the same value as [EWOULDBLOCK]) 71 /// 72 /// 操作将被禁止 Operation would block.(may be the same value as [EAGAIN]). 73 EAGAIN_OR_EWOULDBLOCK = 11, 74 /// 没有足够的空间 Not enough space. 75 ENOMEM = 12, 76 /// 访问被拒绝 Permission denied 77 EACCES = 13, 78 /// 错误的地址 Bad address 79 EFAULT = 14, 80 /// 需要块设备 Block device required 81 ENOTBLK = 15, 82 /// 设备或资源忙 Device or resource busy. 83 EBUSY = 16, 84 /// 文件已存在 File exists. 85 EEXIST = 17, 86 /// 跨设备连接 Cross-device link. 87 EXDEV = 18, 88 /// 没有指定的设备 No such device. 89 ENODEV = 19, 90 /// 不是目录 Not a directory. 91 ENOTDIR = 20, 92 /// 是一个目录 Is a directory 93 EISDIR = 21, 94 /// 不可用的参数 Invalid argument. 95 EINVAL = 22, 96 /// 系统中打开的文件过多 Too many files open in system. 97 ENFILE = 23, 98 /// 文件描述符的值过大 File descriptor value too large. 99 EMFILE = 24, 100 /// 不正确的I/O控制操作 Inappropriate I/O control operation. 101 ENOTTY = 25, 102 /// 文本文件忙 Text file busy. 103 ETXTBSY = 26, 104 /// 文件太大 File too large. 105 EFBIG = 27, 106 /// 设备上没有空间 No space left on device. 107 ENOSPC = 28, 108 /// 错误的寻道.当前文件是pipe,不允许seek请求 Invalid seek. 109 ESPIPE = 29, 110 /// 只读的文件系统 Read-only file system. 111 EROFS = 30, 112 /// 链接数过多 Too many links. 113 EMLINK = 31, 114 /// 断开的管道 Broken pipe. 115 EPIPE = 32, 116 /// 数学参数超出作用域 Mathematics argument out of domain of function. 117 EDOM = 33, 118 /// 结果过大 Result too large. 119 ERANGE = 34, 120 /// 资源死锁将要发生 Resource deadlock would occur. 121 EDEADLK = 35, 122 /// 文件名过长 Filename too long. 123 ENAMETOOLONG = 36, 124 /// 没有可用的锁 No locks available. 125 ENOLCK = 37, 126 /// 功能不支持 Function not supported. 127 ENOSYS = 38, 128 /// 目录非空 Directory not empty. 129 ENOTEMPTY = 39, 130 /// 符号链接级别过多 Too many levels of symbolic links. 131 ELOOP = 40, 132 /// 没有期待类型的消息 No message of the desired type. 133 ENOMSG = 41, 134 /// 标志符被移除 Identifier removed. 135 EIDRM = 42, 136 /// 通道号超出范围 Channel number out of range 137 ECHRNG = 43, 138 /// 二级不同步 Level 2 not synchronized 139 EL2NSYNC = 44, 140 /// 三级暂停 Level 3 halted 141 EL3HLT = 45, 142 /// 三级重置 Level 3 reset 143 EL3RST = 46, 144 /// 链接号超出范围 Link number out of range 145 ELNRNG = 47, 146 /// 未连接协议驱动程序 Protocol driver not attached 147 EUNATCH = 48, 148 /// 没有可用的CSI结构 No CSI structure available 149 ENOCSI = 49, 150 /// 二级暂停 Level 2 halted 151 EL2HLT = 50, 152 /// 无效交换 Invalid exchange 153 EBADE = 51, 154 /// 无效的请求描述符 Invalid request descriptor 155 EBADR = 52, 156 /// 交换满 Exchange full 157 EXFULL = 53, 158 /// 无阳极 No anode 159 ENOANO = 54, 160 /// 请求码无效 Invalid request code 161 EBADRQC = 55, 162 /// 无效插槽 Invalid slot 163 EBADSLT = 56, 164 /// 资源死锁 Resource deadlock would occur 165 EDEADLOCK = 57, 166 /// 错误的字体文件格式 Bad font file format 167 EBFONT = 58, 168 /// 不是STREAM Not a STREAM 169 ENOSTR = 59, 170 /// 队列头没有可读取的消息 No message is available on the STREAM head read queue. 171 ENODATA = 60, 172 /// 流式ioctl()超时 Stream ioctl() timeout 173 ETIME = 61, 174 /// 没有STREAM资源 No STREAM resources. 175 ENOSR = 62, 176 /// 机器不在网络上 Machine is not on the network 177 ENONET = 63, 178 /// 未安装软件包 Package not installed 179 ENOPKG = 64, 180 /// 远程对象 Object is remote 181 EREMOTE = 65, 182 /// 保留 Reserved. 183 ENOLINK = 66, 184 /// 外设错误 Advertise error. 185 EADV = 67, 186 /// 安装错误 Srmount error 187 ESRMNT = 68, 188 /// 发送时发生通信错误 Communication error on send 189 ECOMM = 69, 190 /// 协议错误 Protocol error. 191 EPROTO = 70, 192 /// 保留使用 Reserved. 193 EMULTIHOP = 71, 194 /// RFS特定错误 RFS specific error 195 EDOTDOT = 72, 196 /// 错误的消息 Bad message. 197 EBADMSG = 73, 198 /// 数值过大,产生溢出 Value too large to be stored in data type. 199 EOVERFLOW = 74, 200 /// 名称在网络上不是唯一的 Name not unique on network 201 ENOTUNIQ = 75, 202 /// 处于不良状态的文件描述符 File descriptor in bad state 203 EBADFD = 76, 204 /// 远程地址已更改 Remote address changed 205 EREMCHG = 77, 206 /// 无法访问所需的共享库 Can not access a needed shared library 207 ELIBACC = 78, 208 /// 访问损坏的共享库 Accessing a corrupted shared library 209 ELIBBAD = 79, 210 /// a. out中的.lib部分已损坏 .lib section in a.out corrupted 211 ELIBSCN = 80, 212 /// 尝试链接太多共享库 Attempting to link in too many shared libraries 213 ELIBMAX = 81, 214 /// 无法直接执行共享库 Cannot exec a shared library directly 215 ELIBEXEC = 82, 216 /// 不合法的字符序列 Illegal byte sequence. 217 EILSEQ = 83, 218 /// 中断的系统调用应该重新启动 Interrupted system call should be restarted 219 ERESTART = 84, 220 /// 流管道错误 Streams pipe error 221 ESTRPIPE = 85, 222 /// 用户太多 Too many users 223 EUSERS = 86, 224 /// 不是一个套接字 Not a socket. 225 ENOTSOCK = 87, 226 /// 需要目标地址 Destination address required. 227 EDESTADDRREQ = 88, 228 /// 消息过大 Message too large. 229 EMSGSIZE = 89, 230 /// 对于套接字而言,错误的协议 Protocol wrong type for socket. 231 EPROTOTYPE = 90, 232 /// 协议不可用 Protocol not available. 233 ENOPROTOOPT = 91, 234 /// 协议不被支持 Protocol not supported. 235 EPROTONOSUPPORT = 92, 236 /// 不支持套接字类型 Socket type not supported 237 ESOCKTNOSUPPORT = 93, 238 /// 套接字不支持该操作 Operation not supported on socket (may be the same value as [ENOTSUP]). 239 /// 240 /// 不被支持 Not supported (may be the same value as [EOPNOTSUPP]). 241 EOPNOTSUPP_OR_ENOTSUP = 94, 242 /// 不支持协议系列 Protocol family not supported 243 EPFNOSUPPORT = 95, 244 /// 地址family不支持 Address family not supported. 245 EAFNOSUPPORT = 96, 246 /// 地址正在被使用 Address in use. 247 EADDRINUSE = 97, 248 /// 地址不可用 Address not available. 249 EADDRNOTAVAIL = 98, 250 /// 网络已关闭 Network is down. 251 ENETDOWN = 99, 252 /// 网络不可达 Network unreachable. 253 ENETUNREACH = 100, 254 /// 网络连接已断开 Connection aborted by network. 255 ENETRESET = 101, 256 /// 连接已断开 Connection aborted. 257 ECONNABORTED = 102, 258 /// 连接被重置 Connection reset. 259 ECONNRESET = 103, 260 /// 缓冲区空间不足 No buffer space available. 261 ENOBUFS = 104, 262 /// 套接字已连接 Socket is connected. 263 EISCONN = 105, 264 /// 套接字未连接 The socket is not connected. 265 ENOTCONN = 106, 266 /// 传输端点关闭后无法发送 Cannot send after transport endpoint shutdown 267 ESHUTDOWN = 107, 268 /// 引用太多:无法拼接 Too many references: cannot splice 269 ETOOMANYREFS = 108, 270 /// 连接超时 Connection timed out. 271 ETIMEDOUT = 109, 272 /// 连接被拒绝 Connection refused. 273 ECONNREFUSED = 110, 274 /// 主机已关闭 Host is down 275 EHOSTDOWN = 111, 276 /// 主机不可达 Host is unreachable. 277 EHOSTUNREACH = 112, 278 /// 连接已经在处理 Connection already in progress. 279 EALREADY = 113, 280 /// 操作正在处理 Operation in progress. 281 EINPROGRESS = 114, 282 /// 保留 Reserved. 283 ESTALE = 115, 284 /// 结构需要清理 Structure needs cleaning 285 EUCLEAN = 116, 286 /// 不是XENIX命名类型文件 Not a XENIX named type file 287 ENOTNAM = 117, 288 /// 没有可用的XENIX信号量 No XENIX semaphores available 289 ENAVAIL = 118, 290 /// 是命名类型文件 Is a named type file 291 EISNAM = 119, 292 /// 远程I/O错误 Remote I/O error 293 EREMOTEIO = 120, 294 /// 保留使用 Reserved 295 EDQUOT = 121, 296 /// 没有找到媒介 No medium found 297 ENOMEDIUM = 122, 298 /// 介质类型错误 Wrong medium type 299 EMEDIUMTYPE = 123, 300 /// 操作被取消 Operation canceled. 301 ECANCELED = 124, 302 /// 所需的密钥不可用 Required key not available 303 ENOKEY = 125, 304 /// 密钥已过期 Key has expired 305 EKEYEXPIRED = 126, 306 /// 密钥已被撤销 Key has been revoked 307 EKEYREVOKED = 127, 308 /// 密钥被服务拒绝 Key has been revoked 309 EKEYREJECTED = 128, 310 /// 之前的拥有者挂了 Previous owner died. 311 EOWNERDEAD = 129, 312 /// 状态不可恢复 State not recoverable. 313 ENOTRECOVERABLE = 130, 314 // VMX on 虚拟化开启指令出错 315 EVMXONFailed = 131, 316 // VMX off 虚拟化关闭指令出错 317 EVMXOFFFailed = 132, 318 // VMX VMWRITE 写入虚拟化VMCS内存出错 319 EVMWRITEFailed = 133, 320 EVMREADFailed = 134, 321 EVMPRTLDFailed = 135, 322 EVMLAUNCHFailed = 136, 323 KVM_HVA_ERR_BAD = 137, 324 325 // === 以下错误码不应该被用户态程序使用 === 326 ERESTARTSYS = 512, 327 } 328 329 impl SystemError { 330 /// @brief 把posix错误码转换为系统错误枚举类型。 331 pub fn from_posix_errno(errno: i32) -> Option<SystemError> { 332 // posix 错误码是小于0的 333 if errno >= 0 { 334 return None; 335 } 336 return <Self as FromPrimitive>::from_i32(-errno); 337 } 338 339 /// @brief 把系统错误枚举类型转换为负数posix错误码。 340 pub fn to_posix_errno(&self) -> i32 { 341 return -<Self as ToPrimitive>::to_i32(self).unwrap(); 342 } 343 } 344 345 // 与linux不一致的调用,在linux基础上累加 346 pub const SYS_PUT_STRING: usize = 100000; 347 pub const SYS_SBRK: usize = 100001; 348 /// todo: 该系统调用与Linux不一致,将来需要删除该系统调用!!! 删的时候记得改C版本的libc 349 pub const SYS_CLOCK: usize = 100002; 350 pub const SYS_SCHED: usize = 100003; 351 352 #[derive(Debug)] 353 pub struct Syscall; 354 355 extern "C" { 356 fn do_put_string(s: *const u8, front_color: u32, back_color: u32) -> usize; 357 } 358 359 #[no_mangle] 360 pub extern "C" fn syscall_init() -> i32 { 361 kinfo!("Initializing syscall..."); 362 Syscall::init().expect("syscall init failed"); 363 kinfo!("Syscall init successfully!"); 364 return 0; 365 } 366 367 impl Syscall { 368 /// 初始化系统调用 369 pub fn init() -> Result<(), SystemError> { 370 static INIT_FLAG: AtomicBool = AtomicBool::new(false); 371 let prev = INIT_FLAG.swap(true, Ordering::SeqCst); 372 if prev { 373 panic!("Cannot initialize syscall more than once!"); 374 } 375 return crate::arch::syscall::arch_syscall_init(); 376 } 377 /// @brief 系统调用分发器,用于分发系统调用。 378 /// 379 /// 这个函数内,需要根据系统调用号,调用对应的系统调用处理函数。 380 /// 并且,对于用户态传入的指针参数,需要在本函数内进行越界检查,防止访问到内核空间。 381 #[inline(never)] 382 pub fn handle( 383 syscall_num: usize, 384 args: &[usize], 385 frame: &mut TrapFrame, 386 ) -> Result<usize, SystemError> { 387 let r = match syscall_num { 388 SYS_PUT_STRING => { 389 Self::put_string(args[0] as *const u8, args[1] as u32, args[2] as u32) 390 } 391 #[cfg(target_arch = "x86_64")] 392 SYS_OPEN => { 393 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) }; 394 let path: Result<&str, core::str::Utf8Error> = path.to_str(); 395 let res = if path.is_err() { 396 Err(SystemError::EINVAL) 397 } else { 398 let path: &str = path.unwrap(); 399 400 let flags = args[1]; 401 let mode = args[2]; 402 403 let open_flags: FileMode = FileMode::from_bits_truncate(flags as u32); 404 let mode = ModeType::from_bits(mode as u32).ok_or(SystemError::EINVAL)?; 405 Self::open(path, open_flags, mode, true) 406 }; 407 res 408 } 409 410 SYS_OPENAT => { 411 let dirfd = args[0] as i32; 412 let path: &CStr = unsafe { CStr::from_ptr(args[1] as *const c_char) }; 413 let flags = args[2]; 414 let mode = args[3]; 415 416 let path: Result<&str, core::str::Utf8Error> = path.to_str(); 417 let res = if path.is_err() { 418 Err(SystemError::EINVAL) 419 } else { 420 let path: &str = path.unwrap(); 421 422 let open_flags: FileMode = 423 FileMode::from_bits(flags as u32).ok_or(SystemError::EINVAL)?; 424 let mode = ModeType::from_bits(mode as u32).ok_or(SystemError::EINVAL)?; 425 Self::openat(dirfd, path, open_flags, mode, true) 426 }; 427 res 428 } 429 SYS_CLOSE => { 430 let fd = args[0]; 431 432 let res = Self::close(fd); 433 434 res 435 } 436 SYS_READ => { 437 let fd = args[0] as i32; 438 let buf_vaddr = args[1]; 439 let len = args[2]; 440 let from_user = frame.from_user(); 441 let mut user_buffer_writer = 442 UserBufferWriter::new(buf_vaddr as *mut u8, len, from_user)?; 443 444 let user_buf = user_buffer_writer.buffer(0)?; 445 let res = Self::read(fd, user_buf); 446 res 447 } 448 SYS_WRITE => { 449 let fd = args[0] as i32; 450 let buf_vaddr = args[1]; 451 let len = args[2]; 452 let from_user = frame.from_user(); 453 let user_buffer_reader = 454 UserBufferReader::new(buf_vaddr as *const u8, len, from_user)?; 455 456 let user_buf = user_buffer_reader.read_from_user(0)?; 457 let res = Self::write(fd, user_buf); 458 res 459 } 460 461 SYS_LSEEK => { 462 let fd = args[0] as i32; 463 let offset = args[1] as i64; 464 let whence = args[2] as u32; 465 466 let w = match whence { 467 SEEK_SET => Ok(SeekFrom::SeekSet(offset)), 468 SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)), 469 SEEK_END => Ok(SeekFrom::SeekEnd(offset)), 470 SEEK_MAX => Ok(SeekFrom::SeekEnd(0)), 471 _ => Err(SystemError::EINVAL), 472 }?; 473 474 Self::lseek(fd, w) 475 } 476 SYS_IOCTL => { 477 let fd = args[0]; 478 let cmd = args[1]; 479 let data = args[2]; 480 Self::ioctl(fd, cmd as u32, data) 481 } 482 483 #[cfg(target_arch = "x86_64")] 484 SYS_FORK => Self::fork(frame), 485 #[cfg(target_arch = "x86_64")] 486 SYS_VFORK => Self::vfork(frame), 487 488 SYS_BRK => { 489 let new_brk = VirtAddr::new(args[0]); 490 Self::brk(new_brk).map(|vaddr| vaddr.data()) 491 } 492 493 SYS_SBRK => { 494 let increment = args[0] as isize; 495 Self::sbrk(increment).map(|vaddr: VirtAddr| vaddr.data()) 496 } 497 498 SYS_REBOOT => Self::reboot(), 499 500 SYS_CHDIR => { 501 // Closure for checking arguments 502 let chdir_check = |arg0: usize| { 503 if arg0 == 0 { 504 return Err(SystemError::EFAULT); 505 } 506 let path_ptr = arg0 as *const c_char; 507 let virt_addr = VirtAddr::new(path_ptr as usize); 508 // 权限校验 509 if path_ptr.is_null() 510 || (frame.from_user() 511 && verify_area(virt_addr, PAGE_2M_SIZE as usize).is_err()) 512 { 513 return Err(SystemError::EINVAL); 514 } 515 let dest_path: &CStr = unsafe { CStr::from_ptr(path_ptr) }; 516 let dest_path: &str = dest_path.to_str().map_err(|_| SystemError::EINVAL)?; 517 if dest_path.len() == 0 { 518 return Err(SystemError::EINVAL); 519 } else if dest_path.len() > MAX_PATHLEN as usize { 520 return Err(SystemError::ENAMETOOLONG); 521 } 522 523 return Ok(dest_path); 524 }; 525 526 let r = chdir_check(args[0])?; 527 Self::chdir(r) 528 } 529 530 #[allow(unreachable_patterns)] 531 SYS_GETDENTS64 | SYS_GETDENTS => { 532 let fd = args[0] as i32; 533 534 let buf_vaddr = args[1]; 535 let len = args[2]; 536 let virt_addr: VirtAddr = VirtAddr::new(buf_vaddr); 537 // 判断缓冲区是否来自用户态,进行权限校验 538 let res = if frame.from_user() && verify_area(virt_addr, len as usize).is_err() { 539 // 来自用户态,而buffer在内核态,这样的操作不被允许 540 Err(SystemError::EPERM) 541 } else if buf_vaddr == 0 { 542 Err(SystemError::EFAULT) 543 } else { 544 let buf: &mut [u8] = unsafe { 545 core::slice::from_raw_parts_mut::<'static, u8>(buf_vaddr as *mut u8, len) 546 }; 547 Self::getdents(fd, buf) 548 }; 549 550 res 551 } 552 553 SYS_EXECVE => { 554 let path_ptr = args[0]; 555 let argv_ptr = args[1]; 556 let env_ptr = args[2]; 557 let virt_path_ptr = VirtAddr::new(path_ptr); 558 let virt_argv_ptr = VirtAddr::new(argv_ptr); 559 let virt_env_ptr = VirtAddr::new(env_ptr); 560 // 权限校验 561 if frame.from_user() 562 && (verify_area(virt_path_ptr, MAX_PATHLEN as usize).is_err() 563 || verify_area(virt_argv_ptr, PAGE_4K_SIZE as usize).is_err()) 564 || verify_area(virt_env_ptr, PAGE_4K_SIZE as usize).is_err() 565 { 566 Err(SystemError::EFAULT) 567 } else { 568 Self::execve( 569 path_ptr as *const u8, 570 argv_ptr as *const *const u8, 571 env_ptr as *const *const u8, 572 frame, 573 ) 574 .map(|_| 0) 575 } 576 } 577 SYS_WAIT4 => { 578 let pid = args[0] as i32; 579 let wstatus = args[1] as *mut i32; 580 let options = args[2] as c_int; 581 let rusage = args[3] as *mut c_void; 582 // 权限校验 583 // todo: 引入rusage之后,更正以下权限校验代码中,rusage的大小 584 Self::wait4(pid.into(), wstatus, options, rusage) 585 } 586 587 SYS_EXIT => { 588 let exit_code = args[0]; 589 Self::exit(exit_code) 590 } 591 #[cfg(target_arch = "x86_64")] 592 SYS_MKDIR => { 593 let path_ptr = args[0] as *const c_char; 594 let mode = args[1]; 595 let virt_path_ptr = VirtAddr::new(path_ptr as usize); 596 let security_check = || { 597 if path_ptr.is_null() 598 || (frame.from_user() 599 && verify_area(virt_path_ptr, PAGE_2M_SIZE as usize).is_err()) 600 { 601 return Err(SystemError::EINVAL); 602 } 603 let path: &CStr = unsafe { CStr::from_ptr(path_ptr) }; 604 let path: &str = path.to_str().map_err(|_| SystemError::EINVAL)?.trim(); 605 606 if path == "" { 607 return Err(SystemError::EINVAL); 608 } 609 return Ok(path); 610 }; 611 612 let path = security_check(); 613 if path.is_err() { 614 Err(path.unwrap_err()) 615 } else { 616 Self::mkdir(path.unwrap(), mode) 617 } 618 } 619 620 SYS_NANOSLEEP => { 621 let req = args[0] as *const TimeSpec; 622 let rem = args[1] as *mut TimeSpec; 623 let virt_req = VirtAddr::new(req as usize); 624 let virt_rem = VirtAddr::new(rem as usize); 625 if frame.from_user() 626 && (verify_area(virt_req, core::mem::size_of::<TimeSpec>() as usize).is_err() 627 || verify_area(virt_rem, core::mem::size_of::<TimeSpec>() as usize) 628 .is_err()) 629 { 630 Err(SystemError::EFAULT) 631 } else { 632 Self::nanosleep(req, rem) 633 } 634 } 635 636 SYS_CLOCK => Self::clock(), 637 #[cfg(target_arch = "x86_64")] 638 SYS_PIPE => { 639 let pipefd: *mut i32 = args[0] as *mut c_int; 640 if pipefd.is_null() { 641 Err(SystemError::EFAULT) 642 } else { 643 Self::pipe2(pipefd, FileMode::empty()) 644 } 645 } 646 SYS_PIPE2 => { 647 let pipefd: *mut i32 = args[0] as *mut c_int; 648 let arg1 = args[1]; 649 if pipefd.is_null() { 650 Err(SystemError::EFAULT) 651 } else { 652 let flags = FileMode::from_bits_truncate(arg1 as u32); 653 Self::pipe2(pipefd, flags) 654 } 655 } 656 657 SYS_UNLINKAT => { 658 let dirfd = args[0] as i32; 659 let pathname = args[1] as *const c_char; 660 let flags = args[2] as u32; 661 let virt_pathname = VirtAddr::new(pathname as usize); 662 if frame.from_user() && verify_area(virt_pathname, PAGE_4K_SIZE as usize).is_err() { 663 Err(SystemError::EFAULT) 664 } else if pathname.is_null() { 665 Err(SystemError::EFAULT) 666 } else { 667 let get_path = || { 668 let pathname: &CStr = unsafe { CStr::from_ptr(pathname) }; 669 670 let pathname: &str = pathname.to_str().map_err(|_| SystemError::EINVAL)?; 671 if pathname.len() >= MAX_PATHLEN { 672 return Err(SystemError::ENAMETOOLONG); 673 } 674 return Ok(pathname.trim()); 675 }; 676 let pathname = get_path(); 677 if pathname.is_err() { 678 Err(pathname.unwrap_err()) 679 } else { 680 // kdebug!("sys unlinkat: dirfd: {}, pathname: {}", dirfd, pathname.as_ref().unwrap()); 681 Self::unlinkat(dirfd, pathname.unwrap(), flags) 682 } 683 } 684 } 685 686 #[cfg(target_arch = "x86_64")] 687 SYS_UNLINK => { 688 let pathname = args[0] as *const u8; 689 Self::unlink(pathname) 690 } 691 SYS_KILL => { 692 let pid = Pid::new(args[0]); 693 let sig = args[1] as c_int; 694 // kdebug!("KILL SYSCALL RECEIVED"); 695 Self::kill(pid, sig) 696 } 697 698 SYS_RT_SIGACTION => { 699 let sig = args[0] as c_int; 700 let act = args[1]; 701 let old_act = args[2]; 702 Self::sigaction(sig, act, old_act, frame.from_user()) 703 } 704 705 SYS_RT_SIGRETURN => { 706 // 由于目前signal机制的实现,与x86_64强关联,因此暂时在arch/x86_64/syscall.rs中调用 707 // todo: 未来需要将signal机制与平台解耦 708 todo!() 709 } 710 711 SYS_GETPID => Self::getpid().map(|pid| pid.into()), 712 713 SYS_SCHED => Self::sched(frame.from_user()), 714 SYS_DUP => { 715 let oldfd: i32 = args[0] as c_int; 716 Self::dup(oldfd) 717 } 718 719 #[cfg(target_arch = "x86_64")] 720 SYS_DUP2 => { 721 let oldfd: i32 = args[0] as c_int; 722 let newfd: i32 = args[1] as c_int; 723 Self::dup2(oldfd, newfd) 724 } 725 726 SYS_SOCKET => Self::socket(args[0], args[1], args[2]), 727 SYS_SETSOCKOPT => { 728 let optval = args[3] as *const u8; 729 let optlen = args[4] as usize; 730 let virt_optval = VirtAddr::new(optval as usize); 731 // 验证optval的地址是否合法 732 if verify_area(virt_optval, optlen as usize).is_err() { 733 // 地址空间超出了用户空间的范围,不合法 734 Err(SystemError::EFAULT) 735 } else { 736 let data: &[u8] = unsafe { core::slice::from_raw_parts(optval, optlen) }; 737 Self::setsockopt(args[0], args[1], args[2], data) 738 } 739 } 740 SYS_GETSOCKOPT => { 741 let optval = args[3] as *mut u8; 742 let optlen = args[4] as *mut usize; 743 let virt_optval = VirtAddr::new(optval as usize); 744 let virt_optlen = VirtAddr::new(optlen as usize); 745 let security_check = || { 746 // 验证optval的地址是否合法 747 if verify_area(virt_optval, PAGE_4K_SIZE as usize).is_err() { 748 // 地址空间超出了用户空间的范围,不合法 749 return Err(SystemError::EFAULT); 750 } 751 752 // 验证optlen的地址是否合法 753 if verify_area(virt_optlen, core::mem::size_of::<u32>() as usize).is_err() { 754 // 地址空间超出了用户空间的范围,不合法 755 return Err(SystemError::EFAULT); 756 } 757 return Ok(()); 758 }; 759 let r = security_check(); 760 if r.is_err() { 761 Err(r.unwrap_err()) 762 } else { 763 Self::getsockopt(args[0], args[1], args[2], optval, optlen as *mut u32) 764 } 765 } 766 767 SYS_CONNECT => { 768 let addr = args[1] as *const SockAddr; 769 let addrlen = args[2] as usize; 770 let virt_addr = VirtAddr::new(addr as usize); 771 // 验证addr的地址是否合法 772 if verify_area(virt_addr, addrlen as usize).is_err() { 773 // 地址空间超出了用户空间的范围,不合法 774 Err(SystemError::EFAULT) 775 } else { 776 Self::connect(args[0], addr, addrlen) 777 } 778 } 779 SYS_BIND => { 780 let addr = args[1] as *const SockAddr; 781 let addrlen = args[2] as usize; 782 let virt_addr = VirtAddr::new(addr as usize); 783 // 验证addr的地址是否合法 784 if verify_area(virt_addr, addrlen as usize).is_err() { 785 // 地址空间超出了用户空间的范围,不合法 786 Err(SystemError::EFAULT) 787 } else { 788 Self::bind(args[0], addr, addrlen) 789 } 790 } 791 792 SYS_SENDTO => { 793 let buf = args[1] as *const u8; 794 let len = args[2] as usize; 795 let flags = args[3] as u32; 796 let addr = args[4] as *const SockAddr; 797 let addrlen = args[5] as usize; 798 let virt_buf = VirtAddr::new(buf as usize); 799 let virt_addr = VirtAddr::new(addr as usize); 800 // 验证buf的地址是否合法 801 if verify_area(virt_buf, len as usize).is_err() { 802 // 地址空间超出了用户空间的范围,不合法 803 Err(SystemError::EFAULT) 804 } else if verify_area(virt_addr, addrlen as usize).is_err() { 805 // 地址空间超出了用户空间的范围,不合法 806 Err(SystemError::EFAULT) 807 } else { 808 let data: &[u8] = unsafe { core::slice::from_raw_parts(buf, len) }; 809 Self::sendto(args[0], data, flags, addr, addrlen) 810 } 811 } 812 813 SYS_RECVFROM => { 814 let buf = args[1] as *mut u8; 815 let len = args[2] as usize; 816 let flags = args[3] as u32; 817 let addr = args[4] as *mut SockAddr; 818 let addrlen = args[5] as *mut usize; 819 let virt_buf = VirtAddr::new(buf as usize); 820 let virt_addrlen = VirtAddr::new(addrlen as usize); 821 let virt_addr = VirtAddr::new(addr as usize); 822 let security_check = || { 823 // 验证buf的地址是否合法 824 if verify_area(virt_buf, len as usize).is_err() { 825 // 地址空间超出了用户空间的范围,不合法 826 return Err(SystemError::EFAULT); 827 } 828 829 // 验证addrlen的地址是否合法 830 if verify_area(virt_addrlen, core::mem::size_of::<u32>() as usize).is_err() { 831 // 地址空间超出了用户空间的范围,不合法 832 return Err(SystemError::EFAULT); 833 } 834 835 if verify_area(virt_addr, core::mem::size_of::<SockAddr>() as usize).is_err() { 836 // 地址空间超出了用户空间的范围,不合法 837 return Err(SystemError::EFAULT); 838 } 839 return Ok(()); 840 }; 841 let r = security_check(); 842 if r.is_err() { 843 Err(r.unwrap_err()) 844 } else { 845 let buf = unsafe { core::slice::from_raw_parts_mut(buf, len) }; 846 Self::recvfrom(args[0], buf, flags, addr, addrlen as *mut u32) 847 } 848 } 849 850 SYS_RECVMSG => { 851 let msg = args[1] as *mut crate::net::syscall::MsgHdr; 852 let flags = args[2] as u32; 853 match UserBufferWriter::new( 854 msg, 855 core::mem::size_of::<crate::net::syscall::MsgHdr>(), 856 true, 857 ) { 858 Err(e) => Err(e), 859 Ok(mut user_buffer_writer) => { 860 match user_buffer_writer.buffer::<crate::net::syscall::MsgHdr>(0) { 861 Err(e) => Err(e), 862 Ok(buffer) => { 863 let msg = &mut buffer[0]; 864 Self::recvmsg(args[0], msg, flags) 865 } 866 } 867 } 868 } 869 } 870 871 SYS_LISTEN => Self::listen(args[0], args[1]), 872 SYS_SHUTDOWN => Self::shutdown(args[0], args[1]), 873 SYS_ACCEPT => Self::accept(args[0], args[1] as *mut SockAddr, args[2] as *mut u32), 874 SYS_ACCEPT4 => Self::accept4( 875 args[0], 876 args[1] as *mut SockAddr, 877 args[2] as *mut u32, 878 args[3] as u32, 879 ), 880 SYS_GETSOCKNAME => { 881 Self::getsockname(args[0], args[1] as *mut SockAddr, args[2] as *mut u32) 882 } 883 SYS_GETPEERNAME => { 884 Self::getpeername(args[0], args[1] as *mut SockAddr, args[2] as *mut u32) 885 } 886 SYS_GETTIMEOFDAY => { 887 let timeval = args[0] as *mut PosixTimeval; 888 let timezone_ptr = args[1] as *mut PosixTimeZone; 889 Self::gettimeofday(timeval, timezone_ptr) 890 } 891 SYS_MMAP => { 892 let len = page_align_up(args[1]); 893 let virt_addr = VirtAddr::new(args[0] as usize); 894 if verify_area(virt_addr, len as usize).is_err() { 895 Err(SystemError::EFAULT) 896 } else { 897 Self::mmap( 898 VirtAddr::new(args[0]), 899 len, 900 args[2], 901 args[3], 902 args[4] as i32, 903 args[5], 904 ) 905 } 906 } 907 SYS_MUNMAP => { 908 let addr = args[0]; 909 let len = page_align_up(args[1]); 910 if addr & (MMArch::PAGE_SIZE - 1) != 0 { 911 // The addr argument is not a multiple of the page size 912 Err(SystemError::EINVAL) 913 } else { 914 Self::munmap(VirtAddr::new(addr), len) 915 } 916 } 917 SYS_MPROTECT => { 918 let addr = args[0]; 919 let len = page_align_up(args[1]); 920 if addr & (MMArch::PAGE_SIZE - 1) != 0 { 921 // The addr argument is not a multiple of the page size 922 Err(SystemError::EINVAL) 923 } else { 924 Self::mprotect(VirtAddr::new(addr), len, args[2]) 925 } 926 } 927 928 SYS_GETCWD => { 929 let buf = args[0] as *mut u8; 930 let size = args[1] as usize; 931 let security_check = || { 932 verify_area(VirtAddr::new(buf as usize), size)?; 933 return Ok(()); 934 }; 935 let r = security_check(); 936 if r.is_err() { 937 Err(r.unwrap_err()) 938 } else { 939 let buf = unsafe { core::slice::from_raw_parts_mut(buf, size) }; 940 Self::getcwd(buf).map(|ptr| ptr.data()) 941 } 942 } 943 944 SYS_GETPGID => Self::getpgid(Pid::new(args[0])).map(|pid| pid.into()), 945 946 SYS_GETPPID => Self::getppid().map(|pid| pid.into()), 947 SYS_FSTAT => { 948 let fd = args[0] as i32; 949 let kstat = args[1] as *mut PosixKstat; 950 let vaddr = VirtAddr::new(kstat as usize); 951 // FIXME 由于c中的verify_area与rust中的verify_area重名,所以在引入时加了前缀区分 952 // TODO 应该将用了c版本的verify_area都改为rust的verify_area 953 match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) { 954 Ok(_) => Self::fstat(fd, kstat), 955 Err(e) => Err(e), 956 } 957 } 958 959 SYS_FCNTL => { 960 let fd = args[0] as i32; 961 let cmd: Option<FcntlCommand> = 962 <FcntlCommand as FromPrimitive>::from_u32(args[1] as u32); 963 let arg = args[2] as i32; 964 let res = if let Some(cmd) = cmd { 965 Self::fcntl(fd, cmd, arg) 966 } else { 967 Err(SystemError::EINVAL) 968 }; 969 970 // kdebug!("FCNTL: fd: {}, cmd: {:?}, arg: {}, res: {:?}", fd, cmd, arg, res); 971 res 972 } 973 974 SYS_FTRUNCATE => { 975 let fd = args[0] as i32; 976 let len = args[1] as usize; 977 let res = Self::ftruncate(fd, len); 978 // kdebug!("FTRUNCATE: fd: {}, len: {}, res: {:?}", fd, len, res); 979 res 980 } 981 982 #[cfg(target_arch = "x86_64")] 983 SYS_MKNOD => { 984 let path = args[0]; 985 let flags = args[1]; 986 let dev_t = args[2]; 987 let flags: ModeType = ModeType::from_bits_truncate(flags as u32); 988 Self::mknod( 989 path as *const i8, 990 flags, 991 crate::driver::base::device::DeviceNumber::from(dev_t), 992 ) 993 } 994 995 SYS_CLONE => { 996 let parent_tid = VirtAddr::new(args[2]); 997 let child_tid = VirtAddr::new(args[3]); 998 999 // 地址校验 1000 verify_area(parent_tid, core::mem::size_of::<i32>())?; 1001 verify_area(child_tid, core::mem::size_of::<i32>())?; 1002 1003 let mut clone_args = KernelCloneArgs::new(); 1004 clone_args.flags = CloneFlags::from_bits_truncate(args[0] as u64); 1005 clone_args.stack = args[1]; 1006 clone_args.parent_tid = parent_tid; 1007 clone_args.child_tid = child_tid; 1008 clone_args.tls = args[4]; 1009 Self::clone(frame, clone_args) 1010 } 1011 1012 SYS_FUTEX => { 1013 let uaddr = VirtAddr::new(args[0]); 1014 let operation = FutexFlag::from_bits(args[1] as u32).ok_or(SystemError::ENOSYS)?; 1015 let val = args[2] as u32; 1016 let utime = args[3]; 1017 let uaddr2 = VirtAddr::new(args[4]); 1018 let val3 = args[5] as u32; 1019 1020 verify_area(uaddr, core::mem::size_of::<u32>())?; 1021 verify_area(uaddr2, core::mem::size_of::<u32>())?; 1022 1023 let mut timespec = None; 1024 if utime != 0 && operation.contains(FutexFlag::FLAGS_HAS_TIMEOUT) { 1025 let reader = UserBufferReader::new( 1026 utime as *const TimeSpec, 1027 core::mem::size_of::<TimeSpec>(), 1028 true, 1029 )?; 1030 1031 timespec = Some(reader.read_one_from_user::<TimeSpec>(0)?.clone()); 1032 } 1033 1034 Self::do_futex(uaddr, operation, val, timespec, uaddr2, utime as u32, val3) 1035 } 1036 1037 SYS_READV => Self::readv(args[0] as i32, args[1], args[2]), 1038 SYS_WRITEV => Self::writev(args[0] as i32, args[1], args[2]), 1039 1040 SYS_SET_TID_ADDRESS => Self::set_tid_address(args[0]), 1041 1042 #[cfg(target_arch = "x86_64")] 1043 SYS_LSTAT => { 1044 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) }; 1045 let path: Result<&str, core::str::Utf8Error> = path.to_str(); 1046 let res = if path.is_err() { 1047 Err(SystemError::EINVAL) 1048 } else { 1049 let path: &str = path.unwrap(); 1050 let kstat = args[1] as *mut PosixKstat; 1051 let vaddr = VirtAddr::new(kstat as usize); 1052 match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) { 1053 Ok(_) => Self::lstat(path, kstat), 1054 Err(e) => Err(e), 1055 } 1056 }; 1057 1058 res 1059 } 1060 1061 #[cfg(target_arch = "x86_64")] 1062 SYS_STAT => { 1063 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) }; 1064 let path: Result<&str, core::str::Utf8Error> = path.to_str(); 1065 let res = if path.is_err() { 1066 Err(SystemError::EINVAL) 1067 } else { 1068 let path: &str = path.unwrap(); 1069 let kstat = args[1] as *mut PosixKstat; 1070 let vaddr = VirtAddr::new(kstat as usize); 1071 match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) { 1072 Ok(_) => Self::stat(path, kstat), 1073 Err(e) => Err(e), 1074 } 1075 }; 1076 1077 res 1078 } 1079 1080 // 目前为了适配musl-libc,以下系统调用先这样写着 1081 SYS_GETRANDOM => { 1082 let flags = GRandFlags::from_bits(args[2] as u8).ok_or(SystemError::EINVAL)?; 1083 Self::get_random(args[0] as *mut u8, args[1], flags) 1084 } 1085 1086 SYS_SOCKETPAIR => { 1087 unimplemented!() 1088 } 1089 1090 #[cfg(target_arch = "x86_64")] 1091 SYS_POLL => { 1092 kwarn!("SYS_POLL has not yet been implemented"); 1093 Ok(0) 1094 } 1095 1096 SYS_RT_SIGPROCMASK => { 1097 kwarn!("SYS_RT_SIGPROCMASK has not yet been implemented"); 1098 Ok(0) 1099 } 1100 1101 SYS_TKILL => { 1102 kwarn!("SYS_TKILL has not yet been implemented"); 1103 Ok(0) 1104 } 1105 1106 SYS_SIGALTSTACK => { 1107 kwarn!("SYS_SIGALTSTACK has not yet been implemented"); 1108 Ok(0) 1109 } 1110 1111 SYS_EXIT_GROUP => { 1112 kwarn!("SYS_EXIT_GROUP has not yet been implemented"); 1113 Ok(0) 1114 } 1115 1116 SYS_MADVISE => { 1117 kwarn!("SYS_MADVISE has not yet been implemented"); 1118 Ok(0) 1119 } 1120 SYS_GETTID => Self::gettid().map(|tid| tid.into()), 1121 SYS_GETUID => Self::getuid().map(|uid| uid.into()), 1122 SYS_SYSLOG => { 1123 kwarn!("SYS_SYSLOG has not yet been implemented"); 1124 Ok(0) 1125 } 1126 SYS_GETGID => Self::getgid().map(|gid| gid.into()), 1127 SYS_SETUID => { 1128 kwarn!("SYS_SETUID has not yet been implemented"); 1129 Ok(0) 1130 } 1131 SYS_SETGID => { 1132 kwarn!("SYS_SETGID has not yet been implemented"); 1133 Ok(0) 1134 } 1135 SYS_GETEUID => Self::geteuid().map(|euid| euid.into()), 1136 SYS_GETEGID => Self::getegid().map(|egid| egid.into()), 1137 SYS_GETRUSAGE => { 1138 let who = args[0] as c_int; 1139 let rusage = args[1] as *mut RUsage; 1140 Self::get_rusage(who, rusage) 1141 } 1142 1143 #[cfg(target_arch = "x86_64")] 1144 SYS_READLINK => { 1145 let path = args[0] as *const u8; 1146 let buf = args[1] as *mut u8; 1147 let bufsiz = args[2] as usize; 1148 Self::readlink(path, buf, bufsiz) 1149 } 1150 1151 SYS_READLINKAT => { 1152 let dirfd = args[0] as i32; 1153 let pathname = args[1] as *const u8; 1154 let buf = args[2] as *mut u8; 1155 let bufsiz = args[3] as usize; 1156 Self::readlink_at(dirfd, pathname, buf, bufsiz) 1157 } 1158 1159 SYS_PRLIMIT64 => { 1160 let pid = args[0]; 1161 let pid = Pid::new(pid); 1162 let resource = args[1]; 1163 let new_limit = args[2] as *const RLimit64; 1164 let old_limit = args[3] as *mut RLimit64; 1165 1166 Self::prlimit64(pid, resource, new_limit, old_limit) 1167 } 1168 1169 #[cfg(target_arch = "x86_64")] 1170 SYS_ACCESS => { 1171 let pathname = args[0] as *const u8; 1172 let mode = args[1] as u32; 1173 Self::access(pathname, mode) 1174 } 1175 1176 SYS_FACCESSAT => { 1177 let dirfd = args[0] as i32; 1178 let pathname = args[1] as *const u8; 1179 let mode = args[2] as u32; 1180 Self::faccessat2(dirfd, pathname, mode, 0) 1181 } 1182 1183 SYS_FACCESSAT2 => { 1184 let dirfd = args[0] as i32; 1185 let pathname = args[1] as *const u8; 1186 let mode = args[2] as u32; 1187 let flags = args[3] as u32; 1188 Self::faccessat2(dirfd, pathname, mode, flags) 1189 } 1190 1191 SYS_CLOCK_GETTIME => { 1192 let clockid = args[0] as i32; 1193 let timespec = args[1] as *mut TimeSpec; 1194 Self::clock_gettime(clockid, timespec) 1195 } 1196 1197 SYS_SYSINFO => { 1198 let info = args[0] as *mut SysInfo; 1199 Self::sysinfo(info) 1200 } 1201 1202 SYS_UMASK => { 1203 let mask = args[0] as u32; 1204 Self::umask(mask) 1205 } 1206 1207 #[cfg(target_arch = "x86_64")] 1208 SYS_CHMOD => { 1209 let pathname = args[0] as *const u8; 1210 let mode = args[1] as u32; 1211 Self::chmod(pathname, mode) 1212 } 1213 SYS_FCHMOD => { 1214 let fd = args[0] as i32; 1215 let mode = args[1] as u32; 1216 Self::fchmod(fd, mode) 1217 } 1218 SYS_FCHMODAT => { 1219 let dirfd = args[0] as i32; 1220 let pathname = args[1] as *const u8; 1221 let mode = args[2] as u32; 1222 Self::fchmodat(dirfd, pathname, mode) 1223 } 1224 1225 _ => panic!("Unsupported syscall ID: {}", syscall_num), 1226 }; 1227 1228 return r; 1229 } 1230 1231 pub fn put_string( 1232 s: *const u8, 1233 front_color: u32, 1234 back_color: u32, 1235 ) -> Result<usize, SystemError> { 1236 return Ok(unsafe { do_put_string(s, front_color, back_color) }); 1237 } 1238 1239 pub fn reboot() -> Result<usize, SystemError> { 1240 unsafe { cpu_reset() }; 1241 } 1242 } 1243