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