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

Port more code into Rust #8697

Merged
merged 6 commits into from
Jan 10, 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
9 changes: 6 additions & 3 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,6 @@ def run_ndk_build(cmds: list):


def build_cpp_src(targets: set):
dump_flag_header()

cmds = []
clean = False

Expand Down Expand Up @@ -336,7 +334,11 @@ def dump_flag_header():
flag_txt += f"#define MAGISK_DEBUG {0 if args.release else 1}\n"

native_gen_path.mkdir(mode=0o755, parents=True, exist_ok=True)
write_if_diff(Path(native_gen_path, "flags.h"), flag_txt)
write_if_diff(native_gen_path / "flags.h", flag_txt)

rust_flag_txt = f'pub const MAGISK_VERSION: &str = "{config["version"]}";\n'
rust_flag_txt += f'pub const MAGISK_VER_CODE: i32 = {config["versionCode"]};\n'
write_if_diff(native_gen_path / "flags.rs", rust_flag_txt)


def build_native():
Expand All @@ -363,6 +365,7 @@ def build_native():
if ccache := shutil.which("ccache"):
os.environ["NDK_CCACHE"] = ccache

dump_flag_header()
build_rust_src(targets)
build_cpp_src(targets)

Expand Down
1 change: 0 additions & 1 deletion native/src/Android.mk
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ LOCAL_SRC_FILES := \
core/daemon.cpp \
core/bootstages.cpp \
core/socket.cpp \
core/package.cpp \
core/scripting.cpp \
core/selinux.cpp \
core/sqlite.cpp \
Expand Down
16 changes: 16 additions & 0 deletions native/src/Cargo.lock

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

1 change: 1 addition & 0 deletions native/src/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ der = "0.8.0-rc.1"
bytemuck = "1.16"
fdt = "0.1"
const_format = "0.2"
bit-set = "0.8"

[workspace.dependencies.argh]
git = "https://github.com/google/argh.git"
Expand Down
55 changes: 42 additions & 13 deletions native/src/base/files.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
use crate::cxx_extern::readlinkat_for_cxx;
use crate::{
cstr, errno, error, FsPath, FsPathBuf, LibcReturn, Utf8CStr, Utf8CStrBuf, Utf8CStrBufArr,
Utf8CStrWrite,
};
use bytemuck::{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,
};
use mem::MaybeUninit;
use num_traits::AsPrimitive;
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};

use bytemuck::{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,
};
use num_traits::AsPrimitive;

use crate::cxx_extern::readlinkat_for_cxx;
use crate::{
cstr, errno, error, FsPath, FsPathBuf, LibcReturn, Utf8CStr, Utf8CStrBuf, Utf8CStrBufArr,
Utf8CStrWrite,
};

pub fn __open_fd_impl(path: &Utf8CStr, flags: i32, mode: mode_t) -> io::Result<OwnedFd> {
unsafe {
let fd = libc::open(path.as_ptr(), flags, mode as c_uint).check_os_err()?;
Expand Down Expand Up @@ -1030,3 +1030,32 @@ 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()))),
}
}
}
5 changes: 5 additions & 0 deletions native/src/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ edition = "2021"
crate-type = ["staticlib"]
path = "lib.rs"

[features]
default = ["check-signature"]
check-signature = []

[build-dependencies]
cxx-gen = { workspace = true }
pb-rs = { workspace = true }
Expand All @@ -19,3 +23,4 @@ num-derive = { workspace = true }
quick-protobuf = { workspace = true }
bytemuck = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
bit-set = { workspace = true }
148 changes: 0 additions & 148 deletions native/src/core/cert.rs

This file was deleted.

24 changes: 3 additions & 21 deletions native/src/core/daemon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ static void handle_request_async(int client, int code, const sock_cred &cred) {
break;
case +RequestCode::ZYGOTE_RESTART:
LOGI("** zygote restarted\n");
prune_su_access();
MagiskD().prune_su_access();
scan_deny_apps();
reset_zygisk(false);
close(client);
Expand Down Expand Up @@ -183,7 +183,7 @@ static void handle_request_sync(int client, int code) {
write_int(client, MAGISK_VER_CODE);
break;
case +RequestCode::START_DAEMON:
MagiskD().setup_logfile();
setup_logfile();
break;
case +RequestCode::STOP_DAEMON: {
// Unmount all overlays
Expand Down Expand Up @@ -328,8 +328,7 @@ static void daemon_entry() {
setcon(MAGISK_PROC_CON);

rust::daemon_entry();

LOGI(NAME_WITH_VER(Magisk) " daemon started\n");
SDK_INT = MagiskD().sdk_int();

// Escape from cgroup
int pid = getpid();
Expand All @@ -343,23 +342,6 @@ static void daemon_entry() {
// Get self stat
xstat("/proc/self/exe", &self_st);

// Get API level
parse_prop_file("/system/build.prop", [](auto key, auto val) -> bool {
if (key == "ro.build.version.sdk") {
SDK_INT = parse_int(val);
return false;
}
return true;
});
if (SDK_INT < 0) {
// In case some devices do not store this info in build.prop, fallback to getprop
auto sdk = get_prop("ro.build.version.sdk");
if (!sdk.empty()) {
SDK_INT = parse_int(sdk);
}
}
LOGI("* Device API level: %d\n", SDK_INT);

// Samsung workaround #7887
if (access("/system_ext/app/mediatek-res/mediatek-res.apk", F_OK) == 0) {
set_prop("ro.vendor.mtk_model", "0");
Expand Down
Loading
Loading