Skip to content

Refactor module mount load in rust #8846

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
30 changes: 30 additions & 0 deletions native/src/base/cstr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ pub trait Utf8CStrBuf:
// 2. Ensure len <= capacity - 1
// 3. All bytes from 0 to len is valid UTF-8 and does not contain null
unsafe fn set_len(&mut self, len: usize);

// self[len] = b'\0'; self.set_len(len)
fn resize(&mut self, len: usize);
fn push_str(&mut self, s: &str) -> usize;
fn push_lossy(&mut self, s: &[u8]) -> usize;
// The capacity of the internal buffer. The maximum string length this buffer can contain
Expand Down Expand Up @@ -185,6 +188,7 @@ impl StringExt for PathBuf {
}
}

#[derive(Eq, Ord, PartialOrd)]
pub struct Utf8CString(String);

impl Default for Utf8CString {
Expand Down Expand Up @@ -236,6 +240,16 @@ impl Utf8CStrBuf for Utf8CString {
self.0.as_mut_vec().set_len(len);
}
}

fn resize(&mut self, len: usize) {
if len >= self.0.capacity() {
return;
Comment on lines +244 to +246
Copy link
Preview

Copilot AI Apr 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Utf8CString resize method silently returns if len is greater than or equal to capacity. It might be better to handle this case explicitly (e.g., by returning a Result or panicking) to avoid unintended behavior.

Suggested change
fn resize(&mut self, len: usize) {
if len >= self.0.capacity() {
return;
fn resize(&mut self, len: usize) -> Result<(), &'static str> {
if len >= self.0.capacity() {
return Err("Length exceeds capacity");

Copilot uses AI. Check for mistakes.

}
unsafe {
*self.0.as_mut_ptr().add(len) = b'\0' as _;
self.set_len(len);
}
}

fn push_str(&mut self, s: &str) -> usize {
self.0.push_str(s);
Expand Down Expand Up @@ -583,6 +597,14 @@ impl<const N: usize> FsPathBuf<N> {
inner(self.0.deref_mut(), path.as_ref());
self
}

pub fn resize(mut self, len: usize) -> Self {
unsafe {
self.0.as_bytes_mut()[len] = b'\0';
self.0.set_len(len)
};
Comment on lines +602 to +605
Copy link
Preview

Copilot AI Apr 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FsPathBuf resize method lacks a bounds check on the provided len, which may lead to out-of-bound access. Consider adding a check to ensure len is within the valid range.

Suggested change
unsafe {
self.0.as_bytes_mut()[len] = b'\0';
self.0.set_len(len)
};
if len <= self.0.as_bytes().len() {
unsafe {
self.0.as_bytes_mut()[len] = b'\0';
self.0.set_len(len)
};
} else {
// Handle the error case, e.g., by returning self unchanged or logging an error
// For now, we will just return self unchanged
}

Copilot uses AI. Check for mistakes.

self
}

pub fn join_fmt<T: Display>(mut self, name: T) -> Self {
self.0.write_fmt(format_args!("/{}", name)).ok();
Expand Down Expand Up @@ -742,6 +764,14 @@ macro_rules! impl_str_buf_with_slice {
unsafe fn set_len(&mut self, len: usize) {
self.used = len;
}
fn resize(&mut self, len: usize) {
if len < self.capacity() {
unsafe {
self.buf[len] = b'\0';
self.set_len(len);
}
}
}
#[inline(always)]
fn push_str(&mut self, s: &str) -> usize {
utf8_cstr_buf_append(self, s.as_bytes())
Expand Down
9 changes: 8 additions & 1 deletion native/src/base/dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
cstr, cstr_buf, errno, fd_path, fd_set_attr, FileAttr, FsPath, LibcReturn, Utf8CStr,
Utf8CStrBuf,
};
use libc::{dirent, O_CLOEXEC, O_CREAT, O_RDONLY, O_TRUNC, O_WRONLY};
use libc::{dirent, O_CLOEXEC, O_CREAT, O_DIRECTORY, O_RDONLY, O_TRUNC, O_WRONLY};
use std::ffi::CStr;
use std::fs::File;
use std::ops::Deref;
Expand Down Expand Up @@ -195,6 +195,13 @@ impl Directory {
}
}

pub fn open_dir(&self, name: &CStr) -> io::Result<Directory> {
let dirp = unsafe {
libc::fdopendir(self.open_raw_fd(name, O_RDONLY|O_DIRECTORY|O_CLOEXEC, 0)?).check_os_err()?
};
Ok(Directory { dirp })
}

pub fn contains_path(&self, path: &CStr) -> bool {
// WARNING: Using faccessat is incorrect, because the raw linux kernel syscall
// does not support the flag AT_SYMLINK_NOFOLLOW until 5.8 with faccessat2.
Expand Down
23 changes: 18 additions & 5 deletions native/src/base/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@ use crate::{
Utf8CStrBuf,
};
use bytemuck::{bytes_of, bytes_of_mut, Pod};
use libc::{
c_uint, makedev, mode_t, stat, EEXIST, ENOENT, F_OK, O_CLOEXEC, O_CREAT, O_PATH, O_RDONLY,
O_RDWR, O_TRUNC, O_WRONLY,
};
use libc::{c_uint, makedev, mode_t, stat, EEXIST, ENOENT, F_OK, MS_BIND, MS_RDONLY, MS_REC, MS_REMOUNT, O_CLOEXEC, O_CREAT, O_PATH, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY};
use mem::MaybeUninit;
use num_traits::AsPrimitive;
use std::cmp::min;
Expand Down Expand Up @@ -185,6 +182,10 @@ impl FileAttr {
pub fn is_socket(&self) -> bool {
self.is(libc::S_IFSOCK)
}

pub fn is_whiteout(&self) -> bool {
self.is_char_device() && self.st.st_rdev == 0
}
}

const XATTR_NAME_SELINUX: &CStr = c"security.selinux";
Expand All @@ -199,7 +200,7 @@ impl FsPath {
}

pub fn create(&self, flags: i32, mode: mode_t) -> io::Result<File> {
Ok(File::from(open_fd!(self, flags, mode)?))
Ok(File::from(open_fd!(self, flags | O_CREAT, mode)?))
}

pub fn exists(&self) -> bool {
Expand Down Expand Up @@ -429,6 +430,18 @@ impl FsPath {
false
}
}



pub fn bind_mount_to(&self, path: &FsPath, ro: bool) -> io::Result<()> {
unsafe {
libc::mount(path.as_ptr(), self.as_ptr(), ptr::null(), MS_BIND | MS_REC, ptr::null()).as_os_err()?;
if ro {
libc::mount(ptr::null(), self.as_ptr(), ptr::null(), MS_REMOUNT | MS_BIND | MS_RDONLY, ptr::null()).as_os_err()?;
}
}
Ok(())
}
}

impl FsPathFollow {
Expand Down
10 changes: 5 additions & 5 deletions native/src/base/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl<T> SilentResultExt<T> for Option<T> {
pub trait ResultExt<T> {
fn log(self) -> LoggedResult<T>;
fn log_with_msg<F: FnOnce(Formatter) -> fmt::Result>(self, f: F) -> LoggedResult<T>;
fn log_ok(self);
fn log_ok(self) -> Option<T>;
}

// Internal C++ bridging logging routines
Expand Down Expand Up @@ -108,14 +108,14 @@ impl<T, R: Loggable<T>> ResultExt<T> for R {
}

#[cfg(not(debug_assertions))]
fn log_ok(self) {
self.log().ok();
fn log_ok(self) -> Option<T> {
self.log().ok()
}

#[track_caller]
#[cfg(debug_assertions)]
fn log_ok(self) {
self.do_log(LogLevel::Error, Some(Location::caller())).ok();
fn log_ok(self) -> Option<T> {
self.do_log(LogLevel::Error, Some(Location::caller())).ok()
}
}

Expand Down
4 changes: 4 additions & 0 deletions native/src/core/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#![feature(fn_traits)]
#![feature(unix_socket_ancillary_data)]
#![feature(unix_socket_peek)]
#![feature(btree_set_entry)]
#![allow(clippy::missing_safety_doc)]

use crate::ffi::SuRequest;
Expand All @@ -21,6 +22,7 @@ use std::mem::ManuallyDrop;
use std::ops::DerefMut;
use std::os::fd::FromRawFd;
use zygisk::zygisk_should_load_module;
use module::deploy_modules;

#[path = "../include/consts.rs"]
mod consts;
Expand All @@ -33,6 +35,7 @@ mod resetprop;
mod socket;
mod su;
mod zygisk;
mod module;

#[allow(clippy::needless_lifetimes)]
#[cxx::bridge]
Expand Down Expand Up @@ -239,6 +242,7 @@ pub mod ffi {
#[Self = MagiskD]
#[cxx_name = "Get"]
fn get() -> &'static MagiskD;
fn deploy_modules(module_list: &Vec<ModuleInfo>, zygisk_lib: &CxxString, magisk_path: &CxxString) -> bool;
}
unsafe extern "C++" {
#[allow(dead_code)]
Expand Down
Loading