• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 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 "LogKlog.h"
18 
19 #include <ctype.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <limits.h>
23 #include <stdarg.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/prctl.h>
27 #include <sys/uio.h>
28 #include <syslog.h>
29 
30 #include <private/android_filesystem_config.h>
31 #include <private/android_logger.h>
32 
33 #include "LogBuffer.h"
34 
35 #define KMSG_PRIORITY(PRI) \
36     '<', '0' + (LOG_SYSLOG | (PRI)) / 10, '0' + (LOG_SYSLOG | (PRI)) % 10, '>'
37 
38 static const char priority_message[] = { KMSG_PRIORITY(LOG_INFO), '\0' };
39 
40 // List of the _only_ needles we supply here to android::strnstr
41 static const char suspendStr[] = "PM: suspend entry ";
42 static const char resumeStr[] = "PM: suspend exit ";
43 static const char suspendedStr[] = "Suspended for ";
44 static const char healthdStr[] = "healthd";
45 static const char batteryStr[] = ": battery ";
46 static const char auditStr[] = " audit(";
47 static const char klogdStr[] = "logd.klogd: ";
48 
49 // Parsing is hard
50 
51 // called if we see a '<', s is the next character, returns pointer after '>'
is_prio(char * s,ssize_t len)52 static char* is_prio(char* s, ssize_t len) {
53     if ((len <= 0) || !isdigit(*s++)) return nullptr;
54     --len;
55     static const size_t max_prio_len = (len < 4) ? len : 4;
56     size_t priolen = 0;
57     char c;
58     while (((c = *s++)) && (++priolen <= max_prio_len)) {
59         if (!isdigit(c)) return ((c == '>') && (*s == '[')) ? s : nullptr;
60     }
61     return nullptr;
62 }
63 
64 // called if we see a '[', s is the next character, returns pointer after ']'
is_timestamp(char * s,ssize_t len)65 static char* is_timestamp(char* s, ssize_t len) {
66     while ((len > 0) && (*s == ' ')) {
67         ++s;
68         --len;
69     }
70     if ((len <= 0) || !isdigit(*s++)) return nullptr;
71     --len;
72     bool first_period = true;
73     char c;
74     while ((len > 0) && ((c = *s++))) {
75         --len;
76         if ((c == '.') && first_period) {
77             first_period = false;
78         } else if (!isdigit(c)) {
79             return ((c == ']') && !first_period && (*s == ' ')) ? s : nullptr;
80         }
81     }
82     return nullptr;
83 }
84 
85 // Like strtok_r with "\r\n" except that we look for log signatures (regex)
86 //  \(\(<[0-9]\{1,4\}>\)\([[] *[0-9]+[.][0-9]+[]] \)\{0,1\}\|[[]
87 //  *[0-9]+[.][0-9]+[]] \)
88 // and split if we see a second one without a newline.
89 // We allow nuls in content, monitoring the overall length and sub-length of
90 // the discovered tokens.
91 
92 #define SIGNATURE_MASK 0xF0
93 // <digit> following ('0' to '9' masked with ~SIGNATURE_MASK) added to signature
94 #define LESS_THAN_SIG SIGNATURE_MASK
95 #define OPEN_BRACKET_SIG ((SIGNATURE_MASK << 1) & SIGNATURE_MASK)
96 // space is one more than <digit> of 9
97 #define OPEN_BRACKET_SPACE ((char)(OPEN_BRACKET_SIG | 10))
98 
log_strntok_r(char * s,ssize_t & len,char * & last,ssize_t & sublen)99 char* android::log_strntok_r(char* s, ssize_t& len, char*& last,
100                              ssize_t& sublen) {
101     sublen = 0;
102     if (len <= 0) return nullptr;
103     if (!s) {
104         if (!(s = last)) return nullptr;
105         // fixup for log signature split <,
106         // LESS_THAN_SIG + <digit>
107         if ((*s & SIGNATURE_MASK) == LESS_THAN_SIG) {
108             *s = (*s & ~SIGNATURE_MASK) + '0';
109             *--s = '<';
110             ++len;
111         }
112         // fixup for log signature split [,
113         // OPEN_BRACKET_SPACE is space, OPEN_BRACKET_SIG + <digit>
114         if ((*s & SIGNATURE_MASK) == OPEN_BRACKET_SIG) {
115             *s = (*s == OPEN_BRACKET_SPACE) ? ' ' : (*s & ~SIGNATURE_MASK) + '0';
116             *--s = '[';
117             ++len;
118         }
119     }
120 
121     while ((len > 0) && ((*s == '\r') || (*s == '\n'))) {
122         ++s;
123         --len;
124     }
125 
126     if (len <= 0) return last = nullptr;
127     char *peek, *tok = s;
128 
129     for (;;) {
130         if (len <= 0) {
131             last = nullptr;
132             return tok;
133         }
134         char c = *s++;
135         --len;
136         ssize_t adjust;
137         switch (c) {
138             case '\r':
139             case '\n':
140                 s[-1] = '\0';
141                 last = s;
142                 return tok;
143 
144             case '<':
145                 peek = is_prio(s, len);
146                 if (!peek) break;
147                 if (s != (tok + 1)) {  // not first?
148                     s[-1] = '\0';
149                     *s &= ~SIGNATURE_MASK;
150                     *s |= LESS_THAN_SIG;  // signature for '<'
151                     last = s;
152                     return tok;
153                 }
154                 adjust = peek - s;
155                 if (adjust > len) {
156                     adjust = len;
157                 }
158                 sublen += adjust;
159                 len -= adjust;
160                 s = peek;
161                 if ((*s == '[') && ((peek = is_timestamp(s + 1, len - 1)))) {
162                     adjust = peek - s;
163                     if (adjust > len) {
164                         adjust = len;
165                     }
166                     sublen += adjust;
167                     len -= adjust;
168                     s = peek;
169                 }
170                 break;
171 
172             case '[':
173                 peek = is_timestamp(s, len);
174                 if (!peek) break;
175                 if (s != (tok + 1)) {  // not first?
176                     s[-1] = '\0';
177                     if (*s == ' ') {
178                         *s = OPEN_BRACKET_SPACE;
179                     } else {
180                         *s &= ~SIGNATURE_MASK;
181                         *s |= OPEN_BRACKET_SIG;  // signature for '['
182                     }
183                     last = s;
184                     return tok;
185                 }
186                 adjust = peek - s;
187                 if (adjust > len) {
188                     adjust = len;
189                 }
190                 sublen += adjust;
191                 len -= adjust;
192                 s = peek;
193                 break;
194         }
195         ++sublen;
196     }
197     // NOTREACHED
198 }
199 
200 log_time LogKlog::correction = (log_time(CLOCK_REALTIME) < log_time(CLOCK_MONOTONIC))
201                                        ? log_time(log_time::EPOCH)
202                                        : (log_time(CLOCK_REALTIME) - log_time(CLOCK_MONOTONIC));
203 
LogKlog(LogBuffer * buf,int fdWrite,int fdRead,bool auditd,LogStatistics * stats)204 LogKlog::LogKlog(LogBuffer* buf, int fdWrite, int fdRead, bool auditd, LogStatistics* stats)
205     : SocketListener(fdRead, false),
206       logbuf(buf),
207       signature(CLOCK_MONOTONIC),
208       initialized(false),
209       enableLogging(true),
210       auditd(auditd),
211       stats_(stats) {
212     static const char klogd_message[] = "%s%s%" PRIu64 "\n";
213     char buffer[strlen(priority_message) + strlen(klogdStr) +
214                 strlen(klogd_message) + 20];
215     snprintf(buffer, sizeof(buffer), klogd_message, priority_message, klogdStr,
216              signature.nsec());
217     write(fdWrite, buffer, strlen(buffer));
218 }
219 
onDataAvailable(SocketClient * cli)220 bool LogKlog::onDataAvailable(SocketClient* cli) {
221     if (!initialized) {
222         prctl(PR_SET_NAME, "logd.klogd");
223         initialized = true;
224         enableLogging = false;
225     }
226 
227     char buffer[LOGGER_ENTRY_MAX_PAYLOAD];
228     ssize_t len = 0;
229 
230     for (;;) {
231         ssize_t retval = 0;
232         if (len < (ssize_t)(sizeof(buffer) - 1)) {
233             retval =
234                 read(cli->getSocket(), buffer + len, sizeof(buffer) - 1 - len);
235         }
236         if ((retval == 0) && (len <= 0)) {
237             break;
238         }
239         if (retval < 0) {
240             return false;
241         }
242         len += retval;
243         bool full = len == (sizeof(buffer) - 1);
244         char* ep = buffer + len;
245         *ep = '\0';
246         ssize_t sublen;
247         for (char *ptr = nullptr, *tok = buffer;
248              !!(tok = android::log_strntok_r(tok, len, ptr, sublen));
249              tok = nullptr) {
250             if (((tok + sublen) >= ep) && (retval != 0) && full) {
251                 if (sublen > 0) memmove(buffer, tok, sublen);
252                 len = sublen;
253                 break;
254             }
255             if ((sublen > 0) && *tok) {
256                 log(tok, sublen);
257             }
258         }
259     }
260 
261     return true;
262 }
263 
calculateCorrection(const log_time & monotonic,const char * real_string,ssize_t len)264 void LogKlog::calculateCorrection(const log_time& monotonic,
265                                   const char* real_string, ssize_t len) {
266     static const char real_format[] = "%Y-%m-%d %H:%M:%S.%09q UTC";
267     if (len < (ssize_t)(strlen(real_format) + 5)) return;
268 
269     log_time real(log_time::EPOCH);
270     const char* ep = real.strptime(real_string, real_format);
271     if (!ep || (ep > &real_string[len]) || (real > log_time(CLOCK_REALTIME))) {
272         return;
273     }
274     // kernel report UTC, log_time::strptime is localtime from calendar.
275     // Bionic and liblog strptime does not support %z or %Z to pick up
276     // timezone so we are calculating our own correction.
277     time_t now = real.tv_sec;
278     struct tm tm;
279     memset(&tm, 0, sizeof(tm));
280     tm.tm_isdst = -1;
281     localtime_r(&now, &tm);
282     if ((tm.tm_gmtoff < 0) && ((-tm.tm_gmtoff) > (long)real.tv_sec)) {
283         real = log_time(log_time::EPOCH);
284     } else {
285         real.tv_sec += tm.tm_gmtoff;
286     }
287     if (monotonic > real) {
288         correction = log_time(log_time::EPOCH);
289     } else {
290         correction = real - monotonic;
291     }
292 }
293 
sniffTime(const char * & buf,ssize_t len,bool reverse)294 log_time LogKlog::sniffTime(const char*& buf, ssize_t len, bool reverse) {
295     log_time now(log_time::EPOCH);
296     if (len <= 0) return now;
297 
298     const char* cp = nullptr;
299     if ((len > 10) && (*buf == '[')) {
300         cp = now.strptime(buf, "[ %s.%q]");  // can index beyond buffer bounds
301         if (cp && (cp > &buf[len - 1])) cp = nullptr;
302     }
303     if (cp) {
304         len -= cp - buf;
305         if ((len > 0) && isspace(*cp)) {
306             ++cp;
307             --len;
308         }
309         buf = cp;
310 
311         const char* b;
312         if (((b = android::strnstr(cp, len, suspendStr))) &&
313             (((b += strlen(suspendStr)) - cp) < len)) {
314             len -= b - cp;
315             calculateCorrection(now, b, len);
316         } else if (((b = android::strnstr(cp, len, resumeStr))) &&
317                    (((b += strlen(resumeStr)) - cp) < len)) {
318             len -= b - cp;
319             calculateCorrection(now, b, len);
320         } else if (((b = android::strnstr(cp, len, healthdStr))) &&
321                    (((b += strlen(healthdStr)) - cp) < len) &&
322                    ((b = android::strnstr(b, len -= b - cp, batteryStr))) &&
323                    (((b += strlen(batteryStr)) - cp) < len)) {
324             // NB: healthd is roughly 150us late, so we use it instead to
325             //     trigger a check for ntp-induced or hardware clock drift.
326             log_time real(CLOCK_REALTIME);
327             log_time mono(CLOCK_MONOTONIC);
328             correction = (real < mono) ? log_time(log_time::EPOCH) : (real - mono);
329         } else if (((b = android::strnstr(cp, len, suspendedStr))) &&
330                    (((b += strlen(suspendStr)) - cp) < len)) {
331             len -= b - cp;
332             log_time real(log_time::EPOCH);
333             char* endp;
334             real.tv_sec = strtol(b, &endp, 10);
335             if ((*endp == '.') && ((endp - b) < len)) {
336                 unsigned long multiplier = NS_PER_SEC;
337                 real.tv_nsec = 0;
338                 len -= endp - b;
339                 while (--len && isdigit(*++endp) && (multiplier /= 10)) {
340                     real.tv_nsec += (*endp - '0') * multiplier;
341                 }
342                 if (reverse) {
343                     if (real > correction) {
344                         correction = log_time(log_time::EPOCH);
345                     } else {
346                         correction -= real;
347                     }
348                 } else {
349                     correction += real;
350                 }
351             }
352         }
353 
354         convertMonotonicToReal(now);
355     } else {
356         now = log_time(CLOCK_REALTIME);
357     }
358     return now;
359 }
360 
sniffPid(const char * & buf,ssize_t len)361 pid_t LogKlog::sniffPid(const char*& buf, ssize_t len) {
362     if (len <= 0) return 0;
363 
364     const char* cp = buf;
365     // sscanf does a strlen, let's check if the string is not nul terminated.
366     // pseudo out-of-bounds access since we always have an extra char on buffer.
367     if (((ssize_t)strnlen(cp, len) == len) && cp[len]) {
368         return 0;
369     }
370     while (len) {
371         // Mediatek kernels with modified printk
372         if (*cp == '[') {
373             int pid = 0;
374             char placeholder;
375             if (sscanf(cp, "[%d:%*[a-z_./0-9:A-Z]]%c", &pid, &placeholder) == 2) {
376                 return pid;
377             }
378             break;  // Only the first one
379         }
380         ++cp;
381         --len;
382     }
383     if (len > 8 && cp[0] == '[' && cp[7] == ']' && isdigit(cp[6])) {
384         // Linux 5.10 and above, e.g. "[    T1] init: init first stage started!"
385         int i = 5;
386         while (i > 1 && isdigit(cp[i])) {
387             --i;
388         }
389         int pos = i + 1;
390         if (cp[i] != 'T') {
391             return 0;
392         }
393         while (i > 1) {
394             --i;
395             if (cp[i] != ' ') {
396                 return 0;
397             }
398         }
399         buf = cp + 8;
400         return atoi(cp + pos);
401     }
402     return 0;
403 }
404 
405 // kernel log prefix, convert to a kernel log priority number
parseKernelPrio(const char * & buf,ssize_t len)406 static int parseKernelPrio(const char*& buf, ssize_t len) {
407     int pri = LOG_USER | LOG_INFO;
408     const char* cp = buf;
409     if ((len > 0) && (*cp == '<')) {
410         pri = 0;
411         while (--len && isdigit(*++cp)) {
412             pri = (pri * 10) + *cp - '0';
413         }
414         if ((len > 0) && (*cp == '>')) {
415             ++cp;
416         } else {
417             cp = buf;
418             pri = LOG_USER | LOG_INFO;
419         }
420         buf = cp;
421     }
422     return pri;
423 }
424 
425 // Convert kernel log priority number into an Android Logger priority number
convertKernelPrioToAndroidPrio(int pri)426 static int convertKernelPrioToAndroidPrio(int pri) {
427     switch (pri & LOG_PRIMASK) {
428         case LOG_EMERG:
429         case LOG_ALERT:
430         case LOG_CRIT:
431             return ANDROID_LOG_FATAL;
432 
433         case LOG_ERR:
434             return ANDROID_LOG_ERROR;
435 
436         case LOG_WARNING:
437             return ANDROID_LOG_WARN;
438 
439         default:
440         case LOG_NOTICE:
441         case LOG_INFO:
442             break;
443 
444         case LOG_DEBUG:
445             return ANDROID_LOG_DEBUG;
446     }
447 
448     return ANDROID_LOG_INFO;
449 }
450 
strnrchr(const char * s,ssize_t len,char c)451 static const char* strnrchr(const char* s, ssize_t len, char c) {
452     const char* save = nullptr;
453     for (; len > 0; ++s, len--) {
454         if (*s == c) {
455             save = s;
456         }
457     }
458     return save;
459 }
460 
461 //
462 // log a message into the kernel log buffer
463 //
464 // Filter rules to parse <PRI> <TIME> <tag> and <message> in order for
465 // them to appear correct in the logcat output:
466 //
467 // LOG_KERN (0):
468 // <PRI>[<TIME>] <tag> ":" <message>
469 // <PRI>[<TIME>] <tag> <tag> ":" <message>
470 // <PRI>[<TIME>] <tag> <tag>_work ":" <message>
471 // <PRI>[<TIME>] <tag> '<tag>.<num>' ":" <message>
472 // <PRI>[<TIME>] <tag> '<tag><num>' ":" <message>
473 // <PRI>[<TIME>] <tag>_host '<tag>.<num>' ":" <message>
474 // (unimplemented) <PRI>[<TIME>] <tag> '<num>.<tag>' ":" <message>
475 // <PRI>[<TIME>] "[INFO]"<tag> : <message>
476 // <PRI>[<TIME>] "------------[ cut here ]------------"   (?)
477 // <PRI>[<TIME>] "---[ end trace 3225a3070ca3e4ac ]---"   (?)
478 // LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH, LOG_SYSLOG, LOG_LPR, LOG_NEWS
479 // LOG_UUCP, LOG_CRON, LOG_AUTHPRIV, LOG_FTP:
480 // <PRI+TAG>[<TIME>] (see sys/syslog.h)
481 // Observe:
482 //  Minimum tag length = 3   NB: drops things like r5:c00bbadf, but allow PM:
483 //  Maximum tag words = 2
484 //  Maximum tag length = 16  NB: we are thinking of how ugly logcat can get.
485 //  Not a Tag if there is no message content.
486 //  leading additional spaces means no tag, inherit last tag.
487 //  Not a Tag if <tag>: is "ERROR:", "WARNING:", "INFO:" or "CPU:"
488 // Drop:
489 //  empty messages
490 //  messages with ' audit(' in them if auditd is running
491 //  logd.klogd:
492 // return -1 if message logd.klogd: <signature>
493 //
log(const char * buf,ssize_t len)494 int LogKlog::log(const char* buf, ssize_t len) {
495     if (auditd && android::strnstr(buf, len, auditStr)) {
496         return 0;
497     }
498 
499     const char* p = buf;
500     int pri = parseKernelPrio(p, len);
501 
502     log_time now = sniffTime(p, len - (p - buf), false);
503 
504     // sniff for start marker
505     const char* start = android::strnstr(p, len - (p - buf), klogdStr);
506     if (start) {
507         uint64_t sig = strtoll(start + strlen(klogdStr), nullptr, 10);
508         if (sig == signature.nsec()) {
509             if (initialized) {
510                 enableLogging = true;
511             } else {
512                 enableLogging = false;
513             }
514             return -1;
515         }
516         return 0;
517     }
518 
519     if (!enableLogging) {
520         return 0;
521     }
522 
523     // Parse pid, tid and uid
524     const pid_t pid = sniffPid(p, len - (p - buf));
525     const pid_t tid = pid;
526     uid_t uid = AID_ROOT;
527     if (pid) {
528         uid = stats_->PidToUid(pid);
529     }
530 
531     // Parse (rules at top) to pull out a tag from the incoming kernel message.
532     // Some may view the following as an ugly heuristic, the desire is to
533     // beautify the kernel logs into an Android Logging format; the goal is
534     // admirable but costly.
535     while ((p < &buf[len]) && (isspace(*p) || !*p)) {
536         ++p;
537     }
538     if (p >= &buf[len]) {  // timestamp, no content
539         return 0;
540     }
541     start = p;
542     const char* tag = "";
543     const char* etag = tag;
544     ssize_t taglen = len - (p - buf);
545     const char* bt = p;
546 
547     static const char infoBrace[] = "[INFO]";
548     static const ssize_t infoBraceLen = strlen(infoBrace);
549     if ((taglen >= infoBraceLen) &&
550         !fastcmp<strncmp>(p, infoBrace, infoBraceLen)) {
551         // <PRI>[<TIME>] "[INFO]"<tag> ":" message
552         bt = p + infoBraceLen;
553         taglen -= infoBraceLen;
554     }
555 
556     const char* et;
557     for (et = bt; (taglen > 0) && *et && (*et != ':') && !isspace(*et);
558          ++et, --taglen) {
559         // skip ':' within [ ... ]
560         if (*et == '[') {
561             while ((taglen > 0) && *et && *et != ']') {
562                 ++et;
563                 --taglen;
564             }
565             if (taglen <= 0) {
566                 break;
567             }
568         }
569     }
570     const char* cp;
571     for (cp = et; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
572     }
573 
574     // Validate tag
575     ssize_t size = et - bt;
576     if ((taglen > 0) && (size > 0)) {
577         if (*cp == ':') {
578             // ToDo: handle case insensitive colon separated logging stutter:
579             //       <tag> : <tag>: ...
580 
581             // One Word
582             tag = bt;
583             etag = et;
584             p = cp + 1;
585         } else if ((taglen > size) && (tolower(*bt) == tolower(*cp))) {
586             // clean up any tag stutter
587             if (!fastcmp<strncasecmp>(bt + 1, cp + 1, size - 1)) {  // no match
588                 // <PRI>[<TIME>] <tag> <tag> : message
589                 // <PRI>[<TIME>] <tag> <tag>: message
590                 // <PRI>[<TIME>] <tag> '<tag>.<num>' : message
591                 // <PRI>[<TIME>] <tag> '<tag><num>' : message
592                 // <PRI>[<TIME>] <tag> '<tag><stuff>' : message
593                 const char* b = cp;
594                 cp += size;
595                 taglen -= size;
596                 while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) {
597                 }
598                 const char* e;
599                 for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
600                 }
601                 if ((taglen > 0) && (*cp == ':')) {
602                     tag = b;
603                     etag = e;
604                     p = cp + 1;
605                 }
606             } else {
607                 // what about <PRI>[<TIME>] <tag>_host '<tag><stuff>' : message
608                 static const char host[] = "_host";
609                 static const ssize_t hostlen = strlen(host);
610                 if ((size > hostlen) &&
611                     !fastcmp<strncmp>(bt + size - hostlen, host, hostlen) &&
612                     !fastcmp<strncmp>(bt + 1, cp + 1, size - hostlen - 1)) {
613                     const char* b = cp;
614                     cp += size - hostlen;
615                     taglen -= size - hostlen;
616                     if (*cp == '.') {
617                         while ((--taglen > 0) && !isspace(*++cp) &&
618                                (*cp != ':')) {
619                         }
620                         const char* e;
621                         for (e = cp; (taglen > 0) && isspace(*cp);
622                              ++cp, --taglen) {
623                         }
624                         if ((taglen > 0) && (*cp == ':')) {
625                             tag = b;
626                             etag = e;
627                             p = cp + 1;
628                         }
629                     }
630                 } else {
631                     goto twoWord;
632                 }
633             }
634         } else {
635         // <PRI>[<TIME>] <tag> <stuff>' : message
636         twoWord:
637             while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) {
638             }
639             const char* e;
640             for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
641             }
642             // Two words
643             if ((taglen > 0) && (*cp == ':')) {
644                 tag = bt;
645                 etag = e;
646                 p = cp + 1;
647             }
648         }
649     }  // else no tag
650 
651     static const char cpu[] = "CPU";
652     static const ssize_t cpuLen = strlen(cpu);
653     static const char warning[] = "WARNING";
654     static const ssize_t warningLen = strlen(warning);
655     static const char error[] = "ERROR";
656     static const ssize_t errorLen = strlen(error);
657     static const char info[] = "INFO";
658     static const ssize_t infoLen = strlen(info);
659 
660     size = etag - tag;
661     if ((size <= 1) ||
662         // register names like x9
663         ((size == 2) && (isdigit(tag[0]) || isdigit(tag[1]))) ||
664         // register names like x18 but not driver names like en0
665         ((size == 3) && (isdigit(tag[1]) && isdigit(tag[2]))) ||
666         // ignore
667         ((size == cpuLen) && !fastcmp<strncmp>(tag, cpu, cpuLen)) ||
668         ((size == warningLen) && !fastcmp<strncasecmp>(tag, warning, warningLen)) ||
669         ((size == errorLen) && !fastcmp<strncasecmp>(tag, error, errorLen)) ||
670         ((size == infoLen) && !fastcmp<strncasecmp>(tag, info, infoLen))) {
671         p = start;
672         etag = tag = "";
673     }
674 
675     // Suppress additional stutter in tag:
676     //   eg: [143:healthd]healthd -> [143:healthd]
677     taglen = etag - tag;
678     // Mediatek-special printk induced stutter
679     const char* mp = strnrchr(tag, taglen, ']');
680     if (mp && (++mp < etag)) {
681         ssize_t s = etag - mp;
682         if (((s + s) < taglen) && !fastcmp<memcmp>(mp, mp - 1 - s, s)) {
683             taglen = mp - tag;
684         }
685     }
686     // Deal with sloppy and simplistic harmless p = cp + 1 etc above.
687     if (len < (p - buf)) {
688         p = &buf[len];
689     }
690     // skip leading space
691     while ((p < &buf[len]) && (isspace(*p) || !*p)) {
692         ++p;
693     }
694     // truncate trailing space or nuls
695     ssize_t b = len - (p - buf);
696     while ((b > 0) && (isspace(p[b - 1]) || !p[b - 1])) {
697         --b;
698     }
699     // trick ... allow tag with empty content to be logged. log() drops empty
700     if ((b <= 0) && (taglen > 0)) {
701         p = " ";
702         b = 1;
703     }
704     // This shouldn't happen, but clamp the size if it does.
705     if (b > LOGGER_ENTRY_MAX_PAYLOAD) {
706         b = LOGGER_ENTRY_MAX_PAYLOAD;
707     }
708     if (taglen > LOGGER_ENTRY_MAX_PAYLOAD) {
709         taglen = LOGGER_ENTRY_MAX_PAYLOAD;
710     }
711     // calculate buffer copy requirements
712     ssize_t n = 1 + taglen + 1 + b + 1;
713     // Extra checks for likely impossible cases.
714     if ((taglen > n) || (b > n) || (n > (ssize_t)USHRT_MAX) || (n <= 0)) {
715         return -EINVAL;
716     }
717 
718     // Careful.
719     // We are using the stack to house the log buffer for speed reasons.
720     // If we malloc'd this buffer, we could get away without n's USHRT_MAX
721     // test above, but we would then required a max(n, USHRT_MAX) as
722     // truncating length argument to logbuf->log() below. Gain is protection
723     // against stack corruption and speedup, loss is truncated long-line content.
724     char newstr[n];
725     char* np = newstr;
726 
727     // Convert priority into single-byte Android logger priority
728     *np = convertKernelPrioToAndroidPrio(pri);
729     ++np;
730 
731     // Copy parsed tag following priority
732     memcpy(np, tag, taglen);
733     np += taglen;
734     *np = '\0';
735     ++np;
736 
737     // Copy main message to the remainder
738     memcpy(np, p, b);
739     np[b] = '\0';
740 
741     {
742         // Watch out for singular race conditions with timezone causing near
743         // integer quarter-hour jumps in the time and compensate accordingly.
744         // Entries will be temporal within near_seconds * 2. b/21868540
745         static uint32_t vote_time[3];
746         vote_time[2] = vote_time[1];
747         vote_time[1] = vote_time[0];
748         vote_time[0] = now.tv_sec;
749 
750         if (vote_time[1] && vote_time[2]) {
751             static const unsigned near_seconds = 10;
752             static const unsigned timezones_seconds = 900;
753             int diff0 = (vote_time[0] - vote_time[1]) / near_seconds;
754             unsigned abs0 = (diff0 < 0) ? -diff0 : diff0;
755             int diff1 = (vote_time[1] - vote_time[2]) / near_seconds;
756             unsigned abs1 = (diff1 < 0) ? -diff1 : diff1;
757             if ((abs1 <= 1) &&  // last two were in agreement on timezone
758                 ((abs0 + 1) % (timezones_seconds / near_seconds)) <= 2) {
759                 abs0 = (abs0 + 1) / (timezones_seconds / near_seconds) *
760                        timezones_seconds;
761                 now.tv_sec -= (diff0 < 0) ? -abs0 : abs0;
762             }
763         }
764     }
765 
766     // Log message
767     int rc = logbuf->Log(LOG_ID_KERNEL, now, uid, pid, tid, newstr, (uint16_t)n);
768 
769     return rc;
770 }
771