magiskboot: detect format for XZ BCJ filter

Detect the architecture and file format from input bytes to apply the
proper BCJ pre-filter when compressing with XZ:

- ELF binaries: map e_machine to x86, ARM-Thumb, ARM64, or RISC-V.
- Linux kernels: detect ARM64 raw Image, RISC-V Image, and ARM32 raw
  vmlinux.bin via condition-code density.
- Non-code data: omit BCJ filters to avoid degradation.

Introduce get_encoder_bcj_detection and eliminate the redundant
compress_bytes_kernel and compress_len_kernel helpers.

Assisted-by: Gemini 3.8 Flash
This commit is contained in:
topjohnwu
2026-10-04 04:07:03 +00:00
parent e2dc5984ea
commit 70bf88c383
5 changed files with 79 additions and 51 deletions
+1 -8
View File
@@ -39,13 +39,6 @@ static off_t compress_len(FileFormat type, byte_view in, int fd) {
return now - prev;
}
static off_t compress_len_kernel(FileFormat type, byte_view in, int fd) {
auto prev = lseek(fd, 0, SEEK_CUR);
compress_bytes_kernel(type, in, fd);
auto now = lseek(fd, 0, SEEK_CUR);
return now - prev;
}
static void dump(const void *buf, size_t size, const char *filename) {
if (size == 0)
return;
@@ -656,7 +649,7 @@ void repack(Utf8CStr src_img, Utf8CStr out_img, bool skip_comp) {
mmap_data m(KERNEL_FILE);
uint32_t payload_sz = 0;
if (!skip_comp && !fmt_compressed_any(check_fmt(m.data(), m.size())) && fmt_compressed(boot.k_fmt)) {
payload_sz = compress_len_kernel(boot.k_fmt, m, fd);
payload_sz = compress_len(boot.k_fmt, m, fd);
if (boot.flags[ZIMAGE_KERNEL] && boot.k_fmt != FileFormat::GZIP) {
// For non-gzip compression in zImage, size_append appends the 4-byte LE uncompressed size
uint32_t sz = m.size();
+27 -39
View File
@@ -1,5 +1,5 @@
use crate::ffi::FileFormat;
use crate::format::check_fmt;
use crate::format::{check_fmt, detect_bcj_filter};
use base::nix::fcntl::OFlag;
use base::{Chunker, FileOrStd, LoggedResult, ReadExt, Utf8CStr, Utf8CString, WriteExt, log_err};
use bzip2::Compression as BzCompression;
@@ -15,7 +15,7 @@ use lz4::{
EncoderBuilder as LZ4FrameEncoderBuilder,
};
use lzma_rust2::{
CheckType, FilterType, LzmaOptions, LzmaReader, LzmaWriter, XzOptions, XzReader, XzWriter,
CheckType, LzmaOptions, LzmaReader, LzmaWriter, XzOptions, XzReader, XzWriter,
};
use std::cmp::min;
use std::fmt::Write as FmtWrite;
@@ -208,15 +208,6 @@ impl<R: Read> Read for LZ4BlockDecoder<R> {
}
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
const BCJ_FILTER: FilterType = FilterType::BcjX86;
#[cfg(target_arch = "arm")]
const BCJ_FILTER: FilterType = FilterType::BcjArmThumb;
#[cfg(target_arch = "aarch64")]
const BCJ_FILTER: FilterType = FilterType::BcjArm64;
#[cfg(target_arch = "riscv64")]
const BCJ_FILTER: FilterType = FilterType::BcjRiscv;
// Top-level APIs
pub fn get_encoder<'a, W: Write + 'a>(
@@ -227,7 +218,6 @@ pub fn get_encoder<'a, W: Write + 'a>(
FileFormat::XZ => {
let mut opt = XzOptions::with_preset(6);
opt.set_check_sum_type(CheckType::Crc32);
opt.prepend_pre_filter(BCJ_FILTER, 0);
Box::new(XzWriter::new(w, opt)?)
}
FileFormat::LZMA => Box::new(LzmaWriter::new_use_header(
@@ -254,6 +244,23 @@ pub fn get_encoder<'a, W: Write + 'a>(
})
}
pub fn get_encoder_bcj_detection<'a, W: Write + 'a>(
format: FileFormat,
w: W,
in_bytes: &[u8],
) -> std::io::Result<Box<dyn WriteFinish<W> + 'a>> {
if format == FileFormat::XZ {
let mut opt = XzOptions::with_preset(6);
opt.set_check_sum_type(CheckType::Crc32);
if let Some(filter) = detect_bcj_filter(in_bytes) {
opt.prepend_pre_filter(filter, 0);
}
Ok(Box::new(XzWriter::new(w, opt)?))
} else {
get_encoder(format, w)
}
}
pub fn get_decoder<'a, R: Read + 'a>(
format: FileFormat,
r: R,
@@ -275,31 +282,7 @@ pub fn compress_bytes(format: FileFormat, in_bytes: &[u8], out_fd: RawFd) {
let mut out_file = unsafe { ManuallyDrop::new(File::from_raw_fd(out_fd)) };
let _ = || -> LoggedResult<()> {
let mut encoder = get_encoder(format, out_file.deref_mut())?;
std::io::copy(&mut Cursor::new(in_bytes), encoder.deref_mut())?;
encoder.finish()?;
Ok(())
}();
}
pub fn compress_bytes_kernel(format: FileFormat, in_bytes: &[u8], out_fd: RawFd) {
let mut out_file = unsafe { ManuallyDrop::new(File::from_raw_fd(out_fd)) };
let _ = || -> LoggedResult<()> {
let mut encoder = match format {
FileFormat::XZ => {
let mut opt = XzOptions::with_preset(6);
opt.set_check_sum_type(CheckType::Crc32);
let filter = match BCJ_FILTER {
// ARM32 kernel uses ARM instructions, not thumb2
FilterType::BcjArmThumb => FilterType::BcjArm,
_ => BCJ_FILTER,
};
opt.prepend_pre_filter(filter, 0);
Box::new(XzWriter::new(out_file.deref_mut(), opt)?)
}
_ => get_encoder(format, out_file.deref_mut())?,
};
let mut encoder = get_encoder_bcj_detection(format, out_file.deref_mut(), in_bytes)?;
std::io::copy(&mut Cursor::new(in_bytes), encoder.deref_mut())?;
encoder.finish()?;
Ok(())
@@ -413,8 +396,13 @@ pub(crate) fn compress_cmd(
FileOrStd::File(outfile)
};
let mut encoder = get_encoder(method, output.as_file())?;
std::io::copy(&mut input.as_file(), encoder.as_mut())?;
let mut buf = [0u8; 4096];
let len = input.as_file().read(&mut buf)?;
let buf = &buf[..len];
let mut encoder = get_encoder_bcj_detection(method, output.as_file(), buf)?;
let mut reader = Cursor::new(buf).chain(input.as_file());
std::io::copy(&mut reader, encoder.as_mut())?;
encoder.finish()?;
if rm_in {
+2 -2
View File
@@ -15,7 +15,7 @@ use std::process::exit;
use std::str;
use crate::check_env;
use crate::compress::{get_decoder, get_encoder};
use crate::compress::{get_decoder, get_encoder_bcj_detection};
use crate::ffi::FileFormat;
use crate::patch::{patch_encryption, patch_verity};
use base::libc::{
@@ -700,7 +700,7 @@ impl CpioEntry {
return false;
}
let Ok(data) = || -> std::io::Result<Vec<u8>> {
let mut encoder = get_encoder(FileFormat::XZ, Vec::new())?;
let mut encoder = get_encoder_bcj_detection(FileFormat::XZ, Vec::new(), &self.data)?;
encoder.write_all(&self.data)?;
encoder.finish()
}() else {
+48
View File
@@ -1,5 +1,6 @@
use crate::ffi::FileFormat;
use base::{Utf8CStr, cstr, libc};
use lzma_rust2::FilterType;
use std::fmt::{Display, Formatter};
use std::str::FromStr;
@@ -218,3 +219,50 @@ pub fn check_fmt(buf: &[u8]) -> FileFormat {
FileFormat::UNKNOWN
}
}
fn is_raw_arm32(buf: &[u8]) -> bool {
// Only inspect the first 256 bytes (up to 64 instructions)
let sample = &buf[..buf.len().min(256)];
if sample.len() < 64 {
return false;
}
let words = sample.chunks_exact(4);
let count = words.len();
let arm_cond_count = words
.filter(|chunk| {
let top_nibble = chunk[3] >> 4;
top_nibble == 0xE || top_nibble == 0xF
})
.count();
arm_cond_count * 100 / count >= 75
}
pub fn detect_bcj_filter(buf: &[u8]) -> Option<FilterType> {
if buf.len() >= 20 && buf.starts_with(b"\x7fELF") {
let e_machine = match buf[5] {
1 => u16::from_le_bytes([buf[18], buf[19]]),
2 => u16::from_be_bytes([buf[18], buf[19]]),
_ => return None,
};
return match e_machine {
0x03 | 0x3E => Some(FilterType::BcjX86),
0x28 => Some(FilterType::BcjArmThumb),
0xB7 => Some(FilterType::BcjArm64),
0xF3 => Some(FilterType::BcjRiscv),
_ => None,
};
}
if buf.len() >= 0x3C && &buf[0x38..0x3C] == b"ARM\x64" {
return Some(FilterType::BcjArm64);
}
if buf.len() >= 0x34 && &buf[0x30..0x34] == b"RSC\x05" {
return Some(FilterType::BcjRiscv);
}
if is_raw_arm32(buf) {
return Some(FilterType::BcjArm);
}
None
}
+1 -2
View File
@@ -2,7 +2,7 @@
#![feature(iter_intersperse)]
pub use base;
use compress::{compress_bytes, compress_bytes_kernel, decompress_bytes};
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};
@@ -81,7 +81,6 @@ pub mod ffi {
fn check_fmt(buf: &[u8]) -> FileFormat;
fn compress_bytes(format: FileFormat, in_bytes: &[u8], out_fd: i32);
fn compress_bytes_kernel(format: FileFormat, in_bytes: &[u8], out_fd: i32);
fn decompress_bytes(format: FileFormat, in_bytes: &[u8], out_fd: i32) -> bool;
fn fmt2name(fmt: FileFormat) -> *const c_char;
fn fmt_compressed(fmt: FileFormat) -> bool;