• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 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 // The following is the C version of code from base/process_utils_linux.cc.
6 // We shouldn't link against C++ code in a setuid binary.
7 
8 #define _GNU_SOURCE  // needed for O_DIRECTORY
9 
10 #include "process_util.h"
11 
12 #include <fcntl.h>
13 #include <inttypes.h>
14 #include <limits.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/stat.h>
19 #include <sys/types.h>
20 #include <unistd.h>
21 
22 // Ranges for the current (oom_score_adj) and previous (oom_adj)
23 // flavors of OOM score.
24 static const int kMaxOomScore = 1000;
25 static const int kMaxOldOomScore = 15;
26 
27 // NOTE: This is not the only version of this function in the source:
28 // the base library (in process_util_linux.cc) also has its own C++ version.
AdjustOOMScore(pid_t process,int score)29 bool AdjustOOMScore(pid_t process, int score) {
30   if (score < 0 || score > kMaxOomScore)
31     return false;
32 
33   char oom_adj[27];  // "/proc/" + log_10(2**64) + "\0"
34                      //    6     +       20     +     1         = 27
35   snprintf(oom_adj, sizeof(oom_adj), "/proc/%" PRIdMAX, (intmax_t)process);
36 
37   const int dirfd = open(oom_adj, O_RDONLY | O_DIRECTORY);
38   if (dirfd < 0)
39     return false;
40 
41   struct stat statbuf;
42   if (fstat(dirfd, &statbuf) < 0) {
43     close(dirfd);
44     return false;
45   }
46   if (getuid() != statbuf.st_uid) {
47     close(dirfd);
48     return false;
49   }
50 
51   int fd = openat(dirfd, "oom_score_adj", O_WRONLY);
52   if (fd < 0) {
53     // We failed to open oom_score_adj, so let's try for the older
54     // oom_adj file instead.
55     fd = openat(dirfd, "oom_adj", O_WRONLY);
56     if (fd < 0) {
57       // Nope, that doesn't work either.
58       return false;
59     } else {
60       // If we're using the old oom_adj file, the allowed range is now
61       // [0, kMaxOldOomScore], so we scale the score.  This may result in some
62       // aliasing of values, of course.
63       score = score * kMaxOldOomScore / kMaxOomScore;
64     }
65   }
66   close(dirfd);
67 
68   char buf[11];  // 0 <= |score| <= kMaxOomScore; using log_10(2**32) + 1 size
69   snprintf(buf, sizeof(buf), "%d", score);
70   size_t len = strlen(buf);
71 
72   ssize_t bytes_written = write(fd, buf, len);
73   close(fd);
74   return (bytes_written == len);
75 }
76