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 #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/process/internal_linux.h"
12 #include "base/strings/string_split.h"
13 #include "base/strings/string_util.h"
14 #include "base/threading/thread_restrictions.h"
15 
16 namespace base {
17 
18 namespace {
19 
20 // Reads the |field_num|th field from |proc_stats|.
21 // Returns an empty string on failure.
22 // This version only handles VM_COMM and VM_STATE, which are the only fields
23 // that are strings.
GetProcStatsFieldAsString(const std::vector<std::string> & proc_stats,internal::ProcStatsFields field_num)24 std::string GetProcStatsFieldAsString(
25     const std::vector<std::string>& proc_stats,
26     internal::ProcStatsFields field_num) {
27   if (field_num < internal::VM_COMM || field_num > internal::VM_STATE) {
28     NOTREACHED();
29     return std::string();
30   }
31 
32   if (proc_stats.size() > static_cast<size_t>(field_num))
33     return proc_stats[field_num];
34 
35   NOTREACHED();
36   return 0;
37 }
38 
39 // Reads /proc/<pid>/cmdline and populates |proc_cmd_line_args| with the command
40 // line arguments. Returns true if successful.
41 // Note: /proc/<pid>/cmdline contains command line arguments separated by single
42 // null characters. We tokenize it into a vector of strings using '\0' as a
43 // delimiter.
GetProcCmdline(pid_t pid,std::vector<std::string> * proc_cmd_line_args)44 bool GetProcCmdline(pid_t pid, std::vector<std::string>* proc_cmd_line_args) {
45   // Synchronously reading files in /proc is safe.
46   ThreadRestrictions::ScopedAllowIO allow_io;
47 
48   FilePath cmd_line_file = internal::GetProcPidDir(pid).Append("cmdline");
49   std::string cmd_line;
50   if (!ReadFileToString(cmd_line_file, &cmd_line))
51     return false;
52   std::string delimiters;
53   delimiters.push_back('\0');
54   *proc_cmd_line_args = SplitString(cmd_line, delimiters, KEEP_WHITESPACE,
55                                     SPLIT_WANT_NONEMPTY);
56   return true;
57 }
58 
59 }  // namespace
60 
ProcessIterator(const ProcessFilter * filter)61 ProcessIterator::ProcessIterator(const ProcessFilter* filter)
62     : filter_(filter) {
63   procfs_dir_ = opendir(internal::kProcDir);
64 }
65 
~ProcessIterator()66 ProcessIterator::~ProcessIterator() {
67   if (procfs_dir_) {
68     closedir(procfs_dir_);
69     procfs_dir_ = NULL;
70   }
71 }
72 
CheckForNextProcess()73 bool ProcessIterator::CheckForNextProcess() {
74   // TODO(port): skip processes owned by different UID
75 
76   pid_t pid = kNullProcessId;
77   std::vector<std::string> cmd_line_args;
78   std::string stats_data;
79   std::vector<std::string> proc_stats;
80 
81   // Arbitrarily guess that there will never be more than 200 non-process
82   // files in /proc.  Hardy has 53 and Lucid has 61.
83   int skipped = 0;
84   const int kSkipLimit = 200;
85   while (skipped < kSkipLimit) {
86     dirent* slot = readdir(procfs_dir_);
87     // all done looking through /proc?
88     if (!slot)
89       return false;
90 
91     // If not a process, keep looking for one.
92     pid = internal::ProcDirSlotToPid(slot->d_name);
93     if (!pid) {
94       skipped++;
95       continue;
96     }
97 
98     if (!GetProcCmdline(pid, &cmd_line_args))
99       continue;
100 
101     if (!internal::ReadProcStats(pid, &stats_data))
102       continue;
103     if (!internal::ParseProcStats(stats_data, &proc_stats))
104       continue;
105 
106     std::string runstate =
107         GetProcStatsFieldAsString(proc_stats, internal::VM_STATE);
108     if (runstate.size() != 1) {
109       NOTREACHED();
110       continue;
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   if (skipped >= kSkipLimit) {
123     NOTREACHED();
124     return false;
125   }
126 
127   entry_.pid_ = pid;
128   entry_.ppid_ = GetProcStatsFieldAsInt64(proc_stats, internal::VM_PPID);
129   entry_.gid_ = GetProcStatsFieldAsInt64(proc_stats, internal::VM_PGRP);
130   entry_.cmd_line_args_.assign(cmd_line_args.begin(), cmd_line_args.end());
131   entry_.exe_file_ = GetProcessExecutablePath(pid).BaseName().value();
132   return true;
133 }
134 
IncludeEntry()135 bool NamedProcessIterator::IncludeEntry() {
136   if (executable_name_ != entry().exe_file())
137     return false;
138   return ProcessIterator::IncludeEntry();
139 }
140 
141 }  // namespace base
142