diff --git a/native/src/Cargo.lock b/native/src/Cargo.lock index d4e4ac6c0..2be91437d 100644 --- a/native/src/Cargo.lock +++ b/native/src/Cargo.lock @@ -470,9 +470,9 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "fdt" -version = "0.1.5" +version = "0.2.0-alpha2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784a4df722dc6267a04af36895398f59d21d07dce47232adf31ec0ff2fa45e67" +checksum = "c8ccfb5c9d9425b2191070f0435636f4a9cdfedd107e33b15f861622b222726a" [[package]] name = "ff" diff --git a/native/src/Cargo.toml b/native/src/Cargo.toml index 0241564ea..4e65f8248 100644 --- a/native/src/Cargo.toml +++ b/native/src/Cargo.toml @@ -23,7 +23,7 @@ thiserror = "2.0.19" byteorder = "1.5.0" size = "0.5.0" bytemuck = "1.25.2" -fdt = "0.1.5" +fdt = "0.2.0-alpha2" const_format = "0.2.36" bit-set = "0.11.1" syn = "3.0.3" diff --git a/native/src/boot/bootimg.cpp b/native/src/boot/bootimg.cpp index 562c7ebb8..075dc9660 100644 --- a/native/src/boot/bootimg.cpp +++ b/native/src/boot/bootimg.cpp @@ -20,6 +20,14 @@ using namespace std; #define RETURN_CHROMEOS 2 #define RETURN_VENDOR 3 +static FileFormat check_fmt(const void *buf, size_t len) { + return check_fmt({static_cast(buf), len}); +} + +static int find_dtb_offset(const void *buf, size_t len) { + return find_dtb_offset({static_cast(buf), len}); +} + static void decompress(FileFormat type, int fd, const void *in, size_t size) { decompress_bytes(type, byte_view { in, size }, fd); } @@ -192,77 +200,6 @@ boot_img::~boot_img() { delete hdr; } -struct [[gnu::packed]] fdt_header { - struct fdt32_t { - uint32_t byte0: 8; - uint32_t byte1: 8; - uint32_t byte2: 8; - uint32_t byte3: 8; - - constexpr operator uint32_t() const { - return bit_cast(fdt32_t { - .byte0 = byte3, - .byte1 = byte2, - .byte2 = byte1, - .byte3 = byte0 - }); - } - }; - - struct node_header { - fdt32_t tag; - char name[0]; - }; - - fdt32_t magic; /* magic word FDT_MAGIC */ - fdt32_t totalsize; /* total size of DT block */ - fdt32_t off_dt_struct; /* offset to structure */ - fdt32_t off_dt_strings; /* offset to strings */ - fdt32_t off_mem_rsvmap; /* offset to memory reserve map */ - fdt32_t version; /* format version */ - fdt32_t last_comp_version; /* last compatible version */ - - /* version 2 fields below */ - fdt32_t boot_cpuid_phys; /* Which physical CPU id we're - booting on */ - /* version 3 fields below */ - fdt32_t size_dt_strings; /* size of the strings block */ - - /* version 17 fields below */ - fdt32_t size_dt_struct; /* size of the structure block */ -}; - -static int find_dtb_offset(const uint8_t *buf, unsigned sz) { - const uint8_t * const end = buf + sz; - - for (auto curr = buf; curr < end; curr += sizeof(fdt_header)) { - curr = static_cast(memmem(curr, end - curr, DTB_MAGIC, sizeof(fdt_header::fdt32_t))); - if (curr == nullptr) - return -1; - - auto fdt_hdr = reinterpret_cast(curr); - - // Check that fdt_header.totalsize does not overflow kernel image size or is empty dtb - // https://github.com/torvalds/linux/commit/7b937cc243e5b1df8780a0aa743ce800df6c68d1 - uint32_t totalsize = fdt_hdr->totalsize; - if (totalsize > end - curr || totalsize <= 0x48) - continue; - - // Check that fdt_header.off_dt_struct does not overflow kernel image size - uint32_t off_dt_struct = fdt_hdr->off_dt_struct; - if (off_dt_struct > end - curr) - continue; - - // Check that fdt_node_header.tag of first node is FDT_BEGIN_NODE - auto fdt_node_hdr = reinterpret_cast(curr + off_dt_struct); - if (fdt_node_hdr->tag != 0x1u) - continue; - - return curr - buf; - } - return -1; -} - static FileFormat check_fmt_lg(const uint8_t *buf, unsigned sz) { FileFormat fmt = check_fmt(buf, sz); if (fmt == FileFormat::LZ4_LEGACY) { diff --git a/native/src/boot/bootimg.hpp b/native/src/boot/bootimg.hpp index cb73ff511..6f31d0a73 100644 --- a/native/src/boot/bootimg.hpp +++ b/native/src/boot/bootimg.hpp @@ -5,6 +5,8 @@ #include #include +enum class FileFormat : uint8_t; + /****************** * Special Headers *****************/ diff --git a/native/src/boot/dtb.rs b/native/src/boot/dtb.rs index 749d6b269..faf282c48 100644 --- a/native/src/boot/dtb.rs +++ b/native/src/boot/dtb.rs @@ -1,12 +1,17 @@ use argh::FromArgs; use base::{LoggedResult, MappedFile, Utf8CStr, argh}; -use fdt::node::{FdtNode, NodeProperty}; -use fdt::{Fdt, FdtError}; +use fdt::nodes::{Node, NodeProperty}; +use fdt::parsing::Panic; +use fdt::parsing::unaligned::UnalignedParser; +use fdt::{Fdt, FdtError, FdtHeader}; use std::cell::UnsafeCell; use crate::check_env; use crate::patch::patch_verity; +type UnalignedFdt<'a> = Fdt<'a, (UnalignedParser<'a>, Panic)>; +type UnalignedNode<'a> = Node<'a, (UnalignedParser<'a>, Panic)>; + #[derive(FromArgs)] #[argh(subcommand)] pub(crate) enum DtbAction { @@ -52,7 +57,7 @@ Supported actions: const MAX_PRINT_LEN: usize = 32; -fn print_node(node: &FdtNode) { +fn print_node(node: &UnalignedNode) { fn pretty_node(depth_set: &[bool]) { let mut depth_set = depth_set.iter().peekable(); while let Some(depth) = depth_set.next() { @@ -89,13 +94,13 @@ fn print_node(node: &FdtNode) { } } - fn do_print_node(node: &FdtNode, depth_set: &mut Vec) { + fn do_print_node(node: &UnalignedNode, depth_set: &mut Vec) { pretty_node(depth_set); let depth = depth_set.len(); depth_set.push(true); - println!("{}", node.name); - let mut properties = node.properties().peekable(); - let mut children = node.children().peekable(); + println!("{}", node.name().name); + let mut properties = node.properties().iter().peekable(); + let mut children = node.children().iter().peekable(); while let Some(NodeProperty { name, value }) = properties.next() { let size = value.len(); let is_str = !(size > 1 && value[0] == 0) @@ -136,7 +141,46 @@ fn print_node(node: &FdtNode) { do_print_node(node, &mut vec![]); } -fn for_each_fdt LoggedResult<()>>( +const DTB_MAGIC: &[u8] = b"\xd0\x0d\xfe\xed"; + +/// Minimum size of a valid, non-empty flattened device tree (72 bytes / 0x48). +/// +/// A minimal DTB containing only an empty root node (`/`) with zero properties is +/// exactly 72 bytes: +/// - 40 bytes: Standard FDT header +/// - 16 bytes: Empty memory reserve map (null terminator entry) +/// - 16 bytes: Root node struct block (`BEGIN_NODE` + empty name `""` + `END_NODE` + `END`) +const MIN_NON_EMPTY_DTB_SIZE: usize = 0x48; + +pub(crate) fn find_dtb_offset(buf: &[u8]) -> Option { + let mut pos = 0; + while pos + size_of::() <= buf.len() { + let rel_pos = buf[pos..].windows(4).position(|w| w == DTB_MAGIC)?; + let curr = pos + rel_pos; + let sub = &buf[curr..]; + + let Ok(fdt) = Fdt::new_unaligned_fallible(sub) else { + pos = curr + 4; + continue; + }; + + if fdt.total_size() <= MIN_NON_EMPTY_DTB_SIZE + || fdt.find_node("/").ok().flatten().is_none() + { + pos = curr + 4; + continue; + } + + return Some(curr); + } + None +} + +pub(crate) fn find_dtb_offset_for_cxx(buf: &[u8]) -> i32 { + find_dtb_offset(buf).map_or(-1, |v| v as i32) +} + +fn for_each_fdt LoggedResult<()>>( file: &Utf8CStr, rw: bool, mut f: F, @@ -150,16 +194,13 @@ fn for_each_fdt LoggedResult<()>>( let mut buf = Some(file.as_ref()); let mut dtb_num = 0usize; while let Some(slice) = buf { - let slice = if let Some(pos) = slice.windows(4).position(|w| w == b"\xd0\x0d\xfe\xed") { + let slice = if let Some(pos) = find_dtb_offset(slice) { &slice[pos..] } else { break; }; - if slice.len() < 40 { - break; - } - let fdt = match Fdt::new(slice) { - Err(FdtError::BufferTooSmall) => { + let fdt = match Fdt::new_unaligned(slice) { + Err(FdtError::SliceTooSmall) => { eprintln!("dtb.{dtb_num:04} is truncated"); break; } @@ -177,8 +218,9 @@ fn for_each_fdt LoggedResult<()>>( Ok(()) } -fn find_fstab<'b, 'a: 'b>(fdt: &'b Fdt<'a>) -> Option> { - fdt.all_nodes().find(|node| node.name == "fstab") +fn find_fstab<'a>(fdt: &UnalignedFdt<'a>) -> Option> { + fdt.all_nodes() + .find_map(|(_, node)| (node.name().name == "fstab").then_some(node)) } fn dtb_print(file: &Utf8CStr, fstab: bool) -> LoggedResult<()> { @@ -188,11 +230,8 @@ fn dtb_print(file: &Utf8CStr, fstab: bool) -> LoggedResult<()> { eprintln!("Found fstab in dtb.{n:04}"); print_node(&fstab); } - } else if let Some(mut root) = fdt.find_node("/") { + } else if let Some(root) = fdt.find_node("/") { eprintln!("Printing dtb.{n:04}"); - if root.name.is_empty() { - root.name = "/"; - } print_node(&root); } Ok(()) @@ -203,11 +242,11 @@ fn dtb_test(file: &Utf8CStr) -> LoggedResult { let mut ret = true; for_each_fdt(file, false, |_, fdt| { if let Some(fstab) = find_fstab(&fdt) { - for child in fstab.children() { - if child.name != "system" { + for child in fstab.children().iter() { + if child.name().name != "system" { continue; } - if let Some(mount_point) = child.property("mnt_point") + if let Some(mount_point) = child.raw_property("mnt_point") && mount_point.value == b"/system_root\0" { ret = false; @@ -224,11 +263,11 @@ fn dtb_patch(file: &Utf8CStr) -> LoggedResult { let keep_verity = check_env("KEEPVERITY"); let mut patched = false; for_each_fdt(file, true, |n, fdt| { - for node in fdt.all_nodes() { - if node.name != "chosen" { + for (_, node) in fdt.all_nodes() { + if node.name().name != "chosen" { continue; } - if let Some(boot_args) = node.property("bootargs") { + if let Some(boot_args) = node.raw_property("bootargs") { boot_args.value.windows(14).for_each(|w| { if w == b"skip_initramfs" { let w = unsafe { @@ -245,8 +284,8 @@ fn dtb_patch(file: &Utf8CStr) -> LoggedResult { return Ok(()); } if let Some(fstab) = find_fstab(&fdt) { - for child in fstab.children() { - if let Some(flags) = child.property("fsmgr_flags") { + for child in fstab.children().iter() { + if let Some(flags) = child.raw_property("fsmgr_flags") { let flags = unsafe { &mut *std::mem::transmute::<&[u8], &UnsafeCell<[u8]>>(flags.value).get() }; diff --git a/native/src/boot/lib.rs b/native/src/boot/lib.rs index 25988fef2..7d1f87c3d 100644 --- a/native/src/boot/lib.rs +++ b/native/src/boot/lib.rs @@ -3,6 +3,7 @@ pub use base; use compress::{compress_bytes, decompress_bytes}; +use dtb::find_dtb_offset_for_cxx; use format::{check_fmt, fmt_compressed, fmt_compressed_any, fmt2name}; use sign::{SHA, get_sha, sha256_hash, sign_payload_for_cxx}; use std::env; @@ -75,6 +76,9 @@ pub mod ffi { #[cxx_name = "sign_payload"] fn sign_payload_for_cxx(payload: &[u8]) -> Vec; + + #[cxx_name = "find_dtb_offset"] + fn find_dtb_offset_for_cxx(buf: &[u8]) -> i32; } // BootImage FFI diff --git a/native/src/boot/magiskboot.hpp b/native/src/boot/magiskboot.hpp index deaf52e11..8fe1738c7 100644 --- a/native/src/boot/magiskboot.hpp +++ b/native/src/boot/magiskboot.hpp @@ -34,14 +34,7 @@ #define AVB_FOOTER_MAGIC "AVBf" #define AVB_MAGIC "AVB0" -enum class FileFormat : uint8_t; - int unpack(Utf8CStr image, bool skip_decomp = false, bool hdr = false); void repack(Utf8CStr src_img, Utf8CStr out_img, bool skip_comp = false); int split_image_dtb(Utf8CStr filename, bool skip_decomp = false); void cleanup(); -FileFormat check_fmt(rust::Slice buf) noexcept; - -static inline FileFormat check_fmt(const void *buf, size_t len) { - return check_fmt({static_cast(buf), len}); -}