• 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 "llkd.h"
18 
19 #include <ctype.h>
20 #include <dirent.h>  // opendir() and readdir()
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <pthread.h>
24 #include <pwd.h>  // getpwuid()
25 #include <signal.h>
26 #include <stdint.h>
27 #include <string.h>
28 #include <sys/cdefs.h>  // ___STRING, __predict_true() and _predict_false()
29 #include <sys/mman.h>   // mlockall()
30 #include <sys/prctl.h>
31 #include <sys/stat.h>     // lstat()
32 #include <sys/syscall.h>  // __NR_getdents64
33 #include <sys/sysinfo.h>  // get_nprocs_conf()
34 #include <sys/types.h>
35 #include <time.h>
36 #include <unistd.h>
37 
38 #include <chrono>
39 #include <ios>
40 #include <sstream>
41 #include <string>
42 #include <unordered_map>
43 #include <unordered_set>
44 
45 #include <android-base/file.h>
46 #include <android-base/logging.h>
47 #include <android-base/parseint.h>
48 #include <android-base/properties.h>
49 #include <android-base/strings.h>
50 #include <cutils/android_get_control_file.h>
51 #include <log/log_main.h>
52 
53 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
54 
55 #define TASK_COMM_LEN 16  // internal kernel, not uapi, from .../linux/include/linux/sched.h
56 
57 using namespace std::chrono_literals;
58 using namespace std::chrono;
59 using namespace std::literals;
60 
61 namespace {
62 
63 constexpr pid_t kernelPid = 0;
64 constexpr pid_t initPid = 1;
65 constexpr pid_t kthreaddPid = 2;
66 
67 constexpr char procdir[] = "/proc/";
68 
69 // Configuration
70 milliseconds llkUpdate;                              // last check ms signature
71 milliseconds llkCycle;                               // ms to next thread check
72 bool llkEnable = LLK_ENABLE_DEFAULT;                 // llk daemon enabled
73 bool llkRunning = false;                             // thread is running
74 bool llkMlockall = LLK_MLOCKALL_DEFAULT;             // run mlocked
75 bool llkTestWithKill = LLK_KILLTEST_DEFAULT;         // issue test kills
76 milliseconds llkTimeoutMs = LLK_TIMEOUT_MS_DEFAULT;  // default timeout
77 enum {                                               // enum of state indexes
78     llkStateD,                                       // Persistent 'D' state
79     llkStateZ,                                       // Persistent 'Z' state
80 #ifdef __PTRACE_ENABLED__                            // Extra privileged states
81     llkStateStack,                                   // stack signature
82 #endif                                               // End of extra privilege
83     llkNumStates,                                    // Maxumum number of states
84 };                                                   // state indexes
85 milliseconds llkStateTimeoutMs[llkNumStates];        // timeout override for each detection state
86 milliseconds llkCheckMs;                             // checking interval to inspect any
87                                                      // persistent live-locked states
88 bool llkLowRam;                                      // ro.config.low_ram
89 bool llkEnableSysrqT = LLK_ENABLE_SYSRQ_T_DEFAULT;   // sysrq stack trace dump
90 bool khtEnable = LLK_ENABLE_DEFAULT;                 // [khungtaskd] panic
91 // [khungtaskd] should have a timeout beyond the granularity of llkTimeoutMs.
92 // Provides a wide angle of margin b/c khtTimeout is also its granularity.
93 seconds khtTimeout = duration_cast<seconds>(llkTimeoutMs * (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT) /
94                                             LLK_CHECKS_PER_TIMEOUT_DEFAULT);
95 #ifdef __PTRACE_ENABLED__
96 // list of stack symbols to search for persistence.
97 std::unordered_set<std::string> llkCheckStackSymbols;
98 #endif
99 
100 // Blacklist variables, initialized with comma separated lists of high false
101 // positive and/or dangerous references, e.g. without self restart, for pid,
102 // ppid, name and uid:
103 
104 // list of pids, or tids or names to skip. kernel pid (0), init pid (1),
105 // [kthreadd] pid (2), ourselves, "init", "[kthreadd]", "lmkd", "llkd" or
106 // combinations of watchdogd in kernel and user space.
107 std::unordered_set<std::string> llkBlacklistProcess;
108 // list of parent pids, comm or cmdline names to skip. default:
109 // kernel pid (0), [kthreadd] (2), or ourselves, enforced and implied
110 std::unordered_set<std::string> llkBlacklistParent;
111 // list of parent and target processes to skip. default:
112 // adbd *and* [setsid]
113 std::unordered_map<std::string, std::unordered_set<std::string>> llkBlacklistParentAndChild;
114 // list of uids, and uid names, to skip, default nothing
115 std::unordered_set<std::string> llkBlacklistUid;
116 #ifdef __PTRACE_ENABLED__
117 // list of names to skip stack checking. "init", "lmkd", "llkd", "keystore" or
118 // "logd" (if not userdebug).
119 std::unordered_set<std::string> llkBlacklistStack;
120 #endif
121 
122 class dir {
123   public:
124     enum level { proc, task, numLevels };
125 
126   private:
127     int fd;
128     size_t available_bytes;
129     dirent* next;
130     // each directory level picked to be just north of 4K in size
131     static constexpr size_t buffEntries = 15;
132     static dirent buff[numLevels][buffEntries];
133 
fill(enum level index)134     bool fill(enum level index) {
135         if (index >= numLevels) return false;
136         if (available_bytes != 0) return true;
137         if (__predict_false(fd < 0)) return false;
138         // getdents64 has no libc wrapper
139         auto rc = TEMP_FAILURE_RETRY(syscall(__NR_getdents64, fd, buff[index], sizeof(buff[0]), 0));
140         if (rc <= 0) return false;
141         available_bytes = rc;
142         next = buff[index];
143         return true;
144     }
145 
146   public:
dir()147     dir() : fd(-1), available_bytes(0), next(nullptr) {}
148 
dir(const char * directory)149     explicit dir(const char* directory)
150         : fd(__predict_true(directory != nullptr)
151                  ? ::open(directory, O_CLOEXEC | O_DIRECTORY | O_RDONLY)
152                  : -1),
153           available_bytes(0),
154           next(nullptr) {}
155 
dir(const std::string && directory)156     explicit dir(const std::string&& directory)
157         : fd(::open(directory.c_str(), O_CLOEXEC | O_DIRECTORY | O_RDONLY)),
158           available_bytes(0),
159           next(nullptr) {}
160 
dir(const std::string & directory)161     explicit dir(const std::string& directory)
162         : fd(::open(directory.c_str(), O_CLOEXEC | O_DIRECTORY | O_RDONLY)),
163           available_bytes(0),
164           next(nullptr) {}
165 
166     // Don't need any copy or move constructors.
167     explicit dir(const dir& c) = delete;
168     explicit dir(dir& c) = delete;
169     explicit dir(dir&& c) = delete;
170 
~dir()171     ~dir() {
172         if (fd >= 0) {
173             ::close(fd);
174         }
175     }
176 
operator bool() const177     operator bool() const { return fd >= 0; }
178 
reset(void)179     void reset(void) {
180         if (fd >= 0) {
181             ::close(fd);
182             fd = -1;
183             available_bytes = 0;
184             next = nullptr;
185         }
186     }
187 
reset(const char * directory)188     dir& reset(const char* directory) {
189         reset();
190         // available_bytes will _always_ be zero here as its value is
191         // intimately tied to fd < 0 or not.
192         fd = ::open(directory, O_CLOEXEC | O_DIRECTORY | O_RDONLY);
193         return *this;
194     }
195 
rewind(void)196     void rewind(void) {
197         if (fd >= 0) {
198             ::lseek(fd, off_t(0), SEEK_SET);
199             available_bytes = 0;
200             next = nullptr;
201         }
202     }
203 
read(enum level index=proc,dirent * def=nullptr)204     dirent* read(enum level index = proc, dirent* def = nullptr) {
205         if (!fill(index)) return def;
206         auto ret = next;
207         available_bytes -= next->d_reclen;
208         next = reinterpret_cast<dirent*>(reinterpret_cast<char*>(next) + next->d_reclen);
209         return ret;
210     }
211 } llkTopDirectory;
212 
213 dirent dir::buff[dir::numLevels][dir::buffEntries];
214 
215 // helper functions
216 
llkIsMissingExeLink(pid_t tid)217 bool llkIsMissingExeLink(pid_t tid) {
218     char c;
219     // CAP_SYS_PTRACE is required to prevent ret == -1, but ENOENT is signal
220     auto ret = ::readlink((procdir + std::to_string(tid) + "/exe").c_str(), &c, sizeof(c));
221     return (ret == -1) && (errno == ENOENT);
222 }
223 
224 // Common routine where caller accepts empty content as error/passthrough.
225 // Reduces the churn of reporting read errors in the callers.
ReadFile(std::string && path)226 std::string ReadFile(std::string&& path) {
227     std::string content;
228     if (!android::base::ReadFileToString(path, &content)) {
229         PLOG(DEBUG) << "Read " << path << " failed";
230         content = "";
231     }
232     return content;
233 }
234 
llkProcGetName(pid_t tid,const char * node="/cmdline")235 std::string llkProcGetName(pid_t tid, const char* node = "/cmdline") {
236     std::string content = ReadFile(procdir + std::to_string(tid) + node);
237     static constexpr char needles[] = " \t\r\n";  // including trailing nul
238     auto pos = content.find_first_of(needles, 0, sizeof(needles));
239     if (pos != std::string::npos) {
240         content.erase(pos);
241     }
242     return content;
243 }
244 
llkProcGetUid(pid_t tid)245 uid_t llkProcGetUid(pid_t tid) {
246     // Get the process' uid.  The following read from /status is admittedly
247     // racy, prone to corruption due to shape-changes.  The consequences are
248     // not catastrophic as we sample a few times before taking action.
249     //
250     // If /loginuid worked on reliably, or on Android (all tasks report -1)...
251     // Android lmkd causes /cgroup to contain memory:/<dom>/uid_<uid>/pid_<pid>
252     // which is tighter, but also not reliable.
253     std::string content = ReadFile(procdir + std::to_string(tid) + "/status");
254     static constexpr char Uid[] = "\nUid:";
255     auto pos = content.find(Uid);
256     if (pos == std::string::npos) {
257         return -1;
258     }
259     pos += ::strlen(Uid);
260     while ((pos < content.size()) && ::isblank(content[pos])) {
261         ++pos;
262     }
263     content.erase(0, pos);
264     for (pos = 0; (pos < content.size()) && ::isdigit(content[pos]); ++pos) {
265         ;
266     }
267     // Content of form 'Uid:	0	0	0	0', newline is error
268     if ((pos >= content.size()) || !::isblank(content[pos])) {
269         return -1;
270     }
271     content.erase(pos);
272     uid_t ret;
273     if (!android::base::ParseUint(content, &ret, uid_t(0))) {
274         return -1;
275     }
276     return ret;
277 }
278 
279 struct proc {
280     pid_t tid;                     // monitored thread id (in Z or D state).
281     nanoseconds schedUpdate;       // /proc/<tid>/sched "se.avg.lastUpdateTime",
282     uint64_t nrSwitches;           // /proc/<tid>/sched "nr_switches" for
283                                    // refined ABA problem detection, determine
284                                    // forward scheduling progress.
285     milliseconds update;           // llkUpdate millisecond signature of last.
286     milliseconds count;            // duration in state.
287 #ifdef __PTRACE_ENABLED__          // Privileged state checking
288     milliseconds count_stack;      // duration where stack is stagnant.
289 #endif                             // End privilege
290     pid_t pid;                     // /proc/<pid> before iterating through
291                                    // /proc/<pid>/task/<tid> for threads.
292     pid_t ppid;                    // /proc/<tid>/stat field 4 parent pid.
293     uid_t uid;                     // /proc/<tid>/status Uid: field.
294     unsigned time;                 // sum of /proc/<tid>/stat field 14 utime &
295                                    // 15 stime for coarse ABA problem detection.
296     std::string cmdline;           // cached /cmdline content
297     char state;                    // /proc/<tid>/stat field 3: Z or D
298                                    // (others we do not monitor: S, R, T or ?)
299 #ifdef __PTRACE_ENABLED__          // Privileged state checking
300     char stack;                    // index in llkCheckStackSymbols for matches
301 #endif                             // and with maximum index PROP_VALUE_MAX/2.
302     char comm[TASK_COMM_LEN + 3];  // space for adding '[' and ']'
303     bool exeMissingValid;          // exeMissing has been cached
304     bool cmdlineValid;             // cmdline has been cached
305     bool updated;                  // cleared before monitoring pass.
306     bool killed;                   // sent a kill to this thread, next panic...
307 
setComm__anon19030e590111::proc308     void setComm(const char* _comm) { strncpy(comm + 1, _comm, sizeof(comm) - 2); }
309 
proc__anon19030e590111::proc310     proc(pid_t tid, pid_t pid, pid_t ppid, const char* _comm, int time, char state)
311         : tid(tid),
312           schedUpdate(0),
313           nrSwitches(0),
314           update(llkUpdate),
315           count(0ms),
316 #ifdef __PTRACE_ENABLED__
317           count_stack(0ms),
318 #endif
319           pid(pid),
320           ppid(ppid),
321           uid(-1),
322           time(time),
323           state(state),
324 #ifdef __PTRACE_ENABLED__
325           stack(-1),
326 #endif
327           exeMissingValid(false),
328           cmdlineValid(false),
329           updated(true),
330           killed(!llkTestWithKill) {
331         memset(comm, '\0', sizeof(comm));
332         setComm(_comm);
333     }
334 
getComm__anon19030e590111::proc335     const char* getComm(void) {
336         if (comm[1] == '\0') {  // comm Valid?
337             strncpy(comm + 1, llkProcGetName(tid, "/comm").c_str(), sizeof(comm) - 2);
338         }
339         if (!exeMissingValid) {
340             if (llkIsMissingExeLink(tid)) {
341                 comm[0] = '[';
342             }
343             exeMissingValid = true;
344         }
345         size_t len = strlen(comm + 1);
346         if (__predict_true(len < (sizeof(comm) - 1))) {
347             if (comm[0] == '[') {
348                 if ((comm[len] != ']') && __predict_true(len < (sizeof(comm) - 2))) {
349                     comm[++len] = ']';
350                     comm[++len] = '\0';
351                 }
352             } else {
353                 if (comm[len] == ']') {
354                     comm[len] = '\0';
355                 }
356             }
357         }
358         return &comm[comm[0] != '['];
359     }
360 
getCmdline__anon19030e590111::proc361     const char* getCmdline(void) {
362         if (!cmdlineValid) {
363             cmdline = llkProcGetName(tid);
364             cmdlineValid = true;
365         }
366         return cmdline.c_str();
367     }
368 
getUid__anon19030e590111::proc369     uid_t getUid(void) {
370         if (uid <= 0) {  // Churn on root user, because most likely to setuid()
371             uid = llkProcGetUid(tid);
372         }
373         return uid;
374     }
375 
reset__anon19030e590111::proc376     void reset(void) {  // reset cache, if we detected pid rollover
377         uid = -1;
378         state = '?';
379 #ifdef __PTRACE_ENABLED__
380         count_stack = 0ms;
381         stack = -1;
382 #endif
383         cmdline = "";
384         comm[0] = '\0';
385         exeMissingValid = false;
386         cmdlineValid = false;
387     }
388 };
389 
390 std::unordered_map<pid_t, proc> tids;
391 
392 // Check range and setup defaults, in order of propagation:
393 //     llkTimeoutMs
394 //     llkCheckMs
395 //     ...
396 // KISS to keep it all self-contained, and called multiple times as parameters
397 // are interpreted so that defaults, llkCheckMs and llkCycle make sense.
llkValidate()398 void llkValidate() {
399     if (llkTimeoutMs == 0ms) {
400         llkTimeoutMs = LLK_TIMEOUT_MS_DEFAULT;
401     }
402     llkTimeoutMs = std::max(llkTimeoutMs, LLK_TIMEOUT_MS_MINIMUM);
403     if (llkCheckMs == 0ms) {
404         llkCheckMs = llkTimeoutMs / LLK_CHECKS_PER_TIMEOUT_DEFAULT;
405     }
406     llkCheckMs = std::min(llkCheckMs, llkTimeoutMs);
407 
408     for (size_t state = 0; state < ARRAY_SIZE(llkStateTimeoutMs); ++state) {
409         if (llkStateTimeoutMs[state] == 0ms) {
410             llkStateTimeoutMs[state] = llkTimeoutMs;
411         }
412         llkStateTimeoutMs[state] =
413             std::min(std::max(llkStateTimeoutMs[state], LLK_TIMEOUT_MS_MINIMUM), llkTimeoutMs);
414         llkCheckMs = std::min(llkCheckMs, llkStateTimeoutMs[state]);
415     }
416 
417     llkCheckMs = std::max(llkCheckMs, LLK_CHECK_MS_MINIMUM);
418     if (llkCycle == 0ms) {
419         llkCycle = llkCheckMs;
420     }
421     llkCycle = std::min(llkCycle, llkCheckMs);
422 }
423 
llkGetTimespecDiffMs(timespec * from,timespec * to)424 milliseconds llkGetTimespecDiffMs(timespec* from, timespec* to) {
425     return duration_cast<milliseconds>(seconds(to->tv_sec - from->tv_sec)) +
426            duration_cast<milliseconds>(nanoseconds(to->tv_nsec - from->tv_nsec));
427 }
428 
llkProcGetName(pid_t tid,const char * comm,const char * cmdline)429 std::string llkProcGetName(pid_t tid, const char* comm, const char* cmdline) {
430     if ((cmdline != nullptr) && (*cmdline != '\0')) {
431         return cmdline;
432     }
433     if ((comm != nullptr) && (*comm != '\0')) {
434         return comm;
435     }
436 
437     // UNLIKELY! Here because killed before we kill it?
438     // Assume change is afoot, do not call llkTidAlloc
439 
440     // cmdline ?
441     std::string content = llkProcGetName(tid);
442     if (content.size() != 0) {
443         return content;
444     }
445     // Comm instead?
446     content = llkProcGetName(tid, "/comm");
447     if (llkIsMissingExeLink(tid) && (content.size() != 0)) {
448         return '[' + content + ']';
449     }
450     return content;
451 }
452 
llkKillOneProcess(pid_t pid,char state,pid_t tid,const char * tcomm=nullptr,const char * tcmdline=nullptr,const char * pcomm=nullptr,const char * pcmdline=nullptr)453 int llkKillOneProcess(pid_t pid, char state, pid_t tid, const char* tcomm = nullptr,
454                       const char* tcmdline = nullptr, const char* pcomm = nullptr,
455                       const char* pcmdline = nullptr) {
456     std::string forTid;
457     if (tid != pid) {
458         forTid = " for '" + llkProcGetName(tid, tcomm, tcmdline) + "' (" + std::to_string(tid) + ")";
459     }
460     LOG(INFO) << "Killing '" << llkProcGetName(pid, pcomm, pcmdline) << "' (" << pid
461               << ") to check forward scheduling progress in " << state << " state" << forTid;
462     // CAP_KILL required
463     errno = 0;
464     auto r = ::kill(pid, SIGKILL);
465     if (r) {
466         PLOG(ERROR) << "kill(" << pid << ")=" << r << ' ';
467     }
468 
469     return r;
470 }
471 
472 // Kill one process
llkKillOneProcess(pid_t pid,proc * tprocp)473 int llkKillOneProcess(pid_t pid, proc* tprocp) {
474     return llkKillOneProcess(pid, tprocp->state, tprocp->tid, tprocp->getComm(),
475                              tprocp->getCmdline());
476 }
477 
478 // Kill one process specified by kprocp
llkKillOneProcess(proc * kprocp,proc * tprocp)479 int llkKillOneProcess(proc* kprocp, proc* tprocp) {
480     if (kprocp == nullptr) {
481         return -2;
482     }
483 
484     return llkKillOneProcess(kprocp->tid, tprocp->state, tprocp->tid, tprocp->getComm(),
485                              tprocp->getCmdline(), kprocp->getComm(), kprocp->getCmdline());
486 }
487 
488 // Acquire file descriptor from environment, or open and cache it.
489 // NB: cache is unnecessary in our current context, pedantically
490 //     required to prevent leakage of file descriptors in the future.
llkFileToWriteFd(const std::string & file)491 int llkFileToWriteFd(const std::string& file) {
492     static std::unordered_map<std::string, int> cache;
493     auto search = cache.find(file);
494     if (search != cache.end()) return search->second;
495     auto fd = android_get_control_file(file.c_str());
496     if (fd >= 0) return fd;
497     fd = TEMP_FAILURE_RETRY(::open(file.c_str(), O_WRONLY | O_CLOEXEC));
498     if (fd >= 0) cache.emplace(std::make_pair(file, fd));
499     return fd;
500 }
501 
502 // Wrap android::base::WriteStringToFile to use android_get_control_file.
llkWriteStringToFile(const std::string & string,const std::string & file)503 bool llkWriteStringToFile(const std::string& string, const std::string& file) {
504     auto fd = llkFileToWriteFd(file);
505     if (fd < 0) return false;
506     return android::base::WriteStringToFd(string, fd);
507 }
508 
llkWriteStringToFileConfirm(const std::string & string,const std::string & file)509 bool llkWriteStringToFileConfirm(const std::string& string, const std::string& file) {
510     auto fd = llkFileToWriteFd(file);
511     auto ret = (fd < 0) ? false : android::base::WriteStringToFd(string, fd);
512     std::string content;
513     if (!android::base::ReadFileToString(file, &content)) return ret;
514     return android::base::Trim(content) == string;
515 }
516 
llkPanicKernel(bool dump,pid_t tid,const char * state,const std::string & message="")517 void llkPanicKernel(bool dump, pid_t tid, const char* state, const std::string& message = "") {
518     if (!message.empty()) LOG(ERROR) << message;
519     auto sysrqTriggerFd = llkFileToWriteFd("/proc/sysrq-trigger");
520     if (sysrqTriggerFd < 0) {
521         // DYB
522         llkKillOneProcess(initPid, 'R', tid);
523         // The answer to life, the universe and everything
524         ::exit(42);
525         // NOTREACHED
526         return;
527     }
528     // Wish could ::sync() here, if storage is locked up, we will not continue.
529     if (dump) {
530         // Show all locks that are held
531         android::base::WriteStringToFd("d", sysrqTriggerFd);
532         // Show all waiting tasks
533         android::base::WriteStringToFd("w", sysrqTriggerFd);
534         // This can trigger hardware watchdog, that is somewhat _ok_.
535         // But useless if pstore configured for <256KB, low ram devices ...
536         if (llkEnableSysrqT) {
537             android::base::WriteStringToFd("t", sysrqTriggerFd);
538             // Show all locks that are held (in case 't' overflows ramoops)
539             android::base::WriteStringToFd("d", sysrqTriggerFd);
540             // Show all waiting tasks (in case 't' overflows ramoops)
541             android::base::WriteStringToFd("w", sysrqTriggerFd);
542         }
543         ::usleep(200000);  // let everything settle
544     }
545     // SysRq message matches kernel format, and propagates through bootstat
546     // ultimately to the boot reason into panic,livelock,<state>.
547     llkWriteStringToFile(message + (message.empty() ? "" : "\n") +
548                                  "SysRq : Trigger a crash : 'livelock,"s + state + "'\n",
549                          "/dev/kmsg");
550     // Because panic is such a serious thing to do, let us
551     // make sure that the tid being inspected still exists!
552     auto piddir = procdir + std::to_string(tid) + "/stat";
553     if (access(piddir.c_str(), F_OK) != 0) {
554         PLOG(WARNING) << piddir;
555         return;
556     }
557     android::base::WriteStringToFd("c", sysrqTriggerFd);
558     // NOTREACHED
559     // DYB
560     llkKillOneProcess(initPid, 'R', tid);
561     // I sat at my desk, stared into the garden and thought '42 will do'.
562     // I typed it out. End of story
563     ::exit(42);
564     // NOTREACHED
565 }
566 
llkAlarmHandler(int)567 void llkAlarmHandler(int) {
568     LOG(FATAL) << "alarm";
569     // NOTREACHED
570     llkPanicKernel(true, ::getpid(), "alarm");
571 }
572 
GetUintProperty(const std::string & key,milliseconds def)573 milliseconds GetUintProperty(const std::string& key, milliseconds def) {
574     return milliseconds(android::base::GetUintProperty(key, static_cast<uint64_t>(def.count()),
575                                                        static_cast<uint64_t>(def.max().count())));
576 }
577 
GetUintProperty(const std::string & key,seconds def)578 seconds GetUintProperty(const std::string& key, seconds def) {
579     return seconds(android::base::GetUintProperty(key, static_cast<uint64_t>(def.count()),
580                                                   static_cast<uint64_t>(def.max().count())));
581 }
582 
llkTidLookup(pid_t tid)583 proc* llkTidLookup(pid_t tid) {
584     auto search = tids.find(tid);
585     if (search == tids.end()) {
586         return nullptr;
587     }
588     return &search->second;
589 }
590 
llkTidRemove(pid_t tid)591 void llkTidRemove(pid_t tid) {
592     tids.erase(tid);
593 }
594 
llkTidAlloc(pid_t tid,pid_t pid,pid_t ppid,const char * comm,int time,char state)595 proc* llkTidAlloc(pid_t tid, pid_t pid, pid_t ppid, const char* comm, int time, char state) {
596     auto it = tids.emplace(std::make_pair(tid, proc(tid, pid, ppid, comm, time, state)));
597     return &it.first->second;
598 }
599 
llkFormat(milliseconds ms)600 std::string llkFormat(milliseconds ms) {
601     auto sec = duration_cast<seconds>(ms);
602     std::ostringstream s;
603     s << sec.count() << '.';
604     auto f = s.fill('0');
605     auto w = s.width(3);
606     s << std::right << (ms - sec).count();
607     s.width(w);
608     s.fill(f);
609     s << 's';
610     return s.str();
611 }
612 
llkFormat(seconds s)613 std::string llkFormat(seconds s) {
614     return std::to_string(s.count()) + 's';
615 }
616 
llkFormat(bool flag)617 std::string llkFormat(bool flag) {
618     return flag ? "true" : "false";
619 }
620 
llkFormat(const std::unordered_set<std::string> & blacklist)621 std::string llkFormat(const std::unordered_set<std::string>& blacklist) {
622     std::string ret;
623     for (const auto& entry : blacklist) {
624         if (!ret.empty()) ret += ",";
625         ret += entry;
626     }
627     return ret;
628 }
629 
llkFormat(const std::unordered_map<std::string,std::unordered_set<std::string>> & blacklist,bool leading_comma=false)630 std::string llkFormat(
631         const std::unordered_map<std::string, std::unordered_set<std::string>>& blacklist,
632         bool leading_comma = false) {
633     std::string ret;
634     for (const auto& entry : blacklist) {
635         for (const auto& target : entry.second) {
636             if (leading_comma || !ret.empty()) ret += ",";
637             ret += entry.first + "&" + target;
638         }
639     }
640     return ret;
641 }
642 
643 // This function parses the properties as a list, incorporating the supplied
644 // default.  A leading comma separator means preserve the defaults and add
645 // entries (with an optional leading + sign), or removes entries with a leading
646 // - sign.
647 //
648 // We only officially support comma separators, but wetware being what they
649 // are will take some liberty and I do not believe they should be punished.
llkSplit(const std::string & prop,const std::string & def)650 std::unordered_set<std::string> llkSplit(const std::string& prop, const std::string& def) {
651     auto s = android::base::GetProperty(prop, def);
652     constexpr char separators[] = ", \t:;";
653     if (!s.empty() && (s != def) && strchr(separators, s[0])) s = def + s;
654 
655     std::unordered_set<std::string> result;
656 
657     // Special case, allow boolean false to empty the list, otherwise expected
658     // source of input from android::base::GetProperty will supply the default
659     // value on empty content in the property.
660     if (s == "false") return result;
661 
662     size_t base = 0;
663     while (s.size() > base) {
664         auto found = s.find_first_of(separators, base);
665         // Only emplace unique content, empty entries are not an option
666         if (found != base) {
667             switch (s[base]) {
668                 case '-':
669                     ++base;
670                     if (base >= s.size()) break;
671                     if (base != found) {
672                         auto have = result.find(s.substr(base, found - base));
673                         if (have != result.end()) result.erase(have);
674                     }
675                     break;
676                 case '+':
677                     ++base;
678                     if (base >= s.size()) break;
679                     if (base == found) break;
680                     // FALLTHRU (for gcc, lint, pcc, etc; following for clang)
681                     FALLTHROUGH_INTENDED;
682                 default:
683                     result.emplace(s.substr(base, found - base));
684                     break;
685             }
686         }
687         if (found == s.npos) break;
688         base = found + 1;
689     }
690     return result;
691 }
692 
llkSkipName(const std::string & name,const std::unordered_set<std::string> & blacklist=llkBlacklistProcess)693 bool llkSkipName(const std::string& name,
694                  const std::unordered_set<std::string>& blacklist = llkBlacklistProcess) {
695     if (name.empty() || blacklist.empty()) return false;
696 
697     return blacklist.find(name) != blacklist.end();
698 }
699 
llkSkipProc(proc * procp,const std::unordered_set<std::string> & blacklist=llkBlacklistProcess)700 bool llkSkipProc(proc* procp,
701                  const std::unordered_set<std::string>& blacklist = llkBlacklistProcess) {
702     if (!procp) return false;
703     if (llkSkipName(std::to_string(procp->pid), blacklist)) return true;
704     if (llkSkipName(procp->getComm(), blacklist)) return true;
705     if (llkSkipName(procp->getCmdline(), blacklist)) return true;
706     if (llkSkipName(android::base::Basename(procp->getCmdline()), blacklist)) return true;
707     return false;
708 }
709 
llkSkipName(const std::string & name,const std::unordered_map<std::string,std::unordered_set<std::string>> & blacklist)710 const std::unordered_set<std::string>& llkSkipName(
711         const std::string& name,
712         const std::unordered_map<std::string, std::unordered_set<std::string>>& blacklist) {
713     static const std::unordered_set<std::string> empty;
714     if (name.empty() || blacklist.empty()) return empty;
715     auto found = blacklist.find(name);
716     if (found == blacklist.end()) return empty;
717     return found->second;
718 }
719 
llkSkipPproc(proc * pprocp,proc * procp,const std::unordered_map<std::string,std::unordered_set<std::string>> & blacklist=llkBlacklistParentAndChild)720 bool llkSkipPproc(proc* pprocp, proc* procp,
721                   const std::unordered_map<std::string, std::unordered_set<std::string>>&
722                           blacklist = llkBlacklistParentAndChild) {
723     if (!pprocp || !procp || blacklist.empty()) return false;
724     if (llkSkipProc(procp, llkSkipName(std::to_string(pprocp->pid), blacklist))) return true;
725     if (llkSkipProc(procp, llkSkipName(pprocp->getComm(), blacklist))) return true;
726     if (llkSkipProc(procp, llkSkipName(pprocp->getCmdline(), blacklist))) return true;
727     return llkSkipProc(procp,
728                        llkSkipName(android::base::Basename(pprocp->getCmdline()), blacklist));
729 }
730 
llkSkipPid(pid_t pid)731 bool llkSkipPid(pid_t pid) {
732     return llkSkipName(std::to_string(pid), llkBlacklistProcess);
733 }
734 
llkSkipPpid(pid_t ppid)735 bool llkSkipPpid(pid_t ppid) {
736     return llkSkipName(std::to_string(ppid), llkBlacklistParent);
737 }
738 
llkSkipUid(uid_t uid)739 bool llkSkipUid(uid_t uid) {
740     // Match by number?
741     if (llkSkipName(std::to_string(uid), llkBlacklistUid)) {
742         return true;
743     }
744 
745     // Match by name?
746     auto pwd = ::getpwuid(uid);
747     return (pwd != nullptr) && __predict_true(pwd->pw_name != nullptr) &&
748            __predict_true(pwd->pw_name[0] != '\0') && llkSkipName(pwd->pw_name, llkBlacklistUid);
749 }
750 
getValidTidDir(dirent * dp,std::string * piddir)751 bool getValidTidDir(dirent* dp, std::string* piddir) {
752     if (!::isdigit(dp->d_name[0])) {
753         return false;
754     }
755 
756     // Corner case can not happen in reality b/c of above ::isdigit check
757     if (__predict_false(dp->d_type != DT_DIR)) {
758         if (__predict_false(dp->d_type == DT_UNKNOWN)) {  // can't b/c procfs
759             struct stat st;
760             *piddir = procdir;
761             *piddir += dp->d_name;
762             return (lstat(piddir->c_str(), &st) == 0) && (st.st_mode & S_IFDIR);
763         }
764         return false;
765     }
766 
767     *piddir = procdir;
768     *piddir += dp->d_name;
769     return true;
770 }
771 
llkIsMonitorState(char state)772 bool llkIsMonitorState(char state) {
773     return (state == 'Z') || (state == 'D');
774 }
775 
776 // returns -1 if not found
getSchedValue(const std::string & schedString,const char * key)777 long long getSchedValue(const std::string& schedString, const char* key) {
778     auto pos = schedString.find(key);
779     if (pos == std::string::npos) {
780         return -1;
781     }
782     pos = schedString.find(':', pos);
783     if (__predict_false(pos == std::string::npos)) {
784         return -1;
785     }
786     while ((++pos < schedString.size()) && ::isblank(schedString[pos])) {
787         ;
788     }
789     long long ret;
790     if (!android::base::ParseInt(schedString.substr(pos), &ret, static_cast<long long>(0))) {
791         return -1;
792     }
793     return ret;
794 }
795 
796 #ifdef __PTRACE_ENABLED__
llkCheckStack(proc * procp,const std::string & piddir)797 bool llkCheckStack(proc* procp, const std::string& piddir) {
798     if (llkCheckStackSymbols.empty()) return false;
799     if (procp->state == 'Z') {  // No brains for Zombies
800         procp->stack = -1;
801         procp->count_stack = 0ms;
802         return false;
803     }
804 
805     // Don't check process that are known to block ptrace, save sepolicy noise.
806     if (llkSkipProc(procp, llkBlacklistStack)) return false;
807     auto kernel_stack = ReadFile(piddir + "/stack");
808     if (kernel_stack.empty()) {
809         LOG(VERBOSE) << piddir << "/stack empty comm=" << procp->getComm()
810                      << " cmdline=" << procp->getCmdline();
811         return false;
812     }
813     // A scheduling incident that should not reset count_stack
814     if (kernel_stack.find(" cpu_worker_pools+0x") != std::string::npos) return false;
815     char idx = -1;
816     char match = -1;
817     std::string matched_stack_symbol = "<unknown>";
818     for (const auto& stack : llkCheckStackSymbols) {
819         if (++idx < 0) break;
820         if ((kernel_stack.find(" "s + stack + "+0x") != std::string::npos) ||
821             (kernel_stack.find(" "s + stack + ".cfi+0x") != std::string::npos)) {
822             match = idx;
823             matched_stack_symbol = stack;
824             break;
825         }
826     }
827     if (procp->stack != match) {
828         procp->stack = match;
829         procp->count_stack = 0ms;
830         return false;
831     }
832     if (match == char(-1)) return false;
833     procp->count_stack += llkCycle;
834     if (procp->count_stack < llkStateTimeoutMs[llkStateStack]) return false;
835     LOG(WARNING) << "Found " << matched_stack_symbol << " in stack for pid " << procp->pid;
836     return true;
837 }
838 #endif
839 
840 // Primary ABA mitigation watching last time schedule activity happened
llkCheckSchedUpdate(proc * procp,const std::string & piddir)841 void llkCheckSchedUpdate(proc* procp, const std::string& piddir) {
842     // Audit finds /proc/<tid>/sched is just over 1K, and
843     // is rarely larger than 2K, even less on Android.
844     // For example, the "se.avg.lastUpdateTime" field we are
845     // interested in typically within the primary set in
846     // the first 1K.
847     //
848     // Proc entries can not be read >1K atomically via libbase,
849     // but if there are problems we assume at least a few
850     // samples of reads occur before we take any real action.
851     std::string schedString = ReadFile(piddir + "/sched");
852     if (schedString.empty()) {
853         // /schedstat is not as standardized, but in 3.1+
854         // Android devices, the third field is nr_switches
855         // from /sched:
856         schedString = ReadFile(piddir + "/schedstat");
857         if (schedString.empty()) {
858             return;
859         }
860         auto val = static_cast<unsigned long long>(-1);
861         if (((::sscanf(schedString.c_str(), "%*d %*d %llu", &val)) == 1) &&
862             (val != static_cast<unsigned long long>(-1)) && (val != 0) &&
863             (val != procp->nrSwitches)) {
864             procp->nrSwitches = val;
865             procp->count = 0ms;
866             procp->killed = !llkTestWithKill;
867         }
868         return;
869     }
870 
871     auto val = getSchedValue(schedString, "\nse.avg.lastUpdateTime");
872     if (val == -1) {
873         val = getSchedValue(schedString, "\nse.svg.last_update_time");
874     }
875     if (val != -1) {
876         auto schedUpdate = nanoseconds(val);
877         if (schedUpdate != procp->schedUpdate) {
878             procp->schedUpdate = schedUpdate;
879             procp->count = 0ms;
880             procp->killed = !llkTestWithKill;
881         }
882     }
883 
884     val = getSchedValue(schedString, "\nnr_switches");
885     if (val != -1) {
886         if (static_cast<uint64_t>(val) != procp->nrSwitches) {
887             procp->nrSwitches = val;
888             procp->count = 0ms;
889             procp->killed = !llkTestWithKill;
890         }
891     }
892 }
893 
llkLogConfig(void)894 void llkLogConfig(void) {
895     LOG(INFO) << "ro.config.low_ram=" << llkFormat(llkLowRam) << "\n"
896               << LLK_ENABLE_SYSRQ_T_PROPERTY "=" << llkFormat(llkEnableSysrqT) << "\n"
897               << LLK_ENABLE_PROPERTY "=" << llkFormat(llkEnable) << "\n"
898               << KHT_ENABLE_PROPERTY "=" << llkFormat(khtEnable) << "\n"
899               << LLK_MLOCKALL_PROPERTY "=" << llkFormat(llkMlockall) << "\n"
900               << LLK_KILLTEST_PROPERTY "=" << llkFormat(llkTestWithKill) << "\n"
901               << KHT_TIMEOUT_PROPERTY "=" << llkFormat(khtTimeout) << "\n"
902               << LLK_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkTimeoutMs) << "\n"
903               << LLK_D_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateD]) << "\n"
904               << LLK_Z_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateZ]) << "\n"
905 #ifdef __PTRACE_ENABLED__
906               << LLK_STACK_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateStack])
907               << "\n"
908 #endif
909               << LLK_CHECK_MS_PROPERTY "=" << llkFormat(llkCheckMs) << "\n"
910 #ifdef __PTRACE_ENABLED__
911               << LLK_CHECK_STACK_PROPERTY "=" << llkFormat(llkCheckStackSymbols) << "\n"
912               << LLK_BLACKLIST_STACK_PROPERTY "=" << llkFormat(llkBlacklistStack) << "\n"
913 #endif
914               << LLK_BLACKLIST_PROCESS_PROPERTY "=" << llkFormat(llkBlacklistProcess) << "\n"
915               << LLK_BLACKLIST_PARENT_PROPERTY "=" << llkFormat(llkBlacklistParent)
916               << llkFormat(llkBlacklistParentAndChild, true) << "\n"
917               << LLK_BLACKLIST_UID_PROPERTY "=" << llkFormat(llkBlacklistUid);
918 }
919 
llkThread(void * obj)920 void* llkThread(void* obj) {
921     prctl(PR_SET_DUMPABLE, 0);
922 
923     LOG(INFO) << "started";
924 
925     std::string name = std::to_string(::gettid());
926     if (!llkSkipName(name)) {
927         llkBlacklistProcess.emplace(name);
928     }
929     name = static_cast<const char*>(obj);
930     prctl(PR_SET_NAME, name.c_str());
931     if (__predict_false(!llkSkipName(name))) {
932         llkBlacklistProcess.insert(name);
933     }
934     // No longer modifying llkBlacklistProcess.
935     llkRunning = true;
936     llkLogConfig();
937     while (llkRunning) {
938         ::usleep(duration_cast<microseconds>(llkCheck(true)).count());
939     }
940     // NOTREACHED
941     LOG(INFO) << "exiting";
942     return nullptr;
943 }
944 
945 }  // namespace
946 
llkCheck(bool checkRunning)947 milliseconds llkCheck(bool checkRunning) {
948     if (!llkEnable || (checkRunning != llkRunning)) {
949         return milliseconds::max();
950     }
951 
952     // Reset internal watchdog, which is a healthy engineering margin of
953     // double the maximum wait or cycle time for the mainloop that calls us.
954     //
955     // This alarm is effectively the live lock detection of llkd, as
956     // we understandably can not monitor ourselves otherwise.
957     ::alarm(duration_cast<seconds>(llkTimeoutMs * 2).count());
958 
959     // kernel jiffy precision fastest acquisition
960     static timespec last;
961     timespec now;
962     ::clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
963     auto ms = llkGetTimespecDiffMs(&last, &now);
964     if (ms < llkCycle) {
965         return llkCycle - ms;
966     }
967     last = now;
968 
969     LOG(VERBOSE) << "opendir(\"" << procdir << "\")";
970     if (__predict_false(!llkTopDirectory)) {
971         // gid containing AID_READPROC required
972         llkTopDirectory.reset(procdir);
973         if (__predict_false(!llkTopDirectory)) {
974             // Most likely reason we could be here is a resource limit.
975             // Keep our processing down to a minimum, but not so low that
976             // we do not recover in a timely manner should the issue be
977             // transitory.
978             LOG(DEBUG) << "opendir(\"" << procdir << "\") failed";
979             return llkTimeoutMs;
980         }
981     }
982 
983     for (auto& it : tids) {
984         it.second.updated = false;
985     }
986 
987     auto prevUpdate = llkUpdate;
988     llkUpdate += ms;
989     ms -= llkCycle;
990     auto myPid = ::getpid();
991     auto myTid = ::gettid();
992     auto dump = true;
993     for (auto dp = llkTopDirectory.read(); dp != nullptr; dp = llkTopDirectory.read()) {
994         std::string piddir;
995 
996         if (!getValidTidDir(dp, &piddir)) {
997             continue;
998         }
999 
1000         // Get the process tasks
1001         std::string taskdir = piddir + "/task/";
1002         int pid = -1;
1003         LOG(VERBOSE) << "+opendir(\"" << taskdir << "\")";
1004         dir taskDirectory(taskdir);
1005         if (__predict_false(!taskDirectory)) {
1006             LOG(DEBUG) << "+opendir(\"" << taskdir << "\") failed";
1007         }
1008         for (auto tp = taskDirectory.read(dir::task, dp); tp != nullptr;
1009              tp = taskDirectory.read(dir::task)) {
1010             if (!getValidTidDir(tp, &piddir)) {
1011                 continue;
1012             }
1013 
1014             // Get the process stat
1015             std::string stat = ReadFile(piddir + "/stat");
1016             if (stat.empty()) {
1017                 continue;
1018             }
1019             unsigned tid = -1;
1020             char pdir[TASK_COMM_LEN + 1];
1021             char state = '?';
1022             unsigned ppid = -1;
1023             unsigned utime = -1;
1024             unsigned stime = -1;
1025             int dummy;
1026             pdir[0] = '\0';
1027             // tid should not change value
1028             auto match = ::sscanf(
1029                 stat.c_str(),
1030                 "%u (%" ___STRING(
1031                     TASK_COMM_LEN) "[^)]) %c %u %*d %*d %*d %*d %*d %*d %*d %*d %*d %u %u %d",
1032                 &tid, pdir, &state, &ppid, &utime, &stime, &dummy);
1033             if (pid == -1) {
1034                 pid = tid;
1035             }
1036             LOG(VERBOSE) << "match " << match << ' ' << tid << " (" << pdir << ") " << state << ' '
1037                          << ppid << " ... " << utime << ' ' << stime << ' ' << dummy;
1038             if (match != 7) {
1039                 continue;
1040             }
1041 
1042             auto procp = llkTidLookup(tid);
1043             if (procp == nullptr) {
1044                 procp = llkTidAlloc(tid, pid, ppid, pdir, utime + stime, state);
1045             } else {
1046                 // comm can change ...
1047                 procp->setComm(pdir);
1048                 procp->updated = true;
1049                 // pid/ppid/tid wrap?
1050                 if (((procp->update != prevUpdate) && (procp->update != llkUpdate)) ||
1051                     (procp->ppid != ppid) || (procp->pid != pid)) {
1052                     procp->reset();
1053                 } else if (procp->time != (utime + stime)) {  // secondary ABA.
1054                     // watching utime+stime granularity jiffy
1055                     procp->state = '?';
1056                 }
1057                 procp->update = llkUpdate;
1058                 procp->pid = pid;
1059                 procp->ppid = ppid;
1060                 procp->time = utime + stime;
1061                 if (procp->state != state) {
1062                     procp->count = 0ms;
1063                     procp->killed = !llkTestWithKill;
1064                     procp->state = state;
1065                 } else {
1066                     procp->count += llkCycle;
1067                 }
1068             }
1069 
1070             // Filter checks in intuitive order of CPU cost to evaluate
1071             // If tid unique continue, if ppid or pid unique break
1072 
1073             if (pid == myPid) {
1074                 break;
1075             }
1076 #ifdef __PTRACE_ENABLED__
1077             // if no stack monitoring, we can quickly exit here
1078             if (!llkIsMonitorState(state) && llkCheckStackSymbols.empty()) {
1079                 continue;
1080             }
1081 #else
1082             if (!llkIsMonitorState(state)) continue;
1083 #endif
1084             if ((tid == myTid) || llkSkipPid(tid)) {
1085                 continue;
1086             }
1087             if (llkSkipPpid(ppid)) {
1088                 break;
1089             }
1090 
1091             auto process_comm = procp->getComm();
1092             if (llkSkipName(process_comm)) {
1093                 continue;
1094             }
1095             if (llkSkipName(procp->getCmdline())) {
1096                 break;
1097             }
1098             if (llkSkipName(android::base::Basename(procp->getCmdline()))) {
1099                 break;
1100             }
1101 
1102             auto pprocp = llkTidLookup(ppid);
1103             if (pprocp == nullptr) {
1104                 pprocp = llkTidAlloc(ppid, ppid, 0, "", 0, '?');
1105             }
1106             if (pprocp) {
1107                 if (llkSkipPproc(pprocp, procp)) break;
1108                 if (llkSkipProc(pprocp, llkBlacklistParent)) break;
1109             } else {
1110                 if (llkSkipName(std::to_string(ppid), llkBlacklistParent)) break;
1111             }
1112 
1113             if ((llkBlacklistUid.size() != 0) && llkSkipUid(procp->getUid())) {
1114                 continue;
1115             }
1116 
1117             // ABA mitigation watching last time schedule activity happened
1118             llkCheckSchedUpdate(procp, piddir);
1119 
1120 #ifdef __PTRACE_ENABLED__
1121             auto stuck = llkCheckStack(procp, piddir);
1122             if (llkIsMonitorState(state)) {
1123                 if (procp->count >= llkStateTimeoutMs[(state == 'Z') ? llkStateZ : llkStateD]) {
1124                     stuck = true;
1125                 } else if (procp->count != 0ms) {
1126                     LOG(VERBOSE) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->"
1127                                  << pid << "->" << tid << ' ' << process_comm;
1128                 }
1129             }
1130             if (!stuck) continue;
1131 #else
1132             if (procp->count >= llkStateTimeoutMs[(state == 'Z') ? llkStateZ : llkStateD]) {
1133                 if (procp->count != 0ms) {
1134                     LOG(VERBOSE) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->"
1135                                  << pid << "->" << tid << ' ' << process_comm;
1136                 }
1137                 continue;
1138             }
1139 #endif
1140 
1141             // We have to kill it to determine difference between live lock
1142             // and persistent state blocked on a resource.  Is there something
1143             // wrong with a process that has no forward scheduling progress in
1144             // Z or D?  Yes, generally means improper accounting in the
1145             // process, but not always ...
1146             //
1147             // Whomever we hit with a test kill must accept the Android
1148             // Aphorism that everything can be burned to the ground and
1149             // must survive.
1150             if (procp->killed == false) {
1151                 procp->killed = true;
1152                 // confirm: re-read uid before committing to a panic.
1153                 procp->uid = -1;
1154                 switch (state) {
1155                     case 'Z':  // kill ppid to free up a Zombie
1156                         // Killing init will kernel panic without diagnostics
1157                         // so skip right to controlled kernel panic with
1158                         // diagnostics.
1159                         if (ppid == initPid) {
1160                             break;
1161                         }
1162                         LOG(WARNING) << "Z " << llkFormat(procp->count) << ' ' << ppid << "->"
1163                                      << pid << "->" << tid << ' ' << process_comm << " [kill]";
1164                         if ((llkKillOneProcess(pprocp, procp) >= 0) ||
1165                             (llkKillOneProcess(ppid, procp) >= 0)) {
1166                             continue;
1167                         }
1168                         break;
1169 
1170                     case 'D':  // kill tid to free up an uninterruptible D
1171                         // If ABA is doing its job, we would not need or
1172                         // want the following.  Test kill is a Hail Mary
1173                         // to make absolutely sure there is no forward
1174                         // scheduling progress.  The cost when ABA is
1175                         // not working is we kill a process that likes to
1176                         // stay in 'D' state, instead of panicing the
1177                         // kernel (worse).
1178                     default:
1179                         LOG(WARNING) << state << ' ' << llkFormat(procp->count) << ' ' << pid
1180                                      << "->" << tid << ' ' << process_comm << " [kill]";
1181                         if ((llkKillOneProcess(llkTidLookup(pid), procp) >= 0) ||
1182                             (llkKillOneProcess(pid, state, tid) >= 0) ||
1183                             (llkKillOneProcess(procp, procp) >= 0) ||
1184                             (llkKillOneProcess(tid, state, tid) >= 0)) {
1185                             continue;
1186                         }
1187                         break;
1188                 }
1189             }
1190             // We are here because we have confirmed kernel live-lock
1191             const auto message = state + " "s + llkFormat(procp->count) + " " +
1192                                  std::to_string(ppid) + "->" + std::to_string(pid) + "->" +
1193                                  std::to_string(tid) + " " + process_comm + " [panic]";
1194             llkPanicKernel(dump, tid,
1195                            (state == 'Z') ? "zombie" : (state == 'D') ? "driver" : "sleeping",
1196                            message);
1197             dump = false;
1198         }
1199         LOG(VERBOSE) << "+closedir()";
1200     }
1201     llkTopDirectory.rewind();
1202     LOG(VERBOSE) << "closedir()";
1203 
1204     // garbage collection of old process references
1205     for (auto p = tids.begin(); p != tids.end();) {
1206         if (!p->second.updated) {
1207             IF_ALOG(LOG_VERBOSE, LOG_TAG) {
1208                 std::string ppidCmdline = llkProcGetName(p->second.ppid, nullptr, nullptr);
1209                 if (!ppidCmdline.empty()) ppidCmdline = "(" + ppidCmdline + ")";
1210                 std::string pidCmdline;
1211                 if (p->second.pid != p->second.tid) {
1212                     pidCmdline = llkProcGetName(p->second.pid, nullptr, p->second.getCmdline());
1213                     if (!pidCmdline.empty()) pidCmdline = "(" + pidCmdline + ")";
1214                 }
1215                 std::string tidCmdline =
1216                     llkProcGetName(p->second.tid, p->second.getComm(), p->second.getCmdline());
1217                 if (!tidCmdline.empty()) tidCmdline = "(" + tidCmdline + ")";
1218                 LOG(VERBOSE) << "thread " << p->second.ppid << ppidCmdline << "->" << p->second.pid
1219                              << pidCmdline << "->" << p->second.tid << tidCmdline << " removed";
1220             }
1221             p = tids.erase(p);
1222         } else {
1223             ++p;
1224         }
1225     }
1226     if (__predict_false(tids.empty())) {
1227         llkTopDirectory.reset();
1228     }
1229 
1230     llkCycle = llkCheckMs;
1231 
1232     timespec end;
1233     ::clock_gettime(CLOCK_MONOTONIC_COARSE, &end);
1234     auto milli = llkGetTimespecDiffMs(&now, &end);
1235     LOG((milli > 10s) ? ERROR : (milli > 1s) ? WARNING : VERBOSE) << "sample " << llkFormat(milli);
1236 
1237     // cap to minimum sleep for 1 second since last cycle
1238     if (llkCycle < (ms + 1s)) {
1239         return 1s;
1240     }
1241     return llkCycle - ms;
1242 }
1243 
llkCheckMilliseconds()1244 unsigned llkCheckMilliseconds() {
1245     return duration_cast<milliseconds>(llkCheck()).count();
1246 }
1247 
llkCheckEng(const std::string & property)1248 bool llkCheckEng(const std::string& property) {
1249     return android::base::GetProperty(property, "eng") == "eng";
1250 }
1251 
llkInit(const char * threadname)1252 bool llkInit(const char* threadname) {
1253     auto debuggable = android::base::GetBoolProperty("ro.debuggable", false);
1254     llkLowRam = android::base::GetBoolProperty("ro.config.low_ram", false);
1255     llkEnableSysrqT &= !llkLowRam;
1256     if (debuggable) {
1257         llkEnableSysrqT |= llkCheckEng(LLK_ENABLE_SYSRQ_T_PROPERTY);
1258         if (!LLK_ENABLE_DEFAULT) {  // NB: default is currently true ...
1259             llkEnable |= llkCheckEng(LLK_ENABLE_PROPERTY);
1260             khtEnable |= llkCheckEng(KHT_ENABLE_PROPERTY);
1261         }
1262     }
1263     llkEnableSysrqT = android::base::GetBoolProperty(LLK_ENABLE_SYSRQ_T_PROPERTY, llkEnableSysrqT);
1264     llkEnable = android::base::GetBoolProperty(LLK_ENABLE_PROPERTY, llkEnable);
1265     if (llkEnable && !llkTopDirectory.reset(procdir)) {
1266         // Most likely reason we could be here is llkd was started
1267         // incorrectly without the readproc permissions.  Keep our
1268         // processing down to a minimum.
1269         llkEnable = false;
1270     }
1271     khtEnable = android::base::GetBoolProperty(KHT_ENABLE_PROPERTY, khtEnable);
1272     llkMlockall = android::base::GetBoolProperty(LLK_MLOCKALL_PROPERTY, llkMlockall);
1273     llkTestWithKill = android::base::GetBoolProperty(LLK_KILLTEST_PROPERTY, llkTestWithKill);
1274     // if LLK_TIMOUT_MS_PROPERTY was not set, we will use a set
1275     // KHT_TIMEOUT_PROPERTY as co-operative guidance for the default value.
1276     khtTimeout = GetUintProperty(KHT_TIMEOUT_PROPERTY, khtTimeout);
1277     if (khtTimeout == 0s) {
1278         khtTimeout = duration_cast<seconds>(llkTimeoutMs * (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT) /
1279                                             LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1280     }
1281     llkTimeoutMs =
1282         khtTimeout * LLK_CHECKS_PER_TIMEOUT_DEFAULT / (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1283     llkTimeoutMs = GetUintProperty(LLK_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1284     llkValidate();  // validate llkTimeoutMs, llkCheckMs and llkCycle
1285     llkStateTimeoutMs[llkStateD] = GetUintProperty(LLK_D_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1286     llkStateTimeoutMs[llkStateZ] = GetUintProperty(LLK_Z_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1287 #ifdef __PTRACE_ENABLED__
1288     llkStateTimeoutMs[llkStateStack] = GetUintProperty(LLK_STACK_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1289 #endif
1290     llkCheckMs = GetUintProperty(LLK_CHECK_MS_PROPERTY, llkCheckMs);
1291     llkValidate();  // validate all (effectively minus llkTimeoutMs)
1292 #ifdef __PTRACE_ENABLED__
1293     if (debuggable) {
1294         llkCheckStackSymbols = llkSplit(LLK_CHECK_STACK_PROPERTY, LLK_CHECK_STACK_DEFAULT);
1295     }
1296     std::string defaultBlacklistStack(LLK_BLACKLIST_STACK_DEFAULT);
1297     if (!debuggable) defaultBlacklistStack += ",logd,/system/bin/logd";
1298     llkBlacklistStack = llkSplit(LLK_BLACKLIST_STACK_PROPERTY, defaultBlacklistStack);
1299 #endif
1300     std::string defaultBlacklistProcess(
1301         std::to_string(kernelPid) + "," + std::to_string(initPid) + "," +
1302         std::to_string(kthreaddPid) + "," + std::to_string(::getpid()) + "," +
1303         std::to_string(::gettid()) + "," LLK_BLACKLIST_PROCESS_DEFAULT);
1304     if (threadname) {
1305         defaultBlacklistProcess += ","s + threadname;
1306     }
1307     for (int cpu = 1; cpu < get_nprocs_conf(); ++cpu) {
1308         defaultBlacklistProcess += ",[watchdog/" + std::to_string(cpu) + "]";
1309     }
1310     llkBlacklistProcess = llkSplit(LLK_BLACKLIST_PROCESS_PROPERTY, defaultBlacklistProcess);
1311     if (!llkSkipName("[khungtaskd]")) {  // ALWAYS ignore as special
1312         llkBlacklistProcess.emplace("[khungtaskd]");
1313     }
1314     llkBlacklistParent = llkSplit(LLK_BLACKLIST_PARENT_PROPERTY,
1315                                   std::to_string(kernelPid) + "," + std::to_string(kthreaddPid) +
1316                                           "," LLK_BLACKLIST_PARENT_DEFAULT);
1317     // derive llkBlacklistParentAndChild by moving entries with '&' from above
1318     for (auto it = llkBlacklistParent.begin(); it != llkBlacklistParent.end();) {
1319         auto pos = it->find('&');
1320         if (pos == std::string::npos) {
1321             ++it;
1322             continue;
1323         }
1324         auto parent = it->substr(0, pos);
1325         auto child = it->substr(pos + 1);
1326         it = llkBlacklistParent.erase(it);
1327 
1328         auto found = llkBlacklistParentAndChild.find(parent);
1329         if (found == llkBlacklistParentAndChild.end()) {
1330             llkBlacklistParentAndChild.emplace(std::make_pair(
1331                     std::move(parent), std::unordered_set<std::string>({std::move(child)})));
1332         } else {
1333             found->second.emplace(std::move(child));
1334         }
1335     }
1336 
1337     llkBlacklistUid = llkSplit(LLK_BLACKLIST_UID_PROPERTY, LLK_BLACKLIST_UID_DEFAULT);
1338 
1339     // internal watchdog
1340     ::signal(SIGALRM, llkAlarmHandler);
1341 
1342     // kernel hung task configuration? Otherwise leave it as-is
1343     if (khtEnable) {
1344         // EUID must be AID_ROOT to write to /proc/sys/kernel/ nodes, there
1345         // are no capability overrides.  For security reasons we do not want
1346         // to run as AID_ROOT.  We may not be able to write them successfully,
1347         // we will try, but the least we can do is read the values back to
1348         // confirm expectations and report whether configured or not.
1349         auto configured = llkWriteStringToFileConfirm(std::to_string(khtTimeout.count()),
1350                                                       "/proc/sys/kernel/hung_task_timeout_secs");
1351         if (configured) {
1352             llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_warnings");
1353             llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_check_count");
1354             configured = llkWriteStringToFileConfirm("1", "/proc/sys/kernel/hung_task_panic");
1355         }
1356         if (configured) {
1357             LOG(INFO) << "[khungtaskd] configured";
1358         } else {
1359             LOG(WARNING) << "[khungtaskd] not configurable";
1360         }
1361     }
1362 
1363     bool logConfig = true;
1364     if (llkEnable) {
1365         if (llkMlockall &&
1366             // MCL_ONFAULT pins pages as they fault instead of loading
1367             // everything immediately all at once. (Which would be bad,
1368             // because as of this writing, we have a lot of mapped pages we
1369             // never use.) Old kernels will see MCL_ONFAULT and fail with
1370             // EINVAL; we ignore this failure.
1371             //
1372             // N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
1373             // pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
1374             // in pages.
1375 
1376             // CAP_IPC_LOCK required
1377             mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
1378             PLOG(WARNING) << "mlockall failed ";
1379         }
1380 
1381         if (threadname) {
1382             pthread_attr_t attr;
1383 
1384             if (!pthread_attr_init(&attr)) {
1385                 sched_param param;
1386 
1387                 memset(&param, 0, sizeof(param));
1388                 pthread_attr_setschedparam(&attr, &param);
1389                 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1390                 if (!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1391                     pthread_t thread;
1392                     if (!pthread_create(&thread, &attr, llkThread, const_cast<char*>(threadname))) {
1393                         // wait a second for thread to start
1394                         for (auto retry = 50; retry && !llkRunning; --retry) {
1395                             ::usleep(20000);
1396                         }
1397                         logConfig = !llkRunning;  // printed in llkd context?
1398                     } else {
1399                         LOG(ERROR) << "failed to spawn llkd thread";
1400                     }
1401                 } else {
1402                     LOG(ERROR) << "failed to detach llkd thread";
1403                 }
1404                 pthread_attr_destroy(&attr);
1405             } else {
1406                 LOG(ERROR) << "failed to allocate attibutes for llkd thread";
1407             }
1408         }
1409     } else {
1410         LOG(DEBUG) << "[khungtaskd] left unconfigured";
1411     }
1412     if (logConfig) {
1413         llkLogConfig();
1414     }
1415 
1416     return llkEnable;
1417 }
1418