xref: /aosp_15_r20/external/cronet/base/process/process_posix.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2011 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.h"
6 
7 #include <errno.h>
8 #include <signal.h>
9 #include <stdint.h>
10 #include <sys/resource.h>
11 #include <sys/wait.h>
12 
13 #include <utility>
14 
15 #include "base/clang_profiling_buildflags.h"
16 #include "base/files/scoped_file.h"
17 #include "base/logging.h"
18 #include "base/notimplemented.h"
19 #include "base/posix/eintr_wrapper.h"
20 #include "base/process/kill.h"
21 #include "base/threading/thread_restrictions.h"
22 #include "base/time/time.h"
23 #include "base/trace_event/base_tracing.h"
24 #include "build/build_config.h"
25 
26 #if BUILDFLAG(IS_MAC)
27 #include <sys/event.h>
28 #endif
29 
30 #if BUILDFLAG(CLANG_PROFILING)
31 #include "base/test/clang_profiling.h"
32 #endif
33 
34 #if BUILDFLAG(IS_IOS)
35 #include "TargetConditionals.h"
36 #endif
37 
38 namespace {
39 
40 #if !BUILDFLAG(IS_IOS) || (BUILDFLAG(IS_IOS) && TARGET_OS_SIMULATOR)
WaitpidWithTimeout(base::ProcessHandle handle,int * status,base::TimeDelta wait)41 bool WaitpidWithTimeout(base::ProcessHandle handle,
42                         int* status,
43                         base::TimeDelta wait) {
44   // This POSIX version of this function only guarantees that we wait no less
45   // than |wait| for the process to exit.  The child process may
46   // exit sometime before the timeout has ended but we may still block for up
47   // to 256 milliseconds after the fact.
48   //
49   // waitpid() has no direct support on POSIX for specifying a timeout, you can
50   // either ask it to block indefinitely or return immediately (WNOHANG).
51   // When a child process terminates a SIGCHLD signal is sent to the parent.
52   // Catching this signal would involve installing a signal handler which may
53   // affect other parts of the application and would be difficult to debug.
54   //
55   // Our strategy is to call waitpid() once up front to check if the process
56   // has already exited, otherwise to loop for |wait|, sleeping for
57   // at most 256 milliseconds each time using usleep() and then calling
58   // waitpid().  The amount of time we sleep starts out at 1 milliseconds, and
59   // we double it every 4 sleep cycles.
60   //
61   // usleep() is speced to exit if a signal is received for which a handler
62   // has been installed.  This means that when a SIGCHLD is sent, it will exit
63   // depending on behavior external to this function.
64   //
65   // This function is used primarily for unit tests, if we want to use it in
66   // the application itself it would probably be best to examine other routes.
67 
68   if (wait == base::TimeDelta::Max()) {
69     return HANDLE_EINTR(waitpid(handle, status, 0)) > 0;
70   }
71 
72   pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
73   static const uint32_t kMaxSleepInMicroseconds = 1 << 18;  // ~256 ms.
74   uint32_t max_sleep_time_usecs = 1 << 10;                  // ~1 ms.
75   int double_sleep_time = 0;
76 
77   // If the process hasn't exited yet, then sleep and try again.
78   base::TimeTicks wakeup_time = base::TimeTicks::Now() + wait;
79   while (ret_pid == 0) {
80     base::TimeTicks now = base::TimeTicks::Now();
81     if (now > wakeup_time)
82       break;
83 
84     const uint32_t sleep_time_usecs = static_cast<uint32_t>(
85         std::min(static_cast<uint64_t>((wakeup_time - now).InMicroseconds()),
86                  uint64_t{max_sleep_time_usecs}));
87     // usleep() will return 0 and set errno to EINTR on receipt of a signal
88     // such as SIGCHLD.
89     usleep(sleep_time_usecs);
90     ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
91 
92     if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
93         (double_sleep_time++ % 4 == 0)) {
94       max_sleep_time_usecs *= 2;
95     }
96   }
97 
98   return ret_pid > 0;
99 }
100 #endif
101 
102 #if BUILDFLAG(IS_MAC)
103 // Using kqueue on Mac so that we can wait on non-child processes.
104 // We can't use kqueues on child processes because we need to reap
105 // our own children using wait.
WaitForSingleNonChildProcess(base::ProcessHandle handle,base::TimeDelta wait)106 bool WaitForSingleNonChildProcess(base::ProcessHandle handle,
107                                   base::TimeDelta wait) {
108   DCHECK_GT(handle, 0);
109 
110   base::ScopedFD kq(kqueue());
111   if (!kq.is_valid()) {
112     DPLOG(ERROR) << "kqueue";
113     return false;
114   }
115 
116   struct kevent change = {0};
117   EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
118   int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
119   if (result == -1) {
120     if (errno == ESRCH) {
121       // If the process wasn't found, it must be dead.
122       return true;
123     }
124 
125     DPLOG(ERROR) << "kevent (setup " << handle << ")";
126     return false;
127   }
128 
129   // Keep track of the elapsed time to be able to restart kevent if it's
130   // interrupted.
131   bool wait_forever = (wait == base::TimeDelta::Max());
132   base::TimeDelta remaining_delta;
133   base::TimeTicks deadline;
134   if (!wait_forever) {
135     remaining_delta = wait;
136     deadline = base::TimeTicks::Now() + remaining_delta;
137   }
138 
139   result = -1;
140   struct kevent event = {0};
141 
142   do {
143     struct timespec remaining_timespec;
144     struct timespec* remaining_timespec_ptr;
145     if (wait_forever) {
146       remaining_timespec_ptr = NULL;
147     } else {
148       remaining_timespec = remaining_delta.ToTimeSpec();
149       remaining_timespec_ptr = &remaining_timespec;
150     }
151 
152     result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
153 
154     if (result == -1 && errno == EINTR) {
155       if (!wait_forever) {
156         remaining_delta = deadline - base::TimeTicks::Now();
157       }
158       result = 0;
159     } else {
160       break;
161     }
162   } while (wait_forever || remaining_delta.is_positive());
163 
164   if (result < 0) {
165     DPLOG(ERROR) << "kevent (wait " << handle << ")";
166     return false;
167   } else if (result > 1) {
168     DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
169                 << result;
170     return false;
171   } else if (result == 0) {
172     // Timed out.
173     return false;
174   }
175 
176   DCHECK_EQ(result, 1);
177 
178   if (event.filter != EVFILT_PROC ||
179       (event.fflags & NOTE_EXIT) == 0 ||
180       event.ident != static_cast<uintptr_t>(handle)) {
181     DLOG(ERROR) << "kevent (wait " << handle
182                 << "): unexpected event: filter=" << event.filter
183                 << ", fflags=" << event.fflags
184                 << ", ident=" << event.ident;
185     return false;
186   }
187 
188   return true;
189 }
190 #endif  // BUILDFLAG(IS_MAC)
191 
192 }  // namespace
193 
194 namespace base {
195 
Process(ProcessHandle handle)196 Process::Process(ProcessHandle handle) : process_(handle) {}
197 
Process(Process && other)198 Process::Process(Process&& other) : process_(other.process_) {
199 #if BUILDFLAG(IS_CHROMEOS)
200   unique_token_ = std::move(other.unique_token_);
201 #endif
202 #if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR
203   content_process_ = other.content_process_;
204 #endif
205 
206   other.Close();
207 }
208 
operator =(Process && other)209 Process& Process::operator=(Process&& other) {
210   process_ = other.process_;
211 #if BUILDFLAG(IS_CHROMEOS)
212   unique_token_ = std::move(other.unique_token_);
213 #endif
214 #if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR
215   content_process_ = other.content_process_;
216 #endif
217   other.Close();
218   return *this;
219 }
220 
221 Process::~Process() = default;
222 
223 // static
Current()224 Process Process::Current() {
225   return Process(GetCurrentProcessHandle());
226 }
227 
228 // static
Open(ProcessId pid)229 Process Process::Open(ProcessId pid) {
230   if (pid == GetCurrentProcId())
231     return Current();
232 
233   // On POSIX process handles are the same as PIDs.
234   return Process(pid);
235 }
236 
237 // static
OpenWithExtraPrivileges(ProcessId pid)238 Process Process::OpenWithExtraPrivileges(ProcessId pid) {
239   // On POSIX there are no privileges to set.
240   return Open(pid);
241 }
242 
243 // static
TerminateCurrentProcessImmediately(int exit_code)244 void Process::TerminateCurrentProcessImmediately(int exit_code) {
245 #if BUILDFLAG(CLANG_PROFILING)
246   WriteClangProfilingProfile();
247 #endif
248   _exit(exit_code);
249 }
250 
IsValid() const251 bool Process::IsValid() const {
252   return process_ != kNullProcessHandle;
253 }
254 
Handle() const255 ProcessHandle Process::Handle() const {
256   return process_;
257 }
258 
Duplicate() const259 Process Process::Duplicate() const {
260   if (is_current())
261     return Current();
262 
263   Process duplicate = Process(process_);
264 #if BUILDFLAG(IS_CHROMEOS)
265   duplicate.unique_token_ = unique_token_;
266 #elif BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR
267   duplicate.content_process_ = content_process_;
268 #endif
269   return duplicate;
270 }
271 
Release()272 ProcessHandle Process::Release() {
273   return std::exchange(process_, kNullProcessHandle);
274 }
275 
Pid() const276 ProcessId Process::Pid() const {
277   DCHECK(IsValid());
278   return GetProcId(process_);
279 }
280 
is_current() const281 bool Process::is_current() const {
282   return process_ == GetCurrentProcessHandle();
283 }
284 
Close()285 void Process::Close() {
286   process_ = kNullProcessHandle;
287   // if the process wasn't terminated (so we waited) or the state
288   // wasn't already collected w/ a wait from process_utils, we're gonna
289   // end up w/ a zombie when it does finally exit.
290 }
291 
292 #if !BUILDFLAG(IS_IOS)
Terminate(int exit_code,bool wait) const293 bool Process::Terminate(int exit_code, bool wait) const {
294   // exit_code isn't supportable.
295   DCHECK(IsValid());
296   CHECK_GT(process_, 0);
297   return TerminateInternal(exit_code, wait);
298 }
299 #endif
300 
301 #if !BUILDFLAG(IS_IOS) || (BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR)
TerminateInternal(int exit_code,bool wait) const302 bool Process::TerminateInternal(int exit_code, bool wait) const {
303   // RESULT_CODE_KILLED_BAD_MESSAGE == 3, but layering prevents its use.
304   // |wait| is always false when terminating badly-behaved processes.
305   const bool maybe_compromised = !wait && exit_code == 3;
306   if (maybe_compromised) {
307     // Forcibly terminate the process immediately.
308     const bool was_killed = kill(process_, SIGKILL) != 0;
309 #if BUILDFLAG(IS_CHROMEOS)
310     if (was_killed)
311       CleanUpProcessAsync();
312 #endif
313     DPLOG_IF(ERROR, !was_killed) << "Unable to terminate process " << process_;
314     return was_killed;
315   }
316 
317   // Terminate process giving it a chance to clean up.
318   if (kill(process_, SIGTERM) != 0) {
319     DPLOG(ERROR) << "Unable to terminate process " << process_;
320     return false;
321   }
322 
323 #if BUILDFLAG(IS_CHROMEOS)
324   CleanUpProcessAsync();
325 #endif
326 
327   if (!wait || WaitForExitWithTimeout(Seconds(60), nullptr)) {
328     return true;
329   }
330   if (kill(process_, SIGKILL) != 0) {
331     DPLOG(ERROR) << "Unable to kill process " << process_;
332     return false;
333   }
334   return WaitForExit(nullptr);
335 }
336 #endif
337 
WaitForExit(int * exit_code) const338 bool Process::WaitForExit(int* exit_code) const {
339   return WaitForExitWithTimeout(TimeDelta::Max(), exit_code);
340 }
341 
342 #if !BUILDFLAG(IS_IOS)
WaitForExitWithTimeout(TimeDelta timeout,int * exit_code) const343 bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const {
344   if (!timeout.is_zero()) {
345     // Assert that this thread is allowed to wait below. This intentionally
346     // doesn't use ScopedBlockingCallWithBaseSyncPrimitives because the process
347     // being waited upon tends to itself be using the CPU and considering this
348     // thread non-busy causes more issue than it fixes: http://crbug.com/905788
349     internal::AssertBaseSyncPrimitivesAllowed();
350   }
351 
352   int local_exit_code = 0;
353   bool exited = WaitForExitWithTimeoutImpl(Handle(), &local_exit_code, timeout);
354   if (exited) {
355     Exited(local_exit_code);
356     if (exit_code)
357       *exit_code = local_exit_code;
358   }
359   return exited;
360 }
361 #endif
362 
363 #if !BUILDFLAG(IS_IOS) || (BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR)
WaitForExitWithTimeoutImpl(base::ProcessHandle handle,int * exit_code,base::TimeDelta timeout) const364 bool Process::WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
365                                          int* exit_code,
366                                          base::TimeDelta timeout) const {
367   const base::ProcessHandle our_pid = base::GetCurrentProcessHandle();
368   if (handle == our_pid) {
369     // We won't be able to wait for ourselves to exit.
370     return false;
371   }
372 
373   TRACE_EVENT0("base", "Process::WaitForExitWithTimeout");
374 
375   const base::ProcessHandle parent_pid = base::GetParentProcessId(handle);
376   const bool exited = (parent_pid < 0);
377 
378   if (!exited && parent_pid != our_pid) {
379 #if BUILDFLAG(IS_MAC)
380     // On Mac we can wait on non child processes.
381     return WaitForSingleNonChildProcess(handle, timeout);
382 #else
383     // Currently on Linux we can't handle non child processes.
384     NOTIMPLEMENTED();
385 #endif  // BUILDFLAG(IS_MAC)
386   }
387 
388   int status;
389   if (!WaitpidWithTimeout(handle, &status, timeout)) {
390     return exited;
391   }
392   if (WIFSIGNALED(status)) {
393     if (exit_code) {
394       *exit_code = -1;
395     }
396     return true;
397   }
398   if (WIFEXITED(status)) {
399     if (exit_code) {
400       *exit_code = WEXITSTATUS(status);
401     }
402     return true;
403   }
404   return exited;
405 }
406 #endif
407 
Exited(int exit_code) const408 void Process::Exited(int exit_code) const {
409 #if BUILDFLAG(IS_CHROMEOS)
410   CleanUpProcessAsync();
411 #endif
412 }
413 
GetOSPriority() const414 int Process::GetOSPriority() const {
415   DCHECK(IsValid());
416   return getpriority(PRIO_PROCESS, static_cast<id_t>(process_));
417 }
418 
419 }  // namespace base
420