blob: 1f18dd2cec723b6b82ce5dd0b5bfde24be6ea965 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2011 The Chromium Authors
[email protected]0b100bc8b2008-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
Robert Sesek0e7f165a2020-11-20 21:31:4513#include <utility>
14
Sebastien Marchandbd02bc29e2020-03-11 15:53:3615#include "base/clang_profiling_buildflags.h"
rvargas85728972015-03-03 20:46:1916#include "base/files/scoped_file.h"
[email protected]5d91c9e2010-07-28 17:25:2817#include "base/logging.h"
David Sanders83f8ae42022-04-04 23:15:3918#include "base/notreached.h"
rvargas85728972015-03-03 20:46:1919#include "base/posix/eintr_wrapper.h"
[email protected]dd4b51262013-07-25 21:38:2320#include "base/process/kill.h"
Francois Doraya678fc12017-10-30 22:18:0621#include "base/threading/thread_restrictions.h"
Gabriel Charetted87f10f2022-03-31 00:44:2222#include "base/time/time.h"
Gabriel Charette6836c0d52021-01-11 17:40:2623#include "base/trace_event/base_tracing.h"
avibeced7c2015-12-24 06:47:5924#include "build/build_config.h"
[email protected]0b100bc8b2008-10-14 20:49:1625
Xiaohan Wang37e81612022-01-15 18:27:0026#if BUILDFLAG(IS_MAC)
rvargas85728972015-03-03 20:46:1927#include <sys/event.h>
28#endif
29
Sebastien Marchandbd02bc29e2020-03-11 15:53:3630#if BUILDFLAG(CLANG_PROFILING)
31#include "base/test/clang_profiling.h"
Yuke Liaoa1d9b7b2019-08-14 16:14:3432#endif
Yannic Bonenberger6801e6c2019-06-07 10:42:5333
rvargas85728972015-03-03 20:46:1934namespace {
35
rvargas85728972015-03-03 20:46:1936bool WaitpidWithTimeout(base::ProcessHandle handle,
37 int* status,
38 base::TimeDelta wait) {
39 // This POSIX version of this function only guarantees that we wait no less
40 // than |wait| for the process to exit. The child process may
41 // exit sometime before the timeout has ended but we may still block for up
42 // to 256 milliseconds after the fact.
43 //
44 // waitpid() has no direct support on POSIX for specifying a timeout, you can
45 // either ask it to block indefinitely or return immediately (WNOHANG).
46 // When a child process terminates a SIGCHLD signal is sent to the parent.
47 // Catching this signal would involve installing a signal handler which may
48 // affect other parts of the application and would be difficult to debug.
49 //
50 // Our strategy is to call waitpid() once up front to check if the process
51 // has already exited, otherwise to loop for |wait|, sleeping for
52 // at most 256 milliseconds each time using usleep() and then calling
53 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
54 // we double it every 4 sleep cycles.
55 //
56 // usleep() is speced to exit if a signal is received for which a handler
57 // has been installed. This means that when a SIGCHLD is sent, it will exit
58 // depending on behavior external to this function.
59 //
60 // This function is used primarily for unit tests, if we want to use it in
61 // the application itself it would probably be best to examine other routes.
62
63 if (wait == base::TimeDelta::Max()) {
64 return HANDLE_EINTR(waitpid(handle, status, 0)) > 0;
65 }
66
67 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
Peter Kasting25acd5942022-07-07 17:45:1568 static const uint32_t kMaxSleepInMicroseconds = 1 << 18; // ~256 ms.
69 uint32_t max_sleep_time_usecs = 1 << 10; // ~1 ms.
70 int double_sleep_time = 0;
rvargas85728972015-03-03 20:46:1971
72 // If the process hasn't exited yet, then sleep and try again.
73 base::TimeTicks wakeup_time = base::TimeTicks::Now() + wait;
74 while (ret_pid == 0) {
75 base::TimeTicks now = base::TimeTicks::Now();
76 if (now > wakeup_time)
77 break;
rvargas85728972015-03-03 20:46:1978
Peter Kasting25acd5942022-07-07 17:45:1579 const uint32_t sleep_time_usecs = static_cast<uint32_t>(
80 std::min(static_cast<uint64_t>((wakeup_time - now).InMicroseconds()),
81 uint64_t{max_sleep_time_usecs}));
rvargas85728972015-03-03 20:46:1982 // usleep() will return 0 and set errno to EINTR on receipt of a signal
83 // such as SIGCHLD.
84 usleep(sleep_time_usecs);
85 ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
86
87 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
88 (double_sleep_time++ % 4 == 0)) {
89 max_sleep_time_usecs *= 2;
90 }
91 }
92
93 return ret_pid > 0;
94}
95
Xiaohan Wang37e81612022-01-15 18:27:0096#if BUILDFLAG(IS_MAC)
rvargas85728972015-03-03 20:46:1997// Using kqueue on Mac so that we can wait on non-child processes.
98// We can't use kqueues on child processes because we need to reap
99// our own children using wait.
Wez20d363692018-02-26 22:10:22100bool WaitForSingleNonChildProcess(base::ProcessHandle handle,
101 base::TimeDelta wait) {
rvargas85728972015-03-03 20:46:19102 DCHECK_GT(handle, 0);
rvargas85728972015-03-03 20:46:19103
104 base::ScopedFD kq(kqueue());
105 if (!kq.is_valid()) {
106 DPLOG(ERROR) << "kqueue";
107 return false;
108 }
109
110 struct kevent change = {0};
111 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
112 int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
113 if (result == -1) {
114 if (errno == ESRCH) {
115 // If the process wasn't found, it must be dead.
116 return true;
117 }
118
119 DPLOG(ERROR) << "kevent (setup " << handle << ")";
120 return false;
121 }
122
123 // Keep track of the elapsed time to be able to restart kevent if it's
124 // interrupted.
125 bool wait_forever = (wait == base::TimeDelta::Max());
126 base::TimeDelta remaining_delta;
127 base::TimeTicks deadline;
128 if (!wait_forever) {
129 remaining_delta = wait;
130 deadline = base::TimeTicks::Now() + remaining_delta;
131 }
132
133 result = -1;
134 struct kevent event = {0};
135
Zijie He4dd88ae422017-09-20 01:30:18136 do {
rvargas85728972015-03-03 20:46:19137 struct timespec remaining_timespec;
138 struct timespec* remaining_timespec_ptr;
139 if (wait_forever) {
140 remaining_timespec_ptr = NULL;
141 } else {
142 remaining_timespec = remaining_delta.ToTimeSpec();
143 remaining_timespec_ptr = &remaining_timespec;
144 }
145
146 result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
147
148 if (result == -1 && errno == EINTR) {
149 if (!wait_forever) {
150 remaining_delta = deadline - base::TimeTicks::Now();
151 }
152 result = 0;
153 } else {
154 break;
155 }
Xiaohan Wangabff0302021-10-27 00:42:57156 } while (wait_forever || remaining_delta.is_positive());
rvargas85728972015-03-03 20:46:19157
158 if (result < 0) {
159 DPLOG(ERROR) << "kevent (wait " << handle << ")";
160 return false;
161 } else if (result > 1) {
162 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
163 << result;
164 return false;
165 } else if (result == 0) {
166 // Timed out.
167 return false;
168 }
169
170 DCHECK_EQ(result, 1);
171
172 if (event.filter != EVFILT_PROC ||
173 (event.fflags & NOTE_EXIT) == 0 ||
174 event.ident != static_cast<uintptr_t>(handle)) {
175 DLOG(ERROR) << "kevent (wait " << handle
176 << "): unexpected event: filter=" << event.filter
177 << ", fflags=" << event.fflags
178 << ", ident=" << event.ident;
179 return false;
180 }
181
182 return true;
183}
Xiaohan Wang37e81612022-01-15 18:27:00184#endif // BUILDFLAG(IS_MAC)
rvargas85728972015-03-03 20:46:19185
186bool WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
187 int* exit_code,
188 base::TimeDelta timeout) {
Zijie He4dd88ae422017-09-20 01:30:18189 const base::ProcessHandle our_pid = base::GetCurrentProcessHandle();
190 if (handle == our_pid) {
191 // We won't be able to wait for ourselves to exit.
192 return false;
193 }
rayb0088ee52017-04-26 22:35:08194
Gabriel Charette6836c0d52021-01-11 17:40:26195 TRACE_EVENT0("base", "Process::WaitForExitWithTimeout");
196
Zijie He4dd88ae422017-09-20 01:30:18197 const base::ProcessHandle parent_pid = base::GetParentProcessId(handle);
198 const bool exited = (parent_pid < 0);
199
200 if (!exited && parent_pid != our_pid) {
Xiaohan Wang37e81612022-01-15 18:27:00201#if BUILDFLAG(IS_MAC)
rvargas85728972015-03-03 20:46:19202 // On Mac we can wait on non child processes.
203 return WaitForSingleNonChildProcess(handle, timeout);
204#else
205 // Currently on Linux we can't handle non child processes.
206 NOTIMPLEMENTED();
Xiaohan Wang37e81612022-01-15 18:27:00207#endif // BUILDFLAG(IS_MAC)
rvargas85728972015-03-03 20:46:19208 }
209
210 int status;
Wez2c2caae2018-06-12 04:19:53211 if (!WaitpidWithTimeout(handle, &status, timeout))
212 return exited;
rvargas85728972015-03-03 20:46:19213 if (WIFSIGNALED(status)) {
g.mehndirattfd19e232015-05-29 08:17:14214 if (exit_code)
215 *exit_code = -1;
rvargas85728972015-03-03 20:46:19216 return true;
217 }
218 if (WIFEXITED(status)) {
g.mehndirattfd19e232015-05-29 08:17:14219 if (exit_code)
220 *exit_code = WEXITSTATUS(status);
rvargas85728972015-03-03 20:46:19221 return true;
222 }
Zijie He4dd88ae422017-09-20 01:30:18223 return exited;
rvargas85728972015-03-03 20:46:19224}
rvargas85728972015-03-03 20:46:19225
226} // namespace
227
[email protected]176aa482008-11-14 03:25:15228namespace base {
229
Youssef Esmatc732bf82022-05-27 00:47:19230Process::Process(ProcessHandle handle) : process_(handle) {}
thakis3096dac2015-04-20 16:44:48231
dchenge1b0277c2015-12-01 12:09:52232Process::Process(Process&& other) : process_(other.process_) {
Youssef Esmatc732bf82022-05-27 00:47:19233#if BUILDFLAG(IS_CHROMEOS)
234 unique_token_ = std::move(other.unique_token_);
235#endif
236
dchenge1b0277c2015-12-01 12:09:52237 other.Close();
rvargas079d1842014-10-17 22:32:16238}
239
dchenge1b0277c2015-12-01 12:09:52240Process& Process::operator=(Process&& other) {
dchenge1b0277c2015-12-01 12:09:52241 process_ = other.process_;
Youssef Esmatc732bf82022-05-27 00:47:19242#if BUILDFLAG(IS_CHROMEOS)
243 unique_token_ = std::move(other.unique_token_);
244#endif
dchenge1b0277c2015-12-01 12:09:52245 other.Close();
rvargas079d1842014-10-17 22:32:16246 return *this;
247}
248
Youssef Esmatc732bf82022-05-27 00:47:19249Process::~Process() = default;
250
[email protected]b7d08202011-01-25 17:29:39251// static
252Process Process::Current() {
rvargasd5626f62015-02-05 19:09:24253 return Process(GetCurrentProcessHandle());
rvargas079d1842014-10-17 22:32:16254}
255
rvargas5779b382014-11-18 20:44:11256// static
rvargas6b039c372015-02-04 21:11:29257Process Process::Open(ProcessId pid) {
rvargas747ff242015-01-17 02:46:47258 if (pid == GetCurrentProcId())
259 return Current();
260
rvargas6b039c372015-02-04 21:11:29261 // On POSIX process handles are the same as PIDs.
rvargas747ff242015-01-17 02:46:47262 return Process(pid);
263}
264
265// static
rvargas1c376a82015-03-16 23:03:52266Process Process::OpenWithExtraPrivileges(ProcessId pid) {
rvargas6b039c372015-02-04 21:11:29267 // On POSIX there are no privileges to set.
268 return Open(pid);
269}
270
haraken940efb92017-02-08 05:58:15271// static
272void Process::TerminateCurrentProcessImmediately(int exit_code) {
Sebastien Marchandbd02bc29e2020-03-11 15:53:36273#if BUILDFLAG(CLANG_PROFILING)
274 WriteClangProfilingProfile();
Yuke Liaoa1d9b7b2019-08-14 16:14:34275#endif
haraken940efb92017-02-08 05:58:15276 _exit(exit_code);
277}
278
rvargas079d1842014-10-17 22:32:16279bool Process::IsValid() const {
280 return process_ != kNullProcessHandle;
281}
282
283ProcessHandle Process::Handle() const {
284 return process_;
285}
286
287Process Process::Duplicate() const {
288 if (is_current())
289 return Current();
290
Youssef Esmatc732bf82022-05-27 00:47:19291#if BUILDFLAG(IS_CHROMEOS)
292 Process duplicate = Process(process_);
293 duplicate.unique_token_ = unique_token_;
294 return duplicate;
295#else
rvargas079d1842014-10-17 22:32:16296 return Process(process_);
Youssef Esmatc732bf82022-05-27 00:47:19297#endif
[email protected]b7d08202011-01-25 17:29:39298}
299
Robert Sesek0e7f165a2020-11-20 21:31:45300ProcessHandle Process::Release() {
301 return std::exchange(process_, kNullProcessHandle);
302}
303
rvargas960db882015-01-24 00:27:25304ProcessId Process::Pid() const {
rvargas079d1842014-10-17 22:32:16305 DCHECK(IsValid());
[email protected]b7d08202011-01-25 17:29:39306 return GetProcId(process_);
307}
308
309bool Process::is_current() const {
310 return process_ == GetCurrentProcessHandle();
311}
312
[email protected]176aa482008-11-14 03:25:15313void Process::Close() {
rvargas079d1842014-10-17 22:32:16314 process_ = kNullProcessHandle;
[email protected]276aa6a2009-10-29 17:43:44315 // if the process wasn't terminated (so we waited) or the state
[email protected]1a7813642009-02-05 19:22:01316 // wasn't already collected w/ a wait from process_utils, we're gonna
317 // end up w/ a zombie when it does finally exit.
[email protected]176aa482008-11-14 03:25:15318}
319
rvargas02ad7832015-04-02 01:36:06320bool Process::Terminate(int exit_code, bool wait) const {
rickyz8055dc72015-07-01 22:50:03321 // exit_code isn't supportable.
rvargas079d1842014-10-17 22:32:16322 DCHECK(IsValid());
rickyz8055dc72015-07-01 22:50:03323 CHECK_GT(process_, 0);
324
Tom Sepez8cded8072022-06-27 23:01:43325 // RESULT_CODE_KILLED_BAD_MESSAGE == 3, but layering prevents its use.
326 // |wait| is always false when terminating badly-behaved processes.
327 const bool maybe_compromised = !wait && exit_code == 3;
328 if (maybe_compromised) {
329 // Forcibly terminate the process immediately.
330 const bool was_killed = kill(process_, SIGKILL) != 0;
331#if BUILDFLAG(IS_CHROMEOS)
332 if (was_killed)
333 CleanUpProcessAsync();
334#endif
335 DPLOG_IF(ERROR, !was_killed) << "Unable to terminate process " << process_;
336 return was_killed;
337 }
338
339 // Terminate process giving it a chance to clean up.
Tom Sepez75fafe12022-02-14 18:13:37340 if (kill(process_, SIGTERM) != 0) {
rvargas02ad7832015-04-02 01:36:06341 DPLOG(ERROR) << "Unable to terminate process " << process_;
Tom Sepez75fafe12022-02-14 18:13:37342 return false;
343 }
Youssef Esmatc732bf82022-05-27 00:47:19344
345#if BUILDFLAG(IS_CHROMEOS)
346 CleanUpProcessAsync();
347#endif
348
Tom Sepez75fafe12022-02-14 18:13:37349 if (!wait || WaitForExitWithTimeout(Seconds(60), nullptr)) {
350 return true;
351 }
352 if (kill(process_, SIGKILL) != 0) {
353 DPLOG(ERROR) << "Unable to kill process " << process_;
354 return false;
355 }
356 return WaitForExit(nullptr);
[email protected]176aa482008-11-14 03:25:15357}
358
jcivellif4462a352017-01-10 04:45:59359bool Process::WaitForExit(int* exit_code) const {
rvargas85728972015-03-03 20:46:19360 return WaitForExitWithTimeout(TimeDelta::Max(), exit_code);
rvargas126fd5822014-12-12 00:25:14361}
362
jcivellif4462a352017-01-10 04:45:59363bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const {
Gabriel Charette6836c0d52021-01-11 17:40:26364 if (!timeout.is_zero()) {
Gabriel Charette6836c0d52021-01-11 17:40:26365 // Assert that this thread is allowed to wait below. This intentionally
366 // doesn't use ScopedBlockingCallWithBaseSyncPrimitives because the process
367 // being waited upon tends to itself be using the CPU and considering this
368 // thread non-busy causes more issue than it fixes: http://crbug.com/905788
369 internal::AssertBaseSyncPrimitivesAllowed();
370 }
bcwhited9705962016-08-10 03:10:03371
Dmitry Bezheckovff22a4d2018-07-10 19:42:44372 int local_exit_code = 0;
Brian Whiteae2a8b9a2017-11-02 19:10:36373 bool exited = WaitForExitWithTimeoutImpl(Handle(), &local_exit_code, timeout);
374 if (exited) {
375 Exited(local_exit_code);
376 if (exit_code)
377 *exit_code = local_exit_code;
378 }
379 return exited;
rvargas126fd5822014-12-12 00:25:14380}
381
Youssef Esmatc732bf82022-05-27 00:47:19382void Process::Exited(int exit_code) const {
383#if BUILDFLAG(IS_CHROMEOS)
384 CleanUpProcessAsync();
385#endif
386}
Brian Whiteae2a8b9a2017-11-02 19:10:36387
Patrick Monette740b81b2023-07-21 21:09:09388int Process::GetOSPriority() const {
rvargas079d1842014-10-17 22:32:16389 DCHECK(IsValid());
Peter Kasting25acd5942022-07-07 17:45:15390 return getpriority(PRIO_PROCESS, static_cast<id_t>(process_));
[email protected]276aa6a2009-10-29 17:43:44391}
392
danakjc3762b92015-03-07 01:51:42393} // namespace base