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/notreached.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 namespace {
35
WaitpidWithTimeout(base::ProcessHandle handle,int * status,base::TimeDelta wait)36 bool 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));
68 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;
71
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;
78
79 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}));
82 // 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
96 #if BUILDFLAG(IS_MAC)
97 // 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.
WaitForSingleNonChildProcess(base::ProcessHandle handle,base::TimeDelta wait)100 bool WaitForSingleNonChildProcess(base::ProcessHandle handle,
101 base::TimeDelta wait) {
102 DCHECK_GT(handle, 0);
103
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
136 do {
137 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 }
156 } while (wait_forever || remaining_delta.is_positive());
157
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 }
184 #endif // BUILDFLAG(IS_MAC)
185
WaitForExitWithTimeoutImpl(base::ProcessHandle handle,int * exit_code,base::TimeDelta timeout)186 bool WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
187 int* exit_code,
188 base::TimeDelta timeout) {
189 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 }
194
195 TRACE_EVENT0("base", "Process::WaitForExitWithTimeout");
196
197 const base::ProcessHandle parent_pid = base::GetParentProcessId(handle);
198 const bool exited = (parent_pid < 0);
199
200 if (!exited && parent_pid != our_pid) {
201 #if BUILDFLAG(IS_MAC)
202 // 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();
207 #endif // BUILDFLAG(IS_MAC)
208 }
209
210 int status;
211 if (!WaitpidWithTimeout(handle, &status, timeout))
212 return exited;
213 if (WIFSIGNALED(status)) {
214 if (exit_code)
215 *exit_code = -1;
216 return true;
217 }
218 if (WIFEXITED(status)) {
219 if (exit_code)
220 *exit_code = WEXITSTATUS(status);
221 return true;
222 }
223 return exited;
224 }
225
226 } // namespace
227
228 namespace base {
229
Process(ProcessHandle handle)230 Process::Process(ProcessHandle handle) : process_(handle) {}
231
Process(Process && other)232 Process::Process(Process&& other) : process_(other.process_) {
233 #if BUILDFLAG(IS_CHROMEOS)
234 unique_token_ = std::move(other.unique_token_);
235 #endif
236
237 other.Close();
238 }
239
operator =(Process && other)240 Process& Process::operator=(Process&& other) {
241 process_ = other.process_;
242 #if BUILDFLAG(IS_CHROMEOS)
243 unique_token_ = std::move(other.unique_token_);
244 #endif
245 other.Close();
246 return *this;
247 }
248
249 Process::~Process() = default;
250
251 // static
Current()252 Process Process::Current() {
253 return Process(GetCurrentProcessHandle());
254 }
255
256 // static
Open(ProcessId pid)257 Process Process::Open(ProcessId pid) {
258 if (pid == GetCurrentProcId())
259 return Current();
260
261 // On POSIX process handles are the same as PIDs.
262 return Process(pid);
263 }
264
265 // static
OpenWithExtraPrivileges(ProcessId pid)266 Process Process::OpenWithExtraPrivileges(ProcessId pid) {
267 // On POSIX there are no privileges to set.
268 return Open(pid);
269 }
270
271 // static
TerminateCurrentProcessImmediately(int exit_code)272 void Process::TerminateCurrentProcessImmediately(int exit_code) {
273 #if BUILDFLAG(CLANG_PROFILING)
274 WriteClangProfilingProfile();
275 #endif
276 _exit(exit_code);
277 }
278
IsValid() const279 bool Process::IsValid() const {
280 return process_ != kNullProcessHandle;
281 }
282
Handle() const283 ProcessHandle Process::Handle() const {
284 return process_;
285 }
286
Duplicate() const287 Process Process::Duplicate() const {
288 if (is_current())
289 return Current();
290
291 #if BUILDFLAG(IS_CHROMEOS)
292 Process duplicate = Process(process_);
293 duplicate.unique_token_ = unique_token_;
294 return duplicate;
295 #else
296 return Process(process_);
297 #endif
298 }
299
Release()300 ProcessHandle Process::Release() {
301 return std::exchange(process_, kNullProcessHandle);
302 }
303
Pid() const304 ProcessId Process::Pid() const {
305 DCHECK(IsValid());
306 return GetProcId(process_);
307 }
308
is_current() const309 bool Process::is_current() const {
310 return process_ == GetCurrentProcessHandle();
311 }
312
Close()313 void Process::Close() {
314 process_ = kNullProcessHandle;
315 // if the process wasn't terminated (so we waited) or the state
316 // wasn't already collected w/ a wait from process_utils, we're gonna
317 // end up w/ a zombie when it does finally exit.
318 }
319
Terminate(int exit_code,bool wait) const320 bool Process::Terminate(int exit_code, bool wait) const {
321 // exit_code isn't supportable.
322 DCHECK(IsValid());
323 CHECK_GT(process_, 0);
324
325 // 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.
340 if (kill(process_, SIGTERM) != 0) {
341 DPLOG(ERROR) << "Unable to terminate process " << process_;
342 return false;
343 }
344
345 #if BUILDFLAG(IS_CHROMEOS)
346 CleanUpProcessAsync();
347 #endif
348
349 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);
357 }
358
WaitForExit(int * exit_code) const359 bool Process::WaitForExit(int* exit_code) const {
360 return WaitForExitWithTimeout(TimeDelta::Max(), exit_code);
361 }
362
WaitForExitWithTimeout(TimeDelta timeout,int * exit_code) const363 bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const {
364 if (!timeout.is_zero()) {
365 // 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 }
371
372 int local_exit_code = 0;
373 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;
380 }
381
Exited(int exit_code) const382 void Process::Exited(int exit_code) const {
383 #if BUILDFLAG(IS_CHROMEOS)
384 CleanUpProcessAsync();
385 #endif
386 }
387
GetOSPriority() const388 int Process::GetOSPriority() const {
389 DCHECK(IsValid());
390 return getpriority(PRIO_PROCESS, static_cast<id_t>(process_));
391 }
392
393 } // namespace base
394