blob: 746eb8aa24a9ac97e0bcafbc0f4448c029afcf2f [file] [log] [blame]
Mark Salyzyncf4aa032013-11-22 07:54:30 -08001/*
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07002**
Mark Salyzyn40b21552013-12-18 12:59:01 -08003** Copyright 2006-2014, The Android Open Source Project
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07004**
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
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070020#include <arpa/inet.h>
Mark Salyzyna04464a2014-04-30 08:50:53 -070021#include <assert.h>
22#include <ctype.h>
23#include <errno.h>
Pierre Zurekead88fc2010-10-17 22:39:37 +020024#include <stdbool.h>
Mark Salyzyna04464a2014-04-30 08:50:53 -070025#include <stdint.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
Jeff Brown44193d92015-04-28 12:47:02 -070029#include <inttypes.h>
Pierre Zurekead88fc2010-10-17 22:39:37 +020030#include <sys/param.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070031
Mark Salyzyn4cbed022015-08-31 15:53:41 -070032#include <cutils/list.h>
Colin Cross9227bd32013-07-23 16:59:20 -070033#include <log/logd.h>
34#include <log/logprint.h>
Mark Salyzyn2aa510e2015-12-08 09:15:06 -080035#include <private/android_filesystem_config.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070036
Mark Salyzyn4cbed022015-08-31 15:53:41 -070037#define MS_PER_NSEC 1000000
38#define US_PER_NSEC 1000
39
Mark Salyzynb932b2f2015-05-15 09:01:58 -070040/* open coded fragment, prevent circular dependencies */
41#define WEAK static
42
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070043typedef struct FilterInfo_t {
44 char *mTag;
45 android_LogPriority mPri;
46 struct FilterInfo_t *p_next;
47} FilterInfo;
48
49struct AndroidLogFormat_t {
50 android_LogPriority global_pri;
51 FilterInfo *filters;
52 AndroidLogPrintFormat format;
Pierre Zurekead88fc2010-10-17 22:39:37 +020053 bool colored_output;
Mark Salyzyne1f20042015-05-06 08:40:40 -070054 bool usec_time_output;
Mark Salyzynb932b2f2015-05-15 09:01:58 -070055 bool printable_output;
Mark Salyzynf28f6a92015-08-31 08:01:33 -070056 bool year_output;
57 bool zone_output;
Mark Salyzyn4cbed022015-08-31 15:53:41 -070058 bool epoch_output;
59 bool monotonic_output;
Mark Salyzyn90e7af32015-12-07 16:52:42 -080060 bool uid_output;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070061};
62
Pierre Zurekead88fc2010-10-17 22:39:37 +020063/*
64 * gnome-terminal color tags
65 * See http://misc.flogisoft.com/bash/tip_colors_and_formatting
66 * for ideas on how to set the forground color of the text for xterm.
67 * The color manipulation character stream is defined as:
68 * ESC [ 3 8 ; 5 ; <color#> m
69 */
70#define ANDROID_COLOR_BLUE 75
71#define ANDROID_COLOR_DEFAULT 231
72#define ANDROID_COLOR_GREEN 40
73#define ANDROID_COLOR_ORANGE 166
74#define ANDROID_COLOR_RED 196
75#define ANDROID_COLOR_YELLOW 226
76
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070077static FilterInfo * filterinfo_new(const char * tag, android_LogPriority pri)
78{
79 FilterInfo *p_ret;
80
81 p_ret = (FilterInfo *)calloc(1, sizeof(FilterInfo));
82 p_ret->mTag = strdup(tag);
83 p_ret->mPri = pri;
84
85 return p_ret;
86}
87
Mark Salyzyna04464a2014-04-30 08:50:53 -070088/* balance to above, filterinfo_free left unimplemented */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070089
90/*
91 * Note: also accepts 0-9 priorities
92 * returns ANDROID_LOG_UNKNOWN if the character is unrecognized
93 */
94static android_LogPriority filterCharToPri (char c)
95{
96 android_LogPriority pri;
97
98 c = tolower(c);
99
100 if (c >= '0' && c <= '9') {
101 if (c >= ('0'+ANDROID_LOG_SILENT)) {
102 pri = ANDROID_LOG_VERBOSE;
103 } else {
104 pri = (android_LogPriority)(c - '0');
105 }
106 } else if (c == 'v') {
107 pri = ANDROID_LOG_VERBOSE;
108 } else if (c == 'd') {
109 pri = ANDROID_LOG_DEBUG;
110 } else if (c == 'i') {
111 pri = ANDROID_LOG_INFO;
112 } else if (c == 'w') {
113 pri = ANDROID_LOG_WARN;
114 } else if (c == 'e') {
115 pri = ANDROID_LOG_ERROR;
116 } else if (c == 'f') {
117 pri = ANDROID_LOG_FATAL;
118 } else if (c == 's') {
119 pri = ANDROID_LOG_SILENT;
120 } else if (c == '*') {
121 pri = ANDROID_LOG_DEFAULT;
122 } else {
123 pri = ANDROID_LOG_UNKNOWN;
124 }
125
126 return pri;
127}
128
129static char filterPriToChar (android_LogPriority pri)
130{
131 switch (pri) {
132 case ANDROID_LOG_VERBOSE: return 'V';
133 case ANDROID_LOG_DEBUG: return 'D';
134 case ANDROID_LOG_INFO: return 'I';
135 case ANDROID_LOG_WARN: return 'W';
136 case ANDROID_LOG_ERROR: return 'E';
137 case ANDROID_LOG_FATAL: return 'F';
138 case ANDROID_LOG_SILENT: return 'S';
139
140 case ANDROID_LOG_DEFAULT:
141 case ANDROID_LOG_UNKNOWN:
142 default: return '?';
143 }
144}
145
Pierre Zurekead88fc2010-10-17 22:39:37 +0200146static int colorFromPri (android_LogPriority pri)
147{
148 switch (pri) {
149 case ANDROID_LOG_VERBOSE: return ANDROID_COLOR_DEFAULT;
150 case ANDROID_LOG_DEBUG: return ANDROID_COLOR_BLUE;
151 case ANDROID_LOG_INFO: return ANDROID_COLOR_GREEN;
152 case ANDROID_LOG_WARN: return ANDROID_COLOR_ORANGE;
153 case ANDROID_LOG_ERROR: return ANDROID_COLOR_RED;
154 case ANDROID_LOG_FATAL: return ANDROID_COLOR_RED;
155 case ANDROID_LOG_SILENT: return ANDROID_COLOR_DEFAULT;
156
157 case ANDROID_LOG_DEFAULT:
158 case ANDROID_LOG_UNKNOWN:
159 default: return ANDROID_COLOR_DEFAULT;
160 }
161}
162
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700163static android_LogPriority filterPriForTag(
164 AndroidLogFormat *p_format, const char *tag)
165{
166 FilterInfo *p_curFilter;
167
168 for (p_curFilter = p_format->filters
169 ; p_curFilter != NULL
170 ; p_curFilter = p_curFilter->p_next
171 ) {
172 if (0 == strcmp(tag, p_curFilter->mTag)) {
173 if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
174 return p_format->global_pri;
175 } else {
176 return p_curFilter->mPri;
177 }
178 }
179 }
180
181 return p_format->global_pri;
182}
183
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700184/**
185 * returns 1 if this log line should be printed based on its priority
186 * and tag, and 0 if it should not
187 */
188int android_log_shouldPrintLine (
189 AndroidLogFormat *p_format, const char *tag, android_LogPriority pri)
190{
191 return pri >= filterPriForTag(p_format, tag);
192}
193
194AndroidLogFormat *android_log_format_new()
195{
196 AndroidLogFormat *p_ret;
197
198 p_ret = calloc(1, sizeof(AndroidLogFormat));
199
200 p_ret->global_pri = ANDROID_LOG_VERBOSE;
201 p_ret->format = FORMAT_BRIEF;
Pierre Zurekead88fc2010-10-17 22:39:37 +0200202 p_ret->colored_output = false;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700203 p_ret->usec_time_output = false;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700204 p_ret->printable_output = false;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700205 p_ret->year_output = false;
206 p_ret->zone_output = false;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700207 p_ret->epoch_output = false;
Mark Salyzynba7a9a02015-12-01 15:57:25 -0800208 p_ret->monotonic_output = android_log_clockid() == CLOCK_MONOTONIC;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800209 p_ret->uid_output = false;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700210
211 return p_ret;
212}
213
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700214static list_declare(convertHead);
215
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700216void android_log_format_free(AndroidLogFormat *p_format)
217{
218 FilterInfo *p_info, *p_info_old;
219
220 p_info = p_format->filters;
221
222 while (p_info != NULL) {
223 p_info_old = p_info;
224 p_info = p_info->p_next;
225
226 free(p_info_old);
227 }
228
229 free(p_format);
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700230
231 /* Free conversion resource, can always be reconstructed */
232 while (!list_empty(&convertHead)) {
233 struct listnode *node = list_head(&convertHead);
234 list_remove(node);
235 free(node);
236 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700237}
238
Mark Salyzyne1f20042015-05-06 08:40:40 -0700239int android_log_setPrintFormat(AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700240 AndroidLogPrintFormat format)
241{
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700242 switch (format) {
243 case FORMAT_MODIFIER_COLOR:
Pierre Zurekead88fc2010-10-17 22:39:37 +0200244 p_format->colored_output = true;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700245 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700246 case FORMAT_MODIFIER_TIME_USEC:
Mark Salyzyne1f20042015-05-06 08:40:40 -0700247 p_format->usec_time_output = true;
248 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700249 case FORMAT_MODIFIER_PRINTABLE:
250 p_format->printable_output = true;
251 return 0;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700252 case FORMAT_MODIFIER_YEAR:
253 p_format->year_output = true;
254 return 0;
255 case FORMAT_MODIFIER_ZONE:
256 p_format->zone_output = !p_format->zone_output;
257 return 0;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700258 case FORMAT_MODIFIER_EPOCH:
259 p_format->epoch_output = true;
260 return 0;
261 case FORMAT_MODIFIER_MONOTONIC:
262 p_format->monotonic_output = true;
263 return 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800264 case FORMAT_MODIFIER_UID:
265 p_format->uid_output = true;
266 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700267 default:
268 break;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700269 }
270 p_format->format = format;
271 return 1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700272}
273
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700274static const char tz[] = "TZ";
275static const char utc[] = "UTC";
276
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700277/**
278 * Returns FORMAT_OFF on invalid string
279 */
280AndroidLogPrintFormat android_log_formatFromString(const char * formatString)
281{
282 static AndroidLogPrintFormat format;
283
284 if (strcmp(formatString, "brief") == 0) format = FORMAT_BRIEF;
285 else if (strcmp(formatString, "process") == 0) format = FORMAT_PROCESS;
286 else if (strcmp(formatString, "tag") == 0) format = FORMAT_TAG;
287 else if (strcmp(formatString, "thread") == 0) format = FORMAT_THREAD;
288 else if (strcmp(formatString, "raw") == 0) format = FORMAT_RAW;
289 else if (strcmp(formatString, "time") == 0) format = FORMAT_TIME;
290 else if (strcmp(formatString, "threadtime") == 0) format = FORMAT_THREADTIME;
291 else if (strcmp(formatString, "long") == 0) format = FORMAT_LONG;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700292 else if (strcmp(formatString, "color") == 0) format = FORMAT_MODIFIER_COLOR;
293 else if (strcmp(formatString, "usec") == 0) format = FORMAT_MODIFIER_TIME_USEC;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700294 else if (strcmp(formatString, "printable") == 0) format = FORMAT_MODIFIER_PRINTABLE;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700295 else if (strcmp(formatString, "year") == 0) format = FORMAT_MODIFIER_YEAR;
296 else if (strcmp(formatString, "zone") == 0) format = FORMAT_MODIFIER_ZONE;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700297 else if (strcmp(formatString, "epoch") == 0) format = FORMAT_MODIFIER_EPOCH;
298 else if (strcmp(formatString, "monotonic") == 0) format = FORMAT_MODIFIER_MONOTONIC;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800299 else if (strcmp(formatString, "uid") == 0) format = FORMAT_MODIFIER_UID;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700300 else {
301 extern char *tzname[2];
302 static const char gmt[] = "GMT";
303 char *cp = getenv(tz);
304 if (cp) {
305 cp = strdup(cp);
306 }
307 setenv(tz, formatString, 1);
308 /*
309 * Run tzset here to determine if the timezone is legitimate. If the
310 * zone is GMT, check if that is what was asked for, if not then
311 * did not match any on the system; report an error to caller.
312 */
313 tzset();
314 if (!tzname[0]
315 || ((!strcmp(tzname[0], utc)
316 || !strcmp(tzname[0], gmt)) /* error? */
317 && strcasecmp(formatString, utc)
318 && strcasecmp(formatString, gmt))) { /* ok */
319 if (cp) {
320 setenv(tz, cp, 1);
321 } else {
322 unsetenv(tz);
323 }
324 tzset();
325 format = FORMAT_OFF;
326 } else {
327 format = FORMAT_MODIFIER_ZONE;
328 }
329 free(cp);
330 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700331
332 return format;
333}
334
335/**
336 * filterExpression: a single filter expression
337 * eg "AT:d"
338 *
339 * returns 0 on success and -1 on invalid expression
340 *
341 * Assumes single threaded execution
342 */
343
344int android_log_addFilterRule(AndroidLogFormat *p_format,
345 const char *filterExpression)
346{
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700347 size_t tagNameLength;
348 android_LogPriority pri = ANDROID_LOG_DEFAULT;
349
350 tagNameLength = strcspn(filterExpression, ":");
351
352 if (tagNameLength == 0) {
353 goto error;
354 }
355
356 if(filterExpression[tagNameLength] == ':') {
357 pri = filterCharToPri(filterExpression[tagNameLength+1]);
358
359 if (pri == ANDROID_LOG_UNKNOWN) {
360 goto error;
361 }
362 }
363
364 if(0 == strncmp("*", filterExpression, tagNameLength)) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700365 /*
366 * This filter expression refers to the global filter
367 * The default level for this is DEBUG if the priority
368 * is unspecified
369 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700370 if (pri == ANDROID_LOG_DEFAULT) {
371 pri = ANDROID_LOG_DEBUG;
372 }
373
374 p_format->global_pri = pri;
375 } else {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700376 /*
377 * for filter expressions that don't refer to the global
378 * filter, the default is verbose if the priority is unspecified
379 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700380 if (pri == ANDROID_LOG_DEFAULT) {
381 pri = ANDROID_LOG_VERBOSE;
382 }
383
384 char *tagName;
385
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700386/*
387 * Presently HAVE_STRNDUP is never defined, so the second case is always taken
388 * Darwin doesn't have strnup, everything else does
389 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700390#ifdef HAVE_STRNDUP
391 tagName = strndup(filterExpression, tagNameLength);
392#else
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700393 /* a few extra bytes copied... */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700394 tagName = strdup(filterExpression);
395 tagName[tagNameLength] = '\0';
396#endif /*HAVE_STRNDUP*/
397
398 FilterInfo *p_fi = filterinfo_new(tagName, pri);
399 free(tagName);
400
401 p_fi->p_next = p_format->filters;
402 p_format->filters = p_fi;
403 }
404
405 return 0;
406error:
407 return -1;
408}
409
410
411/**
412 * filterString: a comma/whitespace-separated set of filter expressions
413 *
414 * eg "AT:d *:i"
415 *
416 * returns 0 on success and -1 on invalid expression
417 *
418 * Assumes single threaded execution
419 *
420 */
421
422int android_log_addFilterString(AndroidLogFormat *p_format,
423 const char *filterString)
424{
425 char *filterStringCopy = strdup (filterString);
426 char *p_cur = filterStringCopy;
427 char *p_ret;
428 int err;
429
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700430 /* Yes, I'm using strsep */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700431 while (NULL != (p_ret = strsep(&p_cur, " \t,"))) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700432 /* ignore whitespace-only entries */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700433 if(p_ret[0] != '\0') {
434 err = android_log_addFilterRule(p_format, p_ret);
435
436 if (err < 0) {
437 goto error;
438 }
439 }
440 }
441
442 free (filterStringCopy);
443 return 0;
444error:
445 free (filterStringCopy);
446 return -1;
447}
448
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700449/**
450 * Splits a wire-format buffer into an AndroidLogEntry
451 * entry allocated by caller. Pointers will point directly into buf
452 *
453 * Returns 0 on success and -1 on invalid wire format (entry will be
454 * in unspecified state)
455 */
456int android_log_processLogBuffer(struct logger_entry *buf,
457 AndroidLogEntry *entry)
458{
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700459 entry->tv_sec = buf->sec;
460 entry->tv_nsec = buf->nsec;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800461 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700462 entry->pid = buf->pid;
463 entry->tid = buf->tid;
Kenny Root4bf3c022011-09-30 17:10:14 -0700464
465 /*
466 * format: <priority:1><tag:N>\0<message:N>\0
467 *
468 * tag str
Nick Kraleviche1ede152011-10-18 15:23:33 -0700469 * starts at buf->msg+1
Kenny Root4bf3c022011-09-30 17:10:14 -0700470 * msg
Nick Kraleviche1ede152011-10-18 15:23:33 -0700471 * starts at buf->msg+1+len(tag)+1
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700472 *
473 * The message may have been truncated by the kernel log driver.
474 * When that happens, we must null-terminate the message ourselves.
Kenny Root4bf3c022011-09-30 17:10:14 -0700475 */
Nick Kraleviche1ede152011-10-18 15:23:33 -0700476 if (buf->len < 3) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700477 /*
478 * An well-formed entry must consist of at least a priority
479 * and two null characters
480 */
Nick Kraleviche1ede152011-10-18 15:23:33 -0700481 fprintf(stderr, "+++ LOG: entry too small\n");
Kenny Root4bf3c022011-09-30 17:10:14 -0700482 return -1;
483 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700484
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700485 int msgStart = -1;
486 int msgEnd = -1;
487
Nick Kraleviche1ede152011-10-18 15:23:33 -0700488 int i;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800489 char *msg = buf->msg;
490 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
491 if (buf2->hdr_size) {
492 msg = ((char *)buf2) + buf2->hdr_size;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800493 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
494 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
495 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800496 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700497 for (i = 1; i < buf->len; i++) {
Mark Salyzyn40b21552013-12-18 12:59:01 -0800498 if (msg[i] == '\0') {
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700499 if (msgStart == -1) {
500 msgStart = i + 1;
501 } else {
502 msgEnd = i;
503 break;
504 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700505 }
506 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700507
508 if (msgStart == -1) {
509 fprintf(stderr, "+++ LOG: malformed log message\n");
Nick Kralevich63f4a842011-10-17 10:45:03 -0700510 return -1;
511 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700512 if (msgEnd == -1) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700513 /* incoming message not null-terminated; force it */
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800514 msgEnd = buf->len - 1; /* may result in msgEnd < msgStart */
Mark Salyzyn40b21552013-12-18 12:59:01 -0800515 msg[msgEnd] = '\0';
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700516 }
517
Mark Salyzyn40b21552013-12-18 12:59:01 -0800518 entry->priority = msg[0];
519 entry->tag = msg + 1;
520 entry->message = msg + msgStart;
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800521 entry->messageLen = (msgEnd < msgStart) ? 0 : (msgEnd - msgStart);
Nick Kralevich63f4a842011-10-17 10:45:03 -0700522
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700523 return 0;
524}
525
526/*
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000527 * Extract a 4-byte value from a byte stream.
528 */
529static inline uint32_t get4LE(const uint8_t* src)
530{
531 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
532}
533
534/*
535 * Extract an 8-byte value from a byte stream.
536 */
537static inline uint64_t get8LE(const uint8_t* src)
538{
539 uint32_t low, high;
540
541 low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
542 high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
Jeff Brown44193d92015-04-28 12:47:02 -0700543 return ((uint64_t) high << 32) | (uint64_t) low;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000544}
545
546
547/*
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700548 * Recursively convert binary log data to printable form.
549 *
550 * This needs to be recursive because you can have lists of lists.
551 *
552 * If we run out of room, we stop processing immediately. It's important
553 * for us to check for space on every output element to avoid producing
554 * garbled output.
555 *
556 * Returns 0 on success, 1 on buffer full, -1 on failure.
557 */
558static int android_log_printBinaryEvent(const unsigned char** pEventData,
559 size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen)
560{
561 const unsigned char* eventData = *pEventData;
562 size_t eventDataLen = *pEventDataLen;
563 char* outBuf = *pOutBuf;
564 size_t outBufLen = *pOutBufLen;
565 unsigned char type;
566 size_t outCount;
567 int result = 0;
568
569 if (eventDataLen < 1)
570 return -1;
571 type = *eventData++;
572 eventDataLen--;
573
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700574 switch (type) {
575 case EVENT_TYPE_INT:
576 /* 32-bit signed int */
577 {
578 int ival;
579
580 if (eventDataLen < 4)
581 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000582 ival = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700583 eventData += 4;
584 eventDataLen -= 4;
585
586 outCount = snprintf(outBuf, outBufLen, "%d", ival);
587 if (outCount < outBufLen) {
588 outBuf += outCount;
589 outBufLen -= outCount;
590 } else {
591 /* halt output */
592 goto no_room;
593 }
594 }
595 break;
596 case EVENT_TYPE_LONG:
597 /* 64-bit signed long */
598 {
Jeff Brown44193d92015-04-28 12:47:02 -0700599 uint64_t lval;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700600
601 if (eventDataLen < 8)
602 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000603 lval = get8LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700604 eventData += 8;
605 eventDataLen -= 8;
606
Jeff Brown44193d92015-04-28 12:47:02 -0700607 outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
608 if (outCount < outBufLen) {
609 outBuf += outCount;
610 outBufLen -= outCount;
611 } else {
612 /* halt output */
613 goto no_room;
614 }
615 }
616 break;
617 case EVENT_TYPE_FLOAT:
618 /* float */
619 {
620 uint32_t ival;
621 float fval;
622
623 if (eventDataLen < 4)
624 return -1;
625 ival = get4LE(eventData);
626 fval = *(float*)&ival;
627 eventData += 4;
628 eventDataLen -= 4;
629
630 outCount = snprintf(outBuf, outBufLen, "%f", fval);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700631 if (outCount < outBufLen) {
632 outBuf += outCount;
633 outBufLen -= outCount;
634 } else {
635 /* halt output */
636 goto no_room;
637 }
638 }
639 break;
640 case EVENT_TYPE_STRING:
641 /* UTF-8 chars, not NULL-terminated */
642 {
643 unsigned int strLen;
644
645 if (eventDataLen < 4)
646 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000647 strLen = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700648 eventData += 4;
649 eventDataLen -= 4;
650
651 if (eventDataLen < strLen)
652 return -1;
653
654 if (strLen < outBufLen) {
655 memcpy(outBuf, eventData, strLen);
656 outBuf += strLen;
657 outBufLen -= strLen;
658 } else if (outBufLen > 0) {
659 /* copy what we can */
660 memcpy(outBuf, eventData, outBufLen);
661 outBuf += outBufLen;
662 outBufLen -= outBufLen;
663 goto no_room;
664 }
665 eventData += strLen;
666 eventDataLen -= strLen;
667 break;
668 }
669 case EVENT_TYPE_LIST:
670 /* N items, all different types */
671 {
672 unsigned char count;
673 int i;
674
675 if (eventDataLen < 1)
676 return -1;
677
678 count = *eventData++;
679 eventDataLen--;
680
681 if (outBufLen > 0) {
682 *outBuf++ = '[';
683 outBufLen--;
684 } else {
685 goto no_room;
686 }
687
688 for (i = 0; i < count; i++) {
689 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
690 &outBuf, &outBufLen);
691 if (result != 0)
692 goto bail;
693
694 if (i < count-1) {
695 if (outBufLen > 0) {
696 *outBuf++ = ',';
697 outBufLen--;
698 } else {
699 goto no_room;
700 }
701 }
702 }
703
704 if (outBufLen > 0) {
705 *outBuf++ = ']';
706 outBufLen--;
707 } else {
708 goto no_room;
709 }
710 }
711 break;
712 default:
713 fprintf(stderr, "Unknown binary event type %d\n", type);
714 return -1;
715 }
716
717bail:
718 *pEventData = eventData;
719 *pEventDataLen = eventDataLen;
720 *pOutBuf = outBuf;
721 *pOutBufLen = outBufLen;
722 return result;
723
724no_room:
725 result = 1;
726 goto bail;
727}
728
729/**
730 * Convert a binary log entry to ASCII form.
731 *
732 * For convenience we mimic the processLogBuffer API. There is no
733 * pre-defined output length for the binary data, since we're free to format
734 * it however we choose, which means we can't really use a fixed-size buffer
735 * here.
736 */
737int android_log_processBinaryLogBuffer(struct logger_entry *buf,
738 AndroidLogEntry *entry, const EventTagMap* map, char* messageBuf,
739 int messageBufLen)
740{
741 size_t inCount;
742 unsigned int tagIndex;
743 const unsigned char* eventData;
744
745 entry->tv_sec = buf->sec;
746 entry->tv_nsec = buf->nsec;
747 entry->priority = ANDROID_LOG_INFO;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800748 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700749 entry->pid = buf->pid;
750 entry->tid = buf->tid;
751
752 /*
753 * Pull the tag out.
754 */
755 eventData = (const unsigned char*) buf->msg;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800756 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
757 if (buf2->hdr_size) {
758 eventData = ((unsigned char *)buf2) + buf2->hdr_size;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800759 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
760 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
761 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800762 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700763 inCount = buf->len;
764 if (inCount < 4)
765 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000766 tagIndex = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700767 eventData += 4;
768 inCount -= 4;
769
770 if (map != NULL) {
771 entry->tag = android_lookupEventTag(map, tagIndex);
772 } else {
773 entry->tag = NULL;
774 }
775
776 /*
777 * If we don't have a map, or didn't find the tag number in the map,
778 * stuff a generated tag value into the start of the output buffer and
779 * shift the buffer pointers down.
780 */
781 if (entry->tag == NULL) {
782 int tagLen;
783
784 tagLen = snprintf(messageBuf, messageBufLen, "[%d]", tagIndex);
785 entry->tag = messageBuf;
786 messageBuf += tagLen+1;
787 messageBufLen -= tagLen+1;
788 }
789
790 /*
791 * Format the event log data into the buffer.
792 */
793 char* outBuf = messageBuf;
794 size_t outRemaining = messageBufLen-1; /* leave one for nul byte */
795 int result;
796 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
797 &outRemaining);
798 if (result < 0) {
799 fprintf(stderr, "Binary log entry conversion failed\n");
800 return -1;
801 } else if (result == 1) {
802 if (outBuf > messageBuf) {
803 /* leave an indicator */
804 *(outBuf-1) = '!';
805 } else {
806 /* no room to output anything at all */
807 *outBuf++ = '!';
808 outRemaining--;
809 }
810 /* pretend we ate all the data */
811 inCount = 0;
812 }
813
814 /* eat the silly terminating '\n' */
815 if (inCount == 1 && *eventData == '\n') {
816 eventData++;
817 inCount--;
818 }
819
820 if (inCount != 0) {
821 fprintf(stderr,
Andrew Hsiehd2c8f522012-02-27 16:48:18 -0800822 "Warning: leftover binary log data (%zu bytes)\n", inCount);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700823 }
824
825 /*
826 * Terminate the buffer. The NUL byte does not count as part of
827 * entry->messageLen.
828 */
829 *outBuf = '\0';
830 entry->messageLen = outBuf - messageBuf;
831 assert(entry->messageLen == (messageBufLen-1) - outRemaining);
832
833 entry->message = messageBuf;
834
835 return 0;
836}
837
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700838/*
839 * One utf8 character at a time
840 *
841 * Returns the length of the utf8 character in the buffer,
842 * or -1 if illegal or truncated
843 *
844 * Open coded from libutils/Unicode.cpp, borrowed from utf8_length(),
845 * can not remove from here because of library circular dependencies.
846 * Expect one-day utf8_character_length with the same signature could
847 * _also_ be part of libutils/Unicode.cpp if its usefullness needs to
848 * propagate globally.
849 */
850WEAK ssize_t utf8_character_length(const char *src, size_t len)
851{
852 const char *cur = src;
853 const char first_char = *cur++;
854 static const uint32_t kUnicodeMaxCodepoint = 0x0010FFFF;
855 int32_t mask, to_ignore_mask;
856 size_t num_to_read;
857 uint32_t utf32;
858
859 if ((first_char & 0x80) == 0) { /* ASCII */
Mark Salyzynfaa92e92015-09-08 07:57:27 -0700860 return first_char ? 1 : -1;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700861 }
862
863 /*
864 * (UTF-8's character must not be like 10xxxxxx,
865 * but 110xxxxx, 1110xxxx, ... or 1111110x)
866 */
867 if ((first_char & 0x40) == 0) {
868 return -1;
869 }
870
871 for (utf32 = 1, num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
872 num_to_read < 5 && (first_char & mask);
873 num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
874 if (num_to_read > len) {
875 return -1;
876 }
877 if ((*cur & 0xC0) != 0x80) { /* can not be 10xxxxxx? */
878 return -1;
879 }
880 utf32 = (utf32 << 6) + (*cur++ & 0b00111111);
881 }
882 /* "first_char" must be (110xxxxx - 11110xxx) */
883 if (num_to_read >= 5) {
884 return -1;
885 }
886 to_ignore_mask |= mask;
887 utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
888 if (utf32 > kUnicodeMaxCodepoint) {
889 return -1;
890 }
891 return num_to_read;
892}
893
894/*
895 * Convert to printable from message to p buffer, return string length. If p is
896 * NULL, do not copy, but still return the expected string length.
897 */
898static size_t convertPrintable(char *p, const char *message, size_t messageLen)
899{
900 char *begin = p;
901 bool print = p != NULL;
902
903 while (messageLen) {
904 char buf[6];
905 ssize_t len = sizeof(buf) - 1;
906 if ((size_t)len > messageLen) {
907 len = messageLen;
908 }
909 len = utf8_character_length(message, len);
910
911 if (len < 0) {
912 snprintf(buf, sizeof(buf),
913 ((messageLen > 1) && isdigit(message[1]))
914 ? "\\%03o"
915 : "\\%o",
916 *message & 0377);
917 len = 1;
918 } else {
919 buf[0] = '\0';
920 if (len == 1) {
921 if (*message == '\a') {
922 strcpy(buf, "\\a");
923 } else if (*message == '\b') {
924 strcpy(buf, "\\b");
925 } else if (*message == '\t') {
Mark Salyzyn65d5ca22015-11-18 09:58:00 -0800926 strcpy(buf, "\t"); // Do not escape tabs
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700927 } else if (*message == '\v') {
928 strcpy(buf, "\\v");
929 } else if (*message == '\f') {
930 strcpy(buf, "\\f");
931 } else if (*message == '\r') {
932 strcpy(buf, "\\r");
933 } else if (*message == '\\') {
934 strcpy(buf, "\\\\");
935 } else if ((*message < ' ') || (*message & 0x80)) {
936 snprintf(buf, sizeof(buf), "\\%o", *message & 0377);
937 }
938 }
939 if (!buf[0]) {
940 strncpy(buf, message, len);
941 buf[len] = '\0';
942 }
943 }
944 if (print) {
945 strcpy(p, buf);
946 }
947 p += strlen(buf);
948 message += len;
949 messageLen -= len;
950 }
951 return p - begin;
952}
953
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700954char *readSeconds(char *e, struct timespec *t)
955{
956 unsigned long multiplier;
957 char *p;
958 t->tv_sec = strtoul(e, &p, 10);
959 if (*p != '.') {
960 return NULL;
961 }
962 t->tv_nsec = 0;
963 multiplier = NS_PER_SEC;
964 while (isdigit(*++p) && (multiplier /= 10)) {
965 t->tv_nsec += (*p - '0') * multiplier;
966 }
967 return p;
968}
969
970static struct timespec *sumTimespec(struct timespec *left,
971 struct timespec *right)
972{
973 left->tv_nsec += right->tv_nsec;
974 left->tv_sec += right->tv_sec;
975 if (left->tv_nsec >= (long)NS_PER_SEC) {
976 left->tv_nsec -= NS_PER_SEC;
977 left->tv_sec += 1;
978 }
979 return left;
980}
981
982static struct timespec *subTimespec(struct timespec *result,
983 struct timespec *left,
984 struct timespec *right)
985{
986 result->tv_nsec = left->tv_nsec - right->tv_nsec;
987 result->tv_sec = left->tv_sec - right->tv_sec;
988 if (result->tv_nsec < 0) {
989 result->tv_nsec += NS_PER_SEC;
990 result->tv_sec -= 1;
991 }
992 return result;
993}
994
995static long long nsecTimespec(struct timespec *now)
996{
997 return (long long)now->tv_sec * NS_PER_SEC + now->tv_nsec;
998}
999
1000static void convertMonotonic(struct timespec *result,
1001 const AndroidLogEntry *entry)
1002{
1003 struct listnode *node;
1004 struct conversionList {
1005 struct listnode node; /* first */
1006 struct timespec time;
1007 struct timespec convert;
1008 } *list, *next;
1009 struct timespec time, convert;
1010
1011 /* If we do not have a conversion list, build one up */
1012 if (list_empty(&convertHead)) {
1013 bool suspended_pending = false;
1014 struct timespec suspended_monotonic = { 0, 0 };
1015 struct timespec suspended_diff = { 0, 0 };
1016
1017 /*
1018 * Read dmesg for _some_ synchronization markers and insert
1019 * Anything in the Android Logger before the dmesg logging span will
1020 * be highly suspect regarding the monotonic time calculations.
1021 */
1022 FILE *p = popen("/system/bin/dmesg", "r");
1023 if (p) {
1024 char *line = NULL;
1025 size_t len = 0;
1026 while (getline(&line, &len, p) > 0) {
1027 static const char suspend[] = "PM: suspend entry ";
1028 static const char resume[] = "PM: suspend exit ";
1029 static const char healthd[] = "healthd";
1030 static const char battery[] = ": battery ";
1031 static const char suspended[] = "Suspended for ";
1032 struct timespec monotonic;
1033 struct tm tm;
1034 char *cp, *e = line;
1035 bool add_entry = true;
1036
1037 if (*e == '<') {
1038 while (*e && (*e != '>')) {
1039 ++e;
1040 }
1041 if (*e != '>') {
1042 continue;
1043 }
1044 }
1045 if (*e != '[') {
1046 continue;
1047 }
1048 while (*++e == ' ') {
1049 ;
1050 }
1051 e = readSeconds(e, &monotonic);
1052 if (!e || (*e != ']')) {
1053 continue;
1054 }
1055
1056 if ((e = strstr(e, suspend))) {
1057 e += sizeof(suspend) - 1;
1058 } else if ((e = strstr(line, resume))) {
1059 e += sizeof(resume) - 1;
1060 } else if (((e = strstr(line, healthd)))
1061 && ((e = strstr(e + sizeof(healthd) - 1, battery)))) {
1062 /* NB: healthd is roughly 150us late, worth the price to
1063 * deal with ntp-induced or hardware clock drift. */
1064 e += sizeof(battery) - 1;
1065 } else if ((e = strstr(line, suspended))) {
1066 e += sizeof(suspended) - 1;
1067 e = readSeconds(e, &time);
1068 if (!e) {
1069 continue;
1070 }
1071 add_entry = false;
1072 suspended_pending = true;
1073 suspended_monotonic = monotonic;
1074 suspended_diff = time;
1075 } else {
1076 continue;
1077 }
1078 if (add_entry) {
1079 /* look for "????-??-?? ??:??:??.????????? UTC" */
1080 cp = strstr(e, " UTC");
1081 if (!cp || ((cp - e) < 29) || (cp[-10] != '.')) {
1082 continue;
1083 }
1084 e = cp - 29;
1085 cp = readSeconds(cp - 10, &time);
1086 if (!cp) {
1087 continue;
1088 }
1089 cp = strptime(e, "%Y-%m-%d %H:%M:%S.", &tm);
1090 if (!cp) {
1091 continue;
1092 }
1093 cp = getenv(tz);
1094 if (cp) {
1095 cp = strdup(cp);
1096 }
1097 setenv(tz, utc, 1);
1098 time.tv_sec = mktime(&tm);
1099 if (cp) {
1100 setenv(tz, cp, 1);
1101 free(cp);
1102 } else {
1103 unsetenv(tz);
1104 }
1105 list = calloc(1, sizeof(struct conversionList));
1106 list_init(&list->node);
1107 list->time = time;
1108 subTimespec(&list->convert, &time, &monotonic);
1109 list_add_tail(&convertHead, &list->node);
1110 }
1111 if (suspended_pending && !list_empty(&convertHead)) {
1112 list = node_to_item(list_tail(&convertHead),
1113 struct conversionList, node);
1114 if (subTimespec(&time,
1115 subTimespec(&time,
1116 &list->time,
1117 &list->convert),
1118 &suspended_monotonic)->tv_sec > 0) {
1119 /* resume, what is convert factor before? */
1120 subTimespec(&convert, &list->convert, &suspended_diff);
1121 } else {
1122 /* suspend */
1123 convert = list->convert;
1124 }
1125 time = suspended_monotonic;
1126 sumTimespec(&time, &convert);
1127 /* breakpoint just before sleep */
1128 list = calloc(1, sizeof(struct conversionList));
1129 list_init(&list->node);
1130 list->time = time;
1131 list->convert = convert;
1132 list_add_tail(&convertHead, &list->node);
1133 /* breakpoint just after sleep */
1134 list = calloc(1, sizeof(struct conversionList));
1135 list_init(&list->node);
1136 list->time = time;
1137 sumTimespec(&list->time, &suspended_diff);
1138 list->convert = convert;
1139 sumTimespec(&list->convert, &suspended_diff);
1140 list_add_tail(&convertHead, &list->node);
1141 suspended_pending = false;
1142 }
1143 }
1144 pclose(p);
1145 }
1146 /* last entry is our current time conversion */
1147 list = calloc(1, sizeof(struct conversionList));
1148 list_init(&list->node);
1149 clock_gettime(CLOCK_REALTIME, &list->time);
1150 clock_gettime(CLOCK_MONOTONIC, &convert);
1151 clock_gettime(CLOCK_MONOTONIC, &time);
1152 /* Correct for instant clock_gettime latency (syscall or ~30ns) */
1153 subTimespec(&time, &convert, subTimespec(&time, &time, &convert));
1154 /* Calculate conversion factor */
1155 subTimespec(&list->convert, &list->time, &time);
1156 list_add_tail(&convertHead, &list->node);
1157 if (suspended_pending) {
1158 /* manufacture a suspend @ point before */
1159 subTimespec(&convert, &list->convert, &suspended_diff);
1160 time = suspended_monotonic;
1161 sumTimespec(&time, &convert);
1162 /* breakpoint just after sleep */
1163 list = calloc(1, sizeof(struct conversionList));
1164 list_init(&list->node);
1165 list->time = time;
1166 sumTimespec(&list->time, &suspended_diff);
1167 list->convert = convert;
1168 sumTimespec(&list->convert, &suspended_diff);
1169 list_add_head(&convertHead, &list->node);
1170 /* breakpoint just before sleep */
1171 list = calloc(1, sizeof(struct conversionList));
1172 list_init(&list->node);
1173 list->time = time;
1174 list->convert = convert;
1175 list_add_head(&convertHead, &list->node);
1176 }
1177 }
1178
1179 /* Find the breakpoint in the conversion list */
1180 list = node_to_item(list_head(&convertHead), struct conversionList, node);
1181 next = NULL;
1182 list_for_each(node, &convertHead) {
1183 next = node_to_item(node, struct conversionList, node);
1184 if (entry->tv_sec < next->time.tv_sec) {
1185 break;
1186 } else if (entry->tv_sec == next->time.tv_sec) {
1187 if (entry->tv_nsec < next->time.tv_nsec) {
1188 break;
1189 }
1190 }
1191 list = next;
1192 }
1193
1194 /* blend time from one breakpoint to the next */
1195 convert = list->convert;
1196 if (next) {
1197 unsigned long long total, run;
1198
1199 total = nsecTimespec(subTimespec(&time, &next->time, &list->time));
1200 time.tv_sec = entry->tv_sec;
1201 time.tv_nsec = entry->tv_nsec;
1202 run = nsecTimespec(subTimespec(&time, &time, &list->time));
1203 if (run < total) {
1204 long long crun;
1205
1206 float f = nsecTimespec(subTimespec(&time, &next->convert, &convert));
1207 f *= run;
1208 f /= total;
1209 crun = f;
1210 convert.tv_sec += crun / (long long)NS_PER_SEC;
1211 if (crun < 0) {
1212 convert.tv_nsec -= (-crun) % NS_PER_SEC;
1213 if (convert.tv_nsec < 0) {
1214 convert.tv_nsec += NS_PER_SEC;
1215 convert.tv_sec -= 1;
1216 }
1217 } else {
1218 convert.tv_nsec += crun % NS_PER_SEC;
1219 if (convert.tv_nsec >= (long)NS_PER_SEC) {
1220 convert.tv_nsec -= NS_PER_SEC;
1221 convert.tv_sec += 1;
1222 }
1223 }
1224 }
1225 }
1226
1227 /* Apply the correction factor */
1228 result->tv_sec = entry->tv_sec;
1229 result->tv_nsec = entry->tv_nsec;
1230 subTimespec(result, result, &convert);
1231}
1232
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001233/**
1234 * Formats a log message into a buffer
1235 *
1236 * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
1237 * If return value != defaultBuffer, caller must call free()
1238 * Returns NULL on malloc error
1239 */
1240
1241char *android_log_formatLogLine (
1242 AndroidLogFormat *p_format,
1243 char *defaultBuffer,
1244 size_t defaultBufferSize,
1245 const AndroidLogEntry *entry,
1246 size_t *p_outLength)
1247{
Yabin Cui8a985352014-11-13 10:02:08 -08001248#if !defined(_WIN32)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001249 struct tm tmBuf;
1250#endif
1251 struct tm* ptm;
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001252 char timeBuf[64]; /* good margin, 23+nul for msec, 26+nul for usec */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001253 char prefixBuf[128], suffixBuf[128];
1254 char priChar;
1255 int prefixSuffixIsHeaderFooter = 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001256 char *ret;
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001257 time_t now;
1258 unsigned long nsec;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001259
1260 priChar = filterPriToChar(entry->priority);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001261 size_t prefixLen = 0, suffixLen = 0;
1262 size_t len;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001263
1264 /*
1265 * Get the current date/time in pretty form
1266 *
1267 * It's often useful when examining a log with "less" to jump to
1268 * a specific point in the file by searching for the date/time stamp.
1269 * For this reason it's very annoying to have regexp meta characters
1270 * in the time stamp. Don't use forward slashes, parenthesis,
1271 * brackets, asterisks, or other special chars here.
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001272 *
1273 * The caller may have affected the timezone environment, this is
1274 * expected to be sensitive to that.
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001275 */
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001276 now = entry->tv_sec;
1277 nsec = entry->tv_nsec;
1278 if (p_format->monotonic_output) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001279 // prevent convertMonotonic from being called if logd is monotonic
Mark Salyzynba7a9a02015-12-01 15:57:25 -08001280 if (android_log_clockid() != CLOCK_MONOTONIC) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001281 struct timespec time;
1282 convertMonotonic(&time, entry);
1283 now = time.tv_sec;
1284 nsec = time.tv_nsec;
1285 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001286 }
1287 if (now < 0) {
1288 nsec = NS_PER_SEC - nsec;
1289 }
1290 if (p_format->epoch_output || p_format->monotonic_output) {
1291 ptm = NULL;
1292 snprintf(timeBuf, sizeof(timeBuf),
1293 p_format->monotonic_output ? "%6lld" : "%19lld",
1294 (long long)now);
1295 } else {
Yabin Cui8a985352014-11-13 10:02:08 -08001296#if !defined(_WIN32)
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001297 ptm = localtime_r(&now, &tmBuf);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001298#else
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001299 ptm = localtime(&now);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001300#endif
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001301 strftime(timeBuf, sizeof(timeBuf),
1302 &"%Y-%m-%d %H:%M:%S"[p_format->year_output ? 0 : 3],
1303 ptm);
1304 }
Mark Salyzyne1f20042015-05-06 08:40:40 -07001305 len = strlen(timeBuf);
1306 if (p_format->usec_time_output) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001307 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001308 ".%06ld", nsec / US_PER_NSEC);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001309 } else {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001310 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001311 ".%03ld", nsec / MS_PER_NSEC);
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001312 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001313 if (p_format->zone_output && ptm) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001314 strftime(timeBuf + len, sizeof(timeBuf) - len, " %z", ptm);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001315 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001316
1317 /*
1318 * Construct a buffer containing the log header and log message.
1319 */
Pierre Zurekead88fc2010-10-17 22:39:37 +02001320 if (p_format->colored_output) {
1321 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
1322 colorFromPri(entry->priority));
1323 prefixLen = MIN(prefixLen, sizeof(prefixBuf));
1324 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
1325 suffixLen = MIN(suffixLen, sizeof(suffixBuf));
1326 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001327
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001328 char uid[16];
1329 uid[0] = '\0';
1330 if (p_format->uid_output) {
1331 if (entry->uid >= 0) {
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001332 const struct android_id_info *info = android_ids;
1333 size_t i;
1334
1335 for (i = 0; i < android_id_count; ++i) {
1336 if (info->aid == (unsigned int)entry->uid) {
1337 break;
1338 }
1339 ++info;
1340 }
1341 if ((i < android_id_count) && (strlen(info->name) <= 5)) {
1342 snprintf(uid, sizeof(uid), "%5s:", info->name);
1343 } else {
1344 // Not worth parsing package list, names all longer than 5
1345 snprintf(uid, sizeof(uid), "%5d:", entry->uid);
1346 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001347 } else {
1348 snprintf(uid, sizeof(uid), " ");
1349 }
1350 }
1351
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001352 switch (p_format->format) {
1353 case FORMAT_TAG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001354 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001355 "%c/%-8s: ", priChar, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001356 strcpy(suffixBuf + suffixLen, "\n");
1357 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001358 break;
1359 case FORMAT_PROCESS:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001360 len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001361 " (%s)\n", entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001362 suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
1363 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001364 "%c(%s%5d) ", priChar, uid, entry->pid);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001365 break;
1366 case FORMAT_THREAD:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001367 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001368 "%c(%s%5d:%5d) ", priChar, uid, entry->pid, entry->tid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001369 strcpy(suffixBuf + suffixLen, "\n");
1370 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001371 break;
1372 case FORMAT_RAW:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001373 prefixBuf[prefixLen] = 0;
1374 len = 0;
1375 strcpy(suffixBuf + suffixLen, "\n");
1376 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001377 break;
1378 case FORMAT_TIME:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001379 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001380 "%s %c/%-8s(%s%5d): ", timeBuf, priChar, entry->tag,
1381 uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001382 strcpy(suffixBuf + suffixLen, "\n");
1383 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001384 break;
1385 case FORMAT_THREADTIME:
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001386 ret = strchr(uid, ':');
1387 if (ret) {
1388 *ret = ' ';
1389 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001390 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001391 "%s %s%5d %5d %c %-8s: ", timeBuf,
1392 uid, entry->pid, entry->tid, priChar, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001393 strcpy(suffixBuf + suffixLen, "\n");
1394 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001395 break;
1396 case FORMAT_LONG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001397 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001398 "[ %s %s%5d:%5d %c/%-8s ]\n",
1399 timeBuf, uid, entry->pid, entry->tid, priChar, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001400 strcpy(suffixBuf + suffixLen, "\n\n");
1401 suffixLen += 2;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001402 prefixSuffixIsHeaderFooter = 1;
1403 break;
1404 case FORMAT_BRIEF:
1405 default:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001406 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001407 "%c/%-8s(%s%5d): ", priChar, entry->tag, uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001408 strcpy(suffixBuf + suffixLen, "\n");
1409 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001410 break;
1411 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001412
Keith Prestonb45b5c92010-02-11 15:12:53 -06001413 /* snprintf has a weird return value. It returns what would have been
1414 * written given a large enough buffer. In the case that the prefix is
1415 * longer then our buffer(128), it messes up the calculations below
1416 * possibly causing heap corruption. To avoid this we double check and
1417 * set the length at the maximum (size minus null byte)
1418 */
Pierre Zurekead88fc2010-10-17 22:39:37 +02001419 prefixLen += MIN(len, sizeof(prefixBuf) - prefixLen);
Mark Salyzyne2428422015-01-22 10:00:04 -08001420 suffixLen = MIN(suffixLen, sizeof(suffixBuf));
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001421
1422 /* the following code is tragically unreadable */
1423
1424 size_t numLines;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001425 char *p;
1426 size_t bufferSize;
1427 const char *pm;
1428
1429 if (prefixSuffixIsHeaderFooter) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001430 /* we're just wrapping message with a header/footer */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001431 numLines = 1;
1432 } else {
1433 pm = entry->message;
1434 numLines = 0;
1435
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001436 /*
1437 * The line-end finding here must match the line-end finding
1438 * in for ( ... numLines...) loop below
1439 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001440 while (pm < (entry->message + entry->messageLen)) {
1441 if (*pm++ == '\n') numLines++;
1442 }
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001443 /* plus one line for anything not newline-terminated at the end */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001444 if (pm > entry->message && *(pm-1) != '\n') numLines++;
1445 }
1446
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001447 /*
1448 * this is an upper bound--newlines in message may be counted
1449 * extraneously
1450 */
1451 bufferSize = (numLines * (prefixLen + suffixLen)) + 1;
1452 if (p_format->printable_output) {
1453 /* Calculate extra length to convert non-printable to printable */
1454 bufferSize += convertPrintable(NULL, entry->message, entry->messageLen);
1455 } else {
1456 bufferSize += entry->messageLen;
1457 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001458
1459 if (defaultBufferSize >= bufferSize) {
1460 ret = defaultBuffer;
1461 } else {
1462 ret = (char *)malloc(bufferSize);
1463
1464 if (ret == NULL) {
1465 return ret;
1466 }
1467 }
1468
1469 ret[0] = '\0'; /* to start strcat off */
1470
1471 p = ret;
1472 pm = entry->message;
1473
1474 if (prefixSuffixIsHeaderFooter) {
1475 strcat(p, prefixBuf);
1476 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001477 if (p_format->printable_output) {
1478 p += convertPrintable(p, entry->message, entry->messageLen);
1479 } else {
1480 strncat(p, entry->message, entry->messageLen);
1481 p += entry->messageLen;
1482 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001483 strcat(p, suffixBuf);
1484 p += suffixLen;
1485 } else {
1486 while(pm < (entry->message + entry->messageLen)) {
1487 const char *lineStart;
1488 size_t lineLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001489 lineStart = pm;
1490
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001491 /* Find the next end-of-line in message */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001492 while (pm < (entry->message + entry->messageLen)
1493 && *pm != '\n') pm++;
1494 lineLen = pm - lineStart;
1495
1496 strcat(p, prefixBuf);
1497 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001498 if (p_format->printable_output) {
1499 p += convertPrintable(p, lineStart, lineLen);
1500 } else {
1501 strncat(p, lineStart, lineLen);
1502 p += lineLen;
1503 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001504 strcat(p, suffixBuf);
1505 p += suffixLen;
1506
1507 if (*pm == '\n') pm++;
1508 }
1509 }
1510
1511 if (p_outLength != NULL) {
1512 *p_outLength = p - ret;
1513 }
1514
1515 return ret;
1516}
1517
1518/**
1519 * Either print or do not print log line, based on filter
1520 *
1521 * Returns count bytes written
1522 */
1523
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001524int android_log_printLogLine(
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001525 AndroidLogFormat *p_format,
1526 int fd,
1527 const AndroidLogEntry *entry)
1528{
1529 int ret;
1530 char defaultBuffer[512];
1531 char *outBuffer = NULL;
1532 size_t totalLen;
1533
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001534 outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
1535 sizeof(defaultBuffer), entry, &totalLen);
1536
1537 if (!outBuffer)
1538 return -1;
1539
1540 do {
1541 ret = write(fd, outBuffer, totalLen);
1542 } while (ret < 0 && errno == EINTR);
1543
1544 if (ret < 0) {
1545 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
1546 ret = 0;
1547 goto done;
1548 }
1549
1550 if (((size_t)ret) < totalLen) {
1551 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
1552 (int)totalLen);
1553 goto done;
1554 }
1555
1556done:
1557 if (outBuffer != defaultBuffer) {
1558 free(outBuffer);
1559 }
1560
1561 return ret;
1562}