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 <errno.h>
8#include <sys/sysctl.h>
9
10#include "base/logging.h"
11#include "base/strings/string_util.h"
12
13namespace base {
14
15ProcessIterator::ProcessIterator(const ProcessFilter* filter)
16    : index_of_kinfo_proc_(),
17      filter_(filter) {
18
19  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_UID, getuid(),
20                sizeof(struct kinfo_proc), 0 };
21
22  bool done = false;
23  int try_num = 1;
24  const int max_tries = 10;
25
26  do {
27    size_t len = 0;
28    if (sysctl(mib, arraysize(mib), NULL, &len, NULL, 0) < 0) {
29      DLOG(ERROR) << "failed to get the size needed for the process list";
30      kinfo_procs_.resize(0);
31      done = true;
32    } else {
33      size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
34      // Leave some spare room for process table growth (more could show up
35      // between when we check and now)
36      num_of_kinfo_proc += 16;
37      kinfo_procs_.resize(num_of_kinfo_proc);
38      len = num_of_kinfo_proc * sizeof(struct kinfo_proc);
39      if (sysctl(mib, arraysize(mib), &kinfo_procs_[0], &len, NULL, 0) < 0) {
40        // If we get a mem error, it just means we need a bigger buffer, so
41        // loop around again.  Anything else is a real error and give up.
42        if (errno != ENOMEM) {
43          DLOG(ERROR) << "failed to get the process list";
44          kinfo_procs_.resize(0);
45          done = true;
46        }
47      } else {
48        // Got the list, just make sure we're sized exactly right
49        size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
50        kinfo_procs_.resize(num_of_kinfo_proc);
51        done = true;
52      }
53    }
54  } while (!done && (try_num++ < max_tries));
55
56  if (!done) {
57    DLOG(ERROR) << "failed to collect the process list in a few tries";
58    kinfo_procs_.resize(0);
59  }
60}
61
62ProcessIterator::~ProcessIterator() {
63}
64
65bool ProcessIterator::CheckForNextProcess() {
66  std::string data;
67  for (; index_of_kinfo_proc_ < kinfo_procs_.size(); ++index_of_kinfo_proc_) {
68    kinfo_proc& kinfo = kinfo_procs_[index_of_kinfo_proc_];
69
70    // Skip processes just awaiting collection
71    if ((kinfo.p_pid > 0) && (kinfo.p_stat == SZOMB))
72      continue;
73
74    int mib[] = { CTL_KERN, KERN_PROC_ARGS, kinfo.p_pid };
75
76    // Find out what size buffer we need.
77    size_t data_len = 0;
78    if (sysctl(mib, arraysize(mib), NULL, &data_len, NULL, 0) < 0) {
79      DVPLOG(1) << "failed to figure out the buffer size for a commandline";
80      continue;
81    }
82
83    data.resize(data_len);
84    if (sysctl(mib, arraysize(mib), &data[0], &data_len, NULL, 0) < 0) {
85      DVPLOG(1) << "failed to fetch a commandline";
86      continue;
87    }
88
89    // |data| contains all the command line parameters of the process, separated
90    // by blocks of one or more null characters. We tokenize |data| into a
91    // vector of strings using '\0' as a delimiter and populate
92    // |entry_.cmd_line_args_|.
93    std::string delimiters;
94    delimiters.push_back('\0');
95    Tokenize(data, delimiters, &entry_.cmd_line_args_);
96
97    // |data| starts with the full executable path followed by a null character.
98    // We search for the first instance of '\0' and extract everything before it
99    // to populate |entry_.exe_file_|.
100    size_t exec_name_end = data.find('\0');
101    if (exec_name_end == std::string::npos) {
102      DLOG(ERROR) << "command line data didn't match expected format";
103      continue;
104    }
105
106    entry_.pid_ = kinfo.p_pid;
107    entry_.ppid_ = kinfo.p_ppid;
108    entry_.gid_ = kinfo.p__pgid;
109    size_t last_slash = data.rfind('/', exec_name_end);
110    if (last_slash == std::string::npos)
111      entry_.exe_file_.assign(data, 0, exec_name_end);
112    else
113      entry_.exe_file_.assign(data, last_slash + 1,
114                              exec_name_end - last_slash - 1);
115    // Start w/ the next entry next time through
116    ++index_of_kinfo_proc_;
117    // Done
118    return true;
119  }
120  return false;
121}
122
123bool NamedProcessIterator::IncludeEntry() {
124  return (executable_name_ == entry().exe_file() &&
125          ProcessIterator::IncludeEntry());
126}
127
128}  // namespace base
129