diff --git a/native/src/base/files.rs b/native/src/base/files.rs index 711a07e2d..6c8b721b3 100644 --- a/native/src/base/files.rs +++ b/native/src/base/files.rs @@ -583,7 +583,7 @@ impl FsPathBuilder for S { } fn append_path_fmt(&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(&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 { pub fn parse_mount_info(pid: &str) -> Vec { 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) diff --git a/native/src/base/misc.rs b/native/src/base/misc.rs index 2fa2a1c9e..c72ea5615 100644 --- a/native/src/base/misc.rs +++ b/native/src/base/misc.rs @@ -99,7 +99,7 @@ impl EarlyExitExt for Result { exit(0) } Err(_) => { - eprintln!("{}", output); + eprintln!("{output}"); print_help_msg(); exit(1) } diff --git a/native/src/base/result.rs b/native/src/base/result.rs index 6971fcf9c..0fd3a458b 100644 --- a/native/src/base/result.rs +++ b/native/src/base/result.rs @@ -171,7 +171,7 @@ impl Loggable for Result { 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)) => { diff --git a/native/src/boot/cpio.rs b/native/src/boot/cpio.rs index 1d5875ef0..bfca2701a 100644 --- a/native/src/boot/cpio.rs +++ b/native/src/boot/cpio.rs @@ -269,13 +269,13 @@ impl Cpio { } fn load_from_file(path: &Utf8CStr) -> LoggedResult { - 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 => {} } diff --git a/native/src/boot/dtb.rs b/native/src/boot/dtb.rs index be1d44538..8a0050b24 100644 --- a/native/src/boot/dtb.rs +++ b/native/src/boot/dtb.rs @@ -131,9 +131,9 @@ fn print_node(node: &FdtNode) { } ); } else if size > MAX_PRINT_LEN { - println!("[{}]: ({})", name, size); + println!("[{name}]: ({size})"); } else { - println!("[{}]: {:02x?}", name, value); + println!("[{name}]: {value:02x?}"); } } @@ -154,7 +154,7 @@ fn for_each_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 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 { &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; } }); diff --git a/native/src/boot/patch.rs b/native/src/boot/patch.rs index d9fecd580..fc5ee660c 100644 --- a/native/src/boot/patch.rs +++ b/native/src/boot/patch.rs @@ -45,7 +45,7 @@ fn remove_pattern(buf: &mut [u8], pattern_matcher: unsafe fn(&[u8]) -> Option 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() }; diff --git a/native/src/boot/payload.rs b/native/src/boot/payload.rs index c43d626bc..e6cf7c423 100644 --- a/native/src/boot/payload.rs +++ b/native/src/boot/payload.rs @@ -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)?; diff --git a/native/src/core/daemon.rs b/native/src/core/daemon.rs index 85884b9fe..1e80798a1 100644 --- a/native/src/core/daemon.rs +++ b/native/src/core/daemon.rs @@ -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(); } } diff --git a/native/src/core/logging.rs b/native/src/core/logging.rs index 962dc97db..26fa78ff7 100644 --- a/native/src/core/logging.rs +++ b/native/src/core/logging.rs @@ -131,7 +131,7 @@ fn write_log_to_pipe(mut logd: &File, prio: i32, msg: &Utf8CStr) -> io::Result>> = Mutex::new(None); fn with_logd_fd io::Result>(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; } } diff --git a/native/src/core/module.rs b/native/src/core/module.rs index 5f24f69cb..8c4538e90 100644 --- a/native/src/core/module.rs +++ b/native/src/core/module.rs @@ -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)); } } diff --git a/native/src/core/mount.rs b/native/src/core/mount.rs index e84395ab0..d0021d709 100644 --- a/native/src/core/mount.rs +++ b/native/src/core/mount.rs @@ -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 = 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 diff --git a/native/src/core/resetprop/persist.rs b/native/src/core/resetprop/persist.rs index f666071ac..86eab0d1b 100644 --- a/native/src/core/resetprop/persist.rs +++ b/native/src/core/resetprop/persist.rs @@ -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) diff --git a/native/src/core/selinux.rs b/native/src/core/selinux.rs index 1cd248004..dd07f583e 100644 --- a/native/src/core/selinux.rs +++ b/native/src/core/selinux.rs @@ -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(); diff --git a/native/src/core/su/pts.rs b/native/src/core/su/pts.rs index f6dfa59bd..9d4cb087f 100644 --- a/native/src/core/su/pts.rs +++ b/native/src/core/su/pts.rs @@ -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 diff --git a/native/src/core/zygisk/daemon.rs b/native/src/core/zygisk/daemon.rs index eb398e899..2dafc4498 100644 --- a/native/src/core/zygisk/daemon.rs +++ b/native/src/core/zygisk/daemon.rs @@ -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 diff --git a/native/src/include/codegen.rs b/native/src/include/codegen.rs index d8414b656..df221a414 100644 --- a/native/src/include/codegen.rs +++ b/native/src/include/codegen.rs @@ -17,7 +17,7 @@ impl ResultExt for Result { 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(); } diff --git a/native/src/sepolicy/cli.rs b/native/src/sepolicy/cli.rs index cdbd7f933..85240359a 100644 --- a/native/src/sepolicy/cli.rs +++ b/native/src/sepolicy/cli.rs @@ -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(); diff --git a/native/src/sepolicy/statement.rs b/native/src/sepolicy/statement.rs index 9da73c5c5..9922cd394 100644 --- a/native/src/sepolicy/statement.rs +++ b/native/src/sepolicy/statement.rs @@ -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), } }