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