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