2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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.
22 #include "cutils/logd.h"
34 #define kMaxTagLen 16 /* from the long-dead utils/Log.cpp */
36 #define kTagSetSize 16 /* arbitrary */
39 #define TRACE(...) printf("fake_log_device: " __VA_ARGS__)
41 #define TRACE(...) ((void)0)
44 /* from the long-dead utils/Log.cpp */
61 typedef struct LogState {
62 /* the fake fd that's seen by the user */
65 /* a printable name for this fake device */
68 /* nonzero if this is a binary log */
71 /* global minimum priority */
72 int globalMinPriority;
75 LogFormat outputFormat;
77 /* tags and priorities */
81 } tagSet[kTagSetSize];
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.
92 static pthread_mutex_t fakeLogDeviceLock = PTHREAD_MUTEX_INITIALIZER;
96 pthread_mutex_lock(&fakeLogDeviceLock);
101 pthread_mutex_unlock(&fakeLogDeviceLock);
103 #else // !HAVE_PTHREADS
104 #define lock() ((void)0)
105 #define unlock() ((void)0)
106 #endif // !HAVE_PTHREADS
110 * File descriptor management.
112 #define FAKE_FD_BASE 10000
113 #define MAX_OPEN_LOGS 16
114 static LogState *openLogTable[MAX_OPEN_LOGS];
117 * Allocate an fd and associate a new LogState with it.
118 * The fd is available via the fakeFd field of the return value.
120 static LogState *createLogState()
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];
135 * Translate an fd to a LogState.
137 static LogState *fdToLogState(int fd)
139 if (fd >= FAKE_FD_BASE && fd < FAKE_FD_BASE + MAX_OPEN_LOGS) {
140 return openLogTable[fd - FAKE_FD_BASE];
146 * Unregister the fake fd and free the memory it pointed to.
148 static void deleteFakeFd(int fd)
154 ls = fdToLogState(fd);
156 openLogTable[fd - FAKE_FD_BASE] = NULL;
165 * Configure logging based on ANDROID_LOG_TAGS environment variable. We
166 * need to parse a string that looks like
168 * *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
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.
174 * We also want to check ANDROID_PRINTF_LOG to determine how the output
177 static void configureInitialState(const char* pathName, LogState* logState)
179 static const int kDevLogLen = sizeof("/dev/log/") - 1;
181 logState->debugName = strdup(pathName);
183 /* identify binary logs */
184 if (strcmp(pathName + kDevLogLen, "events") == 0) {
185 logState->isBinary = 1;
188 /* global min priority defaults to "info" level */
189 logState->globalMinPriority = ANDROID_LOG_INFO;
192 * This is based on the the long-dead utils/Log.cpp code.
194 const char* tags = getenv("ANDROID_LOG_TAGS");
195 TRACE("Found ANDROID_LOG_TAGS='%s'\n", tags);
199 while (*tags != '\0') {
200 char tagName[kMaxTagLen];
203 while (isspace(*tags))
207 while (*tags != '\0' && !isspace(*tags) && *tags != ':' &&
210 tagName[i++] = *tags++;
212 if (i == kMaxTagLen) {
213 TRACE("ERROR: env tag too long (%d chars max)\n", kMaxTagLen-1);
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;
227 if (*tags >= '0' && *tags <= '9') {
228 if (*tags >= ('0' + ANDROID_LOG_SILENT))
229 minPrio = ANDROID_LOG_VERBOSE;
231 minPrio = *tags - '\0';
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;
246 if (*tags != '\0' && !isspace(*tags)) {
247 TRACE("ERROR: garbage in tag env; expected whitespace\n");
248 TRACE(" env='%s'\n", tags);
253 if (tagName[0] == 0) {
254 logState->globalMinPriority = minPrio;
255 TRACE("+++ global min prio %d\n", logState->globalMinPriority);
257 logState->tagSet[entry].minPriority = minPrio;
258 strcpy(logState->tagSet[entry].tag, tagName);
259 TRACE("+++ entry %d: %s:%d\n",
261 logState->tagSet[entry].tag,
262 logState->tagSet[entry].minPriority);
270 * Taken from the long-dead utils/Log.cpp
272 const char* fstr = getenv("ANDROID_PRINTF_LOG");
275 format = FORMAT_BRIEF;
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;
292 format = (LogFormat) atoi(fstr); // really?!
295 logState->outputFormat = format;
299 * Return a human-readable string for the priority level. Always returns
302 static const char* getPriorityString(int priority)
304 /* the first character of each string should be unique */
305 static const char* priorityStrings[] = {
306 "Verbose", "Debug", "Info", "Warn", "Error", "Assert"
310 idx = (int) priority - (int) ANDROID_LOG_VERBOSE;
312 idx >= (int) (sizeof(priorityStrings) / sizeof(priorityStrings[0])))
314 return priorityStrings[idx];
319 * Some platforms like WIN32 do not have writev().
320 * Make up something to replace it.
322 static ssize_t fake_writev(int fd, const struct iovec *iov, int iovcnt) {
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) {
337 #define writev fake_writev
342 * Write a filtered log message to stderr.
344 * Log format parsing taken from the long-dead utils/Log.cpp.
346 static void showLog(LogState *state,
347 int logPrio, const char* tag, const char* msg)
349 #if defined(HAVE_LOCALTIME_R)
354 char prefixBuf[128], suffixBuf[128];
359 TRACE("LOG %d: %s %s", logPrio, tag, msg);
361 priChar = getPriorityString(logPrio)[0];
363 pid = tid = getpid(); // find gettid()?
366 * Get the current date/time in pretty form
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.
374 #if defined(HAVE_LOCALTIME_R)
375 ptm = localtime_r(&when, &tmBuf);
377 ptm = localtime(&when);
379 //strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm);
380 strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
383 * Construct a buffer containing the log header and log message.
385 size_t prefixLen, suffixLen;
387 switch (state->outputFormat) {
389 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
390 "%c/%-8s: ", priChar, tag);
391 strcpy(suffixBuf, "\n"); suffixLen = 1;
394 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
395 "%c(%5d) ", priChar, pid);
396 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf),
400 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
401 "%c(%5d:%p) ", priChar, pid, (void*)tid);
402 strcpy(suffixBuf, "\n"); suffixLen = 1;
405 prefixBuf[0] = 0; prefixLen = 0;
406 strcpy(suffixBuf, "\n"); suffixLen = 1;
409 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
410 "%s %-8s\n\t", timeBuf, tag);
411 strcpy(suffixBuf, "\n"); suffixLen = 1;
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;
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;
425 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
426 "%c/%-8s(%5d): ", priChar, tag, pid);
427 strcpy(suffixBuf, "\n"); suffixLen = 1;
432 * Figure out how many lines there will be.
434 const char* end = msg + strlen(msg);
438 if (*p++ == '\n') numLines++;
440 if (p > msg && *(p-1) != '\n') numLines++;
443 * Create an array of iovecs large enough to write all of
444 * the lines with a prefix and a suffix.
446 const size_t INLINE_VECS = 6;
447 const size_t MAX_LINES = ((size_t)~0)/(3*sizeof(struct iovec*));
448 struct iovec stackVec[INLINE_VECS];
449 struct iovec* vec = stackVec;
452 if (numLines > MAX_LINES)
453 numLines = MAX_LINES;
455 numVecs = numLines*3; // 3 iovecs per line.
456 if (numVecs > INLINE_VECS) {
457 vec = (struct iovec*)malloc(sizeof(struct iovec)*numVecs);
459 msg = "LOG: write failed, no memory";
467 * Fill in the iovec pointers.
470 struct iovec* v = vec;
472 while (numLines > 0 && p < end) {
474 v->iov_base = prefixBuf;
475 v->iov_len = prefixLen;
476 totalLen += prefixLen;
479 const char* start = p;
480 while (p < end && *p != '\n') p++;
482 v->iov_base = (void*)start;
483 v->iov_len = p-start;
489 v->iov_base = suffixBuf;
490 v->iov_len = suffixLen;
491 totalLen += suffixLen;
498 * Write the entire message to the log file with a single writev() call.
499 * We need to use this rather than a collection of printf()s on a FILE*
500 * because of multi-threading and multi-process issues.
502 * If the file was not opened with O_APPEND, this will produce interleaved
503 * output when called on the same file from multiple processes.
505 * If the file descriptor is actually a network socket, the writev()
506 * call may return with a partial write. Putting the writev() call in
507 * a loop can result in interleaved data. This can be alleviated
508 * somewhat by wrapping the writev call in the Mutex.
512 int cc = writev(fileno(stderr), vec, v-vec);
514 if (cc == totalLen) break;
517 if(errno == EINTR) continue;
519 /* can't really log the failure; for now, throw out a stderr */
520 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
523 /* shouldn't happen when writing to file or tty */
524 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", cc, totalLen);
529 /* if we allocated storage for the iovecs, free it */
536 * Receive a log message. We happen to know that "vector" has three parts:
539 * tag (N bytes -- null-terminated ASCII string)
540 * message (N bytes -- null-terminated ASCII string)
542 static ssize_t logWritev(int fd, const struct iovec* vector, int count)
546 /* Make sure that no-one frees the LogState while we're using it.
547 * Also guarantees that only one thread is in showLog() at a given
548 * time (if it matters).
552 state = fdToLogState(fd);
558 if (state->isBinary) {
559 TRACE("%s: ignoring binary log\n", state->debugName);
564 TRACE("%s: writevLog with count=%d not expected\n",
565 state->debugName, count);
569 /* pull out the three fields */
570 int logPrio = *(const char*)vector[0].iov_base;
571 const char* tag = (const char*) vector[1].iov_base;
572 const char* msg = (const char*) vector[2].iov_base;
574 /* see if this log tag is configured */
576 int minPrio = state->globalMinPriority;
577 for (i = 0; i < kTagSetSize; i++) {
578 if (state->tagSet[i].minPriority == ANDROID_LOG_UNKNOWN)
579 break; /* reached end of configured values */
581 if (strcmp(state->tagSet[i].tag, tag) == 0) {
582 //TRACE("MATCH tag '%s'\n", tag);
583 minPrio = state->tagSet[i].minPriority;
588 if (logPrio >= minPrio) {
589 showLog(state, logPrio, tag, msg);
591 //TRACE("+++ NOLOG(%d): %s %s", logPrio, tag, msg);
596 return vector[0].iov_len + vector[1].iov_len + vector[2].iov_len;
603 * Free up our state and close the fake descriptor.
605 static int logClose(int fd)
612 * Open a log output device and return a fake fd.
614 static int logOpen(const char* pathName, int flags)
621 logState = createLogState();
622 if (logState != NULL) {
623 configureInitialState(pathName, logState);
624 fd = logState->fakeFd;
636 * Runtime redirection. If this binary is running in the simulator,
637 * just pass log messages to the emulated device. If it's running
638 * outside of the simulator, write the log messages to stderr.
641 static int (*redirectOpen)(const char *pathName, int flags) = NULL;
642 static int (*redirectClose)(int fd) = NULL;
643 static ssize_t (*redirectWritev)(int fd, const struct iovec* vector, int count)
646 static void setRedirects()
650 /* Wrapsim sets this environment variable on children that it's
651 * created using its LD_PRELOAD wrapper.
653 ws = getenv("ANDROID_WRAPSIM");
654 if (ws != NULL && strcmp(ws, "1") == 0) {
655 /* We're running inside wrapsim, so we can just write to the device. */
656 redirectOpen = (int (*)(const char *pathName, int flags))open;
657 redirectClose = close;
658 redirectWritev = writev;
660 /* There's no device to delegate to; handle the logging ourselves. */
661 redirectOpen = logOpen;
662 redirectClose = logClose;
663 redirectWritev = logWritev;
667 int fakeLogOpen(const char *pathName, int flags)
669 if (redirectOpen == NULL) {
672 return redirectOpen(pathName, flags);
675 int fakeLogClose(int fd)
677 /* Assume that open() was called first. */
678 return redirectClose(fd);
681 ssize_t fakeLogWritev(int fd, const struct iovec* vector, int count)
683 /* Assume that open() was called first. */
684 return redirectWritev(fd, vector, count);