Skip to content
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
2 changes: 1 addition & 1 deletion userspace/ksud/src/apk_sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub fn get_apk_signature(apk: &str) -> Result<(u32, String)> {
return Err(anyhow::anyhow!("Unexpected v3 signature found!",));
}

v2_signing.ok_or(anyhow::anyhow!("No signature found!"))
v2_signing.ok_or_else(|| anyhow::anyhow!("No signature found!"))
}

fn calc_cert_sha256(
Expand Down
10 changes: 5 additions & 5 deletions userspace/ksud/src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,25 @@ pub fn ensure_binaries(ignore_if_exist: bool) -> Result<()> {
// don't extract ksuinit and kernel modules
continue;
}
let asset = Asset::get(&file).ok_or(anyhow::anyhow!("asset not found: {}", file))?;
utils::ensure_binary(format!("{BINARY_DIR}{file}"), &asset.data, ignore_if_exist)?
let asset = Asset::get(&file).ok_or_else(|| anyhow::anyhow!("asset not found: {file}"))?;
utils::ensure_binary(format!("{BINARY_DIR}{file}"), &asset.data, ignore_if_exist)?;
}
Ok(())
}

pub fn copy_assets_to_file(name: &str, dst: impl AsRef<Path>) -> Result<()> {
let asset = Asset::get(name).ok_or(anyhow::anyhow!("asset not found: {}", name))?;
let asset = Asset::get(name).ok_or_else(|| anyhow::anyhow!("asset not found: {name}"))?;
std::fs::write(dst, asset.data)?;
Ok(())
}

