• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/threading/platform_thread.h"
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   VM_COMM = 1,         // Filename of executable, without parentheses.
65   VM_STATE = 2,        // Letter indicating the state of the process.
66   VM_PPID = 3,         // PID of the parent.
67   VM_PGRP = 4,         // Process group id.
68   VM_MINFLT = 9,       // Minor page fault count excluding children.
69   VM_MAJFLT = 11,      // Major page fault count excluding children.
70   VM_UTIME = 13,       // Time scheduled in user mode in clock ticks.
71   VM_STIME = 14,       // Time scheduled in kernel mode in clock ticks.
72   VM_NUMTHREADS = 19,  // Number of threads.
73   VM_STARTTIME = 21,   // The time the process started in clock ticks.
74   VM_VSIZE = 22,       // Virtual memory size in bytes.
75   VM_RSS = 23,         // Resident Set Size in pages.
76 };
77 
78 // Reads the |field_num|th field from |proc_stats|. Returns 0 on failure.
79 // This version does not handle the first 3 values, since the first value is
80 // simply |pid|, and the next two values are strings.
81 int64_t GetProcStatsFieldAsInt64(const std::vector<std::string>& proc_stats,
82                                  ProcStatsFields field_num);
83 
84 // Same as GetProcStatsFieldAsInt64(), but for size_t values.
85 size_t GetProcStatsFieldAsSizeT(const std::vector<std::string>& proc_stats,
86                                 ProcStatsFields field_num);
87 
88 // Convenience wrappers around GetProcStatsFieldAsInt64(), ParseProcStats() and
89 // ReadProcStats(). See GetProcStatsFieldAsInt64() for details.
90 int64_t ReadStatsFilendGetFieldAsInt64(const FilePath& stat_file,
91                                        ProcStatsFields field_num);
92 int64_t ReadProcStatsAndGetFieldAsInt64(pid_t pid, ProcStatsFields field_num);
93 int64_t ReadProcSelfStatsAndGetFieldAsInt64(ProcStatsFields field_num);
94 
95 // Same as ReadProcStatsAndGetFieldAsInt64() but for size_t values.
96 size_t ReadProcStatsAndGetFieldAsSizeT(pid_t pid,
97                                        ProcStatsFields field_num);
98 
99 // Returns the time that the OS started. Clock ticks are relative to this.
100 Time GetBootTime();
101 
102 // Returns the amount of time spent in user space since boot across all CPUs.
103 TimeDelta GetUserCpuTimeSinceBoot();
104 
105 // Converts Linux clock ticks to a wall time delta.
106 TimeDelta ClockTicksToTimeDelta(int64_t clock_ticks);
107 
108 // Executes the lambda for every task in the process's /proc/<pid>/task
109 // directory. The thread id and file path of the task directory are provided as
110 // arguments to the lambda.
111 template <typename Lambda>
ForEachProcessTask(base::ProcessHandle process,Lambda && lambda)112 void ForEachProcessTask(base::ProcessHandle process, Lambda&& lambda) {
113   // Iterate through the different threads tracked in /proc/<pid>/task.
114   FilePath fd_path = GetProcPidDir(process).Append("task");
115 
116   DirReaderPosix dir_reader(fd_path.value().c_str());
117   if (!dir_reader.IsValid())
118     return;
119 
120   for (; dir_reader.Next();) {
121     const char* tid_str = dir_reader.name();
122     if (strcmp(tid_str, ".") == 0 || strcmp(tid_str, "..") == 0)
123       continue;
124 
125     PlatformThreadId tid;
126     if (!StringToInt(tid_str, &tid))
127       continue;
128 
129     FilePath task_path = fd_path.Append(tid_str);
130     lambda(tid, task_path);
131   }
132 }
133 
134 }  // namespace internal
135 }  // namespace base
136 
137 #endif  // BASE_PROCESS_INTERNAL_LINUX_H_
138