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

Move MagiskInit to Rust #8743

Merged
merged 16 commits into from
Feb 14, 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
3 changes: 1 addition & 2 deletions native/src/Android.mk
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,17 @@ LOCAL_STATIC_LIBRARIES := \
libinit-rs

LOCAL_SRC_FILES := \
init/init.cpp \
init/mount.cpp \
init/rootdir.cpp \
init/getinfo.cpp \
init/twostage.cpp \
init/selinux.cpp \
init/init-rs.cpp

LOCAL_LDFLAGS := -static

ifdef B_CRT0
LOCAL_STATIC_LIBRARIES += crt0
LOCAL_LDFLAGS += -Wl,--defsym=vfprintf=tiny_vfprintf
endif

include $(BUILD_EXECUTABLE)
Expand Down
3 changes: 2 additions & 1 deletion native/src/base/include/base.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@
#include "../base-rs.hpp"

using rust::xpipe2;
using rust::fd_path;
using rust::fd_path;
using kv_pairs = std::vector<std::pair<std::string, std::string>>;
12 changes: 12 additions & 0 deletions native/src/base/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +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);
}

// Internal C++ bridging logging routines
Expand Down Expand Up @@ -95,6 +96,17 @@ impl<T, R: Loggable<T>> ResultExt<T> for R {
self.do_log(LogLevel::Error, Some(Location::caller()))
}

#[track_caller]
#[cfg(debug_assertions)]
fn log_ok(self) {
self.log().ok();
}

#[cfg(not(debug_assertions))]
fn log_ok(self) {
self.log().ok();
}

