• 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 #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",
119 // "keystore2", or "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__anonc18104f70111::proc310     void setComm(const char* _comm) { strncpy(comm + 1, _comm, sizeof(comm) - 2); }
311 
setFrozen__anonc18104f70111::proc312     void setFrozen(bool _frozen) { frozen = _frozen; }
313 
proc__anonc18104f70111::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__anonc18104f70111::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__anonc18104f70111::proc366     const char* getCmdline(void) {
367         if (!cmdlineValid) {
368             cmdline = llkProcGetName(tid);
369             cmdlineValid = true;
370         }
371         return cmdline.c_str();
372     }
373 
getUid__anonc18104f70111::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__anonc18104f70111::proc381     bool isFrozen() { return frozen; }
382 
reset__anonc18104f70111::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 * android::base::HwTimeoutMultiplier())
966                     .count());
967 
968     // kernel jiffy precision fastest acquisition
969     static timespec last;
970     timespec now;
971     ::clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
972     auto ms = llkGetTimespecDiffMs(&last, &now);
973     if (ms < llkCycle) {
974         return llkCycle - ms;
975     }
976     last = now;
977 
978     LOG(VERBOSE) << "opendir(\"" << procdir << "\")";
979     if (__predict_false(!llkTopDirectory)) {
980         // gid containing AID_READPROC required
981         llkTopDirectory.reset(procdir);
982         if (__predict_false(!llkTopDirectory)) {
983             // Most likely reason we could be here is a resource limit.
984             // Keep our processing down to a minimum, but not so low that
985             // we do not recover in a timely manner should the issue be
986             // transitory.
987             LOG(DEBUG) << "opendir(\"" << procdir << "\") failed";
988             return llkTimeoutMs;
989         }
990     }
991 
992     for (auto& it : tids) {
993         it.second.updated = false;
994     }
995 
996     auto prevUpdate = llkUpdate;
997     llkUpdate += ms;
998     ms -= llkCycle;
999     auto myPid = ::getpid();
1000     auto myTid = ::gettid();
1001     auto dump = true;
1002     for (auto dp = llkTopDirectory.read(); dp != nullptr; dp = llkTopDirectory.read()) {
1003         std::string piddir;
1004 
1005         if (!getValidTidDir(dp, &piddir)) {
1006             continue;
1007         }
1008 
1009         // Get the process tasks
1010         std::string taskdir = piddir + "/task/";
1011         int pid = -1;
1012         LOG(VERBOSE) << "+opendir(\"" << taskdir << "\")";
1013         dir taskDirectory(taskdir);
1014         if (__predict_false(!taskDirectory)) {
1015             LOG(DEBUG) << "+opendir(\"" << taskdir << "\") failed";
1016         }
1017         for (auto tp = taskDirectory.read(dir::task, dp); tp != nullptr;
1018              tp = taskDirectory.read(dir::task)) {
1019             if (!getValidTidDir(tp, &piddir)) {
1020                 continue;
1021             }
1022 
1023             // Get the process stat
1024             std::string stat = ReadFile(piddir + "/stat");
1025             if (stat.empty()) {
1026                 continue;
1027             }
1028             unsigned tid = -1;
1029             char pdir[TASK_COMM_LEN + 1];
1030             char state = '?';
1031             unsigned ppid = -1;
1032             unsigned utime = -1;
1033             unsigned stime = -1;
1034             int dummy;
1035             pdir[0] = '\0';
1036             // tid should not change value
1037             auto match = ::sscanf(
1038                 stat.c_str(),
1039                 "%u (%" ___STRING(
1040                     TASK_COMM_LEN) "[^)]) %c %u %*d %*d %*d %*d %*d %*d %*d %*d %*d %u %u %d",
1041                 &tid, pdir, &state, &ppid, &utime, &stime, &dummy);
1042             if (pid == -1) {
1043                 pid = tid;
1044             }
1045             LOG(VERBOSE) << "match " << match << ' ' << tid << " (" << pdir << ") " << state << ' '
1046                          << ppid << " ... " << utime << ' ' << stime << ' ' << dummy;
1047             if (match != 7) {
1048                 continue;
1049             }
1050 
1051             // Get the process cgroup
1052             auto cgroup = ReadFile(piddir + "/cgroup");
1053             auto frozen = cgroup.find(":freezer:/frozen") != std::string::npos;
1054 
1055             auto procp = llkTidLookup(tid);
1056             if (procp == nullptr) {
1057                 procp = llkTidAlloc(tid, pid, ppid, pdir, utime + stime, state, frozen);
1058             } else {
1059                 // comm can change ...
1060                 procp->setComm(pdir);
1061                 // frozen can change, too...
1062                 procp->setFrozen(frozen);
1063                 procp->updated = true;
1064                 // pid/ppid/tid wrap?
1065                 if (((procp->update != prevUpdate) && (procp->update != llkUpdate)) ||
1066                     (procp->ppid != ppid) || (procp->pid != pid)) {
1067                     procp->reset();
1068                 } else if (procp->time != (utime + stime)) {  // secondary ABA.
1069                     // watching utime+stime granularity jiffy
1070                     procp->state = '?';
1071                 }
1072                 procp->update = llkUpdate;
1073                 procp->pid = pid;
1074                 procp->ppid = ppid;
1075                 procp->time = utime + stime;
1076                 if (procp->state != state) {
1077                     procp->count = 0ms;
1078                     procp->killed = !llkTestWithKill;
1079                     procp->state = state;
1080                 } else {
1081                     procp->count += llkCycle;
1082                 }
1083             }
1084 
1085             // Filter checks in intuitive order of CPU cost to evaluate
1086             // If tid unique continue, if ppid or pid unique break
1087 
1088             if (pid == myPid) {
1089                 break;
1090             }
1091 #ifdef __PTRACE_ENABLED__
1092             // if no stack monitoring, we can quickly exit here
1093             if (!llkIsMonitorState(state) && llkCheckStackSymbols.empty()) {
1094                 continue;
1095             }
1096 #else
1097             if (!llkIsMonitorState(state)) continue;
1098 #endif
1099             if ((tid == myTid) || llkSkipPid(tid)) {
1100                 continue;
1101             }
1102             if (procp->isFrozen()) {
1103                 break;
1104             }
1105             if (llkSkipPpid(ppid)) {
1106                 break;
1107             }
1108 
1109             auto process_comm = procp->getComm();
1110             if (llkSkipName(process_comm)) {
1111                 continue;
1112             }
1113             if (llkSkipName(procp->getCmdline())) {
1114                 break;
1115             }
1116             if (llkSkipName(android::base::Basename(procp->getCmdline()))) {
1117                 break;
1118             }
1119 
1120             auto pprocp = llkTidLookup(ppid);
1121             if (pprocp == nullptr) {
1122                 pprocp = llkTidAlloc(ppid, ppid, 0, "", 0, '?', false);
1123             }
1124             if (pprocp) {
1125                 if (llkSkipPproc(pprocp, procp)) break;
1126                 if (llkSkipProc(pprocp, llkIgnorelistParent)) break;
1127             } else {
1128                 if (llkSkipName(std::to_string(ppid), llkIgnorelistParent)) break;
1129             }
1130 
1131             if ((llkIgnorelistUid.size() != 0) && llkSkipUid(procp->getUid())) {
1132                 continue;
1133             }
1134 
1135             // ABA mitigation watching last time schedule activity happened
1136             llkCheckSchedUpdate(procp, piddir);
1137 
1138 #ifdef __PTRACE_ENABLED__
1139             auto stuck = llkCheckStack(procp, piddir);
1140             if (llkIsMonitorState(state)) {
1141                 if (procp->count >= llkStateTimeoutMs[(state == 'Z') ? llkStateZ : llkStateD]) {
1142                     stuck = true;
1143                 } else if (procp->count != 0ms) {
1144                     LOG(VERBOSE) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->"
1145                                  << pid << "->" << tid << ' ' << process_comm;
1146                 }
1147             }
1148             if (!stuck) continue;
1149 #else
1150             if (procp->count >= llkStateTimeoutMs[(state == 'Z') ? llkStateZ : llkStateD]) {
1151                 if (procp->count != 0ms) {
1152                     LOG(VERBOSE) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->"
1153                                  << pid << "->" << tid << ' ' << process_comm;
1154                 }
1155                 continue;
1156             }
1157 #endif
1158 
1159             // We have to kill it to determine difference between live lock
1160             // and persistent state blocked on a resource.  Is there something
1161             // wrong with a process that has no forward scheduling progress in
1162             // Z or D?  Yes, generally means improper accounting in the
1163             // process, but not always ...
1164             //
1165             // Whomever we hit with a test kill must accept the Android
1166             // Aphorism that everything can be burned to the ground and
1167             // must survive.
1168             if (procp->killed == false) {
1169                 procp->killed = true;
1170                 // confirm: re-read uid before committing to a panic.
1171                 procp->uid = -1;
1172                 switch (state) {
1173                     case 'Z':  // kill ppid to free up a Zombie
1174                         // Killing init will kernel panic without diagnostics
1175                         // so skip right to controlled kernel panic with
1176                         // diagnostics.
1177                         if (ppid == initPid) {
1178                             break;
1179                         }
1180                         LOG(WARNING) << "Z " << llkFormat(procp->count) << ' ' << ppid << "->"
1181                                      << pid << "->" << tid << ' ' << process_comm << " [kill]";
1182                         if ((llkKillOneProcess(pprocp, procp) >= 0) ||
1183                             (llkKillOneProcess(ppid, procp) >= 0)) {
1184                             continue;
1185                         }
1186                         break;
1187 
1188                     case 'D':  // kill tid to free up an uninterruptible D
1189                         // If ABA is doing its job, we would not need or
1190                         // want the following.  Test kill is a Hail Mary
1191                         // to make absolutely sure there is no forward
1192                         // scheduling progress.  The cost when ABA is
1193                         // not working is we kill a process that likes to
1194                         // stay in 'D' state, instead of panicing the
1195                         // kernel (worse).
1196                     default:
1197                         LOG(WARNING) << state << ' ' << llkFormat(procp->count) << ' ' << pid
1198                                      << "->" << tid << ' ' << process_comm << " [kill]";
1199                         if ((llkKillOneProcess(llkTidLookup(pid), procp) >= 0) ||
1200                             (llkKillOneProcess(pid, state, tid) >= 0) ||
1201                             (llkKillOneProcess(procp, procp) >= 0) ||
1202                             (llkKillOneProcess(tid, state, tid) >= 0)) {
1203                             continue;
1204                         }
1205                         break;
1206                 }
1207             }
1208             // We are here because we have confirmed kernel live-lock
1209             std::vector<std::string> threads;
1210             auto taskdir = procdir + std::to_string(tid) + "/task/";
1211             dir taskDirectory(taskdir);
1212             for (auto tp = taskDirectory.read(); tp != nullptr; tp = taskDirectory.read()) {
1213                 std::string piddir;
1214                 if (getValidTidDir(tp, &piddir))
1215                     threads.push_back(android::base::Basename(piddir));
1216             }
1217             const auto message = state + " "s + llkFormat(procp->count) + " " +
1218                                  std::to_string(ppid) + "->" + std::to_string(pid) + "->" +
1219                                  std::to_string(tid) + " " + process_comm + " [panic]\n" +
1220                                  "  thread group: {" + android::base::Join(threads, ",") +
1221                                  "}";
1222             llkPanicKernel(dump, tid,
1223                            (state == 'Z') ? "zombie" : (state == 'D') ? "driver" : "sleeping",
1224                            message);
1225             dump = false;
1226         }
1227         LOG(VERBOSE) << "+closedir()";
1228     }
1229     llkTopDirectory.rewind();
1230     LOG(VERBOSE) << "closedir()";
1231 
1232     // garbage collection of old process references
1233     for (auto p = tids.begin(); p != tids.end();) {
1234         if (!p->second.updated) {
1235             IF_ALOG(LOG_VERBOSE, LOG_TAG) {
1236                 std::string ppidCmdline = llkProcGetName(p->second.ppid, nullptr, nullptr);
1237                 if (!ppidCmdline.empty()) ppidCmdline = "(" + ppidCmdline + ")";
1238                 std::string pidCmdline;
1239                 if (p->second.pid != p->second.tid) {
1240                     pidCmdline = llkProcGetName(p->second.pid, nullptr, p->second.getCmdline());
1241                     if (!pidCmdline.empty()) pidCmdline = "(" + pidCmdline + ")";
1242                 }
1243                 std::string tidCmdline =
1244                     llkProcGetName(p->second.tid, p->second.getComm(), p->second.getCmdline());
1245                 if (!tidCmdline.empty()) tidCmdline = "(" + tidCmdline + ")";
1246                 LOG(VERBOSE) << "thread " << p->second.ppid << ppidCmdline << "->" << p->second.pid
1247                              << pidCmdline << "->" << p->second.tid << tidCmdline << " removed";
1248             }
1249             p = tids.erase(p);
1250         } else {
1251             ++p;
1252         }
1253     }
1254     if (__predict_false(tids.empty())) {
1255         llkTopDirectory.reset();
1256     }
1257 
1258     llkCycle = llkCheckMs;
1259 
1260     timespec end;
1261     ::clock_gettime(CLOCK_MONOTONIC_COARSE, &end);
1262     auto milli = llkGetTimespecDiffMs(&now, &end);
1263     LOG((milli > 10s) ? ERROR : (milli > 1s) ? WARNING : VERBOSE) << "sample " << llkFormat(milli);
1264 
1265     // cap to minimum sleep for 1 second since last cycle
1266     if (llkCycle < (ms + 1s)) {
1267         return 1s;
1268     }
1269     return llkCycle - ms;
1270 }
1271 
llkCheckMilliseconds()1272 unsigned llkCheckMilliseconds() {
1273     return duration_cast<milliseconds>(llkCheck()).count();
1274 }
1275 
llkCheckEng(const std::string & property)1276 bool llkCheckEng(const std::string& property) {
1277     return android::base::GetProperty(property, "eng") == "eng";
1278 }
1279 
llkInit(const char * threadname)1280 bool llkInit(const char* threadname) {
1281     auto debuggable = android::base::GetBoolProperty("ro.debuggable", false);
1282     llkLowRam = android::base::GetBoolProperty("ro.config.low_ram", false);
1283     llkEnableSysrqT &= !llkLowRam;
1284     if (debuggable) {
1285         llkEnableSysrqT |= llkCheckEng(LLK_ENABLE_SYSRQ_T_PROPERTY);
1286         if (!LLK_ENABLE_DEFAULT) {  // NB: default is currently true ...
1287             llkEnable |= llkCheckEng(LLK_ENABLE_PROPERTY);
1288             khtEnable |= llkCheckEng(KHT_ENABLE_PROPERTY);
1289         }
1290     }
1291     llkEnableSysrqT = android::base::GetBoolProperty(LLK_ENABLE_SYSRQ_T_PROPERTY, llkEnableSysrqT);
1292     llkEnable = android::base::GetBoolProperty(LLK_ENABLE_PROPERTY, llkEnable);
1293     if (llkEnable && !llkTopDirectory.reset(procdir)) {
1294         // Most likely reason we could be here is llkd was started
1295         // incorrectly without the readproc permissions.  Keep our
1296         // processing down to a minimum.
1297         llkEnable = false;
1298     }
1299     khtEnable = android::base::GetBoolProperty(KHT_ENABLE_PROPERTY, khtEnable);
1300     llkMlockall = android::base::GetBoolProperty(LLK_MLOCKALL_PROPERTY, llkMlockall);
1301     llkTestWithKill = android::base::GetBoolProperty(LLK_KILLTEST_PROPERTY, llkTestWithKill);
1302     // if LLK_TIMOUT_MS_PROPERTY was not set, we will use a set
1303     // KHT_TIMEOUT_PROPERTY as co-operative guidance for the default value.
1304     khtTimeout = GetUintProperty(KHT_TIMEOUT_PROPERTY, khtTimeout);
1305     if (khtTimeout == 0s) {
1306         khtTimeout = duration_cast<seconds>(llkTimeoutMs * (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT) /
1307                                             LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1308     }
1309     llkTimeoutMs =
1310         khtTimeout * LLK_CHECKS_PER_TIMEOUT_DEFAULT / (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1311     llkTimeoutMs = GetUintProperty(LLK_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1312     llkValidate();  // validate llkTimeoutMs, llkCheckMs and llkCycle
1313     llkStateTimeoutMs[llkStateD] = GetUintProperty(LLK_D_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1314     llkStateTimeoutMs[llkStateZ] = GetUintProperty(LLK_Z_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1315 #ifdef __PTRACE_ENABLED__
1316     llkStateTimeoutMs[llkStateStack] = GetUintProperty(LLK_STACK_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1317 #endif
1318     llkCheckMs = GetUintProperty(LLK_CHECK_MS_PROPERTY, llkCheckMs);
1319     llkValidate();  // validate all (effectively minus llkTimeoutMs)
1320 #ifdef __PTRACE_ENABLED__
1321     if (debuggable) {
1322         llkCheckStackSymbols = llkSplit(LLK_CHECK_STACK_PROPERTY, LLK_CHECK_STACK_DEFAULT);
1323     }
1324     std::string defaultIgnorelistStack(LLK_IGNORELIST_STACK_DEFAULT);
1325     if (!debuggable) defaultIgnorelistStack += ",logd,/system/bin/logd";
1326     llkIgnorelistStack = llkSplit(LLK_IGNORELIST_STACK_PROPERTY, defaultIgnorelistStack);
1327 #endif
1328     std::string defaultIgnorelistProcess(
1329             std::to_string(kernelPid) + "," + std::to_string(initPid) + "," +
1330             std::to_string(kthreaddPid) + "," + std::to_string(::getpid()) + "," +
1331             std::to_string(::gettid()) + "," LLK_IGNORELIST_PROCESS_DEFAULT);
1332     if (threadname) {
1333         defaultIgnorelistProcess += ","s + threadname;
1334     }
1335     for (int cpu = 1; cpu < get_nprocs_conf(); ++cpu) {
1336         defaultIgnorelistProcess += ",[watchdog/" + std::to_string(cpu) + "]";
1337     }
1338     llkIgnorelistProcess = llkSplit(LLK_IGNORELIST_PROCESS_PROPERTY, defaultIgnorelistProcess);
1339     if (!llkSkipName("[khungtaskd]")) {  // ALWAYS ignore as special
1340         llkIgnorelistProcess.emplace("[khungtaskd]");
1341     }
1342     llkIgnorelistParent = llkSplit(LLK_IGNORELIST_PARENT_PROPERTY,
1343                                    std::to_string(kernelPid) + "," + std::to_string(kthreaddPid) +
1344                                            "," LLK_IGNORELIST_PARENT_DEFAULT);
1345     // derive llkIgnorelistParentAndChild by moving entries with '&' from above
1346     for (auto it = llkIgnorelistParent.begin(); it != llkIgnorelistParent.end();) {
1347         auto pos = it->find('&');
1348         if (pos == std::string::npos) {
1349             ++it;
1350             continue;
1351         }
1352         auto parent = it->substr(0, pos);
1353         auto child = it->substr(pos + 1);
1354         it = llkIgnorelistParent.erase(it);
1355 
1356         auto found = llkIgnorelistParentAndChild.find(parent);
1357         if (found == llkIgnorelistParentAndChild.end()) {
1358             llkIgnorelistParentAndChild.emplace(std::make_pair(
1359                     std::move(parent), std::unordered_set<std::string>({std::move(child)})));
1360         } else {
1361             found->second.emplace(std::move(child));
1362         }
1363     }
1364 
1365     llkIgnorelistUid = llkSplit(LLK_IGNORELIST_UID_PROPERTY, LLK_IGNORELIST_UID_DEFAULT);
1366 
1367     // internal watchdog
1368     ::signal(SIGALRM, llkAlarmHandler);
1369 
1370     // kernel hung task configuration? Otherwise leave it as-is
1371     if (khtEnable) {
1372         // EUID must be AID_ROOT to write to /proc/sys/kernel/ nodes, there
1373         // are no capability overrides.  For security reasons we do not want
1374         // to run as AID_ROOT.  We may not be able to write them successfully,
1375         // we will try, but the least we can do is read the values back to
1376         // confirm expectations and report whether configured or not.
1377         auto configured = llkWriteStringToFileConfirm(std::to_string(khtTimeout.count()),
1378                                                       "/proc/sys/kernel/hung_task_timeout_secs");
1379         if (configured) {
1380             llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_warnings");
1381             llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_check_count");
1382             configured = llkWriteStringToFileConfirm("1", "/proc/sys/kernel/hung_task_panic");
1383         }
1384         if (configured) {
1385             LOG(INFO) << "[khungtaskd] configured";
1386         } else {
1387             LOG(WARNING) << "[khungtaskd] not configurable";
1388         }
1389     }
1390 
1391     bool logConfig = true;
1392     if (llkEnable) {
1393         if (llkMlockall &&
1394             // MCL_ONFAULT pins pages as they fault instead of loading
1395             // everything immediately all at once. (Which would be bad,
1396             // because as of this writing, we have a lot of mapped pages we
1397             // never use.) Old kernels will see MCL_ONFAULT and fail with
1398             // EINVAL; we ignore this failure.
1399             //
1400             // N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
1401             // pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
1402             // in pages.
1403 
1404             // CAP_IPC_LOCK required
1405             mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
1406             PLOG(WARNING) << "mlockall failed ";
1407         }
1408 
1409         if (threadname) {
1410             pthread_attr_t attr;
1411 
1412             if (!pthread_attr_init(&attr)) {
1413                 sched_param param;
1414 
1415                 memset(&param, 0, sizeof(param));
1416                 pthread_attr_setschedparam(&attr, &param);
1417                 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1418                 if (!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1419                     pthread_t thread;
1420                     if (!pthread_create(&thread, &attr, llkThread, const_cast<char*>(threadname))) {
1421                         // wait a second for thread to start
1422                         for (auto retry = 50; retry && !llkRunning; --retry) {
1423                             ::usleep(20000);
1424                         }
1425                         logConfig = !llkRunning;  // printed in llkd context?
1426                     } else {
1427                         LOG(ERROR) << "failed to spawn llkd thread";
1428                     }
1429                 } else {
1430                     LOG(ERROR) << "failed to detach llkd thread";
1431                 }
1432                 pthread_attr_destroy(&attr);
1433             } else {
1434                 LOG(ERROR) << "failed to allocate attibutes for llkd thread";
1435             }
1436         }
1437     } else {
1438         LOG(DEBUG) << "[khungtaskd] left unconfigured";
1439     }
1440     if (logConfig) {
1441         llkLogConfig();
1442     }
1443 
1444     return llkEnable;
1445 }
1446