fake_log_device.c revision 4f6e8d7a00cbeda1e70cc15be9c4af1018bdad53
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}
678