1 #include <arpa/inet.h>
2 #include <iostream>
3 #include <chrono>
4 #include <cutils/sockets.h>
5 #include <hardware/gralloc.h>
6 #include <vector>
7 #include <tuple>
8 #include <algorithm>
9 #include <tuple>
10 #include <numeric>
11 #include <fcntl.h>
12 #include <string>
13 #include <fstream>
14 #include <sys/stat.h>
15 #include <sys/wait.h>
16 #include <unistd.h>
17
18 //#define TRACE_CHILD_LIFETIME
19
20 #ifdef TRACE_CHILD_LIFETIME
21 #define ATRACE_TAG ATRACE_TAG_ALWAYS
22 #include <utils/Trace.h>
23 #endif // TRACE_CHILD_LIFETIME
24
25 using namespace std;
26
27 #define ASSERT_TRUE(cond) \
28 do { \
29 if (!(cond)) {\
30 cerr << __func__ << "( " << getpid() << "):" << __LINE__ << " condition:" << #cond << " failed\n" << endl; \
31 exit(EXIT_FAILURE); \
32 } \
33 } while (0)
34
35 class Pipe {
36 int m_readFd;
37 int m_writeFd;
38 Pipe(const Pipe &) = delete;
39 Pipe& operator=(const Pipe &) = delete;
40 Pipe& operator=(const Pipe &&) = delete;
41 public:
Pipe(int readFd,int writeFd)42 Pipe(int readFd, int writeFd) : m_readFd{readFd}, m_writeFd{writeFd} {
43 fcntl(m_readFd, F_SETFD, FD_CLOEXEC);
44 fcntl(m_writeFd, F_SETFD, FD_CLOEXEC);
45 }
Pipe(Pipe && rval)46 Pipe(Pipe&& rval) noexcept {
47 m_readFd = rval.m_readFd;
48 m_writeFd = rval.m_writeFd;
49 rval.m_readFd = 0;
50 rval.m_writeFd = 0;
51 }
~Pipe()52 ~Pipe() {
53 if (m_readFd)
54 close(m_readFd);
55 if (m_writeFd)
56 close(m_writeFd);
57 }
preserveOverFork(bool preserve)58 void preserveOverFork(bool preserve) {
59 if (preserve) {
60 fcntl(m_readFd, F_SETFD, 0);
61 fcntl(m_writeFd, F_SETFD,0);
62 } else {
63 fcntl(m_readFd, F_SETFD, FD_CLOEXEC);
64 fcntl(m_writeFd, F_SETFD, FD_CLOEXEC);
65 }
66 }
getReadFd()67 int getReadFd() {
68 return m_readFd;
69 }
getWriteFd()70 int getWriteFd() {
71 return m_writeFd;
72 }
signal()73 void signal() {
74 bool val = true;
75 int error = write(m_writeFd, &val, sizeof(val));
76 ASSERT_TRUE(error == sizeof(val));
77 };
wait()78 void wait() {
79 bool val = false;
80 int error = read(m_readFd, &val, sizeof(val));
81 ASSERT_TRUE(error == sizeof(val));
82 }
wait_ret_error()83 bool wait_ret_error() {
84 bool val = false;
85 int error = read(m_readFd, &val, sizeof(val));
86 return (error != 1);
87 }
send(const T & v)88 template <typename T> void send(const T& v) {
89 int error = write(m_writeFd, &v, sizeof(T));
90 ASSERT_TRUE(error >= 0);
91 }
recv(T & v)92 template <typename T> void recv(T& v) {
93 int error = read(m_readFd, &v, sizeof(T));
94 ASSERT_TRUE(error >= 0);
95 }
makePipeFromFds(int readFd,int writeFd)96 static Pipe makePipeFromFds(int readFd, int writeFd) {
97 return Pipe(readFd, writeFd);
98 }
createPipePair()99 static tuple<Pipe, Pipe> createPipePair() {
100 int a[2];
101 int b[2];
102
103 int error1 = pipe(a);
104 int error2 = pipe(b);
105 ASSERT_TRUE(error1 >= 0);
106 ASSERT_TRUE(error2 >= 0);
107
108 return make_tuple(Pipe(a[0], b[1]), Pipe(b[0], a[1]));
109 }
110 };
111
createProcess(Pipe pipe,const char * exName,const char * arg,bool use_memcg)112 pid_t createProcess(Pipe pipe, const char *exName,
113 const char *arg, bool use_memcg)
114 {
115 pipe.preserveOverFork(true);
116 pid_t pid = fork();
117 // child proc
118 if (pid == 0) {
119 char readFdStr[16];
120 char writeFdStr[16];
121 snprintf(readFdStr, sizeof(readFdStr), "%d", pipe.getReadFd());
122 snprintf(writeFdStr, sizeof(writeFdStr), "%d", pipe.getWriteFd());
123 char exPath[PATH_MAX];
124 ssize_t exPathLen = readlink("/proc/self/exe", exPath, sizeof(exPath));
125 bool isExPathAvailable =
126 exPathLen != -1 && exPathLen < static_cast<ssize_t>(sizeof(exPath));
127 if (isExPathAvailable) {
128 exPath[exPathLen] = '\0';
129 }
130 execl(isExPathAvailable ? exPath : exName, exName, "--worker", arg, readFdStr, writeFdStr,
131 use_memcg ? "1" : "0", nullptr);
132 ASSERT_TRUE(0);
133 }
134 // parent process
135 else if (pid > 0) {
136 pipe.preserveOverFork(false);
137 }
138 else {
139 ASSERT_TRUE(0);
140 }
141 return pid;
142 }
143
144
write_oomadj_to_lmkd(int oomadj)145 static void write_oomadj_to_lmkd(int oomadj) {
146 // Connect to lmkd and store our oom_adj
147 int lmk_procprio_cmd[4];
148 int sock;
149 int tries = 10;
150 while ((sock = socket_local_client("lmkd",
151 ANDROID_SOCKET_NAMESPACE_RESERVED,
152 SOCK_SEQPACKET)) < 0) {
153 usleep(100000);
154 if (tries-- < 0) break;
155 }
156 if (sock < 0) {
157 cout << "Failed to connect to lmkd, errno " << errno << endl;
158 exit(1);
159 }
160 lmk_procprio_cmd[0] = htonl(1);
161 lmk_procprio_cmd[1] = htonl(getpid());
162 lmk_procprio_cmd[2] = htonl(getuid());
163 lmk_procprio_cmd[3] = htonl(oomadj);
164
165 int written = write(sock, lmk_procprio_cmd, sizeof(lmk_procprio_cmd));
166 cout << "Wrote " << written << " bytes to lmkd control socket." << endl;
167 }
168
create_memcg()169 static void create_memcg() {
170 char buf[256];
171 uid_t uid = getuid();
172 pid_t pid = getpid();
173
174 snprintf(buf, sizeof(buf), "/dev/memcg/apps/uid_%u", uid);
175 int tasks = mkdir(buf, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
176 if (tasks < 0 && errno != EEXIST) {
177 cerr << "Failed to create memory cgroup under " << buf << endl;
178 return;
179 }
180
181 snprintf(buf, sizeof(buf), "/dev/memcg/apps/uid_%u/pid_%u", uid, pid);
182 tasks = mkdir(buf, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
183 if (tasks < 0) {
184 cerr << "Failed to create memory cgroup under " << buf << endl;
185 return;
186 }
187
188 snprintf(buf, sizeof(buf), "/dev/memcg/apps/uid_%u/pid_%u/tasks", uid, pid);
189 tasks = open(buf, O_WRONLY);
190 if (tasks < 0) {
191 cerr << "Unable to add process to memory cgroup" << endl;
192 return;
193 }
194 snprintf(buf, sizeof(buf), "%u", pid);
195 write(tasks, buf, strlen(buf));
196 close(tasks);
197 }
198
usage()199 void usage() {
200 cout << "Application allocates memory until it's killed." << endl
201 << "It starts at max oom_score_adj and gradually "
202 << "decreases it to 0." << endl
203 << "Usage: alloc-stress [-g | --cgroup]" << endl
204 << "\t-g | --cgroup\tcreates memory cgroup for the process" << endl;
205 }
206
207 size_t s = 4 * (1 << 20);
208 void *gptr;
main(int argc,char * argv[])209 int main(int argc, char *argv[])
210 {
211 bool use_memcg = false;
212
213 if ((argc > 1) && (std::string(argv[1]) == "--worker")) {
214 if (std::string(argv[5]) == "1") {
215 create_memcg();
216 }
217
218 write_oomadj_to_lmkd(atoi(argv[2]));
219 Pipe p{atoi(argv[3]), atoi(argv[4])};
220
221 long long allocCount = 0;
222 while (1) {
223 p.wait();
224 char *ptr = (char*)malloc(s);
225 memset(ptr, (int)allocCount >> 10, s);
226 for (int i = 0; i < s; i+= 4096) {
227 *((long long*)&ptr[i]) = allocCount + i;
228 }
229 usleep(10 * 1000);
230 gptr = ptr;
231 //cout << "total alloc: " << allocCount / (1<<20)<< " adj: " << argv[2]<< endl;;
232 //cout << "ptr: " << (long long)(void*)ptr << endl;;
233 p.signal();
234 allocCount += s;
235 }
236 } else {
237 if (argc == 2) {
238 if (std::string(argv[1]) == "--help" ||
239 std::string(argv[1]) == "-h") {
240 usage();
241 return 0;
242 }
243
244 if (std::string(argv[1]) == "--cgroup" ||
245 std::string(argv[1]) == "-g") {
246 use_memcg = true;
247 }
248 }
249
250 cout << "Memory cgroups are "
251 << (use_memcg ? "used" : "not used") << endl;
252
253 write_oomadj_to_lmkd(-1000);
254 for (int i = 1000; i >= 0; i -= 100) {
255 auto pipes = Pipe::createPipePair();
256 char arg[16];
257 pid_t ch_pid;
258 snprintf(arg, sizeof(arg), "%d", i);
259 ch_pid = createProcess(std::move(std::get<1>(pipes)),
260 argv[0], arg, use_memcg);
261 Pipe &p = std::get<0>(pipes);
262
263 size_t t = 0;
264
265 #ifdef TRACE_CHILD_LIFETIME
266 char trace_str[64];
267 snprintf(trace_str, sizeof(trace_str), "alloc-stress, adj=%d, pid=%u", i, ch_pid);
268 ATRACE_INT(trace_str, i);
269 #endif
270 while (1) {
271 //;cout << getpid() << ":" << "parent signal" << endl;
272 p.signal();
273 if (p.wait_ret_error()) {
274 int status;
275 waitpid(0, &status, 0);
276 break;
277 }
278 t += s;
279 }
280 cout << "pid: " << ch_pid << " adj: " << i << " sz: " << t / (1 << 20) << endl;
281 #ifdef TRACE_CHILD_LIFETIME
282 ATRACE_INT(trace_str, 0);
283 #endif
284 }
285 }
286 return 0;
287 }
288