| 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/clang_profiling_buildflags.h" |
| 14 | #include "base/debug/activity_tracker.h" |
| 15 | #include "base/files/scoped_file.h" |
| 16 | #include "base/logging.h" |
| 17 | #include "base/posix/eintr_wrapper.h" |
| 18 | #include "base/process/kill.h" |
| 19 | #include "base/threading/thread_restrictions.h" |
| 20 | #include "build/build_config.h" |
| 21 |
| 22 | #if defined(OS_MACOSX) |
| 23 | #include <sys/event.h> |
| 24 | #endif |
| 25 |
| 26 | #if BUILDFLAG(CLANG_PROFILING) |
| 27 | #include "base/test/clang_profiling.h" |
| 28 | #endif |
| 29 |
| 30 | namespace { |
| 31 |
| 32 | #if !defined(OS_NACL_NONSFI) |
| 33 |
| 34 | bool WaitpidWithTimeout(base::ProcessHandle handle, |
| 35 | int* status, |
| 36 | base::TimeDelta wait) { |
| 37 | // This POSIX version of this function only guarantees that we wait no less |
| 38 | // than |wait| for the process to exit. The child process may |
| 39 | // exit sometime before the timeout has ended but we may still block for up |
| 40 | // to 256 milliseconds after the fact. |
| 41 | // |
| 42 | // waitpid() has no direct support on POSIX for specifying a timeout, you can |
| 43 | // either ask it to block indefinitely or return immediately (WNOHANG). |
| 44 | // When a child process terminates a SIGCHLD signal is sent to the parent. |
| 45 | // Catching this signal would involve installing a signal handler which may |
| 46 | // affect other parts of the application and would be difficult to debug. |
| 47 | // |
| 48 | // Our strategy is to call waitpid() once up front to check if the process |
| 49 | // has already exited, otherwise to loop for |wait|, sleeping for |
| 50 | // at most 256 milliseconds each time using usleep() and then calling |
| 51 | // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and |
| 52 | // we double it every 4 sleep cycles. |
| 53 | // |
| 54 | // usleep() is speced to exit if a signal is received for which a handler |
| 55 | // has been installed. This means that when a SIGCHLD is sent, it will exit |
| 56 | // depending on behavior external to this function. |
| 57 | // |
| 58 | // This function is used primarily for unit tests, if we want to use it in |
| 59 | // the application itself it would probably be best to examine other routes. |
| 60 |
| 61 | if (wait == base::TimeDelta::Max()) { |
| 62 | return HANDLE_EINTR(waitpid(handle, status, 0)) > 0; |
| 63 | } |
| 64 |
| 65 | pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG)); |
| 66 | static const int64_t kMaxSleepInMicroseconds = 1 << 18; // ~256 milliseconds. |
| 67 | int64_t max_sleep_time_usecs = 1 << 10; // ~1 milliseconds. |
| 68 | int64_t double_sleep_time = 0; |
| 69 |
| 70 | // If the process hasn't exited yet, then sleep and try again. |
| 71 | base::TimeTicks wakeup_time = base::TimeTicks::Now() + wait; |
| 72 | while (ret_pid == 0) { |
| 73 | base::TimeTicks now = base::TimeTicks::Now(); |
| 74 | if (now > wakeup_time) |
| 75 | break; |
| 76 | // Guaranteed to be non-negative! |
| 77 | int64_t sleep_time_usecs = (wakeup_time - now).InMicroseconds(); |
| 78 | // Sleep for a bit while we wait for the process to finish. |
| 79 | if (sleep_time_usecs > max_sleep_time_usecs) |
| 80 | sleep_time_usecs = max_sleep_time_usecs; |
| 81 |
| 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 defined(OS_MACOSX) |
| 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. |
| 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 > base::TimeDelta()); |
| 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 // OS_MACOSX |
| 185 |
| 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 | const base::ProcessHandle parent_pid = base::GetParentProcessId(handle); |
| 196 | const bool exited = (parent_pid < 0); |
| 197 |
| 198 | if (!exited && parent_pid != our_pid) { |
| 199 | #if defined(OS_MACOSX) |
| 200 | // On Mac we can wait on non child processes. |
| 201 | return WaitForSingleNonChildProcess(handle, timeout); |
| 202 | #else |
| 203 | // Currently on Linux we can't handle non child processes. |
| 204 | NOTIMPLEMENTED(); |
| 205 | #endif // OS_MACOSX |
| 206 | } |
| 207 |
| 208 | int status; |
| 209 | if (!WaitpidWithTimeout(handle, &status, timeout)) |
| 210 | return exited; |
| 211 | if (WIFSIGNALED(status)) { |
| 212 | if (exit_code) |
| 213 | *exit_code = -1; |
| 214 | return true; |
| 215 | } |
| 216 | if (WIFEXITED(status)) { |
| 217 | if (exit_code) |
| 218 | *exit_code = WEXITSTATUS(status); |
| 219 | return true; |
| 220 | } |
| 221 | return exited; |
| 222 | } |
| 223 | #endif // !defined(OS_NACL_NONSFI) |
| 224 |
| 225 | } // namespace |
| 226 |
| 227 | namespace base { |
| 228 |
| 229 | Process::Process(ProcessHandle handle) : process_(handle) { |
| 230 | } |
| 231 |
| 232 | Process::~Process() = default; |
| 233 |
| 234 | Process::Process(Process&& other) : process_(other.process_) { |
| 235 | other.Close(); |
| 236 | } |
| 237 |
| 238 | Process& Process::operator=(Process&& other) { |
| 239 | process_ = other.process_; |
| 240 | other.Close(); |
| 241 | return *this; |
| 242 | } |
| 243 |
| 244 | // static |
| 245 | Process Process::Current() { |
| 246 | return Process(GetCurrentProcessHandle()); |
| 247 | } |
| 248 |
| 249 | // static |
| 250 | Process Process::Open(ProcessId pid) { |
| 251 | if (pid == GetCurrentProcId()) |
| 252 | return Current(); |
| 253 |
| 254 | // On POSIX process handles are the same as PIDs. |
| 255 | return Process(pid); |
| 256 | } |
| 257 |
| 258 | // static |
| 259 | Process Process::OpenWithExtraPrivileges(ProcessId pid) { |
| 260 | // On POSIX there are no privileges to set. |
| 261 | return Open(pid); |
| 262 | } |
| 263 |
| 264 | // static |
| 265 | Process Process::DeprecatedGetProcessFromHandle(ProcessHandle handle) { |
| 266 | DCHECK_NE(handle, GetCurrentProcessHandle()); |
| 267 | return Process(handle); |
| 268 | } |
| 269 |
| 270 | #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_AIX) |
| 271 | // static |
| 272 | bool Process::CanBackgroundProcesses() { |
| 273 | return false; |
| 274 | } |
| 275 | #endif // !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_AIX) |
| 276 |
| 277 | // static |
| 278 | void Process::TerminateCurrentProcessImmediately(int exit_code) { |
| 279 | #if BUILDFLAG(CLANG_PROFILING) |
| 280 | WriteClangProfilingProfile(); |
| 281 | #endif |
| 282 | _exit(exit_code); |
| 283 | } |
| 284 |
| 285 | bool Process::IsValid() const { |
| 286 | return process_ != kNullProcessHandle; |
| 287 | } |
| 288 |
| 289 | ProcessHandle Process::Handle() const { |
| 290 | return process_; |
| 291 | } |
| 292 |
| 293 | Process Process::Duplicate() const { |
| 294 | if (is_current()) |
| 295 | return Current(); |
| 296 |
| 297 | return Process(process_); |
| 298 | } |
| 299 |
| 300 | ProcessId Process::Pid() const { |
| 301 | DCHECK(IsValid()); |
| 302 | return GetProcId(process_); |
| 303 | } |
| 304 |
| 305 | bool Process::is_current() const { |
| 306 | return process_ == GetCurrentProcessHandle(); |
| 307 | } |
| 308 |
| 309 | void Process::Close() { |
| 310 | process_ = kNullProcessHandle; |
| 311 | // if the process wasn't terminated (so we waited) or the state |
| 312 | // wasn't already collected w/ a wait from process_utils, we're gonna |
| 313 | // end up w/ a zombie when it does finally exit. |
| 314 | } |
| 315 |
| 316 | #if !defined(OS_NACL_NONSFI) |
| 317 | bool Process::Terminate(int exit_code, bool wait) const { |
| 318 | // exit_code isn't supportable. |
| 319 | DCHECK(IsValid()); |
| 320 | CHECK_GT(process_, 0); |
| 321 |
| 322 | bool did_terminate = kill(process_, SIGTERM) == 0; |
| 323 |
| 324 | if (wait && did_terminate) { |
| 325 | if (WaitForExitWithTimeout(TimeDelta::FromSeconds(60), nullptr)) |
| 326 | return true; |
| 327 | did_terminate = kill(process_, SIGKILL) == 0; |
| 328 | if (did_terminate) |
| 329 | return WaitForExit(nullptr); |
| 330 | } |
| 331 |
| 332 | if (!did_terminate) |
| 333 | DPLOG(ERROR) << "Unable to terminate process " << process_; |
| 334 |
| 335 | return did_terminate; |
| 336 | } |
| 337 | #endif // !defined(OS_NACL_NONSFI) |
| 338 |
| 339 | bool Process::WaitForExit(int* exit_code) const { |
| 340 | return WaitForExitWithTimeout(TimeDelta::Max(), exit_code); |
| 341 | } |
| 342 |
| 343 | bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const { |
| 344 | // Intentionally avoid instantiating ScopedBlockingCallWithBaseSyncPrimitives. |
| 345 | // In some cases, this function waits on a child Process doing CPU work. |
| 346 | // http://crbug.com/905788 |
| 347 | if (!timeout.is_zero()) |
| 348 | internal::AssertBaseSyncPrimitivesAllowed(); |
| 349 |
| 350 | // Record the event that this thread is blocking upon (for hang diagnosis). |
| 351 | base::debug::ScopedProcessWaitActivity process_activity(this); |
| 352 |
| 353 | int local_exit_code = 0; |
| 354 | bool exited = WaitForExitWithTimeoutImpl(Handle(), &local_exit_code, timeout); |
| 355 | if (exited) { |
| 356 | Exited(local_exit_code); |
| 357 | if (exit_code) |
| 358 | *exit_code = local_exit_code; |
| 359 | } |
| 360 | return exited; |
| 361 | } |
| 362 |
| 363 | void Process::Exited(int exit_code) const {} |
| 364 |
| 365 | #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_AIX) |
| 366 | bool Process::IsProcessBackgrounded() const { |
| 367 | // See SetProcessBackgrounded(). |
| 368 | DCHECK(IsValid()); |
| 369 | return false; |
| 370 | } |
| 371 |
| 372 | bool Process::SetProcessBackgrounded(bool value) { |
| 373 | // Not implemented for POSIX systems other than Linux and Mac. With POSIX, if |
| 374 | // we were to lower the process priority we wouldn't be able to raise it back |
| 375 | // to its initial priority. |
| 376 | NOTIMPLEMENTED(); |
| 377 | return false; |
| 378 | } |
| 379 | #endif // !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_AIX) |
| 380 |
| 381 | int Process::GetPriority() const { |
| 382 | DCHECK(IsValid()); |
| 383 | return getpriority(PRIO_PROCESS, process_); |
| 384 | } |
| 385 |
| 386 | } // namespace base |
| 387 |