1 // Copyright 2011 The Chromium Authors. All rights reserved.
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 "base/debug/activity_tracker.h"
14 #include "base/files/scoped_file.h"
15 #include "base/logging.h"
16 #include "base/posix/eintr_wrapper.h"
17 #include "base/process/kill.h"
18 #include "base/threading/thread_restrictions.h"
19 #include "build/build_config.h"
20
21 #if defined(OS_MACOSX)
22 #include <sys/event.h>
23 #endif
24
25 namespace {
26
27 #if !defined(OS_NACL_NONSFI)
28
WaitpidWithTimeout(base::ProcessHandle handle,int * status,base::TimeDelta wait)29 bool WaitpidWithTimeout(base::ProcessHandle handle,
30 int* status,
31 base::TimeDelta wait) {
32 // This POSIX version of this function only guarantees that we wait no less
33 // than |wait| for the process to exit. The child process may
34 // exit sometime before the timeout has ended but we may still block for up
35 // to 256 milliseconds after the fact.
36 //
37 // waitpid() has no direct support on POSIX for specifying a timeout, you can
38 // either ask it to block indefinitely or return immediately (WNOHANG).
39 // When a child process terminates a SIGCHLD signal is sent to the parent.
40 // Catching this signal would involve installing a signal handler which may
41 // affect other parts of the application and would be difficult to debug.
42 //
43 // Our strategy is to call waitpid() once up front to check if the process
44 // has already exited, otherwise to loop for |wait|, sleeping for
45 // at most 256 milliseconds each time using usleep() and then calling
46 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
47 // we double it every 4 sleep cycles.
48 //
49 // usleep() is speced to exit if a signal is received for which a handler
50 // has been installed. This means that when a SIGCHLD is sent, it will exit
51 // depending on behavior external to this function.
52 //
53 // This function is used primarily for unit tests, if we want to use it in
54 // the application itself it would probably be best to examine other routes.
55
56 if (wait == base::TimeDelta::Max()) {
57 return HANDLE_EINTR(waitpid(handle, status, 0)) > 0;
58 }
59
60 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
61 static const int64_t kMaxSleepInMicroseconds = 1 << 18; // ~256 milliseconds.
62 int64_t max_sleep_time_usecs = 1 << 10; // ~1 milliseconds.
63 int64_t double_sleep_time = 0;
64
65 // If the process hasn't exited yet, then sleep and try again.
66 base::TimeTicks wakeup_time = base::TimeTicks::Now() + wait;
67 while (ret_pid == 0) {
68 base::TimeTicks now = base::TimeTicks::Now();
69 if (now > wakeup_time)
70 break;
71 // Guaranteed to be non-negative!
72 int64_t sleep_time_usecs = (wakeup_time - now).InMicroseconds();
73 // Sleep for a bit while we wait for the process to finish.
74 if (sleep_time_usecs > max_sleep_time_usecs)
75 sleep_time_usecs = max_sleep_time_usecs;
76
77 // usleep() will return 0 and set errno to EINTR on receipt of a signal
78 // such as SIGCHLD.
79 usleep(sleep_time_usecs);
80 ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
81
82 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
83 (double_sleep_time++ % 4 == 0)) {
84 max_sleep_time_usecs *= 2;
85 }
86 }
87
88 return ret_pid > 0;
89 }
90
91 #if defined(OS_MACOSX)
92 // Using kqueue on Mac so that we can wait on non-child processes.
93 // We can't use kqueues on child processes because we need to reap
94 // our own children using wait.
WaitForSingleNonChildProcess(base::ProcessHandle handle,base::TimeDelta wait)95 bool WaitForSingleNonChildProcess(base::ProcessHandle handle,
96 base::TimeDelta wait) {
97 DCHECK_GT(handle, 0);
98
99 base::ScopedFD kq(kqueue());
100 if (!kq.is_valid()) {
101 DPLOG(ERROR) << "kqueue";
102 return false;
103 }
104
105 struct kevent change = {0};
106 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
107 int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
108 if (result == -1) {
109 if (errno == ESRCH) {
110 // If the process wasn't found, it must be dead.
111 return true;
112 }
113
114 DPLOG(ERROR) << "kevent (setup " << handle << ")";
115 return false;
116 }
117
118 // Keep track of the elapsed time to be able to restart kevent if it's
119 // interrupted.
120 bool wait_forever = (wait == base::TimeDelta::Max());
121 base::TimeDelta remaining_delta;
122 base::TimeTicks deadline;
123 if (!wait_forever) {
124 remaining_delta = wait;
125 deadline = base::TimeTicks::Now() + remaining_delta;
126 }
127
128 result = -1;
129 struct kevent event = {0};
130
131 do {
132 struct timespec remaining_timespec;
133 struct timespec* remaining_timespec_ptr;
134 if (wait_forever) {
135 remaining_timespec_ptr = NULL;
136 } else {
137 remaining_timespec = remaining_delta.ToTimeSpec();
138 remaining_timespec_ptr = &remaining_timespec;
139 }
140
141 result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
142
143 if (result == -1 && errno == EINTR) {
144 if (!wait_forever) {
145 remaining_delta = deadline - base::TimeTicks::Now();
146 }
147 result = 0;
148 } else {
149 break;
150 }
151 } while (wait_forever || remaining_delta > base::TimeDelta());
152
153 if (result < 0) {
154 DPLOG(ERROR) << "kevent (wait " << handle << ")";
155 return false;
156 } else if (result > 1) {
157 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
158 << result;
159 return false;
160 } else if (result == 0) {
161 // Timed out.
162 return false;
163 }
164
165 DCHECK_EQ(result, 1);
166
167 if (event.filter != EVFILT_PROC ||
168 (event.fflags & NOTE_EXIT) == 0 ||
169 event.ident != static_cast<uintptr_t>(handle)) {
170 DLOG(ERROR) << "kevent (wait " << handle
171 << "): unexpected event: filter=" << event.filter
172 << ", fflags=" << event.fflags
173 << ", ident=" << event.ident;
174 return false;
175 }
176
177 return true;
178 }
179 #endif // OS_MACOSX
180
WaitForExitWithTimeoutImpl(base::ProcessHandle handle,int * exit_code,base::TimeDelta timeout)181 bool WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
182 int* exit_code,
183 base::TimeDelta timeout) {
184 const base::ProcessHandle our_pid = base::GetCurrentProcessHandle();
185 if (handle == our_pid) {
186 // We won't be able to wait for ourselves to exit.
187 return false;
188 }
189
190 const base::ProcessHandle parent_pid = base::GetParentProcessId(handle);
191 const bool exited = (parent_pid < 0);
192
193 if (!exited && parent_pid != our_pid) {
194 #if defined(OS_MACOSX)
195 // On Mac we can wait on non child processes.
196 return WaitForSingleNonChildProcess(handle, timeout);
197 #else
198 // Currently on Linux we can't handle non child processes.
199 NOTIMPLEMENTED();
200 #endif // OS_MACOSX
201 }
202
203 int status;
204 if (!WaitpidWithTimeout(handle, &status, timeout))
205 return exited;
206 if (WIFSIGNALED(status)) {
207 if (exit_code)
208 *exit_code = -1;
209 return true;
210 }
211 if (WIFEXITED(status)) {
212 if (exit_code)
213 *exit_code = WEXITSTATUS(status);
214 return true;
215 }
216 return exited;
217 }
218 #endif // !defined(OS_NACL_NONSFI)
219
220 } // namespace
221
222 namespace base {
223
Process(ProcessHandle handle)224 Process::Process(ProcessHandle handle) : process_(handle) {
225 }
226
227 Process::~Process() = default;
228
Process(Process && other)229 Process::Process(Process&& other) : process_(other.process_) {
230 other.Close();
231 }
232
operator =(Process && other)233 Process& Process::operator=(Process&& other) {
234 process_ = other.process_;
235 other.Close();
236 return *this;
237 }
238
239 // static
Current()240 Process Process::Current() {
241 return Process(GetCurrentProcessHandle());
242 }
243
244 // static
Open(ProcessId pid)245 Process Process::Open(ProcessId pid) {
246 if (pid == GetCurrentProcId())
247 return Current();
248
249 // On POSIX process handles are the same as PIDs.
250 return Process(pid);
251 }
252
253 // static
OpenWithExtraPrivileges(ProcessId pid)254 Process Process::OpenWithExtraPrivileges(ProcessId pid) {
255 // On POSIX there are no privileges to set.
256 return Open(pid);
257 }
258
259 // static
DeprecatedGetProcessFromHandle(ProcessHandle handle)260 Process Process::DeprecatedGetProcessFromHandle(ProcessHandle handle) {
261 DCHECK_NE(handle, GetCurrentProcessHandle());
262 return Process(handle);
263 }
264
265 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_AIX)
266 // static
CanBackgroundProcesses()267 bool Process::CanBackgroundProcesses() {
268 return false;
269 }
270 #endif // !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_AIX)
271
272 // static
TerminateCurrentProcessImmediately(int exit_code)273 void Process::TerminateCurrentProcessImmediately(int exit_code) {
274 _exit(exit_code);
275 }
276
IsValid() const277 bool Process::IsValid() const {
278 return process_ != kNullProcessHandle;
279 }
280
Handle() const281 ProcessHandle Process::Handle() const {
282 return process_;
283 }
284
Duplicate() const285 Process Process::Duplicate() const {
286 if (is_current())
287 return Current();
288
289 return Process(process_);
290 }
291
Pid() const292 ProcessId Process::Pid() const {
293 DCHECK(IsValid());
294 return GetProcId(process_);
295 }
296
is_current() const297 bool Process::is_current() const {
298 return process_ == GetCurrentProcessHandle();
299 }
300
Close()301 void Process::Close() {
302 process_ = kNullProcessHandle;
303 // if the process wasn't terminated (so we waited) or the state
304 // wasn't already collected w/ a wait from process_utils, we're gonna
305 // end up w/ a zombie when it does finally exit.
306 }
307
308 #if !defined(OS_NACL_NONSFI)
Terminate(int exit_code,bool wait) const309 bool Process::Terminate(int exit_code, bool wait) const {
310 // exit_code isn't supportable.
311 DCHECK(IsValid());
312 CHECK_GT(process_, 0);
313
314 bool did_terminate = kill(process_, SIGTERM) == 0;
315
316 if (wait && did_terminate) {
317 if (WaitForExitWithTimeout(TimeDelta::FromSeconds(60), nullptr))
318 return true;
319 did_terminate = kill(process_, SIGKILL) == 0;
320 if (did_terminate)
321 return WaitForExit(nullptr);
322 }
323
324 if (!did_terminate)
325 DPLOG(ERROR) << "Unable to terminate process " << process_;
326
327 return did_terminate;
328 }
329 #endif // !defined(OS_NACL_NONSFI)
330
WaitForExit(int * exit_code) const331 bool Process::WaitForExit(int* exit_code) const {
332 return WaitForExitWithTimeout(TimeDelta::Max(), exit_code);
333 }
334
WaitForExitWithTimeout(TimeDelta timeout,int * exit_code) const335 bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const {
336 if (!timeout.is_zero())
337 internal::AssertBaseSyncPrimitivesAllowed();
338
339 // Record the event that this thread is blocking upon (for hang diagnosis).
340 base::debug::ScopedProcessWaitActivity process_activity(this);
341
342 int local_exit_code = 0;
343 bool exited = WaitForExitWithTimeoutImpl(Handle(), &local_exit_code, timeout);
344 if (exited) {
345 Exited(local_exit_code);
346 if (exit_code)
347 *exit_code = local_exit_code;
348 }
349 return exited;
350 }
351
Exited(int exit_code) const352 void Process::Exited(int exit_code) const {}
353
354 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_AIX)
IsProcessBackgrounded() const355 bool Process::IsProcessBackgrounded() const {
356 // See SetProcessBackgrounded().
357 DCHECK(IsValid());
358 return false;
359 }
360
SetProcessBackgrounded(bool value)361 bool Process::SetProcessBackgrounded(bool value) {
362 // Not implemented for POSIX systems other than Linux and Mac. With POSIX, if
363 // we were to lower the process priority we wouldn't be able to raise it back
364 // to its initial priority.
365 NOTIMPLEMENTED();
366 return false;
367 }
368 #endif // !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_AIX)
369
GetPriority() const370 int Process::GetPriority() const {
371 DCHECK(IsValid());
372 return getpriority(PRIO_PROCESS, process_);
373 }
374
375 } // namespace base
376