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