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