#[cfg(not(debug_assertions))]
fn log_with_msg<F: FnOnce(Formatter) -> fmt::Result>(self, f: F) -> LoggedResult<T> {
self.do_log_msg(LogLevel::Error, None, f)
Expand Down
8 changes: 4 additions & 4 deletions native/src/core/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ impl MagiskD {
let secure_dir = FsPath::from(cstr!(SECURE_DIR));
if !secure_dir.exists() {
if self.sdk_int < 24 {
secure_dir.mkdir(0o700).log().ok();
secure_dir.mkdir(0o700).log_ok();
} else {
error!("* {} is not present, abort", SECURE_DIR);
return true;
Expand Down Expand Up @@ -137,7 +137,7 @@ impl MagiskD {
info!("* Safe mode triggered");
// Disable all modules and zygisk so next boot will be clean
disable_modules();
self.set_db_setting(DbEntryKey::ZygiskConfig, 0).log().ok();
self.set_db_setting(DbEntryKey::ZygiskConfig, 0).log_ok();
return true;
}

Expand Down Expand Up @@ -169,12 +169,12 @@ impl MagiskD {
info!("** boot-complete triggered");

// Reset the bootloop counter once we have boot-complete
self.set_db_setting(DbEntryKey::BootloopCount, 0).log().ok();
self.set_db_setting(DbEntryKey::BootloopCount, 0).log_ok();

// At this point it's safe to create the folder
let secure_dir = FsPath::from(cstr!(SECURE_DIR));
if !secure_dir.exists() {
secure_dir.mkdir(0o700).log().ok();
secure_dir.mkdir(0o700).log_ok();
}

self.ensure_manager();
Expand Down
2 changes: 1 addition & 1 deletion native/src/core/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ impl MagiskD {
out.push('=');
out.push_str(values.get_text(i as i32));
}
writer.write_encodable(&out).log().ok();
writer.write_encodable(&out).log_ok();
};
self.db_exec_with_rows(&sql, &[], &mut output_fn);
writer.write_encodable("").log()
Expand Down
4 changes: 2 additions & 2 deletions native/src/core/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,11 +465,11 @@ impl MagiskD {
if let Ok(mut fd) = apk.open(O_RDONLY | O_CLOEXEC) {
info.trusted_cert = read_certificate(&mut fd, MAGISK_VER_CODE);
// Seek the fd back to start
fd.seek(SeekFrom::Start(0)).log().ok();
fd.seek(SeekFrom::Start(0)).log_ok();
info.stub_apk_fd = Some(fd);
}

apk.remove().log().ok();
apk.remove().log_ok();
}

pub fn get_manager_uid(&self, user: i32) -> i32 {
Expand Down
69 changes: 14 additions & 55 deletions native/src/init/getinfo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -118,67 +118,57 @@ static bool check_key_combo() {
return false;
}

void BootConfig::set(const kv_pairs &kv) {
void BootConfig::set(const kv_pairs &kv) noexcept {
for (const auto &[key, value] : kv) {
if (key == "androidboot.slot_suffix") {
// Many Amlogic devices are A-only but have slot_suffix...
if (value == "normal") {
LOGW("Skip invalid androidboot.slot_suffix=[normal]\n");
continue;
}
strscpy(slot, value.data(), sizeof(slot));
strscpy(slot.data(), value.data(), slot.size());
} else if (key == "androidboot.slot") {
slot[0] = '_';
strscpy(slot + 1, value.data(), sizeof(slot) - 1);
strscpy(slot.data() + 1, value.data(), slot.size() - 1);
} else if (key == "skip_initramfs") {
skip_initramfs = true;
} else if (key == "androidboot.force_normal_boot") {
force_normal_boot = !value.empty() && value[0] == '1';
} else if (key == "rootwait") {
rootwait = true;
} else if (key == "androidboot.android_dt_dir") {
strscpy(dt_dir, value.data(), sizeof(dt_dir));
strscpy(dt_dir.data(), value.data(), dt_dir.size());
} else if (key == "androidboot.hardware") {
strscpy(hardware, value.data(), sizeof(hardware));
strscpy(hardware.data(), value.data(), hardware.size());
} else if (key == "androidboot.hardware.platform") {
strscpy(hardware_plat, value.data(), sizeof(hardware_plat));
strscpy(hardware_plat.data(), value.data(), hardware_plat.size());
} else if (key == "androidboot.fstab_suffix") {
strscpy(fstab_suffix, value.data(), sizeof(fstab_suffix));
strscpy(fstab_suffix.data(), value.data(), fstab_suffix.size());
} else if (key == "qemu") {
emulator = true;
} else if (key == "androidboot.partition_map") {
// androidboot.partition_map allows mapping a partition name to a raw block device.
// For example, "androidboot.partition_map=vdb,metadata;vdc,userdata" maps
// "vdb" to "metadata", and "vdc" to "userdata".
// https://android.googlesource.com/platform/system/core/+/refs/heads/android13-release/init/devices.cpp#191
partition_map = parse_partition_map(value);
for (const auto &[k, v]: parse_partition_map(value)) {
partition_map.emplace_back(k, v);
}
}
}
}

void BootConfig::print() {
LOGD("skip_initramfs=[%d]\n", skip_initramfs);
LOGD("force_normal_boot=[%d]\n", force_normal_boot);
LOGD("rootwait=[%d]\n", rootwait);
LOGD("slot=[%s]\n", slot);
LOGD("dt_dir=[%s]\n", dt_dir);
LOGD("fstab_suffix=[%s]\n", fstab_suffix);
LOGD("hardware=[%s]\n", hardware);
LOGD("hardware.platform=[%s]\n", hardware_plat);
LOGD("emulator=[%d]\n", emulator);
}

#define read_dt(name, key) \
ssprintf(file_name, sizeof(file_name), "%s/" name, dt_dir); \
ssprintf(file_name, sizeof(file_name), "%s/" name, dt_dir.data()); \
if (access(file_name, R_OK) == 0) { \
string data = full_read(file_name); \
if (!data.empty()) { \
data.pop_back(); \
strscpy(key, data.data(), sizeof(key)); \
strscpy(key.data(), data.data(), key.size()); \
} \
}

void BootConfig::init() {
void BootConfig::init() noexcept {
set(parse_cmdline(full_read("/proc/cmdline")));
set(parse_bootconfig(full_read("/proc/bootconfig")));

Expand All @@ -191,7 +181,7 @@ void BootConfig::init() {
});

if (dt_dir[0] == '\0')
strscpy(dt_dir, DEFAULT_DT_DIR, sizeof(dt_dir));
strscpy(dt_dir.data(), DEFAULT_DT_DIR, dt_dir.size());

char file_name[128];
read_dt("fstab_suffix", fstab_suffix)
Expand All @@ -201,34 +191,3 @@ void BootConfig::init() {
LOGD("Device config:\n");
print();
}

bool check_two_stage() {
if (access("/first_stage_ramdisk", F_OK) == 0)
return true;
if (access("/second_stage_resources", F_OK) == 0)
return true;
if (access("/system/bin/init", F_OK) == 0)
return true;
// Use the apex folder to determine whether 2SI (Android 10+)
if (access("/apex", F_OK) == 0)
return true;
// If we still have no indication, parse the original init and see what's up
mmap_data init(backup_init());
return init.contains("selinux_setup");
}

static void unxz_init(const char *init_xz, const char *init) {
LOGD("unxz %s -> %s\n", init_xz, init);
int fd = xopen(init, O_WRONLY | O_CREAT, 0777);
fd_stream ch(fd);
unxz(ch, mmap_data{init_xz});
close(fd);
clone_attr(init_xz, init);
unlink(init_xz);
}

const char *backup_init() {
if (access("/.backup/init.xz", F_OK) == 0)
unxz_init("/.backup/init.xz", "/.backup/init");
return "/.backup/init";
}
38 changes: 38 additions & 0 deletions native/src/init/getinfo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use crate::ffi::{BootConfig, MagiskInit};
use base::{cstr, debug, BytesExt, FsPath, MappedFile, Utf8CStr};
use std::ffi::CStr;

impl BootConfig {
pub(crate) fn print(&self) {
debug!("skip_initramfs=[{}]", self.skip_initramfs);
debug!("force_normal_boot=[{}]", self.force_normal_boot);
debug!("rootwait=[{}]", self.rootwait);
unsafe {
debug!("slot=[{:?}]", CStr::from_ptr(self.slot.as_ptr()));
debug!("dt_dir=[{:?}]", CStr::from_ptr(self.dt_dir.as_ptr()));
debug!(
"fstab_suffix=[{:?}]",
CStr::from_ptr(self.fstab_suffix.as_ptr())
);
debug!("hardware=[{:?}]", CStr::from_ptr(self.hardware.as_ptr()));
debug!(
"hardware.platform=[{:?}]",
CStr::from_ptr(self.hardware_plat.as_ptr())
);
}
debug!("emulator=[{}]", self.emulator);
debug!("partition_map=[{:?}]", self.partition_map);
}
}

impl MagiskInit {
pub(crate) fn check_two_stage(&self) -> bool {
FsPath::from(cstr!("/first_stage_ramdisk")).exists() ||
FsPath::from(cstr!("/second_stage_resources")).exists() ||
FsPath::from(cstr!("/system/bin/init")).exists() ||
// Use the apex folder to determine whether 2SI (Android 10+)
FsPath::from(cstr!("/apex")).exists() ||
// If we still have no indication, parse the original init and see what's up
MappedFile::open(unsafe { Utf8CStr::from_ptr_unchecked(self.backup_init()) }).map(|map| map.contains(b"selinux_setup")).unwrap_or(false)
}
}
Loading
Loading