Apply clippy fix

This commit is contained in:
topjohnwu 2025-07-02 19:36:27 -07:00 committed by John Wu
parent d660401063
commit 37a9724a54
18 changed files with 112 additions and 114 deletions

View File

@ -583,7 +583,7 @@ impl<S: Utf8CStrBuf + Sized> FsPathBuilder for S {
}
fn append_path_fmt<T: Display>(&mut self, name: T) -> &mut Self {
self.write_fmt(format_args!("/{}", name)).ok();
self.write_fmt(format_args!("/{name}")).ok();
self
}
}
@ -595,7 +595,7 @@ impl FsPathBuilder for dyn Utf8CStrBuf + '_ {
}
fn append_path_fmt<T: Display>(&mut self, name: T) -> &mut Self {
self.write_fmt(format_args!("/{}", name)).ok();
self.write_fmt(format_args!("/{name}")).ok();
self
}
}
@ -846,7 +846,7 @@ fn parse_mount_info_line(line: &str) -> Option<MountInfo> {
pub fn parse_mount_info(pid: &str) -> Vec<MountInfo> {
let mut res = vec![];
let mut path = format!("/proc/{}/mountinfo", pid);
let mut path = format!("/proc/{pid}/mountinfo");
if let Ok(file) = Utf8CStr::from_string(&mut path).open(O_RDONLY | O_CLOEXEC) {
BufReader::new(file).foreach_lines(|line| {
parse_mount_info_line(line)

View File

@ -99,7 +99,7 @@ impl<T> EarlyExitExt<T> for Result<T, EarlyExit> {
exit(0)
}
Err(_) => {
eprintln!("{}", output);
eprintln!("{output}");
print_help_msg();
exit(1)
}

View File

@ -171,7 +171,7 @@ impl<T, E: Display> Loggable<T> for Result<T, E> {
write!(w, "[{}:{}] ", caller.file(), caller.line())?;
}
f(w)?;
writeln!(w, ": {:#}", e)
writeln!(w, ": {e:#}")
});
Err(LoggedError::default())
}
@ -366,7 +366,7 @@ impl Display for OsError<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let error = self.as_io_error();
if self.name.is_empty() {
write!(f, "{:#}", error)
write!(f, "{error:#}")
} else {
match (self.arg1.ok(), self.arg2.ok()) {
(Some(arg1), Some(arg2)) => {

View File

@ -269,13 +269,13 @@ impl Cpio {
}
fn load_from_file(path: &Utf8CStr) -> LoggedResult<Self> {
eprintln!("Loading cpio: [{}]", path);
eprintln!("Loading cpio: [{path}]");
let file = MappedFile::open(path)?;
Self::load_from_data(file.as_ref())
}
fn dump(&self, path: &str) -> LoggedResult<()> {
eprintln!("Dumping cpio: [{}]", path);
eprintln!("Dumping cpio: [{path}]");
let mut file = File::create(path)?;
let mut pos = 0usize;
let mut inode = 300000i64;
@ -320,13 +320,13 @@ impl Cpio {
fn rm(&mut self, path: &str, recursive: bool) {
let path = norm_path(path);
if self.entries.remove(&path).is_some() {
eprintln!("Removed entry [{}]", path);
eprintln!("Removed entry [{path}]");
}
if recursive {
let path = path + "/";
self.entries.retain(|k, _| {
if k.starts_with(&path) {
eprintln!("Removed entry [{}]", k);
eprintln!("Removed entry [{k}]");
false
} else {
true
@ -340,7 +340,7 @@ impl Cpio {
.entries
.get(path)
.ok_or_else(|| log_err!("No such file"))?;
eprintln!("Extracting entry [{}] to [{}]", path, out);
eprintln!("Extracting entry [{path}] to [{out}]");
let out = Utf8CStr::from_string(out);
@ -435,7 +435,7 @@ impl Cpio {
data: content,
}),
);
eprintln!("Add file [{}] ({:04o})", path, mode);
eprintln!("Add file [{path}] ({mode:04o})");
Ok(())
}
@ -451,7 +451,7 @@ impl Cpio {
data: vec![],
}),
);
eprintln!("Create directory [{}] ({:04o})", dir, mode);
eprintln!("Create directory [{dir}] ({mode:04o})");
}
fn ln(&mut self, src: &str, dst: &str) {
@ -466,7 +466,7 @@ impl Cpio {
data: norm_path(src).as_bytes().to_vec(),
}),
);
eprintln!("Create symlink [{}] -> [{}]", dst, src);
eprintln!("Create symlink [{dst}] -> [{src}]");
}
fn mv(&mut self, from: &str, to: &str) -> LoggedResult<()> {
@ -475,7 +475,7 @@ impl Cpio {
.remove(&norm_path(from))
.ok_or_else(|| log_err!("no such entry {}", from))?;
self.entries.insert(norm_path(to), entry);
eprintln!("Move [{}] -> [{}]", from, to);
eprintln!("Move [{from}] -> [{to}]");
Ok(())
}
@ -498,7 +498,7 @@ impl Cpio {
if !recursive && !p.is_empty() && p.matches('/').count() > 1 {
continue;
}
println!("{}\t{}", entry, name);
println!("{entry}\t{name}");
}
}
}
@ -511,8 +511,7 @@ impl Cpio {
let keep_verity = check_env("KEEPVERITY");
let keep_force_encrypt = check_env("KEEPFORCEENCRYPT");
eprintln!(
"Patch with flag KEEPVERITY=[{}] KEEPFORCEENCRYPT=[{}]",
keep_verity, keep_force_encrypt
"Patch with flag KEEPVERITY=[{keep_verity}] KEEPFORCEENCRYPT=[{keep_force_encrypt}]"
);
self.entries.retain(|name, entry| {
let fstab = (!keep_verity || !keep_force_encrypt)
@ -523,7 +522,7 @@ impl Cpio {
&& name.starts_with("fstab");
if !keep_verity {
if fstab {
eprintln!("Found fstab file [{}]", name);
eprintln!("Found fstab file [{name}]");
let len = patch_verity(entry.data.as_mut_slice());
if len != entry.data.len() {
entry.data.resize(len, 0);
@ -581,7 +580,7 @@ impl Cpio {
} else {
&name[8..]
};
eprintln!("Restore [{}] -> [{}]", name, new_name);
eprintln!("Restore [{name}] -> [{new_name}]");
backups.insert(new_name.to_string(), entry);
}
});
@ -658,16 +657,16 @@ impl Cpio {
match action {
Action::Backup(name, mut entry) => {
let backup = if !skip_compress && entry.compress() {
format!(".backup/{}.xz", name)
format!(".backup/{name}.xz")
} else {
format!(".backup/{}", name)
format!(".backup/{name}")
};
eprintln!("Backup [{}] -> [{}]", name, backup);
eprintln!("Backup [{name}] -> [{backup}]");
backups.insert(backup, entry);
}
Action::Record(name) => {
eprintln!("Record new entry: [{}] -> [.backup/.rmlist]", name);
rm_list.push_str(&format!("{}\0", name));
eprintln!("Record new entry: [{name}] -> [.backup/.rmlist]");
rm_list.push_str(&format!("{name}\0"));
}
Action::Noop => {}
}

View File

@ -131,9 +131,9 @@ fn print_node(node: &FdtNode) {
}
);
} else if size > MAX_PRINT_LEN {
println!("[{}]: <bytes>({})", name, size);
println!("[{name}]: <bytes>({size})");
} else {
println!("[{}]: {:02x?}", name, value);
println!("[{name}]: {value:02x?}");
}
}
@ -154,7 +154,7 @@ fn for_each_fdt<F: FnMut(usize, Fdt) -> LoggedResult<()>>(
rw: bool,
mut f: F,
) -> LoggedResult<()> {
eprintln!("Loading dtbs from [{}]", file);
eprintln!("Loading dtbs from [{file}]");
let file = if rw {
MappedFile::open_rw(file)?
} else {
@ -173,7 +173,7 @@ fn for_each_fdt<F: FnMut(usize, Fdt) -> LoggedResult<()>>(
}
let fdt = match Fdt::new(slice) {
Err(FdtError::BufferTooSmall) => {
eprintln!("dtb.{:04} is truncated", dtb_num);
eprintln!("dtb.{dtb_num:04} is truncated");
break;
}
Ok(fdt) => fdt,
@ -198,11 +198,11 @@ fn dtb_print(file: &Utf8CStr, fstab: bool) -> LoggedResult<()> {
for_each_fdt(file, false, |n, fdt| {
if fstab {
if let Some(fstab) = find_fstab(&fdt) {
eprintln!("Found fstab in dtb.{:04}", n);
eprintln!("Found fstab in dtb.{n:04}");
print_node(&fstab);
}
} else if let Some(mut root) = fdt.find_node("/") {
eprintln!("Printing dtb.{:04}", n);
eprintln!("Printing dtb.{n:04}");
if root.name.is_empty() {
root.name = "/";
}
@ -248,7 +248,7 @@ fn dtb_patch(file: &Utf8CStr) -> LoggedResult<bool> {
&mut *std::mem::transmute::<&[u8], &UnsafeCell<[u8]>>(w).get()
};
w[..=4].copy_from_slice(b"want");
eprintln!("Patch [skip_initramfs] -> [want_initramfs] in dtb.{:04}", n);
eprintln!("Patch [skip_initramfs] -> [want_initramfs] in dtb.{n:04}");
patched = true;
}
});

View File

@ -45,7 +45,7 @@ fn remove_pattern(buf: &mut [u8], pattern_matcher: unsafe fn(&[u8]) -> Option<us
let skipped = buf.get_unchecked(read..(read + len));
// SAFETY: all matching patterns are ASCII bytes
let skipped = std::str::from_utf8_unchecked(skipped);
eprintln!("Remove pattern [{}]", skipped);
eprintln!("Remove pattern [{skipped}]");
sz -= len;
read += len;
} else {
@ -114,7 +114,7 @@ pub fn hexpatch(file: &[u8], from: &[u8], to: &[u8]) -> bool {
let v = map.patch(pattern.as_slice(), patch.as_slice());
for off in &v {
eprintln!("Patch @ {:#010X} [{}] -> [{}]", off, from, to);
eprintln!("Patch @ {off:#010X} [{from}] -> [{to}]");
}
!v.is_empty()
};

View File

@ -34,7 +34,7 @@ fn do_extract_boot_from_payload(
let mut reader = BufReader::new(if in_path == "-" {
unsafe { File::from_raw_fd(0) }
} else {
File::open(in_path).log_with_msg(|w| write!(w, "Cannot open '{}'", in_path))?
File::open(in_path).log_with_msg(|w| write!(w, "Cannot open '{in_path}'"))?
});
let buf = &mut [0u8; 4];
@ -107,7 +107,7 @@ fn do_extract_boot_from_payload(
};
let mut out_file =
File::create(out_path).log_with_msg(|w| write!(w, "Cannot write to '{}'", out_path))?;
File::create(out_path).log_with_msg(|w| write!(w, "Cannot write to '{out_path}'"))?;
// Skip the manifest signature
reader.skip(manifest_sig_len as usize)?;

View File

@ -336,7 +336,7 @@ fn switch_cgroup(cgroup: &str, pid: i32) {
}
if let Ok(mut file) = buf.open(O_WRONLY | O_APPEND | O_CLOEXEC) {
buf.clear();
buf.write_fmt(format_args!("{}", pid)).ok();
buf.write_fmt(format_args!("{pid}")).ok();
file.write_all(buf.as_bytes()).log_ok();
}
}

View File

@ -131,7 +131,7 @@ fn write_log_to_pipe(mut logd: &File, prio: i32, msg: &Utf8CStr) -> io::Result<u
let result = logd.write_vectored(&[io1, io2]);
if let Err(ref e) = result {
let mut buf = cstr::buf::default();
buf.write_fmt(format_args!("Cannot write_log_to_pipe: {}", e))
buf.write_fmt(format_args!("Cannot write_log_to_pipe: {e}"))
.ok();
android_log_write(LogLevel::Error, &buf);
}
@ -142,11 +142,11 @@ static MAGISK_LOGD_FD: Mutex<Option<Arc<File>>> = Mutex::new(None);
fn with_logd_fd<R, F: FnOnce(&File) -> io::Result<R>>(f: F) {
let fd = MAGISK_LOGD_FD.lock().unwrap().clone();
if let Some(logd) = fd {
if f(&logd).is_err() {
// If any error occurs, shut down the logd pipe
*MAGISK_LOGD_FD.lock().unwrap() = None;
}
if let Some(logd) = fd
&& f(&logd).is_err()
{
// If any error occurs, shut down the logd pipe
*MAGISK_LOGD_FD.lock().unwrap() = None;
}
}

View File

@ -399,7 +399,7 @@ fn inject_magisk_bins(system: &mut FsNode) {
// Strip /system prefix to insert correct node
fn strip_system_prefix(orig_item: &str) -> String {
match orig_item.strip_prefix("/system/") {
Some(rest) => format!("/{}", rest),
Some(rest) => format!("/{rest}"),
None => orig_item.to_string(),
}
}
@ -421,7 +421,7 @@ fn inject_magisk_bins(system: &mut FsNode) {
}
// Override existing su first
let su_path = Utf8CString::from(format!("{}/su", orig_item));
let su_path = Utf8CString::from(format!("{orig_item}/su"));
if su_path.exists() {
let item = strip_system_prefix(orig_item);
candidates.push((item, 0));
@ -431,21 +431,23 @@ fn inject_magisk_bins(system: &mut FsNode) {
let path = Utf8CString::from(orig_item);
if let Ok(attr) = path.get_attr()
&& (attr.st.st_mode & 0x0001) != 0
&& let Ok(mut dir) = Directory::open(&path)
{
if let Ok(mut dir) = Directory::open(&path) {
let mut count = 0;
if let Err(_) = dir.pre_order_walk(|e| {
let mut count = 0;
if dir
.pre_order_walk(|e| {
if e.is_file() {
count += 1;
}
Ok(WalkResult::Continue)
}) {
// Skip, we cannot ensure the result is correct
continue;
}
let item = strip_system_prefix(orig_item);
candidates.push((item, count));
})
.is_err()
{
// Skip, we cannot ensure the result is correct
continue;
}
let item = strip_system_prefix(orig_item);
candidates.push((item, count));
}
}

View File

@ -22,37 +22,37 @@ pub fn setup_preinit_dir() {
let dev_path = cstr::buf::new::<64>()
.join_path(magisk_tmp)
.join_path(PREINITDEV);
if let Ok(attr) = dev_path.get_attr() {
if attr.st.st_mode & libc::S_IFMT as c_uint == libc::S_IFBLK.as_() {
// DO NOT mount the block device directly, as we do not know the flags and configs
// to properly mount the partition; mounting block devices directly as rw could cause
// crashes if the filesystem driver is crap (e.g. some broken F2FS drivers).
// What we do instead is to scan through the current mountinfo and find a pre-existing
// mount point mounting our desired partition, and then bind mount the target folder.
let preinit_dev = attr.st.st_rdev;
let mnt_path = cstr::buf::default()
.join_path(magisk_tmp)
.join_path(PREINITMIRR);
for info in parse_mount_info("self") {
if info.root == "/" && info.device == preinit_dev {
if !info.fs_option.split(',').any(|s| s == "rw") {
// Only care about rw mounts
continue;
}
let mut target = info.target;
let target = Utf8CStr::from_string(&mut target);
let mut preinit_dir = resolve_preinit_dir(target);
let preinit_dir = Utf8CStr::from_string(&mut preinit_dir);
let r: LoggedResult<()> = try {
preinit_dir.mkdir(0o700)?;
mnt_path.mkdirs(0o755)?;
mnt_path.remove().ok();
mnt_path.create_symlink_to(preinit_dir)?;
};
if r.is_ok() {
info!("* Found preinit dir: {}", preinit_dir);
return;
}
if let Ok(attr) = dev_path.get_attr()
&& attr.st.st_mode & libc::S_IFMT as c_uint == libc::S_IFBLK.as_()
{
// DO NOT mount the block device directly, as we do not know the flags and configs
// to properly mount the partition; mounting block devices directly as rw could cause
// crashes if the filesystem driver is crap (e.g. some broken F2FS drivers).
// What we do instead is to scan through the current mountinfo and find a pre-existing
// mount point mounting our desired partition, and then bind mount the target folder.
let preinit_dev = attr.st.st_rdev;
let mnt_path = cstr::buf::default()
.join_path(magisk_tmp)
.join_path(PREINITMIRR);
for info in parse_mount_info("self") {
if info.root == "/" && info.device == preinit_dev {
if !info.fs_option.split(',').any(|s| s == "rw") {
// Only care about rw mounts
continue;
}
let mut target = info.target;
let target = Utf8CStr::from_string(&mut target);
let mut preinit_dir = resolve_preinit_dir(target);
let preinit_dir = Utf8CStr::from_string(&mut preinit_dir);
let r: LoggedResult<()> = try {
preinit_dir.mkdir(0o700)?;
mnt_path.mkdirs(0o755)?;
mnt_path.remove().ok();
mnt_path.create_symlink_to(preinit_dir)?;
};
if r.is_ok() {
info!("* Found preinit dir: {}", preinit_dir);
return;
}
}
}
@ -238,10 +238,10 @@ pub fn revert_unmount(pid: i32) {
let mut prev: Option<PathBuf> = None;
targets.sort();
targets.retain(|target| {
if let Some(prev) = &prev {
if Path::new(target).starts_with(prev) {
return false;
}
if let Some(prev) = &prev
&& Path::new(target).starts_with(prev)
{
return false;
}
prev = Some(PathBuf::from(target.clone()));
true

View File

@ -167,10 +167,10 @@ pub fn persist_get_props(mut prop_cb: Pin<&mut PropCb>) {
} else {
let mut dir = Directory::open(cstr!(PERSIST_PROP_DIR))?;
dir.pre_order_walk(|e| {
if e.is_file() {
if let Ok(mut value) = file_get_prop(e.name()) {
prop_cb.exec(e.name(), Utf8CStr::from_string(&mut value));
}
if e.is_file()
&& let Ok(mut value) = file_get_prop(e.name())
{
prop_cb.exec(e.name(), Utf8CStr::from_string(&mut value));
}
// Do not traverse recursively
Ok(WalkResult::Skip)

View File

@ -55,10 +55,9 @@ pub(crate) fn restorecon() {
if let Ok(mut file) = cstr!("/sys/fs/selinux/context")
.open(O_WRONLY | O_CLOEXEC)
.log()
&& file.write_all(ADB_CON.as_bytes_with_nul()).is_ok()
{
if file.write_all(ADB_CON.as_bytes_with_nul()).is_ok() {
cstr!(SECURE_DIR).set_secontext(ADB_CON).log_ok();
}
cstr!(SECURE_DIR).set_secontext(ADB_CON).log_ok();
}
let mut path = cstr::buf::default();

View File

@ -52,13 +52,12 @@ fn set_stdin_raw() -> bool {
pub fn restore_stdin() -> bool {
unsafe {
if let Some(ref termios) = OLD_STDIN {
if tcsetattr(STDIN_FILENO, TCSAFLUSH, termios) < 0
&& tcsetattr(STDIN_FILENO, TCSADRAIN, termios) < 0
{
warn!("Failed to restore terminal attributes");
return false;
}
if let Some(ref termios) = OLD_STDIN
&& tcsetattr(STDIN_FILENO, TCSAFLUSH, termios) < 0
&& tcsetattr(STDIN_FILENO, TCSADRAIN, termios) < 0
{
warn!("Failed to restore terminal attributes");
return false;
}
OLD_STDIN = None;
true

View File

@ -170,10 +170,10 @@ impl MagiskD {
client.write_pod(&flags)?;
// Next send modules
if zygisk_should_load_module(flags) {
if let Some(module_fds) = self.get_module_fds(is_64_bit) {
client.send_fds(&module_fds)?;
}
if zygisk_should_load_module(flags)
&& let Some(module_fds) = self.get_module_fds(is_64_bit)
{
client.send_fds(&module_fds)?;
}
// If we're not in system_server, we are done

View File

@ -17,7 +17,7 @@ impl<T, E: Display> ResultExt<T> for Result<T, E> {
match self {
Ok(r) => r,
Err(e) => {
eprintln!("error occurred: {}", e);
eprintln!("error occurred: {e}");
process::exit(1);
}
}
@ -40,6 +40,6 @@ pub fn gen_cxx_binding(name: &str) {
println!("cargo:rerun-if-changed=lib.rs");
let opt = Opt::default();
let code = cxx_gen::generate_header_and_cc_with_path("lib.rs", &opt);
write_if_diff(format!("{}.cpp", name), code.implementation.as_slice()).ok_or_exit();
write_if_diff(format!("{}.hpp", name), code.header.as_slice()).ok_or_exit();
write_if_diff(format!("{name}.cpp"), code.implementation.as_slice()).ok_or_exit();
write_if_diff(format!("{name}.hpp"), code.header.as_slice()).ok_or_exit();
}

View File

@ -42,7 +42,7 @@ fn print_usage(cmd: &str) {
eprintln!(
r#"MagiskPolicy - SELinux Policy Patch Tool
Usage: {} [--options...] [policy statements...]
Usage: {cmd} [--options...] [policy statements...]
Options:
--help show help message for policy statements
@ -60,8 +60,7 @@ Options:
If neither --load, --load-split, nor --compile-split is specified,
it will load from current live policies (/sys/fs/selinux/policy)
"#,
cmd
"#
);
format_statement_help(&mut FmtAdaptor(&mut stderr())).ok();

View File

@ -504,7 +504,7 @@ impl Display for Token<'_> {
Token::ST => f.write_char('*'),
Token::TL => f.write_char('~'),
Token::HP => f.write_char('-'),
Token::HX(n) => f.write_fmt(format_args!("{:06X}", n)),
Token::HX(n) => f.write_fmt(format_args!("{n:06X}")),
Token::ID(s) => f.write_str(s),
}
}