summaryrefslogtreecommitdiffstats
path: root/liblog
diff options
context:
space:
mode:
authorThe Android Open Source Project2008-10-21 09:00:00 -0500
committerThe Android Open Source Project2008-10-21 09:00:00 -0500
commit4f6e8d7a00cbeda1e70cc15be9c4af1018bdad53 (patch)
tree54fd1b2695a591d2306d41264df67c53077b752c /liblog
downloadplatform-system-core-4f6e8d7a00cbeda1e70cc15be9c4af1018bdad53.tar.gz
platform-system-core-4f6e8d7a00cbeda1e70cc15be9c4af1018bdad53.tar.xz
platform-system-core-4f6e8d7a00cbeda1e70cc15be9c4af1018bdad53.zip
Initial Contribution
Diffstat (limited to 'liblog')
-rw-r--r--liblog/Android.mk72
-rw-r--r--liblog/event_tag_map.c438
-rw-r--r--liblog/fake_log_device.c677
-rw-r--r--liblog/logd_write.c229
-rw-r--r--liblog/logprint.c972
5 files changed, 2388 insertions, 0 deletions
diff --git a/liblog/Android.mk b/liblog/Android.mk
new file mode 100644
index 000000000..0eec87f04
--- /dev/null
+++ b/liblog/Android.mk
@@ -0,0 +1,72 @@
1#
2# Copyright (C) 2008 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16LOCAL_PATH := $(my-dir)
17include $(CLEAR_VARS)
18
19liblog_sources := logd_write.c
20
21# some files must not be compiled when building against Mingw
22# they correspond to features not used by our host development tools
23# which are also hard or even impossible to port to native Win32
24WITH_MINGW :=
25ifeq ($(HOST_OS),windows)
26 ifeq ($(strip $(USE_CYGWIN)),)
27 WITH_MINGW := true
28 endif
29endif
30# USE_MINGW is defined when we build against Mingw on Linux
31ifneq ($(strip $(USE_MINGW)),)
32 WITH_MINGW := true
33endif
34
35ifndef WITH_MINGW
36 liblog_sources += \
37 logprint.c \
38 event_tag_map.c
39endif
40
41liblog_host_sources := $(liblog_sources) fake_log_device.c
42
43# Static library for host
44# ========================================================
45LOCAL_MODULE := liblog
46LOCAL_SRC_FILES := $(liblog_host_sources)
47LOCAL_LDLIBS := -lpthread
48LOCAL_CFLAGS := -DFAKE_LOG_DEVICE=1
49include $(BUILD_HOST_STATIC_LIBRARY)
50
51ifeq ($(TARGET_SIMULATOR),true)
52 # Shared library for simulator
53 # ========================================================
54 include $(CLEAR_VARS)
55 LOCAL_MODULE := liblog
56 LOCAL_SRC_FILES := $(liblog_host_sources)
57 LOCAL_LDLIBS := -lpthread
58 LOCAL_CFLAGS := -DFAKE_LOG_DEVICE=1
59 include $(BUILD_SHARED_LIBRARY)
60else # !sim
61 # Shared and static library for target
62 # ========================================================
63 include $(CLEAR_VARS)
64 LOCAL_MODULE := liblog
65 LOCAL_SRC_FILES := $(liblog_sources)
66 include $(BUILD_STATIC_LIBRARY)
67
68 include $(CLEAR_VARS)
69 LOCAL_MODULE := liblog
70 LOCAL_WHOLE_STATIC_LIBRARIES := liblog
71 include $(BUILD_SHARED_LIBRARY)
72endif # !sim
diff --git a/liblog/event_tag_map.c b/liblog/event_tag_map.c
new file mode 100644
index 000000000..e70754e17
--- /dev/null
+++ b/liblog/event_tag_map.c
@@ -0,0 +1,438 @@
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include "cutils/event_tag_map.h"
17#include "cutils/log.h"
18
19#include <stdlib.h>
20#include <string.h>
21#include <fcntl.h>
22#include <sys/mman.h>
23#include <errno.h>
24#include <assert.h>
25
26#define OUT_TAG "EventTagMap"
27
28/*
29 * Single entry.
30 */
31typedef struct EventTag {
32 unsigned int tagIndex;
33 const char* tagStr;
34} EventTag;
35
36/*
37 * Map.
38 */
39struct EventTagMap {
40 /* memory-mapped source file; we get strings from here */
41 void* mapAddr;
42 size_t mapLen;
43
44 /* array of event tags, sorted numerically by tag index */
45 EventTag* tagArray;
46 int numTags;
47};
48
49/* fwd */
50static int processFile(EventTagMap* map);
51static int countMapLines(const EventTagMap* map);
52static int parseMapLines(EventTagMap* map);
53static int scanTagLine(char** pData, EventTag* tag, int lineNum);
54static int sortTags(EventTagMap* map);
55static void dumpTags(const EventTagMap* map);
56
57
58/*
59 * Open the map file and allocate a structure to manage it.
60 *
61 * We create a private mapping because we want to terminate the log tag
62 * strings with '\0'.
63 */
64EventTagMap* android_openEventTagMap(const char* fileName)
65{
66 EventTagMap* newTagMap;
67 off_t end;
68 int fd = -1;
69
70 newTagMap = calloc(1, sizeof(EventTagMap));
71 if (newTagMap == NULL)
72 return NULL;
73
74 fd = open(fileName, O_RDONLY);
75 if (fd < 0) {
76 fprintf(stderr, "%s: unable to open map '%s': %s\n",
77 OUT_TAG, fileName, strerror(errno));
78 goto fail;
79 }
80
81 end = lseek(fd, 0L, SEEK_END);
82 (void) lseek(fd, 0L, SEEK_SET);
83 if (end < 0) {
84 fprintf(stderr, "%s: unable to seek map '%s'\n", OUT_TAG, fileName);
85 goto fail;
86 }
87
88 newTagMap->mapAddr = mmap(NULL, end, PROT_READ | PROT_WRITE, MAP_PRIVATE,
89 fd, 0);
90 if (newTagMap->mapAddr == MAP_FAILED) {
91 fprintf(stderr, "%s: mmap(%s) failed: %s\n",
92 OUT_TAG, fileName, strerror(errno));
93 goto fail;
94 }
95 newTagMap->mapLen = end;
96
97 if (processFile(newTagMap) != 0)
98 goto fail;
99
100 return newTagMap;
101
102fail:
103 android_closeEventTagMap(newTagMap);
104 if (fd >= 0)
105 close(fd);
106 return NULL;
107}
108
109/*
110 * Close the map.
111 */
112void android_closeEventTagMap(EventTagMap* map)
113{
114 if (map == NULL)
115 return;
116
117 munmap(map->mapAddr, map->mapLen);
118 free(map);
119}
120
121/*
122 * Look up an entry in the map.
123 *
124 * The entries are sorted by tag number, so we can do a binary search.
125 */
126const char* android_lookupEventTag(const EventTagMap* map, int tag)
127{
128 int hi, lo, mid;
129
130 lo = 0;
131 hi = map->numTags-1;
132
133 while (lo <= hi) {
134 int cmp;
135
136 mid = (lo+hi)/2;
137 cmp = map->tagArray[mid].tagIndex - tag;
138 if (cmp < 0) {
139 /* tag is bigger */
140 lo = mid + 1;
141 } else if (cmp > 0) {
142 /* tag is smaller */
143 hi = mid - 1;
144 } else {
145 /* found */
146 return map->tagArray[mid].tagStr;
147 }
148 }
149
150 return NULL;
151}
152
153
154
155/*
156 * Determine whether "c" is a whitespace char.
157 */
158static inline int isCharWhitespace(char c)
159{
160 return (c == ' ' || c == '\n' || c == '\r' || c == '\t');
161}
162
163/*
164 * Determine whether "c" is a valid tag char.
165 */
166static inline int isCharValidTag(char c)
167{
168 return ((c >= 'A' && c <= 'Z') ||
169 (c >= 'a' && c <= 'z') ||
170 (c >= '0' && c <= '9') ||
171 (c == '_'));
172}
173
174/*
175 * Determine whether "c" is a valid decimal digit.
176 */
177static inline int isCharDigit(char c)
178{
179 return (c >= '0' && c <= '9');
180}
181
182
183/*
184 * Crunch through the file, parsing the contents and creating a tag index.
185 */
186static int processFile(EventTagMap* map)
187{
188 EventTag* tagArray = NULL;
189
190 /* get a tag count */
191 map->numTags = countMapLines(map);
192 if (map->numTags < 0)
193 return -1;
194
195 //printf("+++ found %d tags\n", map->numTags);
196
197 /* allocate storage for the tag index array */
198 map->tagArray = calloc(1, sizeof(EventTag) * map->numTags);
199 if (map->tagArray == NULL)
200 return -1;
201
202 /* parse the file, null-terminating tag strings */
203 if (parseMapLines(map) != 0) {
204 fprintf(stderr, "%s: file parse failed\n", OUT_TAG);
205 return -1;
206 }
207
208 /* sort the tags and check for duplicates */
209 if (sortTags(map) != 0)
210 return -1;
211
212 return 0;
213}
214
215/*
216 * Run through all lines in the file, determining whether they're blank,
217 * comments, or possibly have a tag entry.
218 *
219 * This is a very "loose" scan. We don't try to detect syntax errors here.
220 * The later pass is more careful, but the number of tags found there must
221 * match the number of tags found here.
222 *
223 * Returns the number of potential tag entries found.
224 */
225static int countMapLines(const EventTagMap* map)
226{
227 int numTags, unknown;
228 const char* cp;
229 const char* endp;
230
231 cp = (const char*) map->mapAddr;
232 endp = cp + map->mapLen;
233
234 numTags = 0;
235 unknown = 1;
236 while (cp < endp) {
237 if (*cp == '\n') {
238 unknown = 1;
239 } else if (unknown) {
240 if (isCharDigit(*cp)) {
241 /* looks like a tag to me */
242 numTags++;
243 unknown = 0;
244 } else if (isCharWhitespace(*cp)) {
245 /* might be leading whitespace before tag num, keep going */
246 } else {
247 /* assume comment; second pass can complain in detail */
248 unknown = 0;
249 }
250 } else {
251 /* we've made up our mind; just scan to end of line */
252 }
253 cp++;
254 }
255
256 return numTags;
257}
258
259/*
260 * Parse the tags out of the file.
261 */
262static int parseMapLines(EventTagMap* map)
263{
264 int tagNum, lineStart, lineNum;
265 char* cp;
266 char* endp;
267
268 cp = (char*) map->mapAddr;
269 endp = cp + map->mapLen;
270
271 /* insist on EOL at EOF; simplifies parsing and null-termination */
272 if (*(endp-1) != '\n') {
273 fprintf(stderr, "%s: map file missing EOL on last line\n", OUT_TAG);
274 return -1;
275 }
276
277 tagNum = 0;
278 lineStart = 1;
279 lineNum = 1;
280 while (cp < endp) {
281 //printf("{%02x}", *cp); fflush(stdout);
282 if (*cp == '\n') {
283 lineStart = 1;
284 lineNum++;
285 } else if (lineStart) {
286 if (*cp == '#') {
287 /* comment; just scan to end */
288 lineStart = 0;
289 } else if (isCharDigit(*cp)) {
290 /* looks like a tag; scan it out */
291 if (tagNum >= map->numTags) {
292 fprintf(stderr,
293 "%s: more tags than expected (%d)\n", OUT_TAG, tagNum);
294 return -1;
295 }
296 if (scanTagLine(&cp, &map->tagArray[tagNum], lineNum) != 0)
297 return -1;
298 tagNum++;
299 lineNum++; // we eat the '\n'
300 /* leave lineStart==1 */
301 } else if (isCharWhitespace(*cp)) {
302 /* looks like leading whitespace; keep scanning */
303 } else {
304 fprintf(stderr,
305 "%s: unexpected chars (0x%02x) in tag number on line %d\n",
306 OUT_TAG, *cp, lineNum);
307 return -1;
308 }
309 } else {
310 /* this is a blank or comment line */
311 }
312 cp++;
313 }
314
315 if (tagNum != map->numTags) {
316 fprintf(stderr, "%s: parsed %d tags, expected %d\n",
317 OUT_TAG, tagNum, map->numTags);
318 return -1;
319 }
320
321 return 0;
322}
323
324/*
325 * Scan one tag line.
326 *
327 * "*pData" should be pointing to the first digit in the tag number. On
328 * successful return, it will be pointing to the last character in the
329 * tag line (i.e. the character before the start of the next line).
330 *
331 * Returns 0 on success, nonzero on failure.
332 */
333static int scanTagLine(char** pData, EventTag* tag, int lineNum)
334{
335 char* cp = *pData;
336 char* startp;
337 char* endp;
338 unsigned long val;
339
340 startp = cp;
341 while (isCharDigit(*++cp))
342 ;
343 *cp = '\0';
344
345 val = strtoul(startp, &endp, 10);
346 assert(endp == cp);
347 if (endp != cp)
348 fprintf(stderr, "ARRRRGH\n");
349
350 tag->tagIndex = val;
351
352 while (*++cp != '\n' && isCharWhitespace(*cp))
353 ;
354
355 if (*cp == '\n') {
356 fprintf(stderr,
357 "%s: missing tag string on line %d\n", OUT_TAG, lineNum);
358 return -1;
359 }
360
361 tag->tagStr = cp;
362
363 while (isCharValidTag(*++cp))
364 ;
365
366 if (*cp == '\n') {
367 /* null terminate and return */
368 *cp = '\0';
369 } else if (isCharWhitespace(*cp)) {
370 /* CRLF or trailin spaces; zap this char, then scan for the '\n' */
371 *cp = '\0';
372
373 /* just ignore the rest of the line till \n
374 TODO: read the tag description that follows the tag name
375 */
376 while (*++cp != '\n') {
377 }
378 } else {
379 fprintf(stderr,
380 "%s: invalid tag chars on line %d\n", OUT_TAG, lineNum);
381 return -1;
382 }
383
384 *pData = cp;
385
386 //printf("+++ Line %d: got %d '%s'\n", lineNum, tag->tagIndex, tag->tagStr);
387 return 0;
388}
389
390/*
391 * Compare two EventTags.
392 */
393static int compareEventTags(const void* v1, const void* v2)
394{
395 const EventTag* tag1 = (const EventTag*) v1;
396 const EventTag* tag2 = (const EventTag*) v2;
397
398 return tag1->tagIndex - tag2->tagIndex;
399}
400
401/*
402 * Sort the EventTag array so we can do fast lookups by tag index. After
403 * the sort we do a quick check for duplicate tag indices.
404 *
405 * Returns 0 on success.
406 */
407static int sortTags(EventTagMap* map)
408{
409 int i;
410
411 qsort(map->tagArray, map->numTags, sizeof(EventTag), compareEventTags);
412
413 for (i = 1; i < map->numTags; i++) {
414 if (map->tagArray[i].tagIndex == map->tagArray[i-1].tagIndex) {
415 fprintf(stderr, "%s: duplicate tag entries (%d:%s and %d:%s)\n",
416 OUT_TAG,
417 map->tagArray[i].tagIndex, map->tagArray[i].tagStr,
418 map->tagArray[i-1].tagIndex, map->tagArray[i-1].tagStr);
419 return -1;
420 }
421 }
422
423 return 0;
424}
425
426/*
427 * Dump the tag array for debugging.
428 */
429static void dumpTags(const EventTagMap* map)
430{
431 int i;
432
433 for (i = 0; i < map->numTags; i++) {
434 const EventTag* tag = &map->tagArray[i];
435 printf(" %3d: %6d '%s'\n", i, tag->tagIndex, tag->tagStr);
436 }
437}
438
diff --git a/liblog/fake_log_device.c b/liblog/fake_log_device.c
new file mode 100644
index 000000000..d9d67b473
--- /dev/null
+++ b/liblog/fake_log_device.c
@@ -0,0 +1,677 @@
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16/*
17 * Intercepts log messages intended for the Android log device.
18 * When running in the context of the simulator, the messages are
19 * passed on to the underlying (fake) log device. When not in the
20 * simulator, messages are printed to stderr.
21 */
22#include "cutils/logd.h"
23
24#include <stdlib.h>
25#include <string.h>
26#include <ctype.h>
27#include <errno.h>
28#include <fcntl.h>
29
30#ifdef HAVE_PTHREADS
31#include <pthread.h>
32#endif
33
34#define kMaxTagLen 16 /* from the long-dead utils/Log.cpp */
35
36#define kTagSetSize 16 /* arbitrary */
37
38#if 0
39#define TRACE(...) printf("fake_log_device: " __VA_ARGS__)
40#else
41#define TRACE(...) ((void)0)
42#endif
43
44/* from the long-dead utils/Log.cpp */
45typedef enum {
46 FORMAT_OFF = 0,
47 FORMAT_BRIEF,
48 FORMAT_PROCESS,
49 FORMAT_TAG,
50 FORMAT_THREAD,
51 FORMAT_RAW,
52 FORMAT_TIME,
53 FORMAT_THREADTIME,
54 FORMAT_LONG
55} LogFormat;
56
57
58/*
59 * Log driver state.
60 */
61typedef struct LogState {
62 /* the fake fd that's seen by the user */
63 int fakeFd;
64
65 /* a printable name for this fake device */
66 char *debugName;
67
68 /* nonzero if this is a binary log */
69 int isBinary;
70
71 /* global minimum priority */
72 int globalMinPriority;
73
74 /* output format */
75 LogFormat outputFormat;
76
77 /* tags and priorities */
78 struct {
79 char tag[kMaxTagLen];
80 int minPriority;
81 } tagSet[kTagSetSize];
82} LogState;
83
84
85#ifdef HAVE_PTHREADS
86/*
87 * Locking. Since we're emulating a device, we need to be prepared
88 * to have multiple callers at the same time. This lock is used
89 * to both protect the fd list and to prevent LogStates from being
90 * freed out from under a user.
91 */
92static pthread_mutex_t fakeLogDeviceLock = PTHREAD_MUTEX_INITIALIZER;
93
94static void lock()
95{
96 pthread_mutex_lock(&fakeLogDeviceLock);
97}
98
99static void unlock()
100{
101 pthread_mutex_unlock(&fakeLogDeviceLock);
102}
103#else // !HAVE_PTHREADS
104#define lock() ((void)0)
105#define unlock() ((void)0)
106#endif // !HAVE_PTHREADS
107
108
109/*
110 * File descriptor management.
111 */
112#define FAKE_FD_BASE 10000
113#define MAX_OPEN_LOGS 16
114static LogState *openLogTable[MAX_OPEN_LOGS];
115
116/*
117 * Allocate an fd and associate a new LogState with it.
118 * The fd is available via the fakeFd field of the return value.
119 */
120static LogState *createLogState()
121{
122 size_t i;
123
124 for (i = 0; i < sizeof(openLogTable); i++) {
125 if (openLogTable[i] == NULL) {
126 openLogTable[i] = calloc(1, sizeof(LogState));
127 openLogTable[i]->fakeFd = FAKE_FD_BASE + i;
128 return openLogTable[i];
129 }
130 }
131 return NULL;
132}
133
134/*
135 * Translate an fd to a LogState.
136 */
137static LogState *fdToLogState(int fd)
138{
139 if (fd >= FAKE_FD_BASE && fd < FAKE_FD_BASE + MAX_OPEN_LOGS) {
140 return openLogTable[fd - FAKE_FD_BASE];
141 }
142 return NULL;
143}
144
145/*
146 * Unregister the fake fd and free the memory it pointed to.
147 */
148static void deleteFakeFd(int fd)
149{
150 LogState *ls;
151
152 lock();
153
154 ls = fdToLogState(fd);
155 if (ls != NULL) {
156 openLogTable[fd - FAKE_FD_BASE] = NULL;
157 free(ls->debugName);
158 free(ls);
159 }
160
161 unlock();
162}
163
164/*
165 * Configure logging based on ANDROID_LOG_TAGS environment variable. We
166 * need to parse a string that looks like
167 *
168 * *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
169 *
170 * The tag (or '*' for the global level) comes first, followed by a colon
171 * and a letter indicating the minimum priority level we're expected to log.
172 * This can be used to reveal or conceal logs with specific tags.
173 *
174 * We also want to check ANDROID_PRINTF_LOG to determine how the output
175 * will look.
176 */
177static void configureInitialState(const char* pathName, LogState* logState)
178{
179 static const int kDevLogLen = sizeof("/dev/log/") - 1;
180
181 logState->debugName = strdup(pathName);
182
183 /* identify binary logs */
184 if (strcmp(pathName + kDevLogLen, "events") == 0) {
185 logState->isBinary = 1;
186 }
187
188 /* global min priority defaults to "info" level */
189 logState->globalMinPriority = ANDROID_LOG_INFO;
190
191 /*
192 * This is based on the the long-dead utils/Log.cpp code.
193 */
194 const char* tags = getenv("ANDROID_LOG_TAGS");
195 TRACE("Found ANDROID_LOG_TAGS='%s'\n", tags);
196 if (tags != NULL) {
197 int entry = 0;
198
199 while (*tags != '\0') {
200 char tagName[kMaxTagLen];
201 int i, minPrio;
202
203 while (isspace(*tags))
204 tags++;
205
206 i = 0;
207 while (*tags != '\0' && !isspace(*tags) && *tags != ':' &&
208 i < kMaxTagLen)
209 {
210 tagName[i++] = *tags++;
211 }
212 if (i == kMaxTagLen) {
213 TRACE("ERROR: env tag too long (%d chars max)\n", kMaxTagLen-1);
214 return;
215 }
216 tagName[i] = '\0';
217
218 /* default priority, if there's no ":" part; also zero out '*' */
219 minPrio = ANDROID_LOG_VERBOSE;
220 if (tagName[0] == '*' && tagName[1] == '\0') {
221 minPrio = ANDROID_LOG_DEBUG;
222 tagName[0] = '\0';
223 }
224
225 if (*tags == ':') {
226 tags++;
227 if (*tags >= '0' && *tags <= '9') {
228 if (*tags >= ('0' + ANDROID_LOG_SILENT))
229 minPrio = ANDROID_LOG_VERBOSE;
230 else
231 minPrio = *tags - '\0';
232 } else {
233 switch (*tags) {
234 case 'v': minPrio = ANDROID_LOG_VERBOSE; break;
235 case 'd': minPrio = ANDROID_LOG_DEBUG; break;
236 case 'i': minPrio = ANDROID_LOG_INFO; break;
237 case 'w': minPrio = ANDROID_LOG_WARN; break;
238 case 'e': minPrio = ANDROID_LOG_ERROR; break;
239 case 'f': minPrio = ANDROID_LOG_FATAL; break;
240 case 's': minPrio = ANDROID_LOG_SILENT; break;
241 default: minPrio = ANDROID_LOG_DEFAULT; break;
242 }
243 }
244
245 tags++;
246 if (*tags != '\0' && !isspace(*tags)) {
247 TRACE("ERROR: garbage in tag env; expected whitespace\n");
248 TRACE(" env='%s'\n", tags);
249 return;
250 }
251 }
252
253 if (tagName[0] == 0) {
254 logState->globalMinPriority = minPrio;
255 TRACE("+++ global min prio %d\n", logState->globalMinPriority);
256 } else {
257 logState->tagSet[entry].minPriority = minPrio;
258 strcpy(logState->tagSet[entry].tag, tagName);
259 TRACE("+++ entry %d: %s:%d\n",
260 entry,
261 logState->tagSet[entry].tag,
262 logState->tagSet[entry].minPriority);
263 entry++;
264 }
265 }
266 }
267
268
269 /*
270 * Taken from the long-dead utils/Log.cpp
271 */
272 const char* fstr = getenv("ANDROID_PRINTF_LOG");
273 LogFormat format;
274 if (fstr == NULL) {
275 format = FORMAT_BRIEF;
276 } else {
277 if (strcmp(fstr, "brief") == 0)
278 format = FORMAT_BRIEF;
279 else if (strcmp(fstr, "process") == 0)
280 format = FORMAT_PROCESS;
281 else if (strcmp(fstr, "tag") == 0)
282 format = FORMAT_PROCESS;
283 else if (strcmp(fstr, "thread") == 0)
284 format = FORMAT_PROCESS;
285 else if (strcmp(fstr, "raw") == 0)
286 format = FORMAT_PROCESS;
287 else if (strcmp(fstr, "time") == 0)
288 format = FORMAT_PROCESS;
289 else if (strcmp(fstr, "long") == 0)
290 format = FORMAT_PROCESS;
291 else
292 format = (LogFormat) atoi(fstr); // really?!
293 }
294
295 logState->outputFormat = format;
296}
297
298/*
299 * Return a human-readable string for the priority level. Always returns
300 * a valid string.
301 */
302static const char* getPriorityString(int priority)
303{
304 /* the first character of each string should be unique */
305 static const char* priorityStrings[] = {
306 "Verbose", "Debug", "Info", "Warn", "Error", "Assert"
307 };
308 int idx;
309
310 idx = (int) priority - (int) ANDROID_LOG_VERBOSE;
311 if (idx < 0 ||
312 idx >= (int) (sizeof(priorityStrings) / sizeof(priorityStrings[0])))
313 return "?unknown?";
314 return priorityStrings[idx];
315}
316
317#ifndef HAVE_WRITEV
318/*
319 * Some platforms like WIN32 do not have writev().
320 * Make up something to replace it.
321 */
322static ssize_t fake_writev(int fd, const struct iovec *iov, int iovcnt) {
323 int result = 0;
324 struct iovec* end = iov + iovcnt;
325 for (; iov < end; iov++) {
326 int w = write(fd, iov->iov_base, iov->iov_len);
327 if (w != iov->iov_len) {
328 if (w < 0)
329 return w;
330 return result + w;
331 }
332 result += w;
333 }
334 return result;
335}
336
337#define writev fake_writev
338#endif
339
340
341/*
342 * Write a filtered log message to stderr.
343 *
344 * Log format parsing taken from the long-dead utils/Log.cpp.
345 */
346static void showLog(LogState *state,
347 int logPrio, const char* tag, const char* msg)
348{
349#if defined(HAVE_LOCALTIME_R)
350 struct tm tmBuf;
351#endif
352 struct tm* ptm;
353 char timeBuf[32];
354 char prefixBuf[128], suffixBuf[128];
355 char priChar;
356 time_t when;
357 pid_t pid, tid;
358
359 TRACE("LOG %d: %s %s", logPrio, tag, msg);
360
361 priChar = getPriorityString(logPrio)[0];
362 when = time(NULL);
363 pid = tid = getpid(); // find gettid()?
364
365 /*
366 * Get the current date/time in pretty form
367 *
368 * It's often useful when examining a log with "less" to jump to
369 * a specific point in the file by searching for the date/time stamp.
370 * For this reason it's very annoying to have regexp meta characters
371 * in the time stamp. Don't use forward slashes, parenthesis,
372 * brackets, asterisks, or other special chars here.
373 */
374#if defined(HAVE_LOCALTIME_R)
375 ptm = localtime_r(&when, &tmBuf);
376#else
377 ptm = localtime(&when);
378#endif
379 //strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm);
380 strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
381
382 /*
383 * Construct a buffer containing the log header and log message.
384 */
385 size_t prefixLen, suffixLen;
386
387 switch (state->outputFormat) {
388 case FORMAT_TAG:
389 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
390 "%c/%-8s: ", priChar, tag);
391 strcpy(suffixBuf, "\n"); suffixLen = 1;
392 break;
393 case FORMAT_PROCESS:
394 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
395 "%c(%5d) ", priChar, pid);
396 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf),
397 " (%s)\n", tag);
398 break;
399 case FORMAT_THREAD:
400 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
401 "%c(%5d:%p) ", priChar, pid, (void*)tid);
402 strcpy(suffixBuf, "\n"); suffixLen = 1;
403 break;
404 case FORMAT_RAW:
405 prefixBuf[0] = 0; prefixLen = 0;
406 strcpy(suffixBuf, "\n"); suffixLen = 1;
407 break;
408 case FORMAT_TIME:
409 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
410 "%s %-8s\n\t", timeBuf, tag);
411 strcpy(suffixBuf, "\n"); suffixLen = 1;
412 break;
413 case FORMAT_THREADTIME:
414 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
415 "%s %5d %5d %c %-8s \n\t", timeBuf, pid, tid, priChar, tag);
416 strcpy(suffixBuf, "\n"); suffixLen = 1;
417 break;
418 case FORMAT_LONG:
419 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
420 "[ %s %5d:%p %c/%-8s ]\n",
421 timeBuf, pid, (void*)tid, priChar, tag);
422 strcpy(suffixBuf, "\n\n"); suffixLen = 2;
423 break;
424 default:
425 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
426 "%c/%-8s(%5d): ", priChar, tag, pid);
427 strcpy(suffixBuf, "\n"); suffixLen = 1;
428 break;
429 }
430
431 /*
432 * Figure out how many lines there will be.
433 */
434 const char* end = msg + strlen(msg);
435 size_t numLines = 0;
436 const char* p = msg;
437 while (p < end) {
438 if (*p++ == '\n') numLines++;
439 }
440 if (p > msg && *(p-1) != '\n') numLines++;
441
442 /*
443 * Create an array of iovecs large enough to write all of
444 * the lines with a prefix and a suffix.
445 */
446 const size_t INLINE_VECS = 6;
447 struct iovec stackVec[INLINE_VECS];
448 struct iovec* vec = stackVec;
449
450 numLines *= 3; // 3 iovecs per line.
451 if (numLines > INLINE_VECS) {
452 vec = (struct iovec*)malloc(sizeof(struct iovec)*numLines);
453 if (vec == NULL) {
454 msg = "LOG: write failed, no memory";
455 numLines = 3;
456 }
457 }
458
459 /*
460 * Fill in the iovec pointers.
461 */
462 p = msg;
463 struct iovec* v = vec;
464 int totalLen = 0;
465 while (p < end) {
466 if (prefixLen > 0) {
467 v->iov_base = prefixBuf;
468 v->iov_len = prefixLen;
469 totalLen += prefixLen;
470 v++;
471 }
472 const char* start = p;
473 while (p < end && *p != '\n') p++;
474 if ((p-start) > 0) {
475 v->iov_base = (void*)start;
476 v->iov_len = p-start;
477 totalLen += p-start;
478 v++;
479 }
480 if (*p == '\n') p++;
481 if (suffixLen > 0) {
482 v->iov_base = suffixBuf;
483 v->iov_len = suffixLen;
484 totalLen += suffixLen;
485 v++;
486 }
487 }
488
489 /*
490 * Write the entire message to the log file with a single writev() call.
491 * We need to use this rather than a collection of printf()s on a FILE*
492 * because of multi-threading and multi-process issues.
493 *
494 * If the file was not opened with O_APPEND, this will produce interleaved
495 * output when called on the same file from multiple processes.
496 *
497 * If the file descriptor is actually a network socket, the writev()
498 * call may return with a partial write. Putting the writev() call in
499 * a loop can result in interleaved data. This can be alleviated
500 * somewhat by wrapping the writev call in the Mutex.
501 */
502
503 for(;;) {
504 int cc = writev(fileno(stderr), vec, v-vec);
505
506 if (cc == totalLen) break;
507
508 if (cc < 0) {
509 if(errno == EINTR) continue;
510
511 /* can't really log the failure; for now, throw out a stderr */
512 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
513 break;
514 } else {
515 /* shouldn't happen when writing to file or tty */
516 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", cc, totalLen);
517 break;
518 }
519 }
520
521 /* if we allocated storage for the iovecs, free it */
522 if (vec != stackVec)
523 free(vec);
524}
525
526
527/*
528 * Receive a log message. We happen to know that "vector" has three parts:
529 *
530 * priority (1 byte)
531 * tag (N bytes -- null-terminated ASCII string)
532 * message (N bytes -- null-terminated ASCII string)
533 */
534static ssize_t logWritev(int fd, const struct iovec* vector, int count)
535{
536 LogState* state;
537
538 /* Make sure that no-one frees the LogState while we're using it.
539 * Also guarantees that only one thread is in showLog() at a given
540 * time (if it matters).
541 */
542 lock();
543
544 state = fdToLogState(fd);
545 if (state == NULL) {
546 errno = EBADF;
547 goto error;
548 }
549
550 if (state->isBinary) {
551 TRACE("%s: ignoring binary log\n", state->debugName);
552 goto bail;
553 }
554
555 if (count != 3) {
556 TRACE("%s: writevLog with count=%d not expected\n",
557 state->debugName, count);
558 goto error;
559 }
560
561 /* pull out the three fields */
562 int logPrio = *(const char*)vector[0].iov_base;
563 const char* tag = (const char*) vector[1].iov_base;
564 const char* msg = (const char*) vector[2].iov_base;
565
566 /* see if this log tag is configured */
567 int i;
568 int minPrio = state->globalMinPriority;
569 for (i = 0; i < kTagSetSize; i++) {
570 if (state->tagSet[i].minPriority == ANDROID_LOG_UNKNOWN)
571 break; /* reached end of configured values */
572
573 if (strcmp(state->tagSet[i].tag, tag) == 0) {
574 //TRACE("MATCH tag '%s'\n", tag);
575 minPrio = state->tagSet[i].minPriority;
576 break;
577 }
578 }
579
580 if (logPrio >= minPrio) {
581 showLog(state, logPrio, tag, msg);
582 } else {
583 //TRACE("+++ NOLOG(%d): %s %s", logPrio, tag, msg);
584 }
585
586bail:
587 unlock();
588 return vector[0].iov_len + vector[1].iov_len + vector[2].iov_len;
589error:
590 unlock();
591 return -1;
592}
593
594/*
595 * Free up our state and close the fake descriptor.
596 */
597static int logClose(int fd)
598{
599 deleteFakeFd(fd);
600 return 0;
601}
602
603/*
604 * Open a log output device and return a fake fd.
605 */
606static int logOpen(const char* pathName, int flags)
607{
608 LogState *logState;
609 int fd = -1;
610
611 lock();
612
613 logState = createLogState();
614 if (logState != NULL) {
615 configureInitialState(pathName, logState);
616 fd = logState->fakeFd;
617 } else {
618 errno = ENFILE;
619 }
620
621 unlock();
622
623 return fd;
624}
625
626
627/*
628 * Runtime redirection. If this binary is running in the simulator,
629 * just pass log messages to the emulated device. If it's running
630 * outside of the simulator, write the log messages to stderr.
631 */
632
633static int (*redirectOpen)(const char *pathName, int flags) = NULL;
634static int (*redirectClose)(int fd) = NULL;
635static ssize_t (*redirectWritev)(int fd, const struct iovec* vector, int count)
636 = NULL;
637
638static void setRedirects()
639{
640 const char *ws;
641
642 /* Wrapsim sets this environment variable on children that it's
643 * created using its LD_PRELOAD wrapper.
644 */
645 ws = getenv("ANDROID_WRAPSIM");
646 if (ws != NULL && strcmp(ws, "1") == 0) {
647 /* We're running inside wrapsim, so we can just write to the device. */
648 redirectOpen = (int (*)(const char *pathName, int flags))open;
649 redirectClose = close;
650 redirectWritev = writev;
651 } else {
652 /* There's no device to delegate to; handle the logging ourselves. */
653 redirectOpen = logOpen;
654 redirectClose = logClose;
655 redirectWritev = logWritev;
656 }
657}
658
659int fakeLogOpen(const char *pathName, int flags)
660{
661 if (redirectOpen == NULL) {
662 setRedirects();
663 }
664 return redirectOpen(pathName, flags);
665}
666
667int fakeLogClose(int fd)
668{
669 /* Assume that open() was called first. */
670 return redirectClose(fd);
671}
672
673ssize_t fakeLogWritev(int fd, const struct iovec* vector, int count)
674{
675 /* Assume that open() was called first. */
676 return redirectWritev(fd, vector, count);
677}
diff --git a/liblog/logd_write.c b/liblog/logd_write.c
new file mode 100644
index 000000000..d5d81383b
--- /dev/null
+++ b/liblog/logd_write.c
@@ -0,0 +1,229 @@
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include <time.h>
17#include <stdio.h>
18#ifdef HAVE_PTHREADS
19#include <pthread.h>
20#endif
21#include <unistd.h>
22#include <errno.h>
23#include <fcntl.h>
24#include <string.h>
25#include <stdlib.h>
26#include <stdarg.h>
27
28#include <utils/logger.h>
29#include <cutils/logd.h>
30
31#define LOG_BUF_SIZE 1024
32
33#if FAKE_LOG_DEVICE
34// This will be defined when building for the host.
35#define log_open(pathname, flags) fakeLogOpen(pathname, flags)
36#define log_writev(filedes, vector, count) fakeLogWritev(filedes, vector, count)
37#define log_close(filedes) fakeLogClose(filedes)
38#else
39#define log_open(pathname, flags) open(pathname, flags)
40#define log_writev(filedes, vector, count) writev(filedes, vector, count)
41#define log_close(filedes) close(filedes)
42#endif
43
44typedef enum {
45 LOG_ID_MAIN = 0,
46 LOG_ID_RADIO,
47 LOG_ID_EVENTS,
48 LOG_ID_MAX
49} log_id_t;
50
51static int __write_to_log_init(log_id_t, struct iovec *vec, size_t nr);
52static int (*write_to_log)(log_id_t, struct iovec *vec, size_t nr) =
53 __write_to_log_init;
54#ifdef HAVE_PTHREADS
55static pthread_mutex_t log_init_lock = PTHREAD_MUTEX_INITIALIZER;
56#endif
57
58static int log_fds[(int)LOG_ID_MAX] = { -1, -1, -1 };
59
60/*
61 * This is used by the C++ code to decide if it should write logs through
62 * the C code. Basically, if /dev/log/... is available, we're running in
63 * the simulator rather than a desktop tool and want to use the device.
64 */
65static enum {
66 kLogUninitialized, kLogNotAvailable, kLogAvailable
67} g_log_status = kLogUninitialized;
68int __android_log_dev_available(void)
69{
70 if (g_log_status == kLogUninitialized) {
71 if (access("/dev/"LOGGER_LOG_MAIN, W_OK) == 0)
72 g_log_status = kLogAvailable;
73 else
74 g_log_status = kLogNotAvailable;
75 }
76
77 return (g_log_status == kLogAvailable);
78}
79
80static int __write_to_log_null(log_id_t log_fd, struct iovec *vec, size_t nr)
81{
82 return -1;
83}
84
85static int __write_to_log_kernel(log_id_t log_id, struct iovec *vec, size_t nr)
86{
87 ssize_t ret;
88 int log_fd;
89
90 if (/*(int)log_id >= 0 &&*/ (int)log_id < (int)LOG_ID_MAX) {
91 log_fd = log_fds[(int)log_id];
92 } else {
93 return EBADF;
94 }
95
96 do {
97 ret = log_writev(log_fd, vec, nr);
98 } while (ret < 0 && errno == EINTR);
99
100 return ret;
101}
102
103static int __write_to_log_init(log_id_t log_id, struct iovec *vec, size_t nr)
104{
105#ifdef HAVE_PTHREADS
106 pthread_mutex_lock(&log_init_lock);
107#endif
108
109 if (write_to_log == __write_to_log_init) {
110 log_fds[LOG_ID_MAIN] = log_open("/dev/"LOGGER_LOG_MAIN, O_WRONLY);
111 log_fds[LOG_ID_RADIO] = log_open("/dev/"LOGGER_LOG_RADIO, O_WRONLY);
112 log_fds[LOG_ID_EVENTS] = log_open("/dev/"LOGGER_LOG_EVENTS, O_WRONLY);
113
114 write_to_log = __write_to_log_kernel;
115
116 if (log_fds[LOG_ID_MAIN] < 0 || log_fds[LOG_ID_RADIO] < 0 ||
117 log_fds[LOG_ID_EVENTS] < 0) {
118 log_close(log_fds[LOG_ID_MAIN]);
119 log_close(log_fds[LOG_ID_RADIO]);
120 log_close(log_fds[LOG_ID_EVENTS]);
121 log_fds[LOG_ID_MAIN] = -1;
122 log_fds[LOG_ID_RADIO] = -1;
123 log_fds[LOG_ID_EVENTS] = -1;
124 write_to_log = __write_to_log_null;
125 }
126 }
127
128#ifdef HAVE_PTHREADS
129 pthread_mutex_unlock(&log_init_lock);
130#endif
131
132 return write_to_log(log_id, vec, nr);
133}
134
135int __android_log_write(int prio, const char *tag, const char *msg)
136{
137 struct iovec vec[3];
138 log_id_t log_id = LOG_ID_MAIN;
139
140 if (!tag)
141 tag = "";
142
143 /* XXX: This needs to go! */
144 if (!strcmp(tag, "HTC_RIL") ||
145 !strcmp(tag, "RILJ") ||
146 !strcmp(tag, "RILC") ||
147 !strcmp(tag, "RIL") ||
148 !strcmp(tag, "AT") ||
149 !strcmp(tag, "GSM") ||
150 !strcmp(tag, "STK"))
151 log_id = LOG_ID_RADIO;
152
153 vec[0].iov_base = (unsigned char *) &prio;
154 vec[0].iov_len = 1;
155 vec[1].iov_base = (void *) tag;
156 vec[1].iov_len = strlen(tag) + 1;
157 vec[2].iov_base = (void *) msg;
158 vec[2].iov_len = strlen(msg) + 1;
159
160 return write_to_log(log_id, vec, 3);
161}
162
163int __android_log_vprint(int prio, const char *tag, const char *fmt, va_list ap)
164{
165 char buf[LOG_BUF_SIZE];
166
167 vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
168
169 return __android_log_write(prio, tag, buf);
170}
171
172int __android_log_print(int prio, const char *tag, const char *fmt, ...)
173{
174 va_list ap;
175 char buf[LOG_BUF_SIZE];
176
177 va_start(ap, fmt);
178 vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
179 va_end(ap);
180
181 return __android_log_write(prio, tag, buf);
182}
183
184void __android_log_assert(const char *cond, const char *tag,
185 const char *fmt, ...)
186{
187 va_list ap;
188 char buf[LOG_BUF_SIZE];
189
190 va_start(ap, fmt);
191 vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
192 va_end(ap);
193
194 __android_log_write(ANDROID_LOG_FATAL, tag, buf);
195
196 __builtin_trap(); /* trap so we have a chance to debug the situation */
197}
198
199int __android_log_bwrite(int32_t tag, const void *payload, size_t len)
200{
201 struct iovec vec[2];
202
203 vec[0].iov_base = &tag;
204 vec[0].iov_len = sizeof(tag);
205 vec[1].iov_base = (void*)payload;
206 vec[1].iov_len = len;
207
208 return write_to_log(LOG_ID_EVENTS, vec, 2);
209}
210
211/*
212 * Like __android_log_bwrite, but takes the type as well. Doesn't work
213 * for the general case where we're generating lists of stuff, but very
214 * handy if we just want to dump an integer into the log.
215 */
216int __android_log_btwrite(int32_t tag, char type, const void *payload,
217 size_t len)
218{
219 struct iovec vec[3];
220
221 vec[0].iov_base = &tag;
222 vec[0].iov_len = sizeof(tag);
223 vec[1].iov_base = &type;
224 vec[1].iov_len = sizeof(type);
225 vec[2].iov_base = (void*)payload;
226 vec[2].iov_len = len;
227
228 return write_to_log(LOG_ID_EVENTS, vec, 3);
229}
diff --git a/liblog/logprint.c b/liblog/logprint.c
new file mode 100644
index 000000000..2cf12545f
--- /dev/null
+++ b/liblog/logprint.c
@@ -0,0 +1,972 @@
1/* //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>
26#include <alloca.h>
27#include <assert.h>
28#include <arpa/inet.h>
29
30#include <cutils/logd.h>
31#include <cutils/logprint.h>
32
33typedef struct FilterInfo_t {
34 char *mTag;
35 android_LogPriority mPri;
36 struct FilterInfo_t *p_next;
37} FilterInfo;
38
39struct AndroidLogFormat_t {
40 android_LogPriority global_pri;
41 FilterInfo *filters;
42 AndroidLogPrintFormat format;
43};
44
45static FilterInfo * filterinfo_new(const char * tag, android_LogPriority pri)
46{
47 FilterInfo *p_ret;
48
49 p_ret = (FilterInfo *)calloc(1, sizeof(FilterInfo));
50 p_ret->mTag = strdup(tag);
51 p_ret->mPri = pri;
52
53 return p_ret;
54}
55
56static void filterinfo_free(FilterInfo *p_info)
57{
58 if (p_info == NULL) {
59 return;
60 }
61
62 free(p_info->mTag);
63 p_info->mTag = NULL;
64}
65
66/*
67 * Note: also accepts 0-9 priorities
68 * returns ANDROID_LOG_UNKNOWN if the character is unrecognized
69 */
70static android_LogPriority filterCharToPri (char c)
71{
72 android_LogPriority pri;
73
74 c = tolower(c);
75
76 if (c >= '0' && c <= '9') {
77 if (c >= ('0'+ANDROID_LOG_SILENT)) {
78 pri = ANDROID_LOG_VERBOSE;
79 } else {
80 pri = (android_LogPriority)(c - '0');
81 }
82 } else if (c == 'v') {
83 pri = ANDROID_LOG_VERBOSE;
84 } else if (c == 'd') {
85 pri = ANDROID_LOG_DEBUG;
86 } else if (c == 'i') {
87 pri = ANDROID_LOG_INFO;
88 } else if (c == 'w') {
89 pri = ANDROID_LOG_WARN;
90 } else if (c == 'e') {
91 pri = ANDROID_LOG_ERROR;
92 } else if (c == 'f') {
93 pri = ANDROID_LOG_FATAL;
94 } else if (c == 's') {
95 pri = ANDROID_LOG_SILENT;
96 } else if (c == '*') {
97 pri = ANDROID_LOG_DEFAULT;
98 } else {
99 pri = ANDROID_LOG_UNKNOWN;
100 }
101
102 return pri;
103}
104
105static char filterPriToChar (android_LogPriority pri)
106{
107 switch (pri) {
108 case ANDROID_LOG_VERBOSE: return 'V';
109 case ANDROID_LOG_DEBUG: return 'D';
110 case ANDROID_LOG_INFO: return 'I';
111 case ANDROID_LOG_WARN: return 'W';
112 case ANDROID_LOG_ERROR: return 'E';
113 case ANDROID_LOG_FATAL: return 'F';
114 case ANDROID_LOG_SILENT: return 'S';
115
116 case ANDROID_LOG_DEFAULT:
117 case ANDROID_LOG_UNKNOWN:
118 default: return '?';
119 }
120}
121
122static android_LogPriority filterPriForTag(
123 AndroidLogFormat *p_format, const char *tag)
124{
125 FilterInfo *p_curFilter;
126
127 for (p_curFilter = p_format->filters
128 ; p_curFilter != NULL
129 ; p_curFilter = p_curFilter->p_next
130 ) {
131 if (0 == strcmp(tag, p_curFilter->mTag)) {
132 if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
133 return p_format->global_pri;
134 } else {
135 return p_curFilter->mPri;
136 }
137 }
138 }
139
140 return p_format->global_pri;
141}
142
143/** for debugging */
144static void dumpFilters(AndroidLogFormat *p_format)
145{
146 FilterInfo *p_fi;
147
148 for (p_fi = p_format->filters ; p_fi != NULL ; p_fi = p_fi->p_next) {
149 char cPri = filterPriToChar(p_fi->mPri);
150 if (p_fi->mPri == ANDROID_LOG_DEFAULT) {
151 cPri = filterPriToChar(p_format->global_pri);
152 }
153 fprintf(stderr,"%s:%c\n", p_fi->mTag, cPri);
154 }
155
156 fprintf(stderr,"*:%c\n", filterPriToChar(p_format->global_pri));
157
158}
159
160/**
161 * returns 1 if this log line should be printed based on its priority
162 * and tag, and 0 if it should not
163 */
164int android_log_shouldPrintLine (
165 AndroidLogFormat *p_format, const char *tag, android_LogPriority pri)
166{
167 return pri >= filterPriForTag(p_format, tag);
168}
169
170AndroidLogFormat *android_log_format_new()
171{
172 AndroidLogFormat *p_ret;
173
174 p_ret = calloc(1, sizeof(AndroidLogFormat));
175
176 p_ret->global_pri = ANDROID_LOG_VERBOSE;
177 p_ret->format = FORMAT_BRIEF;
178
179 return p_ret;
180}
181
182void android_log_format_free(AndroidLogFormat *p_format)
183{
184 FilterInfo *p_info, *p_info_old;
185
186 p_info = p_format->filters;
187
188 while (p_info != NULL) {
189 p_info_old = p_info;
190 p_info = p_info->p_next;
191
192 free(p_info_old);
193 }
194
195 free(p_format);
196}
197
198
199
200void android_log_setPrintFormat(AndroidLogFormat *p_format,
201 AndroidLogPrintFormat format)
202{
203 p_format->format=format;
204}
205
206/**
207 * Returns FORMAT_OFF on invalid string
208 */
209AndroidLogPrintFormat android_log_formatFromString(const char * formatString)
210{
211 static AndroidLogPrintFormat format;
212
213 if (strcmp(formatString, "brief") == 0) format = FORMAT_BRIEF;
214 else if (strcmp(formatString, "process") == 0) format = FORMAT_PROCESS;
215 else if (strcmp(formatString, "tag") == 0) format = FORMAT_TAG;
216 else if (strcmp(formatString, "thread") == 0) format = FORMAT_THREAD;
217 else if (strcmp(formatString, "raw") == 0) format = FORMAT_RAW;
218 else if (strcmp(formatString, "time") == 0) format = FORMAT_TIME;
219 else if (strcmp(formatString, "threadtime") == 0) format = FORMAT_THREADTIME;
220 else if (strcmp(formatString, "long") == 0) format = FORMAT_LONG;
221 else format = FORMAT_OFF;
222
223 return format;
224}
225
226/**
227 * filterExpression: a single filter expression
228 * eg "AT:d"
229 *
230 * returns 0 on success and -1 on invalid expression
231 *
232 * Assumes single threaded execution
233 */
234
235int android_log_addFilterRule(AndroidLogFormat *p_format,
236 const char *filterExpression)
237{
238 size_t i=0;
239 size_t tagNameLength;
240 android_LogPriority pri = ANDROID_LOG_DEFAULT;
241
242 tagNameLength = strcspn(filterExpression, ":");
243
244 if (tagNameLength == 0) {
245 goto error;
246 }
247
248 if(filterExpression[tagNameLength] == ':') {
249 pri = filterCharToPri(filterExpression[tagNameLength+1]);
250
251 if (pri == ANDROID_LOG_UNKNOWN) {
252 goto error;
253 }
254 }
255
256 if(0 == strncmp("*", filterExpression, tagNameLength)) {
257 // This filter expression refers to the global filter
258 // The default level for this is DEBUG if the priority
259 // is unspecified
260 if (pri == ANDROID_LOG_DEFAULT) {
261 pri = ANDROID_LOG_DEBUG;
262 }
263
264 p_format->global_pri = pri;
265 } else {
266 // for filter expressions that don't refer to the global
267 // filter, the default is verbose if the priority is unspecified
268 if (pri == ANDROID_LOG_DEFAULT) {
269 pri = ANDROID_LOG_VERBOSE;
270 }
271
272 char *tagName;
273
274// Presently HAVE_STRNDUP is never defined, so the second case is always taken
275// Darwin doesn't have strnup, everything else does
276#ifdef HAVE_STRNDUP
277 tagName = strndup(filterExpression, tagNameLength);
278#else
279 //a few extra bytes copied...
280 tagName = strdup(filterExpression);
281 tagName[tagNameLength] = '\0';
282#endif /*HAVE_STRNDUP*/
283
284 FilterInfo *p_fi = filterinfo_new(tagName, pri);
285 free(tagName);
286
287 p_fi->p_next = p_format->filters;
288 p_format->filters = p_fi;
289 }
290
291 return 0;
292error:
293 return -1;
294}
295
296
297/**
298 * filterString: a comma/whitespace-separated set of filter expressions
299 *
300 * eg "AT:d *:i"
301 *
302 * returns 0 on success and -1 on invalid expression
303 *
304 * Assumes single threaded execution
305 *
306 */
307
308int android_log_addFilterString(AndroidLogFormat *p_format,
309 const char *filterString)
310{
311 char *filterStringCopy = strdup (filterString);
312 char *p_cur = filterStringCopy;
313 char *p_ret;
314 int err;
315
316 // Yes, I'm using strsep
317 while (NULL != (p_ret = strsep(&p_cur, " \t,"))) {
318 // ignore whitespace-only entries
319 if(p_ret[0] != '\0') {
320 err = android_log_addFilterRule(p_format, p_ret);
321
322 if (err < 0) {
323 goto error;
324 }
325 }
326 }
327
328 free (filterStringCopy);
329 return 0;
330error:
331 free (filterStringCopy);
332 return -1;
333}
334
335static inline char * strip_end(char *str)
336{
337 char *end = str + strlen(str) - 1;
338
339 while (end >= str && isspace(*end))
340 *end-- = '\0';
341 return str;
342}
343
344/**
345 * Splits a wire-format buffer into an AndroidLogEntry
346 * entry allocated by caller. Pointers will point directly into buf
347 *
348 * Returns 0 on success and -1 on invalid wire format (entry will be
349 * in unspecified state)
350 */
351int android_log_processLogBuffer(struct logger_entry *buf,
352 AndroidLogEntry *entry)
353{
354 size_t tag_len;
355
356 entry->tv_sec = buf->sec;
357 entry->tv_nsec = buf->nsec;
358 entry->priority = buf->msg[0];
359 entry->pid = buf->pid;
360 entry->tid = buf->tid;
361 entry->tag = buf->msg + 1;
362 tag_len = strlen(entry->tag);
363 entry->messageLen = buf->len - tag_len - 3;
364 entry->message = entry->tag + tag_len + 1;
365
366 return 0;
367}
368
369/*
370 * Extract a 4-byte value from a byte stream.
371 */
372static inline uint32_t get4LE(const uint8_t* src)
373{
374 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
375}
376
377/*
378 * Extract an 8-byte value from a byte stream.
379 */
380static inline uint64_t get8LE(const uint8_t* src)
381{
382 uint32_t low, high;
383
384 low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
385 high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
386 return ((long long) high << 32) | (long long) low;
387}
388
389
390/*
391 * Recursively convert binary log data to printable form.
392 *
393 * This needs to be recursive because you can have lists of lists.
394 *
395 * If we run out of room, we stop processing immediately. It's important
396 * for us to check for space on every output element to avoid producing
397 * garbled output.
398 *
399 * Returns 0 on success, 1 on buffer full, -1 on failure.
400 */
401static int android_log_printBinaryEvent(const unsigned char** pEventData,
402 size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen)
403{
404 const unsigned char* eventData = *pEventData;
405 size_t eventDataLen = *pEventDataLen;
406 char* outBuf = *pOutBuf;
407 size_t outBufLen = *pOutBufLen;
408 unsigned char type;
409 size_t outCount;
410 int result = 0;
411
412 if (eventDataLen < 1)
413 return -1;
414 type = *eventData++;
415 eventDataLen--;
416
417 //fprintf(stderr, "--- type=%d (rem len=%d)\n", type, eventDataLen);
418
419 switch (type) {
420 case EVENT_TYPE_INT:
421 /* 32-bit signed int */
422 {
423 int ival;
424
425 if (eventDataLen < 4)
426 return -1;
427 ival = get4LE(eventData);
428 eventData += 4;
429 eventDataLen -= 4;
430
431 outCount = snprintf(outBuf, outBufLen, "%d", ival);
432 if (outCount < outBufLen) {
433 outBuf += outCount;
434 outBufLen -= outCount;
435 } else {
436 /* halt output */
437 goto no_room;
438 }
439 }
440 break;
441 case EVENT_TYPE_LONG:
442 /* 64-bit signed long */
443 {
444 long long lval;
445
446 if (eventDataLen < 8)
447 return -1;
448 lval = get8LE(eventData);
449 eventData += 8;
450 eventDataLen -= 8;
451
452 outCount = snprintf(outBuf, outBufLen, "%lld", lval);
453 if (outCount < outBufLen) {
454 outBuf += outCount;
455 outBufLen -= outCount;
456 } else {
457 /* halt output */
458 goto no_room;
459 }
460 }
461 break;
462 case EVENT_TYPE_STRING:
463 /* UTF-8 chars, not NULL-terminated */
464 {
465 unsigned int strLen;
466
467 if (eventDataLen < 4)
468 return -1;
469 strLen = get4LE(eventData);
470 eventData += 4;
471 eventDataLen -= 4;
472
473 if (eventDataLen < strLen)
474 return -1;
475
476 if (strLen < outBufLen) {
477 memcpy(outBuf, eventData, strLen);
478 outBuf += strLen;
479 outBufLen -= strLen;
480 } else if (outBufLen > 0) {
481 /* copy what we can */
482 memcpy(outBuf, eventData, outBufLen);
483 outBuf += outBufLen;
484 outBufLen -= outBufLen;
485 goto no_room;
486 }
487 eventData += strLen;
488 eventDataLen -= strLen;
489 break;
490 }
491 case EVENT_TYPE_LIST:
492 /* N items, all different types */
493 {
494 unsigned char count;
495 int i;
496
497 if (eventDataLen < 1)
498 return -1;
499
500 count = *eventData++;
501 eventDataLen--;
502
503 if (outBufLen > 0) {
504 *outBuf++ = '[';
505 outBufLen--;
506 } else {
507 goto no_room;
508 }
509
510 for (i = 0; i < count; i++) {
511 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
512 &outBuf, &outBufLen);
513 if (result != 0)
514 goto bail;
515
516 if (i < count-1) {
517 if (outBufLen > 0) {
518 *outBuf++ = ',';
519 outBufLen--;
520 } else {
521 goto no_room;
522 }
523 }
524 }
525
526 if (outBufLen > 0) {
527 *outBuf++ = ']';
528 outBufLen--;
529 } else {
530 goto no_room;
531 }
532 }
533 break;
534 default:
535 fprintf(stderr, "Unknown binary event type %d\n", type);
536 return -1;
537 }
538
539bail:
540 *pEventData = eventData;
541 *pEventDataLen = eventDataLen;
542 *pOutBuf = outBuf;
543 *pOutBufLen = outBufLen;
544 return result;
545
546no_room:
547 result = 1;
548 goto bail;
549}
550
551/**
552 * Convert a binary log entry to ASCII form.
553 *
554 * For convenience we mimic the processLogBuffer API. There is no
555 * pre-defined output length for the binary data, since we're free to format
556 * it however we choose, which means we can't really use a fixed-size buffer
557 * here.
558 */
559int android_log_processBinaryLogBuffer(struct logger_entry *buf,
560 AndroidLogEntry *entry, const EventTagMap* map, char* messageBuf,
561 int messageBufLen)
562{
563 size_t inCount;
564 unsigned int tagIndex;
565 const unsigned char* eventData;
566
567 entry->tv_sec = buf->sec;
568 entry->tv_nsec = buf->nsec;
569 entry->priority = ANDROID_LOG_INFO;
570 entry->pid = buf->pid;
571 entry->tid = buf->tid;
572
573 /*
574 * Pull the tag out.
575 */
576 eventData = (const unsigned char*) buf->msg;
577 inCount = buf->len;
578 if (inCount < 4)
579 return -1;
580 tagIndex = get4LE(eventData);
581 eventData += 4;
582 inCount -= 4;
583
584 if (map != NULL) {
585 entry->tag = android_lookupEventTag(map, tagIndex);
586 } else {
587 entry->tag = NULL;
588 }
589
590 /*
591 * If we don't have a map, or didn't find the tag number in the map,
592 * stuff a generated tag value into the start of the output buffer and
593 * shift the buffer pointers down.
594 */
595 if (entry->tag == NULL) {
596 int tagLen;
597
598 tagLen = snprintf(messageBuf, messageBufLen, "[%d]", tagIndex);
599 entry->tag = messageBuf;
600 messageBuf += tagLen+1;
601 messageBufLen -= tagLen+1;
602 }
603
604 /*
605 * Format the event log data into the buffer.
606 */
607 char* outBuf = messageBuf;
608 size_t outRemaining = messageBufLen-1; /* leave one for nul byte */
609 int result;
610 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
611 &outRemaining);
612 if (result < 0) {
613 fprintf(stderr, "Binary log entry conversion failed\n");
614 return -1;
615 } else if (result == 1) {
616 if (outBuf > messageBuf) {
617 /* leave an indicator */
618 *(outBuf-1) = '!';
619 } else {
620 /* no room to output anything at all */
621 *outBuf++ = '!';
622 outRemaining--;
623 }
624 /* pretend we ate all the data */
625 inCount = 0;
626 }
627
628 /* eat the silly terminating '\n' */
629 if (inCount == 1 && *eventData == '\n') {
630 eventData++;
631 inCount--;
632 }
633
634 if (inCount != 0) {
635 fprintf(stderr,
636 "Warning: leftover binary log data (%d bytes)\n", inCount);
637 }
638
639 /*
640 * Terminate the buffer. The NUL byte does not count as part of
641 * entry->messageLen.
642 */
643 *outBuf = '\0';
644 entry->messageLen = outBuf - messageBuf;
645 assert(entry->messageLen == (messageBufLen-1) - outRemaining);
646
647 entry->message = messageBuf;
648
649 return 0;
650}
651
652/**
653 * Formats a log message into a buffer
654 *
655 * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
656 * If return value != defaultBuffer, caller must call free()
657 * Returns NULL on malloc error
658 */
659
660char *android_log_formatLogLine (
661 AndroidLogFormat *p_format,
662 char *defaultBuffer,
663 size_t defaultBufferSize,
664 const AndroidLogEntry *entry,
665 size_t *p_outLength)
666{
667#if defined(HAVE_LOCALTIME_R)
668 struct tm tmBuf;
669#endif
670 struct tm* ptm;
671 char timeBuf[32];
672 char headerBuf[128];
673 char prefixBuf[128], suffixBuf[128];
674 char priChar;
675 int prefixSuffixIsHeaderFooter = 0;
676 char * ret = NULL;
677
678 priChar = filterPriToChar(entry->priority);
679
680 /*
681 * Get the current date/time in pretty form
682 *
683 * It's often useful when examining a log with "less" to jump to
684 * a specific point in the file by searching for the date/time stamp.
685 * For this reason it's very annoying to have regexp meta characters
686 * in the time stamp. Don't use forward slashes, parenthesis,
687 * brackets, asterisks, or other special chars here.
688 */
689#if defined(HAVE_LOCALTIME_R)
690 ptm = localtime_r(&(entry->tv_sec), &tmBuf);
691#else
692 ptm = localtime(&(entry->tv_sec));
693#endif
694 //strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm);
695 strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
696
697 /*
698 * Construct a buffer containing the log header and log message.
699 */
700 size_t prefixLen, suffixLen;
701
702 switch (p_format->format) {
703 case FORMAT_TAG:
704 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
705 "%c/%-8s: ", priChar, entry->tag);
706 strcpy(suffixBuf, "\n"); suffixLen = 1;
707 break;
708 case FORMAT_PROCESS:
709 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
710 "%c(%5d) ", priChar, entry->pid);
711 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf),
712 " (%s)\n", entry->tag);
713 break;
714 case FORMAT_THREAD:
715 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
716 "%c(%5d:%p) ", priChar, entry->pid, (void*)entry->tid);
717 strcpy(suffixBuf, "\n");
718 suffixLen = 1;
719 break;
720 case FORMAT_RAW:
721 prefixBuf[0] = 0;
722 prefixLen = 0;
723 strcpy(suffixBuf, "\n");
724 suffixLen = 1;
725 break;
726 case FORMAT_TIME:
727 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
728 "%s.%03ld %c/%-8s(%5d): ", timeBuf, entry->tv_nsec / 1000000,
729 priChar, entry->tag, entry->pid);
730 strcpy(suffixBuf, "\n");
731 suffixLen = 1;
732 break;
733 case FORMAT_THREADTIME:
734 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
735 "%s.%03ld %5d %5d %c %-8s: ", timeBuf, entry->tv_nsec / 1000000,
736 (int)entry->pid, (int)entry->tid, priChar, entry->tag);
737 strcpy(suffixBuf, "\n");
738 suffixLen = 1;
739 break;
740 case FORMAT_LONG:
741 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
742 "[ %s.%03ld %5d:%p %c/%-8s ]\n",
743 timeBuf, entry->tv_nsec / 1000000, entry->pid,
744 (void*)entry->tid, priChar, entry->tag);
745 strcpy(suffixBuf, "\n\n");
746 suffixLen = 2;
747 prefixSuffixIsHeaderFooter = 1;
748 break;
749 case FORMAT_BRIEF:
750 default:
751 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
752 "%c/%-8s(%5d): ", priChar, entry->tag, entry->pid);
753 strcpy(suffixBuf, "\n");
754 suffixLen = 1;
755 break;
756 }
757
758 /* the following code is tragically unreadable */
759
760 size_t numLines;
761 size_t i;
762 char *p;
763 size_t bufferSize;
764 const char *pm;
765
766 if (prefixSuffixIsHeaderFooter) {
767 // we're just wrapping message with a header/footer
768 numLines = 1;
769 } else {
770 pm = entry->message;
771 numLines = 0;
772
773 // The line-end finding here must match the line-end finding
774 // in for ( ... numLines...) loop below
775 while (pm < (entry->message + entry->messageLen)) {
776 if (*pm++ == '\n') numLines++;
777 }
778 // plus one line for anything not newline-terminated at the end
779 if (pm > entry->message && *(pm-1) != '\n') numLines++;
780 }
781
782 // this is an upper bound--newlines in message may be counted
783 // extraneously
784 bufferSize = (numLines * (prefixLen + suffixLen)) + entry->messageLen + 1;
785
786 if (defaultBufferSize >= bufferSize) {
787 ret = defaultBuffer;
788 } else {
789 ret = (char *)malloc(bufferSize);
790
791 if (ret == NULL) {
792 return ret;
793 }
794 }
795
796 ret[0] = '\0'; /* to start strcat off */
797
798 p = ret;
799 pm = entry->message;
800
801 if (prefixSuffixIsHeaderFooter) {
802 strcat(p, prefixBuf);
803 p += prefixLen;
804 strncat(p, entry->message, entry->messageLen);
805 p += entry->messageLen;
806 strcat(p, suffixBuf);
807 p += suffixLen;
808 } else {
809 while(pm < (entry->message + entry->messageLen)) {
810 const char *lineStart;
811 size_t lineLen;
812
813 lineStart = pm;
814
815 // Find the next end-of-line in message
816 while (pm < (entry->message + entry->messageLen)
817 && *pm != '\n') pm++;
818 lineLen = pm - lineStart;
819
820 strcat(p, prefixBuf);
821 p += prefixLen;
822 strncat(p, lineStart, lineLen);
823 p += lineLen;
824 strcat(p, suffixBuf);
825 p += suffixLen;
826
827 if (*pm == '\n') pm++;
828 }
829 }
830
831 if (p_outLength != NULL) {
832 *p_outLength = p - ret;
833 }
834
835 return ret;
836}
837
838/**
839 * Either print or do not print log line, based on filter
840 *
841 * Returns count bytes written
842 */
843
844int android_log_filterAndPrintLogLine(
845 AndroidLogFormat *p_format,
846 int fd,
847 const AndroidLogEntry *entry)
848{
849 int ret;
850 char defaultBuffer[512];
851 char *outBuffer = NULL;
852 size_t totalLen;
853
854 if (0 == android_log_shouldPrintLine(p_format, entry->tag,
855 entry->priority)) {
856 return 0;
857 }
858
859 outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
860 sizeof(defaultBuffer), entry, &totalLen);
861
862 if (!outBuffer)
863 return -1;
864
865 do {
866 ret = write(fd, outBuffer, totalLen);
867 } while (ret < 0 && errno == EINTR);
868
869 if (ret < 0) {
870 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
871 ret = 0;
872 goto done;
873 }
874
875 if (((size_t)ret) < totalLen) {
876 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
877 (int)totalLen);
878 goto done;
879 }
880
881done:
882 if (outBuffer != defaultBuffer) {
883 free(outBuffer);
884 }
885
886 return ret;
887}
888
889
890
891void logprint_run_tests()
892{
893#if 0
894
895 fprintf(stderr, "tests disabled\n");
896
897#else
898
899 int err;
900 const char *tag;
901 AndroidLogFormat *p_format;
902
903 p_format = android_log_format_new();
904
905 fprintf(stderr, "running tests\n");
906
907 tag = "random";
908
909 android_log_addFilterRule(p_format,"*:i");
910
911 assert (ANDROID_LOG_INFO == filterPriForTag(p_format, "random"));
912 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
913 android_log_addFilterRule(p_format, "*");
914 assert (ANDROID_LOG_DEBUG == filterPriForTag(p_format, "random"));
915 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
916 android_log_addFilterRule(p_format, "*:v");
917 assert (ANDROID_LOG_VERBOSE == filterPriForTag(p_format, "random"));
918 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
919 android_log_addFilterRule(p_format, "*:i");
920 assert (ANDROID_LOG_INFO == filterPriForTag(p_format, "random"));
921 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
922
923 android_log_addFilterRule(p_format, "random");
924 assert (ANDROID_LOG_VERBOSE == filterPriForTag(p_format, "random"));
925 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
926 android_log_addFilterRule(p_format, "random:v");
927 assert (ANDROID_LOG_VERBOSE == filterPriForTag(p_format, "random"));
928 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
929 android_log_addFilterRule(p_format, "random:d");
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, "random:w");
933 assert (ANDROID_LOG_WARN == filterPriForTag(p_format, "random"));
934 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
935
936 android_log_addFilterRule(p_format, "crap:*");
937 assert (ANDROID_LOG_VERBOSE== filterPriForTag(p_format, "crap"));
938 assert(android_log_shouldPrintLine(p_format, "crap", ANDROID_LOG_VERBOSE) > 0);
939
940 // invalid expression
941 err = android_log_addFilterRule(p_format, "random:z");
942 assert (err < 0);
943 assert (ANDROID_LOG_WARN == filterPriForTag(p_format, "random"));
944 assert(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
945
946 // Issue #550946
947 err = android_log_addFilterString(p_format, " ");
948 assert(err == 0);
949 assert(ANDROID_LOG_WARN == filterPriForTag(p_format, "random"));
950
951 // note trailing space
952 err = android_log_addFilterString(p_format, "*:s random:d ");
953 assert(err == 0);
954 assert(ANDROID_LOG_DEBUG == filterPriForTag(p_format, "random"));
955
956 err = android_log_addFilterString(p_format, "*:s random:z");
957 assert(err < 0);
958
959
960#if 0
961 char *ret;
962 char defaultBuffer[512];
963
964 ret = android_log_formatLogLine(p_format,
965 defaultBuffer, sizeof(defaultBuffer), 0, ANDROID_LOG_ERROR, 123,
966 123, 123, "random", "nofile", strlen("Hello"), "Hello", NULL);
967#endif
968
969
970 fprintf(stderr, "tests complete\n");
971#endif
972}