From 7cb72c96b4d5ede1b5526a526ccb7dae0490bb0e Mon Sep 17 00:00:00 2001 From: Bernie Innocenti Date: Thu, 28 Mar 2019 15:32:37 +0900 Subject: [PATCH] Disallow operator!() on unique_fd This catches a common mistake where client code checks for errors using the common idiom that works for std::iostream and other file-like classes: unique_fd fd = open(...); if (!fd) { } Test: atest libbase_test Test: m droid Change-Id: I9629a7795537ecb3b57be9c741c06f80967e4cc2 --- base/include/android-base/unique_fd.h | 3 +++ init/service.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/base/include/android-base/unique_fd.h b/base/include/android-base/unique_fd.h index 83213e9c4..3fa3bea2e 100644 --- a/base/include/android-base/unique_fd.h +++ b/base/include/android-base/unique_fd.h @@ -105,6 +105,9 @@ class unique_fd_impl final { int get() const { return fd_; } operator int() const { return get(); } // NOLINT + // Catch bogus error checks (i.e.: "!fd" instead of "fd != -1"). + bool operator!() const = delete; + int release() __attribute__((warn_unused_result)) { tag(fd_, this, nullptr); int ret = fd_; diff --git a/init/service.cpp b/init/service.cpp index 6d08cb14a..f5c13b983 100644 --- a/init/service.cpp +++ b/init/service.cpp @@ -177,7 +177,7 @@ Result Service::SetUpPidNamespace() const { Result Service::EnterNamespaces() const { for (const auto& [nstype, path] : namespaces_to_enter_) { auto fd = unique_fd{open(path.c_str(), O_RDONLY | O_CLOEXEC)}; - if (!fd) { + if (fd == -1) { return ErrnoError() << "Could not open namespace at " << path; } if (setns(fd, nstype) == -1) {