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