Isabelle Taylor | d15631b | 2018-02-12 10:32:41 +0000 | [diff] [blame] | 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 | |
Isabelle Taylor | d404ea1 | 2018-02-19 17:28:01 +0000 | [diff] [blame] | 5 | #ifndef SRC_PROCESS_STATS_FILE_UTILS_H_ |
| 6 | #define SRC_PROCESS_STATS_FILE_UTILS_H_ |
Isabelle Taylor | d15631b | 2018-02-12 10:32:41 +0000 | [diff] [blame] | 7 | |
| 8 | #include <ctype.h> |
| 9 | #include <dirent.h> |
| 10 | #include <sys/types.h> |
| 11 | #include <unistd.h> |
| 12 | |
| 13 | #include <functional> |
| 14 | #include <map> |
| 15 | #include <memory> |
| 16 | |
| 17 | namespace file_utils { |
| 18 | |
| 19 | // TODO(taylori): Migrate to using perfetto:base:ScopedFD. |
| 20 | |
| 21 | // RAII classes for auto-releasing fd/dirs. |
| 22 | template <typename RESOURCE_TYPE, int (*CLOSE_FN)(RESOURCE_TYPE)> |
| 23 | struct ScopedResource { |
| 24 | explicit ScopedResource(RESOURCE_TYPE r) : r_(r) {} |
| 25 | ~ScopedResource() { CLOSE_FN(r_); } |
| 26 | RESOURCE_TYPE r_; |
| 27 | }; |
| 28 | |
| 29 | using ScopedFD = ScopedResource<int, close>; |
| 30 | using ScopedDir = ScopedResource<DIR*, closedir>; |
| 31 | |
| 32 | bool IsNumeric(const char* str); |
| 33 | |
| 34 | // Invokes predicate(pid) for each folder in |proc_path|/[0-9]+ which has |
| 35 | // a numeric name (typically pids and tids). |
| 36 | void ForEachPidInProcPath(const char* proc_path, |
| 37 | std::function<void(int)> predicate); |
| 38 | |
| 39 | // Reads the contents of |path| fully into |buf| up to |length| chars. |
| 40 | // |buf| is guaranteed to be null terminated. |
| 41 | ssize_t ReadFile(const char* path, char* buf, size_t length); |
| 42 | |
| 43 | // Reads a single-line file, stripping out any \0, \r, \n and replacing |
| 44 | // non-printable charcters with '?'. |buf| is guaranteed to be null terminated. |
| 45 | bool ReadFileTrimmed(const char* path, char* buf, size_t length); |
| 46 | |
| 47 | // Convenience wrappers for /proc/|pid|/|proc_file| paths. |
| 48 | ssize_t ReadProcFile(int pid, const char* proc_file, char* buf, size_t length); |
| 49 | bool ReadProcFileTrimmed(int pid, |
| 50 | const char* proc_file, |
| 51 | char* buf, |
| 52 | size_t length); |
| 53 | |
| 54 | // Takes a C string buffer and chunks it into lines without creating any |
| 55 | // copies. It modifies the original buffer, by replacing \n with \0. |
| 56 | class LineReader { |
| 57 | public: |
| 58 | LineReader(char* buf, size_t size); |
| 59 | ~LineReader(); |
| 60 | |
| 61 | const char* NextLine(); |
| 62 | |
| 63 | private: |
| 64 | char* ptr_; |
| 65 | char* end_; |
| 66 | }; |
| 67 | |
| 68 | } // namespace file_utils |
| 69 | |
Isabelle Taylor | d404ea1 | 2018-02-19 17:28:01 +0000 | [diff] [blame] | 70 | #endif // SRC_PROCESS_STATS_FILE_UTILS_H_ |