From b76d674a60dcaf1c7541ea8bae2a4b1987a7b71d Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Thu, 1 Oct 2026 15:47:33 -0700 Subject: [PATCH] Move daemon utilities from base to core Move utilities that are exclusively used by the daemon (core module) from base to core: - fork_dont_care, fork_no_orphan, new_daemon_thread, init_argv0, set_nice_name, and switch_mnt_ns into utils.cpp - exec_command* functions and exec_t into scripting.cpp as static functions, as scripting is their sole consumer Also remove the unused exec_command_sync overload. Assisted-by: Gemini 3.8 Flash --- native/src/base/base.cpp | 123 ------------------------------- native/src/base/include/base.hpp | 45 ----------- native/src/base/lib.rs | 10 +-- native/src/core/daemon.rs | 5 +- native/src/core/include/core.hpp | 11 ++- native/src/core/lib.rs | 7 ++ native/src/core/logging.rs | 3 +- native/src/core/scripting.cpp | 83 +++++++++++++++++++++ native/src/core/su/connect.rs | 4 +- native/src/core/thread.rs | 3 +- native/src/core/utils.cpp | 69 +++++++++++++++++ native/src/core/zygisk/daemon.rs | 8 +- 12 files changed, 183 insertions(+), 188 deletions(-) diff --git a/native/src/base/base.cpp b/native/src/base/base.cpp index 3ba52bb53..a1d555003 100644 --- a/native/src/base/base.cpp +++ b/native/src/base/base.cpp @@ -1,9 +1,6 @@ -#include -#include #include #include #include -#include #include #include @@ -43,106 +40,6 @@ rust::Vec mut_u8_patch(MutByteSlice buf, ByteSlice from, ByteSlice to) { return data.patch(from, to); } -int fork_dont_care() { - if (int pid = xfork()) { - waitpid(pid, nullptr, 0); - return pid; - } else if (xfork()) { - exit(0); - } - return 0; -} - -int fork_no_orphan() { - int pid = xfork(); - if (pid) - return pid; - prctl(PR_SET_PDEATHSIG, SIGKILL); - if (getppid() == 1) - exit(1); - return 0; -} - -int exec_command(exec_t &exec) { - auto pipefd = array{-1, -1}; - int outfd = -1; - - if (exec.fd == -1) { - if (xpipe2(pipefd, O_CLOEXEC) == -1) - return -1; - outfd = pipefd[1]; - } else if (exec.fd >= 0) { - outfd = exec.fd; - } - - int pid = exec.fork(); - if (pid < 0) { - close(pipefd[0]); - close(pipefd[1]); - return -1; - } else if (pid) { - if (exec.fd == -1) { - exec.fd = pipefd[0]; - close(pipefd[1]); - } - return pid; - } - - // Unblock all signals - sigset_t set; - sigfillset(&set); - pthread_sigmask(SIG_UNBLOCK, &set, nullptr); - - if (outfd >= 0) { - xdup2(outfd, STDOUT_FILENO); - if (exec.err) - xdup2(outfd, STDERR_FILENO); - close(outfd); - } - - // Call the pre-exec callback - if (exec.pre_exec) - exec.pre_exec(); - - execve(exec.argv[0], (char **) exec.argv, environ); - PLOGE("execve %s", exec.argv[0]); - exit(-1); -} - -int exec_command_sync(exec_t &exec) { - int pid = exec_command(exec); - if (pid < 0) - return -1; - int status; - waitpid(pid, &status, 0); - return WEXITSTATUS(status); -} - -int new_daemon_thread(thread_entry entry, void *arg) { - pthread_t thread; - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - errno = pthread_create(&thread, &attr, entry, arg); - if (errno) { - PLOGE("pthread_create"); - } - return errno; -} - -static char *argv0; -static size_t name_len; -void init_argv0(int argc, char **argv) { - argv0 = argv[0]; - name_len = (argv[argc - 1] - argv[0]) + strlen(argv[argc - 1]) + 1; -} - -void set_nice_name(Utf8CStr name) { - memset(argv0, 0, name_len); - strscpy(argv0, name.c_str(), name_len); - prctl(PR_SET_NAME, name.c_str()); -} - template static T parse_num(string_view s) { T val = 0; @@ -175,26 +72,6 @@ uint32_t parse_uint32_hex(string_view s) { return parse_num(s); } -int switch_mnt_ns(int pid) { - int ret = -1; - int fd = syscall(__NR_pidfd_open, pid, 0); - if (fd > 0) { - ret = setns(fd, CLONE_NEWNS); - close(fd); - } - if (ret < 0) { - char mnt[32]; - ssprintf(mnt, sizeof(mnt), "/proc/%d/ns/mnt", pid); - fd = open(mnt, O_RDONLY); - if (fd < 0) return 1; // Maybe process died.. - - // Switch to its namespace - ret = xsetns(fd, 0); - close(fd); - } - return ret; -} - string &replace_all(string &str, string_view from, string_view to) { size_t pos = 0; while((pos = str.find(from, pos)) != string::npos) { diff --git a/native/src/base/include/base.hpp b/native/src/base/include/base.hpp index aec25a172..7f4b558cd 100644 --- a/native/src/base/include/base.hpp +++ b/native/src/base/include/base.hpp @@ -188,9 +188,6 @@ rust::Vec mut_u8_patch(MutByteSlice buf, ByteSlice from, ByteSlice to); uint32_t parse_uint32_hex(std::string_view s); int parse_int(std::string_view s); -using thread_entry = void *(*)(void *); -extern "C" int new_daemon_thread(thread_entry entry, void *arg = nullptr); - static inline std::string rtrim(std::string &&s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch) && ch != '\0'; @@ -198,11 +195,6 @@ static inline std::string rtrim(std::string &&s) { return std::move(s); } -int fork_dont_care(); -int fork_no_orphan(); -void init_argv0(int argc, char **argv); -void set_nice_name(Utf8CStr name); -int switch_mnt_ns(int pid); std::string &replace_all(std::string &str, std::string_view from, std::string_view to); std::vector split(std::string_view s, std::string_view delims); @@ -219,43 +211,6 @@ extern "C" size_t strscpy(char *dest, const char *src, size_t size); #define snprintf __use_ssprintf_instead__ #define strlcpy __use_strscpy_instead__ -struct exec_t { - bool err = false; - int fd = -2; - void (*pre_exec)() = nullptr; - int (*fork)() = xfork; - const char **argv = nullptr; -}; - -int exec_command(exec_t &exec); -template -int exec_command(exec_t &exec, Args &&...args) { - const char *argv[] = {args..., nullptr}; - exec.argv = argv; - return exec_command(exec); -} -int exec_command_sync(exec_t &exec); -template -int exec_command_sync(exec_t &exec, Args &&...args) { - const char *argv[] = {args..., nullptr}; - exec.argv = argv; - return exec_command_sync(exec); -} -template -int exec_command_sync(Args &&...args) { - exec_t exec; - return exec_command_sync(exec, args...); -} -template -void exec_command_async(Args &&...args) { - const char *argv[] = {args..., nullptr}; - exec_t exec { - .fork = fork_dont_care, - .argv = argv, - }; - exec_command(exec); -} - template constexpr auto operator+(T e) noexcept -> std::enable_if_t::value, std::underlying_type_t> { diff --git a/native/src/base/lib.rs b/native/src/base/lib.rs index 8b4d9f187..130af8bce 100644 --- a/native/src/base/lib.rs +++ b/native/src/base/lib.rs @@ -10,7 +10,7 @@ pub use cstr::{ use cxx_extern::*; pub use derive; pub use dir::*; -pub use ffi::{Utf8CStrRef, fork_dont_care, set_nice_name}; +pub use ffi::Utf8CStrRef; pub use files::*; pub use logging::*; pub use misc::*; @@ -46,8 +46,6 @@ mod ffi { type Utf8CStrRef<'a> = &'a crate::cstr::Utf8CStr; fn mut_u8_patch(buf: &mut [u8], from: &[u8], to: &[u8]) -> Vec; - fn fork_dont_care() -> i32; - fn set_nice_name(name: Utf8CStrRef); type FnBoolStrStr; fn call(self: &FnBoolStrStr, key: &str, value: &str) -> bool; @@ -77,9 +75,3 @@ mod ffi { } } -// In Rust, we do not want to deal with raw pointers, so we change the -// signature of all *mut c_void to usize for new_daemon_thread. -pub type ThreadEntry = extern "C" fn(usize) -> usize; -unsafe extern "C" { - pub fn new_daemon_thread(entry: ThreadEntry, arg: usize); -} diff --git a/native/src/core/daemon.rs b/native/src/core/daemon.rs index d493fb7a3..d6a584f26 100644 --- a/native/src/core/daemon.rs +++ b/native/src/core/daemon.rs @@ -5,7 +5,8 @@ use crate::consts::{ }; use crate::db::Sqlite3; use crate::ffi::{ - ModuleInfo, RequestCode, RespondCode, denylist_handler, get_magisk_tmp, scan_deny_apps, + ModuleInfo, RequestCode, RespondCode, denylist_handler, fork_dont_care, get_magisk_tmp, + scan_deny_apps, set_nice_name, }; use crate::logging::{android_logging, magisk_logging, setup_logfile, start_log_daemon}; use crate::module::remove_modules; @@ -19,7 +20,7 @@ use crate::zygisk::ZygiskState; use base::const_format::concatcp; use base::{ AtomicArc, BufReadExt, FileAttr, FsPathBuilder, LoggedResult, ReadExt, ResultExt, Utf8CStr, - Utf8CStrBuf, WriteExt, cstr, fork_dont_care, info, libc, log_err, set_nice_name, + Utf8CStrBuf, WriteExt, cstr, info, libc, log_err, }; use nix::fcntl::OFlag; use nix::mount::MsFlags; diff --git a/native/src/core/include/core.hpp b/native/src/core/include/core.hpp index ee42f1ae4..c792ee15d 100644 --- a/native/src/core/include/core.hpp +++ b/native/src/core/include/core.hpp @@ -1,9 +1,7 @@ #pragma once -#include #include #include -#include #include @@ -33,6 +31,15 @@ struct ModuleInfo; const char *get_magisk_tmp(); void unlock_blocks(); bool check_key_combo(); +int fork_dont_care(); +int fork_no_orphan(); +int switch_mnt_ns(int pid); +void init_argv0(int argc, char **argv); +void set_nice_name(Utf8CStr name); + +using thread_entry = void *(*)(void *); +extern "C" int new_daemon_thread(thread_entry entry, void *arg = nullptr); + template requires(std::is_trivially_copyable_v) T read_any(int fd) { T val; diff --git a/native/src/core/lib.rs b/native/src/core/lib.rs index 44459966b..b801da246 100644 --- a/native/src/core/lib.rs +++ b/native/src/core/lib.rs @@ -25,6 +25,11 @@ use std::os::fd::FromRawFd; use su::{get_pty_num, pump_tty}; use zygisk::zygisk_should_load_module; +pub type ThreadEntry = extern "C" fn(usize) -> usize; +unsafe extern "C" { + pub fn new_daemon_thread(entry: ThreadEntry, arg: usize); +} + mod bootstages; #[path = "../include/consts.rs"] mod consts; @@ -150,6 +155,8 @@ pub mod ffi { fn resolve_preinit_dir(base_dir: Utf8CStrRef) -> String; fn check_key_combo() -> bool; fn unlock_blocks(); + fn fork_dont_care() -> i32; + fn set_nice_name(name: Utf8CStrRef); fn update_deny_flags(uid: i32, process: &str, flags: &mut u32); fn initialize_denylist(); fn switch_mnt_ns(pid: i32) -> i32; diff --git a/native/src/core/logging.rs b/native/src/core/logging.rs index 9f8142d75..554cdb941 100644 --- a/native/src/core/logging.rs +++ b/native/src/core/logging.rs @@ -1,10 +1,11 @@ use crate::consts::{LOG_PIPE, LOGFILE}; use crate::ffi::get_magisk_tmp; use crate::logging::LogFile::{Actual, Buffer}; +use crate::new_daemon_thread; use base::const_format::concatcp; use base::{ FsPathBuilder, LogLevel, LoggedResult, ReadExt, ResultExt, Utf8CStr, Utf8CStrBuf, WriteExt, - cstr, libc, new_daemon_thread, raw_cstr, update_logger, + cstr, libc, raw_cstr, update_logger, }; use bytemuck::{Pod, Zeroable, bytes_of, write_zeroes}; use libc::{PIPE_BUF, c_char, localtime_r, sigtimedwait, time_t, timespec, tm}; diff --git a/native/src/core/scripting.cpp b/native/src/core/scripting.cpp index 7db172d45..98b74e3d3 100644 --- a/native/src/core/scripting.cpp +++ b/native/src/core/scripting.cpp @@ -29,6 +29,89 @@ static void set_script_env() { setenv("ZYGISK_ENABLED", "1", 1); }; +struct exec_t { + bool err = false; + int fd = -2; + void (*pre_exec)() = nullptr; + int (*fork)() = xfork; + const char **argv = nullptr; +}; + +static int exec_command(exec_t &exec) { + auto pipefd = array{-1, -1}; + int outfd = -1; + + if (exec.fd == -1) { + if (xpipe2(pipefd, O_CLOEXEC) == -1) + return -1; + outfd = pipefd[1]; + } else if (exec.fd >= 0) { + outfd = exec.fd; + } + + int pid = exec.fork(); + if (pid < 0) { + close(pipefd[0]); + close(pipefd[1]); + return -1; + } else if (pid) { + if (exec.fd == -1) { + exec.fd = pipefd[0]; + close(pipefd[1]); + } + return pid; + } + + // Unblock all signals + sigset_t set; + sigfillset(&set); + pthread_sigmask(SIG_UNBLOCK, &set, nullptr); + + if (outfd >= 0) { + xdup2(outfd, STDOUT_FILENO); + if (exec.err) + xdup2(outfd, STDERR_FILENO); + close(outfd); + } + + // Call the pre-exec callback + if (exec.pre_exec) + exec.pre_exec(); + + execve(exec.argv[0], (char **) exec.argv, environ); + PLOGE("execve %s", exec.argv[0]); + exit(-1); +} + +template +static int exec_command(exec_t &exec, Args &&...args) { + const char *argv[] = {args..., nullptr}; + exec.argv = argv; + return exec_command(exec); +} + +template +static int exec_command_sync(exec_t &exec, Args &&...args) { + const char *argv[] = {args..., nullptr}; + exec.argv = argv; + int pid = exec_command(exec); + if (pid < 0) + return -1; + int status; + waitpid(pid, &status, 0); + return WEXITSTATUS(status); +} + +template +static void exec_command_async(Args &&...args) { + const char *argv[] = {args..., nullptr}; + exec_t exec { + .fork = fork_dont_care, + .argv = argv, + }; + exec_command(exec); +} + void exec_script(Utf8CStr script) { exec_t exec { .pre_exec = set_script_env, diff --git a/native/src/core/su/connect.rs b/native/src/core/su/connect.rs index 87b5a50f0..3ce1b6620 100644 --- a/native/src/core/su/connect.rs +++ b/native/src/core/su/connect.rs @@ -2,11 +2,11 @@ use super::SuInfo; use super::db::RootSettings; use crate::consts::{INTERNAL_DIR, MAGISK_FILE_CON}; use crate::daemon::to_user_id; -use crate::ffi::{SuPolicy, SuRequest, get_magisk_tmp}; +use crate::ffi::{SuPolicy, SuRequest, fork_dont_care, get_magisk_tmp}; use crate::socket::IpcRead; use ExtraVal::{Bool, Int, IntList, Str}; use base::{ - BytesExt, FileAttr, LibcReturn, LoggedResult, ResultExt, Utf8CStrBuf, cstr, error, fork_dont_care, + BytesExt, FileAttr, LibcReturn, LoggedResult, ResultExt, Utf8CStrBuf, cstr, error, }; use nix::fcntl::OFlag; use nix::poll::{PollFd, PollFlags, PollTimeout}; diff --git a/native/src/core/thread.rs b/native/src/core/thread.rs index 277c08302..586cae65c 100644 --- a/native/src/core/thread.rs +++ b/native/src/core/thread.rs @@ -1,4 +1,5 @@ -use base::{ResultExt, new_daemon_thread}; +use crate::new_daemon_thread; +use base::ResultExt; use nix::sys::signal::SigSet; use nix::unistd::{getpid, gettid}; use std::sync::LazyLock; diff --git a/native/src/core/utils.cpp b/native/src/core/utils.cpp index 2a2f14bb6..2fc3bfbc4 100644 --- a/native/src/core/utils.cpp +++ b/native/src/core/utils.cpp @@ -2,6 +2,10 @@ #include #include #include +#include +#include +#include +#include #include #include @@ -107,3 +111,68 @@ bool check_key_combo() { LOGD("KEY_VOLUMEDOWN detected: enter safe mode\n"); return true; } + +int fork_dont_care() { + if (int pid = xfork()) { + waitpid(pid, nullptr, 0); + return pid; + } else if (xfork()) { + exit(0); + } + return 0; +} + +int fork_no_orphan() { + int pid = xfork(); + if (pid) + return pid; + prctl(PR_SET_PDEATHSIG, SIGKILL); + if (getppid() == 1) + exit(1); + return 0; +} + +int new_daemon_thread(thread_entry entry, void *arg) { + pthread_t thread; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + errno = pthread_create(&thread, &attr, entry, arg); + if (errno) { + PLOGE("pthread_create"); + } + return errno; +} + +static char *argv0; +static size_t name_len; +void init_argv0(int argc, char **argv) { + argv0 = argv[0]; + name_len = (argv[argc - 1] - argv[0]) + strlen(argv[argc - 1]) + 1; +} + +void set_nice_name(Utf8CStr name) { + memset(argv0, 0, name_len); + strscpy(argv0, name.c_str(), name_len); + prctl(PR_SET_NAME, name.c_str()); +} + +int switch_mnt_ns(int pid) { + int ret = -1; + int fd = syscall(__NR_pidfd_open, pid, 0); + if (fd > 0) { + ret = setns(fd, CLONE_NEWNS); + close(fd); + } + if (ret < 0) { + char mnt[32]; + ssprintf(mnt, sizeof(mnt), "/proc/%d/ns/mnt", pid); + fd = open(mnt, O_RDONLY); + if (fd < 0) return 1; // Maybe process died.. + + // Switch to its namespace + ret = xsetns(fd, 0); + close(fd); + } + return ret; +} diff --git a/native/src/core/zygisk/daemon.rs b/native/src/core/zygisk/daemon.rs index 86956acc0..23af05341 100644 --- a/native/src/core/zygisk/daemon.rs +++ b/native/src/core/zygisk/daemon.rs @@ -1,12 +1,14 @@ use crate::consts::MODULEROOT; use crate::daemon::{MagiskD, to_user_id}; -use crate::ffi::{ZygiskRequest, ZygiskStateFlags, get_magisk_tmp, update_deny_flags}; +use crate::ffi::{ + ZygiskRequest, ZygiskStateFlags, fork_dont_care, get_magisk_tmp, update_deny_flags, +}; use crate::resetprop::{get_prop, set_prop}; use crate::socket::{IpcRead, UnixSocketExt}; use base::libc::STDOUT_FILENO; use base::{ - Directory, FsPathBuilder, LoggedResult, ResultExt, Utf8CStr, WriteExt, cstr, fork_dont_care, - libc, log_err, raw_cstr, warn, + Directory, FsPathBuilder, LoggedResult, ResultExt, Utf8CStr, WriteExt, cstr, libc, log_err, + raw_cstr, warn, }; use nix::fcntl::OFlag; use std::fmt::Write;