Replace Pod with zerocopy-backed Pod

This commit is contained in:
jiangjianfeng 2026-01-27 08:35:10 +00:00 committed by Tate, Hongliang Tian
parent c8f2cfaeae
commit 4a80f0e5eb
104 changed files with 288 additions and 269 deletions

67
Cargo.lock generated
View File

@ -103,7 +103,9 @@ dependencies = [
"int-to-c-enum",
"log",
"ostd",
"ostd-pod",
"spin",
"zerocopy",
]
[[package]]
@ -161,7 +163,9 @@ dependencies = [
"component",
"log",
"ostd",
"ostd-pod",
"spin",
"zerocopy",
]
[[package]]
@ -214,6 +218,7 @@ dependencies = [
"osdk-frame-allocator",
"osdk-heap-allocator",
"ostd",
"ostd-pod",
"paste",
"rand",
"riscv",
@ -225,6 +230,7 @@ dependencies = [
"typeflags-util",
"xarray",
"xmas-elf",
"zerocopy",
]
[[package]]
@ -254,8 +260,10 @@ dependencies = [
"log",
"lru",
"ostd",
"ostd-pod",
"postcard",
"serde",
"zerocopy",
]
[[package]]
@ -267,7 +275,9 @@ dependencies = [
"bitvec",
"component",
"ostd",
"ostd-pod",
"spin",
"zerocopy",
]
[[package]]
@ -363,6 +373,7 @@ dependencies = [
"ostd",
"ostd-pod",
"typeflags-util",
"zerocopy",
]
[[package]]
@ -386,9 +397,11 @@ dependencies = [
"int-to-c-enum",
"log",
"ostd",
"ostd-pod",
"spin",
"tdx-guest",
"typeflags-util",
"zerocopy",
]
[[package]]
@ -451,26 +464,6 @@ dependencies = [
"wyz",
]
[[package]]
name = "bytemuck"
version = "1.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9134a6ef01ce4b366b50689c94f82c14bc72bc5d0386829828a2e2752ef7958c"
dependencies = [
"bytemuck_derive",
]
[[package]]
name = "bytemuck_derive"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ecc273b49b3205b83d648f0690daa588925572cc5063745bfe547fe7ec8e1a1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.101",
]
[[package]]
name = "byteorder"
version = "1.5.0"
@ -1113,10 +1106,11 @@ version = "0.17.0"
dependencies = [
"align_ext",
"bitflags 1.3.2",
"bytemuck",
"libflate",
"ostd-pod",
"serde",
"xmas-elf",
"zerocopy",
]
[[package]]
@ -1351,7 +1345,7 @@ dependencies = [
"multiboot2",
"num-traits",
"ostd-macros",
"ostd-pod 0.1.1",
"ostd-pod",
"ostd-test",
"riscv",
"sbi-rt",
@ -1362,6 +1356,7 @@ dependencies = [
"volatile 0.6.1",
"x86",
"x86_64",
"zerocopy",
]
[[package]]
@ -1376,38 +1371,22 @@ dependencies = [
[[package]]
name = "ostd-pod"
version = "0.1.1"
source = "git+https://github.com/asterinas/ostd-pod?rev=c4644be#c4644be401cae1e046a810574078b64e35924f5f"
dependencies = [
"ostd-pod-derive",
]
[[package]]
name = "ostd-pod"
version = "0.1.2"
version = "0.4.0"
dependencies = [
"ostd-pod-macros",
"padding-struct",
"zerocopy",
]
[[package]]
name = "ostd-pod-derive"
version = "0.1.1"
source = "git+https://github.com/asterinas/ostd-pod?rev=c4644be#c4644be401cae1e046a810574078b64e35924f5f"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "ostd-pod-macros"
version = "0.1.2"
version = "0.4.0"
dependencies = [
"ostd-pod",
"proc-macro2",
"quote",
"syn 2.0.101",
"zerocopy",
]
[[package]]
@ -1422,12 +1401,12 @@ checksum = "48dd4f4a2c8405440fd0462561f0e5806bd0f77e86f51c761481bdd4018b545e"
[[package]]
name = "padding-struct"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"bytemuck",
"proc-macro2",
"quote",
"syn 2.0.101",
"zerocopy",
]
[[package]]

View File

@ -91,6 +91,7 @@ id-alloc = { path = "ostd/libs/id-alloc", version = "0.1.0" }
int-to-c-enum = { path = "ostd/libs/int-to-c-enum", version = "0.1.0" }
linux-boot-params = { version = "0.17.0", path = "ostd/libs/linux-bzimage/boot-params" }
ostd-macros = { version = "0.17.0", path = "ostd/libs/ostd-macros" }
ostd-pod = { path = "ostd/libs/ostd-pod", version = "0.4.0" }
ostd-test = { version = "0.17.0", path = "ostd/libs/ostd-test" }
# Crates under kernel/comps
@ -135,16 +136,13 @@ osdk-heap-allocator = { path = "osdk/deps/heap-allocator" }
# External dependencies only for unsafe crates (i.e., crates under ostd directory)
bit_field = "0.10.1"
bytemuck = { version = "1.17.0", features = ["derive"] }
gimli = { version = "0.28", default-features = false, features = ["read-core"] }
minicov = "0.3"
num-traits = { version = "0.2", default-features = false }
ostd-pod = { git = "https://github.com/asterinas/ostd-pod", rev = "c4644be", version = "0.1.1" }
serde = { version = "1.0.192", default-features = false, features = ["alloc", "derive"] }
smallvec = "1.13.2"
uart_16550 = "0.3.0"
volatile = "0.6.1"
zerocopy = { version = "0.8.34", features = [ "derive" ] }
# External dependencies only for safe crates (i.e., crates under kernel or osdk/deps directories)
#
@ -191,6 +189,9 @@ log = "0.4"
rand = { version = "0.9.2", default-features = false }
spin = "0.9.4"
xmas-elf = "0.10.0"
# Note: when updating the zerocopy version,
# also update it in `ostd/libs/ostd-pod/README.md`.
zerocopy = { version = "0.8.34", features = [ "derive" ] }
# Proc-macro dependencies
proc-macro2 = { version = "1.0.95", features = ["span-locations"] }

View File

@ -51,6 +51,7 @@ lru.workspace = true
osdk-frame-allocator.workspace = true
osdk-heap-allocator.workspace = true
ostd.workspace = true
ostd-pod.workspace = true
paste.workspace = true
rand = { workspace = true, features = [
"small_rng",
@ -63,6 +64,7 @@ typeflags.workspace = true
typeflags-util.workspace = true
xarray.workspace = true
xmas-elf.workspace = true
zerocopy.workspace = true
[target.x86_64-unknown-none.dependencies]
tdx-guest = { version = "0.2.4", optional = true }

View File

@ -15,7 +15,9 @@ id-alloc.workspace = true
int-to-c-enum.workspace = true
log.workspace = true
ostd.workspace = true
ostd-pod.workspace = true
spin.workspace = true
zerocopy.workspace = true
[lints]
workspace = true

View File

@ -5,7 +5,7 @@ use core::{
ops::{Add, Sub},
};
use ostd::{Pod, const_assert};
use ostd::const_assert;
/// The block index used in the filesystem.
pub type Bid = BlockId<BLOCK_SIZE>;

View File

@ -31,6 +31,8 @@
#![feature(step_trait)]
extern crate alloc;
#[macro_use]
extern crate ostd_pod;
pub mod bio;
mod device_id;

View File

@ -1,7 +1,8 @@
// SPDX-License-Identifier: MPL-2.0
use device_id::DeviceId;
use ostd::{Pod, mm::VmIo};
use ostd::mm::VmIo;
use ostd_pod::Pod;
use crate::{
BlockDevice, BlockDeviceMeta, SECTOR_SIZE,

View File

@ -11,7 +11,9 @@ bitflags.workspace = true
bitvec.workspace = true
log.workspace = true
ostd.workspace = true
ostd-pod.workspace = true
spin.workspace = true
zerocopy.workspace = true
[lints]
workspace = true

View File

@ -3,10 +3,7 @@
use alloc::{sync::Arc, vec::Vec};
use core::{any::Any, fmt::Debug};
use ostd::{
Pod,
sync::{RwLock, WriteIrqDisabled},
};
use ostd::sync::{RwLock, WriteIrqDisabled};
use crate::{
event_type_codes::{EventTypes, KeyCode, KeyCodeSet, KeyStatus, RelCode, RelCodeSet, SynEvent},

View File

@ -35,6 +35,8 @@
#![deny(unsafe_code)]
extern crate alloc;
#[macro_use]
extern crate ostd_pod;
pub mod event_type_codes;
mod input_core;

View File

@ -18,8 +18,10 @@ lending-iterator.workspace = true
lru.workspace = true
log.workspace = true
ostd.workspace = true
ostd-pod.workspace = true
postcard.workspace = true
serde.workspace = true
zerocopy.workspace = true
[lints]
workspace = true

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: MPL-2.0
use ostd::Pod;
use ostd_pod::{FromZeros, IntoBytes, Pod};
use super::{Iv, Key, Mac, VersionId};
use crate::{

View File

@ -3,7 +3,7 @@
use core::ops::Range;
use lending_iterator::prelude::*;
use ostd::Pod;
use ostd_pod::{IntoBytes, Pod};
use super::{Iv, Key, Mac};
use crate::{

View File

@ -3,7 +3,8 @@
use alloc::vec;
use core::any::Any;
use ostd::{Pod, const_assert};
use ostd::const_assert;
use ostd_pod::{FromZeros, IntoBytes, Pod};
use serde::{Deserialize, Serialize};
use super::{Iv, Key, Mac};
@ -111,6 +112,7 @@ pub struct RootMhtMeta {
/// The Merkle-Hash Tree (MHT) node (internal).
/// It contains a header for node metadata and a bunch of entries for managing children nodes.
#[repr(C)]
#[padding_struct]
#[derive(Clone, Copy, Pod)]
struct MhtNode {
header: MhtNodeHeader,
@ -120,7 +122,8 @@ const_assert!(size_of::<MhtNode>() <= BLOCK_SIZE);
/// The header contains metadata of the current MHT node.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod)]
#[padding_struct]
#[derive(Clone, Copy, Debug, Pod, Default)]
struct MhtNodeHeader {
// The height of the MHT whose root is this node
height: Height,
@ -262,7 +265,7 @@ impl<L: BlockLog> CryptoLog<L> {
let data_nodes: Vec<Arc<DataNode>> = buf
.iter()
.map(|block_buf| {
let mut node = DataNode::new_uninit();
let mut node = DataNode::new_zeroed();
node.0.copy_from_slice(block_buf.as_slice());
Arc::new(node)
})
@ -743,6 +746,7 @@ impl LevelBuilder {
height: self.height,
num_data_nodes: MhtNode::max_num_data_nodes(self.height) as _,
num_valid_entries: MHT_NBRANCHES as _,
..Default::default()
};
for (i, entry) in mht_node.entries.iter_mut().enumerate() {
*entry = *entries_per_node[i];
@ -772,13 +776,14 @@ impl LevelBuilder {
height: self.height,
num_data_nodes: num_data_nodes as _,
num_valid_entries: num_valid_entries as _,
..Default::default()
};
for (i, entry) in last_mht_node.entries.iter_mut().enumerate() {
*entry = if i < num_valid_entries {
*entries[i]
} else {
// Padding invalid entries to the rest
MhtNodeEntry::new_uninit()
MhtNodeEntry::new_zeroed()
};
}

View File

@ -3,7 +3,7 @@
use core::marker::PhantomData;
use lending_iterator::LendingIterator;
use ostd::Pod;
use ostd_pod::{IntoBytes, Pod};
use serde::{
Deserialize, Serialize,
de::{VariantAccess, Visitor},

View File

@ -66,7 +66,7 @@ use core::{
};
use lru::LruCache;
use ostd::Pod;
use ostd_pod::{FromZeros, IntoBytes, Pod};
use serde::{Deserialize, Serialize};
use self::journaling::{AllEdit, AllState, Journal, JournalCompactPolicy};

View File

@ -243,7 +243,7 @@ impl<K: RecordKey<K>, V: RecordValue> MemTable<K, V> {
// Insert an empty range upon first sync
let _ = self
.unsynced_range
.get_or_insert_with(|| K::new_uninit()..K::new_uninit());
.get_or_insert_with(|| K::new_zeroed()..K::new_zeroed());
}
/// Return the sync ID of this table.
@ -343,7 +343,7 @@ impl<V: RecordValue> ValueEx<V> {
impl<V: RecordValue> Default for ValueEx<V> {
fn default() -> Self {
Self::Unsynced(V::new_uninit())
Self::Unsynced(V::new_zeroed())
}
}

View File

@ -5,7 +5,7 @@ use alloc::vec;
use core::{marker::PhantomData, num::NonZeroUsize, ops::RangeInclusive};
use lru::LruCache;
use ostd::Pod;
use ostd_pod::{IntoBytes, Pod};
use super::{
RangeQueryCtx, RecordKey, RecordValue, SyncId, TxEventListener, mem_table::ValueEx,
@ -42,7 +42,8 @@ struct Footer<K> {
/// Footer metadata to describe a `SSTable`.
#[repr(C)]
#[derive(Copy, Clone, Pod, Debug)]
#[padding_struct]
#[derive(Copy, Clone, Pod, Debug, Default)]
struct FooterMeta {
num_index: u16,
index_nblocks: u16,
@ -486,6 +487,7 @@ impl<K: RecordKey<K>, V: RecordValue> SSTable<K, V> {
total_records: total_records as _,
record_block_size: RECORD_BLOCK_SIZE as _,
sync_id,
..Default::default()
};
append_buf[footer_buf_len - FOOTER_META_SIZE..].copy_from_slice(meta.as_bytes());
tx_log.append(BufRef::try_from(&append_buf[..]).unwrap())?;

View File

@ -14,7 +14,7 @@ use core::{
sync::atomic::{AtomicU64, Ordering},
};
use ostd::Pod;
use ostd_pod::Pod;
use super::{
compaction::Compactor,

View File

@ -4,7 +4,7 @@
use alloc::vec;
use core::fmt::Debug;
use ostd::Pod;
use ostd_pod::Pod;
use super::{AsKV, SyncId};
use crate::{

View File

@ -7,7 +7,7 @@ use core::{
sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};
use ostd::Pod;
use ostd_pod::{IntoBytes, Pod};
use serde::{Deserialize, Serialize};
use super::mlsdisk::Hba;

View File

@ -16,10 +16,8 @@ use core::{
};
use device_id::DeviceId;
use ostd::{
Pod,
mm::{HasSize, VmIo},
};
use ostd::mm::{HasSize, VmIo};
use ostd_pod::{FromZeros, Pod};
use super::{
bio::{BioReq, BioReqQueue, BioResp, BioType},

View File

@ -14,6 +14,8 @@ mod tx;
mod util;
extern crate alloc;
#[macro_use]
extern crate ostd_pod;
use alloc::{string::ToString, sync::Arc, vec};
use core::ops::Range;

View File

@ -23,11 +23,11 @@ use ctr::cipher::{NewCipher, StreamCipher};
pub use hashbrown::{HashMap, HashSet};
pub use ostd::sync::{Mutex, MutexGuard, RwLock, SpinLock};
use ostd::{
Pod,
arch::read_random,
sync::{self, PreemptDisabled, WaitQueue},
task::{Task, TaskOptions},
};
use ostd_pod::{FromZeros, IntoBytes, Pod};
use serde::{Deserialize, Serialize};
use crate::{

View File

@ -11,7 +11,9 @@ aster-softirq.workspace = true
bitvec.workspace = true
component.workspace = true
ostd.workspace = true
ostd-pod.workspace = true
spin.workspace = true
zerocopy.workspace = true
[lints]
workspace = true

View File

@ -4,7 +4,6 @@ use alloc::{collections::linked_list::LinkedList, sync::Arc};
use aster_softirq::BottomHalfDisabled;
use ostd::{
Pod,
mm::{
Daddr, FrameAllocOptions, HasDaddr, HasSize, Infallible, PAGE_SIZE, VmReader, VmWriter,
dma::{DmaStream, FromDevice, ToDevice},
@ -12,6 +11,7 @@ use ostd::{
},
sync::SpinLock,
};
use ostd_pod::Pod;
use spin::Once;
use crate::dma_pool::{DmaPool, DmaSegment};

View File

@ -9,6 +9,8 @@ pub mod dma_pool;
mod driver;
extern crate alloc;
#[macro_use]
extern crate ostd_pod;
use alloc::{collections::BTreeMap, string::String, sync::Arc, vec::Vec};
use core::{any::Any, fmt::Debug};
@ -21,7 +23,7 @@ use aster_softirq::{
pub use buffer::{RX_BUFFER_POOL, RxBuffer, TX_BUFFER_LEN, TxBuffer};
use component::{ComponentInitError, init_component};
pub use dma_pool::DmaSegment;
use ostd::{Pod, sync::SpinLock};
use ostd::sync::SpinLock;
use spin::Once;
#[derive(Debug, Clone, Copy, Pod)]

View File

@ -24,7 +24,9 @@ device-id.workspace = true
id-alloc.workspace = true
log.workspace = true
ostd.workspace = true
ostd-pod.workspace = true
typeflags-util.workspace = true
zerocopy.workspace = true
[target.x86_64-unknown-none.dependencies]
tdx-guest = { version = "0.2.4", optional = true }

View File

@ -22,7 +22,6 @@ use aster_util::mem_obj_slice::Slice;
use device_id::{DeviceId, MinorId};
use log::{debug, info};
use ostd::{
Pod,
arch::trap::TrapFrame,
mm::{HasSize, VmIo, dma::DmaStream},
sync::SpinLock,

View File

@ -8,7 +8,7 @@ use aster_block::SECTOR_SIZE;
use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
use ostd::Pod;
use ostd_pod::FromZeros;
use crate::transport::{ConfigManager, VirtioTransport};
@ -57,8 +57,9 @@ pub enum RespStatus {
_NotReady = 3,
}
#[derive(Debug, Copy, Clone, Pod)]
#[repr(C)]
#[padding_struct]
#[derive(Debug, Copy, Clone, Pod)]
pub struct VirtioBlockConfig {
/// The number of 512-byte sectors.
capacity: u64,
@ -138,7 +139,7 @@ impl VirtioBlockConfig {
impl ConfigManager<VirtioBlockConfig> {
pub(super) fn read_config(&self) -> VirtioBlockConfig {
let mut blk_config = VirtioBlockConfig::new_uninit();
let mut blk_config = VirtioBlockConfig::new_zeroed();
// Only following fields are defined in legacy interface.
let cap_low = self
.read_once::<u32>(offset_of!(VirtioBlockConfig, capacity))

View File

@ -3,7 +3,7 @@
use core::mem::offset_of;
use aster_util::safe_ptr::SafePtr;
use ostd::Pod;
use ostd_pod::FromZeros;
use crate::transport::{ConfigManager, VirtioTransport};
@ -41,7 +41,7 @@ impl VirtioConsoleConfig {
impl ConfigManager<VirtioConsoleConfig> {
pub(super) fn read_config(&self) -> VirtioConsoleConfig {
let mut console_config = VirtioConsoleConfig::new_uninit();
let mut console_config = VirtioConsoleConfig::new_zeroed();
// Only following fields are defined in legacy interface.
console_config.cols = self
.read_once::<u16>(offset_of!(VirtioConsoleConfig, cols))

View File

@ -19,12 +19,12 @@ use aster_util::{field_ptr, safe_ptr::SafePtr};
use bitflags::bitflags;
use log::{debug, info};
use ostd::{
Pod,
arch::trap::TrapFrame,
io::IoMem,
mm::{HasDaddr, PAGE_SIZE, dma::DmaStream},
sync::SpinLock,
};
use ostd_pod::IntoBytes;
use super::{InputConfigSelect, QUEUE_EVENT, QUEUE_STATUS, VirtioInputConfig, VirtioInputEvent};
use crate::{

View File

@ -28,7 +28,7 @@
pub mod device;
use aster_util::safe_ptr::SafePtr;
use ostd::{Pod, io::IoMem};
use ostd::io::IoMem;
use crate::transport::VirtioTransport;

View File

@ -5,7 +5,7 @@ use core::mem::offset_of;
use aster_network::EthernetAddr;
use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
use ostd::Pod;
use ostd_pod::FromZeros;
use crate::transport::{ConfigManager, VirtioTransport};
@ -90,7 +90,7 @@ impl VirtioNetConfig {
impl ConfigManager<VirtioNetConfig> {
pub(super) fn read_config(&self) -> VirtioNetConfig {
let mut net_config = VirtioNetConfig::new_uninit();
let mut net_config = VirtioNetConfig::new_zeroed();
// Only following fields are defined in legacy interface.
for i in 0..6 {
net_config.mac.0[i] = self

View File

@ -2,7 +2,6 @@
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
use ostd::Pod;
pub const VIRTIO_NET_HDR_LEN: usize = size_of::<VirtioNetHdr>();

View File

@ -2,7 +2,7 @@
use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
use ostd::{Pod, io::IoMem, mm::PodOnce};
use ostd::{io::IoMem, mm::PodOnce};
use crate::transport::VirtioTransport;

View File

@ -6,7 +6,8 @@ use core::{fmt::Debug, hint::spin_loop};
use aster_network::{RxBuffer, TxBuffer};
use aster_util::{field_ptr, slot_vec::SlotVec};
use log::debug;
use ostd::{Pod, arch::trap::TrapFrame, mm::VmWriter, sync::SpinLock};
use ostd::{arch::trap::TrapFrame, mm::VmWriter, sync::SpinLock};
use ostd_pod::Pod;
use super::{
config::{VirtioVsockConfig, VsockFeatures},

View File

@ -27,7 +27,6 @@
//
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
use ostd::Pod;
use super::error::{self, SocketError};

View File

@ -1,6 +1,5 @@
// SPDX-License-Identifier: MPL-2.0
// ! #![feature(linked_list_cursors)]
use alloc::{collections::BTreeMap, string::String, sync::Arc, vec::Vec};
use ostd::sync::SpinLock;

View File

@ -3,10 +3,12 @@
//! The virtio of Asterinas.
#![no_std]
#![deny(unsafe_code)]
#![feature(trait_alias)]
#![feature(linked_list_cursors)]
#![feature(trait_alias)]
extern crate alloc;
#[macro_use]
extern crate ostd_pod;
use alloc::boxed::Box;
use core::hint::spin_loop;

View File

@ -12,10 +12,7 @@ use aster_rights::{Dup, TRightSet, TRights, Write};
use aster_util::{field_ptr, safe_ptr::SafePtr};
use bitflags::bitflags;
use log::debug;
use ostd::{
Pod,
mm::{HasPaddr, PodOnce, Split, dma::DmaCoherent},
};
use ostd::mm::{HasPaddr, PodOnce, Split, dma::DmaCoherent};
use crate::{
dma_buf::DmaBuf,
@ -439,6 +436,7 @@ pub struct AvailRing {
/// The used ring is where the device returns buffers once it is done with them:
/// it is only written to by the device, and read by the driver.
#[repr(C, align(4))]
#[padding_struct]
#[derive(Debug, Copy, Clone, Pod)]
pub struct UsedRing {
// the flag in UsedRing

View File

@ -2,8 +2,6 @@
use core::fmt::Debug;
use ostd::Pod;
#[derive(Clone, Copy, Pod)]
#[repr(C)]
pub struct VirtioMmioLayout {

View File

@ -6,12 +6,12 @@ use core::fmt::Debug;
use aster_pci::cfg_space::Bar;
use aster_util::safe_ptr::SafePtr;
use ostd::{
Pod,
arch::device::io_port::{PortRead, PortWrite},
io::IoMem,
irq::IrqCallbackFunction,
mm::{PodOnce, dma::DmaCoherent},
};
use ostd_pod::Pod;
use self::{mmio::virtio_mmio_init, pci::virtio_pci_init};
use crate::{

View File

@ -1,7 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use aster_util::safe_ptr::SafePtr;
use ostd::{Pod, io::IoMem};
use ostd::io::IoMem;
use super::capability::VirtioPciCapabilityData;
use crate::transport::pci::capability::VirtioPciCpabilityType;

View File

@ -11,7 +11,9 @@ aster-rights-proc.workspace = true
inherit-methods-macro.workspace = true
osdk-heap-allocator.workspace = true
ostd.workspace = true
ostd-pod.workspace = true
typeflags-util.workspace = true
zerocopy.workspace = true
[lints]
workspace = true

View File

@ -16,4 +16,3 @@ pub mod printer;
pub mod ranged_integer;
pub mod safe_ptr;
pub mod slot_vec;
pub mod union_read_ptr;

View File

@ -112,14 +112,15 @@ pub enum VmPrinterError {
#[cfg(ktest)]
mod test {
use ostd::{Pod, mm::VmWriter, prelude::*};
use ostd::{mm::VmWriter, prelude::*};
use ostd_pod::IntoBytes;
use super::*;
#[ktest]
fn basic_write() {
let mut buf = [0u8; 64];
let mut writer = VmWriter::from(buf.as_bytes_mut()).to_fallible();
let mut writer = VmWriter::from(buf.as_mut_bytes()).to_fallible();
let mut printer = VmPrinter::from(&mut writer);
let res = writeln!(printer, "test");
@ -132,7 +133,7 @@ mod test {
#[ktest]
fn write_with_skip() {
let mut buf = [0u8; 3];
let mut writer = VmWriter::from(buf.as_bytes_mut()).to_fallible();
let mut writer = VmWriter::from(buf.as_mut_bytes()).to_fallible();
let mut printer = VmPrinter::new_skip(&mut writer, 3);
let res = writeln!(printer, "val: {}", 123);
@ -145,7 +146,7 @@ mod test {
#[ktest]
fn skip_all_content() {
let mut buf = [0u8; 64];
let mut writer = VmWriter::from(buf.as_bytes_mut()).to_fallible();
let mut writer = VmWriter::from(buf.as_mut_bytes()).to_fallible();
let mut printer = VmPrinter::new_skip(&mut writer, 100);
let res = writeln!(printer, "short message");

View File

@ -5,13 +5,14 @@ use core::{fmt::Debug, marker::PhantomData};
use aster_rights::{Dup, Exec, Full, Read, Signal, TRightSet, TRights, Write};
use aster_rights_proc::require;
use ostd::{
Error, Pod, Result,
Error, Result,
mm::{
Daddr, HasDaddr, HasPaddr, Paddr, PodOnce, VmIo, VmIoOnce,
dma::DmaDirection,
io_util::{HasVmReaderWriter, VmReaderWriterTypes},
},
};
use ostd_pod::Pod;
/// Safe pointers.
///

View File

@ -1,39 +0,0 @@
// SPDX-License-Identifier: MPL-2.0
use ostd::Pod;
/// A reader to read `Pod` fields from a `Pod` type.
pub struct Reader<'a> {
bytes: &'a [u8],
}
impl<'a> Reader<'a> {
pub fn new<T: Pod>(object: &'a T) -> Self {
Self {
bytes: object.as_bytes(),
}
}
pub fn read_at<F: Pod>(&self, field_offset: usize, _type_infer: *const F) -> F {
F::from_bytes(&self.bytes[field_offset..])
}
}
#[macro_export]
macro_rules! read_union_field {
($container:expr, $type:ty, $($field:tt)+) => {{
use $crate::union_read_ptr::Reader;
// Perform type checking first.
let container: &$type = $container;
let reader = Reader::new(container);
let field_offset = core::mem::offset_of!($type, $($field)*);
let type_infer = ostd::ptr_null_of!({
// This is not safe, but the code won't be executed.
&raw const container.$($field)*
});
reader.read_at(field_offset, type_infer)
}}
}

View File

@ -3,7 +3,6 @@
use core::fmt;
use ostd::{
Pod,
arch::cpu::context::{CpuExceptionInfo, UserContext},
cpu::PinCurrentCpu,
task::DisabledPreemptGuard,
@ -45,6 +44,7 @@ impl LinuxAbi for UserContext {
/// Reference: <https://elixir.bootlin.com/linux/v6.15.7/source/arch/loongarch/include/uapi/asm/sigcontext.h#L20>
#[repr(C)]
#[repr(align(16))]
#[padding_struct]
#[derive(Clone, Copy, Debug, Default, Pod)]
pub struct SigContext {
pub pc: usize,

View File

@ -3,7 +3,6 @@
use core::fmt;
use ostd::{
Pod,
arch::cpu::context::{CpuException, UserContext},
cpu::PinCurrentCpu,
task::DisabledPreemptGuard,

View File

@ -4,7 +4,6 @@ use alloc::{borrow::ToOwned, collections::btree_set::BTreeSet, string::String, v
use core::{arch::x86_64::CpuidResult, ffi::CStr, fmt, str};
use ostd::{
Pod,
arch::{
cpu::{
context::{CpuException, PageFaultErrorCode, RawPageFaultInfo, UserContext},

View File

@ -13,7 +13,6 @@ use aster_input::{
};
use atomic_integer_wrapper::define_atomic_version_of_integer_like_type;
use ostd::{
Pod,
mm::{VmReader, VmWriter},
sync::Mutex,
};

View File

@ -4,10 +4,7 @@ use alloc::sync::Arc;
use aster_framebuffer::{ColorMapEntry, FRAMEBUFFER, FrameBuffer, MAX_CMAP_SIZE, PixelFormat};
use device_id::{DeviceId, MajorId, MinorId};
use ostd::{
Pod,
mm::{HasPaddr, HasSize, VmIo, io_util::HasVmReaderWriter},
};
use ostd::mm::{HasPaddr, HasSize, VmIo, io_util::HasVmReaderWriter};
use super::registry::char;
use crate::{
@ -149,6 +146,7 @@ struct FbVarScreenInfo {
///
/// Reference: <https://elixir.bootlin.com/linux/v6.17/source/include/uapi/linux/fb.h#L158>.
#[repr(C)]
#[padding_struct]
#[derive(Debug, Default, Clone, Copy, Pod)]
struct FbFixScreenInfo {
/// Identification string (e.g., "EFI VGA")

View File

@ -192,6 +192,7 @@ impl<D: TtyDriver> Tty<D> {
height,
charcount,
data,
..
} = font_op;
let vpitch = match *op {

View File

@ -318,8 +318,9 @@ pub struct CWinSize {
/// A font operation; `struct console_font_op` in Linux.
///
/// Reference: <https://elixir.bootlin.com/linux/v6.15/source/include/uapi/linux/kd.h#L159>.
#[derive(Debug, Clone, Copy, Default, Pod)]
#[repr(C)]
#[padding_struct]
#[derive(Debug, Clone, Copy, Default, Pod)]
pub struct CFontOp {
pub(super) op: u32,
pub(super) flags: u32,

View File

@ -29,10 +29,10 @@ use aster_systree::{
};
use inherit_methods_macro::inherit_methods;
use ostd::{
Pod,
mm::{VmReader, VmWriter},
prelude::ktest,
};
use ostd_pod::IntoBytes;
use spin::Once;
use crate::{
@ -191,7 +191,7 @@ fn test_config_fs() {
// Test attr_a read/write on demo_foo
assert!(
attr_a_foo
.read_bytes_at(0, read_buffer.as_bytes_mut())
.read_bytes_at(0, read_buffer.as_mut_bytes())
.is_ok()
);
assert_eq!(read_buffer, 0);
@ -204,7 +204,7 @@ fn test_config_fs() {
);
assert!(
attr_a_foo
.read_bytes_at(0, read_buffer.as_bytes_mut())
.read_bytes_at(0, read_buffer.as_mut_bytes())
.is_ok()
);
assert_eq!(read_buffer, 42);
@ -212,7 +212,7 @@ fn test_config_fs() {
// Test attr_b read/write on demo_foo
assert!(
attr_b_foo
.read_bytes_at(0, read_buffer.as_bytes_mut())
.read_bytes_at(0, read_buffer.as_mut_bytes())
.is_ok()
);
assert_eq!(read_buffer, 0);
@ -225,7 +225,7 @@ fn test_config_fs() {
);
assert!(
attr_b_foo
.read_bytes_at(0, read_buffer.as_bytes_mut())
.read_bytes_at(0, read_buffer.as_mut_bytes())
.is_ok()
);
assert_eq!(read_buffer, 100);
@ -236,7 +236,7 @@ fn test_config_fs() {
// Verify that demo_bar has independent state from demo_foo
assert!(
attr_a_bar
.read_bytes_at(0, read_buffer.as_bytes_mut())
.read_bytes_at(0, read_buffer.as_mut_bytes())
.is_ok()
);
assert_eq!(read_buffer, 0); // Should be 0, not 42 like demo_foo
@ -249,7 +249,7 @@ fn test_config_fs() {
);
assert!(
attr_a_bar
.read_bytes_at(0, read_buffer.as_bytes_mut())
.read_bytes_at(0, read_buffer.as_mut_bytes())
.is_ok()
);
assert_eq!(read_buffer, 200);
@ -257,7 +257,7 @@ fn test_config_fs() {
// Verify demo_foo's attr_a is still 42
assert!(
attr_a_foo
.read_bytes_at(0, read_buffer.as_bytes_mut())
.read_bytes_at(0, read_buffer.as_mut_bytes())
.is_ok()
);
assert_eq!(read_buffer, 42);

View File

@ -1,7 +1,5 @@
// SPDX-License-Identifier: MPL-2.0
use ostd::Pod;
use super::constants::{EXFAT_FIRST_CLUSTER, EXFAT_RESERVED_CLUSTERS, MEDIA_FAILURE, VOLUME_DIRTY};
use crate::prelude::*;

View File

@ -69,7 +69,7 @@ impl BlockPtrs {
/// Views it as a mutable slice of `u8` bytes.
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
self.inner.as_bytes_mut()
self.inner.as_mut_bytes()
}
}

View File

@ -1333,7 +1333,7 @@ impl InodeImpl {
pub fn device_id(&self) -> u64 {
let mut device_id: u64 = 0;
device_id
.as_bytes_mut()
.as_mut_bytes()
.copy_from_slice(&self.desc.block_ptrs.as_bytes()[..size_of::<u64>()]);
device_id
}

View File

@ -578,7 +578,9 @@ impl From<&SuperBlock> for RawSuperBlock {
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod)]
struct Reserved([u32; 190]);
// FIXME: `pub(super)` is needed due to a bug in `zerocopy`. See
// <https://github.com/google/zerocopy/issues/1292>.
pub(super) struct Reserved([u32; 190]);
impl Default for Reserved {
fn default() -> Self {

View File

@ -52,6 +52,7 @@ pub struct SemaphoreSet {
// https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/ipcbuf.h
#[repr(C)]
#[padding_struct]
#[derive(Debug, Copy, Clone, Default, Pod)]
pub struct IpcPerm {
key: u32,
@ -70,21 +71,34 @@ pub struct IpcPerm {
// In Linux, most popular 64-bit architectures except x86_64 adopt the same
// layout of `semid_ds`.
// Reference: <https://elixir.bootlin.com/linux/v6.16.9/A/ident/semid64_ds>.
#[cfg(target_arch = "x86_64")]
#[repr(C)]
#[padding_struct]
#[derive(Debug, Copy, Clone, Default, Pod)]
pub struct SemidDs {
sem_perm: IpcPerm,
sem_otime: u64,
#[cfg(target_arch = "x86_64")]
_unused1: u64,
sem_ctime: u64,
#[cfg(target_arch = "x86_64")]
_unused2: u64,
sem_nsems: u64,
_unused3: u64,
_unused4: u64,
}
#[cfg(not(target_arch = "x86_64"))]
#[repr(C)]
#[padding_struct]
#[derive(Debug, Copy, Clone, Default, Pod)]
pub struct SemidDs {
sem_perm: IpcPerm,
sem_otime: u64,
sem_ctime: u64,
sem_nsems: u64,
_unused3: u64,
_unused4: u64,
}
#[derive(Debug)]
pub(super) struct SemSetInner {
/// Semaphores

View File

@ -6,6 +6,7 @@
#![no_std]
#![no_main]
#![deny(unsafe_code)]
#![feature(associated_type_defaults)]
#![feature(btree_cursors)]
#![feature(debug_closure_helpers)]
#![feature(format_args_nl)]
@ -17,7 +18,6 @@
#![feature(min_specialization)]
#![feature(thin_box)]
#![feature(trait_alias)]
#![feature(associated_type_defaults)]
#![register_tool(component_access_control)]
extern crate alloc;
@ -26,6 +26,8 @@ extern crate lru;
extern crate controlled;
#[macro_use]
extern crate getset;
#[macro_use]
extern crate ostd_pod;
#[cfg_attr(target_arch = "x86_64", path = "arch/x86/mod.rs")]
#[cfg_attr(target_arch = "riscv64", path = "arch/riscv/mod.rs")]

View File

@ -129,7 +129,7 @@ impl<Message: 'static> ProtocolSocketTable<Message> {
let mut random_port = current!().pid();
while random_port == UNSPECIFIED_PORT || self.unicast_sockets.contains_key(&random_port)
{
getrandom(random_port.as_bytes_mut());
getrandom(random_port.as_mut_bytes());
}
random_port
};

View File

@ -17,10 +17,10 @@ pub(crate) use bitflags::bitflags;
pub(crate) use int_to_c_enum::TryFromInt;
pub(crate) use log::{debug, error, info, log_enabled, trace, warn};
pub(crate) use ostd::{
Pod,
mm::{FallibleVmRead, FallibleVmWrite, PAGE_SIZE, Vaddr, VmReader, VmWriter},
sync::{Mutex, MutexGuard, RwLock, RwMutex, SpinLock, SpinLockGuard},
};
pub(crate) use ostd_pod::{FromBytes, FromZeros, IntoBytes, Pod};
/// return current process
#[macro_export]

View File

@ -63,7 +63,7 @@ impl Heap {
// make the heap values of a buggy user program harder
// to be exploited by attackers.
let mut nr_random_padding_pages: u8 = 0;
getrandom(nr_random_padding_pages.as_bytes_mut());
getrandom(nr_random_padding_pages.as_mut_bytes());
nr_random_padding_pages as usize
};

View File

@ -134,7 +134,7 @@ impl InitStack {
// make the stack values of a buggy user program harder
// to be exploited by attackers.
let mut nr_random_padding_pages: u8 = 0;
getrandom(nr_random_padding_pages.as_bytes_mut());
getrandom(nr_random_padding_pages.as_mut_bytes());
nr_random_padding_pages as usize + NR_FIXED_PADDING_PAGES
};

View File

@ -259,7 +259,7 @@ fn map_segment_vmos(
// Add some random padding.
let nr_pages_padding = {
let mut nr_random_padding_pages: u8 = 0;
getrandom(nr_random_padding_pages.as_bytes_mut());
getrandom(nr_random_padding_pages.as_mut_bytes());
nr_random_padding_pages as usize
};
let offset = (PIE_BASE_ADDR + nr_pages_padding * PAGE_SIZE).align_down(align);

View File

@ -3,7 +3,6 @@
#![expect(dead_code)]
#![expect(non_camel_case_types)]
use aster_util::read_union_field;
use inherit_methods_macro::inherit_methods;
use ostd::arch::cpu::context::UserContext;
@ -18,8 +17,9 @@ pub type sigset_t = u64;
// FIXME: this type should be put at suitable place
pub type clock_t = i64;
#[derive(Debug, Clone, Copy, Pod)]
#[repr(C)]
#[padding_struct]
#[derive(Debug, Clone, Copy, Default, Pod)]
pub struct sigaction_t {
pub handler_ptr: Vaddr,
pub flags: u32,
@ -27,8 +27,9 @@ pub struct sigaction_t {
pub mask: sigset_t,
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[padding_struct]
#[derive(Clone, Copy, Pod, Default)]
pub struct siginfo_t {
pub si_signo: i32,
pub si_errno: i32,
@ -36,8 +37,6 @@ pub struct siginfo_t {
// In x86_64, there will be a 4-bytes padding here automatically, the offset of `siginfo_fields` is `0x10`.
// Yet in other architectures like arm64, there is no padding here and the offset of `siginfo_fields` is `0x0c`.
//_padding: i32,
/// siginfo_fields should be a union type ( See occlum definition ). But union type have unsafe interfaces.
/// Here we use a simple byte array.
siginfo_fields: siginfo_fields_t,
}
@ -48,43 +47,55 @@ impl siginfo_t {
si_errno: 0,
si_code: code,
siginfo_fields: siginfo_fields_t::zero_fields(),
..Default::default()
}
}
pub fn set_si_addr(&mut self, si_addr: Vaddr) {
self.siginfo_fields.sigfault.addr = si_addr;
self.siginfo_fields.sigfault_mut().addr = si_addr;
}
pub fn set_pid_uid(&mut self, pid: Pid, uid: Uid) {
let pid_uid = siginfo_common_first_t {
piduid: siginfo_piduid_t { pid, uid },
let pid_uid = {
let pid_uid = siginfo_piduid_t { pid, uid };
siginfo_common_first_t::new_piduid(pid_uid)
};
self.siginfo_fields.common.first = pid_uid;
self.siginfo_fields.common_mut().first = pid_uid;
}
pub fn set_status(&mut self, status: i32) {
self.siginfo_fields.common.second.sigchild.status = status;
*self
.siginfo_fields
.common_mut()
.second
.sigchild_mut()
.status_mut() = status;
}
pub fn si_addr(&self) -> Vaddr {
read_union_field!(self, Self, siginfo_fields.sigfault.addr)
self.siginfo_fields.sigfault().addr
}
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[pod_union]
#[derive(Clone, Copy)]
union siginfo_fields_t {
bytes: [u8; 128 - size_of::<i32>() * 4],
common: siginfo_common_t,
sigfault: siginfo_sigfault_t,
}
impl Default for siginfo_fields_t {
fn default() -> Self {
Self::new_zeroed()
}
}
impl siginfo_fields_t {
fn zero_fields() -> Self {
Self {
bytes: [0; 128 - size_of::<i32>() * 4],
}
Self::new_zeroed()
}
}
@ -95,8 +106,9 @@ struct siginfo_common_t {
second: siginfo_common_second_t,
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[pod_union]
#[derive(Clone, Copy)]
union siginfo_common_first_t {
piduid: siginfo_piduid_t,
timer: siginfo_timer_t,
@ -116,15 +128,17 @@ struct siginfo_timer_t {
overrun: i32,
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[pod_union]
#[derive(Clone, Copy)]
union siginfo_common_second_t {
value: sigval_t,
sigchild: siginfo_sigchild_t,
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[pod_union]
#[derive(Clone, Copy)]
pub union sigval_t {
sigval_int: i32,
sigval_ptr: Vaddr, //*mut c_void
@ -132,39 +146,43 @@ pub union sigval_t {
impl sigval_t {
pub fn read_int(&self) -> i32 {
read_union_field!(self, Self, sigval_int)
*self.sigval_int()
}
pub fn read_ptr(&self) -> Vaddr {
read_union_field!(self, Self, sigval_ptr)
*self.sigval_ptr()
}
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[pod_union]
#[derive(Clone, Copy)]
union siginfo_sigchild_t {
status: i32,
utime: clock_t,
stime: clock_t,
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[padding_struct]
#[derive(Clone, Copy, Pod)]
struct siginfo_sigfault_t {
addr: Vaddr, //*const c_void
addr_lsb: i16,
first: siginfo_sigfault_first_t,
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[pod_union]
#[derive(Clone, Copy)]
union siginfo_sigfault_first_t {
addr_bnd: siginfo_addr_bnd_t,
pkey: u32,
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[pod_union]
#[derive(Clone, Copy)]
union siginfo_addr_bnd_t {
lower: Vaddr, // *const c_void
upper: Vaddr, // *const c_void,
@ -185,6 +203,7 @@ pub struct ucontext_t {
/// Reference: <https://elixir.bootlin.com/linux/v6.15.7/source/arch/riscv/include/uapi/asm/ucontext.h>
/// Reference: <https://elixir.bootlin.com/linux/v6.15.7/source/arch/loongarch/include/uapi/asm/ucontext.h>
#[cfg(any(target_arch = "riscv64", target_arch = "loongarch64"))]
#[padding_struct]
#[derive(Clone, Copy, Debug, Pod)]
#[repr(C)]
pub struct ucontext_t {
@ -211,14 +230,21 @@ impl Default for ucontext_t {
uc_sigmask: Default::default(),
__unused: [0; 120],
uc_mcontext: Default::default(),
__pad1: [0; _],
__pad2: [0; _],
__pad3: [0; _],
__pad4: [0; _],
__pad5: [0; _],
__pad6: [0; _],
}
}
}
pub type stack_t = sigaltstack_t;
#[derive(Debug, Clone, Copy, Pod, Default)]
#[repr(C)]
#[padding_struct]
#[derive(Debug, Clone, Copy, Pod, Default)]
pub struct sigaltstack_t {
pub ss_sp: Vaddr, // *mut c_void
pub ss_flags: i32,
@ -253,8 +279,9 @@ const SIGEV_MAX_SIZE: usize = 64;
const SIGEV_PREAMBLE_SIZE: usize = size_of::<i32>() * 2 + size_of::<sigval_t>();
const SIGEV_PAD_SIZE: usize = (SIGEV_MAX_SIZE - SIGEV_PREAMBLE_SIZE) / size_of::<i32>();
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[pod_union]
#[derive(Clone, Copy)]
pub union _sigev_un {
pub _pad: [i32; SIGEV_PAD_SIZE],
pub _tid: i32,
@ -263,15 +290,15 @@ pub union _sigev_un {
impl _sigev_un {
pub fn read_tid(&self) -> i32 {
read_union_field!(self, Self, _tid)
*self._tid()
}
pub fn read_function(&self) -> Vaddr {
read_union_field!(self, Self, _sigev_thread.function)
self._sigev_thread().function
}
pub fn read_attribute(&self) -> Vaddr {
read_union_field!(self, Self, _sigev_thread.attribute)
self._sigev_thread().attribute
}
}
@ -284,8 +311,8 @@ pub enum SigNotify {
SIGEV_THREAD_ID = 4,
}
#[derive(Clone, Copy, Pod)]
#[repr(C)]
#[derive(Clone, Copy, Pod)]
pub struct sigevent_t {
pub sigev_value: sigval_t,
pub sigev_signo: i32,

View File

@ -57,12 +57,14 @@ impl SigAction {
flags: 0,
restorer_ptr: 0,
mask: 0,
..Default::default()
},
SigAction::Ign => sigaction_t {
handler_ptr: SIG_IGN,
flags: 0,
restorer_ptr: 0,
mask: 0,
..Default::default()
},
SigAction::User {
handler_addr,
@ -74,6 +76,7 @@ impl SigAction {
flags: flags.as_u32(),
restorer_ptr: *restorer_addr,
mask: (*mask).into(),
..Default::default()
},
}
}

View File

@ -99,6 +99,7 @@ impl From<&SigStack> for stack_t {
ss_sp: value.base,
ss_flags: value.flags.bits as _,
ss_size: value.size,
..Default::default()
}
}
}

View File

@ -266,21 +266,24 @@ pub fn sys_epoll_pwait2(
Ok(SyscallReturn::Return(events_len as _))
}
#[derive(Debug, Clone, Copy, Pod)]
#[repr(C)]
// Here we use `repr(packed)` on x86_64 to ensure the same layout as Linux.
// Reference: <https://elixir.bootlin.com/linux/v6.16.9/source/include/uapi/linux/eventpoll.h#L71-L81>.
#[cfg_attr(target_arch = "x86_64", repr(packed))]
#[cfg_attr(not(target_arch = "x86_64"), padding_struct)]
#[derive(Debug, Clone, Copy, Pod, Default)]
struct c_epoll_event {
events: u32,
data: u64,
}
impl From<&EpollEvent> for c_epoll_event {
#[cfg_attr(target_arch = "x86_64", expect(clippy::needless_update))]
fn from(ep_event: &EpollEvent) -> Self {
Self {
events: ep_event.events.bits(),
data: ep_event.user_data,
..Default::default()
}
}
}

View File

@ -213,6 +213,7 @@ pub enum RangeLockWhence {
/// C struct for a file range lock in Libc
#[repr(C)]
#[padding_struct]
#[derive(Debug, Copy, Clone, Pod)]
pub struct c_flock {
/// Type of lock: F_RDLCK, F_WRLCK, or F_UNLCK

View File

@ -47,6 +47,7 @@ pub fn sys_sendmmsg(
}
#[repr(C)]
#[padding_struct]
#[derive(Debug, Clone, Copy, Pod)]
struct CMmsgHdr {
msg_hdr: CUserMsgHdr,

View File

@ -48,6 +48,7 @@ fn get_old_stack(ctx: &Context, sp: usize) -> Result<stack_t> {
ss_sp: old_stack.base(),
ss_flags: flags.cast_signed(),
ss_size: old_stack.size(),
..Default::default()
};
Ok(stack)

View File

@ -6,8 +6,9 @@ use ostd::mm::VmIo;
use super::SyscallReturn;
use crate::{prelude::*, process::process_table};
#[derive(Debug, Default, Clone, Copy, Pod)]
#[repr(C)]
#[padding_struct]
#[derive(Debug, Default, Clone, Copy, Pod)]
struct SysInfo {
uptime: i64, /* Seconds since boot */
loads: [u64; 3], /* 1, 5, and 15 minute load averages */

View File

@ -1,7 +1,5 @@
// SPDX-License-Identifier: MPL-2.0
use ostd::Pod;
use crate::prelude::*;
/// A trait that can copies structures from/to the user space in a backward-compatible way.
@ -37,7 +35,7 @@ impl CopyCompat for CurrentUserSpace<'_> {
let mut val = T::new_zeroed();
let mut reader = self.reader(src, size)?;
reader.read_fallible(&mut VmWriter::from(val.as_bytes_mut()))?;
reader.read_fallible(&mut VmWriter::from(val.as_mut_bytes()))?;
while reader.remain() > size_of::<u64>() {
if reader.read_val::<u64>()? != 0 {

View File

@ -272,7 +272,7 @@ impl dyn MultiRead + '_ {
/// Reads a `T` value, returning a `None` if the readers have insufficient bytes.
pub fn read_val_opt<T: Pod>(&mut self) -> Result<Option<T>> {
let mut val = T::new_zeroed();
let nbytes = self.read(&mut VmWriter::from(val.as_bytes_mut()))?;
let nbytes = self.read(&mut VmWriter::from(val.as_mut_bytes()))?;
if nbytes == size_of::<T>() {
Ok(Some(val))

View File

@ -145,7 +145,7 @@ pub fn read_socket_addr_from_user(addr: Vaddr, addr_len: usize) -> Result<Socket
}
let mut storage = Storage::new_zeroed();
current_userspace!().read_bytes(addr, &mut storage.as_bytes_mut()[..addr_len])?;
current_userspace!().read_bytes(addr, &mut storage.as_mut_bytes()[..addr_len])?;
let result = match CSocketAddrFamily::try_from(storage.sa_family as i32) {
Ok(CSocketAddrFamily::AF_INET) => {

View File

@ -43,7 +43,7 @@ where
// bytes may exceed the size of `CSocketAddrUnix`. This is to match the Linux
// implementation. See the "BUGS" section at
// <https://man7.org/linux/man-pages/man7/unix.7.html>.
let mut bytes: [u8; CSocketAddrUnix::MAX_LEN + 1] = Pod::new_zeroed();
let mut bytes: [u8; CSocketAddrUnix::MAX_LEN + 1] = FromZeros::new_zeroed();
bytes[..2].copy_from_slice(&(CSocketAddrFamily::AF_UNIX as u16).to_ne_bytes());
const { assert!(CSocketAddrUnix::PATH_OFFSET == 2) };

View File

@ -78,6 +78,7 @@ bitflags! {
}
#[repr(C)]
#[padding_struct]
#[derive(Debug, Clone, Copy, Pod)]
pub struct CUserMsgHdr {
/// Pointer to socket address structure

View File

@ -18,10 +18,11 @@ use core::{mem::ManuallyDrop, time::Duration};
use aster_time::{Instant, read_monotonic_time};
use aster_util::coeff::Coeff;
use ostd::{
Pod, const_assert,
const_assert,
mm::{PAGE_SIZE, UFrame, VmIo, VmIoOnce},
sync::SpinLock,
};
use ostd_pod::IntoBytes;
use spin::Once;
use crate::{

View File

@ -36,6 +36,7 @@ ostd-pod.workspace = true
spin.workspace = true
smallvec.workspace = true
volatile.workspace = true
zerocopy.workspace = true
# The targets are chosen to prevent the generated machine code from using any
# vector or floating-point registers.

View File

@ -11,10 +11,11 @@ edition.workspace = true
[dependencies]
align_ext.workspace = true
bitflags.workspace = true
bytemuck.workspace = true
libflate = { workspace = true, features = [ "std" ] }
ostd-pod.workspace = true
serde.workspace = true
xmas-elf.workspace = true
zerocopy.workspace = true
[lints]
workspace = true

View File

@ -13,6 +13,9 @@
//! The setup code should be built into the ELF target and we convert it to a flat binary
//! in the builder.
#[macro_use]
extern crate ostd_pod;
pub mod encoder;
mod mapping;
mod pe_header;

View File

@ -11,8 +11,8 @@
use std::vec;
use align_ext::AlignExt;
use bytemuck::{Pod, Zeroable};
use serde::Serialize;
use zerocopy::IntoBytes;
use crate::mapping::{LEGACY_SETUP_SEC_SIZE, SetupFileOffset, SetupVA};
@ -50,7 +50,7 @@ bitflags::bitflags! {
}
}
#[derive(Zeroable, Pod, Serialize, Clone, Copy)]
#[derive(Pod, Serialize, Clone, Copy)]
#[repr(C, packed)]
struct PeHdr {
magic: u32, // PE magic
@ -73,7 +73,7 @@ enum PeImageSubsystem {
EfiApplication = 10,
}
#[derive(Zeroable, Pod, Serialize, Clone, Copy)]
#[derive(Pod, Serialize, Clone, Copy)]
#[repr(C, packed)]
struct Pe32PlusOptHdr {
magic: u16, // file type
@ -107,7 +107,7 @@ struct Pe32PlusOptHdr {
data_dirs: u32, // number of data dir entries
}
#[derive(Zeroable, Pod, Serialize, Clone, Copy)]
#[derive(Pod, Serialize, Clone, Copy)]
#[repr(C, packed)]
struct Pe32PlusOptDataDirEnt {
/// The RVA is the address of the table relative to the base address of the image when the table is loaded.
@ -126,7 +126,7 @@ impl Pe32PlusOptDataDirEnt {
/// The `data_dirs` number field in the PE32+ optional header is just an illusion that you can choose to have a
/// subset of the data directories. The actual number of data directories is fixed to 16 and you can only ignore
/// data directories at the end of the list. We ignore data directories after the 8th as what Linux do.
#[derive(Zeroable, Pod, Serialize, Clone, Copy)]
#[derive(Pod, Serialize, Clone, Copy)]
#[repr(C, packed)]
struct Pe32PlusOptDataDirs {
export_table: Pe32PlusOptDataDirEnt,
@ -166,7 +166,7 @@ bitflags::bitflags! {
}
}
#[derive(Zeroable, Pod, Serialize, Clone, Copy)]
#[derive(Pod, Serialize, Clone, Copy)]
#[repr(C, packed)]
struct PeSectionHdr {
name: [u8; 8], // name or "/12\0" string tbl offset
@ -263,13 +263,13 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8]) -> Vec<u8> {
// Write the PE header
pe_hdr.sections = sec_hdr_vec.len() as u16;
bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr));
bin.extend_from_slice(pe_hdr.as_bytes());
// Write the PE32+ optional header
bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr));
bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs));
bin.extend_from_slice(pe_opt_hdr.as_bytes());
bin.extend_from_slice(pe_opt_hdr_data_dirs.as_bytes());
// Write the PE section headers
for sec_hdr in sec_hdr_vec {
bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr));
bin.extend_from_slice(sec_hdr.as_bytes());
}
bin

View File

@ -1,7 +1,8 @@
[package]
name = "ostd-pod"
# REMINDER: Whenever you change this number,
# update the external documentation links in README.md.
# update all occurrences of the version in README
# (e.g., in external links and in the sample Cargo.toml).
version = "0.4.0"
description = "A trait for plain old data (POD)"
readme = "README.md"

View File

@ -29,7 +29,7 @@ pub fn expand_derive(attrs: TokenStream, input: TokenStream) -> TokenStream {
let attr_tokens = proc_macro2::TokenStream::from(attrs);
for token in attr_tokens.into_iter() {
match token {
TokenTree::Ident(ident) if ident.to_string() == "Pod" => {
TokenTree::Ident(ident) if ident == "Pod" => {
// Replace Pod with zerocopy traits
push_zerocopy_derive(&mut new_derives, "FromBytes", true);
push_zerocopy_derive(&mut new_derives, "IntoBytes", true);

View File

@ -2,16 +2,13 @@
use core::{arch::asm, intrinsics::AtomicOrdering::Relaxed, ops::Range};
use crate::{
Pod,
mm::{
PAGE_SIZE, Paddr, PagingConstsTrait, PagingLevel, PodOnce, Vaddr,
dma::DmaDirection,
page_prop::{
CachePolicy, PageFlags, PageProperty, PageTableFlags, PrivilegedPageFlags as PrivFlags,
},
page_table::{PteScalar, PteTrait},
use crate::mm::{
PAGE_SIZE, Paddr, PagingConstsTrait, PagingLevel, PodOnce, Vaddr,
dma::DmaDirection,
page_prop::{
CachePolicy, PageFlags, PageProperty, PageTableFlags, PrivilegedPageFlags as PrivFlags,
},
page_table::{PteScalar, PteTrait},
};
#[derive(Clone, Debug, Default)]

View File

@ -5,7 +5,7 @@
use alloc::boxed::Box;
use core::{arch::global_asm, fmt::Debug};
use ostd_pod::Pod;
use ostd_pod::IntoBytes;
use riscv::{
interrupt::supervisor::{Exception, Interrupt},
register::scause::Trap,
@ -375,9 +375,9 @@ impl FpuContext {
/// Returns the FPU context as a mutable byte slice.
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
match self {
Self::F(ctx) => ctx.as_bytes_mut(),
Self::D(ctx) => ctx.as_bytes_mut(),
Self::Q(ctx) => ctx.as_bytes_mut(),
Self::F(ctx) => ctx.as_mut_bytes(),
Self::D(ctx) => ctx.as_mut_bytes(),
Self::Q(ctx) => ctx.as_mut_bytes(),
Self::None => &mut [],
}
}
@ -399,6 +399,7 @@ pub struct FFpuContext {
/// FPU context for D extension (64-bit floating point).
#[repr(C)]
#[padding_struct]
#[derive(Clone, Copy, Debug, Default, Pod)]
pub struct DFpuContext {
f: [u64; 32],
@ -407,6 +408,7 @@ pub struct DFpuContext {
/// FPU context for Q extension (128-bit floating point).
#[repr(C)]
#[padding_struct]
#[derive(Clone, Copy, Debug, Pod)]
pub struct QFpuContext {
f: [u64; 64],
@ -423,6 +425,8 @@ impl Default for QFpuContext {
Self {
f: [0; 64],
fcsr: 0,
__pad1: [0; _],
__pad2: [0; _],
}
}
}

View File

@ -8,7 +8,6 @@ pub(crate) use util::{
};
use crate::{
Pod,
arch::{
boot::DEVICE_TREE,
cpu::extension::{IsaExtensions, has_extensions},

View File

@ -8,7 +8,7 @@ use core::arch::x86_64::{_fxrstor64, _fxsave64, _xrstor64, _xsave64};
use bitflags::bitflags;
use cfg_if::cfg_if;
use log::debug;
use ostd_pod::Pod;
use ostd_pod::{FromZeros, IntoBytes};
use spin::Once;
use x86::bits64::segmentation::wrfsbase;
use x86_64::registers::{
@ -551,7 +551,7 @@ impl FpuContext {
/// Returns the FPU context as a mutable byte slice.
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
&mut self.xsave_area.as_bytes_mut()[..self.area_size]
&mut self.xsave_area.as_mut_bytes()[..self.area_size]
}
}

View File

@ -5,7 +5,6 @@
use alloc::collections::BTreeMap;
use log::trace;
use ostd_pod::Pod;
use super::second_stage::IommuPtConfig;
use crate::{

View File

@ -2,13 +2,10 @@
use core::ops::Range;
use crate::{
Pod,
mm::{
Paddr, PageProperty, PagingConstsTrait, PagingLevel, PodOnce,
page_prop::{CachePolicy, PageFlags, PageTableFlags, PrivilegedPageFlags as PrivFlags},
page_table::{PageTableConfig, PteScalar, PteTrait},
},
use crate::mm::{
Paddr, PageProperty, PagingConstsTrait, PagingLevel, PodOnce,
page_prop::{CachePolicy, PageFlags, PageTableFlags, PrivilegedPageFlags as PrivFlags},
page_table::{PageTableConfig, PteScalar, PteTrait},
};
/// The page table used by iommu maps the device address

View File

@ -90,6 +90,7 @@ pub struct AtsrHeader {
/// This optional structure provides the association between each Remapping hardware unit (identified
/// by its espective Base Address) and the proximity domain to which that hardware unit belongs.
#[repr(C)]
#[padding_struct]
#[derive(Debug, Clone, Copy, Pod)]
pub struct Rhsa {
typ: u16,

View File

@ -13,16 +13,13 @@ use x86_64::{
structures::paging::PhysFrame,
};
use crate::{
Pod,
mm::{
PAGE_SIZE, Paddr, PagingConstsTrait, PagingLevel, PodOnce, Vaddr,
dma::DmaDirection,
page_prop::{
CachePolicy, PageFlags, PageProperty, PageTableFlags, PrivilegedPageFlags as PrivFlags,
},
page_table::{PteScalar, PteTrait},
use crate::mm::{
PAGE_SIZE, Paddr, PagingConstsTrait, PagingLevel, PodOnce, Vaddr,
dma::DmaDirection,
page_prop::{
CachePolicy, PageFlags, PageProperty, PageTableFlags, PrivilegedPageFlags as PrivFlags,
},
page_table::{PteScalar, PteTrait},
};
mod pat;

View File

@ -18,6 +18,8 @@
#![warn(missing_docs)]
extern crate alloc;
#[macro_use]
extern crate ostd_pod;
#[cfg_attr(target_arch = "x86_64", path = "arch/x86/mod.rs")]
#[cfg_attr(target_arch = "riscv64", path = "arch/riscv/mod.rs")]
@ -53,7 +55,6 @@ pub use ostd_macros::{
global_frame_allocator, global_heap_allocator, global_heap_allocator_slot_map, main,
panic_handler,
};
pub use ostd_pod::Pod;
pub use self::{error::Error, prelude::Result};

View File

@ -42,8 +42,10 @@
use core::{marker::PhantomData, mem::MaybeUninit};
use ostd_pod::Pod;
use crate::{
Error, Pod,
Error,
arch::mm::{
__atomic_cmpxchg_fallible, __atomic_load_fallible, __memcpy_fallible, __memset_fallible,
},
@ -109,7 +111,7 @@ pub trait VmIo {
// may not really initialize the bits of `val` at all!
let mut val = T::new_zeroed();
self.read_bytes(offset, val.as_bytes_mut())?;
self.read_bytes(offset, val.as_mut_bytes())?;
Ok(val)
}

View File

@ -10,7 +10,7 @@ use core::{
sync::atomic::{AtomicU32, Ordering},
};
use ostd_pod::Pod;
use ostd_pod::FromZeros;
use super::{PteTrait, pte_index};
use crate::{

View File

@ -12,12 +12,13 @@ use core::{
sync::atomic::{AtomicUsize, Ordering},
};
use ostd_pod::Pod;
use super::{
HasPaddr, Paddr, PagingConstsTrait, PagingLevel, PodOnce, Vaddr, kspace::KernelPtConfig,
nr_subpage_per_huge, page_prop::PageProperty, page_size, vm_space::UserPtConfig,
};
use crate::{
Pod,
arch::mm::{PageTableEntry, PagingConsts},
mm::page_prop::PageTableFlags,
task::{atomic_mode::AsAtomicModeGuard, disable_preempt},

Some files were not shown because too many files have changed in this diff Show More