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

ksud(feat): Parse KMI from boot or kernel #1914

Merged
merged 5 commits into from
Jul 26, 2024
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
46 changes: 6 additions & 40 deletions userspace/ksud/Cargo.lock

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

6 changes: 3 additions & 3 deletions userspace/ksud/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@ zip = { version = "2.1.5", features = [
"xz",
], default-features = false }
zip-extensions = "0.8"
java-properties = "2"
java-properties = { git = "https://github.com/Kernel-SU/java-properties.git", branch = "master", default-features = false }
log = "0.4"
env_logger = { version = "0.11", default-features = false }
serde = { version = "1" }
serde_json = "1"
regex = "1"
encoding_rs = "0.8"
retry = "2"
humansize = "2"
Expand All @@ -46,6 +45,7 @@ sha1 = "0.10"
tempdir = "0.3"
chrono = "0.4"
hole-punch = { git = "https://github.com/tiann/hole-punch" }
regex-lite = "0.1.6"

[target.'cfg(any(target_os = "android", target_os = "linux"))'.dependencies]
rustix = { git = "https://github.com/Kernel-SU/rustix.git", branch = "main", features = [
Expand All @@ -57,7 +57,7 @@ procfs = "0.16"
loopdev = { git = "https://github.com/Kernel-SU/loopdev" }

[target.'cfg(target_os = "android")'.dependencies]
android_logger = "0.14"
android_logger = { version = "0.14", default-features = false }

[profile.release]
strip = true
Expand Down
90 changes: 83 additions & 7 deletions userspace/ksud/src/boot_patch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use anyhow::bail;
use anyhow::ensure;
use anyhow::Context;
use anyhow::Result;
use regex_lite::Regex;
use which::which;

use crate::defs;
Expand All @@ -27,7 +28,6 @@ fn ensure_gki_kernel() -> Result<()> {

#[cfg(target_os = "android")]
pub fn get_kernel_version() -> Result<(i32, i32, i32)> {
use regex::Regex;
let uname = rustix::system::uname();
let version = uname.release().to_string_lossy();
let re = Regex::new(r"(\d+)\.(\d+)\.(\d+)")?;
Expand All @@ -52,7 +52,6 @@ pub fn get_kernel_version() -> Result<(i32, i32, i32)> {

#[cfg(target_os = "android")]
fn parse_kmi(version: &str) -> Result<String> {
use regex::Regex;
let re = Regex::new(r"(.* )?(\d+\.\d+)(\S+)?(android\d+)(.*)")?;
let cap = re
.captures(version)
Expand Down Expand Up @@ -97,6 +96,63 @@ pub fn get_current_kmi() -> Result<String> {
bail!("Unsupported platform")
}

fn parse_kmi_from_kernel(kernel: &PathBuf, workdir: &Path) -> Result<String> {
use std::fs::{copy, File};
use std::io::{BufReader, Read};
let kernel_path = workdir.join("kernel");
copy(kernel, &kernel_path).context("Failed to copy kernel")?;

let file = File::open(&kernel_path).context("Failed to open kernel file")?;
let mut reader = BufReader::new(file);
let mut buffer = Vec::new();
reader
.read_to_end(&mut buffer)
.context("Failed to read kernel file")?;

let printable_strings: Vec<&str> = buffer
.split(|&b| b == 0)
.filter_map(|slice| std::str::from_utf8(slice).ok())
.filter(|s| s.chars().all(|c| c.is_ascii_graphic() || c == ' '))
.collect();

let re =
Regex::new(r"(?:.* )?(\d+\.\d+)(?:\S+)?(android\d+)").context("Failed to compile regex")?;
for s in printable_strings {
if let Some(caps) = re.captures(s) {
if let (Some(kernel_version), Some(android_version)) = (caps.get(1), caps.get(2)) {
let kmi = format!("{}-{}", android_version.as_str(), kernel_version.as_str());
return Ok(kmi);
}
}
}
println!("- Failed to get KMI version");
bail!("Try to choose LKM manually")
}

fn parse_kmi_from_boot(magiskboot: &Path, image: &PathBuf, workdir: &Path) -> Result<String> {
let image_path = workdir.join("image");

std::fs::copy(image, &image_path).context("Failed to copy image")?;

let status = Command::new(magiskboot)
.current_dir(workdir)
.stdout(Stdio::null())
.stderr(Stdio::null())
.arg("unpack")
.arg(&image_path)
.status()
.context("Failed to execute magiskboot command")?;

if !status.success() {
bail!(
"magiskboot unpack failed with status: {:?}",
status.code().unwrap()
);
}

parse_kmi_from_kernel(&image_path, workdir)
}

fn do_cpio_cmd(magiskboot: &Path, workdir: &Path, cmd: &str) -> Result<()> {
let status = Command::new(magiskboot)
.current_dir(workdir)
Expand Down Expand Up @@ -313,10 +369,33 @@ fn do_patch(
let tmpdir = tempdir::TempDir::new("KernelSU").context("create temp dir failed")?;
let workdir = tmpdir.path();

// extract magiskboot
let magiskboot = find_magiskboot(magiskboot_path, workdir)?;

let kmi = if let Some(kmi) = kmi {
kmi
} else {
get_current_kmi().context("Unknown KMI, please choose LKM manually")?
match get_current_kmi() {
Ok(value) => value,
Err(e) => {
println!("- {}", e);
if let Some(image_path) = &image {
println!(
"- Trying to auto detect KMI version for {}",
image_path.to_str().unwrap()
);
parse_kmi_from_boot(&magiskboot, image_path, tmpdir.path())?
} else if let Some(kernel_path) = &kernel {
println!(
"- Trying to auto detect KMI version for {}",
kernel_path.to_str().unwrap()
);
parse_kmi_from_kernel(kernel_path, tmpdir.path())?
} else {
"".to_string()
}
}
}
};

let skip_init = kmi.starts_with("android12-");
Expand All @@ -329,9 +408,6 @@ fn do_patch(
// try extract magiskboot/bootctl
let _ = assets::ensure_binaries(false);

// extract magiskboot
let magiskboot = find_magiskboot(magiskboot_path, workdir)?;

if let Some(kernel) = kernel {
std::fs::copy(kernel, workdir.join("kernel")).context("copy kernel from failed")?;
}
Expand Down Expand Up @@ -558,7 +634,7 @@ fn find_boot_image(
} else {
if cfg!(not(target_os = "android")) {
println!("- Current OS is not android, refusing auto bootimage/bootdevice detection");
bail!("please specify a boot image");
bail!("Please specify a boot image");
}
let mut slot_suffix =
utils::getprop("ro.boot.slot_suffix").unwrap_or_else(|| String::from(""));
Expand Down
Loading