blob: 7b2eed784deea54570550663ffd49c872376bdfe [file] [log] [blame]
shrike08e576f2015-06-03 04:53:57 +09001// Copyright 2011 The Chromium Authors. All rights reserved.
evanm@google.com0c9f1eb2008-10-15 05:49:16 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
rsesek@chromium.orgc2b81bd2013-07-20 01:48:56 +09005#include "base/process/process.h"
pvalchev@google.com1d919db2010-03-10 16:46:43 +09006
mostynb8b7b1172015-11-07 09:57:14 +09007#include <errno.h>
davemoore@chromium.orgad59fcb2009-10-30 02:43:44 +09008#include <sys/resource.h>
rvargasc66501f2015-03-04 05:46:19 +09009#include <sys/wait.h>
davemoore@chromium.orgad59fcb2009-10-30 02:43:44 +090010
rvargasc66501f2015-03-04 05:46:19 +090011#include "base/files/scoped_file.h"
erg@google.com6e67c1d2010-07-29 02:25:28 +090012#include "base/logging.h"
rvargasc66501f2015-03-04 05:46:19 +090013#include "base/posix/eintr_wrapper.h"
rsesek@chromium.org687756f2013-07-26 06:38:23 +090014#include "base/process/kill.h"
rvargaseb3cd352015-04-02 10:36:06 +090015#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
evanm@google.com0c9f1eb2008-10-15 05:49:16 +090016
rvargasc66501f2015-03-04 05:46:19 +090017#if defined(OS_MACOSX)
18#include <sys/event.h>
19#endif
20
21namespace {
22
23#if !defined(OS_NACL_NONSFI)
24
25bool WaitpidWithTimeout(base::ProcessHandle handle,
26 int* status,
27 base::TimeDelta wait) {
28 // This POSIX version of this function only guarantees that we wait no less
29 // than |wait| for the process to exit. The child process may
30 // exit sometime before the timeout has ended but we may still block for up
31 // to 256 milliseconds after the fact.
32 //
33 // waitpid() has no direct support on POSIX for specifying a timeout, you can
34 // either ask it to block indefinitely or return immediately (WNOHANG).
35 // When a child process terminates a SIGCHLD signal is sent to the parent.
36 // Catching this signal would involve installing a signal handler which may
37 // affect other parts of the application and would be difficult to debug.
38 //
39 // Our strategy is to call waitpid() once up front to check if the process
40 // has already exited, otherwise to loop for |wait|, sleeping for
41 // at most 256 milliseconds each time using usleep() and then calling
42 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
43 // we double it every 4 sleep cycles.
44 //
45 // usleep() is speced to exit if a signal is received for which a handler
46 // has been installed. This means that when a SIGCHLD is sent, it will exit
47 // depending on behavior external to this function.
48 //
49 // This function is used primarily for unit tests, if we want to use it in
50 // the application itself it would probably be best to examine other routes.
51
52 if (wait == base::TimeDelta::Max()) {
53 return HANDLE_EINTR(waitpid(handle, status, 0)) > 0;
54 }
55
56 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
57 static const int64 kMaxSleepInMicroseconds = 1 << 18; // ~256 milliseconds.
58 int64 max_sleep_time_usecs = 1 << 10; // ~1 milliseconds.
59 int64 double_sleep_time = 0;
60
61 // If the process hasn't exited yet, then sleep and try again.
62 base::TimeTicks wakeup_time = base::TimeTicks::Now() + wait;
63 while (ret_pid == 0) {
64 base::TimeTicks now = base::TimeTicks::Now();
65 if (now > wakeup_time)
66 break;
67 // Guaranteed to be non-negative!
68 int64 sleep_time_usecs = (wakeup_time - now).InMicroseconds();
69 // Sleep for a bit while we wait for the process to finish.
70 if (sleep_time_usecs > max_sleep_time_usecs)
71 sleep_time_usecs = max_sleep_time_usecs;
72
73 // usleep() will return 0 and set errno to EINTR on receipt of a signal
74 // such as SIGCHLD.
75 usleep(sleep_time_usecs);
76 ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
77
78 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
79 (double_sleep_time++ % 4 == 0)) {
80 max_sleep_time_usecs *= 2;
81 }
82 }
83
84 return ret_pid > 0;
85}
86
87#if defined(OS_MACOSX)
88// Using kqueue on Mac so that we can wait on non-child processes.
89// We can't use kqueues on child processes because we need to reap
90// our own children using wait.
91static bool WaitForSingleNonChildProcess(base::ProcessHandle handle,
92 base::TimeDelta wait) {
93 DCHECK_GT(handle, 0);
94 DCHECK_GT(wait, base::TimeDelta());
95
96 base::ScopedFD kq(kqueue());
97 if (!kq.is_valid()) {
98 DPLOG(ERROR) << "kqueue";
99 return false;
100 }
101
102 struct kevent change = {0};
103 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
104 int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
105 if (result == -1) {
106 if (errno == ESRCH) {
107 // If the process wasn't found, it must be dead.
108 return true;
109 }
110
111 DPLOG(ERROR) << "kevent (setup " << handle << ")";
112 return false;
113 }
114
115 // Keep track of the elapsed time to be able to restart kevent if it's
116 // interrupted.
117 bool wait_forever = (wait == base::TimeDelta::Max());
118 base::TimeDelta remaining_delta;
119 base::TimeTicks deadline;
120 if (!wait_forever) {
121 remaining_delta = wait;
122 deadline = base::TimeTicks::Now() + remaining_delta;
123 }
124
125 result = -1;
126 struct kevent event = {0};
127
128 while (wait_forever || remaining_delta > base::TimeDelta()) {
129 struct timespec remaining_timespec;
130 struct timespec* remaining_timespec_ptr;
131 if (wait_forever) {
132 remaining_timespec_ptr = NULL;
133 } else {
134 remaining_timespec = remaining_delta.ToTimeSpec();
135 remaining_timespec_ptr = &remaining_timespec;
136 }
137
138 result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
139
140 if (result == -1 && errno == EINTR) {
141 if (!wait_forever) {
142 remaining_delta = deadline - base::TimeTicks::Now();
143 }
144 result = 0;
145 } else {
146 break;
147 }
148 }
149
150 if (result < 0) {
151 DPLOG(ERROR) << "kevent (wait " << handle << ")";
152 return false;
153 } else if (result > 1) {
154 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
155 << result;
156 return false;
157 } else if (result == 0) {
158 // Timed out.
159 return false;
160 }
161
162 DCHECK_EQ(result, 1);
163
164 if (event.filter != EVFILT_PROC ||
165 (event.fflags & NOTE_EXIT) == 0 ||
166 event.ident != static_cast<uintptr_t>(handle)) {
167 DLOG(ERROR) << "kevent (wait " << handle
168 << "): unexpected event: filter=" << event.filter
169 << ", fflags=" << event.fflags
170 << ", ident=" << event.ident;
171 return false;
172 }
173
174 return true;
175}
176#endif // OS_MACOSX
177
178bool WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
179 int* exit_code,
180 base::TimeDelta timeout) {
181 base::ProcessHandle parent_pid = base::GetParentProcessId(handle);
182 base::ProcessHandle our_pid = base::GetCurrentProcessHandle();
183 if (parent_pid != our_pid) {
184#if defined(OS_MACOSX)
185 // On Mac we can wait on non child processes.
186 return WaitForSingleNonChildProcess(handle, timeout);
187#else
188 // Currently on Linux we can't handle non child processes.
189 NOTIMPLEMENTED();
190#endif // OS_MACOSX
191 }
192
193 int status;
194 if (!WaitpidWithTimeout(handle, &status, timeout))
195 return false;
196 if (WIFSIGNALED(status)) {
g.mehndiratt6acf5ca2015-05-29 17:17:14 +0900197 if (exit_code)
198 *exit_code = -1;
rvargasc66501f2015-03-04 05:46:19 +0900199 return true;
200 }
201 if (WIFEXITED(status)) {
g.mehndiratt6acf5ca2015-05-29 17:17:14 +0900202 if (exit_code)
203 *exit_code = WEXITSTATUS(status);
rvargasc66501f2015-03-04 05:46:19 +0900204 return true;
205 }
206 return false;
207}
208#endif // !defined(OS_NACL_NONSFI)
209
210} // namespace
211
brettw@google.comc60d9892008-11-14 12:25:15 +0900212namespace base {
213
rvargasa9aa6712014-10-18 07:32:16 +0900214Process::Process(ProcessHandle handle) : process_(handle) {
rvargasa9aa6712014-10-18 07:32:16 +0900215}
216
thakisb1e9a072015-04-21 01:44:48 +0900217Process::~Process() {
218}
219
dcheng8e5e0e62015-12-01 21:09:52 +0900220Process::Process(Process&& other) : process_(other.process_) {
221 other.Close();
rvargasa9aa6712014-10-18 07:32:16 +0900222}
223
dcheng8e5e0e62015-12-01 21:09:52 +0900224Process& Process::operator=(Process&& other) {
225 DCHECK_NE(this, &other);
226 process_ = other.process_;
227 other.Close();
rvargasa9aa6712014-10-18 07:32:16 +0900228 return *this;
229}
230
erg@google.comd00c64e2011-01-26 02:29:39 +0900231// static
232Process Process::Current() {
rvargasbe05ac22015-02-06 04:09:24 +0900233 return Process(GetCurrentProcessHandle());
rvargasa9aa6712014-10-18 07:32:16 +0900234}
235
rvargasc0165662014-11-19 05:44:11 +0900236// static
rvargas2b74c8f2015-02-05 06:11:29 +0900237Process Process::Open(ProcessId pid) {
rvargas27f47562015-01-17 11:46:47 +0900238 if (pid == GetCurrentProcId())
239 return Current();
240
rvargas2b74c8f2015-02-05 06:11:29 +0900241 // On POSIX process handles are the same as PIDs.
rvargas27f47562015-01-17 11:46:47 +0900242 return Process(pid);
243}
244
245// static
rvargas1a114482015-03-17 08:03:52 +0900246Process Process::OpenWithExtraPrivileges(ProcessId pid) {
rvargas2b74c8f2015-02-05 06:11:29 +0900247 // On POSIX there are no privileges to set.
248 return Open(pid);
249}
250
251// static
rvargasc0165662014-11-19 05:44:11 +0900252Process Process::DeprecatedGetProcessFromHandle(ProcessHandle handle) {
253 DCHECK_NE(handle, GetCurrentProcessHandle());
254 return Process(handle);
255}
256
shrike6e8e11d2015-09-25 03:38:00 +0900257#if !defined(OS_LINUX)
rvargasa9aa6712014-10-18 07:32:16 +0900258// static
259bool Process::CanBackgroundProcesses() {
260 return false;
261}
shrike6e8e11d2015-09-25 03:38:00 +0900262#endif // !defined(OS_LINUX)
rvargasa9aa6712014-10-18 07:32:16 +0900263
264bool Process::IsValid() const {
265 return process_ != kNullProcessHandle;
266}
267
268ProcessHandle Process::Handle() const {
269 return process_;
270}
271
272Process Process::Duplicate() const {
273 if (is_current())
274 return Current();
275
276 return Process(process_);
erg@google.comd00c64e2011-01-26 02:29:39 +0900277}
278
rvargasc5a6f982015-01-24 09:27:25 +0900279ProcessId Process::Pid() const {
rvargasa9aa6712014-10-18 07:32:16 +0900280 DCHECK(IsValid());
erg@google.comd00c64e2011-01-26 02:29:39 +0900281 return GetProcId(process_);
282}
283
284bool Process::is_current() const {
285 return process_ == GetCurrentProcessHandle();
286}
287
brettw@google.comc60d9892008-11-14 12:25:15 +0900288void Process::Close() {
rvargasa9aa6712014-10-18 07:32:16 +0900289 process_ = kNullProcessHandle;
davemoore@chromium.orgad59fcb2009-10-30 02:43:44 +0900290 // if the process wasn't terminated (so we waited) or the state
thomasvl@chromium.org570d7442009-02-06 04:22:01 +0900291 // wasn't already collected w/ a wait from process_utils, we're gonna
292 // end up w/ a zombie when it does finally exit.
brettw@google.comc60d9892008-11-14 12:25:15 +0900293}
294
rvargaseb3cd352015-04-02 10:36:06 +0900295#if !defined(OS_NACL_NONSFI)
296bool Process::Terminate(int exit_code, bool wait) const {
rickyz593f78c2015-07-02 07:50:03 +0900297 // exit_code isn't supportable.
rvargasa9aa6712014-10-18 07:32:16 +0900298 DCHECK(IsValid());
rickyz593f78c2015-07-02 07:50:03 +0900299 CHECK_GT(process_, 0);
300
rvargaseb3cd352015-04-02 10:36:06 +0900301 bool result = kill(process_, SIGTERM) == 0;
302 if (result && wait) {
303 int tries = 60;
304
305 if (RunningOnValgrind()) {
306 // Wait for some extra time when running under Valgrind since the child
307 // processes may take some time doing leak checking.
308 tries *= 2;
309 }
310
311 unsigned sleep_ms = 4;
312
313 // The process may not end immediately due to pending I/O
314 bool exited = false;
315 while (tries-- > 0) {
316 pid_t pid = HANDLE_EINTR(waitpid(process_, NULL, WNOHANG));
317 if (pid == process_) {
318 exited = true;
319 break;
320 }
321 if (pid == -1) {
322 if (errno == ECHILD) {
323 // The wait may fail with ECHILD if another process also waited for
324 // the same pid, causing the process state to get cleaned up.
325 exited = true;
326 break;
327 }
328 DPLOG(ERROR) << "Error waiting for process " << process_;
329 }
330
331 usleep(sleep_ms * 1000);
332 const unsigned kMaxSleepMs = 1000;
333 if (sleep_ms < kMaxSleepMs)
334 sleep_ms *= 2;
335 }
336
337 // If we're waiting and the child hasn't died by now, force it
338 // with a SIGKILL.
339 if (!exited)
340 result = kill(process_, SIGKILL) == 0;
341 }
342
343 if (!result)
344 DPLOG(ERROR) << "Unable to terminate process " << process_;
345
346 return result;
brettw@google.comc60d9892008-11-14 12:25:15 +0900347}
rvargaseb3cd352015-04-02 10:36:06 +0900348#endif // !defined(OS_NACL_NONSFI)
brettw@google.comc60d9892008-11-14 12:25:15 +0900349
rvargas74cc1372014-12-12 09:25:14 +0900350bool Process::WaitForExit(int* exit_code) {
rvargasc66501f2015-03-04 05:46:19 +0900351 return WaitForExitWithTimeout(TimeDelta::Max(), exit_code);
rvargas74cc1372014-12-12 09:25:14 +0900352}
353
354bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) {
rvargasc66501f2015-03-04 05:46:19 +0900355 return WaitForExitWithTimeoutImpl(Handle(), exit_code, timeout);
rvargas74cc1372014-12-12 09:25:14 +0900356}
357
shrike6e8e11d2015-09-25 03:38:00 +0900358#if !defined(OS_LINUX)
brettw@google.comba3b5a32008-11-12 07:35:19 +0900359bool Process::IsProcessBackgrounded() const {
davemoore@chromium.orgad59fcb2009-10-30 02:43:44 +0900360 // See SetProcessBackgrounded().
rvargasa9aa6712014-10-18 07:32:16 +0900361 DCHECK(IsValid());
evanm@google.com0c9f1eb2008-10-15 05:49:16 +0900362 return false;
363}
364
365bool Process::SetProcessBackgrounded(bool value) {
shrike00a05f72015-10-02 11:46:58 +0900366 // Not implemented for POSIX systems other than Linux. With POSIX, if we were
367 // to lower the process priority we wouldn't be able to raise it back to its
368 // initial priority.
shrike08e576f2015-06-03 04:53:57 +0900369 NOTIMPLEMENTED();
davemoore@chromium.orgad59fcb2009-10-30 02:43:44 +0900370 return false;
evanm@google.com0c9f1eb2008-10-15 05:49:16 +0900371}
shrike6e8e11d2015-09-25 03:38:00 +0900372#endif // !defined(OS_LINUX)
evanm@google.com0c9f1eb2008-10-15 05:49:16 +0900373
davemoore@chromium.orgad59fcb2009-10-30 02:43:44 +0900374int Process::GetPriority() const {
rvargasa9aa6712014-10-18 07:32:16 +0900375 DCHECK(IsValid());
davemoore@chromium.orgad59fcb2009-10-30 02:43:44 +0900376 return getpriority(PRIO_PROCESS, process_);
377}
378
danakj651c3e22015-03-07 10:51:42 +0900379} // namespace base