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