Make FsPathBuf a trait and rename to FsPathBuilder

This commit is contained in:
topjohnwu 2025-04-21 21:11:13 -07:00 committed by John Wu
parent f3fef7bfe4
commit ab2e5d1e7e
11 changed files with 152 additions and 147 deletions

View File

@ -358,11 +358,6 @@ impl Utf8CStr {
self.0.as_ptr().cast() self.0.as_ptr().cast()
} }
#[inline(always)]
pub fn as_mut_ptr(&mut self) -> *mut c_char {
self.0.as_mut_ptr().cast()
}
#[inline(always)] #[inline(always)]
pub fn as_cstr(&self) -> &CStr { pub fn as_cstr(&self) -> &CStr {
// SAFETY: Already validated as null terminated during construction // SAFETY: Already validated as null terminated during construction
@ -424,64 +419,6 @@ impl AsUtf8CStr for FsPathFollow {
} }
} }
pub struct FsPathBuf<'a, const N: usize>(pub Utf8CStrBuffer<'a, N>);
impl From<Utf8CString> for FsPathBuf<'static, 0> {
fn from(value: Utf8CString) -> Self {
FsPathBuf(From::from(value))
}
}
impl<const N: usize> From<Utf8CStrBufArr<N>> for FsPathBuf<'static, N> {
fn from(value: Utf8CStrBufArr<N>) -> Self {
FsPathBuf(From::from(value))
}
}
impl<'a> From<&'a mut dyn Utf8CStrBuf> for FsPathBuf<'a, 0> {
fn from(value: &'a mut dyn Utf8CStrBuf) -> Self {
FsPathBuf(From::from(value))
}
}
impl Default for FsPathBuf<'static, 4096> {
fn default() -> Self {
FsPathBuf(Default::default())
}
}
impl<const N: usize> FsPathBuf<'_, N> {
pub fn clear(&mut self) {
self.0.clear();
}
pub fn join<T: AsRef<str>>(mut self, path: T) -> Self {
fn inner(buf: &mut dyn Utf8CStrBuf, path: &str) {
if path.starts_with('/') {
buf.clear();
}
if !buf.is_empty() && !buf.ends_with('/') {
buf.push_str("/");
}
buf.push_str(path);
}
inner(self.0.deref_mut(), path.as_ref());
self
}
pub fn join_fmt<T: Display>(mut self, name: T) -> Self {
self.0.write_fmt(format_args!("/{}", name)).ok();
self
}
}
impl<const N: usize> AsUtf8CStr for FsPathBuf<'_, N> {
#[inline(always)]
fn as_utf8_cstr(&self) -> &Utf8CStr {
&self.0
}
}
// impl<T: AsUtf8CStr> Deref<Target = Utf8CStr> for T { ... } // impl<T: AsUtf8CStr> Deref<Target = Utf8CStr> for T { ... }
macro_rules! impl_cstr_deref { macro_rules! impl_cstr_deref {
($( ($t:ty, $($g:tt)*) )*) => {$( ($( ($t:ty, $($g:tt)*) )*) => {$(
@ -501,7 +438,6 @@ impl_cstr_deref!(
(Utf8CStrBufArr<N>, const N: usize) (Utf8CStrBufArr<N>, const N: usize)
(Utf8CString,) (Utf8CString,)
(FsPathFollow,) (FsPathFollow,)
(FsPathBuf<'_, N>, const N: usize)
); );
// impl<T: Deref<Target = Utf8CStr>> BoilerPlate for T { ... } // impl<T: Deref<Target = Utf8CStr>> BoilerPlate for T { ... }
@ -588,7 +524,6 @@ impl_cstr_misc!(
(Utf8CStrBufArr<N>, const N: usize) (Utf8CStrBufArr<N>, const N: usize)
(Utf8CString,) (Utf8CString,)
(FsPathFollow,) (FsPathFollow,)
(FsPathBuf<'_, N>, const N: usize)
); );
fn copy_cstr_truncate(dest: &mut [u8], src: &[u8]) -> usize { fn copy_cstr_truncate(dest: &mut [u8], src: &[u8]) -> usize {
@ -688,7 +623,6 @@ impl_fs_path!(
(Utf8CStrBufRef<'_>,) (Utf8CStrBufRef<'_>,)
(Utf8CStrBufArr<N>, const N: usize) (Utf8CStrBufArr<N>, const N: usize)
(Utf8CString,) (Utf8CString,)
(FsPathBuf<'_, N>, const N: usize)
); );
#[macro_export] #[macro_export]

View File

@ -1,6 +1,6 @@
use crate::cxx_extern::readlinkat; use crate::cxx_extern::readlinkat;
use crate::{ use crate::{
FileAttr, FsPath, FsPathBuf, LibcReturn, OsError, OsResult, OsResultStatic, Utf8CStr, FileAttr, FsPath, FsPathBuilder, LibcReturn, OsError, OsResult, OsResultStatic, Utf8CStr,
Utf8CStrBuf, cstr_buf, errno, fd_path, fd_set_attr, Utf8CStrBuf, cstr_buf, errno, fd_path, fd_set_attr,
}; };
use libc::{EEXIST, O_CLOEXEC, O_CREAT, O_RDONLY, O_TRUNC, O_WRONLY, dirent, mode_t}; use libc::{EEXIST, O_CLOEXEC, O_CREAT, O_RDONLY, O_TRUNC, O_WRONLY, dirent, mode_t};
@ -184,7 +184,7 @@ impl Directory {
fn path_at(&self, name: &Utf8CStr, buf: &mut dyn Utf8CStrBuf) -> OsResult<'static, ()> { fn path_at(&self, name: &Utf8CStr, buf: &mut dyn Utf8CStrBuf) -> OsResult<'static, ()> {
self.path(buf)?; self.path(buf)?;
FsPathBuf::from(buf).join(name); buf.append_path(name);
Ok(()) Ok(())
} }
} }
@ -247,14 +247,14 @@ impl Directory {
} }
pub fn get_attr_at<'a>(&self, name: &'a Utf8CStr) -> OsResult<'a, FileAttr> { pub fn get_attr_at<'a>(&self, name: &'a Utf8CStr) -> OsResult<'a, FileAttr> {
let mut path = FsPathBuf::default(); let mut path = cstr_buf::default();
self.path_at(name, path.0.deref_mut())?; self.path_at(name, &mut path)?;
path.get_attr().map_err(|e| e.set_args(Some(name), None)) path.get_attr().map_err(|e| e.set_args(Some(name), None))
} }
pub fn set_attr_at<'a>(&self, name: &'a Utf8CStr, attr: &FileAttr) -> OsResult<'a, ()> { pub fn set_attr_at<'a>(&self, name: &'a Utf8CStr, attr: &FileAttr) -> OsResult<'a, ()> {
let mut path = FsPathBuf::default(); let mut path = cstr_buf::default();
self.path_at(name, path.0.deref_mut())?; self.path_at(name, &mut path)?;
path.set_attr(attr) path.set_attr(attr)
.map_err(|e| e.set_args(Some(name), None)) .map_err(|e| e.set_args(Some(name), None))
} }
@ -264,15 +264,15 @@ impl Directory {
name: &'a Utf8CStr, name: &'a Utf8CStr,
con: &mut dyn Utf8CStrBuf, con: &mut dyn Utf8CStrBuf,
) -> OsResult<'a, ()> { ) -> OsResult<'a, ()> {
let mut path = FsPathBuf::default(); let mut path = cstr_buf::default();
self.path_at(name, path.0.deref_mut())?; self.path_at(name, &mut path)?;
path.get_secontext(con) path.get_secontext(con)
.map_err(|e| e.set_args(Some(name), None)) .map_err(|e| e.set_args(Some(name), None))
} }
pub fn set_secontext_at<'a>(&self, name: &'a Utf8CStr, con: &'a Utf8CStr) -> OsResult<'a, ()> { pub fn set_secontext_at<'a>(&self, name: &'a Utf8CStr, con: &'a Utf8CStr) -> OsResult<'a, ()> {
let mut path = FsPathBuf::default(); let mut path = cstr_buf::default();
self.path_at(name, path.0.deref_mut())?; self.path_at(name, &mut path)?;
path.set_secontext(con) path.set_secontext(con)
.map_err(|e| e.set_args(Some(name), Some(con))) .map_err(|e| e.set_args(Some(name), Some(con)))
} }

View File

@ -1,6 +1,6 @@
use crate::{ use crate::{
Directory, FsPathBuf, FsPathFollow, LibcReturn, OsError, OsResult, OsResultStatic, Utf8CStr, Directory, FsPathFollow, LibcReturn, OsError, OsResult, OsResultStatic, Utf8CStr, Utf8CStrBuf,
Utf8CStrBuf, cstr_buf, errno, error, cstr_buf, errno, error,
}; };
use bytemuck::{Pod, bytes_of, bytes_of_mut}; use bytemuck::{Pod, bytes_of, bytes_of_mut};
use libc::{ use libc::{
@ -11,6 +11,7 @@ use mem::MaybeUninit;
use num_traits::AsPrimitive; use num_traits::AsPrimitive;
use std::cmp::min; use std::cmp::min;
use std::ffi::CStr; use std::ffi::CStr;
use std::fmt::Display;
use std::fs::File; use std::fs::File;
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write}; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::ops::Deref; use std::ops::Deref;
@ -138,7 +139,9 @@ macro_rules! open_fd {
} }
pub fn fd_path(fd: RawFd, buf: &mut dyn Utf8CStrBuf) -> OsResult<'static, ()> { pub fn fd_path(fd: RawFd, buf: &mut dyn Utf8CStrBuf) -> OsResult<'static, ()> {
let path = FsPathBuf::default().join("/proc/self/fd").join_fmt(fd); let path = cstr_buf::default()
.join_path("/proc/self/fd")
.join_path_fmt(fd);
path.read_link(buf).map_err(|e| e.set_args(None, None)) path.read_link(buf).map_err(|e| e.set_args(None, None))
} }
@ -267,13 +270,13 @@ pub trait FsPath: Deref<Target = Utf8CStr> {
return Ok(()); return Ok(());
} }
let mut path = FsPathBuf::default(); let mut path = cstr_buf::default();
let mut components = self.split('/').filter(|s| !s.is_empty()); let mut components = self.split('/').filter(|s| !s.is_empty());
loop { loop {
let Some(s) = components.next() else { let Some(s) = components.next() else {
break; break;
}; };
path = path.join(s); path.append_path(s);
unsafe { unsafe {
if libc::mkdir(path.as_ptr(), mode) < 0 && *errno() != EEXIST { if libc::mkdir(path.as_ptr(), mode) < 0 && *errno() != EEXIST {
@ -548,6 +551,59 @@ impl FsPath for FsPathFollow {
} }
} }
pub trait FsPathBuilder {
fn join_path<T: AsRef<str>>(mut self, path: T) -> Self
where
Self: Sized,
{
self.append_path(path);
self
}
fn join_path_fmt<T: Display>(mut self, name: T) -> Self
where
Self: Sized,
{
self.append_path_fmt(name);
self
}
fn append_path<T: AsRef<str>>(&mut self, path: T) -> &mut Self;
fn append_path_fmt<T: Display>(&mut self, name: T) -> &mut Self;
}
fn append_path_impl(buf: &mut dyn Utf8CStrBuf, path: &str) {
if path.starts_with('/') {
buf.clear();
}
if !buf.is_empty() && !buf.ends_with('/') {
buf.push_str("/");
}
buf.push_str(path);
}
impl<S: Utf8CStrBuf + Sized> FsPathBuilder for S {
fn append_path<T: AsRef<str>>(&mut self, path: T) -> &mut Self {
append_path_impl(self, path.as_ref());
self
}
fn append_path_fmt<T: Display>(&mut self, name: T) -> &mut Self {
self.write_fmt(format_args!("/{}", name)).ok();
self
}
}
impl FsPathBuilder for dyn Utf8CStrBuf + '_ {
fn append_path<T: AsRef<str>>(&mut self, path: T) -> &mut Self {
append_path_impl(self, path.as_ref());
self
}
fn append_path_fmt<T: Display>(&mut self, name: T) -> &mut Self {
self.write_fmt(format_args!("/{}", name)).ok();
self
}
}
pub fn fd_get_attr(fd: RawFd) -> OsResult<'static, FileAttr> { pub fn fd_get_attr(fd: RawFd) -> OsResult<'static, FileAttr> {
let mut attr = FileAttr::new(); let mut attr = FileAttr::new();
unsafe { unsafe {

View File

@ -11,7 +11,7 @@ use crate::package::ManagerInfo;
use crate::su::SuInfo; use crate::su::SuInfo;
use base::libc::{O_CLOEXEC, O_RDONLY}; use base::libc::{O_CLOEXEC, O_RDONLY};
use base::{ use base::{
AtomicArc, BufReadExt, FsPath, FsPathBuf, ResultExt, Utf8CStr, cstr, cstr_buf, error, info, AtomicArc, BufReadExt, FsPath, FsPathBuilder, ResultExt, Utf8CStr, cstr, cstr_buf, error, info,
libc, open_fd, libc, open_fd,
}; };
use std::fs::File; use std::fs::File;
@ -229,9 +229,9 @@ pub fn daemon_entry() {
|| get_prop(cstr!("ro.product.device"), false).contains("vsoc"); || get_prop(cstr!("ro.product.device"), false).contains("vsoc");
// Load config status // Load config status
let path = FsPathBuf::from(cstr_buf::new::<64>()) let path = cstr_buf::new::<64>()
.join(get_magisk_tmp()) .join_path(get_magisk_tmp())
.join(MAIN_CONFIG); .join_path(MAIN_CONFIG);
let mut is_recovery = false; let mut is_recovery = false;
if let Ok(file) = path.open(O_RDONLY | O_CLOEXEC) { if let Ok(file) = path.open(O_RDONLY | O_CLOEXEC) {
let mut file = BufReader::new(file); let mut file = BufReader::new(file);

View File

@ -6,7 +6,7 @@ use base::libc::{
localtime_r, pthread_sigmask, sigaddset, sigset_t, sigtimedwait, time_t, timespec, tm, localtime_r, pthread_sigmask, sigaddset, sigset_t, sigtimedwait, time_t, timespec, tm,
}; };
use base::{ use base::{
FsPathBuf, LOGGER, LogLevel, Logger, ReadExt, Utf8CStr, Utf8CStrBuf, WriteExt, FsPathBuilder, LOGGER, LogLevel, Logger, ReadExt, Utf8CStr, Utf8CStrBuf, WriteExt,
const_format::concatcp, cstr_buf, libc, raw_cstr, const_format::concatcp, cstr_buf, libc, raw_cstr,
}; };
use bytemuck::{Pod, Zeroable, bytes_of, write_zeroes}; use bytemuck::{Pod, Zeroable, bytes_of, write_zeroes};
@ -180,7 +180,9 @@ pub fn zygisk_get_logd() -> i32 {
let mut fd = ZYGISK_LOGD.load(Ordering::Relaxed); let mut fd = ZYGISK_LOGD.load(Ordering::Relaxed);
if fd < 0 { if fd < 0 {
android_logging(); android_logging();
let path = FsPathBuf::default().join(get_magisk_tmp()).join(LOG_PIPE); let path = cstr_buf::default()
.join_path(get_magisk_tmp())
.join_path(LOG_PIPE);
// Open as RW as sometimes it may block // Open as RW as sometimes it may block
fd = unsafe { libc::open(path.as_ptr(), O_RDWR | O_CLOEXEC) }; fd = unsafe { libc::open(path.as_ptr(), O_RDWR | O_CLOEXEC) };
if fd >= 0 { if fd >= 0 {
@ -355,7 +357,9 @@ pub fn setup_logfile() {
} }
pub fn start_log_daemon() { pub fn start_log_daemon() {
let path = FsPathBuf::default().join(get_magisk_tmp()).join(LOG_PIPE); let path = cstr_buf::default()
.join_path(get_magisk_tmp())
.join_path(LOG_PIPE);
unsafe { unsafe {
libc::mkfifo(path.as_ptr(), 0o666); libc::mkfifo(path.as_ptr(), 0o666);

View File

@ -7,8 +7,8 @@ use num_traits::AsPrimitive;
use base::libc::{c_uint, dev_t}; use base::libc::{c_uint, dev_t};
use base::{ use base::{
FsPath, FsPathBuf, FsPathMnt, LibcReturn, LoggedResult, MountInfo, ResultExt, Utf8CStr, cstr, FsPath, FsPathBuilder, FsPathMnt, LibcReturn, LoggedResult, MountInfo, ResultExt, Utf8CStr,
cstr_buf, debug, info, libc, parse_mount_info, warn, Utf8CStrBuf, cstr, cstr_buf, debug, info, libc, parse_mount_info, warn,
}; };
use crate::consts::{MODULEMNT, MODULEROOT, PREINITDEV, PREINITMIRR, WORKERDIR}; use crate::consts::{MODULEMNT, MODULEROOT, PREINITDEV, PREINITMIRR, WORKERDIR};
@ -21,9 +21,9 @@ pub fn setup_mounts() {
let magisk_tmp = get_magisk_tmp(); let magisk_tmp = get_magisk_tmp();
// Mount preinit directory // Mount preinit directory
let dev_path = FsPathBuf::from(cstr_buf::new::<64>()) let dev_path = cstr_buf::new::<64>()
.join(magisk_tmp) .join_path(magisk_tmp)
.join(PREINITDEV); .join_path(PREINITDEV);
let mut linked = false; let mut linked = false;
if let Ok(attr) = dev_path.get_attr() { if let Ok(attr) = dev_path.get_attr() {
if attr.st.st_mode & libc::S_IFMT as c_uint == libc::S_IFBLK.as_() { if attr.st.st_mode & libc::S_IFMT as c_uint == libc::S_IFBLK.as_() {
@ -33,7 +33,9 @@ pub fn setup_mounts() {
// What we do instead is to scan through the current mountinfo and find a pre-existing // What we do instead is to scan through the current mountinfo and find a pre-existing
// mount point mounting our desired partition, and then bind mount the target folder. // mount point mounting our desired partition, and then bind mount the target folder.
let preinit_dev = attr.st.st_rdev; let preinit_dev = attr.st.st_rdev;
let mnt_path = FsPathBuf::default().join(magisk_tmp).join(PREINITMIRR); let mnt_path = cstr_buf::default()
.join_path(magisk_tmp)
.join_path(PREINITMIRR);
for info in parse_mount_info("self") { for info in parse_mount_info("self") {
if info.root == "/" && info.device == preinit_dev { if info.root == "/" && info.device == preinit_dev {
if !info.fs_option.split(',').any(|s| s == "rw") { if !info.fs_option.split(',').any(|s| s == "rw") {
@ -66,7 +68,9 @@ pub fn setup_mounts() {
} }
// Bind remount module root to clear nosuid // Bind remount module root to clear nosuid
let module_mnt = FsPathBuf::default().join(magisk_tmp).join(MODULEMNT); let module_mnt = cstr_buf::default()
.join_path(magisk_tmp)
.join_path(MODULEMNT);
let _: LoggedResult<()> = try { let _: LoggedResult<()> = try {
module_mnt.mkdir(0o755)?; module_mnt.mkdir(0o755)?;
cstr!(MODULEROOT).bind_mount_to(&module_mnt)?; cstr!(MODULEROOT).bind_mount_to(&module_mnt)?;
@ -77,11 +81,13 @@ pub fn setup_mounts() {
pub fn clean_mounts() { pub fn clean_mounts() {
let magisk_tmp = get_magisk_tmp(); let magisk_tmp = get_magisk_tmp();
let mut module_mnt = FsPathBuf::default().join(magisk_tmp).join(MODULEMNT); let mut buf = cstr_buf::default();
module_mnt.unmount().log_ok();
module_mnt.clear(); let module_mnt = buf.append_path(magisk_tmp).append_path(MODULEMNT);
let worker_dir = module_mnt.join(magisk_tmp).join(WORKERDIR); module_mnt.unmount().log_ok();
buf.clear();
let worker_dir = buf.append_path(magisk_tmp).append_path(WORKERDIR);
let _: LoggedResult<()> = try { let _: LoggedResult<()> = try {
worker_dir.set_mount_private(true)?; worker_dir.set_mount_private(true)?;
worker_dir.unmount()?; worker_dir.unmount()?;
@ -180,7 +186,8 @@ pub fn find_preinit_device() -> String {
&& let Ok(tmp) = std::env::var("MAGISKTMP") && let Ok(tmp) = std::env::var("MAGISKTMP")
&& !tmp.is_empty() && !tmp.is_empty()
{ {
let mut mirror_dir = FsPathBuf::default().join(&tmp).join(PREINITMIRR); let mut buf = cstr_buf::default();
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<()> = try {
preinit_dir.mkdirs(0o700)?; preinit_dir.mkdirs(0o700)?;
@ -190,8 +197,8 @@ pub fn find_preinit_device() -> String {
mirror_dir.create_symlink_to(preinit_dir)?; mirror_dir.create_symlink_to(preinit_dir)?;
}; };
if std::env::var_os("MAKEDEV").is_some() { if std::env::var_os("MAKEDEV").is_some() {
mirror_dir.clear(); buf.clear();
let dev_path = mirror_dir.join(&tmp).join(PREINITDEV); let dev_path = buf.append_path(&tmp).append_path(PREINITDEV);
unsafe { unsafe {
libc::mknod( libc::mknod(
dev_path.as_ptr(), dev_path.as_ptr(),

View File

@ -4,8 +4,8 @@ use crate::ffi::{DbEntryKey, get_magisk_tmp, install_apk, uninstall_pkg};
use base::WalkResult::{Abort, Continue, Skip}; use base::WalkResult::{Abort, Continue, Skip};
use base::libc::{O_CLOEXEC, O_CREAT, O_RDONLY, O_TRUNC, O_WRONLY}; use base::libc::{O_CLOEXEC, O_CREAT, O_RDONLY, O_TRUNC, O_WRONLY};
use base::{ use base::{
BufReadExt, Directory, FsPath, FsPathBuf, LoggedResult, ReadExt, ResultExt, Utf8CStrBuf, cstr, BufReadExt, Directory, FsPath, FsPathBuilder, LoggedResult, ReadExt, ResultExt, Utf8CStrBuf,
cstr_buf, error, fd_get_attr, open_fd, warn, cstr, cstr_buf, error, fd_get_attr, open_fd, warn,
}; };
use bit_set::BitSet; use bit_set::BitSet;
use cxx::CxxString; use cxx::CxxString;
@ -239,12 +239,12 @@ impl TrackedFile {
impl ManagerInfo { impl ManagerInfo {
fn check_dyn(&mut self, daemon: &MagiskD, user: i32, pkg: &str) -> Status { fn check_dyn(&mut self, daemon: &MagiskD, user: i32, pkg: &str) -> Status {
let apk = FsPathBuf::default() let apk = cstr_buf::default()
.join(daemon.app_data_dir()) .join_path(daemon.app_data_dir())
.join_fmt(user) .join_path_fmt(user)
.join(pkg) .join_path(pkg)
.join("dyn") .join_path("dyn")
.join("current.apk"); .join_path("current.apk");
let uid: i32; let uid: i32;
let cert = match apk.open(O_RDONLY | O_CLOEXEC) { let cert = match apk.open(O_RDONLY | O_CLOEXEC) {
Ok(mut fd) => { Ok(mut fd) => {
@ -441,10 +441,10 @@ impl ManagerInfo {
impl MagiskD { impl MagiskD {
fn get_package_uid(&self, user: i32, pkg: &str) -> i32 { fn get_package_uid(&self, user: i32, pkg: &str) -> i32 {
let path = FsPathBuf::default() let path = cstr_buf::default()
.join(self.app_data_dir()) .join_path(self.app_data_dir())
.join_fmt(user) .join_path_fmt(user)
.join(pkg); .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)
@ -453,7 +453,9 @@ impl MagiskD {
pub fn preserve_stub_apk(&self) { pub fn preserve_stub_apk(&self) {
let mut info = self.manager_info.lock().unwrap(); let mut info = self.manager_info.lock().unwrap();
let apk = FsPathBuf::default().join(get_magisk_tmp()).join("stub.apk"); let apk = cstr_buf::default()
.join_path(get_magisk_tmp())
.join_path("stub.apk");
if let Ok(mut fd) = apk.open(O_RDONLY | O_CLOEXEC) { if let Ok(mut fd) = apk.open(O_RDONLY | O_CLOEXEC) {
info.trusted_cert = read_certificate(&mut fd, MAGISK_VER_CODE); info.trusted_cert = read_certificate(&mut fd, MAGISK_VER_CODE);

View File

@ -16,8 +16,8 @@ use crate::resetprop::proto::persistent_properties::{
use base::const_format::concatcp; use base::const_format::concatcp;
use base::libc::{O_CLOEXEC, O_RDONLY}; use base::libc::{O_CLOEXEC, O_RDONLY};
use base::{ use base::{
Directory, FsPath, FsPathBuf, LibcReturn, LoggedResult, MappedFile, SilentResultExt, Utf8CStr, Directory, FsPath, FsPathBuilder, LibcReturn, LoggedResult, MappedFile, SilentResultExt,
WalkResult, clone_attr, cstr, debug, libc::mkstemp, Utf8CStr, Utf8CStrBuf, WalkResult, clone_attr, cstr, cstr_buf, debug, libc::mkstemp,
}; };
const PERSIST_PROP_DIR: &str = "/data/property"; const PERSIST_PROP_DIR: &str = "/data/property";
@ -68,7 +68,9 @@ fn check_proto() -> bool {
} }
fn file_get_prop(name: &Utf8CStr) -> LoggedResult<String> { fn file_get_prop(name: &Utf8CStr) -> LoggedResult<String> {
let path = FsPathBuf::default().join(PERSIST_PROP_DIR).join(name); let path = cstr_buf::default()
.join_path(PERSIST_PROP_DIR)
.join_path(name);
let mut file = path.open(O_RDONLY | O_CLOEXEC).silent()?; let mut file = path.open(O_RDONLY | O_CLOEXEC).silent()?;
debug!("resetprop: read prop from [{}]", path); debug!("resetprop: read prop from [{}]", path);
let mut s = String::new(); let mut s = String::new();
@ -77,14 +79,16 @@ fn file_get_prop(name: &Utf8CStr) -> LoggedResult<String> {
} }
fn file_set_prop(name: &Utf8CStr, value: Option<&Utf8CStr>) -> LoggedResult<()> { fn file_set_prop(name: &Utf8CStr, value: Option<&Utf8CStr>) -> LoggedResult<()> {
let path = FsPathBuf::default().join(PERSIST_PROP_DIR).join(name); let path = cstr_buf::default()
.join_path(PERSIST_PROP_DIR)
.join_path(name);
if let Some(value) = value { if let Some(value) = value {
let mut tmp = FsPathBuf::default() let mut tmp = cstr_buf::default()
.join(PERSIST_PROP_DIR) .join_path(PERSIST_PROP_DIR)
.join("prop.XXXXXX"); .join_path("prop.XXXXXX");
{ {
let mut f = unsafe { let mut f = unsafe {
mkstemp(tmp.0.as_mut_ptr()) mkstemp(tmp.as_mut_ptr())
.as_os_result("mkstemp", None, None) .as_os_result("mkstemp", None, None)
.map(|fd| File::from_raw_fd(fd))? .map(|fd| File::from_raw_fd(fd))?
}; };
@ -111,10 +115,10 @@ fn proto_read_props() -> LoggedResult<PersistentProperties> {
} }
fn proto_write_props(props: &PersistentProperties) -> LoggedResult<()> { fn proto_write_props(props: &PersistentProperties) -> LoggedResult<()> {
let mut tmp = FsPathBuf::default().join(concatcp!(PERSIST_PROP, ".XXXXXX")); let mut tmp = cstr_buf::default().join_path(concatcp!(PERSIST_PROP, ".XXXXXX"));
{ {
let f = unsafe { let f = unsafe {
mkstemp(tmp.0.as_mut_ptr()) mkstemp(tmp.as_mut_ptr())
.as_os_result("mkstemp", None, None) .as_os_result("mkstemp", None, None)
.map(|fd| File::from_raw_fd(fd))? .map(|fd| File::from_raw_fd(fd))?
}; };

View File

@ -6,8 +6,8 @@ use crate::ffi::{
use crate::socket::{IpcRead, UnixSocketExt}; use crate::socket::{IpcRead, UnixSocketExt};
use base::libc::{O_CLOEXEC, O_CREAT, O_RDONLY, STDOUT_FILENO}; use base::libc::{O_CLOEXEC, O_CREAT, O_RDONLY, STDOUT_FILENO};
use base::{ use base::{
Directory, FsPathBuf, LoggedError, LoggedResult, ResultExt, WriteExt, cstr, cstr_buf, error, Directory, FsPathBuilder, LoggedError, LoggedResult, ResultExt, WriteExt, cstr, cstr_buf,
fork_dont_care, libc, open_fd, raw_cstr, warn, error, fork_dont_care, libc, open_fd, raw_cstr, warn,
}; };
use std::fmt::Write; use std::fmt::Write;
use std::os::fd::{AsRawFd, FromRawFd, RawFd}; use std::os::fd::{AsRawFd, FromRawFd, RawFd};
@ -37,9 +37,9 @@ fn exec_zygiskd(is_64_bit: bool, remote: UnixStream) {
#[cfg(target_pointer_width = "32")] #[cfg(target_pointer_width = "32")]
let magisk = "magisk"; let magisk = "magisk";
let exe = FsPathBuf::from(cstr_buf::new::<64>()) let exe = cstr_buf::new::<64>()
.join(get_magisk_tmp()) .join_path(get_magisk_tmp())
.join(magisk); .join_path(magisk);
let mut fd_str = cstr_buf::new::<16>(); let mut fd_str = cstr_buf::new::<16>();
write!(fd_str, "{}", remote.as_raw_fd()).ok(); write!(fd_str, "{}", remote.as_raw_fd()).ok();
@ -185,10 +185,10 @@ impl MagiskD {
let failed_ids: Vec<i32> = client.read_decodable()?; let failed_ids: Vec<i32> = client.read_decodable()?;
if let Some(module_list) = self.module_list.get() { if let Some(module_list) = self.module_list.get() {
for id in failed_ids { for id in failed_ids {
let path = FsPathBuf::default() let path = cstr_buf::default()
.join(MODULEROOT) .join_path(MODULEROOT)
.join(&module_list[id as usize].name) .join_path(&module_list[id as usize].name)
.join("zygisk"); .join_path("zygisk");
// Create the unloaded marker file // Create the unloaded marker file
if let Ok(dir) = Directory::open(&path) { if let Ok(dir) = Directory::open(&path) {
dir.openat_as_file(cstr!("unloaded"), O_CREAT | O_RDONLY, 0o644) dir.openat_as_file(cstr!("unloaded"), O_CREAT | O_RDONLY, 0o644)
@ -204,7 +204,9 @@ impl MagiskD {
fn get_mod_dir(&self, mut client: UnixStream) -> LoggedResult<()> { fn get_mod_dir(&self, mut client: UnixStream) -> LoggedResult<()> {
let id: i32 = client.read_decodable()?; let id: i32 = client.read_decodable()?;
let module = &self.module_list.get().unwrap()[id as usize]; let module = &self.module_list.get().unwrap()[id as usize];
let dir = FsPathBuf::default().join(MODULEROOT).join(&module.name); let dir = cstr_buf::default()
.join_path(MODULEROOT)
.join_path(&module.name);
let fd = open_fd!(&dir, O_RDONLY | O_CLOEXEC)?; let fd = open_fd!(&dir, O_RDONLY | O_CLOEXEC)?;
client.send_fds(&[fd.as_raw_fd()])?; client.send_fds(&[fd.as_raw_fd()])?;
Ok(()) Ok(())

View File

@ -1,8 +1,8 @@
use crate::ffi::MagiskInit; use crate::ffi::MagiskInit;
use base::libc::{TMPFS_MAGIC, statfs}; use base::libc::{TMPFS_MAGIC, statfs};
use base::{ use base::{
Directory, FsPath, FsPathBuf, FsPathMnt, LibcReturn, LoggedResult, ResultExt, Utf8CStr, cstr, Directory, FsPath, FsPathBuilder, FsPathMnt, LibcReturn, LoggedResult, ResultExt, Utf8CStr,
debug, libc, cstr, cstr_buf, debug, libc,
libc::{chdir, chroot, execve, exit, mount}, libc::{chdir, chroot, execve, exit, mount},
parse_mount_info, raw_cstr, parse_mount_info, raw_cstr,
}; };
@ -38,9 +38,9 @@ pub(crate) fn switch_root(path: &Utf8CStr) {
let mut target = info.target.clone(); let mut target = info.target.clone();
let target = Utf8CStr::from_string(&mut target); let target = Utf8CStr::from_string(&mut target);
let new_path = FsPathBuf::default() let new_path = cstr_buf::default()
.join(path) .join_path(path)
.join(info.target.trim_start_matches('/')); .join_path(info.target.trim_start_matches('/'));
new_path.mkdirs(0o755).ok(); new_path.mkdirs(0o755).ok();
target.move_mount_to(&new_path)?; target.move_mount_to(&new_path)?;
mounts.insert(info.target); mounts.insert(info.target);

View File

@ -2,7 +2,7 @@ use crate::consts::{ROOTMNT, ROOTOVL};
use crate::ffi::MagiskInit; use crate::ffi::MagiskInit;
use base::libc::{O_CREAT, O_RDONLY, O_WRONLY}; use base::libc::{O_CREAT, O_RDONLY, O_WRONLY};
use base::{ use base::{
BufReadExt, Directory, FsPath, FsPathBuf, FsPathMnt, LoggedResult, ResultExt, Utf8CStr, BufReadExt, Directory, FsPath, FsPathBuilder, FsPathMnt, LoggedResult, ResultExt, Utf8CStr,
Utf8CString, clone_attr, cstr, cstr_buf, debug, Utf8CString, clone_attr, cstr, cstr_buf, debug,
}; };
use std::io::BufReader; use std::io::BufReader;
@ -72,12 +72,8 @@ impl MagiskInit {
None => return Ok(()), None => return Ok(()),
Some(e) => { Some(e) => {
let name = e.name(); let name = e.name();
let src = FsPathBuf::from(cstr_buf::dynamic(256)) let src = cstr_buf::dynamic(256).join_path(src_dir).join_path(name);
.join(src_dir) let dest = cstr_buf::dynamic(256).join_path(dest_dir).join_path(name);
.join(name);
let dest = FsPathBuf::from(cstr_buf::dynamic(256))
.join(dest_dir)
.join(name);
if dest.exists() { if dest.exists() {
if e.is_dir() { if e.is_dir() {
// Recursive // Recursive