f2fs_reader/
inode.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4use crate::crypto;
5use crate::dir::InlineDentry;
6use crate::reader::{NEW_ADDR, NULL_ADDR, Reader};
7use crate::superblock::BLOCK_SIZE;
8use crate::xattr::{XattrEntry, decode_xattr};
9use anyhow::{Error, anyhow, ensure};
10use bitflags::bitflags;
11use std::collections::HashMap;
12use std::fmt::Debug;
13use storage_device::buffer::Buffer;
14use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Ref, Unaligned};
15
16const NAME_MAX: usize = 255;
17// The number of addresses that fit in an Inode block with a header and footer.
18const INODE_BLOCK_MAX_ADDR: usize = 923;
19// Hard coded constant from layout.h -- Number of 32-bit addresses that fit in an address block.
20const ADDR_BLOCK_NUM_ADDR: u32 = 1018;
21
22/// F2fs supports an extent tree and cached the largest extent for the file here.
23/// (We don't make use of this.)
24#[repr(C, packed)]
25#[derive(Copy, Clone, Debug, Immutable, KnownLayout, FromBytes, IntoBytes, Unaligned)]
26pub struct Extent {
27    file_offset: u32,
28    block_address: u32,
29    len: u32,
30}
31
32#[derive(Copy, Clone, Debug, Immutable, FromBytes, IntoBytes)]
33pub struct Mode(u16);
34bitflags! {
35    impl Mode: u16 {
36        const RegularFile = 0o100000;
37        const Directory = 0o040000;
38    }
39}
40
41#[derive(Copy, Clone, Debug, Immutable, FromBytes, IntoBytes)]
42pub struct AdviseFlags(u8);
43bitflags! {
44    impl AdviseFlags: u8 {
45        const Encrypted = 0x04;
46        const EncryptedName = 0x08;
47        const Verity = 0x40;
48    }
49}
50
51#[derive(Copy, Clone, Debug, Immutable, FromBytes, IntoBytes)]
52pub struct InlineFlags(u8);
53bitflags! {
54    impl InlineFlags: u8 {
55        const Xattr = 0b00000001;
56        const Data = 0b00000010;
57        const Dentry = 0b00000100;
58        const ExtraAttr = 0b00100000;
59    }
60}
61
62#[derive(Copy, Clone, Debug, Immutable, FromBytes, IntoBytes)]
63pub struct Flags(u32);
64bitflags! {
65    impl Flags: u32 {
66        const Casefold = 0x40000000;
67    }
68}
69
70#[repr(C, packed)]
71#[derive(Copy, Clone, Debug, Immutable, KnownLayout, FromBytes, IntoBytes, Unaligned)]
72pub struct InodeHeader {
73    pub mode: Mode,
74    pub advise_flags: AdviseFlags,
75    pub inline_flags: InlineFlags,
76    pub uid: u32,
77    pub gid: u32,
78    pub links: u32,
79    pub size: u64,
80    pub block_size: u64,
81    pub atime: i64,
82    pub ctime: i64,
83    pub mtime: i64,
84    pub atime_nanos: u32,
85    pub ctime_nanos: u32,
86    pub mtime_nanos: u32,
87    pub generation: u32,
88    pub dir_depth: u32,
89    pub xattr_nid: u32,
90    pub flags: Flags,
91    pub parent_inode: u32,
92    pub name_len: u32,
93    pub name: [u8; NAME_MAX],
94    pub dir_level: u8,
95
96    ext: Extent, // Holds the largest extent of this file, if using read extents. We ignore this.
97}
98
99/// This is optionally written after the header and before 'addr[0]' in Inode.
100#[repr(C, packed)]
101#[derive(Copy, Clone, Debug, Immutable, KnownLayout, FromBytes, IntoBytes, Unaligned)]
102pub struct InodeExtraAttr {
103    pub extra_size: u16,
104    pub inline_xattr_size: u16,
105    pub project_id: u32,
106    pub inode_checksum: u32,
107    pub creation_time: u64,
108    pub creation_time_nanos: u32,
109    pub compressed_blocks: u64,
110    pub compression_algorithm: u8,
111    pub log_cluster_size: u8,
112    pub compression_flags: u16,
113}
114
115#[repr(C, packed)]
116#[derive(Copy, Clone, Debug, Immutable, KnownLayout, FromBytes, IntoBytes, Unaligned)]
117pub struct InodeFooter {
118    pub nid: u32,
119    pub ino: u32,
120    pub flag: u32,
121    pub cp_ver: u64,
122    pub next_blkaddr: u32,
123}
124
125/// Inode represents a file or directory and consumes one 4kB block in the metadata region.
126///
127/// An Inode's basic layout is as follows:
128///    +--------------+
129///    | InodeHeader  |
130///    +--------------+
131///    | i_addrs[923] |
132///    +--------------+
133///    | nids[5]      |
134///    +--------------+
135///    | InodeFooter  |
136///    +--------------+
137///
138/// The i_addrs region consists of 32-bit block addresses to data associated with the inode.
139/// Some or all of this may be repurposed for optional structures based on header flags:
140///
141///   * extra: Contains additional metadata. Consumes the first 9 entries of i_addrs.
142///   * xattr: Extended attributes. Consumes the last 50 entries of i_addrs.
143///   * inline_data: Consumes all remaining i_addrs. If used, no external data blocks are used.
144///   * inline_dentry: Consumes all remaining i_addrs. If used, no external data blocks are used.
145///
146/// For inodes that do not contain inline data or inline dentry, the remaining i_addrs[] list
147/// the block offsets for data blocks that contain the contents of the inode. A value of NULL_ADDR
148/// indicates a zero page. A value of NEW_ADDR indicates a page that has not yet been allocated and
149/// should be treated the same as a zero page for our purposes.
150///
151/// If a file contains more data than available i_addrs[], nids[] will be used.
152///
153/// nids[0] and nids[1] are what F2fs called "direct node" blocks. These contain nids (i.e. NAT
154/// translated block addresses) to RawAddrBlock. Each RawAddrBlock contains up to 1018 block
155/// offsets to data blocks.
156///
157/// If that is insufficient, nids[2] and nids[3] contain what F2fs calls "indirect node" blocks.
158/// This is the same format as RawAddrBlock but each entry contains the nid of another
159/// RawAddrBlock, providing another layer of indirection and thus the ability to reference
160/// 1018^2 further blocks.
161///
162/// Finally, nids[4] may point at a "double indirect node" block. This adds one more layer of
163/// indirection, allowing for a further 1018^3 blocks.
164///
165/// For sparse files, any individual blocks or pages of blocks (at any indirection level) may be
166/// replaced with NULL_ADDR.
167///
168/// Block addressing starts at i_addrs and flows through each of nids[0..5] in order.
169pub struct Inode {
170    pub header: InodeHeader,
171    pub extra: Option<InodeExtraAttr>,
172    pub inline_data: Option<Box<[u8]>>,
173    pub(super) inline_dentry: Option<InlineDentry>,
174    pub(super) i_addrs: Vec<u32>,
175    nids: [u32; 5],
176    pub footer: InodeFooter,
177
178    // These are loaded from additional nodes.
179    nid_pages: HashMap<u32, Box<RawAddrBlock>>,
180    pub xattr: Vec<XattrEntry>,
181
182    // Crypto context, if present in xattr.
183    pub context: Option<fscrypt::Context>,
184
185    // Contains the set of block addresses in the data segment used by this inode.
186    // This includes nids, indirect and double indirect address pages, and the xattr page
187    pub block_addrs: Vec<u32>,
188}
189
190/// Both direct and indirect node address pages use this same format.
191/// In the case of direct nodes, the addrs point to data blocks.
192/// In the case of indirect and double-indirect nodes, the addrs point to nids of the next layer.
193#[repr(C, packed)]
194#[derive(Copy, Clone, Debug, Immutable, KnownLayout, FromBytes, IntoBytes, Unaligned)]
195pub struct RawAddrBlock {
196    pub addrs: [u32; ADDR_BLOCK_NUM_ADDR as usize],
197    _reserved:
198        [u8; BLOCK_SIZE - std::mem::size_of::<InodeFooter>() - 4 * ADDR_BLOCK_NUM_ADDR as usize],
199    pub footer: InodeFooter,
200}
201
202impl TryFrom<Buffer<'_>> for Box<RawAddrBlock> {
203    type Error = Error;
204    fn try_from(block: Buffer<'_>) -> Result<Self, Self::Error> {
205        Ok(Box::new(
206            RawAddrBlock::read_from_bytes(block.as_slice())
207                .map_err(|_| anyhow!("RawAddrBlock read failed"))?,
208        ))
209    }
210}
211
212impl Debug for Inode {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        let mut out = f.debug_struct("Inode");
215        out.field("header", &self.header);
216        if let Some(extra) = &self.extra {
217            out.field("extra", &extra);
218        }
219        if let Some(inline_dentry) = &self.inline_dentry {
220            out.field("inline_dentry", &inline_dentry);
221        }
222        out.field("i_addrs", &self.i_addrs).field("footer", &self.footer);
223        out.field("xattr", &self.xattr);
224        out.finish()
225    }
226}
227
228impl Inode {
229    /// Attempt to load (and validate) an inode at a given nid.
230    pub(super) async fn try_load(f2fs: &impl Reader, ino: u32) -> Result<Box<Inode>, Error> {
231        let mut block_addrs = vec![];
232        let mut raw_xattr = vec![];
233        let mut this = {
234            let block = f2fs.read_node(ino).await?;
235            block_addrs.push(f2fs.get_nat_entry(ino).await?.block_addr);
236            // Layout:
237            //   header: InodeHeader
238            //   extra: InodeExtraAttr # optional, based on header flag.
239            //   i_addr: [u32; N]       # N = <=923 addr data or repurposed for inline fields.
240            //   [u8; 200]      # optional, inline_xattr.
241            //   [u32; 5]       # nids (for large block maps)
242            //   InodeFooter
243            let (header, rest): (Ref<_, InodeHeader>, _) =
244                Ref::from_prefix(block.as_slice()).unwrap();
245            let (rest, footer): (_, Ref<_, InodeFooter>) = Ref::from_suffix(rest).unwrap();
246            ensure!(footer.ino == ino, "Footer ino doesn't match.");
247
248            // nids are additional nodes pointing to data blocks. index has a specific meaning:
249            //  - 0..2 => nid of nodes that contain addresses to data blocks.
250            //  - 2..4 => nid of nodes that contain addresses to addresses of data blocks.
251            //  - 5 => nid of a node that contains double-indirect addresses ot data blocks.
252            let mut nids = [0u32; 5];
253            nids.as_mut_bytes()
254                .copy_from_slice(&rest[INODE_BLOCK_MAX_ADDR * 4..(INODE_BLOCK_MAX_ADDR + 5) * 4]);
255            let rest = &rest[..INODE_BLOCK_MAX_ADDR * 4];
256
257            let (extra, rest) = if header.inline_flags.contains(InlineFlags::ExtraAttr) {
258                let (extra, _): (Ref<_, InodeExtraAttr>, _) = Ref::from_prefix(rest).unwrap();
259                let extra_size = extra.extra_size as usize;
260                ensure!(extra_size <= rest.len(), "Bad extra_size in inode");
261                (Some((*extra).clone()), &rest[extra_size..])
262            } else {
263                (None, rest)
264            };
265            let rest = if header.inline_flags.contains(InlineFlags::Xattr) {
266                // xattr always take up the last 50 i_addr slots. i.e. 200 bytes.
267                ensure!(
268                    rest.len() >= 200,
269                    "Insufficient space for inline xattr. Likely bad extra_size."
270                );
271                raw_xattr.extend_from_slice(&rest[rest.len() - 200..]);
272                &rest[..rest.len() - 200]
273            } else {
274                rest
275            };
276
277            let mut inline_data = None;
278            let mut inline_dentry = None;
279            let mut i_addrs: Vec<u32> = Vec::new();
280
281            if header.inline_flags.contains(InlineFlags::Data) {
282                // Inline data skips the first address slot then repurposes the remainder as data.
283                ensure!(header.size as usize + 4 < rest.len(), "Invalid or corrupt inode.");
284                inline_data = Some(rest[4..4 + header.size as usize].to_vec().into_boxed_slice());
285            } else if header.inline_flags.contains(InlineFlags::Dentry) {
286                // Repurposes i_addr to store a set of directory entry records.
287                inline_dentry = Some(InlineDentry::try_from_bytes(rest)?);
288            } else {
289                // &rest[..] is not necessarily 4-byte aligned so can't simply cast to [u32].
290                i_addrs.resize(rest.len() / 4, 0);
291                i_addrs.as_mut_bytes().copy_from_slice(&rest[..rest.len() / 4 * 4]);
292            };
293
294            Box::new(Self {
295                header: (*header).clone(),
296                extra,
297                inline_data: inline_data.map(|x| x.into()),
298                inline_dentry,
299                i_addrs,
300                nids,
301                footer: (*footer).clone(),
302
303                nid_pages: HashMap::new(),
304                xattr: vec![],
305                context: None,
306
307                block_addrs,
308            })
309        };
310
311        // Note that this call is done outside the above block to reduce the size of the future
312        // that '.await' produces by ensuring any unnecessary local variables are out of scope.
313        if this.header.xattr_nid != 0 {
314            raw_xattr.extend_from_slice(f2fs.read_node(this.header.xattr_nid).await?.as_slice());
315            this.block_addrs.push(f2fs.get_nat_entry(this.header.xattr_nid).await?.block_addr);
316        }
317        this.xattr = decode_xattr(&raw_xattr)?;
318
319        this.context = crypto::try_read_context_from_xattr(&this.xattr)?;
320
321        // The set of blocks making up the file begin with i_addrs. If more blocks are required
322        // nids[0..5] are used. Zero pages (nid == NULL_ADDR) can be omitted at any level.
323        for (i, nid) in this.nids.into_iter().enumerate() {
324            if nid == NULL_ADDR {
325                continue;
326            }
327            match i {
328                0..2 => {
329                    this.nid_pages.insert(nid, f2fs.read_node(nid).await?.try_into()?);
330                    this.block_addrs.push(f2fs.get_nat_entry(nid).await?.block_addr);
331                }
332                2..4 => {
333                    let indirect = Box::<RawAddrBlock>::try_from(f2fs.read_node(nid).await?)?;
334                    this.block_addrs.push(f2fs.get_nat_entry(nid).await?.block_addr);
335                    for nid in indirect.addrs {
336                        if nid != NULL_ADDR {
337                            this.nid_pages.insert(nid, f2fs.read_node(nid).await?.try_into()?);
338                            this.block_addrs.push(f2fs.get_nat_entry(nid).await?.block_addr);
339                        }
340                    }
341                    this.nid_pages.insert(nid, indirect);
342                }
343                4 => {
344                    let double_indirect =
345                        Box::<RawAddrBlock>::try_from(f2fs.read_node(nid).await?)?;
346                    this.block_addrs.push(f2fs.get_nat_entry(nid).await?.block_addr);
347                    for nid in double_indirect.addrs {
348                        if nid != NULL_ADDR {
349                            let indirect =
350                                Box::<RawAddrBlock>::try_from(f2fs.read_node(nid).await?)?;
351                            this.block_addrs.push(f2fs.get_nat_entry(nid).await?.block_addr);
352                            for nid in indirect.addrs {
353                                if nid != NULL_ADDR {
354                                    this.nid_pages
355                                        .insert(nid, f2fs.read_node(nid).await?.try_into()?);
356                                    this.block_addrs
357                                        .push(f2fs.get_nat_entry(nid).await?.block_addr);
358                                }
359                            }
360                            this.nid_pages.insert(nid, indirect);
361                        }
362                    }
363                    this.nid_pages.insert(nid, double_indirect);
364                }
365                _ => unreachable!(),
366            }
367        }
368
369        Ok(this)
370    }
371
372    /// Walks through the data blocks of the file in order, handling sparse regions.
373    /// Emits extents of (logical_block_num, physical_block_num, length).
374    pub fn data_blocks(&self) -> DataBlocksIter<'_> {
375        DataBlocksIter {
376            iter: BlockIter { inode: self, stage: 0, offset: 0, a: 0, b: 0, c: 0 },
377            next_block: None,
378        }
379    }
380
381    /// Get the address of a specific logical data block.
382    /// NULL_ADDR and NEW_ADDR should be considered sparse (unallocated) zero blocks.
383    pub fn data_block_addr(&self, mut block_num: u32) -> u32 {
384        let offset = block_num;
385
386        if block_num < self.i_addrs.len() as u32 {
387            return self.i_addrs[block_num as usize];
388        }
389        block_num -= self.i_addrs.len() as u32;
390
391        // After we adjust for i_addrs, all offsets are simple constants.
392        const NID0_END: u32 = ADDR_BLOCK_NUM_ADDR;
393        const NID1_END: u32 = NID0_END + ADDR_BLOCK_NUM_ADDR;
394        const NID2_END: u32 = NID1_END + ADDR_BLOCK_NUM_ADDR * ADDR_BLOCK_NUM_ADDR;
395        const NID3_END: u32 = NID2_END + ADDR_BLOCK_NUM_ADDR * ADDR_BLOCK_NUM_ADDR;
396
397        let mut iter = match block_num {
398            ..NID0_END => {
399                let a = block_num;
400                BlockIter { inode: self, stage: 1, offset, a, b: 0, c: 0 }
401            }
402            ..NID1_END => {
403                let a = block_num - NID0_END;
404                BlockIter { inode: self, stage: 2, offset, a, b: 0, c: 0 }
405            }
406            ..NID2_END => {
407                block_num -= NID1_END;
408                let a = block_num / ADDR_BLOCK_NUM_ADDR;
409                let b = block_num % ADDR_BLOCK_NUM_ADDR;
410                BlockIter { inode: self, stage: 3, offset, a, b, c: 0 }
411            }
412            ..NID3_END => {
413                block_num -= NID2_END;
414                let a = block_num / ADDR_BLOCK_NUM_ADDR;
415                let b = block_num % ADDR_BLOCK_NUM_ADDR;
416                BlockIter { inode: self, stage: 4, offset, a, b, c: 0 }
417            }
418            _ => {
419                block_num -= NID3_END;
420                let a = block_num / ADDR_BLOCK_NUM_ADDR / ADDR_BLOCK_NUM_ADDR;
421                let b = (block_num / ADDR_BLOCK_NUM_ADDR) % ADDR_BLOCK_NUM_ADDR;
422                let c = block_num % ADDR_BLOCK_NUM_ADDR;
423                BlockIter { inode: self, stage: 5, offset, a, b, c }
424            }
425        };
426        if let Some((logical, physical)) = iter.next() {
427            if logical == offset { physical } else { NULL_ADDR }
428        } else {
429            NULL_ADDR
430        }
431    }
432}
433
434#[derive(Copy, Clone, Debug, PartialEq, Eq)]
435pub struct DataBlockExtent {
436    /// The starting logical block number.
437    pub logical_block_num: u32,
438    /// The starting physical block number.
439    pub physical_block_num: u32,
440    /// The number of contiguous blocks in this extent.
441    pub length: u32,
442}
443
444/// Iterates extents in the file. Will always create an extent break at end of file.
445pub struct DataBlocksIter<'a> {
446    iter: BlockIter<'a>,
447    next_block: Option<(u32, u32)>,
448}
449
450impl Iterator for DataBlocksIter<'_> {
451    type Item = DataBlockExtent;
452    fn next(&mut self) -> Option<Self::Item> {
453        let (log_start, phys_start) = self.next_block.take().or_else(|| self.iter.next())?;
454        let mut len = 1;
455        let file_end = (self.iter.inode.header.size.next_multiple_of(BLOCK_SIZE as u64)
456            / BLOCK_SIZE as u64) as u32;
457        loop {
458            match self.iter.next() {
459                Some((log, phys))
460                    if log == log_start + len && phys == phys_start + len && log != file_end =>
461                {
462                    len += 1;
463                }
464                other => {
465                    self.next_block = other;
466                    return Some(DataBlockExtent {
467                        logical_block_num: log_start,
468                        physical_block_num: phys_start,
469                        length: len,
470                    });
471                }
472            }
473        }
474    }
475}
476
477struct BlockIter<'a> {
478    inode: &'a Inode,
479    stage: u32, // 0 -> i_addr, 1-> nids[0], 2 -> nids[1] -> ...
480    offset: u32,
481    a: u32, // depends on stage
482    b: u32, // used for nids 2+ for indirection
483    c: u32, // used for nids[4] for double-indirection.
484}
485
486impl Iterator for BlockIter<'_> {
487    type Item = (u32, u32);
488    fn next(&mut self) -> Option<Self::Item> {
489        loop {
490            match self.stage {
491                0 => {
492                    // i_addrs
493                    while let Some(&addr) = self.inode.i_addrs.get(self.a as usize) {
494                        self.a += 1;
495                        self.offset += 1;
496                        if addr != NULL_ADDR && addr != NEW_ADDR {
497                            return Some((self.offset - 1, addr));
498                        }
499                    }
500                    self.stage += 1;
501                    self.a = 0;
502                }
503                1..3 => {
504                    // "direct"
505                    let nid = self.inode.nids[self.stage as usize - 1];
506
507                    if nid == NULL_ADDR || nid == NEW_ADDR {
508                        self.stage += 1;
509                        self.offset += ADDR_BLOCK_NUM_ADDR;
510                    } else {
511                        let addrs = self.inode.nid_pages.get(&nid).unwrap().addrs;
512                        while let Some(&addr) = addrs.get(self.a as usize) {
513                            self.a += 1;
514                            self.offset += 1;
515                            if addr != NULL_ADDR && addr != NEW_ADDR {
516                                return Some((self.offset - 1, addr));
517                            }
518                        }
519                        self.stage += 1;
520                        self.a = 0;
521                    }
522                }
523
524                3..5 => {
525                    let nid = self.inode.nids[self.stage as usize - 1];
526                    // "indirect"
527                    if nid == NULL_ADDR || nid == NEW_ADDR {
528                        self.stage += 1;
529                        self.offset += ADDR_BLOCK_NUM_ADDR * ADDR_BLOCK_NUM_ADDR;
530                    } else {
531                        let addrs = self.inode.nid_pages.get(&nid).unwrap().addrs;
532                        while let Some(&nid) = addrs.get(self.a as usize) {
533                            if nid == NULL_ADDR || nid == NEW_ADDR {
534                                self.a += 1;
535                                self.offset += ADDR_BLOCK_NUM_ADDR;
536                            } else {
537                                let addrs = self.inode.nid_pages.get(&nid).unwrap().addrs;
538                                while let Some(&addr) = addrs.get(self.b as usize) {
539                                    self.b += 1;
540                                    self.offset += 1;
541                                    if addr != NULL_ADDR && addr != NEW_ADDR {
542                                        return Some((self.offset - 1, addr));
543                                    }
544                                }
545                                self.a += 1;
546                                self.b = 0;
547                            }
548                        }
549                        self.stage += 1;
550                        self.a = 0;
551                    }
552                }
553
554                5 => {
555                    let nid = self.inode.nids[4];
556                    // "double-indirect"
557                    if nid != NULL_ADDR && nid != NEW_ADDR {
558                        let addrs = self.inode.nid_pages.get(&nid).unwrap().addrs;
559                        while let Some(&nid) = addrs.get(self.a as usize) {
560                            if nid == NULL_ADDR || nid == NEW_ADDR {
561                                self.a += 1;
562                                self.offset += ADDR_BLOCK_NUM_ADDR * ADDR_BLOCK_NUM_ADDR;
563                            } else {
564                                let addrs = self.inode.nid_pages.get(&nid).unwrap().addrs;
565                                while let Some(&nid) = addrs.get(self.b as usize) {
566                                    if nid == NULL_ADDR || nid == NEW_ADDR {
567                                        self.b += 1;
568                                        self.offset += ADDR_BLOCK_NUM_ADDR;
569                                    } else {
570                                        let addrs = self.inode.nid_pages.get(&nid).unwrap().addrs;
571                                        while let Some(&addr) = addrs.get(self.c as usize) {
572                                            self.c += 1;
573                                            self.offset += 1;
574                                            if addr != NULL_ADDR && addr != NEW_ADDR {
575                                                return Some((self.offset - 1, addr));
576                                            }
577                                        }
578                                        self.b += 1;
579                                        self.c = 0;
580                                    }
581                                }
582
583                                self.a += 1;
584                                self.b = 0;
585                            }
586                        }
587                    }
588                    self.stage += 1;
589                }
590                _ => {
591                    break;
592                }
593            }
594        }
595        None
596    }
597}
598
599#[cfg(test)]
600mod test {
601    use super::*;
602    use crate::nat::RawNatEntry;
603    use crate::reader;
604    use anyhow;
605    use async_trait::async_trait;
606    use storage_device::buffer_allocator::{BufferAllocator, BufferSource};
607    use zerocopy::FromZeros;
608
609    /// A simple reader that can be filled explicitly with blocks to exercise inode.
610    struct FakeReader {
611        data: HashMap<u32, Box<[u8; 4096]>>,
612        nids: HashMap<u32, Box<[u8; 4096]>>,
613        allocator: BufferAllocator,
614    }
615
616    #[async_trait]
617    impl reader::Reader for FakeReader {
618        async fn read_raw_block(&self, block_addr: u32) -> Result<Buffer<'_>, Error> {
619            match self.data.get(&block_addr) {
620                None => Err(anyhow!("unexpected block {block_addr}")),
621                Some(value) => {
622                    let mut block = self.allocator.allocate_buffer(BLOCK_SIZE).await;
623                    block.as_mut_slice().copy_from_slice(value.as_ref());
624                    Ok(block)
625                }
626            }
627        }
628
629        async fn read_node(&self, nid: u32) -> Result<Buffer<'_>, Error> {
630            match self.nids.get(&nid) {
631                None => Err(anyhow!("unexpected nid {nid}")),
632                Some(value) => {
633                    let mut block = self.allocator.allocate_buffer(BLOCK_SIZE).await;
634                    block.as_mut_slice().copy_from_slice(value.as_ref());
635                    Ok(block)
636                }
637            }
638        }
639
640        fn fs_uuid(&self) -> &[u8; 16] {
641            &[0; 16]
642        }
643
644        async fn get_nat_entry(&self, nid: u32) -> Result<RawNatEntry, Error> {
645            Ok(RawNatEntry { ino: nid, block_addr: 0, ..Default::default() })
646        }
647    }
648
649    // Builds a bare-bones inode block.
650    fn build_inode(ino: u32) -> Box<[u8; BLOCK_SIZE]> {
651        let mut header = InodeHeader::new_zeroed();
652        let mut footer = InodeFooter::new_zeroed();
653        let mut extra = InodeExtraAttr::new_zeroed();
654
655        extra.extra_size = std::mem::size_of::<InodeExtraAttr>().try_into().unwrap();
656
657        header.mode = Mode::RegularFile;
658        header.inline_flags.set(InlineFlags::ExtraAttr, true);
659        header.inline_flags.set(InlineFlags::Xattr, true);
660        footer.ino = ino;
661
662        let mut out = [0u8; BLOCK_SIZE];
663        out[..std::mem::size_of::<InodeHeader>()].copy_from_slice(&header.as_bytes());
664        out[std::mem::size_of::<InodeHeader>()
665            ..std::mem::size_of::<InodeHeader>() + std::mem::size_of::<InodeExtraAttr>()]
666            .copy_from_slice(&extra.as_bytes());
667        out[BLOCK_SIZE - std::mem::size_of::<InodeFooter>()..].copy_from_slice(&footer.as_bytes());
668        Box::new(out)
669    }
670
671    #[fuchsia::test]
672    async fn test_xattr_bounds() {
673        let mut reader = FakeReader {
674            data: [].into(),
675            nids: [(1, build_inode(1)), (2, [0u8; 4096].into()), (3, [0u8; 4096].into())].into(),
676            allocator: BufferAllocator::new(BLOCK_SIZE, BufferSource::new(BLOCK_SIZE * 10)),
677        };
678        assert!(Inode::try_load(&reader, 1).await.is_ok());
679
680        let header_len = std::mem::size_of::<InodeHeader>();
681        let footer_len = std::mem::size_of::<InodeFooter>();
682        let nids_len = std::mem::size_of::<u32>() * 5;
683        let overheads = header_len + footer_len + nids_len;
684
685        // Just enough room for xattrs.
686        let mut extra = InodeExtraAttr::new_zeroed();
687        extra.extra_size = (BLOCK_SIZE - overheads - 200) as u16;
688        reader.nids.get_mut(&1).unwrap()[std::mem::size_of::<InodeHeader>()
689            ..std::mem::size_of::<InodeHeader>() + std::mem::size_of::<InodeExtraAttr>()]
690            .copy_from_slice(&extra.as_bytes());
691        assert!(Inode::try_load(&reader, 1).await.is_ok());
692
693        // No room for xattrs.
694        let mut extra = InodeExtraAttr::new_zeroed();
695        extra.extra_size = (BLOCK_SIZE - overheads - 199) as u16;
696        reader.nids.get_mut(&1).unwrap()[std::mem::size_of::<InodeHeader>()
697            ..std::mem::size_of::<InodeHeader>() + std::mem::size_of::<InodeExtraAttr>()]
698            .copy_from_slice(&extra.as_bytes());
699        assert!(Inode::try_load(&reader, 1).await.is_err());
700    }
701}
702
703#[cfg(test)]
704mod tests {
705    use zerocopy::FromZeros;
706
707    use super::*;
708
709    fn last_addr_block(addr: u32) -> Box<RawAddrBlock> {
710        let mut addr_block = RawAddrBlock::new_zeroed();
711        addr_block.addrs[ADDR_BLOCK_NUM_ADDR as usize - 1] = addr;
712        Box::new(addr_block)
713    }
714
715    #[test]
716    fn test_data_iter() {
717        // Fake up an inode with datablocks for the last block in each layer.
718        //   1. The last i_addrs.
719        //   2. The last nids[0] and nids[1].
720        //   3. The last block of the last nids[2] and nids[3] blocks.
721        //   4. The last block of the last block of nids[4] block.
722        // All other blocks are unallocated.
723        let header = InodeHeader::new_zeroed();
724        let footer = InodeFooter::new_zeroed();
725        let mut nids = [0u32; 5];
726        let mut nid_pages = HashMap::new();
727        nid_pages.insert(101, last_addr_block(1001));
728        nid_pages.insert(102, last_addr_block(1002));
729
730        let mut i_addrs: Vec<u32> = Vec::new();
731        i_addrs.resize(INODE_BLOCK_MAX_ADDR, 0);
732        i_addrs[0] = 100;
733        i_addrs[1] = 101;
734        i_addrs[2] = 102;
735        i_addrs[INODE_BLOCK_MAX_ADDR - 1] = 1000;
736
737        nids[0] = 101;
738        nid_pages.insert(101, last_addr_block(1001));
739
740        nids[1] = 102;
741        nid_pages.insert(102, last_addr_block(1002));
742
743        nids[2] = 103;
744        nid_pages.insert(103, last_addr_block(104));
745        nid_pages.insert(104, last_addr_block(1003));
746
747        nids[3] = 105;
748        nid_pages.insert(105, last_addr_block(106));
749        nid_pages.insert(106, last_addr_block(1004));
750
751        nids[4] = 107;
752        nid_pages.insert(107, last_addr_block(108));
753        nid_pages.insert(108, last_addr_block(109));
754        nid_pages.insert(109, last_addr_block(1005));
755
756        let inode = Box::new(Inode {
757            header,
758            extra: None,
759            inline_data: None,
760            inline_dentry: None,
761            i_addrs,
762            nids,
763            footer: footer,
764
765            nid_pages,
766            xattr: vec![],
767            context: None,
768
769            block_addrs: vec![],
770        });
771
772        // Also test data_block_addr while we're walking.
773        assert_eq!(inode.data_block_addr(0), 100);
774
775        let mut iter = inode.data_blocks();
776        assert_eq!(
777            iter.next(),
778            Some(DataBlockExtent { logical_block_num: 0, physical_block_num: 100, length: 3 })
779        );
780
781        let mut block_num = 922;
782        assert_eq!(
783            iter.next(),
784            Some(DataBlockExtent {
785                logical_block_num: block_num,
786                physical_block_num: 1000,
787                length: 1
788            })
789        ); // i_addrs
790        assert_eq!(inode.data_block_addr(block_num), 1000);
791        block_num += ADDR_BLOCK_NUM_ADDR;
792        assert_eq!(
793            iter.next(),
794            Some(DataBlockExtent {
795                logical_block_num: block_num,
796                physical_block_num: 1001,
797                length: 1
798            })
799        ); // nids[0]
800        assert_eq!(inode.data_block_addr(block_num), 1001);
801        block_num += ADDR_BLOCK_NUM_ADDR;
802        assert_eq!(
803            iter.next(),
804            Some(DataBlockExtent {
805                logical_block_num: block_num,
806                physical_block_num: 1002,
807                length: 1
808            })
809        ); // nids[1]
810        assert_eq!(inode.data_block_addr(block_num), 1002);
811        block_num += ADDR_BLOCK_NUM_ADDR * ADDR_BLOCK_NUM_ADDR;
812        assert_eq!(
813            iter.next(),
814            Some(DataBlockExtent {
815                logical_block_num: block_num,
816                physical_block_num: 1003,
817                length: 1
818            })
819        ); // nids[2]
820        assert_eq!(inode.data_block_addr(block_num), 1003);
821        block_num += ADDR_BLOCK_NUM_ADDR * ADDR_BLOCK_NUM_ADDR;
822        assert_eq!(
823            iter.next(),
824            Some(DataBlockExtent {
825                logical_block_num: block_num,
826                physical_block_num: 1004,
827                length: 1
828            })
829        ); // nids[3]
830        assert_eq!(inode.data_block_addr(block_num), 1004);
831        block_num += ADDR_BLOCK_NUM_ADDR * ADDR_BLOCK_NUM_ADDR * ADDR_BLOCK_NUM_ADDR;
832        assert_eq!(
833            iter.next(),
834            Some(DataBlockExtent {
835                logical_block_num: block_num,
836                physical_block_num: 1005,
837                length: 1
838            })
839        ); // nids[4]
840        assert_eq!(inode.data_block_addr(block_num), 1005);
841        assert_eq!(iter.next(), None);
842        assert_eq!(inode.data_block_addr(block_num - 1), 0);
843        assert_eq!(inode.data_block_addr(block_num + 1), 0);
844    }
845}