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