use super::xattr::XATTR_MAGIC;
use super::{ParseError, get_u16, get_u32, join64, put_u16, put_u32};
use crate::time::Timestamp;
pub const ROOT_INODE_MODE: u16 = 0o40755;
pub const GOOD_OLD_SIZE: usize = 128;
pub const GOOD_OLD_FIRST_INODE: u32 = 11;
#[must_use]
pub const fn extra_isize_for(inode_size: u16) -> u16 {
if inode_size as usize > GOOD_OLD_SIZE {
32
} else {
0
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct InodeFlags(u32);
crate::flags::flag_set!(InodeFlags: u32);
impl InodeFlags {
pub const EXTENTS: Self = Self(0x0008_0000);
pub const HUGE_FILE: Self = Self(0x0004_0000);
pub const INDEX: Self = Self(0x0000_1000);
pub const ENCRYPT: Self = Self(0x0000_0800);
pub const EA_INODE: Self = Self(0x0020_0000);
pub const INLINE_DATA: Self = Self(0x1000_0000);
pub const CASEFOLD: Self = Self(0x4000_0000);
}
pub const TIME_SECS_MIN: i64 = i32::MIN as i64;
pub const TIME_SECS_MAX: i64 = i32::MAX as i64 + (3 << 32);
#[must_use]
pub const fn time_is_representable(t: Timestamp, inode_size: u16) -> bool {
if inode_size as usize > GOOD_OLD_SIZE {
t.secs >= TIME_SECS_MIN && t.secs <= TIME_SECS_MAX && t.has_proper_fraction()
} else {
t.secs >= TIME_SECS_MIN && t.secs <= i32::MAX as i64 && t.nanos == 0
}
}
#[must_use]
pub const fn encode_time(t: Timestamp) -> (u32, u32) {
let field = t.secs as u32;
let low = field as i32 as i64;
let epoch = ((t.secs - low) >> 32) as u32;
let extra = (epoch & 0x3) | (t.nanos << 2);
(field, extra)
}
#[must_use]
pub const fn decode_time(field: u32, extra: u32) -> Timestamp {
let secs = (field as i32 as i64) + (((extra & 0x3) as i64) << 32);
Timestamp {
secs,
nanos: extra >> 2,
}
}
#[must_use]
pub(crate) fn encode_device(major: u32, minor: u32) -> (u32, u32) {
debug_assert!(
major < 1 << 12 && minor < 1 << 20,
"{major}:{minor} is out of range"
);
if major < 1 << 8 && minor < 1 << 8 {
return ((major << 8) | minor, 0);
}
let wide = (minor & 0xff) | (major << 8) | ((minor >> 8) << 20);
(0, wide)
}
#[must_use]
pub(crate) fn decode_device(block0: u32, block1: u32) -> (u32, u32) {
if block0 != 0 {
return ((block0 >> 8) & 0xff, block0 & 0xff);
}
let major = (block1 >> 8) & 0xfff;
let minor = (block1 & 0xff) | ((block1 >> 20) << 8);
(major, minor)
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Inode {
pub mode: u16,
pub uid: u32,
pub gid: u32,
pub size: u64,
pub links_count: u16,
pub blocks: u64,
pub flags: InodeFlags,
pub atime: Timestamp,
pub ctime: Timestamp,
pub mtime: Timestamp,
pub crtime: Timestamp,
pub dtime: u32,
pub generation: u32,
pub file_acl: u64,
pub extra_isize: u16,
pub block: [u8; Self::BLOCK_BYTES],
pub checksum: u32,
pub inline_xattr: Vec<u8>,
}
impl Inode {
pub const BLOCK_BYTES: usize = 60;
pub const BLOCK_OFFSET: usize = 0x28;
pub const EXTRA_ISIZE_OFFSET: usize = 0x80;
pub const CHECKSUM_LO_OFFSET: usize = 0x7c;
pub const CHECKSUM_HI_OFFSET: usize = 0x82;
#[must_use]
pub const fn fits(inode_size: u16, extra_isize: u16, off: usize, width: usize) -> bool {
let end = off + width;
end <= inode_size as usize && end <= GOOD_OLD_SIZE + extra_isize as usize
}
#[must_use]
pub const fn has_checksum_hi(inode_size: u16, extra_isize: u16) -> bool {
Self::fits(inode_size, extra_isize, Self::CHECKSUM_HI_OFFSET, 2)
}
pub const CRTIME_OFFSET: usize = 0x90;
#[must_use]
pub const fn has_crtime(inode_size: u16, extra_isize: u16) -> bool {
Self::fits(inode_size, extra_isize, Self::CRTIME_OFFSET, 4)
}
#[must_use]
pub fn empty(inode_size: u16) -> Self {
Self {
mode: 0,
uid: 0,
gid: 0,
size: 0,
links_count: 0,
blocks: 0,
flags: InodeFlags::NONE,
atime: Timestamp::default(),
ctime: Timestamp::default(),
mtime: Timestamp::default(),
crtime: Timestamp::default(),
dtime: 0,
generation: 0,
file_acl: 0,
extra_isize: extra_isize_for(inode_size),
block: [0u8; Self::BLOCK_BYTES],
checksum: 0,
inline_xattr: Vec::new(),
}
}
#[must_use]
pub fn inline_xattr_capacity(&self, inode_size: u16) -> usize {
(inode_size as usize).saturating_sub(GOOD_OLD_SIZE + self.extra_isize as usize)
}
#[must_use]
pub fn inline_xattr_capacity_for(inode_size: u16) -> usize {
(inode_size as usize).saturating_sub(GOOD_OLD_SIZE + extra_isize_for(inode_size) as usize)
}
pub fn write_to(&self, buf: &mut [u8], inode_size: u16) -> Result<(), ParseError> {
let size = check_inode_size(inode_size, buf.len())?;
let b = &mut buf[..size];
b.fill(0);
let (atime, atime_x) = encode_time(self.atime);
let (ctime, ctime_x) = encode_time(self.ctime);
let (mtime, mtime_x) = encode_time(self.mtime);
let (crtime, crtime_x) = encode_time(self.crtime);
let fits = |off, width| Self::fits(inode_size, self.extra_isize, off, width);
put_u16(b, 0x00, self.mode);
put_u16(b, 0x02, self.uid as u16);
put_u32(b, 0x04, self.size as u32);
put_u32(b, 0x08, atime);
put_u32(b, 0x0c, ctime);
put_u32(b, 0x10, mtime);
put_u32(b, 0x14, self.dtime);
put_u16(b, 0x18, self.gid as u16);
put_u16(b, 0x1a, self.links_count);
put_u32(b, 0x1c, self.blocks as u32);
put_u32(b, 0x20, self.flags.bits());
b[Self::BLOCK_OFFSET..Self::BLOCK_OFFSET + Self::BLOCK_BYTES].copy_from_slice(&self.block);
put_u32(b, 0x64, self.generation);
put_u32(b, 0x68, self.file_acl as u32);
put_u32(b, 0x6c, (self.size >> 32) as u32);
put_u16(b, 0x74, (self.blocks >> 32) as u16);
put_u16(b, 0x76, (self.file_acl >> 32) as u16);
put_u16(b, 0x78, (self.uid >> 16) as u16);
put_u16(b, 0x7a, (self.gid >> 16) as u16);
put_u16(b, Self::CHECKSUM_LO_OFFSET, self.checksum as u16);
if size >= Self::EXTRA_ISIZE_OFFSET + 2 {
put_u16(b, Self::EXTRA_ISIZE_OFFSET, self.extra_isize);
}
if fits(Self::CHECKSUM_HI_OFFSET, 2) {
put_u16(b, Self::CHECKSUM_HI_OFFSET, (self.checksum >> 16) as u16);
}
if fits(0x84, 4) {
put_u32(b, 0x84, ctime_x);
}
if fits(0x88, 4) {
put_u32(b, 0x88, mtime_x);
}
if fits(0x8c, 4) {
put_u32(b, 0x8c, atime_x);
}
if fits(Self::CRTIME_OFFSET, 4) {
put_u32(b, Self::CRTIME_OFFSET, crtime);
}
if fits(0x94, 4) {
put_u32(b, 0x94, crtime_x);
}
let xoff = GOOD_OLD_SIZE + self.extra_isize as usize;
if !self.inline_xattr.is_empty() && xoff < size {
debug_assert!(
xoff + self.inline_xattr.len() <= size,
"inline xattr region overflows the inode"
);
let n = self.inline_xattr.len().min(size - xoff);
b[xoff..xoff + n].copy_from_slice(&self.inline_xattr[..n]);
}
Ok(())
}
pub fn to_bytes(&self, inode_size: u16) -> Result<Vec<u8>, ParseError> {
let mut b = vec![0u8; inode_size as usize];
self.write_to(&mut b, inode_size)?;
Ok(b)
}
pub fn read_from(buf: &[u8], inode_size: u16) -> Result<Self, ParseError> {
let size = check_inode_size(inode_size, buf.len())?;
let mut block = [0u8; Self::BLOCK_BYTES];
block.copy_from_slice(&buf[Self::BLOCK_OFFSET..Self::BLOCK_OFFSET + Self::BLOCK_BYTES]);
let extra_isize = if size >= Self::EXTRA_ISIZE_OFFSET + 2 {
get_u16(buf, Self::EXTRA_ISIZE_OFFSET)
} else {
0
};
let fits = |off, width| Self::fits(inode_size, extra_isize, off, width);
let extra = |off| if fits(off, 4) { get_u32(buf, off) } else { 0 };
let xoff = GOOD_OLD_SIZE + extra_isize as usize;
let inline_xattr = match buf.get(xoff..size) {
Some(region) if region.len() >= 4 && get_u32(region, 0) == XATTR_MAGIC => {
region.to_vec()
}
_ => Vec::new(),
};
let checksum = {
let lo = u32::from(get_u16(buf, Self::CHECKSUM_LO_OFFSET));
if Self::has_checksum_hi(inode_size, extra_isize) {
lo | (u32::from(get_u16(buf, Self::CHECKSUM_HI_OFFSET)) << 16)
} else {
lo
}
};
let mode = get_u16(buf, 0x00);
let size_hi = if mode & 0o170000 == 0o100000 {
get_u32(buf, 0x6c)
} else {
0
};
Ok(Self {
mode,
uid: u32::from(get_u16(buf, 0x02)) | (u32::from(get_u16(buf, 0x78)) << 16),
gid: u32::from(get_u16(buf, 0x18)) | (u32::from(get_u16(buf, 0x7a)) << 16),
size: join64(get_u32(buf, 0x04), size_hi),
links_count: get_u16(buf, 0x1a),
blocks: join64(get_u32(buf, 0x1c), u32::from(get_u16(buf, 0x74))),
flags: InodeFlags::from_bits(get_u32(buf, 0x20)),
atime: decode_time(get_u32(buf, 0x08), extra(0x8c)),
ctime: decode_time(get_u32(buf, 0x0c), extra(0x84)),
mtime: decode_time(get_u32(buf, 0x10), extra(0x88)),
crtime: decode_time(extra(Self::CRTIME_OFFSET), extra(0x94)),
dtime: get_u32(buf, 0x14),
generation: get_u32(buf, 0x64),
file_acl: join64(get_u32(buf, 0x68), u32::from(get_u16(buf, 0x76))),
extra_isize,
block,
checksum,
inline_xattr,
})
}
}
fn check_inode_size(inode_size: u16, available: usize) -> Result<usize, ParseError> {
let size = inode_size as usize;
if size < GOOD_OLD_SIZE {
return Err(ParseError::InvalidField {
structure: "Inode",
field: "s_inode_size",
value: u64::from(inode_size),
});
}
if available < size {
return Err(ParseError::TooShort {
structure: "Inode",
need: size,
got: available,
});
}
Ok(size)
}
#[cfg(test)]
mod tests {
use super::*;
const S: u16 = 256;
fn root_like() -> Inode {
let t = Timestamp::from_secs(1_700_000_000);
let mut ino = Inode::empty(S);
ino.mode = ROOT_INODE_MODE;
ino.size = 4096;
ino.links_count = 3;
ino.blocks = 8;
ino.flags = InodeFlags::EXTENTS;
ino.atime = t;
ino.ctime = t;
ino.mtime = t;
ino.crtime = t;
ino
}
fn bytes(ino: &Inode, size: u16) -> Vec<u8> {
ino.to_bytes(size).expect("serializes")
}
#[test]
fn round_trips() {
let ino = root_like();
assert_eq!(Inode::read_from(&bytes(&ino, S), S).unwrap(), ino);
}
#[test]
fn matches_ground_truth_root_fields() {
let ino = root_like();
let b = bytes(&ino, S);
assert_eq!(get_u16(&b, 0x00), 0o40755);
assert_eq!(get_u32(&b, 0x20), InodeFlags::EXTENTS.bits());
assert_eq!(get_u32(&b, 0x04), 4096);
assert_eq!(get_u16(&b, 0x1a), 3);
assert_eq!(get_u32(&b, 0x1c), 8);
assert_eq!(get_u16(&b, 0x80), 32);
assert_eq!(get_u32(&b, 0x0c), 0x6553_f100);
assert_eq!(get_u32(&b, 0x84), 0, "ctime_extra: nanos 0, epoch bits 0");
}
#[test]
fn large_size_and_blocks_split_across_halves() {
let mut ino = Inode::empty(S);
ino.mode = 0o100600;
ino.size = 4_299_210_752;
ino.blocks = 80;
ino.links_count = 1;
let b = bytes(&ino, S);
assert_eq!(get_u32(&b, 0x04), 0x0040_c000, "size low");
assert_eq!(get_u32(&b, 0x6c), 1, "size high");
assert_eq!(Inode::read_from(&b, S).unwrap(), ino);
}
#[test]
fn only_a_regular_file_takes_its_size_from_both_words() {
let mut b = vec![0u8; S as usize];
put_u16(&mut b, 0x00, ROOT_INODE_MODE);
put_u32(&mut b, 0x04, 4096);
put_u32(&mut b, 0x6c, 1);
assert_eq!(
Inode::read_from(&b, S).unwrap().size,
4096,
"a directory's size is the low word alone"
);
put_u16(&mut b, 0x00, 0o120777);
assert_eq!(
Inode::read_from(&b, S).unwrap().size,
4096,
"and so is a symlink's"
);
put_u16(&mut b, 0x00, 0o100644);
assert_eq!(Inode::read_from(&b, S).unwrap().size, 4096 + (1 << 32));
}
#[test]
fn high_uid_gid_and_blocks_round_trip() {
let mut ino = Inode::empty(S);
ino.uid = 0x0012_3456;
ino.gid = 0x0065_4321;
ino.blocks = 0x1_0000_0000;
ino.file_acl = 0x1_0000_2000;
assert_eq!(Inode::read_from(&bytes(&ino, S), S).unwrap(), ino);
}
#[test]
fn round_trips_at_every_inode_size() {
for size in [128u16, 256, 512, 1024] {
let mut ino = Inode::empty(size);
ino.mode = ROOT_INODE_MODE;
ino.size = 4096;
ino.links_count = 3;
ino.mtime = Timestamp::from_secs(1_700_000_000);
let b = bytes(&ino, size);
assert_eq!(
b.len(),
size as usize,
"serializes exactly s_inode_size bytes"
);
assert_eq!(
Inode::read_from(&b, size).unwrap(),
ino,
"round trip at inode_size={size}"
);
}
}
#[test]
fn the_classic_inode_carries_no_extended_field() {
assert_eq!(extra_isize_for(128), 0);
assert!(!Inode::has_checksum_hi(128, 0));
assert!(!Inode::fits(128, 0, 0x84, 4), "no ctime_extra");
assert!(!Inode::fits(128, 0, 0x90, 4), "no crtime");
let mut ino = Inode::empty(128);
ino.mtime = Timestamp {
secs: 1_700_000_000,
nanos: 123_456_789,
};
ino.crtime = Timestamp::from_secs(1_700_000_000);
let back = Inode::read_from(&bytes(&ino, 128), 128).unwrap();
assert_eq!(back.mtime.secs, 1_700_000_000, "seconds survive");
assert_eq!(back.mtime.nanos, 0, "the fraction has nowhere to live");
assert_eq!(back.crtime, Timestamp::default(), "no creation time exists");
}
#[test]
fn the_checksum_high_half_exists_only_when_the_extra_area_reaches_it() {
assert!(!Inode::has_checksum_hi(256, 0), "mke2fs's reserved inodes");
assert!(!Inode::has_checksum_hi(256, 3));
assert!(Inode::has_checksum_hi(256, 4), "the exact threshold");
assert!(Inode::has_checksum_hi(256, 32), "the usual extra area");
assert!(!Inode::has_checksum_hi(128, 32), "no extra area at all");
let mut ino = Inode::empty(256);
ino.extra_isize = 0;
ino.checksum = 0xdead_beef;
let b = bytes(&ino, 256);
assert_eq!(get_u16(&b, 0x7c), 0xbeef, "the low half is written");
assert_eq!(get_u16(&b, 0x82), 0, "the high half is not");
assert_eq!(
Inode::read_from(&b, 256).unwrap().checksum,
0x0000_beef,
"and reads back as the low half alone"
);
}
#[test]
fn a_declared_extra_area_past_the_inode_reads_no_fields_and_does_not_panic() {
let mut b = vec![0u8; 256];
put_u16(&mut b, 0x80, 0xffff);
let ino = Inode::read_from(&b, 256).expect("parses");
assert_eq!(ino.extra_isize, 0xffff);
assert!(ino.inline_xattr.is_empty());
assert_eq!(ino.crtime, Timestamp::default());
}
#[test]
fn an_inode_size_below_the_classic_one_is_refused() {
let b = vec![0u8; 256];
assert!(matches!(
Inode::read_from(&b, 64),
Err(ParseError::InvalidField { field, .. }) if field == "s_inode_size"
));
}
#[test]
fn an_odd_inode_size_short_of_the_extra_field_reads_and_writes_without_panic() {
for size in [129u16, 130] {
let buf = vec![0u8; size as usize];
let ino = Inode::read_from(&buf, size).expect("parses without panic");
assert_eq!(ino.extra_isize, 0);
assert!(ino.inline_xattr.is_empty());
let mut out = vec![0u8; size as usize];
let mut written = Inode::empty(size);
written.extra_isize = 0;
written
.write_to(&mut out, size)
.expect("serializes without panic");
assert_eq!(out.len(), size as usize);
}
let mut ino = Inode::empty(130);
ino.extra_isize = 2;
let mut out = vec![0u8; 130];
ino.write_to(&mut out, 130).expect("serializes");
assert_eq!(
get_u16(&out, 0x80),
2,
"i_extra_isize occupies the last two bytes"
);
assert_eq!(Inode::read_from(&out, 130).unwrap().extra_isize, 2);
}
#[test]
fn timestamp_encodes_seconds_and_nanoseconds() {
let t = Timestamp {
secs: 1_700_000_000,
nanos: 123_456_789,
};
let (field, extra) = encode_time(t);
assert_eq!(field, 1_700_000_000);
assert_eq!(extra & 0x3, 0, "epoch high bits");
assert_eq!(extra >> 2, 123_456_789, "nanoseconds");
assert_eq!(decode_time(field, extra), t);
}
#[test]
fn timestamp_matches_kernel_epoch_scheme() {
for (secs, field, epoch) in [
(-86_400i64, 0xfffe_ae80u32, 0u32), (-1, 0xffff_ffff, 0), (2_147_483_648, 0x8000_0000, 1), (4_294_967_296, 0x0000_0000, 1), (1_700_000_000, 0x6553_f100, 0), ] {
let (f, e) = encode_time(Timestamp::from_secs(secs));
assert_eq!(f, field, "field for secs={secs}");
assert_eq!(e & 0x3, epoch, "epoch for secs={secs}");
assert_eq!(
decode_time(f, e),
Timestamp::from_secs(secs),
"round-trip for secs={secs}"
);
}
}
#[test]
fn timestamp_representable_range_tracks_the_on_disk_limits() {
assert_eq!(TIME_SECS_MIN, -(1 << 31));
assert_eq!(TIME_SECS_MAX, (1 << 31) - 1 + (3 << 32));
let held = |t: Timestamp| time_is_representable(t, 256);
assert!(held(Timestamp::from_secs(0)));
assert!(held(Timestamp::from_secs(TIME_SECS_MIN)));
assert!(held(Timestamp::from_secs(TIME_SECS_MAX)));
assert!(!held(Timestamp::from_secs(TIME_SECS_MIN - 1)));
assert!(!held(Timestamp::from_secs(TIME_SECS_MAX + 1)));
assert!(!held(Timestamp {
secs: 0,
nanos: Timestamp::NANOS_PER_SEC
}));
}
#[test]
fn an_inode_with_no_extra_words_holds_a_signed_second_and_no_fraction() {
let held = |t: Timestamp| time_is_representable(t, 128);
assert!(held(Timestamp::from_secs(TIME_SECS_MIN)));
assert!(held(Timestamp::from_secs(i64::from(i32::MAX))));
assert!(!held(Timestamp::from_secs(i64::from(i32::MAX) + 1)));
assert!(!held(Timestamp { secs: 0, nanos: 1 }));
let t = Timestamp {
secs: i64::from(i32::MAX) + 1,
nanos: 5,
};
let mut ino = Inode::empty(128);
ino.mtime = t;
let mut buf = vec![0u8; 128];
ino.write_to(&mut buf, 128).expect("writes");
let back = Inode::read_from(&buf, 128).expect("parses");
assert_ne!(back.mtime, t, "the instant does not survive");
assert!(time_is_representable(t, 256));
}
#[test]
fn a_device_number_is_laid_out_as_a_kernel_and_debugfs_lay_it_out() {
let observed = [
((1, 3), (0x0000_0103, 0)),
((8, 0), (0x0000_0800, 0)),
((0, 1), (0x0000_0001, 0)),
((255, 255), (0x0000_ffff, 0)),
((0, 0), (0, 0)),
((256, 0), (0, 0x0001_0000)),
((0, 256), (0, 0x0010_0000)),
((255, 256), (0, 0x0010_ff00)),
((256, 255), (0, 0x0001_00ff)),
((300, 5), (0, 0x0001_2c05)),
((4095, 0), (0, 0x000f_ff00)),
((0, 65_535), (0, 0x0ff0_00ff)),
((255, 65_536), (0, 0x1000_ff00)),
((0x123, 0x4_5678), (0, 0x4561_2378)),
((0, 1_048_575), (0, 0xfff0_00ff)),
((4095, 1_048_575), (0, 0xffff_ffff)),
];
for ((major, minor), words) in observed {
assert_eq!(encode_device(major, minor), words, "{major}:{minor}");
assert_eq!(
decode_device(words.0, words.1),
(major, minor),
"{words:x?}"
);
}
}
#[test]
fn every_device_number_in_range_round_trips() {
for major in (0..4096).step_by(7).chain([255, 256, 4095]) {
for minor in (0..1 << 20)
.step_by(4099)
.chain([255, 256, 65_535, 1_048_575])
{
let (b0, b1) = encode_device(major, minor);
assert_eq!(decode_device(b0, b1), (major, minor), "{major}:{minor}");
assert!(b0 == 0 || b1 == 0, "one form at a time");
}
}
}
#[test]
fn inline_xattr_region_round_trips() {
let mut ino = root_like();
let mut region = vec![0u8; 96];
region[0..4].copy_from_slice(&XATTR_MAGIC.to_le_bytes());
ino.inline_xattr = region.clone();
let b = bytes(&ino, S);
assert_eq!(get_u32(&b, 0xa0), 0xEA02_0000);
let back = Inode::read_from(&b, S).unwrap();
assert_eq!(back.inline_xattr, region);
assert_eq!(back, ino);
}
#[test]
fn absent_inline_xattr_stays_empty() {
let ino = root_like();
let back = Inode::read_from(&bytes(&ino, S), S).unwrap();
assert!(back.inline_xattr.is_empty());
assert_eq!(back, ino);
}
#[test]
fn the_inline_xattr_region_grows_with_the_inode() {
let ino = root_like();
assert_eq!(ino.inline_xattr_capacity(128), 0);
assert_eq!(ino.inline_xattr_capacity(256), 96);
assert_eq!(ino.inline_xattr_capacity(512), 352);
assert_eq!(ino.inline_xattr_capacity(1024), 864);
let mut big = Inode::empty(512);
let mut region = vec![0u8; big.inline_xattr_capacity(512)];
region[0..4].copy_from_slice(&XATTR_MAGIC.to_le_bytes());
big.inline_xattr = region.clone();
let back = Inode::read_from(&bytes(&big, 512), 512).unwrap();
assert_eq!(back.inline_xattr, region);
}
}