From 66bcdaf4e0f6798a24c755148aaa694ca4cd4271 Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Fri, 2 Oct 2026 17:05:01 -0700 Subject: [PATCH] magiskboot: support building on host Allow magiskboot to be built directly on host platforms (macOS and Linux) using Cargo: - Add a binary target to boot module with a no_main entry point that directly reuses the C main CLI implementation. - Compile native C and C++ sources (base, boot, cxx, and lz4) via cc in base and boot build.rs when target_os is not Android. - Platform gate Linux-specific functionality (SELinux xattrs, mount, namespaces) in base on Linux and Android, and provide macOS fallback for xsendfile. - Move MountInfo and mount parsing from files to mount module. - Scope Android-specific LTO rustflags in config.toml to Android targets. - Ensure build.py compiles Rust modules as static libraries (--lib). Assisted-by: Gemini 3.8 Flash --- build.py | 2 +- native/src/.cargo/config.toml | 4 +- native/src/Cargo.lock | 2 + native/src/Cargo.toml | 1 + native/src/base/Cargo.toml | 1 + native/src/base/build.rs | 17 +++ native/src/base/derive/Cargo.toml | 3 + native/src/base/derive/lib.rs | 1 + native/src/base/files.rs | 93 ++--------------- native/src/base/lib.rs | 3 + native/src/base/mount.rs | 84 ++++++++++++++- native/src/base/xwrap.rs | 167 ++++++++++++++++++++---------- native/src/boot/Cargo.toml | 7 +- native/src/boot/build.rs | 28 +++++ native/src/boot/lib.rs | 1 + native/src/boot/main.rs | 3 + 16 files changed, 274 insertions(+), 143 deletions(-) create mode 100644 native/src/boot/main.rs diff --git a/build.py b/build.py index 27a0a8a69..bc0b10ea4 100755 --- a/build.py +++ b/build.py @@ -230,7 +230,7 @@ def build_rust_src(targets: set[str]): os.chdir(Path("native", "src")) # Start building the build commands - cmds = ["cargo", "build"] + cmds = ["cargo", "build", "--lib"] if args.release: cmds.append("-r") profile = "release" diff --git a/native/src/.cargo/config.toml b/native/src/.cargo/config.toml index 8bf89eed5..74d221a68 100644 --- a/native/src/.cargo/config.toml +++ b/native/src/.cargo/config.toml @@ -2,6 +2,9 @@ # Set arm64 as the default target # The actual compilation will have the target overriden by command-line. target = "aarch64-linux-android" +target-dir = "../out/rust" + +[target.'cfg(target_os = "android")'] # Enable cross language LTO, and explicitly set dwarf-version for ThinLTO rustflags = [ "-Z", @@ -11,7 +14,6 @@ rustflags = [ "-C", "force-unwind-tables=no", ] -target-dir = "../out/rust" [unstable] build-std = ["std", "panic_abort"] diff --git a/native/src/Cargo.lock b/native/src/Cargo.lock index d6f25b87c..18593d6ee 100644 --- a/native/src/Cargo.lock +++ b/native/src/Cargo.lock @@ -20,6 +20,7 @@ version = "0.0.0" dependencies = [ "bitflags", "bytemuck", + "cc", "cfg-if", "const_format", "cxx", @@ -639,6 +640,7 @@ dependencies = [ "bytemuck", "byteorder", "bzip2", + "cc", "cxx", "cxx-gen", "der", diff --git a/native/src/Cargo.toml b/native/src/Cargo.toml index d843cce9a..1e7a82850 100644 --- a/native/src/Cargo.toml +++ b/native/src/Cargo.toml @@ -10,6 +10,7 @@ version = "0.0.0" edition = "2024" [workspace.dependencies] +cc = "1.0" base = { path = "base" } derive = { path = "base/derive" } magiskpolicy = { path = "sepolicy" } diff --git a/native/src/base/Cargo.toml b/native/src/base/Cargo.toml index fef103795..c1faf6bf5 100644 --- a/native/src/base/Cargo.toml +++ b/native/src/base/Cargo.toml @@ -14,6 +14,7 @@ workspace = true [build-dependencies] cxx-gen = { workspace = true } +cc = { workspace = true } [dependencies] derive = { workspace = true } diff --git a/native/src/base/build.rs b/native/src/base/build.rs index 0cd5d17c4..ea1139b0e 100644 --- a/native/src/base/build.rs +++ b/native/src/base/build.rs @@ -5,4 +5,21 @@ mod codegen; fn main() { gen_cxx_binding("base-rs"); + + let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + if target_os != "android" { + let mut build = cc::Build::new(); + build + .cpp(true) + .std("c++23") + .include("include") + .include("../include") + .include("../../out/generated") + .include("../external/cxx-rs/include") + .file("base.cpp") + .file("base-rs.cpp") + .file("../external/cxx-rs/src/cxx.cc") + .warnings(false) + .compile("base_cxx"); + } } diff --git a/native/src/base/derive/Cargo.toml b/native/src/base/derive/Cargo.toml index 89f7334fa..42dce9766 100644 --- a/native/src/base/derive/Cargo.toml +++ b/native/src/base/derive/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true path = "lib.rs" proc-macro = true +[lints] +workspace = true + [dependencies] syn = { workspace = true } quote = { workspace = true } diff --git a/native/src/base/derive/lib.rs b/native/src/base/derive/lib.rs index 732924802..810ffef86 100644 --- a/native/src/base/derive/lib.rs +++ b/native/src/base/derive/lib.rs @@ -1,4 +1,5 @@ #![recursion_limit = "256"] +#![allow(clippy::unwrap_used)] use proc_macro::TokenStream; diff --git a/native/src/base/files.rs b/native/src/base/files.rs index 16f8e7bb1..99988008d 100644 --- a/native/src/base/files.rs +++ b/native/src/base/files.rs @@ -3,17 +3,18 @@ use crate::{ cstr, error, }; use bytemuck::{Pod, bytes_of, bytes_of_mut}; -use libc::{c_uint, makedev, mode_t}; +use libc::mode_t; use nix::errno::Errno; use nix::fcntl::{AT_FDCWD, OFlag}; use nix::sys::stat::{FchmodatFlags, Mode}; use nix::unistd::{AccessFlags, Gid, Uid}; use num_traits::AsPrimitive; use std::cmp::min; +#[cfg(any(target_os = "linux", target_os = "android"))] use std::ffi::CStr; use std::fmt::Display; use std::fs::File; -use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write}; +use std::io::{BufRead, Read, Seek, SeekFrom, Write}; use std::mem::MaybeUninit; use std::os::fd::{AsFd, BorrowedFd}; use std::os::unix::ffi::OsStrExt; @@ -172,7 +173,7 @@ impl FileAttr { #[inline(always)] #[allow(clippy::unnecessary_cast)] fn is(&self, mode: mode_t) -> bool { - (self.st.st_mode & libc::S_IFMT as c_uint) as mode_t == mode + (self.st.st_mode as mode_t & libc::S_IFMT as mode_t) == mode } pub fn is_dir(&self) -> bool { @@ -208,6 +209,7 @@ impl FileAttr { } } +#[cfg(any(target_os = "linux", target_os = "android"))] const XATTR_NAME_SELINUX: &CStr = c"security.selinux"; // Low-level methods, we should track the caller when error occurs, so return OsResult. @@ -297,6 +299,7 @@ impl Utf8CStr { Ok(()) } + #[cfg(any(target_os = "linux", target_os = "android"))] pub fn get_secontext(&self, con: &mut dyn Utf8CStrBuf) -> OsResult<'_, ()> { con.clear(); let result = unsafe { @@ -319,6 +322,7 @@ impl Utf8CStr { } } + #[cfg(any(target_os = "linux", target_os = "android"))] pub fn set_secontext<'a>(&'a self, con: &'a Utf8CStr) -> OsResult<'a, ()> { unsafe { libc::lsetxattr( @@ -525,6 +529,7 @@ impl FsPathFollow { Ok(()) } + #[cfg(any(target_os = "linux", target_os = "android"))] pub fn get_secontext(&self, con: &mut dyn Utf8CStrBuf) -> OsResult<'_, ()> { con.clear(); let result = unsafe { @@ -547,6 +552,7 @@ impl FsPathFollow { } } + #[cfg(any(target_os = "linux", target_os = "android"))] pub fn set_secontext<'a>(&'a self, con: &'a Utf8CStr) -> OsResult<'a, ()> { unsafe { libc::setxattr( @@ -638,6 +644,7 @@ pub fn fd_set_attr(fd: RawFd, attr: &FileAttr) -> OsResult<'_, ()> { Ok(()) } +#[cfg(any(target_os = "linux", target_os = "android"))] pub fn fd_get_secontext(fd: RawFd, con: &mut dyn Utf8CStrBuf) -> OsResult<'static, ()> { con.clear(); let result = unsafe { @@ -660,6 +667,7 @@ pub fn fd_get_secontext(fd: RawFd, con: &mut dyn Utf8CStrBuf) -> OsResult<'stati } } +#[cfg(any(target_os = "linux", target_os = "android"))] pub fn fd_set_secontext(fd: RawFd, con: &Utf8CStr) -> OsResult<'_, ()> { unsafe { libc::fsetxattr( @@ -775,82 +783,3 @@ pub(crate) fn map_fd(fd: BorrowedFd, sz: usize, rw: bool) -> OsResult<'static, & Ok(slice::from_raw_parts_mut(ptr.cast(), sz)) } } - -#[allow(dead_code)] -pub struct MountInfo { - pub id: u32, - pub parent: u32, - pub device: u64, - pub root: String, - pub target: String, - pub vfs_option: String, - pub shared: u32, - pub master: u32, - pub propagation_from: u32, - pub unbindable: bool, - pub fs_type: String, - pub source: String, - pub fs_option: String, -} - -#[allow(clippy::useless_conversion)] -fn parse_mount_info_line(line: &str) -> Option { - let mut iter = line.split_whitespace(); - let id = iter.next()?.parse().ok()?; - let parent = iter.next()?.parse().ok()?; - let (maj, min) = iter.next()?.split_once(':')?; - let maj = maj.parse().ok()?; - let min = min.parse().ok()?; - let device = makedev(maj, min).into(); - let root = iter.next()?.to_string(); - let target = iter.next()?.to_string(); - let vfs_option = iter.next()?.to_string(); - let mut optional = iter.next()?; - let mut shared = 0; - let mut master = 0; - let mut propagation_from = 0; - let mut unbindable = false; - while optional != "-" { - if let Some(peer) = optional.strip_prefix("master:") { - master = peer.parse().ok()?; - } else if let Some(peer) = optional.strip_prefix("shared:") { - shared = peer.parse().ok()?; - } else if let Some(peer) = optional.strip_prefix("propagate_from:") { - propagation_from = peer.parse().ok()?; - } else if optional == "unbindable" { - unbindable = true; - } - optional = iter.next()?; - } - let fs_type = iter.next()?.to_string(); - let source = iter.next()?.to_string(); - let fs_option = iter.next()?.to_string(); - Some(MountInfo { - id, - parent, - device, - root, - target, - vfs_option, - shared, - master, - propagation_from, - unbindable, - fs_type, - source, - fs_option, - }) -} - -pub fn parse_mount_info(pid: &str) -> Vec { - let mut res = vec![]; - let mut path = format!("/proc/{pid}/mountinfo"); - if let Ok(file) = Utf8CStr::from_string(&mut path).open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) { - BufReader::new(file).for_each_line(|line| { - parse_mount_info_line(line) - .map(|info| res.push(info)) - .is_some() - }); - } - res -} diff --git a/native/src/base/lib.rs b/native/src/base/lib.rs index e42f5df33..02596ee19 100644 --- a/native/src/base/lib.rs +++ b/native/src/base/lib.rs @@ -14,6 +14,8 @@ pub use ffi::Utf8CStrRef; pub use files::*; pub use logging::*; pub use misc::*; +#[cfg(any(target_os = "linux", target_os = "android"))] +pub use mount::*; pub use result::*; pub mod argh; @@ -23,6 +25,7 @@ mod dir; mod files; mod logging; mod misc; +#[cfg(any(target_os = "linux", target_os = "android"))] mod mount; mod result; mod xwrap; diff --git a/native/src/base/mount.rs b/native/src/base/mount.rs index 4c0dc7818..1b4ea2e63 100644 --- a/native/src/base/mount.rs +++ b/native/src/base/mount.rs @@ -1,5 +1,8 @@ -use crate::{LibcReturn, OsResult, Utf8CStr}; +use crate::{BufReadExt, LibcReturn, OsResult, Utf8CStr}; +use libc::makedev; +use nix::fcntl::OFlag; use nix::mount::{MntFlags, MsFlags, mount, umount2}; +use std::io::BufReader; impl Utf8CStr { pub fn bind_mount_to<'a>(&'a self, path: &'a Utf8CStr, rec: bool) -> OsResult<'a, ()> { @@ -82,3 +85,82 @@ impl Utf8CStr { .check_os_err("set_mount_private", Some(self), None) } } + +#[allow(dead_code)] +pub struct MountInfo { + pub id: u32, + pub parent: u32, + pub device: u64, + pub root: String, + pub target: String, + pub vfs_option: String, + pub shared: u32, + pub master: u32, + pub propagation_from: u32, + pub unbindable: bool, + pub fs_type: String, + pub source: String, + pub fs_option: String, +} + +#[allow(clippy::useless_conversion)] +fn parse_mount_info_line(line: &str) -> Option { + let mut iter = line.split_whitespace(); + let id = iter.next()?.parse().ok()?; + let parent = iter.next()?.parse().ok()?; + let (maj, min) = iter.next()?.split_once(':')?; + let maj = maj.parse().ok()?; + let min = min.parse().ok()?; + let device = makedev(maj, min).into(); + let root = iter.next()?.to_string(); + let target = iter.next()?.to_string(); + let vfs_option = iter.next()?.to_string(); + let mut optional = iter.next()?; + let mut shared = 0; + let mut master = 0; + let mut propagation_from = 0; + let mut unbindable = false; + while optional != "-" { + if let Some(peer) = optional.strip_prefix("master:") { + master = peer.parse().ok()?; + } else if let Some(peer) = optional.strip_prefix("shared:") { + shared = peer.parse().ok()?; + } else if let Some(peer) = optional.strip_prefix("propagate_from:") { + propagation_from = peer.parse().ok()?; + } else if optional == "unbindable" { + unbindable = true; + } + optional = iter.next()?; + } + let fs_type = iter.next()?.to_string(); + let source = iter.next()?.to_string(); + let fs_option = iter.next()?.to_string(); + Some(MountInfo { + id, + parent, + device, + root, + target, + vfs_option, + shared, + master, + propagation_from, + unbindable, + fs_type, + source, + fs_option, + }) +} + +pub fn parse_mount_info(pid: &str) -> Vec { + let mut res = vec![]; + let mut path = format!("/proc/{pid}/mountinfo"); + if let Ok(file) = Utf8CStr::from_string(&mut path).open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) { + BufReader::new(file).for_each_line(|line| { + parse_mount_info_line(line) + .map(|info| res.push(info)) + .is_some() + }); + } + res +} diff --git a/native/src/base/xwrap.rs b/native/src/base/xwrap.rs index f33ad6d1d..9185ff046 100644 --- a/native/src/base/xwrap.rs +++ b/native/src/base/xwrap.rs @@ -2,7 +2,7 @@ use crate::cxx_extern::readlinkat; use crate::{Directory, LibcReturn, ResultExt, Utf8CStr, slice_from_ptr, slice_from_ptr_mut}; -use libc::{c_char, c_uint, c_ulong, c_void, dev_t, mode_t, off_t}; +use libc::{c_char, c_uint, c_void, dev_t, mode_t, off_t}; use std::ffi::CStr; use std::fs::File; use std::io::{Read, Write}; @@ -20,6 +20,70 @@ fn ptr_to_str<'a>(ptr: *const c_char) -> Option<&'a str> { } } +#[cfg(any(target_os = "linux", target_os = "android"))] +mod linux { + use crate::xwrap::ptr_to_str; + use crate::{LibcReturn, ResultExt}; + use std::ffi::{c_char, c_void}; + use std::os::fd::RawFd; + + #[unsafe(no_mangle)] + extern "C" fn xsetns(fd: RawFd, nstype: i32) -> i32 { + unsafe { + libc::setns(fd, nstype) + .into_os_result("setns", None, None) + .log() + .unwrap_or(-1) + } + } + + #[unsafe(no_mangle)] + extern "C" fn xunshare(flags: i32) -> i32 { + unsafe { + libc::unshare(flags) + .into_os_result("unshare", None, None) + .log() + .unwrap_or(-1) + } + } + + #[unsafe(no_mangle)] + unsafe extern "C" fn xpipe2(fds: *mut i32, flags: i32) -> i32 { + unsafe { + libc::pipe2(fds, flags) + .into_os_result("pipe2", None, None) + .log() + .unwrap_or(-1) + } + } + + #[unsafe(no_mangle)] + unsafe extern "C" fn xmount( + src: *const c_char, + target: *const c_char, + fstype: *const c_char, + flags: libc::c_ulong, + data: *const c_void, + ) -> i32 { + unsafe { + libc::mount(src, target, fstype, flags, data) + .into_os_result("mount", ptr_to_str(src), ptr_to_str(target)) + .log() + .unwrap_or(-1) + } + } + + #[unsafe(no_mangle)] + unsafe extern "C" fn xumount2(target: *const c_char, flags: i32) -> i32 { + unsafe { + libc::umount2(target, flags) + .into_os_result("umount2", ptr_to_str(target), None) + .log() + .unwrap_or(-1) + } + } +} + #[unsafe(no_mangle)] unsafe extern "C" fn xreadlinkat( dirfd: RawFd, @@ -103,36 +167,6 @@ unsafe extern "C" fn xxread(fd: RawFd, buf: *mut u8, bufsz: usize) -> isize { .map_or(-1, |_| data.len() as isize) } -#[unsafe(no_mangle)] -unsafe extern "C" fn xpipe2(fds: *mut i32, flags: i32) -> i32 { - unsafe { - libc::pipe2(fds, flags) - .into_os_result("pipe2", None, None) - .log() - .unwrap_or(-1) - } -} - -#[unsafe(no_mangle)] -extern "C" fn xsetns(fd: RawFd, nstype: i32) -> i32 { - unsafe { - libc::setns(fd, nstype) - .into_os_result("setns", None, None) - .log() - .unwrap_or(-1) - } -} - -#[unsafe(no_mangle)] -extern "C" fn xunshare(flags: i32) -> i32 { - unsafe { - libc::unshare(flags) - .into_os_result("unshare", None, None) - .log() - .unwrap_or(-1) - } -} - #[unsafe(no_mangle)] unsafe extern "C" fn xopendir(path: *const c_char) -> *mut libc::DIR { unsafe { @@ -202,32 +236,6 @@ unsafe extern "C" fn xsymlink(target: *const c_char, linkpath: *const c_char) -> } } -#[unsafe(no_mangle)] -unsafe extern "C" fn xmount( - src: *const c_char, - target: *const c_char, - fstype: *const c_char, - flags: c_ulong, - data: *const c_void, -) -> i32 { - unsafe { - libc::mount(src, target, fstype, flags, data) - .into_os_result("mount", ptr_to_str(src), ptr_to_str(target)) - .log() - .unwrap_or(-1) - } -} - -#[unsafe(no_mangle)] -unsafe extern "C" fn xumount2(target: *const c_char, flags: i32) -> i32 { - unsafe { - libc::umount2(target, flags) - .into_os_result("umount2", ptr_to_str(target), None) - .log() - .unwrap_or(-1) - } -} - #[unsafe(no_mangle)] unsafe extern "C" fn xrename(oldname: *const c_char, newname: *const c_char) -> i32 { unsafe { @@ -265,12 +273,57 @@ unsafe extern "C" fn xsendfile( offset: *mut off_t, count: usize, ) -> isize { + #[cfg(any(target_os = "linux", target_os = "android"))] unsafe { libc::sendfile(out_fd, in_fd, offset, count) .into_os_result("sendfile", None, None) .log() .unwrap_or(-1) } + #[cfg(not(any(target_os = "linux", target_os = "android")))] + unsafe { + let mut total = 0; + let mut buf = [0u8; 65536]; + if !offset.is_null() { + let cur = libc::lseek(in_fd, *offset, libc::SEEK_SET); + if cur < 0 { + return (-1isize) + .into_os_result("lseek", None, None) + .log() + .unwrap_or(-1); + } + } + while total < count { + let to_read = std::cmp::min(buf.len(), count - total); + let nread = libc::read(in_fd, buf.as_mut_ptr().cast(), to_read); + if nread < 0 { + return nread.into_os_result("read", None, None).log().unwrap_or(-1); + } + if nread == 0 { + break; + } + let mut written = 0; + while written < nread { + let nwrite = libc::write( + out_fd, + buf.as_ptr().add(written as usize).cast(), + (nread - written) as usize, + ); + if nwrite < 0 { + return nwrite + .into_os_result("write", None, None) + .log() + .unwrap_or(-1); + } + written += nwrite; + } + total += nread as usize; + } + if !offset.is_null() { + *offset += total as off_t; + } + total as isize + } } #[unsafe(no_mangle)] diff --git a/native/src/boot/Cargo.toml b/native/src/boot/Cargo.toml index 258bf383c..89dfc390f 100644 --- a/native/src/boot/Cargo.toml +++ b/native/src/boot/Cargo.toml @@ -4,15 +4,20 @@ version.workspace = true edition.workspace = true [lib] -crate-type = ["staticlib"] +crate-type = ["staticlib", "rlib"] path = "lib.rs" +[[bin]] +name = "magiskboot" +path = "main.rs" + [lints] workspace = true [build-dependencies] cxx-gen = { workspace = true } pb-rs = { workspace = true } +cc = { workspace = true } [dependencies] base = { workspace = true } diff --git a/native/src/boot/build.rs b/native/src/boot/build.rs index 4aadd0356..e8164dbfd 100644 --- a/native/src/boot/build.rs +++ b/native/src/boot/build.rs @@ -26,4 +26,32 @@ fn main() { .build(), ) .unwrap(); + + let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + if target_os != "android" { + // Compile liblz4 C sources to satisfy lz4-sys extern symbols on host + let mut lz4_build = cc::Build::new(); + lz4_build + .include("../external/lz4/lib") + .file("../external/lz4/lib/lz4.c") + .file("../external/lz4/lib/lz4frame.c") + .file("../external/lz4/lib/lz4hc.c") + .file("../external/lz4/lib/xxhash.c") + .warnings(false) + .compile("lz4"); + + // Compile magiskboot C++ sources + let mut build = cc::Build::new(); + build + .cpp(true) + .std("c++23") + .include("../include") + .include("../base/include") + .include("../external/cxx-rs/include") + .include("../../out/generated") + .file("bootimg.cpp") + .file("boot-rs.cpp") + .warnings(false) + .compile("boot_cxx"); + } } diff --git a/native/src/boot/lib.rs b/native/src/boot/lib.rs index 9d72005ba..0433d1c6c 100644 --- a/native/src/boot/lib.rs +++ b/native/src/boot/lib.rs @@ -9,6 +9,7 @@ use sign::{SHA, get_sha, sha256_hash, sign_payload_for_cxx}; use std::env; mod cli; +pub use cli::main; mod compress; mod cpio; mod dtb; diff --git a/native/src/boot/main.rs b/native/src/boot/main.rs new file mode 100644 index 000000000..b8a00528a --- /dev/null +++ b/native/src/boot/main.rs @@ -0,0 +1,3 @@ +#![no_main] + +pub use magiskboot::main;