1 /*
2 **
3 ** Copyright 2006-2014, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 #define _GNU_SOURCE /* for asprintf */
19 
20 #include <arpa/inet.h>
21 #include <assert.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <stdbool.h>
25 #include <stdint.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <inttypes.h>
30 #include <sys/param.h>
31 
32 #include <log/logd.h>
33 #include <log/logprint.h>
34 
35 /* open coded fragment, prevent circular dependencies */
36 #define WEAK static
37 
38 typedef struct FilterInfo_t {
39     char *mTag;
40     android_LogPriority mPri;
41     struct FilterInfo_t *p_next;
42 } FilterInfo;
43 
44 struct AndroidLogFormat_t {
45     android_LogPriority global_pri;
46     FilterInfo *filters;
47     AndroidLogPrintFormat format;
48     bool colored_output;
49     bool usec_time_output;
50     bool printable_output;
51 };
52 
53 /*
54  *  gnome-terminal color tags
55  *    See http://misc.flogisoft.com/bash/tip_colors_and_formatting
56  *    for ideas on how to set the forground color of the text for xterm.
57  *    The color manipulation character stream is defined as:
58  *      ESC [ 3 8 ; 5 ; <color#> m
59  */
60 #define ANDROID_COLOR_BLUE     75
61 #define ANDROID_COLOR_DEFAULT 231
62 #define ANDROID_COLOR_GREEN    40
63 #define ANDROID_COLOR_ORANGE  166
64 #define ANDROID_COLOR_RED     196
65 #define ANDROID_COLOR_YELLOW  226
66 
filterinfo_new(const char * tag,android_LogPriority pri)67 static FilterInfo * filterinfo_new(const char * tag, android_LogPriority pri)
68 {
69     FilterInfo *p_ret;
70 
71     p_ret = (FilterInfo *)calloc(1, sizeof(FilterInfo));
72     p_ret->mTag = strdup(tag);
73     p_ret->mPri = pri;
74 
75     return p_ret;
76 }
77 
78 /* balance to above, filterinfo_free left unimplemented */
79 
80 /*
81  * Note: also accepts 0-9 priorities
82  * returns ANDROID_LOG_UNKNOWN if the character is unrecognized
83  */
filterCharToPri(char c)84 static android_LogPriority filterCharToPri (char c)
85 {
86     android_LogPriority pri;
87 
88     c = tolower(c);
89 
90     if (c >= '0' && c <= '9') {
91         if (c >= ('0'+ANDROID_LOG_SILENT)) {
92             pri = ANDROID_LOG_VERBOSE;
93         } else {
94             pri = (android_LogPriority)(c - '0');
95         }
96     } else if (c == 'v') {
97         pri = ANDROID_LOG_VERBOSE;
98     } else if (c == 'd') {
99         pri = ANDROID_LOG_DEBUG;
100     } else if (c == 'i') {
101         pri = ANDROID_LOG_INFO;
102     } else if (c == 'w') {
103         pri = ANDROID_LOG_WARN;
104     } else if (c == 'e') {
105         pri = ANDROID_LOG_ERROR;
106     } else if (c == 'f') {
107         pri = ANDROID_LOG_FATAL;
108     } else if (c == 's') {
109         pri = ANDROID_LOG_SILENT;
110     } else if (c == '*') {
111         pri = ANDROID_LOG_DEFAULT;
112     } else {
113         pri = ANDROID_LOG_UNKNOWN;
114     }
115 
116     return pri;
117 }
118 
filterPriToChar(android_LogPriority pri)119 static char filterPriToChar (android_LogPriority pri)
120 {
121     switch (pri) {
122         case ANDROID_LOG_VERBOSE:       return 'V';
123         case ANDROID_LOG_DEBUG:         return 'D';
124         case ANDROID_LOG_INFO:          return 'I';
125         case ANDROID_LOG_WARN:          return 'W';
126         case ANDROID_LOG_ERROR:         return 'E';
127         case ANDROID_LOG_FATAL:         return 'F';
128         case ANDROID_LOG_SILENT:        return 'S';
129 
130         case ANDROID_LOG_DEFAULT:
131         case ANDROID_LOG_UNKNOWN:
132         default:                        return '?';
133     }
134 }
135 
colorFromPri(android_LogPriority pri)136 static int colorFromPri (android_LogPriority pri)
137 {
138     switch (pri) {
139         case ANDROID_LOG_VERBOSE:       return ANDROID_COLOR_DEFAULT;
140         case ANDROID_LOG_DEBUG:         return ANDROID_COLOR_BLUE;
141         case ANDROID_LOG_INFO:          return ANDROID_COLOR_GREEN;
142         case ANDROID_LOG_WARN:          return ANDROID_COLOR_ORANGE;
143         case ANDROID_LOG_ERROR:         return ANDROID_COLOR_RED;
144         case ANDROID_LOG_FATAL:         return ANDROID_COLOR_RED;
145         case ANDROID_LOG_SILENT:        return ANDROID_COLOR_DEFAULT;
146 
147         case ANDROID_LOG_DEFAULT:
148         case ANDROID_LOG_UNKNOWN:
149         default:                        return ANDROID_COLOR_DEFAULT;
150     }
151 }
152 
filterPriForTag(AndroidLogFormat * p_format,const char * tag)153 static android_LogPriority filterPriForTag(
154         AndroidLogFormat *p_format, const char *tag)
155 {
156     FilterInfo *p_curFilter;
157 
158     for (p_curFilter = p_format->filters
159             ; p_curFilter != NULL
160             ; p_curFilter = p_curFilter->p_next
161     ) {
162         if (0 == strcmp(tag, p_curFilter->mTag)) {
163             if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
164                 return p_format->global_pri;
165             } else {
166                 return p_curFilter->mPri;
167             }
168         }
169     }
170 
171     return p_format->global_pri;
172 }
173 
174 /**
175  * returns 1 if this log line should be printed based on its priority
176  * and tag, and 0 if it should not
177  */
android_log_shouldPrintLine(AndroidLogFormat * p_format,const char * tag,android_LogPriority pri)178 int android_log_shouldPrintLine (
179         AndroidLogFormat *p_format, const char *tag, android_LogPriority pri)
180 {
181     return pri >= filterPriForTag(p_format, tag);
182 }
183 
android_log_format_new()184 AndroidLogFormat *android_log_format_new()
185 {
186     AndroidLogFormat *p_ret;
187 
188     p_ret = calloc(1, sizeof(AndroidLogFormat));
189 
190     p_ret->global_pri = ANDROID_LOG_VERBOSE;
191     p_ret->format = FORMAT_BRIEF;
192     p_ret->colored_output = false;
193     p_ret->usec_time_output = false;
194     p_ret->printable_output = false;
195 
196     return p_ret;
197 }
198 
android_log_format_free(AndroidLogFormat * p_format)199 void android_log_format_free(AndroidLogFormat *p_format)
200 {
201     FilterInfo *p_info, *p_info_old;
202 
203     p_info = p_format->filters;
204 
205     while (p_info != NULL) {
206         p_info_old = p_info;
207         p_info = p_info->p_next;
208 
209         free(p_info_old);
210     }
211 
212     free(p_format);
213 }
214 
215 
216 
android_log_setPrintFormat(AndroidLogFormat * p_format,AndroidLogPrintFormat format)217 int android_log_setPrintFormat(AndroidLogFormat *p_format,
218         AndroidLogPrintFormat format)
219 {
220     switch (format) {
221     case FORMAT_MODIFIER_COLOR:
222         p_format->colored_output = true;
223         return 0;
224     case FORMAT_MODIFIER_TIME_USEC:
225         p_format->usec_time_output = true;
226         return 0;
227     case FORMAT_MODIFIER_PRINTABLE:
228         p_format->printable_output = true;
229         return 0;
230     default:
231         break;
232     }
233     p_format->format = format;
234     return 1;
235 }
236 
237 /**
238  * Returns FORMAT_OFF on invalid string
239  */
android_log_formatFromString(const char * formatString)240 AndroidLogPrintFormat android_log_formatFromString(const char * formatString)
241 {
242     static AndroidLogPrintFormat format;
243 
244     if (strcmp(formatString, "brief") == 0) format = FORMAT_BRIEF;
245     else if (strcmp(formatString, "process") == 0) format = FORMAT_PROCESS;
246     else if (strcmp(formatString, "tag") == 0) format = FORMAT_TAG;
247     else if (strcmp(formatString, "thread") == 0) format = FORMAT_THREAD;
248     else if (strcmp(formatString, "raw") == 0) format = FORMAT_RAW;
249     else if (strcmp(formatString, "time") == 0) format = FORMAT_TIME;
250     else if (strcmp(formatString, "threadtime") == 0) format = FORMAT_THREADTIME;
251     else if (strcmp(formatString, "long") == 0) format = FORMAT_LONG;
252     else if (strcmp(formatString, "color") == 0) format = FORMAT_MODIFIER_COLOR;
253     else if (strcmp(formatString, "usec") == 0) format = FORMAT_MODIFIER_TIME_USEC;
254     else if (strcmp(formatString, "printable") == 0) format = FORMAT_MODIFIER_PRINTABLE;
255     else format = FORMAT_OFF;
256 
257     return format;
258 }
259 
260 /**
261  * filterExpression: a single filter expression
262  * eg "AT:d"
263  *
264  * returns 0 on success and -1 on invalid expression
265  *
266  * Assumes single threaded execution
267  */
268 
android_log_addFilterRule(AndroidLogFormat * p_format,const char * filterExpression)269 int android_log_addFilterRule(AndroidLogFormat *p_format,
270         const char *filterExpression)
271 {
272     size_t tagNameLength;
273     android_LogPriority pri = ANDROID_LOG_DEFAULT;
274 
275     tagNameLength = strcspn(filterExpression, ":");
276 
277     if (tagNameLength == 0) {
278         goto error;
279     }
280 
281     if(filterExpression[tagNameLength] == ':') {
282         pri = filterCharToPri(filterExpression[tagNameLength+1]);
283 
284         if (pri == ANDROID_LOG_UNKNOWN) {
285             goto error;
286         }
287     }
288 
289     if(0 == strncmp("*", filterExpression, tagNameLength)) {
290         /*
291          * This filter expression refers to the global filter
292          * The default level for this is DEBUG if the priority
293          * is unspecified
294          */
295         if (pri == ANDROID_LOG_DEFAULT) {
296             pri = ANDROID_LOG_DEBUG;
297         }
298 
299         p_format->global_pri = pri;
300     } else {
301         /*
302          * for filter expressions that don't refer to the global
303          * filter, the default is verbose if the priority is unspecified
304          */
305         if (pri == ANDROID_LOG_DEFAULT) {
306             pri = ANDROID_LOG_VERBOSE;
307         }
308 
309         char *tagName;
310 
311 /*
312  * Presently HAVE_STRNDUP is never defined, so the second case is always taken
313  * Darwin doesn't have strnup, everything else does
314  */
315 #ifdef HAVE_STRNDUP
316         tagName = strndup(filterExpression, tagNameLength);
317 #else
318         /* a few extra bytes copied... */
319         tagName = strdup(filterExpression);
320         tagName[tagNameLength] = '\0';
321 #endif /*HAVE_STRNDUP*/
322 
323         FilterInfo *p_fi = filterinfo_new(tagName, pri);
324         free(tagName);
325 
326         p_fi->p_next = p_format->filters;
327         p_format->filters = p_fi;
328     }
329 
330     return 0;
331 error:
332     return -1;
333 }
334 
335 
336 /**
337  * filterString: a comma/whitespace-separated set of filter expressions
338  *
339  * eg "AT:d *:i"
340  *
341  * returns 0 on success and -1 on invalid expression
342  *
343  * Assumes single threaded execution
344  *
345  */
346 
android_log_addFilterString(AndroidLogFormat * p_format,const char * filterString)347 int android_log_addFilterString(AndroidLogFormat *p_format,
348         const char *filterString)
349 {
350     char *filterStringCopy = strdup (filterString);
351     char *p_cur = filterStringCopy;
352     char *p_ret;
353     int err;
354 
355     /* Yes, I'm using strsep */
356     while (NULL != (p_ret = strsep(&p_cur, " \t,"))) {
357         /* ignore whitespace-only entries */
358         if(p_ret[0] != '\0') {
359             err = android_log_addFilterRule(p_format, p_ret);
360 
361             if (err < 0) {
362                 goto error;
363             }
364         }
365     }
366 
367     free (filterStringCopy);
368     return 0;
369 error:
370     free (filterStringCopy);
371     return -1;
372 }
373 
374 /**
375  * Splits a wire-format buffer into an AndroidLogEntry
376  * entry allocated by caller. Pointers will point directly into buf
377  *
378  * Returns 0 on success and -1 on invalid wire format (entry will be
379  * in unspecified state)
380  */
android_log_processLogBuffer(struct logger_entry * buf,AndroidLogEntry * entry)381 int android_log_processLogBuffer(struct logger_entry *buf,
382                                  AndroidLogEntry *entry)
383 {
384     entry->tv_sec = buf->sec;
385     entry->tv_nsec = buf->nsec;
386     entry->pid = buf->pid;
387     entry->tid = buf->tid;
388 
389     /*
390      * format: <priority:1><tag:N>\0<message:N>\0
391      *
392      * tag str
393      *   starts at buf->msg+1
394      * msg
395      *   starts at buf->msg+1+len(tag)+1
396      *
397      * The message may have been truncated by the kernel log driver.
398      * When that happens, we must null-terminate the message ourselves.
399      */
400     if (buf->len < 3) {
401         /*
402          * An well-formed entry must consist of at least a priority
403          * and two null characters
404          */
405         fprintf(stderr, "+++ LOG: entry too small\n");
406         return -1;
407     }
408 
409     int msgStart = -1;
410     int msgEnd = -1;
411 
412     int i;
413     char *msg = buf->msg;
414     struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
415     if (buf2->hdr_size) {
416         msg = ((char *)buf2) + buf2->hdr_size;
417     }
418     for (i = 1; i < buf->len; i++) {
419         if (msg[i] == '\0') {
420             if (msgStart == -1) {
421                 msgStart = i + 1;
422             } else {
423                 msgEnd = i;
424                 break;
425             }
426         }
427     }
428 
429     if (msgStart == -1) {
430         fprintf(stderr, "+++ LOG: malformed log message\n");
431         return -1;
432     }
433     if (msgEnd == -1) {
434         /* incoming message not null-terminated; force it */
435         msgEnd = buf->len - 1;
436         msg[msgEnd] = '\0';
437     }
438 
439     entry->priority = msg[0];
440     entry->tag = msg + 1;
441     entry->message = msg + msgStart;
442     entry->messageLen = msgEnd - msgStart;
443 
444     return 0;
445 }
446 
447 /*
448  * Extract a 4-byte value from a byte stream.
449  */
get4LE(const uint8_t * src)450 static inline uint32_t get4LE(const uint8_t* src)
451 {
452     return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
453 }
454 
455 /*
456  * Extract an 8-byte value from a byte stream.
457  */
get8LE(const uint8_t * src)458 static inline uint64_t get8LE(const uint8_t* src)
459 {
460     uint32_t low, high;
461 
462     low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
463     high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
464     return ((uint64_t) high << 32) | (uint64_t) low;
465 }
466 
467 
468 /*
469  * Recursively convert binary log data to printable form.
470  *
471  * This needs to be recursive because you can have lists of lists.
472  *
473  * If we run out of room, we stop processing immediately.  It's important
474  * for us to check for space on every output element to avoid producing
475  * garbled output.
476  *
477  * Returns 0 on success, 1 on buffer full, -1 on failure.
478  */
android_log_printBinaryEvent(const unsigned char ** pEventData,size_t * pEventDataLen,char ** pOutBuf,size_t * pOutBufLen)479 static int android_log_printBinaryEvent(const unsigned char** pEventData,
480     size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen)
481 {
482     const unsigned char* eventData = *pEventData;
483     size_t eventDataLen = *pEventDataLen;
484     char* outBuf = *pOutBuf;
485     size_t outBufLen = *pOutBufLen;
486     unsigned char type;
487     size_t outCount;
488     int result = 0;
489 
490     if (eventDataLen < 1)
491         return -1;
492     type = *eventData++;
493     eventDataLen--;
494 
495     switch (type) {
496     case EVENT_TYPE_INT:
497         /* 32-bit signed int */
498         {
499             int ival;
500 
501             if (eventDataLen < 4)
502                 return -1;
503             ival = get4LE(eventData);
504             eventData += 4;
505             eventDataLen -= 4;
506 
507             outCount = snprintf(outBuf, outBufLen, "%d", ival);
508             if (outCount < outBufLen) {
509                 outBuf += outCount;
510                 outBufLen -= outCount;
511             } else {
512                 /* halt output */
513                 goto no_room;
514             }
515         }
516         break;
517     case EVENT_TYPE_LONG:
518         /* 64-bit signed long */
519         {
520             uint64_t lval;
521 
522             if (eventDataLen < 8)
523                 return -1;
524             lval = get8LE(eventData);
525             eventData += 8;
526             eventDataLen -= 8;
527 
528             outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
529             if (outCount < outBufLen) {
530                 outBuf += outCount;
531                 outBufLen -= outCount;
532             } else {
533                 /* halt output */
534                 goto no_room;
535             }
536         }
537         break;
538     case EVENT_TYPE_FLOAT:
539         /* float */
540         {
541             uint32_t ival;
542             float fval;
543 
544             if (eventDataLen < 4)
545                 return -1;
546             ival = get4LE(eventData);
547             fval = *(float*)&ival;
548             eventData += 4;
549             eventDataLen -= 4;
550 
551             outCount = snprintf(outBuf, outBufLen, "%f", fval);
552             if (outCount < outBufLen) {
553                 outBuf += outCount;
554                 outBufLen -= outCount;
555             } else {
556                 /* halt output */
557                 goto no_room;
558             }
559         }
560         break;
561     case EVENT_TYPE_STRING:
562         /* UTF-8 chars, not NULL-terminated */
563         {
564             unsigned int strLen;
565 
566             if (eventDataLen < 4)
567                 return -1;
568             strLen = get4LE(eventData);
569             eventData += 4;
570             eventDataLen -= 4;
571 
572             if (eventDataLen < strLen)
573                 return -1;
574 
575             if (strLen < outBufLen) {
576                 memcpy(outBuf, eventData, strLen);
577                 outBuf += strLen;
578                 outBufLen -= strLen;
579             } else if (outBufLen > 0) {
580                 /* copy what we can */
581                 memcpy(outBuf, eventData, outBufLen);
582                 outBuf += outBufLen;
583                 outBufLen -= outBufLen;
584                 goto no_room;
585             }
586             eventData += strLen;
587             eventDataLen -= strLen;
588             break;
589         }
590     case EVENT_TYPE_LIST:
591         /* N items, all different types */
592         {
593             unsigned char count;
594             int i;
595 
596             if (eventDataLen < 1)
597                 return -1;
598 
599             count = *eventData++;
600             eventDataLen--;
601 
602             if (outBufLen > 0) {
603                 *outBuf++ = '[';
604                 outBufLen--;
605             } else {
606                 goto no_room;
607             }
608 
609             for (i = 0; i < count; i++) {
610                 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
611                         &outBuf, &outBufLen);
612                 if (result != 0)
613                     goto bail;
614 
615                 if (i < count-1) {
616                     if (outBufLen > 0) {
617                         *outBuf++ = ',';
618                         outBufLen--;
619                     } else {
620                         goto no_room;
621                     }
622                 }
623             }
624 
625             if (outBufLen > 0) {
626                 *outBuf++ = ']';
627                 outBufLen--;
628             } else {
629                 goto no_room;
630             }
631         }
632         break;
633     default:
634         fprintf(stderr, "Unknown binary event type %d\n", type);
635         return -1;
636     }
637 
638 bail:
639     *pEventData = eventData;
640     *pEventDataLen = eventDataLen;
641     *pOutBuf = outBuf;
642     *pOutBufLen = outBufLen;
643     return result;
644 
645 no_room:
646     result = 1;
647     goto bail;
648 }
649 
650 /**
651  * Convert a binary log entry to ASCII form.
652  *
653  * For convenience we mimic the processLogBuffer API.  There is no
654  * pre-defined output length for the binary data, since we're free to format
655  * it however we choose, which means we can't really use a fixed-size buffer
656  * here.
657  */
android_log_processBinaryLogBuffer(struct logger_entry * buf,AndroidLogEntry * entry,const EventTagMap * map,char * messageBuf,int messageBufLen)658 int android_log_processBinaryLogBuffer(struct logger_entry *buf,
659     AndroidLogEntry *entry, const EventTagMap* map, char* messageBuf,
660     int messageBufLen)
661 {
662     size_t inCount;
663     unsigned int tagIndex;
664     const unsigned char* eventData;
665 
666     entry->tv_sec = buf->sec;
667     entry->tv_nsec = buf->nsec;
668     entry->priority = ANDROID_LOG_INFO;
669     entry->pid = buf->pid;
670     entry->tid = buf->tid;
671 
672     /*
673      * Pull the tag out.
674      */
675     eventData = (const unsigned char*) buf->msg;
676     struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
677     if (buf2->hdr_size) {
678         eventData = ((unsigned char *)buf2) + buf2->hdr_size;
679     }
680     inCount = buf->len;
681     if (inCount < 4)
682         return -1;
683     tagIndex = get4LE(eventData);
684     eventData += 4;
685     inCount -= 4;
686 
687     if (map != NULL) {
688         entry->tag = android_lookupEventTag(map, tagIndex);
689     } else {
690         entry->tag = NULL;
691     }
692 
693     /*
694      * If we don't have a map, or didn't find the tag number in the map,
695      * stuff a generated tag value into the start of the output buffer and
696      * shift the buffer pointers down.
697      */
698     if (entry->tag == NULL) {
699         int tagLen;
700 
701         tagLen = snprintf(messageBuf, messageBufLen, "[%d]", tagIndex);
702         entry->tag = messageBuf;
703         messageBuf += tagLen+1;
704         messageBufLen -= tagLen+1;
705     }
706 
707     /*
708      * Format the event log data into the buffer.
709      */
710     char* outBuf = messageBuf;
711     size_t outRemaining = messageBufLen-1;      /* leave one for nul byte */
712     int result;
713     result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
714                 &outRemaining);
715     if (result < 0) {
716         fprintf(stderr, "Binary log entry conversion failed\n");
717         return -1;
718     } else if (result == 1) {
719         if (outBuf > messageBuf) {
720             /* leave an indicator */
721             *(outBuf-1) = '!';
722         } else {
723             /* no room to output anything at all */
724             *outBuf++ = '!';
725             outRemaining--;
726         }
727         /* pretend we ate all the data */
728         inCount = 0;
729     }
730 
731     /* eat the silly terminating '\n' */
732     if (inCount == 1 && *eventData == '\n') {
733         eventData++;
734         inCount--;
735     }
736 
737     if (inCount != 0) {
738         fprintf(stderr,
739             "Warning: leftover binary log data (%zu bytes)\n", inCount);
740     }
741 
742     /*
743      * Terminate the buffer.  The NUL byte does not count as part of
744      * entry->messageLen.
745      */
746     *outBuf = '\0';
747     entry->messageLen = outBuf - messageBuf;
748     assert(entry->messageLen == (messageBufLen-1) - outRemaining);
749 
750     entry->message = messageBuf;
751 
752     return 0;
753 }
754 
755 /*
756  * One utf8 character at a time
757  *
758  * Returns the length of the utf8 character in the buffer,
759  * or -1 if illegal or truncated
760  *
761  * Open coded from libutils/Unicode.cpp, borrowed from utf8_length(),
762  * can not remove from here because of library circular dependencies.
763  * Expect one-day utf8_character_length with the same signature could
764  * _also_ be part of libutils/Unicode.cpp if its usefullness needs to
765  * propagate globally.
766  */
utf8_character_length(const char * src,size_t len)767 WEAK ssize_t utf8_character_length(const char *src, size_t len)
768 {
769     const char *cur = src;
770     const char first_char = *cur++;
771     static const uint32_t kUnicodeMaxCodepoint = 0x0010FFFF;
772     int32_t mask, to_ignore_mask;
773     size_t num_to_read;
774     uint32_t utf32;
775 
776     if ((first_char & 0x80) == 0) { /* ASCII */
777         return 1;
778     }
779 
780     /*
781      * (UTF-8's character must not be like 10xxxxxx,
782      *  but 110xxxxx, 1110xxxx, ... or 1111110x)
783      */
784     if ((first_char & 0x40) == 0) {
785         return -1;
786     }
787 
788     for (utf32 = 1, num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
789          num_to_read < 5 && (first_char & mask);
790          num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
791         if (num_to_read > len) {
792             return -1;
793         }
794         if ((*cur & 0xC0) != 0x80) { /* can not be 10xxxxxx? */
795             return -1;
796         }
797         utf32 = (utf32 << 6) + (*cur++ & 0b00111111);
798     }
799     /* "first_char" must be (110xxxxx - 11110xxx) */
800     if (num_to_read >= 5) {
801         return -1;
802     }
803     to_ignore_mask |= mask;
804     utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
805     if (utf32 > kUnicodeMaxCodepoint) {
806         return -1;
807     }
808     return num_to_read;
809 }
810 
811 /*
812  * Convert to printable from message to p buffer, return string length. If p is
813  * NULL, do not copy, but still return the expected string length.
814  */
convertPrintable(char * p,const char * message,size_t messageLen)815 static size_t convertPrintable(char *p, const char *message, size_t messageLen)
816 {
817     char *begin = p;
818     bool print = p != NULL;
819 
820     while (messageLen) {
821         char buf[6];
822         ssize_t len = sizeof(buf) - 1;
823         if ((size_t)len > messageLen) {
824             len = messageLen;
825         }
826         len = utf8_character_length(message, len);
827 
828         if (len < 0) {
829             snprintf(buf, sizeof(buf),
830                      ((messageLen > 1) && isdigit(message[1]))
831                          ? "\\%03o"
832                          : "\\%o",
833                      *message & 0377);
834             len = 1;
835         } else {
836             buf[0] = '\0';
837             if (len == 1) {
838                 if (*message == '\a') {
839                     strcpy(buf, "\\a");
840                 } else if (*message == '\b') {
841                     strcpy(buf, "\\b");
842                 } else if (*message == '\t') {
843                     strcpy(buf, "\\t");
844                 } else if (*message == '\v') {
845                     strcpy(buf, "\\v");
846                 } else if (*message == '\f') {
847                     strcpy(buf, "\\f");
848                 } else if (*message == '\r') {
849                     strcpy(buf, "\\r");
850                 } else if (*message == '\\') {
851                     strcpy(buf, "\\\\");
852                 } else if ((*message < ' ') || (*message & 0x80)) {
853                     snprintf(buf, sizeof(buf), "\\%o", *message & 0377);
854                 }
855             }
856             if (!buf[0]) {
857                 strncpy(buf, message, len);
858                 buf[len] = '\0';
859             }
860         }
861         if (print) {
862             strcpy(p, buf);
863         }
864         p += strlen(buf);
865         message += len;
866         messageLen -= len;
867     }
868     return p - begin;
869 }
870 
871 /**
872  * Formats a log message into a buffer
873  *
874  * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
875  * If return value != defaultBuffer, caller must call free()
876  * Returns NULL on malloc error
877  */
878 
android_log_formatLogLine(AndroidLogFormat * p_format,char * defaultBuffer,size_t defaultBufferSize,const AndroidLogEntry * entry,size_t * p_outLength)879 char *android_log_formatLogLine (
880     AndroidLogFormat *p_format,
881     char *defaultBuffer,
882     size_t defaultBufferSize,
883     const AndroidLogEntry *entry,
884     size_t *p_outLength)
885 {
886 #if !defined(_WIN32)
887     struct tm tmBuf;
888 #endif
889     struct tm* ptm;
890     char timeBuf[32]; /* good margin, 23+nul for msec, 26+nul for usec */
891     char prefixBuf[128], suffixBuf[128];
892     char priChar;
893     int prefixSuffixIsHeaderFooter = 0;
894     char * ret = NULL;
895 
896     priChar = filterPriToChar(entry->priority);
897     size_t prefixLen = 0, suffixLen = 0;
898     size_t len;
899 
900     /*
901      * Get the current date/time in pretty form
902      *
903      * It's often useful when examining a log with "less" to jump to
904      * a specific point in the file by searching for the date/time stamp.
905      * For this reason it's very annoying to have regexp meta characters
906      * in the time stamp.  Don't use forward slashes, parenthesis,
907      * brackets, asterisks, or other special chars here.
908      */
909 #if !defined(_WIN32)
910     ptm = localtime_r(&(entry->tv_sec), &tmBuf);
911 #else
912     ptm = localtime(&(entry->tv_sec));
913 #endif
914     /* strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm); */
915     strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
916     len = strlen(timeBuf);
917     if (p_format->usec_time_output) {
918         snprintf(timeBuf + len, sizeof(timeBuf) - len,
919                  ".%06ld", entry->tv_nsec / 1000);
920     } else {
921         snprintf(timeBuf + len, sizeof(timeBuf) - len,
922                  ".%03ld", entry->tv_nsec / 1000000);
923     }
924 
925     /*
926      * Construct a buffer containing the log header and log message.
927      */
928     if (p_format->colored_output) {
929         prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
930                              colorFromPri(entry->priority));
931         prefixLen = MIN(prefixLen, sizeof(prefixBuf));
932         suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
933         suffixLen = MIN(suffixLen, sizeof(suffixBuf));
934     }
935 
936     switch (p_format->format) {
937         case FORMAT_TAG:
938             len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
939                 "%c/%-8s: ", priChar, entry->tag);
940             strcpy(suffixBuf + suffixLen, "\n");
941             ++suffixLen;
942             break;
943         case FORMAT_PROCESS:
944             len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
945                 "  (%s)\n", entry->tag);
946             suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
947             len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
948                 "%c(%5d) ", priChar, entry->pid);
949             break;
950         case FORMAT_THREAD:
951             len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
952                 "%c(%5d:%5d) ", priChar, entry->pid, entry->tid);
953             strcpy(suffixBuf + suffixLen, "\n");
954             ++suffixLen;
955             break;
956         case FORMAT_RAW:
957             prefixBuf[prefixLen] = 0;
958             len = 0;
959             strcpy(suffixBuf + suffixLen, "\n");
960             ++suffixLen;
961             break;
962         case FORMAT_TIME:
963             len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
964                 "%s %c/%-8s(%5d): ", timeBuf, priChar, entry->tag, entry->pid);
965             strcpy(suffixBuf + suffixLen, "\n");
966             ++suffixLen;
967             break;
968         case FORMAT_THREADTIME:
969             len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
970                 "%s %5d %5d %c %-8s: ", timeBuf,
971                 entry->pid, entry->tid, priChar, entry->tag);
972             strcpy(suffixBuf + suffixLen, "\n");
973             ++suffixLen;
974             break;
975         case FORMAT_LONG:
976             len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
977                 "[ %s %5d:%5d %c/%-8s ]\n",
978                 timeBuf, entry->pid, entry->tid, priChar, entry->tag);
979             strcpy(suffixBuf + suffixLen, "\n\n");
980             suffixLen += 2;
981             prefixSuffixIsHeaderFooter = 1;
982             break;
983         case FORMAT_BRIEF:
984         default:
985             len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
986                 "%c/%-8s(%5d): ", priChar, entry->tag, entry->pid);
987             strcpy(suffixBuf + suffixLen, "\n");
988             ++suffixLen;
989             break;
990     }
991 
992     /* snprintf has a weird return value.   It returns what would have been
993      * written given a large enough buffer.  In the case that the prefix is
994      * longer then our buffer(128), it messes up the calculations below
995      * possibly causing heap corruption.  To avoid this we double check and
996      * set the length at the maximum (size minus null byte)
997      */
998     prefixLen += MIN(len, sizeof(prefixBuf) - prefixLen);
999     suffixLen = MIN(suffixLen, sizeof(suffixBuf));
1000 
1001     /* the following code is tragically unreadable */
1002 
1003     size_t numLines;
1004     char *p;
1005     size_t bufferSize;
1006     const char *pm;
1007 
1008     if (prefixSuffixIsHeaderFooter) {
1009         /* we're just wrapping message with a header/footer */
1010         numLines = 1;
1011     } else {
1012         pm = entry->message;
1013         numLines = 0;
1014 
1015         /*
1016          * The line-end finding here must match the line-end finding
1017          * in for ( ... numLines...) loop below
1018          */
1019         while (pm < (entry->message + entry->messageLen)) {
1020             if (*pm++ == '\n') numLines++;
1021         }
1022         /* plus one line for anything not newline-terminated at the end */
1023         if (pm > entry->message && *(pm-1) != '\n') numLines++;
1024     }
1025 
1026     /*
1027      * this is an upper bound--newlines in message may be counted
1028      * extraneously
1029      */
1030     bufferSize = (numLines * (prefixLen + suffixLen)) + 1;
1031     if (p_format->printable_output) {
1032         /* Calculate extra length to convert non-printable to printable */
1033         bufferSize += convertPrintable(NULL, entry->message, entry->messageLen);
1034     } else {
1035         bufferSize += entry->messageLen;
1036     }
1037 
1038     if (defaultBufferSize >= bufferSize) {
1039         ret = defaultBuffer;
1040     } else {
1041         ret = (char *)malloc(bufferSize);
1042 
1043         if (ret == NULL) {
1044             return ret;
1045         }
1046     }
1047 
1048     ret[0] = '\0';       /* to start strcat off */
1049 
1050     p = ret;
1051     pm = entry->message;
1052 
1053     if (prefixSuffixIsHeaderFooter) {
1054         strcat(p, prefixBuf);
1055         p += prefixLen;
1056         if (p_format->printable_output) {
1057             p += convertPrintable(p, entry->message, entry->messageLen);
1058         } else {
1059             strncat(p, entry->message, entry->messageLen);
1060             p += entry->messageLen;
1061         }
1062         strcat(p, suffixBuf);
1063         p += suffixLen;
1064     } else {
1065         while(pm < (entry->message + entry->messageLen)) {
1066             const char *lineStart;
1067             size_t lineLen;
1068             lineStart = pm;
1069 
1070             /* Find the next end-of-line in message */
1071             while (pm < (entry->message + entry->messageLen)
1072                     && *pm != '\n') pm++;
1073             lineLen = pm - lineStart;
1074 
1075             strcat(p, prefixBuf);
1076             p += prefixLen;
1077             if (p_format->printable_output) {
1078                 p += convertPrintable(p, lineStart, lineLen);
1079             } else {
1080                 strncat(p, lineStart, lineLen);
1081                 p += lineLen;
1082             }
1083             strcat(p, suffixBuf);
1084             p += suffixLen;
1085 
1086             if (*pm == '\n') pm++;
1087         }
1088     }
1089 
1090     if (p_outLength != NULL) {
1091         *p_outLength = p - ret;
1092     }
1093 
1094     return ret;
1095 }
1096 
1097 /**
1098  * Either print or do not print log line, based on filter
1099  *
1100  * Returns count bytes written
1101  */
1102 
android_log_printLogLine(AndroidLogFormat * p_format,int fd,const AndroidLogEntry * entry)1103 int android_log_printLogLine(
1104     AndroidLogFormat *p_format,
1105     int fd,
1106     const AndroidLogEntry *entry)
1107 {
1108     int ret;
1109     char defaultBuffer[512];
1110     char *outBuffer = NULL;
1111     size_t totalLen;
1112 
1113     outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
1114             sizeof(defaultBuffer), entry, &totalLen);
1115 
1116     if (!outBuffer)
1117         return -1;
1118 
1119     do {
1120         ret = write(fd, outBuffer, totalLen);
1121     } while (ret < 0 && errno == EINTR);
1122 
1123     if (ret < 0) {
1124         fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
1125         ret = 0;
1126         goto done;
1127     }
1128 
1129     if (((size_t)ret) < totalLen) {
1130         fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
1131                 (int)totalLen);
1132         goto done;
1133     }
1134 
1135 done:
1136     if (outBuffer != defaultBuffer) {
1137         free(outBuffer);
1138     }
1139 
1140     return ret;
1141 }
1142