Browse Source

引入clippy,并根据clippy的提示,修改部分代码 (#575)

LoGin 1 year ago
parent
commit
840045af94

+ 2 - 0
kernel/.clippy.toml

@@ -0,0 +1,2 @@
+# 这是clippy的配置文件,详情请见:
+# https://doc.rust-lang.org/clippy/lint_configuration.html

+ 1 - 0
kernel/crates/bitmap/src/lib.rs

@@ -2,6 +2,7 @@
 #![feature(core_intrinsics)]
 #![allow(incomplete_features)] // for const generics
 #![feature(generic_const_exprs)]
+#![allow(clippy::needless_return)]
 
 #[macro_use]
 extern crate alloc;

+ 2 - 0
kernel/crates/crc/src/lib.rs

@@ -2,6 +2,8 @@
 #![feature(const_for)]
 #![feature(const_mut_refs)]
 #![feature(const_trait_impl)]
+#![allow(clippy::needless_return)]
+
 #[cfg(test)]
 extern crate std;
 

+ 0 - 2
kernel/crates/kdepends/src/lib.rs

@@ -1,7 +1,5 @@
 #![no_std]
 
-#[allow(unused)]
-#[macro_use]
 pub extern crate thingbuf;
 
 pub extern crate memoffset;

+ 3 - 2
kernel/crates/klog_types/src/lib.rs

@@ -1,6 +1,7 @@
 #![no_std]
 #![feature(const_refs_to_cell)]
 #![feature(const_size_of_val)]
+#![allow(clippy::needless_return)]
 
 extern crate alloc;
 use core::{fmt::Debug, mem::size_of_val};
@@ -88,7 +89,7 @@ impl AllocatorLog {
 
     /// 当前日志是否有效
     pub fn is_valid(&self) -> bool {
-        if self.validate_checksum() == false {
+        if !self.validate_checksum() {
             return false;
         }
 
@@ -102,7 +103,7 @@ impl AllocatorLog {
 
 impl PartialOrd for AllocatorLog {
     fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
-        return self.id.partial_cmp(&other.id);
+        Some(self.cmp(other))
     }
 }
 

+ 2 - 0
kernel/crates/system_error/src/lib.rs

@@ -1,4 +1,6 @@
 #![no_std]
+#![allow(clippy::needless_return)]
+#![allow(clippy::upper_case_acronyms)]
 
 use num_derive::{FromPrimitive, ToPrimitive};
 

+ 1 - 0
kernel/crates/unified-init/src/lib.rs

@@ -1,4 +1,5 @@
 #![no_std]
+#![allow(clippy::needless_return)]
 
 use system_error::SystemError;
 pub use unified_init_macros as macros;

+ 1 - 1
kernel/rust-toolchain.toml

@@ -1,3 +1,3 @@
 [toolchain]
 channel = "nightly-2023-08-15"
-components = ["rust-src"]
+components = ["rust-src", "clippy"]

+ 7 - 0
kernel/src/lib.rs

@@ -23,6 +23,13 @@
 #![feature(slice_ptr_get)]
 #![feature(vec_into_raw_parts)]
 #![cfg_attr(target_os = "none", no_std)]
+// clippy的配置
+#![deny(clippy::all)]
+// DragonOS允许在函数中使用return语句(尤其是长函数时,我们推荐这么做)
+#![allow(clippy::let_and_return)]
+#![allow(clippy::needless_pass_by_ref_mut)]
+#![allow(clippy::needless_return)]
+#![allow(clippy::upper_case_acronyms)]
 
 #[cfg(test)]
 #[macro_use]

+ 1 - 0
kernel/src/libs/ida/src/lib.rs

@@ -1,5 +1,6 @@
 #![no_std]
 #![feature(core_intrinsics)]
+#![allow(clippy::needless_return)]
 
 use core::intrinsics::unlikely;
 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

+ 1 - 1
kernel/src/mm/page.rs

@@ -791,7 +791,7 @@ impl<Arch: MemoryManagementArch, F: FrameAllocator> PageMapper<Arch, F> {
 /// 如果取消成功,返回被取消映射的页表项的:【物理地址】和【flags】,否则返回None
 unsafe fn unmap_phys_inner<Arch: MemoryManagementArch>(
     vaddr: VirtAddr,
-    table: &mut PageTable<Arch>,
+    table: &PageTable<Arch>,
     unmap_parents: bool,
     allocator: &mut impl FrameAllocator,
 ) -> Option<(PhysAddr, PageFlags<Arch>)> {

+ 1 - 1
kernel/src/net/event_poll/mod.rs

@@ -707,7 +707,7 @@ impl EventPoll {
 
     /// ### epoll的回调,支持epoll的文件有事件到来时直接调用该方法即可
     pub fn wakeup_epoll(
-        epitems: &mut SpinLock<LinkedList<Arc<EPollItem>>>,
+        epitems: &SpinLock<LinkedList<Arc<EPollItem>>>,
         pollflags: EPollEventType,
     ) -> Result<(), SystemError> {
         let mut epitems_guard = epitems.try_lock_irqsave()?;

+ 2 - 2
kernel/src/process/fork.rs

@@ -151,7 +151,7 @@ impl ProcessManager {
     ///
     /// - fork失败的话,子线程不会执行。
     pub fn fork(
-        current_trapframe: &mut TrapFrame,
+        current_trapframe: &TrapFrame,
         clone_flags: CloneFlags,
     ) -> Result<Pid, SystemError> {
         let current_pcb = ProcessManager::current_pcb();
@@ -300,7 +300,7 @@ impl ProcessManager {
         current_pcb: &Arc<ProcessControlBlock>,
         pcb: &Arc<ProcessControlBlock>,
         clone_args: KernelCloneArgs,
-        current_trapframe: &mut TrapFrame,
+        current_trapframe: &TrapFrame,
     ) -> Result<(), SystemError> {
         let clone_flags = clone_args.flags;
         // 不允许与不同namespace的进程共享根目录

+ 3 - 3
kernel/src/process/syscall.rs

@@ -30,11 +30,11 @@ use crate::{
 };
 
 impl Syscall {
-    pub fn fork(frame: &mut TrapFrame) -> Result<usize, SystemError> {
+    pub fn fork(frame: &TrapFrame) -> Result<usize, SystemError> {
         ProcessManager::fork(frame, CloneFlags::empty()).map(|pid| pid.into())
     }
 
-    pub fn vfork(frame: &mut TrapFrame) -> Result<usize, SystemError> {
+    pub fn vfork(frame: &TrapFrame) -> Result<usize, SystemError> {
         // 由于Linux vfork需要保证子进程先运行(除非子进程调用execve或者exit),
         // 而我们目前没有实现这个特性,所以暂时使用fork代替vfork(linux文档表示这样也是也可以的)
         Self::fork(frame)
@@ -171,7 +171,7 @@ impl Syscall {
     }
 
     pub fn clone(
-        current_trapframe: &mut TrapFrame,
+        current_trapframe: &TrapFrame,
         clone_args: KernelCloneArgs,
     ) -> Result<usize, SystemError> {
         let flags = clone_args.flags;

+ 1 - 1
kernel/src/sched/cfs.rs

@@ -57,7 +57,7 @@ impl CFSQueue {
         CFSQueue {
             cpu_exec_proc_jiffies: 0,
             locked_queue: SpinLock::new(RBTree::new()),
-            idle_pcb: idle_pcb,
+            idle_pcb,
         }
     }
 

+ 1 - 1
kernel/src/syscall/misc.rs

@@ -77,7 +77,7 @@ impl Syscall {
         while count < len {
             let rand = rand();
             for offset in 0..4 {
-                ret.push((rand >> offset * 2) as u8);
+                ret.push(rand >> (offset * 2));
                 count += 1;
             }
         }

+ 18 - 19
kernel/src/syscall/mod.rs

@@ -543,18 +543,18 @@ impl Syscall {
                 let virt_addr = VirtAddr::new(addr as usize);
                 let security_check = || {
                     // 验证buf的地址是否合法
-                    if verify_area(virt_buf, len as usize).is_err() {
+                    if verify_area(virt_buf, len).is_err() {
                         // 地址空间超出了用户空间的范围,不合法
                         return Err(SystemError::EFAULT);
                     }
 
                     // 验证addrlen的地址是否合法
-                    if verify_area(virt_addrlen, core::mem::size_of::<u32>() as usize).is_err() {
+                    if verify_area(virt_addrlen, core::mem::size_of::<u32>()).is_err() {
                         // 地址空间超出了用户空间的范围,不合法
                         return Err(SystemError::EFAULT);
                     }
 
-                    if verify_area(virt_addr, core::mem::size_of::<SockAddr>() as usize).is_err() {
+                    if verify_area(virt_addr, core::mem::size_of::<SockAddr>()).is_err() {
                         // 地址空间超出了用户空间的范围,不合法
                         return Err(SystemError::EFAULT);
                     }
@@ -603,8 +603,8 @@ impl Syscall {
             }
             SYS_MMAP => {
                 let len = page_align_up(args[1]);
-                let virt_addr = VirtAddr::new(args[0] as usize);
-                if verify_area(virt_addr, len as usize).is_err() {
+                let virt_addr = VirtAddr::new(args[0]);
+                if verify_area(virt_addr, len).is_err() {
                     Err(SystemError::EFAULT)
                 } else {
                     Self::mmap(
@@ -649,7 +649,7 @@ impl Syscall {
 
             SYS_GETCWD => {
                 let buf = args[0] as *mut u8;
-                let size = args[1] as usize;
+                let size = args[1];
                 let security_check = || {
                     verify_area(VirtAddr::new(buf as usize), size)?;
                     return Ok(());
@@ -695,7 +695,7 @@ impl Syscall {
 
             SYS_FTRUNCATE => {
                 let fd = args[0] as i32;
-                let len = args[1] as usize;
+                let len = args[1];
                 let res = Self::ftruncate(fd, len);
                 // kdebug!("FTRUNCATE: fd: {}, len: {}, res: {:?}", fd, len, res);
                 res
@@ -746,7 +746,7 @@ impl Syscall {
                         true,
                     )?;
 
-                    timespec = Some(reader.read_one_from_user::<TimeSpec>(0)?.clone());
+                    timespec = Some(*reader.read_one_from_user::<TimeSpec>(0)?);
                 }
 
                 Self::do_futex(uaddr, operation, val, timespec, uaddr2, utime as u32, val3)
@@ -824,7 +824,7 @@ impl Syscall {
                 }
                 let sigmask_reader =
                     UserBufferReader::new(sigmask_addr, core::mem::size_of::<SigSet>(), true)?;
-                let mut sigmask = sigmask_reader.read_one_from_user::<SigSet>(0)?.clone();
+                let mut sigmask = *sigmask_reader.read_one_from_user::<SigSet>(0)?;
 
                 Self::epoll_pwait(
                     args[0] as i32,
@@ -888,10 +888,10 @@ impl Syscall {
                 Ok(0)
             }
             SYS_GETTID => Self::gettid().map(|tid| tid.into()),
-            SYS_GETUID => Self::getuid().map(|uid| uid.into()),
+            SYS_GETUID => Self::getuid(),
 
             SYS_SYSLOG => {
-                let syslog_action_type = args[0] as usize;
+                let syslog_action_type = args[0];
                 let buf_vaddr = args[1];
                 let len = args[2];
                 let from_user = frame.from_user();
@@ -899,11 +899,10 @@ impl Syscall {
                     UserBufferWriter::new(buf_vaddr as *mut u8, len, from_user)?;
 
                 let user_buf = user_buffer_writer.buffer(0)?;
-                let res = Self::do_syslog(syslog_action_type, user_buf, len);
-                res
+                Self::do_syslog(syslog_action_type, user_buf, len)
             }
 
-            SYS_GETGID => Self::getgid().map(|gid| gid.into()),
+            SYS_GETGID => Self::getgid(),
             SYS_SETUID => {
                 kwarn!("SYS_SETUID has not yet been implemented");
                 Ok(0)
@@ -912,8 +911,8 @@ impl Syscall {
                 kwarn!("SYS_SETGID has not yet been implemented");
                 Ok(0)
             }
-            SYS_GETEUID => Self::geteuid().map(|euid| euid.into()),
-            SYS_GETEGID => Self::getegid().map(|egid| egid.into()),
+            SYS_GETEUID => Self::geteuid(),
+            SYS_GETEGID => Self::getegid(),
             SYS_GETRUSAGE => {
                 let who = args[0] as c_int;
                 let rusage = args[1] as *mut RUsage;
@@ -924,7 +923,7 @@ impl Syscall {
             SYS_READLINK => {
                 let path = args[0] as *const u8;
                 let buf = args[1] as *mut u8;
-                let bufsiz = args[2] as usize;
+                let bufsiz = args[2];
                 Self::readlink(path, buf, bufsiz)
             }
 
@@ -932,7 +931,7 @@ impl Syscall {
                 let dirfd = args[0] as i32;
                 let pathname = args[1] as *const u8;
                 let buf = args[2] as *mut u8;
-                let bufsiz = args[3] as usize;
+                let bufsiz = args[3];
                 Self::readlink_at(dirfd, pathname, buf, bufsiz)
             }
 
@@ -1026,7 +1025,7 @@ impl Syscall {
                 Self::prlimit64(
                     ProcessManager::current_pcb().pid(),
                     resource,
-                    0 as *const RLimit64,
+                    core::ptr::null::<RLimit64>(),
                     rlimit,
                 )
             }

+ 2 - 2
kernel/src/time/clocksource.rs

@@ -248,11 +248,11 @@ impl dyn Clocksource {
     /// # 计算时钟源能记录的最大时间跨度
     pub fn clocksource_max_deferment(&self) -> u64 {
         let cs_data_guard = self.clocksource_data();
-        let max_nsecs: u64;
+
         let mut max_cycles: u64;
         max_cycles = (1 << (63 - (log2(cs_data_guard.mult) + 1))) as u64;
         max_cycles = max_cycles.min(cs_data_guard.mask.bits);
-        max_nsecs = clocksource_cyc2ns(
+        let max_nsecs = clocksource_cyc2ns(
             CycleNum(max_cycles),
             cs_data_guard.mult,
             cs_data_guard.shift,

+ 2 - 2
kernel/src/time/jiffies.rs

@@ -16,9 +16,9 @@ lazy_static! {
 }
 pub const CLOCK_TICK_RATE: u32 = HZ as u32 * 100000;
 pub const JIFFIES_SHIFT: u32 = 8;
-pub const LATCH: u32 = ((CLOCK_TICK_RATE + (HZ as u32) / 2) / HZ as u32) as u32;
+pub const LATCH: u32 = (CLOCK_TICK_RATE + (HZ as u32) / 2) / HZ as u32;
 pub const ACTHZ: u32 = sh_div(CLOCK_TICK_RATE, LATCH, 8);
-pub const NSEC_PER_JIFFY: u32 = ((NSEC_PER_SEC << 8) / ACTHZ) as u32;
+pub const NSEC_PER_JIFFY: u32 = (NSEC_PER_SEC << 8) / ACTHZ;
 pub const fn sh_div(nom: u32, den: u32, lsh: u32) -> u32 {
     (((nom) / (den)) << (lsh)) + ((((nom) % (den)) << (lsh)) + (den) / 2) / (den)
 }

+ 9 - 9
kernel/src/time/mod.rs

@@ -99,9 +99,9 @@ impl From<Duration> for TimeSpec {
     }
 }
 
-impl Into<Duration> for TimeSpec {
-    fn into(self) -> Duration {
-        Duration::from_micros(self.tv_sec as u64 * 1000000 + self.tv_nsec as u64 / 1000)
+impl From<TimeSpec> for Duration {
+    fn from(val: TimeSpec) -> Self {
+        Duration::from_micros(val.tv_sec as u64 * 1000000 + val.tv_nsec as u64 / 1000)
     }
 }
 
@@ -403,9 +403,9 @@ impl From<smoltcp::time::Instant> for Instant {
     }
 }
 
-impl Into<smoltcp::time::Instant> for Instant {
-    fn into(self) -> smoltcp::time::Instant {
-        smoltcp::time::Instant::from_millis(self.millis())
+impl From<Instant> for smoltcp::time::Instant {
+    fn from(val: Instant) -> Self {
+        smoltcp::time::Instant::from_millis(val.millis())
     }
 }
 
@@ -416,9 +416,9 @@ impl From<smoltcp::time::Duration> for Duration {
     }
 }
 
-impl Into<smoltcp::time::Duration> for Duration {
-    fn into(self) -> smoltcp::time::Duration {
-        smoltcp::time::Duration::from_millis(self.millis())
+impl From<Duration> for smoltcp::time::Duration {
+    fn from(val: Duration) -> Self {
+        smoltcp::time::Duration::from_millis(val.millis())
     }
 }
 

+ 3 - 6
kernel/src/time/syscall.rs

@@ -1,7 +1,4 @@
-use core::{
-    ffi::{c_int, c_longlong},
-    ptr::null_mut,
-};
+use core::ffi::{c_int, c_longlong};
 
 use num_traits::FromPrimitive;
 use system_error::SystemError;
@@ -76,7 +73,7 @@ impl Syscall {
         sleep_time: *const TimeSpec,
         rm_time: *mut TimeSpec,
     ) -> Result<usize, SystemError> {
-        if sleep_time == null_mut() {
+        if sleep_time.is_null() {
             return Err(SystemError::EFAULT);
         }
         let slt_spec = TimeSpec {
@@ -85,7 +82,7 @@ impl Syscall {
         };
 
         let r: Result<usize, SystemError> = nanosleep(slt_spec).map(|slt_spec| {
-            if rm_time != null_mut() {
+            if !rm_time.is_null() {
                 unsafe { *rm_time }.tv_sec = slt_spec.tv_sec;
                 unsafe { *rm_time }.tv_nsec = slt_spec.tv_nsec;
             }

+ 2 - 2
kernel/src/time/timeconv.rs

@@ -101,11 +101,11 @@ pub fn time_to_calendar(totalsecs: PosixTimeT, offset: i32) -> CalendarTime {
     }
     // 计算对应的小时数
     result.tm_hour = (rem / SECS_PER_HOUR) as i32;
-    rem = rem % SECS_PER_HOUR;
+    rem %= SECS_PER_HOUR;
 
     // 计算对应的分钟数
     result.tm_min = (rem / 60) as i32;
-    rem = rem % 60;
+    rem %= 60;
 
     // 秒数
     result.tm_sec = rem as i32;

+ 3 - 3
kernel/src/time/timekeep.rs

@@ -8,7 +8,7 @@ pub type ktime_t = i64;
 // @brief 将ktime_t类型转换为纳秒类型
 #[inline]
 fn ktime_to_ns(kt: ktime_t) -> i64 {
-    return kt as i64;
+    return kt;
 }
 
 /// @brief 从RTC获取当前时间,然后计算时间戳。
@@ -20,8 +20,8 @@ fn ktime_get_real() -> ktime_t {
     {
         let r = rtc_time.get();
         // 返回错误码
-        if r.is_err() {
-            return r.unwrap_err() as ktime_t;
+        if let Err(e) = r {
+            return e as ktime_t;
         }
     }
 

+ 3 - 7
kernel/src/time/timer.rs

@@ -145,7 +145,7 @@ impl Timer {
         TIMER_LIST
             .lock_irqsave()
             .extract_if(|x| Arc::ptr_eq(&this_arc, x))
-            .for_each(|p| drop(p));
+            .for_each(drop);
         true
     }
 }
@@ -179,11 +179,7 @@ impl DoTimerSoftirq {
         let x = self
             .running
             .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed);
-        if x.is_ok() {
-            return true;
-        } else {
-            return false;
-        }
+        return x.is_ok();
     }
 
     fn clear_run(&self) {
@@ -192,7 +188,7 @@ impl DoTimerSoftirq {
 }
 impl SoftirqVec for DoTimerSoftirq {
     fn run(&self) {
-        if self.set_run() == false {
+        if !self.set_run() {
             return;
         }
         // 最多只处理TIMER_RUN_CYCLE_THRESHOLD个计时器

+ 4 - 15
kernel/src/virt/kvm/host_mem.rs

@@ -40,9 +40,10 @@ pub const PAGE_SHIFT: u32 = 12;
 pub const PAGE_SIZE: u32 = 1 << PAGE_SHIFT;
 pub const PAGE_MASK: u32 = !(PAGE_SIZE - 1);
 
-#[repr(C)]
 /// 通过这个结构可以将虚拟机的物理地址对应到用户进程的虚拟地址
 /// 用来表示虚拟机的一段物理内存
+#[repr(C)]
+#[derive(Default)]
 pub struct KvmUserspaceMemoryRegion {
     pub slot: u32, // 要在哪个slot上注册内存区间
     // flags有两个取值,KVM_MEM_LOG_DIRTY_PAGES和KVM_MEM_READONLY,用来指示kvm针对这段内存应该做的事情。
@@ -79,18 +80,6 @@ pub enum KvmMemoryChange {
     FlagsOnly,
 }
 
-impl Default for KvmUserspaceMemoryRegion {
-    fn default() -> KvmUserspaceMemoryRegion {
-        KvmUserspaceMemoryRegion {
-            slot: 0,
-            flags: 0,
-            guest_phys_addr: 0,
-            memory_size: 0,
-            userspace_addr: 0,
-        }
-    }
-}
-
 pub fn kvm_vcpu_memslots(_vcpu: &mut dyn Vcpu) -> KvmMemorySlots {
     let kvm = vm(0).unwrap();
     let as_id = 0;
@@ -127,10 +116,10 @@ fn __gfn_to_hva_many(
         return Err(SystemError::KVM_HVA_ERR_BAD);
     }
 
-    if nr_pages.is_some() {
-        let nr_pages = nr_pages.unwrap();
+    if let Some(nr_pages) = nr_pages {
         *nr_pages = slot.npages - (gfn - slot.base_gfn);
     }
+
     return Ok(__gfn_to_hva(slot, gfn));
 }
 

+ 2 - 2
kernel/src/virt/kvm/vm.rs

@@ -142,7 +142,7 @@ impl Vm {
             }
         }
 
-        if !(new_slot.flags & KVM_MEM_LOG_DIRTY_PAGES != 0) {
+        if (new_slot.flags & KVM_MEM_LOG_DIRTY_PAGES) == 0 {
             // new_slot.dirty_bitmap = 0;
         }
 
@@ -154,7 +154,7 @@ impl Vm {
         // }
         if change == KvmMemoryChange::Create {
             new_slot.userspace_addr = mem.userspace_addr;
-            let mut memslots = self.memslots[as_id as usize].memslots.clone();
+            let mut memslots = self.memslots[as_id as usize].memslots;
             memslots[id as usize] = new_slot;
             self.memslots[as_id as usize].memslots = memslots;
             self.memslots[as_id as usize].used_slots += 1;