blob: 8e8c6acda3c43eae9d0651a4341a079bf85db265 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2011 The Chromium Authors
[email protected]0b100bc82008-10-14 20:49:162// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]76bea672013-07-19 16:48:565#include "base/process/process.h"
[email protected]66700d42010-03-10 07:46:436
mostynb522dfa52015-11-07 00:57:147#include <errno.h>
raphael.kubo.da.costa531c29b2017-04-18 14:11:148#include <signal.h>
avibeced7c2015-12-24 06:47:599#include <stdint.h>
[email protected]276aa6a2009-10-29 17:43:4410#include <sys/resource.h>
rvargas85728972015-03-03 20:46:1911#include <sys/wait.h>
[email protected]276aa6a2009-10-29 17:43:4412
S. Ganeshe4a99862025-04-29 03:30:4513#include <algorithm>
Robert Sesek0e7f165a2020-11-20 21:31:4514#include <utility>
15
S. Ganeshe4a99862025-04-29 03:30:4516#include "base/check_op.h"
Sebastien Marchandbd02bc29e2020-03-11 15:53:3617#include "base/clang_profiling_buildflags.h"
rvargas85728972015-03-03 20:46:1918#include "base/files/scoped_file.h"
[email protected]5d91c9e2010-07-28 17:25:2819#include "base/logging.h"
Peter Boström6e2fd082024-01-23 01:17:5520#include "base/notimplemented.h"
rvargas85728972015-03-03 20:46:1921#include "base/posix/eintr_wrapper.h"
[email protected]dd4b51262013-07-25 21:38:2322#include "base/process/kill.h"
Francois Doraya678fc12017-10-30 22:18:0623#include "base/threading/thread_restrictions.h"
Gabriel Charetted87f10f2022-03-31 00:44:2224#include "base/time/time.h"
Etienne Pierre-dorayfc7952f02025-06-06 00:04:3325#include "base/trace_event/trace_event.h"
avibeced7c2015-12-24 06:47:5926#include "build/build_config.h"
[email protected]0b100bc82008-10-14 20:49:1627
Xiaohan Wang37e81612022-01-15 18:27:0028#if BUILDFLAG(IS_MAC)
rvargas85728972015-03-03 20:46:1929#include <sys/event.h>
30#endif
31
Sebastien Marchandbd02bc29e2020-03-11 15:53:3632#if BUILDFLAG(CLANG_PROFILING)
33#include "base/test/clang_profiling.h"
Yuke Liaoa1d9b7b2019-08-14 16:14:3434#endif
Yannic Bonenberger6801e6c2019-06-07 10:42:5335
Dave Tapuska31c385c2024-04-12 18:43:1136#if BUILDFLAG(IS_IOS)
37#include "TargetConditionals.h"
38#endif
39
rvargas85728972015-03-03 20:46:1940namespace {
41
Dave Tapuska31c385c2024-04-12 18:43:1142#if !BUILDFLAG(IS_IOS) || (BUILDFLAG(IS_IOS) && TARGET_OS_SIMULATOR)
rvargas85728972015-03-03 20:46:1943bool WaitpidWithTimeout(base::ProcessHandle handle,
44 int* status,
45 base::TimeDelta wait) {
S. Ganeshe4a99862025-04-29 03:30:4546 DCHECK_GE(wait, base::TimeDelta());
47
rvargas85728972015-03-03 20:46:1948 // This POSIX version of this function only guarantees that we wait no less
49 // than |wait| for the process to exit. The child process may
50 // exit sometime before the timeout has ended but we may still block for up
51 // to 256 milliseconds after the fact.
52 //
53 // waitpid() has no direct support on POSIX for specifying a timeout, you can
54 // either ask it to block indefinitely or return immediately (WNOHANG).
55 // When a child process terminates a SIGCHLD signal is sent to the parent.
56 // Catching this signal would involve installing a signal handler which may
57 // affect other parts of the application and would be difficult to debug.
58 //
59 // Our strategy is to call waitpid() once up front to check if the process
60 // has already exited, otherwise to loop for |wait|, sleeping for
61 // at most 256 milliseconds each time using usleep() and then calling
62 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
63 // we double it every 4 sleep cycles.
64 //
65 // usleep() is speced to exit if a signal is received for which a handler
66 // has been installed. This means that when a SIGCHLD is sent, it will exit
67 // depending on behavior external to this function.
68 //
69 // This function is used primarily for unit tests, if we want to use it in
70 // the application itself it would probably be best to examine other routes.
71
72 if (wait == base::TimeDelta::Max()) {
73 return HANDLE_EINTR(waitpid(handle, status, 0)) > 0;
74 }
75
76 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
Peter Kasting25acd5942022-07-07 17:45:1577 static const uint32_t kMaxSleepInMicroseconds = 1 << 18; // ~256 ms.
78 uint32_t max_sleep_time_usecs = 1 << 10; // ~1 ms.
79 int double_sleep_time = 0;
rvargas85728972015-03-03 20:46:1980
81 // If the process hasn't exited yet, then sleep and try again.
82 base::TimeTicks wakeup_time = base::TimeTicks::Now() + wait;
83 while (ret_pid == 0) {
84 base::TimeTicks now = base::TimeTicks::Now();
Peter Kasting134ef9af2024-12-28 02:30:0985 if (now > wakeup_time) {
rvargas85728972015-03-03 20:46:1986 break;
Peter Kasting134ef9af2024-12-28 02:30:0987 }
rvargas85728972015-03-03 20:46:1988
Peter Kasting25acd5942022-07-07 17:45:1589 const uint32_t sleep_time_usecs = static_cast<uint32_t>(
90 std::min(static_cast<uint64_t>((wakeup_time - now).InMicroseconds()),
91 uint64_t{max_sleep_time_usecs}));
rvargas85728972015-03-03 20:46:1992 // usleep() will return 0 and set errno to EINTR on receipt of a signal
93 // such as SIGCHLD.
94 usleep(sleep_time_usecs);
95 ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
96
97 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
98 (double_sleep_time++ % 4 == 0)) {
99 max_sleep_time_usecs *= 2;
100 }
101 }
102
103 return ret_pid > 0;
104}
Dave Tapuska31c385c2024-04-12 18:43:11105#endif
rvargas85728972015-03-03 20:46:19106
Xiaohan Wang37e81612022-01-15 18:27:00107#if BUILDFLAG(IS_MAC)
rvargas85728972015-03-03 20:46:19108// Using kqueue on Mac so that we can wait on non-child processes.
109// We can't use kqueues on child processes because we need to reap
110// our own children using wait.
Wez20d363692018-02-26 22:10:22111bool WaitForSingleNonChildProcess(base::ProcessHandle handle,
112 base::TimeDelta wait) {
rvargas85728972015-03-03 20:46:19113 DCHECK_GT(handle, 0);
S. Ganeshe4a99862025-04-29 03:30:45114 DCHECK_GE(wait, base::TimeDelta());
rvargas85728972015-03-03 20:46:19115
116 base::ScopedFD kq(kqueue());
117 if (!kq.is_valid()) {
118 DPLOG(ERROR) << "kqueue";
119 return false;
120 }
121
122 struct kevent change = {0};
123 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
124 int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
125 if (result == -1) {
126 if (errno == ESRCH) {
127 // If the process wasn't found, it must be dead.
128 return true;
129 }
130
131 DPLOG(ERROR) << "kevent (setup " << handle << ")";
132 return false;
133 }
134
135 // Keep track of the elapsed time to be able to restart kevent if it's
136 // interrupted.
137 bool wait_forever = (wait == base::TimeDelta::Max());
138 base::TimeDelta remaining_delta;
139 base::TimeTicks deadline;
140 if (!wait_forever) {
141 remaining_delta = wait;
142 deadline = base::TimeTicks::Now() + remaining_delta;
143 }
144
145 result = -1;
146 struct kevent event = {0};
147
Zijie He4dd88ae422017-09-20 01:30:18148 do {
rvargas85728972015-03-03 20:46:19149 struct timespec remaining_timespec;
150 struct timespec* remaining_timespec_ptr;
151 if (wait_forever) {
152 remaining_timespec_ptr = NULL;
153 } else {
154 remaining_timespec = remaining_delta.ToTimeSpec();
155 remaining_timespec_ptr = &remaining_timespec;
156 }
157
158 result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
159
160 if (result == -1 && errno == EINTR) {
161 if (!wait_forever) {
162 remaining_delta = deadline - base::TimeTicks::Now();
163 }
164 result = 0;
165 } else {
166 break;
167 }
Xiaohan Wangabff0302021-10-27 00:42:57168 } while (wait_forever || remaining_delta.is_positive());
rvargas85728972015-03-03 20:46:19169
170 if (result < 0) {
171 DPLOG(ERROR) << "kevent (wait " << handle << ")";
172 return false;
173 } else if (result > 1) {
174 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
175 << result;
176 return false;
177 } else if (result == 0) {
178 // Timed out.
179 return false;
180 }
181
182 DCHECK_EQ(result, 1);
183
Peter Kasting134ef9af2024-12-28 02:30:09184 if (event.filter != EVFILT_PROC || (event.fflags & NOTE_EXIT) == 0 ||
rvargas85728972015-03-03 20:46:19185 event.ident != static_cast<uintptr_t>(handle)) {
186 DLOG(ERROR) << "kevent (wait " << handle
187 << "): unexpected event: filter=" << event.filter
Peter Kasting134ef9af2024-12-28 02:30:09188 << ", fflags=" << event.fflags << ", ident=" << event.ident;
rvargas85728972015-03-03 20:46:19189 return false;
190 }
191
192 return true;
193}
Xiaohan Wang37e81612022-01-15 18:27:00194#endif // BUILDFLAG(IS_MAC)
rvargas85728972015-03-03 20:46:19195
rvargas85728972015-03-03 20:46:19196} // namespace
197
[email protected]176aa482008-11-14 03:25:15198namespace base {
199
Youssef Esmatc732bf82022-05-27 00:47:19200Process::Process(ProcessHandle handle) : process_(handle) {}
thakis3096dac2015-04-20 16:44:48201
dchenge1b0277c2015-12-01 12:09:52202Process::Process(Process&& other) : process_(other.process_) {
Youssef Esmatc732bf82022-05-27 00:47:19203#if BUILDFLAG(IS_CHROMEOS)
204 unique_token_ = std::move(other.unique_token_);
205#endif
Dave Tapuska31c385c2024-04-12 18:43:11206#if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR
207 content_process_ = other.content_process_;
208#endif
Youssef Esmatc732bf82022-05-27 00:47:19209
dchenge1b0277c2015-12-01 12:09:52210 other.Close();
rvargas079d1842014-10-17 22:32:16211}
212
dchenge1b0277c2015-12-01 12:09:52213Process& Process::operator=(Process&& other) {
dchenge1b0277c2015-12-01 12:09:52214 process_ = other.process_;
Youssef Esmatc732bf82022-05-27 00:47:19215#if BUILDFLAG(IS_CHROMEOS)
216 unique_token_ = std::move(other.unique_token_);
217#endif
Dave Tapuska31c385c2024-04-12 18:43:11218#if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR
219 content_process_ = other.content_process_;
220#endif
dchenge1b0277c2015-12-01 12:09:52221 other.Close();
rvargas079d1842014-10-17 22:32:16222 return *this;
223}
224
Youssef Esmatc732bf82022-05-27 00:47:19225Process::~Process() = default;
226
[email protected]b7d08202011-01-25 17:29:39227// static
228Process Process::Current() {
rvargasd5626f62015-02-05 19:09:24229 return Process(GetCurrentProcessHandle());
rvargas079d1842014-10-17 22:32:16230}
231
rvargas5779b382014-11-18 20:44:11232// static
rvargas6b039c372015-02-04 21:11:29233Process Process::Open(ProcessId pid) {
Peter Kasting134ef9af2024-12-28 02:30:09234 if (pid == GetCurrentProcId()) {
rvargas747ff242015-01-17 02:46:47235 return Current();
Peter Kasting134ef9af2024-12-28 02:30:09236 }
rvargas747ff242015-01-17 02:46:47237
rvargas6b039c372015-02-04 21:11:29238 // On POSIX process handles are the same as PIDs.
rvargas747ff242015-01-17 02:46:47239 return Process(pid);
240}
241
242// static
rvargas1c376a82015-03-16 23:03:52243Process Process::OpenWithExtraPrivileges(ProcessId pid) {
rvargas6b039c372015-02-04 21:11:29244 // On POSIX there are no privileges to set.
245 return Open(pid);
246}
247
haraken940efb92017-02-08 05:58:15248// static
249void Process::TerminateCurrentProcessImmediately(int exit_code) {
Sebastien Marchandbd02bc29e2020-03-11 15:53:36250#if BUILDFLAG(CLANG_PROFILING)
251 WriteClangProfilingProfile();
Yuke Liaoa1d9b7b2019-08-14 16:14:34252#endif
haraken940efb92017-02-08 05:58:15253 _exit(exit_code);
254}
255
rvargas079d1842014-10-17 22:32:16256bool Process::IsValid() const {
257 return process_ != kNullProcessHandle;
258}
259
260ProcessHandle Process::Handle() const {
261 return process_;
262}
263
264Process Process::Duplicate() const {
Peter Kasting134ef9af2024-12-28 02:30:09265 if (is_current()) {
rvargas079d1842014-10-17 22:32:16266 return Current();
Peter Kasting134ef9af2024-12-28 02:30:09267 }
rvargas079d1842014-10-17 22:32:16268
Youssef Esmatc732bf82022-05-27 00:47:19269 Process duplicate = Process(process_);
Dave Tapuska31c385c2024-04-12 18:43:11270#if BUILDFLAG(IS_CHROMEOS)
Youssef Esmatc732bf82022-05-27 00:47:19271 duplicate.unique_token_ = unique_token_;
Dave Tapuska31c385c2024-04-12 18:43:11272#elif BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR
273 duplicate.content_process_ = content_process_;
Youssef Esmatc732bf82022-05-27 00:47:19274#endif
Dave Tapuska31c385c2024-04-12 18:43:11275 return duplicate;
[email protected]b7d08202011-01-25 17:29:39276}
277
Robert Sesek0e7f165a2020-11-20 21:31:45278ProcessHandle Process::Release() {
279 return std::exchange(process_, kNullProcessHandle);
280}
281
rvargas960db882015-01-24 00:27:25282ProcessId Process::Pid() const {
rvargas079d1842014-10-17 22:32:16283 DCHECK(IsValid());
[email protected]b7d08202011-01-25 17:29:39284 return GetProcId(process_);
285}
286
287bool Process::is_current() const {
288 return process_ == GetCurrentProcessHandle();
289}
290
[email protected]176aa482008-11-14 03:25:15291void Process::Close() {
rvargas079d1842014-10-17 22:32:16292 process_ = kNullProcessHandle;
[email protected]276aa6a2009-10-29 17:43:44293 // if the process wasn't terminated (so we waited) or the state
[email protected]1a7813642009-02-05 19:22:01294 // wasn't already collected w/ a wait from process_utils, we're gonna
295 // end up w/ a zombie when it does finally exit.
[email protected]176aa482008-11-14 03:25:15296}
297
Dave Tapuska31c385c2024-04-12 18:43:11298#if !BUILDFLAG(IS_IOS)
rvargas02ad7832015-04-02 01:36:06299bool Process::Terminate(int exit_code, bool wait) const {
rickyz8055dc72015-07-01 22:50:03300 // exit_code isn't supportable.
rvargas079d1842014-10-17 22:32:16301 DCHECK(IsValid());
rickyz8055dc72015-07-01 22:50:03302 CHECK_GT(process_, 0);
Dave Tapuska31c385c2024-04-12 18:43:11303 return TerminateInternal(exit_code, wait);
304}
305#endif
rickyz8055dc72015-07-01 22:50:03306
Dave Tapuska31c385c2024-04-12 18:43:11307#if !BUILDFLAG(IS_IOS) || (BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR)
308bool Process::TerminateInternal(int exit_code, bool wait) const {
Tom Sepez8cded8072022-06-27 23:01:43309 // RESULT_CODE_KILLED_BAD_MESSAGE == 3, but layering prevents its use.
310 // |wait| is always false when terminating badly-behaved processes.
311 const bool maybe_compromised = !wait && exit_code == 3;
312 if (maybe_compromised) {
313 // Forcibly terminate the process immediately.
314 const bool was_killed = kill(process_, SIGKILL) != 0;
315#if BUILDFLAG(IS_CHROMEOS)
Peter Kasting134ef9af2024-12-28 02:30:09316 if (was_killed) {
Tom Sepez8cded8072022-06-27 23:01:43317 CleanUpProcessAsync();
Peter Kasting134ef9af2024-12-28 02:30:09318 }
Tom Sepez8cded8072022-06-27 23:01:43319#endif
320 DPLOG_IF(ERROR, !was_killed) << "Unable to terminate process " << process_;
321 return was_killed;
322 }
323
324 // Terminate process giving it a chance to clean up.
Tom Sepez75fafe12022-02-14 18:13:37325 if (kill(process_, SIGTERM) != 0) {
rvargas02ad7832015-04-02 01:36:06326 DPLOG(ERROR) << "Unable to terminate process " << process_;
Tom Sepez75fafe12022-02-14 18:13:37327 return false;
328 }
Youssef Esmatc732bf82022-05-27 00:47:19329
330#if BUILDFLAG(IS_CHROMEOS)
331 CleanUpProcessAsync();
332#endif
333
Tom Sepez75fafe12022-02-14 18:13:37334 if (!wait || WaitForExitWithTimeout(Seconds(60), nullptr)) {
335 return true;
336 }
337 if (kill(process_, SIGKILL) != 0) {
338 DPLOG(ERROR) << "Unable to kill process " << process_;
339 return false;
340 }
341 return WaitForExit(nullptr);
[email protected]176aa482008-11-14 03:25:15342}
Dave Tapuska31c385c2024-04-12 18:43:11343#endif
[email protected]176aa482008-11-14 03:25:15344
jcivellif4462a352017-01-10 04:45:59345bool Process::WaitForExit(int* exit_code) const {
rvargas85728972015-03-03 20:46:19346 return WaitForExitWithTimeout(TimeDelta::Max(), exit_code);
rvargas126fd5822014-12-12 00:25:14347}
348
Dave Tapuska31c385c2024-04-12 18:43:11349#if !BUILDFLAG(IS_IOS)
jcivellif4462a352017-01-10 04:45:59350bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const {
S. Ganeshe4a99862025-04-29 03:30:45351 timeout = std::max(timeout, TimeDelta());
Gabriel Charette6836c0d52021-01-11 17:40:26352 if (!timeout.is_zero()) {
Gabriel Charette6836c0d52021-01-11 17:40:26353 // Assert that this thread is allowed to wait below. This intentionally
354 // doesn't use ScopedBlockingCallWithBaseSyncPrimitives because the process
355 // being waited upon tends to itself be using the CPU and considering this
356 // thread non-busy causes more issue than it fixes: http://crbug.com/905788
357 internal::AssertBaseSyncPrimitivesAllowed();
358 }
bcwhited9705962016-08-10 03:10:03359
Dmitry Bezheckovff22a4d2018-07-10 19:42:44360 int local_exit_code = 0;
Brian Whiteae2a8b9a2017-11-02 19:10:36361 bool exited = WaitForExitWithTimeoutImpl(Handle(), &local_exit_code, timeout);
362 if (exited) {
363 Exited(local_exit_code);
Peter Kasting134ef9af2024-12-28 02:30:09364 if (exit_code) {
Brian Whiteae2a8b9a2017-11-02 19:10:36365 *exit_code = local_exit_code;
Peter Kasting134ef9af2024-12-28 02:30:09366 }
Brian Whiteae2a8b9a2017-11-02 19:10:36367 }
368 return exited;
rvargas126fd5822014-12-12 00:25:14369}
Dave Tapuska31c385c2024-04-12 18:43:11370#endif
371
372#if !BUILDFLAG(IS_IOS) || (BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR)
373bool Process::WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
374 int* exit_code,
375 base::TimeDelta timeout) const {
S. Ganeshe4a99862025-04-29 03:30:45376 DCHECK_GE(timeout, TimeDelta());
377
Dave Tapuska31c385c2024-04-12 18:43:11378 const base::ProcessHandle our_pid = base::GetCurrentProcessHandle();
379 if (handle == our_pid) {
380 // We won't be able to wait for ourselves to exit.
381 return false;
382 }
383
384 TRACE_EVENT0("base", "Process::WaitForExitWithTimeout");
385
386 const base::ProcessHandle parent_pid = base::GetParentProcessId(handle);
387 const bool exited = (parent_pid < 0);
388
389 if (!exited && parent_pid != our_pid) {
390#if BUILDFLAG(IS_MAC)
391 // On Mac we can wait on non child processes.
392 return WaitForSingleNonChildProcess(handle, timeout);
393#else
394 // Currently on Linux we can't handle non child processes.
395 NOTIMPLEMENTED();
396#endif // BUILDFLAG(IS_MAC)
397 }
398
399 int status;
400 if (!WaitpidWithTimeout(handle, &status, timeout)) {
401 return exited;
402 }
403 if (WIFSIGNALED(status)) {
404 if (exit_code) {
405 *exit_code = -1;
406 }
407 return true;
408 }
409 if (WIFEXITED(status)) {
410 if (exit_code) {
411 *exit_code = WEXITSTATUS(status);
412 }
413 return true;
414 }
415 return exited;
416}
417#endif
rvargas126fd5822014-12-12 00:25:14418
Youssef Esmatc732bf82022-05-27 00:47:19419void Process::Exited(int exit_code) const {
420#if BUILDFLAG(IS_CHROMEOS)
421 CleanUpProcessAsync();
422#endif
423}
Brian Whiteae2a8b9a2017-11-02 19:10:36424
Patrick Monette740b81b2023-07-21 21:09:09425int Process::GetOSPriority() const {
rvargas079d1842014-10-17 22:32:16426 DCHECK(IsValid());
Peter Kasting25acd5942022-07-07 17:45:15427 return getpriority(PRIO_PROCESS, static_cast<id_t>(process_));
[email protected]276aa6a2009-10-29 17:43:44428}
429
danakjc3762b92015-03-07 01:51:42430} // namespace base