pub fn list_supported_kmi() -> Result<Vec<String>> {
pub fn list_supported_kmi() -> std::vec::Vec<std::string::String> {
let mut list = Vec::new();
for file in Asset::iter() {
// kmi_name = "xxx_kernelsu.ko"
if let Some(kmi) = file.strip_suffix("_kernelsu.ko") {
list.push(kmi.to_string());
}
}
Ok(list)
list
}
42 changes: 22 additions & 20 deletions userspace/ksud/src/boot_patch.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![allow(clippy::ref_option, clippy::needless_pass_by_value)]
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
Expand Down Expand Up @@ -220,7 +221,7 @@ pub fn restore(
let workdir = tmpdir.path();
let magiskboot = find_magiskboot(magiskboot_path, workdir)?;

let kmi = get_current_kmi().unwrap_or_else(|_| String::from(""));
let kmi = get_current_kmi().unwrap_or_default();

let (bootimage, bootdevice) = find_boot_image(&image, &kmi, false, false, workdir, &None)?;

Expand All @@ -236,7 +237,7 @@ pub fn restore(

let mut ramdisk = workdir.join("ramdisk.cpio");
if !ramdisk.exists() {
ramdisk = workdir.join("vendor_ramdisk").join("init_boot.cpio")
ramdisk = workdir.join("vendor_ramdisk").join("init_boot.cpio");
}
if !ramdisk.exists() {
ramdisk = workdir.join("vendor_ramdisk").join("ramdisk.cpio");
Expand Down Expand Up @@ -275,7 +276,7 @@ pub fn restore(
new_boot = Some(backup_path);
from_backup = true;
} else {
println!("- Warning: no backup {backup_path:?} found!");
println!("- Warning: no backup {} found!", backup_path.display());
}

if let Err(e) = clean_backup(sha) {
Expand Down Expand Up @@ -358,7 +359,7 @@ pub fn patch(
result
}

#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments, clippy::needless_pass_by_value)]
fn do_patch(
image: Option<PathBuf>,
kernel: Option<PathBuf>,
Expand Down Expand Up @@ -418,7 +419,7 @@ fn do_patch(
);
parse_kmi_from_kernel(kernel_path, tmpdir.path())?
} else {
"".to_string()
String::new()
}
}
}
Expand Down Expand Up @@ -447,7 +448,7 @@ fn do_patch(
let name = format!("{kmi}_kernelsu.ko");
assets::copy_assets_to_file(&name, kmod_file)
.with_context(|| format!("Failed to copy {name}"))?;
};
}

let init_file = workdir.join("init");
if let Some(init) = init {
Expand All @@ -468,7 +469,7 @@ fn do_patch(

let mut ramdisk = workdir.join("ramdisk.cpio");
if !ramdisk.exists() {
ramdisk = workdir.join("vendor_ramdisk").join("init_boot.cpio")
ramdisk = workdir.join("vendor_ramdisk").join("init_boot.cpio");
}
if !ramdisk.exists() {
ramdisk = workdir.join("vendor_ramdisk").join("ramdisk.cpio");
Expand All @@ -484,15 +485,16 @@ fn do_patch(
println!("- Adding KernelSU LKM");
let is_kernelsu_patched = is_kernelsu_patched(&magiskboot, workdir, ramdisk)?;

let mut need_backup = false;
if !is_kernelsu_patched {
let need_backup = if is_kernelsu_patched {
false
} else {
// kernelsu.ko is not exist, backup init if necessary
let status = do_cpio_cmd(&magiskboot, workdir, ramdisk, "exists init");
if status.is_ok() {
do_cpio_cmd(&magiskboot, workdir, ramdisk, "mv init init.real")?;
}
need_backup = flash;
}
flash
};

do_cpio_cmd(&magiskboot, workdir, ramdisk, "add 0755 init init")?;
do_cpio_cmd(
Expand Down Expand Up @@ -681,7 +683,7 @@ fn find_boot_image(

bootimage = tmp_boot_path;
bootdevice = Some(boot_partition);
};
}
Ok((bootimage, bootdevice))
}

Expand Down Expand Up @@ -722,12 +724,12 @@ pub fn choose_boot_partition(

#[cfg(target_os = "android")]
pub fn get_slot_suffix(ota: bool) -> String {
let mut slot_suffix = utils::getprop("ro.boot.slot_suffix").unwrap_or_else(|| String::from(""));
let mut slot_suffix = utils::getprop("ro.boot.slot_suffix").unwrap_or_default();
if !slot_suffix.is_empty() && ota {
if slot_suffix == "_a" {
slot_suffix = "_b".to_string()
slot_suffix = "_b".to_string();
} else {
slot_suffix = "_a".to_string()
slot_suffix = "_a".to_string();
}
}
slot_suffix
Expand All @@ -744,8 +746,8 @@ pub fn list_available_partitions() -> Vec<String> {
let candidates = vec!["boot", "init_boot", "vendor_boot"];
candidates
.into_iter()
.filter(|name| Path::new(&format!("/dev/block/by-name/{}{}", name, slot_suffix)).exists())
.map(|s| s.to_string())
.filter(|name| Path::new(&format!("/dev/block/by-name/{name}{slot_suffix}")).exists())
.map(std::string::ToString::to_string)
.collect()
}

Expand All @@ -768,7 +770,7 @@ fn post_ota() -> Result<()> {
.stdout;
let current_slot = String::from_utf8(current_slot)?;
let current_slot = current_slot.trim();
let target_slot = if current_slot == "0" { 1 } else { 0 };
let target_slot = i32::from(current_slot == "0");

Command::new(BOOTCTL_PATH)
.arg(format!("set-active-boot-slot {target_slot}"))
Expand All @@ -779,11 +781,11 @@ fn post_ota() -> Result<()> {
let post_ota_sh = post_fs_data.join("post_ota.sh");

let sh_content = format!(
r###"
r"
{BOOTCTL_PATH} mark-boot-successful
rm -f {BOOTCTL_PATH}
rm -f /data/adb/post-fs-data.d/post_ota.sh
"###
"
);

std::fs::write(&post_ota_sh, sh_content)?;
Expand Down
42 changes: 27 additions & 15 deletions userspace/ksud/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use android_logger::Config;
#[cfg(target_os = "android")]
use log::LevelFilter;

use crate::{apk_sign, assets, debug, defs, init_event, ksucalls, module, utils};
use crate::{apk_sign, assets, debug, defs, init_event, ksucalls, module, module_config, utils};

/// KernelSU userspace cli
#[derive(Parser, Debug)]
Expand Down Expand Up @@ -465,7 +465,10 @@ pub fn run() -> Result<()> {

let result = match cli.command {
Commands::PostFsData => init_event::on_post_data_fs(),
Commands::BootCompleted => init_event::on_boot_completed(),
Commands::BootCompleted => {
init_event::on_boot_completed();
Ok(())
}

Commands::Module { command } => {
#[cfg(any(target_os = "linux", target_os = "android"))]
Expand All @@ -486,17 +489,16 @@ pub fn run() -> Result<()> {
anyhow::anyhow!("This command must be run in the context of a module")
})?;

use crate::module_config;
match command {
ModuleConfigCmd::Get { key } => {
// Use merge_configs to respect priority (temp overrides persist)
let config = module_config::merge_configs(&module_id)?;
match config.get(&key) {
Some(value) => {
println!("{}", value);
println!("{value}");
Ok(())
}
None => anyhow::bail!("Key '{}' not found", key),
None => anyhow::bail!("Key '{key}' not found"),
}
}
ModuleConfigCmd::Set { key, value, temp } => {
Expand All @@ -517,7 +519,7 @@ pub fn run() -> Result<()> {
println!("No config entries found");
} else {
for (key, value) in config {
println!("{}={}", key, value);
println!("{key}={value}");
}
}
Ok(())
Expand Down Expand Up @@ -549,7 +551,10 @@ pub fn run() -> Result<()> {
Sepolicy::Apply { file } => crate::sepolicy::apply_file(file),
Sepolicy::Check { sepolicy } => crate::sepolicy::check_rule(&sepolicy),
},
Commands::Services => init_event::on_services(),
Commands::Services => {
init_event::on_services();
Ok(())
}
Commands::Profile { command } => match command {
Profile::GetSepolicy { package } => crate::profile::get_sepolicy(package),
Profile::SetSepolicy { package, policy } => {
Expand All @@ -562,10 +567,13 @@ pub fn run() -> Result<()> {
},

Commands::Feature { command } => match command {
Feature::Get { id } => crate::feature::get_feature(id),
Feature::Set { id, value } => crate::feature::set_feature(id, value),
Feature::List => crate::feature::list_features(),
Feature::Check { id } => crate::feature::check_feature(id),
Feature::Get { id } => crate::feature::get_feature(&id),
Feature::Set { id, value } => crate::feature::set_feature(&id, value),
Feature::List => {
crate::feature::list_features();
Ok(())
}
Feature::Check { id } => crate::feature::check_feature(&id),
Feature::Load => crate::feature::load_config_and_apply(),
Feature::Save => crate::feature::save_config(),
},
Expand Down Expand Up @@ -614,8 +622,10 @@ pub fn run() -> Result<()> {
return Ok(());
}
BootInfo::SupportedKmis => {
let kmi = crate::assets::list_supported_kmi()?;
kmi.iter().for_each(|kmi| println!("{kmi}"));
let kmi = crate::assets::list_supported_kmi();
for kmi in &kmi {
println!("{kmi}");
}
return Ok(());
}
BootInfo::IsAbDevice => {
Expand All @@ -626,7 +636,7 @@ pub fn run() -> Result<()> {
return Ok(());
}
BootInfo::DefaultPartition => {
let kmi = crate::boot_patch::get_current_kmi().unwrap_or_else(|_| String::from(""));
let kmi = crate::boot_patch::get_current_kmi().unwrap_or_else(|_| String::new());
let name = crate::boot_patch::choose_boot_partition(&kmi, false, &None);
println!("{name}");
return Ok(());
Expand All @@ -638,7 +648,9 @@ pub fn run() -> Result<()> {
}
BootInfo::AvailablePartitions => {
let parts = crate::boot_patch::list_available_partitions();
parts.iter().for_each(|p| println!("{p}"));
for p in &parts {
println!("{p}");
}
return Ok(());
}
},
Expand Down
14 changes: 6 additions & 8 deletions userspace/ksud/src/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,11 @@ pub fn mark_get(pid: i32) -> Result<()> {
let result = ksucalls::mark_get(pid)?;
if pid == 0 {
bail!("Please specify a pid to get its mark status");
} else {
println!(
"Process {} mark status: {}",
pid,
if result != 0 { "marked" } else { "unmarked" }
);
}
println!(
"Process {pid} mark status: {}",
if result != 0 { "marked" } else { "unmarked" }
);
Ok(())
}

Expand All @@ -74,7 +72,7 @@ pub fn mark_set(pid: i32) -> Result<()> {
if pid == 0 {
println!("All processes marked successfully");
} else {
println!("Process {} marked successfully", pid);
println!("Process {pid} marked successfully");
}
Ok(())
}
Expand All @@ -85,7 +83,7 @@ pub fn mark_unset(pid: i32) -> Result<()> {
if pid == 0 {
println!("All processes unmarked successfully");
} else {
println!("Process {} unmarked successfully", pid);
println!("Process {pid} unmarked successfully");
}
Ok(())
}
Expand Down
Loading
Loading