garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /boot/src/fdt.rs

raw

//! A copy of the firmware's device tree (Devicetree Specification 0.4,
//! chapter 5) with the kernel's command line as `/chosen/bootargs`: the
//! tree's blocks copied over, the property put in (in place of one there
//! was), `/chosen` made when the tree has none.

const MAGIC: u32 = 0xd00d_feed;
const BEGIN_NODE: u32 = 1;
const END_NODE: u32 = 2;
const PROP: u32 = 3;
const NOP: u32 = 4;
const END: u32 = 9;

fn be(b: &[u8], at: usize) -> u32 {
    u32::from_be_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
}

/// The tree's size, from its header, if `tree` points at one.
///
/// # Safety
/// `tree` must be readable for its header.
pub unsafe fn size(tree: *const u8) -> Option<usize> {
    // SAFETY: as the caller promises.
    let header = unsafe { core::slice::from_raw_parts(tree, 40) };
    (be(header, 0) == MAGIC).then(|| be(header, 4) as usize)
}

/// Writes into `out` the tree `tree` with `bootargs`. Its size, or None
/// when `out` is too small or the tree is not one.
pub fn with_bootargs(tree: &[u8], bootargs: &str, out: &mut [u8]) -> Option<usize> {
    if tree.len() < 40 || be(tree, 0) != MAGIC {
        return None;
    }
    let (structure, strings, reserved) = (be(tree, 8) as usize, be(tree, 12) as usize, be(tree, 16) as usize);
    let (strings_size, structure_size) = (be(tree, 32) as usize, be(tree, 36) as usize);
    let strings_block = tree.get(strings..strings + strings_size)?;
    let mut w = Writer { out, at: 40 };
    // The memory reservation block: 16-byte entries up to one of zeros.
    let mut r = reserved;
    w.at = 40usize.next_multiple_of(8);
    loop {
        let entry = tree.get(r..r + 16)?;
        w.bytes(entry)?;
        r += 16;
        if entry.iter().all(|&b| b == 0) {
            break;
        }
    }
    let new_structure = w.at;
    // Where "bootargs" is among the strings, or where it will be added.
    let name = b"bootargs\0";
    let found = (0..strings_block.len())
        .find(|&i| (i == 0 || strings_block[i - 1] == 0) && strings_block[i..].starts_with(name));
    let name_offset = found.unwrap_or(strings_block.len()) as u32;
    let property = |w: &mut Writer| -> Option<()> {
        w.word(PROP)?;
        w.word(bootargs.len() as u32 + 1)?;
        w.word(name_offset)?;
        w.bytes(bootargs.as_bytes())?;
        w.bytes(&[0])?;
        w.align()
    };
    let block = tree.get(structure..structure + structure_size)?;
    let (mut at, mut depth, mut in_chosen, mut chosen_seen) = (0usize, 0, false, false);
    while at + 4 <= block.len() {
        let token = be(block, at);
        match token {
            BEGIN_NODE => {
                let end = block[at + 4..].iter().position(|&b| b == 0)? + at + 4;
                let node = &block[at + 4..end];
                let next = (end + 1).next_multiple_of(4);
                w.bytes(&block[at..next])?;
                depth += 1;
                if depth == 2 && node == b"chosen" {
                    in_chosen = true;
                    chosen_seen = true;
                }
                at = next;
            }
            END_NODE => {
                if in_chosen && depth == 2 {
                    property(&mut w)?;
                    in_chosen = false;
                }
                if depth == 1 && !chosen_seen {
                    w.word(BEGIN_NODE)?;
                    w.bytes(b"chosen\0")?;
                    w.align()?;
                    property(&mut w)?;
                    w.word(END_NODE)?;
                }
                w.word(END_NODE)?;
                depth -= 1;
                at += 4;
            }
            PROP => {
                let len = be(block, at + 4) as usize;
                let name = be(block, at + 8) as usize;
                let next = (at + 12 + len).next_multiple_of(4);
                let is_bootargs = strings_block
                    .get(name..)
                    .is_some_and(|s| s.starts_with(name_of_bootargs()));
                if !(in_chosen && depth == 2 && is_bootargs) {
                    w.bytes(block.get(at..next)?)?;
                }
                at = next;
            }
            NOP => at += 4,
            END => {
                w.word(END)?;
                break;
            }
            _ => return None,
        }
    }
    let structure_end = w.at;
    let new_strings = w.at;
    w.bytes(strings_block)?;
    if found.is_none() {
        w.bytes(name)?;
    }
    let total = w.at;
    let header: [u32; 10] = [
        MAGIC,
        total as u32,
        new_structure as u32,
        new_strings as u32,
        40usize.next_multiple_of(8) as u32,
        17,
        16,
        be(tree, 28),
        (total - new_strings) as u32,
        (structure_end - new_structure) as u32,
    ];
    for (i, word) in header.iter().enumerate() {
        w.out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes());
    }
    Some(total)
}

fn name_of_bootargs() -> &'static [u8] {
    b"bootargs\0"
}

struct Writer<'a> {
    out: &'a mut [u8],
    at: usize,
}

impl Writer<'_> {
    fn bytes(&mut self, b: &[u8]) -> Option<()> {
        self.out.get_mut(self.at..self.at + b.len())?.copy_from_slice(b);
        self.at += b.len();
        Some(())
    }

    fn word(&mut self, w: u32) -> Option<()> {
        self.bytes(&w.to_be_bytes())
    }

    fn align(&mut self) -> Option<()> {
        while !self.at.is_multiple_of(4) {
            self.bytes(&[0])?;
        }
        Some(())
    }
}