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
This commit is contained in:
topjohnwu
2026-10-02 17:17:48 -07:00
parent 33d09a2aff
commit 66bcdaf4e0
16 changed files with 274 additions and 143 deletions
+1
View File
@@ -14,6 +14,7 @@ workspace = true
[build-dependencies]
cxx-gen = { workspace = true }
cc = { workspace = true }
[dependencies]
derive = { workspace = true }
+17
View File
@@ -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");
}
}
+3
View File
@@ -7,6 +7,9 @@ edition.workspace = true
path = "lib.rs"
proc-macro = true
[lints]
workspace = true
[dependencies]
syn = { workspace = true }
quote = { workspace = true }
+1
View File
@@ -1,4 +1,5 @@
#![recursion_limit = "256"]
#![allow(clippy::unwrap_used)]
use proc_macro::TokenStream;
+11 -82
View File
@@ -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<MountInfo> {
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<MountInfo> {
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
}
+3
View File
@@ -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;
+83 -1
View File
@@ -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<MountInfo> {
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<MountInfo> {
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
}
+110 -57
View File
@@ -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)]