POSIX: CHECK() that file_util::ScopedFD fulfills promise.
CHECK() that file_util::ScopedFD will actually close the file descriptors.
There are security implications to not doing so, and logging an error is not
enough: file descriptor are security capabilities. Failing to close them is a
failure to revoke access to certain resources, which is heavily relied on in the
code base.
This CL also adds unit tests to file_util::ScopedFD.
Review URL: https://codereview.chromium.org/183953004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@254129 0039d316-1c4b-4281-b951-d872f2087c98
CrOS-Libchrome-Original-Commit: fb73aed94a95f568a846644cd60021b2c5569274
diff --git a/base/file_util_unittest.cc b/base/file_util_unittest.cc
index e7c43ff..e410c64 100644
--- a/base/file_util_unittest.cc
+++ b/base/file_util_unittest.cc
@@ -12,6 +12,12 @@
#include <winioctl.h>
#endif
+#if defined(OS_POSIX)
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#endif
+
#include <algorithm>
#include <fstream>
#include <set>
@@ -2463,6 +2469,43 @@
}
#endif
+TEST(ScopedFD, ScopedFDDoesClose) {
+ int fds[2];
+ char c = 0;
+ ASSERT_EQ(0, pipe(fds));
+ const int write_end = fds[1];
+ file_util::ScopedFDCloser read_end_closer(fds);
+ {
+ file_util::ScopedFDCloser write_end_closer(fds + 1);
+ }
+ // This is the only thread. This file descriptor should no longer be valid.
+ int ret = close(write_end);
+ EXPECT_EQ(-1, ret);
+ EXPECT_EQ(EBADF, errno);
+ // Make sure read(2) won't block.
+ ASSERT_EQ(0, fcntl(fds[0], F_SETFL, O_NONBLOCK));
+ // Reading the pipe should EOF.
+ EXPECT_EQ(0, read(fds[0], &c, 1));
+}
+
+#if defined(GTEST_HAS_DEATH_TEST)
+void CloseWithScopedFD(int fd) {
+ file_util::ScopedFDCloser fd_closer(&fd);
+}
+#endif
+
+TEST(ScopedFD, ScopedFDCrashesOnCloseFailure) {
+ int fds[2];
+ ASSERT_EQ(0, pipe(fds));
+ file_util::ScopedFDCloser read_end_closer(fds);
+ EXPECT_EQ(0, IGNORE_EINTR(close(fds[1])));
+#if defined(GTEST_HAS_DEATH_TEST)
+ // This is the only thread. This file descriptor should no longer be valid.
+ // Trying to close it should crash. This is important for security.
+ EXPECT_DEATH(CloseWithScopedFD(fds[1]), "");
+#endif
+}
+
#endif // defined(OS_POSIX)
} // namespace