From ac71a459863eb6e5394521ee3a05c8d6754c3f4a Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Mon, 17 Dec 2018 22:50:26 +0800 Subject: [PATCH 01/15] use enum instead of consts for syscall id in user lib --- user/ucore-ulib/src/syscall.rs | 90 ++++++++++++++++++---------------- 1 file changed, 47 insertions(+), 43 deletions(-) diff --git a/user/ucore-ulib/src/syscall.rs b/user/ucore-ulib/src/syscall.rs index 1a75785..da3ae5d 100644 --- a/user/ucore-ulib/src/syscall.rs +++ b/user/ucore-ulib/src/syscall.rs @@ -44,7 +44,8 @@ impl fmt::Write for SysPutc { } #[inline(always)] -fn sys_call(id: usize, arg0: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) -> i32 { +fn sys_call(syscall_id: SyscallId, arg0: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) -> i32 { + let id = syscall_id as usize; let ret: i32; unsafe { #[cfg(target_arch = "riscv32")] @@ -70,12 +71,12 @@ fn sys_call(id: usize, arg0: usize, arg1: usize, arg2: usize, arg3: usize, arg4: } pub fn sys_exit(code: usize) -> ! { - sys_call(SYS_EXIT, code, 0, 0, 0, 0, 0); + sys_call(SyscallId::Exit, code, 0, 0, 0, 0, 0); unreachable!() } pub fn sys_write(fd: usize, base: *const u8, len: usize) -> i32 { - sys_call(SYS_WRITE, fd, base as usize, len, 0, 0, 0) + sys_call(SyscallId::Write, fd, base as usize, len, 0, 0, 0) } pub fn sys_open(path: &str, flags: usize) -> i32 { @@ -83,86 +84,89 @@ pub fn sys_open(path: &str, flags: usize) -> i32 { use core::mem::replace; let end = unsafe { &mut *(path.as_ptr().offset(path.len() as isize) as *mut u8) }; let backup = replace(end, 0); - let ret = sys_call(SYS_OPEN, path.as_ptr() as usize, flags, 0, 0, 0, 0); + let ret = sys_call(SyscallId::Open, path.as_ptr() as usize, flags, 0, 0, 0, 0); *end = backup; ret } pub fn sys_close(fd: usize) -> i32 { - sys_call(SYS_CLOSE, fd, 0, 0, 0, 0, 0) + sys_call(SyscallId::Close, fd, 0, 0, 0, 0, 0) } pub fn sys_dup(fd1: usize, fd2: usize) -> i32 { - sys_call(SYS_DUP, fd1, fd2, 0, 0, 0, 0) + sys_call(SyscallId::Dup, fd1, fd2, 0, 0, 0, 0) } /// Fork the current process. Return the child's PID. pub fn sys_fork() -> i32 { - sys_call(SYS_FORK, 0, 0, 0, 0, 0, 0) + sys_call(SyscallId::Fork, 0, 0, 0, 0, 0, 0) } /// Wait the process exit. /// Return the PID. Store exit code to `code` if it's not null. pub fn sys_wait(pid: usize, code: *mut i32) -> i32 { - sys_call(SYS_WAIT, pid, code as usize, 0, 0, 0, 0) + sys_call(SyscallId::Wait, pid, code as usize, 0, 0, 0, 0) } pub fn sys_yield() -> i32 { - sys_call(SYS_YIELD, 0, 0, 0, 0, 0, 0) + sys_call(SyscallId::Yield, 0, 0, 0, 0, 0, 0) } /// Kill the process pub fn sys_kill(pid: usize) -> i32 { - sys_call(SYS_KILL, pid, 0, 0, 0, 0, 0) + sys_call(SyscallId::Kill, pid, 0, 0, 0, 0, 0) } /// Get the current process id pub fn sys_getpid() -> i32 { - sys_call(SYS_GETPID, 0, 0, 0, 0, 0, 0) + sys_call(SyscallId::GetPid, 0, 0, 0, 0, 0, 0) } pub fn sys_sleep(time: usize) -> i32 { - sys_call(SYS_SLEEP, time, 0, 0, 0, 0, 0) + sys_call(SyscallId::Sleep, time, 0, 0, 0, 0, 0) } pub fn sys_get_time() -> i32 { - sys_call(SYS_GETTIME, 0, 0, 0, 0, 0, 0) + sys_call(SyscallId::GetTime, 0, 0, 0, 0, 0, 0) } pub fn sys_lab6_set_priority(priority: usize) -> i32 { - sys_call(SYS_LAB6_SET_PRIORITY, priority, 0, 0, 0, 0, 0) + sys_call(SyscallId::Lab6SetPriority, priority, 0, 0, 0, 0, 0) } pub fn sys_putc(c: char) -> i32 { - sys_call(SYS_PUTC, c as usize, 0, 0, 0, 0, 0) -} - -const SYS_EXIT: usize = 1; -const SYS_FORK: usize = 2; -const SYS_WAIT: usize = 3; -const SYS_EXEC: usize = 4; -const SYS_CLONE: usize = 5; -const SYS_YIELD: usize = 10; -const SYS_SLEEP: usize = 11; -const SYS_KILL: usize = 12; -const SYS_GETTIME: usize = 17; -const SYS_GETPID: usize = 18; -const SYS_MMAP: usize = 20; -const SYS_MUNMAP: usize = 21; -const SYS_SHMEM: usize = 22; -const SYS_PUTC: usize = 30; -const SYS_PGDIR: usize = 31; -const SYS_OPEN: usize = 100; -const SYS_CLOSE: usize = 101; -const SYS_READ: usize = 102; -const SYS_WRITE: usize = 103; -const SYS_SEEK: usize = 104; -const SYS_FSTAT: usize = 110; -const SYS_FSYNC: usize = 111; -const SYS_GETCWD: usize = 121; -const SYS_GETDIRENTRY: usize = 128; -const SYS_DUP: usize = 130; -const SYS_LAB6_SET_PRIORITY: usize = 255; + sys_call(SyscallId::Putc, c as usize, 0, 0, 0, 0, 0) +} + +#[allow(dead_code)] +enum SyscallId{ + Exit = 1, + Fork = 2, + Wait = 3, + Exec = 4, + Clone = 5, + Yield = 10, + Sleep = 11, + Kill = 12, + GetTime = 17, + GetPid = 18, + Mmap = 20, + Munmap = 21, + Shmem = 22, + Putc = 30, + Pgdir = 31, + Open = 100, + Close = 101, + Read = 102, + Write = 103, + Seek = 104, + Fstat = 110, + Fsync = 111, + GetCwd = 121, + GetDirEntry = 128, + Dup = 130, + Lab6SetPriority = 255, +} /* VFS flags */ // TODO: use bitflags From 1ca2bde069441fd48d35eb7f5319c96b9ea1c6ea Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Mon, 17 Dec 2018 23:54:13 +0800 Subject: [PATCH 02/15] maually remove warning, pt1 --- crate/memory/src/paging/mod.rs | 1 - crate/memory/src/swap/mod.rs | 2 +- crate/process/src/process_manager.rs | 2 -- crate/process/src/processor.rs | 15 ++++++--------- crate/process/src/thread.rs | 3 --- kernel/src/fs.rs | 1 - kernel/src/main.rs | 1 + kernel/src/memory.rs | 4 +--- kernel/src/process/context.rs | 7 +++---- kernel/src/process/mod.rs | 5 +---- kernel/src/shell.rs | 1 - kernel/src/syscall.rs | 3 ++- kernel/src/util.rs | 2 -- 13 files changed, 15 insertions(+), 32 deletions(-) diff --git a/crate/memory/src/paging/mod.rs b/crate/memory/src/paging/mod.rs index ccb2a0e..322df2c 100644 --- a/crate/memory/src/paging/mod.rs +++ b/crate/memory/src/paging/mod.rs @@ -3,7 +3,6 @@ //! Implemented for every architecture, used by OS. use super::*; -use log::*; #[cfg(test)] pub use self::mock_page_table::MockPageTable; pub use self::ext::*; diff --git a/crate/memory/src/swap/mod.rs b/crate/memory/src/swap/mod.rs index 14a027a..5f47391 100644 --- a/crate/memory/src/swap/mod.rs +++ b/crate/memory/src/swap/mod.rs @@ -296,7 +296,7 @@ impl SwapExt { entry.set_present(true); entry.update(); } - if(swapin){ + if swapin { unsafe { self.set_swappable(pt, addr & 0xfffff000); } diff --git a/crate/process/src/process_manager.rs b/crate/process/src/process_manager.rs index b6e8af6..d052470 100644 --- a/crate/process/src/process_manager.rs +++ b/crate/process/src/process_manager.rs @@ -1,9 +1,7 @@ use alloc::boxed::Box; -use alloc::sync::Arc; use alloc::vec::Vec; use spin::Mutex; use log::*; -use core::cell::UnsafeCell; use crate::scheduler::Scheduler; use crate::event_hub::EventHub; diff --git a/crate/process/src/processor.rs b/crate/process/src/processor.rs index d29d560..e316324 100644 --- a/crate/process/src/processor.rs +++ b/crate/process/src/processor.rs @@ -1,6 +1,5 @@ use alloc::boxed::Box; use alloc::sync::Arc; -use spin::Mutex; use log::*; use core::cell::UnsafeCell; use crate::process_manager::*; @@ -30,14 +29,12 @@ impl Processor { } pub unsafe fn init(&self, id: usize, context: Box, manager: Arc) { - unsafe { - *self.inner.get() = Some(ProcessorInner { - id, - proc: None, - loop_context: context, - manager, - }); - } + *self.inner.get() = Some(ProcessorInner { + id, + proc: None, + loop_context: context, + manager, + }); } fn inner(&self) -> &mut ProcessorInner { diff --git a/crate/process/src/thread.rs b/crate/process/src/thread.rs index d333bc1..65406c4 100644 --- a/crate/process/src/thread.rs +++ b/crate/process/src/thread.rs @@ -7,14 +7,11 @@ //! - `new_kernel_context`: Construct a `Context` of the new kernel thread use alloc::boxed::Box; -use alloc::collections::BTreeMap; use core::marker::PhantomData; -use core::ptr; use core::time::Duration; use log::*; use crate::processor::*; use crate::process_manager::*; -use crate::scheduler::Scheduler; #[linkage = "weak"] #[no_mangle] diff --git a/kernel/src/fs.rs b/kernel/src/fs.rs index 725642d..7c6d4cc 100644 --- a/kernel/src/fs.rs +++ b/kernel/src/fs.rs @@ -1,7 +1,6 @@ use simple_filesystem::*; use alloc::{boxed::Box, sync::Arc, string::String, collections::VecDeque, vec::Vec}; use core::any::Any; -use core::slice; use lazy_static::lazy_static; #[cfg(target_arch = "x86_64")] use crate::arch::driver::ide; diff --git a/kernel/src/main.rs b/kernel/src/main.rs index 3199250..b5190fe 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -2,4 +2,5 @@ #![cfg_attr(not(test), no_main)] // disable all Rust-level entry points #![cfg_attr(test, allow(dead_code, unused_macros, unused_imports))] +#[allow(unused_imports)] use ucore; \ No newline at end of file diff --git a/kernel/src/memory.rs b/kernel/src/memory.rs index 295e26e..875c9b2 100644 --- a/kernel/src/memory.rs +++ b/kernel/src/memory.rs @@ -2,13 +2,11 @@ pub use crate::arch::paging::*; use bit_allocator::BitAlloc; use crate::consts::MEMORY_OFFSET; use super::HEAP_ALLOCATOR; -use ucore_memory::{*, paging::PageTable}; +use ucore_memory::*; use ucore_memory::cow::CowExt; pub use ucore_memory::memory_set::{MemoryArea, MemoryAttr, handler::*}; -use ucore_memory::swap::*; use crate::process::{process}; use crate::sync::{SpinNoIrqLock, SpinNoIrq, MutexGuard}; -use alloc::collections::VecDeque; use lazy_static::*; use log::*; use linked_list_allocator::LockedHeap; diff --git a/kernel/src/process/context.rs b/kernel/src/process/context.rs index c115bdf..e83e364 100644 --- a/kernel/src/process/context.rs +++ b/kernel/src/process/context.rs @@ -4,10 +4,10 @@ use log::*; use simple_filesystem::file::File; use spin::Mutex; use ucore_process::Context; -use xmas_elf::{ElfFile, header, program::{Flags, ProgramHeader, SegmentData, Type}}; +use xmas_elf::{ElfFile, header, program::{Flags, Type}}; use crate::arch::interrupt::{Context as ArchContext, TrapFrame}; -use crate::memory::{ByFrame, Delay, FrameAllocator, GlobalFrameAlloc, KernelStack, MemoryArea, MemoryAttr, MemorySet}; +use crate::memory::{ByFrame, GlobalFrameAlloc, KernelStack, MemoryAttr, MemorySet}; // TODO: avoid pub pub struct Process { @@ -110,7 +110,7 @@ impl Process { pub fn fork(&self, tf: &TrapFrame) -> Box { info!("COME into fork!"); // Clone memory set, make a new page table - let mut memory_set = self.memory_set.clone(); + let memory_set = self.memory_set.clone(); info!("finish mmset clone in fork!"); // MMU: copy data to the new space @@ -149,7 +149,6 @@ unsafe fn push_slice(mut sp: usize, vs: &[T]) -> usize { unsafe fn push_args_at_stack<'a, Iter>(args: Iter, stack_top: usize) -> usize where Iter: Iterator { - use core::{ptr, slice}; let mut sp = stack_top; let mut argv = Vec::new(); for arg in args { diff --git a/kernel/src/process/mod.rs b/kernel/src/process/mod.rs index 790e4ce..2f2a4e5 100644 --- a/kernel/src/process/mod.rs +++ b/kernel/src/process/mod.rs @@ -1,11 +1,8 @@ -use spin::Mutex; pub use self::context::Process; pub use ucore_process::*; use crate::consts::{MAX_CPU_NUM, MAX_PROCESS_NUM}; use crate::arch::cpu; -use alloc::{boxed::Box, sync::Arc, vec::Vec}; -use crate::sync::Condvar; -use core::sync::atomic::*; +use alloc::{boxed::Box, sync::Arc}; use log::*; pub mod context; diff --git a/kernel/src/shell.rs b/kernel/src/shell.rs index 236bb42..cddd898 100644 --- a/kernel/src/shell.rs +++ b/kernel/src/shell.rs @@ -1,7 +1,6 @@ //! Kernel shell use alloc::string::String; -use alloc::vec::Vec; use crate::fs::{ROOT_INODE, INodeExt}; use crate::process::*; diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 2a7ffdf..e438ee8 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -141,7 +141,7 @@ fn sys_dup(fd1: usize, fd2: usize) -> SysResult { /// Fork the current process. Return the child's PID. fn sys_fork(tf: &TrapFrame) -> SysResult { - let mut context = process().fork(tf); + let context = process().fork(tf); //memory_set_map_swappable(context.get_memory_set_mut()); let pid = processor().manager().add(context, thread::current().id()); //memory_set_map_swappable(processor.get_context_mut(pid).get_memory_set_mut()); @@ -374,6 +374,7 @@ impl From for Stat { mode: match info.type_ { FileType::File => StatMode::FILE, FileType::Dir => StatMode::DIR, + #[allow(unreachable_patterns)] _ => StatMode::NULL, }, nlinks: info.nlinks as u32, diff --git a/kernel/src/util.rs b/kernel/src/util.rs index 1629386..a4ff86a 100644 --- a/kernel/src/util.rs +++ b/kernel/src/util.rs @@ -1,5 +1,3 @@ -use core::fmt::Debug; - /// Convert C string to Rust string pub unsafe fn from_cstr(s: *const u8) -> &'static str { use core::{str, slice}; From 07b8a063ecd9fed0fcbba89b419447653ddece80 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Tue, 18 Dec 2018 12:53:56 +0800 Subject: [PATCH 03/15] maually remove warning, pt2 --- crate/memory/src/swap/mod.rs | 4 ++-- crate/process/src/event_hub.rs | 1 + crate/process/src/process_manager.rs | 1 + crate/process/src/scheduler.rs | 2 +- crate/process/src/thread.rs | 2 +- kernel/src/syscall.rs | 6 ++++-- 6 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crate/memory/src/swap/mod.rs b/crate/memory/src/swap/mod.rs index 5f47391..a161dcb 100644 --- a/crate/memory/src/swap/mod.rs +++ b/crate/memory/src/swap/mod.rs @@ -108,7 +108,7 @@ impl SwapExt { ** @param addr: VirtAddr the target page's virtual address */ pub unsafe fn set_swappable(&mut self, pt: *mut T2, addr: VirtAddr){ - let Self {ref mut page_table, ref mut swap_manager, ref mut swapper} = self; + let Self {ref mut page_table, ref mut swap_manager, ..} = self; let targetpt = &mut *(pt); let pttoken = { info!("SET_SWAPPABLE: the target page table token is {:x?}, addr is {:x?}", targetpt.token(), addr); @@ -209,7 +209,7 @@ impl SwapExt { ** the error if failed */ fn swap_out(&mut self, frame: &Frame) -> Result { - let Self {ref mut page_table, ref mut swap_manager, ref mut swapper} = self; + let Self {ref mut page_table, ref mut swapper, ..} = self; let ret = unsafe{ let pt = &mut *(frame.get_page_table() as *mut T2); pt.with(|| { diff --git a/crate/process/src/event_hub.rs b/crate/process/src/event_hub.rs index 97fa80c..62d2cec 100644 --- a/crate/process/src/event_hub.rs +++ b/crate/process/src/event_hub.rs @@ -69,6 +69,7 @@ impl EventHub { } self.timers.insert(i, timer); } + #[allow(dead_code)] pub fn get_time(&self) -> Time { self.tick } diff --git a/crate/process/src/process_manager.rs b/crate/process/src/process_manager.rs index d052470..2ca17b5 100644 --- a/crate/process/src/process_manager.rs +++ b/crate/process/src/process_manager.rs @@ -6,6 +6,7 @@ use crate::scheduler::Scheduler; use crate::event_hub::EventHub; struct Process { + #[allow(dead_code)] id: Pid, status: Status, status_after_stop: Status, diff --git a/crate/process/src/scheduler.rs b/crate/process/src/scheduler.rs index 55e10e6..a73960d 100644 --- a/crate/process/src/scheduler.rs +++ b/crate/process/src/scheduler.rs @@ -79,7 +79,7 @@ mod rr { *rest == 0 } - fn set_priority(&mut self, pid: usize, priority: u8) { + fn set_priority(&mut self, _pid: usize, _priority: u8) { } fn move_to_head(&mut self, pid: usize) { diff --git a/crate/process/src/thread.rs b/crate/process/src/thread.rs index 65406c4..7657492 100644 --- a/crate/process/src/thread.rs +++ b/crate/process/src/thread.rs @@ -23,7 +23,7 @@ fn processor() -> &'static Processor { #[linkage = "weak"] #[no_mangle] /// Construct a `Context` of the new kernel thread -fn new_kernel_context(entry: extern fn(usize) -> !, arg: usize) -> Box { +fn new_kernel_context(_entry: extern fn(usize) -> !, _arg: usize) -> Box { unimplemented!("thread: Please implement and export `new_kernel_context`") } diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index e438ee8..5ba5cb3 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -374,8 +374,10 @@ impl From for Stat { mode: match info.type_ { FileType::File => StatMode::FILE, FileType::Dir => StatMode::DIR, - #[allow(unreachable_patterns)] - _ => StatMode::NULL, + // _ => StatMode::NULL, + //Note: we should mark FileType as #[non_exhaustive] + // but it is currently not implemented for enum + // see rust-lang/rust#44109 }, nlinks: info.nlinks as u32, blocks: info.blocks as u32, From 935c595083e717b6fda40163817784fa95427580 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Tue, 18 Dec 2018 13:31:31 +0800 Subject: [PATCH 04/15] maually remove warning, pt3 --- kernel/src/fs.rs | 26 +++++++++++++------------- kernel/src/logging.rs | 9 ++++----- kernel/src/sync/mod.rs | 1 + 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/kernel/src/fs.rs b/kernel/src/fs.rs index 7c6d4cc..d4a5eeb 100644 --- a/kernel/src/fs.rs +++ b/kernel/src/fs.rs @@ -42,7 +42,7 @@ impl Device for MemBuf { buf[..len].copy_from_slice(&slice[offset..offset + len]); Some(len) } - fn write_at(&mut self, offset: usize, buf: &[u8]) -> Option { + fn write_at(&mut self, _offset: usize, _buf: &[u8]) -> Option { None } } @@ -105,31 +105,31 @@ macro_rules! impl_inode { () => { fn info(&self) -> Result { unimplemented!() } fn sync(&self) -> Result<()> { unimplemented!() } - fn resize(&self, len: usize) -> Result<()> { unimplemented!() } - fn create(&self, name: &str, type_: FileType) -> Result> { unimplemented!() } - fn unlink(&self, name: &str) -> Result<()> { unimplemented!() } - fn link(&self, name: &str, other: &Arc) -> Result<()> { unimplemented!() } - fn rename(&self, old_name: &str, new_name: &str) -> Result<()> { unimplemented!() } - fn move_(&self, old_name: &str, target: &Arc, new_name: &str) -> Result<()> { unimplemented!() } - fn find(&self, name: &str) -> Result> { unimplemented!() } - fn get_entry(&self, id: usize) -> Result { unimplemented!() } + fn resize(&self, _len: usize) -> Result<()> { unimplemented!() } + fn create(&self, _name: &str, _type_: FileType) -> Result> { unimplemented!() } + fn unlink(&self, _name: &str) -> Result<()> { unimplemented!() } + fn link(&self, _name: &str, _other: &Arc) -> Result<()> { unimplemented!() } + fn rename(&self, _old_name: &str, _new_name: &str) -> Result<()> { unimplemented!() } + fn move_(&self, _old_name: &str, _target: &Arc, _new_name: &str) -> Result<()> { unimplemented!() } + fn find(&self, _name: &str) -> Result> { unimplemented!() } + fn get_entry(&self, _id: usize) -> Result { unimplemented!() } fn fs(&self) -> Arc { unimplemented!() } fn as_any_ref(&self) -> &Any { self } }; } impl INode for Stdin { - fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result { + fn read_at(&self, _offset: usize, buf: &mut [u8]) -> Result { buf[0] = self.pop() as u8; Ok(1) } - fn write_at(&self, offset: usize, buf: &[u8]) -> Result { unimplemented!() } + fn write_at(&self, _offset: usize, _buf: &[u8]) -> Result { unimplemented!() } impl_inode!(); } impl INode for Stdout { - fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result { unimplemented!() } - fn write_at(&self, offset: usize, buf: &[u8]) -> Result { + fn read_at(&self, _offset: usize, _buf: &mut [u8]) -> Result { unimplemented!() } + fn write_at(&self, _offset: usize, buf: &[u8]) -> Result { use core::str; let s = str::from_utf8(buf).map_err(|_| ())?; print!("{}", s); diff --git a/kernel/src/logging.rs b/kernel/src/logging.rs index 86bd1c2..8769c1a 100644 --- a/kernel/src/logging.rs +++ b/kernel/src/logging.rs @@ -44,22 +44,21 @@ macro_rules! with_color { fn print_in_color(args: fmt::Arguments, color: Color) { use crate::arch::io; - let mutex = log_mutex.lock(); + let _guard = log_mutex.lock(); io::putfmt(with_color!(args, color)); } pub fn print(args: fmt::Arguments) { use crate::arch::io; - let mutex = log_mutex.lock(); + let _guard = log_mutex.lock(); io::putfmt(args); } struct SimpleLogger; impl Log for SimpleLogger { - fn enabled(&self, metadata: &Metadata) -> bool { - true -// metadata.level() <= Level::Info + fn enabled(&self, _metadata: &Metadata) -> bool { + true } fn log(&self, record: &Record) { static DISABLED_TARGET: &[&str] = &[ diff --git a/kernel/src/sync/mod.rs b/kernel/src/sync/mod.rs index cfa5071..17de3ed 100644 --- a/kernel/src/sync/mod.rs +++ b/kernel/src/sync/mod.rs @@ -48,6 +48,7 @@ //! Dining_Philosophers --> Monitor //! end //! ``` +#![allow(dead_code)] pub use self::condvar::*; pub use self::mutex::*; From 7eb9f7abcf3f31dba954945adf1f9119df8ff580 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Tue, 18 Dec 2018 15:16:30 +0800 Subject: [PATCH 05/15] maually remove warning, pt4 --- kernel/build.rs | 1 + kernel/src/arch/riscv32/compiler_rt.c | 2 +- kernel/src/arch/riscv32/consts.rs | 2 ++ kernel/src/arch/riscv32/context.rs | 4 ++-- kernel/src/arch/riscv32/cpu.rs | 1 - kernel/src/arch/riscv32/interrupt.rs | 1 - kernel/src/arch/riscv32/io.rs | 1 + kernel/src/arch/riscv32/memory.rs | 5 +++-- kernel/src/arch/riscv32/mod.rs | 2 +- kernel/src/arch/riscv32/paging.rs | 8 +++----- 10 files changed, 14 insertions(+), 13 deletions(-) diff --git a/kernel/build.rs b/kernel/build.rs index 73117d7..3a8a541 100644 --- a/kernel/build.rs +++ b/kernel/build.rs @@ -22,6 +22,7 @@ fn main() { .file("src/arch/riscv32/compiler_rt.c") .flag("-march=rv32ia") .flag("-mabi=ilp32") + .flag("-Wno-builtin-declaration-mismatch") .compile("atomic_rt"); if let Ok(file_path) = gen_sfsimg_asm() { cc::Build::new() diff --git a/kernel/src/arch/riscv32/compiler_rt.c b/kernel/src/arch/riscv32/compiler_rt.c index 95c871f..1a22db7 100644 --- a/kernel/src/arch/riscv32/compiler_rt.c +++ b/kernel/src/arch/riscv32/compiler_rt.c @@ -6,7 +6,7 @@ int __atomic_load_4(int *src) { return res; } -int __atomic_store_4(int *dst, int val) { +void __atomic_store_4(int *dst, int val) { __asm__ __volatile__("amoswap.w.aq zero, %0, (%1)" :: "r"(val), "r"(dst) : "memory"); } diff --git a/kernel/src/arch/riscv32/consts.rs b/kernel/src/arch/riscv32/consts.rs index 40a8e6b..fb534f8 100644 --- a/kernel/src/arch/riscv32/consts.rs +++ b/kernel/src/arch/riscv32/consts.rs @@ -1,6 +1,8 @@ // Physical address available on THINPAD: // [0x80000000, 0x80800000] +#[allow(dead_code)] const P2_SIZE: usize = 1 << 22; +#[allow(dead_code)] const P2_MASK: usize = 0x3ff << 22; pub const RECURSIVE_INDEX: usize = 0x3fe; pub const KERNEL_OFFSET: usize = 0; diff --git a/kernel/src/arch/riscv32/context.rs b/kernel/src/arch/riscv32/context.rs index 11c657b..2c92a3e 100644 --- a/kernel/src/arch/riscv32/context.rs +++ b/kernel/src/arch/riscv32/context.rs @@ -155,7 +155,7 @@ impl Context { /// Pop all callee-saved registers, then return to the target. #[naked] #[inline(never)] - pub unsafe extern fn switch(&mut self, target: &mut Self) { + pub unsafe extern fn switch(&mut self, _target: &mut Self) { asm!( " // save from's registers @@ -241,7 +241,7 @@ impl Context { * @retval: * a Context struct with the pointer to the kernel stack top - 1 as its only element */ - pub unsafe fn new_user_thread(entry_addr: usize, ustack_top: usize, kstack_top: usize, is32: bool, cr3: usize) -> Self { + pub unsafe fn new_user_thread(entry_addr: usize, ustack_top: usize, kstack_top: usize, _is32: bool, cr3: usize) -> Self { InitStack { context: ContextData::new(cr3), tf: TrapFrame::new_user_thread(entry_addr, ustack_top), diff --git a/kernel/src/arch/riscv32/cpu.rs b/kernel/src/arch/riscv32/cpu.rs index 0f21646..74c04be 100644 --- a/kernel/src/arch/riscv32/cpu.rs +++ b/kernel/src/arch/riscv32/cpu.rs @@ -1,6 +1,5 @@ use crate::consts::MAX_CPU_NUM; use core::ptr::{read_volatile, write_volatile}; -use crate::memory::*; static mut STARTED: [bool; MAX_CPU_NUM] = [false; MAX_CPU_NUM]; diff --git a/kernel/src/arch/riscv32/interrupt.rs b/kernel/src/arch/riscv32/interrupt.rs index 22a3674..218808b 100644 --- a/kernel/src/arch/riscv32/interrupt.rs +++ b/kernel/src/arch/riscv32/interrupt.rs @@ -12,7 +12,6 @@ use riscv::register::{ }; use riscv::register::{mcause, mepc, sie}; pub use self::context::*; -use crate::memory::{MemorySet, InactivePageTable0}; use log::*; #[path = "context.rs"] diff --git a/kernel/src/arch/riscv32/io.rs b/kernel/src/arch/riscv32/io.rs index b2c49d2..60135fd 100644 --- a/kernel/src/arch/riscv32/io.rs +++ b/kernel/src/arch/riscv32/io.rs @@ -56,5 +56,6 @@ pub fn putfmt(fmt: Arguments) { const DATA: *mut u8 = 0x10000000 as *mut u8; const STATUS: *const u8 = 0x10000005 as *const u8; +#[allow(dead_code)] const CAN_READ: u8 = 1 << 0; const CAN_WRITE: u8 = 1 << 5; diff --git a/kernel/src/arch/riscv32/memory.rs b/kernel/src/arch/riscv32/memory.rs index f633ac2..07f52e4 100644 --- a/kernel/src/arch/riscv32/memory.rs +++ b/kernel/src/arch/riscv32/memory.rs @@ -1,8 +1,8 @@ -use core::{slice, mem}; +use core::mem; use riscv::{addr::*, register::sstatus}; use ucore_memory::PAGE_SIZE; use log::*; -use crate::memory::{active_table, FRAME_ALLOCATOR, init_heap, MemoryArea, MemoryAttr, MemorySet, MEMORY_ALLOCATOR, Linear}; +use crate::memory::{FRAME_ALLOCATOR, init_heap, MemoryAttr, MemorySet, Linear}; use crate::consts::{MEMORY_OFFSET, MEMORY_END}; #[cfg(feature = "no_mmu")] @@ -94,6 +94,7 @@ fn remap_the_kernel() { static mut SATP: usize = 0; // Symbols provided by linker script +#[allow(dead_code)] extern { fn stext(); fn etext(); diff --git a/kernel/src/arch/riscv32/mod.rs b/kernel/src/arch/riscv32/mod.rs index eb2a17a..dd919d8 100644 --- a/kernel/src/arch/riscv32/mod.rs +++ b/kernel/src/arch/riscv32/mod.rs @@ -16,7 +16,7 @@ pub extern fn rust_main(hartid: usize, dtb: usize, hart_mask: usize, functions: if hartid != 0 { while unsafe { !cpu::has_started(hartid) } { } others_main(); - unreachable!(); + //other_main -> ! } crate::logging::init(); diff --git a/kernel/src/arch/riscv32/paging.rs b/kernel/src/arch/riscv32/paging.rs index 0d86c29..15bb281 100644 --- a/kernel/src/arch/riscv32/paging.rs +++ b/kernel/src/arch/riscv32/paging.rs @@ -6,8 +6,6 @@ use riscv::asm::{sfence_vma, sfence_vma_all}; use riscv::paging::{Mapper, PageTable as RvPageTable, PageTableEntry, PageTableFlags as EF, RecursivePageTable}; use riscv::paging::{FrameAllocator, FrameDeallocator}; use riscv::register::satp; -use ucore_memory::memory_set::*; -use ucore_memory::PAGE_SIZE; use ucore_memory::paging::*; use log::*; @@ -26,7 +24,7 @@ pub fn setup_page_table(frame: Frame) { // Set kernel identity map // 0x10000000 ~ 1K area p2.map_identity(0x40, EF::VALID | EF::READABLE | EF::WRITABLE); - // 0x80000000 ~ 12M area + // 0x80000000 ~ 12M area p2.map_identity(KERNEL_P2_INDEX, EF::VALID | EF::READABLE | EF::WRITABLE | EF::EXECUTABLE); p2.map_identity(KERNEL_P2_INDEX + 1, EF::VALID | EF::READABLE | EF::WRITABLE | EF::EXECUTABLE); p2.map_identity(KERNEL_P2_INDEX + 2, EF::VALID | EF::READABLE | EF::WRITABLE | EF::EXECUTABLE); @@ -71,7 +69,7 @@ impl PageTable for ActivePageTable { */ fn unmap(&mut self, addr: usize) { let page = Page::of_addr(VirtAddr::new(addr)); - let (frame, flush) = self.0.unmap(page).unwrap(); + let (_, flush) = self.0.unmap(page).unwrap(); flush.flush(); } @@ -154,7 +152,7 @@ impl Entry for PageEntry { fn execute(&self) -> bool { self.0.flags().contains(EF::EXECUTABLE) } fn set_execute(&mut self, value: bool) { self.0.flags_mut().set(EF::EXECUTABLE, value); } fn mmio(&self) -> bool { false } - fn set_mmio(&mut self, value: bool) { } + fn set_mmio(&mut self, _value: bool) { } } #[derive(Debug)] From 6eb49a0106e258995bdd54fdf94c7fcdbc462396 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Tue, 18 Dec 2018 16:29:09 +0800 Subject: [PATCH 06/15] maually remove warning, pt5 --- crate/bit-allocator/src/lib.rs | 6 +----- kernel/src/arch/x86_64/cpu.rs | 2 +- kernel/src/arch/x86_64/driver/ide.rs | 2 +- kernel/src/arch/x86_64/driver/keyboard.rs | 2 +- kernel/src/arch/x86_64/driver/serial.rs | 3 +-- kernel/src/arch/x86_64/gdt.rs | 2 -- kernel/src/arch/x86_64/idt.rs | 8 ++++---- kernel/src/arch/x86_64/interrupt/mod.rs | 2 +- kernel/src/arch/x86_64/interrupt/trapframe.rs | 2 +- kernel/src/arch/x86_64/memory.rs | 1 - kernel/src/arch/x86_64/mod.rs | 1 - kernel/src/arch/x86_64/paging.rs | 11 +++-------- kernel/src/fs.rs | 5 +++++ 13 files changed, 19 insertions(+), 28 deletions(-) diff --git a/crate/bit-allocator/src/lib.rs b/crate/bit-allocator/src/lib.rs index c2c94a3..28f1d5d 100644 --- a/crate/bit-allocator/src/lib.rs +++ b/crate/bit-allocator/src/lib.rs @@ -134,11 +134,7 @@ fn log2(x: u16) -> usize { #[inline(always)] #[cfg(not(target_arch = "x86_64"))] fn log2(x: u16) -> usize { - log2_naive(x) -} - -#[inline(always)] -fn log2_naive(mut x: u16) -> usize { + //a naive implement assert_ne!(x, 0); let mut pos = -1; while x != 0 { diff --git a/kernel/src/arch/x86_64/cpu.rs b/kernel/src/arch/x86_64/cpu.rs index 6207177..85a1a97 100644 --- a/kernel/src/arch/x86_64/cpu.rs +++ b/kernel/src/arch/x86_64/cpu.rs @@ -18,7 +18,7 @@ pub fn id() -> usize { pub fn send_ipi(cpu_id: usize) { let mut lapic = unsafe { XApic::new(0xffffff00_fee00000) }; - unsafe { lapic.send_ipi(cpu_id as u8, 0x30); } // TODO: Find a IPI trap num + lapic.send_ipi(cpu_id as u8, 0x30); // TODO: Find a IPI trap num } pub fn init() { diff --git a/kernel/src/arch/x86_64/driver/ide.rs b/kernel/src/arch/x86_64/driver/ide.rs index 6b26feb..097e1a4 100644 --- a/kernel/src/arch/x86_64/driver/ide.rs +++ b/kernel/src/arch/x86_64/driver/ide.rs @@ -88,7 +88,7 @@ impl IDE { } // ??? - let mut data = [0; SECTOR_SIZE]; + let data = [0; SECTOR_SIZE]; asm!("rep insl" :: "{dx}"(self.base + ISA_DATA), "{rdi}"(data.as_ptr()), "{cx}"(SECTOR_SIZE) : "rdi" : "volatile"); } } diff --git a/kernel/src/arch/x86_64/driver/keyboard.rs b/kernel/src/arch/x86_64/driver/keyboard.rs index cd7b3a6..ad000fd 100644 --- a/kernel/src/arch/x86_64/driver/keyboard.rs +++ b/kernel/src/arch/x86_64/driver/keyboard.rs @@ -25,7 +25,7 @@ pub fn receive() -> Option { if let Some(key) = keyboard.process_keyevent(key_event) { match key { DecodedKey::Unicode(character) => return Some(character), - DecodedKey::RawKey(key) => {}, // TODO: handle RawKey from keyboard + DecodedKey::RawKey(_key) => {}, // TODO: handle RawKey from keyboard } } } diff --git a/kernel/src/arch/x86_64/driver/serial.rs b/kernel/src/arch/x86_64/driver/serial.rs index 9616518..443a2a8 100644 --- a/kernel/src/arch/x86_64/driver/serial.rs +++ b/kernel/src/arch/x86_64/driver/serial.rs @@ -1,6 +1,5 @@ // Copy from Redox -use core::fmt::{self, Write}; use x86_64::instructions::port::Port; use spin::Mutex; use uart_16550::SerialPort; @@ -27,7 +26,7 @@ impl SerialRead for SerialPort { fn receive(&mut self) -> u8 { unsafe { let ports = self as *mut _ as *mut [Port; 6]; - let line_sts = &(*ports)[5]; + let _line_sts = &(*ports)[5]; let data = &(*ports)[0]; data.read() } diff --git a/kernel/src/arch/x86_64/gdt.rs b/kernel/src/arch/x86_64/gdt.rs index de581e4..87df160 100644 --- a/kernel/src/arch/x86_64/gdt.rs +++ b/kernel/src/arch/x86_64/gdt.rs @@ -1,7 +1,5 @@ use alloc::boxed::Box; use crate::consts::MAX_CPU_NUM; -use core::fmt; -use core::fmt::Debug; use spin::{Mutex, MutexGuard, Once}; use x86_64::{PrivilegeLevel, VirtAddr}; use x86_64::structures::gdt::*; diff --git a/kernel/src/arch/x86_64/idt.rs b/kernel/src/arch/x86_64/idt.rs index fd7504c..0d6b94f 100644 --- a/kernel/src/arch/x86_64/idt.rs +++ b/kernel/src/arch/x86_64/idt.rs @@ -6,7 +6,7 @@ pub fn init() { } lazy_static! { - static ref IDT: Idt = { + static ref IDT: InterruptDescriptorTable = { use crate::arch::interrupt::consts::*; use crate::arch::gdt::DOUBLE_FAULT_IST_INDEX; use x86_64::PrivilegeLevel; @@ -21,10 +21,10 @@ lazy_static! { let ring3 = [T_SWITCH_TOK, T_SYSCALL, T_SYSCALL32]; - let mut idt = Idt::new(); - let entries = unsafe{ &mut *(&mut idt as *mut _ as *mut [IdtEntry; 256]) }; + let mut idt = InterruptDescriptorTable::new(); + let entries = unsafe{ &mut *(&mut idt as *mut _ as *mut [Entry; 256]) }; for i in 0..256 { - let mut opt = entries[i].set_handler_fn(unsafe { transmute(__vectors[i]) }); + let opt = entries[i].set_handler_fn(unsafe { transmute(__vectors[i]) }); if ring3.contains(&(i as u8)) { opt.set_privilege_level(PrivilegeLevel::Ring3); opt.disable_interrupts(false); diff --git a/kernel/src/arch/x86_64/interrupt/mod.rs b/kernel/src/arch/x86_64/interrupt/mod.rs index ecb602b..db14851 100644 --- a/kernel/src/arch/x86_64/interrupt/mod.rs +++ b/kernel/src/arch/x86_64/interrupt/mod.rs @@ -43,7 +43,7 @@ pub fn enable_irq(irq: u8) { } #[inline(always)] -pub fn ack(irq: u8) { +pub fn ack(_irq: u8) { let mut lapic = unsafe { XApic::new(KERNEL_OFFSET + LAPIC_ADDR) }; lapic.eoi(); } \ No newline at end of file diff --git a/kernel/src/arch/x86_64/interrupt/trapframe.rs b/kernel/src/arch/x86_64/interrupt/trapframe.rs index ab522d5..6f76103 100644 --- a/kernel/src/arch/x86_64/interrupt/trapframe.rs +++ b/kernel/src/arch/x86_64/interrupt/trapframe.rs @@ -119,7 +119,7 @@ impl Context { /// Pop all callee-saved registers, then return to the target. #[naked] #[inline(never)] - pub unsafe extern fn switch(&mut self, target: &mut Self) { + pub unsafe extern fn switch(&mut self, _target: &mut Self) { asm!( " // push rip (by caller) diff --git a/kernel/src/arch/x86_64/memory.rs b/kernel/src/arch/x86_64/memory.rs index 4aead7f..c9007f4 100644 --- a/kernel/src/arch/x86_64/memory.rs +++ b/kernel/src/arch/x86_64/memory.rs @@ -3,7 +3,6 @@ use crate::consts::KERNEL_OFFSET; // Depends on kernel use crate::memory::{FRAME_ALLOCATOR, init_heap, active_table}; use super::{BootInfo, MemoryRegionType}; -use ucore_memory::PAGE_SIZE; use ucore_memory::paging::*; use once::*; use log::*; diff --git a/kernel/src/arch/x86_64/mod.rs b/kernel/src/arch/x86_64/mod.rs index e453346..eb070f5 100644 --- a/kernel/src/arch/x86_64/mod.rs +++ b/kernel/src/arch/x86_64/mod.rs @@ -1,7 +1,6 @@ use bootloader::bootinfo::{BootInfo, MemoryRegionType}; use core::sync::atomic::*; use log::*; -use crate::consts::KERNEL_OFFSET; pub mod driver; pub mod cpu; diff --git a/kernel/src/arch/x86_64/paging.rs b/kernel/src/arch/x86_64/paging.rs index 0ae779d..5230955 100644 --- a/kernel/src/arch/x86_64/paging.rs +++ b/kernel/src/arch/x86_64/paging.rs @@ -1,16 +1,11 @@ // Depends on kernel use crate::memory::{active_table, alloc_frame, dealloc_frame}; -use spin::{Mutex, MutexGuard}; -use ucore_memory::cow::CowExt; -use ucore_memory::memory_set::*; -use ucore_memory::PAGE_SIZE; use ucore_memory::paging::*; use x86_64::instructions::tlb; use x86_64::PhysAddr; use x86_64::registers::control::{Cr3, Cr3Flags}; use x86_64::structures::paging::{Mapper, PageTable as x86PageTable, PageTableEntry, PageTableFlags as EF, RecursivePageTable}; use x86_64::structures::paging::{FrameAllocator, FrameDeallocator, Page, PageRange, PhysFrame as Frame, Size4KiB}; -use x86_64::ux::u9; use log::*; pub trait PageExt { @@ -51,7 +46,7 @@ impl PageTable for ActivePageTable { } fn unmap(&mut self, addr: usize) { - let (frame, flush) = self.0.unmap(Page::of_addr(addr)).unwrap(); + let (_, flush) = self.0.unmap(Page::of_addr(addr)).unwrap(); flush.flush(); } @@ -117,7 +112,7 @@ impl Entry for PageEntry { fn execute(&self) -> bool { !self.0.flags().contains(EF::NO_EXECUTE) } fn set_execute(&mut self, value: bool) { self.as_flags().set(EF::NO_EXECUTE, !value); } fn mmio(&self) -> bool { false } - fn set_mmio(&mut self, value: bool) { } + fn set_mmio(&mut self, _value: bool) { } } fn get_entry_ptr(addr: usize, level: u8) -> *mut PageEntry { @@ -152,7 +147,7 @@ impl InactivePageTable for InactivePageTable0 { } fn map_kernel(&mut self) { - let mut table = unsafe { &mut *(0xffffffff_fffff000 as *mut x86PageTable) }; + let table = unsafe { &mut *(0xffffffff_fffff000 as *mut x86PageTable) }; // Kernel at 0xffff_ff00_0000_0000 // Kernel stack at 0x0000_57ac_0000_0000 (defined in bootloader crate) let e510 = table[510].clone(); diff --git a/kernel/src/fs.rs b/kernel/src/fs.rs index d4a5eeb..c10bf90 100644 --- a/kernel/src/fs.rs +++ b/kernel/src/fs.rs @@ -26,8 +26,10 @@ lazy_static! { }; } +#[cfg(not(target_arch = "x86_64"))] struct MemBuf(&'static [u8]); +#[cfg(not(target_arch = "x86_64"))] impl MemBuf { unsafe fn new(begin: unsafe extern fn(), end: unsafe extern fn()) -> Self { use core::slice; @@ -35,6 +37,7 @@ impl MemBuf { } } +#[cfg(not(target_arch = "x86_64"))] impl Device for MemBuf { fn read_at(&mut self, offset: usize, buf: &mut [u8]) -> Option { let slice = self.0; @@ -51,11 +54,13 @@ impl Device for MemBuf { impl BlockedDevice for ide::IDE { const BLOCK_SIZE_LOG2: u8 = 9; fn read_at(&mut self, block_id: usize, buf: &mut [u8]) -> bool { + use core::slice; assert!(buf.len() >= ide::BLOCK_SIZE); let buf = unsafe { slice::from_raw_parts_mut(buf.as_ptr() as *mut u32, ide::BLOCK_SIZE / 4) }; self.read(block_id as u64, 1, buf).is_ok() } fn write_at(&mut self, block_id: usize, buf: &[u8]) -> bool { + use core::slice; assert!(buf.len() >= ide::BLOCK_SIZE); let buf = unsafe { slice::from_raw_parts(buf.as_ptr() as *mut u32, ide::BLOCK_SIZE / 4) }; self.write(block_id as u64, 1, buf).is_ok() From d737b1e7ba5676a70b2d6e6cf1b296df1c67c8cd Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Tue, 18 Dec 2018 21:39:19 +0800 Subject: [PATCH 07/15] maually remove warning, pt6 --- crate/bit-allocator/src/lib.rs | 7 +++++++ kernel/src/arch/aarch64/board/raspi3/irq.rs | 1 - kernel/src/arch/aarch64/memory.rs | 2 +- kernel/src/arch/aarch64/paging.rs | 4 +--- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crate/bit-allocator/src/lib.rs b/crate/bit-allocator/src/lib.rs index 28f1d5d..325e74e 100644 --- a/crate/bit-allocator/src/lib.rs +++ b/crate/bit-allocator/src/lib.rs @@ -134,6 +134,12 @@ fn log2(x: u16) -> usize { #[inline(always)] #[cfg(not(target_arch = "x86_64"))] fn log2(x: u16) -> usize { + log2_naive(x) +} + +#[cfg(not(target_arch = "x86_64"))] +#[inline(always)] +fn log2_naive(mut x: u16) -> usize { //a naive implement assert_ne!(x, 0); let mut pos = -1; @@ -148,6 +154,7 @@ fn log2(x: u16) -> usize { mod tests { use super::*; + #[cfg(not(target_arch = "x86_64"))] #[test] fn log2_() { for x in 1..=0xffff { diff --git a/kernel/src/arch/aarch64/board/raspi3/irq.rs b/kernel/src/arch/aarch64/board/raspi3/irq.rs index d8730dc..9575e29 100644 --- a/kernel/src/arch/aarch64/board/raspi3/irq.rs +++ b/kernel/src/arch/aarch64/board/raspi3/irq.rs @@ -1,6 +1,5 @@ use crate::arch::interrupt::TrapFrame; use bcm2837::interrupt::Controller; -use log::*; pub use bcm2837::interrupt::Interrupt; diff --git a/kernel/src/arch/aarch64/memory.rs b/kernel/src/arch/aarch64/memory.rs index 1ba7a67..13996fe 100644 --- a/kernel/src/arch/aarch64/memory.rs +++ b/kernel/src/arch/aarch64/memory.rs @@ -5,7 +5,7 @@ use ucore_memory::PAGE_SIZE; use atags::atags::Atags; use aarch64::{barrier, regs::*, addr::*}; use aarch64::paging::{PhysFrame as Frame, memory_attribute::*}; -use crate::memory::{FRAME_ALLOCATOR, init_heap, MemoryArea, MemoryAttr, MemorySet, Linear}; +use crate::memory::{FRAME_ALLOCATOR, init_heap, MemoryAttr, MemorySet, Linear}; /// Memory initialization. pub fn init() { diff --git a/kernel/src/arch/aarch64/paging.rs b/kernel/src/arch/aarch64/paging.rs index 8173681..8bfee47 100644 --- a/kernel/src/arch/aarch64/paging.rs +++ b/kernel/src/arch/aarch64/paging.rs @@ -1,8 +1,6 @@ //! Page table implementations for aarch64. -use ucore_memory::memory_set::*; -use ucore_memory::PAGE_SIZE; use ucore_memory::paging::*; -use aarch64::asm::{tlb_invalidate, tlb_invalidate_all, flush_icache_all, ttbr_el1_read, ttbr_el1_write}; +use aarch64::asm::{tlb_invalidate, tlb_invalidate_all, ttbr_el1_read, ttbr_el1_write}; use aarch64::{PhysAddr, VirtAddr}; use aarch64::paging::{Mapper, PageTable as Aarch64PageTable, PageTableEntry, PageTableFlags as EF, RecursivePageTable}; use aarch64::paging::{FrameAllocator, FrameDeallocator, Page, PhysFrame as Frame, Size4KiB, Size2MiB, Size1GiB}; From fa03f7b11238e79927a736b52790644e4c6462b9 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Thu, 20 Dec 2018 12:27:21 +0800 Subject: [PATCH 08/15] use the simple-filesystem crate with FsError --- kernel/Cargo.lock | 6 +++--- kernel/Cargo.toml | 3 +++ kernel/src/fs.rs | 3 ++- kernel/src/syscall.rs | 6 +++--- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/kernel/Cargo.lock b/kernel/Cargo.lock index 064af4a..958b992 100644 --- a/kernel/Cargo.lock +++ b/kernel/Cargo.lock @@ -253,7 +253,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "simple-filesystem" version = "0.0.1" -source = "git+https://github.com/wangrunji0408/SimpleFileSystem-Rust?branch=multi-thread#249383f7e3f195e0a8ce858f40394e9d5f7f58e0" +source = "git+https://github.com/benpigchu/SimpleFileSystem-Rust?branch=ucore-fs-enhance#b216da64ce4ee9cb24059478ffd4fa80ab8f30d2" dependencies = [ "bit-vec 0.5.0 (git+https://github.com/AltSysrq/bit-vec.git)", "spin 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", @@ -323,7 +323,7 @@ dependencies = [ "pc-keyboard 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "raw-cpuid 6.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "riscv 0.3.0 (git+https://github.com/riscv-and-rust-and-decaf/riscv)", - "simple-filesystem 0.0.1 (git+https://github.com/wangrunji0408/SimpleFileSystem-Rust?branch=multi-thread)", + "simple-filesystem 0.0.1 (git+https://github.com/benpigchu/SimpleFileSystem-Rust?branch=ucore-fs-enhance)", "spin 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", "uart_16550 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "ucore-memory 0.1.0", @@ -466,7 +466,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" "checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" "checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" -"checksum simple-filesystem 0.0.1 (git+https://github.com/wangrunji0408/SimpleFileSystem-Rust?branch=multi-thread)" = "" +"checksum simple-filesystem 0.0.1 (git+https://github.com/benpigchu/SimpleFileSystem-Rust?branch=ucore-fs-enhance)" = "" "checksum skeptic 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "061203a849117b0f7090baf8157aa91dac30545208fbb85166ac58b4ca33d89c" "checksum spin 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)" = "ceac490aa12c567115b40b7b7fceca03a6c9d53d5defea066123debc83c5dc1f" "checksum static_assertions 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "389ce475f424f267dbed6479cbd8f126c5e1afb053b0acdaa019c74305fc65d1" diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index 6718500..17305ec 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -56,6 +56,9 @@ aarch64 = { git = "https://github.com/equation314/aarch64" } atags = { path = "../crate/atags" } bcm2837 = { path = "../crate/bcm2837", optional = true } +[patch.'https://github.com/wangrunji0408/SimpleFileSystem-Rust'] +simple-filesystem = { git = "https://github.com/benpigchu/SimpleFileSystem-Rust", branch = "ucore-fs-enhance" } + [package.metadata.bootimage] default-target = "x86_64-blog_os.json" output = "target/x86_64-blog_os/bootimage.bin" diff --git a/kernel/src/fs.rs b/kernel/src/fs.rs index c10bf90..10f85fe 100644 --- a/kernel/src/fs.rs +++ b/kernel/src/fs.rs @@ -136,7 +136,8 @@ impl INode for Stdout { fn read_at(&self, _offset: usize, _buf: &mut [u8]) -> Result { unimplemented!() } fn write_at(&self, _offset: usize, buf: &[u8]) -> Result { use core::str; - let s = str::from_utf8(buf).map_err(|_| ())?; + //we do not care the utf-8 things, we just want to print it! + let s = unsafe{ str::from_utf8_unchecked(buf) }; print!("{}", s); Ok(buf.len()) } diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 5ba5cb3..61c7540 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -1,6 +1,6 @@ //! System call -use simple_filesystem::{INode, file::File, FileInfo, FileType}; +use simple_filesystem::{INode, file::File, FileInfo, FileType, FsError}; use core::{slice, str}; use alloc::{sync::Arc, vec::Vec, string::String}; use spin::Mutex; @@ -291,8 +291,8 @@ pub enum SysError { InvalidArgument, } -impl From<()> for SysError { - fn from(_: ()) -> Self { +impl From for SysError { + fn from(_: FsError) -> Self { SysError::VfsError } } From f8533442f2553541c917d8f2f456cc2af9e6897a Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Thu, 20 Dec 2018 13:20:00 +0800 Subject: [PATCH 09/15] return error code from syscall, not always -1 --- kernel/src/syscall.rs | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 61c7540..d2907e8 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -53,7 +53,7 @@ pub fn syscall(id: usize, args: [usize; 6], tf: &mut TrapFrame) -> i32 { }; match ret { Ok(code) => code, - Err(_) => -1, + Err(err) => -(err as i32), } } @@ -96,7 +96,7 @@ fn sys_close(fd: usize) -> SysResult { info!("close: fd: {:?}", fd); match process().files.remove(&fd) { Some(_) => Ok(0), - None => Err(SysError::InvalidFile), + None => Err(SysError::Badf), } } @@ -118,11 +118,11 @@ fn sys_getdirentry(fd: usize, dentry_ptr: *mut DirEntry) -> SysResult { let file = get_file(fd)?; let dentry = unsafe { &mut *dentry_ptr }; if !dentry.check() { - return Err(SysError::InvalidArgument); + return Err(SysError::Inval); } let info = file.lock().info()?; if info.type_ != FileType::Dir || info.size <= dentry.entry_id() { - return Err(SysError::InvalidArgument); + return Err(SysError::Inval); } let name = file.lock().get_entry(dentry.entry_id())?; dentry.set_name(name.as_str()); @@ -133,7 +133,7 @@ fn sys_dup(fd1: usize, fd2: usize) -> SysResult { info!("dup: {} {}", fd1, fd2); let file = get_file(fd1)?; if process().files.contains_key(&fd2) { - return Err(SysError::InvalidFile); + return Err(SysError::Badf); } process().files.insert(fd2, file.clone()); Ok(0) @@ -278,7 +278,7 @@ fn sys_putc(c: char) -> SysResult { } fn get_file(fd: usize) -> Result<&'static Arc>, SysError> { - process().files.get(&fd).ok_or(SysError::InvalidFile) + process().files.get(&fd).ok_or(SysError::Badf) } pub type SysResult = Result; @@ -286,14 +286,21 @@ pub type SysResult = Result; #[repr(i32)] #[derive(Debug)] pub enum SysError { - VfsError, - InvalidFile, - InvalidArgument, + // ucore compatible error code, which is a modified version of the ones used in linux + // name conversion E_XXXXX -> SysError::Xxxxx + // see https://github.com/oscourse-tsinghua/ucore_plus/blob/master/ucore/src/libs-user-ucore/common/error.h + // we only add current used errors here + Badf = 9,// Invaild fd number + Inval = 22,// Invalid argument. + + Unknown = 65535,// A really really unknown error. } impl From for SysError { - fn from(_: FsError) -> Self { - SysError::VfsError + fn from(error: FsError) -> Self { + match error { + _ => SysError::Unknown + } } } From 113a33e5756d8362de035f3bb3219abc320a9aa1 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Thu, 20 Dec 2018 14:03:11 +0800 Subject: [PATCH 10/15] translate FsError to SysError --- kernel/src/syscall.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index d2907e8..4d82415 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -290,16 +290,35 @@ pub enum SysError { // name conversion E_XXXXX -> SysError::Xxxxx // see https://github.com/oscourse-tsinghua/ucore_plus/blob/master/ucore/src/libs-user-ucore/common/error.h // we only add current used errors here + Noent = 2,// No such file or directory Badf = 9,// Invaild fd number + Nomem = 12,// Out of memory, also used as no device space in ucore + Exist = 17,// File exists + Xdev = 18,// Cross-device link + Notdir = 20,// Fd is not a directory + Isdir = 21,// Fd is a directory Inval = 22,// Invalid argument. + Unimp = 35,// Not implemented operation + #[allow(dead_code)] Unknown = 65535,// A really really unknown error. } impl From for SysError { fn from(error: FsError) -> Self { match error { - _ => SysError::Unknown + FsError::NotSupported => SysError::Unimp, + FsError::NotFile => SysError::Isdir, + FsError::IsDir => SysError::Isdir, + FsError::NotDir => SysError::Notdir, + FsError::EntryNotFound => SysError::Noent, + FsError::EntryExist => SysError::Exist, + FsError::NotSameFs => SysError::Xdev, + FsError::InvalidParam => SysError::Inval, + FsError::NoDeviceSpace => SysError::Nomem, + FsError::DirRemoved => SysError::Noent, + FsError::DirNotEmpty => SysError::Isdir,// It should be E_NOTEMPTY in linux, but in ucore it is equal to E_Isdir + FsError::WrongFs => SysError::Inval, } } } From 6e8c80d3285a64c933150447f846277dcb62a6b4 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Thu, 20 Dec 2018 14:26:32 +0800 Subject: [PATCH 11/15] panicless default fs implement --- kernel/src/fs.rs | 20 ++++++++++---------- kernel/src/syscall.rs | 5 +++-- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/kernel/src/fs.rs b/kernel/src/fs.rs index 10f85fe..0603a0d 100644 --- a/kernel/src/fs.rs +++ b/kernel/src/fs.rs @@ -108,16 +108,16 @@ lazy_static! { // TODO: better way to provide default impl? macro_rules! impl_inode { () => { - fn info(&self) -> Result { unimplemented!() } - fn sync(&self) -> Result<()> { unimplemented!() } - fn resize(&self, _len: usize) -> Result<()> { unimplemented!() } - fn create(&self, _name: &str, _type_: FileType) -> Result> { unimplemented!() } - fn unlink(&self, _name: &str) -> Result<()> { unimplemented!() } - fn link(&self, _name: &str, _other: &Arc) -> Result<()> { unimplemented!() } - fn rename(&self, _old_name: &str, _new_name: &str) -> Result<()> { unimplemented!() } - fn move_(&self, _old_name: &str, _target: &Arc, _new_name: &str) -> Result<()> { unimplemented!() } - fn find(&self, _name: &str) -> Result> { unimplemented!() } - fn get_entry(&self, _id: usize) -> Result { unimplemented!() } + fn info(&self) -> Result { Err(FsError::NotSupported) } + fn sync(&self) -> Result<()> { Ok(()) } + fn resize(&self, _len: usize) -> Result<()> { Err(FsError::NotSupported) } + fn create(&self, _name: &str, _type_: FileType) -> Result> { Err(FsError::NotDir) } + fn unlink(&self, _name: &str) -> Result<()> { Err(FsError::NotDir) } + fn link(&self, _name: &str, _other: &Arc) -> Result<()> { Err(FsError::NotDir) } + fn rename(&self, _old_name: &str, _new_name: &str) -> Result<()> { Err(FsError::NotDir) } + fn move_(&self, _old_name: &str, _target: &Arc, _new_name: &str) -> Result<()> { Err(FsError::NotDir) } + fn find(&self, _name: &str) -> Result> { Err(FsError::NotDir) } + fn get_entry(&self, _id: usize) -> Result { Err(FsError::NotDir) } fn fs(&self) -> Arc { unimplemented!() } fn as_any_ref(&self) -> &Any { self } }; diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 4d82415..00971e3 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -53,7 +53,7 @@ pub fn syscall(id: usize, args: [usize; 6], tf: &mut TrapFrame) -> i32 { }; match ret { Ok(code) => code, - Err(err) => -(err as i32), + Err(err) => (err as i32), } } @@ -286,7 +286,8 @@ pub type SysResult = Result; #[repr(i32)] #[derive(Debug)] pub enum SysError { - // ucore compatible error code, which is a modified version of the ones used in linux + // ucore_plus compatible error code, which is a modified version of the ones used in linux + // note that ucore_os_lab use another error code table // name conversion E_XXXXX -> SysError::Xxxxx // see https://github.com/oscourse-tsinghua/ucore_plus/blob/master/ucore/src/libs-user-ucore/common/error.h // we only add current used errors here From 364497e3791eef1ee70eca62bb62332505e1f026 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Thu, 20 Dec 2018 19:36:19 +0800 Subject: [PATCH 12/15] use the error code specified in ucore_os_lab instead of ucore_plus --- kernel/src/syscall.rs | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 00971e3..4f60ca2 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -53,7 +53,7 @@ pub fn syscall(id: usize, args: [usize; 6], tf: &mut TrapFrame) -> i32 { }; match ret { Ok(code) => code, - Err(err) => (err as i32), + Err(err) => -(err as i32), } } @@ -96,7 +96,7 @@ fn sys_close(fd: usize) -> SysResult { info!("close: fd: {:?}", fd); match process().files.remove(&fd) { Some(_) => Ok(0), - None => Err(SysError::Badf), + None => Err(SysError::Inval), } } @@ -133,7 +133,7 @@ fn sys_dup(fd1: usize, fd2: usize) -> SysResult { info!("dup: {} {}", fd1, fd2); let file = get_file(fd1)?; if process().files.contains_key(&fd2) { - return Err(SysError::Badf); + return Err(SysError::Inval); } process().files.insert(fd2, file.clone()); Ok(0) @@ -278,7 +278,7 @@ fn sys_putc(c: char) -> SysResult { } fn get_file(fd: usize) -> Result<&'static Arc>, SysError> { - process().files.get(&fd).ok_or(SysError::Badf) + process().files.get(&fd).ok_or(SysError::Inval) } pub type SysResult = Result; @@ -286,23 +286,23 @@ pub type SysResult = Result; #[repr(i32)] #[derive(Debug)] pub enum SysError { - // ucore_plus compatible error code, which is a modified version of the ones used in linux - // note that ucore_os_lab use another error code table + // ucore compatible error code + // note that ucore_plus use another error code table, which is a modified version of the ones used in linux // name conversion E_XXXXX -> SysError::Xxxxx - // see https://github.com/oscourse-tsinghua/ucore_plus/blob/master/ucore/src/libs-user-ucore/common/error.h + // see https://github.com/oscourse-tsinghua/ucore_os_lab/blob/master/labcodes/lab8/libs/error.h // we only add current used errors here - Noent = 2,// No such file or directory - Badf = 9,// Invaild fd number - Nomem = 12,// Out of memory, also used as no device space in ucore - Exist = 17,// File exists - Xdev = 18,// Cross-device link - Notdir = 20,// Fd is not a directory - Isdir = 21,// Fd is a directory - Inval = 22,// Invalid argument. - Unimp = 35,// Not implemented operation + Inval = 3,// Invalid argument, also Invaild fd number. + Nomem = 4,// Out of memory, also used as no device space in ucore + Noent = 16,// No such file or directory + Isdir = 17,// Fd is a directory + Notdir = 18,// Fd is not a directory + Xdev = 19,// Cross-device link + Unimp = 20,// Not implemented + Exists = 23,// File exists + Notempty = 24,// Directory is not empty #[allow(dead_code)] - Unknown = 65535,// A really really unknown error. + Unspcified = 1,// A really really unknown error. } impl From for SysError { @@ -313,12 +313,12 @@ impl From for SysError { FsError::IsDir => SysError::Isdir, FsError::NotDir => SysError::Notdir, FsError::EntryNotFound => SysError::Noent, - FsError::EntryExist => SysError::Exist, + FsError::EntryExist => SysError::Exists, FsError::NotSameFs => SysError::Xdev, FsError::InvalidParam => SysError::Inval, FsError::NoDeviceSpace => SysError::Nomem, FsError::DirRemoved => SysError::Noent, - FsError::DirNotEmpty => SysError::Isdir,// It should be E_NOTEMPTY in linux, but in ucore it is equal to E_Isdir + FsError::DirNotEmpty => SysError::Notempty, FsError::WrongFs => SysError::Inval, } } From 6302497c52c2514c073bed828293fd1b58e4b49a Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Thu, 20 Dec 2018 22:15:14 +0800 Subject: [PATCH 13/15] a shell without execute is a repeater! --- user/src/bin/sh.rs | 61 +++++++++++++++++++++++++ user/ucore-ulib/src/io.rs | 76 +++++++++++++++++++++++++++++++ user/ucore-ulib/src/lang_items.rs | 8 ++-- user/ucore-ulib/src/lib.rs | 1 + user/ucore-ulib/src/syscall.rs | 63 ++----------------------- 5 files changed, 147 insertions(+), 62 deletions(-) create mode 100644 user/src/bin/sh.rs create mode 100644 user/ucore-ulib/src/io.rs diff --git a/user/src/bin/sh.rs b/user/src/bin/sh.rs new file mode 100644 index 0000000..486541f --- /dev/null +++ b/user/src/bin/sh.rs @@ -0,0 +1,61 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate ucore_ulib; +use ucore_ulib::io::getc; + +pub fn get_line(buffer: &mut[u8]) -> usize { + let mut pos: usize=0; + loop { + let ret=getc(); + match ret { + None => break, + Some(byte) => { + let c = byte as char; + match c { + '\u{8}' /* '\b' */ => { + if pos > 0 { + print!("\u{8} \u{8}"); + pos-=1; + } + } + ' '...'\u{7e}' => { + if pos { + print!("\n"); + break; + } + _ => {} + } + }, + } + } + pos +} + +const BUFFER_SIZE:usize=4096; + +// IMPORTANT: Must define main() like this +#[no_mangle] +pub fn main() { + use core::mem::uninitialized; + let mut buf:[u8;BUFFER_SIZE] = unsafe { uninitialized() }; + println!("Rust user shell"); + loop { + print!(">> "); + let len = get_line(&mut buf); + if len>BUFFER_SIZE { + println!("Command is too long!"); + continue; + } + let command=&buf[..len]; + use core::str; + println!("{}", unsafe{ str::from_utf8_unchecked(command) }) + } +} diff --git a/user/ucore-ulib/src/io.rs b/user/ucore-ulib/src/io.rs new file mode 100644 index 0000000..4c287c2 --- /dev/null +++ b/user/ucore-ulib/src/io.rs @@ -0,0 +1,76 @@ +use core::fmt::{self, Write}; +use core::option::Option; +use crate::syscall::{sys_write, sys_read, sys_putc}; + +pub const STDIN: usize=0; +pub const STDOUT: usize=1; + +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ({ + $crate::io::print(format_args!($($arg)*)); + }); +} + +#[macro_export] +macro_rules! println { + ($fmt:expr) => (print!(concat!($fmt, "\n"))); + ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*)); +} + +pub fn print(args: fmt::Arguments) { + StdOut.write_fmt(args).unwrap(); +} + +pub fn print_putc(args: fmt::Arguments) { + SysPutc.write_fmt(args).unwrap(); +} + +pub fn getc() -> Option{ + use core::mem::uninitialized; + let mut c:[u8;1] = unsafe { uninitialized() }; + let ret=sys_read(STDIN,c.as_mut_ptr(),1); + match ret { + 1 => Some(c[0]), + 0 => None, + _ => panic!(), + } +} + +pub fn putc(c:u8){ + sys_putc(c); +} + +struct StdOut; +struct SysPutc; + +impl fmt::Write for StdOut { + fn write_str(&mut self, s: &str) -> fmt::Result { + if sys_write(STDOUT, s.as_ptr(), s.len()) >= 0 { + Ok(()) + } else { + Err(fmt::Error::default()) + } + } +} + +impl fmt::Write for SysPutc { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.bytes() { + sys_putc(c); + } + Ok(()) + } +} + +/* VFS flags */ +// TODO: use bitflags +// flags for open: choose one of these +pub const O_RDONLY: usize = 0; // open for reading only +pub const O_WRONLY: usize = 1; // open for writing only +pub const O_RDWR: usize = 2; // open for reading and writing +// then or in any of these: +pub const O_CREAT: usize = 0x00000004; // create file if it does not exist +pub const O_EXCL: usize = 0x00000008; // error if O_CREAT and the file exists +pub const O_TRUNC: usize = 0x00000010; // truncate file upon open +pub const O_APPEND: usize = 0x00000020; // append on each write \ No newline at end of file diff --git a/user/ucore-ulib/src/lang_items.rs b/user/ucore-ulib/src/lang_items.rs index e1e58d8..fbcb1b2 100644 --- a/user/ucore-ulib/src/lang_items.rs +++ b/user/ucore-ulib/src/lang_items.rs @@ -1,12 +1,12 @@ use crate::syscall::{sys_close, sys_dup, sys_exit, sys_open}; -use crate::syscall::{O_RDONLY, O_WRONLY}; +use crate::io::{O_RDONLY, O_WRONLY, STDIN, STDOUT}; use core::alloc::Layout; use core::panic::PanicInfo; // used for panic macro_rules! print { ($($arg:tt)*) => ({ - $crate::syscall::print_putc(format_args!($($arg)*)); + $crate::io::print_putc(format_args!($($arg)*)); }); } @@ -33,11 +33,11 @@ fn initfd(fd2: usize, path: &str, open_flags: usize) -> i32 { #[no_mangle] pub extern "C" fn _start(_argc: isize, _argv: *const *const u8) -> ! { - let fd = initfd(0, "stdin:", O_RDONLY); + let fd = initfd(STDIN, "stdin:", O_RDONLY); if fd < 0 { panic!("open failed: {}.", fd); } - let fd = initfd(1, "stdout:", O_WRONLY); + let fd = initfd(STDOUT, "stdout:", O_WRONLY); if fd < 0 { panic!("open failed: {}.", fd); } diff --git a/user/ucore-ulib/src/lib.rs b/user/ucore-ulib/src/lib.rs index 4908eb5..3cd6042 100644 --- a/user/ucore-ulib/src/lib.rs +++ b/user/ucore-ulib/src/lib.rs @@ -6,5 +6,6 @@ #![feature(compiler_builtins_lib)] #[macro_use] +pub mod io; pub mod syscall; pub mod lang_items; \ No newline at end of file diff --git a/user/ucore-ulib/src/syscall.rs b/user/ucore-ulib/src/syscall.rs index da3ae5d..9eeddf2 100644 --- a/user/ucore-ulib/src/syscall.rs +++ b/user/ucore-ulib/src/syscall.rs @@ -1,48 +1,3 @@ -use core::fmt::{self, Write}; - -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ({ - $crate::syscall::print(format_args!($($arg)*)); - }); -} - -#[macro_export] -macro_rules! println { - ($fmt:expr) => (print!(concat!($fmt, "\n"))); - ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*)); -} - -pub fn print(args: fmt::Arguments) { - StdOut.write_fmt(args).unwrap(); -} - -pub fn print_putc(args: fmt::Arguments) { - SysPutc.write_fmt(args).unwrap(); -} - -struct StdOut; -struct SysPutc; - -impl fmt::Write for StdOut { - fn write_str(&mut self, s: &str) -> fmt::Result { - if sys_write(1, s.as_ptr(), s.len()) >= 0 { - Ok(()) - } else { - Err(fmt::Error::default()) - } - } -} - -impl fmt::Write for SysPutc { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.bytes() { - sys_putc(c as char); - } - Ok(()) - } -} - #[inline(always)] fn sys_call(syscall_id: SyscallId, arg0: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) -> i32 { let id = syscall_id as usize; @@ -79,6 +34,10 @@ pub fn sys_write(fd: usize, base: *const u8, len: usize) -> i32 { sys_call(SyscallId::Write, fd, base as usize, len, 0, 0, 0) } +pub fn sys_read(fd: usize, base: *mut u8, len: usize) -> i32 { + sys_call(SyscallId::Read, fd, base as usize, len, 0, 0, 0) +} + pub fn sys_open(path: &str, flags: usize) -> i32 { // UNSAFE: append '\0' to the string use core::mem::replace; @@ -134,7 +93,7 @@ pub fn sys_lab6_set_priority(priority: usize) -> i32 { sys_call(SyscallId::Lab6SetPriority, priority, 0, 0, 0, 0, 0) } -pub fn sys_putc(c: char) -> i32 { +pub fn sys_putc(c: u8) -> i32 { sys_call(SyscallId::Putc, c as usize, 0, 0, 0, 0, 0) } @@ -167,15 +126,3 @@ enum SyscallId{ Dup = 130, Lab6SetPriority = 255, } - -/* VFS flags */ -// TODO: use bitflags -// flags for open: choose one of these -pub const O_RDONLY: usize = 0; // open for reading only -pub const O_WRONLY: usize = 1; // open for writing only -pub const O_RDWR: usize = 2; // open for reading and writing -// then or in any of these: -pub const O_CREAT: usize = 0x00000004; // create file if it does not exist -pub const O_EXCL: usize = 0x00000008; // error if O_CREAT and the file exists -pub const O_TRUNC: usize = 0x00000010; // truncate file upon open -pub const O_APPEND: usize = 0x00000020; // append on each write From 5135fb0c0e12c73f91020957c27e62f029a2f9f2 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Fri, 21 Dec 2018 14:18:23 +0800 Subject: [PATCH 14/15] the shell that is able to fork-exec-wait --- kernel/src/syscall.rs | 3 ++ user/src/bin/sh.rs | 62 +++++++++++++++++++++++++++++++--- user/ucore-ulib/src/syscall.rs | 5 +++ 3 files changed, 65 insertions(+), 5 deletions(-) diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 4f60ca2..fab4552 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -198,6 +198,9 @@ fn sys_exec(name: *const u8, argc: usize, argv: *const *const u8, tf: &mut TrapF .collect() }; + if args.len() <= 0 { + return Err(SysError::Inval); + } // Read program file let path = args[0].as_str(); let inode = crate::fs::ROOT_INODE.lookup(path)?; diff --git a/user/src/bin/sh.rs b/user/src/bin/sh.rs index 486541f..70e84e3 100644 --- a/user/src/bin/sh.rs +++ b/user/src/bin/sh.rs @@ -4,6 +4,7 @@ #[macro_use] extern crate ucore_ulib; use ucore_ulib::io::getc; +use ucore_ulib::syscall::{sys_fork, sys_exec, sys_wait}; pub fn get_line(buffer: &mut[u8]) -> usize { let mut pos: usize=0; @@ -43,7 +44,7 @@ const BUFFER_SIZE:usize=4096; // IMPORTANT: Must define main() like this #[no_mangle] -pub fn main() { +pub fn main() -> i32 { use core::mem::uninitialized; let mut buf:[u8;BUFFER_SIZE] = unsafe { uninitialized() }; println!("Rust user shell"); @@ -52,10 +53,61 @@ pub fn main() { let len = get_line(&mut buf); if len>BUFFER_SIZE { println!("Command is too long!"); - continue; + }else{ + let cmd=&buf[..len]; + let mut parsed:[u8;BUFFER_SIZE+1] = unsafe { uninitialized() }; + let mut offset:[usize;BUFFER_SIZE+1] = unsafe { uninitialized() }; + let mut start:usize = 0; + let mut pos:usize = 0; + let mut is_word = false; + let mut parsed_pos:usize = 0; + let mut offset_pos:usize = 0; + loop { + if pos>=cmd.len() { + if is_word { + offset[offset_pos]=parsed_pos; + offset_pos+=1; + parsed[parsed_pos..parsed_pos+pos-start].copy_from_slice(&cmd[start..pos]); + parsed_pos+=pos-start; + parsed[parsed_pos]=0; + // parsed_pos+=1; + } + break; + } + if cmd[pos]==(' ' as u8) { + if is_word { + is_word=false; + offset[offset_pos]=parsed_pos; + offset_pos+=1; + parsed[parsed_pos..parsed_pos+pos-start].copy_from_slice(&cmd[start..pos]); + parsed_pos+=pos-start; + parsed[parsed_pos]=0; + parsed_pos+=1; + } + }else{ + if !is_word { + is_word=true; + start=pos; + } + } + pos+=1; + } + if offset_pos > 0 { + let pid=sys_fork(); + if pid==0 { + let mut ptrs:[*const u8;BUFFER_SIZE] = unsafe { uninitialized() }; + for i in 0..offset_pos { + ptrs[i]=unsafe {parsed.as_ptr().offset(offset[i] as isize)}; + } + return sys_exec(parsed.as_ptr(),offset_pos,ptrs.as_ptr()); + }else if pid<0 { + panic!("pid<0") + }else{ + let mut code:i32 = unsafe { uninitialized() }; + sys_wait(pid as usize,&mut code as *mut i32); + println!("\n[Process exited with code {}]",code); + } + } } - let command=&buf[..len]; - use core::str; - println!("{}", unsafe{ str::from_utf8_unchecked(command) }) } } diff --git a/user/ucore-ulib/src/syscall.rs b/user/ucore-ulib/src/syscall.rs index 9eeddf2..8f0b06a 100644 --- a/user/ucore-ulib/src/syscall.rs +++ b/user/ucore-ulib/src/syscall.rs @@ -30,6 +30,11 @@ pub fn sys_exit(code: usize) -> ! { unreachable!() } + +pub fn sys_exec(name: *const u8, argc: usize, argv: *const *const u8) -> i32 { + sys_call(SyscallId::Exec, name as usize, argc, argv as usize, 0, 0, 0) +} + pub fn sys_write(fd: usize, base: *const u8, len: usize) -> i32 { sys_call(SyscallId::Write, fd, base as usize, len, 0, 0, 0) } From 64a00d49462975b80ac9710ac23b6337b39adce9 Mon Sep 17 00:00:00 2001 From: Ben Pig Chu Date: Thu, 27 Dec 2018 16:04:07 +0800 Subject: [PATCH 15/15] rustfmt the sh.rs --- user/src/bin/sh.rs | 158 +++++++++++++++++++++++---------------------- 1 file changed, 80 insertions(+), 78 deletions(-) diff --git a/user/src/bin/sh.rs b/user/src/bin/sh.rs index 70e84e3..c145be0 100644 --- a/user/src/bin/sh.rs +++ b/user/src/bin/sh.rs @@ -4,17 +4,17 @@ #[macro_use] extern crate ucore_ulib; use ucore_ulib::io::getc; -use ucore_ulib::syscall::{sys_fork, sys_exec, sys_wait}; +use ucore_ulib::syscall::{sys_exec, sys_fork, sys_wait}; -pub fn get_line(buffer: &mut[u8]) -> usize { - let mut pos: usize=0; - loop { - let ret=getc(); - match ret { - None => break, - Some(byte) => { - let c = byte as char; - match c { +pub fn get_line(buffer: &mut [u8]) -> usize { + let mut pos: usize = 0; + loop { + let ret = getc(); + match ret { + None => break, + Some(byte) => { + let c = byte as char; + match c { '\u{8}' /* '\b' */ => { if pos > 0 { print!("\u{8} \u{8}"); @@ -34,80 +34,82 @@ pub fn get_line(buffer: &mut[u8]) -> usize { } _ => {} } - }, - } - } - pos + } + } + } + pos } -const BUFFER_SIZE:usize=4096; +const BUFFER_SIZE: usize = 4096; // IMPORTANT: Must define main() like this #[no_mangle] pub fn main() -> i32 { - use core::mem::uninitialized; - let mut buf:[u8;BUFFER_SIZE] = unsafe { uninitialized() }; - println!("Rust user shell"); - loop { + use core::mem::uninitialized; + let mut buf: [u8; BUFFER_SIZE] = unsafe { uninitialized() }; + println!("Rust user shell"); + loop { print!(">> "); let len = get_line(&mut buf); - if len>BUFFER_SIZE { - println!("Command is too long!"); - }else{ - let cmd=&buf[..len]; - let mut parsed:[u8;BUFFER_SIZE+1] = unsafe { uninitialized() }; - let mut offset:[usize;BUFFER_SIZE+1] = unsafe { uninitialized() }; - let mut start:usize = 0; - let mut pos:usize = 0; - let mut is_word = false; - let mut parsed_pos:usize = 0; - let mut offset_pos:usize = 0; - loop { - if pos>=cmd.len() { - if is_word { - offset[offset_pos]=parsed_pos; - offset_pos+=1; - parsed[parsed_pos..parsed_pos+pos-start].copy_from_slice(&cmd[start..pos]); - parsed_pos+=pos-start; - parsed[parsed_pos]=0; - // parsed_pos+=1; - } - break; - } - if cmd[pos]==(' ' as u8) { - if is_word { - is_word=false; - offset[offset_pos]=parsed_pos; - offset_pos+=1; - parsed[parsed_pos..parsed_pos+pos-start].copy_from_slice(&cmd[start..pos]); - parsed_pos+=pos-start; - parsed[parsed_pos]=0; - parsed_pos+=1; - } - }else{ - if !is_word { - is_word=true; - start=pos; - } - } - pos+=1; - } - if offset_pos > 0 { - let pid=sys_fork(); - if pid==0 { - let mut ptrs:[*const u8;BUFFER_SIZE] = unsafe { uninitialized() }; - for i in 0..offset_pos { - ptrs[i]=unsafe {parsed.as_ptr().offset(offset[i] as isize)}; - } - return sys_exec(parsed.as_ptr(),offset_pos,ptrs.as_ptr()); - }else if pid<0 { - panic!("pid<0") - }else{ - let mut code:i32 = unsafe { uninitialized() }; - sys_wait(pid as usize,&mut code as *mut i32); - println!("\n[Process exited with code {}]",code); - } - } - } - } + if len > BUFFER_SIZE { + println!("Command is too long!"); + } else { + let cmd = &buf[..len]; + let mut parsed: [u8; BUFFER_SIZE + 1] = unsafe { uninitialized() }; + let mut offset: [usize; BUFFER_SIZE + 1] = unsafe { uninitialized() }; + let mut start: usize = 0; + let mut pos: usize = 0; + let mut is_word = false; + let mut parsed_pos: usize = 0; + let mut offset_pos: usize = 0; + loop { + if pos >= cmd.len() { + if is_word { + offset[offset_pos] = parsed_pos; + offset_pos += 1; + parsed[parsed_pos..parsed_pos + pos - start] + .copy_from_slice(&cmd[start..pos]); + parsed_pos += pos - start; + parsed[parsed_pos] = 0; + // parsed_pos+=1; + } + break; + } + if cmd[pos] == (' ' as u8) { + if is_word { + is_word = false; + offset[offset_pos] = parsed_pos; + offset_pos += 1; + parsed[parsed_pos..parsed_pos + pos - start] + .copy_from_slice(&cmd[start..pos]); + parsed_pos += pos - start; + parsed[parsed_pos] = 0; + parsed_pos += 1; + } + } else { + if !is_word { + is_word = true; + start = pos; + } + } + pos += 1; + } + if offset_pos > 0 { + let pid = sys_fork(); + if pid == 0 { + let mut ptrs: [*const u8; BUFFER_SIZE] = unsafe { uninitialized() }; + for i in 0..offset_pos { + ptrs[i] = unsafe { parsed.as_ptr().offset(offset[i] as isize) }; + } + return sys_exec(parsed.as_ptr(), offset_pos, ptrs.as_ptr()); + } else if pid < 0 { + panic!("pid<0") + } else { + let mut code: i32 = unsafe { uninitialized() }; + sys_wait(pid as usize, &mut code as *mut i32); + println!("\n[Process exited with code {}]", code); + } + } + } + } }