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