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

Replace rust inner functions to try blocks #8749

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
12 changes: 5 additions & 7 deletions native/src/boot/cpio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -755,9 +755,9 @@ impl Display for CpioEntry {
}

pub fn cpio_commands(argc: i32, argv: *const *const c_char) -> bool {
fn inner(argc: i32, argv: *const *const c_char) -> LoggedResult<()> {
let res: LoggedResult<()> = try {
if argc < 1 {
return Err(log_err!("No arguments"));
Err(log_err!("No arguments"))?;
}

let cmds = map_args(argc, argv)?;
Expand Down Expand Up @@ -807,7 +807,7 @@ pub fn cpio_commands(argc: i32, argv: *const *const c_char) -> bool {
CpioAction::Add(Add { mode, path, file }) => cpio.add(*mode, path, file)?,
CpioAction::Extract(Extract { paths }) => {
if !paths.is_empty() && paths.len() != 2 {
return Err(log_err!("invalid arguments"));
Err(log_err!("invalid arguments"))?;
}
let mut it = paths.iter_mut();
cpio.extract(it.next(), it.next())?;
Expand All @@ -819,10 +819,8 @@ pub fn cpio_commands(argc: i32, argv: *const *const c_char) -> bool {
};
}
cpio.dump(file)?;
Ok(())
}
inner(argc, argv)
.log_with_msg(|w| w.write_str("Failed to process cpio"))
};
res.log_with_msg(|w| w.write_str("Failed to process cpio"))
.is_ok()
}

Expand Down
10 changes: 4 additions & 6 deletions native/src/boot/dtb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,9 +273,9 @@ fn dtb_patch(file: &Utf8CStr) -> LoggedResult<bool> {
}

pub fn dtb_commands(argc: i32, argv: *const *const c_char) -> bool {
fn inner(argc: i32, argv: *const *const c_char) -> LoggedResult<()> {
let res: LoggedResult<()> = try {
if argc < 1 {
return Err(log_err!("No arguments"));
Err(log_err!("No arguments"))?;
}
let cmds = map_args(argc, argv)?;

Expand All @@ -299,9 +299,7 @@ pub fn dtb_commands(argc: i32, argv: *const *const c_char) -> bool {
}
}
}
Ok(())
}
inner(argc, argv)
.log_with_msg(|w| w.write_str("Failed to process dtb"))
};
res.log_with_msg(|w| w.write_str("Failed to process dtb"))
.is_ok()
}
17 changes: 13 additions & 4 deletions native/src/boot/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![feature(format_args_nl)]
#![feature(btree_extract_if)]
#![feature(iter_intersperse)]
#![feature(try_blocks)]

pub use base;
use cpio::cpio_commands;
Expand All @@ -21,6 +22,14 @@ mod sign;

