ipc/chromium/src/base/process_util_posix.cc

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 //* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
michael@0 2 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
michael@0 3 // Use of this source code is governed by a BSD-style license that can be
michael@0 4 // found in the LICENSE file.
michael@0 5
michael@0 6 #include <dirent.h>
michael@0 7 #include <errno.h>
michael@0 8 #include <fcntl.h>
michael@0 9 #include <signal.h>
michael@0 10 #include <stdlib.h>
michael@0 11 #include <sys/resource.h>
michael@0 12 #include <sys/time.h>
michael@0 13 #include <sys/types.h>
michael@0 14 #include <sys/wait.h>
michael@0 15 #include <unistd.h>
michael@0 16
michael@0 17 #include <limits>
michael@0 18 #include <set>
michael@0 19
michael@0 20 #include "base/basictypes.h"
michael@0 21 #include "base/eintr_wrapper.h"
michael@0 22 #include "base/logging.h"
michael@0 23 #include "base/platform_thread.h"
michael@0 24 #include "base/process_util.h"
michael@0 25 #include "base/scoped_ptr.h"
michael@0 26 #include "base/sys_info.h"
michael@0 27 #include "base/time.h"
michael@0 28 #include "base/waitable_event.h"
michael@0 29 #include "base/dir_reader_posix.h"
michael@0 30
michael@0 31 const int kMicrosecondsPerSecond = 1000000;
michael@0 32
michael@0 33 namespace base {
michael@0 34
michael@0 35 ProcessId GetCurrentProcId() {
michael@0 36 return getpid();
michael@0 37 }
michael@0 38
michael@0 39 ProcessHandle GetCurrentProcessHandle() {
michael@0 40 return GetCurrentProcId();
michael@0 41 }
michael@0 42
michael@0 43 bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle) {
michael@0 44 // On Posix platforms, process handles are the same as PIDs, so we
michael@0 45 // don't need to do anything.
michael@0 46 *handle = pid;
michael@0 47 return true;
michael@0 48 }
michael@0 49
michael@0 50 bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle) {
michael@0 51 // On POSIX permissions are checked for each operation on process,
michael@0 52 // not when opening a "handle".
michael@0 53 return OpenProcessHandle(pid, handle);
michael@0 54 }
michael@0 55
michael@0 56 void CloseProcessHandle(ProcessHandle process) {
michael@0 57 // See OpenProcessHandle, nothing to do.
michael@0 58 return;
michael@0 59 }
michael@0 60
michael@0 61 ProcessId GetProcId(ProcessHandle process) {
michael@0 62 return process;
michael@0 63 }
michael@0 64
michael@0 65 // Attempts to kill the process identified by the given process
michael@0 66 // entry structure. Ignores specified exit_code; posix can't force that.
michael@0 67 // Returns true if this is successful, false otherwise.
michael@0 68 bool KillProcess(ProcessHandle process_id, int exit_code, bool wait) {
michael@0 69 bool result = kill(process_id, SIGTERM) == 0;
michael@0 70
michael@0 71 if (result && wait) {
michael@0 72 int tries = 60;
michael@0 73 // The process may not end immediately due to pending I/O
michael@0 74 while (tries-- > 0) {
michael@0 75 int pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
michael@0 76 if (pid == process_id)
michael@0 77 break;
michael@0 78
michael@0 79 sleep(1);
michael@0 80 }
michael@0 81
michael@0 82 result = kill(process_id, SIGKILL) == 0;
michael@0 83 }
michael@0 84
michael@0 85 if (!result)
michael@0 86 DLOG(ERROR) << "Unable to terminate process.";
michael@0 87
michael@0 88 return result;
michael@0 89 }
michael@0 90
michael@0 91 #ifdef ANDROID
michael@0 92 typedef unsigned long int rlim_t;
michael@0 93 #endif
michael@0 94
michael@0 95 // A class to handle auto-closing of DIR*'s.
michael@0 96 class ScopedDIRClose {
michael@0 97 public:
michael@0 98 inline void operator()(DIR* x) const {
michael@0 99 if (x) {
michael@0 100 closedir(x);
michael@0 101 }
michael@0 102 }
michael@0 103 };
michael@0 104 typedef scoped_ptr_malloc<DIR, ScopedDIRClose> ScopedDIR;
michael@0 105
michael@0 106
michael@0 107 void CloseSuperfluousFds(const base::InjectiveMultimap& saved_mapping) {
michael@0 108 // DANGER: no calls to malloc are allowed from now on:
michael@0 109 // http://crbug.com/36678
michael@0 110 #if defined(ANDROID)
michael@0 111 static const rlim_t kSystemDefaultMaxFds = 1024;
michael@0 112 static const char kFDDir[] = "/proc/self/fd";
michael@0 113 #elif defined(OS_LINUX)
michael@0 114 static const rlim_t kSystemDefaultMaxFds = 8192;
michael@0 115 static const char kFDDir[] = "/proc/self/fd";
michael@0 116 #elif defined(OS_MACOSX)
michael@0 117 static const rlim_t kSystemDefaultMaxFds = 256;
michael@0 118 static const char kFDDir[] = "/dev/fd";
michael@0 119 #elif defined(OS_BSD)
michael@0 120 // the getrlimit below should never fail, so whatever ..
michael@0 121 static const rlim_t kSystemDefaultMaxFds = 1024;
michael@0 122 // at least /dev/fd will exist
michael@0 123 static const char kFDDir[] = "/dev/fd";
michael@0 124 #endif
michael@0 125
michael@0 126 // Get the maximum number of FDs possible.
michael@0 127 struct rlimit nofile;
michael@0 128 rlim_t max_fds;
michael@0 129 if (getrlimit(RLIMIT_NOFILE, &nofile)) {
michael@0 130 // getrlimit failed. Take a best guess.
michael@0 131 max_fds = kSystemDefaultMaxFds;
michael@0 132 DLOG(ERROR) << "getrlimit(RLIMIT_NOFILE) failed: " << errno;
michael@0 133 } else {
michael@0 134 max_fds = nofile.rlim_cur;
michael@0 135 }
michael@0 136
michael@0 137 if (max_fds > INT_MAX)
michael@0 138 max_fds = INT_MAX;
michael@0 139
michael@0 140 DirReaderPosix fd_dir(kFDDir);
michael@0 141
michael@0 142 if (!fd_dir.IsValid()) {
michael@0 143 // Fallback case: Try every possible fd.
michael@0 144 for (rlim_t i = 0; i < max_fds; ++i) {
michael@0 145 const int fd = static_cast<int>(i);
michael@0 146 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
michael@0 147 continue;
michael@0 148 InjectiveMultimap::const_iterator j;
michael@0 149 for (j = saved_mapping.begin(); j != saved_mapping.end(); j++) {
michael@0 150 if (fd == j->dest)
michael@0 151 break;
michael@0 152 }
michael@0 153 if (j != saved_mapping.end())
michael@0 154 continue;
michael@0 155
michael@0 156 // Since we're just trying to close anything we can find,
michael@0 157 // ignore any error return values of close().
michael@0 158 HANDLE_EINTR(close(fd));
michael@0 159 }
michael@0 160 return;
michael@0 161 }
michael@0 162
michael@0 163 const int dir_fd = fd_dir.fd();
michael@0 164
michael@0 165 for ( ; fd_dir.Next(); ) {
michael@0 166 // Skip . and .. entries.
michael@0 167 if (fd_dir.name()[0] == '.')
michael@0 168 continue;
michael@0 169
michael@0 170 char *endptr;
michael@0 171 errno = 0;
michael@0 172 const long int fd = strtol(fd_dir.name(), &endptr, 10);
michael@0 173 if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno)
michael@0 174 continue;
michael@0 175 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
michael@0 176 continue;
michael@0 177 InjectiveMultimap::const_iterator i;
michael@0 178 for (i = saved_mapping.begin(); i != saved_mapping.end(); i++) {
michael@0 179 if (fd == i->dest)
michael@0 180 break;
michael@0 181 }
michael@0 182 if (i != saved_mapping.end())
michael@0 183 continue;
michael@0 184 if (fd == dir_fd)
michael@0 185 continue;
michael@0 186
michael@0 187 // When running under Valgrind, Valgrind opens several FDs for its
michael@0 188 // own use and will complain if we try to close them. All of
michael@0 189 // these FDs are >= |max_fds|, so we can check against that here
michael@0 190 // before closing. See https://bugs.kde.org/show_bug.cgi?id=191758
michael@0 191 if (fd < static_cast<int>(max_fds)) {
michael@0 192 int ret = HANDLE_EINTR(close(fd));
michael@0 193 if (ret != 0) {
michael@0 194 DLOG(ERROR) << "Problem closing fd";
michael@0 195 }
michael@0 196 }
michael@0 197 }
michael@0 198 }
michael@0 199
michael@0 200 // Sets all file descriptors to close on exec except for stdin, stdout
michael@0 201 // and stderr.
michael@0 202 // TODO(agl): Remove this function. It's fundamentally broken for multithreaded
michael@0 203 // apps.
michael@0 204 void SetAllFDsToCloseOnExec() {
michael@0 205 #if defined(OS_LINUX)
michael@0 206 const char fd_dir[] = "/proc/self/fd";
michael@0 207 #elif defined(OS_MACOSX) || defined(OS_BSD)
michael@0 208 const char fd_dir[] = "/dev/fd";
michael@0 209 #endif
michael@0 210 ScopedDIR dir_closer(opendir(fd_dir));
michael@0 211 DIR *dir = dir_closer.get();
michael@0 212 if (NULL == dir) {
michael@0 213 DLOG(ERROR) << "Unable to open " << fd_dir;
michael@0 214 return;
michael@0 215 }
michael@0 216
michael@0 217 struct dirent *ent;
michael@0 218 while ((ent = readdir(dir))) {
michael@0 219 // Skip . and .. entries.
michael@0 220 if (ent->d_name[0] == '.')
michael@0 221 continue;
michael@0 222 int i = atoi(ent->d_name);
michael@0 223 // We don't close stdin, stdout or stderr.
michael@0 224 if (i <= STDERR_FILENO)
michael@0 225 continue;
michael@0 226
michael@0 227 int flags = fcntl(i, F_GETFD);
michael@0 228 if ((flags == -1) || (fcntl(i, F_SETFD, flags | FD_CLOEXEC) == -1)) {
michael@0 229 DLOG(ERROR) << "fcntl failure.";
michael@0 230 }
michael@0 231 }
michael@0 232 }
michael@0 233
michael@0 234 ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process),
michael@0 235 last_time_(0),
michael@0 236 last_system_time_(0) {
michael@0 237 processor_count_ = base::SysInfo::NumberOfProcessors();
michael@0 238 }
michael@0 239
michael@0 240 // static
michael@0 241 ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
michael@0 242 return new ProcessMetrics(process);
michael@0 243 }
michael@0 244
michael@0 245 ProcessMetrics::~ProcessMetrics() { }
michael@0 246
michael@0 247 bool DidProcessCrash(bool* child_exited, ProcessHandle handle) {
michael@0 248 int status;
michael@0 249 const int result = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
michael@0 250 if (result == -1) {
michael@0 251 // This shouldn't happen, but sometimes it does. The error is
michael@0 252 // probably ECHILD and the reason is probably that a pid was
michael@0 253 // waited on again after a previous wait reclaimed its zombie.
michael@0 254 // (It could also occur if the process isn't a direct child, but
michael@0 255 // don't do that.) This is bad, because it risks interfering with
michael@0 256 // an unrelated child process if the pid is reused.
michael@0 257 //
michael@0 258 // So, lacking reliable information, we indicate that the process
michael@0 259 // is dead, in the hope that the caller will give up and stop
michael@0 260 // calling us. See also bug 943174 and bug 933680.
michael@0 261 CHROMIUM_LOG(ERROR) << "waitpid failed pid:" << handle << " errno:" << errno;
michael@0 262 if (child_exited)
michael@0 263 *child_exited = true;
michael@0 264 return false;
michael@0 265 } else if (result == 0) {
michael@0 266 // the child hasn't exited yet.
michael@0 267 if (child_exited)
michael@0 268 *child_exited = false;
michael@0 269 return false;
michael@0 270 }
michael@0 271
michael@0 272 if (child_exited)
michael@0 273 *child_exited = true;
michael@0 274
michael@0 275 if (WIFSIGNALED(status)) {
michael@0 276 switch(WTERMSIG(status)) {
michael@0 277 case SIGSYS:
michael@0 278 case SIGSEGV:
michael@0 279 case SIGILL:
michael@0 280 case SIGABRT:
michael@0 281 case SIGFPE:
michael@0 282 return true;
michael@0 283 default:
michael@0 284 return false;
michael@0 285 }
michael@0 286 }
michael@0 287
michael@0 288 if (WIFEXITED(status))
michael@0 289 return WEXITSTATUS(status) != 0;
michael@0 290
michael@0 291 return false;
michael@0 292 }
michael@0 293
michael@0 294 namespace {
michael@0 295
michael@0 296 int64_t TimeValToMicroseconds(const struct timeval& tv) {
michael@0 297 return tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec;
michael@0 298 }
michael@0 299
michael@0 300 }
michael@0 301
michael@0 302 int ProcessMetrics::GetCPUUsage() {
michael@0 303 struct timeval now;
michael@0 304 struct rusage usage;
michael@0 305
michael@0 306 int retval = gettimeofday(&now, NULL);
michael@0 307 if (retval)
michael@0 308 return 0;
michael@0 309 retval = getrusage(RUSAGE_SELF, &usage);
michael@0 310 if (retval)
michael@0 311 return 0;
michael@0 312
michael@0 313 int64_t system_time = (TimeValToMicroseconds(usage.ru_stime) +
michael@0 314 TimeValToMicroseconds(usage.ru_utime)) /
michael@0 315 processor_count_;
michael@0 316 int64_t time = TimeValToMicroseconds(now);
michael@0 317
michael@0 318 if ((last_system_time_ == 0) || (last_time_ == 0)) {
michael@0 319 // First call, just set the last values.
michael@0 320 last_system_time_ = system_time;
michael@0 321 last_time_ = time;
michael@0 322 return 0;
michael@0 323 }
michael@0 324
michael@0 325 int64_t system_time_delta = system_time - last_system_time_;
michael@0 326 int64_t time_delta = time - last_time_;
michael@0 327 DCHECK(time_delta != 0);
michael@0 328 if (time_delta == 0)
michael@0 329 return 0;
michael@0 330
michael@0 331 // We add time_delta / 2 so the result is rounded.
michael@0 332 int cpu = static_cast<int>((system_time_delta * 100 + time_delta / 2) /
michael@0 333 time_delta);
michael@0 334
michael@0 335 last_system_time_ = system_time;
michael@0 336 last_time_ = time;
michael@0 337
michael@0 338 return cpu;
michael@0 339 }
michael@0 340
michael@0 341 } // namespace base

mercurial