diff --git a/util/file/file_io.cc b/util/file/file_io.cc index 6cae837a..d196c9eb 100644 --- a/util/file/file_io.cc +++ b/util/file/file_io.cc @@ -156,6 +156,26 @@ void CheckedReadFileAtEOF(FileHandle file) { } } +bool LoggingReadEntireFile(const base::FilePath& path, std::string* contents) { + FileHandle handle = LoggingOpenFileForRead(path); + if (handle == kInvalidFileHandle) { + return false; + } + + char buffer[4096]; + FileOperationResult rv; + std::string local_contents; + while ((rv = ReadFile(handle, buffer, sizeof(buffer))) > 0) { + local_contents.append(buffer, rv); + } + if (rv < 0) { + PLOG(ERROR) << internal::kNativeReadFunctionName; + return false; + } + contents->swap(local_contents); + return true; +} + void CheckedCloseFile(FileHandle file) { CHECK(LoggingCloseFile(file)); } diff --git a/util/file/file_io.h b/util/file/file_io.h index 87c40702..c70dff30 100644 --- a/util/file/file_io.h +++ b/util/file/file_io.h @@ -17,6 +17,8 @@ #include +#include + #include "build/build_config.h" #if defined(OS_POSIX) @@ -306,6 +308,12 @@ void CheckedWriteFile(FileHandle file, const void* buffer, size_t size); //! \sa ReadFile void CheckedReadFileAtEOF(FileHandle file); +//! brief Wraps LoggingOpenFileForRead() and ReadFile() reading the entire file +//! into \a contents. +//! +//! \return `true` on success, or `false` with a message logged. +bool LoggingReadEntireFile(const base::FilePath& path, std::string* contents); + //! \brief Wraps `open()` or `CreateFile()`, opening an existing file for //! reading. //! diff --git a/util/posix/process_info_linux.cc b/util/posix/process_info_linux.cc index 60b7b7f8..65d96442 100644 --- a/util/posix/process_info_linux.cc +++ b/util/posix/process_info_linux.cc @@ -31,6 +31,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "util/file/delimited_file_reader.h" +#include "util/file/file_io.h" #include "util/file/file_reader.h" #include "util/linux/scoped_ptrace_attach.h" @@ -78,20 +79,6 @@ bool AdvancePastNumber(const char** input, T* value) { return false; } -bool ReadEntireFile(const char* path, std::string* contents) { - FileReader file; - if (!file.Open(base::FilePath(path))) { - return false; - } - - char buffer[4096]; - FileOperationResult length; - while ((length = file.Read(buffer, sizeof(buffer))) > 0) { - contents->append(buffer, length); - } - return length >= 0; -} - void SubtractTimespec(const timespec& t1, const timespec& t2, timespec* result) { result->tv_sec = t1.tv_sec - t2.tv_sec; @@ -391,7 +378,7 @@ bool ProcessInfo::StartTime(timeval* start_time) const { char path[32]; snprintf(path, sizeof(path), "/proc/%d/stat", pid_); std::string stat_contents; - if (!ReadEntireFile(path, &stat_contents)) { + if (!LoggingReadEntireFile(base::FilePath(path), &stat_contents)) { return false; }