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