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