blob: 59fed9bc7d247d6e731dccb7392ff15064377bdd [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;
355 entry->priority = buf->msg[0];
356 entry->pid = buf->pid;
357 entry->tid = buf->tid;
Kenny Root4bf3c022011-09-30 17:10:14 -0700358
359 /*
360 * format: <priority:1><tag:N>\0<message:N>\0
361 *
362 * tag str
363 * starts at msg+1
364 * msg
365 * starts at msg+1+len(tag)+1
366 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700367 entry->tag = buf->msg + 1;
Kenny Root4bf3c022011-09-30 17:10:14 -0700368 const size_t tag_len = strlen(entry->tag);
369 const size_t preambleAndNullLen = tag_len + 3;
370 if (buf->len <= preambleAndNullLen) {
371 fprintf(stderr, "+++ LOG: entry corrupt or truncated\n");
372 return -1;
373 }
374 entry->messageLen = buf->len - preambleAndNullLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700375 entry->message = entry->tag + tag_len + 1;
376
377 return 0;
378}
379
380/*
381 * Extract a 4-byte value from a byte stream.
382 */
383static inline uint32_t get4LE(const uint8_t* src)
384{
385 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
386}
387
388/*
389 * Extract an 8-byte value from a byte stream.
390 */
391static inline uint64_t get8LE(const uint8_t* src)
392{
393 uint32_t low, high;
394
395 low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
396 high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
397 return ((long long) high << 32) | (long long) low;
398}
399
400
401/*
402 * Recursively convert binary log data to printable form.
403 *
404 * This needs to be recursive because you can have lists of lists.
405 *
406 * If we run out of room, we stop processing immediately. It's important
407 * for us to check for space on every output element to avoid producing
408 * garbled output.
409 *
410 * Returns 0 on success, 1 on buffer full, -1 on failure.
411 */
412static int android_log_printBinaryEvent(const unsigned char** pEventData,
413 size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen)
414{
415 const unsigned char* eventData = *pEventData;
416 size_t eventDataLen = *pEventDataLen;
417 char* outBuf = *pOutBuf;
418 size_t outBufLen = *pOutBufLen;
419 unsigned char type;
420 size_t outCount;
421 int result = 0;
422
423 if (eventDataLen < 1)
424 return -1;
425 type = *eventData++;
426 eventDataLen--;
427
428 //fprintf(stderr, "--- type=%d (rem len=%d)\n", type, eventDataLen);
429
430 switch (type) {
431 case EVENT_TYPE_INT:
432 /* 32-bit signed int */
433 {
434 int ival;
435
436 if (eventDataLen < 4)
437 return -1;
438 ival = get4LE(eventData);
439 eventData += 4;
440 eventDataLen -= 4;
441
442 outCount = snprintf(outBuf, outBufLen, "%d", ival);
443 if (outCount < outBufLen) {
444 outBuf += outCount;
445 outBufLen -= outCount;
446 } else {
447 /* halt output */
448 goto no_room;
449 }
450 }
451 break;
452 case EVENT_TYPE_LONG:
453 /* 64-bit signed long */
454 {
455 long long lval;
456
457 if (eventDataLen < 8)
458 return -1;
459 lval = get8LE(eventData);
460 eventData += 8;
461 eventDataLen -= 8;
462
463 outCount = snprintf(outBuf, outBufLen, "%lld", lval);
464 if (outCount < outBufLen) {
465 outBuf += outCount;
466 outBufLen -= outCount;
467 } else {
468 /* halt output */
469 goto no_room;
470 }
471 }
472 break;
473 case EVENT_TYPE_STRING:
474 /* UTF-8 chars, not NULL-terminated */
475 {
476 unsigned int strLen;
477
478 if (eventDataLen < 4)
479 return -1;
480 strLen = get4LE(eventData);
481 eventData += 4;
482 eventDataLen -= 4;
483
484 if (eventDataLen < strLen)
485 return -1;
486
487 if (strLen < outBufLen) {
488 memcpy(outBuf, eventData, strLen);
489 outBuf += strLen;
490 outBufLen -= strLen;
491 } else if (outBufLen > 0) {
492 /* copy what we can */
493 memcpy(outBuf, eventData, outBufLen);
494 outBuf += outBufLen;
495 outBufLen -= outBufLen;
496 goto no_room;
497 }
498 eventData += strLen;
499 eventDataLen -= strLen;
500 break;
501 }
502 case EVENT_TYPE_LIST:
503 /* N items, all different types */
504 {
505 unsigned char count;
506 int i;
507
508 if (eventDataLen < 1)
509 return -1;
510
511 count = *eventData++;
512 eventDataLen--;
513
514 if (outBufLen > 0) {
515 *outBuf++ = '[';
516 outBufLen--;
517 } else {
518 goto no_room;
519 }
520
521 for (i = 0; i < count; i++) {
522 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
523 &outBuf, &outBufLen);
524 if (result != 0)
525 goto bail;
526
527 if (i < count-1) {
528 if (outBufLen > 0) {
529 *outBuf++ = ',';
530 outBufLen--;
531 } else {
532 goto no_room;
533 }
534 }
535 }
536
537 if (outBufLen > 0) {
538 *outBuf++ = ']';
539 outBufLen--;
540 } else {
541 goto no_room;
542 }
543 }
544 break;
545 default:
546 fprintf(stderr, "Unknown binary event type %d\n", type);
547 return -1;
548 }
549
550bail:
551 *pEventData = eventData;
552 *pEventDataLen = eventDataLen;
553 *pOutBuf = outBuf;
554 *pOutBufLen = outBufLen;
555 return result;
556
557no_room:
558 result = 1;
559 goto bail;
560}
561
562/**
563 * Convert a binary log entry to ASCII form.
564 *
565 * For convenience we mimic the processLogBuffer API. There is no
566 * pre-defined output length for the binary data, since we're free to format
567 * it however we choose, which means we can't really use a fixed-size buffer
568 * here.
569 */
570int android_log_processBinaryLogBuffer(struct logger_entry *buf,
571 AndroidLogEntry *entry, const EventTagMap* map, char* messageBuf,
572 int messageBufLen)
573{
574 size_t inCount;
575 unsigned int tagIndex;
576 const unsigned char* eventData;
577
578 entry->tv_sec = buf->sec;
579 entry->tv_nsec = buf->nsec;
580 entry->priority = ANDROID_LOG_INFO;
581 entry->pid = buf->pid;
582 entry->tid = buf->tid;
583
584 /*
585 * Pull the tag out.
586 */
587 eventData = (const unsigned char*) buf->msg;
588 inCount = buf->len;
589 if (inCount < 4)
590 return -1;
591 tagIndex = get4LE(eventData);
592 eventData += 4;
593 inCount -= 4;
594
595 if (map != NULL) {
596 entry->tag = android_lookupEventTag(map, tagIndex);
597 } else {
598 entry->tag = NULL;
599 }
600
601 /*
602 * If we don't have a map, or didn't find the tag number in the map,
603 * stuff a generated tag value into the start of the output buffer and
604 * shift the buffer pointers down.
605 */
606 if (entry->tag == NULL) {
607 int tagLen;
608
609 tagLen = snprintf(messageBuf, messageBufLen, "[%d]", tagIndex);
610 entry->tag = messageBuf;
611 messageBuf += tagLen+1;
612 messageBufLen -= tagLen+1;
613 }
614
615 /*
616 * Format the event log data into the buffer.
617 */
618 char* outBuf = messageBuf;
619 size_t outRemaining = messageBufLen-1; /* leave one for nul byte */
620 int result;
621 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
622 &outRemaining);
623 if (result < 0) {
624 fprintf(stderr, "Binary log entry conversion failed\n");
625 return -1;
626 } else if (result == 1) {
627 if (outBuf > messageBuf) {
628 /* leave an indicator */
629 *(outBuf-1) = '!';
630 } else {
631 /* no room to output anything at all */
632 *outBuf++ = '!';
633 outRemaining--;
634 }
635 /* pretend we ate all the data */
636 inCount = 0;
637 }
638
639 /* eat the silly terminating '\n' */
640 if (inCount == 1 && *eventData == '\n') {
641 eventData++;
642 inCount--;
643 }
644
645 if (inCount != 0) {
646 fprintf(stderr,
647 "Warning: leftover binary log data (%d bytes)\n", inCount);
648 }
649
650 /*
651 * Terminate the buffer. The NUL byte does not count as part of
652 * entry->messageLen.
653 */
654 *outBuf = '\0';
655 entry->messageLen = outBuf - messageBuf;
656 assert(entry->messageLen == (messageBufLen-1) - outRemaining);
657
658 entry->message = messageBuf;
659
660 return 0;
661}
662
663/**
664 * Formats a log message into a buffer
665 *
666 * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
667 * If return value != defaultBuffer, caller must call free()
668 * Returns NULL on malloc error
669 */
670
671char *android_log_formatLogLine (
672 AndroidLogFormat *p_format,
673 char *defaultBuffer,
674 size_t defaultBufferSize,
675 const AndroidLogEntry *entry,
676 size_t *p_outLength)
677{
678#if defined(HAVE_LOCALTIME_R)
679 struct tm tmBuf;
680#endif
681 struct tm* ptm;
682 char timeBuf[32];
683 char headerBuf[128];
684 char prefixBuf[128], suffixBuf[128];
685 char priChar;
686 int prefixSuffixIsHeaderFooter = 0;
687 char * ret = NULL;
688
689 priChar = filterPriToChar(entry->priority);
690
691 /*
692 * Get the current date/time in pretty form
693 *
694 * It's often useful when examining a log with "less" to jump to
695 * a specific point in the file by searching for the date/time stamp.
696 * For this reason it's very annoying to have regexp meta characters
697 * in the time stamp. Don't use forward slashes, parenthesis,
698 * brackets, asterisks, or other special chars here.
699 */
700#if defined(HAVE_LOCALTIME_R)
701 ptm = localtime_r(&(entry->tv_sec), &tmBuf);
702#else
703 ptm = localtime(&(entry->tv_sec));
704#endif
705 //strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm);
706 strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
707
708 /*
709 * Construct a buffer containing the log header and log message.
710 */
711 size_t prefixLen, suffixLen;
712
713 switch (p_format->format) {
714 case FORMAT_TAG:
715 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
716 "%c/%-8s: ", priChar, entry->tag);
717 strcpy(suffixBuf, "\n"); suffixLen = 1;
718 break;
719 case FORMAT_PROCESS:
720 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
721 "%c(%5d) ", priChar, entry->pid);
722 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf),
723 " (%s)\n", entry->tag);
724 break;
725 case FORMAT_THREAD:
726 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
727 "%c(%5d:%p) ", priChar, entry->pid, (void*)entry->tid);
728 strcpy(suffixBuf, "\n");
729 suffixLen = 1;
730 break;
731 case FORMAT_RAW:
732 prefixBuf[0] = 0;
733 prefixLen = 0;
734 strcpy(suffixBuf, "\n");
735 suffixLen = 1;
736 break;
737 case FORMAT_TIME:
738 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
739 "%s.%03ld %c/%-8s(%5d): ", timeBuf, entry->tv_nsec / 1000000,
740 priChar, entry->tag, entry->pid);
741 strcpy(suffixBuf, "\n");
742 suffixLen = 1;
743 break;
744 case FORMAT_THREADTIME:
745 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
746 "%s.%03ld %5d %5d %c %-8s: ", timeBuf, entry->tv_nsec / 1000000,
747 (int)entry->pid, (int)entry->tid, priChar, entry->tag);
748 strcpy(suffixBuf, "\n");
749 suffixLen = 1;
750 break;
751 case FORMAT_LONG:
752 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
753 "[ %s.%03ld %5d:%p %c/%-8s ]\n",
754 timeBuf, entry->tv_nsec / 1000000, entry->pid,
755 (void*)entry->tid, priChar, entry->tag);
756 strcpy(suffixBuf, "\n\n");
757 suffixLen = 2;
758 prefixSuffixIsHeaderFooter = 1;
759 break;
760 case FORMAT_BRIEF:
761 default:
762 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
763 "%c/%-8s(%5d): ", priChar, entry->tag, entry->pid);
764 strcpy(suffixBuf, "\n");
765 suffixLen = 1;
766 break;
767 }
Keith Prestonb45b5c92010-02-11 15:12:53 -0600768 /* snprintf has a weird return value. It returns what would have been
769 * written given a large enough buffer. In the case that the prefix is
770 * longer then our buffer(128), it messes up the calculations below
771 * possibly causing heap corruption. To avoid this we double check and
772 * set the length at the maximum (size minus null byte)
773 */
774 if(prefixLen >= sizeof(prefixBuf))
775 prefixLen = sizeof(prefixBuf) - 1;
776 if(suffixLen >= sizeof(suffixBuf))
777 suffixLen = sizeof(suffixBuf) - 1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700778
779 /* the following code is tragically unreadable */
780
781 size_t numLines;
782 size_t i;
783 char *p;
784 size_t bufferSize;
785 const char *pm;
786
787 if (prefixSuffixIsHeaderFooter) {
788 // we're just wrapping message with a header/footer
789 numLines = 1;
790 } else {
791 pm = entry->message;
792 numLines = 0;
793
794 // The line-end finding here must match the line-end finding
795 // in for ( ... numLines...) loop below
796 while (pm < (entry->message + entry->messageLen)) {
797 if (*pm++ == '\n') numLines++;
798 }
799 // plus one line for anything not newline-terminated at the end
800 if (pm > entry->message && *(pm-1) != '\n') numLines++;
801 }
802
803 // this is an upper bound--newlines in message may be counted
804 // extraneously
805 bufferSize = (numLines * (prefixLen + suffixLen)) + entry->messageLen + 1;
806
807 if (defaultBufferSize >= bufferSize) {
808 ret = defaultBuffer;
809 } else {
810 ret = (char *)malloc(bufferSize);
811
812 if (ret == NULL) {
813 return ret;
814 }
815 }
816
817 ret[0] = '\0'; /* to start strcat off */
818
819 p = ret;
820 pm = entry->message;
821
822 if (prefixSuffixIsHeaderFooter) {
823 strcat(p, prefixBuf);
824 p += prefixLen;
825 strncat(p, entry->message, entry->messageLen);
826 p += entry->messageLen;
827 strcat(p, suffixBuf);
828 p += suffixLen;
829 } else {
830 while(pm < (entry->message + entry->messageLen)) {
831 const char *lineStart;
832 size_t lineLen;
833
834 lineStart = pm;
835
836 // Find the next end-of-line in message
837 while (pm < (entry->message + entry->messageLen)
838 && *pm != '\n') pm++;
839 lineLen = pm - lineStart;
840
841 strcat(p, prefixBuf);
842 p += prefixLen;
843 strncat(p, lineStart, lineLen);
844 p += lineLen;
845 strcat(p, suffixBuf);
846 p += suffixLen;
847
848 if (*pm == '\n') pm++;
849 }
850 }
851
852 if (p_outLength != NULL) {
853 *p_outLength = p - ret;
854 }
855
856 return ret;
857}
858
859/**
860 * Either print or do not print log line, based on filter
861 *
862 * Returns count bytes written
863 */
864
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800865int android_log_printLogLine(
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700866 AndroidLogFormat *p_format,
867 int fd,
868 const AndroidLogEntry *entry)
869{
870 int ret;
871 char defaultBuffer[512];
872 char *outBuffer = NULL;
873 size_t totalLen;
874
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700875 outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
876 sizeof(defaultBuffer), entry, &totalLen);
877
878 if (!outBuffer)
879 return -1;
880
881 do {
882 ret = write(fd, outBuffer, totalLen);
883 } while (ret < 0 && errno == EINTR);
884
885 if (ret < 0) {
886 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
887 ret = 0;
888 goto done;
889 }
890
891 if (((size_t)ret) < totalLen) {
892 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
893 (int)totalLen);
894 goto done;
895 }
896
897done:
898 if (outBuffer != defaultBuffer) {
899 free(outBuffer);
900 }
901
902 return ret;
903}
904
905
906
907void logprint_run_tests()
908{
909#if 0
910
911 fprintf(stderr, "tests disabled\n");
912
913#else
914
915 int err;
916 const char *tag;
917 AndroidLogFormat *p_format;
918
919 p_format = android_log_format_new();
920
921 fprintf(stderr, "running tests\n");
922
923 tag = "random";
924
925 android_log_addFilterRule(p_format,"*:i");
926
927 assert (ANDROID_LOG_INFO == filterPriForTag(p_format, "random"));
928 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
929 android_log_addFilterRule(p_format, "*");
930 assert (ANDROID_LOG_DEBUG == filterPriForTag(p_format, "random"));
931 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
932 android_log_addFilterRule(p_format, "*:v");
933 assert (ANDROID_LOG_VERBOSE == filterPriForTag(p_format, "random"));
934 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
935 android_log_addFilterRule(p_format, "*:i");
936 assert (ANDROID_LOG_INFO == filterPriForTag(p_format, "random"));
937 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
938
939 android_log_addFilterRule(p_format, "random");
940 assert (ANDROID_LOG_VERBOSE == filterPriForTag(p_format, "random"));
941 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
942 android_log_addFilterRule(p_format, "random:v");
943 assert (ANDROID_LOG_VERBOSE == filterPriForTag(p_format, "random"));
944 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
945 android_log_addFilterRule(p_format, "random:d");
946 assert (ANDROID_LOG_DEBUG == filterPriForTag(p_format, "random"));
947 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
948 android_log_addFilterRule(p_format, "random:w");
949 assert (ANDROID_LOG_WARN == filterPriForTag(p_format, "random"));
950 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
951
952 android_log_addFilterRule(p_format, "crap:*");
953 assert (ANDROID_LOG_VERBOSE== filterPriForTag(p_format, "crap"));
954 assert(android_log_shouldPrintLine(p_format, "crap", ANDROID_LOG_VERBOSE) > 0);
955
956 // invalid expression
957 err = android_log_addFilterRule(p_format, "random:z");
958 assert (err < 0);
959 assert (ANDROID_LOG_WARN == filterPriForTag(p_format, "random"));
960 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
961
962 // Issue #550946
963 err = android_log_addFilterString(p_format, " ");
964 assert(err == 0);
965 assert(ANDROID_LOG_WARN == filterPriForTag(p_format, "random"));
966
967 // note trailing space
968 err = android_log_addFilterString(p_format, "*:s random:d ");
969 assert(err == 0);
970 assert(ANDROID_LOG_DEBUG == filterPriForTag(p_format, "random"));
971
972 err = android_log_addFilterString(p_format, "*:s random:z");
973 assert(err < 0);
974
975
976#if 0
977 char *ret;
978 char defaultBuffer[512];
979
980 ret = android_log_formatLogLine(p_format,
981 defaultBuffer, sizeof(defaultBuffer), 0, ANDROID_LOG_ERROR, 123,
982 123, 123, "random", "nofile", strlen("Hello"), "Hello", NULL);
983#endif
984
985
986 fprintf(stderr, "tests complete\n");
987#endif
988}