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 <stdint.h>
9 #include <sys/resource.h>
10 #include <sys/wait.h>
11
12 #include "base/files/scoped_file.h"
13 #include "base/logging.h"
14 #include "base/posix/eintr_wrapper.h"
15 #include "base/process/kill.h"
16 #include "build/build_config.h"
17
18 #if defined(OS_MACOSX)
19 #include <sys/event.h>
20 #endif
21
22 namespace {
23
24 #if !defined(OS_NACL_NONSFI)
25
WaitpidWithTimeout(base::ProcessHandle handle,int * status,base::TimeDelta wait)26 bool WaitpidWithTimeout(base::ProcessHandle handle,
27 int* status,
28 base::TimeDelta wait) {
29 // This POSIX version of this function only guarantees that we wait no less
30 // than |wait| for the process to exit. The child process may
31 // exit sometime before the timeout has ended but we may still block for up
32 // to 256 milliseconds after the fact.
33 //
34 // waitpid() has no direct support on POSIX for specifying a timeout, you can
35 // either ask it to block indefinitely or return immediately (WNOHANG).
36 // When a child process terminates a SIGCHLD signal is sent to the parent.
37 // Catching this signal would involve installing a signal handler which may
38 // affect other parts of the application and would be difficult to debug.
39 //
40 // Our strategy is to call waitpid() once up front to check if the process
41 // has already exited, otherwise to loop for |wait|, sleeping for
42 // at most 256 milliseconds each time using usleep() and then calling
43 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
44 // we double it every 4 sleep cycles.
45 //
46 // usleep() is speced to exit if a signal is received for which a handler
47 // has been installed. This means that when a SIGCHLD is sent, it will exit
48 // depending on behavior external to this function.
49 //
50 // This function is used primarily for unit tests, if we want to use it in
51 // the application itself it would probably be best to examine other routes.
52
53 if (wait == base::TimeDelta::Max()) {
54 return HANDLE_EINTR(waitpid(handle, status, 0)) > 0;
55 }
56
57 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
58 static const int64_t kMaxSleepInMicroseconds = 1 << 18; // ~256 milliseconds.
59 int64_t max_sleep_time_usecs = 1 << 10; // ~1 milliseconds.
60 int64_t double_sleep_time = 0;
61
62 // If the process hasn't exited yet, then sleep and try again.
63 base::TimeTicks wakeup_time = base::TimeTicks::Now() + wait;
64 while (ret_pid == 0) {
65 base::TimeTicks now = base::TimeTicks::Now();
66 if (now > wakeup_time)
67 break;
68 // Guaranteed to be non-negative!
69 int64_t sleep_time_usecs = (wakeup_time - now).InMicroseconds();
70 // Sleep for a bit while we wait for the process to finish.
71 if (sleep_time_usecs > max_sleep_time_usecs)
72 sleep_time_usecs = max_sleep_time_usecs;
73
74 // usleep() will return 0 and set errno to EINTR on receipt of a signal
75 // such as SIGCHLD.
76 usleep(sleep_time_usecs);
77 ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
78
79 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
80 (double_sleep_time++ % 4 == 0)) {
81 max_sleep_time_usecs *= 2;
82 }
83 }
84
85 return ret_pid > 0;
86 }
87
88 #if defined(OS_MACOSX)
89 // Using kqueue on Mac so that we can wait on non-child processes.
90 // We can't use kqueues on child processes because we need to reap
91 // our own children using wait.
WaitForSingleNonChildProcess(base::ProcessHandle handle,base::TimeDelta wait)92 static bool WaitForSingleNonChildProcess(base::ProcessHandle handle,
93 base::TimeDelta wait) {
94 DCHECK_GT(handle, 0);
95 DCHECK_GT(wait, base::TimeDelta());
96
97 base::ScopedFD kq(kqueue());
98 if (!kq.is_valid()) {
99 DPLOG(ERROR) << "kqueue";
100 return false;
101 }
102
103 struct kevent change;
104 memset(&change, 0, sizeof(change));
105 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
106 int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
107 if (result == -1) {
108 if (errno == ESRCH) {
109 // If the process wasn't found, it must be dead.
110 return true;
111 }
112
113 DPLOG(ERROR) << "kevent (setup " << handle << ")";
114 return false;
115 }
116
117 // Keep track of the elapsed time to be able to restart kevent if it's
118 // interrupted.
119 bool wait_forever = (wait == base::TimeDelta::Max());
120 base::TimeDelta remaining_delta;
121 base::TimeTicks deadline;
122 if (!wait_forever) {
123 remaining_delta = wait;
124 deadline = base::TimeTicks::Now() + remaining_delta;
125 }
126
127 result = -1;
128 struct kevent event;
129 memset(&event, 0, sizeof(event));
130
131 while (wait_forever || remaining_delta > base::TimeDelta()) {
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 }
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 base::ProcessHandle parent_pid = base::GetParentProcessId(handle);
185 base::ProcessHandle our_pid = base::GetCurrentProcessHandle();
186 if (parent_pid != our_pid) {
187 #if defined(OS_MACOSX)
188 // On Mac we can wait on non child processes.
189 return WaitForSingleNonChildProcess(handle, timeout);
190 #else
191 // Currently on Linux we can't handle non child processes.
192 NOTIMPLEMENTED();
193 #endif // OS_MACOSX
194 }
195
196 int status;
197 if (!WaitpidWithTimeout(handle, &status, timeout))
198 return false;
199 if (WIFSIGNALED(status)) {
200 if (exit_code)
201 *exit_code = -1;
202 return true;
203 }
204 if (WIFEXITED(status)) {
205 if (exit_code)
206 *exit_code = WEXITSTATUS(status);
207 return true;
208 }
209 return false;
210 }
211 #endif // !defined(OS_NACL_NONSFI)
212
213 } // namespace
214
215 namespace base {
216
Process(ProcessHandle handle)217 Process::Process(ProcessHandle handle) : process_(handle) {
218 }
219
~Process()220 Process::~Process() {
221 }
222
Process(Process && other)223 Process::Process(Process&& other) : process_(other.process_) {
224 other.Close();
225 }
226
operator =(Process && other)227 Process& Process::operator=(Process&& other) {
228 DCHECK_NE(this, &other);
229 process_ = other.process_;
230 other.Close();
231 return *this;
232 }
233
234 // static
Current()235 Process Process::Current() {
236 return Process(GetCurrentProcessHandle());
237 }
238
239 // static
Open(ProcessId pid)240 Process Process::Open(ProcessId pid) {
241 if (pid == GetCurrentProcId())
242 return Current();
243
244 // On POSIX process handles are the same as PIDs.
245 return Process(pid);
246 }
247
248 // static
OpenWithExtraPrivileges(ProcessId pid)249 Process Process::OpenWithExtraPrivileges(ProcessId pid) {
250 // On POSIX there are no privileges to set.
251 return Open(pid);
252 }
253
254 // static
DeprecatedGetProcessFromHandle(ProcessHandle handle)255 Process Process::DeprecatedGetProcessFromHandle(ProcessHandle handle) {
256 DCHECK_NE(handle, GetCurrentProcessHandle());
257 return Process(handle);
258 }
259
260 #if !defined(OS_LINUX)
261 // static
CanBackgroundProcesses()262 bool Process::CanBackgroundProcesses() {
263 return false;
264 }
265 #endif // !defined(OS_LINUX)
266
IsValid() const267 bool Process::IsValid() const {
268 return process_ != kNullProcessHandle;
269 }
270
Handle() const271 ProcessHandle Process::Handle() const {
272 return process_;
273 }
274
Duplicate() const275 Process Process::Duplicate() const {
276 if (is_current())
277 return Current();
278
279 return Process(process_);
280 }
281
Pid() const282 ProcessId Process::Pid() const {
283 DCHECK(IsValid());
284 return GetProcId(process_);
285 }
286
is_current() const287 bool Process::is_current() const {
288 return process_ == GetCurrentProcessHandle();
289 }
290
Close()291 void Process::Close() {
292 process_ = kNullProcessHandle;
293 // if the process wasn't terminated (so we waited) or the state
294 // wasn't already collected w/ a wait from process_utils, we're gonna
295 // end up w/ a zombie when it does finally exit.
296 }
297
298 #if !defined(OS_NACL_NONSFI)
Terminate(int,bool wait) const299 bool Process::Terminate(int /* exit_code */, bool wait) const {
300 // exit_code isn't supportable.
301 DCHECK(IsValid());
302 CHECK_GT(process_, 0);
303
304 bool result = kill(process_, SIGTERM) == 0;
305 if (result && wait) {
306 int tries = 60;
307
308 unsigned sleep_ms = 4;
309
310 // The process may not end immediately due to pending I/O
311 bool exited = false;
312 while (tries-- > 0) {
313 pid_t pid = HANDLE_EINTR(waitpid(process_, NULL, WNOHANG));
314 if (pid == process_) {
315 exited = true;
316 break;
317 }
318 if (pid == -1) {
319 if (errno == ECHILD) {
320 // The wait may fail with ECHILD if another process also waited for
321 // the same pid, causing the process state to get cleaned up.
322 exited = true;
323 break;
324 }
325 DPLOG(ERROR) << "Error waiting for process " << process_;
326 }
327
328 usleep(sleep_ms * 1000);
329 const unsigned kMaxSleepMs = 1000;
330 if (sleep_ms < kMaxSleepMs)
331 sleep_ms *= 2;
332 }
333
334 // If we're waiting and the child hasn't died by now, force it
335 // with a SIGKILL.
336 if (!exited)
337 result = kill(process_, SIGKILL) == 0;
338 }
339
340 if (!result)
341 DPLOG(ERROR) << "Unable to terminate process " << process_;
342
343 return result;
344 }
345 #endif // !defined(OS_NACL_NONSFI)
346
WaitForExit(int * exit_code)347 bool Process::WaitForExit(int* exit_code) {
348 return WaitForExitWithTimeout(TimeDelta::Max(), exit_code);
349 }
350
WaitForExitWithTimeout(TimeDelta timeout,int * exit_code)351 bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) {
352 return WaitForExitWithTimeoutImpl(Handle(), exit_code, timeout);
353 }
354
355 #if !defined(OS_LINUX)
IsProcessBackgrounded() const356 bool Process::IsProcessBackgrounded() const {
357 // See SetProcessBackgrounded().
358 DCHECK(IsValid());
359 return false;
360 }
361
SetProcessBackgrounded(bool)362 bool Process::SetProcessBackgrounded(bool /*value*/) {
363 // Not implemented for POSIX systems other than Linux. With POSIX, if we were
364 // to lower the process priority we wouldn't be able to raise it back to its
365 // initial priority.
366 NOTIMPLEMENTED();
367 return false;
368 }
369 #endif // !defined(OS_LINUX)
370
GetPriority() const371 int Process::GetPriority() const {
372 DCHECK(IsValid());
373 return getpriority(PRIO_PROCESS, process_);
374 }
375
376 } // namespace base
377