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
17namespace base {
18
19int64_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
26ProcessMetrics::~ProcessMetrics() { }
27
28#if defined(OS_LINUX)
29static const rlim_t kSystemDefaultMaxFds = 8192;
30#elif defined(OS_MACOSX)
31static const rlim_t kSystemDefaultMaxFds = 256;
32#elif defined(OS_SOLARIS)
33static const rlim_t kSystemDefaultMaxFds = 8192;
34#elif defined(OS_FREEBSD)
35static const rlim_t kSystemDefaultMaxFds = 8192;
36#elif defined(OS_OPENBSD)
37static const rlim_t kSystemDefaultMaxFds = 256;
38#elif defined(OS_ANDROID)
39static const rlim_t kSystemDefaultMaxFds = 1024;
40#endif
41
42size_t GetMaxFds() {
43  rlim_t max_fds;
44  struct rlimit nofile;
45  if (getrlimit(RLIMIT_NOFILE, &nofile)) {
46    // getrlimit failed. Take a best guess.
47    max_fds = kSystemDefaultMaxFds;
48    RAW_LOG(ERROR, "getrlimit(RLIMIT_NOFILE) failed");
49  } else {
50    max_fds = nofile.rlim_cur;
51  }
52
53  if (max_fds > INT_MAX)
54    max_fds = INT_MAX;
55
56  return static_cast<size_t>(max_fds);
57}
58
59
60void SetFdLimit(unsigned int max_descriptors) {
61  struct rlimit limits;
62  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
63    unsigned int new_limit = max_descriptors;
64    if (limits.rlim_max > 0 && limits.rlim_max < max_descriptors) {
65      new_limit = limits.rlim_max;
66    }
67    limits.rlim_cur = new_limit;
68    if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
69      PLOG(INFO) << "Failed to set file descriptor limit";
70    }
71  } else {
72    PLOG(INFO) << "Failed to get file descriptor limit";
73  }
74}
75
76size_t GetPageSize() {
77  return getpagesize();
78}
79
80}  // namespace base
81