size_of and align_of are part of the prelude nowadays

This commit is contained in:
bjorn3
2026-04-06 15:19:52 +02:00
committed by Jeremy Soller
parent 2e784dfe46
commit 654ee6ca3e
42 changed files with 137 additions and 166 deletions
+1 -2
View File
@@ -1,5 +1,4 @@
use alloc::boxed::Box;
use core::mem;
use super::{find_sdt, sdt::Sdt};
use crate::{
@@ -56,7 +55,7 @@ impl Gtdt {
}
pub fn new(sdt: &'static Sdt) -> Option<&'static Gtdt> {
if &sdt.signature == b"GTDT" && sdt.length as usize >= mem::size_of::<Gtdt>() {
if &sdt.signature == b"GTDT" && sdt.length as usize >= size_of::<Gtdt>() {
Some(unsafe { &*((sdt as *const Sdt) as *const Gtdt) })
} else {
None
+2 -4
View File
@@ -1,6 +1,4 @@
use core::{mem, ptr};
use core::ptr::{read_volatile, write_volatile};
use core::ptr::{self, read_volatile, write_volatile};
#[cfg(not(target_arch = "x86"))]
use crate::memory::{RmmA, RmmArch};
@@ -37,7 +35,7 @@ impl Hpet {
}
pub fn new(sdt: &'static Sdt) -> Option<Hpet> {
if &sdt.signature == b"HPET" && sdt.length as usize >= mem::size_of::<Hpet>() {
if &sdt.signature == b"HPET" && sdt.length as usize >= size_of::<Hpet>() {
let s = unsafe { ptr::read((sdt as *const Sdt) as *const Hpet) };
if s.base_address.address_space == 0 {
unsafe { s.map() };
+6 -6
View File
@@ -1,4 +1,4 @@
use core::{cell::SyncUnsafeCell, mem};
use core::cell::SyncUnsafeCell;
use super::sdt::Sdt;
use crate::find_one_sdt;
@@ -179,7 +179,7 @@ impl Iterator for MadtIter {
if self.i + entry_len <= self.sdt.data_len() {
let item = match entry_type {
0x0 => {
if entry_len == mem::size_of::<MadtLocalApic>() + 2 {
if entry_len == size_of::<MadtLocalApic>() + 2 {
MadtEntry::LocalApic(unsafe {
&*((self.sdt.data_address() + self.i + 2) as *const MadtLocalApic)
})
@@ -188,7 +188,7 @@ impl Iterator for MadtIter {
}
}
0x1 => {
if entry_len == mem::size_of::<MadtIoApic>() + 2 {
if entry_len == size_of::<MadtIoApic>() + 2 {
MadtEntry::IoApic(unsafe {
&*((self.sdt.data_address() + self.i + 2) as *const MadtIoApic)
})
@@ -197,7 +197,7 @@ impl Iterator for MadtIter {
}
}
0x2 => {
if entry_len == mem::size_of::<MadtIntSrcOverride>() + 2 {
if entry_len == size_of::<MadtIntSrcOverride>() + 2 {
MadtEntry::IntSrcOverride(unsafe {
&*((self.sdt.data_address() + self.i + 2)
as *const MadtIntSrcOverride)
@@ -207,7 +207,7 @@ impl Iterator for MadtIter {
}
}
0xB => {
if entry_len >= mem::size_of::<MadtGicc>() + 2 {
if entry_len >= size_of::<MadtGicc>() + 2 {
MadtEntry::Gicc(unsafe {
&*((self.sdt.data_address() + self.i + 2) as *const MadtGicc)
})
@@ -216,7 +216,7 @@ impl Iterator for MadtIter {
}
}
0xC => {
if entry_len >= mem::size_of::<MadtGicd>() + 2 {
if entry_len >= size_of::<MadtGicd>() + 2 {
MadtEntry::Gicd(unsafe {
&*((self.sdt.data_address() + self.i + 2) as *const MadtGicd)
})
+1 -1
View File
@@ -43,7 +43,7 @@ pub fn get_sdt(sdt_address: PhysicalAddress, mapper: &mut KernelMapper<true>) ->
let sdt;
unsafe {
const SDT_SIZE: usize = core::mem::size_of::<Sdt>();
const SDT_SIZE: usize = size_of::<Sdt>();
map_linearly(sdt_address, SDT_SIZE, mapper);
sdt = &*(RmmA::phys_to_virt(sdt_address).data() as *const Sdt);
+2 -2
View File
@@ -1,5 +1,5 @@
use alloc::boxed::Box;
use core::{convert::TryFrom, mem};
use core::convert::TryFrom;
use rmm::PhysicalAddress;
use super::{rxsdt::Rxsdt, sdt::Sdt};
@@ -37,7 +37,7 @@ pub struct RsdtIter {
impl Iterator for RsdtIter {
type Item = PhysicalAddress;
fn next(&mut self) -> Option<Self::Item> {
if self.i < self.sdt.data_len() / mem::size_of::<u32>() {
if self.i < self.sdt.data_len() / size_of::<u32>() {
let item = unsafe {
(self.sdt.data_address() as *const u32)
.add(self.i)
+2 -4
View File
@@ -1,5 +1,3 @@
use core::mem;
#[derive(Copy, Clone, Debug)]
#[repr(C, packed)]
pub struct Sdt {
@@ -17,13 +15,13 @@ pub struct Sdt {
impl Sdt {
/// Get the address of this tables data
pub fn data_address(&self) -> usize {
self as *const _ as usize + mem::size_of::<Sdt>()
self as *const _ as usize + size_of::<Sdt>()
}
/// Get the length of this tables data
pub fn data_len(&self) -> usize {
let total_size = self.length as usize;
let header_size = mem::size_of::<Sdt>();
let header_size = size_of::<Sdt>();
total_size.saturating_sub(header_size)
}
}
+1 -3
View File
@@ -1,5 +1,3 @@
use core::mem;
use super::{find_sdt, sdt::Sdt, GenericAddressStructure};
use crate::{
device::serial::COM1,
@@ -133,7 +131,7 @@ impl Spcr {
}
pub fn new(sdt: &'static Sdt) -> Option<&'static Spcr> {
if &sdt.signature == b"SPCR" && sdt.length as usize >= mem::size_of::<Spcr>() {
if &sdt.signature == b"SPCR" && sdt.length as usize >= size_of::<Spcr>() {
Some(unsafe { &*((sdt as *const Sdt) as *const Spcr) })
} else {
None
+2 -2
View File
@@ -1,5 +1,5 @@
use alloc::boxed::Box;
use core::{convert::TryFrom, mem};
use core::convert::TryFrom;
use rmm::PhysicalAddress;
use super::{rxsdt::Rxsdt, sdt::Sdt};
@@ -37,7 +37,7 @@ pub struct XsdtIter {
impl Iterator for XsdtIter {
type Item = PhysicalAddress;
fn next(&mut self) -> Option<Self::Item> {
if self.i < self.sdt.data_len() / mem::size_of::<u64>() {
if self.i < self.sdt.data_len() / size_of::<u64>() {
let item = unsafe {
core::ptr::read_unaligned((self.sdt.data_address() as *const u64).add(self.i))
};
+3 -3
View File
@@ -1,4 +1,4 @@
use core::{arch::asm, mem};
use core::arch::asm;
pub struct StackTrace {
pub fp: usize,
@@ -11,7 +11,7 @@ impl StackTrace {
unsafe {
let fp: usize;
asm!("mov {}, fp", out(reg) fp);
let pc_ptr = fp.checked_add(mem::size_of::<usize>())?;
let pc_ptr = fp.checked_add(size_of::<usize>())?;
Some(StackTrace {
fp,
pc_ptr: pc_ptr as *const usize,
@@ -22,7 +22,7 @@ impl StackTrace {
pub unsafe fn next(self) -> Option<Self> {
unsafe {
let fp = *(self.fp as *const usize);
let pc_ptr = fp.checked_add(mem::size_of::<usize>())?;
let pc_ptr = fp.checked_add(size_of::<usize>())?;
Some(StackTrace {
fp: fp,
pc_ptr: pc_ptr as *const usize,
+1 -1
View File
@@ -24,7 +24,7 @@ pub static CLINT: Mutex<Option<Clint>> = Mutex::new(None);
impl Clint {
pub fn new(addr: *mut u8, size: usize, freq: usize) -> Self {
assert!(size >= core::mem::size_of::<ClintRegs>());
assert!(size >= size_of::<ClintRegs>());
Self {
regs: unsafe { (addr as *mut ClintRegs).as_mut().unwrap() },
freq: freq as u64
+1 -1
View File
@@ -37,7 +37,7 @@ struct PlicRegs {
const _: () = assert!(0x1000 == mem::offset_of!(PlicRegs, pending));
const _: () = assert!(0x2000 == mem::offset_of!(PlicRegs, enable));
const _: () = assert!(0x20_0000 == mem::offset_of!(PlicRegs, thresholds));
const _: () = assert!(0x1000 == mem::size_of::<InterruptThresholdRegs>());
const _: () = assert!(0x1000 == size_of::<InterruptThresholdRegs>());
impl PlicRegs {
pub fn set_priority(self: &mut Self, irq: usize, priority: usize) {
-1
View File
@@ -1,5 +1,4 @@
use crate::{memory::ArchIntCtx, panic, syscall::IntRegisters};
use core::mem::size_of;
#[derive(Default)]
#[repr(C)]
+5 -5
View File
@@ -1,4 +1,4 @@
use core::{arch::asm, mem};
use core::arch::asm;
pub struct StackTrace {
pub fp: usize,
@@ -12,8 +12,8 @@ impl StackTrace {
let fp: usize;
asm!("mv {}, fp", out(reg) fp);
let pc_ptr = fp.checked_sub(mem::size_of::<usize>())?;
let fp = pc_ptr.checked_sub(mem::size_of::<usize>())?;
let pc_ptr = fp.checked_sub(size_of::<usize>())?;
let fp = pc_ptr.checked_sub(size_of::<usize>())?;
Some(StackTrace {
fp,
pc_ptr: pc_ptr as *const usize,
@@ -24,8 +24,8 @@ impl StackTrace {
pub unsafe fn next(self) -> Option<Self> {
unsafe {
let fp = *(self.fp as *const usize);
let pc_ptr = fp.checked_sub(mem::size_of::<usize>())?;
let fp = pc_ptr.checked_sub(mem::size_of::<usize>())?;
let pc_ptr = fp.checked_sub(size_of::<usize>())?;
let fp = pc_ptr.checked_sub(size_of::<usize>())?;
Some(StackTrace {
fp: fp,
pc_ptr: pc_ptr as *const usize,
+1 -3
View File
@@ -1,7 +1,5 @@
#![allow(unused_imports)]
use core::mem::size_of;
use spin::Once;
use x86::controlregs::{Cr4, Xcr0};
@@ -115,7 +113,7 @@ pub unsafe fn early_init(bsp: bool) {
// 16 * size_of::<u128>() is well below usize::MAX
#[expect(clippy::arithmetic_side_effects)]
if state.size() as usize != 16 * core::mem::size_of::<u128>() {
if state.size() as usize != 16 * size_of::<u128>() {
warn!("Unusual AVX state size {}", state.size());
}
+1 -1
View File
@@ -510,7 +510,7 @@ macro_rules! interrupt_error {
"iretq;",
inner = sym inner,
rax_offset = const(::core::mem::size_of::<$crate::interrupt::handler::PreservedRegisters>() + ::core::mem::size_of::<$crate::interrupt::handler::ScratchRegisters>() - 8),
rax_offset = const(size_of::<$crate::interrupt::handler::PreservedRegisters>() + size_of::<$crate::interrupt::handler::ScratchRegisters>() - 8),
);
}
};
+1 -1
View File
@@ -273,7 +273,7 @@ pub unsafe fn install_idt(idt_ptr: *mut Idt) {
}
let idtr: DescriptorTablePointer<X86IdtEntry> = DescriptorTablePointer {
limit: (idt.entries.len() * mem::size_of::<IdtEntry>() - 1) as u16,
limit: (idt.entries.len() * size_of::<IdtEntry>() - 1) as u16,
base: idt.entries.as_ptr() as *const X86IdtEntry,
};
+2 -4
View File
@@ -1,5 +1,3 @@
use core::mem;
pub struct StackTrace {
pub fp: usize,
pub pc_ptr: *const usize,
@@ -14,7 +12,7 @@ impl StackTrace {
core::arch::asm!("mov {}, ebp", out(reg) fp);
#[cfg(target_arch = "x86_64")]
core::arch::asm!("mov {}, rbp", out(reg) fp);
let pc_ptr = fp.checked_add(mem::size_of::<usize>())?;
let pc_ptr = fp.checked_add(size_of::<usize>())?;
Some(Self {
fp,
pc_ptr: pc_ptr as *const usize,
@@ -25,7 +23,7 @@ impl StackTrace {
pub unsafe fn next(self) -> Option<Self> {
unsafe {
let fp = *(self.fp as *const usize);
let pc_ptr = fp.checked_add(mem::size_of::<usize>())?;
let pc_ptr = fp.checked_add(size_of::<usize>())?;
Some(Self {
fp,
pc_ptr: pc_ptr as *const usize,
-1
View File
@@ -149,7 +149,6 @@ macro_rules! int_like {
#[test]
fn test() {
use ::core::sync::atomic::AtomicUsize;
use core::mem::size_of;
// Generate type `usize_like`.
int_like!(UsizeLike, usize);
+8 -8
View File
@@ -4,7 +4,7 @@ use crate::{
percpu::PercpuBlock,
syscall::FloatRegisters,
};
use core::{mem, mem::offset_of, ptr, sync::atomic::AtomicBool};
use core::{mem::offset_of, ptr, sync::atomic::AtomicBool};
use spin::Once;
use syscall::{EnvRegisters, Result};
@@ -92,7 +92,7 @@ impl Context {
) {
let mut stack_top = stack.initial_top();
const INT_REGS_SIZE: usize = core::mem::size_of::<InterruptStack>();
const INT_REGS_SIZE: usize = size_of::<InterruptStack>();
if userspace_allowed {
unsafe {
@@ -230,9 +230,9 @@ unsafe extern "C" fn fp_save(float_regs: &mut FloatRegisters) {
"str x9, [{3}]",
"mrs x9, fpsr",
"str x9, [{3}, {2} - {1}]",
const mem::offset_of!(FloatRegisters, fp_simd_regs),
const mem::offset_of!(FloatRegisters, fpcr),
const mem::offset_of!(FloatRegisters, fpsr),
const offset_of!(FloatRegisters, fp_simd_regs),
const offset_of!(FloatRegisters, fpcr),
const offset_of!(FloatRegisters, fpsr),
inout(reg) float_regs => _,
);
}
@@ -263,9 +263,9 @@ unsafe extern "C" fn fp_load(float_regs: &mut FloatRegisters) {
"msr fpcr, x9",
"ldr x9, [{3}, {2} - {1}]",
"msr fpsr, x9",
const mem::offset_of!(FloatRegisters, fp_simd_regs),
const mem::offset_of!(FloatRegisters, fpcr),
const mem::offset_of!(FloatRegisters, fpsr),
const offset_of!(FloatRegisters, fp_simd_regs),
const offset_of!(FloatRegisters, fpcr),
const offset_of!(FloatRegisters, fpsr),
inout(reg) float_regs => _,
);
}
+1 -1
View File
@@ -55,7 +55,7 @@ impl Context {
) {
let mut stack_top = stack.initial_top();
const INT_REGS_SIZE: usize = core::mem::size_of::<InterruptStack>();
const INT_REGS_SIZE: usize = size_of::<InterruptStack>();
if userspace_allowed {
unsafe {
+3 -3
View File
@@ -77,7 +77,7 @@ impl Context {
) {
let mut stack_top = stack.initial_top();
const INT_REGS_SIZE: usize = core::mem::size_of::<InterruptStack>();
const INT_REGS_SIZE: usize = size_of::<InterruptStack>();
unsafe {
if userspace_allowed {
@@ -86,13 +86,13 @@ impl Context {
stack_top.write_bytes(0_u8, INT_REGS_SIZE);
(&mut *stack_top.cast::<InterruptStack>()).init();
stack_top = stack_top.sub(core::mem::size_of::<usize>());
stack_top = stack_top.sub(size_of::<usize>());
stack_top
.cast::<usize>()
.write(crate::interrupt::syscall::enter_usermode as usize);
}
stack_top = stack_top.sub(core::mem::size_of::<usize>());
stack_top = stack_top.sub(size_of::<usize>());
stack_top.cast::<usize>().write(func as usize);
}
+3 -3
View File
@@ -89,7 +89,7 @@ impl Context {
) {
let mut stack_top = stack.initial_top();
const INT_REGS_SIZE: usize = core::mem::size_of::<InterruptStack>();
const INT_REGS_SIZE: usize = size_of::<InterruptStack>();
// Kstack::initial_top() is always at least 8 byte aligned. assertion to be safe
debug_assert!(
@@ -104,13 +104,13 @@ impl Context {
stack_top.write_bytes(0_u8, INT_REGS_SIZE);
(*stack_top.cast::<InterruptStack>()).init();
stack_top = stack_top.sub(core::mem::size_of::<usize>());
stack_top = stack_top.sub(size_of::<usize>());
stack_top
.cast::<usize>()
.write(crate::interrupt::syscall::enter_usermode as usize);
}
stack_top = stack_top.sub(core::mem::size_of::<usize>());
stack_top = stack_top.sub(size_of::<usize>());
stack_top.cast::<usize>().write(func as usize);
}
+4 -4
View File
@@ -405,7 +405,7 @@ impl Context {
this_percpu.maybe_handle_tlb_shootdown();
}
let _old_addrsp = core::mem::replace(
let _old_addrsp = mem::replace(
&mut *this_percpu.current_addrsp.borrow_mut(),
addr_space.clone(),
);
@@ -454,8 +454,8 @@ impl Context {
sig: &mut SignalState,
) -> (&Sigcontrol, &SigProcControl, &mut SignalState) {
let check = |off| {
assert_eq!(usize::from(off) % mem::align_of::<usize>(), 0);
assert!(usize::from(off).saturating_add(mem::size_of::<Sigcontrol>()) < PAGE_SIZE);
assert_eq!(usize::from(off) % align_of::<usize>(), 0);
assert!(usize::from(off).saturating_add(size_of::<Sigcontrol>()) < PAGE_SIZE);
};
check(sig.procctl_off);
check(sig.threadctl_off);
@@ -547,7 +547,7 @@ impl BorrowedHtBuf {
core::str::from_utf8(slice).map_err(|_| Error::new(EINVAL))
}
pub unsafe fn use_for_struct<T>(&mut self) -> Result<&mut T> {
if mem::size_of::<T>() > PAGE_SIZE || mem::align_of::<T>() > PAGE_SIZE {
if size_of::<T>() > PAGE_SIZE || align_of::<T>() > PAGE_SIZE {
return Err(Error::new(EINVAL));
}
self.buf_mut().fill(0_u8);
+1 -1
View File
@@ -128,5 +128,5 @@ impl Display for LogicalCpuSet {
pub type RawMask = [usize; SET_WORDS];
pub fn mask_as_bytes(mask: &RawMask) -> &[u8] {
unsafe { core::slice::from_raw_parts(mask.as_ptr().cast(), core::mem::size_of::<RawMask>()) }
unsafe { core::slice::from_raw_parts(mask.as_ptr().cast(), size_of::<RawMask>()) }
}
+1 -1
View File
@@ -227,7 +227,7 @@ fn dump_stack(context: &Context, mut sp: usize) {
}) {
let value = unsafe { *(sp as *const usize) };
println!(" {:>0width$x}: {:>0width$x}", sp, value, width = width);
if let Some(next_sp) = sp.checked_add(core::mem::size_of::<usize>()) {
if let Some(next_sp) = sp.checked_add(size_of::<usize>()) {
sp = next_sp;
} else {
println!(" {:>0width$x}: OVERFLOW", sp, width = width);
+3 -4
View File
@@ -3,7 +3,6 @@
use core::{
cell::SyncUnsafeCell,
mem,
num::NonZeroUsize,
sync::atomic::{AtomicUsize, Ordering},
};
@@ -495,7 +494,7 @@ pub const MAX_SECTION_SIZE: usize = 1 << MAX_SECTION_SIZE_BITS;
pub const MAX_SECTION_PAGE_COUNT: usize = MAX_SECTION_SIZE / PAGE_SIZE;
const _: () = {
assert!(mem::size_of::<PageInfo>().is_power_of_two());
assert!(size_of::<PageInfo>().is_power_of_two());
};
#[cold]
@@ -529,7 +528,7 @@ fn init_sections(mut allocator: BumpAllocator<RmmA>) {
})
.sum();
let section_array_page_count =
(max_section_count * mem::size_of::<Section>()).div_ceil(PAGE_SIZE);
(max_section_count * size_of::<Section>()).div_ceil(PAGE_SIZE);
let base = allocator
.allocate(FrameCount::new(section_array_page_count))
@@ -589,7 +588,7 @@ fn init_sections(mut allocator: BumpAllocator<RmmA>) {
let page_info_count = core::cmp::min(page_info_max_count, pages_to_next_section);
let page_info_array_size_pages =
(page_info_count * mem::size_of::<PageInfo>()).div_ceil(PAGE_SIZE);
(page_info_count * size_of::<PageInfo>()).div_ceil(PAGE_SIZE);
let page_info_array = unsafe {
let base = allocator
.allocate(FrameCount::new(page_info_array_size_pages))
+6 -8
View File
@@ -1,6 +1,6 @@
//! Intrinsics for panic handling
use core::{mem, panic::PanicInfo, slice};
use core::{panic::PanicInfo, slice};
#[cfg(target_pointer_width = "32")]
use object::elf::FileHeader32 as FileHeader;
@@ -171,8 +171,7 @@ pub unsafe fn user_stack_trace(stack: &InterruptStack) {
break;
}
let rip_addr = fp + size_of::<usize>();
let rip = match UserSliceRo::new(rip_addr, mem::size_of::<usize>())
.and_then(|x| x.read_usize())
let rip = match UserSliceRo::new(rip_addr, size_of::<usize>()).and_then(|x| x.read_usize())
{
Ok(val) => val,
Err(err) => {
@@ -185,11 +184,10 @@ pub unsafe fn user_stack_trace(stack: &InterruptStack) {
break;
}
let next_fp =
match UserSliceRo::new(fp, mem::size_of::<usize>()).and_then(|x| x.read_usize()) {
Ok(val) => val,
Err(_err) => break,
};
let next_fp = match UserSliceRo::new(fp, size_of::<usize>()).and_then(|x| x.read_usize()) {
Ok(val) => val,
Err(_err) => break,
};
if next_fp <= fp {
println!(
" <Invalid next frame pointer 0x{:>016x}; stack walk ended>",
-1
View File
@@ -2,7 +2,6 @@
use core::sync::atomic::AtomicU32;
use core::{
cell::UnsafeCell,
mem::size_of,
sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering},
};
+2 -3
View File
@@ -1,5 +1,4 @@
use alloc::sync::Arc;
use core::mem;
use syscall::{EventFlags, O_NONBLOCK};
use crate::{
@@ -88,7 +87,7 @@ impl KernelScheme for EventScheme {
};
let mut events_written = 0;
for chunk in buf.in_exact_chunks(mem::size_of::<Event>()) {
for chunk in buf.in_exact_chunks(size_of::<Event>()) {
let event = unsafe { chunk.read_exact::<Event>()? };
if queue.write(&[event], token)? == 0 {
break;
@@ -96,7 +95,7 @@ impl KernelScheme for EventScheme {
events_written += 1;
}
Ok(events_written * mem::size_of::<Event>())
Ok(events_written * size_of::<Event>())
}
fn kfpath(&self, _id: usize, buf: UserSliceWo, _token: &mut CleanLockToken) -> Result<usize> {
+11 -11
View File
@@ -2,7 +2,7 @@
// this scheme should only handle raw IRQ registration and delivery to userspace.
use core::{
mem, str,
str,
str::FromStr,
sync::atomic::{AtomicUsize, Ordering},
};
@@ -450,7 +450,7 @@ impl crate::scheme::KernelScheme for IrqScheme {
irq: handle_irq,
ack: ref handle_ack,
} => {
if buffer.len() < mem::size_of::<usize>() {
if buffer.len() < size_of::<usize>() {
return Err(Error::new(EINVAL));
}
let ack = buffer.read_usize()?;
@@ -463,7 +463,7 @@ impl crate::scheme::KernelScheme for IrqScheme {
unsafe {
acknowledge(handle_irq as usize);
}
Ok(mem::size_of::<usize>())
Ok(size_of::<usize>())
}
_ => Err(Error::new(EBADF)),
}
@@ -478,18 +478,18 @@ impl crate::scheme::KernelScheme for IrqScheme {
irq: handle_irq, ..
} => Stat {
st_mode: MODE_CHR | 0o600,
st_size: mem::size_of::<usize>() as u64,
st_size: size_of::<usize>() as u64,
st_blocks: 1,
st_blksize: mem::size_of::<usize>() as u32,
st_blksize: size_of::<usize>() as u32,
st_ino: handle_irq.into(),
st_nlink: 1,
..Default::default()
},
Handle::Bsp => Stat {
st_mode: MODE_CHR | 0o400,
st_size: mem::size_of::<usize>() as u64,
st_size: size_of::<usize>() as u64,
st_blocks: 1,
st_blksize: mem::size_of::<usize>() as u32,
st_blksize: size_of::<usize>() as u32,
st_ino: INO_BSP,
st_nlink: 1,
..Default::default()
@@ -554,23 +554,23 @@ impl crate::scheme::KernelScheme for IrqScheme {
irq: handle_irq,
ack: ref handle_ack,
} => {
if buffer.len() < mem::size_of::<usize>() {
if buffer.len() < size_of::<usize>() {
return Err(Error::new(EINVAL));
}
let current = COUNTS.lock()[handle_irq as usize];
if handle_ack.load(Ordering::SeqCst) != current {
buffer.write_usize(current)?;
Ok(mem::size_of::<usize>())
Ok(size_of::<usize>())
} else {
Ok(0)
}
}
Handle::Bsp => {
if buffer.len() < mem::size_of::<usize>() {
if buffer.len() < size_of::<usize>() {
return Err(Error::new(EINVAL));
}
buffer.write_u32(LogicalCpuId::BSP.get())?;
Ok(mem::size_of::<usize>())
Ok(size_of::<usize>())
}
Handle::Avail(_) | Handle::TopLevel | Handle::Phandle(_, _) | Handle::SchemeRoot => {
Err(Error::new(EISDIR))
+1 -1
View File
@@ -469,7 +469,7 @@ impl KernelScheme for PipeScheme {
let (mut vec, mut token) = vec.into_split();
let fds_available = vec.len();
let max_fds_read = payload.len() / core::mem::size_of::<usize>();
let max_fds_read = payload.len() / size_of::<usize>();
let fds_to_read = core::cmp::min(fds_available, max_fds_read);
if fds_to_read > 0 {
let fds_to_transfer: Vec<_> = vec.drain(..fds_to_read).collect();
+24 -24
View File
@@ -28,7 +28,7 @@ use alloc::{
vec::Vec,
};
use core::{
mem::{self, size_of},
mem::size_of,
num::NonZeroUsize,
slice, str,
sync::atomic::{AtomicUsize, Ordering},
@@ -954,7 +954,7 @@ impl ContextHandle {
}
_ => return Err(Error::new(EINVAL)),
}
Ok(words_read * mem::size_of::<usize>())
Ok(words_read * size_of::<usize>())
}
ContextHandle::Regs(kind) => match kind {
RegsKind::Float => {
@@ -967,7 +967,7 @@ impl ContextHandle {
// registers being uninitiated
context.set_fx_regs(regs);
Ok(mem::size_of::<FloatRegisters>())
Ok(size_of::<FloatRegisters>())
})
}
RegsKind::Int => {
@@ -985,14 +985,14 @@ impl ContextHandle {
Some(stack) => {
stack.load(&regs);
Ok(mem::size_of::<IntRegisters>())
Ok(size_of::<IntRegisters>())
}
})
}
RegsKind::Env => {
let regs = unsafe { buf.read_exact::<EnvRegisters>()? };
write_env_regs(context, regs, token)?;
Ok(mem::size_of::<EnvRegisters>())
Ok(size_of::<EnvRegisters>())
}
},
ContextHandle::Sighandler => {
@@ -1012,7 +1012,7 @@ impl ContextHandle {
let state = if data.thread_control_addr != 0 && data.proc_control_addr != 0 {
let validate_off = |addr, sz| {
let off: usize = addr % PAGE_SIZE;
if off.is_multiple_of(mem::align_of::<usize>()) && off + sz <= PAGE_SIZE {
if off.is_multiple_of(align_of::<usize>()) && off + sz <= PAGE_SIZE {
Ok(off as u16)
} else {
Err(Error::new(EINVAL))
@@ -1024,11 +1024,11 @@ impl ContextHandle {
Some(SignalState {
threadctl_off: validate_off(
data.thread_control_addr,
mem::size_of::<Sigcontrol>(),
size_of::<Sigcontrol>(),
)?,
procctl_off: validate_off(
data.proc_control_addr,
mem::size_of::<SigProcControl>(),
size_of::<SigProcControl>(),
)?,
user_handler: NonZeroUsize::new(data.user_handler)
.ok_or(Error::new(EINVAL))?,
@@ -1048,7 +1048,7 @@ impl ContextHandle {
context.write(token.token()).sig = state;
Ok(mem::size_of::<SetSighandlerData>())
Ok(size_of::<SetSighandlerData>())
}
ContextHandle::Start => match context.write(token.token()).status {
ref mut status @ Status::HardBlocked {
@@ -1106,7 +1106,7 @@ impl ContextHandle {
context,
};
Ok(mem::size_of::<usize>())
Ok(size_of::<usize>())
}
ContextHandle::CurrentAddrSpace => {
let mut iter = buf.usizes();
@@ -1138,9 +1138,9 @@ impl ContextHandle {
};
let written = if arg1.is_some() {
4 * mem::size_of::<usize>()
4 * size_of::<usize>()
} else {
3 * mem::size_of::<usize>()
3 * size_of::<usize>()
};
Ok(written)
@@ -1152,7 +1152,7 @@ impl ContextHandle {
}
let mut lock_token = token.token();
addrspace.acquire_write(lock_token.downgrade()).mmap_min = val;
Ok(mem::size_of::<usize>())
Ok(size_of::<usize>())
}
Self::SchedAffinity => {
let mask = unsafe { buf.read_exact::<crate::cpu_set::RawMask>()? };
@@ -1162,7 +1162,7 @@ impl ContextHandle {
.sched_affinity
.override_from(&mask);
Ok(mem::size_of_val(&mask))
Ok(size_of_val(&mask))
}
ContextHandle::Status { privileged } => {
let mut args = buf.usizes();
@@ -1240,11 +1240,11 @@ impl ContextHandle {
let mut ctxt = context.write(token.token());
//trace!("FORCEKILL NONSELF={} {}, SELF={}", ctxt.debug_id, ctxt.pid, context::current().read().debug_id);
if let context::Status::Dead { .. } = ctxt.status {
return Ok(mem::size_of::<usize>());
return Ok(size_of::<usize>());
}
ctxt.status = context::Status::Runnable;
ctxt.being_sigkilled = true;
Ok(mem::size_of::<usize>())
Ok(size_of::<usize>())
}
}
}
@@ -1340,7 +1340,7 @@ impl ContextHandle {
Output {
float: context.get_fx_regs(),
},
mem::size_of::<FloatRegisters>(),
size_of::<FloatRegisters>(),
)
}
RegsKind::Int => {
@@ -1357,7 +1357,7 @@ impl ContextHandle {
Some(stack) => {
let mut regs = IntRegisters::default();
stack.save(&mut regs);
Ok((Output { int: regs }, mem::size_of::<IntRegisters>()))
Ok((Output { int: regs }, size_of::<IntRegisters>()))
}
})?
}
@@ -1365,7 +1365,7 @@ impl ContextHandle {
Output {
env: read_env_regs(context, token)?,
},
mem::size_of::<EnvRegisters>(),
size_of::<EnvRegisters>(),
),
};
@@ -1378,7 +1378,7 @@ impl ContextHandle {
let Ok(offset) = usize::try_from(offset) else {
return Ok(0);
};
let grants_to_skip = offset / mem::size_of::<GrantDesc>();
let grants_to_skip = offset / size_of::<GrantDesc>();
// Output a list of grant descriptors, sufficient to allow relibc's fork()
// implementation to fmap MAP_SHARED grants.
@@ -1405,12 +1405,12 @@ impl ContextHandle {
for (src, chunk) in dst
.iter()
.take(grants_read)
.zip(buf.in_exact_chunks(mem::size_of::<GrantDesc>()))
.zip(buf.in_exact_chunks(size_of::<GrantDesc>()))
{
chunk.copy_exactly(src)?;
}
Ok(grants_read * mem::size_of::<GrantDesc>())
Ok(grants_read * size_of::<GrantDesc>())
}
ContextHandle::Filetable { data, .. } => read_from(buf, data, offset),
@@ -1418,13 +1418,13 @@ impl ContextHandle {
let mut token = token.token();
let addr = addrspace.acquire_read(token.downgrade());
buf.write_usize(addr.mmap_min)?;
Ok(mem::size_of::<usize>())
Ok(size_of::<usize>())
}
ContextHandle::SchedAffinity => {
let mask = context.read(token.token()).sched_affinity.to_raw();
buf.copy_exactly(crate::cpu_set::mask_as_bytes(&mask))?;
Ok(mem::size_of_val(&mask))
Ok(size_of_val(&mask))
} // TODO: Replace write() with SYS_SENDFD?
ContextHandle::Status { .. } => {
let status = {
+5 -5
View File
@@ -1,6 +1,6 @@
use alloc::vec::Vec;
use core::{
fmt, mem, str,
fmt, str,
sync::atomic::{AtomicUsize, Ordering},
};
use hashbrown::{hash_map::DefaultHashBuilder, HashMap};
@@ -165,7 +165,7 @@ impl KernelScheme for TimeScheme {
let mut bytes_read = 0;
for current_chunk in buf.in_exact_chunks(mem::size_of::<TimeSpec>()) {
for current_chunk in buf.in_exact_chunks(size_of::<TimeSpec>()) {
let arch_time = match (handle.clock, handle.kind.clone()) {
(CLOCK_REALTIME, TimeSchemeKind::Default | TimeSchemeKind::ClockGettime) => {
time::realtime(token)
@@ -183,7 +183,7 @@ impl KernelScheme for TimeScheme {
};
current_chunk.copy_exactly(&time)?;
bytes_read += mem::size_of::<TimeSpec>();
bytes_read += size_of::<TimeSpec>();
}
Ok(bytes_read)
@@ -208,7 +208,7 @@ impl KernelScheme for TimeScheme {
let mut bytes_written = 0;
for current_chunk in buf.in_exact_chunks(mem::size_of::<TimeSpec>()) {
for current_chunk in buf.in_exact_chunks(size_of::<TimeSpec>()) {
let time = unsafe { current_chunk.read_exact::<TimeSpec>()? };
match (handle.clock, handle.kind.clone()) {
@@ -224,7 +224,7 @@ impl KernelScheme for TimeScheme {
_ => return Err(Error::new(EINVAL)),
};
bytes_written += mem::size_of::<TimeSpec>();
bytes_written += size_of::<TimeSpec>();
}
Ok(bytes_written)
+3 -3
View File
@@ -252,7 +252,7 @@ impl UserInner {
// for TLB, but we don't really have any other choice. The scheme must be able
// to access the borrowed memory until it has responded to the request.
*callee_responsible =
core::mem::replace(caller_responsible, PageSpan::empty());
mem::replace(caller_responsible, PageSpan::empty());
Err(Error::new(EINTR))
} else {
@@ -2043,7 +2043,7 @@ impl KernelScheme for UserScheme {
token: &mut CleanLockToken,
) -> Result<usize> {
let inner = self.inner.clone();
if !payload.len().is_multiple_of(mem::size_of::<usize>()) {
if !payload.len().is_multiple_of(size_of::<usize>()) {
return Err(Error::new(EINVAL));
}
@@ -2056,7 +2056,7 @@ impl KernelScheme for UserScheme {
}
let ctx = { context::current().read(token.token()).caller_ctx() };
let len = payload.len() / mem::size_of::<usize>();
let len = payload.len() / size_of::<usize>();
let res = inner.call(
ctx,
Vec::new(),
+1 -2
View File
@@ -6,7 +6,6 @@ use crate::{
use core::{
cell::SyncUnsafeCell,
cmp::{max, min},
mem,
slice::{self, Iter},
};
use rmm::{
@@ -184,7 +183,7 @@ fn register_bootloader_areas(areas_base: usize, areas_size: usize) {
let bootloader_areas = unsafe {
slice::from_raw_parts(
areas_base as *const BootloaderMemoryEntry,
areas_size / mem::size_of::<BootloaderMemoryEntry>(),
areas_size / size_of::<BootloaderMemoryEntry>(),
)
};
for bootloader_area in bootloader_areas.iter() {
+6 -8
View File
@@ -46,7 +46,7 @@ impl<T> WaitQueue<T> {
continue;
} else if buf.is_empty() {
return Ok(0);
} else if buf.len() < core::mem::size_of::<T>() {
} else if buf.len() < size_of::<T>() {
return Err(Error::new(EINVAL));
} else {
// TODO: EWOULDBLOCK?
@@ -55,12 +55,10 @@ impl<T> WaitQueue<T> {
}
let (s1, s2) = inner.as_slices();
let s1_bytes = unsafe {
core::slice::from_raw_parts(s1.as_ptr().cast::<u8>(), core::mem::size_of_val(s1))
};
let s2_bytes = unsafe {
core::slice::from_raw_parts(s2.as_ptr().cast::<u8>(), core::mem::size_of_val(s2))
};
let s1_bytes =
unsafe { core::slice::from_raw_parts(s1.as_ptr().cast::<u8>(), size_of_val(s1)) };
let s2_bytes =
unsafe { core::slice::from_raw_parts(s2.as_ptr().cast::<u8>(), size_of_val(s2)) };
let mut bytes_copied = buf.copy_common_bytes_from_slice(s1_bytes)?;
@@ -68,7 +66,7 @@ impl<T> WaitQueue<T> {
bytes_copied += buf_for_s2.copy_common_bytes_from_slice(s2_bytes)?;
}
let _ = inner.drain(..bytes_copied / core::mem::size_of::<T>());
let _ = inner.drain(..bytes_copied / size_of::<T>());
return Ok(bytes_copied);
}
+3 -3
View File
@@ -1,5 +1,5 @@
use alloc::{borrow::ToOwned, string::String, vec::Vec};
use core::{ascii, fmt::Debug, mem};
use core::{ascii, fmt::Debug};
use super::{
copy_path_to_buf,
@@ -38,7 +38,7 @@ fn debug_buf(ptr: usize, len: usize) -> Result<Vec<u8>> {
})
}
unsafe fn read_struct<T>(ptr: usize) -> Result<T> {
unsafe { UserSlice::ro(ptr, mem::size_of::<T>()).and_then(|slice| slice.read_exact::<T>()) }
unsafe { UserSlice::ro(ptr, size_of::<T>()).and_then(|slice| slice.read_exact::<T>()) }
}
//TODO: calling format_call with arguments from another process space will not work
@@ -144,7 +144,7 @@ pub fn format_call(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g
let mut times = vec![unsafe { buf.read_exact::<TimeSpec>()? }];
// One or two timespecs
if let Some(second) = buf.advance(mem::size_of::<TimeSpec>()) {
if let Some(second) = buf.advance(size_of::<TimeSpec>()) {
times.push(unsafe { second.read_exact::<TimeSpec>()? });
}
Ok(times)
+1 -1
View File
@@ -1,6 +1,6 @@
//! Filesystem syscalls
use core::{mem::size_of, num::NonZeroUsize};
use core::num::NonZeroUsize;
use alloc::{string::String, sync::Arc, vec::Vec};
use redox_path::RedoxPath;
+2 -2
View File
@@ -54,7 +54,7 @@ static FUTEXES: Mutex<L1, FutexList> =
fn validate_and_translate_virt(space: &AddrSpace, addr: VirtualAddress) -> Option<PhysicalAddress> {
// TODO: Move this elsewhere!
if addr.data().saturating_add(core::mem::size_of::<usize>()) >= crate::USER_END_OFFSET {
if addr.data().saturating_add(size_of::<usize>()) >= crate::USER_END_OFFSET {
return None;
}
@@ -87,7 +87,7 @@ pub fn futex(
match op {
// TODO: FUTEX_WAIT_MULTIPLE?
FUTEX_WAIT | FUTEX_WAIT64 => {
let timeout_opt = UserSlice::ro(val2, core::mem::size_of::<TimeSpec>())?
let timeout_opt = UserSlice::ro(val2, size_of::<TimeSpec>())?
.none_if_null()
.map(|buf| unsafe { buf.read_exact::<TimeSpec>() })
.transpose()?;
+5 -10
View File
@@ -4,8 +4,6 @@
extern crate syscall;
use core::mem::size_of;
use syscall::{dirent::DirentHeader, CallFlags, RwFlags, EINVAL};
pub use self::syscall::{
@@ -223,17 +221,14 @@ pub fn syscall(
}
SYS_YIELD => sched_yield(token).map(|()| 0),
SYS_NANOSLEEP => nanosleep(
UserSlice::ro(b, core::mem::size_of::<TimeSpec>())?,
UserSlice::wo(c, core::mem::size_of::<TimeSpec>())?.none_if_null(),
token,
)
.map(|()| 0),
SYS_CLOCK_GETTIME => clock_gettime(
b,
UserSlice::wo(c, core::mem::size_of::<TimeSpec>())?,
UserSlice::ro(b, size_of::<TimeSpec>())?,
UserSlice::wo(c, size_of::<TimeSpec>())?.none_if_null(),
token,
)
.map(|()| 0),
SYS_CLOCK_GETTIME => {
clock_gettime(b, UserSlice::wo(c, size_of::<TimeSpec>())?, token).map(|()| 0)
}
SYS_FUTEX => futex(b, c, d, e, f, token),
SYS_MPROTECT => mprotect(b, c, MapFlags::from_bits_truncate(d), token).map(|()| 0),
+5 -5
View File
@@ -204,7 +204,7 @@ pub unsafe fn usermode_bootstrap(bootstrap: &Bootstrap, token: &mut CleanLockTok
.expect("Failed to allocate kernel scheme info page");
let mut cursor = kernel_schemes_info_page.start_address().data();
const HEADER_SIZE: usize = mem::size_of::<usize>();
const HEADER_SIZE: usize = size_of::<usize>();
UserSliceWo::new(cursor, HEADER_SIZE)
.expect("failed to create kernel schemes header user slice")
.copy_common_bytes_from_slice(&KERNEL_SCHEMES_COUNT.to_ne_bytes())
@@ -213,18 +213,18 @@ pub unsafe fn usermode_bootstrap(bootstrap: &Bootstrap, token: &mut CleanLockTok
let info_bytes = unsafe {
core::slice::from_raw_parts(
kernel_schemes_infos.as_ptr() as *const u8,
KERNEL_SCHEMES_COUNT * mem::size_of::<syscall::data::KernelSchemeInfo>(),
KERNEL_SCHEMES_COUNT * size_of::<syscall::data::KernelSchemeInfo>(),
)
};
UserSliceWo::new(
cursor,
KERNEL_SCHEMES_COUNT * mem::size_of::<syscall::data::KernelSchemeInfo>(),
KERNEL_SCHEMES_COUNT * size_of::<syscall::data::KernelSchemeInfo>(),
)
.expect("failed to create kernel schemes info user slice")
.copy_common_bytes_from_slice(info_bytes)
.expect("failed to copy kernel schemes info");
cursor += KERNEL_SCHEMES_COUNT * mem::size_of::<syscall::data::KernelSchemeInfo>();
UserSliceWo::new(cursor, mem::size_of::<usize>())
cursor += KERNEL_SCHEMES_COUNT * size_of::<syscall::data::KernelSchemeInfo>();
UserSliceWo::new(cursor, size_of::<usize>())
.expect("failed to create scheme creation cap user slice")
.copy_common_bytes_from_slice(&scheme_creation_cap.to_ne_bytes())
.expect("failed to copy scheme creation cap");
+6 -9
View File
@@ -109,13 +109,10 @@ impl<const WRITE: bool> UserSlice<true, WRITE> {
pub unsafe fn read_exact<T>(self) -> Result<T> {
let mut t: T = unsafe { core::mem::zeroed() };
let slice = unsafe {
core::slice::from_raw_parts_mut(
(&mut t as *mut T).cast::<u8>(),
core::mem::size_of::<T>(),
)
core::slice::from_raw_parts_mut((&mut t as *mut T).cast::<u8>(), size_of::<T>())
};
self.limit(core::mem::size_of::<T>())
self.limit(size_of::<T>())
.ok_or(Error::new(EINVAL))?
.copy_to_slice(slice)?;
@@ -131,7 +128,7 @@ impl<const WRITE: bool> UserSlice<true, WRITE> {
// TODO: Merge int IO functions?
pub fn read_usize(self) -> Result<usize> {
let mut ret = 0_usize.to_ne_bytes();
self.limit(core::mem::size_of::<usize>())
self.limit(size_of::<usize>())
.ok_or(Error::new(EINVAL))?
.copy_to_slice(&mut ret)?;
Ok(usize::from_ne_bytes(ret))
@@ -144,7 +141,7 @@ impl<const WRITE: bool> UserSlice<true, WRITE> {
Ok(u32::from_ne_bytes(ret))
}
pub fn usizes(self) -> impl Iterator<Item = Result<usize>> {
self.in_exact_chunks(core::mem::size_of::<usize>())
self.in_exact_chunks(size_of::<usize>())
.map(Self::read_usize)
}
}
@@ -177,13 +174,13 @@ impl<const READ: bool> UserSlice<READ, true> {
Ok(())
}
pub fn write_usize(self, word: usize) -> Result<()> {
self.limit(core::mem::size_of::<usize>())
self.limit(size_of::<usize>())
.ok_or(Error::new(EINVAL))?
.copy_from_slice(&word.to_ne_bytes())?;
Ok(())
}
pub fn write_u32(self, int: u32) -> Result<()> {
self.limit(core::mem::size_of::<u32>())
self.limit(size_of::<u32>())
.ok_or(Error::new(EINVAL))?
.copy_from_slice(&int.to_ne_bytes())?;
Ok(())