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