#[cxx::bridge]
pub mod ffi {
unsafe extern "C++" {
include!("../base/include/base.hpp");

#[namespace = "rust"]
#[cxx_name = "Utf8CStr"]
type Utf8CStrRef<'a> = base::ffi::Utf8CStrRef<'a>;
}

unsafe extern "C++" {
include!("compress.hpp");
fn decompress(buf: &[u8], fd: i32) -> bool;
Expand Down Expand Up @@ -51,10 +60,10 @@ pub mod ffi {
#[namespace = "rust"]
#[allow(unused_unsafe)]
extern "Rust" {
unsafe fn extract_boot_from_payload(
partition: *const c_char,
in_path: *const c_char,
out_path: *const c_char,
fn extract_boot_from_payload(
partition: Utf8CStrRef,
in_path: Utf8CStrRef,
out_path: Utf8CStrRef,
) -> bool;
unsafe fn cpio_commands(argc: i32, argv: *const *const c_char) -> bool;
unsafe fn verify_boot_image(img: &BootImage, cert: *const c_char) -> bool;
Expand Down
4 changes: 2 additions & 2 deletions native/src/boot/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,8 @@ int main(int argc, char *argv[]) {
} else if (argc > 2 && action == "extract") {
return rust::extract_boot_from_payload(
argv[2],
argc > 3 ? argv[3] : nullptr,
argc > 4 ? argv[4] : nullptr
argc > 3 ? argv[3] : "",
argc > 4 ? argv[4] : ""
) ? 0 : 1;
} else {
usage(argv[0]);
Expand Down
9 changes: 4 additions & 5 deletions native/src/boot/patch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ fn hex2byte(hex: &[u8]) -> Vec<u8> {
}

pub fn hexpatch(file: &[u8], from: &[u8], to: &[u8]) -> bool {
fn inner(file: &[u8], from: &[u8], to: &[u8]) -> LoggedResult<bool> {
let res: LoggedResult<bool> = try {
let file = Utf8CStr::from_bytes(file)?;
let from = Utf8CStr::from_bytes(from)?;
let to = Utf8CStr::from_bytes(to)?;
Expand All @@ -114,8 +114,7 @@ pub fn hexpatch(file: &[u8], from: &[u8], to: &[u8]) -> bool {
for off in &v {
eprintln!("Patch @ {:#010X} [{}] -> [{}]", off, from, to);
}

Ok(!v.is_empty())
}
inner(file, from, to).unwrap_or(false)
!v.is_empty()
};
res.unwrap_or(false)
}
59 changes: 28 additions & 31 deletions native/src/boot/payload.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom, Write};
use std::os::fd::{AsRawFd, FromRawFd};
use std::{
fs::File,
io::{BufReader, Read, Seek, SeekFrom, Write},
os::fd::{AsRawFd, FromRawFd},
};

use byteorder::{BigEndian, ReadBytesExt};
use quick_protobuf::{BytesReader, MessageRead};

use base::libc::c_char;
use base::{error, LoggedError, LoggedResult, ReadSeekExt, StrErr, Utf8CStr};
use base::{ResultExt, WriteExt};

use crate::ffi;
use crate::proto::update_metadata::mod_InstallOperation::Type;
use crate::proto::update_metadata::DeltaArchiveManifest;
use crate::{
ffi,
proto::update_metadata::{mod_InstallOperation::Type, DeltaArchiveManifest},
};
use base::{
error, ffi::Utf8CStrRef, LoggedError, LoggedResult, ReadSeekExt, ResultExt, Utf8CStr, WriteExt,
};

macro_rules! bad_payload {
($msg:literal) => {{
Expand Down Expand Up @@ -178,28 +180,23 @@ fn do_extract_boot_from_payload(
}

pub fn extract_boot_from_payload(
in_path: *const c_char,
partition: *const c_char,
out_path: *const c_char,
in_path: Utf8CStrRef,
partition: Utf8CStrRef,
out_path: Utf8CStrRef,
) -> bool {
fn inner(
in_path: *const c_char,
partition: *const c_char,
out_path: *const c_char,
) -> LoggedResult<()> {
let in_path = unsafe { Utf8CStr::from_ptr(in_path) }?;
let partition = match unsafe { Utf8CStr::from_ptr(partition) } {
Ok(s) => Some(s),
Err(StrErr::NullPointerError) => None,
Err(e) => Err(e)?,
let res: LoggedResult<()> = try {
let partition = if partition.is_empty() {
None
} else {
Some(partition)
};
let out_path = match unsafe { Utf8CStr::from_ptr(out_path) } {
Ok(s) => Some(s),
Err(StrErr::NullPointerError) => None,
Err(e) => Err(e)?,
let out_path = if out_path.is_empty() {
None
} else {
Some(out_path)
};
do_extract_boot_from_payload(in_path, partition, out_path)
.log_with_msg(|w| w.write_str("Failed to extract from payload"))
}
inner(in_path, partition, out_path).is_ok()
do_extract_boot_from_payload(in_path, partition, out_path)?
};
res.log_with_msg(|w| w.write_str("Failed to extract from payload"))
.is_ok()
}
20 changes: 7 additions & 13 deletions native/src/boot/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ impl BootSignature {
}

pub fn verify_boot_image(img: &BootImage, cert: *const c_char) -> bool {
fn inner(img: &BootImage, cert: *const c_char) -> LoggedResult<()> {
let res: LoggedResult<()> = try {
let tail = img.tail();
// Don't use BootSignature::from_der because tail might have trailing zeros
let mut reader = SliceReader::new(tail)?;
Expand All @@ -268,9 +268,8 @@ pub fn verify_boot_image(img: &BootImage, cert: *const c_char) -> bool {
Err(e) => Err(e)?,
};
sig.verify(img.payload())?;
Ok(())
}
inner(img, cert).is_ok()
};
res.is_ok()
}

enum Bytes {
Expand All @@ -296,12 +295,7 @@ pub fn sign_boot_image(
cert: *const c_char,
key: *const c_char,
) -> Vec<u8> {
fn inner(
payload: &[u8],
name: *const c_char,
cert: *const c_char,
key: *const c_char,
) -> LoggedResult<Vec<u8>> {
let res: LoggedResult<Vec<u8>> = try {
// Process arguments
let name = unsafe { Utf8CStr::from_ptr(name) }?;
let cert = match unsafe { Utf8CStr::from_ptr(cert) } {
Expand Down Expand Up @@ -337,7 +331,7 @@ pub fn sign_boot_image(
authenticated_attributes: attr,
signature: OctetString::new(sig)?,
};
sig.to_der().log()
}
inner(payload, name, cert, key).unwrap_or_default()
sig.to_der()?
};
res.unwrap_or_default()
}
12 changes: 2 additions & 10 deletions native/src/core/mount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,7 @@ pub fn clean_mounts() {
let module_mnt = FsPathBuf::new(&mut buf).join(magisk_tmp).join(MODULEMNT);
let _: LoggedResult<()> = try {
unsafe {
libc::umount2(
module_mnt.as_ptr(),
libc::MNT_DETACH,
)
.as_os_err()?;
libc::umount2(module_mnt.as_ptr(), libc::MNT_DETACH).as_os_err()?;
}
};

Expand All @@ -125,11 +121,7 @@ pub fn clean_mounts() {
ptr::null(),
)
.as_os_err()?;
libc::umount2(
worker_dir.as_ptr(),
libc::MNT_DETACH,
)
.as_os_err()?;
libc::umount2(worker_dir.as_ptr(), libc::MNT_DETACH).as_os_err()?;
}
};
}
Expand Down
20 changes: 9 additions & 11 deletions native/src/core/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ macro_rules! bad_apk {
* within the APK v2 signature block.
*/
fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {
fn inner(apk: &mut File, version: i32) -> io::Result<Vec<u8>> {
let res: io::Result<Vec<u8>> = try {
let mut u32_val = 0u32;
let mut u64_val = 0u64;

Expand All @@ -71,7 +71,7 @@ fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {
}
}
if i == 0xffff {
return Err(bad_apk!("invalid APK format"));
Err(bad_apk!("invalid APK format"))?;
}
}

Expand All @@ -98,7 +98,7 @@ fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {
}
});
if version > apk_ver {
return Err(bad_apk!("APK version too low"));
Err(bad_apk!("APK version too low"))?;
}
}

Expand All @@ -108,22 +108,22 @@ fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {
let mut magic = [0u8; 16];
apk.read_exact(&mut magic)?;
if magic != APK_SIGNING_BLOCK_MAGIC {
return Err(bad_apk!("invalid signing block magic"));
Err(bad_apk!("invalid signing block magic"))?;
}
let mut signing_blk_sz = 0u64;
apk.seek(SeekFrom::Current(
-(u64_val as i64) - (size_of_val(&signing_blk_sz) as i64),
))?;
apk.read_pod(&mut signing_blk_sz)?;
if signing_blk_sz != u64_val {
return Err(bad_apk!("invalid signing block size"));
Err(bad_apk!("invalid signing block size"))?;
}

// Finally, we are now at the beginning of the id-value pair sequence
loop {
apk.read_pod(&mut u64_val)?; // id-value pair length
if u64_val == signing_blk_sz {
break;
Err(bad_apk!("cannot find certificate"))?;
}

let mut id = 0u32;
Expand All @@ -140,18 +140,16 @@ fn read_certificate(apk: &mut File, version: i32) -> Vec<u8> {

let mut cert = vec![0; u32_val as usize];
apk.read_exact(cert.as_mut())?;
return Ok(cert);
break cert;
} else {
// Skip this id-value pair
apk.seek(SeekFrom::Current(
u64_val as i64 - (size_of_val(&id) as i64),
))?;
}
}

Err(bad_apk!("cannot find certificate"))
}
inner(apk, version).log().unwrap_or(vec![])
};
res.log().unwrap_or(vec![])
}

fn find_apk_path(pkg: &str, buf: &mut dyn Utf8CStrBuf) -> io::Result<()> {
Expand Down
Loading
Loading