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
This commit is contained in:
topjohnwu
2026-10-22 14:06:48 -07:00
committed by John Wu
parent e8e8c3e3f1
commit a51dc10f88
6 changed files with 85 additions and 162 deletions
+2 -2
View File
@@ -10,7 +10,7 @@ use crate::ffi::{
}; };
use crate::logging::{android_logging, magisk_logging, setup_logfile, start_log_daemon}; use crate::logging::{android_logging, magisk_logging, setup_logfile, start_log_daemon};
use crate::module::remove_modules; use crate::module::remove_modules;
use crate::package::ManagerInfo; use crate::package::TrackedFile;
use crate::resetprop::{get_prop, set_prop}; use crate::resetprop::{get_prop, set_prop};
use crate::selinux::restore_tmpcon; use crate::selinux::restore_tmpcon;
use crate::socket::{IpcRead, IpcWrite}; use crate::socket::{IpcRead, IpcWrite};
@@ -56,7 +56,7 @@ pub const fn to_user_id(uid: i32) -> i32 {
#[derive(Default)] #[derive(Default)]
pub struct MagiskD { pub struct MagiskD {
pub sql_connection: Mutex<Option<Sqlite3>>, pub sql_connection: Mutex<Option<Sqlite3>>,
pub manager_info: Mutex<ManagerInfo>, pub manager_info: Mutex<TrackedFile>,
pub boot_stage_lock: Mutex<BootState>, pub boot_stage_lock: Mutex<BootState>,
pub module_list: OnceLock<Vec<ModuleInfo>>, pub module_list: OnceLock<Vec<ModuleInfo>>,
pub zygisk_enabled: AtomicBool, pub zygisk_enabled: AtomicBool,
+2 -42
View File
@@ -1,13 +1,10 @@
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <unistd.h> #include <unistd.h>
#include <fcntl.h> #include <fcntl.h>
#include <dirent.h> #include <dirent.h>
#include <set> #include <set>
#include <map> #include <map>
#include <consts.hpp>
#include <sqlite.hpp> #include <sqlite.hpp>
#include <core.hpp> #include <core.hpp>
@@ -32,38 +29,12 @@ static pthread_mutex_t data_lock = PTHREAD_MUTEX_INITIALIZER;
atomic<bool> denylist_enforced = false; atomic<bool> denylist_enforced = false;
static int get_app_id(const vector<int> &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<int> &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) { static int get_app_id(const string &pkg) {
if (pkg == ISOLATED_MAGIC) if (pkg == ISOLATED_MAGIC)
return -1; return -1;
if (pkg == WEBVIEW_ZYGOTE_MAGIC) if (pkg == WEBVIEW_ZYGOTE_MAGIC)
return WEBVIEW_ZYGOTE_UID; return WEBVIEW_ZYGOTE_UID;
vector<int> users; return MagiskD::Get().get_app_id(pkg);
collect_users(users);
return get_app_id(users, pkg);
} }
static void update_app_id(int app_id, const string &pkg, bool remove) { 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(); app_id_to_pkgs.clear();
char sql[4096]; char sql[4096];
vector<int> users;
collect_users(users);
for (auto it = pkg_to_procs.begin(); it != pkg_to_procs.end();) { for (auto it = pkg_to_procs.begin(); it != pkg_to_procs.end();) {
if (it->first == ISOLATED_MAGIC) { int app_id = get_app_id(it->first);
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);
if (app_id == 0) { if (app_id == 0) {
LOGI("denylist rm: [%s]\n", it->first.data()); LOGI("denylist rm: [%s]\n", it->first.data());
ssprintf(sql, sizeof(sql), "DELETE FROM denylist WHERE package_name='%s'", ssprintf(sql, sizeof(sql), "DELETE FROM denylist WHERE package_name='%s'",
+1
View File
@@ -224,6 +224,7 @@ pub mod ffi {
fn get_db_setting(&self, key: DbEntryKey) -> i32; fn get_db_setting(&self, key: DbEntryKey) -> i32;
#[cxx_name = "set_db_setting"] #[cxx_name = "set_db_setting"]
fn set_db_setting_for_cxx(&self, key: DbEntryKey, value: i32) -> bool; fn set_db_setting_for_cxx(&self, key: DbEntryKey, value: i32) -> bool;
fn get_app_id(&self, pkg: &str) -> i32;
#[Self = MagiskD] #[Self = MagiskD]
#[cxx_name = "Get"] #[cxx_name = "Get"]
+66 -99
View File
@@ -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)))] #[cfg(all(feature = "check-signature", not(debug_assertions)))]
use crate::ffi::uninstall_pkg; use crate::ffi::uninstall_pkg;
use base::WalkResult::{Abort, Continue, Skip}; use base::WalkResult::{Abort, Continue, Skip};
use base::const_format::concatcp;
use base::{ use base::{
BufReadExt, Directory, FsPathBuilder, LoggedResult, ReadExt, ResultExt, Utf8CStrBuf, BufReadExt, Directory, FsPathBuilder, LoggedResult, ReadExt, ResultExt, Utf8CStrBuf,
Utf8CString, cstr, error, pre_order_walk, Utf8CString, cstr, error, pre_order_walk,
@@ -47,7 +48,7 @@ macro_rules! bad_apk {
* This method extracts the first certificate of the first signer * This method extracts the first certificate of the first signer
* 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) -> Vec<u8> {
let res = || -> io::Result<Vec<u8>> { 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;
@@ -78,24 +79,22 @@ fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {
apk.read_pod(&mut central_dir_off)?; apk.read_pod(&mut central_dir_off)?;
// Code for parse APK comment to get version code // Code for parse APK comment to get version code
if version >= 0 { let mut comment_sz = 0u16;
let mut comment_sz = 0u16; apk.read_pod(&mut comment_sz)?;
apk.read_pod(&mut comment_sz)?; let mut comment = vec![0u8; comment_sz as usize];
let mut comment = vec![0u8; comment_sz as usize]; apk.read_exact(&mut comment)?;
apk.read_exact(&mut comment)?; let mut comment = Cursor::new(&comment);
let mut comment = Cursor::new(&comment); let mut apk_ver = 0;
let mut apk_ver = 0; comment.for_each_prop(|k, v| {
comment.for_each_prop(|k, v| { if k == "versionCode" {
if k == "versionCode" { apk_ver = v.parse::<i32>().unwrap_or(0);
apk_ver = v.parse::<i32>().unwrap_or(0); false
false } else {
} else { true
true
}
});
if version > apk_ver {
Err(bad_apk!("APK version too low"))?;
} }
});
if MAGISK_VER_CODE > apk_ver {
Err(bad_apk!("APK version too low"))?;
} }
// Next, find the start of the APK signing block // Next, find the start of the APK signing block
@@ -154,15 +153,13 @@ fn find_apk_path() -> Option<Utf8CString> {
if !e.is_dir() { if !e.is_dir() {
return Ok(Skip); return Ok(Skip);
} }
let name_bytes = e.name().as_bytes(); let name = e.name();
if name_bytes.starts_with(APP_PACKAGE_NAME.as_bytes()) if name.starts_with(concatcp!(APP_PACKAGE_NAME, "-")) {
&& name_bytes.get(APP_PACKAGE_NAME.len()) == Some(&b'-')
{
// Found the APK path, we can abort now // Found the APK path, we can abort now
buf.append_path(path).append_path("base.apk"); buf.append_path(path).append_path("base.apk");
return Ok(Abort); return Ok(Abort);
} }
if name_bytes.starts_with(b"~~") { if name.starts_with("~~") {
return Ok(Continue); return Ok(Continue);
} }
Ok(Skip) Ok(Skip)
@@ -171,30 +168,18 @@ fn find_apk_path() -> Option<Utf8CString> {
if buf.is_empty() { None } else { Some(buf) } 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() let path = cstr::buf::default()
.join_path(APP_DATA_DIR) .join_path(APP_DATA_DIR)
.join_path_fmt(user) .join_path_fmt(user)
.join_path(APP_PACKAGE_NAME); .join_path(pkg);
path.get_attr() path.get_attr()
.map(|attr| attr.st.st_uid as i32) .map(|attr| attr.st.st_uid as i32)
.unwrap_or(-1) .unwrap_or(-1)
} }
enum Status {
Installed,
NotInstalled,
#[cfg(all(feature = "check-signature", not(debug_assertions)))]
CertMismatch,
}
#[derive(Default)] #[derive(Default)]
pub struct ManagerInfo { pub struct TrackedFile {
tracked_file: TrackedFile,
}
#[derive(Default)]
struct TrackedFile {
path: Utf8CString, path: Utf8CString,
timestamp: Duration, timestamp: Duration,
} }
@@ -222,77 +207,49 @@ impl TrackedFile {
} }
} }
impl ManagerInfo { fn check_apk(tracked: &mut TrackedFile) -> bool {
fn check_orig(&mut self) -> Status { let Some(apk) = find_apk_path() else {
let Some(apk) = find_apk_path() else { return false;
return Status::NotInstalled; };
};
let cert = match apk.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) { let cert = match apk.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) {
Ok(mut fd) => read_certificate(&mut fd, MAGISK_VER_CODE), Ok(mut fd) => read_certificate(&mut fd),
Err(_) => return Status::NotInstalled, Err(_) => return false,
}; };
if cert.is_empty() || (!TRUSTED_CERT.is_empty() && cert != TRUSTED_CERT) { if cert.is_empty() || (!TRUSTED_CERT.is_empty() && cert != TRUSTED_CERT) {
error!("pkg: APK signature mismatch: {}", apk); error!("pkg: APK signature mismatch: {}", apk);
#[cfg(all(feature = "check-signature", not(debug_assertions)))] #[cfg(all(feature = "check-signature", not(debug_assertions)))]
{ {
uninstall_pkg(cstr!(APP_PACKAGE_NAME)); uninstall_pkg(cstr!(APP_PACKAGE_NAME));
return Status::CertMismatch; return false;
}
} }
self.tracked_file = TrackedFile::new(apk);
Status::Installed
} }
fn get_manager(&mut self, user: i32) -> (i32, &str) { *tracked = TrackedFile::new(apk);
if self.tracked_file.is_same() { true
// 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, "")
}
} }
impl MagiskD { impl MagiskD {
pub fn get_manager_uid(&self, user: i32) -> i32 { pub fn get_manager_uid(&self, user: i32) -> i32 {
let mut info = self.manager_info.lock(); let mut tracked = self.manager_info.lock();
let (uid, _) = info.get_manager(user); if tracked.is_same() {
uid 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) { if check_apk(&mut tracked) {
let mut info = self.manager_info.lock(); return get_package_uid(user, APP_PACKAGE_NAME);
let (uid, pkg) = info.get_manager(user); }
(uid, pkg.to_string())
// 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 // app_id = app_no + AID_APP_START
@@ -351,5 +308,15 @@ impl MagiskD {
users.dedup(); users.dedup();
users 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
}
} }
+5 -8
View File
@@ -1,7 +1,9 @@
use super::SuInfo; use super::SuInfo;
use crate::consts::APP_PACKAGE_NAME;
use crate::daemon::{AID_APP_START, MagiskD, to_app_id, to_user_id}; use crate::daemon::{AID_APP_START, MagiskD, to_app_id, to_user_id};
use crate::ffi::{SuRequest, fork_dont_care}; use crate::ffi::{SuRequest, fork_dont_care};
use ExtraVal::{Bool, Int, IntList, Str}; use ExtraVal::{Bool, Int, IntList, Str};
use base::const_format::concatcp;
use base::{BytesExt, error}; use base::{BytesExt, error};
use nix::sys::signal::SigSet; use nix::sys::signal::SigSet;
use num_traits::AsPrimitive; use num_traits::AsPrimitive;
@@ -70,15 +72,14 @@ impl Extra<'_> {
} }
impl MagiskD { impl MagiskD {
fn exec_cmd(&self, user: &str, mgr_pkg: &str, action: &'static str, extras: &[Extra]) { fn exec_cmd(&self, user: &str, action: &'static str, extras: &[Extra]) {
let provider = format!("content://{mgr_pkg}.provider");
let mut cmd = app_process(); let mut cmd = app_process();
cmd.args([ cmd.args([
"/system/bin", "/system/bin",
"com.android.commands.content.Content", "com.android.commands.content.Content",
"call", "call",
"--uri", "--uri",
&provider, concatcp!("content://", APP_PACKAGE_NAME, ".provider"),
"--user", "--user",
user, user,
"--method", "--method",
@@ -169,14 +170,10 @@ impl MagiskD {
user_id = to_user_id(info.eval_uid).to_string(); user_id = to_user_id(info.eval_uid).to_string();
&user_id &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) { 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 { if !info.settings.log && !info.settings.notify {
return; return;
} }
+9 -11
View File
@@ -30,7 +30,6 @@ impl Default for SuRequest {
pub struct SuInfo { pub struct SuInfo {
pub(super) uid: i32, pub(super) uid: i32,
pub(super) eval_uid: i32, pub(super) eval_uid: i32,
pub(super) mgr_pkg: String,
pub(super) settings: RootSettings, pub(super) settings: RootSettings,
cfg: DbSettings, cfg: DbSettings,
timestamp: Instant, timestamp: Instant,
@@ -41,7 +40,6 @@ impl Default for SuInfo {
SuInfo { SuInfo {
uid: -1, uid: -1,
eval_uid: -1, eval_uid: -1,
mgr_pkg: Default::default(),
settings: Default::default(), settings: Default::default(),
cfg: Default::default(), cfg: Default::default(),
timestamp: Instant::now(), timestamp: Instant::now(),
@@ -193,20 +191,21 @@ impl MagiskD {
let mut settings = RootSettings::default(); let mut settings = RootSettings::default();
self.get_root_settings(eval_uid, &mut settings)?; self.get_root_settings(eval_uid, &mut settings)?;
let (mut mgr_uid, mut mgr_pkg) = self.get_manager(to_user_id(eval_uid)); let mut mgr_uid = self.get_manager_uid(to_user_id(eval_uid));
if mgr_pkg.is_empty() && to_app_id(eval_uid) < AID_APP_START { if mgr_uid < 0 && to_app_id(eval_uid) < AID_APP_START {
for user in self.get_users() { for user in self.get_users() {
let (id, pkg) = self.get_manager(user); mgr_uid = self.get_manager_uid(user);
if !pkg.is_empty() { if mgr_uid >= 0 {
mgr_uid = id;
mgr_pkg = pkg;
break; break;
} }
} }
} }
// If it's the manager, allow it silently if mgr_uid < 0 {
if to_app_id(uid) == to_app_id(mgr_uid) { 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))); return Ok(Arc::new(SuInfo::allow(uid)));
} }
@@ -214,7 +213,6 @@ impl MagiskD {
Ok(Arc::new(SuInfo { Ok(Arc::new(SuInfo {
uid, uid,
eval_uid, eval_uid,
mgr_pkg,
settings, settings,
cfg, cfg,
timestamp: Instant::now(), timestamp: Instant::now(),