blob: daada5ad733bf90d612b6d3f2dfd785a19004afb [file] [log] [blame]
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001/* //device/libs/cutils/logprint.c
2**
3** Copyright 2006, 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 <ctype.h>
21#include <stdio.h>
22#include <errno.h>
23#include <stdlib.h>
24#include <stdint.h>
25#include <string.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070026#include <assert.h>
27#include <arpa/inet.h>
28
29#include <cutils/logd.h>
30#include <cutils/logprint.h>
31
32typedef struct FilterInfo_t {
33 char *mTag;
34 android_LogPriority mPri;
35 struct FilterInfo_t *p_next;
36} FilterInfo;
37
38struct AndroidLogFormat_t {
39 android_LogPriority global_pri;
40 FilterInfo *filters;
41 AndroidLogPrintFormat format;
42};
43
44static FilterInfo * filterinfo_new(const char * tag, android_LogPriority pri)
45{
46 FilterInfo *p_ret;
47
48 p_ret = (FilterInfo *)calloc(1, sizeof(FilterInfo));
49 p_ret->mTag = strdup(tag);
50 p_ret->mPri = pri;
51
52 return p_ret;
53}
54
55static void filterinfo_free(FilterInfo *p_info)
56{
57 if (p_info == NULL) {
58 return;
59 }
60
61 free(p_info->mTag);
62 p_info->mTag = NULL;
63}
64
65/*
66 * Note: also accepts 0-9 priorities
67 * returns ANDROID_LOG_UNKNOWN if the character is unrecognized
68 */
69static android_LogPriority filterCharToPri (char c)
70{
71 android_LogPriority pri;
72
73 c = tolower(c);
74
75 if (c >= '0' && c <= '9') {
76 if (c >= ('0'+ANDROID_LOG_SILENT)) {
77 pri = ANDROID_LOG_VERBOSE;
78 } else {
79 pri = (android_LogPriority)(c - '0');
80 }
81 } else if (c == 'v') {
82 pri = ANDROID_LOG_VERBOSE;
83 } else if (c == 'd') {
84 pri = ANDROID_LOG_DEBUG;
85 } else if (c == 'i') {
86 pri = ANDROID_LOG_INFO;
87 } else if (c == 'w') {
88 pri = ANDROID_LOG_WARN;
89 } else if (c == 'e') {
90 pri = ANDROID_LOG_ERROR;
91 } else if (c == 'f') {
92 pri = ANDROID_LOG_FATAL;
93 } else if (c == 's') {
94 pri = ANDROID_LOG_SILENT;
95 } else if (c == '*') {
96 pri = ANDROID_LOG_DEFAULT;
97 } else {
98 pri = ANDROID_LOG_UNKNOWN;
99 }
100
101 return pri;
102}
103
104static char filterPriToChar (android_LogPriority pri)
105{
106 switch (pri) {
107 case ANDROID_LOG_VERBOSE: return 'V';
108 case ANDROID_LOG_DEBUG: return 'D';
109 case ANDROID_LOG_INFO: return 'I';
110 case ANDROID_LOG_WARN: return 'W';
111 case ANDROID_LOG_ERROR: return 'E';
112 case ANDROID_LOG_FATAL: return 'F';
113 case ANDROID_LOG_SILENT: return 'S';
114
115 case ANDROID_LOG_DEFAULT:
116 case ANDROID_LOG_UNKNOWN:
117 default: return '?';
118 }
119}
120
121static android_LogPriority filterPriForTag(
122 AndroidLogFormat *p_format, const char *tag)
123{
124 FilterInfo *p_curFilter;
125
126 for (p_curFilter = p_format->filters
127 ; p_curFilter != NULL
128 ; p_curFilter = p_curFilter->p_next
129 ) {
130 if (0 == strcmp(tag, p_curFilter->mTag)) {
131 if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
132 return p_format->global_pri;
133 } else {
134 return p_curFilter->mPri;
135 }
136 }
137 }
138
139 return p_format->global_pri;
140}
141
142/** for debugging */
143static void dumpFilters(AndroidLogFormat *p_format)
144{
145 FilterInfo *p_fi;
146
147 for (p_fi = p_format->filters ; p_fi != NULL ; p_fi = p_fi->p_next) {
148 char cPri = filterPriToChar(p_fi->mPri);
149 if (p_fi->mPri == ANDROID_LOG_DEFAULT) {
150 cPri = filterPriToChar(p_format->global_pri);
151 }
152 fprintf(stderr,"%s:%c\n", p_fi->mTag, cPri);
153 }
154
155 fprintf(stderr,"*:%c\n", filterPriToChar(p_format->global_pri));
156
157}
158
159/**
160 * returns 1 if this log line should be printed based on its priority
161 * and tag, and 0 if it should not
162 */
163int android_log_shouldPrintLine (
164 AndroidLogFormat *p_format, const char *tag, android_LogPriority pri)
165{
166 return pri >= filterPriForTag(p_format, tag);
167}
168
169AndroidLogFormat *android_log_format_new()
170{
171 AndroidLogFormat *p_ret;
172
173 p_ret = calloc(1, sizeof(AndroidLogFormat));
174
175 p_ret->global_pri = ANDROID_LOG_VERBOSE;
176 p_ret->format = FORMAT_BRIEF;
177
178 return p_ret;
179}
180
181void android_log_format_free(AndroidLogFormat *p_format)
182{
183 FilterInfo *p_info, *p_info_old;
184
185 p_info = p_format->filters;
186
187 while (p_info != NULL) {
188 p_info_old = p_info;
189 p_info = p_info->p_next;
190
191 free(p_info_old);
192 }
193
194 free(p_format);
195}
196
197
198
199void android_log_setPrintFormat(AndroidLogFormat *p_format,
200 AndroidLogPrintFormat format)
201{
202 p_format->format=format;
203}
204
205/**
206 * Returns FORMAT_OFF on invalid string
207 */
208AndroidLogPrintFormat android_log_formatFromString(const char * formatString)
209{
210 static AndroidLogPrintFormat format;
211
212 if (strcmp(formatString, "brief") == 0) format = FORMAT_BRIEF;
213 else if (strcmp(formatString, "process") == 0) format = FORMAT_PROCESS;
214 else if (strcmp(formatString, "tag") == 0) format = FORMAT_TAG;
215 else if (strcmp(formatString, "thread") == 0) format = FORMAT_THREAD;
216 else if (strcmp(formatString, "raw") == 0) format = FORMAT_RAW;
217 else if (strcmp(formatString, "time") == 0) format = FORMAT_TIME;
218 else if (strcmp(formatString, "threadtime") == 0) format = FORMAT_THREADTIME;
219 else if (strcmp(formatString, "long") == 0) format = FORMAT_LONG;
220 else format = FORMAT_OFF;
221
222 return format;
223}
224
225/**
226 * filterExpression: a single filter expression
227 * eg "AT:d"
228 *
229 * returns 0 on success and -1 on invalid expression
230 *
231 * Assumes single threaded execution
232 */
233
234int android_log_addFilterRule(AndroidLogFormat *p_format,
235 const char *filterExpression)
236{
237 size_t i=0;
238 size_t tagNameLength;
239 android_LogPriority pri = ANDROID_LOG_DEFAULT;
240
241 tagNameLength = strcspn(filterExpression, ":");
242
243 if (tagNameLength == 0) {
244 goto error;
245 }
246
247 if(filterExpression[tagNameLength] == ':') {
248 pri = filterCharToPri(filterExpression[tagNameLength+1]);
249
250 if (pri == ANDROID_LOG_UNKNOWN) {
251 goto error;
252 }
253 }
254
255 if(0 == strncmp("*", filterExpression, tagNameLength)) {
256 // This filter expression refers to the global filter
257 // The default level for this is DEBUG if the priority
258 // is unspecified
259 if (pri == ANDROID_LOG_DEFAULT) {
260 pri = ANDROID_LOG_DEBUG;
261 }
262
263 p_format->global_pri = pri;
264 } else {
265 // for filter expressions that don't refer to the global
266 // filter, the default is verbose if the priority is unspecified
267 if (pri == ANDROID_LOG_DEFAULT) {
268 pri = ANDROID_LOG_VERBOSE;
269 }
270
271 char *tagName;
272
273// Presently HAVE_STRNDUP is never defined, so the second case is always taken
274// Darwin doesn't have strnup, everything else does
275#ifdef HAVE_STRNDUP
276 tagName = strndup(filterExpression, tagNameLength);
277#else
278 //a few extra bytes copied...
279 tagName = strdup(filterExpression);
280 tagName[tagNameLength] = '\0';
281#endif /*HAVE_STRNDUP*/
282
283 FilterInfo *p_fi = filterinfo_new(tagName, pri);
284 free(tagName);
285
286 p_fi->p_next = p_format->filters;
287 p_format->filters = p_fi;
288 }
289
290 return 0;
291error:
292 return -1;
293}
294
295
296/**
297 * filterString: a comma/whitespace-separated set of filter expressions
298 *
299 * eg "AT:d *:i"
300 *
301 * returns 0 on success and -1 on invalid expression
302 *
303 * Assumes single threaded execution
304 *
305 */
306
307int android_log_addFilterString(AndroidLogFormat *p_format,
308 const char *filterString)
309{
310 char *filterStringCopy = strdup (filterString);
311 char *p_cur = filterStringCopy;
312 char *p_ret;
313 int err;
314
315 // Yes, I'm using strsep
316 while (NULL != (p_ret = strsep(&p_cur, " \t,"))) {
317 // ignore whitespace-only entries
318 if(p_ret[0] != '\0') {
319 err = android_log_addFilterRule(p_format, p_ret);
320
321 if (err < 0) {
322 goto error;
323 }
324 }
325 }
326
327 free (filterStringCopy);
328 return 0;
329error:
330 free (filterStringCopy);
331 return -1;
332}
333
334static inline char * strip_end(char *str)
335{
336 char *end = str + strlen(str) - 1;
337
338 while (end >= str && isspace(*end))
339 *end-- = '\0';
340 return str;
341}
342
343/**
344 * Splits a wire-format buffer into an AndroidLogEntry
345 * entry allocated by caller. Pointers will point directly into buf
346 *
347 * Returns 0 on success and -1 on invalid wire format (entry will be
348 * in unspecified state)
349 */
350int android_log_processLogBuffer(struct logger_entry *buf,
351 AndroidLogEntry *entry)
352{
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700353 entry->tv_sec = buf->sec;
354 entry->tv_nsec = buf->nsec;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700355 entry->pid = buf->pid;
356 entry->tid = buf->tid;
Kenny Root4bf3c022011-09-30 17:10:14 -0700357
358 /*
359 * format: <priority:1><tag:N>\0<message:N>\0
360 *
361 * tag str
Nick Kraleviche1ede152011-10-18 15:23:33 -0700362 * starts at buf->msg+1
Kenny Root4bf3c022011-09-30 17:10:14 -0700363 * msg
Nick Kraleviche1ede152011-10-18 15:23:33 -0700364 * starts at buf->msg+1+len(tag)+1
Kenny Root4bf3c022011-09-30 17:10:14 -0700365 */
Nick Kraleviche1ede152011-10-18 15:23:33 -0700366 if (buf->len < 3) {
367 // An well-formed entry must consist of at least a priority
368 // and two null characters
369 fprintf(stderr, "+++ LOG: entry too small\n");
Kenny Root4bf3c022011-09-30 17:10:14 -0700370 return -1;
371 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700372
Nick Kraleviche1ede152011-10-18 15:23:33 -0700373 int nullsFound = 0;
374 int i;
375 for (i = 1; i < buf->len; i++) {
376 if (buf->msg[i] == '\0') {
377 nullsFound++;
378 }
379 }
380 if (nullsFound != 2) {
381 fprintf(stderr, "+++ LOG: malformed log entry\n");
Nick Kralevich63f4a842011-10-17 10:45:03 -0700382 return -1;
383 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700384 entry->priority = buf->msg[0];
385 entry->tag = buf->msg + 1;
386 entry->message = entry->tag + strlen(entry->tag) + 1;
387 entry->messageLen = strlen(entry->message);
Nick Kralevich63f4a842011-10-17 10:45:03 -0700388
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700389 return 0;
390}
391
392/*
393 * Extract a 4-byte value from a byte stream.
394 */
395static inline uint32_t get4LE(const uint8_t* src)
396{
397 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
398}
399
400/*
401 * Extract an 8-byte value from a byte stream.
402 */
403static inline uint64_t get8LE(const uint8_t* src)
404{
405 uint32_t low, high;
406
407 low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
408 high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
409 return ((long long) high << 32) | (long long) low;
410}
411
412
413/*
414 * Recursively convert binary log data to printable form.
415 *
416 * This needs to be recursive because you can have lists of lists.
417 *
418 * If we run out of room, we stop processing immediately. It's important
419 * for us to check for space on every output element to avoid producing
420 * garbled output.
421 *
422 * Returns 0 on success, 1 on buffer full, -1 on failure.
423 */
424static int android_log_printBinaryEvent(const unsigned char** pEventData,
425 size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen)
426{
427 const unsigned char* eventData = *pEventData;
428 size_t eventDataLen = *pEventDataLen;
429 char* outBuf = *pOutBuf;
430 size_t outBufLen = *pOutBufLen;
431 unsigned char type;
432 size_t outCount;
433 int result = 0;
434
435 if (eventDataLen < 1)
436 return -1;
437 type = *eventData++;
438 eventDataLen--;
439
440 //fprintf(stderr, "--- type=%d (rem len=%d)\n", type, eventDataLen);
441
442 switch (type) {
443 case EVENT_TYPE_INT:
444 /* 32-bit signed int */
445 {
446 int ival;
447
448 if (eventDataLen < 4)
449 return -1;
450 ival = get4LE(eventData);
451 eventData += 4;
452 eventDataLen -= 4;
453
454 outCount = snprintf(outBuf, outBufLen, "%d", ival);
455 if (outCount < outBufLen) {
456 outBuf += outCount;
457 outBufLen -= outCount;
458 } else {
459 /* halt output */
460 goto no_room;
461 }
462 }
463 break;
464 case EVENT_TYPE_LONG:
465 /* 64-bit signed long */
466 {
467 long long lval;
468
469 if (eventDataLen < 8)
470 return -1;
471 lval = get8LE(eventData);
472 eventData += 8;
473 eventDataLen -= 8;
474
475 outCount = snprintf(outBuf, outBufLen, "%lld", lval);
476 if (outCount < outBufLen) {
477 outBuf += outCount;
478 outBufLen -= outCount;
479 } else {
480 /* halt output */
481 goto no_room;
482 }
483 }
484 break;
485 case EVENT_TYPE_STRING:
486 /* UTF-8 chars, not NULL-terminated */
487 {
488 unsigned int strLen;
489
490 if (eventDataLen < 4)
491 return -1;
492 strLen = get4LE(eventData);
493 eventData += 4;
494 eventDataLen -= 4;
495
496 if (eventDataLen < strLen)
497 return -1;
498
499 if (strLen < outBufLen) {
500 memcpy(outBuf, eventData, strLen);
501 outBuf += strLen;
502 outBufLen -= strLen;
503 } else if (outBufLen > 0) {
504 /* copy what we can */
505 memcpy(outBuf, eventData, outBufLen);
506 outBuf += outBufLen;
507 outBufLen -= outBufLen;
508 goto no_room;
509 }
510 eventData += strLen;
511 eventDataLen -= strLen;
512 break;
513 }
514 case EVENT_TYPE_LIST:
515 /* N items, all different types */
516 {
517 unsigned char count;
518 int i;
519
520 if (eventDataLen < 1)
521 return -1;
522
523 count = *eventData++;
524 eventDataLen--;
525
526 if (outBufLen > 0) {
527 *outBuf++ = '[';
528 outBufLen--;
529 } else {
530 goto no_room;
531 }
532
533 for (i = 0; i < count; i++) {
534 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
535 &outBuf, &outBufLen);
536 if (result != 0)
537 goto bail;
538
539 if (i < count-1) {
540 if (outBufLen > 0) {
541 *outBuf++ = ',';
542 outBufLen--;
543 } else {
544 goto no_room;
545 }
546 }
547 }
548
549 if (outBufLen > 0) {
550 *outBuf++ = ']';
551 outBufLen--;
552 } else {
553 goto no_room;
554 }
555 }
556 break;
557 default:
558 fprintf(stderr, "Unknown binary event type %d\n", type);
559 return -1;
560 }
561
562bail:
563 *pEventData = eventData;
564 *pEventDataLen = eventDataLen;
565 *pOutBuf = outBuf;
566 *pOutBufLen = outBufLen;
567 return result;
568
569no_room:
570 result = 1;
571 goto bail;
572}
573
574/**
575 * Convert a binary log entry to ASCII form.
576 *
577 * For convenience we mimic the processLogBuffer API. There is no
578 * pre-defined output length for the binary data, since we're free to format
579 * it however we choose, which means we can't really use a fixed-size buffer
580 * here.
581 */
582int android_log_processBinaryLogBuffer(struct logger_entry *buf,
583 AndroidLogEntry *entry, const EventTagMap* map, char* messageBuf,
584 int messageBufLen)
585{
586 size_t inCount;
587 unsigned int tagIndex;
588 const unsigned char* eventData;
589
590 entry->tv_sec = buf->sec;
591 entry->tv_nsec = buf->nsec;
592 entry->priority = ANDROID_LOG_INFO;
593 entry->pid = buf->pid;
594 entry->tid = buf->tid;
595
596 /*
597 * Pull the tag out.
598 */
599 eventData = (const unsigned char*) buf->msg;
600 inCount = buf->len;
601 if (inCount < 4)
602 return -1;
603 tagIndex = get4LE(eventData);
604 eventData += 4;
605 inCount -= 4;
606
607 if (map != NULL) {
608 entry->tag = android_lookupEventTag(map, tagIndex);
609 } else {
610 entry->tag = NULL;
611 }
612
613 /*
614 * If we don't have a map, or didn't find the tag number in the map,
615 * stuff a generated tag value into the start of the output buffer and
616 * shift the buffer pointers down.
617 */
618 if (entry->tag == NULL) {
619 int tagLen;
620
621 tagLen = snprintf(messageBuf, messageBufLen, "[%d]", tagIndex);
622 entry->tag = messageBuf;
623 messageBuf += tagLen+1;
624 messageBufLen -= tagLen+1;
625 }
626
627 /*
628 * Format the event log data into the buffer.
629 */
630 char* outBuf = messageBuf;
631 size_t outRemaining = messageBufLen-1; /* leave one for nul byte */
632 int result;
633 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
634 &outRemaining);
635 if (result < 0) {
636 fprintf(stderr, "Binary log entry conversion failed\n");
637 return -1;
638 } else if (result == 1) {
639 if (outBuf > messageBuf) {
640 /* leave an indicator */
641 *(outBuf-1) = '!';
642 } else {
643 /* no room to output anything at all */
644 *outBuf++ = '!';
645 outRemaining--;
646 }
647 /* pretend we ate all the data */
648 inCount = 0;
649 }
650
651 /* eat the silly terminating '\n' */
652 if (inCount == 1 && *eventData == '\n') {
653 eventData++;
654 inCount--;
655 }
656
657 if (inCount != 0) {
658 fprintf(stderr,
659 "Warning: leftover binary log data (%d bytes)\n", inCount);
660 }
661
662 /*
663 * Terminate the buffer. The NUL byte does not count as part of
664 * entry->messageLen.
665 */
666 *outBuf = '\0';
667 entry->messageLen = outBuf - messageBuf;
668 assert(entry->messageLen == (messageBufLen-1) - outRemaining);
669
670 entry->message = messageBuf;
671
672 return 0;
673}
674
675/**
676 * Formats a log message into a buffer
677 *
678 * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
679 * If return value != defaultBuffer, caller must call free()
680 * Returns NULL on malloc error
681 */
682
683char *android_log_formatLogLine (
684 AndroidLogFormat *p_format,
685 char *defaultBuffer,
686 size_t defaultBufferSize,
687 const AndroidLogEntry *entry,
688 size_t *p_outLength)
689{
690#if defined(HAVE_LOCALTIME_R)
691 struct tm tmBuf;
692#endif
693 struct tm* ptm;
694 char timeBuf[32];
695 char headerBuf[128];
696 char prefixBuf[128], suffixBuf[128];
697 char priChar;
698 int prefixSuffixIsHeaderFooter = 0;
699 char * ret = NULL;
700
701 priChar = filterPriToChar(entry->priority);
702
703 /*
704 * Get the current date/time in pretty form
705 *
706 * It's often useful when examining a log with "less" to jump to
707 * a specific point in the file by searching for the date/time stamp.
708 * For this reason it's very annoying to have regexp meta characters
709 * in the time stamp. Don't use forward slashes, parenthesis,
710 * brackets, asterisks, or other special chars here.
711 */
712#if defined(HAVE_LOCALTIME_R)
713 ptm = localtime_r(&(entry->tv_sec), &tmBuf);
714#else
715 ptm = localtime(&(entry->tv_sec));
716#endif
717 //strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm);
718 strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
719
720 /*
721 * Construct a buffer containing the log header and log message.
722 */
723 size_t prefixLen, suffixLen;
724
725 switch (p_format->format) {
726 case FORMAT_TAG:
727 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
728 "%c/%-8s: ", priChar, entry->tag);
729 strcpy(suffixBuf, "\n"); suffixLen = 1;
730 break;
731 case FORMAT_PROCESS:
732 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
733 "%c(%5d) ", priChar, entry->pid);
734 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf),
735 " (%s)\n", entry->tag);
736 break;
737 case FORMAT_THREAD:
738 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
739 "%c(%5d:%p) ", priChar, entry->pid, (void*)entry->tid);
740 strcpy(suffixBuf, "\n");
741 suffixLen = 1;
742 break;
743 case FORMAT_RAW:
744 prefixBuf[0] = 0;
745 prefixLen = 0;
746 strcpy(suffixBuf, "\n");
747 suffixLen = 1;
748 break;
749 case FORMAT_TIME:
750 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
751 "%s.%03ld %c/%-8s(%5d): ", timeBuf, entry->tv_nsec / 1000000,
752 priChar, entry->tag, entry->pid);
753 strcpy(suffixBuf, "\n");
754 suffixLen = 1;
755 break;
756 case FORMAT_THREADTIME:
757 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
758 "%s.%03ld %5d %5d %c %-8s: ", timeBuf, entry->tv_nsec / 1000000,
759 (int)entry->pid, (int)entry->tid, priChar, entry->tag);
760 strcpy(suffixBuf, "\n");
761 suffixLen = 1;
762 break;
763 case FORMAT_LONG:
764 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
765 "[ %s.%03ld %5d:%p %c/%-8s ]\n",
766 timeBuf, entry->tv_nsec / 1000000, entry->pid,
767 (void*)entry->tid, priChar, entry->tag);
768 strcpy(suffixBuf, "\n\n");
769 suffixLen = 2;
770 prefixSuffixIsHeaderFooter = 1;
771 break;
772 case FORMAT_BRIEF:
773 default:
774 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
775 "%c/%-8s(%5d): ", priChar, entry->tag, entry->pid);
776 strcpy(suffixBuf, "\n");
777 suffixLen = 1;
778 break;
779 }
Keith Prestonb45b5c92010-02-11 15:12:53 -0600780 /* snprintf has a weird return value. It returns what would have been
781 * written given a large enough buffer. In the case that the prefix is
782 * longer then our buffer(128), it messes up the calculations below
783 * possibly causing heap corruption. To avoid this we double check and
784 * set the length at the maximum (size minus null byte)
785 */
786 if(prefixLen >= sizeof(prefixBuf))
787 prefixLen = sizeof(prefixBuf) - 1;
788 if(suffixLen >= sizeof(suffixBuf))
789 suffixLen = sizeof(suffixBuf) - 1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700790
791 /* the following code is tragically unreadable */
792
793 size_t numLines;
794 size_t i;
795 char *p;
796 size_t bufferSize;
797 const char *pm;
798
799 if (prefixSuffixIsHeaderFooter) {
800 // we're just wrapping message with a header/footer
801 numLines = 1;
802 } else {
803 pm = entry->message;
804 numLines = 0;
805
806 // The line-end finding here must match the line-end finding
807 // in for ( ... numLines...) loop below
808 while (pm < (entry->message + entry->messageLen)) {
809 if (*pm++ == '\n') numLines++;
810 }
811 // plus one line for anything not newline-terminated at the end
812 if (pm > entry->message && *(pm-1) != '\n') numLines++;
813 }
814
815 // this is an upper bound--newlines in message may be counted
816 // extraneously
817 bufferSize = (numLines * (prefixLen + suffixLen)) + entry->messageLen + 1;
818
819 if (defaultBufferSize >= bufferSize) {
820 ret = defaultBuffer;
821 } else {
822 ret = (char *)malloc(bufferSize);
823
824 if (ret == NULL) {
825 return ret;
826 }
827 }
828
829 ret[0] = '\0'; /* to start strcat off */
830
831 p = ret;
832 pm = entry->message;
833
834 if (prefixSuffixIsHeaderFooter) {
835 strcat(p, prefixBuf);
836 p += prefixLen;
837 strncat(p, entry->message, entry->messageLen);
838 p += entry->messageLen;
839 strcat(p, suffixBuf);
840 p += suffixLen;
841 } else {
842 while(pm < (entry->message + entry->messageLen)) {
843 const char *lineStart;
844 size_t lineLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700845 lineStart = pm;
846
847 // Find the next end-of-line in message
848 while (pm < (entry->message + entry->messageLen)
849 && *pm != '\n') pm++;
850 lineLen = pm - lineStart;
851
852 strcat(p, prefixBuf);
853 p += prefixLen;
854 strncat(p, lineStart, lineLen);
855 p += lineLen;
856 strcat(p, suffixBuf);
857 p += suffixLen;
858
859 if (*pm == '\n') pm++;
860 }
861 }
862
863 if (p_outLength != NULL) {
864 *p_outLength = p - ret;
865 }
866
867 return ret;
868}
869
870/**
871 * Either print or do not print log line, based on filter
872 *
873 * Returns count bytes written
874 */
875
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800876int android_log_printLogLine(
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700877 AndroidLogFormat *p_format,
878 int fd,
879 const AndroidLogEntry *entry)
880{
881 int ret;
882 char defaultBuffer[512];
883 char *outBuffer = NULL;
884 size_t totalLen;
885
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700886 outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
887 sizeof(defaultBuffer), entry, &totalLen);
888
889 if (!outBuffer)
890 return -1;
891
892 do {
893 ret = write(fd, outBuffer, totalLen);
894 } while (ret < 0 && errno == EINTR);
895
896 if (ret < 0) {
897 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
898 ret = 0;
899 goto done;
900 }
901
902 if (((size_t)ret) < totalLen) {
903 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
904 (int)totalLen);
905 goto done;
906 }
907
908done:
909 if (outBuffer != defaultBuffer) {
910 free(outBuffer);
911 }
912
913 return ret;
914}
915
916
917
918void logprint_run_tests()
919{
920#if 0
921
922 fprintf(stderr, "tests disabled\n");
923
924#else
925
926 int err;
927 const char *tag;
928 AndroidLogFormat *p_format;
929
930 p_format = android_log_format_new();
931
932 fprintf(stderr, "running tests\n");
933
934 tag = "random";
935
936 android_log_addFilterRule(p_format,"*:i");
937
938 assert (ANDROID_LOG_INFO == filterPriForTag(p_format, "random"));
939 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
940 android_log_addFilterRule(p_format, "*");
941 assert (ANDROID_LOG_DEBUG == filterPriForTag(p_format, "random"));
942 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
943 android_log_addFilterRule(p_format, "*:v");
944 assert (ANDROID_LOG_VERBOSE == filterPriForTag(p_format, "random"));
945 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
946 android_log_addFilterRule(p_format, "*:i");
947 assert (ANDROID_LOG_INFO == filterPriForTag(p_format, "random"));
948 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
949
950 android_log_addFilterRule(p_format, "random");
951 assert (ANDROID_LOG_VERBOSE == filterPriForTag(p_format, "random"));
952 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
953 android_log_addFilterRule(p_format, "random:v");
954 assert (ANDROID_LOG_VERBOSE == filterPriForTag(p_format, "random"));
955 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
956 android_log_addFilterRule(p_format, "random:d");
957 assert (ANDROID_LOG_DEBUG == filterPriForTag(p_format, "random"));
958 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
959 android_log_addFilterRule(p_format, "random:w");
960 assert (ANDROID_LOG_WARN == filterPriForTag(p_format, "random"));
961 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
962
963 android_log_addFilterRule(p_format, "crap:*");
964 assert (ANDROID_LOG_VERBOSE== filterPriForTag(p_format, "crap"));
965 assert(android_log_shouldPrintLine(p_format, "crap", ANDROID_LOG_VERBOSE) > 0);
966
967 // invalid expression
968 err = android_log_addFilterRule(p_format, "random:z");
969 assert (err < 0);
970 assert (ANDROID_LOG_WARN == filterPriForTag(p_format, "random"));
971 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
972
973 // Issue #550946
974 err = android_log_addFilterString(p_format, " ");
975 assert(err == 0);
976 assert(ANDROID_LOG_WARN == filterPriForTag(p_format, "random"));
977
978 // note trailing space
979 err = android_log_addFilterString(p_format, "*:s random:d ");
980 assert(err == 0);
981 assert(ANDROID_LOG_DEBUG == filterPriForTag(p_format, "random"));
982
983 err = android_log_addFilterString(p_format, "*:s random:z");
984 assert(err < 0);
985
986
987#if 0
988 char *ret;
989 char defaultBuffer[512];
990
991 ret = android_log_formatLogLine(p_format,
992 defaultBuffer, sizeof(defaultBuffer), 0, ANDROID_LOG_ERROR, 123,
993 123, 123, "random", "nofile", strlen("Hello"), "Hello", NULL);
994#endif
995
996
997 fprintf(stderr, "tests complete\n");
998#endif
999}