Skip to content

Commit

Permalink
Merge branch 'topjohnwu:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
deep-soft authored Feb 6, 2025
2 parents 37f7b9f + b7ca73f commit 87652e4
Show file tree
Hide file tree
Showing 68 changed files with 2,448 additions and 2,202 deletions.
2 changes: 1 addition & 1 deletion README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Click the icon below to download Magisk apk.

[![](https://img.shields.io/badge/Magisk-v28.1-blue)](https://github.com/topjohnwu/Magisk/releases/tag/v28.1)
[![](https://img.shields.io/badge/Magisk%20Beta-v28.1-blue)](https://github.com/topjohnwu/Magisk/releases/tag/v28.1)
[![](https://img.shields.io/badge/Magisk-Canary-red)](https://github.com/topjohnwu/Magisk/releases/tag/canary-28101)
[![](https://img.shields.io/badge/Magisk-Canary-red)](https://github.com/topjohnwu/Magisk/releases/tag/canary-28102)

## Useful Links

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ object RebootMenu {
activity.getSystemService<PowerManager>()?.isRebootingUserspaceSupported == true) {
menu.menu.findItem(R.id.action_reboot_userspace).isVisible = true
}
if (Const.Version.isCanary()) {
if (Const.Version.atLeast_28_0()) {
menu.menu.findItem(R.id.action_reboot_safe_mode).isChecked = Config.bootloop >= 2
} else {
menu.menu.findItem(R.id.action_reboot_safe_mode).isVisible = false
Expand Down
1 change: 1 addition & 0 deletions app/core/src/main/java/com/topjohnwu/magisk/core/Const.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ object Const {

fun atLeast_24_0() = Info.env.versionCode >= 24000 || isCanary()
fun atLeast_25_0() = Info.env.versionCode >= 25000 || isCanary()
fun atLeast_28_0() = Info.env.versionCode >= 28000 || isCanary()
fun isCanary() = isCanary(Info.env.versionCode)

fun isCanary(ver: Int) = ver > 0 && ver % 100 != 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,9 @@ abstract class MagiskInstallImpl protected constructor(
if (result)
return true

Shell.cmd("rm -rf $installDir").submit()
// Not every operation initializes installDir
if (::installDir.isInitialized)
Shell.cmd("rm -rf $installDir").submit()
return false
}

Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ android.nonFinalResIds=false

# Magisk
magisk.stubVersion=40
magisk.versionCode=28101
magisk.versionCode=28102
magisk.ondkVersion=r28.2
11 changes: 4 additions & 7 deletions native/src/Android.mk
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ LOCAL_SRC_FILES := \
core/applets.cpp \
core/magisk.cpp \
core/daemon.cpp \
core/bootstages.cpp \
core/socket.cpp \
core/scripting.cpp \
core/selinux.cpp \
core/sqlite.cpp \
Expand All @@ -30,9 +28,7 @@ LOCAL_SRC_FILES := \
core/su/su.cpp \
core/su/connect.cpp \
core/su/pts.cpp \
core/su/su_daemon.cpp \
core/zygisk/entry.cpp \
core/zygisk/main.cpp \
core/zygisk/module.cpp \
core/zygisk/hook.cpp \
core/deny/cli.cpp \
Expand Down Expand Up @@ -168,6 +164,7 @@ LOCAL_SRC_FILES := \
sepolicy/policy-rs.cpp
include $(BUILD_STATIC_LIBRARY)

include src/Android-rs.mk
include src/base/Android.mk
include src/external/Android.mk
CWD := $(LOCAL_PATH)
include $(CWD)/Android-rs.mk
include $(CWD)/base/Android.mk
include $(CWD)/external/Android.mk
20 changes: 15 additions & 5 deletions native/src/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion native/src/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[workspace]
exclude = ["external"]
members = ["base", "boot", "core", "init", "sepolicy"]
members = ["base", "boot", "core", "core/derive", "init", "sepolicy"]
resolver = "2"

[workspace.dependencies]
Expand All @@ -26,6 +26,9 @@ bytemuck = "1.16"
fdt = "0.1"
const_format = "0.2"
bit-set = "0.8"
syn = "2"
quote = "1"
proc-macro2 = "1"

[workspace.dependencies.argh]
git = "https://github.com/google/argh.git"
Expand Down
51 changes: 16 additions & 35 deletions native/src/base/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
cstr, errno, error, FsPath, FsPathBuf, LibcReturn, Utf8CStr, Utf8CStrBuf, Utf8CStrBufArr,
Utf8CStrWrite,
};
use bytemuck::{bytes_of_mut, Pod};
use bytemuck::{bytes_of, bytes_of_mut, Pod};
use libc::{
c_uint, dirent, makedev, mode_t, EEXIST, ENOENT, F_OK, O_CLOEXEC, O_CREAT, O_PATH, O_RDONLY,
O_RDWR, O_TRUNC, O_WRONLY,
Expand All @@ -14,13 +14,11 @@ use std::cmp::min;
use std::ffi::CStr;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::os::fd::{AsFd, BorrowedFd, IntoRawFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::path::Path;
use std::sync::Arc;
use std::{io, mem, ptr, slice};

pub fn __open_fd_impl(path: &Utf8CStr, flags: i32, mode: mode_t) -> io::Result<OwnedFd> {
Expand Down Expand Up @@ -123,6 +121,7 @@ impl<T: BufRead> BufReadExt for T {

pub trait WriteExt {
fn write_zeros(&mut self, len: usize) -> io::Result<()>;
fn write_pod<F: Pod>(&mut self, data: &F) -> io::Result<()>;
}

impl<T: Write> WriteExt for T {
Expand All @@ -135,6 +134,10 @@ impl<T: Write> WriteExt for T {
}
Ok(())
}

fn write_pod<F: Pod>(&mut self, data: &F) -> io::Result<()> {
self.write_all(bytes_of(data))
}
}

pub struct FileAttr {
Expand Down Expand Up @@ -265,7 +268,7 @@ impl DirEntry<'_> {
}

unsafe fn open_fd(&self, flags: i32) -> io::Result<RawFd> {
self.dir.open_fd(self.d_name(), flags, 0)
self.dir.open_raw_fd(self.d_name(), flags, 0)
}

pub fn open_as_dir(&self) -> io::Result<Directory> {
Expand Down Expand Up @@ -350,10 +353,17 @@ impl Directory {
unsafe { libc::rewinddir(self.dirp) }
}

unsafe fn open_fd(&self, name: &CStr, flags: i32, mode: i32) -> io::Result<RawFd> {
unsafe fn open_raw_fd(&self, name: &CStr, flags: i32, mode: i32) -> io::Result<RawFd> {
libc::openat(self.as_raw_fd(), name.as_ptr(), flags | O_CLOEXEC, mode).check_os_err()
}

pub fn open_fd(&self, name: &Utf8CStr, flags: i32, mode: i32) -> io::Result<OwnedFd> {
unsafe {
self.open_raw_fd(name.as_cstr(), flags, mode)
.map(|fd| OwnedFd::from_raw_fd(fd))
}
}

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 Expand Up @@ -414,7 +424,7 @@ impl Directory {
} else if e.is_file() {
let mut src = e.open_as_file(O_RDONLY)?;
let mut dest = unsafe {
File::from_raw_fd(dir.open_fd(
File::from_raw_fd(dir.open_raw_fd(
e.d_name(),
O_WRONLY | O_CREAT | O_TRUNC,
0o777,
Expand Down Expand Up @@ -1030,32 +1040,3 @@ pub fn parse_mount_info(pid: &str) -> Vec<MountInfo> {
}
res
}

#[derive(Default, Clone)]
pub enum SharedFd {
#[default]
None,
Shared(Arc<OwnedFd>),
}

impl From<OwnedFd> for SharedFd {
fn from(fd: OwnedFd) -> Self {
SharedFd::Shared(Arc::new(fd))
}
}

impl SharedFd {
pub const fn new() -> Self {
SharedFd::None
}

// This is unsafe because we cannot create multiple mutable references to the same fd.
// This can only be safely used if and only if the underlying fd points to a pipe,
// and the read/write operations performed on the file involves bytes less than PIPE_BUF.
pub unsafe fn as_file(&self) -> Option<ManuallyDrop<File>> {
match self {
SharedFd::None => None,
SharedFd::Shared(arc) => Some(ManuallyDrop::new(File::from_raw_fd(arc.as_raw_fd()))),
}
}
}
2 changes: 2 additions & 0 deletions native/src/base/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use num_traits::FromPrimitive;

pub use cstr::*;
use cxx_extern::*;
pub use ffi::fork_dont_care;
pub use files::*;
pub use logging::*;
pub use misc::*;
Expand Down Expand Up @@ -42,6 +43,7 @@ pub mod ffi {
type Utf8CStrRef<'a> = &'a crate::cstr::Utf8CStr;

fn mut_u8_patch(buf: &mut [u8], from: &[u8], to: &[u8]) -> Vec<usize>;
fn fork_dont_care() -> i32;
}

extern "Rust" {
Expand Down
60 changes: 55 additions & 5 deletions native/src/base/misc.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use crate::{ffi, StrErr, Utf8CStr};
use argh::EarlyExit;
use libc::c_char;
use std::fmt::Arguments;
use std::io::Write;
use std::mem::ManuallyDrop;
use std::process::exit;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::sync::Arc;
use std::{fmt, io, slice, str};

use argh::EarlyExit;
use libc::c_char;

use crate::{ffi, StrErr, Utf8CStr};

pub fn errno() -> &'static mut i32 {
unsafe { &mut *libc::__errno() }
}
Expand Down Expand Up @@ -161,3 +162,52 @@ impl<T: Write> fmt::Write for FmtAdaptor<'_, T> {
self.0.write_fmt(args).map_err(|_| fmt::Error)
}
}

pub struct AtomicArc<T> {
ptr: AtomicPtr<T>,
}

impl<T> AtomicArc<T> {
pub fn new(arc: Arc<T>) -> AtomicArc<T> {
let raw = Arc::into_raw(arc);
Self {
ptr: AtomicPtr::new(raw as *mut _),
}
}

pub fn load(&self) -> Arc<T> {
let raw = self.ptr.load(Ordering::Acquire);
// SAFETY: the raw pointer is always created from Arc::into_raw
let arc = ManuallyDrop::new(unsafe { Arc::from_raw(raw) });
ManuallyDrop::into_inner(arc.clone())
}

fn swap_ptr(&self, raw: *const T) -> Arc<T> {
let prev = self.ptr.swap(raw as *mut _, Ordering::AcqRel);
// SAFETY: the raw pointer is always created from Arc::into_raw
unsafe { Arc::from_raw(prev) }
}

pub fn swap(&self, arc: Arc<T>) -> Arc<T> {
let raw = Arc::into_raw(arc);
self.swap_ptr(raw)
}

pub fn store(&self, arc: Arc<T>) {
// Drop the previous value
let _ = self.swap(arc);
}
}

impl<T> Drop for AtomicArc<T> {
fn drop(&mut self) {
// Drop the internal value
let _ = self.swap_ptr(std::ptr::null());
}
}

impl<T: Default> Default for AtomicArc<T> {
fn default() -> Self {
Self::new(Default::default())
}
}
12 changes: 5 additions & 7 deletions native/src/boot/cpio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -755,9 +755,9 @@ impl Display for CpioEntry {
}

pub fn cpio_commands(argc: i32, argv: *const *const c_char) -> bool {
fn inner(argc: i32, argv: *const *const c_char) -> LoggedResult<()> {
let res: LoggedResult<()> = try {
if argc < 1 {
return Err(log_err!("No arguments"));
Err(log_err!("No arguments"))?;
}

let cmds = map_args(argc, argv)?;
Expand Down Expand Up @@ -807,7 +807,7 @@ pub fn cpio_commands(argc: i32, argv: *const *const c_char) -> bool {
CpioAction::Add(Add { mode, path, file }) => cpio.add(*mode, path, file)?,
CpioAction::Extract(Extract { paths }) => {
if !paths.is_empty() && paths.len() != 2 {
return Err(log_err!("invalid arguments"));
Err(log_err!("invalid arguments"))?;
}
let mut it = paths.iter_mut();
cpio.extract(it.next(), it.next())?;
Expand All @@ -819,10 +819,8 @@ pub fn cpio_commands(argc: i32, argv: *const *const c_char) -> bool {
};
}
cpio.dump(file)?;
Ok(())
}
inner(argc, argv)
.log_with_msg(|w| w.write_str("Failed to process cpio"))
};
res.log_with_msg(|w| w.write_str("Failed to process cpio"))
.is_ok()
}

Expand Down
Loading

0 comments on commit 87652e4

Please sign in to comment.