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
This commit is contained in:
topjohnwu
2026-10-02 17:17:48 -07:00
parent 93708e5e73
commit b76d674a60
12 changed files with 183 additions and 188 deletions
+3 -2
View File
@@ -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;
+9 -2
View File
@@ -1,9 +1,7 @@
#pragma once
#include <sys/socket.h>
#include <string>
#include <atomic>
#include <functional>
#include <base.hpp>
@@ -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<typename T> requires(std::is_trivially_copyable_v<T>)
T read_any(int fd) {
T val;
+7
View File
@@ -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;
+2 -1
View File
@@ -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};
+83
View File
@@ -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<int, 2>{-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 <class ...Args>
static int exec_command(exec_t &exec, Args &&...args) {
const char *argv[] = {args..., nullptr};
exec.argv = argv;
return exec_command(exec);
}
template <class ...Args>
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 <class ...Args>
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,
+2 -2
View File
@@ -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};
+2 -1
View File
@@ -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;
+69
View File
@@ -2,6 +2,10 @@
#include <libgen.h>
#include <sys/mount.h>
#include <sys/sysmacros.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <syscall.h>
#include <sched.h>
#include <linux/input.h>
#include <map>
@@ -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;
}
+5 -3
View File
@@ -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;