Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up code #8794

Merged
merged 3 commits into from
Feb 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
231 changes: 142 additions & 89 deletions native/src/base/cstr.rs

Large diffs are not rendered by default.

12 changes: 5 additions & 7 deletions native/src/base/files.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::cxx_extern::readlinkat_for_cxx;
use crate::{
cstr, errno, error, FsPath, FsPathBuf, LibcReturn, Utf8CStr, Utf8CStrBuf, Utf8CStrBufArr,
Utf8CStrWrite,
};
use bytemuck::{bytes_of, bytes_of_mut, Pod};
use libc::{
Expand Down Expand Up @@ -39,8 +38,7 @@ macro_rules! open_fd {
}

pub fn fd_path(fd: RawFd, buf: &mut dyn Utf8CStrBuf) -> io::Result<()> {
let mut arr = Utf8CStrBufArr::<40>::new();
let path = FsPathBuf::new(&mut arr).join("/proc/self/fd").join_fmt(fd);
let path = FsPathBuf::default().join("/proc/self/fd").join_fmt(fd);
path.read_link(buf)
}

Expand Down Expand Up @@ -622,9 +620,9 @@ impl FsPath {
buf.clear();
unsafe {
let r = libc::readlink(self.as_ptr(), buf.as_mut_ptr().cast(), buf.capacity() - 1)
.check_os_err()? as usize;
*buf.mut_buf().get_unchecked_mut(r) = b'\0';
buf.set_len(r);
.check_os_err()? as isize;
*(buf.as_mut_ptr().offset(r) as *mut u8) = b'\0';
buf.set_len(r as usize);
}
Ok(())
}
Expand Down Expand Up @@ -791,7 +789,7 @@ impl FsPath {
unsafe { libc::symlink(self.as_ptr(), path.as_ptr()).as_os_err() }
}

pub fn parent(&self, buf: &mut dyn Utf8CStrWrite) -> bool {
pub fn parent(&self, buf: &mut dyn Utf8CStrBuf) -> bool {
buf.clear();
if let Some(parent) = Path::new(self.as_str()).parent() {
let bytes = parent.as_os_str().as_bytes();
Expand Down
2 changes: 1 addition & 1 deletion native/src/boot/cpio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use base::libc::{
};
use base::{
log_err, map_args, BytesExt, EarlyExitExt, FsPath, LoggedResult, MappedFile, ResultExt,
Utf8CStr, Utf8CStrBufArr, Utf8CStrWrite, WriteExt,
Utf8CStr, Utf8CStrBuf, Utf8CStrBufArr, WriteExt,
};

use crate::check_env;
Expand Down
6 changes: 2 additions & 4 deletions native/src/core/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ use crate::package::ManagerInfo;
use crate::su::SuInfo;
use base::libc::{O_CLOEXEC, O_RDONLY};
use base::{
cstr, error, info, libc, open_fd, AtomicArc, BufReadExt, FsPath, FsPathBuf, ResultExt,
Utf8CStr, Utf8CStrBufArr,
cstr, error, info, libc, open_fd, AtomicArc, BufReadExt, FsPath, FsPathBuf, ResultExt, Utf8CStr,
};
use std::fs::File;
use std::io::BufReader;
Expand Down Expand Up @@ -229,8 +228,7 @@ pub fn daemon_entry() {
|| get_prop(cstr!("ro.product.device"), false).contains("vsoc");

// Load config status
let mut buf = Utf8CStrBufArr::<64>::new();
let path = FsPathBuf::new(&mut buf)
let path = FsPathBuf::<64>::new()
.join(get_magisk_tmp())
.join(MAIN_CONFIG);
let mut is_recovery = false;
Expand Down
19 changes: 4 additions & 15 deletions native/src/core/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use base::libc::{
};
use base::{
const_format::concatcp, libc, raw_cstr, FsPathBuf, LogLevel, Logger, ReadExt, Utf8CStr,
Utf8CStrBuf, Utf8CStrBufArr, Utf8CStrWrite, WriteExt, LOGGER,
Utf8CStrBuf, Utf8CStrBufArr, WriteExt, LOGGER,
};
use bytemuck::{bytes_of, write_zeroes, Pod, Zeroable};
use num_derive::{FromPrimitive, ToPrimitive};
Expand Down Expand Up @@ -180,10 +180,7 @@ pub fn zygisk_get_logd() -> i32 {
let mut fd = ZYGISK_LOGD.load(Ordering::Relaxed);
if fd < 0 {
android_logging();
let mut buf = Utf8CStrBufArr::default();
let path = FsPathBuf::new(&mut buf)
.join(get_magisk_tmp())
.join(LOG_PIPE);
let path = FsPathBuf::default().join(get_magisk_tmp()).join(LOG_PIPE);
// Open as RW as sometimes it may block
fd = unsafe { libc::open(path.as_ptr(), O_RDWR | O_CLOEXEC) };
if fd >= 0 {
Expand Down Expand Up @@ -319,12 +316,7 @@ extern "C" fn logfile_writer(arg: *mut c_void) -> *mut c_void {
if localtime_r(&secs, &mut tm).is_null() {
continue;
}
let len = strftime(
aux.mut_buf().as_mut_ptr().cast(),
aux.capacity(),
raw_cstr!("%m-%d %T"),
&tm,
);
let len = strftime(aux.as_mut_ptr(), aux.capacity(), raw_cstr!("%m-%d %T"), &tm);
aux.set_len(len);
aux.write_fmt(format_args!(
".{:03} {:5} {:5} {} : ",
Expand Down Expand Up @@ -363,10 +355,7 @@ pub fn setup_logfile() {
}

pub fn start_log_daemon() {
let mut buf = Utf8CStrBufArr::default();
let path = FsPathBuf::new(&mut buf)
.join(get_magisk_tmp())
.join(LOG_PIPE);
let path = FsPathBuf::default().join(get_magisk_tmp()).join(LOG_PIPE);

unsafe {
libc::mkfifo(path.as_ptr(), 0o666);
Expand Down
23 changes: 9 additions & 14 deletions native/src/core/mount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,9 @@ pub fn setup_mounts() {
info!("* Setup internal mounts");

let magisk_tmp = get_magisk_tmp();
let mut buf = Utf8CStrBufArr::default();

// Mount preinit directory
let mut dev_buf = Utf8CStrBufArr::<64>::new();
let dev_path = FsPathBuf::new(&mut dev_buf)
.join(magisk_tmp)
.join(PREINITDEV);
let dev_path = FsPathBuf::<64>::new().join(magisk_tmp).join(PREINITDEV);
let mut linked = false;
if let Ok(attr) = dev_path.get_attr() {
if attr.st.st_mode & libc::S_IFMT as c_uint == libc::S_IFBLK.as_() {
Expand All @@ -36,7 +32,7 @@ pub fn setup_mounts() {
// 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.
let preinit_dev = attr.st.st_rdev;
let mnt_path = FsPathBuf::new(&mut buf).join(magisk_tmp).join(PREINITMIRR);
let mnt_path = FsPathBuf::default().join(magisk_tmp).join(PREINITMIRR);
for info in parse_mount_info("self") {
if info.root == "/" && info.device == preinit_dev {
if !info.fs_option.split(',').any(|s| s == "rw") {
Expand Down Expand Up @@ -74,7 +70,7 @@ pub fn setup_mounts() {
}

// Bind remount module root to clear nosuid
let module_mnt = FsPathBuf::new(&mut buf).join(magisk_tmp).join(MODULEMNT);
let module_mnt = FsPathBuf::default().join(magisk_tmp).join(MODULEMNT);
let _: LoggedResult<()> = try {
module_mnt.mkdir(0o755)?;
unsafe {
Expand All @@ -101,16 +97,15 @@ pub fn setup_mounts() {
pub fn clean_mounts() {
let magisk_tmp = get_magisk_tmp();

let mut buf = Utf8CStrBufArr::default();

let module_mnt = FsPathBuf::new(&mut buf).join(magisk_tmp).join(MODULEMNT);
let mut module_mnt = FsPathBuf::default().join(magisk_tmp).join(MODULEMNT);
let _: LoggedResult<()> = try {
unsafe {
libc::umount2(module_mnt.as_ptr(), libc::MNT_DETACH).as_os_err()?;
}
};

let worker_dir = FsPathBuf::new(&mut buf).join(magisk_tmp).join(WORKERDIR);
module_mnt.clear();
let worker_dir = module_mnt.join(magisk_tmp).join(WORKERDIR);
let _: LoggedResult<()> = try {
unsafe {
libc::mount(
Expand Down Expand Up @@ -218,8 +213,7 @@ pub fn find_preinit_device() -> String {
&& let Ok(tmp) = std::env::var("MAGISKTMP")
&& !tmp.is_empty()
{
let mut buf = Utf8CStrBufArr::default();
let mirror_dir = FsPathBuf::new(&mut buf).join(&tmp).join(PREINITMIRR);
let mut mirror_dir = FsPathBuf::default().join(&tmp).join(PREINITMIRR);
let preinit_dir = FsPath::from(Utf8CStr::from_string(&mut preinit_dir));
let _: LoggedResult<()> = try {
preinit_dir.mkdirs(0o700)?;
Expand All @@ -236,7 +230,8 @@ pub fn find_preinit_device() -> String {
}
};
if std::env::var_os("MAKEDEV").is_some() {
let dev_path = FsPathBuf::new(&mut buf).join(&tmp).join(PREINITDEV);
mirror_dir.clear();
let dev_path = mirror_dir.join(&tmp).join(PREINITDEV);
unsafe {
libc::mknod(
dev_path.as_ptr(),
Expand Down
11 changes: 3 additions & 8 deletions native/src/core/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,7 @@ impl TrackedFile {

impl ManagerInfo {
fn check_dyn(&mut self, daemon: &MagiskD, user: i32, pkg: &str) -> Status {
let mut arr = Utf8CStrBufArr::default();
let apk = FsPathBuf::new(&mut arr)
let apk = FsPathBuf::default()
.join(daemon.app_data_dir())
.join_fmt(user)
.join(pkg)
Expand Down Expand Up @@ -444,8 +443,7 @@ impl ManagerInfo {

impl MagiskD {
fn get_package_uid(&self, user: i32, pkg: &str) -> i32 {
let mut arr = Utf8CStrBufArr::default();
let path = FsPathBuf::new(&mut arr)
let path = FsPathBuf::default()
.join(self.app_data_dir())
.join_fmt(user)
.join(pkg);
Expand All @@ -457,10 +455,7 @@ impl MagiskD {
pub fn preserve_stub_apk(&self) {
let mut info = self.manager_info.lock().unwrap();

let mut arr = Utf8CStrBufArr::default();
let apk = FsPathBuf::new(&mut arr)
.join(get_magisk_tmp())
.join("stub.apk");
let apk = FsPathBuf::default().join(get_magisk_tmp()).join("stub.apk");

if let Ok(mut fd) = apk.open(O_RDONLY | O_CLOEXEC) {
info.trusted_cert = read_certificate(&mut fd, MAGISK_VER_CODE);
Expand Down
18 changes: 5 additions & 13 deletions native/src/core/resetprop/persist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use quick_protobuf::{BytesReader, MessageRead, MessageWrite, Writer};
use base::libc::{O_CLOEXEC, O_RDONLY};
use base::{
clone_attr, cstr, debug, libc::mkstemp, Directory, FsPath, FsPathBuf, LibcReturn, LoggedResult,
MappedFile, SilentResultExt, Utf8CStr, Utf8CStrBufArr, WalkResult,
MappedFile, SilentResultExt, Utf8CStr, WalkResult,
};

use crate::ffi::{prop_cb_exec, PropCb};
Expand Down Expand Up @@ -77,10 +77,7 @@ fn check_proto() -> bool {
}

fn file_get_prop(name: &Utf8CStr) -> LoggedResult<String> {
let mut buf = Utf8CStrBufArr::default();
let path = FsPathBuf::new(&mut buf)
.join(PERSIST_PROP_DIR!())
.join(name);
let path = FsPathBuf::default().join(PERSIST_PROP_DIR!()).join(name);
let mut file = path.open(O_RDONLY | O_CLOEXEC).silent()?;
debug!("resetprop: read prop from [{}]", path);
let mut s = String::new();
Expand All @@ -89,13 +86,9 @@ fn file_get_prop(name: &Utf8CStr) -> LoggedResult<String> {
}

fn file_set_prop(name: &Utf8CStr, value: Option<&Utf8CStr>) -> LoggedResult<()> {
let mut buf = Utf8CStrBufArr::default();
let path = FsPathBuf::new(&mut buf)
.join(PERSIST_PROP_DIR!())
.join(name);
let path = FsPathBuf::default().join(PERSIST_PROP_DIR!()).join(name);
if let Some(value) = value {
let mut buf = Utf8CStrBufArr::default();
let mut tmp = FsPathBuf::new(&mut buf)
let mut tmp = FsPathBuf::default()
.join(PERSIST_PROP_DIR!())
.join("prop.XXXXXX");
{
Expand Down Expand Up @@ -126,8 +119,7 @@ fn proto_read_props() -> LoggedResult<PersistentProperties> {
}

fn proto_write_props(props: &PersistentProperties) -> LoggedResult<()> {
let mut buf = Utf8CStrBufArr::default();
let mut tmp = FsPathBuf::new(&mut buf).join(concat!(PERSIST_PROP!(), ".XXXXXX"));
let mut tmp = FsPathBuf::default().join(concat!(PERSIST_PROP!(), ".XXXXXX"));
{
let f = unsafe {
let fd = mkstemp(tmp.as_mut_ptr()).check_os_err()?;
Expand Down
9 changes: 3 additions & 6 deletions native/src/core/zygisk/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,14 @@ fn exec_zygiskd(is_64_bit: bool, remote: UnixStream) {
}

// Start building the exec arguments
let mut exe = Utf8CStrBufArr::<64>::new();

#[cfg(target_pointer_width = "64")]
let magisk = if is_64_bit { "magisk" } else { "magisk32" };

#[cfg(target_pointer_width = "32")]
let magisk = "magisk";

let exe = FsPathBuf::new(&mut exe).join(get_magisk_tmp()).join(magisk);
let exe = FsPathBuf::<64>::new().join(get_magisk_tmp()).join(magisk);

let mut fd_str = Utf8CStrBufArr::<16>::new();
write!(fd_str, "{}", remote.as_raw_fd()).ok();
Expand Down Expand Up @@ -184,8 +183,7 @@ impl MagiskD {
let failed_ids: Vec<i32> = client.read_decodable()?;
if let Some(module_list) = self.module_list.get() {
for id in failed_ids {
let mut buf = Utf8CStrBufArr::default();
let path = FsPathBuf::new(&mut buf)
let path = FsPathBuf::default()
.join(MODULEROOT)
.join(&module_list[id as usize].name)
.join("zygisk");
Expand All @@ -204,8 +202,7 @@ impl MagiskD {
fn get_mod_dir(&self, mut client: UnixStream) -> LoggedResult<()> {
let id: i32 = client.read_decodable()?;
let module = &self.module_list.get().unwrap()[id as usize];
let mut buf = Utf8CStrBufArr::default();
let dir = FsPathBuf::new(&mut buf).join(MODULEROOT).join(&module.name);
let dir = FsPathBuf::default().join(MODULEROOT).join(&module.name);
let fd = open_fd!(&dir, O_RDONLY | O_CLOEXEC)?;
client.send_fds(&[fd.as_raw_fd()])?;
Ok(())
Expand Down
8 changes: 5 additions & 3 deletions native/src/init/getinfo.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::ffi::{BootConfig, MagiskInit};
use base::{cstr, debug, BytesExt, FsPath, MappedFile, Utf8CStr};
use crate::ffi::{backup_init, BootConfig, MagiskInit};
use base::{cstr, debug, BytesExt, FsPath, MappedFile};
use std::ffi::CStr;

impl BootConfig {
Expand Down Expand Up @@ -33,6 +33,8 @@ impl MagiskInit {
// Use the apex folder to determine whether 2SI (Android 10+)
FsPath::from(cstr!("/apex")).exists() ||
// If we still have no indication, parse the original init and see what's up
MappedFile::open(unsafe { Utf8CStr::from_ptr_unchecked(self.backup_init()) }).map(|map| map.contains(b"selinux_setup")).unwrap_or(false)
MappedFile::open(backup_init())
.map(|data| data.contains(b"selinux_setup"))
.unwrap_or(false)
}
}
8 changes: 4 additions & 4 deletions native/src/init/init.hpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#include <base.hpp>
#include <stream.hpp>

#include "init-rs.hpp"

#define DEFAULT_DT_DIR "/proc/device-tree/firmware/android"
#define INIT_PATH "/system/bin/init"
#define REDIR_PATH "/data/magiskinit"

int magisk_proxy_main(int argc, char *argv[]);

#include "init-rs.hpp"
int magisk_proxy_main(int, char *argv[]);
rust::Utf8CStr backup_init();
5 changes: 3 additions & 2 deletions native/src/init/init.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::ffi::backup_init;
use crate::{
ffi::{magisk_proxy_main, BootConfig, MagiskInit},
logging::setup_klog,
};
use base::{
cstr, debug, info,
libc::{basename, getpid, mount, umask},
raw_cstr, FsPath, LibcReturn, LoggedResult, ResultExt, Utf8CStr,
raw_cstr, FsPath, LibcReturn, LoggedResult, ResultExt,
};
use std::{
ffi::{c_char, CStr},
Expand Down Expand Up @@ -63,7 +64,7 @@ impl MagiskInit {
pub(crate) fn restore_ramdisk_init(&self) {
FsPath::from(cstr!("/init")).remove().ok();

let orig_init = FsPath::from(unsafe { Utf8CStr::from_ptr_unchecked(self.backup_init()) });
let orig_init = FsPath::from(backup_init());

if orig_init.exists() {
orig_init.rename_to(FsPath::from(cstr!("/init"))).log_ok();
Expand Down
Loading
Loading