Update to ONDK r29.5

This commit is contained in:
topjohnwu
2026-02-06 12:25:03 -08:00
committed by John Wu
parent e872fafd8b
commit 9ee6a6b3d7
21 changed files with 114 additions and 97 deletions
+1 -1
View File
@@ -80,7 +80,7 @@ support_targets = {"magisk", "magiskinit", "magiskboot", "magiskpolicy", "resetp
default_targets = support_targets - {"resetprop"} default_targets = support_targets - {"resetprop"}
rust_targets = default_targets.copy() rust_targets = default_targets.copy()
clean_targets = {"native", "cpp", "rust", "app"} clean_targets = {"native", "cpp", "rust", "app"}
ondk_version = "r29.4" ondk_version = "r29.5"
# Global vars # Global vars
config = {} config = {}
-1
View File
@@ -1,4 +1,3 @@
#![feature(vec_into_raw_parts)]
#![allow(clippy::missing_safety_doc)] #![allow(clippy::missing_safety_doc)]
pub use {const_format, libc, nix}; pub use {const_format, libc, nix};
+6 -4
View File
@@ -279,20 +279,22 @@ pub fn get_decoder<'a, R: Read + 'a>(
pub fn compress_bytes(format: FileFormat, in_bytes: &[u8], out_fd: RawFd) { 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 mut out_file = unsafe { ManuallyDrop::new(File::from_raw_fd(out_fd)) };
let _: LoggedResult<()> = try { let _ = || -> LoggedResult<()> {
let mut encoder = get_encoder(format, out_file.deref_mut())?; let mut encoder = get_encoder(format, out_file.deref_mut())?;
std::io::copy(&mut Cursor::new(in_bytes), encoder.deref_mut())?; std::io::copy(&mut Cursor::new(in_bytes), encoder.deref_mut())?;
encoder.finish()?; encoder.finish()?;
}; Ok(())
}();
} }
pub fn decompress_bytes(format: FileFormat, in_bytes: &[u8], out_fd: RawFd) { pub fn decompress_bytes(format: FileFormat, in_bytes: &[u8], out_fd: RawFd) {
let mut out_file = unsafe { ManuallyDrop::new(File::from_raw_fd(out_fd)) }; let mut out_file = unsafe { ManuallyDrop::new(File::from_raw_fd(out_fd)) };
let _: LoggedResult<()> = try { let _ = || -> LoggedResult<()> {
let mut decoder = get_decoder(format, in_bytes)?; let mut decoder = get_decoder(format, in_bytes)?;
std::io::copy(decoder.as_mut(), out_file.deref_mut())?; std::io::copy(decoder.as_mut(), out_file.deref_mut())?;
}; Ok(())
}();
} }
// Command-line entry points // Command-line entry points
+6 -6
View File
@@ -699,11 +699,11 @@ impl CpioEntry {
if self.mode & S_IFMT != S_IFREG { if self.mode & S_IFMT != S_IFREG {
return false; return false;
} }
let Ok(data): std::io::Result<Vec<u8>> = (try { let Ok(data) = || -> std::io::Result<Vec<u8>> {
let mut encoder = get_encoder(FileFormat::XZ, Vec::new())?; let mut encoder = get_encoder(FileFormat::XZ, Vec::new())?;
encoder.write_all(&self.data)?; encoder.write_all(&self.data)?;
encoder.finish()? encoder.finish()
}) else { }() else {
eprintln!("xz compression failed"); eprintln!("xz compression failed");
return false; return false;
}; };
@@ -717,12 +717,12 @@ impl CpioEntry {
return false; return false;
} }
let Ok(data): std::io::Result<Vec<u8>> = (try { let Ok(data) = || -> std::io::Result<Vec<u8>> {
let mut decoder = get_decoder(FileFormat::XZ, Cursor::new(&self.data))?; let mut decoder = get_decoder(FileFormat::XZ, Cursor::new(&self.data))?;
let mut data = Vec::new(); let mut data = Vec::new();
std::io::copy(decoder.as_mut(), &mut data)?; std::io::copy(decoder.as_mut(), &mut data)?;
data Ok(data)
}) else { }() else {
eprintln!("xz compression failed"); eprintln!("xz compression failed");
return false; return false;
}; };
-1
View File
@@ -1,6 +1,5 @@
#![feature(format_args_nl)] #![feature(format_args_nl)]
#![feature(iter_intersperse)] #![feature(iter_intersperse)]
#![feature(try_blocks)]
pub use base; pub use base;
use compress::{compress_bytes, decompress_bytes}; use compress::{compress_bytes, decompress_bytes};
+3 -3
View File
@@ -103,7 +103,7 @@ fn hex2byte(hex: &[u8]) -> Vec<u8> {
} }
pub fn hexpatch(file: &Utf8CStr, from: &Utf8CStr, to: &Utf8CStr) -> bool { pub fn hexpatch(file: &Utf8CStr, from: &Utf8CStr, to: &Utf8CStr) -> bool {
let res: LoggedResult<bool> = try { let res = || -> LoggedResult<bool> {
let mut map = MappedFile::open_rw(file)?; let mut map = MappedFile::open_rw(file)?;
let pattern = hex2byte(from.as_bytes()); let pattern = hex2byte(from.as_bytes());
let patch = hex2byte(to.as_bytes()); let patch = hex2byte(to.as_bytes());
@@ -112,7 +112,7 @@ pub fn hexpatch(file: &Utf8CStr, from: &Utf8CStr, to: &Utf8CStr) -> bool {
for off in &v { for off in &v {
eprintln!("Patch @ {off:#010X} [{from}] -> [{to}]"); eprintln!("Patch @ {off:#010X} [{from}] -> [{to}]");
} }
!v.is_empty() Ok(!v.is_empty())
}; }();
res.unwrap_or(false) res.unwrap_or(false)
} }
+3 -2
View File
@@ -164,10 +164,11 @@ pub fn extract_boot_from_payload(
out_file.seek(SeekFrom::Start(out_offset))?; out_file.seek(SeekFrom::Start(out_offset))?;
let fmt = check_fmt(data); let fmt = check_fmt(data);
let Ok(_): std::io::Result<()> = (try { let Ok(_) = || -> std::io::Result<()> {
let mut decoder = get_decoder(fmt, Cursor::new(data))?; let mut decoder = get_decoder(fmt, Cursor::new(data))?;
std::io::copy(decoder.as_mut(), &mut out_file)?; std::io::copy(decoder.as_mut(), &mut out_file)?;
}) else { Ok(())
}() else {
return Err(bad_payload!("decompression failed")); return Err(bad_payload!("decompression failed"));
}; };
} }
-1
View File
@@ -1,4 +1,3 @@
#![feature(try_blocks)]
#![feature(fn_traits)] #![feature(fn_traits)]
#![feature(unix_socket_ancillary_data)] #![feature(unix_socket_ancillary_data)]
#![feature(unix_socket_peek)] #![feature(unix_socket_peek)]
+3 -2
View File
@@ -329,7 +329,7 @@ pub fn start_log_daemon() {
0 0
} }
let _: LoggedResult<()> = try { let _ = || -> LoggedResult<()> {
path.mkfifo(0o666).log_ok(); path.mkfifo(0o666).log_ok();
chown(path.as_utf8_cstr(), Some(Uid::from(0)), Some(Gid::from(0)))?; chown(path.as_utf8_cstr(), Some(Uid::from(0)), Some(Gid::from(0)))?;
let read = path.open(OFlag::O_RDWR | OFlag::O_CLOEXEC)?; let read = path.open(OFlag::O_RDWR | OFlag::O_CLOEXEC)?;
@@ -338,5 +338,6 @@ pub fn start_log_daemon() {
unsafe { unsafe {
new_daemon_thread(logfile_writer_thread, read.into_raw_fd() as usize); new_daemon_thread(logfile_writer_thread, read.into_raw_fd() as usize);
} }
}; Ok(())
}();
} }
+17 -12
View File
@@ -46,12 +46,13 @@ pub fn setup_preinit_dir() {
let target = Utf8CStr::from_string(&mut target); let target = Utf8CStr::from_string(&mut target);
let mut preinit_dir = resolve_preinit_dir(target); let mut preinit_dir = resolve_preinit_dir(target);
let preinit_dir = Utf8CStr::from_string(&mut preinit_dir); let preinit_dir = Utf8CStr::from_string(&mut preinit_dir);
let r: LoggedResult<()> = try { let r = || -> LoggedResult<()> {
preinit_dir.mkdir(0o700)?; preinit_dir.mkdir(0o700)?;
mnt_path.mkdirs(0o755)?; mnt_path.mkdirs(0o755)?;
mnt_path.remove().ok(); mnt_path.remove().ok();
mnt_path.create_symlink_to(preinit_dir)?; mnt_path.create_symlink_to(preinit_dir)?;
}; Ok(())
}();
if r.is_ok() { if r.is_ok() {
info!("* Found preinit dir: {}", preinit_dir); info!("* Found preinit dir: {}", preinit_dir);
return; return;
@@ -68,11 +69,12 @@ pub fn setup_module_mount() {
let module_mnt = cstr::buf::default() let module_mnt = cstr::buf::default()
.join_path(get_magisk_tmp()) .join_path(get_magisk_tmp())
.join_path(MODULEMNT); .join_path(MODULEMNT);
let _: LoggedResult<()> = try { let _ = || -> LoggedResult<()> {
module_mnt.mkdir(0o755)?; module_mnt.mkdir(0o755)?;
cstr!(MODULEROOT).bind_mount_to(&module_mnt, false)?; cstr!(MODULEROOT).bind_mount_to(&module_mnt, false)?;
module_mnt.remount_mount_point_flags(MsFlags::MS_RDONLY)?; module_mnt.remount_mount_point_flags(MsFlags::MS_RDONLY)?;
}; Ok(())
}();
} }
pub fn clean_mounts() { pub fn clean_mounts() {
@@ -85,10 +87,11 @@ pub fn clean_mounts() {
buf.clear(); buf.clear();
let worker_dir = buf.append_path(magisk_tmp).append_path(WORKERDIR); let worker_dir = buf.append_path(magisk_tmp).append_path(WORKERDIR);
let _: LoggedResult<()> = try { let _ = || -> LoggedResult<()> {
worker_dir.set_mount_private(true)?; worker_dir.set_mount_private(true)?;
worker_dir.unmount()?; worker_dir.unmount()?;
}; Ok(())
}();
} }
// when partitions have the same fs type, the order is: // when partitions have the same fs type, the order is:
@@ -146,10 +149,11 @@ pub fn find_preinit_device() -> String {
} }
// use device major number to filter out device-mapper // use device major number to filter out device-mapper
let maj = major(info.device as dev_t) as u32; let maj = major(info.device as dev_t) as u32;
if maj >= DYNAMIC_MAJOR_MIN && maj <= DYNAMIC_MAJOR_MAX { if (DYNAMIC_MAJOR_MIN..=DYNAMIC_MAJOR_MAX).contains(&maj)
if !info.source.contains("/vd") && !info.source.contains("/by-name/") { && !info.source.contains("/vd")
return None; && !info.source.contains("/by-name/")
} {
return None;
} }
// take data iff it's not encrypted or file-based encrypted without metadata // take data iff it's not encrypted or file-based encrypted without metadata
// other partitions are always taken // other partitions are always taken
@@ -196,13 +200,14 @@ pub fn find_preinit_device() -> String {
let mut buf = cstr::buf::default(); let mut buf = cstr::buf::default();
let mirror_dir = buf.append_path(&tmp).append_path(PREINITMIRR); let mirror_dir = buf.append_path(&tmp).append_path(PREINITMIRR);
let preinit_dir = Utf8CStr::from_string(&mut preinit_dir); let preinit_dir = Utf8CStr::from_string(&mut preinit_dir);
let _: LoggedResult<()> = try { let _ = || -> LoggedResult<()> {
preinit_dir.mkdirs(0o700)?; preinit_dir.mkdirs(0o700)?;
mirror_dir.mkdirs(0o755)?; mirror_dir.mkdirs(0o755)?;
mirror_dir.unmount().ok(); mirror_dir.unmount().ok();
mirror_dir.remove().ok(); mirror_dir.remove().ok();
mirror_dir.create_symlink_to(preinit_dir)?; mirror_dir.create_symlink_to(preinit_dir)?;
}; Ok(())
}();
if std::env::var_os("MAKEDEV").is_some() { if std::env::var_os("MAKEDEV").is_some() {
buf.clear(); buf.clear();
let dev_path = buf.append_path(&tmp).append_path(PREINITDEV); let dev_path = buf.append_path(&tmp).append_path(PREINITDEV);
+9 -7
View File
@@ -49,7 +49,7 @@ macro_rules! bad_apk {
* within the APK v2 signature block. * within the APK v2 signature block.
*/ */
fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> { fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {
let res: io::Result<Vec<u8>> = try { let res = || -> io::Result<Vec<u8>> {
let mut u32_val = 0u32; let mut u32_val = 0u32;
let mut u64_val = 0u64; let mut u64_val = 0u64;
@@ -137,7 +137,7 @@ fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {
let mut cert = vec![0; u32_val as usize]; let mut cert = vec![0; u32_val as usize];
apk.read_exact(cert.as_mut())?; apk.read_exact(cert.as_mut())?;
break cert; break Ok(cert);
} else { } else {
// Skip this id-value pair // Skip this id-value pair
apk.seek(SeekFrom::Current( apk.seek(SeekFrom::Current(
@@ -145,7 +145,7 @@ fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {
))?; ))?;
} }
} }
}; }();
res.log().unwrap_or(vec![]) res.log().unwrap_or(vec![])
} }
@@ -315,7 +315,7 @@ impl ManagerInfo {
if let Some(ref mut stub_fd) = self.stub_apk_fd { if let Some(ref mut stub_fd) = self.stub_apk_fd {
// Copy the stub APK // Copy the stub APK
let tmp_apk = cstr!("/data/stub.apk"); let tmp_apk = cstr!("/data/stub.apk");
let result: LoggedResult<()> = try { let result = || -> LoggedResult<()> {
{ {
let mut tmp_apk_file = tmp_apk.create( let mut tmp_apk_file = tmp_apk.create(
OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_TRUNC | OFlag::O_CLOEXEC, OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_TRUNC | OFlag::O_CLOEXEC,
@@ -325,7 +325,8 @@ impl ManagerInfo {
} }
// Seek the fd back to start // Seek the fd back to start
stub_fd.seek(SeekFrom::Start(0))?; stub_fd.seek(SeekFrom::Start(0))?;
}; Ok(())
}();
if result.is_ok() { if result.is_ok() {
install_apk(tmp_apk); install_apk(tmp_apk);
} }
@@ -478,7 +479,7 @@ impl MagiskD {
// app_no range: [0, 9999] // app_no range: [0, 9999]
pub fn get_app_no_list(&self) -> BitSet { pub fn get_app_no_list(&self) -> BitSet {
let mut list = BitSet::new(); let mut list = BitSet::new();
let _: LoggedResult<()> = try { let _ = || -> LoggedResult<()> {
let mut app_data_dir = Directory::open(self.app_data_dir())?; let mut app_data_dir = Directory::open(self.app_data_dir())?;
// For each user // For each user
loop { loop {
@@ -507,7 +508,8 @@ impl MagiskD {
} }
} }
} }
}; Ok(())
}();
list list
} }
} }
+3 -3
View File
@@ -175,7 +175,7 @@ impl SuAppContext<'_> {
)) ))
.ok(); .ok();
let fd: LoggedResult<File> = try { let fd = || -> LoggedResult<File> {
let mut attr = FileAttr::new(); let mut attr = FileAttr::new();
attr.st.st_mode = 0o600; attr.st.st_mode = 0o600;
attr.st.st_uid = self.info.mgr_uid.as_(); attr.st.st_uid = self.info.mgr_uid.as_();
@@ -211,8 +211,8 @@ impl SuAppContext<'_> {
PollTimeout::try_from(70 * 1000).unwrap_or(PollTimeout::NONE), PollTimeout::try_from(70 * 1000).unwrap_or(PollTimeout::NONE),
) )
.check_os_err("poll", None, None)?; .check_os_err("poll", None, None)?;
fd Ok(fd)
}; }();
fifo.remove().log_ok(); fifo.remove().log_ok();
+10 -10
View File
@@ -215,14 +215,14 @@ impl MagiskD {
#[cfg(feature = "su-check-db")] #[cfg(feature = "su-check-db")]
fn build_su_info(&self, uid: i32) -> Arc<SuInfo> { fn build_su_info(&self, uid: i32) -> Arc<SuInfo> {
let result: LoggedResult<Arc<SuInfo>> = try { let result = || -> LoggedResult<Arc<SuInfo>> {
let cfg = self.get_db_settings()?; let cfg = self.get_db_settings()?;
// Check multiuser settings // Check multiuser settings
let eval_uid = match cfg.multiuser_mode { let eval_uid = match cfg.multiuser_mode {
MultiuserMode::OwnerOnly => { MultiuserMode::OwnerOnly => {
if to_user_id(uid) != 0 { if to_user_id(uid) != 0 {
return Arc::new(SuInfo::deny(uid)); return Ok(Arc::new(SuInfo::deny(uid)));
} }
uid uid
} }
@@ -243,25 +243,25 @@ impl MagiskD {
// If it's the manager, allow it silently // If it's the manager, allow it silently
if to_app_id(uid) == to_app_id(mgr_uid) { if to_app_id(uid) == to_app_id(mgr_uid) {
return Arc::new(SuInfo::allow(uid)); return Ok(Arc::new(SuInfo::allow(uid)));
} }
// Check su access settings // Check su access settings
match cfg.root_access { match cfg.root_access {
RootAccess::Disabled => { RootAccess::Disabled => {
warn!("Root access is disabled!"); warn!("Root access is disabled!");
return Arc::new(SuInfo::deny(uid)); return Ok(Arc::new(SuInfo::deny(uid)));
} }
RootAccess::AdbOnly => { RootAccess::AdbOnly => {
if uid != AID_SHELL { if uid != AID_SHELL {
warn!("Root access limited to ADB only!"); warn!("Root access limited to ADB only!");
return Arc::new(SuInfo::deny(uid)); return Ok(Arc::new(SuInfo::deny(uid)));
} }
} }
RootAccess::AppsOnly => { RootAccess::AppsOnly => {
if uid == AID_SHELL { if uid == AID_SHELL {
warn!("Root access is disabled for ADB!"); warn!("Root access is disabled for ADB!");
return Arc::new(SuInfo::deny(uid)); return Ok(Arc::new(SuInfo::deny(uid)));
} }
} }
_ => {} _ => {}
@@ -269,19 +269,19 @@ impl MagiskD {
// If still not determined, check if manager exists // If still not determined, check if manager exists
if access.policy == SuPolicy::Query && mgr_uid < 0 { if access.policy == SuPolicy::Query && mgr_uid < 0 {
return Arc::new(SuInfo::deny(uid)); return Ok(Arc::new(SuInfo::deny(uid)));
} }
// Finally, the SuInfo // Finally, the SuInfo
Arc::new(SuInfo { Ok(Arc::new(SuInfo {
uid, uid,
eval_uid, eval_uid,
mgr_pkg, mgr_pkg,
mgr_uid, mgr_uid,
cfg, cfg,
access: Mutex::new(AccessInfo::new(access)), access: Mutex::new(AccessInfo::new(access)),
}) }))
}; }();
result.unwrap_or(Arc::new(SuInfo::deny(uid))) result.unwrap_or(Arc::new(SuInfo::deny(uid)))
} }
+4 -6
View File
@@ -1,8 +1,8 @@
use base::{ResultExt, new_daemon_thread}; use base::{ResultExt, new_daemon_thread};
use nix::sys::signal::SigSet; use nix::sys::signal::SigSet;
use nix::unistd::{getpid, gettid}; use nix::unistd::{getpid, gettid};
use std::sync::LazyLock;
use std::sync::nonpoison::{Condvar, Mutex}; use std::sync::nonpoison::{Condvar, Mutex};
use std::sync::{LazyLock, WaitTimeoutResult};
use std::time::Duration; use std::time::Duration;
static THREAD_POOL: LazyLock<ThreadPool> = LazyLock::new(ThreadPool::default); static THREAD_POOL: LazyLock<ThreadPool> = LazyLock::new(ThreadPool::default);
@@ -39,12 +39,10 @@ impl ThreadPool {
if info.task.is_none() { if info.task.is_none() {
if is_core_pool { if is_core_pool {
// Core pool never closes, wait forever. // Core pool never closes, wait forever.
info = self.task_is_some.wait(info); self.task_is_some.wait(&mut info);
} else { } else {
let dur = Duration::from_secs(THREAD_IDLE_MAX_SEC); let dur = Duration::from_secs(THREAD_IDLE_MAX_SEC);
let result: WaitTimeoutResult; if self.task_is_some.wait_timeout(&mut info, dur).timed_out() {
(info, result) = self.task_is_some.wait_timeout(info, dur);
if result.timed_out() {
// Terminate thread after timeout // Terminate thread after timeout
info.idle_threads -= 1; info.idle_threads -= 1;
info.total_threads -= 1; info.total_threads -= 1;
@@ -76,7 +74,7 @@ impl ThreadPool {
let mut info = self.info.lock(); let mut info = self.info.lock();
while info.task.is_some() { while info.task.is_some() {
// Wait until task is none // Wait until task is none
info = self.task_is_none.wait(info); self.task_is_none.wait(&mut info);
} }
info.task = Some(Box::new(f)); info.task = Some(Box::new(f));
if info.idle_threads == 0 { if info.idle_threads == 0 {
+3 -2
View File
@@ -157,7 +157,7 @@ impl ZygiskState {
impl MagiskD { impl MagiskD {
pub fn zygisk_handler(&self, mut client: UnixStream) { pub fn zygisk_handler(&self, mut client: UnixStream) {
let _: LoggedResult<()> = try { let _ = || -> LoggedResult<()> {
let code = ZygiskRequest { let code = ZygiskRequest {
repr: client.read_decodable()?, repr: client.read_decodable()?,
}; };
@@ -171,7 +171,8 @@ impl MagiskD {
ZygiskRequest::GetModDir => self.get_mod_dir(client)?, ZygiskRequest::GetModDir => self.get_mod_dir(client)?,
_ => {} _ => {}
} }
}; Ok(())
}();
} }
fn get_module_fds(&self, is_64_bit: bool) -> Option<Vec<RawFd>> { fn get_module_fds(&self, is_64_bit: bool) -> Option<Vec<RawFd>> {
-1
View File
@@ -1,4 +1,3 @@
#![feature(try_blocks)]
#![allow(clippy::missing_safety_doc)] #![allow(clippy::missing_safety_doc)]
use logging::setup_klog; use logging::setup_klog;
+4 -3
View File
@@ -17,7 +17,7 @@ unsafe extern "C" {
} }
pub(crate) fn switch_root(path: &Utf8CStr) { pub(crate) fn switch_root(path: &Utf8CStr) {
let res: LoggedResult<()> = try { || -> LoggedResult<()> {
debug!("Switch root to {}", path); debug!("Switch root to {}", path);
let mut mounts = BTreeSet::new(); let mut mounts = BTreeSet::new();
let rootfs = Directory::open(cstr!("/"))?; let rootfs = Directory::open(cstr!("/"))?;
@@ -48,8 +48,9 @@ pub(crate) fn switch_root(path: &Utf8CStr) {
debug!("Cleaning rootfs"); debug!("Cleaning rootfs");
rootfs.remove_all()?; rootfs.remove_all()?;
}; Ok(())
res.ok(); }()
.ok();
} }
pub(crate) fn is_device_mounted(dev: u64, target: Pin<&mut CxxString>) -> bool { pub(crate) fn is_device_mounted(dev: u64, target: Pin<&mut CxxString>) -> bool {
+3 -2
View File
@@ -28,7 +28,7 @@ pub(crate) fn hexpatch_init_for_second_stage(writable: bool) {
// If we cannot directly modify /init, we need to bind mount a replacement on top of it // If we cannot directly modify /init, we need to bind mount a replacement on top of it
let src = cstr!("/init"); let src = cstr!("/init");
let dest = cstr!("/data/init"); let dest = cstr!("/data/init");
let _: LoggedResult<()> = try { let _ = || -> LoggedResult<()> {
{ {
let mut fd = dest.create(OFlag::O_CREAT | OFlag::O_WRONLY, 0)?; let mut fd = dest.create(OFlag::O_CREAT | OFlag::O_WRONLY, 0)?;
fd.write_all(init.as_ref())?; fd.write_all(init.as_ref())?;
@@ -36,7 +36,8 @@ pub(crate) fn hexpatch_init_for_second_stage(writable: bool) {
let attr = src.follow_link().get_attr()?; let attr = src.follow_link().get_attr()?;
dest.set_attr(&attr)?; dest.set_attr(&attr)?;
dest.bind_mount_to(src, false)?; dest.bind_mount_to(src, false)?;
}; Ok(())
}();
} }
} }
+5 -4
View File
@@ -79,12 +79,12 @@ pub unsafe extern "C" fn main(
umask(0); umask(0);
} }
let res: LoggedResult<()> = try { let res = || -> LoggedResult<()> {
let cmds = CmdArgs::new(argc, argv); let cmds = CmdArgs::new(argc, argv);
let cmds = cmds.as_slice(); let cmds = cmds.as_slice();
if argc < 2 { if argc < 2 {
print_usage(cmds.first().unwrap_or(&"magiskpolicy")); print_usage(cmds.first().unwrap_or(&"magiskpolicy"));
return 1; return log_err!();
} }
let cli = Cli::from_args(&[cmds[0]], &cmds[1..]).on_early_exit(|| print_usage(cmds[0])); let cli = Cli::from_args(&[cmds[0]], &cmds[1..]).on_early_exit(|| print_usage(cmds[0]));
@@ -109,7 +109,7 @@ pub unsafe extern "C" fn main(
log_err!("Cannot print rules with other options")?; log_err!("Cannot print rules with other options")?;
} }
sepol.print_rules(); sepol.print_rules();
return 0; return Ok(());
} }
if cli.magisk { if cli.magisk {
@@ -133,6 +133,7 @@ pub unsafe extern "C" fn main(
{ {
log_err!("Cannot dump policy to {}", file)?; log_err!("Cannot dump policy to {}", file)?;
} }
}; Ok(())
}();
if res.is_ok() { 0 } else { 1 } if res.is_ok() { 0 } else { 1 }
} }
-2
View File
@@ -1,5 +1,3 @@
#![feature(try_blocks)]
pub use base; pub use base;
use std::fmt::Write; use std::fmt::Write;
+34 -24
View File
@@ -279,11 +279,12 @@ impl SePolicy {
} }
pub fn load_rule_file(&mut self, filename: &Utf8CStr) { pub fn load_rule_file(&mut self, filename: &Utf8CStr) {
let result: LoggedResult<()> = try { let result = || -> LoggedResult<()> {
let file = filename.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC)?; let file = filename.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC)?;
let mut reader = BufReader::new(file); let mut reader = BufReader::new(file);
self.load_rules_from_reader(&mut reader); self.load_rules_from_reader(&mut reader);
}; Ok(())
}();
result.ok(); result.ok();
} }
@@ -339,7 +340,7 @@ impl SePolicy {
}; };
match action { match action {
Token::AL | Token::DN | Token::AA | Token::DA => { Token::AL | Token::DN | Token::AA | Token::DA => {
let result: ParseResult<()> = try { let result = || -> ParseResult<()> {
let s = parse_sterm(tokens)?; let s = parse_sterm(tokens)?;
let t = parse_sterm(tokens)?; let t = parse_sterm(tokens)?;
let c = parse_sterm(tokens)?; let c = parse_sterm(tokens)?;
@@ -352,13 +353,14 @@ impl SePolicy {
Token::DA => self.dontaudit(s, t, c, p), Token::DA => self.dontaudit(s, t, c, p),
_ => unreachable!(), _ => unreachable!(),
} }
}; Ok(())
}();
if result.is_err() { if result.is_err() {
Err(ParseError::AvtabAv(action))? Err(ParseError::AvtabAv(action))?
} }
} }
Token::AX | Token::AY | Token::DX => { Token::AX | Token::AY | Token::DX => {
let result: ParseResult<()> = try { let result = || -> ParseResult<()> {
let s = parse_sterm(tokens)?; let s = parse_sterm(tokens)?;
let t = parse_sterm(tokens)?; let t = parse_sterm(tokens)?;
let c = parse_sterm(tokens)?; let c = parse_sterm(tokens)?;
@@ -371,13 +373,14 @@ impl SePolicy {
Token::DX => self.dontauditxperm(s, t, c, p), Token::DX => self.dontauditxperm(s, t, c, p),
_ => unreachable!(), _ => unreachable!(),
} }
}; Ok(())
}();
if result.is_err() { if result.is_err() {
Err(ParseError::AvtabXperms(action))? Err(ParseError::AvtabXperms(action))?
} }
} }
Token::PM | Token::EF => { Token::PM | Token::EF => {
let result: ParseResult<()> = try { let result = || -> ParseResult<()> {
let t = parse_sterm(tokens)?; let t = parse_sterm(tokens)?;
check_additional_args(tokens)?; check_additional_args(tokens)?;
match action { match action {
@@ -385,24 +388,26 @@ impl SePolicy {
Token::EF => self.enforce(t), Token::EF => self.enforce(t),
_ => unreachable!(), _ => unreachable!(),
} }
}; Ok(())
}();
if result.is_err() { if result.is_err() {
Err(ParseError::TypeState(action))? Err(ParseError::TypeState(action))?
} }
} }
Token::TA => { Token::TA => {
let result: ParseResult<()> = try { let result = || -> ParseResult<()> {
let t = parse_term(tokens)?; let t = parse_term(tokens)?;
let a = parse_term(tokens)?; let a = parse_term(tokens)?;
check_additional_args(tokens)?; check_additional_args(tokens)?;
self.typeattribute(t, a) self.typeattribute(t, a);
}; Ok(())
}();
if result.is_err() { if result.is_err() {
Err(ParseError::TypeAttr)? Err(ParseError::TypeAttr)?
} }
} }
Token::TY => { Token::TY => {
let result: ParseResult<()> = try { let result = || -> ParseResult<()> {
let t = parse_id(tokens)?; let t = parse_id(tokens)?;
let a = if tokens.peek().is_none() { let a = if tokens.peek().is_none() {
vec![] vec![]
@@ -410,24 +415,26 @@ impl SePolicy {
parse_term(tokens)? parse_term(tokens)?
}; };
check_additional_args(tokens)?; check_additional_args(tokens)?;
self.type_(t, a) self.type_(t, a);
}; Ok(())
}();
if result.is_err() { if result.is_err() {
Err(ParseError::NewType)? Err(ParseError::NewType)?
} }
} }
Token::AT => { Token::AT => {
let result: ParseResult<()> = try { let result = || -> ParseResult<()> {
let t = parse_id(tokens)?; let t = parse_id(tokens)?;
check_additional_args(tokens)?; check_additional_args(tokens)?;
self.attribute(t) self.attribute(t);
}; Ok(())
}();
if result.is_err() { if result.is_err() {
Err(ParseError::NewAttr)? Err(ParseError::NewAttr)?
} }
} }
Token::TC | Token::TM => { Token::TC | Token::TM => {
let result: ParseResult<()> = try { let result = || -> ParseResult<()> {
let s = parse_id(tokens)?; let s = parse_id(tokens)?;
let t = parse_id(tokens)?; let t = parse_id(tokens)?;
let c = parse_id(tokens)?; let c = parse_id(tokens)?;
@@ -438,13 +445,14 @@ impl SePolicy {
Token::TM => self.type_member(s, t, c, d), Token::TM => self.type_member(s, t, c, d),
_ => unreachable!(), _ => unreachable!(),
} }
}; Ok(())
}();
if result.is_err() { if result.is_err() {
Err(ParseError::AvtabType(action))? Err(ParseError::AvtabType(action))?
} }
} }
Token::TT => { Token::TT => {
let result: ParseResult<()> = try { let result = || -> ParseResult<()> {
let s = parse_id(tokens)?; let s = parse_id(tokens)?;
let t = parse_id(tokens)?; let t = parse_id(tokens)?;
let c = parse_id(tokens)?; let c = parse_id(tokens)?;
@@ -456,19 +464,21 @@ impl SePolicy {
}; };
check_additional_args(tokens)?; check_additional_args(tokens)?;
self.type_transition(s, t, c, d, o); self.type_transition(s, t, c, d, o);
}; Ok(())
}();
if result.is_err() { if result.is_err() {
Err(ParseError::TypeTrans)? Err(ParseError::TypeTrans)?
} }
} }
Token::GF => { Token::GF => {
let result: ParseResult<()> = try { let result = || -> ParseResult<()> {
let s = parse_id(tokens)?; let s = parse_id(tokens)?;
let t = parse_id(tokens)?; let t = parse_id(tokens)?;
let c = parse_id(tokens)?; let c = parse_id(tokens)?;
check_additional_args(tokens)?; check_additional_args(tokens)?;
self.genfscon(s, t, c) self.genfscon(s, t, c);
}; Ok(())
}();
if result.is_err() { if result.is_err() {
Err(ParseError::GenfsCon)? Err(ParseError::GenfsCon)?
} }