blob: a853ecda61723bcd18239375727c83d09a2b79ea [file] [log] [blame]
Isabelle Taylord15631b2018-02-12 10:32:41 +00001// 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 Taylord404ea12018-02-19 17:28:01 +00005#ifndef SRC_PROCESS_STATS_FILE_UTILS_H_
6#define SRC_PROCESS_STATS_FILE_UTILS_H_
Isabelle Taylord15631b2018-02-12 10:32:41 +00007
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
17namespace file_utils {
18
19// TODO(taylori): Migrate to using perfetto:base:ScopedFD.
20
21// RAII classes for auto-releasing fd/dirs.
22template <typename RESOURCE_TYPE, int (*CLOSE_FN)(RESOURCE_TYPE)>
23struct ScopedResource {
24 explicit ScopedResource(RESOURCE_TYPE r) : r_(r) {}
25 ~ScopedResource() { CLOSE_FN(r_); }
26 RESOURCE_TYPE r_;
27};
28
29using ScopedFD = ScopedResource<int, close>;
30using ScopedDir = ScopedResource<DIR*, closedir>;
31
32bool 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).
36void 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.
41ssize_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.
45bool ReadFileTrimmed(const char* path, char* buf, size_t length);
46
47// Convenience wrappers for /proc/|pid|/|proc_file| paths.
48ssize_t ReadProcFile(int pid, const char* proc_file, char* buf, size_t length);
49bool 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.
56class 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 Taylord404ea12018-02-19 17:28:01 +000070#endif // SRC_PROCESS_STATS_FILE_UTILS_H_