From 16c727b65c90772dc8d01d7ee5af3835d5e84de1 Mon Sep 17 00:00:00 2001 From: Dean Lee Date: Mon, 9 Aug 2021 17:56:45 +0800 Subject: [PATCH] fix: util::file_exists will return false on no permissions (#21880) * fix bug * add test case old-commit-hash: 3a7959b5ffff6f866e592fc815692ec469f4fbb6 --- selfdrive/common/tests/test_util.cc | 24 ++++++++++++++++++++++++ selfdrive/common/util.cc | 6 ++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/selfdrive/common/tests/test_util.cc b/selfdrive/common/tests/test_util.cc index 06261d01ad..d61ca38886 100644 --- a/selfdrive/common/tests/test_util.cc +++ b/selfdrive/common/tests/test_util.cc @@ -1,5 +1,6 @@ #include +#include #include #include @@ -51,3 +52,26 @@ TEST_CASE("util::read_file") { REQUIRE(util::read_file("/proc/kmsg").empty()); } } + +TEST_CASE("util::file_exists") { + char filename[] = "/tmp/test_file_exists_XXXXXX"; + int fd = mkstemp(filename); + REQUIRE(fd != -1); + close(fd); + + SECTION("existent file") { + REQUIRE(util::file_exists(filename)); + REQUIRE(util::file_exists("/tmp")); + } + SECTION("nonexistent file") { + std::string fn = filename; + REQUIRE(!util::file_exists(fn + "/nonexistent")); + } + SECTION("file has no access permissions") { + std::string fn = "/proc/kmsg"; + std::ifstream f(fn); + REQUIRE(f.good() == false); + REQUIRE(util::file_exists(fn)); + } + ::remove(filename); +} diff --git a/selfdrive/common/util.cc b/selfdrive/common/util.cc index 2771d76668..cf570430e4 100644 --- a/selfdrive/common/util.cc +++ b/selfdrive/common/util.cc @@ -1,5 +1,7 @@ #include "selfdrive/common/util.h" +#include + #include #include #include @@ -113,8 +115,8 @@ std::string readlink(const std::string &path) { } bool file_exists(const std::string& fn) { - std::ifstream f(fn); - return f.good(); + struct stat st = {}; + return stat(fn.c_str(), &st) != -1; } std::string getenv(const char* key, const char* default_val) {