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.
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.
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).
13 #include "sandbox/linux/suid/process_util.h"
22 #include <sys/types.h>
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;
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.
32 bool AdjustOOMScore(pid_t process
, int score
) {
33 if (score
< 0 || score
> kMaxOomScore
)
36 char oom_adj
[27]; // "/proc/" + log_10(2**64) + "\0"
38 snprintf(oom_adj
, sizeof(oom_adj
), "/proc/%" PRIdMAX
, (intmax_t)process
);
40 const int dirfd
= open(oom_adj
, O_RDONLY
| O_DIRECTORY
);
45 if (fstat(dirfd
, &statbuf
) < 0) {
49 if (getuid() != statbuf
.st_uid
) {
54 int fd
= openat(dirfd
, "oom_score_adj", O_WRONLY
);
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
);
60 // Nope, that doesn't work either.
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
;
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
);
75 ssize_t bytes_written
= write(fd
, buf
, len
);
77 return (bytes_written
== (ssize_t
)len
);