lmkd_test.cpp 12 KB

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