• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2013 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_metrics.h"
6 
7 #include <limits.h>
8 #include <stddef.h>
9 #include <stdint.h>
10 #include <sys/resource.h>
11 #include <sys/time.h>
12 #include <unistd.h>
13 
14 #include "base/logging.h"
15 #include "build/build_config.h"
16 
17 namespace base {
18 
TimeValToMicroseconds(const struct timeval & tv)19 int64_t TimeValToMicroseconds(const struct timeval& tv) {
20   int64_t ret = tv.tv_sec;  // Avoid (int * int) integer overflow.
21   ret *= Time::kMicrosecondsPerSecond;
22   ret += tv.tv_usec;
23   return ret;
24 }
25 
~ProcessMetrics()26 ProcessMetrics::~ProcessMetrics() { }
27 
28 #if defined(OS_LINUX)
29 static const rlim_t kSystemDefaultMaxFds = 8192;
30 #elif defined(OS_MACOSX)
31 static const rlim_t kSystemDefaultMaxFds = 256;
32 #elif defined(OS_SOLARIS)
33 static const rlim_t kSystemDefaultMaxFds = 8192;
34 #elif defined(OS_FREEBSD)
35 static const rlim_t kSystemDefaultMaxFds = 8192;
36 #elif defined(OS_NETBSD)
37 static const rlim_t kSystemDefaultMaxFds = 1024;
38 #elif defined(OS_OPENBSD)
39 static const rlim_t kSystemDefaultMaxFds = 256;
40 #elif defined(OS_ANDROID)
41 static const rlim_t kSystemDefaultMaxFds = 1024;
42 #endif
43 
GetMaxFds()44 size_t GetMaxFds() {
45   rlim_t max_fds;
46   struct rlimit nofile;
47   if (getrlimit(RLIMIT_NOFILE, &nofile)) {
48     // getrlimit failed. Take a best guess.
49     max_fds = kSystemDefaultMaxFds;
50     RAW_LOG(ERROR, "getrlimit(RLIMIT_NOFILE) failed");
51   } else {
52     max_fds = nofile.rlim_cur;
53   }
54 
55   if (max_fds > INT_MAX)
56     max_fds = INT_MAX;
57 
58   return static_cast<size_t>(max_fds);
59 }
60 
61 
SetFdLimit(unsigned int max_descriptors)62 void SetFdLimit(unsigned int max_descriptors) {
63   struct rlimit limits;
64   if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
65     unsigned int new_limit = max_descriptors;
66     if (limits.rlim_max > 0 && limits.rlim_max < max_descriptors) {
67       new_limit = limits.rlim_max;
68     }
69     limits.rlim_cur = new_limit;
70     if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
71       PLOG(INFO) << "Failed to set file descriptor limit";
72     }
73   } else {
74     PLOG(INFO) << "Failed to get file descriptor limit";
75   }
76 }
77 
GetPageSize()78 size_t GetPageSize() {
79   return getpagesize();
80 }
81 
82 }  // namespace base
83