From e9f562a8b76be91513cd253d6633772e3e5dd1c3 Mon Sep 17 00:00:00 2001 From: LoveSy Date: Wed, 2 Feb 2022 18:39:13 +0800 Subject: [PATCH] Fix abuse of `fdopendir` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After `fdopendir`, the fd is no longer usable. Should dup and make use of RAII Co-authored-by: 残页 <31466456+canyie@users.noreply.github.com> --- native/jni/core/restorecon.cpp | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/native/jni/core/restorecon.cpp b/native/jni/core/restorecon.cpp index b97de1d0d..307866648 100644 --- a/native/jni/core/restorecon.cpp +++ b/native/jni/core/restorecon.cpp @@ -15,7 +15,6 @@ using namespace std; static void restore_syscon(int dirfd) { struct dirent *entry; - DIR *dir; char *con; if (fgetfilecon(dirfd, &con) >= 0) { @@ -24,11 +23,12 @@ static void restore_syscon(int dirfd) { freecon(con); } - dir = xfdopendir(dirfd); - while ((entry = xreaddir(dir))) { + auto dir = xopen_dir(dirfd); + while ((entry = xreaddir(dir.get()))) { int fd = openat(dirfd, entry->d_name, O_RDONLY | O_CLOEXEC); if (entry->d_type == DT_DIR) { restore_syscon(fd); + continue; } else if (entry->d_type == DT_REG) { if (fgetfilecon(fd, &con) >= 0) { if (con[0] == '\0' || strcmp(con, UNLABEL_CON) == 0 || strcmp(con, ADB_CON) == 0) @@ -47,16 +47,16 @@ static void restore_syscon(int dirfd) { static void restore_magiskcon(int dirfd) { struct dirent *entry; - DIR *dir; fsetfilecon(dirfd, MAGISK_CON); fchown(dirfd, 0, 0); - dir = xfdopendir(dirfd); - while ((entry = xreaddir(dir))) { + auto dir = xopen_dir(dirfd); + while ((entry = xreaddir(dir.get()))) { int fd = xopenat(dirfd, entry->d_name, O_RDONLY | O_CLOEXEC); if (entry->d_type == DT_DIR) { restore_magiskcon(fd); + continue; } else if (entry->d_type) { fsetfilecon(fd, MAGISK_CON); fchown(fd, 0, 0); @@ -71,12 +71,8 @@ void restorecon() { lsetfilecon(SECURE_DIR, ADB_CON); close(fd); lsetfilecon(MODULEROOT, SYSTEM_CON); - fd = xopen(MODULEROOT, O_RDONLY | O_CLOEXEC); - restore_syscon(fd); - close(fd); - fd = xopen(DATABIN, O_RDONLY | O_CLOEXEC); - restore_magiskcon(fd); - close(fd); + restore_syscon(xopen(MODULEROOT, O_RDONLY | O_CLOEXEC)); + restore_magiskcon(xopen(DATABIN, O_RDONLY | O_CLOEXEC)); } void restore_tmpcon() {