base: eliminate /proc/self/fd path resolution

Remove reliance on /proc/self/fd symlink resolution across base and core
components:
- Add top-level pre_order_walk and post_order_walk that track entry
  paths via an internal buffer, and unify Directory walk methods to
  support path-tracking and pathless traversals without extra overhead.
- Add DirEntry::get_stat using fstatat(AT_SYMLINK_NOFOLLOW) directly on
  directory file descriptors.
- Update Directory::copy_into and link_into to operate directly on file
  descriptors with fd_get_attr/fd_set_attr, passing paths only for
  symlink attribute updates.
- Refactor find_apk_path and restore_tmpcon to use pre_order_walk, and
  update get_app_no_list to use DirEntry::get_stat.
- Remove DirEntry::resolve_path, Directory::path_at,
  Directory::resolve_path, and fd_path.
- Replace remaining consumers of xrealpath and canonical_path (in su
  and magiskinit) with standard realpath or partition matching, allowing
  removal of Utf8CStr::realpath and its C FFI exports.

Assisted-by: Gemini 3.8 Flash
This commit is contained in:
topjohnwu
2026-10-02 17:17:48 -07:00
parent 0e228db61f
commit 8348d6e39c
9 changed files with 131 additions and 151 deletions
-15
View File
@@ -17,21 +17,6 @@ use cfg_if::cfg_if;
use libc::{c_char, mode_t};
use nix::fcntl::OFlag;
#[unsafe(no_mangle)]
unsafe extern "C" fn canonical_path(path: *const c_char, buf: *mut u8, bufsz: usize) -> isize {
unsafe {
match Utf8CStr::from_ptr(path) {
Ok(path) => {
let mut buf = cstr::buf::wrap_ptr(buf, bufsz);
path.realpath(&mut buf)
.log()
.map_or(-1_isize, |_| buf.len() as isize)
}
Err(_) => -1,
}
}
}
#[unsafe(export_name = "mkdirs")]
unsafe extern "C" fn mkdirs_for_cxx(path: *const c_char, mode: mode_t) -> i32 {
unsafe {
+105 -49
View File
@@ -1,7 +1,7 @@
use crate::cxx_extern::readlinkat;
use crate::{
FsPathBuilder, LibcReturn, LoggedResult, OsError, OsResult, Utf8CStr, Utf8CStrBuf, cstr,
fd_path, fd_set_attr,
fd_get_attr, fd_set_attr,
};
use libc::{dirent, mode_t};
use nix::errno::Errno;
@@ -35,8 +35,9 @@ impl DirEntry<'_> {
}
}
pub fn resolve_path(&self, buf: &mut dyn Utf8CStrBuf) -> OsResult<'static, ()> {
self.dir.path_at(self.name(), buf)
pub fn get_stat(&self) -> OsResult<'_, libc::stat> {
nix::sys::stat::fstatat(self.dir, self.name(), AtFlags::AT_SYMLINK_NOFOLLOW)
.into_os_result("fstatat", Some(self.name()), None)
}
pub fn is_dir(&self) -> bool {
@@ -142,12 +143,6 @@ impl Directory {
)
.into_os_result("openat", Some(name), None)
}
fn path_at(&self, name: &Utf8CStr, buf: &mut dyn Utf8CStrBuf) -> OsResult<'static, ()> {
self.resolve_path(buf)?;
buf.append_path(name);
Ok(())
}
}
// Low-level methods, we should track the caller when error occurs, so return OsResult.
@@ -258,10 +253,6 @@ impl Directory {
nix::sys::stat::fstatat(self, path, AtFlags::AT_SYMLINK_NOFOLLOW).is_ok()
}
pub fn resolve_path(&self, buf: &mut dyn Utf8CStrBuf) -> OsResult<'static, ()> {
fd_path(self.as_raw_fd(), buf)
}
pub fn rename_at<'a>(
&self,
old: &'a Utf8CStr,
@@ -272,6 +263,38 @@ impl Directory {
}
}
pub fn post_order_walk<F: FnMut(&DirEntry, &Utf8CStr) -> LoggedResult<WalkResult>>(
path: &Utf8CStr,
mut f: F,
) -> LoggedResult<WalkResult> {
let mut dir = Directory::open(path)?;
let mut buf = cstr::buf::default();
buf.append_path(path);
while buf.ends_with('/') && buf.len() > 1 {
buf.truncate(buf.len() - 1);
}
dir.post_order_walk_impl(Some(&mut buf), &mut |e, p| match p {
Some(p) => f(e, p),
None => unreachable!(),
})
}
pub fn pre_order_walk<F: FnMut(&DirEntry, &Utf8CStr) -> LoggedResult<WalkResult>>(
path: &Utf8CStr,
mut f: F,
) -> LoggedResult<WalkResult> {
let mut dir = Directory::open(path)?;
let mut buf = cstr::buf::default();
buf.append_path(path);
while buf.ends_with('/') && buf.len() > 1 {
buf.truncate(buf.len() - 1);
}
dir.pre_order_walk_impl(Some(&mut buf), &mut |e, p| match p {
Some(p) => f(e, p),
None => unreachable!(),
})
}
// High-level helper methods, composed of multiple operations.
// We should treat these as application logic and log ASAP, so return LoggedResult.
impl Directory {
@@ -279,14 +302,14 @@ impl Directory {
&mut self,
mut f: F,
) -> LoggedResult<WalkResult> {
self.post_order_walk_impl(&mut f)
self.post_order_walk_impl(None, &mut |e, _| f(e))
}
pub fn pre_order_walk<F: FnMut(&DirEntry) -> LoggedResult<WalkResult>>(
&mut self,
mut f: F,
) -> LoggedResult<WalkResult> {
self.pre_order_walk_impl(&mut f)
self.pre_order_walk_impl(None, &mut |e, _| f(e))
}
pub fn remove_all(mut self) -> LoggedResult<()> {
@@ -297,9 +320,17 @@ impl Directory {
Ok(())
}
pub fn copy_into(&mut self, dir: &Directory) -> LoggedResult<()> {
let mut buf = cstr::buf::default();
self.copy_into_impl(dir, &mut buf)
pub fn copy_into(
&mut self,
dir: &Directory,
src_path: &Utf8CStr,
dest_path: &Utf8CStr,
) -> LoggedResult<()> {
let mut src_buf = cstr::buf::default();
let mut dest_buf = cstr::buf::default();
src_buf.push_str(src_path.as_str());
dest_buf.push_str(dest_path.as_str());
self.copy_into_impl(dir, &mut src_buf, &mut dest_buf)
}
pub fn move_into(&mut self, dir: &Directory) -> LoggedResult<()> {
@@ -317,28 +348,39 @@ impl Directory {
}
pub fn link_into(&mut self, dir: &Directory) -> LoggedResult<()> {
let mut buf = cstr::buf::default();
self.link_into_impl(dir, &mut buf)
self.link_into_impl(dir)
}
}
impl Directory {
fn post_order_walk_impl<F: FnMut(&DirEntry) -> LoggedResult<WalkResult>>(
fn post_order_walk_impl<F: FnMut(&DirEntry, Option<&Utf8CStr>) -> LoggedResult<WalkResult>>(
&mut self,
mut path: Option<&mut dyn Utf8CStrBuf>,
f: &mut F,
) -> LoggedResult<WalkResult> {
use WalkResult::*;
let base_len = path.as_ref().map(|b| b.len()).unwrap_or(0);
loop {
match self.read()? {
None => return Ok(Continue),
Some(ref e) => {
if let Some(buf) = path.as_mut() {
buf.truncate(base_len);
buf.append_path(e.name());
}
if e.is_dir() {
let mut dir = e.open_as_dir()?;
if let Abort = dir.post_order_walk_impl(f)? {
let sub_path = path.as_mut().map(|b| &mut **b as &mut dyn Utf8CStrBuf);
if let Abort = dir.post_order_walk_impl(sub_path, f)? {
return Ok(Abort);
}
if let Some(buf) = path.as_mut() {
buf.truncate(base_len);
buf.append_path(e.name());
}
}
match f(e)? {
let entry_path = path.as_ref().map(|b| b.as_ref());
match f(e, entry_path)? {
Abort => return Ok(Abort),
Skip => return Ok(Continue),
Continue => {}
@@ -348,26 +390,37 @@ impl Directory {
}
}
fn pre_order_walk_impl<F: FnMut(&DirEntry) -> LoggedResult<WalkResult>>(
fn pre_order_walk_impl<F: FnMut(&DirEntry, Option<&Utf8CStr>) -> LoggedResult<WalkResult>>(
&mut self,
mut path: Option<&mut dyn Utf8CStrBuf>,
f: &mut F,
) -> LoggedResult<WalkResult> {
use WalkResult::*;
let base_len = path.as_ref().map(|b| b.len()).unwrap_or(0);
loop {
match self.read()? {
None => return Ok(Continue),
Some(ref e) => match f(e)? {
Abort => return Ok(Abort),
Skip => continue,
Continue => {
if e.is_dir() {
let mut dir = e.open_as_dir()?;
if let Abort = dir.pre_order_walk_impl(f)? {
return Ok(Abort);
Some(ref e) => {
if let Some(buf) = path.as_mut() {
buf.truncate(base_len);
buf.append_path(e.name());
}
let entry_path = path.as_ref().map(|b| b.as_ref());
match f(e, entry_path)? {
Abort => return Ok(Abort),
Skip => continue,
Continue => {
if e.is_dir() {
let mut dir = e.open_as_dir()?;
let sub_path =
path.as_mut().map(|b| &mut **b as &mut dyn Utf8CStrBuf);
if let Abort = dir.pre_order_walk_impl(sub_path, f)? {
return Ok(Abort);
}
}
}
}
},
}
}
}
}
@@ -375,16 +428,22 @@ impl Directory {
fn copy_into_impl(
&mut self,
dest_dir: &Directory,
buf: &mut dyn Utf8CStrBuf,
src_buf: &mut dyn Utf8CStrBuf,
dest_buf: &mut dyn Utf8CStrBuf,
) -> LoggedResult<()> {
let src_len = src_buf.len();
let dest_len = dest_buf.len();
while let Some(ref e) = self.read()? {
e.resolve_path(buf)?;
let attr = buf.get_attr()?;
src_buf.truncate(src_len);
dest_buf.truncate(dest_len);
src_buf.append_path(e.name());
dest_buf.append_path(e.name());
if e.is_dir() {
dest_dir.mkdir_at(e.name(), 0o777)?;
let mut src = e.open_as_dir()?;
let dest = dest_dir.open_as_dir_at(e.name())?;
src.copy_into_impl(&dest, buf)?;
let attr = fd_get_attr(src.as_raw_fd())?;
src.copy_into_impl(&dest, src_buf, dest_buf)?;
fd_set_attr(dest.as_raw_fd(), &attr)?;
} else if e.is_file() {
let mut src = e.open_as_file(OFlag::O_RDONLY)?;
@@ -393,31 +452,28 @@ impl Directory {
OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_TRUNC,
0o777,
)?;
let attr = fd_get_attr(src.as_raw_fd())?;
std::io::copy(&mut src, &mut dest)?;
fd_set_attr(dest.as_raw_fd(), &attr)?;
} else if e.is_symlink() {
e.read_link(buf)?;
dest_dir.create_symlink_at(e.name(), buf)?;
dest_dir.path_at(e.name(), buf)?;
buf.set_attr(&attr)?;
let attr = src_buf.get_attr()?;
let mut link_buf = cstr::buf::default();
e.read_link(&mut link_buf)?;
dest_dir.create_symlink_at(e.name(), &link_buf)?;
dest_buf.set_attr(&attr)?;
}
}
Ok(())
}
fn link_into_impl(
&mut self,
dest_dir: &Directory,
buf: &mut dyn Utf8CStrBuf,
) -> LoggedResult<()> {
fn link_into_impl(&mut self, dest_dir: &Directory) -> LoggedResult<()> {
while let Some(ref e) = self.read()? {
if e.is_dir() {
dest_dir.mkdir_at(e.name(), 0o777)?;
e.resolve_path(buf)?;
let attr = buf.get_attr()?;
let mut src = e.open_as_dir()?;
let attr = fd_get_attr(src.as_raw_fd())?;
let dest = dest_dir.open_as_dir_at(e.name())?;
src.link_into_impl(&dest, buf)?;
src.link_into_impl(&dest)?;
fd_set_attr(dest.as_raw_fd(), &attr)?;
} else {
nix::unistd::linkat(e.dir, e.name(), dest_dir, e.name(), AtFlags::empty())
+1 -31
View File
@@ -148,13 +148,6 @@ fn open_fd(path: &Utf8CStr, flags: OFlag, mode: mode_t) -> OsResult<'_, OwnedFd>
)
}
pub fn fd_path(fd: RawFd, buf: &mut dyn Utf8CStrBuf) -> OsResult<'static, ()> {
let path = cstr::buf::new::<64>()
.join_path("/proc/self/fd")
.join_path_fmt(fd);
path.read_link(buf).map_err(|e| e.set_args(None, None))
}
pub struct FileAttr {
pub st: libc::stat,
#[cfg(feature = "selinux")]
@@ -266,29 +259,6 @@ impl Utf8CStr {
}
}
// Inspired by https://android.googlesource.com/platform/bionic/+/master/libc/bionic/realpath.cpp
pub fn realpath(&self, buf: &mut dyn Utf8CStrBuf) -> OsResult<'_, ()> {
let fd = self.open(OFlag::O_PATH | OFlag::O_CLOEXEC)?;
let mut skip_check = false;
let st1 = match nix::sys::stat::fstat(&fd) {
Ok(st) => st,
Err(_) => {
// This will only fail on Linux < 3.6
skip_check = true;
unsafe { mem::zeroed() }
}
};
fd_path(fd.as_raw_fd(), buf)?;
let st2 = nix::sys::stat::stat(buf.as_cstr()).into_os_result("stat", Some(self), None)?;
if !skip_check && (st2.st_dev != st1.st_dev || st2.st_ino != st1.st_ino) {
return Err(OsError::new(Errno::ENOENT, "realpath", Some(self), None));
}
Ok(())
}
pub fn get_attr(&self) -> OsResult<'_, FileAttr> {
#[allow(unused_mut)]
let mut attr = FileAttr {
@@ -443,7 +413,7 @@ impl Utf8CStr {
path.mkdir(0o777)?;
let mut src = Directory::open(self)?;
let dest = Directory::open(path)?;
src.copy_into(&dest)?;
src.copy_into(&dest, self, path)?;
} else {
// It's OK if remove failed
path.remove().ok();
-2
View File
@@ -46,13 +46,11 @@ int xmkdir(const char *pathname, mode_t mode);
int xmkdirs(const char *pathname, mode_t mode);
ssize_t xsendfile(int out_fd, int in_fd, off_t *offset, size_t count);
pid_t xfork();
ssize_t xrealpath(const char * __restrict__ path, char * __restrict__ buf, size_t bufsiz);
int xmknod(const char * pathname, mode_t mode, dev_t dev);
// Utils
int mkdirs(const char *path, mode_t mode);
ssize_t canonical_path(const char * __restrict__ path, char * __restrict__ buf, size_t bufsiz);
bool rm_rf(const char *path);
bool cp_afc(const char *src, const char *dest);
bool mv_path(const char *src, const char *dest);
+1 -16
View File
@@ -1,7 +1,7 @@
// Functions in this file are only for exporting to C++, DO NOT USE IN RUST
use crate::cxx_extern::readlinkat;
use crate::{Directory, LibcReturn, ResultExt, Utf8CStr, cstr, slice_from_ptr, slice_from_ptr_mut};
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 std::ffi::CStr;
use std::fs::File;
@@ -20,21 +20,6 @@ fn ptr_to_str<'a>(ptr: *const c_char) -> Option<&'a str> {
}
}
#[unsafe(no_mangle)]
unsafe extern "C" fn xrealpath(path: *const c_char, buf: *mut u8, bufsz: usize) -> isize {
unsafe {
match Utf8CStr::from_ptr(path) {
Ok(path) => {
let mut buf = cstr::buf::wrap_ptr(buf, bufsz);
path.realpath(&mut buf)
.log()
.map_or(-1, |_| buf.len() as isize)
}
Err(_) => -1,
}
}
}
#[unsafe(no_mangle)]
unsafe extern "C" fn xreadlinkat(
dirfd: RawFd,
+12 -22
View File
@@ -4,7 +4,7 @@ use crate::ffi::{DbEntryKey, get_magisk_tmp, install_apk, uninstall_pkg};
use base::WalkResult::{Abort, Continue, Skip};
use base::{
BufReadExt, Directory, FsPathBuilder, LoggedResult, ReadExt, ResultExt, Utf8CStrBuf,
Utf8CString, cstr, error, fd_get_attr, warn,
Utf8CString, cstr, error, fd_get_attr, pre_order_walk, warn,
};
use bit_set::BitSet;
use nix::fcntl::OFlag;
@@ -150,15 +150,15 @@ fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {
}
fn find_apk_path(pkg: &str) -> LoggedResult<Utf8CString> {
let mut buf = cstr::buf::default();
Directory::open(cstr!("/data/app"))?.pre_order_walk(|e| {
let mut buf = Utf8CString::default();
pre_order_walk(cstr!("/data/app"), |e, path| {
if !e.is_dir() {
return Ok(Skip);
}
let name_bytes = e.name().as_bytes();
if name_bytes.starts_with(pkg.as_bytes()) && name_bytes[pkg.len()] == b'-' {
if name_bytes.starts_with(pkg.as_bytes()) && name_bytes.get(pkg.len()) == Some(&b'-') {
// Found the APK path, we can abort now
e.resolve_path(&mut buf)?;
buf.append_path(path).append_path("base.apk");
return Ok(Abort);
}
if name_bytes.starts_with(b"~~") {
@@ -166,10 +166,7 @@ fn find_apk_path(pkg: &str) -> LoggedResult<Utf8CString> {
}
Ok(Skip)
})?;
if !buf.is_empty() {
buf.push_str("/base.apk");
}
Ok(buf.to_owned())
Ok(buf)
}
enum Status {
@@ -492,19 +489,12 @@ impl MagiskD {
Ok(dir) => dir,
};
// For each package
loop {
match user_dir.read()? {
None => break,
Some(e) => {
let mut entry_path = cstr::buf::default();
e.resolve_path(&mut entry_path)?;
let attr = entry_path.get_attr()?;
let app_id = to_app_id(attr.st.st_uid as i32);
if (AID_APP_START..=AID_APP_END).contains(&app_id) {
let app_no = app_id - AID_APP_START;
list.insert(app_no as usize);
}
}
while let Some(e) = user_dir.read()? {
let st = e.get_stat()?;
let app_id = to_app_id(st.st_uid as i32);
if (AID_APP_START..=AID_APP_END).contains(&app_id) {
let app_no = app_id - AID_APP_START;
list.insert(app_no as usize);
}
}
}
+8 -7
View File
@@ -1,6 +1,9 @@
use crate::consts::{DATABIN, LOG_PIPE, MAGISK_LOG_CON, MAGISKDB, MODULEROOT, SECURE_DIR};
use crate::ffi::get_magisk_tmp;
use base::{Directory, FsPathBuilder, LoggedResult, ResultExt, Utf8CStr, Utf8CStrBuf, cstr, libc};
use base::{
Directory, FsPathBuilder, LoggedResult, ResultExt, Utf8CStr, Utf8CStrBuf, WalkResult, cstr,
libc, pre_order_walk,
};
use nix::fcntl::OFlag;
use std::io::Write;
@@ -80,16 +83,14 @@ pub(crate) fn restore_tmpcon() -> LoggedResult<()> {
unsafe { libc::chmod(tmp.as_ptr(), 0o711) };
}
let mut path = cstr::buf::default();
let mut dir = Directory::open(tmp)?;
while let Some(ref e) = dir.read()? {
pre_order_walk(tmp, |e, path| {
if !e.is_symlink() {
e.resolve_path(&mut path)?;
path.set_secontext(SYSTEM_CON).log_ok();
}
}
Ok(WalkResult::Skip)
})?;
path.clear();
let mut path = cstr::buf::default();
path.append_path(tmp).append_path(LOG_PIPE);
path.set_secontext(cstr!(MAGISK_LOG_CON))?;
+3 -2
View File
@@ -420,9 +420,10 @@ void exec_root_shell(int client, int pid, SuRequest &req, MntNsMode mode) {
umask(022);
char path[32];
ssprintf(path, sizeof(path), "/proc/%d/cwd", pid);
char cwd[4096];
if (canonical_path(path, cwd, sizeof(cwd)) > 0)
if (auto cwd = realpath(path, nullptr)) {
chdir(cwd);
free(cwd);
}
ssprintf(path, sizeof(path), "/proc/%d/environ", pid);
auto env = full_read(path);
clearenv();
+1 -7
View File
@@ -16,7 +16,6 @@ struct devinfo {
char devname[32];
char partname[32];
char dmname[32];
char devpath[PATH_MAX];
};
static vector<devinfo> dev_list;
@@ -27,7 +26,6 @@ bool avd_hack = false;
static void parse_device(devinfo *dev, const char *uevent) {
dev->partname[0] = '\0';
dev->devpath[0] = '\0';
dev->dmname[0] = '\0';
dev->devname[0] = '\0';
parse_prop_file(uevent, [=](Utf8CStr key, Utf8CStr value) -> bool {
@@ -38,7 +36,7 @@ static void parse_device(devinfo *dev, const char *uevent) {
else if (key == "DEVNAME")
strscpy(dev->devname, value.c_str(), sizeof(dev->devname));
else if (key == "PARTNAME")
strscpy(dev->partname, value.c_str(), sizeof(dev->devname));
strscpy(dev->partname, value.c_str(), sizeof(dev->partname));
return true;
});
@@ -64,8 +62,6 @@ void MagiskInit::collect_devices() const noexcept {
// use androidboot.partition_map as partname fallback.
strscpy(dev.partname, it->value.data(), sizeof(dev.partname));
}
sprintf(path, "/sys/dev/block/%s", entry->d_name);
xrealpath(path, dev.devpath, sizeof(dev.devpath));
dev_list.push_back(dev);
}
}
@@ -84,8 +80,6 @@ uint64_t MagiskInit::find_block(const char *partname) const noexcept {
name = dev.dmname;
else if (strcasecmp(dev.devname, partname) == 0)
name = dev.devname;
else if (std::string_view(dev.devpath).ends_with("/"s + partname))
name = dev.devpath;
else
continue;