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