• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008-2014 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  * Messages are printed to stderr.
19  */
20 
21 #include "fake_log_device.h"
22 
23 #include <ctype.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #if !defined(_WIN32)
27 #include <pthread.h>
28 #endif
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <time.h>
34 
35 #include <android/log.h>
36 
37 #include "log_portability.h"
38 
39 #define kMaxTagLen 16 /* from the long-dead utils/Log.cpp */
40 
41 #define kTagSetSize 16 /* arbitrary */
42 
43 #if 0
44 #define TRACE(...) printf("fake_log_device: " __VA_ARGS__)
45 #else
46 #define TRACE(...) ((void)0)
47 #endif
48 
49 /* from the long-dead utils/Log.cpp */
50 typedef enum {
51   FORMAT_OFF = 0,
52   FORMAT_BRIEF,
53   FORMAT_PROCESS,
54   FORMAT_TAG,
55   FORMAT_THREAD,
56   FORMAT_RAW,
57   FORMAT_TIME,
58   FORMAT_THREADTIME,
59   FORMAT_LONG
60 } LogFormat;
61 
62 /*
63  * Log driver state.
64  */
65 typedef struct LogState {
66   /* the fake fd that's seen by the user */
67   int fakeFd;
68 
69   /* a printable name for this fake device */
70   char debugName[sizeof("/dev/log/security")];
71 
72   /* nonzero if this is a binary log */
73   int isBinary;
74 
75   /* global minimum priority */
76   int globalMinPriority;
77 
78   /* output format */
79   LogFormat outputFormat;
80 
81   /* tags and priorities */
82   struct {
83     char tag[kMaxTagLen];
84     int minPriority;
85   } tagSet[kTagSetSize];
86 } LogState;
87 
88 #if !defined(_WIN32)
89 /*
90  * Locking.  Since we're emulating a device, we need to be prepared
91  * to have multiple callers at the same time.  This lock is used
92  * to both protect the fd list and to prevent LogStates from being
93  * freed out from under a user.
94  */
95 static pthread_mutex_t fakeLogDeviceLock = PTHREAD_MUTEX_INITIALIZER;
96 
lock()97 static void lock() {
98   /*
99    * If we trigger a signal handler in the middle of locked activity and the
100    * signal handler logs a message, we could get into a deadlock state.
101    */
102   pthread_mutex_lock(&fakeLogDeviceLock);
103 }
104 
unlock()105 static void unlock() {
106   pthread_mutex_unlock(&fakeLogDeviceLock);
107 }
108 
109 #else  // !defined(_WIN32)
110 
111 #define lock() ((void)0)
112 #define unlock() ((void)0)
113 
114 #endif  // !defined(_WIN32)
115 
116 /*
117  * File descriptor management.
118  */
119 #define FAKE_FD_BASE 10000
120 #define MAX_OPEN_LOGS 8
121 static LogState openLogTable[MAX_OPEN_LOGS];
122 
123 /*
124  * Allocate an fd and associate a new LogState with it.
125  * The fd is available via the fakeFd field of the return value.
126  */
createLogState()127 static LogState* createLogState() {
128   size_t i;
129 
130   for (i = 0; i < (sizeof(openLogTable) / sizeof(openLogTable[0])); i++) {
131     if (openLogTable[i].fakeFd == 0) {
132       openLogTable[i].fakeFd = FAKE_FD_BASE + i;
133       return &openLogTable[i];
134     }
135   }
136   return NULL;
137 }
138 
139 /*
140  * Translate an fd to a LogState.
141  */
fdToLogState(int fd)142 static LogState* fdToLogState(int fd) {
143   if (fd >= FAKE_FD_BASE && fd < FAKE_FD_BASE + MAX_OPEN_LOGS) {
144     return &openLogTable[fd - FAKE_FD_BASE];
145   }
146   return NULL;
147 }
148 
149 /*
150  * Unregister the fake fd and free the memory it pointed to.
151  */
deleteFakeFd(int fd)152 static void deleteFakeFd(int fd) {
153   LogState* ls;
154 
155   lock();
156 
157   ls = fdToLogState(fd);
158   if (ls != NULL) {
159     memset(&openLogTable[fd - FAKE_FD_BASE], 0, sizeof(openLogTable[0]));
160   }
161 
162   unlock();
163 }
164 
165 /*
166  * Configure logging based on ANDROID_LOG_TAGS environment variable.  We
167  * need to parse a string that looks like
168  *
169  *   *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
170  *
171  * The tag (or '*' for the global level) comes first, followed by a colon
172  * and a letter indicating the minimum priority level we're expected to log.
173  * This can be used to reveal or conceal logs with specific tags.
174  *
175  * We also want to check ANDROID_PRINTF_LOG to determine how the output
176  * will look.
177  */
configureInitialState(const char * pathName,LogState * logState)178 static void configureInitialState(const char* pathName, LogState* logState) {
179   static const int kDevLogLen = sizeof("/dev/log/") - 1;
180 
181   strncpy(logState->debugName, pathName, sizeof(logState->debugName));
182   logState->debugName[sizeof(logState->debugName) - 1] = '\0';
183 
184   /* identify binary logs */
185   if (!strcmp(pathName + kDevLogLen, "events") || !strcmp(pathName + kDevLogLen, "security")) {
186     logState->isBinary = 1;
187   }
188 
189   /* global min priority defaults to "info" level */
190   logState->globalMinPriority = ANDROID_LOG_INFO;
191 
192   /*
193    * This is based on the the long-dead utils/Log.cpp code.
194    */
195   const char* tags = getenv("ANDROID_LOG_TAGS");
196   TRACE("Found ANDROID_LOG_TAGS='%s'\n", tags);
197   if (tags != NULL) {
198     int entry = 0;
199 
200     while (*tags != '\0') {
201       char tagName[kMaxTagLen];
202       int i, minPrio;
203 
204       while (isspace(*tags)) tags++;
205 
206       i = 0;
207       while (*tags != '\0' && !isspace(*tags) && *tags != ':' && i < kMaxTagLen) {
208         tagName[i++] = *tags++;
209       }
210       if (i == kMaxTagLen) {
211         TRACE("ERROR: env tag too long (%d chars max)\n", kMaxTagLen - 1);
212         return;
213       }
214       tagName[i] = '\0';
215 
216       /* default priority, if there's no ":" part; also zero out '*' */
217       minPrio = ANDROID_LOG_VERBOSE;
218       if (tagName[0] == '*' && tagName[1] == '\0') {
219         minPrio = ANDROID_LOG_DEBUG;
220         tagName[0] = '\0';
221       }
222 
223       if (*tags == ':') {
224         tags++;
225         if (*tags >= '0' && *tags <= '9') {
226           if (*tags >= ('0' + ANDROID_LOG_SILENT))
227             minPrio = ANDROID_LOG_VERBOSE;
228           else
229             minPrio = *tags - '\0';
230         } else {
231           switch (*tags) {
232             case 'v':
233               minPrio = ANDROID_LOG_VERBOSE;
234               break;
235             case 'd':
236               minPrio = ANDROID_LOG_DEBUG;
237               break;
238             case 'i':
239               minPrio = ANDROID_LOG_INFO;
240               break;
241             case 'w':
242               minPrio = ANDROID_LOG_WARN;
243               break;
244             case 'e':
245               minPrio = ANDROID_LOG_ERROR;
246               break;
247             case 'f':
248               minPrio = ANDROID_LOG_FATAL;
249               break;
250             case 's':
251               minPrio = ANDROID_LOG_SILENT;
252               break;
253             default:
254               minPrio = ANDROID_LOG_DEFAULT;
255               break;
256           }
257         }
258 
259         tags++;
260         if (*tags != '\0' && !isspace(*tags)) {
261           TRACE("ERROR: garbage in tag env; expected whitespace\n");
262           TRACE("       env='%s'\n", tags);
263           return;
264         }
265       }
266 
267       if (tagName[0] == 0) {
268         logState->globalMinPriority = minPrio;
269         TRACE("+++ global min prio %d\n", logState->globalMinPriority);
270       } else {
271         logState->tagSet[entry].minPriority = minPrio;
272         strcpy(logState->tagSet[entry].tag, tagName);
273         TRACE("+++ entry %d: %s:%d\n", entry, logState->tagSet[entry].tag,
274               logState->tagSet[entry].minPriority);
275         entry++;
276       }
277     }
278   }
279 
280   /*
281    * Taken from the long-dead utils/Log.cpp
282    */
283   const char* fstr = getenv("ANDROID_PRINTF_LOG");
284   LogFormat format;
285   if (fstr == NULL) {
286     format = FORMAT_BRIEF;
287   } else {
288     if (strcmp(fstr, "brief") == 0)
289       format = FORMAT_BRIEF;
290     else if (strcmp(fstr, "process") == 0)
291       format = FORMAT_PROCESS;
292     else if (strcmp(fstr, "tag") == 0)
293       format = FORMAT_PROCESS;
294     else if (strcmp(fstr, "thread") == 0)
295       format = FORMAT_PROCESS;
296     else if (strcmp(fstr, "raw") == 0)
297       format = FORMAT_PROCESS;
298     else if (strcmp(fstr, "time") == 0)
299       format = FORMAT_PROCESS;
300     else if (strcmp(fstr, "long") == 0)
301       format = FORMAT_PROCESS;
302     else
303       format = (LogFormat)atoi(fstr);  // really?!
304   }
305 
306   logState->outputFormat = format;
307 }
308 
309 /*
310  * Return a human-readable string for the priority level.  Always returns
311  * a valid string.
312  */
getPriorityString(int priority)313 static const char* getPriorityString(int priority) {
314   /* the first character of each string should be unique */
315   static const char* priorityStrings[] = {"Verbose", "Debug", "Info", "Warn", "Error", "Assert"};
316   int idx;
317 
318   idx = (int)priority - (int)ANDROID_LOG_VERBOSE;
319   if (idx < 0 || idx >= (int)(sizeof(priorityStrings) / sizeof(priorityStrings[0])))
320     return "?unknown?";
321   return priorityStrings[idx];
322 }
323 
324 #if defined(_WIN32)
325 /*
326  * WIN32 does not have writev().
327  * Make up something to replace it.
328  */
fake_writev(int fd,const struct iovec * iov,int iovcnt)329 static ssize_t fake_writev(int fd, const struct iovec* iov, int iovcnt) {
330   ssize_t result = 0;
331   const struct iovec* end = iov + iovcnt;
332   for (; iov < end; iov++) {
333     ssize_t w = write(fd, iov->iov_base, iov->iov_len);
334     if (w != (ssize_t)iov->iov_len) {
335       if (w < 0) return w;
336       return result + w;
337     }
338     result += w;
339   }
340   return result;
341 }
342 
343 #define writev fake_writev
344 #endif
345 
346 /*
347  * Write a filtered log message to stderr.
348  *
349  * Log format parsing taken from the long-dead utils/Log.cpp.
350  */
showLog(LogState * state,int logPrio,const char * tag,const char * msg)351 static void showLog(LogState* state, int logPrio, const char* tag, const char* msg) {
352 #if !defined(_WIN32)
353   struct tm tmBuf;
354 #endif
355   struct tm* ptm;
356   char timeBuf[32];
357   char prefixBuf[128], suffixBuf[128];
358   char priChar;
359   time_t when;
360 #if !defined(_WIN32)
361   pid_t pid, tid;
362 #else
363   uint32_t pid, tid;
364 #endif
365 
366   TRACE("LOG %d: %s %s", logPrio, tag, msg);
367 
368   priChar = getPriorityString(logPrio)[0];
369   when = time(NULL);
370   pid = tid = getpid();  // find gettid()?
371 
372 /*
373  * Get the current date/time in pretty form
374  *
375  * It's often useful when examining a log with "less" to jump to
376  * a specific point in the file by searching for the date/time stamp.
377  * For this reason it's very annoying to have regexp meta characters
378  * in the time stamp.  Don't use forward slashes, parenthesis,
379  * brackets, asterisks, or other special chars here.
380  */
381 #if !defined(_WIN32)
382   ptm = localtime_r(&when, &tmBuf);
383 #else
384   ptm = localtime(&when);
385 #endif
386   // strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm);
387   strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
388 
389   /*
390    * Construct a buffer containing the log header and log message.
391    */
392   size_t prefixLen, suffixLen;
393 
394   switch (state->outputFormat) {
395     case FORMAT_TAG:
396       prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%c/%-8s: ", priChar, tag);
397       strcpy(suffixBuf, "\n");
398       suffixLen = 1;
399       break;
400     case FORMAT_PROCESS:
401       prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%c(%5d) ", priChar, pid);
402       suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "  (%s)\n", tag);
403       break;
404     case FORMAT_THREAD:
405       prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%c(%5d:%5d) ", priChar, pid, tid);
406       strcpy(suffixBuf, "\n");
407       suffixLen = 1;
408       break;
409     case FORMAT_RAW:
410       prefixBuf[0] = 0;
411       prefixLen = 0;
412       strcpy(suffixBuf, "\n");
413       suffixLen = 1;
414       break;
415     case FORMAT_TIME:
416       prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%s %-8s\n\t", timeBuf, tag);
417       strcpy(suffixBuf, "\n");
418       suffixLen = 1;
419       break;
420     case FORMAT_THREADTIME:
421       prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%s %5d %5d %c %-8s \n\t", timeBuf, pid,
422                            tid, priChar, tag);
423       strcpy(suffixBuf, "\n");
424       suffixLen = 1;
425       break;
426     case FORMAT_LONG:
427       prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "[ %s %5d:%5d %c/%-8s ]\n", timeBuf, pid,
428                            tid, priChar, tag);
429       strcpy(suffixBuf, "\n\n");
430       suffixLen = 2;
431       break;
432     default:
433       prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%c/%-8s(%5d): ", priChar, tag, pid);
434       strcpy(suffixBuf, "\n");
435       suffixLen = 1;
436       break;
437   }
438 
439   /*
440    * Figure out how many lines there will be.
441    */
442   const char* end = msg + strlen(msg);
443   size_t numLines = 0;
444   const char* p = msg;
445   while (p < end) {
446     if (*p++ == '\n') numLines++;
447   }
448   if (p > msg && *(p - 1) != '\n') {
449     numLines++;
450   }
451 
452   /*
453    * Create an array of iovecs large enough to write all of
454    * the lines with a prefix and a suffix.
455    */
456   const size_t INLINE_VECS = 64;
457   const size_t MAX_LINES = ((size_t)~0) / (3 * sizeof(struct iovec*));
458   struct iovec stackVec[INLINE_VECS];
459   struct iovec* vec = stackVec;
460   size_t numVecs;
461 
462   if (numLines > MAX_LINES) numLines = MAX_LINES;
463 
464   numVecs = numLines * 3;  // 3 iovecs per line.
465   if (numVecs > INLINE_VECS) {
466     vec = (struct iovec*)malloc(sizeof(struct iovec) * numVecs);
467     if (vec == NULL) {
468       msg = "LOG: write failed, no memory";
469       numVecs = INLINE_VECS;
470       numLines = numVecs / 3;
471       vec = stackVec;
472     }
473   }
474 
475   /*
476    * Fill in the iovec pointers.
477    */
478   p = msg;
479   struct iovec* v = vec;
480   int totalLen = 0;
481   while (numLines > 0 && p < end) {
482     if (prefixLen > 0) {
483       v->iov_base = prefixBuf;
484       v->iov_len = prefixLen;
485       totalLen += prefixLen;
486       v++;
487     }
488     const char* start = p;
489     while (p < end && *p != '\n') {
490       p++;
491     }
492     if ((p - start) > 0) {
493       v->iov_base = (void*)start;
494       v->iov_len = p - start;
495       totalLen += p - start;
496       v++;
497     }
498     if (*p == '\n') p++;
499     if (suffixLen > 0) {
500       v->iov_base = suffixBuf;
501       v->iov_len = suffixLen;
502       totalLen += suffixLen;
503       v++;
504     }
505     numLines -= 1;
506   }
507 
508   /*
509    * Write the entire message to the log file with a single writev() call.
510    * We need to use this rather than a collection of printf()s on a FILE*
511    * because of multi-threading and multi-process issues.
512    *
513    * If the file was not opened with O_APPEND, this will produce interleaved
514    * output when called on the same file from multiple processes.
515    *
516    * If the file descriptor is actually a network socket, the writev()
517    * call may return with a partial write.  Putting the writev() call in
518    * a loop can result in interleaved data.  This can be alleviated
519    * somewhat by wrapping the writev call in the Mutex.
520    */
521 
522   for (;;) {
523     int cc = writev(fileno(stderr), vec, v - vec);
524 
525     if (cc == totalLen) break;
526 
527     if (cc < 0) {
528       if (errno == EINTR) continue;
529 
530       /* can't really log the failure; for now, throw out a stderr */
531       fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
532       break;
533     } else {
534       /* shouldn't happen when writing to file or tty */
535       fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", cc, totalLen);
536       break;
537     }
538   }
539 
540   /* if we allocated storage for the iovecs, free it */
541   if (vec != stackVec) free(vec);
542 }
543 
544 /*
545  * Receive a log message.  We happen to know that "vector" has three parts:
546  *
547  *  priority (1 byte)
548  *  tag (N bytes -- null-terminated ASCII string)
549  *  message (N bytes -- null-terminated ASCII string)
550  */
fakeLogWritev(int fd,const struct iovec * vector,int count)551 ssize_t fakeLogWritev(int fd, const struct iovec* vector, int count) {
552   LogState* state;
553 
554   /* Make sure that no-one frees the LogState while we're using it.
555    * Also guarantees that only one thread is in showLog() at a given
556    * time (if it matters).
557    */
558   lock();
559 
560   state = fdToLogState(fd);
561   if (state == NULL) {
562     errno = EBADF;
563     unlock();
564     return -1;
565   }
566 
567   if (state->isBinary) {
568     TRACE("%s: ignoring binary log\n", state->debugName);
569     unlock();
570     int len = 0;
571     for (int i = 0; i < count; ++i) {
572       len += vector[i].iov_len;
573     }
574     return len;
575   }
576 
577   if (count != 3) {
578     TRACE("%s: writevLog with count=%d not expected\n", state->debugName, count);
579     unlock();
580     return -1;
581   }
582 
583   /* pull out the three fields */
584   int logPrio = *(const char*)vector[0].iov_base;
585   const char* tag = (const char*)vector[1].iov_base;
586   const char* msg = (const char*)vector[2].iov_base;
587 
588   /* see if this log tag is configured */
589   int i;
590   int minPrio = state->globalMinPriority;
591   for (i = 0; i < kTagSetSize; i++) {
592     if (state->tagSet[i].minPriority == ANDROID_LOG_UNKNOWN)
593       break; /* reached end of configured values */
594 
595     if (strcmp(state->tagSet[i].tag, tag) == 0) {
596       minPrio = state->tagSet[i].minPriority;
597       break;
598     }
599   }
600 
601   if (logPrio >= minPrio) {
602     showLog(state, logPrio, tag, msg);
603   }
604 
605   unlock();
606   int len = 0;
607   for (i = 0; i < count; ++i) {
608     len += vector[i].iov_len;
609   }
610   return len;
611 }
612 
613 /*
614  * Free up our state and close the fake descriptor.
615  *
616  * The logger API has no means or need to 'stop' or 'close' using the logs,
617  * and as such, there is no way for that 'stop' or 'close' to translate into
618  * a close operation to the fake log handler. fakeLogClose is provided for
619  * completeness only.
620  *
621  * We have no intention of adding a log close operation as it would complicate
622  * every user of the logging API with no gain since the only valid place to
623  * call is in the exit handler. Logging can continue in the exit handler to
624  * help debug HOST tools ...
625  */
fakeLogClose(int fd)626 int fakeLogClose(int fd) {
627   deleteFakeFd(fd);
628   return 0;
629 }
630 
631 /*
632  * Open a log output device and return a fake fd.
633  */
fakeLogOpen(const char * pathName)634 int fakeLogOpen(const char* pathName) {
635   LogState* logState;
636   int fd = -1;
637 
638   lock();
639 
640   logState = createLogState();
641   if (logState != NULL) {
642     configureInitialState(pathName, logState);
643     fd = logState->fakeFd;
644   } else {
645     errno = ENFILE;
646   }
647 
648   unlock();
649 
650   return fd;
651 }
652 
__send_log_msg(char *,size_t)653 ssize_t __send_log_msg(char*, size_t) {
654   return -ENODEV;
655 }
656 
__android_log_is_loggable(int prio,const char *,int def)657 int __android_log_is_loggable(int prio, const char*, int def) {
658   int logLevel = def;
659   return logLevel >= 0 && prio >= logLevel;
660 }
661 
__android_log_is_loggable_len(int prio,const char *,size_t,int def)662 int __android_log_is_loggable_len(int prio, const char*, size_t, int def) {
663   int logLevel = def;
664   return logLevel >= 0 && prio >= logLevel;
665 }
666 
__android_log_is_debuggable()667 int __android_log_is_debuggable() {
668   return 1;
669 }
670