1 // Copyright 2017 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef FILE_UTILS_H_ 6 #define FILE_UTILS_H_ 7 8 #include <dirent.h> 9 #include <sys/types.h> 10 #include <unistd.h> 11 12 #include <functional> 13 #include <map> 14 #include <memory> 15 16 #include "logging.h" 17 18 namespace file_utils { 19 20 // RAII classes for auto-releasing fd/dirs. 21 template <typename RESOURCE_TYPE, int (*CLOSE_FN)(RESOURCE_TYPE)> 22 struct ScopedResource { ScopedResourceScopedResource23 explicit ScopedResource(RESOURCE_TYPE r) : r_(r) { CHECK(r); } ~ScopedResourceScopedResource24 ~ScopedResource() { CLOSE_FN(r_); } 25 RESOURCE_TYPE r_; 26 }; 27 28 using ScopedFD = ScopedResource<int, close>; 29 using ScopedDir = ScopedResource<DIR*, closedir>; 30 31 // Invokes predicate(pid) for each folder in |proc_path|/[0-9]+ which has 32 // a numeric name (typically pids and tids). 33 void ForEachPidInProcPath(const char* proc_path, 34 std::function<void(int)> predicate); 35 36 // Reads the contents of |path| fully into |buf| up to |length| chars. 37 // |buf| is guaranteed to be null terminated. 38 ssize_t ReadFile(const char* path, char* buf, size_t length); 39 40 // Reads a single-line file, stripping out any \0, \r, \n and replacing 41 // non-printable charcters with '?'. |buf| is guaranteed to be null terminated. 42 bool ReadFileTrimmed(const char* path, char* buf, size_t length); 43 44 // Convenience wrappers for /proc/|pid|/|proc_file| paths. 45 ssize_t ReadProcFile(int pid, const char* proc_file, char* buf, size_t length); 46 bool ReadProcFileTrimmed(int pid, 47 const char* proc_file, 48 char* buf, 49 size_t length); 50 51 // Takes a C string buffer and chunks it into lines without creating any 52 // copies. It modifies the original buffer, by replacing \n with \0. 53 class LineReader { 54 public: 55 LineReader(char* buf, size_t size); 56 ~LineReader(); 57 58 const char* NextLine(); 59 60 private: 61 char* ptr_; 62 char* end_; 63 }; 64 65 } // namespace file_utils 66 67 #endif // FILE_UTILS_H_ 68