• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 #include <sys/mman.h>
17 #include <sys/syscall.h>
18 #include <sstream>
19 #include <string>
20 
21 #include <android-base/file.h>
22 #include <android-base/logging.h>
23 #include <android-base/stringprintf.h>
24 #include <cutils/properties.h>
25 #include <gtest/gtest.h>
26 #include <liblmkd_utils.h>
27 #include <log/log_properties.h>
28 #include <private/android_filesystem_config.h>
29 
30 using namespace android::base;
31 
32 #ifndef __NR_process_mrelease
33 #define __NR_process_mrelease 448
34 #endif
35 
36 #define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
37 
38 #define LMKD_LOGCAT_MARKER "lowmemorykiller"
39 #define LMKD_KILL_TEMPLATE "Kill \'[^']*\' \\\(%d\\)"
40 #define LMKD_REAP_TEMPLATE "Process %d was reaped"
41 #define LMKD_REAP_FAIL_TEMPLATE "process_mrelease %d failed"
42 
43 #define LMKD_KILL_LINE_START LMKD_LOGCAT_MARKER ": Kill"
44 #define LMKD_REAP_LINE_START LMKD_LOGCAT_MARKER ": Process"
45 #define LMKD_REAP_TIME_TEMPLATE LMKD_LOGCAT_MARKER ": Process %d was reaped in %ldms"
46 #define LMKD_REAP_MRELESE_ERR_MARKER ": process_mrelease"
47 #define LMKD_REAP_NO_PROCESS_TEMPLATE ": process_mrelease %d failed: No such process"
48 
49 #define ONE_MB (1 << 20)
50 
51 // Test constant parameters
52 #define OOM_ADJ_MAX 1000
53 #define ALLOC_STEP (5 * ONE_MB)
54 #define ALLOC_DELAY 200
55 
56 // used to create ptr aliasing and prevent compiler optimizing the access
57 static volatile void* gptr;
58 
59 class LmkdTest : public ::testing::Test {
60   public:
SetUp()61     virtual void SetUp() {
62         // test requirements
63         if (getuid() != static_cast<unsigned>(AID_ROOT)) {
64             GTEST_SKIP() << "Must be root, skipping test";
65         }
66 
67         if (!__android_log_is_debuggable()) {
68             GTEST_SKIP() << "Must be userdebug build, skipping test";
69         }
70 
71         if (!access(INKERNEL_MINFREE_PATH, W_OK)) {
72             GTEST_SKIP() << "Must not have kernel lowmemorykiller driver,"
73                          << " skipping test";
74         }
75 
76         // should be able to turn on lmkd debug information
77         if (!property_get_bool("ro.lmk.debug", true)) {
78             GTEST_SKIP() << "Can't run with ro.lmk.debug property set to 'false', skipping test";
79         }
80 
81         // setup lmkd connection
82         ASSERT_FALSE((sock = lmkd_connect()) < 0)
83                 << "Failed to connect to lmkd process, err=" << strerror(errno);
84 
85         // enable ro.lmk.debug if not already enabled
86         if (!property_get_bool("ro.lmk.debug", false)) {
87             EXPECT_EQ(property_set("ro.lmk.debug", "true"), 0);
88             EXPECT_EQ(lmkd_update_props(sock), UPDATE_PROPS_SUCCESS)
89                     << "Failed to reinitialize lmkd";
90         }
91 
92         uid = getuid();
93     }
94 
TearDown()95     virtual void TearDown() {
96         // drop lmkd connection
97         close(sock);
98     }
99 
SetupChild(pid_t pid,int oomadj)100     void SetupChild(pid_t pid, int oomadj) {
101         struct lmk_procprio params;
102 
103         params.pid = pid;
104         params.uid = uid;
105         params.oomadj = oomadj;
106         params.ptype = PROC_TYPE_APP;
107         ASSERT_FALSE(lmkd_register_proc(sock, &params) < 0)
108                 << "Failed to communicate with lmkd, err=" << strerror(errno);
109         GTEST_LOG_(INFO) << "Target process " << pid << " launched";
110         if (property_get_bool("ro.config.low_ram", false)) {
111             ASSERT_FALSE(create_memcg(uid, pid) != 0)
112                     << "Target process " << pid << " failed to create a cgroup";
113         }
114     }
115 
ExecCommand(const std::string & command)116     static std::string ExecCommand(const std::string& command) {
117         FILE* fp = popen(command.c_str(), "r");
118         std::string content;
119         ReadFdToString(fileno(fp), &content);
120         pclose(fp);
121         return content;
122     }
123 
ReadLogcat(const std::string & tag,const std::string & regex)124     static std::string ReadLogcat(const std::string& tag, const std::string& regex) {
125         std::string cmd = "logcat -d -b all";
126         if (!tag.empty()) {
127             cmd += " -s \"" + tag + "\"";
128         }
129         if (!regex.empty()) {
130             cmd += " -e \"" + regex + "\"";
131         }
132         return ExecCommand(cmd);
133     }
134 
ConsumeMemory(size_t total_size,size_t step_size,size_t step_delay)135     static size_t ConsumeMemory(size_t total_size, size_t step_size, size_t step_delay) {
136         volatile void* ptr;
137         size_t allocated_size = 0;
138 
139         while (allocated_size < total_size) {
140             ptr = mmap(NULL, step_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
141             if (ptr != MAP_FAILED) {
142                 // create ptr aliasing to prevent compiler optimizing the access
143                 gptr = ptr;
144                 // make data non-zero
145                 memset((void*)ptr, (int)(allocated_size + 1), step_size);
146                 allocated_size += step_size;
147             }
148             usleep(step_delay);
149         }
150         return allocated_size;
151     }
152 
ParseProcSize(const std::string & line,long & rss,long & swap)153     static bool ParseProcSize(const std::string& line, long& rss, long& swap) {
154         size_t pos = line.find("to free");
155         if (pos == std::string::npos) {
156             return false;
157         }
158         return sscanf(line.c_str() + pos, "to free %ldkB rss, %ldkB swap", &rss, &swap) == 2;
159     }
160 
ParseReapTime(const std::string & line,pid_t pid,long & reap_time)161     static bool ParseReapTime(const std::string& line, pid_t pid, long& reap_time) {
162         int reap_pid;
163         return sscanf(line.c_str(), LMKD_REAP_TIME_TEMPLATE, &reap_pid, &reap_time) == 2 &&
164                reap_pid == pid;
165     }
166 
ParseReapNoProcess(const std::string & line,pid_t pid)167     static bool ParseReapNoProcess(const std::string& line, pid_t pid) {
168         int reap_pid;
169         return sscanf(line.c_str(), LMKD_REAP_NO_PROCESS_TEMPLATE, &reap_pid) == 1 &&
170                reap_pid == pid;
171     }
172 
173   private:
174     int sock;
175     uid_t uid;
176 };
177 
TEST_F(LmkdTest,TargetReaping)178 TEST_F(LmkdTest, TargetReaping) {
179     // test specific requirements
180     if (syscall(__NR_process_mrelease, -1, 0) && errno == ENOSYS) {
181         GTEST_SKIP() << "Must support process_mrelease syscall, skipping test";
182     }
183 
184     // for a child to act as a target process
185     pid_t pid = fork();
186     ASSERT_FALSE(pid < 0) << "Failed to spawn a child process, err=" << strerror(errno);
187     if (pid != 0) {
188         // parent
189         waitpid(pid, NULL, 0);
190     } else {
191         // child
192         SetupChild(getpid(), OOM_ADJ_MAX);
193         // allocate memory until killed
194         ConsumeMemory((size_t)-1, ALLOC_STEP, ALLOC_DELAY);
195         // should not reach here, child should be killed by OOM
196         FAIL() << "Target process " << pid << " was not killed";
197     }
198 
199     std::string regex = StringPrintf("((" LMKD_KILL_TEMPLATE ")|(" LMKD_REAP_TEMPLATE
200                                      ")|(" LMKD_REAP_FAIL_TEMPLATE "))",
201                                      pid, pid, pid);
202     std::string logcat_out = ReadLogcat(LMKD_LOGCAT_MARKER ":I", regex);
203 
204     // find kill report
205     size_t line_start = logcat_out.find(LMKD_KILL_LINE_START);
206     ASSERT_TRUE(line_start != std::string::npos) << "Kill report is not found";
207     size_t line_end = logcat_out.find('\n', line_start);
208     std::string line = logcat_out.substr(
209             line_start, line_end == std::string::npos ? std::string::npos : line_end - line_start);
210     long rss, swap;
211     ASSERT_TRUE(ParseProcSize(line, rss, swap)) << "Kill report format is invalid";
212 
213     // find reap duration report
214     line_start = logcat_out.find(LMKD_REAP_LINE_START, line_end);
215     if (line_start == std::string::npos) {
216         // Target might have exited before reaping started
217         line_start = logcat_out.find(LMKD_REAP_MRELESE_ERR_MARKER, line_end);
218 
219         ASSERT_TRUE(line_start != std::string::npos) << "Reaping time report is not found";
220 
221         line_end = logcat_out.find('\n', line_start);
222         line = logcat_out.substr(line_start, line_end == std::string::npos ? std::string::npos
223                                                                            : line_end - line_start);
224         ASSERT_TRUE(ParseReapNoProcess(line, pid)) << "Failed to reap the target " << pid;
225         return;
226     }
227     line_end = logcat_out.find('\n', line_start);
228     line = logcat_out.substr(
229             line_start, line_end == std::string::npos ? std::string::npos : line_end - line_start);
230     long reap_time;
231     ASSERT_TRUE(ParseReapTime(line, pid, reap_time) && reap_time > 0)
232             << "Reaping time report format is invalid";
233 
234     double reclaim_speed = ((double)rss + swap) / reap_time;
235     GTEST_LOG_(INFO) << "Reclaim speed " << reclaim_speed << "kB/ms (" << rss << "kB rss + " << swap
236                      << "kB swap) / " << reap_time << "ms";
237 }
238 
main(int argc,char ** argv)239 int main(int argc, char** argv) {
240     ::testing::InitGoogleTest(&argc, argv);
241     InitLogging(argv, StderrLogger);
242     return RUN_ALL_TESTS();
243 }
244