From a51dc10f88ea3a8aac7fa02e95ae7589a034730b Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Thu, 22 Oct 2026 19:44:07 +0000 Subject: [PATCH] native: Simplify and deduplicate package lookup - Expose MagiskD::get_app_id via CXX bridge and reuse it in denylist instead of duplicating user collection and package UID lookup in C++. - Remove redundant manager package name returns, Status enum, and the ManagerInfo wrapper struct now that the package name is fixed. Assisted-by: Gemini 4 Argon --- native/src/core/daemon.rs | 4 +- native/src/core/deny/utils.cpp | 44 +-------- native/src/core/lib.rs | 1 + native/src/core/package.rs | 165 +++++++++++++-------------------- native/src/core/su/connect.rs | 13 +-- native/src/core/su/daemon.rs | 20 ++-- 6 files changed, 85 insertions(+), 162 deletions(-) diff --git a/native/src/core/daemon.rs b/native/src/core/daemon.rs index 1b9248888..88914373e 100644 --- a/native/src/core/daemon.rs +++ b/native/src/core/daemon.rs @@ -10,7 +10,7 @@ use crate::ffi::{ }; use crate::logging::{android_logging, magisk_logging, setup_logfile, start_log_daemon}; use crate::module::remove_modules; -use crate::package::ManagerInfo; +use crate::package::TrackedFile; use crate::resetprop::{get_prop, set_prop}; use crate::selinux::restore_tmpcon; use crate::socket::{IpcRead, IpcWrite}; @@ -56,7 +56,7 @@ pub const fn to_user_id(uid: i32) -> i32 { #[derive(Default)] pub struct MagiskD { pub sql_connection: Mutex>, - pub manager_info: Mutex, + pub manager_info: Mutex, pub boot_stage_lock: Mutex, pub module_list: OnceLock>, pub zygisk_enabled: AtomicBool, diff --git a/native/src/core/deny/utils.cpp b/native/src/core/deny/utils.cpp index 4dd702e21..45b2a0142 100644 --- a/native/src/core/deny/utils.cpp +++ b/native/src/core/deny/utils.cpp @@ -1,13 +1,10 @@ #include -#include -#include #include #include #include #include #include -#include #include #include @@ -32,38 +29,12 @@ static pthread_mutex_t data_lock = PTHREAD_MUTEX_INITIALIZER; atomic denylist_enforced = false; -static int get_app_id(const vector &users, const string &pkg) { - struct stat st{}; - char buf[PATH_MAX]; - for (const auto &user_id: users) { - ssprintf(buf, sizeof(buf), "%s/%d/%s", APP_DATA_DIR, user_id, pkg.data()); - if (stat(buf, &st) == 0) { - return to_app_id(st.st_uid); - } - } - return 0; -} - -static void collect_users(vector &users) { - auto data_dir = xopen_dir(APP_DATA_DIR); - if (!data_dir) - return; - dirent *entry; - while ((entry = xreaddir(data_dir.get()))) { - int u = parse_int(entry->d_name); - if (u >= 0) - users.emplace_back(u); - } -} - static int get_app_id(const string &pkg) { if (pkg == ISOLATED_MAGIC) return -1; if (pkg == WEBVIEW_ZYGOTE_MAGIC) return WEBVIEW_ZYGOTE_UID; - vector users; - collect_users(users); - return get_app_id(users, pkg); + return MagiskD::Get().get_app_id(pkg); } static void update_app_id(int app_id, const string &pkg, bool remove) { @@ -197,19 +168,8 @@ void scan_deny_apps() { app_id_to_pkgs.clear(); char sql[4096]; - vector users; - collect_users(users); for (auto it = pkg_to_procs.begin(); it != pkg_to_procs.end();) { - if (it->first == ISOLATED_MAGIC) { - it++; - continue; - } - if (it->first == WEBVIEW_ZYGOTE_MAGIC) { - update_app_id(WEBVIEW_ZYGOTE_UID, it->first, false); - it++; - continue; - } - int app_id = get_app_id(users, it->first); + int app_id = get_app_id(it->first); if (app_id == 0) { LOGI("denylist rm: [%s]\n", it->first.data()); ssprintf(sql, sizeof(sql), "DELETE FROM denylist WHERE package_name='%s'", diff --git a/native/src/core/lib.rs b/native/src/core/lib.rs index 0c44e4830..2b27f1562 100644 --- a/native/src/core/lib.rs +++ b/native/src/core/lib.rs @@ -224,6 +224,7 @@ pub mod ffi { fn get_db_setting(&self, key: DbEntryKey) -> i32; #[cxx_name = "set_db_setting"] fn set_db_setting_for_cxx(&self, key: DbEntryKey, value: i32) -> bool; + fn get_app_id(&self, pkg: &str) -> i32; #[Self = MagiskD] #[cxx_name = "Get"] diff --git a/native/src/core/package.rs b/native/src/core/package.rs index 2c929d6c0..94fea3ae4 100644 --- a/native/src/core/package.rs +++ b/native/src/core/package.rs @@ -3,6 +3,7 @@ use crate::daemon::{AID_APP_END, AID_APP_START, MagiskD, to_app_id}; #[cfg(all(feature = "check-signature", not(debug_assertions)))] use crate::ffi::uninstall_pkg; use base::WalkResult::{Abort, Continue, Skip}; +use base::const_format::concatcp; use base::{ BufReadExt, Directory, FsPathBuilder, LoggedResult, ReadExt, ResultExt, Utf8CStrBuf, Utf8CString, cstr, error, pre_order_walk, @@ -47,7 +48,7 @@ macro_rules! bad_apk { * This method extracts the first certificate of the first signer * within the APK v2 signature block. */ -fn read_certificate(apk: &mut File, version: i32) -> Vec { +fn read_certificate(apk: &mut File) -> Vec { let res = || -> io::Result> { let mut u32_val = 0u32; let mut u64_val = 0u64; @@ -78,24 +79,22 @@ fn read_certificate(apk: &mut File, version: i32) -> Vec { apk.read_pod(&mut central_dir_off)?; // Code for parse APK comment to get version code - if version >= 0 { - let mut comment_sz = 0u16; - apk.read_pod(&mut comment_sz)?; - let mut comment = vec![0u8; comment_sz as usize]; - apk.read_exact(&mut comment)?; - let mut comment = Cursor::new(&comment); - let mut apk_ver = 0; - comment.for_each_prop(|k, v| { - if k == "versionCode" { - apk_ver = v.parse::().unwrap_or(0); - false - } else { - true - } - }); - if version > apk_ver { - Err(bad_apk!("APK version too low"))?; + let mut comment_sz = 0u16; + apk.read_pod(&mut comment_sz)?; + let mut comment = vec![0u8; comment_sz as usize]; + apk.read_exact(&mut comment)?; + let mut comment = Cursor::new(&comment); + let mut apk_ver = 0; + comment.for_each_prop(|k, v| { + if k == "versionCode" { + apk_ver = v.parse::().unwrap_or(0); + false + } else { + true } + }); + if MAGISK_VER_CODE > apk_ver { + Err(bad_apk!("APK version too low"))?; } // Next, find the start of the APK signing block @@ -154,15 +153,13 @@ fn find_apk_path() -> Option { if !e.is_dir() { return Ok(Skip); } - let name_bytes = e.name().as_bytes(); - if name_bytes.starts_with(APP_PACKAGE_NAME.as_bytes()) - && name_bytes.get(APP_PACKAGE_NAME.len()) == Some(&b'-') - { + let name = e.name(); + if name.starts_with(concatcp!(APP_PACKAGE_NAME, "-")) { // Found the APK path, we can abort now buf.append_path(path).append_path("base.apk"); return Ok(Abort); } - if name_bytes.starts_with(b"~~") { + if name.starts_with("~~") { return Ok(Continue); } Ok(Skip) @@ -171,30 +168,18 @@ fn find_apk_path() -> Option { if buf.is_empty() { None } else { Some(buf) } } -fn get_package_uid(user: i32) -> i32 { +fn get_package_uid(user: i32, pkg: &str) -> i32 { let path = cstr::buf::default() .join_path(APP_DATA_DIR) .join_path_fmt(user) - .join_path(APP_PACKAGE_NAME); + .join_path(pkg); path.get_attr() .map(|attr| attr.st.st_uid as i32) .unwrap_or(-1) } -enum Status { - Installed, - NotInstalled, - #[cfg(all(feature = "check-signature", not(debug_assertions)))] - CertMismatch, -} - #[derive(Default)] -pub struct ManagerInfo { - tracked_file: TrackedFile, -} - -#[derive(Default)] -struct TrackedFile { +pub struct TrackedFile { path: Utf8CString, timestamp: Duration, } @@ -222,77 +207,49 @@ impl TrackedFile { } } -impl ManagerInfo { - fn check_orig(&mut self) -> Status { - let Some(apk) = find_apk_path() else { - return Status::NotInstalled; - }; +fn check_apk(tracked: &mut TrackedFile) -> bool { + let Some(apk) = find_apk_path() else { + return false; + }; - let cert = match apk.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) { - Ok(mut fd) => read_certificate(&mut fd, MAGISK_VER_CODE), - Err(_) => return Status::NotInstalled, - }; + let cert = match apk.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) { + Ok(mut fd) => read_certificate(&mut fd), + Err(_) => return false, + }; - if cert.is_empty() || (!TRUSTED_CERT.is_empty() && cert != TRUSTED_CERT) { - error!("pkg: APK signature mismatch: {}", apk); - #[cfg(all(feature = "check-signature", not(debug_assertions)))] - { - uninstall_pkg(cstr!(APP_PACKAGE_NAME)); - return Status::CertMismatch; - } + if cert.is_empty() || (!TRUSTED_CERT.is_empty() && cert != TRUSTED_CERT) { + error!("pkg: APK signature mismatch: {}", apk); + #[cfg(all(feature = "check-signature", not(debug_assertions)))] + { + uninstall_pkg(cstr!(APP_PACKAGE_NAME)); + return false; } - - self.tracked_file = TrackedFile::new(apk); - Status::Installed } - fn get_manager(&mut self, user: i32) -> (i32, &str) { - if self.tracked_file.is_same() { - // no APK - if &self.tracked_file.path == PACKAGES_XML { - return (-1, ""); - } - // orig APK is still the same - let uid = get_package_uid(user); - return if uid < 0 { - (-1, "") - } else { - (uid, APP_PACKAGE_NAME) - }; - } - - match self.check_orig() { - Status::Installed => { - let uid = get_package_uid(user); - return if uid < 0 { - (-1, "") - } else { - (uid, APP_PACKAGE_NAME) - }; - } - #[cfg(all(feature = "check-signature", not(debug_assertions)))] - Status::CertMismatch => {} - Status::NotInstalled => {} - } - - // If we cannot find any manager, track packages.xml for new package installs - self.tracked_file = TrackedFile::new(PACKAGES_XML.into()); - - (-1, "") - } + *tracked = TrackedFile::new(apk); + true } impl MagiskD { pub fn get_manager_uid(&self, user: i32) -> i32 { - let mut info = self.manager_info.lock(); - let (uid, _) = info.get_manager(user); - uid - } + let mut tracked = self.manager_info.lock(); + if tracked.is_same() { + return if &tracked.path == PACKAGES_XML { + // no APK + -1 + } else { + // APK is still the same + get_package_uid(user, APP_PACKAGE_NAME) + }; + } - pub fn get_manager(&self, user: i32) -> (i32, String) { - let mut info = self.manager_info.lock(); - let (uid, pkg) = info.get_manager(user); - (uid, pkg.to_string()) + if check_apk(&mut tracked) { + return get_package_uid(user, APP_PACKAGE_NAME); + } + + // If we cannot find any manager, track packages.xml for new package installs + *tracked = TrackedFile::new(PACKAGES_XML.into()); + -1 } // app_id = app_no + AID_APP_START @@ -351,5 +308,15 @@ impl MagiskD { users.dedup(); users } + + pub fn get_app_id(&self, pkg: &str) -> i32 { + for user in self.get_users() { + let uid = get_package_uid(user, pkg); + if uid >= 0 { + return to_app_id(uid); + } + } + 0 + } } diff --git a/native/src/core/su/connect.rs b/native/src/core/su/connect.rs index 94f832cbb..0ccd3fc7b 100644 --- a/native/src/core/su/connect.rs +++ b/native/src/core/su/connect.rs @@ -1,7 +1,9 @@ use super::SuInfo; +use crate::consts::APP_PACKAGE_NAME; use crate::daemon::{AID_APP_START, MagiskD, to_app_id, to_user_id}; use crate::ffi::{SuRequest, fork_dont_care}; use ExtraVal::{Bool, Int, IntList, Str}; +use base::const_format::concatcp; use base::{BytesExt, error}; use nix::sys::signal::SigSet; use num_traits::AsPrimitive; @@ -70,15 +72,14 @@ impl Extra<'_> { } impl MagiskD { - fn exec_cmd(&self, user: &str, mgr_pkg: &str, action: &'static str, extras: &[Extra]) { - let provider = format!("content://{mgr_pkg}.provider"); + fn exec_cmd(&self, user: &str, action: &'static str, extras: &[Extra]) { let mut cmd = app_process(); cmd.args([ "/system/bin", "com.android.commands.content.Content", "call", "--uri", - &provider, + concatcp!("content://", APP_PACKAGE_NAME, ".provider"), "--user", user, "--method", @@ -169,14 +170,10 @@ impl MagiskD { user_id = to_user_id(info.eval_uid).to_string(); &user_id }; - self.exec_cmd(user, &info.mgr_pkg, "notify", &extras); + self.exec_cmd(user, "notify", &extras); } pub(super) fn notify_app(&self, cred: &UCred, info: &SuInfo, request: &SuRequest) { - if info.mgr_pkg.is_empty() { - return; - } - if !info.settings.log && !info.settings.notify { return; } diff --git a/native/src/core/su/daemon.rs b/native/src/core/su/daemon.rs index 1f30c0c18..7e9d85930 100644 --- a/native/src/core/su/daemon.rs +++ b/native/src/core/su/daemon.rs @@ -30,7 +30,6 @@ impl Default for SuRequest { pub struct SuInfo { pub(super) uid: i32, pub(super) eval_uid: i32, - pub(super) mgr_pkg: String, pub(super) settings: RootSettings, cfg: DbSettings, timestamp: Instant, @@ -41,7 +40,6 @@ impl Default for SuInfo { SuInfo { uid: -1, eval_uid: -1, - mgr_pkg: Default::default(), settings: Default::default(), cfg: Default::default(), timestamp: Instant::now(), @@ -193,20 +191,21 @@ impl MagiskD { let mut settings = RootSettings::default(); self.get_root_settings(eval_uid, &mut settings)?; - let (mut mgr_uid, mut mgr_pkg) = self.get_manager(to_user_id(eval_uid)); - if mgr_pkg.is_empty() && to_app_id(eval_uid) < AID_APP_START { + let mut mgr_uid = self.get_manager_uid(to_user_id(eval_uid)); + if mgr_uid < 0 && to_app_id(eval_uid) < AID_APP_START { for user in self.get_users() { - let (id, pkg) = self.get_manager(user); - if !pkg.is_empty() { - mgr_uid = id; - mgr_pkg = pkg; + mgr_uid = self.get_manager_uid(user); + if mgr_uid >= 0 { break; } } } - // If it's the manager, allow it silently - if to_app_id(uid) == to_app_id(mgr_uid) { + if mgr_uid < 0 { + settings.log = false; + settings.notify = false; + } else if to_app_id(uid) == to_app_id(mgr_uid) { + // If it's the manager, allow it silently return Ok(Arc::new(SuInfo::allow(uid))); } @@ -214,7 +213,6 @@ impl MagiskD { Ok(Arc::new(SuInfo { uid, eval_uid, - mgr_pkg, settings, cfg, timestamp: Instant::now(),