diff --git a/Makefile b/Makefile index 974879bbb..83c70b9e4 100644 --- a/Makefile +++ b/Makefile @@ -56,8 +56,8 @@ docs: @cd docs && mdbook build # Build mdBook check: - @cargo fmt --check # Check Rust format issues - @cargo kclippy # Check common programming mistakes + @cargo fmt --check # Check Rust format issues + @cargo kclippy -- -D warnings # Make build fail if any warnings are found by rustc and clippy clean: @cargo clean diff --git a/framework/jinux-frame/src/arch/x86/cpu.rs b/framework/jinux-frame/src/arch/x86/cpu.rs index b825867d4..4f493c0dd 100644 --- a/framework/jinux-frame/src/arch/x86/cpu.rs +++ b/framework/jinux-frame/src/arch/x86/cpu.rs @@ -2,7 +2,6 @@ use core::arch::x86_64::{_fxrstor, _fxsave}; use core::fmt::Debug; -use core::mem::MaybeUninit; use trapframe::{GeneralRegs, UserContext as RawUserContext}; @@ -87,7 +86,7 @@ impl UserContextApiInternal for UserContext { } } }; - call_irq_callback_functions(&self.into_trap_frame()); + call_irq_callback_functions(&self.as_trap_frame()); } crate::arch::irq::enable_local(); @@ -103,7 +102,7 @@ impl UserContextApiInternal for UserContext { } } - fn into_trap_frame(&self) -> trapframe::TrapFrame { + fn as_trap_frame(&self) -> trapframe::TrapFrame { trapframe::TrapFrame { rax: self.user_context.general.rax, rbx: self.user_context.general.rbx, @@ -350,7 +349,7 @@ impl FpRegs { let ptr = unsafe { alloc::alloc::alloc(layout) } as usize; debug!("ptr = 0x{:x}", ptr); unsafe { - _fxsave((&mut self.buf.data).as_mut_ptr() as *mut u8); + _fxsave(self.buf.data.as_mut_ptr()); } debug!("save fpregs success"); self.is_valid = true; @@ -365,7 +364,7 @@ impl FpRegs { /// It is the caller's responsibility to ensure that the source slice contains /// data that is in xsave/xrstor format. The slice must have a length of 512 bytes. pub unsafe fn save_from_slice(&mut self, src: &[u8]) { - (&mut self.buf.data).copy_from_slice(src); + self.buf.data.copy_from_slice(src); self.is_valid = true; } @@ -388,7 +387,7 @@ impl FpRegs { pub fn restore(&self) { debug!("restore fpregs"); assert!(self.is_valid); - unsafe { _fxrstor((&self.buf.data).as_ptr()) }; + unsafe { _fxrstor(self.buf.data.as_ptr()) }; debug!("restore fpregs success"); } diff --git a/framework/jinux-frame/src/arch/x86/device/io_port.rs b/framework/jinux-frame/src/arch/x86/device/io_port.rs index 2af83f91f..42d329f4d 100644 --- a/framework/jinux-frame/src/arch/x86/device/io_port.rs +++ b/framework/jinux-frame/src/arch/x86/device/io_port.rs @@ -33,7 +33,7 @@ impl IoPort { /// a privileged operation. pub const unsafe fn new(port: u16) -> Self { Self { - port: port, + port, value_marker: PhantomData, access_marker: PhantomData, } diff --git a/framework/jinux-frame/src/arch/x86/device/serial.rs b/framework/jinux-frame/src/arch/x86/device/serial.rs index 59f6cb0b7..094802324 100644 --- a/framework/jinux-frame/src/arch/x86/device/serial.rs +++ b/framework/jinux-frame/src/arch/x86/device/serial.rs @@ -26,6 +26,7 @@ static SERIAL_MODEM_CTRL: IoPort = static SERIAL_LINE_STS: IoPort = unsafe { IoPort::new(SERIAL_DATA_PORT + 5) }; static CONSOLE_IRQ_CALLBACK: Once> = Once::new(); +#[allow(clippy::type_complexity)] static SERIAL_INPUT_CALLBACKS: SpinLock>> = SpinLock::new(Vec::new()); diff --git a/framework/jinux-frame/src/arch/x86/iommu/context_table.rs b/framework/jinux-frame/src/arch/x86/iommu/context_table.rs index ce215f025..c6be14e67 100644 --- a/framework/jinux-frame/src/arch/x86/iommu/context_table.rs +++ b/framework/jinux-frame/src/arch/x86/iommu/context_table.rs @@ -49,7 +49,7 @@ pub enum ContextTableError { impl RootTable { pub fn new() -> Self { Self { - root_frame: VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false)) + root_frame: VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false)) .unwrap() .pop() .unwrap(), @@ -128,7 +128,7 @@ impl RootTable { let bus_entry = context_table .entries_frame .read_val::( - (device_id.device as usize * 8 + device_id.function as usize) as usize + (device_id.device as usize * 8 + device_id.function as usize) * size_of::(), ) .unwrap(); @@ -141,7 +141,7 @@ impl RootTable { context_table .entries_frame .write_val::( - (device_id.device as usize * 8 + device_id.function as usize) as usize + (device_id.device as usize * 8 + device_id.function as usize) * size_of::(), &entry, ) @@ -237,7 +237,7 @@ pub struct ContextTable { impl ContextTable { fn new() -> Self { Self { - entries_frame: VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false)) + entries_frame: VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false)) .unwrap() .pop() .unwrap(), @@ -256,8 +256,7 @@ impl ContextTable { let bus_entry = self .entries_frame .read_val::( - (device.device as usize * 8 + device.function as usize) as usize - * size_of::(), + (device.device as usize * 8 + device.function as usize) * size_of::(), ) .unwrap(); @@ -270,7 +269,7 @@ impl ContextTable { let entry = ContextEntry(address as u128 | 3 | 0x1_0000_0000_0000_0000); self.entries_frame .write_val::( - (device.device as usize * 8 + device.function as usize) as usize + (device.device as usize * 8 + device.function as usize) * size_of::(), &entry, ) @@ -298,7 +297,7 @@ impl ContextTable { paddr, PageTableFlags::WRITABLE | PageTableFlags::READABLE | PageTableFlags::LAST_PAGE, ) - .map_err(|err| ContextTableError::ModificationError(err)) + .map_err(ContextTableError::ModificationError) } fn unmap(&mut self, device: PciDeviceLocation, vaddr: Vaddr) -> Result<(), ContextTableError> { @@ -308,6 +307,6 @@ impl ContextTable { self.get_or_create_page_table(device) .unmap(vaddr) - .map_err(|err| ContextTableError::ModificationError(err)) + .map_err(ContextTableError::ModificationError) } } diff --git a/framework/jinux-frame/src/arch/x86/iommu/fault.rs b/framework/jinux-frame/src/arch/x86/iommu/fault.rs index dda652280..8536ef1be 100644 --- a/framework/jinux-frame/src/arch/x86/iommu/fault.rs +++ b/framework/jinux-frame/src/arch/x86/iommu/fault.rs @@ -116,7 +116,7 @@ impl FaultRecording { pub fn pasid_value(&self) -> u32 { // bit 123:104 - ((self.0 & 0xF_FFFF0_0000_0000_0000_0000_0000_0000) >> 104) as u32 + ((self.0 & 0x00FF_FFF0_0000_0000_0000_0000_0000_0000) >> 104) as u32 } pub fn fault_reason(&self) -> u8 { @@ -165,6 +165,7 @@ pub enum FaultRequestType { #[derive(Debug)] #[repr(u8)] +#[allow(clippy::enum_variant_names)] pub enum FaultAddressType { UntranslatedRequest = 0, TranslationRequest = 1, @@ -201,6 +202,6 @@ pub(super) unsafe fn init(base_register_vaddr: Vaddr) { fn iommu_page_fault_handler(frame: &TrapFrame) { let fault_event = FAULT_EVENT_REGS.get().unwrap(); let index = (fault_event.status().bits & FaultStatus::FRI.bits) >> 8; - let recording = FaultRecording(*(&fault_event.recordings[index as usize].read())); + let recording = FaultRecording(fault_event.recordings[index as usize].read()); info!("Catch iommu page fault, recording:{:x?}", recording) } diff --git a/framework/jinux-frame/src/arch/x86/iommu/remapping.rs b/framework/jinux-frame/src/arch/x86/iommu/remapping.rs index ca2a2165c..d584d69fb 100644 --- a/framework/jinux-frame/src/arch/x86/iommu/remapping.rs +++ b/framework/jinux-frame/src/arch/x86/iommu/remapping.rs @@ -44,9 +44,8 @@ impl RemappingRegisters { let base_address = { let mut addr = 0; for remapping in dmar.remapping_iter() { - match remapping { - Remapping::Drhd(drhd) => addr = drhd.register_base_addr(), - _ => {} + if let Remapping::Drhd(drhd) = remapping { + addr = drhd.register_base_addr() } } if addr == 0 { @@ -110,7 +109,7 @@ bitflags! { /// 6 => 16-bit domain-ids with support for up to 64K domains. /// 7 => Reserved. /// ``` - const ND = 0x7 << 0; + const ND = 0x7; /// Required Write-Buffer Flushing. const RWBF = 1 << 4; /// Protected Low-Memory Region diff --git a/framework/jinux-frame/src/arch/x86/iommu/second_stage.rs b/framework/jinux-frame/src/arch/x86/iommu/second_stage.rs index 3d96c1507..f36a298d3 100644 --- a/framework/jinux-frame/src/arch/x86/iommu/second_stage.rs +++ b/framework/jinux-frame/src/arch/x86/iommu/second_stage.rs @@ -126,7 +126,7 @@ impl PageTableEntryTrait for PageTableEntry { // bit 47~12 type F = PageTableFlags; fn new(paddr: crate::vm::Paddr, flags: PageTableFlags) -> Self { - Self(((paddr & Self::PHYS_MASK) as u64 | flags.bits) as u64) + Self((paddr & Self::PHYS_MASK) as u64 | flags.bits) } fn paddr(&self) -> crate::vm::Paddr { @@ -150,7 +150,7 @@ impl PageTableEntryTrait for PageTableEntry { } fn page_index(va: crate::vm::Vaddr, level: usize) -> usize { - debug_assert!(level >= 1 && level <= 5); + debug_assert!((1..=5).contains(&level)); va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1) } } diff --git a/framework/jinux-frame/src/arch/x86/irq.rs b/framework/jinux-frame/src/arch/x86/irq.rs index 9107d478a..4fcc83d50 100644 --- a/framework/jinux-frame/src/arch/x86/irq.rs +++ b/framework/jinux-frame/src/arch/x86/irq.rs @@ -72,6 +72,7 @@ impl IrqLine { /// /// This function is marked unsafe as manipulating interrupt lines is /// considered a dangerous operation. + #[allow(clippy::redundant_allocation)] pub unsafe fn acquire(irq_num: u8) -> Arc<&'static Self> { Arc::new(IRQ_LIST.get().unwrap().get(irq_num as usize).unwrap()) } @@ -126,7 +127,7 @@ impl Drop for IrqCallbackHandle { .unwrap() .callback_list .lock(); - a.retain(|item| if (*item).id == self.id { false } else { true }); + a.retain(|item| item.id != self.id); ID_ALLOCATOR.lock().dealloc(self.id); } } diff --git a/framework/jinux-frame/src/arch/x86/kernel/acpi/dmar.rs b/framework/jinux-frame/src/arch/x86/kernel/acpi/dmar.rs index 058edf6cf..cb15c812c 100644 --- a/framework/jinux-frame/src/arch/x86/kernel/acpi/dmar.rs +++ b/framework/jinux-frame/src/arch/x86/kernel/acpi/dmar.rs @@ -34,6 +34,7 @@ pub enum Remapping { #[derive(Debug, Clone, Copy)] #[repr(u16)] +#[allow(clippy::upper_case_acronyms)] pub enum RemappingType { DRHD = 0, RMRR = 1, @@ -65,14 +66,9 @@ impl Dmar { let acpi_table_lock = super::ACPI_TABLES.get().unwrap().lock(); // Safety: The DmarHeader is the header for the DMAR structure, it fits all the field described in Intel manual. let dmar_mapping = unsafe { - if let Some(temp) = acpi_table_lock + acpi_table_lock .get_sdt::(Signature::DMAR) - .unwrap() - { - temp - } else { - return None; - } + .unwrap()? }; let physical_address = dmar_mapping.physical_start(); @@ -93,9 +89,9 @@ impl Dmar { unsafe { while remain_length > 0 { // Common header: type: u16, length: u16 - let length = *dmar_slice[index as usize + 2..index as usize + 4].as_ptr() as usize; - let typ = *dmar_slice[index as usize..index as usize + 2].as_ptr() as usize; - let bytes = &&dmar_slice[index as usize..index as usize + length]; + let length = *dmar_slice[index + 2..index + 4].as_ptr() as usize; + let typ = *dmar_slice[index..index + 2].as_ptr() as usize; + let bytes = &&dmar_slice[index..index + length]; let remapping = match typ { 0 => Remapping::Drhd(Drhd::from_bytes(bytes)), 1 => Remapping::Rmrr(Rmrr::from_bytes(bytes)), @@ -119,7 +115,7 @@ impl Dmar { Some(Dmar { header: *dmar_mapping, - remapping_structures: remapping_structures, + remapping_structures, }) } diff --git a/framework/jinux-frame/src/arch/x86/kernel/acpi/mod.rs b/framework/jinux-frame/src/arch/x86/kernel/acpi/mod.rs index 7d04d5e85..d269731f5 100644 --- a/framework/jinux-frame/src/arch/x86/kernel/acpi/mod.rs +++ b/framework/jinux-frame/src/arch/x86/kernel/acpi/mod.rs @@ -94,13 +94,13 @@ impl AcpiHandler for AcpiMemoryHandler { pub fn init() { let acpi_tables = match boot::acpi_arg().to_owned() { BootloaderAcpiArg::Rsdp(addr) => unsafe { - AcpiTables::from_rsdp(AcpiMemoryHandler {}, addr as usize).unwrap() + AcpiTables::from_rsdp(AcpiMemoryHandler {}, addr).unwrap() }, BootloaderAcpiArg::Rsdt(addr) => unsafe { - AcpiTables::from_rsdt(AcpiMemoryHandler {}, 0, addr as usize).unwrap() + AcpiTables::from_rsdt(AcpiMemoryHandler {}, 0, addr).unwrap() }, BootloaderAcpiArg::Xsdt(addr) => unsafe { - AcpiTables::from_rsdt(AcpiMemoryHandler {}, 1, addr as usize).unwrap() + AcpiTables::from_rsdt(AcpiMemoryHandler {}, 1, addr).unwrap() }, }; diff --git a/framework/jinux-frame/src/arch/x86/kernel/acpi/remapping.rs b/framework/jinux-frame/src/arch/x86/kernel/acpi/remapping.rs index 6d25aa8c8..8c41e0889 100644 --- a/framework/jinux-frame/src/arch/x86/kernel/acpi/remapping.rs +++ b/framework/jinux-frame/src/arch/x86/kernel/acpi/remapping.rs @@ -250,8 +250,7 @@ impl Rhsa { pub unsafe fn from_bytes(bytes: &[u8]) -> Self { let length = u16_from_slice(&bytes[2..4]) as u32; debug_assert_eq!(length, bytes.len() as u32); - let result = *(bytes.as_ptr() as *const Self); - result + *(bytes.as_ptr() as *const Self) } } diff --git a/framework/jinux-frame/src/arch/x86/kernel/apic/ioapic.rs b/framework/jinux-frame/src/arch/x86/kernel/apic/ioapic.rs index 454815469..77e526ec3 100644 --- a/framework/jinux-frame/src/arch/x86/kernel/apic/ioapic.rs +++ b/framework/jinux-frame/src/arch/x86/kernel/apic/ioapic.rs @@ -52,8 +52,7 @@ pub fn init() { acpi::InterruptModel::Unknown => panic!("not found APIC in ACPI Table"), acpi::InterruptModel::Apic(apic) => { apic.io_apics - .iter() - .next() + .first() .expect("There must be at least one IO APIC") .address } diff --git a/framework/jinux-frame/src/arch/x86/kernel/apic/x2apic.rs b/framework/jinux-frame/src/arch/x86/kernel/apic/x2apic.rs index bfd35ad45..bf30afed8 100644 --- a/framework/jinux-frame/src/arch/x86/kernel/apic/x2apic.rs +++ b/framework/jinux-frame/src/arch/x86/kernel/apic/x2apic.rs @@ -27,7 +27,7 @@ impl X2Apic { unsafe { // Enable x2APIC mode globally let mut base = rdmsr(IA32_APIC_BASE); - base = base | 0b1100_0000_0000; // Enable x2APIC and xAPIC + base |= 0b1100_0000_0000; // Enable x2APIC and xAPIC wrmsr(IA32_APIC_BASE, base); // Set SVR, Enable APIC and set Spurious Vector to 15 (Reserved irq number) diff --git a/framework/jinux-frame/src/arch/x86/mm/mod.rs b/framework/jinux-frame/src/arch/x86/mm/mod.rs index eb5b96243..2e4f98899 100644 --- a/framework/jinux-frame/src/arch/x86/mm/mod.rs +++ b/framework/jinux-frame/src/arch/x86/mm/mod.rs @@ -49,6 +49,10 @@ pub fn tlb_flush(vaddr: Vaddr) { #[repr(C)] pub struct PageTableEntry(usize); +/// ## Safety +/// +/// Changing the level 4 page table is unsafe, because it's possible to violate memory safety by +/// changing the page mapping. pub unsafe fn activate_page_table(root_paddr: Paddr, flags: x86_64::registers::control::Cr3Flags) { x86_64::registers::control::Cr3::write( PhysFrame::from_start_address(x86_64::PhysAddr::new(root_paddr as u64)).unwrap(), @@ -67,9 +71,9 @@ pub fn init() { // Cancel mapping in lowest addresses. p4[0].clear(); let mut map_pte = ALL_MAPPED_PTE.lock(); - for i in 0..512 { - if p4[i].flags().contains(PageTableFlags::PRESENT) { - map_pte.insert(i, p4[i]); + for (i, p4_i) in p4.iter().enumerate().take(512) { + if p4_i.flags().contains(PageTableFlags::PRESENT) { + map_pte.insert(i, *p4_i); } } } @@ -166,7 +170,7 @@ impl PageTableEntryTrait for PageTableEntry { Self((paddr & Self::PHYS_ADDR_MASK) | flags.bits) } fn paddr(&self) -> Paddr { - self.0 as usize & Self::PHYS_ADDR_MASK + self.0 & Self::PHYS_ADDR_MASK } fn flags(&self) -> PageTableFlags { PageTableFlags::from_bits_truncate(self.0) @@ -184,7 +188,7 @@ impl PageTableEntryTrait for PageTableEntry { } fn page_index(va: crate::vm::Vaddr, level: usize) -> usize { - debug_assert!(level >= 1 && level <= 5); + debug_assert!((1..=5).contains(&level)); va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1) } } diff --git a/framework/jinux-frame/src/arch/x86/timer/apic.rs b/framework/jinux-frame/src/arch/x86/timer/apic.rs index b45026689..61397dbe5 100644 --- a/framework/jinux-frame/src/arch/x86/timer/apic.rs +++ b/framework/jinux-frame/src/arch/x86/timer/apic.rs @@ -1,7 +1,6 @@ use core::arch::x86_64::_rdtsc; use core::sync::atomic::{AtomicBool, Ordering}; -use alloc::boxed::Box; use alloc::sync::Arc; use log::info; use spin::Once; @@ -83,7 +82,6 @@ fn periodic_mode_init() { } x86_64::instructions::interrupts::disable(); drop(a); - drop(handle); fn init_function(trap_frame: &TrapFrame) { static mut IN_TIME: u8 = 0; diff --git a/framework/jinux-frame/src/boot/kcmdline.rs b/framework/jinux-frame/src/boot/kcmdline.rs index f0f32b96f..09982c01d 100644 --- a/framework/jinux-frame/src/boot/kcmdline.rs +++ b/framework/jinux-frame/src/boot/kcmdline.rs @@ -32,7 +32,7 @@ pub struct KCmdlineArg { impl KCmdlineArg { /// Get the path of the initprocess. pub fn get_initproc_path(&self) -> Option<&str> { - self.initproc.path.as_ref().map(|s| s.as_str()) + self.initproc.path.as_deref() } /// Get the argument vector(argv) of the initprocess. pub fn get_initproc_argv(&self) -> &Vec { @@ -85,7 +85,7 @@ impl From<&str> for KCmdlineArg { // KernelArg => Arg "\s+" KernelArg | %empty // InitArg => Arg "\s+" InitArg | %empty if kcmdline_end { - if result.initproc.path == None { + if result.initproc.path.is_none() { panic!("Initproc arguments provided but no initproc path specified!"); } result.initproc.argv.push(CString::new(arg).unwrap()); @@ -96,7 +96,7 @@ impl From<&str> for KCmdlineArg { continue; } // Arg => Entry | Entry "=" Value - let arg_pattern: Vec<_> = arg.split("=").collect(); + let arg_pattern: Vec<_> = arg.split('=').collect(); let (entry, value) = match arg_pattern.len() { 1 => (arg_pattern[0], None), 2 => (arg_pattern[0], Some(arg_pattern[1])), @@ -105,7 +105,7 @@ impl From<&str> for KCmdlineArg { } }; // Entry => Module "." ModuleOptionName | KernelOptionName - let entry_pattern: Vec<_> = entry.split(".").collect(); + let entry_pattern: Vec<_> = entry.split('.').collect(); let (node, option) = match entry_pattern.len() { 1 => (None, entry_pattern[0]), 2 => (Some(entry_pattern[0]), entry_pattern[1]), @@ -145,14 +145,11 @@ impl From<&str> for KCmdlineArg { } } else { // There is no value, the entry is only a option. - match option { - _ => { - // If the option is not recognized, it is passed to the initproc. - // Pattern 'option' without value is treated as the init argument. - let argv_entry = CString::new(option.to_string()).unwrap(); - result.initproc.argv.push(argv_entry); - } - } + + // If the option is not recognized, it is passed to the initproc. + // Pattern 'option' without value is treated as the init argument. + let argv_entry = CString::new(option.to_string()).unwrap(); + result.initproc.argv.push(argv_entry); } } diff --git a/framework/jinux-frame/src/boot/memory_region.rs b/framework/jinux-frame/src/boot/memory_region.rs index 20096623c..b68a5e49d 100644 --- a/framework/jinux-frame/src/boot/memory_region.rs +++ b/framework/jinux-frame/src/boot/memory_region.rs @@ -36,11 +36,7 @@ pub struct MemoryRegion { impl MemoryRegion { /// Construct a page aligned memory region. pub fn new(base: usize, len: usize, typ: MemoryRegionType) -> Self { - MemoryRegion { - base: base, - len: len, - typ: typ, - } + MemoryRegion { base, len, typ } } /// The physical address of the base of the region. @@ -53,6 +49,10 @@ impl MemoryRegion { self.len } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + /// The type of the region. pub fn typ(&self) -> MemoryRegionType { self.typ @@ -86,20 +86,18 @@ impl MemoryRegion { } else { vec![*self] } - } else { - if self.base < t.base + t.len { - if self.base + self.len > t.base + t.len { - vec![MemoryRegion { - base: t.base + t.len, - len: self.base + self.len - (t.base + t.len), - typ: self.typ, - }] - } else { - vec![] - } + } else if self.base < t.base + t.len { + if self.base + self.len > t.base + t.len { + vec![MemoryRegion { + base: t.base + t.len, + len: self.base + self.len - (t.base + t.len), + typ: self.typ, + }] } else { - vec![*self] + vec![] } + } else { + vec![*self] } } } diff --git a/framework/jinux-frame/src/bus/pci/bus.rs b/framework/jinux-frame/src/bus/pci/bus.rs index 968e76755..ccb30fbc7 100644 --- a/framework/jinux-frame/src/bus/pci/bus.rs +++ b/framework/jinux-frame/src/bus/pci/bus.rs @@ -25,6 +25,7 @@ pub trait PciDriver: Sync + Send + Debug { /// /// Once a device is matched and claimed by a driver, /// it won't be fed to another driver for probing. + #[allow(clippy::result_large_err)] fn probe( &self, device: PciCommonDevice, @@ -69,7 +70,7 @@ impl PciBus { pub(super) fn register_common_device(&mut self, mut common_device: PciCommonDevice) { debug!("Find pci common devices:{:x?}", common_device); - let device_id = common_device.device_id().clone(); + let device_id = *common_device.device_id(); for driver in self.drivers.iter() { common_device = match driver.probe(common_device) { Ok(device) => { diff --git a/framework/jinux-frame/src/bus/pci/capability/msix.rs b/framework/jinux-frame/src/bus/pci/capability/msix.rs index 608d4f878..e162da67e 100644 --- a/framework/jinux-frame/src/bus/pci/capability/msix.rs +++ b/framework/jinux-frame/src/bus/pci/capability/msix.rs @@ -31,9 +31,9 @@ impl Clone for CapabilityMsixData { fn clone(&self) -> Self { let new_vec = self.irqs.clone().to_vec(); Self { - loc: self.loc.clone(), - ptr: self.ptr.clone(), - table_size: self.table_size.clone(), + loc: self.loc, + ptr: self.ptr, + table_size: self.table_size, table_bar: self.table_bar.clone(), pending_table_bar: self.pending_table_bar.clone(), irqs: new_vec, @@ -99,7 +99,7 @@ impl CapabilityMsixData { .unwrap(); table_bar .io_mem() - .write_val((16 * i + 12) as usize + table_offset, &(1 as u32)) + .write_val((16 * i + 12) as usize + table_offset, &1_u32) .unwrap(); } @@ -115,13 +115,13 @@ impl CapabilityMsixData { } Self { - loc: dev.location().clone(), + loc: *dev.location(), ptr: cap_ptr, table_size: (dev.location().read16(cap_ptr + 2) & 0b11_1111_1111) + 1, table_bar, pending_table_bar: pba_bar, irqs, - table_offset: table_offset, + table_offset, pending_table_offset: pba_offset, } } @@ -146,7 +146,7 @@ impl CapabilityMsixData { // Enable this msix vector self.table_bar .io_mem() - .write_val((16 * index + 12) as usize + self.table_offset, &(0 as u32)) + .write_val((16 * index + 12) as usize + self.table_offset, &0_u32) .unwrap(); } diff --git a/framework/jinux-frame/src/bus/pci/capability/vendor.rs b/framework/jinux-frame/src/bus/pci/capability/vendor.rs index a43ea829d..b1c5f36ec 100644 --- a/framework/jinux-frame/src/bus/pci/capability/vendor.rs +++ b/framework/jinux-frame/src/bus/pci/capability/vendor.rs @@ -13,7 +13,7 @@ pub struct CapabilityVndrData { impl CapabilityVndrData { pub(super) fn new(dev: &PciCommonDevice, cap_ptr: u16, length: u16) -> Self { Self { - location: dev.location().clone(), + location: *dev.location(), cap_ptr, length, } @@ -23,6 +23,10 @@ impl CapabilityVndrData { self.length } + pub fn is_empty(&self) -> bool { + self.length == 0 + } + pub fn read8(&self, offset: u16) -> Result { self.check_range(offset)?; Ok(self.location.read8(self.cap_ptr + offset)) @@ -30,7 +34,8 @@ impl CapabilityVndrData { pub fn write8(&self, offset: u16, value: u8) -> Result<()> { self.check_range(offset)?; - Ok(self.location.write8(self.cap_ptr + offset, value)) + self.location.write8(self.cap_ptr + offset, value); + Ok(()) } pub fn read16(&self, offset: u16) -> Result { @@ -40,7 +45,8 @@ impl CapabilityVndrData { pub fn write16(&self, offset: u16, value: u16) -> Result<()> { self.check_range(offset)?; - Ok(self.location.write16(self.cap_ptr + offset, value)) + self.location.write16(self.cap_ptr + offset, value); + Ok(()) } pub fn read32(&self, offset: u16) -> Result { @@ -50,7 +56,8 @@ impl CapabilityVndrData { pub fn write32(&self, offset: u16, value: u32) -> Result<()> { self.check_range(offset)?; - Ok(self.location.write32(self.cap_ptr + offset, value)) + self.location.write32(self.cap_ptr + offset, value); + Ok(()) } #[inline] diff --git a/framework/jinux-frame/src/bus/pci/cfg_space.rs b/framework/jinux-frame/src/bus/pci/cfg_space.rs index 20b7912b1..775023862 100644 --- a/framework/jinux-frame/src/bus/pci/cfg_space.rs +++ b/framework/jinux-frame/src/bus/pci/cfg_space.rs @@ -153,7 +153,7 @@ impl MemoryBar { }; // length let size = !(len_encoded & !0xF).wrapping_add(1); - let prefetchable = if raw & 0b1000 == 0 { false } else { true }; + let prefetchable = raw & 0b1000 != 0; // The BAR is located in I/O memory region Ok(MemoryBar { base, diff --git a/framework/jinux-frame/src/bus/pci/common_device.rs b/framework/jinux-frame/src/bus/pci/common_device.rs index 5cd0d23f7..110fdad69 100644 --- a/framework/jinux-frame/src/bus/pci/common_device.rs +++ b/framework/jinux-frame/src/bus/pci/common_device.rs @@ -110,22 +110,18 @@ impl BarManager { let mut idx = 0; let mut bars = [None, None, None, None, None, None]; while idx < max { - match Bar::new(location, idx) { - Ok(bar) => { - let mut idx_step = 0; - match &bar { - Bar::Memory(memory_bar) => { - if memory_bar.address_length() == AddrLen::Bits64 { - idx_step = 1; - } + if let Ok(bar) = Bar::new(location, idx) { + let mut idx_step = 0; + match &bar { + Bar::Memory(memory_bar) => { + if memory_bar.address_length() == AddrLen::Bits64 { + idx_step = 1; } - Bar::Io(_) => {} } - bars[idx as usize] = Some((bar, true)); - idx += idx_step; + Bar::Io(_) => {} } - // ignore for now - Err(_) => {} + bars[idx as usize] = Some((bar, true)); + idx += idx_step; } idx += 1; } diff --git a/framework/jinux-frame/src/cpu.rs b/framework/jinux-frame/src/cpu.rs index 4af4bdb99..4b94bf6b3 100644 --- a/framework/jinux-frame/src/cpu.rs +++ b/framework/jinux-frame/src/cpu.rs @@ -38,7 +38,7 @@ macro_rules! cpu_local { // multiple declarations ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => { $(#[$attr])* $vis static $name: CpuLocal<$t> = unsafe { CpuLocal::new($init) }; - crate::cpu_local!($($rest)*); + $crate::cpu_local!($($rest)*); }; // single declaration @@ -66,6 +66,7 @@ unsafe impl Sync for CpuLocal {} impl CpuLocal { /// Initialize CPU-local object /// Developer cannot construct a valid CpuLocal object arbitrarily + #[allow(clippy::missing_safety_doc)] pub const unsafe fn new(val: T) -> Self { Self(UnsafeCell::new(val)) } diff --git a/framework/jinux-frame/src/lib.rs b/framework/jinux-frame/src/lib.rs index c5cf5fb46..21d715155 100644 --- a/framework/jinux-frame/src/lib.rs +++ b/framework/jinux-frame/src/lib.rs @@ -70,11 +70,10 @@ fn invoke_c_init_funcs() { fn __sinit_array(); fn __einit_array(); } - let call_len = (__einit_array as u64 - __sinit_array as u64) / 8; + let call_len = (__einit_array as usize - __sinit_array as usize) / 8; for i in 0..call_len { unsafe { - let address = (__sinit_array as u64 + 8 * i) as *const u64; - let function = address as *const fn(); + let function = (__sinit_array as usize + 8 * i) as *const fn(); (*function)(); } } @@ -96,7 +95,7 @@ pub(crate) const fn zero() -> T { } pub trait Testable { - fn run(&self) -> (); + fn run(&self); } impl Testable for T diff --git a/framework/jinux-frame/src/sync/atomic_bits.rs b/framework/jinux-frame/src/sync/atomic_bits.rs index aa32434a8..5b5cb682e 100644 --- a/framework/jinux-frame/src/sync/atomic_bits.rs +++ b/framework/jinux-frame/src/sync/atomic_bits.rs @@ -83,17 +83,17 @@ impl AtomicBits { } /// Get an iterator for the bits. - pub fn iter<'a>(&'a self) -> Iter<'a> { + pub fn iter(&self) -> Iter<'_> { Iter::new(self) } /// Get an iterator that gives the positions of all 1s in the bits. - pub fn iter_ones<'a>(&'a self) -> OnesIter<'a> { + pub fn iter_ones(&self) -> OnesIter<'_> { OnesIter::new(self) } /// Get an iterator that gives the positions of all 0s in the bits. - pub fn iter_zeroes<'a>(&'a self) -> ZeroesIter<'a> { + pub fn iter_zeroes(&self) -> ZeroesIter<'_> { ZeroesIter::new(self) } } diff --git a/framework/jinux-frame/src/sync/mutex.rs b/framework/jinux-frame/src/sync/mutex.rs index f76c35663..799a5ccc2 100644 --- a/framework/jinux-frame/src/sync/mutex.rs +++ b/framework/jinux-frame/src/sync/mutex.rs @@ -31,7 +31,7 @@ impl Mutex { /// Try Acquire the mutex immedidately. pub fn try_lock(&self) -> Option> { - self.acquire_lock().then(|| MutexGuard { mutex: &self }) + self.acquire_lock().then_some(MutexGuard { mutex: self }) } /// Release the mutex and wake up one thread which is blocked on this mutex. diff --git a/framework/jinux-frame/src/sync/rwlock.rs b/framework/jinux-frame/src/sync/rwlock.rs index 2f728a057..1ae3f17a6 100644 --- a/framework/jinux-frame/src/sync/rwlock.rs +++ b/framework/jinux-frame/src/sync/rwlock.rs @@ -70,7 +70,7 @@ impl RwLock { let lock = self.lock.fetch_add(READER, Acquire); if lock & (WRITER | MAX_READER) == 0 { Some(RwLockReadGuard { - inner: &self, + inner: self, inner_guard: InnerGuard::IrqGuard(irq_guard), }) } else { @@ -88,7 +88,7 @@ impl RwLock { .is_ok() { Some(RwLockWriteGuard { - inner: &self, + inner: self, inner_guard: InnerGuard::IrqGuard(irq_guard), }) } else { @@ -130,7 +130,7 @@ impl RwLock { let lock = self.lock.fetch_add(READER, Acquire); if lock & (WRITER | MAX_READER) == 0 { Some(RwLockReadGuard { - inner: &self, + inner: self, inner_guard: InnerGuard::PreemptGuard(guard), }) } else { @@ -148,7 +148,7 @@ impl RwLock { .is_ok() { Some(RwLockWriteGuard { - inner: &self, + inner: self, inner_guard: InnerGuard::PreemptGuard(guard), }) } else { diff --git a/framework/jinux-frame/src/sync/rwmutex.rs b/framework/jinux-frame/src/sync/rwmutex.rs index 36c1cad71..789a5fa05 100644 --- a/framework/jinux-frame/src/sync/rwmutex.rs +++ b/framework/jinux-frame/src/sync/rwmutex.rs @@ -25,7 +25,7 @@ const MAX_READER: usize = WRITER >> 1; impl RwMutex { /// Creates a new `RwMutex`. - pub fn new(val: T) -> Self { + pub const fn new(val: T) -> Self { Self { val: UnsafeCell::new(val), lock: AtomicUsize::new(0), @@ -47,7 +47,7 @@ impl RwMutex { pub fn try_read(&self) -> Option> { let lock = self.lock.fetch_add(READER, Acquire); if lock & (WRITER | MAX_READER) == 0 { - Some(RwMutexReadGuard { inner: &self }) + Some(RwMutexReadGuard { inner: self }) } else { self.lock.fetch_sub(READER, Release); None @@ -61,7 +61,7 @@ impl RwMutex { .compare_exchange(0, WRITER, Acquire, Relaxed) .is_ok() { - Some(RwMutexWriteGuard { inner: &self }) + Some(RwMutexWriteGuard { inner: self }) } else { None } diff --git a/framework/jinux-frame/src/sync/spin.rs b/framework/jinux-frame/src/sync/spin.rs index 0349110a0..5981c83dc 100644 --- a/framework/jinux-frame/src/sync/spin.rs +++ b/framework/jinux-frame/src/sync/spin.rs @@ -31,7 +31,7 @@ impl SpinLock { let guard = disable_local(); self.acquire_lock(); SpinLockGuard { - lock: &self, + lock: self, inner_guard: InnerGuard::IrqGuard(guard), } } @@ -41,12 +41,12 @@ impl SpinLock { let irq_guard = disable_local(); if self.try_acquire_lock() { let lock_guard = SpinLockGuard { - lock: &self, + lock: self, inner_guard: InnerGuard::IrqGuard(irq_guard), }; return Some(lock_guard); } - return None; + None } /// Acquire the spin lock without disabling local IRQs. @@ -61,7 +61,7 @@ impl SpinLock { let guard = disable_preempt(); self.acquire_lock(); SpinLockGuard { - lock: &self, + lock: self, inner_guard: InnerGuard::PreemptGuard(guard), } } @@ -71,12 +71,12 @@ impl SpinLock { let guard = disable_preempt(); if self.try_acquire_lock() { let lock_guard = SpinLockGuard { - lock: &self, + lock: self, inner_guard: InnerGuard::PreemptGuard(guard), }; return Some(lock_guard); } - return None; + None } /// Access the spin lock, otherwise busy waiting diff --git a/framework/jinux-frame/src/sync/wait.rs b/framework/jinux-frame/src/sync/wait.rs index 38a097d8e..1a3477629 100644 --- a/framework/jinux-frame/src/sync/wait.rs +++ b/framework/jinux-frame/src/sync/wait.rs @@ -17,7 +17,6 @@ pub struct WaitQueue { } impl WaitQueue { - /// Creates a new instance. pub const fn new() -> Self { WaitQueue { waiters: SpinLock::new(VecDeque::new()), diff --git a/framework/jinux-frame/src/task/processor.rs b/framework/jinux-frame/src/task/processor.rs index d824cd11d..dfdef5ac1 100644 --- a/framework/jinux-frame/src/task/processor.rs +++ b/framework/jinux-frame/src/task/processor.rs @@ -13,7 +13,6 @@ use super::{ }; use alloc::sync::Arc; use lazy_static::lazy_static; -use log::warn; pub struct Processor { current: Option>, @@ -83,17 +82,18 @@ pub fn switch_to_task(next_task: Arc) { let current_task_option = current_task(); let next_task_cx_ptr = &next_task.inner_ctx() as *const TaskContext; let current_task: Arc; - let current_task_cx_ptr = if current_task_option.is_none() { - PROCESSOR.lock().get_idle_task_cx_ptr() - } else { - current_task = current_task_option.unwrap(); - if current_task.status() == TaskStatus::Runnable { - GLOBAL_SCHEDULER - .lock_irq_disabled() - .enqueue(current_task.clone()); + let current_task_cx_ptr = match current_task_option { + None => PROCESSOR.lock().get_idle_task_cx_ptr(), + Some(current_task) => { + if current_task.status() == TaskStatus::Runnable { + GLOBAL_SCHEDULER + .lock_irq_disabled() + .enqueue(current_task.clone()); + } + &mut current_task.inner_exclusive_access().ctx as *mut TaskContext } - &mut current_task.inner_exclusive_access().ctx as *mut TaskContext }; + // change the current task to the next task PROCESSOR.lock().current = Some(next_task.clone()); diff --git a/framework/jinux-frame/src/task/task.rs b/framework/jinux-frame/src/task/task.rs index 1f79989f7..e6196c091 100644 --- a/framework/jinux-frame/src/task/task.rs +++ b/framework/jinux-frame/src/task/task.rs @@ -44,7 +44,7 @@ impl KernelStack { pub fn new() -> Result { Ok(Self { frame: VmFrameVec::allocate( - &VmAllocOptions::new(KERNEL_STACK_SIZE / PAGE_SIZE).is_contiguous(true), + VmAllocOptions::new(KERNEL_STACK_SIZE / PAGE_SIZE).is_contiguous(true), )?, }) } diff --git a/framework/jinux-frame/src/trap/handler.rs b/framework/jinux-frame/src/trap/handler.rs index 4c26f4026..4174dfa02 100644 --- a/framework/jinux-frame/src/trap/handler.rs +++ b/framework/jinux-frame/src/trap/handler.rs @@ -12,11 +12,7 @@ extern "sysv64" fn trap_handler(f: &mut TrapFrame) { } pub(crate) fn call_irq_callback_functions(trap_frame: &TrapFrame) { - let irq_line = IRQ_LIST - .get() - .unwrap() - .get(trap_frame.trap_num as usize) - .unwrap(); + let irq_line = IRQ_LIST.get().unwrap().get(trap_frame.trap_num).unwrap(); let callback_functions = irq_line.callback_list(); for callback_function in callback_functions.iter() { callback_function.call(trap_frame); diff --git a/framework/jinux-frame/src/trap/irq.rs b/framework/jinux-frame/src/trap/irq.rs index 93e48a13f..7856d94b6 100644 --- a/framework/jinux-frame/src/trap/irq.rs +++ b/framework/jinux-frame/src/trap/irq.rs @@ -13,6 +13,7 @@ use trapframe::TrapFrame; #[must_use] pub struct IrqLine { irq_num: u8, + #[allow(clippy::redundant_allocation)] irq: Arc<&'static irq::IrqLine>, callbacks: Vec, } @@ -68,7 +69,7 @@ impl IrqLine { impl Clone for IrqLine { fn clone(&self) -> Self { Self { - irq_num: self.irq_num.clone(), + irq_num: self.irq_num, irq: self.irq.clone(), callbacks: Vec::new(), } diff --git a/framework/jinux-frame/src/user.rs b/framework/jinux-frame/src/user.rs index daa006a6f..97b950390 100644 --- a/framework/jinux-frame/src/user.rs +++ b/framework/jinux-frame/src/user.rs @@ -54,7 +54,7 @@ pub(crate) trait UserContextApiInternal { fn execute(&mut self) -> UserEvent; /// Use the information inside CpuContext to build a trapframe - fn into_trap_frame(&self) -> TrapFrame; + fn as_trap_frame(&self) -> TrapFrame; } /// The common interface that every CPU architecture-specific `CpuContext` implements. diff --git a/framework/jinux-frame/src/util/recycle_allocator.rs b/framework/jinux-frame/src/util/recycle_allocator.rs index 798b147a8..265372801 100644 --- a/framework/jinux-frame/src/util/recycle_allocator.rs +++ b/framework/jinux-frame/src/util/recycle_allocator.rs @@ -23,7 +23,7 @@ impl RecycleAllocator { current: start, recycled: Vec::new(), skip: Vec::new(), - max: max, + max, } } @@ -82,13 +82,11 @@ impl RecycleAllocator { self.skip.push(target); true } + } else if self.recycled.contains(&target) { + self.recycled.retain(|value| *value != target); + true } else { - if self.recycled.contains(&target) { - self.recycled.retain(|value| *value != target); - true - } else { - false - } + false } } } diff --git a/framework/jinux-frame/src/vm/frame.rs b/framework/jinux-frame/src/vm/frame.rs index 072b74ce4..395b6f75e 100644 --- a/framework/jinux-frame/src/vm/frame.rs +++ b/framework/jinux-frame/src/vm/frame.rs @@ -123,11 +123,6 @@ impl VmFrameVec { self.0.iter() } - /// Return IntoIterator for internal frames - pub fn into_iter(self) -> alloc::vec::IntoIter { - self.0.into_iter() - } - /// Returns the number of frames. pub fn len(&self) -> usize { self.0.len() @@ -150,6 +145,16 @@ impl VmFrameVec { } } +impl IntoIterator for VmFrameVec { + type Item = VmFrame; + + type IntoIter = alloc::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + impl VmIo for VmFrameVec { fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> { let mut start = offset; @@ -362,6 +367,7 @@ impl VmFrame { // FIXME: need a sound reason for creating a mutable reference // for getting the content of the frame. #[allow(clippy::mut_from_ref)] + #[allow(clippy::missing_safety_doc)] pub unsafe fn as_slice(&self) -> &mut [u8] { core::slice::from_raw_parts_mut( super::paddr_to_vaddr(self.start_paddr()) as *mut u8, diff --git a/framework/jinux-frame/src/vm/frame_allocator.rs b/framework/jinux-frame/src/vm/frame_allocator.rs index e631a09f0..9c19f7fe7 100644 --- a/framework/jinux-frame/src/vm/frame_allocator.rs +++ b/framework/jinux-frame/src/vm/frame_allocator.rs @@ -57,7 +57,7 @@ pub(crate) unsafe fn dealloc(index: usize) { FRAME_ALLOCATOR.get().unwrap().lock().dealloc(index, 1); } -pub(crate) fn init(regions: &Vec) { +pub(crate) fn init(regions: &[MemoryRegion]) { let mut allocator = FrameAllocator::<32>::new(); for region in regions.iter() { if region.typ() == MemoryRegionType::Usable { diff --git a/framework/jinux-frame/src/vm/heap_allocator.rs b/framework/jinux-frame/src/vm/heap_allocator.rs index 091a0c6e8..081c39718 100644 --- a/framework/jinux-frame/src/vm/heap_allocator.rs +++ b/framework/jinux-frame/src/vm/heap_allocator.rs @@ -67,14 +67,16 @@ unsafe impl GlobalAlloc for LockedHeapWithRescue { } // Avoid locking self.heap when calling rescue. - if (self.rescue)(&self, &layout).is_err() { - return 0 as *mut u8; + if (self.rescue)(self, &layout).is_err() { + return core::ptr::null_mut::(); } self.heap .lock() .alloc(layout) - .map_or(0 as *mut u8, |allocation| allocation.as_ptr()) + .map_or(core::ptr::null_mut::(), |allocation| { + allocation.as_ptr() + }) } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { diff --git a/framework/jinux-frame/src/vm/memory_set.rs b/framework/jinux-frame/src/vm/memory_set.rs index 57646a0d6..03f13ad97 100644 --- a/framework/jinux-frame/src/vm/memory_set.rs +++ b/framework/jinux-frame/src/vm/memory_set.rs @@ -28,12 +28,8 @@ pub struct MemorySet { areas: BTreeMap, } -impl MapArea { - pub fn mapped_size(&self) -> usize { - self.size - } - - pub fn clone(&self) -> Self { +impl Clone for MapArea { + fn clone(&self) -> Self { let mut mapper = BTreeMap::new(); for (&va, old) in &self.mapper { let new = frame_allocator::alloc(VmFrameFlags::empty()).unwrap(); @@ -49,6 +45,12 @@ impl MapArea { mapper, } } +} + +impl MapArea { + pub fn mapped_size(&self) -> usize { + self.size + } /// This function will map the vitural address to the given physical frames pub fn new( @@ -69,7 +71,7 @@ impl MapArea { size, mapper: BTreeMap::new(), }; - let mut current_va = start_va.clone(); + let mut current_va = start_va; let page_size = size / PAGE_SIZE; let mut phy_frame_iter = physical_frames.iter(); @@ -149,6 +151,12 @@ impl MapArea { } } +impl Default for MemorySet { + fn default() -> Self { + Self::new() + } +} + impl MemorySet { pub fn map(&mut self, area: MapArea) { if area.size > 0 { diff --git a/framework/jinux-frame/src/vm/mod.rs b/framework/jinux-frame/src/vm/mod.rs index dfee10fcd..0f02fb3e6 100644 --- a/framework/jinux-frame/src/vm/mod.rs +++ b/framework/jinux-frame/src/vm/mod.rs @@ -15,7 +15,7 @@ mod offset; pub(crate) mod page_table; mod space; -use crate::config::{PAGE_SIZE, PHYS_OFFSET}; +use crate::config::{KERNEL_OFFSET, PAGE_SIZE, PHYS_OFFSET}; pub use self::frame::{VmAllocOptions, VmFrame, VmFrameVec, VmFrameVecIter}; pub use self::io::VmIo; @@ -38,7 +38,7 @@ pub trait HasPaddr { } pub fn vaddr_to_paddr(va: Vaddr) -> Option { - if va >= crate::config::PHYS_OFFSET && va <= crate::config::KERNEL_OFFSET { + if (PHYS_OFFSET..=KERNEL_OFFSET).contains(&va) { // can use offset to get the physical address Some(va - PHYS_OFFSET) } else { @@ -67,7 +67,7 @@ pub(crate) fn init() { let mut framebuffer_regions = Vec::new(); for i in memory_regions.iter() { if i.typ() == MemoryRegionType::Framebuffer { - framebuffer_regions.push(i.clone()); + framebuffer_regions.push(*i); } } FRAMEBUFFER_REGIONS.call_once(|| framebuffer_regions); diff --git a/framework/jinux-frame/src/vm/page_table.rs b/framework/jinux-frame/src/vm/page_table.rs index b8d81ce74..4d625d476 100644 --- a/framework/jinux-frame/src/vm/page_table.rs +++ b/framework/jinux-frame/src/vm/page_table.rs @@ -89,6 +89,7 @@ pub struct PageTableConfig { #[derive(Debug, Clone, Copy)] #[repr(usize)] +#[allow(clippy::enum_variant_names)] pub enum AddressWidth { Level3PageTable = 3, Level4PageTable = 4, @@ -190,7 +191,7 @@ impl PageTable { return None; } // Create next table - let frame = VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false)) + let frame = VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false)) .unwrap() .pop() .unwrap(); diff --git a/framework/jinux-frame/src/vm/space.rs b/framework/jinux-frame/src/vm/space.rs index 75818244d..3c2ccb206 100644 --- a/framework/jinux-frame/src/vm/space.rs +++ b/framework/jinux-frame/src/vm/space.rs @@ -36,6 +36,7 @@ impl VmSpace { } } /// Activate the page table, load root physical address to cr3 + #[allow(clippy::missing_safety_doc)] pub unsafe fn activate(&self) { #[cfg(target_arch = "x86_64")] crate::arch::x86::mm::activate_page_table( @@ -188,7 +189,7 @@ impl VmMapOptions { /// /// The default value of this option is `None`. pub fn addr(&mut self, addr: Option) -> &mut Self { - if addr == None { + if addr.is_none() { return self; } self.addr = Some(addr.unwrap()); diff --git a/services/comps/network/src/driver.rs b/services/comps/network/src/driver.rs index 4fa1b1905..7b8f0cbd8 100644 --- a/services/comps/network/src/driver.rs +++ b/services/comps/network/src/driver.rs @@ -39,8 +39,7 @@ impl phy::RxToken for RxToken { F: FnOnce(&mut [u8]) -> R, { let packet_but = self.0.packet_mut(); - let res = f(packet_but); - res + f(packet_but) } } diff --git a/services/comps/network/src/lib.rs b/services/comps/network/src/lib.rs index 6210d9ed8..03e111003 100644 --- a/services/comps/network/src/lib.rs +++ b/services/comps/network/src/lib.rs @@ -91,7 +91,7 @@ pub fn handle_recv_irq(name: &String) { } } -pub fn all_devices() -> Vec<(String, Arc>>)> { +pub fn all_devices() -> Vec<(String, NetworkDeviceRef)> { let lock = COMPONENT.get().unwrap().devices.lock(); let mut vec = Vec::new(); for (name, (_, device)) in lock.iter() { @@ -112,17 +112,12 @@ fn init() -> Result<(), ComponentInitError> { Ok(()) } +type NetDeviceIrqHandlerListRef = Arc>>>; +type NetworkDeviceRef = Arc>>; + struct Component { /// Device list, the key is device name, value is (callbacks, device); - devices: SpinLock< - BTreeMap< - String, - ( - Arc>>>, - Arc>>, - ), - >, - >, + devices: SpinLock>, } impl Component { diff --git a/services/comps/time/src/rtc.rs b/services/comps/time/src/rtc.rs index 61e4657d3..dfa44744f 100644 --- a/services/comps/time/src/rtc.rs +++ b/services/comps/time/src/rtc.rs @@ -26,7 +26,7 @@ pub fn is_updating() -> bool { pub fn read() -> SystemTime { update_time(); - READ_TIME.lock().clone() + *READ_TIME.lock() } /// read year,month,day and other data @@ -34,22 +34,21 @@ pub fn read() -> SystemTime { fn update_time() { let mut last_time: SystemTime; - let register_b: u8; let mut lock = READ_TIME.lock(); lock.update_from_rtc(); - last_time = lock.clone(); + last_time = *lock; lock.update_from_rtc(); while *lock != last_time { - last_time = lock.clone(); + last_time = *lock; lock.update_from_rtc(); } - register_b = get_cmos(0x0B); + let register_b: u8 = get_cmos(0x0B); lock.convert_bcd_to_binary(register_b); lock.convert_12_hour_to_24_hour(register_b); diff --git a/services/comps/virtio/src/device/block/mod.rs b/services/comps/virtio/src/device/block/mod.rs index b61a210b2..3a892f93f 100644 --- a/services/comps/virtio/src/device/block/mod.rs +++ b/services/comps/virtio/src/device/block/mod.rs @@ -9,7 +9,7 @@ use pod::Pod; use crate::transport::VirtioTransport; pub const BLK_SIZE: usize = 512; -pub static DEVICE_NAME: &'static str = "Virtio-Block"; +pub static DEVICE_NAME: &str = "Virtio-Block"; bitflags! { /// features for virtio block device @@ -112,7 +112,7 @@ pub struct VirtioBlkTopology { } impl VirtioBlkConfig { - pub(self) fn new(transport: &mut dyn VirtioTransport) -> SafePtr { + pub(self) fn new(transport: &dyn VirtioTransport) -> SafePtr { let memory = transport.device_config_memory(); SafePtr::new(memory, 0) } diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs index aaae50304..73e1705ad 100644 --- a/services/comps/virtio/src/device/input/device.rs +++ b/services/comps/virtio/src/device/input/device.rs @@ -63,6 +63,7 @@ pub struct InputDevice { event_queue: SpinLock, status_queue: VirtQueue, event_buf: SpinLock>, + #[allow(clippy::type_complexity)] callbacks: SpinLock>>, transport: Box, } @@ -161,7 +162,7 @@ impl InputDevice { .write(&(select as u8)) .unwrap(); field_ptr!(&self.config, VirtioInputConfig, subsel) - .write(&(subsel as u8)) + .write(&subsel) .unwrap(); let size = field_ptr!(&self.config, VirtioInputConfig, size) .read() diff --git a/services/comps/virtio/src/device/input/mod.rs b/services/comps/virtio/src/device/input/mod.rs index b0936e215..c1310718d 100644 --- a/services/comps/virtio/src/device/input/mod.rs +++ b/services/comps/virtio/src/device/input/mod.rs @@ -30,7 +30,7 @@ use jinux_frame::io_mem::IoMem; use jinux_util::safe_ptr::SafePtr; use pod::Pod; -pub static DEVICE_NAME: &'static str = "Virtio-Input"; +pub static DEVICE_NAME: &str = "Virtio-Input"; /// Select value used for [`VirtIOInput::query_config_select()`]. #[repr(u8)] @@ -72,7 +72,7 @@ pub struct VirtioInputConfig { } impl VirtioInputConfig { - pub(self) fn new(transport: &mut dyn VirtioTransport) -> SafePtr { + pub(self) fn new(transport: &dyn VirtioTransport) -> SafePtr { let memory = transport.device_config_memory(); SafePtr::new(memory, 0) } diff --git a/services/comps/virtio/src/device/network/config.rs b/services/comps/virtio/src/device/network/config.rs index 71c2d73d7..1971655bb 100644 --- a/services/comps/virtio/src/device/network/config.rs +++ b/services/comps/virtio/src/device/network/config.rs @@ -71,7 +71,7 @@ pub struct VirtioNetConfig { } impl VirtioNetConfig { - pub(super) fn new(transport: &mut dyn VirtioTransport) -> SafePtr { + pub(super) fn new(transport: &dyn VirtioTransport) -> SafePtr { let memory = transport.device_config_memory(); SafePtr::new(memory, 0) } diff --git a/services/comps/virtio/src/device/network/device.rs b/services/comps/virtio/src/device/network/device.rs index dedb24973..14806a7e7 100644 --- a/services/comps/virtio/src/device/network/device.rs +++ b/services/comps/virtio/src/device/network/device.rs @@ -60,7 +60,7 @@ impl NetworkDevice { let mut rx_buffers = SlotVec::new(); for i in 0..QUEUE_SIZE { let mut rx_buffer = RxBuffer::new(RX_BUFFER_LEN, size_of::()); - let token = recv_queue.add(&[], &mut [rx_buffer.buf_mut()])?; + let token = recv_queue.add(&[], &[rx_buffer.buf_mut()])?; assert_eq!(i, token); assert_eq!(rx_buffers.put(rx_buffer) as u16, i); } @@ -109,7 +109,7 @@ impl NetworkDevice { fn add_rx_buffer(&mut self, mut rx_buffer: RxBuffer) -> Result<(), VirtioNetError> { let token = self .recv_queue - .add(&[], &mut [rx_buffer.buf_mut()]) + .add(&[], &[rx_buffer.buf_mut()]) .map_err(queue_to_network_error)?; assert!(self.rx_buffers.put_at(token as usize, rx_buffer).is_none()); if self.recv_queue.should_notify() { @@ -140,7 +140,7 @@ impl NetworkDevice { let header = VirtioNetHdr::default(); let token = self .send_queue - .add(&[header.as_bytes(), tx_buffer.buf()], &mut []) + .add(&[header.as_bytes(), tx_buffer.buf()], &[]) .map_err(queue_to_network_error)?; if self.send_queue.should_notify() { diff --git a/services/comps/virtio/src/device/network/mod.rs b/services/comps/virtio/src/device/network/mod.rs index 99b6ec5a3..b88f1c3d3 100644 --- a/services/comps/virtio/src/device/network/mod.rs +++ b/services/comps/virtio/src/device/network/mod.rs @@ -2,4 +2,4 @@ pub mod config; pub mod device; pub mod header; -pub static DEVICE_NAME: &'static str = "Virtio-Net"; +pub static DEVICE_NAME: &str = "Virtio-Net"; diff --git a/services/comps/virtio/src/queue.rs b/services/comps/virtio/src/queue.rs index e19e33b9e..38ba9298d 100644 --- a/services/comps/virtio/src/queue.rs +++ b/services/comps/virtio/src/queue.rs @@ -67,21 +67,21 @@ impl VirtQueue { } let descriptor_ptr: SafePtr = SafePtr::new( - VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false).can_dma(true)) + VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false).can_dma(true)) .unwrap() .pop() .unwrap(), 0, ); let avail_ring_ptr: SafePtr = SafePtr::new( - VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false).can_dma(true)) + VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false).can_dma(true)) .unwrap() .pop() .unwrap(), 0, ); let used_ring_ptr: SafePtr = SafePtr::new( - VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false).can_dma(true)) + VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false).can_dma(true)) .unwrap() .pop() .unwrap(), @@ -311,6 +311,7 @@ pub struct Descriptor { } #[inline] +#[allow(clippy::type_complexity)] fn set_buf(ptr: &SafePtr>, buf: &[u8]) { let va = buf.as_ptr() as usize; let pa = jinux_frame::vm::vaddr_to_paddr(va).unwrap(); @@ -323,7 +324,7 @@ fn set_buf(ptr: &SafePtr>, } bitflags! { /// Descriptor flags - #[derive(Pod)] + #[derive(Pod, Default)] #[repr(C)] struct DescFlags: u16 { const NEXT = 1; @@ -331,13 +332,6 @@ bitflags! { const INDIRECT = 4; } } -impl Default for DescFlags { - fn default() -> Self { - Self { - bits: Default::default(), - } - } -} /// The driver uses the available ring to offer buffers to the device: /// each ring entry refers to the head of a descriptor chain. diff --git a/services/comps/virtio/src/transport/pci/capability.rs b/services/comps/virtio/src/transport/pci/capability.rs index e5c91f362..9e6c35701 100644 --- a/services/comps/virtio/src/transport/pci/capability.rs +++ b/services/comps/virtio/src/transport/pci/capability.rs @@ -7,6 +7,7 @@ use jinux_frame::bus::pci::{ #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[repr(u8)] +#[allow(clippy::enum_variant_names)] pub enum VirtioPciCpabilityType { CommonCfg = 1, NotifyCfg = 2, @@ -72,16 +73,15 @@ impl VirtioPciCapabilityData { let mut io_bar = None; let mut memory_bar = None; - match bar_manager.bar(bar) { - Some(bar) => match bar { + if let Some(bar) = bar_manager.bar(bar) { + match bar { Bar::Memory(memory) => { memory_bar = Some(memory); } Bar::Io(io) => { io_bar = Some(io); } - }, - None => {} + } }; Self { cfg_type, diff --git a/services/comps/virtio/src/transport/pci/device.rs b/services/comps/virtio/src/transport/pci/device.rs index de15415fd..a1fae2121 100644 --- a/services/comps/virtio/src/transport/pci/device.rs +++ b/services/comps/virtio/src/transport/pci/device.rs @@ -49,7 +49,7 @@ pub struct VirtioPciTransport { impl PciDevice for VirtioPciDevice { fn device_id(&self) -> PciDeviceId { - self.device_id.clone() + self.device_id } } @@ -78,13 +78,13 @@ impl VirtioTransport for VirtioPciTransport { return Err(VirtioTransportError::InvalidArgs); } field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_select) - .write(&(idx as u16)) + .write(&idx) .unwrap(); debug_assert_eq!( field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_select) .read() .unwrap(), - idx as u16 + idx ); field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_size) @@ -189,13 +189,13 @@ impl VirtioTransport for VirtioPciTransport { fn max_queue_size(&self, idx: u16) -> Result { field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_select) - .write(&(idx as u16)) + .write(&idx) .unwrap(); debug_assert_eq!( field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_select) .read() .unwrap(), - idx as u16 + idx ); Ok(field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_size) @@ -250,6 +250,7 @@ impl VirtioPciTransport { &self.device } + #[allow(clippy::result_large_err)] pub(super) fn new( common_device: PciCommonDevice, ) -> Result { @@ -280,8 +281,7 @@ impl VirtioPciTransport { for cap in common_device.capabilities().iter() { match cap.capability_data() { CapabilityData::Vndr(vendor) => { - let data = - VirtioPciCapabilityData::new(common_device.bar_manager(), vendor.clone()); + let data = VirtioPciCapabilityData::new(common_device.bar_manager(), *vendor); match data.typ() { VirtioPciCpabilityType::CommonCfg => { common_cfg = Some(VirtioPciCommonCfg::new(&data)); @@ -317,7 +317,7 @@ impl VirtioPciTransport { let common_cfg = common_cfg.unwrap(); let device_cfg = device_cfg.unwrap(); let msix_manager = VirtioMsixManager::new(msix); - let device_id = common_device.device_id().clone(); + let device_id = *common_device.device_id(); Ok(Self { common_device, common_cfg, diff --git a/services/libs/comp-sys/component-macro/src/priority.rs b/services/libs/comp-sys/component-macro/src/priority.rs index 39ff5af62..04f7243fd 100644 --- a/services/libs/comp-sys/component-macro/src/priority.rs +++ b/services/libs/comp-sys/component-macro/src/priority.rs @@ -30,7 +30,7 @@ pub fn component_generate() -> Vec { let mut component_packages = vec![]; let workspace_root = metadata["workspace_root"].as_str().unwrap(); - let workspace_root = String::from_str(workspace_root).unwrap().replace("\\", "/"); + let workspace_root = String::from_str(workspace_root).unwrap().replace('\\', "/"); let comps_name = get_components_name(&workspace_root, &metadata["packages"]); for package in metadata["packages"].members_mut() { @@ -78,7 +78,7 @@ pub fn component_generate() -> Vec { // remove the last character let mut path1 = paths.pop().unwrap().to_string(); path1.pop(); - if path1.starts_with("/") { + if path1.starts_with('/') { path1.remove(0); } path1 @@ -101,7 +101,7 @@ pub fn get_component_toml_path() -> TokenStream { let workspace_root = metadata["workspace_root"].as_str().unwrap(); let mut workspace_root = String::from_str(workspace_root) .unwrap() - .replace("\\", "/") + .replace('\\', "/") .add("/") .add(COMPONENT_FILE_NAME) .add("\""); @@ -141,10 +141,10 @@ fn get_components_name(workspace_root: &String, packages: &JsonValue) -> Vec Vec { +fn read_component_file(workspace_root: &str) -> Vec { let component_toml: toml::Value = { - let mut component_file_path = workspace_root.clone(); - component_file_path.push_str("/"); + let mut component_file_path = workspace_root.to_owned(); + component_file_path.push('/'); component_file_path.push_str(COMPONENT_FILE_NAME); let mut file = File::open(component_file_path) .expect("Components.toml file not found, please check if the file exists"); @@ -179,7 +179,7 @@ fn calculate_priority( node_name: String, ) -> u16 { if prioritys.contains_key(&node_name) { - return prioritys.get(&node_name).unwrap().clone(); + return *prioritys.get(&node_name).unwrap(); } let package = &package_mapping[&node_name]; @@ -209,7 +209,5 @@ fn metadata() -> json::JsonValue { } let output = String::from_utf8(output.stdout).unwrap(); - let parsed = json::parse(&output).unwrap(); - - parsed + json::parse(&output).unwrap() } diff --git a/services/libs/comp-sys/component/src/lib.rs b/services/libs/comp-sys/component/src/lib.rs index 855b49ad5..c019bde45 100644 --- a/services/libs/comp-sys/component/src/lib.rs +++ b/services/libs/comp-sys/component/src/lib.rs @@ -4,7 +4,6 @@ #![no_std] #![forbid(unsafe_code)] #![feature(fn_traits)] -#![feature(once_cell)] extern crate alloc; @@ -132,7 +131,7 @@ fn match_and_call( for registry in inventory::iter:: { // relative/path/to/comps/pci/src/lib.rs let mut str: String = registry.path.to_owned(); - str = str.replace("\\", "/"); + str = str.replace('\\', "/"); // relative/path/to/comps/pci // There are two cases, one in the test folder and one in the src folder. // There may be multiple directories within the folder. @@ -148,7 +147,7 @@ fn match_and_call( } else { panic!("The path of {} cannot recognized by component system", str); } - str = str.trim_end_matches("/").to_owned(); + str = str.trim_end_matches('/').to_owned(); let mut info = components .remove(&str) @@ -159,7 +158,7 @@ fn match_and_call( debug!("Remain componets:{components:?}"); - if components.len() != 0 { + if !components.is_empty() { info!("Exists components that are not initialized"); } diff --git a/services/libs/cpio-decoder/src/lib.rs b/services/libs/cpio-decoder/src/lib.rs index aa2d7a9d3..fa2924f3f 100644 --- a/services/libs/cpio-decoder/src/lib.rs +++ b/services/libs/cpio-decoder/src/lib.rs @@ -68,7 +68,7 @@ where type Item<'a> = Result>; /// Stops if reaches to the trailer entry or encounters an error. - fn next<'a>(self: &'a mut Self) -> Option> { + fn next(&mut self) -> Option> { // Stop to iterate entries if encounters an error. if self.is_error { return None; @@ -159,7 +159,7 @@ where while send_len < data_len { let len = min(buffer.len(), data_len - send_len); self.reader.read_exact(&mut buffer[..len])?; - writer.write_all(&mut buffer[..len])?; + writer.write_all(&buffer[..len])?; send_len += len; } if self.data_padding_len > 0 { @@ -170,7 +170,7 @@ where } pub fn is_trailer(&self) -> bool { - &self.name == TRAILER_NAME + self.name == TRAILER_NAME } } diff --git a/services/libs/int-to-c-enum/derive/src/lib.rs b/services/libs/int-to-c-enum/derive/src/lib.rs index 2d9393840..a9793d2ff 100644 --- a/services/libs/int-to-c-enum/derive/src/lib.rs +++ b/services/libs/int-to-c-enum/derive/src/lib.rs @@ -36,7 +36,7 @@ fn impl_try_from( } else { panic!( "{} does not have invalid repr to implement TryFromInt.", - ident.to_string() + ident ); }; diff --git a/services/libs/jinux-rights-proc/src/require_attr.rs b/services/libs/jinux-rights-proc/src/require_attr.rs index ffcebea3a..6cf791a9f 100644 --- a/services/libs/jinux-rights-proc/src/require_attr.rs +++ b/services/libs/jinux-rights-proc/src/require_attr.rs @@ -83,13 +83,13 @@ fn is_generic_param(ident: Ident, generic_params: &Punctuated { let type_param_ident = type_param.ident.clone(); - if ident.to_string() == type_param_ident.to_string() { + if ident == type_param_ident { return true; } } GenericParam::Const(const_param) => { let const_param_ident = const_param.ident.clone(); - if ident.to_string() == const_param_ident.to_string() { + if const_param_ident == ident { return true; } } diff --git a/services/libs/jinux-std/src/device/pty/mod.rs b/services/libs/jinux-std/src/device/pty/mod.rs index 998b59476..aac3510ab 100644 --- a/services/libs/jinux-std/src/device/pty/mod.rs +++ b/services/libs/jinux-std/src/device/pty/mod.rs @@ -3,6 +3,7 @@ use crate::fs::fs_resolver::{FsPath, FsResolver}; use crate::fs::utils::{Dentry, Inode, InodeMode, InodeType}; use crate::prelude::*; +#[allow(clippy::module_inception)] mod pty; pub use pty::{PtyMaster, PtySlave}; diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs index e8d1cc1f8..e7ecd1164 100644 --- a/services/libs/jinux-std/src/device/pty/pty.rs +++ b/services/libs/jinux-std/src/device/pty/pty.rs @@ -88,7 +88,7 @@ impl PtyMaster { impl FileLike for PtyMaster { fn read(&self, buf: &mut [u8]) -> Result { // TODO: deal with nonblocking read - if buf.len() == 0 { + if buf.is_empty() { return Ok(0); } @@ -261,7 +261,7 @@ impl Device for PtySlave { } fn id(&self) -> crate::fs::device::DeviceId { - DeviceId::new(88, self.index() as u32) + DeviceId::new(88, self.index()) } fn read(&self, buf: &mut [u8]) -> Result { diff --git a/services/libs/jinux-std/src/device/tty/driver.rs b/services/libs/jinux-std/src/device/tty/driver.rs index 722b480ec..8e53854c7 100644 --- a/services/libs/jinux-std/src/device/tty/driver.rs +++ b/services/libs/jinux-std/src/device/tty/driver.rs @@ -22,7 +22,7 @@ pub struct TtyDriver { } impl TtyDriver { - pub fn new() -> Self { + pub const fn new() -> Self { Self { ttys: SpinLock::new(Vec::new()), } diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs index 2d52c318e..233798f30 100644 --- a/services/libs/jinux-std/src/device/tty/line_discipline.rs +++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs @@ -31,6 +31,7 @@ pub struct LineDiscipline { pollee: Pollee, } +#[derive(Default)] pub struct CurrentLine { buffer: StaticRb, } @@ -66,6 +67,12 @@ impl CurrentLine { } } +impl Default for LineDiscipline { + fn default() -> Self { + Self::new() + } +} + impl LineDiscipline { /// Create a new line discipline pub fn new() -> Self { @@ -120,7 +127,7 @@ impl LineDiscipline { } } - if item >= 0x20 && item < 0x7f { + if (0x20..0x7f).contains(&item) { // Printable character self.current_line.lock_irq_disabled().push_char(item); } @@ -174,7 +181,7 @@ impl LineDiscipline { let backspace: &str = core::str::from_utf8(&[b'\x08', b' ', b'\x08']).unwrap(); echo_callback(backspace); } - item if 0x20 <= item && item < 0x7f => print!("{}", char::from(item)), + item if (0x20..0x7f).contains(&item) => print!("{}", char::from(item)), item if 0 < item && item < 0x20 && termios.contains_echo_ctl() => { // The unprintable chars between 1-31 are mapped to ctrl characters between 65-95. // e.g., 0x3 is mapped to 0x43, which is C. So, we will print ^C when 0x3 is met. @@ -263,25 +270,25 @@ impl LineDiscipline { return 0; } let mut read_len = 0; - for i in 0..max_read_len { + for dst_i in dst.iter_mut().take(max_read_len) { if let Some(next_char) = buffer.pop() { let termios = self.termios.lock_irq_disabled(); if termios.is_canonical_mode() { // canonical mode, read until meet new line if meet_new_line(next_char, &termios) { if !should_not_be_read(next_char, &termios) { - dst[i] = next_char; + *dst_i = next_char; read_len += 1; } break; } else { - dst[i] = next_char; + *dst_i = next_char; read_len += 1; } } else { // raw mode // FIXME: avoid addtional bound check - dst[i] = next_char; + *dst_i = next_char; read_len += 1; } } else { @@ -333,7 +340,7 @@ impl LineDiscipline { self.foreground .lock_irq_disabled() .upgrade() - .and_then(|foreground| Some(foreground.pgid())) + .map(|foreground| foreground.pgid()) } /// whether there is buffered data @@ -359,7 +366,7 @@ impl LineDiscipline { } pub fn window_size(&self) -> WinSize { - self.winsize.lock().clone() + *self.winsize.lock() } pub fn set_window_size(&self, winsize: WinSize) { @@ -384,9 +391,5 @@ fn meet_new_line(item: u8, termios: &KernelTermios) -> bool { /// The special char should not be read by reading process fn should_not_be_read(item: u8, termios: &KernelTermios) -> bool { - if item == *termios.get_special_char(CC_C_CHAR::VEOF) { - true - } else { - false - } + item == *termios.get_special_char(CC_C_CHAR::VEOF) } diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs index 00615ec16..c60cbd26e 100644 --- a/services/libs/jinux-std/src/device/tty/termio.rs +++ b/services/libs/jinux-std/src/device/tty/termio.rs @@ -188,21 +188,21 @@ impl CC_C_CHAR { match self { CC_C_CHAR::VINTR => control_character('C'), CC_C_CHAR::VQUIT => control_character('\\'), - CC_C_CHAR::VERASE => '\x7f' as u8, + CC_C_CHAR::VERASE => b'\x7f', CC_C_CHAR::VKILL => control_character('U'), CC_C_CHAR::VEOF => control_character('D'), - CC_C_CHAR::VTIME => '\0' as u8, + CC_C_CHAR::VTIME => b'\0', CC_C_CHAR::VMIN => 1, - CC_C_CHAR::VSWTC => '\0' as u8, + CC_C_CHAR::VSWTC => b'\0', CC_C_CHAR::VSTART => control_character('Q'), CC_C_CHAR::VSTOP => control_character('S'), CC_C_CHAR::VSUSP => control_character('Z'), - CC_C_CHAR::VEOL => '\0' as u8, + CC_C_CHAR::VEOL => b'\0', CC_C_CHAR::VREPRINT => control_character('R'), CC_C_CHAR::VDISCARD => control_character('O'), CC_C_CHAR::VWERASE => control_character('W'), CC_C_CHAR::VLNEXT => control_character('V'), - CC_C_CHAR::VEOL2 => '\0' as u8, + CC_C_CHAR::VEOL2 => b'\0', } } } @@ -218,8 +218,8 @@ pub struct KernelTermios { c_cc: [CcT; KERNEL_NCCS], } -impl KernelTermios { - pub fn default() -> Self { +impl Default for KernelTermios { + fn default() -> Self { let mut termios = Self { c_iflags: C_IFLAGS::default(), c_oflags: C_OFLAGS::default(), @@ -247,7 +247,9 @@ impl KernelTermios { *termios.get_special_char_mut(CC_C_CHAR::VEOL2) = CC_C_CHAR::VEOL2.default_char(); termios } +} +impl KernelTermios { pub fn get_special_char(&self, cc_c_char: CC_C_CHAR) -> &CcT { &self.c_cc[cc_c_char as usize] } @@ -292,8 +294,8 @@ impl KernelTermios { } const fn control_character(c: char) -> u8 { - debug_assert!(c as u8 >= 'A' as u8); - c as u8 - 'A' as u8 + 1u8 + debug_assert!(c as u8 >= b'A'); + c as u8 - b'A' + 1u8 } #[derive(Debug, Clone, Copy, Default, Pod)] diff --git a/services/libs/jinux-std/src/error.rs b/services/libs/jinux-std/src/error.rs index c4b5f7246..847646751 100644 --- a/services/libs/jinux-std/src/error.rs +++ b/services/libs/jinux-std/src/error.rs @@ -268,13 +268,13 @@ impl From for Error { #[macro_export] macro_rules! return_errno { ($errno: expr) => { - return core::prelude::v1::Err(crate::error::Error::new($errno)) + return Err($crate::error::Error::new($errno)) }; } #[macro_export] macro_rules! return_errno_with_message { ($errno: expr, $message: expr) => { - return core::prelude::v1::Err(crate::error::Error::with_message($errno, $message)) + return Err($crate::error::Error::with_message($errno, $message)) }; } diff --git a/services/libs/jinux-std/src/events/mod.rs b/services/libs/jinux-std/src/events/mod.rs index 10f4421e5..f5c035236 100644 --- a/services/libs/jinux-std/src/events/mod.rs +++ b/services/libs/jinux-std/src/events/mod.rs @@ -1,3 +1,4 @@ +#[allow(clippy::module_inception)] mod events; mod observer; mod subject; diff --git a/services/libs/jinux-std/src/events/subject.rs b/services/libs/jinux-std/src/events/subject.rs index 54dfc2d22..611b6550a 100644 --- a/services/libs/jinux-std/src/events/subject.rs +++ b/services/libs/jinux-std/src/events/subject.rs @@ -14,13 +14,12 @@ pub struct Subject = ()> { } impl> Subject { - pub fn new() -> Self { + pub const fn new() -> Self { Self { observers: Mutex::new(BTreeMap::new()), num_observers: AtomicUsize::new(0), } } - /// Register an observer. /// /// A registered observer will get notified through its `on_events` method. diff --git a/services/libs/jinux-std/src/fs/device.rs b/services/libs/jinux-std/src/fs/device.rs index 3062e0df2..dc5fb9f7e 100644 --- a/services/libs/jinux-std/src/fs/device.rs +++ b/services/libs/jinux-std/src/fs/device.rs @@ -79,9 +79,9 @@ impl Debug for DeviceId { } } -impl Into for DeviceId { - fn into(self) -> u64 { - self.0 +impl From for u64 { + fn from(value: DeviceId) -> Self { + value.0 } } diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs index ac2a0ddd7..024c782b9 100644 --- a/services/libs/jinux-std/src/fs/devpts/mod.rs +++ b/services/libs/jinux-std/src/fs/devpts/mod.rs @@ -43,13 +43,12 @@ pub struct DevPts { impl DevPts { pub fn new() -> Arc { let sb = SuperBlock::new(DEVPTS_MAGIC, BLOCK_SIZE, NAME_MAX); - let devpts = Arc::new_cyclic(|weak_self| Self { + Arc::new_cyclic(|weak_self| Self { root: RootInode::new(weak_self.clone(), &sb), sb, index_alloc: Mutex::new(IdAlloc::with_capacity(MAX_PTY_NUM)), this: weak_self.clone(), - }); - devpts + }) } /// Create the master and slave pair. @@ -194,7 +193,7 @@ impl Inode for RootInode { // Read the slaves. let slaves = self.slaves.read(); - let start_offset = offset.clone(); + let start_offset = *offset; for (idx, (name, node)) in slaves .idxes_and_items() .map(|(idx, (name, node))| (idx + 3, (name, node))) @@ -239,7 +238,7 @@ impl Inode for RootInode { .slaves .read() .idxes_and_items() - .find(|(_, (child_name, _))| child_name == &slave) + .find(|(_, (child_name, _))| child_name == slave) .map(|(_, (_, node))| node.clone()) .ok_or(Error::new(Errno::ENOENT))?, }; diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/jinux-std/src/fs/file_table.rs index 40d8ee795..39d3ef460 100644 --- a/services/libs/jinux-std/src/fs/file_table.rs +++ b/services/libs/jinux-std/src/fs/file_table.rs @@ -17,7 +17,7 @@ pub struct FileTable { } impl FileTable { - pub fn new() -> Self { + pub const fn new() -> Self { Self { table: SlotVec::new(), subject: Subject::new(), diff --git a/services/libs/jinux-std/src/fs/fs_resolver.rs b/services/libs/jinux-std/src/fs/fs_resolver.rs index 650d8703c..faeb05281 100644 --- a/services/libs/jinux-std/src/fs/fs_resolver.rs +++ b/services/libs/jinux-std/src/fs/fs_resolver.rs @@ -23,6 +23,12 @@ impl Clone for FsResolver { } } +impl Default for FsResolver { + fn default() -> Self { + Self::new() + } +} + impl FsResolver { pub fn new() -> Self { Self { @@ -86,14 +92,13 @@ impl FsResolver { } let (dir_dentry, file_name) = self.lookup_dir_and_base_name_inner(path, follow_tail_link)?; - if file_name.ends_with("/") { + if file_name.ends_with('/') { return_errno_with_message!(Errno::EISDIR, "path refers to a directory"); } if !dir_dentry.vnode().inode_mode().is_writable() { return_errno_with_message!(Errno::EACCES, "file cannot be created"); } - let new_dentry = dir_dentry.create(&file_name, InodeType::File, inode_mode)?; - new_dentry + dir_dentry.create(&file_name, InodeType::File, inode_mode)? } Err(e) => return Err(e), }; @@ -148,7 +153,7 @@ impl FsResolver { relative_path: &str, follow_tail_link: bool, ) -> Result> { - debug_assert!(!relative_path.starts_with("/")); + debug_assert!(!relative_path.starts_with('/')); if relative_path.len() > PATH_MAX { return_errno_with_message!(Errno::ENAMETOOLONG, "path is too long"); @@ -195,11 +200,11 @@ impl FsResolver { }; // Change the dentry and relative path according to symlink - if link_path_remain.starts_with("/") { + if link_path_remain.starts_with('/') { dentry = self.root.clone(); } link_path.clear(); - link_path.push_str(&link_path_remain.trim_start_matches('/')); + link_path.push_str(link_path_remain.trim_start_matches('/')); relative_path = &link_path; follows += 1; } else { @@ -269,20 +274,20 @@ impl FsResolver { // Dereference the tail symlinks if needed loop { - match dir_dentry.lookup(&base_name.trim_end_matches('/')) { + match dir_dentry.lookup(base_name.trim_end_matches('/')) { Ok(dentry) if dentry.vnode().inode_type() == InodeType::SymLink => { let link = { let mut link = dentry.vnode().read_link()?; if link.is_empty() { return_errno_with_message!(Errno::ENOENT, "invalid symlink"); } - if base_name.ends_with("/") && !link.ends_with("/") { + if base_name.ends_with('/') && !link.ends_with('/') { link += "/"; } link }; let (dir, file_name) = split_path(&link); - if dir.starts_with("/") { + if dir.starts_with('/') { dir_dentry = self.lookup_from_parent(&self.root, dir.trim_start_matches('/'), true)?; base_name = String::from(file_name); @@ -326,7 +331,7 @@ impl<'a> FsPath<'a> { return_errno_with_message!(Errno::ENAMETOOLONG, "path name too long"); } - let fs_path_inner = if path.starts_with("/") { + let fs_path_inner = if path.starts_with('/') { FsPathInner::Absolute(path) } else if dirfd >= 0 { if path.is_empty() { diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs index b36f729af..a60ea1a2f 100644 --- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs +++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs @@ -53,7 +53,7 @@ impl InodeHandle { impl Clone for InodeHandle { fn clone(&self) -> Self { - Self(self.0.clone(), self.1.clone()) + Self(self.0.clone(), self.1) } } diff --git a/services/libs/jinux-std/src/fs/procfs/mod.rs b/services/libs/jinux-std/src/fs/procfs/mod.rs index 8fdd7281b..965b1c84f 100644 --- a/services/libs/jinux-std/src/fs/procfs/mod.rs +++ b/services/libs/jinux-std/src/fs/procfs/mod.rs @@ -43,8 +43,7 @@ impl ProcFS { } pub(in crate::fs::procfs) fn alloc_id(&self) -> usize { - let next_id = self.inode_allocator.fetch_add(1, Ordering::SeqCst); - next_id + self.inode_allocator.fetch_add(1, Ordering::SeqCst) } } diff --git a/services/libs/jinux-std/src/fs/procfs/template/builder.rs b/services/libs/jinux-std/src/fs/procfs/template/builder.rs index f0b403521..60263a6ac 100644 --- a/services/libs/jinux-std/src/fs/procfs/template/builder.rs +++ b/services/libs/jinux-std/src/fs/procfs/template/builder.rs @@ -151,6 +151,7 @@ impl OptionalBuilder { self } + #[allow(clippy::type_complexity)] pub fn build(self) -> Result<(Arc, Option>, bool)> { if self.parent.is_none() && self.fs.is_none() { return_errno_with_message!(Errno::EINVAL, "must have parent or fs"); diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs index bb0abb87e..3da24c62b 100644 --- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs +++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs @@ -124,7 +124,7 @@ impl Inode for ProcDir { // Read the normal child entries. self.inner.populate_children(self.this.clone()); let cached_children = self.cached_children.read(); - let start_offset = offset.clone(); + let start_offset = *offset; for (idx, (name, child)) in cached_children .idxes_and_items() .map(|(idx, (name, child))| (idx + 2, (name, child))) diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs index de8d95901..06ec9a3aa 100644 --- a/services/libs/jinux-std/src/fs/ramfs/fs.rs +++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs @@ -157,6 +157,7 @@ impl Inode_ { } } +#[allow(clippy::large_enum_variant)] enum Inner { Dir(DirEntry), File, @@ -232,8 +233,7 @@ impl DirEntry { } else { self.children .iter() - .find(|(child, _)| child == &Str256::from(name)) - .is_some() + .any(|(child, _)| child == &Str256::from(name)) } } @@ -292,7 +292,7 @@ impl DirEntry { *idx += 1; } // Read the normal child entries. - let start_idx = idx.clone(); + let start_idx = *idx; for (offset, (name, child)) in self .children .idxes_and_items() diff --git a/services/libs/jinux-std/src/fs/utils/access_mode.rs b/services/libs/jinux-std/src/fs/utils/access_mode.rs index 352d81f4b..3929abd5f 100644 --- a/services/libs/jinux-std/src/fs/utils/access_mode.rs +++ b/services/libs/jinux-std/src/fs/utils/access_mode.rs @@ -15,17 +15,11 @@ pub enum AccessMode { impl AccessMode { pub fn is_readable(&self) -> bool { - match *self { - AccessMode::O_RDONLY | AccessMode::O_RDWR => true, - _ => false, - } + matches!(*self, AccessMode::O_RDONLY | AccessMode::O_RDWR) } pub fn is_writable(&self) -> bool { - match *self { - AccessMode::O_WRONLY | AccessMode::O_RDWR => true, - _ => false, - } + matches!(*self, AccessMode::O_WRONLY | AccessMode::O_RDWR) } } diff --git a/services/libs/jinux-std/src/fs/utils/channel.rs b/services/libs/jinux-std/src/fs/utils/channel.rs index fa6e8a572..d3449aabe 100644 --- a/services/libs/jinux-std/src/fs/utils/channel.rs +++ b/services/libs/jinux-std/src/fs/utils/channel.rs @@ -162,7 +162,7 @@ impl Producer { return_errno!(Errno::EPIPE); } - if buf.len() == 0 { + if buf.is_empty() { return Ok(0); } @@ -249,7 +249,7 @@ impl Consumer { if self.is_shutdown() { return_errno!(Errno::EPIPE); } - if buf.len() == 0 { + if buf.is_empty() { return Ok(0); } diff --git a/services/libs/jinux-std/src/fs/utils/dentry.rs b/services/libs/jinux-std/src/fs/utils/dentry.rs index 89957a7a0..7d2d7d95a 100644 --- a/services/libs/jinux-std/src/fs/utils/dentry.rs +++ b/services/libs/jinux-std/src/fs/utils/dentry.rs @@ -58,7 +58,7 @@ impl Dentry { if !self.is_mountpoint() { return self.this(); } - match self.mount_node().get(&self) { + match self.mount_node().get(self) { Some(child_mount) => child_mount.root_dentry().overlaid_dentry(), None => self.this(), } @@ -126,7 +126,7 @@ impl Dentry { /// Get the DentryKey. pub fn key(&self) -> DentryKey { - DentryKey::new(&self) + DentryKey::new(self) } /// Get the vnode. @@ -331,7 +331,7 @@ impl Dentry { Some(dentry) => { children.delete_dentry(old_name); dentry.set_name_and_parent(new_name, self.this()); - children.insert_dentry(&dentry); + children.insert_dentry(dentry); } None => { children.delete_dentry(new_name); @@ -343,7 +343,7 @@ impl Dentry { return_errno_with_message!(Errno::EXDEV, "cannot cross mount"); } let (mut self_children, mut new_dir_children) = - write_lock_children_on_two_dentries(&self, &new_dir); + write_lock_children_on_two_dentries(self, new_dir); let old_dentry = self_children.find_dentry_with_checking_mountpoint(old_name)?; let _ = new_dir_children.find_dentry_with_checking_mountpoint(new_name)?; self.vnode.rename(old_name, &new_dir.vnode, new_name)?; @@ -351,7 +351,7 @@ impl Dentry { Some(dentry) => { self_children.delete_dentry(old_name); dentry.set_name_and_parent(new_name, new_dir.this()); - new_dir_children.insert_dentry(&dentry); + new_dir_children.insert_dentry(dentry); } None => { new_dir_children.delete_dentry(new_name); @@ -473,7 +473,7 @@ impl Dentry { } } - debug_assert!(path.starts_with("/")); + debug_assert!(path.starts_with('/')); path } } diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs index b58fea932..5d139caac 100644 --- a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs +++ b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs @@ -14,11 +14,7 @@ pub trait DirEntryVecExt { impl DirEntryVecExt for SlotVec<(String, Arc)> { fn put_entry_if_not_found(&mut self, name: &str, f: impl Fn() -> Arc) { - if self - .iter() - .find(|(child_name, _)| child_name == name) - .is_none() - { + if !self.iter().any(|(child_name, _)| child_name == name) { let inode = f(); self.put((String::from(name), inode)); } diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/jinux-std/src/fs/utils/inode.rs index 310a58314..5bf42d0ae 100644 --- a/services/libs/jinux-std/src/fs/utils/inode.rs +++ b/services/libs/jinux-std/src/fs/utils/inode.rs @@ -23,23 +23,17 @@ pub enum InodeType { impl InodeType { pub fn support_read(&self) -> bool { - match self { - InodeType::File - | InodeType::Socket - | InodeType::CharDevice - | InodeType::BlockDevice => true, - _ => false, - } + matches!( + self, + InodeType::File | InodeType::Socket | InodeType::CharDevice | InodeType::BlockDevice + ) } pub fn support_write(&self) -> bool { - match self { - InodeType::File - | InodeType::Socket - | InodeType::CharDevice - | InodeType::BlockDevice => true, - _ => false, - } + matches!( + self, + InodeType::File | InodeType::Socket | InodeType::CharDevice | InodeType::BlockDevice + ) } pub fn is_reguler_file(&self) -> bool { @@ -232,6 +226,10 @@ impl Metadata { pub trait Inode: Any + Sync + Send { fn len(&self) -> usize; + fn is_empty(&self) -> bool { + self.len() == 0 + } + fn resize(&self, new_size: usize); fn metadata(&self) -> Metadata; diff --git a/services/libs/jinux-std/src/fs/utils/page_cache.rs b/services/libs/jinux-std/src/fs/utils/page_cache.rs index eb777c833..694c333db 100644 --- a/services/libs/jinux-std/src/fs/utils/page_cache.rs +++ b/services/libs/jinux-std/src/fs/utils/page_cache.rs @@ -106,13 +106,11 @@ impl Pager for PageCacheManager { let page_idx = offset / PAGE_SIZE; let mut pages = self.pages.lock(); if let Some(page) = pages.pop(&page_idx) { - match page.state() { - PageState::Dirty => self - .backed_inode + if let PageState::Dirty = page.state() { + self.backed_inode .upgrade() .unwrap() - .write_page(page_idx, &page.frame())?, - _ => (), + .write_page(page_idx, &page.frame())? } } else { warn!("page {} is not in page cache, do nothing", page_idx); diff --git a/services/libs/jinux-std/src/fs/utils/poll.rs b/services/libs/jinux-std/src/fs/utils/poll.rs index 9d83abc80..9cff2bde5 100644 --- a/services/libs/jinux-std/src/fs/utils/poll.rs +++ b/services/libs/jinux-std/src/fs/utils/poll.rs @@ -53,8 +53,7 @@ impl Pollee { self.register_poller(poller.unwrap(), mask); // It is important to check events again to handle race conditions - let revents = self.events() & mask; - revents + self.events() & mask } fn register_poller(&self, poller: &Poller, mask: IoEvents) { @@ -139,6 +138,12 @@ struct PollerInner { pollees: Mutex, ()>>, } +impl Default for Poller { + fn default() -> Self { + Self::new() + } +} + impl Poller { /// Constructs a new `Poller`. pub fn new() -> Self { diff --git a/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs index 617f6c36b..6e387e40e 100644 --- a/services/libs/jinux-std/src/fs/utils/vnode.rs +++ b/services/libs/jinux-std/src/fs/utils/vnode.rs @@ -235,6 +235,10 @@ impl Vnode { self.inner.read().inode.len() } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + pub fn atime(&self) -> Duration { self.inner.read().inode.atime() } @@ -257,7 +261,7 @@ impl Vnode { pub fn writer(&self, from_offset: usize) -> VnodeWriter { VnodeWriter { - inner: &self, + inner: self, offset: from_offset, } } diff --git a/services/libs/jinux-std/src/net/iface/any_socket.rs b/services/libs/jinux-std/src/net/iface/any_socket.rs index 7c054c163..f43f9d606 100644 --- a/services/libs/jinux-std/src/net/iface/any_socket.rs +++ b/services/libs/jinux-std/src/net/iface/any_socket.rs @@ -15,6 +15,7 @@ pub struct AnyUnboundSocket { pollee: Pollee, } +#[allow(clippy::large_enum_variant)] pub(super) enum AnyRawSocket { Tcp(RawTcpSocket), Udp(RawUdpSocket), diff --git a/services/libs/jinux-std/src/net/iface/common.rs b/services/libs/jinux-std/src/net/iface/common.rs index 8ab3c771d..f4f8ee939 100644 --- a/services/libs/jinux-std/src/net/iface/common.rs +++ b/services/libs/jinux-std/src/net/iface/common.rs @@ -2,6 +2,7 @@ use core::sync::atomic::{AtomicU64, Ordering}; use super::Ipv4Address; use crate::prelude::*; +use alloc::collections::btree_map::Entry; use keyable_arc::KeyableWeak; use smoltcp::{ iface::{SocketHandle, SocketSet}, @@ -62,8 +63,8 @@ impl IfaceCommon { fn alloc_ephemeral_port(&self) -> Result { let mut used_ports = self.used_ports.write(); for port in IP_LOCAL_PORT_START..=IP_LOCAL_PORT_END { - if !used_ports.contains_key(&port) { - used_ports.insert(port, 0); + if let Entry::Vacant(e) = used_ports.entry(port) { + e.insert(0); return Ok(port); } } @@ -74,7 +75,7 @@ impl IfaceCommon { let mut used_ports = self.used_ports.write(); if let Some(used_times) = used_ports.get_mut(&port) { if *used_times == 0 || can_reuse { - *used_times = *used_times + 1; + *used_times += 1; } else { return_errno_with_message!(Errno::EADDRINUSE, "cannot bind port"); } @@ -163,7 +164,7 @@ impl IfaceCommon { } fn insert_bound_socket(&self, socket: &Arc) -> Result<()> { - let weak_ref = KeyableWeak::from(Arc::downgrade(&socket)); + let weak_ref = KeyableWeak::from(Arc::downgrade(socket)); let mut bound_sockets = self.bound_sockets.write(); if bound_sockets.contains(&weak_ref) { return_errno_with_message!(Errno::EINVAL, "the socket is already bound"); diff --git a/services/libs/jinux-std/src/net/iface/loopback.rs b/services/libs/jinux-std/src/net/iface/loopback.rs index 61a802448..0d40e18fc 100644 --- a/services/libs/jinux-std/src/net/iface/loopback.rs +++ b/services/libs/jinux-std/src/net/iface/loopback.rs @@ -28,7 +28,7 @@ impl IfaceLoopback { let config = Config::new(); let mut interface = smoltcp::iface::Interface::new(config, &mut loopback); interface.update_ip_addrs(|ip_addrs| { - debug_assert!(ip_addrs.len() == 0); + debug_assert!(ip_addrs.is_empty()); let ip_addr = IpCidr::new(LOOPBACK_ADDRESS, LOOPBACK_ADDRESS_PREFIX_LEN); ip_addrs.push(ip_addr).unwrap(); }); diff --git a/services/libs/jinux-std/src/net/iface/util.rs b/services/libs/jinux-std/src/net/iface/util.rs index 57e254c51..d0e950d8e 100644 --- a/services/libs/jinux-std/src/net/iface/util.rs +++ b/services/libs/jinux-std/src/net/iface/util.rs @@ -21,22 +21,16 @@ impl BindPortConfig { } else { Self::Specified(port) } + } else if can_reuse { + return_errno_with_message!(Errno::EINVAL, "invalid bind port config"); } else { - if can_reuse { - return_errno_with_message!(Errno::EINVAL, "invalid bind port config"); - } else { - Self::Ephemeral - } + Self::Ephemeral }; Ok(config) } pub(super) fn can_reuse(&self) -> bool { - if let Self::CanReuse(_) = self { - true - } else { - false - } + matches!(self, Self::CanReuse(_)) } pub(super) fn port(&self) -> Option { diff --git a/services/libs/jinux-std/src/net/iface/virtio.rs b/services/libs/jinux-std/src/net/iface/virtio.rs index d77e249d5..e2239637a 100644 --- a/services/libs/jinux-std/src/net/iface/virtio.rs +++ b/services/libs/jinux-std/src/net/iface/virtio.rs @@ -19,7 +19,7 @@ pub struct IfaceVirtio { impl IfaceVirtio { pub fn new() -> Arc { - let mut virtio_net = jinux_network::get_device(&(DEVICE_NAME).to_string()).unwrap(); + let virtio_net = jinux_network::get_device(&(DEVICE_NAME).to_string()).unwrap(); let interface = { let mac_addr = virtio_net.lock().mac_addr(); let ip_addr = IpCidr::new(wire::IpAddress::Ipv4(wire::Ipv4Address::UNSPECIFIED), 0); @@ -33,7 +33,7 @@ impl IfaceVirtio { }; let mut interface = smoltcp::iface::Interface::new(config, &mut **virtio_net.lock()); interface.update_ip_addrs(|ip_addrs| { - debug_assert!(ip_addrs.len() == 0); + debug_assert!(ip_addrs.is_empty()); ip_addrs.push(ip_addr).unwrap(); }); interface diff --git a/services/libs/jinux-std/src/net/socket/ip/datagram.rs b/services/libs/jinux-std/src/net/socket/ip/datagram.rs index c790af97b..308c41139 100644 --- a/services/libs/jinux-std/src/net/socket/ip/datagram.rs +++ b/services/libs/jinux-std/src/net/socket/ip/datagram.rs @@ -37,11 +37,7 @@ enum Inner { impl Inner { fn is_bound(&self) -> bool { - if let Inner::Bound { .. } = self { - true - } else { - false - } + matches!(self, Inner::Bound { .. }) } fn bind(&mut self, endpoint: IpEndpoint) -> Result<()> { @@ -91,7 +87,7 @@ impl Inner { remote_endpoint, .. } = self { - remote_endpoint.clone() + *remote_endpoint } else { None } diff --git a/services/libs/jinux-std/src/net/socket/ip/stream/init.rs b/services/libs/jinux-std/src/net/socket/ip/stream/init.rs index 92578dfa3..b38c64475 100644 --- a/services/libs/jinux-std/src/net/socket/ip/stream/init.rs +++ b/services/libs/jinux-std/src/net/socket/ip/stream/init.rs @@ -72,7 +72,7 @@ impl Inner { fn bound_socket(&self) -> Option<&Arc> { match self { - Inner::Bound(bound_socket) => Some(&bound_socket), + Inner::Bound(bound_socket) => Some(bound_socket), Inner::Connecting { bound_socket, .. } => Some(bound_socket), _ => None, } @@ -96,8 +96,7 @@ impl Inner { fn local_endpoint(&self) -> Option { self.bound_socket() - .map(|socket| socket.local_endpoint()) - .flatten() + .and_then(|socket| socket.local_endpoint()) } fn remote_endpoint(&self) -> Option { diff --git a/services/libs/jinux-std/src/net/socket/ip/stream/listen.rs b/services/libs/jinux-std/src/net/socket/ip/stream/listen.rs index 9bbf8ae19..aa68bb680 100644 --- a/services/libs/jinux-std/src/net/socket/ip/stream/listen.rs +++ b/services/libs/jinux-std/src/net/socket/ip/stream/listen.rs @@ -105,7 +105,7 @@ impl ListenStream { backlog_socket.poll(mask, poller); } } - return IoEvents::empty(); + IoEvents::empty() } fn bound_socket(&self) -> Arc { diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/endpoint.rs b/services/libs/jinux-std/src/net/socket/unix/stream/endpoint.rs index e56ba9226..88d8d780a 100644 --- a/services/libs/jinux-std/src/net/socket/unix/stream/endpoint.rs +++ b/services/libs/jinux-std/src/net/socket/unix/stream/endpoint.rs @@ -52,7 +52,7 @@ impl Endpoint { } pub(super) fn peer_addr(&self) -> Option { - self.0.peer.upgrade().map(|peer| peer.addr()).flatten() + self.0.peer.upgrade().and_then(|peer| peer.addr()) } pub(super) fn is_nonblocking(&self) -> bool { diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/listener.rs b/services/libs/jinux-std/src/net/socket/unix/stream/listener.rs index 4470183c5..8af27adea 100644 --- a/services/libs/jinux-std/src/net/socket/unix/stream/listener.rs +++ b/services/libs/jinux-std/src/net/socket/unix/stream/listener.rs @@ -205,7 +205,7 @@ fn create_keyable_inode(dentry: &Arc) -> KeyableWeak { } pub(super) fn unregister_backlog(addr: &UnixSocketAddrBound) { - BACKLOG_TABLE.remove_backlog(&addr); + BACKLOG_TABLE.remove_backlog(addr); } pub(super) fn push_incoming( diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/mod.rs b/services/libs/jinux-std/src/net/socket/unix/stream/mod.rs index ee410dc89..52fd78f7b 100644 --- a/services/libs/jinux-std/src/net/socket/unix/stream/mod.rs +++ b/services/libs/jinux-std/src/net/socket/unix/stream/mod.rs @@ -2,6 +2,6 @@ mod connected; mod endpoint; mod init; mod listener; -mod stream; +mod socket; -pub use stream::UnixStreamSocket; +pub use socket::UnixStreamSocket; diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/stream.rs b/services/libs/jinux-std/src/net/socket/unix/stream/socket.rs similarity index 97% rename from services/libs/jinux-std/src/net/socket/unix/stream/stream.rs rename to services/libs/jinux-std/src/net/socket/unix/stream/socket.rs index c6294bcd1..ba41c3591 100644 --- a/services/libs/jinux-std/src/net/socket/unix/stream/stream.rs +++ b/services/libs/jinux-std/src/net/socket/unix/stream/socket.rs @@ -233,10 +233,8 @@ impl Socket for UnixStreamSocket { }; match connected.peer_addr() { - None => return Ok(SocketAddr::Unix(UnixSocketAddr::Path(String::new()))), - Some(peer_addr) => { - return Ok(SocketAddr::from(peer_addr.clone())); - } + None => Ok(SocketAddr::Unix(UnixSocketAddr::Path(String::new()))), + Some(peer_addr) => Ok(SocketAddr::from(peer_addr.clone())), } } @@ -295,5 +293,5 @@ fn lookup_socket_file(path: &str) -> Result> { if !dentry.inode_mode().is_readable() || !dentry.inode_mode().is_writable() { return_errno_with_message!(Errno::EACCES, "the socket cannot be read or written") } - return Ok(dentry); + Ok(dentry) } diff --git a/services/libs/jinux-std/src/prelude.rs b/services/libs/jinux-std/src/prelude.rs index 31585b3a6..4be03973b 100644 --- a/services/libs/jinux-std/src/prelude.rs +++ b/services/libs/jinux-std/src/prelude.rs @@ -28,7 +28,7 @@ pub(crate) use pod::Pod; #[macro_export] macro_rules! current { () => { - crate::process::Process::current() + $crate::process::Process::current() }; } @@ -36,7 +36,7 @@ macro_rules! current { #[macro_export] macro_rules! current_thread { () => { - crate::thread::Thread::current() + $crate::thread::Thread::current() }; } diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs index 77f23db21..db35bfe25 100644 --- a/services/libs/jinux-std/src/process/clone.rs +++ b/services/libs/jinux-std/src/process/clone.rs @@ -178,7 +178,7 @@ fn clone_child_thread(parent_context: UserContext, clone_args: CloneArgs) -> Res // inherit sigmask from current thread let current_thread = current_thread!(); let current_posix_thread = current_thread.as_posix_thread().unwrap(); - let sig_mask = current_posix_thread.sig_mask().lock().clone(); + let sig_mask = *current_posix_thread.sig_mask().lock(); let is_main_thread = child_tid == current.pid(); let thread_builder = PosixThreadBuilder::new(child_tid, child_user_space) .process(Arc::downgrade(¤t)) @@ -241,7 +241,7 @@ fn clone_child_process(parent_context: UserContext, clone_args: CloneArgs) -> Re // inherit parent's sig mask let current_thread = current_thread!(); let posix_thread = current_thread.as_posix_thread().unwrap(); - let child_sig_mask = posix_thread.sig_mask().lock().clone(); + let child_sig_mask = *posix_thread.sig_mask().lock(); let child_tid = allocate_tid(); let mut child_thread_builder = PosixThreadBuilder::new(child_tid, child_user_space) @@ -338,7 +338,7 @@ fn clone_cpu_context( tls: u64, clone_flags: CloneFlags, ) -> UserContext { - let mut child_context = parent_context.clone(); + let mut child_context = parent_context; // The return value of child thread is zero child_context.set_rax(0); @@ -390,7 +390,7 @@ fn clone_sighand( if clone_flags.contains(CloneFlags::CLONE_SIGHAND) { parent_sig_dispositions.clone() } else { - Arc::new(Mutex::new(parent_sig_dispositions.lock().clone())) + Arc::new(Mutex::new(*parent_sig_dispositions.lock())) } } diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs index cb333e638..18ad42f9d 100644 --- a/services/libs/jinux-std/src/process/mod.rs +++ b/services/libs/jinux-std/src/process/mod.rs @@ -91,6 +91,7 @@ impl Process { } /// create a new process(not schedule it) + #[allow(clippy::too_many_arguments)] pub fn new( pid: Pid, parent: Weak, @@ -328,7 +329,7 @@ impl Process { /// returns the root vmar pub fn root_vmar(&self) -> &Vmar { - &self.process_vm.root_vmar() + self.process_vm.root_vmar() } /// returns the user heap if the process does have, otherwise None diff --git a/services/libs/jinux-std/src/process/posix_thread/builder.rs b/services/libs/jinux-std/src/process/posix_thread/builder.rs index 253ec6f9c..28cad6fe4 100644 --- a/services/libs/jinux-std/src/process/posix_thread/builder.rs +++ b/services/libs/jinux-std/src/process/posix_thread/builder.rs @@ -63,6 +63,7 @@ impl PosixThreadBuilder { self } + #[allow(clippy::wrong_self_convention)] pub fn is_main_thread(mut self, is_main_thread: bool) -> Self { self.is_main_thread = is_main_thread; self diff --git a/services/libs/jinux-std/src/process/posix_thread/futex.rs b/services/libs/jinux-std/src/process/posix_thread/futex.rs index 83d856c05..33a46b930 100644 --- a/services/libs/jinux-std/src/process/posix_thread/futex.rs +++ b/services/libs/jinux-std/src/process/posix_thread/futex.rs @@ -64,7 +64,7 @@ pub fn futex_wake_bitset( ) -> Result { debug!( "futex_wake_bitset addr: {:#x}, max_count: {}, bitset: {:#x}", - futex_addr as usize, max_count, bitset + futex_addr, max_count, bitset ); let futex_key = FutexKey::new(futex_addr); @@ -234,8 +234,8 @@ impl FutexBucket { if count == max_count { break; } - if (*item).key == key { - (*item).key = new_key; + if item.key == key { + item.key = new_key; count += 1; } } diff --git a/services/libs/jinux-std/src/process/posix_thread/name.rs b/services/libs/jinux-std/src/process/posix_thread/name.rs index cd689a818..b8a945ed8 100644 --- a/services/libs/jinux-std/src/process/posix_thread/name.rs +++ b/services/libs/jinux-std/src/process/posix_thread/name.rs @@ -43,6 +43,6 @@ impl ThreadName { } pub fn name(&self) -> Result> { - Ok(Some(&(CStr::from_bytes_until_nul(&self.inner)?))) + Ok(Some(CStr::from_bytes_until_nul(&self.inner)?)) } } diff --git a/services/libs/jinux-std/src/process/posix_thread/robust_list.rs b/services/libs/jinux-std/src/process/posix_thread/robust_list.rs index 0452b4c9b..dd923015a 100644 --- a/services/libs/jinux-std/src/process/posix_thread/robust_list.rs +++ b/services/libs/jinux-std/src/process/posix_thread/robust_list.rs @@ -34,7 +34,7 @@ impl RobustListHead { /// /// The futex refered to by `list_op_pending`, if any, will be returned as /// the last item. - pub fn futexes<'a>(&'a self) -> FutexIter<'a> { + pub fn futexes(&self) -> FutexIter<'_> { FutexIter::new(self) } diff --git a/services/libs/jinux-std/src/process/process_group.rs b/services/libs/jinux-std/src/process/process_group.rs index b203b38ab..1a18ea0cd 100644 --- a/services/libs/jinux-std/src/process/process_group.rs +++ b/services/libs/jinux-std/src/process/process_group.rs @@ -71,15 +71,15 @@ impl ProcessGroup { /// send kernel signal to all processes in the group pub fn kernel_signal(&self, signal: KernelSignal) { - for (_, process) in &self.inner.lock().processes { - process.enqueue_signal(Box::new(signal.clone())); + for process in self.inner.lock().processes.values() { + process.enqueue_signal(Box::new(signal)); } } /// send user signal to all processes in the group pub fn user_signal(&self, signal: UserSignal) { - for (_, process) in &self.inner.lock().processes { - process.enqueue_signal(Box::new(signal.clone())); + for process in self.inner.lock().processes.values() { + process.enqueue_signal(Box::new(signal)); } } } diff --git a/services/libs/jinux-std/src/process/process_table.rs b/services/libs/jinux-std/src/process/process_table.rs index 50a693a8e..428659843 100644 --- a/services/libs/jinux-std/src/process/process_table.rs +++ b/services/libs/jinux-std/src/process/process_table.rs @@ -30,10 +30,7 @@ pub fn remove_process(pid: Pid) { /// get a process with pid pub fn pid_to_process(pid: Pid) -> Option> { - PROCESS_TABLE - .lock() - .get(&pid) - .map(|process| process.clone()) + PROCESS_TABLE.lock().get(&pid).cloned() } /// get all processes @@ -58,10 +55,7 @@ pub fn remove_process_group(pgid: Pgid) { /// get a process group with pgid pub fn pgid_to_process_group(pgid: Pgid) -> Option> { - PROCESS_GROUP_TABLE - .lock() - .get(&pgid) - .map(|process_group| process_group.clone()) + PROCESS_GROUP_TABLE.lock().get(&pgid).cloned() } pub fn register_observer(observer: Weak>) { diff --git a/services/libs/jinux-std/src/process/process_vm/mmap_options.rs b/services/libs/jinux-std/src/process/process_vm/mmap_options.rs index 7431ba7ab..50295c57e 100644 --- a/services/libs/jinux-std/src/process/process_vm/mmap_options.rs +++ b/services/libs/jinux-std/src/process/process_vm/mmap_options.rs @@ -10,12 +10,13 @@ use crate::prelude::*; // The map type mask const MAP_TYPE: u32 = 0xf; -#[derive(Copy, Clone, PartialEq, Debug)] +#[derive(Copy, Clone, PartialEq, Debug, TryFromInt)] +#[repr(u8)] pub enum MMapType { - MapFile = 0x0, - MapShared = 0x1, - MapPrivate = 0x2, - MapSharedValidate = 0x3, + File = 0x0, // Invalid + Shared = 0x1, + Private = 0x2, + SharedValidate = 0x3, } bitflags! { @@ -46,15 +47,10 @@ impl TryFrom for MMapOptions { type Error = Error; fn try_from(value: u32) -> Result { - let typ_raw = value & MAP_TYPE; + let typ_raw = (value & MAP_TYPE) as u8; + let typ = MMapType::try_from(typ_raw)?; + let flags_raw = value & !MAP_TYPE; - let typ = match typ_raw { - 0x0 => MMapType::MapFile, - 0x1 => MMapType::MapShared, - 0x2 => MMapType::MapPrivate, - 0x3 => MMapType::MapSharedValidate, - _ => return Err(Error::with_message(Errno::EINVAL, "unknown mmap flags")), - }; let Some(flags) = MMapFlags::from_bits(flags_raw) else { return Err(Error::with_message(Errno::EINVAL, "unknown mmap flags")); }; diff --git a/services/libs/jinux-std/src/process/process_vm/user_heap.rs b/services/libs/jinux-std/src/process/process_vm/user_heap.rs index 08b1bc769..df78f10ea 100644 --- a/services/libs/jinux-std/src/process/process_vm/user_heap.rs +++ b/services/libs/jinux-std/src/process/process_vm/user_heap.rs @@ -40,16 +40,14 @@ impl UserHeap { .offset(self.heap_base) .size(self.heap_size_limit); vmar_map_options.build().unwrap(); - return self.current_heap_end.load(Ordering::Relaxed); + self.current_heap_end.load(Ordering::Relaxed) } pub fn brk(&self, new_heap_end: Option) -> Result { let current = current!(); let root_vmar = current.root_vmar(); match new_heap_end { - None => { - return Ok(self.current_heap_end.load(Ordering::Relaxed)); - } + None => Ok(self.current_heap_end.load(Ordering::Relaxed)), Some(new_heap_end) => { if new_heap_end > self.heap_base + self.heap_size_limit { return_errno_with_message!(Errno::ENOMEM, "heap size limit was met."); @@ -64,7 +62,7 @@ impl UserHeap { let heap_vmo = heap_mapping.vmo(); heap_vmo.resize(new_size)?; self.current_heap_end.store(new_heap_end, Ordering::Release); - return Ok(new_heap_end); + Ok(new_heap_end) } } } @@ -82,8 +80,8 @@ impl Clone for UserHeap { fn clone(&self) -> Self { let current_heap_end = self.current_heap_end.load(Ordering::Relaxed); Self { - heap_base: self.heap_base.clone(), - heap_size_limit: self.heap_size_limit.clone(), + heap_base: self.heap_base, + heap_size_limit: self.heap_size_limit, current_heap_end: AtomicUsize::new(current_heap_end), } } diff --git a/services/libs/jinux-std/src/process/program_loader/elf/aux_vec.rs b/services/libs/jinux-std/src/process/program_loader/elf/aux_vec.rs index f97fe0730..d81e3e1a6 100644 --- a/services/libs/jinux-std/src/process/program_loader/elf/aux_vec.rs +++ b/services/libs/jinux-std/src/process/program_loader/elf/aux_vec.rs @@ -80,7 +80,7 @@ impl AuxVec { } pub fn get(&self, key: AuxKey) -> Option { - self.table.get(&key).map(|val_ref| *val_ref) + self.table.get(&key).copied() } pub fn del(&mut self, key: AuxKey) -> Option { diff --git a/services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs b/services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs index 6ab336256..e2b8fd9f0 100644 --- a/services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs +++ b/services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs @@ -33,7 +33,7 @@ impl Elf { let program_header = xmas_elf::program::parse_program_header(input, header, index) .map_err(|_| Error::with_message(Errno::ENOEXEC, "parse program header fails"))?; let ph64 = match program_header { - xmas_elf::program::ProgramHeader::Ph64(ph64) => ph64.clone(), + xmas_elf::program::ProgramHeader::Ph64(ph64) => *ph64, xmas_elf::program::ProgramHeader::Ph32(_) => { return_errno_with_message!(Errno::ENOEXEC, "Not 64 byte executable") } @@ -111,7 +111,7 @@ impl Elf { // An offset to be subtracted from ELF vaddr for PIE pub fn base_load_address_offset(&self) -> u64 { - let phdr = self.program_headers.iter().nth(0).unwrap(); + let phdr = self.program_headers.get(0).unwrap(); phdr.virtual_addr - phdr.offset } } @@ -123,7 +123,7 @@ pub struct ElfHeader { impl ElfHeader { fn parse_elf_header(header: Header) -> Result { - let pt1 = header.pt1.clone(); + let pt1 = *header.pt1; let pt2 = match header.pt2 { HeaderPt2::Header64(header_pt2) => { let HeaderPt2_ { diff --git a/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs b/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs index bb6108226..83159f676 100644 --- a/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs +++ b/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs @@ -184,7 +184,7 @@ impl InitStack { let ldso_base = ldso_load_info.base_addr(); aux_vec.set(AuxKey::AT_BASE, ldso_base as u64)?; } - self.adjust_stack_alignment(root_vmar, &envp_pointers, &argv_pointers, &aux_vec)?; + self.adjust_stack_alignment(root_vmar, &envp_pointers, &argv_pointers, aux_vec)?; self.write_aux_vec(root_vmar, aux_vec)?; self.write_envp_pointers(root_vmar, envp_pointers)?; self.write_argv_pointers(root_vmar, argv_pointers)?; @@ -195,11 +195,7 @@ impl InitStack { } fn write_envp_strings(&mut self, root_vmar: &Vmar) -> Result> { - let envp = self - .envp - .iter() - .map(|envp| envp.clone()) - .collect::>(); + let envp = self.envp.to_vec(); let mut envp_pointers = Vec::with_capacity(envp.len()); for envp in envp.iter() { let pointer = self.write_cstring(envp, root_vmar)?; @@ -209,11 +205,7 @@ impl InitStack { } fn write_argv_strings(&mut self, root_vmar: &Vmar) -> Result> { - let argv = self - .argv - .iter() - .map(|argv| argv.clone()) - .collect::>(); + let argv = self.argv.to_vec(); let mut argv_pointers = Vec::with_capacity(argv.len()); for argv in argv.iter().rev() { let pointer = self.write_cstring(argv, root_vmar)?; @@ -224,7 +216,7 @@ impl InitStack { Ok(argv_pointers) } - fn write_aux_vec(&mut self, root_vmar: &Vmar, aux_vec: &mut AuxVec) -> Result<()> { + fn write_aux_vec(&mut self, root_vmar: &Vmar, aux_vec: &AuxVec) -> Result<()> { // Write NULL auxilary self.write_u64(0, root_vmar)?; self.write_u64(AuxKey::AT_NULL as u64, root_vmar)?; diff --git a/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs b/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs index 7ec1a24c8..12b2f5984 100644 --- a/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs +++ b/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs @@ -43,7 +43,7 @@ pub fn load_elf_to_vm( process_vm.clear(); match init_and_map_vmos(process_vm, ldso, &elf, &elf_file, argv, envp) { - Ok(elf_load_info) => return Ok(elf_load_info), + Ok(elf_load_info) => Ok(elf_load_info), Err(e) => { // Since the process_vm is cleared, the process cannot return to user space again, // so exit_group is called here. @@ -78,7 +78,7 @@ fn lookup_and_parse_ldso( } fn load_ldso(root_vmar: &Vmar, ldso_file: &Dentry, ldso_elf: &Elf) -> Result { - let map_addr = map_segment_vmos(&ldso_elf, root_vmar, &ldso_file)?; + let map_addr = map_segment_vmos(ldso_elf, root_vmar, ldso_file)?; Ok(LdsoLoadInfo::new( ldso_elf.entry_point() + map_addr, map_addr, @@ -102,21 +102,19 @@ fn init_and_map_vmos( None }; - let map_addr = map_segment_vmos(&elf, root_vmar, &elf_file)?; - let mut aux_vec = init_aux_vec(&elf, map_addr)?; + let map_addr = map_segment_vmos(elf, root_vmar, elf_file)?; + let mut aux_vec = init_aux_vec(elf, map_addr)?; let mut init_stack = InitStack::new_default_config(argv, envp); - init_stack.init(root_vmar, &elf, &ldso_load_info, &mut aux_vec)?; + init_stack.init(root_vmar, elf, &ldso_load_info, &mut aux_vec)?; let entry_point = if let Some(ldso_load_info) = ldso_load_info { // Normal shared object ldso_load_info.entry_point() + } else if elf.is_shared_object() { + // ldso itself + elf.entry_point() + map_addr } else { - if elf.is_shared_object() { - // ldso itself - elf.entry_point() + map_addr - } else { - // statically linked executable - elf.entry_point() - } + // statically linked executable + elf.entry_point() }; let elf_load_info = ElfLoadInfo::new(entry_point, init_stack.user_stack_top()); diff --git a/services/libs/jinux-std/src/process/signal/mod.rs b/services/libs/jinux-std/src/process/signal/mod.rs index 136926ea8..4564536a0 100644 --- a/services/libs/jinux-std/src/process/signal/mod.rs +++ b/services/libs/jinux-std/src/process/signal/mod.rs @@ -32,16 +32,14 @@ pub fn handle_pending_signal(context: &mut UserContext) -> Result<()> { let current_thread = current_thread!(); let posix_thread = current_thread.as_posix_thread().unwrap(); let pid = current.pid(); - let sig_mask = posix_thread.sig_mask().lock().clone(); + let sig_mask = *posix_thread.sig_mask().lock(); let mut thread_sig_queues = posix_thread.sig_queues().lock(); let mut proc_sig_queues = current.sig_queues().lock(); // We first deal with signal in current thread, then signal in current process. let signal = if let Some(signal) = thread_sig_queues.dequeue(&sig_mask) { Some(signal) - } else if let Some(signal) = proc_sig_queues.dequeue(&sig_mask) { - Some(signal) } else { - None + proc_sig_queues.dequeue(&sig_mask) }; if let Some(signal) = signal { let sig_num = signal.num(); @@ -132,18 +130,20 @@ pub fn handle_user_signal( // Set up signal stack in user stack, // to avoid corrupting user stack, we minus 128 first. let mut user_rsp = context.rsp() as u64; - user_rsp = user_rsp - 128; + user_rsp -= 128; // 1. write siginfo_t - user_rsp = user_rsp - mem::size_of::() as u64; + user_rsp -= mem::size_of::() as u64; write_val_to_user(user_rsp as _, &sig_info)?; let siginfo_addr = user_rsp; // debug!("siginfo_addr = 0x{:x}", siginfo_addr); // 2. write ucontext_t. user_rsp = alloc_aligned_in_user_stack(user_rsp, mem::size_of::(), 16)?; - let mut ucontext = ucontext_t::default(); - ucontext.uc_sigmask = mask.as_u64(); + let mut ucontext = ucontext_t { + uc_sigmask: mask.as_u64(), + ..Default::default() + }; ucontext.uc_mcontext.inner.gp_regs = *context.general_regs(); let mut sig_context = posix_thread.sig_context().lock(); if let Some(sig_context_addr) = *sig_context { @@ -172,7 +172,7 @@ pub fn handle_user_signal( 0x0f, 0x05, // syscall (call rt_sigreturn) 0x90, // nop (for alignment) ]; - user_rsp = user_rsp - TRAMPOLINE.len() as u64; + user_rsp -= TRAMPOLINE.len() as u64; let trampoline_rip = user_rsp; write_bytes_to_user(user_rsp as Vaddr, TRAMPOLINE)?; user_rsp = write_u64_to_user_stack(user_rsp, trampoline_rip)?; diff --git a/services/libs/jinux-std/src/process/signal/sig_action.rs b/services/libs/jinux-std/src/process/signal/sig_action.rs index b036aba45..d7dc97996 100644 --- a/services/libs/jinux-std/src/process/signal/sig_action.rs +++ b/services/libs/jinux-std/src/process/signal/sig_action.rs @@ -2,8 +2,9 @@ use super::{c_types::sigaction_t, constants::*, sig_mask::SigMask, sig_num::SigN use crate::prelude::*; use bitflags::bitflags; -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] pub enum SigAction { + #[default] Dfl, // Default action Ign, // Ignore this signal User { @@ -15,12 +16,6 @@ pub enum SigAction { }, } -impl Default for SigAction { - fn default() -> Self { - SigAction::Dfl - } -} - impl TryFrom for SigAction { type Error = Error; @@ -44,7 +39,7 @@ impl TryFrom for SigAction { } impl SigAction { - pub fn to_c(&self) -> sigaction_t { + pub fn as_c_type(&self) -> sigaction_t { match self { SigAction::Dfl => sigaction_t { handler_ptr: SIG_DFL, @@ -65,7 +60,7 @@ impl SigAction { mask, } => sigaction_t { handler_ptr: *handler_addr, - flags: flags.to_u32(), + flags: flags.as_u32(), restorer_ptr: *restorer_addr, mask: mask.as_u64(), }, @@ -100,7 +95,7 @@ impl TryFrom for SigActionFlags { } impl SigActionFlags { - pub fn to_u32(&self) -> u32 { + pub fn as_u32(&self) -> u32 { self.bits() } diff --git a/services/libs/jinux-std/src/process/signal/sig_disposition.rs b/services/libs/jinux-std/src/process/signal/sig_disposition.rs index 1c67904d2..f644eb2ca 100644 --- a/services/libs/jinux-std/src/process/signal/sig_disposition.rs +++ b/services/libs/jinux-std/src/process/signal/sig_disposition.rs @@ -6,6 +6,12 @@ pub struct SigDispositions { map: [SigAction; COUNT_ALL_SIGS], } +impl Default for SigDispositions { + fn default() -> Self { + Self::new() + } +} + impl SigDispositions { pub fn new() -> Self { Self { @@ -34,11 +40,8 @@ impl SigDispositions { /// This function should be used when execve. pub fn inherit(&mut self) { for sigaction in &mut self.map { - match sigaction { - SigAction::User { .. } => { - *sigaction = SigAction::Dfl; - } - _ => {} + if let SigAction::User { .. } = sigaction { + *sigaction = SigAction::Dfl; } } } diff --git a/services/libs/jinux-std/src/process/signal/sig_num.rs b/services/libs/jinux-std/src/process/signal/sig_num.rs index 2c7329fc0..76a48accb 100644 --- a/services/libs/jinux-std/src/process/signal/sig_num.rs +++ b/services/libs/jinux-std/src/process/signal/sig_num.rs @@ -10,7 +10,7 @@ impl TryFrom for SigNum { type Error = Error; fn try_from(sig_num: u8) -> Result { - if sig_num > MAX_RT_SIG_NUM || sig_num < MIN_STD_SIG_NUM { + if !(MIN_STD_SIG_NUM..=MAX_RT_SIG_NUM).contains(&sig_num) { return_errno_with_message!(Errno::EINVAL, "invalid signal number"); } Ok(SigNum { sig_num }) diff --git a/services/libs/jinux-std/src/process/signal/signals/kernel.rs b/services/libs/jinux-std/src/process/signal/signals/kernel.rs index b91768293..bb01f1426 100644 --- a/services/libs/jinux-std/src/process/signal/signals/kernel.rs +++ b/services/libs/jinux-std/src/process/signal/signals/kernel.rs @@ -19,7 +19,6 @@ impl Signal for KernelSignal { } fn to_info(&self) -> siginfo_t { - let info = siginfo_t::new(self.num, SI_KERNEL); - info + siginfo_t::new(self.num, SI_KERNEL) } } diff --git a/services/libs/jinux-std/src/process/signal/signals/user.rs b/services/libs/jinux-std/src/process/signal/signals/user.rs index 98649ca24..c784d938d 100644 --- a/services/libs/jinux-std/src/process/signal/signals/user.rs +++ b/services/libs/jinux-std/src/process/signal/signals/user.rs @@ -61,13 +61,11 @@ impl Signal for UserSignal { UserSignalKind::Sigqueue => SI_QUEUE, }; - let info = siginfo_t::new(self.num, code); + siginfo_t::new(self.num, code) // info.set_si_pid(self.pid); // info.set_si_uid(self.uid); // if let UserSignalKind::Sigqueue(val) = self.kind { // info.set_si_value(val); // } - - info } } diff --git a/services/libs/jinux-std/src/process/wait.rs b/services/libs/jinux-std/src/process/wait.rs index d2c6f5cba..519cb1b78 100644 --- a/services/libs/jinux-std/src/process/wait.rs +++ b/services/libs/jinux-std/src/process/wait.rs @@ -40,7 +40,7 @@ pub fn wait_child_exit( // we need to drop the lock here, since reap child process need to acquire this lock again drop(children_lock); - if unwaited_children.len() == 0 { + if unwaited_children.is_empty() { return Some(Err(jinux_frame::Error::NoChild)); } diff --git a/services/libs/jinux-std/src/syscall/epoll.rs b/services/libs/jinux-std/src/syscall/epoll.rs index 50fdbdbdc..bbb403e67 100644 --- a/services/libs/jinux-std/src/syscall/epoll.rs +++ b/services/libs/jinux-std/src/syscall/epoll.rs @@ -142,7 +142,7 @@ struct c_epoll_event { impl From<&EpollEvent> for c_epoll_event { fn from(ep_event: &EpollEvent) -> Self { Self { - events: ep_event.events.bits() as u32, + events: ep_event.events.bits(), data: ep_event.user_data, } } @@ -150,9 +150,6 @@ impl From<&EpollEvent> for c_epoll_event { impl From<&c_epoll_event> for EpollEvent { fn from(c_event: &c_epoll_event) -> Self { - Self::new( - IoEvents::from_bits_truncate(c_event.events as u32), - c_event.data, - ) + Self::new(IoEvents::from_bits_truncate(c_event.events), c_event.data) } } diff --git a/services/libs/jinux-std/src/syscall/execve.rs b/services/libs/jinux-std/src/syscall/execve.rs index 47c7fe3bd..dda220fc2 100644 --- a/services/libs/jinux-std/src/syscall/execve.rs +++ b/services/libs/jinux-std/src/syscall/execve.rs @@ -55,7 +55,7 @@ fn lookup_executable_file( ) -> Result> { let current = current!(); let fs_resolver = current.fs().read(); - let dentry = if flags.contains(OpenFlags::AT_EMPTY_PATH) && filename.len() == 0 { + let dentry = if flags.contains(OpenFlags::AT_EMPTY_PATH) && filename.is_empty() { fs_resolver.lookup_from_fd(dfd) } else { let fs_path = FsPath::new(dfd, &filename)?; diff --git a/services/libs/jinux-std/src/syscall/fcntl.rs b/services/libs/jinux-std/src/syscall/fcntl.rs index 0df68ca58..bbd1fe402 100644 --- a/services/libs/jinux-std/src/syscall/fcntl.rs +++ b/services/libs/jinux-std/src/syscall/fcntl.rs @@ -15,14 +15,14 @@ pub fn sys_fcntl(fd: FileDescripter, cmd: i32, arg: u64) -> Result { if arg != 1 { panic!("Unknown setfd argument"); } // TODO: Set cloexec - return Ok(SyscallReturn::Return(0)); + Ok(SyscallReturn::Return(0)) } FcntlCmd::F_GETFL => { let current = current!(); @@ -32,9 +32,9 @@ pub fn sys_fcntl(fd: FileDescripter, cmd: i32, arg: u64) -> Result { let current = current!(); @@ -56,7 +56,7 @@ pub fn sys_fcntl(fd: FileDescripter, cmd: i32, arg: u64) -> Result todo!(), } diff --git a/services/libs/jinux-std/src/syscall/ioctl.rs b/services/libs/jinux-std/src/syscall/ioctl.rs index eb09b5cdd..6d478a4c5 100644 --- a/services/libs/jinux-std/src/syscall/ioctl.rs +++ b/services/libs/jinux-std/src/syscall/ioctl.rs @@ -17,5 +17,5 @@ pub fn sys_ioctl(fd: FileDescripter, cmd: u32, arg: Vaddr) -> Result Result<()> { match filter { ProcessFilter::Any => { for process in process_table::get_all_processes() { - process.enqueue_signal(Box::new(signal.clone())); + process.enqueue_signal(Box::new(signal)); } } ProcessFilter::WithPid(pid) => { diff --git a/services/libs/jinux-std/src/syscall/link.rs b/services/libs/jinux-std/src/syscall/link.rs index 9fa82b153..a7ad770fb 100644 --- a/services/libs/jinux-std/src/syscall/link.rs +++ b/services/libs/jinux-std/src/syscall/link.rs @@ -30,14 +30,14 @@ pub fn sys_linkat( let current = current!(); let (old_dentry, new_dir_dentry, new_name) = { let old_pathname = old_pathname.to_string_lossy(); - if old_pathname.ends_with("/") { + if old_pathname.ends_with('/') { return_errno_with_message!(Errno::EPERM, "oldpath is dir"); } if old_pathname.is_empty() && !flags.contains(LinkFlags::AT_EMPTY_PATH) { return_errno_with_message!(Errno::ENOENT, "oldpath is empty"); } let new_pathname = new_pathname.to_string_lossy(); - if new_pathname.ends_with("/") { + if new_pathname.ends_with('/') { return_errno_with_message!(Errno::EPERM, "newpath is dir"); } if new_pathname.is_empty() { diff --git a/services/libs/jinux-std/src/syscall/mkdir.rs b/services/libs/jinux-std/src/syscall/mkdir.rs index ddf46a347..12213d201 100644 --- a/services/libs/jinux-std/src/syscall/mkdir.rs +++ b/services/libs/jinux-std/src/syscall/mkdir.rs @@ -33,7 +33,7 @@ pub fn sys_mkdirat( current.fs().read().lookup_dir_and_base_name(&fs_path)? }; let inode_mode = InodeMode::from_bits_truncate(mode); - let _ = dir_dentry.create(&name.trim_end_matches('/'), InodeType::Dir, inode_mode)?; + let _ = dir_dentry.create(name.trim_end_matches('/'), InodeType::Dir, inode_mode)?; Ok(SyscallReturn::Return(0)) } diff --git a/services/libs/jinux-std/src/syscall/mmap.rs b/services/libs/jinux-std/src/syscall/mmap.rs index 6443df3de..dbaef70a3 100644 --- a/services/libs/jinux-std/src/syscall/mmap.rs +++ b/services/libs/jinux-std/src/syscall/mmap.rs @@ -73,7 +73,7 @@ fn mmap_anonymous_vmo( debug_assert!(offset == 0); // TODO: implement features presented by other flags. - if option.typ() != MMapType::MapPrivate { + if option.typ() != MMapType::Private { panic!("Unsupported mmap flags {:?} now", option); } @@ -110,7 +110,7 @@ fn mmap_filebacked_vmo( ))? }; - let vmo = if option.typ() == MMapType::MapPrivate { + let vmo = if option.typ() == MMapType::Private { // map private VmoChildOptions::new_cow(page_cache_vmo, offset..(offset + len)).alloc()? } else { diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs index df44b0933..d245667aa 100644 --- a/services/libs/jinux-std/src/syscall/mod.rs +++ b/services/libs/jinux-std/src/syscall/mod.rs @@ -406,8 +406,8 @@ pub fn syscall_dispatch( SYS_SOCKETPAIR => syscall_handler!(4, sys_socketpair, args), SYS_SETSOCKOPT => syscall_handler!(5, sys_setsockopt, args), SYS_GETSOCKOPT => syscall_handler!(5, sys_getsockopt, args), - SYS_CLONE => syscall_handler!(5, sys_clone, args, context.clone()), - SYS_FORK => syscall_handler!(0, sys_fork, context.clone()), + SYS_CLONE => syscall_handler!(5, sys_clone, args, *context), + SYS_FORK => syscall_handler!(0, sys_fork, *context), SYS_EXECVE => syscall_handler!(3, sys_execve, args, context), SYS_EXIT => syscall_handler!(1, sys_exit, args), SYS_WAIT4 => syscall_handler!(3, sys_wait4, args), diff --git a/services/libs/jinux-std/src/syscall/poll.rs b/services/libs/jinux-std/src/syscall/poll.rs index c1cdebd2b..1bbdf3cb5 100644 --- a/services/libs/jinux-std/src/syscall/poll.rs +++ b/services/libs/jinux-std/src/syscall/poll.rs @@ -154,11 +154,7 @@ impl From for PollFd { impl From for c_pollfd { fn from(raw: PollFd) -> Self { - let fd = if let Some(fd) = raw.fd() { - fd as i32 - } else { - -1 - }; + let fd = if let Some(fd) = raw.fd() { fd } else { -1 }; let events = raw.events().bits() as i16; let revents = raw.revents().get().bits() as i16; Self { diff --git a/services/libs/jinux-std/src/syscall/read.rs b/services/libs/jinux-std/src/syscall/read.rs index 5a37e1f8e..f12ba29e3 100644 --- a/services/libs/jinux-std/src/syscall/read.rs +++ b/services/libs/jinux-std/src/syscall/read.rs @@ -17,5 +17,5 @@ pub fn sys_read(fd: FileDescripter, user_buf_addr: Vaddr, buf_len: usize) -> Res let mut read_buf = vec![0u8; buf_len]; let read_len = file.read(&mut read_buf)?; write_bytes_to_user(user_buf_addr, &read_buf)?; - return Ok(SyscallReturn::Return(read_len as _)); + Ok(SyscallReturn::Return(read_len as _)) } diff --git a/services/libs/jinux-std/src/syscall/rename.rs b/services/libs/jinux-std/src/syscall/rename.rs index 5b2cca0e7..2441d5567 100644 --- a/services/libs/jinux-std/src/syscall/rename.rs +++ b/services/libs/jinux-std/src/syscall/rename.rs @@ -43,7 +43,7 @@ pub fn sys_renameat( if new_pathname.is_empty() { return_errno_with_message!(Errno::ENOENT, "newpath is empty"); } - if new_pathname.ends_with("/") && old_dentry.inode_type() != InodeType::Dir { + if new_pathname.ends_with('/') && old_dentry.inode_type() != InodeType::Dir { return_errno_with_message!(Errno::ENOTDIR, "oldpath is not dir"); } let new_fs_path = FsPath::new(new_dirfd, new_pathname.as_ref().trim_end_matches('/'))?; diff --git a/services/libs/jinux-std/src/syscall/rmdir.rs b/services/libs/jinux-std/src/syscall/rmdir.rs index c642f59c2..5d91f8a1b 100644 --- a/services/libs/jinux-std/src/syscall/rmdir.rs +++ b/services/libs/jinux-std/src/syscall/rmdir.rs @@ -18,6 +18,6 @@ pub fn sys_rmdir(pathname_addr: Vaddr) -> Result { let fs_path = FsPath::try_from(pathname.as_ref())?; current.fs().read().lookup_dir_and_base_name(&fs_path)? }; - dir_dentry.rmdir(&name.trim_end_matches('/'))?; + dir_dentry.rmdir(name.trim_end_matches('/'))?; Ok(SyscallReturn::Return(0)) } diff --git a/services/libs/jinux-std/src/syscall/rt_sigaction.rs b/services/libs/jinux-std/src/syscall/rt_sigaction.rs index cab93e291..ef7346faa 100644 --- a/services/libs/jinux-std/src/syscall/rt_sigaction.rs +++ b/services/libs/jinux-std/src/syscall/rt_sigaction.rs @@ -26,7 +26,7 @@ pub fn sys_rt_sigaction( let current = current!(); let mut sig_dispositions = current.sig_dispositions().lock(); let old_action = sig_dispositions.get(sig_num); - let old_action_c = old_action.to_c(); + let old_action_c = old_action.as_c_type(); if old_sig_action_addr != 0 { write_val_to_user(old_sig_action_addr, &old_action_c)?; } diff --git a/services/libs/jinux-std/src/syscall/rt_sigreturn.rs b/services/libs/jinux-std/src/syscall/rt_sigreturn.rs index f36f0eb71..a42eb4ff6 100644 --- a/services/libs/jinux-std/src/syscall/rt_sigreturn.rs +++ b/services/libs/jinux-std/src/syscall/rt_sigreturn.rs @@ -13,7 +13,7 @@ pub fn sys_rt_sigreturn(context: &mut UserContext) -> Result { let current_thread = current_thread!(); let posix_thread = current_thread.as_posix_thread().unwrap(); let mut sig_context = posix_thread.sig_context().lock(); - if None == *sig_context { + if (*sig_context).is_none() { return_errno_with_message!(Errno::EINVAL, "sigretrun should not been called"); } let sig_context_addr = sig_context.unwrap(); diff --git a/services/libs/jinux-std/src/syscall/select.rs b/services/libs/jinux-std/src/syscall/select.rs index b4fa4375c..9ab34ba75 100644 --- a/services/libs/jinux-std/src/syscall/select.rs +++ b/services/libs/jinux-std/src/syscall/select.rs @@ -100,9 +100,15 @@ fn do_select( }; // Clear up the three input fd_set's, which will be used for output as well - readfds.as_mut().map_or((), |fds| fds.clear()); - writefds.as_mut().map_or((), |fds| fds.clear()); - exceptfds.as_mut().map_or((), |fds| fds.clear()); + if let Some(fds) = readfds.as_mut() { + fds.clear(); + } + if let Some(fds) = writefds.as_mut() { + fds.clear(); + } + if let Some(fds) = exceptfds.as_mut() { + fds.clear(); + } // Do the poll syscall that is equivalent to the select syscall let num_revents = do_poll(&poll_fds, timeout)?; diff --git a/services/libs/jinux-std/src/syscall/symlink.rs b/services/libs/jinux-std/src/syscall/symlink.rs index d264426b2..b2b205eb4 100644 --- a/services/libs/jinux-std/src/syscall/symlink.rs +++ b/services/libs/jinux-std/src/syscall/symlink.rs @@ -34,7 +34,7 @@ pub fn sys_symlinkat( if linkpath.is_empty() { return_errno_with_message!(Errno::ENOENT, "linkpath is empty"); } - if linkpath.ends_with("/") { + if linkpath.ends_with('/') { return_errno_with_message!(Errno::EISDIR, "linkpath is dir"); } let fs_path = FsPath::new(dirfd, linkpath.as_ref())?; diff --git a/services/libs/jinux-std/src/syscall/unlink.rs b/services/libs/jinux-std/src/syscall/unlink.rs index 5f5cbfa8e..4823aae7a 100644 --- a/services/libs/jinux-std/src/syscall/unlink.rs +++ b/services/libs/jinux-std/src/syscall/unlink.rs @@ -31,7 +31,7 @@ pub fn sys_unlinkat( if pathname.is_empty() { return_errno_with_message!(Errno::ENOENT, "path is empty"); } - if pathname.ends_with("/") { + if pathname.ends_with('/') { return_errno_with_message!(Errno::EISDIR, "unlink on directory"); } let fs_path = FsPath::new(dirfd, pathname.as_ref())?; diff --git a/services/libs/jinux-std/src/syscall/write.rs b/services/libs/jinux-std/src/syscall/write.rs index d1ffcb57a..589b66bac 100644 --- a/services/libs/jinux-std/src/syscall/write.rs +++ b/services/libs/jinux-std/src/syscall/write.rs @@ -24,7 +24,7 @@ pub fn sys_write( let file_table = current.file_table().lock(); let file = file_table.get_file(fd)?; let mut buffer = vec![0u8; user_buf_len]; - read_bytes_from_user(user_buf_ptr as usize, &mut buffer)?; + read_bytes_from_user(user_buf_ptr, &mut buffer)?; debug!("write content = {:?}", buffer); let write_len = file.write(&buffer)?; Ok(SyscallReturn::Return(write_len as _)) diff --git a/services/libs/jinux-std/src/thread/exception.rs b/services/libs/jinux-std/src/thread/exception.rs index c62b8b7f2..9768d75f7 100644 --- a/services/libs/jinux-std/src/thread/exception.rs +++ b/services/libs/jinux-std/src/thread/exception.rs @@ -4,7 +4,7 @@ use crate::vm::page_fault_handler::PageFaultHandler; use crate::{prelude::*, process::signal::signals::fault::FaultSignal}; /// We can't handle most exceptions, just send self a fault signal before return to user space. -pub fn handle_exception(context: &mut UserContext) { +pub fn handle_exception(context: &UserContext) { let trap_info = context.trap_information(); let exception = CpuException::to_cpu_exception(trap_info.id as u16).unwrap(); log_trap_info(exception, trap_info); @@ -12,10 +12,10 @@ pub fn handle_exception(context: &mut UserContext) { let root_vmar = current.root_vmar(); match *exception { - PAGE_FAULT => handle_page_fault(&trap_info), + PAGE_FAULT => handle_page_fault(trap_info), _ => { // We current do nothing about other exceptions - generate_fault_signal(&trap_info); + generate_fault_signal(trap_info); } } } diff --git a/services/libs/jinux-std/src/thread/mod.rs b/services/libs/jinux-std/src/thread/mod.rs index bda751824..34c5a692c 100644 --- a/services/libs/jinux-std/src/thread/mod.rs +++ b/services/libs/jinux-std/src/thread/mod.rs @@ -91,6 +91,8 @@ impl Thread { self.tid } + // The return type must be borrowed box, otherwise the downcast_ref will fail + #[allow(clippy::borrowed_box)] pub fn data(&self) -> &Box { &self.data } diff --git a/services/libs/jinux-std/src/thread/thread_table.rs b/services/libs/jinux-std/src/thread/thread_table.rs index 35f6b7059..b1ae4463f 100644 --- a/services/libs/jinux-std/src/thread/thread_table.rs +++ b/services/libs/jinux-std/src/thread/thread_table.rs @@ -16,5 +16,5 @@ pub fn remove_thread(tid: Tid) { } pub fn tid_to_thread(tid: Tid) -> Option> { - THREAD_TABLE.lock().get(&tid).map(|thread| thread.clone()) + THREAD_TABLE.lock().get(&tid).cloned() } diff --git a/services/libs/jinux-std/src/time/system_time.rs b/services/libs/jinux-std/src/time/system_time.rs index f7ae815bf..b885aeca7 100644 --- a/services/libs/jinux-std/src/time/system_time.rs +++ b/services/libs/jinux-std/src/time/system_time.rs @@ -33,13 +33,13 @@ impl SystemTime { /// Add a duration to self. If the result does not exceed inner bounds return Some(t), else return None. pub fn checked_add(&self, duration: Duration) -> Option { let duration = convert_to_time_duration(duration); - self.0.checked_add(duration).map(|inner| SystemTime(inner)) + self.0.checked_add(duration).map(SystemTime) } /// Substract a duration from self. If the result does not exceed inner bounds return Some(t), else return None. pub fn checked_sub(&self, duration: Duration) -> Option { let duration = convert_to_time_duration(duration); - self.0.checked_sub(duration).map(|inner| SystemTime(inner)) + self.0.checked_sub(duration).map(SystemTime) } /// Returns the duration since an earlier time. Return error if `earlier` is later than self. diff --git a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs b/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs index cef1dd617..17e277f40 100644 --- a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs +++ b/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs @@ -140,7 +140,7 @@ impl Vmar { /// The method requires the Dup right. pub fn dup(&self) -> Result { self.check_rights(Rights::DUP)?; - Ok(Vmar(self.0.clone(), self.1.clone())) + Ok(Vmar(self.0.clone(), self.1)) } /// Given a map size, returns the possible map address without doing actual allocation. diff --git a/services/libs/jinux-std/src/vm/vmar/mod.rs b/services/libs/jinux-std/src/vm/vmar/mod.rs index a07851cfe..fd7f5f71b 100644 --- a/services/libs/jinux-std/src/vm/vmar/mod.rs +++ b/services/libs/jinux-std/src/vm/vmar/mod.rs @@ -140,11 +140,7 @@ impl Vmar_ { } fn is_root_vmar(&self) -> bool { - if let Some(_) = self.parent.upgrade() { - false - } else { - true - } + self.parent.upgrade().is_none() } pub fn protect(&self, perms: VmPerms, range: Range) -> Result<()> { @@ -165,7 +161,7 @@ impl Vmar_ { } } - for (_, child_vmar_) in &self.inner.lock().child_vmar_s { + for child_vmar_ in self.inner.lock().child_vmar_s.values() { let child_vmar_range = child_vmar_.range(); if is_intersected(&range, &child_vmar_range) { let intersected_range = get_intersected_range(&range, &child_vmar_range); @@ -185,17 +181,17 @@ impl Vmar_ { assert!(protected_range.end <= self.base + self.size); // The protected range should not interstect with any free region - for (_, free_region) in &self.inner.lock().free_regions { - if is_intersected(&free_region.range, &protected_range) { + for free_region in self.inner.lock().free_regions.values() { + if is_intersected(&free_region.range, protected_range) { return_errno_with_message!(Errno::EACCES, "protected range is not fully mapped"); } } // if the protected range intersects with child vmar_, child vmar_ is responsible to do the check. - for (_, child_vmar_) in &self.inner.lock().child_vmar_s { + for child_vmar_ in self.inner.lock().child_vmar_s.values() { let child_range = child_vmar_.range(); - if is_intersected(&child_range, &protected_range) { - let intersected_range = get_intersected_range(&child_range, &protected_range); + if is_intersected(&child_range, protected_range) { + let intersected_range = get_intersected_range(&child_range, protected_range); child_vmar_.check_protected_range(&intersected_range)?; } } @@ -263,7 +259,7 @@ impl Vmar_ { inner.child_vmar_s.clear(); inner.free_regions.append(&mut free_regions); - for (_, vm_mapping) in &inner.vm_mappings { + for vm_mapping in inner.vm_mappings.values() { vm_mapping.unmap(&vm_mapping.range(), true)?; let free_region = FreeRegion::new(vm_mapping.range()); free_regions.insert(free_region.start(), free_region); @@ -296,7 +292,7 @@ impl Vmar_ { let mut mappings_to_remove = BTreeSet::new(); let mut mappings_to_append = BTreeMap::new(); - for (_, vm_mapping) in &inner.vm_mappings { + for vm_mapping in inner.vm_mappings.values() { let vm_mapping_range = vm_mapping.range(); if is_intersected(&vm_mapping_range, &range) { let intersected_range = get_intersected_range(&vm_mapping_range, &range); @@ -501,7 +497,7 @@ impl Vmar_ { fn check_vmo_overwrite(&self, vmo_range: Range, can_overwrite: bool) -> Result<()> { let inner = self.inner.lock(); - for (_, child_vmar) in &inner.child_vmar_s { + for child_vmar in inner.child_vmar_s.values() { let child_vmar_range = child_vmar.range(); if is_intersected(&vmo_range, &child_vmar_range) { return_errno_with_message!( @@ -578,7 +574,7 @@ impl Vmar_ { } drop(inner); self.trim_existing_mappings(map_range)?; - return Ok(offset); + Ok(offset) } else { // Otherwise, the vmo in a single region let (free_region_base, offset) = @@ -591,7 +587,7 @@ impl Vmar_ { regions_after_split.into_iter().for_each(|region| { inner.free_regions.insert(region.start(), region); }); - return Ok(offset); + Ok(offset) } } @@ -609,7 +605,7 @@ impl Vmar_ { let mut inner = self.inner.lock(); let mut mappings_to_remove = BTreeSet::new(); let mut mappings_to_append = BTreeMap::new(); - for (_, vm_mapping) in &inner.vm_mappings { + for vm_mapping in inner.vm_mappings.values() { vm_mapping.trim_mapping( &trim_range, &mut mappings_to_remove, diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs index 994c94880..87e179473 100644 --- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs +++ b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs @@ -270,7 +270,7 @@ impl VmMapping { let map_to_addr = self.map_to_addr(); let map_size = self.map_size(); let range = self.range(); - if !is_intersected(&range, &trim_range) { + if !is_intersected(&range, trim_range) { return Ok(()); } if trim_range.start <= map_to_addr && trim_range.end >= map_to_addr + map_size { @@ -334,7 +334,7 @@ impl VmMappingInner { let map_addr = self.page_map_addr(page_idx); let vm_perm = { - let mut perm = self.page_perms.get(&page_idx).unwrap().clone(); + let mut perm = *self.page_perms.get(&page_idx).unwrap(); if is_readonly { debug_assert!(vmo.is_cow_child()); perm -= VmPerm::W; @@ -345,7 +345,7 @@ impl VmMappingInner { let vm_map_options = { let mut options = VmMapOptions::new(); options.addr(Some(map_addr)); - options.perm(vm_perm.clone()); + options.perm(vm_perm); options }; @@ -440,8 +440,8 @@ impl VmMappingInner { self.map_to_addr = vaddr; let old_vmo_offset = self.vmo_offset; - self.vmo_offset = self.vmo_offset + trim_size; - self.map_size = self.map_size - trim_size; + self.vmo_offset += trim_size; + self.map_size -= trim_size; for page_idx in old_vmo_offset / PAGE_SIZE..self.vmo_offset / PAGE_SIZE { self.page_perms.remove(&page_idx); if self.mapped_pages.remove(&page_idx) { @@ -477,7 +477,7 @@ impl VmMappingInner { fn check_perm(&self, page_idx: &usize, perm: &VmPerm) -> Result<()> { let page_perm = self .page_perms - .get(&page_idx) + .get(page_idx) .ok_or(Error::with_message(Errno::EINVAL, "invalid page idx"))?; if !page_perm.contains(*perm) { @@ -637,15 +637,15 @@ impl VmarMapOptions { fn check_overwrite(&self) -> Result<()> { if self.can_overwrite { // if can_overwrite is set, the offset cannot be None - debug_assert!(self.offset != None); - if self.offset == None { + debug_assert!(self.offset.is_some()); + if self.offset.is_none() { return_errno_with_message!( Errno::EINVAL, "offset can not be none when can overwrite is true" ); } } - if self.offset == None { + if self.offset.is_none() { // if does not specify the offset, we assume the map can always find suitable free region. // FIXME: is this always true? return Ok(()); diff --git a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs b/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs index 2b30c69eb..9eb0c6b34 100644 --- a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs +++ b/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs @@ -133,7 +133,7 @@ impl Vmo { /// The method requires the Dup right. pub fn dup(&self) -> Result { self.check_rights(Rights::DUP)?; - Ok(Self(self.0.clone(), self.1.clone())) + Ok(Self(self.0.clone(), self.1)) } /// Restricts the access rights given the mask. diff --git a/services/libs/jinux-std/src/vm/vmo/mod.rs b/services/libs/jinux-std/src/vm/vmo/mod.rs index ada102409..14aef0a29 100644 --- a/services/libs/jinux-std/src/vm/vmo/mod.rs +++ b/services/libs/jinux-std/src/vm/vmo/mod.rs @@ -230,7 +230,7 @@ impl VmoInner { } fn should_share_frame_with_parent(&self, write_page: bool) -> bool { - !self.is_cow || (self.is_cow && !write_page) + !self.is_cow || !write_page } } @@ -343,7 +343,7 @@ impl Vmo_ { } pub fn flags(&self) -> VmoFlags { - self.flags.clone() + self.flags } } diff --git a/services/libs/jinux-std/src/vm/vmo/static_cap.rs b/services/libs/jinux-std/src/vm/vmo/static_cap.rs index c96c1c520..0b4a6dcc8 100644 --- a/services/libs/jinux-std/src/vm/vmo/static_cap.rs +++ b/services/libs/jinux-std/src/vm/vmo/static_cap.rs @@ -134,7 +134,7 @@ impl Vmo> { /// The method requires the Dup right. #[require(R > Dup)] pub fn dup(&self) -> Result { - Ok(Vmo(self.0.clone(), self.1.clone())) + Ok(Vmo(self.0.clone(), self.1)) } /// Strict the access rights. diff --git a/services/libs/jinux-util/src/slot_vec.rs b/services/libs/jinux-util/src/slot_vec.rs index 027f3faec..3fc35f506 100644 --- a/services/libs/jinux-util/src/slot_vec.rs +++ b/services/libs/jinux-util/src/slot_vec.rs @@ -13,7 +13,7 @@ pub struct SlotVec { impl SlotVec { /// New an empty vector. - pub fn new() -> Self { + pub const fn new() -> Self { Self { slots: Vec::new(), num_occupied: 0, @@ -120,7 +120,7 @@ impl Clone for SlotVec { fn clone(&self) -> Self { Self { slots: self.slots.clone(), - num_occupied: self.num_occupied.clone(), + num_occupied: self.num_occupied, } } } diff --git a/services/libs/keyable-arc/src/lib.rs b/services/libs/keyable-arc/src/lib.rs index f6a5571a1..d768daf2f 100644 --- a/services/libs/keyable-arc/src/lib.rs +++ b/services/libs/keyable-arc/src/lib.rs @@ -145,21 +145,21 @@ impl Deref for KeyableArc { #[inline] fn deref(&self) -> &T { - &*self.0 + &self.0 } } impl AsRef for KeyableArc { #[inline] fn as_ref(&self) -> &T { - &**self + self } } impl Borrow for KeyableArc { #[inline] fn borrow(&self) -> &T { - &**self + self } } @@ -170,10 +170,10 @@ impl From> for KeyableArc { } } -impl Into> for KeyableArc { +impl From> for Arc { #[inline] - fn into(self) -> Arc { - self.0 + fn from(value: KeyableArc) -> Self { + value.0 } } @@ -230,6 +230,7 @@ impl KeyableWeak { /// Constructs a new `KeyableWeak`, without allocating any memory. /// Calling `upgrade` on the return value always gives `None`. #[inline] + #[allow(clippy::new_without_default)] pub fn new() -> Self { Self(Weak::new()) } @@ -300,10 +301,9 @@ impl From> for KeyableWeak { } } -impl Into> for KeyableWeak { - #[inline] - fn into(self) -> Weak { - self.0 +impl From> for Weak { + fn from(value: KeyableWeak) -> Self { + value.0 } } diff --git a/services/libs/typeflags-util/src/assert.rs b/services/libs/typeflags-util/src/assert.rs index f4458a3ec..a9f0afe55 100644 --- a/services/libs/typeflags-util/src/assert.rs +++ b/services/libs/typeflags-util/src/assert.rs @@ -7,7 +7,7 @@ pub type AssertTypeSame = >::Output; #[macro_export] macro_rules! assert_type_same { ($lhs:ty, $rhs:ty) => { - const _: $crate::assert::AssertTypeSame<$lhs, $rhs> = crate::True; + const _: $crate::assert::AssertTypeSame<$lhs, $rhs> = $crate::True; }; } diff --git a/services/libs/typeflags-util/src/set.rs b/services/libs/typeflags-util/src/set.rs index a9ee0e211..4e21c92cb 100644 --- a/services/libs/typeflags-util/src/set.rs +++ b/services/libs/typeflags-util/src/set.rs @@ -17,6 +17,7 @@ pub trait Set {} pub struct Cons(PhantomData<(T, S)>); impl Cons { + #[allow(clippy::new_without_default)] pub fn new() -> Self { Cons(PhantomData) } diff --git a/services/libs/typeflags/src/flag_set.rs b/services/libs/typeflags/src/flag_set.rs index 1045fdde3..2b1fd4089 100644 --- a/services/libs/typeflags/src/flag_set.rs +++ b/services/libs/typeflags/src/flag_set.rs @@ -5,8 +5,8 @@ use syn::Expr; use crate::type_flag::TypeFlagDef; -const EMPTY_SET_NAME: &'static str = "::typeflags_util::Nil"; -const SET_NAME: &'static str = "::typeflags_util::Cons"; +const EMPTY_SET_NAME: &str = "::typeflags_util::Nil"; +const SET_NAME: &str = "::typeflags_util::Cons"; /// A flagSet represent the combination of differnt flag item. /// e.g. [Read, Write], [Read], [] are all flag sets. @@ -27,26 +27,6 @@ impl FlagSet { self.items.push(flag_item); } - /// the flag set string. debug use. - pub fn to_string(&self) -> String { - if self.items.len() == 0 { - return EMPTY_SET_NAME.to_string(); - } - - let mut res = EMPTY_SET_NAME.to_string(); - - for item in self.items.iter() { - let replace_set = format!( - "{}<{}, {}>", - SET_NAME, - item.ident.to_string(), - EMPTY_SET_NAME - ); - res = res.replace(EMPTY_SET_NAME, &replace_set); - } - res - } - /// the tokens represents the flag set type name pub fn type_name_tokens(&self) -> TokenStream { let mut res = quote!(::typeflags_util::Nil); @@ -110,10 +90,7 @@ impl FlagSet { pub fn contains_type(&self, type_ident: &Ident) -> bool { let type_name = type_ident.to_string(); - self.items - .iter() - .position(|item| item.ident.to_string() == type_name) - .is_some() + self.items.iter().any(|item| item.ident == type_name) } pub fn contains_set(&self, other_set: &FlagSet) -> bool { @@ -122,7 +99,7 @@ impl FlagSet { return false; } } - return true; + true } /// The token stream inside macro definition. We will generate a token stream for each permutation of items @@ -177,9 +154,9 @@ pub fn generate_flag_sets(type_flag_def: &TypeFlagDef) -> Vec { for i in 0..limit { let mut flag_set = FlagSet::new(); - for j in 0..flag_item_num { + for (j, item_j) in flag_items.iter().enumerate().take(flag_item_num) { if (i >> j) & 0x1 == 1usize { - flag_set.push_item(flag_items[j].clone()); + flag_set.push_item(item_j.clone()); } } res.push(flag_set); diff --git a/services/libs/typeflags/src/type_flag.rs b/services/libs/typeflags/src/type_flag.rs index e5f4dda71..0d4366f38 100644 --- a/services/libs/typeflags/src/type_flag.rs +++ b/services/libs/typeflags/src/type_flag.rs @@ -106,7 +106,7 @@ impl TypeFlagDef { /// get item at specific position pub fn get_item(&self, index: usize) -> Option { - self.items.iter().nth(index).map(|item| item.clone()) + self.items.iter().nth(index).cloned() } /// the trait ident @@ -147,9 +147,9 @@ impl TypeFlagItem { impl TypeFlagDef { /// Debug use. Print all item's name. pub fn debug(&self) { - println!("{}", self.ident.to_string()); + println!("{}", self.ident); for type_flag_item in &self.items { - println!("{}", type_flag_item.ident.to_string()); + println!("{}", type_flag_item.ident); } } } diff --git a/services/libs/typeflags/src/util.rs b/services/libs/typeflags/src/util.rs index 47631154d..fcc9d53d8 100644 --- a/services/libs/typeflags/src/util.rs +++ b/services/libs/typeflags/src/util.rs @@ -17,7 +17,7 @@ pub fn expand_type_flag(type_flags_def: &TypeFlagDef) -> TokenStream { let impl_same_as_tokens = impl_same_as(type_flags_def); all_tokens.append_all(impl_same_as_tokens); - let flag_sets = generate_flag_sets(&type_flags_def); + let flag_sets = generate_flag_sets(type_flags_def); flag_sets.iter().for_each(|flag_set| { let impl_main_trait_tokens = flag_set.impl_main_trait_tokens(type_flags_def); all_tokens.append_all(impl_main_trait_tokens);