1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // This file contains internal routines that are called by other files in
6 // base/process/.
7
8 #ifndef BASE_PROCESS_INTERNAL_LINUX_H_
9 #define BASE_PROCESS_INTERNAL_LINUX_H_
10
11 #include <stddef.h>
12 #include <stdint.h>
13 #include <unistd.h>
14
15 #include <optional>
16 #include <string>
17 #include <string_view>
18 #include <vector>
19
20 #include "base/containers/span.h"
21 #include "base/files/dir_reader_posix.h"
22 #include "base/files/file_path.h"
23 #include "base/process/process_handle.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_split.h"
26 #include "base/threading/platform_thread.h"
27
28 namespace base {
29
30 class Time;
31 class TimeDelta;
32
33 namespace internal {
34
35 // "/proc"
36 extern const char kProcDir[];
37
38 // "stat"
39 extern const char kStatFile[];
40
41 // Returns a FilePath to "/proc/pid".
42 BASE_EXPORT base::FilePath GetProcPidDir(pid_t pid);
43
44 // Reads a file from /proc into a string. This is allowed on any thread as
45 // reading from /proc does not hit the disk. Returns true if the file can be
46 // read and is non-empty.
47 bool ReadProcFile(const FilePath& file, std::string* buffer);
48
49 // Take a /proc directory entry named |d_name|, and if it is the directory for
50 // a process, convert it to a pid_t.
51 // Returns 0 on failure.
52 // e.g. /proc/self/ will return 0, whereas /proc/1234 will return 1234.
53 pid_t ProcDirSlotToPid(const char* d_name);
54
55 // Read |filename| in /proc/<pid>/, split the entries into key/value pairs, and
56 // trim the key and value. On success, return true and write the trimmed
57 // key/value pairs into |key_value_pairs|.
58 bool ReadProcFileToTrimmedStringPairs(pid_t pid,
59 std::string_view filename,
60 StringPairs* key_value_pairs);
61
62 // Read /proc/<pid>/status and return the value for |field|, or 0 on failure.
63 // Only works for fields in the form of "Field: value kB".
64 size_t ReadProcStatusAndGetKbFieldAsSizeT(pid_t pid, std::string_view field);
65
66 // Read /proc/<pid>/status and look for |field|. On success, return true and
67 // write the value for |field| into |result|.
68 // Only works for fields in the form of "field : uint_value"
69 bool ReadProcStatusAndGetFieldAsUint64(pid_t pid,
70 std::string_view field,
71 uint64_t* result);
72
73 // Reads /proc/<pid>/stat into |buffer|. Returns true if the file can be read
74 // and is non-empty.
75 bool ReadProcStats(pid_t pid, std::string* buffer);
76
77 // Takes |stats_data| and populates |proc_stats| with the values split by
78 // spaces. Taking into account the 2nd field may, in itself, contain spaces.
79 // Returns true if successful.
80 bool ParseProcStats(const std::string& stats_data,
81 std::vector<std::string>* proc_stats);
82
83 // Fields from /proc/<pid>/stat, 0-based. See man 5 proc.
84 // If the ordering ever changes, carefully review functions that use these
85 // values.
86 enum ProcStatsFields {
87 VM_COMM = 1, // Filename of executable, without parentheses.
88 VM_STATE = 2, // Letter indicating the state of the process.
89 VM_PPID = 3, // PID of the parent.
90 VM_PGRP = 4, // Process group id.
91 VM_MINFLT = 9, // Minor page fault count excluding children.
92 VM_MAJFLT = 11, // Major page fault count excluding children.
93 VM_UTIME = 13, // Time scheduled in user mode in clock ticks.
94 VM_STIME = 14, // Time scheduled in kernel mode in clock ticks.
95 VM_NUMTHREADS = 19, // Number of threads.
96 VM_STARTTIME = 21, // The time the process started in clock ticks.
97 VM_VSIZE = 22, // Virtual memory size in bytes.
98 VM_RSS = 23, // Resident Set Size in pages.
99 };
100
101 // Reads the |field_num|th field from |proc_stats|. Returns 0 on failure.
102 // This version does not handle the first 3 values, since the first value is
103 // simply |pid|, and the next two values are strings.
104 int64_t GetProcStatsFieldAsInt64(const std::vector<std::string>& proc_stats,
105 ProcStatsFields field_num);
106
107 // Reads the `field_num`th field from `proc_stats`. Asserts that `field_num` is
108 // a valid index into `proc_stats`. Returns nullopt if the field doesn't contain
109 // a valid integer.
110 std::optional<int64_t> GetProcStatsFieldAsOptionalInt64(
111 base::span<const std::string> proc_stats,
112 ProcStatsFields field_num);
113
114 // Same as GetProcStatsFieldAsInt64(), but for size_t values.
115 size_t GetProcStatsFieldAsSizeT(const std::vector<std::string>& proc_stats,
116 ProcStatsFields field_num);
117
118 // Convenience wrappers around GetProcStatsFieldAsInt64(), ParseProcStats() and
119 // ReadProcStats(). See GetProcStatsFieldAsInt64() for details.
120 int64_t ReadStatsFilendGetFieldAsInt64(const FilePath& stat_file,
121 ProcStatsFields field_num);
122 int64_t ReadProcStatsAndGetFieldAsInt64(pid_t pid, ProcStatsFields field_num);
123 int64_t ReadProcSelfStatsAndGetFieldAsInt64(ProcStatsFields field_num);
124
125 // Same as ReadProcStatsAndGetFieldAsInt64() but for size_t values.
126 size_t ReadProcStatsAndGetFieldAsSizeT(pid_t pid,
127 ProcStatsFields field_num);
128
129 // Returns the time that the OS started. Clock ticks are relative to this.
130 Time GetBootTime();
131
132 // Returns the amount of time spent in user space since boot across all CPUs.
133 TimeDelta GetUserCpuTimeSinceBoot();
134
135 // Converts Linux clock ticks to a wall time delta.
136 TimeDelta ClockTicksToTimeDelta(int64_t clock_ticks);
137
138 // Executes the lambda for every task in the process's /proc/<pid>/task
139 // directory. The thread id and file path of the task directory are provided as
140 // arguments to the lambda.
141 template <typename Lambda>
ForEachProcessTask(base::ProcessHandle process,Lambda && lambda)142 void ForEachProcessTask(base::ProcessHandle process, Lambda&& lambda) {
143 // Iterate through the different threads tracked in /proc/<pid>/task.
144 FilePath fd_path = GetProcPidDir(process).Append("task");
145
146 DirReaderPosix dir_reader(fd_path.value().c_str());
147 if (!dir_reader.IsValid())
148 return;
149
150 for (; dir_reader.Next();) {
151 const char* tid_str = dir_reader.name();
152 if (strcmp(tid_str, ".") == 0 || strcmp(tid_str, "..") == 0)
153 continue;
154
155 PlatformThreadId tid;
156 if (!StringToInt(tid_str, &tid))
157 continue;
158
159 FilePath task_path = fd_path.Append(tid_str);
160 lambda(tid, task_path);
161 }
162 }
163
164 } // namespace internal
165 } // namespace base
166
167 #endif // BASE_PROCESS_INTERNAL_LINUX_H_
168