• 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 = {.tm_isdst = -1};
279     localtime_r(&now, &tm);
280     if ((tm.tm_gmtoff < 0) && ((-tm.tm_gmtoff) > (long)real.tv_sec)) {
281         real = log_time(log_time::EPOCH);
282     } else {
283         real.tv_sec += tm.tm_gmtoff;
284     }
285     if (monotonic > real) {
286         correction = log_time(log_time::EPOCH);
287     } else {
288         correction = real - monotonic;
289     }
290 }
291 
sniffTime(const char * & buf,ssize_t len,bool reverse)292 log_time LogKlog::sniffTime(const char*& buf, ssize_t len, bool reverse) {
293     log_time now(log_time::EPOCH);
294     if (len <= 0) return now;
295 
296     const char* cp = nullptr;
297     if ((len > 10) && (*buf == '[')) {
298         cp = now.strptime(buf, "[ %s.%q]");  // can index beyond buffer bounds
299         if (cp && (cp > &buf[len - 1])) cp = nullptr;
300     }
301     if (cp) {
302         len -= cp - buf;
303         if ((len > 0) && isspace(*cp)) {
304             ++cp;
305             --len;
306         }
307         buf = cp;
308 
309         const char* b;
310         if (((b = android::strnstr(cp, len, suspendStr))) &&
311             (((b += strlen(suspendStr)) - cp) < len)) {
312             len -= b - cp;
313             calculateCorrection(now, b, len);
314         } else if (((b = android::strnstr(cp, len, resumeStr))) &&
315                    (((b += strlen(resumeStr)) - cp) < len)) {
316             len -= b - cp;
317             calculateCorrection(now, b, len);
318         } else if (((b = android::strnstr(cp, len, healthdStr))) &&
319                    (((b += strlen(healthdStr)) - cp) < len) &&
320                    ((b = android::strnstr(b, len -= b - cp, batteryStr))) &&
321                    (((b += strlen(batteryStr)) - cp) < len)) {
322             // NB: healthd is roughly 150us late, so we use it instead to
323             //     trigger a check for ntp-induced or hardware clock drift.
324             log_time real(CLOCK_REALTIME);
325             log_time mono(CLOCK_MONOTONIC);
326             correction = (real < mono) ? log_time(log_time::EPOCH) : (real - mono);
327         } else if (((b = android::strnstr(cp, len, suspendedStr))) &&
328                    (((b += strlen(suspendStr)) - cp) < len)) {
329             len -= b - cp;
330             log_time real(log_time::EPOCH);
331             char* endp;
332             real.tv_sec = strtol(b, &endp, 10);
333             if ((*endp == '.') && ((endp - b) < len)) {
334                 unsigned long multiplier = NS_PER_SEC;
335                 real.tv_nsec = 0;
336                 len -= endp - b;
337                 while (--len && isdigit(*++endp) && (multiplier /= 10)) {
338                     real.tv_nsec += (*endp - '0') * multiplier;
339                 }
340                 if (reverse) {
341                     if (real > correction) {
342                         correction = log_time(log_time::EPOCH);
343                     } else {
344                         correction -= real;
345                     }
346                 } else {
347                     correction += real;
348                 }
349             }
350         }
351 
352         convertMonotonicToReal(now);
353     } else {
354         now = log_time(CLOCK_REALTIME);
355     }
356     return now;
357 }
358 
sniffPid(const char * & buf,ssize_t len)359 pid_t LogKlog::sniffPid(const char*& buf, ssize_t len) {
360     if (len <= 0) return 0;
361 
362     const char* cp = buf;
363     // sscanf does a strlen, let's check if the string is not nul terminated.
364     // pseudo out-of-bounds access since we always have an extra char on buffer.
365     if (((ssize_t)strnlen(cp, len) == len) && cp[len]) {
366         return 0;
367     }
368     while (len) {
369         // Mediatek kernels with modified printk
370         if (*cp == '[') {
371             int pid = 0;
372             char placeholder;
373             if (sscanf(cp, "[%d:%*[a-z_./0-9:A-Z]]%c", &pid, &placeholder) == 2) {
374                 return pid;
375             }
376             break;  // Only the first one
377         }
378         ++cp;
379         --len;
380     }
381     if (len > 8 && cp[0] == '[' && cp[7] == ']' && isdigit(cp[6])) {
382         // Linux 5.10 and above, e.g. "[    T1] init: init first stage started!"
383         int i = 5;
384         while (i > 1 && isdigit(cp[i])) {
385             --i;
386         }
387         int pos = i + 1;
388         if (cp[i] != 'T') {
389             return 0;
390         }
391         while (i > 1) {
392             --i;
393             if (cp[i] != ' ') {
394                 return 0;
395             }
396         }
397         buf = cp + 8;
398         return atoi(cp + pos);
399     }
400     return 0;
401 }
402 
403 // kernel log prefix, convert to a kernel log priority number
parseKernelPrio(const char * & buf,ssize_t len)404 static int parseKernelPrio(const char*& buf, ssize_t len) {
405     int pri = LOG_USER | LOG_INFO;
406     const char* cp = buf;
407     if ((len > 0) && (*cp == '<')) {
408         pri = 0;
409         while (--len && isdigit(*++cp)) {
410             pri = (pri * 10) + *cp - '0';
411         }
412         if ((len > 0) && (*cp == '>')) {
413             ++cp;
414         } else {
415             cp = buf;
416             pri = LOG_USER | LOG_INFO;
417         }
418         buf = cp;
419     }
420     return pri;
421 }
422 
423 // Convert kernel log priority number into an Android Logger priority number
convertKernelPrioToAndroidPrio(int pri)424 static int convertKernelPrioToAndroidPrio(int pri) {
425     switch (pri & LOG_PRIMASK) {
426         case LOG_EMERG:
427         case LOG_ALERT:
428         case LOG_CRIT:
429             return ANDROID_LOG_FATAL;
430 
431         case LOG_ERR:
432             return ANDROID_LOG_ERROR;
433 
434         case LOG_WARNING:
435             return ANDROID_LOG_WARN;
436 
437         default:
438         case LOG_NOTICE:
439         case LOG_INFO:
440             break;
441 
442         case LOG_DEBUG:
443             return ANDROID_LOG_DEBUG;
444     }
445 
446     return ANDROID_LOG_INFO;
447 }
448 
strnrchr(const char * s,ssize_t len,char c)449 static const char* strnrchr(const char* s, ssize_t len, char c) {
450     const char* save = nullptr;
451     for (; len > 0; ++s, len--) {
452         if (*s == c) {
453             save = s;
454         }
455     }
456     return save;
457 }
458 
459 //
460 // log a message into the kernel log buffer
461 //
462 // Filter rules to parse <PRI> <TIME> <tag> and <message> in order for
463 // them to appear correct in the logcat output:
464 //
465 // LOG_KERN (0):
466 // <PRI>[<TIME>] <tag> ":" <message>
467 // <PRI>[<TIME>] <tag> <tag> ":" <message>
468 // <PRI>[<TIME>] <tag> <tag>_work ":" <message>
469 // <PRI>[<TIME>] <tag> '<tag>.<num>' ":" <message>
470 // <PRI>[<TIME>] <tag> '<tag><num>' ":" <message>
471 // <PRI>[<TIME>] <tag>_host '<tag>.<num>' ":" <message>
472 // (unimplemented) <PRI>[<TIME>] <tag> '<num>.<tag>' ":" <message>
473 // <PRI>[<TIME>] "[INFO]"<tag> : <message>
474 // <PRI>[<TIME>] "------------[ cut here ]------------"   (?)
475 // <PRI>[<TIME>] "---[ end trace 3225a3070ca3e4ac ]---"   (?)
476 // LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH, LOG_SYSLOG, LOG_LPR, LOG_NEWS
477 // LOG_UUCP, LOG_CRON, LOG_AUTHPRIV, LOG_FTP:
478 // <PRI+TAG>[<TIME>] (see sys/syslog.h)
479 // Observe:
480 //  Minimum tag length = 3   NB: drops things like r5:c00bbadf, but allow PM:
481 //  Maximum tag words = 2
482 //  Maximum tag length = 16  NB: we are thinking of how ugly logcat can get.
483 //  Not a Tag if there is no message content.
484 //  leading additional spaces means no tag, inherit last tag.
485 //  Not a Tag if <tag>: is "ERROR:", "WARNING:", "INFO:" or "CPU:"
486 // Drop:
487 //  empty messages
488 //  messages with ' audit(' in them if auditd is running
489 //  logd.klogd:
490 // return -1 if message logd.klogd: <signature>
491 //
log(const char * buf,ssize_t len)492 int LogKlog::log(const char* buf, ssize_t len) {
493     if (auditd && android::strnstr(buf, len, auditStr)) {
494         return 0;
495     }
496 
497     const char* p = buf;
498     int pri = parseKernelPrio(p, len);
499 
500     log_time now = sniffTime(p, len - (p - buf), false);
501 
502     // sniff for start marker
503     const char* start = android::strnstr(p, len - (p - buf), klogdStr);
504     if (start) {
505         uint64_t sig = strtoll(start + strlen(klogdStr), nullptr, 10);
506         if (sig == signature.nsec()) {
507             if (initialized) {
508                 enableLogging = true;
509             } else {
510                 enableLogging = false;
511             }
512             return -1;
513         }
514         return 0;
515     }
516 
517     if (!enableLogging) {
518         return 0;
519     }
520 
521     // Parse pid, tid and uid
522     const pid_t pid = sniffPid(p, len - (p - buf));
523     const pid_t tid = pid;
524     uid_t uid = AID_ROOT;
525     if (pid) {
526         uid = stats_->PidToUid(pid);
527     }
528 
529     // Parse (rules at top) to pull out a tag from the incoming kernel message.
530     // Some may view the following as an ugly heuristic, the desire is to
531     // beautify the kernel logs into an Android Logging format; the goal is
532     // admirable but costly.
533     while ((p < &buf[len]) && (isspace(*p) || !*p)) {
534         ++p;
535     }
536     if (p >= &buf[len]) {  // timestamp, no content
537         return 0;
538     }
539     start = p;
540     const char* tag = "";
541     const char* etag = tag;
542     ssize_t taglen = len - (p - buf);
543     const char* bt = p;
544 
545     static const char infoBrace[] = "[INFO]";
546     static const ssize_t infoBraceLen = strlen(infoBrace);
547     if ((taglen >= infoBraceLen) &&
548         !fastcmp<strncmp>(p, infoBrace, infoBraceLen)) {
549         // <PRI>[<TIME>] "[INFO]"<tag> ":" message
550         bt = p + infoBraceLen;
551         taglen -= infoBraceLen;
552     }
553 
554     const char* et;
555     for (et = bt; (taglen > 0) && *et && (*et != ':') && !isspace(*et);
556          ++et, --taglen) {
557         // skip ':' within [ ... ]
558         if (*et == '[') {
559             while ((taglen > 0) && *et && *et != ']') {
560                 ++et;
561                 --taglen;
562             }
563             if (taglen <= 0) {
564                 break;
565             }
566         }
567     }
568     const char* cp;
569     for (cp = et; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
570     }
571 
572     // Validate tag
573     ssize_t size = et - bt;
574     if ((taglen > 0) && (size > 0)) {
575         if (*cp == ':') {
576             // ToDo: handle case insensitive colon separated logging stutter:
577             //       <tag> : <tag>: ...
578 
579             // One Word
580             tag = bt;
581             etag = et;
582             p = cp + 1;
583         } else if ((taglen > size) && (tolower(*bt) == tolower(*cp))) {
584             // clean up any tag stutter
585             if (!fastcmp<strncasecmp>(bt + 1, cp + 1, size - 1)) {  // no match
586                 // <PRI>[<TIME>] <tag> <tag> : message
587                 // <PRI>[<TIME>] <tag> <tag>: message
588                 // <PRI>[<TIME>] <tag> '<tag>.<num>' : message
589                 // <PRI>[<TIME>] <tag> '<tag><num>' : message
590                 // <PRI>[<TIME>] <tag> '<tag><stuff>' : message
591                 const char* b = cp;
592                 cp += size;
593                 taglen -= size;
594                 while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) {
595                 }
596                 const char* e;
597                 for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
598                 }
599                 if ((taglen > 0) && (*cp == ':')) {
600                     tag = b;
601                     etag = e;
602                     p = cp + 1;
603                 }
604             } else {
605                 // what about <PRI>[<TIME>] <tag>_host '<tag><stuff>' : message
606                 static const char host[] = "_host";
607                 static const ssize_t hostlen = strlen(host);
608                 if ((size > hostlen) &&
609                     !fastcmp<strncmp>(bt + size - hostlen, host, hostlen) &&
610                     !fastcmp<strncmp>(bt + 1, cp + 1, size - hostlen - 1)) {
611                     const char* b = cp;
612                     cp += size - hostlen;
613                     taglen -= size - hostlen;
614                     if (*cp == '.') {
615                         while ((--taglen > 0) && !isspace(*++cp) &&
616                                (*cp != ':')) {
617                         }
618                         const char* e;
619                         for (e = cp; (taglen > 0) && isspace(*cp);
620                              ++cp, --taglen) {
621                         }
622                         if ((taglen > 0) && (*cp == ':')) {
623                             tag = b;
624                             etag = e;
625                             p = cp + 1;
626                         }
627                     }
628                 } else {
629                     goto twoWord;
630                 }
631             }
632         } else {
633         // <PRI>[<TIME>] <tag> <stuff>' : message
634         twoWord:
635             while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) {
636             }
637             const char* e;
638             for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
639             }
640             // Two words
641             if ((taglen > 0) && (*cp == ':')) {
642                 tag = bt;
643                 etag = e;
644                 p = cp + 1;
645             }
646         }
647     }  // else no tag
648 
649     static const char cpu[] = "CPU";
650     static const ssize_t cpuLen = strlen(cpu);
651     static const char warning[] = "WARNING";
652     static const ssize_t warningLen = strlen(warning);
653     static const char error[] = "ERROR";
654     static const ssize_t errorLen = strlen(error);
655     static const char info[] = "INFO";
656     static const ssize_t infoLen = strlen(info);
657 
658     size = etag - tag;
659     if ((size <= 1) ||
660         // register names like x9
661         ((size == 2) && (isdigit(tag[0]) || isdigit(tag[1]))) ||
662         // register names like x18 but not driver names like en0
663         ((size == 3) && (isdigit(tag[1]) && isdigit(tag[2]))) ||
664         // ignore
665         ((size == cpuLen) && !fastcmp<strncmp>(tag, cpu, cpuLen)) ||
666         ((size == warningLen) && !fastcmp<strncasecmp>(tag, warning, warningLen)) ||
667         ((size == errorLen) && !fastcmp<strncasecmp>(tag, error, errorLen)) ||
668         ((size == infoLen) && !fastcmp<strncasecmp>(tag, info, infoLen))) {
669         p = start;
670         etag = tag = "";
671     }
672 
673     // Suppress additional stutter in tag:
674     //   eg: [143:healthd]healthd -> [143:healthd]
675     taglen = etag - tag;
676     // Mediatek-special printk induced stutter
677     const char* mp = strnrchr(tag, taglen, ']');
678     if (mp && (++mp < etag)) {
679         ssize_t s = etag - mp;
680         if (((s + s) < taglen) && !fastcmp<memcmp>(mp, mp - 1 - s, s)) {
681             taglen = mp - tag;
682         }
683     }
684     // Deal with sloppy and simplistic harmless p = cp + 1 etc above.
685     if (len < (p - buf)) {
686         p = &buf[len];
687     }
688     // skip leading space
689     while ((p < &buf[len]) && (isspace(*p) || !*p)) {
690         ++p;
691     }
692     // truncate trailing space or nuls
693     ssize_t b = len - (p - buf);
694     while ((b > 0) && (isspace(p[b - 1]) || !p[b - 1])) {
695         --b;
696     }
697     // trick ... allow tag with empty content to be logged. log() drops empty
698     if ((b <= 0) && (taglen > 0)) {
699         p = " ";
700         b = 1;
701     }
702     // This shouldn't happen, but clamp the size if it does.
703     if (b > LOGGER_ENTRY_MAX_PAYLOAD) {
704         b = LOGGER_ENTRY_MAX_PAYLOAD;
705     }
706     if (taglen > LOGGER_ENTRY_MAX_PAYLOAD) {
707         taglen = LOGGER_ENTRY_MAX_PAYLOAD;
708     }
709     // calculate buffer copy requirements
710     ssize_t n = 1 + taglen + 1 + b + 1;
711     // Extra checks for likely impossible cases.
712     if ((taglen > n) || (b > n) || (n > (ssize_t)USHRT_MAX) || (n <= 0)) {
713         return -EINVAL;
714     }
715 
716     // Careful.
717     // We are using the stack to house the log buffer for speed reasons.
718     // If we malloc'd this buffer, we could get away without n's USHRT_MAX
719     // test above, but we would then required a max(n, USHRT_MAX) as
720     // truncating length argument to logbuf->log() below. Gain is protection
721     // against stack corruption and speedup, loss is truncated long-line content.
722     char newstr[n];
723     char* np = newstr;
724 
725     // Convert priority into single-byte Android logger priority
726     *np = convertKernelPrioToAndroidPrio(pri);
727     ++np;
728 
729     // Copy parsed tag following priority
730     memcpy(np, tag, taglen);
731     np += taglen;
732     *np = '\0';
733     ++np;
734 
735     // Copy main message to the remainder
736     memcpy(np, p, b);
737     np[b] = '\0';
738 
739     {
740         // Watch out for singular race conditions with timezone causing near
741         // integer quarter-hour jumps in the time and compensate accordingly.
742         // Entries will be temporal within near_seconds * 2. b/21868540
743         static uint32_t vote_time[3];
744         vote_time[2] = vote_time[1];
745         vote_time[1] = vote_time[0];
746         vote_time[0] = now.tv_sec;
747 
748         if (vote_time[1] && vote_time[2]) {
749             static const unsigned near_seconds = 10;
750             static const unsigned timezones_seconds = 900;
751             int diff0 = (vote_time[0] - vote_time[1]) / near_seconds;
752             unsigned abs0 = (diff0 < 0) ? -diff0 : diff0;
753             int diff1 = (vote_time[1] - vote_time[2]) / near_seconds;
754             unsigned abs1 = (diff1 < 0) ? -diff1 : diff1;
755             if ((abs1 <= 1) &&  // last two were in agreement on timezone
756                 ((abs0 + 1) % (timezones_seconds / near_seconds)) <= 2) {
757                 abs0 = (abs0 + 1) / (timezones_seconds / near_seconds) *
758                        timezones_seconds;
759                 now.tv_sec -= (diff0 < 0) ? -abs0 : abs0;
760             }
761         }
762     }
763 
764     // Log message
765     int rc = logbuf->Log(LOG_ID_KERNEL, now, uid, pid, tid, newstr, (uint16_t)n);
766 
767     return rc;
768 }
769