Make log_err directly return LoggedResult

This commit is contained in:
topjohnwu
2025-08-21 21:05:35 -07:00
committed by John Wu
parent 5caf28d27c
commit 36d33c7a85
7 changed files with 41 additions and 34 deletions

View File

@@ -23,9 +23,12 @@ pub type LoggedResult<T> = Result<T, LoggedError>;
#[macro_export] #[macro_export]
macro_rules! log_err { macro_rules! log_err {
() => {{
Err($crate::LoggedError::default())
}};
($($args:tt)+) => {{ ($($args:tt)+) => {{
$crate::error!($($args)+); $crate::error!($($args)+);
$crate::LoggedError::default() Err($crate::LoggedError::default())
}}; }};
} }

View File

@@ -363,7 +363,7 @@ pub extern "C" fn main(argc: i32, argv: *const *const c_char, _envp: *const *con
ref args, ref args,
}) => { }) => {
if args.len() > 2 { if args.len() > 2 {
Err(log_err!("Too many arguments"))?; log_err!("Too many arguments")?;
} }
extract_boot_from_payload( extract_boot_from_payload(
payload, payload,
@@ -382,7 +382,7 @@ pub extern "C" fn main(argc: i32, argv: *const *const c_char, _envp: *const *con
Utf8CStr::from_string(src), Utf8CStr::from_string(src),
Utf8CStr::from_string(dest), Utf8CStr::from_string(dest),
) { ) {
Err(log_err!("Failed to patch"))?; log_err!("Failed to patch")?;
} }
} }
Action::Cpio(Cpio { Action::Cpio(Cpio {

View File

@@ -462,7 +462,7 @@ pub(crate) fn decompress(infile: &mut String, outfile: Option<&mut String>) -> L
eprintln!("Detected format: {format}"); eprintln!("Detected format: {format}");
if !format.is_compressed() { if !format.is_compressed() {
return Err(log_err!("Input file is not a supported type!")); return log_err!("Input file is not a supported type!");
} }
let raw_out = if let Some(outfile) = outfile { let raw_out = if let Some(outfile) = outfile {
@@ -478,7 +478,7 @@ pub(crate) fn decompress(infile: &mut String, outfile: Option<&mut String>) -> L
rm_in = true; rm_in = true;
let mut outfile = if let Some((outfile, ext)) = infile.rsplit_once('.') { let mut outfile = if let Some((outfile, ext)) = infile.rsplit_once('.') {
if ext != format.ext() { if ext != format.ext() {
Err(log_err!("Input file is not a supported type!"))?; log_err!("Input file is not a supported type!")?;
} }
outfile.to_owned() outfile.to_owned()
} else { } else {

View File

@@ -20,8 +20,8 @@ use base::libc::{
dev_t, gid_t, major, makedev, minor, mknod, mode_t, uid_t, dev_t, gid_t, major, makedev, minor, mknod, mode_t, uid_t,
}; };
use base::{ use base::{
BytesExt, EarlyExitExt, LoggedResult, MappedFile, ResultExt, Utf8CStr, Utf8CStrBuf, WriteExt, BytesExt, EarlyExitExt, LoggedError, LoggedResult, MappedFile, ResultExt, Utf8CStr,
cstr, log_err, Utf8CStrBuf, WriteExt, cstr, error, log_err,
}; };
use crate::check_env; use crate::check_env;
@@ -227,7 +227,7 @@ impl Cpio {
let hdr_sz = size_of::<CpioHeader>(); let hdr_sz = size_of::<CpioHeader>();
let hdr = from_bytes::<CpioHeader>(&data[pos..(pos + hdr_sz)]); let hdr = from_bytes::<CpioHeader>(&data[pos..(pos + hdr_sz)]);
if &hdr.magic != b"070701" { if &hdr.magic != b"070701" {
return Err(log_err!("invalid cpio magic")); return log_err!("invalid cpio magic");
} }
pos += hdr_sz; pos += hdr_sz;
let name_sz = x8u(&hdr.namesize)? as usize; let name_sz = x8u(&hdr.namesize)? as usize;
@@ -328,10 +328,10 @@ impl Cpio {
} }
fn extract_entry(&self, path: &str, out: &mut String) -> LoggedResult<()> { fn extract_entry(&self, path: &str, out: &mut String) -> LoggedResult<()> {
let entry = self let entry = self.entries.get(path).ok_or_else(|| {
.entries error!("No such file");
.get(path) LoggedError::default()
.ok_or_else(|| log_err!("No such file"))?; })?;
eprintln!("Extracting entry [{path}] to [{out}]"); eprintln!("Extracting entry [{path}] to [{out}]");
let out = Utf8CStr::from_string(out); let out = Utf8CStr::from_string(out);
@@ -362,7 +362,7 @@ impl Cpio {
unsafe { mknod(out.as_ptr().cast(), entry.mode, dev) }; unsafe { mknod(out.as_ptr().cast(), entry.mode, dev) };
} }
_ => { _ => {
return Err(log_err!("unknown entry type")); return log_err!("unknown entry type");
} }
} }
Ok(()) Ok(())
@@ -389,7 +389,7 @@ impl Cpio {
fn add(&mut self, mode: mode_t, path: &str, file: &mut String) -> LoggedResult<()> { fn add(&mut self, mode: mode_t, path: &str, file: &mut String) -> LoggedResult<()> {
if path.ends_with('/') { if path.ends_with('/') {
return Err(log_err!("path cannot end with / for add")); return log_err!("path cannot end with / for add");
} }
let file = Utf8CStr::from_string(file); let file = Utf8CStr::from_string(file);
let attr = file.get_attr()?; let attr = file.get_attr()?;
@@ -412,7 +412,7 @@ impl Cpio {
} else if attr.is_char_device() { } else if attr.is_char_device() {
mode | S_IFCHR mode | S_IFCHR
} else { } else {
return Err(log_err!("unsupported file type")); return log_err!("unsupported file type");
} }
}; };
@@ -462,10 +462,10 @@ impl Cpio {
} }
fn mv(&mut self, from: &str, to: &str) -> LoggedResult<()> { fn mv(&mut self, from: &str, to: &str) -> LoggedResult<()> {
let entry = self let entry = self.entries.remove(&norm_path(from)).ok_or_else(|| {
.entries error!("no such entry {}", from);
.remove(&norm_path(from)) LoggedError::default()
.ok_or_else(|| log_err!("no such entry {}", from))?; })?;
self.entries.insert(norm_path(to), entry); self.entries.insert(norm_path(to), entry);
eprintln!("Move [{from}] -> [{to}]"); eprintln!("Move [{from}] -> [{to}]");
Ok(()) Ok(())
@@ -792,7 +792,7 @@ pub(crate) fn cpio_commands(file: &mut String, cmds: &mut Vec<String>) -> Logged
CpioAction::Add(Add { mode, path, file }) => cpio.add(*mode, path, file)?, CpioAction::Add(Add { mode, path, file }) => cpio.add(*mode, path, file)?,
CpioAction::Extract(Extract { paths }) => { CpioAction::Extract(Extract { paths }) => {
if !paths.is_empty() && paths.len() != 2 { if !paths.is_empty() && paths.len() != 2 {
Err(log_err!("invalid arguments"))?; log_err!("invalid arguments")?;
} }
let mut it = paths.iter_mut(); let mut it = paths.iter_mut();
cpio.extract(it.next(), it.next())?; cpio.extract(it.next(), it.next())?;
@@ -812,7 +812,11 @@ fn x8u(x: &[u8; 8]) -> LoggedResult<u32> {
let mut ret = 0u32; let mut ret = 0u32;
let s = str::from_utf8(x).log_with_msg(|w| w.write_str("bad cpio header"))?; let s = str::from_utf8(x).log_with_msg(|w| w.write_str("bad cpio header"))?;
for c in s.chars() { for c in s.chars() {
ret = ret * 16 + c.to_digit(16).ok_or_else(|| log_err!("bad cpio header"))?; ret = ret * 16
+ c.to_digit(16).ok_or_else(|| {
error!("bad cpio header");
LoggedError::default()
})?;
} }
Ok(ret) Ok(ret)
} }

View File

@@ -25,7 +25,7 @@ use x509_cert::der::Any;
use x509_cert::der::asn1::{OctetString, PrintableString}; use x509_cert::der::asn1::{OctetString, PrintableString};
use x509_cert::spki::AlgorithmIdentifier; use x509_cert::spki::AlgorithmIdentifier;
use base::{LoggedError, LoggedResult, MappedFile, ResultExt, Utf8CStr, cstr, log_err}; use base::{LoggedResult, MappedFile, ResultExt, Utf8CStr, cstr, log_err};
use crate::ffi::BootImage; use crate::ffi::BootImage;
@@ -116,7 +116,7 @@ impl Verifier {
digest = Box::<Sha512>::default(); digest = Box::<Sha512>::default();
VerifyingKey::SHA521withECDSA(ec) VerifyingKey::SHA521withECDSA(ec)
} else { } else {
return Err(log_err!("Unsupported private key")); return log_err!("Unsupported private key");
}; };
Ok(Verifier { digest, key }) Ok(Verifier { digest, key })
} }
@@ -177,7 +177,7 @@ impl Signer {
SigningKey::SHA521withECDSA(ec) SigningKey::SHA521withECDSA(ec)
} }
_ => { _ => {
return Err(log_err!("Unsupported private key")); return log_err!("Unsupported private key");
} }
}, },
}, },
@@ -248,7 +248,7 @@ struct BootSignature {
impl BootSignature { impl BootSignature {
fn verify(self, payload: &[u8]) -> LoggedResult<()> { fn verify(self, payload: &[u8]) -> LoggedResult<()> {
if self.authenticated_attributes.length as usize != payload.len() { if self.authenticated_attributes.length as usize != payload.len() {
return Err(log_err!("Invalid image size")); return log_err!("Invalid image size");
} }
let mut verifier = Verifier::from_public_key( let mut verifier = Verifier::from_public_key(
self.certificate self.certificate
@@ -268,7 +268,7 @@ impl BootImage {
pub fn verify(&self, cert: Option<&Utf8CStr>) -> LoggedResult<()> { pub fn verify(&self, cert: Option<&Utf8CStr>) -> LoggedResult<()> {
let tail = self.tail(); let tail = self.tail();
if tail.starts_with(b"AVB0") { if tail.starts_with(b"AVB0") {
return Err(LoggedError::default()); return log_err!();
} }
// Don't use BootSignature::from_der because tail might have trailing zeros // Don't use BootSignature::from_der because tail might have trailing zeros

View File

@@ -6,8 +6,8 @@ use crate::ffi::{
use crate::socket::{IpcRead, UnixSocketExt}; use crate::socket::{IpcRead, UnixSocketExt};
use base::libc::{O_CLOEXEC, O_CREAT, O_RDONLY, STDOUT_FILENO}; use base::libc::{O_CLOEXEC, O_CREAT, O_RDONLY, STDOUT_FILENO};
use base::{ use base::{
Directory, FsPathBuilder, LoggedError, LoggedResult, ResultExt, Utf8CStr, WriteExt, cstr, Directory, FsPathBuilder, LoggedResult, ResultExt, Utf8CStr, WriteExt, cstr, fork_dont_care,
fork_dont_care, libc, raw_cstr, warn, libc, log_err, raw_cstr, warn,
}; };
use std::fmt::Write; use std::fmt::Write;
use std::os::fd::{AsRawFd, FromRawFd, RawFd}; use std::os::fd::{AsRawFd, FromRawFd, RawFd};
@@ -101,7 +101,7 @@ impl ZygiskState {
local.send_fds(&module_fds)?; local.send_fds(&module_fds)?;
} }
if local.read_decodable::<i32>()? != 0 { if local.read_decodable::<i32>()? != 0 {
Err(LoggedError::default())?; return log_err!();
} }
local local
}; };

View File

@@ -92,10 +92,10 @@ pub unsafe extern "C" fn main(
(None, true, false) => SePolicy::from_split(), (None, true, false) => SePolicy::from_split(),
(None, false, true) => SePolicy::compile_split(), (None, false, true) => SePolicy::compile_split(),
(None, false, false) => SePolicy::from_file(cstr!("/sys/fs/selinux/policy")), (None, false, false) => SePolicy::from_file(cstr!("/sys/fs/selinux/policy")),
_ => Err(log_err!("Multiple load source supplied"))?, _ => log_err!("Multiple load source supplied")?,
}; };
if sepol._impl.is_null() { if sepol._impl.is_null() {
Err(log_err!("Cannot load policy"))?; log_err!("Cannot load policy")?;
} }
if cli.print_rules { if cli.print_rules {
@@ -105,7 +105,7 @@ pub unsafe extern "C" fn main(
|| cli.live || cli.live
|| cli.save.is_some() || cli.save.is_some()
{ {
Err(log_err!("Cannot print rules with other options"))?; log_err!("Cannot print rules with other options")?;
} }
sepol.print_rules(); sepol.print_rules();
return 0; return 0;
@@ -124,12 +124,12 @@ pub unsafe extern "C" fn main(
} }
if cli.live && !sepol.to_file(cstr!("/sys/fs/selinux/load")) { if cli.live && !sepol.to_file(cstr!("/sys/fs/selinux/load")) {
Err(log_err!("Cannot apply policy"))?; log_err!("Cannot apply policy")?;
} }
if let Some(file) = &mut cli.save { if let Some(file) = &mut cli.save {
if !sepol.to_file(Utf8CStr::from_string(file)) { if !sepol.to_file(Utf8CStr::from_string(file)) {
Err(log_err!("Cannot dump policy to {}", file))?; log_err!("Cannot dump policy to {}", file)?;
} }
} }
}; };