• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 The Chromium Authors
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/posix/can_lower_nice_to.h"
6 
7 #include <limits.h>
8 #include <sys/resource.h>
9 #include <sys/types.h>
10 #include <unistd.h>
11 
12 #include "build/build_config.h"
13 
14 // Not defined on AIX by default.
15 #if BUILDFLAG(IS_AIX)
16 #if defined(RLIMIT_NICE)
17 #error Assumption about OS_AIX is incorrect
18 #endif
19 #define RLIMIT_NICE 20
20 #endif
21 
22 namespace base {
23 namespace internal {
24 
CanLowerNiceTo(int nice_value)25 bool CanLowerNiceTo(int nice_value) {
26   // On a POSIX system, the nice value of a thread can be lowered 1. by the root
27   // user, 2. by a user with the CAP_SYS_NICE permission or 3. by any user if
28   // the target value is within the range allowed by RLIMIT_NICE.
29 
30   // 1. Check for root user.
31   if (geteuid() == 0)
32     return true;
33 
34   // 2. Skip checking the CAP_SYS_NICE permission because it would require
35   // libcap.so.
36 
37   // 3. Check whether the target value is within the range allowed by
38   // RLIMIT_NICE.
39   //
40   // NZERO should be defined in <limits.h> per POSIX, and should be at least 20.
41   // (NZERO-1) is the highest possible niceness value (i.e. lowest priority).
42   // Most platforms use NZERO=20.
43   //
44   // RLIMIT_NICE tells us how much we can reduce niceness (increase priority) if
45   // we start at NZERO. For example, if NZERO is 20 and the rlimit is 30, we can
46   // lower niceness anywhere within the [-10, 19] range (20 - 30 = -10).
47   //
48   // So, we are allowed to reduce niceness to a minimum of NZERO - rlimit:
49   struct rlimit rlim;
50   if (getrlimit(RLIMIT_NICE, &rlim) != 0)
51     return false;
52   const int lowest_nice_allowed = NZERO - static_cast<int>(rlim.rlim_cur);
53 
54   // And lowering niceness to |nice_value| is allowed if it is greater than or
55   // equal to the limit:
56   return nice_value >= lowest_nice_allowed;
57 }
58 
59 }  // namespace internal
60 }  // namespace base
61