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