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