• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <sstream>
18 #include <stdio.h>
19 #include <string.h>
20 #include <string>
21 #include <sys/mman.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 
25 #include <android-base/file.h>
26 #include <android-base/logging.h>
27 #include <android-base/properties.h>
28 #include <android-base/stringprintf.h>
29 #include <android-base/strings.h>
30 #include <cutils/properties.h>
31 #include <gtest/gtest.h>
32 #include <lmkd.h>
33 #include <liblmkd_utils.h>
34 #include <log/log_properties.h>
35 #include <private/android_filesystem_config.h>
36 
37 using namespace android::base;
38 
39 #define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
40 #define LMKDTEST_RESPAWN_FLAG "LMKDTEST_RESPAWN"
41 
42 #define LMKD_LOGCAT_MARKER "lowmemorykiller"
43 #define LMKD_KILL_MARKER_TEMPLATE LMKD_LOGCAT_MARKER ": Kill '%s'"
44 #define OOM_MARKER "Out of memory"
45 #define OOM_KILL_MARKER "Killed process"
46 #define MIN_LOG_SIZE 100
47 
48 #define ONE_MB (1 << 20)
49 
50 /* Test constant parameters */
51 #define OOM_ADJ_MAX 1000
52 #define OOM_ADJ_MIN 0
53 #define OOM_ADJ_STEP 100
54 #define STEP_COUNT ((OOM_ADJ_MAX - OOM_ADJ_MIN) / OOM_ADJ_STEP + 1)
55 
56 #define ALLOC_STEP (ONE_MB)
57 #define ALLOC_DELAY 1000
58 
59 /* Utility functions */
readCommand(const std::string & command)60 std::string readCommand(const std::string& command) {
61     FILE* fp = popen(command.c_str(), "r");
62     std::string content;
63     ReadFdToString(fileno(fp), &content);
64     pclose(fp);
65     return content;
66 }
67 
readLogcat(const std::string & marker)68 std::string readLogcat(const std::string& marker) {
69     std::string content = readCommand("logcat -d -b all");
70     size_t pos = content.find(marker);
71     if (pos == std::string::npos) return "";
72     content.erase(0, pos);
73     return content;
74 }
75 
writeFile(const std::string & file,const std::string & string)76 bool writeFile(const std::string& file, const std::string& string) {
77     if (getuid() == static_cast<unsigned>(AID_ROOT)) {
78         return WriteStringToFile(string, file);
79     }
80     return string == readCommand(
81         "echo -n '" + string + "' | su root tee " + file + " 2>&1");
82 }
83 
writeKmsg(const std::string & marker)84 bool writeKmsg(const std::string& marker) {
85     return writeFile("/dev/kmsg", marker);
86 }
87 
getTextAround(const std::string & text,size_t pos,size_t lines_before,size_t lines_after)88 std::string getTextAround(const std::string& text, size_t pos,
89                           size_t lines_before, size_t lines_after) {
90     size_t start_pos = pos;
91 
92     // find start position
93     // move up lines_before number of lines
94     while (lines_before > 0 &&
95            (start_pos = text.rfind('\n', start_pos)) != std::string::npos) {
96         lines_before--;
97     }
98     // move to the beginning of the line
99     start_pos = text.rfind('\n', start_pos);
100     start_pos = (start_pos == std::string::npos) ? 0 : start_pos + 1;
101 
102     // find end position
103     // move down lines_after number of lines
104     while (lines_after > 0 &&
105            (pos = text.find('\n', pos)) != std::string::npos) {
106         pos++;
107         lines_after--;
108     }
109     return text.substr(start_pos, (pos == std::string::npos) ?
110                        std::string::npos : pos - start_pos);
111 }
112 
getTaskName(std::string & name)113 bool getTaskName(std::string &name) {
114     std::string cmdline;
115 
116     if (!ReadFileToString("/proc/self/cmdline", &cmdline)) {
117         GTEST_LOG_(INFO) << "Failed to read /proc/self/cmdline";
118         return false;
119     }
120     //filter out paramters as cmdline use null bytes to separate
121     name = cmdline.c_str();
122     return true;
123 }
124 
125 /* Child synchronization primitives */
126 #define STATE_INIT 0
127 #define STATE_CHILD_READY 1
128 #define STATE_PARENT_READY 2
129 
130 struct state_sync {
131     pthread_mutex_t mutex;
132     pthread_cond_t condition;
133     int state;
134 };
135 
init_state_sync_obj()136 struct state_sync * init_state_sync_obj() {
137     struct state_sync *ssync;
138 
139     ssync = (struct state_sync*)mmap(NULL, sizeof(struct state_sync),
140                 PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
141     if (ssync == MAP_FAILED) {
142         return NULL;
143     }
144 
145     pthread_mutexattr_t mattr;
146     pthread_mutexattr_init(&mattr);
147     pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
148     pthread_mutex_init(&ssync->mutex, &mattr);
149 
150     pthread_condattr_t cattr;
151     pthread_condattr_init(&cattr);
152     pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED);
153     pthread_cond_init(&ssync->condition, &cattr);
154 
155     ssync->state = STATE_INIT;
156     return ssync;
157 }
158 
destroy_state_sync_obj(struct state_sync * ssync)159 void destroy_state_sync_obj(struct state_sync *ssync) {
160     pthread_cond_destroy(&ssync->condition);
161     pthread_mutex_destroy(&ssync->mutex);
162     munmap(ssync, sizeof(struct state_sync));
163 }
164 
signal_state(struct state_sync * ssync,int state)165 void signal_state(struct state_sync *ssync, int state) {
166     pthread_mutex_lock(&ssync->mutex);
167     ssync->state = state;
168     pthread_cond_signal(&ssync->condition);
169     pthread_mutex_unlock(&ssync->mutex);
170 }
171 
wait_for_state(struct state_sync * ssync,int state)172 void wait_for_state(struct state_sync *ssync, int state) {
173     pthread_mutex_lock(&ssync->mutex);
174     while (ssync->state != state) {
175         pthread_cond_wait(&ssync->condition, &ssync->mutex);
176     }
177     pthread_mutex_unlock(&ssync->mutex);
178 }
179 
180 /* Memory allocation and data sharing */
181 struct shared_data {
182     size_t allocated;
183     bool finished;
184     size_t total_size;
185     size_t step_size;
186     size_t step_delay;
187     int oomadj;
188 };
189 
190 volatile void *gptr;
add_pressure(struct shared_data * data)191 void add_pressure(struct shared_data *data) {
192     volatile void *ptr;
193     size_t allocated_size = 0;
194 
195     data->finished = false;
196     while (allocated_size < data->total_size) {
197         ptr = mmap(NULL, data->step_size, PROT_READ | PROT_WRITE,
198                 MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
199         if (ptr != MAP_FAILED) {
200             /* create ptr aliasing to prevent compiler optimizing the access */
201             gptr = ptr;
202             /* make data non-zero */
203             memset((void*)ptr, (int)(allocated_size + 1), data->step_size);
204             allocated_size += data->step_size;
205             data->allocated = allocated_size;
206         }
207         usleep(data->step_delay);
208     }
209     data->finished = (allocated_size >= data->total_size);
210 }
211 
212 /* Memory stress test main body */
runMemStressTest()213 void runMemStressTest() {
214     struct shared_data *data;
215     struct state_sync *ssync;
216     int sock;
217     pid_t pid;
218     uid_t uid = getuid();
219 
220     // check if in-kernel LMK driver is present
221     if (!access(INKERNEL_MINFREE_PATH, W_OK)) {
222         GTEST_LOG_(INFO) << "Must not have kernel lowmemorykiller driver,"
223                          << " terminating test";
224         return;
225     }
226 
227     ASSERT_FALSE((sock = lmkd_connect()) < 0)
228         << "Failed to connect to lmkd process, err=" << strerror(errno);
229 
230     /* allocate shared memory to communicate params with a child */
231     data = (struct shared_data*)mmap(NULL, sizeof(struct shared_data),
232                 PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
233     ASSERT_FALSE(data == MAP_FAILED) << "Memory allocation failure";
234     data->total_size = (size_t)-1; /* allocate until killed */
235     data->step_size = ALLOC_STEP;
236     data->step_delay = ALLOC_DELAY;
237 
238     /* allocate state sync object */
239     ASSERT_FALSE((ssync = init_state_sync_obj()) == NULL)
240         << "Memory allocation failure";
241 
242     /* run the test gradually decreasing oomadj */
243     data->oomadj = OOM_ADJ_MAX;
244     while (data->oomadj >= OOM_ADJ_MIN) {
245         ASSERT_FALSE((pid = fork()) < 0)
246             << "Failed to spawn a child process, err=" << strerror(errno);
247         if (pid != 0) {
248             /* Parent */
249             struct lmk_procprio params;
250             /* wait for child to start and get ready */
251             wait_for_state(ssync, STATE_CHILD_READY);
252             params.pid = pid;
253             params.uid = uid;
254             params.oomadj = data->oomadj;
255             params.ptype = PROC_TYPE_APP;
256             ASSERT_FALSE(lmkd_register_proc(sock, &params) < 0)
257                 << "Failed to communicate with lmkd, err=" << strerror(errno);
258             // signal the child it can proceed
259             signal_state(ssync, STATE_PARENT_READY);
260             waitpid(pid, NULL, 0);
261             if (data->finished) {
262                 GTEST_LOG_(INFO) << "Child [pid=" << pid << "] allocated "
263                                  << data->allocated / ONE_MB << "MB";
264             } else {
265                 GTEST_LOG_(INFO) << "Child [pid=" << pid << "] allocated "
266                                  << data->allocated / ONE_MB
267                                  << "MB before being killed";
268             }
269             data->oomadj -= OOM_ADJ_STEP;
270         } else {
271             /* Child */
272             pid = getpid();
273             GTEST_LOG_(INFO) << "Child [pid=" << pid
274                              << "] is running at oomadj="
275                              << data->oomadj;
276             data->allocated = 0;
277             data->finished = false;
278             if (property_get_bool("ro.config.low_ram", false)) {
279                 ASSERT_FALSE(create_memcg(uid, pid) != 0)
280                     << "Child [pid=" << pid << "] failed to create a cgroup";
281             }
282             signal_state(ssync, STATE_CHILD_READY);
283             wait_for_state(ssync, STATE_PARENT_READY);
284             add_pressure(data);
285             /* should not reach here, child should be killed by OOM/LMK */
286             FAIL() << "Child [pid=" << pid << "] was not killed";
287             break;
288         }
289     }
290     destroy_state_sync_obj(ssync);
291     munmap(data, sizeof(struct shared_data));
292     close(sock);
293 }
294 
TEST(lmkd,check_for_oom)295 TEST(lmkd, check_for_oom) {
296     // test requirements
297     //   userdebug build
298     if (!__android_log_is_debuggable()) {
299         GTEST_LOG_(INFO) << "Must be userdebug build, terminating test";
300         return;
301     }
302 
303     // if respawned test process then run the test and exit (no analysis)
304     if (getenv(LMKDTEST_RESPAWN_FLAG) != NULL) {
305         runMemStressTest();
306         return;
307     }
308 
309     // Main test process
310     // mark the beginning of the test
311     std::string marker = StringPrintf(
312         "LMKD test start %lu\n", static_cast<unsigned long>(time(nullptr)));
313     ASSERT_TRUE(writeKmsg(marker));
314 
315     // get executable complete path
316     std::string task_name;
317     ASSERT_TRUE(getTaskName(task_name));
318 
319     std::string test_output;
320     if (getuid() != static_cast<unsigned>(AID_ROOT)) {
321         // if not root respawn itself as root and capture output
322         std::string command = StringPrintf(
323             "%s=true su root %s 2>&1", LMKDTEST_RESPAWN_FLAG,
324             task_name.c_str());
325         std::string test_output = readCommand(command);
326         GTEST_LOG_(INFO) << test_output;
327     } else {
328         // main test process is root, run the test
329         runMemStressTest();
330     }
331 
332     // Analyze results
333     // capture logcat containind kernel logs
334     std::string logcat_out = readLogcat(marker);
335 
336     // 1. extract LMKD kills from logcat output, count kills
337     std::stringstream kill_logs;
338     int hit_count = 0;
339     size_t pos = 0;
340     marker = StringPrintf(LMKD_KILL_MARKER_TEMPLATE, task_name.c_str());
341 
342     while (true) {
343         if ((pos = logcat_out.find(marker, pos)) != std::string::npos) {
344             kill_logs << getTextAround(logcat_out, pos, 0, 1);
345             pos += marker.length();
346             hit_count++;
347         } else {
348             break;
349         }
350     }
351     GTEST_LOG_(INFO) << "====Logged kills====" << std::endl
352                      << kill_logs.str();
353     EXPECT_TRUE(hit_count == STEP_COUNT) << "Number of kills " << hit_count
354                                          << " is less than expected "
355                                          << STEP_COUNT;
356 
357     // 2. check kernel logs for OOM kills
358     pos = logcat_out.find(OOM_MARKER);
359     bool oom_detected = (pos != std::string::npos);
360     bool oom_kill_detected = (oom_detected &&
361         logcat_out.find(OOM_KILL_MARKER, pos) != std::string::npos);
362 
363     EXPECT_FALSE(oom_kill_detected) << "OOM kill is detected!";
364     if (oom_detected || oom_kill_detected) {
365         // capture logcat with logs around all OOMs
366         pos = 0;
367         while ((pos = logcat_out.find(OOM_MARKER, pos)) != std::string::npos) {
368             GTEST_LOG_(INFO) << "====Logs around OOM====" << std::endl
369                              << getTextAround(logcat_out, pos,
370                                     MIN_LOG_SIZE / 2, MIN_LOG_SIZE / 2);
371             pos += strlen(OOM_MARKER);
372         }
373     }
374 
375     // output complete logcat with kernel (might get truncated)
376     GTEST_LOG_(INFO) << "====Complete logcat output====" << std::endl
377                      << logcat_out;
378 }
379 
380