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 #include "base/process/process_iterator.h"
6
7 #include <stddef.h>
8
9 #include "base/files/file_util.h"
10 #include "base/logging.h"
11 #include "base/notreached.h"
12 #include "base/numerics/safe_conversions.h"
13 #include "base/process/internal_linux.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/string_util.h"
16 #include "base/threading/thread_restrictions.h"
17
18 namespace base {
19
20 class ScopedAllowBlockingForProc : public ScopedAllowBlocking {};
21
22 namespace {
23
24 // Reads the |field_num|th field from |proc_stats|.
25 // Returns an empty string on failure.
26 // This version only handles VM_COMM and VM_STATE, which are the only fields
27 // that are strings.
GetProcStatsFieldAsString(const std::vector<std::string> & proc_stats,internal::ProcStatsFields field_num)28 std::string GetProcStatsFieldAsString(
29 const std::vector<std::string>& proc_stats,
30 internal::ProcStatsFields field_num) {
31 if (field_num < internal::VM_COMM || field_num > internal::VM_STATE) {
32 NOTREACHED();
33 return std::string();
34 }
35
36 if (proc_stats.size() > static_cast<size_t>(field_num))
37 return proc_stats[field_num];
38
39 NOTREACHED();
40 return std::string();
41 }
42
43 // Reads /proc/<pid>/cmdline and populates |proc_cmd_line_args| with the command
44 // line arguments. Returns true if successful.
45 // Note: /proc/<pid>/cmdline contains command line arguments separated by single
46 // null characters. We tokenize it into a vector of strings using '\0' as a
47 // delimiter.
GetProcCmdline(pid_t pid,std::vector<std::string> * proc_cmd_line_args)48 bool GetProcCmdline(pid_t pid, std::vector<std::string>* proc_cmd_line_args) {
49 // Synchronously reading files in /proc is safe.
50 ScopedAllowBlockingForProc allow_blocking;
51
52 FilePath cmd_line_file = internal::GetProcPidDir(pid).Append("cmdline");
53 std::string cmd_line;
54 if (!ReadFileToString(cmd_line_file, &cmd_line))
55 return false;
56 std::string delimiters;
57 delimiters.push_back('\0');
58 *proc_cmd_line_args = SplitString(cmd_line, delimiters, KEEP_WHITESPACE,
59 SPLIT_WANT_NONEMPTY);
60 return true;
61 }
62
63 } // namespace
64
ProcessIterator(const ProcessFilter * filter)65 ProcessIterator::ProcessIterator(const ProcessFilter* filter)
66 : procfs_dir_(opendir(internal::kProcDir)), filter_(filter) {
67 if (!procfs_dir_) {
68 // On Android, SELinux may prevent reading /proc. See
69 // https://crbug.com/581517 for details.
70 PLOG(ERROR) << "opendir " << internal::kProcDir;
71 }
72 }
73
74 ProcessIterator::~ProcessIterator() = default;
75
CheckForNextProcess()76 bool ProcessIterator::CheckForNextProcess() {
77 // TODO(port): skip processes owned by different UID
78
79 if (!procfs_dir_) {
80 DLOG(ERROR) << "Skipping CheckForNextProcess(), no procfs_dir_";
81 return false;
82 }
83
84 pid_t pid = kNullProcessId;
85 std::vector<std::string> cmd_line_args;
86 std::string stats_data;
87 std::vector<std::string> proc_stats;
88
89 while (true) {
90 dirent* const slot = readdir(procfs_dir_.get());
91 // all done looking through /proc?
92 if (!slot)
93 return false;
94
95 // If not a process, keep looking for one.
96 pid = internal::ProcDirSlotToPid(slot->d_name);
97 if (!pid) {
98 continue;
99 }
100
101 if (!GetProcCmdline(pid, &cmd_line_args))
102 continue;
103
104 if (!internal::ReadProcStats(pid, &stats_data))
105 continue;
106 if (!internal::ParseProcStats(stats_data, &proc_stats))
107 continue;
108
109 std::string runstate =
110 GetProcStatsFieldAsString(proc_stats, internal::VM_STATE);
111 if (runstate.size() != 1) {
112 NOTREACHED();
113 continue;
114 }
115
116 // Is the process in 'Zombie' state, i.e. dead but waiting to be reaped?
117 // Allowed values: D R S T Z
118 if (runstate[0] != 'Z')
119 break;
120
121 // Nope, it's a zombie; somebody isn't cleaning up after their children.
122 // (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.)
123 // There could be a lot of zombies, can't really decrement i here.
124 }
125
126 entry_.pid_ = pid;
127 entry_.ppid_ = checked_cast<ProcessId>(
128 GetProcStatsFieldAsInt64(proc_stats, internal::VM_PPID));
129 entry_.gid_ = checked_cast<ProcessId>(
130 GetProcStatsFieldAsInt64(proc_stats, internal::VM_PGRP));
131 entry_.cmd_line_args_.assign(cmd_line_args.begin(), cmd_line_args.end());
132 entry_.exe_file_ = GetProcessExecutablePath(pid).BaseName().value();
133 return true;
134 }
135
IncludeEntry()136 bool NamedProcessIterator::IncludeEntry() {
137 if (executable_name_ != entry().exe_file())
138 return false;
139 return ProcessIterator::IncludeEntry();
140 }
141
142 } // namespace base
143